core :: BytesReader :: defaultinit
# Read from `bytes` in memory
#
# ~~~
# var reader = new BytesReader(b"a…b")
# assert reader.read_char == 'a'
# assert reader.read_byte == 0xE2 # 1st byte of '…'
# assert reader.read_byte == 0x80 # 2nd byte of '…'
# assert reader.read_char == '�' # Reads the last byte as an invalid char
# assert reader.read_all_bytes == b"b"
# ~~~
class BytesReader
super Reader
# Source data to read
var bytes: Bytes
# The current position in `bytes`
private var cursor = 0
redef fun raw_read_byte
do
if cursor >= bytes.length then return -1
var c = bytes[cursor]
cursor += 1
return c.to_i
end
redef fun close do bytes = new Bytes.empty
redef fun read_all_bytes
do
var res = bytes.slice_from(cursor)
cursor = bytes.length
return res
end
redef fun raw_read_bytes(ns, max) do
if cursor >= bytes.length then return 0
var copy = max.min(bytes.length - cursor)
bytes.items.copy_to(ns, copy, cursor, 0)
cursor += copy
return copy
end
redef fun eof do return cursor >= bytes.length
end
lib/core/stream.nit:693,1--740,3