reader/
reader.rs

1use core::str::from_utf8;
2use std::io::Write;
3
4use embytes_buffer::{Buffer, BufferReader, ReadWrite};
5
6
7
8fn main () {
9    let mut bytes = [0; 1024];
10    let mut buffer = Buffer::new(&mut bytes);
11
12    // Write some bytes
13    buffer.write_all("abc".as_bytes()).unwrap();
14
15    // try to read to a komma but there is none
16    let reader = buffer.create_reader();
17    let result = read_til_komma(&reader);
18    assert_eq!(result, None);
19    drop(reader);
20
21    // Write a string that now contains a comma
22    buffer.write_all("def,1234".as_bytes()).unwrap();
23
24    // try to read to a komma. now there is one
25    let reader = buffer.create_reader();
26    let result = read_til_komma(&reader);
27    assert_eq!(result, Some("abcdef"));
28    drop(reader);
29
30    assert_eq!(buffer.data(), "1234".as_bytes());
31}
32
33/// This method reads a string from buf until there is a comma
34/// 
35/// Returns:
36/// - [`Option::None`] if the string is not complete yet
37/// - [`Option::Some`] with the string if there is a string
38fn read_til_komma<'a>(reader: &'a impl BufferReader) -> Option<&'a str> {
39
40    if reader.is_empty() {
41        return None;
42    }
43
44    let str = from_utf8(&reader)
45        .expect("expected valid utf8");
46
47    // Find the position of the first comma
48    let comma_position = str.find(',');
49
50    if let Some(comma_position) = comma_position {
51        let data = &str[..comma_position];
52
53        // Tell the reader that you have read `data.len() + 1` bytes
54        reader.add_bytes_read(data.len() + 1);
55        Some(data)
56    } else {
57        None
58    }
59}