fire_stream/packet/
body_bytes.rs

1#[cfg(feature = "json")]
2use super::Result;
3
4use std::io;
5use std::result::Result as StdResult;
6
7#[cfg(feature = "fs")]
8use std::path::Path;
9
10use bytes::{
11	Offset, Cursor, Bytes, BytesRead, BytesReadRef, BytesWrite, BytesSeek
12};
13
14#[cfg(feature = "json")]
15use serde::{Serialize, de::DeserializeOwned};
16
17#[cfg(feature = "fs")]
18use tokio::fs::{self, File};
19#[cfg(feature = "fs")]
20use tokio::io::AsyncReadExt;
21
22/// Read more from a body.
23pub struct BodyBytes<'a> {
24	inner: Bytes<'a>
25}
26
27impl<'a> BodyBytes<'a> {
28	/// Creates a new body bytes.
29	pub fn new(slice: &'a [u8]) -> Self {
30		Self { inner: slice.into() }
31	}
32
33	/// Returns the length of this body.
34	pub fn len(&self) -> usize {
35		self.inner.len()
36	}
37
38	/// returns the inner slice
39	pub fn inner(&self) -> &'a [u8] {
40		self.inner.inner()
41	}
42
43	#[cfg(feature = "json")]
44	#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
45	pub fn deserialize<D>(&self) -> Result<D>
46	where D: DeserializeOwned {
47		serde_json::from_slice(self.inner.as_slice())
48			.map_err(|e| e.into())
49	}
50
51	#[cfg(feature = "fs")]
52	#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
53	pub async fn to_file<P>(&mut self, path: P) -> Result<()>
54	where P: AsRef<Path> {
55		fs::write(path, self.as_slice()).await
56			.map_err(|e| e.into())
57	}
58}
59
60impl BytesRead for BodyBytes<'_> {
61	// returns the full slice
62	#[inline]
63	fn as_slice(&self) -> &[u8] {
64		self.inner.as_slice()
65	}
66
67	#[inline]
68	fn remaining(&self) -> &[u8] {
69		 self.inner.remaining()
70	}
71
72	#[inline]
73	fn try_read(&mut self, len: usize) -> StdResult<&[u8], bytes::ReadError> {
74		self.inner.try_read(len)
75	}
76
77	#[inline]
78	fn peek(&self, len: usize) -> Option<&[u8]> {
79		self.inner.peek(len)
80	}
81}
82
83impl<'a> BytesReadRef<'a> for BodyBytes<'a> {
84	#[inline]
85	fn as_slice_ref(&self) -> &'a [u8] {
86		self.inner.as_slice_ref()
87	}
88
89	#[inline]
90	fn remaining_ref(&self) -> &'a [u8] {
91		self.inner.remaining_ref()
92	}
93
94	#[inline]
95	fn try_read_ref(
96		&mut self,
97		len: usize
98	) -> StdResult<&'a [u8], bytes::ReadError> {
99		self.inner.try_read_ref(len)
100	}
101
102	#[inline]
103	fn peek_ref(&self, len: usize) -> Option<&'a [u8]> {
104		self.inner.peek_ref(len)
105	}
106}
107
108impl BytesSeek for BodyBytes<'_> {
109	fn position(&self) -> usize {
110		self.inner.position()
111	}
112
113	fn try_seek(&mut self, pos: usize) -> StdResult<(), bytes::SeekError> {
114		self.inner.try_seek(pos)
115	}
116}
117
118/// Write easely more to a body.
119pub struct BodyBytesMut<'a> {
120	inner: Offset<Cursor<&'a mut Vec<u8>>>
121}
122
123impl<'a> BodyBytesMut<'a> {
124	/// Creates a new body bytes.
125	/// 
126	/// This should only be used if you implement your own MessageBytes.
127	pub fn new(offset: usize, buffer: &'a mut Vec<u8>) -> Self {
128		Self {
129			inner: Offset::new(Cursor::new(buffer), offset)
130		}
131	}
132
133	/// Shrinks and grows the internal bytes.
134	pub fn resize(&mut self, len: usize) {
135		let offset = self.inner.offset();
136		unsafe {
137			// safe because the offset is kept
138			self.as_mut_vec().resize(offset + len, 0);
139		}
140	}
141
142	pub fn reserve(&mut self, len: usize) {
143		let offset = self.inner.offset();
144		unsafe {
145			// safe because the offset is kept
146			self.as_mut_vec().reserve(offset + len);
147		}
148	}
149
150	/// Returns the length of this body.
151	pub fn len(&self) -> usize {
152		self.inner.len()
153	}
154
155	#[cfg(feature = "json")]
156	pub fn serialize<S: ?Sized>(&mut self, value: &S) -> Result<()>
157	where S: Serialize {
158		serde_json::to_writer(self, value)
159			.map_err(|e| e.into())
160	}
161
162	#[cfg(feature = "fs")]
163	pub async fn from_file<P>(&mut self, path: P) -> Result<()>
164	where P: AsRef<Path> {
165
166		let mut file = File::open(path).await?;
167
168		// check how big the file is then allocate
169		let buf_size = file.metadata().await
170			.map(|m| m.len() as usize + 1)
171			.unwrap_or(0);
172
173		self.reserve(buf_size);
174
175		unsafe {
176			// safe because file.read_to_end only appends
177			let v = self.as_mut_vec();
178			file.read_to_end(v).await?;
179		}
180
181		Ok(())
182	}
183
184	/// ## Safety
185	/// 
186	/// You are not allowed to remove any data.
187	#[doc(hidden)]
188	pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
189		self.inner.inner_mut().inner_mut()
190	}
191}
192
193impl BytesWrite for BodyBytesMut<'_> {
194	fn as_mut(&mut self) -> &mut [u8] {
195		self.inner.as_mut()
196	}
197
198	fn as_bytes(&self) -> Bytes<'_> {
199		self.inner.as_bytes()
200	}
201
202	fn remaining_mut(&mut self) -> &mut [u8] {
203		self.inner.remaining_mut()
204	}
205
206	fn try_write(
207		&mut self,
208		slice: impl AsRef<[u8]>
209	) -> StdResult<(), bytes::WriteError> {
210		self.inner.try_write(slice)
211	}
212}
213
214impl BytesSeek for BodyBytesMut<'_> {
215	fn position(&self) -> usize {
216		self.inner.position()
217	}
218
219	fn try_seek(&mut self, pos: usize) -> StdResult<(), bytes::SeekError> {
220		self.inner.try_seek(pos)
221	}
222}
223
224
225impl io::Write for BodyBytesMut<'_> {
226	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
227		self.inner.write(buf);
228		Ok(buf.len())
229	}
230
231	fn flush(&mut self) -> io::Result<()> {
232		Ok(())
233	}
234}