2021-03-04 09:57:30 +03:00
|
|
|
import io
|
|
|
|
|
|
|
|
struct StringReader {
|
|
|
|
text string
|
|
|
|
mut:
|
|
|
|
place int
|
|
|
|
}
|
|
|
|
|
|
|
|
fn imin(a int, b int) int {
|
|
|
|
return if a < b { a } else { b }
|
|
|
|
}
|
|
|
|
|
2022-08-08 02:33:25 +03:00
|
|
|
fn (mut s StringReader) read(mut buf []u8) !int {
|
2021-03-04 09:57:30 +03:00
|
|
|
$if debug {
|
|
|
|
eprintln('>>>> StringReader.read output buf.len: $buf.len')
|
|
|
|
}
|
|
|
|
if s.place > s.text.len + 1 {
|
2022-10-28 19:08:30 +03:00
|
|
|
return io.Eof{}
|
2021-03-04 09:57:30 +03:00
|
|
|
}
|
|
|
|
mut howmany := imin(buf.len, s.text.len - s.place)
|
|
|
|
xxx := s.text[s.place..s.place + howmany].bytes()
|
2022-03-09 21:26:00 +03:00
|
|
|
read := copy(mut buf, xxx)
|
2021-03-04 09:57:30 +03:00
|
|
|
s.place += read
|
|
|
|
return read
|
|
|
|
}
|
|
|
|
|
2022-04-15 15:35:35 +03:00
|
|
|
fn read_from_string(text string, capacity int) []u8 {
|
2021-03-04 09:57:30 +03:00
|
|
|
mut str := StringReader{
|
|
|
|
text: text
|
|
|
|
}
|
2021-05-13 10:26:10 +03:00
|
|
|
mut stream := io.new_buffered_reader(reader: str, cap: capacity)
|
2021-03-04 09:57:30 +03:00
|
|
|
//
|
2022-04-15 15:35:35 +03:00
|
|
|
mut buf := []u8{len: 1}
|
|
|
|
mut res := []u8{}
|
2021-03-04 09:57:30 +03:00
|
|
|
mut i := 0
|
|
|
|
for {
|
|
|
|
z := stream.read(mut buf) or { break }
|
|
|
|
res << buf
|
|
|
|
$if debug {
|
|
|
|
println('capacity: $capacity, i: $i, buf: $buf | z: $z')
|
|
|
|
}
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn test_reading_from_a_string() {
|
|
|
|
for capacity in 1 .. 1000 {
|
2022-04-15 14:58:56 +03:00
|
|
|
assert read_from_string('a', capacity) == [u8(`a`)]
|
|
|
|
assert read_from_string('ab', capacity) == [u8(`a`), `b`]
|
|
|
|
assert read_from_string('abc', capacity) == [u8(`a`), `b`, `c`]
|
|
|
|
assert read_from_string('abcde', capacity) == [u8(`a`), `b`, `c`, `d`, `e`]
|
2022-04-15 15:35:35 +03:00
|
|
|
large_string_bytes := []u8{len: 1000, init: `x`}
|
2021-03-04 09:57:30 +03:00
|
|
|
large_string := large_string_bytes.bytestr()
|
|
|
|
assert read_from_string(large_string, capacity) == large_string_bytes
|
|
|
|
}
|
|
|
|
}
|