Skip to main content

rustorb_rtps/
wire.rs

1//! Byte order and the low-level cursor used by the message codec.
2
3use crate::error::DecodeError;
4
5/// The byte order of a submessage or of a CDR stream.
6///
7/// In a submessage, the EndiannessFlag (the least significant bit of the
8/// flags) selects it: 0 is big-endian and 1 is little-endian
9/// (DDSI-RTPS 2.5, 9.4.5.1.2).
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub enum Endianness {
12    /// Big-endian (EndiannessFlag = 0).
13    Big,
14    /// Little-endian (EndiannessFlag = 1).
15    Little,
16}
17
18impl Endianness {
19    /// The byte order of the machine this code runs on.
20    pub const NATIVE: Endianness = if cfg!(target_endian = "big") {
21        Endianness::Big
22    } else {
23        Endianness::Little
24    };
25
26    /// Reads the EndiannessFlag out of submessage flags.
27    pub fn from_flags(flags: u8) -> Endianness {
28        if flags & 0x01 != 0 {
29            Endianness::Little
30        } else {
31            Endianness::Big
32        }
33    }
34
35    /// The EndiannessFlag bit for this byte order.
36    pub fn flag(self) -> u8 {
37        match self {
38            Endianness::Big => 0x00,
39            Endianness::Little => 0x01,
40        }
41    }
42}
43
44/// A read cursor over a byte slice with a fixed byte order.
45#[derive(Debug)]
46pub(crate) struct Reader<'a> {
47    buf: &'a [u8],
48    pos: usize,
49    endianness: Endianness,
50    /// The shared buffer `buf` lies in, if any: what [`Reader::share`]
51    /// takes slices of.
52    base: Option<&'a crate::Octets>,
53}
54
55impl<'a> Reader<'a> {
56    pub(crate) fn new(buf: &'a [u8], endianness: Endianness) -> Self {
57        Reader {
58            buf,
59            pos: 0,
60            endianness,
61            base: None,
62        }
63    }
64
65    /// A reader of `buf`, which lies in `base` (if given).
66    pub(crate) fn with_base(
67        buf: &'a [u8],
68        endianness: Endianness,
69        base: Option<&'a crate::Octets>,
70    ) -> Self {
71        Reader {
72            base,
73            ..Reader::new(buf, endianness)
74        }
75    }
76
77    /// `s`, read from this reader, as [`crate::Octets`]: a slice of the
78    /// shared buffer when there is one, else a copy.
79    pub(crate) fn share(&self, s: &[u8]) -> crate::Octets {
80        self.base
81            .and_then(|b| b.slice_ref(s))
82            .unwrap_or_else(|| crate::Octets::from(s))
83    }
84
85    pub(crate) fn endianness(&self) -> Endianness {
86        self.endianness
87    }
88
89    pub(crate) fn position(&self) -> usize {
90        self.pos
91    }
92
93    pub(crate) fn remaining(&self) -> usize {
94        self.buf.len() - self.pos
95    }
96
97    pub(crate) fn is_empty(&self) -> bool {
98        self.remaining() == 0
99    }
100
101    pub(crate) fn bytes(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
102        if n > self.remaining() {
103            return Err(DecodeError::UnexpectedEnd);
104        }
105        let out = &self.buf[self.pos..self.pos + n];
106        self.pos += n;
107        Ok(out)
108    }
109
110    pub(crate) fn skip(&mut self, n: usize) -> Result<(), DecodeError> {
111        self.bytes(n).map(|_| ())
112    }
113
114    pub(crate) fn rest(&mut self) -> &'a [u8] {
115        let out = &self.buf[self.pos..];
116        self.pos = self.buf.len();
117        out
118    }
119
120    pub(crate) fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
121        let mut out = [0u8; N];
122        out.copy_from_slice(self.bytes(N)?);
123        Ok(out)
124    }
125
126    pub(crate) fn u16(&mut self) -> Result<u16, DecodeError> {
127        let b = self.array::<2>()?;
128        Ok(match self.endianness {
129            Endianness::Big => u16::from_be_bytes(b),
130            Endianness::Little => u16::from_le_bytes(b),
131        })
132    }
133
134    pub(crate) fn u32(&mut self) -> Result<u32, DecodeError> {
135        let b = self.array::<4>()?;
136        Ok(match self.endianness {
137            Endianness::Big => u32::from_be_bytes(b),
138            Endianness::Little => u32::from_le_bytes(b),
139        })
140    }
141
142    pub(crate) fn i32(&mut self) -> Result<i32, DecodeError> {
143        self.u32().map(|v| v as i32)
144    }
145}
146
147/// Writes integers in a fixed byte order to the end of a vector.
148#[derive(Debug)]
149pub(crate) struct Writer<'a> {
150    buf: &'a mut Vec<u8>,
151    endianness: Endianness,
152}
153
154impl<'a> Writer<'a> {
155    pub(crate) fn new(buf: &'a mut Vec<u8>, endianness: Endianness) -> Self {
156        Writer { buf, endianness }
157    }
158
159    pub(crate) fn endianness(&self) -> Endianness {
160        self.endianness
161    }
162
163    pub(crate) fn len(&self) -> usize {
164        self.buf.len()
165    }
166
167    pub(crate) fn bytes(&mut self, b: &[u8]) {
168        self.buf.extend_from_slice(b);
169    }
170
171    pub(crate) fn zeros(&mut self, n: usize) {
172        self.buf.resize(self.buf.len() + n, 0);
173    }
174
175    /// Pads with zeros until the length is a multiple of 4.
176    pub(crate) fn align4(&mut self) {
177        let pad = (4 - self.buf.len() % 4) % 4;
178        self.zeros(pad);
179    }
180
181    pub(crate) fn u16(&mut self, v: u16) {
182        match self.endianness {
183            Endianness::Big => self.bytes(&v.to_be_bytes()),
184            Endianness::Little => self.bytes(&v.to_le_bytes()),
185        }
186    }
187
188    /// Overwrites octets already written, starting at `at`.
189    pub(crate) fn patch(&mut self, at: usize, b: &[u8]) {
190        self.buf[at..at + b.len()].copy_from_slice(b);
191    }
192
193    pub(crate) fn u32(&mut self, v: u32) {
194        match self.endianness {
195            Endianness::Big => self.bytes(&v.to_be_bytes()),
196            Endianness::Little => self.bytes(&v.to_le_bytes()),
197        }
198    }
199
200    pub(crate) fn i32(&mut self, v: i32) {
201        self.u32(v as u32);
202    }
203}