send_it/
lib.rs

1use std::fmt::Display;
2
3#[cfg(feature="writing")]
4#[cfg(not(feature="tokio"))]
5pub mod writer;
6#[cfg(feature="reading")]
7#[cfg(not(feature="tokio"))]
8pub mod reader;
9
10#[cfg(feature="writing")]
11#[cfg(feature="tokio")]
12pub mod async_writer;
13#[cfg(feature="reading")]
14#[cfg(feature="tokio")]
15pub mod async_reader;
16
17/// A segment of data used by VarReader and VarWriter to send and receive data over a stream.
18/// # Examples
19/// ```
20/// use send_it::Segment;
21///
22/// let mut segment = Segment::new();
23/// segment.append(Segment::from("Hello, "));
24/// segment.append(Segment::from("World!"));
25///
26/// assert_eq!(segment.to_string(), "Hello, World!");
27/// ```
28#[derive(Debug, Clone)]
29pub struct Segment {
30    seg: Vec<u8>
31}
32
33impl Segment {
34    /// Creates a new Segment.
35    pub fn new() -> Self {
36        Self {
37            seg: Vec::new()
38        }
39    }
40
41    pub fn to_readable(segments: Vec<Segment>) -> Vec<String> {
42        segments.iter().map(|s| s.to_string()).collect::<Vec<String>>()
43    }
44
45    /// Appends a Segment to the end of this Segment.
46    pub fn append(&mut self, seg: Segment) {
47        self.seg.extend(seg.seg);
48    }
49
50    pub(crate) fn len(&self) -> usize {
51        self.seg.len()
52    }
53
54    pub fn to_raw(&self) -> Vec<u8> {
55        self.seg.clone()
56    }
57    
58}
59
60impl Default for Segment {
61    fn default() -> Self {
62        Self::new()
63    }
64}
65
66impl AsRef<[u8]> for Segment {
67    fn as_ref(&self) -> &[u8] {
68        &self.seg
69    }
70}
71
72impl From<&[u8]> for Segment {
73    fn from(value: &[u8]) -> Self {
74        Self {
75            seg: value.to_vec()
76        }
77    }
78}
79
80impl From<Vec<u8>> for Segment {
81    fn from(value: Vec<u8>) -> Self {
82        Self {
83            seg: value
84        }
85    }
86}
87
88impl From<String> for Segment {
89    fn from(value: String) -> Self {
90        Self {
91            seg: value.as_bytes().to_vec()
92        }
93    }
94}
95
96impl Display for Segment {
97    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98        write!(f, "{}", String::from_utf8_lossy(&self.seg))
99    }
100}
101
102mod tests {
103
104    #[test]
105    fn test_writer() {
106        // Create a new VarWriter
107        let mut writer = crate::writer::VarWriter::new();
108
109        // Add some sample data
110        writer.add_string("Hello, ");
111        writer.add_string("World!");
112
113        // Use any Write implementor as your stream (i.e. TcpStream)
114        let mut stream: Vec<u8> = Vec::new();
115
116        // encode the data and send it over the stream
117        writer.send(&mut stream).expect("Failed to send data");
118    }
119
120    #[test]
121    fn test_reader() {
122        // Create a sample stream, this is the output from the above test_writer test
123        let stream: Vec<u8> = vec![21, 7, 0, 0, 0, 72, 101, 108, 108, 111, 44, 32, 6, 0, 0, 0, 87, 111, 114, 108, 100, 33];
124        // turn the vector into a slice as Vec does not implement Read
125        let mut fake_stream = stream.as_slice();
126
127        // create a new VarReader
128        let mut reader = crate::reader::VarReader::new(&mut fake_stream);
129
130        // read the data from the stream
131        let data = reader.read_data().unwrap();
132        assert_eq!(data[0].to_string(), "Hello, ");
133        assert_eq!(data[1].to_string(), "World!");
134    }
135
136    #[test]
137    fn both_test() {
138        // Create a new VarWriter
139        let mut writer = crate::writer::VarWriter::new();
140
141        // Add some sample data
142        writer.add_string("Hello, ");
143        writer.add_string("World!");
144
145        // Use any Write implementor as your stream (i.e. TcpStream)
146        let mut stream: Vec<u8> = Vec::new();
147
148        // encode the data and send it over the stream
149        writer.send(&mut stream).expect("Failed to send data");
150
151        // turn the vector into a slice as Vec does not implement Read
152        let mut fake_stream = stream.as_slice();
153
154        // create a new VarReader
155        let mut reader = crate::reader::VarReader::new(&mut fake_stream);
156
157        // read the data from the stream
158        let data = reader.read_data().unwrap();
159        assert_eq!(data[0].to_string(), "Hello, ");
160        assert_eq!(data[1].to_string(), "World!");
161    }
162}