v2 / vlib / io / custom_string_reading_test.v
77 lines · 70 sloc · 1.69 KB · 19f080ffb8f8f01976692f6b79d9f857c685e109
Raw
1import io
2
3struct StringReader {
4 text string
5mut:
6 place int
7}
8
9fn imin(a int, b int) int {
10 return if a < b { a } else { b }
11}
12
13fn (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
27fn 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
47pub 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
59pub 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