syntax_parser_generator/readers/
byte_array_reader.rs1use crate::readers::address_based::{AddressBasedReader, AddressSpace};
2
3pub struct ByteArrayAddressSpace {
4 data: Box<[u8]>,
5}
6
7impl ByteArrayAddressSpace {
8 fn from_string(data: String) -> Self {
9 ByteArrayAddressSpace {
10 data: data.into_bytes().into_boxed_slice(),
11 }
12 }
13}
14
15impl AddressSpace<u8> for ByteArrayAddressSpace {
16 fn read_at(&self, address: usize) -> Option<u8> {
17 self.data.get(address).copied()
18 }
19}
20
21pub type ByteArrayReader = AddressBasedReader<u8, ByteArrayAddressSpace>;
24
25impl ByteArrayReader {
26 pub fn from_string(data: String) -> ByteArrayReader {
29 let address_space = ByteArrayAddressSpace::from_string(data);
30 AddressBasedReader::raw_new(address_space)
31 }
32
33 pub fn from_string_slice(data: &str) -> Self {
36 Self::from_string(String::from(data))
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use crate::readers::Reader;
43
44 use super::*;
45
46 #[test]
47 fn test_reading() {
48 let mut reader = ByteArrayReader::from_string("Hi, this is data".to_string());
49 assert_eq!(reader.read_next(), Some('H' as u8));
50 assert_eq!(reader.read_next(), Some('i' as u8));
51 assert_eq!(reader.read_next(), Some(',' as u8));
52 }
53
54 #[test]
55 fn test_sequence_extraction() {
56 let mut reader = ByteArrayReader::from_string("Hi, this is data".to_string());
57 reader.read_next();
58 reader.read_next();
59 reader.read_next();
60 reader.read_next();
61 reader.set_head();
62 reader.read_next();
63 reader.read_next();
64 reader.read_next();
65 reader.read_next();
66 reader.set_tail();
67 assert_eq!(
68 String::from_utf8(reader.get_sequence().collect()).unwrap(),
69 "this".to_string(),
70 );
71 }
72
73 #[test]
74 fn test_reset_to_tail() {
75 let mut reader = ByteArrayReader::from_string("Hi, this is data".to_string());
76 reader.set_tail();
77 reader.read_next();
78 reader.restart_from_tail();
79 assert_eq!(reader.read_next(), Some('H' as u8));
80 }
81}