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}
51
52impl<'a> Reader<'a> {
53    pub(crate) fn new(buf: &'a [u8], endianness: Endianness) -> Self {
54        Reader {
55            buf,
56            pos: 0,
57            endianness,
58        }
59    }
60
61    pub(crate) fn endianness(&self) -> Endianness {
62        self.endianness
63    }
64
65    pub(crate) fn position(&self) -> usize {
66        self.pos
67    }
68
69    pub(crate) fn remaining(&self) -> usize {
70        self.buf.len() - self.pos
71    }
72
73    pub(crate) fn is_empty(&self) -> bool {
74        self.remaining() == 0
75    }
76
77    pub(crate) fn bytes(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
78        if n > self.remaining() {
79            return Err(DecodeError::UnexpectedEnd);
80        }
81        let out = &self.buf[self.pos..self.pos + n];
82        self.pos += n;
83        Ok(out)
84    }
85
86    pub(crate) fn skip(&mut self, n: usize) -> Result<(), DecodeError> {
87        self.bytes(n).map(|_| ())
88    }
89
90    pub(crate) fn rest(&mut self) -> &'a [u8] {
91        let out = &self.buf[self.pos..];
92        self.pos = self.buf.len();
93        out
94    }
95
96    pub(crate) fn array<const N: usize>(&mut self) -> Result<[u8; N], DecodeError> {
97        let mut out = [0u8; N];
98        out.copy_from_slice(self.bytes(N)?);
99        Ok(out)
100    }
101
102    pub(crate) fn u16(&mut self) -> Result<u16, DecodeError> {
103        let b = self.array::<2>()?;
104        Ok(match self.endianness {
105            Endianness::Big => u16::from_be_bytes(b),
106            Endianness::Little => u16::from_le_bytes(b),
107        })
108    }
109
110    pub(crate) fn u32(&mut self) -> Result<u32, DecodeError> {
111        let b = self.array::<4>()?;
112        Ok(match self.endianness {
113            Endianness::Big => u32::from_be_bytes(b),
114            Endianness::Little => u32::from_le_bytes(b),
115        })
116    }
117
118    pub(crate) fn i32(&mut self) -> Result<i32, DecodeError> {
119        self.u32().map(|v| v as i32)
120    }
121}
122
123/// Writes integers in a fixed byte order to the end of a vector.
124#[derive(Debug)]
125pub(crate) struct Writer<'a> {
126    buf: &'a mut Vec<u8>,
127    endianness: Endianness,
128}
129
130impl<'a> Writer<'a> {
131    pub(crate) fn new(buf: &'a mut Vec<u8>, endianness: Endianness) -> Self {
132        Writer { buf, endianness }
133    }
134
135    pub(crate) fn endianness(&self) -> Endianness {
136        self.endianness
137    }
138
139    pub(crate) fn len(&self) -> usize {
140        self.buf.len()
141    }
142
143    pub(crate) fn bytes(&mut self, b: &[u8]) {
144        self.buf.extend_from_slice(b);
145    }
146
147    pub(crate) fn zeros(&mut self, n: usize) {
148        self.buf.resize(self.buf.len() + n, 0);
149    }
150
151    /// Pads with zeros until the length is a multiple of 4.
152    pub(crate) fn align4(&mut self) {
153        let pad = (4 - self.buf.len() % 4) % 4;
154        self.zeros(pad);
155    }
156
157    pub(crate) fn u16(&mut self, v: u16) {
158        match self.endianness {
159            Endianness::Big => self.bytes(&v.to_be_bytes()),
160            Endianness::Little => self.bytes(&v.to_le_bytes()),
161        }
162    }
163
164    /// Overwrites octets already written, starting at `at`.
165    pub(crate) fn patch(&mut self, at: usize, b: &[u8]) {
166        self.buf[at..at + b.len()].copy_from_slice(b);
167    }
168
169    pub(crate) fn u32(&mut self, v: u32) {
170        match self.endianness {
171            Endianness::Big => self.bytes(&v.to_be_bytes()),
172            Endianness::Little => self.bytes(&v.to_le_bytes()),
173        }
174    }
175
176    pub(crate) fn i32(&mut self, v: i32) {
177        self.u32(v as u32);
178    }
179}