Skip to main content

rustorb_rtps/
octets.rs

1//! [`Octets`]: a shared, immutable run of octets.
2//!
3//! A serialized payload goes from the application to the history of a
4//! writer, into DATA_FRAGs, to local readers, and from a received datagram
5//! to a reader. Kept as `Octets`, each of those steps shares the octets
6//! instead of copying them (#112): a received DATA's payload is a slice of
7//! the datagram, a DATA_FRAG's fragments are slices of the change.
8
9use std::fmt;
10use std::ops::{Deref, Range};
11use std::sync::Arc;
12
13/// A slice of a shared buffer. Cloning it, or taking a slice of it with
14/// [`Octets::slice`], copies nothing.
15#[derive(Clone)]
16pub struct Octets {
17    buf: Arc<Vec<u8>>,
18    start: usize,
19    end: usize,
20}
21
22impl Octets {
23    /// No octets.
24    pub fn new() -> Self {
25        Octets::from(Vec::new())
26    }
27
28    /// The octets of `range` (relative to this slice), sharing the buffer.
29    ///
30    /// # Panics
31    ///
32    /// When `range` is not within the slice.
33    pub fn slice(&self, range: Range<usize>) -> Octets {
34        assert!(
35            range.start <= range.end && range.end <= self.len(),
36            "slice {range:?} out of {} octets",
37            self.len()
38        );
39        Octets {
40            buf: self.buf.clone(),
41            start: self.start + range.start,
42            end: self.start + range.end,
43        }
44    }
45
46    /// `sub`, which must lie within these octets, as a slice of them;
47    /// `None` when it does not.
48    pub fn slice_ref(&self, sub: &[u8]) -> Option<Octets> {
49        let base = self.as_ptr() as usize;
50        let at = sub.as_ptr() as usize;
51        if at < base || at + sub.len() > base + self.len() {
52            return None;
53        }
54        let from = at - base;
55        Some(self.slice(from..from + sub.len()))
56    }
57
58    /// The octets as a vector of their own: without a copy when nothing
59    /// else shares them and they are the whole buffer.
60    pub fn into_vec(self) -> Vec<u8> {
61        if self.start == 0 && self.end == self.buf.len() {
62            match Arc::try_unwrap(self.buf) {
63                Ok(v) => v,
64                Err(buf) => buf.to_vec(),
65            }
66        } else {
67            self.to_vec()
68        }
69    }
70}
71
72impl Default for Octets {
73    fn default() -> Self {
74        Octets::new()
75    }
76}
77
78impl Deref for Octets {
79    type Target = [u8];
80    fn deref(&self) -> &[u8] {
81        &self.buf[self.start..self.end]
82    }
83}
84
85impl AsRef<[u8]> for Octets {
86    fn as_ref(&self) -> &[u8] {
87        self
88    }
89}
90
91impl From<Vec<u8>> for Octets {
92    fn from(v: Vec<u8>) -> Self {
93        let end = v.len();
94        Octets {
95            buf: Arc::new(v),
96            start: 0,
97            end,
98        }
99    }
100}
101
102impl From<&[u8]> for Octets {
103    fn from(s: &[u8]) -> Self {
104        Octets::from(s.to_vec())
105    }
106}
107
108impl<const N: usize> From<[u8; N]> for Octets {
109    fn from(a: [u8; N]) -> Self {
110        Octets::from(a.to_vec())
111    }
112}
113
114impl FromIterator<u8> for Octets {
115    fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> Self {
116        Octets::from(iter.into_iter().collect::<Vec<u8>>())
117    }
118}
119
120impl From<Octets> for Vec<u8> {
121    fn from(o: Octets) -> Self {
122        o.into_vec()
123    }
124}
125
126impl fmt::Debug for Octets {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        fmt::Debug::fmt(&**self, f)
129    }
130}
131
132impl PartialEq for Octets {
133    fn eq(&self, other: &Self) -> bool {
134        **self == **other
135    }
136}
137
138impl Eq for Octets {}
139
140impl PartialEq<[u8]> for Octets {
141    fn eq(&self, other: &[u8]) -> bool {
142        **self == *other
143    }
144}
145
146impl PartialEq<Vec<u8>> for Octets {
147    fn eq(&self, other: &Vec<u8>) -> bool {
148        **self == **other
149    }
150}
151
152impl<const N: usize> PartialEq<[u8; N]> for Octets {
153    fn eq(&self, other: &[u8; N]) -> bool {
154        **self == *other
155    }
156}
157
158impl std::hash::Hash for Octets {
159    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
160        (**self).hash(state)
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn slices_share_the_buffer() {
170        let o = Octets::from(vec![1, 2, 3, 4, 5]);
171        let s = o.slice(1..4);
172        assert_eq!(&*s, &[2, 3, 4]);
173        assert_eq!(s.as_ptr(), o[1..].as_ptr());
174        let t = s.slice(1..2);
175        assert_eq!(&*t, &[3]);
176        assert_eq!(o.slice_ref(&o[2..5]).unwrap(), vec![3, 4, 5]);
177        assert!(o.slice_ref(&[9, 9]).is_none());
178        assert!(s.slice_ref(&o[0..2]).is_none());
179    }
180
181    #[test]
182    fn into_vec_copies_only_when_shared_or_partial() {
183        let v = vec![7u8; 16];
184        let p = v.as_ptr();
185        let o = Octets::from(v);
186        assert_eq!(o.clone().into_vec(), vec![7u8; 16]);
187        let back = o.into_vec();
188        assert_eq!(back.as_ptr(), p);
189        let o = Octets::from(vec![1, 2, 3]);
190        assert_eq!(o.slice(1..3).into_vec(), vec![2, 3]);
191    }
192}