Skip to main content

rustorb_cdr/
octets.rs

1use std::fmt;
2use std::ops::{Deref, Range};
3use std::sync::Arc;
4
5/// A `sequence<octet>` that shares its bytes instead of copying them.
6///
7/// Read from a received message with
8/// [`Decoder::read_octet_seq_shared`](crate::Decoder::read_octet_seq_shared),
9/// it keeps the message buffer and points into it. Written with
10/// [`Encoder::write_octet_seq_shared`](crate::Encoder::write_octet_seq_shared),
11/// a large one is sent from where it is, without being copied into the
12/// message. Cloning is cheap. Made from a `Vec<u8>` without copying.
13#[derive(Clone)]
14pub struct Octets {
15    buf: Arc<Vec<u8>>,
16    range: Range<usize>,
17}
18
19impl Octets {
20    /// No octets.
21    pub fn new() -> Octets {
22        Octets::from(Vec::new())
23    }
24
25    /// The bytes `range` of `buf`.
26    ///
27    /// # Panics
28    ///
29    /// If `range` is not within `buf`.
30    pub fn slice_of(buf: Arc<Vec<u8>>, range: Range<usize>) -> Octets {
31        assert!(range.start <= range.end && range.end <= buf.len());
32        Octets { buf, range }
33    }
34
35    /// The bytes.
36    pub fn as_slice(&self) -> &[u8] {
37        &self.buf[self.range.clone()]
38    }
39
40    /// The bytes as a vector of their own: no copy when nothing else
41    /// shares them and they are the whole buffer.
42    pub fn into_vec(self) -> Vec<u8> {
43        if self.range.start == 0 && self.range.end == self.buf.len() {
44            match Arc::try_unwrap(self.buf) {
45                Ok(v) => v,
46                Err(buf) => buf.to_vec(),
47            }
48        } else {
49            self.as_slice().to_vec()
50        }
51    }
52}
53
54impl Default for Octets {
55    fn default() -> Octets {
56        Octets::new()
57    }
58}
59
60impl Deref for Octets {
61    type Target = [u8];
62
63    fn deref(&self) -> &[u8] {
64        self.as_slice()
65    }
66}
67
68impl AsRef<[u8]> for Octets {
69    fn as_ref(&self) -> &[u8] {
70        self.as_slice()
71    }
72}
73
74impl From<Vec<u8>> for Octets {
75    fn from(v: Vec<u8>) -> Octets {
76        let range = 0..v.len();
77        Octets {
78            buf: Arc::new(v),
79            range,
80        }
81    }
82}
83
84impl FromIterator<u8> for Octets {
85    fn from_iter<I: IntoIterator<Item = u8>>(iter: I) -> Octets {
86        Octets::from(iter.into_iter().collect::<Vec<u8>>())
87    }
88}
89
90impl From<&[u8]> for Octets {
91    fn from(v: &[u8]) -> Octets {
92        Octets::from(v.to_vec())
93    }
94}
95
96impl From<Octets> for Vec<u8> {
97    fn from(o: Octets) -> Vec<u8> {
98        o.into_vec()
99    }
100}
101
102impl PartialEq for Octets {
103    fn eq(&self, other: &Octets) -> bool {
104        self.as_slice() == other.as_slice()
105    }
106}
107
108impl Eq for Octets {}
109
110impl PartialEq<[u8]> for Octets {
111    fn eq(&self, other: &[u8]) -> bool {
112        self.as_slice() == other
113    }
114}
115
116impl PartialEq<Vec<u8>> for Octets {
117    fn eq(&self, other: &Vec<u8>) -> bool {
118        self.as_slice() == other.as_slice()
119    }
120}
121
122impl std::hash::Hash for Octets {
123    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
124        self.as_slice().hash(state);
125    }
126}
127
128impl fmt::Debug for Octets {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        fmt::Debug::fmt(self.as_slice(), f)
131    }
132}