-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileIO.swift
More file actions
60 lines (46 loc) · 1.43 KB
/
FileIO.swift
File metadata and controls
60 lines (46 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//
// FileIO.swift
// AlgorithmReview
//
// Created by 박소윤 on 2023/02/27.
//
import Foundation
final class FileIO {
private let buffer: Data
private var index: Int = 0
init(fileHandle: FileHandle = FileHandle.standardInput) {
self.buffer = try! fileHandle.readToEnd()! // 인덱스 범위 넘어가는 것 방지
}
@inline(__always) private func read() -> UInt8 {
defer {
index += 1
}
guard index < buffer.count else { return 0 }
return buffer[index]
}
@inline(__always) func readInt() -> Int {
var sum = 0
var now = read()
var isPositive = true
while now == 10
|| now == 32 { now = read() } // 공백과 줄바꿈 무시
if now == 45 { isPositive.toggle(); now = read() } // 음수 처리
while now >= 48, now <= 57 {
sum = sum * 10 + Int(now-48)
now = read()
}
return sum * (isPositive ? 1:-1)
}
@inline(__always) func readString() -> String {
var str = ""
var now = read()
while now == 10
|| now == 32 { now = read() } // 공백과 줄바꿈 무시
while now != 10
&& now != 32 && now != 0 {
str += String(bytes: [now], encoding: .ascii)!
now = read()
}
return str
}
}