Skip to main content

xuko_core/
bytes.rs

1//! Reference counted bytes structure
2
3use std::ops::Deref;
4use std::sync::Arc;
5
6/// Reference counted bytes structure
7///
8/// It is simply just a wrapper around [`Arc`]<[`u8`]>
9///
10/// # Examples
11///
12/// ```
13/// use xuko_core::bytes::Bytes;
14///
15/// let bytes = Bytes::from("hello".as_bytes());
16/// let clone = bytes.clone(); // Cheap clone
17///
18/// assert_eq!(*bytes, *clone);
19/// ```
20#[derive(Clone, Debug)]
21pub struct Bytes {
22    bytes: Arc<[u8]>,
23}
24
25impl Bytes {
26    /// Create a new [`Bytes`].
27    pub fn new(bytes: &[u8]) -> Self {
28        Self {
29            bytes: Arc::from(bytes),
30        }
31    }
32}
33
34impl<B: AsRef<[u8]>> From<B> for Bytes {
35    fn from(value: B) -> Bytes {
36        Bytes::new(value.as_ref())
37    }
38}
39
40impl Deref for Bytes {
41    type Target = [u8];
42
43    fn deref(&self) -> &Self::Target {
44        &self.bytes
45    }
46}
47
48#[cfg(feature = "serde")]
49impl serde::Serialize for Bytes {
50    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
51    where
52        S: serde::Serializer,
53    {
54        self.bytes.serialize(serializer)
55    }
56}
57
58#[cfg(feature = "serde")]
59impl<'de> serde::Deserialize<'de> for Bytes {
60    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
61    where
62        D: serde::Deserializer<'de>,
63    {
64        let bytes = Vec::deserialize(deserializer)?;
65        Ok(Self::from(bytes))
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn basic() {
75        let b = Bytes::from([1, 2, 3]);
76        let rc = b.clone();
77
78        assert_eq!(b.first(), Some(&1));
79        assert_eq!(*b, *rc);
80
81        let _ = Bytes::clone(&b);
82    }
83}