diff --git a/src/buffered_input.jl b/src/buffered_input.jl index dfa7b5a..ca1e3e9 100644 --- a/src/buffered_input.jl +++ b/src/buffered_input.jl @@ -15,40 +15,35 @@ mutable struct BufferedInput end end - -# Read and buffer n more characters -function __fill(bi::BufferedInput, bi_input::IO, n::Integer) - for _ in 1:n - c = eof(bi_input) ? '\0' : read(bi_input, Char) - i = bi.offset + bi.avail + 1 +# Read and buffer `n` more characters +function buffer!(bi::BufferedInput, n::Integer)::Nothing + for i in (bi.offset + bi.avail) .+ (1:n) + c = eof(bi.input) ? '\0' : read(bi.input, Char) if i ≤ length(bi.buffer) bi.buffer[i] = c else push!(bi.buffer, c) end - bi.avail += 1 end + bi.avail += n + nothing 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) - i1 = i + 1 - if bi.avail < i1 - _fill(bi, i1 - bi.avail) - end - bi.buffer[bi.offset + i1] +# Peek the character in the `i`-th position relative to the current position. +function peek1(bi::BufferedInput, i::Integer=1)::Char + bi.avail < i && buffer!(bi, i - bi.avail) + bi.buffer[bi.offset + i] end +# peek function for 0-based indices +peek(bi::BufferedInput, i::Integer=0) = peek1(bi, i + 1) # Return the string formed from the first n characters from the current position # of the stream. function prefix(bi::BufferedInput, n::Integer=1) n1 = n + 1 if bi.avail < n1 - _fill(bi, n1 - bi.avail) + buffer!(bi, n1 - bi.avail) end String(bi.buffer[bi.offset .+ (1:n)]) end