simple_bytes/
bytes_owned.rs

1//! # Note
2//!	Internally there exists only one position
3//! So if you read and write you should keep this in mind
4
5use crate::{
6	Bytes, Cursor,
7	BytesRead, ReadError,
8	BytesWrite, WriteError,
9	BytesSeek, SeekError
10};
11
12use std::io;
13
14/// A Vec wrapper that implements BytesWrite and BytesRead
15#[derive(Debug, Clone, PartialEq, Eq, Hash)]
16pub struct BytesOwned {
17	inner: Cursor<Vec<u8>>
18}
19
20impl BytesOwned {
21
22	/// Creates an empty Vec.
23	pub fn new() -> Self {
24		Self {
25			inner: Cursor::new(vec![])
26		}
27	}
28
29	/// Creates a new Vec with the given capacity.
30	pub fn with_capacity(cap: usize) -> Self {
31		Self {
32			inner: Cursor::new(Vec::with_capacity(cap))
33		}
34	}
35
36	/// Creates a BytesOwned struct.
37	pub fn new_raw(position: usize, inner: Vec<u8>) -> Self {
38		let mut cursor = Cursor::new(inner);
39		cursor.seek(position);
40		Self { inner: cursor }
41	}
42
43	/// Resizes the len to `new_len` allocates some more space if needed.
44	pub fn resize(&mut self, new_len: usize) {
45		self.inner.inner_mut().resize(new_len, 0);
46		if self.inner.position() > new_len {
47			self.inner.seek(new_len);
48		}
49	}
50
51	/// Returns the underlying Vec mutably.
52	/// 
53	/// Removing items can lead to panics while
54	/// reading or writing.
55	#[inline]
56	pub fn as_mut_vec(&mut self) -> &mut Vec<u8> {
57		self.inner.inner_mut()
58	}
59
60	/// Returns the underlying Vec.
61	#[inline]
62	pub fn into_vec(self) -> Vec<u8> {
63		self.inner.into_inner()
64	}
65
66}
67
68impl BytesRead for BytesOwned {
69
70	#[inline]
71	fn as_slice(&self) -> &[u8] {
72		self.inner.as_slice()
73	}
74
75	#[inline]
76	fn len(&self) -> usize {
77		self.inner.len()
78	}
79
80	#[inline]
81	fn remaining(&self) -> &[u8] {
82		self.inner.remaining()
83	}
84
85	#[inline]
86	fn try_read(&mut self, len: usize) -> Result<&[u8], ReadError> {
87		self.inner.try_read(len)
88	}
89
90	#[inline]
91	fn peek(&self, len: usize) -> Option<&[u8]> {
92		self.inner.peek(len)
93	}
94
95}
96
97impl io::Read for BytesOwned {
98	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
99		io::Read::read(&mut self.inner, buf)
100	}
101}
102
103impl BytesWrite for BytesOwned {
104
105	#[inline]
106	fn as_mut(&mut self) -> &mut [u8] {
107		self.inner.as_mut()
108	}
109
110	#[inline]
111	fn as_bytes(&self) -> Bytes<'_> {
112		self.inner.as_bytes()
113	}
114
115	/// Returns the remaining mutable slice.
116	/// 
117	/// If an empty slice is returned, this does not mean
118	/// you can't write anymore.
119	#[inline]
120	fn remaining_mut(&mut self) -> &mut [u8] {
121		self.inner.remaining_mut()
122	}
123
124	/// Writes a slice. Allocates more space if the slice is
125	/// bigger than the `Vec`.
126	#[inline]
127	fn try_write(&mut self, slice: impl AsRef<[u8]>) -> Result<(), WriteError> {
128		self.inner.try_write(slice)
129	}
130
131}
132
133impl io::Write for BytesOwned {
134	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
135		io::Write::write(&mut self.inner, buf)
136	}
137
138	fn flush(&mut self) -> io::Result<()> {
139		Ok(())
140	}
141}
142
143impl BytesSeek for BytesOwned {
144	/// Returns the internal position.
145	fn position(&self) -> usize {
146		self.inner.position()
147	}
148
149	/// Sets the internal position, allocating more space
150	/// if the position is bigger than the `Vec`.
151	fn try_seek(&mut self, pos: usize) -> Result<(), SeekError> {
152		self.inner.try_seek(pos)
153	}
154}
155
156impl io::Seek for BytesOwned {
157	fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
158		io::Seek::seek(&mut self.inner, pos)
159	}
160}
161
162impl From<Vec<u8>> for BytesOwned {
163	fn from(b: Vec<u8>) -> Self {
164		Self::new_raw(0, b)
165	}
166}
167
168impl From<BytesOwned> for Vec<u8> {
169	fn from(b: BytesOwned) -> Self {
170		b.into_vec()
171	}
172}
173
174
175#[cfg(test)]
176mod tests {
177
178	use super::*;
179
180
181	#[test]
182	fn write() {
183
184		let mut bytes = BytesOwned::new();
185		assert_eq!(bytes.len(), 0);
186
187		let to_write: Vec<u8> = (0..10).collect();
188		bytes.write(&to_write);
189		bytes.write(&to_write);
190
191		assert_eq!(bytes.len(), 20);
192
193		assert_eq!(&bytes.as_mut()[..10], to_write.as_slice());
194		assert_eq!(&bytes.as_mut()[10..20], to_write.as_slice());
195
196		bytes.write_u8(5u8);
197		bytes.write_u16(20u16);
198
199		assert_eq!(bytes.len(), 23);
200
201		// seek
202		bytes.seek(20);
203		assert_eq!(bytes.len(), 23);
204
205		// seek
206		bytes.seek(99);
207		assert_eq!(bytes.len(), 99);
208		// should now write to the 99 byte // this is the last byte
209		// this will resize
210		bytes.write_u8(5u8);
211		assert_eq!(bytes.as_mut()[99], 5u8);
212		assert_eq!(bytes.len(), 100);
213
214	}
215
216	#[test]
217	fn read() {
218		use crate::BytesRead;
219
220		let bytes: Vec<u8> = (1..=255).collect();
221		let mut bytes: BytesOwned = bytes.into();
222
223		assert_eq!(bytes.as_slice(), bytes.as_slice());
224		assert_eq!(bytes.len(), 255);
225		assert_eq!(bytes.remaining().len(), 255);
226
227		let to_read: Vec<u8> = (1..=10).collect();
228		assert_eq!(to_read.as_slice(), bytes.read(10));
229		assert_eq!(bytes.remaining().len(), 255 - 10);
230
231		assert_eq!(11u8, bytes.read_u8());
232
233		// peek
234		let to_peek: Vec<u8> = (12..=20).collect();
235		assert_eq!(to_peek.as_slice(), bytes.peek(to_peek.len()).unwrap());
236
237		bytes.seek(255);
238		assert_eq!(bytes.remaining().len(), 0);
239		bytes.seek(254);
240		assert_eq!(255u8, bytes.read_u8());
241
242		bytes.seek(256);// should have allocated one byte
243		bytes.seek(255);
244		assert_eq!(0u8, bytes.read_u8());
245	}
246
247	#[test]
248	fn test_empty() {
249		let mut bytes = BytesOwned::new();
250		assert_eq!(bytes.as_slice(), &[]);
251		assert_eq!(bytes.len(), 0);
252		bytes.seek(0);
253		assert_eq!(bytes.len(), 0);
254	}
255
256	#[test]
257	fn resize() {
258		let mut bytes = BytesOwned::new();
259		bytes.resize(4);
260		assert_eq!(bytes.as_slice(), &[0, 0, 0, 0]);
261		assert_eq!(bytes.position(), 0);
262		bytes.write_u8(2);
263		assert_eq!(bytes.as_slice(), &[2, 0, 0, 0]);
264		bytes.seek(4);
265		bytes.write_u8(2);
266		assert_eq!(bytes.as_slice(), &[2, 0, 0, 0, 2]);
267		bytes.resize(4);
268		assert_eq!(bytes.as_slice(), &[2, 0, 0, 0]);
269		assert!(bytes.try_read(1).is_err());
270	}
271}