Coverage Report

Created: 2025-10-10 06:41

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/bytes.rs
Line
Count
Source
1
use core::cmp::Ordering;
2
use core::fmt::{self, Debug};
3
use core::hash::{Hash, Hasher};
4
use core::ops::{Deref, DerefMut};
5
6
#[cfg(feature = "alloc")]
7
use alloc::borrow::ToOwned;
8
9
#[cfg(feature = "alloc")]
10
use alloc::boxed::Box;
11
12
#[cfg(any(feature = "std", feature = "alloc"))]
13
use crate::ByteBuf;
14
15
use serde::de::{Deserialize, Deserializer};
16
use serde::ser::{Serialize, Serializer};
17
18
/// Wrapper around `[u8]` to serialize and deserialize efficiently.
19
///
20
/// ```
21
/// use std::collections::HashMap;
22
/// use std::io;
23
///
24
/// use serde_bytes::Bytes;
25
///
26
/// fn print_encoded_cache() -> Result<(), bincode::error::EncodeError> {
27
///     let mut cache = HashMap::new();
28
///     cache.insert(3, Bytes::new(b"three"));
29
///     cache.insert(2, Bytes::new(b"two"));
30
///     cache.insert(1, Bytes::new(b"one"));
31
///
32
///     bincode::serde::encode_into_std_write(
33
///         &cache,
34
///         &mut io::stdout(),
35
///         bincode::config::standard(),
36
///     )?;
37
///
38
///     Ok(())
39
/// }
40
/// #
41
/// # fn main() {
42
/// #     print_encoded_cache().unwrap();
43
/// # }
44
/// ```
45
#[derive(Eq, Ord)]
46
#[repr(transparent)]
47
pub struct Bytes {
48
    bytes: [u8],
49
}
50
51
impl Bytes {
52
    /// Wrap an existing `&[u8]`.
53
2.17k
    pub fn new(bytes: &[u8]) -> &Self {
54
2.17k
        unsafe { &*(bytes as *const [u8] as *const Bytes) }
55
2.17k
    }
56
}
57
58
impl Debug for Bytes {
59
0
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60
0
        Debug::fmt(&self.bytes, f)
61
0
    }
62
}
63
64
impl AsRef<[u8]> for Bytes {
65
0
    fn as_ref(&self) -> &[u8] {
66
0
        &self.bytes
67
0
    }
68
}
69
70
impl AsMut<[u8]> for Bytes {
71
0
    fn as_mut(&mut self) -> &mut [u8] {
72
0
        &mut self.bytes
73
0
    }
74
}
75
76
impl Deref for Bytes {
77
    type Target = [u8];
78
79
0
    fn deref(&self) -> &Self::Target {
80
0
        &self.bytes
81
0
    }
82
}
83
84
impl DerefMut for Bytes {
85
0
    fn deref_mut(&mut self) -> &mut Self::Target {
86
0
        &mut self.bytes
87
0
    }
88
}
89
90
impl<'a> From<&'a [u8]> for &'a Bytes {
91
0
    fn from(bytes: &'a [u8]) -> Self {
92
0
        Bytes::new(bytes)
93
0
    }
94
}
95
96
#[cfg(any(feature = "std", feature = "alloc"))]
97
impl ToOwned for Bytes {
98
    type Owned = ByteBuf;
99
100
0
    fn to_owned(&self) -> Self::Owned {
101
0
        ByteBuf::from(&self.bytes)
102
0
    }
103
}
104
105
#[cfg(any(feature = "std", feature = "alloc"))]
106
impl From<Box<[u8]>> for Box<Bytes> {
107
0
    fn from(bytes: Box<[u8]>) -> Self {
108
0
        unsafe { Box::from_raw(Box::into_raw(bytes) as *mut Bytes) }
109
0
    }
110
}
111
112
impl Default for &Bytes {
113
0
    fn default() -> Self {
114
0
        Bytes::new(&[])
115
0
    }
116
}
117
118
#[cfg(any(feature = "std", feature = "alloc"))]
119
impl Default for Box<Bytes> {
120
0
    fn default() -> Self {
121
0
        ByteBuf::new().into_boxed_bytes()
122
0
    }
123
}
124
125
impl<Rhs> PartialEq<Rhs> for Bytes
126
where
127
    Rhs: ?Sized + AsRef<[u8]>,
128
{
129
0
    fn eq(&self, other: &Rhs) -> bool {
130
0
        self.as_ref().eq(other.as_ref())
131
0
    }
132
}
133
134
impl<Rhs> PartialOrd<Rhs> for Bytes
135
where
136
    Rhs: ?Sized + AsRef<[u8]>,
137
{
138
0
    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering> {
139
0
        self.as_ref().partial_cmp(other.as_ref())
140
0
    }
141
}
142
143
impl Hash for Bytes {
144
0
    fn hash<H: Hasher>(&self, state: &mut H) {
145
0
        self.bytes.hash(state);
146
0
    }
147
}
148
149
impl<'a> IntoIterator for &'a Bytes {
150
    type Item = &'a u8;
151
    type IntoIter = <&'a [u8] as IntoIterator>::IntoIter;
152
153
0
    fn into_iter(self) -> Self::IntoIter {
154
0
        self.bytes.iter()
155
0
    }
156
}
157
158
impl<'a> IntoIterator for &'a mut Bytes {
159
    type Item = &'a mut u8;
160
    type IntoIter = <&'a mut [u8] as IntoIterator>::IntoIter;
161
162
0
    fn into_iter(self) -> Self::IntoIter {
163
0
        self.bytes.iter_mut()
164
0
    }
165
}
166
167
impl Serialize for Bytes {
168
2.17k
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
169
2.17k
    where
170
2.17k
        S: Serializer,
171
    {
172
2.17k
        serializer.serialize_bytes(&self.bytes)
173
2.17k
    }
Unexecuted instantiation: <serde_bytes::bytes::Bytes as serde_core::ser::Serialize>::serialize::<_>
Unexecuted instantiation: <serde_bytes::bytes::Bytes as serde_core::ser::Serialize>::serialize::<&mut bson::ser::raw::Serializer>
<serde_bytes::bytes::Bytes as serde_core::ser::Serialize>::serialize::<&mut bson::ser::raw::value_serializer::ValueSerializer>
Line
Count
Source
168
1.34k
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
169
1.34k
    where
170
1.34k
        S: Serializer,
171
    {
172
1.34k
        serializer.serialize_bytes(&self.bytes)
173
1.34k
    }
Unexecuted instantiation: <serde_bytes::bytes::Bytes as serde_core::ser::Serialize>::serialize::<&mut bson::ser::raw::Serializer>
<serde_bytes::bytes::Bytes as serde_core::ser::Serialize>::serialize::<&mut bson::ser::raw::value_serializer::ValueSerializer>
Line
Count
Source
168
833
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
169
833
    where
170
833
        S: Serializer,
171
    {
172
833
        serializer.serialize_bytes(&self.bytes)
173
833
    }
174
}
175
176
impl<'a, 'de: 'a> Deserialize<'de> for &'a Bytes {
177
0
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
178
0
    where
179
0
        D: Deserializer<'de>,
180
    {
181
        // serde::Deserialize for &[u8] is already optimized, so simply forward to that.
182
0
        Deserialize::deserialize(deserializer).map(Bytes::new)
183
0
    }
184
}