Coverage Report

Created: 2025-11-11 06:29

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