Debian Codegraph @

third_party/rust/serde_bytes/src/bytebuf.rs

raw
1 use core::borrow::{Borrow, BorrowMut};
2 use core::cmp::{self, Ordering};
3 use core::fmt::{self, Debug};
4 use core::hash::{Hash, Hasher};
5 use core::ops::{Deref, DerefMut};
6
7 #[cfg(feature = "alloc")]
8 use alloc::boxed::Box;
9 #[cfg(feature = "alloc")]
10 use alloc::string::String;
11 #[cfg(feature = "alloc")]
12 use alloc::vec::Vec;
13
14 use serde::de::{Deserialize, Deserializer, Error, SeqAccess, Visitor};
15 use serde::ser::{Serialize, Serializer};
16
17 use crate::Bytes;
18
19 /// Wrapper around `Vec<u8>` to serialize and deserialize efficiently.
20 ///
21 /// ```
22 /// use std::collections::HashMap;
23 /// use std::io;
24 ///
25 /// use serde_bytes::ByteBuf;
26 ///
27 /// fn deserialize_bytebufs() -> bincode::Result<()> {
28 /// let example_data = [
29 /// 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 116,
30 /// 119, 111, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 111, 110, 101];
31 ///
32 /// let map: HashMap<u32, ByteBuf> = bincode::deserialize(&example_data[..])?;
33 ///
34 /// println!("{:?}", map);
35 ///
36 /// Ok(())
37 /// }
38 /// #
39 /// # fn main() {
40 /// # deserialize_bytebufs().unwrap();
41 /// # }
42 /// ```
43 #[derive(Clone, Default, Eq, Ord)]
44 pub struct ByteBuf {
45 bytes: Vec<u8>,
46 }
47
48 impl ByteBuf {
49 /// Construct a new, empty `ByteBuf`.
50 pub fn new() -> Self {
51 ByteBuf::from(Vec::new())
52 }
53
54 /// Construct a new, empty `ByteBuf` with the specified capacity.
55 pub fn with_capacity(cap: usize) -> Self {
56 ByteBuf::from(Vec::with_capacity(cap))
57 }
58
59 /// Wrap existing bytes in a `ByteBuf`.
60 pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self {
61 ByteBuf {
62 bytes: bytes.into(),
63 }
64 }
65
66 /// Unwrap the vector of byte underlying this `ByteBuf`.
67 pub fn into_vec(self) -> Vec<u8> {
68 self.bytes
69 }
70
71 #[allow(missing_docs)]
72 pub fn into_boxed_bytes(self) -> Box<Bytes> {
73 self.bytes.into_boxed_slice().into()
74 }
75
76 // This would hit "cannot move out of borrowed content" if invoked through
77 // the Deref impl; make it just work.
78 #[doc(hidden)]
79 pub fn into_boxed_slice(self) -> Box<[u8]> {
80 self.bytes.into_boxed_slice()
81 }
82
83 #[doc(hidden)]
84 #[allow(clippy::should_implement_trait)]
85 pub fn into_iter(self) -> <Vec<u8> as IntoIterator>::IntoIter {
86 self.bytes.into_iter()
87 }
88 }
89
90 impl Debug for ByteBuf {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 Debug::fmt(&self.bytes, f)
93 }
94 }
95
96 impl AsRef<[u8]> for ByteBuf {
97 fn as_ref(&self) -> &[u8] {
98 &self.bytes
99 }
100 }
101
102 impl AsMut<[u8]> for ByteBuf {
103 fn as_mut(&mut self) -> &mut [u8] {
104 &mut self.bytes
105 }
106 }
107
108 impl Deref for ByteBuf {
109 type Target = Vec<u8>;
110
111 fn deref(&self) -> &Self::Target {
112 &self.bytes
113 }
114 }
115
116 impl DerefMut for ByteBuf {
117 fn deref_mut(&mut self) -> &mut Self::Target {
118 &mut self.bytes
119 }
120 }
121
122 impl Borrow<Bytes> for ByteBuf {
123 fn borrow(&self) -> &Bytes {
124 Bytes::new(&self.bytes)
125 }
126 }
127
128 impl BorrowMut<Bytes> for ByteBuf {
129 fn borrow_mut(&mut self) -> &mut Bytes {
130 unsafe { &mut *(&mut self.bytes as &mut [u8] as *mut [u8] as *mut Bytes) }
131 }
132 }
133
134 impl<Rhs> PartialEq<Rhs> for ByteBuf
135 where
136 Rhs: ?Sized + AsRef<[u8]>,
137 {
138 fn eq(&self, other: &Rhs) -> bool {
139 self.as_ref().eq(other.as_ref())
140 }
141 }
142
143 impl<Rhs> PartialOrd<Rhs> for ByteBuf
144 where
145 Rhs: ?Sized + AsRef<[u8]>,
146 {
147 fn partial_cmp(&self, other: &Rhs) -> Option<Ordering> {
148 self.as_ref().partial_cmp(other.as_ref())
149 }
150 }
151
152 impl Hash for ByteBuf {
153 fn hash<H: Hasher>(&self, state: &mut H) {
154 self.bytes.hash(state);
155 }
156 }
157
158 impl IntoIterator for ByteBuf {
159 type Item = u8;
160 type IntoIter = <Vec<u8> as IntoIterator>::IntoIter;
161
162 fn into_iter(self) -> Self::IntoIter {
163 self.bytes.into_iter()
164 }
165 }
166
167 impl<'a> IntoIterator for &'a ByteBuf {
168 type Item = &'a u8;
169 type IntoIter = <&'a [u8] as IntoIterator>::IntoIter;
170
171 fn into_iter(self) -> Self::IntoIter {
172 self.bytes.iter()
173 }
174 }
175
176 impl<'a> IntoIterator for &'a mut ByteBuf {
177 type Item = &'a mut u8;
178 type IntoIter = <&'a mut [u8] as IntoIterator>::IntoIter;
179
180 fn into_iter(self) -> Self::IntoIter {
181 self.bytes.iter_mut()
182 }
183 }
184
185 impl Serialize for ByteBuf {
186 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
187 where
188 S: Serializer,
189 {
190 serializer.serialize_bytes(&self.bytes)
191 }
192 }
193
194 struct ByteBufVisitor;
195
196 impl<'de> Visitor<'de> for ByteBufVisitor {
197 type Value = ByteBuf;
198
199 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
200 formatter.write_str("byte array")
201 }
202
203 fn visit_seq<V>(self, mut visitor: V) -> Result<ByteBuf, V::Error>
204 where
205 V: SeqAccess<'de>,
206 {
207 let len = cmp::min(visitor.size_hint().unwrap_or(0), 4096);
208 let mut bytes = Vec::with_capacity(len);
209
210 while let Some(b) = visitor.next_element()? {
211 bytes.push(b);
212 }
213
214 Ok(ByteBuf::from(bytes))
215 }
216
217 fn visit_bytes<E>(self, v: &[u8]) -> Result<ByteBuf, E>
218 where
219 E: Error,
220 {
221 Ok(ByteBuf::from(v))
222 }
223
224 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<ByteBuf, E>
225 where
226 E: Error,
227 {
228 Ok(ByteBuf::from(v))
229 }
230
231 fn visit_str<E>(self, v: &str) -> Result<ByteBuf, E>
232 where
233 E: Error,
234 {
235 Ok(ByteBuf::from(v))
236 }
237
238 fn visit_string<E>(self, v: String) -> Result<ByteBuf, E>
239 where
240 E: Error,
241 {
242 Ok(ByteBuf::from(v))
243 }
244 }
245
246 impl<'de> Deserialize<'de> for ByteBuf {
247 fn deserialize<D>(deserializer: D) -> Result<ByteBuf, D::Error>
248 where
249 D: Deserializer<'de>,
250 {
251 deserializer.deserialize_byte_buf(ByteBufVisitor)
252 }
253 }