-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathbuffered_input.jl
More file actions
75 lines (64 loc) · 1.87 KB
/
Copy pathbuffered_input.jl
File metadata and controls
75 lines (64 loc) · 1.87 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Simple buffered input that allows peeking an arbitrary number of characters
# ahead by maintaining a typically quite small buffer of a few characters.
mutable struct BufferedInput
input::IO
buffer::Vector{Char}
offset::UInt64
avail::UInt64
function BufferedInput(input::IO)
return new(input, Vector{Char}(undef, 0), 0, 0)
end
end
# Read and buffer n more characters
function __fill(bi::BufferedInput, bi_input::IO, n::Integer)
for i in 1:n
c = eof(bi_input) ? '\0' : read(bi_input, Char)
if bi.offset + bi.avail + 1 <= length(bi.buffer)
bi.buffer[bi.offset+bi.avail+1] = c
else
push!(bi.buffer, c)
end
bi.avail += 1
end
end
_fill(bi::BufferedInput, n::Integer) = __fill(bi, bi.input, n)
# Peek the character in the i-th position relative to the current position.
# (0-based)
function peek(bi::BufferedInput, i::Integer=0)
if bi.avail < i + 1
_fill(bi, i + 1 - bi.avail)
end
return bi.buffer[bi.offset+i+1]
end
# Return the string formed from the first n characters from the current position
# of the stream.
function prefix(bi::BufferedInput, n::Integer=1)
if bi.avail < n + 1
_fill(bi, n + 1 - bi.avail)
end
return string(bi.buffer[(bi.offset+1):(bi.offset+n)]...)
end
# NOPE: This is wrong. What if n > bi.avail
# Advance the stream by n characters.
function forward!(bi::BufferedInput, n::Integer=1)
if n < bi.avail
bi.offset += n
bi.avail -= n
else
n -= bi.avail
bi.offset = 0
bi.avail = 0
while n > 0
read(bi.input, Char)
n -= 1
end
end
end
# Ugly hack to allow peeking of `StringDecoder`s
function peek(io::StringDecoder, ::Type{UInt8})
c = read(io, UInt8)
io.skip -= 1
c
end
# The same but for Julia 1.3
peek(io::StringDecoder) = peek(io, UInt8)