1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
use std::borrow::Cow;
use std::fmt::{self as stdfmt, Debug};
use std::ops::Deref;

/// An owned or borrowed byte array.
///
/// `Barr` provides a thin wrapper around [`Cow<u8>`]. The smart pointer allows the byte array to
/// be borrowed up until the point of mutation, at which point a clone is made.
///
/// [`Cow<u8>`]: std::borrow::Cow
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Barr<'a> {
    /// Inner access to the underlying clone-on-write smart pointer.
    pub inner: Cow<'a, [u8]>,
}

impl<'a> Barr<'a> {
    /// A new _borrowed_ byte array. `Barr` has the same lifetime as the borrowed data.
    pub const fn brwed(bytes: &'a [u8]) -> Self {
        Self {
            inner: Cow::Borrowed(bytes),
        }
    }

    /// A new _owned_ byte array. Takes ownership of the vector of bytes and has a `'static`
    /// lifetime.
    pub const fn owned(bytes: Vec<u8>) -> Barr<'static> {
        Barr {
            inner: Cow::Owned(bytes),
        }
    }

    /// Represent the byte array as a slice.
    ///
    /// # Example
    /// ```rust
    /// # use kserd::*;
    /// let barr = Barr::owned(vec![0,1,2]);
    /// assert_eq!(barr.as_bytes(), &[0,1,2]);
    /// ```
    pub fn as_bytes(&self) -> &[u8] {
        &self.inner
    }

    /// Acquires a mutable reference to the owned vector of bytes.
    ///
    /// **_Allocates a new vector and clones the data if not already owned._**
    ///
    /// # Example
    /// ```rust
    /// # use kserd::*;
    /// let mut barr = Barr::brwed([0,1,2,3].as_ref());
    /// barr.to_mut().push(4);
    /// assert_eq!(barr, Barr::brwed([0,1,2,3,4].as_ref()));
    /// ```
    pub fn to_mut(&mut self) -> &mut Vec<u8> {
        self.inner.to_mut()
    }

    /// Makes the underlying byte array owned.
    ///
    /// **_Allocates a new vector and clones the data if it is not already owned_**.
    /// This upgrades the lifetime to `'static`.
    ///
    /// # Example
    /// ```rust
    /// # use kserd::*;
    /// let mut barr = Barr::brwed([0,1,2,3].as_ref());    
    /// assert_eq!(barr.to_owned(), Barr::owned(vec![0,1,2,3]));
    /// ```
    pub fn into_owned(self) -> Barr<'static> {
        Barr::owned(self.inner.into_owned())
    }
}

impl<'a> Deref for Barr<'a> {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        &self.inner
    }
}

impl<'a> AsRef<[u8]> for Barr<'a> {
    fn as_ref(&self) -> &[u8] {
        &*self
    }
}

impl<'a> From<&'a [u8]> for Barr<'a> {
    fn from(bytes: &'a [u8]) -> Self {
        Self::brwed(bytes)
    }
}

impl From<Vec<u8>> for Barr<'static> {
    fn from(bytes: Vec<u8>) -> Self {
        Self::owned(bytes)
    }
}

impl<'a> Debug for Barr<'a> {
    fn fmt(&self, f: &mut stdfmt::Formatter<'_>) -> stdfmt::Result {
        write!(f, "{:?}", &self.inner)
    }
}

impl<'a> PartialEq<[u8]> for Barr<'a> {
    fn eq(&self, other: &[u8]) -> bool {
        self.as_ref() == other
    }
}

impl<'a> PartialEq<[u8]> for &Barr<'a> {
    fn eq(&self, other: &[u8]) -> bool {
        self.as_ref() == other
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_eq() {
        let one: Barr = b"Hello, world".to_vec().into();
        let two: Barr = b"Hello, world"[..].into();
        assert_eq!(one, two);
    }

    #[test]
    fn test_hash() {
        let mut set = std::collections::HashSet::new();
        set.insert(Barr::owned(b"Hello, world!".to_vec()));
        let two = Barr::brwed(b"Hello, world!");

        assert_eq!(set.contains(&two), true);
    }

    #[test]
    fn test_to_mut() {
        let mut x: Barr = b"Hello"[..].into();
        assert_eq!(&x, &b"Hello"[..]);
        x.to_mut().extend(b", world!".iter());
        assert_eq!(&x, b"Hello, world!"[..]);
    }

    #[test]
    fn test_as_ref() {
        let x = Barr::brwed(b"Hello, world!");
        assert_eq!(x.as_ref(), &b"Hello, world!"[..]);
    }

    #[test]
    fn fmt_test() {
        let x = Barr::brwed(&[100]);
        assert_eq!(&format!("{:?}", x), "[100]");
        let x = Barr::owned(vec![100]);
        assert_eq!(&format!("{:?}", x), "[100]");
    }
}