| 1 | import io |
| 2 | |
| 3 | struct StringReader { |
| 4 | text string |
| 5 | mut: |
| 6 | place int |
| 7 | } |
| 8 | |
| 9 | fn imin(a int, b int) int { |
| 10 | return if a < b { a } else { b } |
| 11 | } |
| 12 | |
| 13 | fn (mut s StringReader) read(mut buf []u8) !int { |
| 14 | $if debug { |
| 15 | eprintln('>>>> StringReader.read output buf.len: ${buf.len}') |
| 16 | } |
| 17 | if s.place > s.text.len + 1 { |
| 18 | return io.Eof{} |
| 19 | } |
| 20 | mut howmany := imin(buf.len, s.text.len - s.place) |
| 21 | xxx := s.text[s.place..s.place + howmany].bytes() |
| 22 | read := copy(mut buf, xxx) |
| 23 | s.place += read |
| 24 | return read |
| 25 | } |
| 26 | |
| 27 | fn read_from_string(text string, capacity int) []u8 { |
| 28 | mut str := StringReader{ |
| 29 | text: text |
| 30 | } |
| 31 | mut stream := io.new_buffered_reader(reader: str, cap: capacity) |
| 32 | |
| 33 | mut buf := []u8{len: 1} |
| 34 | mut res := []u8{} |
| 35 | mut i := 0 |
| 36 | for { |
| 37 | z := stream.read(mut buf) or { break } |
| 38 | res << buf |
| 39 | $if debug { |
| 40 | println('capacity: ${capacity}, i: ${i}, buf: ${buf} | z: ${z}') |
| 41 | } |
| 42 | i++ |
| 43 | } |
| 44 | return res |
| 45 | } |
| 46 | |
| 47 | pub fn test_reading_from_a_string() { |
| 48 | for capacity in 1 .. 1000 { |
| 49 | assert read_from_string('a', capacity) == [u8(`a`)] |
| 50 | assert read_from_string('ab', capacity) == [u8(`a`), `b`] |
| 51 | assert read_from_string('abc', capacity) == [u8(`a`), `b`, `c`] |
| 52 | assert read_from_string('abcde', capacity) == [u8(`a`), `b`, `c`, `d`, `e`] |
| 53 | large_string_bytes := []u8{len: 1000, init: `x`} |
| 54 | large_string := large_string_bytes.bytestr() |
| 55 | assert read_from_string(large_string, capacity) == large_string_bytes |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn test_buffered_reader_readline() { |
| 60 | text := 'hello\nworld' |
| 61 | want := text.split_into_lines() |
| 62 | mut str := StringReader{ |
| 63 | text: text |
| 64 | } |
| 65 | mut stream := io.new_buffered_reader(reader: str) |
| 66 | mut buf := []u8{len: 1} |
| 67 | mut i := 0 |
| 68 | for { |
| 69 | line := stream.read_line() or { |
| 70 | assert err is io.Eof |
| 71 | break |
| 72 | } |
| 73 | assert i < want.len |
| 74 | assert want[i] == line |
| 75 | i++ |
| 76 | } |
| 77 | } |
| 78 | |