Skip to content
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

Add peek1(::BufferedInput, ::Integer) as 1-based indexing peek function #209

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
31 changes: 13 additions & 18 deletions src/buffered_input.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading