Skip to content

Fix the bug where prefix buffers too much #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jun 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 9 additions & 15 deletions src/buffered_input.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +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)
buffer!(bi, i1 - bi.avail)
end
bi.buffer[bi.offset + i1]
end


# 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)
end
function prefix(bi::BufferedInput, n::Integer=1)::String
bi.avail < n && buffer!(bi, n - bi.avail)
String(bi.buffer[bi.offset .+ (1:n)])
end

Expand Down
Loading