1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#[cfg(feature = "json")]
use super::Result;

use std::io;
use std::result::Result as StdResult;

#[cfg(feature = "fs")]
use std::path::Path;

use bytes::{
	Offset, Cursor, Bytes, BytesRead, BytesReadRef, BytesWrite, BytesSeek
};

#[cfg(feature = "json")]
use serde::{Serialize, de::DeserializeOwned};

#[cfg(feature = "fs")]
use tokio::fs::{self, File};
#[cfg(feature = "fs")]
use tokio::io::AsyncReadExt;

/// Read more from a body.
pub struct BodyBytes<'a> {
	inner: Bytes<'a>
}

impl<'a> BodyBytes<'a> {
	/// Creates a new body bytes.
	pub fn new(slice: &'a [u8]) -> Self {
		Self { inner: slice.into() }
	}

	/// Returns the length of this body.
	pub fn len(&self) -> usize {
		self.inner.len()
	}

	/// returns the inner slice
	pub fn inner(&self) -> &'a [u8] {
		self.inner.inner()
	}

	#[cfg(feature = "json")]
	#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
	pub fn deserialize<D>(&self) -> Result<D>
	where D: DeserializeOwned {
		serde_json::from_slice(self.inner.as_slice())
			.map_err(|e| e.into())
	}

	#[cfg(feature = "fs")]
	#[cfg_attr(docsrs, doc(cfg(feature = "fs")))]
	pub async fn to_file<P>(&mut self, path: P) -> Result<()>
	where P: AsRef<Path> {
		fs::write(path, self.as_slice()).await
			.map_err(|e| e.into())
	}
}

impl BytesRead for BodyBytes<'_> {
	// returns the full slice
	#[inline]
	fn as_slice(&self) -> &[u8] {
		self.inner.as_slice()
	}

	#[inline]
	fn remaining(&self) -> &[u8] {
		 self.inner.remaining()
	}

	#[inline]
	fn try_read(&mut self, len: usize) -> StdResult<&[u8], bytes::ReadError> {
		self.inner.try_read(len)
	}

	#[inline]
	fn peek(&self, len: usize) -> Option<&[u8]> {
		self.inner.peek(len)
	}
}

impl<'a> BytesReadRef<'a> for BodyBytes<'a> {
	#[inline]
	fn as_slice_ref(&self) -> &'a [u8] {
		self.inner.as_slice_ref()
	}

	#[inline]
	fn remaining_ref(&self) -> &'a [u8] {
		self.inner.remaining_ref()
	}

	#[inline]
	fn try_read_ref(
		&mut self,
		len: usize
	) -> StdResult<&'a [u8], bytes::ReadError> {
		self.inner.try_read_ref(len)
	}

	#[inline]
	fn peek_ref(&self, len: usize) -> Option<&'a [u8]> {
		self.inner.peek_ref(len)
	}
}

impl BytesSeek for BodyBytes<'_> {
	fn position(&self) -> usize {
		self.inner.position()
	}

	fn try_seek(&mut self, pos: usize) -> StdResult<(), bytes::SeekError> {
		self.inner.try_seek(pos)
	}
}

/// Write easely more to a body.
pub struct BodyBytesMut<'a> {
	inner: Offset<Cursor<&'a mut Vec<u8>>>
}

impl<'a> BodyBytesMut<'a> {
	/// Creates a new body bytes.
	/// 
	/// This should only be used if you implement your own MessageBytes.
	pub fn new(offset: usize, buffer: &'a mut Vec<u8>) -> Self {
		Self {
			inner: Offset::new(Cursor::new(buffer), offset)
		}
	}

	/// Shrinks and grows the internal bytes.
	pub fn resize(&mut self, len: usize) {
		let offset = self.inner.offset();
		unsafe {
			// safe because the offset is kept
			self.as_mut_vec().resize(offset + len, 0);
		}
	}

	pub fn reserve(&mut self, len: usize) {
		let offset = self.inner.offset();
		unsafe {
			// safe because the offset is kept
			self.as_mut_vec().reserve(offset + len);
		}
	}

	/// Returns the length of this body.
	pub fn len(&self) -> usize {
		self.inner.len()
	}

	#[cfg(feature = "json")]
	pub fn serialize<S: ?Sized>(&mut self, value: &S) -> Result<()>
	where S: Serialize {
		serde_json::to_writer(self, value)
			.map_err(|e| e.into())
	}

	#[cfg(feature = "fs")]
	pub async fn from_file<P>(&mut self, path: P) -> Result<()>
	where P: AsRef<Path> {

		let mut file = File::open(path).await?;

		// check how big the file is then allocate
		let buf_size = file.metadata().await
			.map(|m| m.len() as usize + 1)
			.unwrap_or(0);

		self.reserve(buf_size);

		unsafe {
			// safe because file.read_to_end only appends
			let v = self.as_mut_vec();
			file.read_to_end(v).await?;
		}

		Ok(())
	}

	/// ## Safety
	/// 
	/// You are not allowed to remove any data.
	#[doc(hidden)]
	pub unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8> {
		self.inner.inner_mut().inner_mut()
	}
}

impl BytesWrite for BodyBytesMut<'_> {
	fn as_mut(&mut self) -> &mut [u8] {
		self.inner.as_mut()
	}

	fn as_bytes(&self) -> Bytes<'_> {
		self.inner.as_bytes()
	}

	fn remaining_mut(&mut self) -> &mut [u8] {
		self.inner.remaining_mut()
	}

	fn try_write(
		&mut self,
		slice: impl AsRef<[u8]>
	) -> StdResult<(), bytes::WriteError> {
		self.inner.try_write(slice)
	}
}

impl BytesSeek for BodyBytesMut<'_> {
	fn position(&self) -> usize {
		self.inner.position()
	}

	fn try_seek(&mut self, pos: usize) -> StdResult<(), bytes::SeekError> {
		self.inner.try_seek(pos)
	}
}


impl io::Write for BodyBytesMut<'_> {
	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
		self.inner.write(buf);
		Ok(buf.len())
	}

	fn flush(&mut self) -> io::Result<()> {
		Ok(())
	}
}