Skip to main content

serde_bytes/
bytes.rs

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