Skip to main content

xtce_decode/
bits.rs

1//! MSB-first bit cursor over a byte slice.
2//!
3//! CCSDS packets are bit-packed big-endian: a field starts at an arbitrary bit offset and
4//! runs most-significant bit first, straddling byte boundaries freely. Everything the
5//! decoder reads goes through [`BitCursor`].
6//!
7//! # The 9-byte case
8//!
9//! A 64-bit field at a non-zero bit offset spans **nine** bytes. The obvious implementation
10//! — load eight bytes and shift — silently truncates it. Every read here goes through a
11//! `u128` accumulator, which covers the widest possible span (7 offset bits + 64 width) with
12//! room to spare. The property tests deliberately generate that case.
13//!
14//! # No panics
15//!
16//! Every out-of-range read returns [`BitError`]. A corrupt or hostile packet must never
17//! bring down a decoder that is processing a live downlink.
18
19use std::borrow::Cow;
20
21/// Reading past the end of the data, or asking for more bits than fit in the result.
22#[derive(Clone, Copy, PartialEq, Eq, Debug, thiserror::Error)]
23pub enum BitError {
24    /// The requested field extends past the end of the buffer.
25    #[error("read of {width} bit(s) at bit {position} exceeds the {available}-bit buffer")]
26    OutOfBounds {
27        /// Bit offset the read started at.
28        position: usize,
29        /// Width requested, in bits.
30        width: usize,
31        /// Total size of the buffer, in bits.
32        available: usize,
33    },
34
35    /// More than 64 bits were requested as an integer.
36    #[error("integer read of {width} bits exceeds the 64-bit maximum")]
37    TooWide {
38        /// Width requested, in bits.
39        width: u32,
40    },
41}
42
43/// A big-endian, MSB-first bit reader.
44#[derive(Clone, Copy, Debug)]
45pub struct BitCursor<'a> {
46    data: &'a [u8],
47    position: usize,
48}
49
50impl<'a> BitCursor<'a> {
51    /// Creates a cursor at bit 0 of `data`.
52    #[must_use]
53    pub const fn new(data: &'a [u8]) -> Self {
54        Self { data, position: 0 }
55    }
56
57    /// The underlying buffer.
58    #[must_use]
59    pub const fn data(&self) -> &'a [u8] {
60        self.data
61    }
62
63    /// Current position, in bits from the start of the buffer.
64    #[must_use]
65    pub const fn position(&self) -> usize {
66        self.position
67    }
68
69    /// Total size of the buffer, in bits.
70    #[must_use]
71    pub const fn len_bits(&self) -> usize {
72        self.data.len() * 8
73    }
74
75    /// Bits between the cursor and the end of the buffer.
76    #[must_use]
77    pub const fn remaining(&self) -> usize {
78        self.len_bits().saturating_sub(self.position)
79    }
80
81    /// Moves the cursor to an absolute bit position.
82    ///
83    /// Positions past the end are allowed; the failure surfaces on the next read. XTCE
84    /// `LocationInContainerInBits` can legitimately seek forward past unparsed padding.
85    pub const fn seek(&mut self, position: usize) {
86        self.position = position;
87    }
88
89    /// Advances the cursor without reading.
90    ///
91    /// # Errors
92    ///
93    /// Returns [`BitError::OutOfBounds`] if the skip would pass the end of the buffer.
94    pub fn skip(&mut self, bits: usize) -> Result<(), BitError> {
95        let end = self.position.saturating_add(bits);
96        if end > self.len_bits() {
97            return Err(BitError::OutOfBounds {
98                position: self.position,
99                width: bits,
100                available: self.len_bits(),
101            });
102        }
103        self.position = end;
104        Ok(())
105    }
106
107    /// Reads `width` bits as an unsigned integer and advances the cursor.
108    ///
109    /// Width 0 yields 0, matching the reference implementation's treatment of an empty
110    /// field. Widths above 64 are rejected.
111    ///
112    /// # Errors
113    ///
114    /// [`BitError::TooWide`] above 64 bits, [`BitError::OutOfBounds`] past the end.
115    #[inline]
116    pub fn read_uint(&mut self, width: u32) -> Result<u64, BitError> {
117        let value = self.peek_uint(self.position, width)?;
118        self.position += width as usize;
119        Ok(value)
120    }
121
122    /// Reads `width` bits as an unsigned integer at an absolute position, without moving
123    /// the cursor.
124    ///
125    /// # Errors
126    ///
127    /// [`BitError::TooWide`] above 64 bits, [`BitError::OutOfBounds`] past the end.
128    #[inline]
129    pub fn peek_uint(&self, position: usize, width: u32) -> Result<u64, BitError> {
130        if width > 64 {
131            return Err(BitError::TooWide { width });
132        }
133        if width == 0 {
134            return Ok(0);
135        }
136        let end = position.saturating_add(width as usize);
137        if end > self.len_bits() {
138            return Err(BitError::OutOfBounds {
139                position,
140                width: width as usize,
141                available: self.len_bits(),
142            });
143        }
144
145        let byte = position / 8;
146        let bit_in_byte = (position % 8) as u32;
147
148        // A 16-byte window always covers the widest field (7 offset bits + 64 width = 71),
149        // so one `u128` load and one shift handles every case uniformly. Near the end of
150        // the buffer the window is assembled in a zeroed stack array instead; the padding
151        // bits are never part of the result because the bounds check above already
152        // guaranteed the field itself is in range.
153        let window = if let Some(slice) = self.data.get(byte..byte + 16) {
154            let mut buf = [0u8; 16];
155            buf.copy_from_slice(slice);
156            u128::from_be_bytes(buf)
157        } else {
158            let mut buf = [0u8; 16];
159            let tail = self.data.get(byte..).unwrap_or_default();
160            let take = tail.len().min(16);
161            if let (Some(dst), Some(src)) = (buf.get_mut(..take), tail.get(..take)) {
162                dst.copy_from_slice(src);
163            }
164            u128::from_be_bytes(buf)
165        };
166
167        let shift = 128 - u32::from(bit_in_byte as u8) - width;
168        let mask = if width == 64 {
169            u64::MAX
170        } else {
171            (1u64 << width) - 1
172        };
173        Ok(((window >> shift) as u64) & mask)
174    }
175
176    /// Reads `width` bits as an unsigned integer without advancing the cursor.
177    ///
178    /// # Errors
179    ///
180    /// As [`Self::peek_uint`].
181    #[inline]
182    pub fn peek_next(&self, width: u32) -> Result<u64, BitError> {
183        self.peek_uint(self.position, width)
184    }
185
186    /// Reads `width` bits as bytes, right-aligned in the result.
187    ///
188    /// The result is `ceil(width / 8)` bytes holding the field as a big-endian integer, so a
189    /// 12-bit field becomes two bytes with four leading zero bits. This is the layout the
190    /// reference implementation produces for binary fields, and the layout XTCE implies by
191    /// treating a binary field as an integer of that width.
192    ///
193    /// Byte-aligned whole-byte reads borrow from the packet; everything else allocates.
194    ///
195    /// # Errors
196    ///
197    /// [`BitError::OutOfBounds`] past the end of the buffer.
198    pub fn read_bytes(&mut self, width: usize) -> Result<Cow<'a, [u8]>, BitError> {
199        let out_len = width.div_ceil(8);
200        let pad = out_len * 8 - width;
201
202        if let Some(slice) = self.aligned_slice(width) {
203            return Ok(Cow::Borrowed(slice));
204        }
205
206        let start = self.position;
207        self.bounds_check(width)?;
208
209        let mut out = vec![0u8; out_len];
210        for (index, slot) in out.iter_mut().enumerate() {
211            // Output byte `index` holds source bits `[8*index - pad, 8*index - pad + 8)`;
212            // the first byte is short by `pad` bits, which stay zero.
213            let (from, take) = match (index * 8).checked_sub(pad) {
214                Some(offset) => (start + offset, 8),
215                None => (start, 8 - pad as u32),
216            };
217            *slot = self.peek_uint(from, take)? as u8;
218        }
219        self.position = start + width;
220        Ok(Cow::Owned(out))
221    }
222
223    /// Reads `width` bits as bytes, left-aligned in the result.
224    ///
225    /// The result is `ceil(width / 8)` bytes holding the field starting at bit 0, with any
226    /// slack **at the end**. This is what a string buffer needs: characters are read from
227    /// the front, so padding must not displace them.
228    ///
229    /// # Errors
230    ///
231    /// [`BitError::OutOfBounds`] past the end of the buffer.
232    pub fn read_bytes_left_aligned(&mut self, width: usize) -> Result<Cow<'a, [u8]>, BitError> {
233        if let Some(slice) = self.aligned_slice(width) {
234            return Ok(Cow::Borrowed(slice));
235        }
236
237        let start = self.position;
238        self.bounds_check(width)?;
239
240        let out_len = width.div_ceil(8);
241        let mut out = vec![0u8; out_len];
242        for (index, slot) in out.iter_mut().enumerate() {
243            let offset = index * 8;
244            let take = u32::try_from(width - offset).unwrap_or(8).min(8);
245            // Left-align the final partial byte, matching the shift the reference applies
246            // to the whole buffer.
247            *slot = (self.peek_uint(start + offset, take)? as u8) << (8 - take);
248        }
249        self.position = start + width;
250        Ok(Cow::Owned(out))
251    }
252
253    /// Borrows the next `width` bits when the read is byte-aligned in both position and
254    /// length, advancing the cursor. Returns `None` when a copy is required.
255    fn aligned_slice(&mut self, width: usize) -> Option<&'a [u8]> {
256        if self.position % 8 != 0 || width % 8 != 0 {
257            return None;
258        }
259        let start = self.position / 8;
260        let end = start.checked_add(width / 8)?;
261        let slice = self.data.get(start..end)?;
262        self.position += width;
263        Some(slice)
264    }
265
266    fn bounds_check(&self, width: usize) -> Result<(), BitError> {
267        let end = self.position.saturating_add(width);
268        if end > self.len_bits() {
269            return Err(BitError::OutOfBounds {
270                position: self.position,
271                width,
272                available: self.len_bits(),
273            });
274        }
275        Ok(())
276    }
277}
278
279/// Reinterprets an unsigned field of `width` bits as a signed integer.
280///
281/// Sign-extends by shifting rather than by subtracting `2^width`. The subtraction form
282/// overflows at width 63 — `1i64 << 63` is `i64::MIN`, so `positive - i64::MIN` wraps — which
283/// release builds happen to get right and debug builds panic on, so no differential test
284/// against real packets would ever have caught it. Shifting is branchless and correct for
285/// every width from 1 to 64.
286#[must_use]
287pub fn twos_complement(value: u64, width: u32) -> i64 {
288    if width == 0 || width > 64 {
289        return value as i64;
290    }
291    let shift = 64 - width;
292    ((value << shift) as i64) >> shift
293}
294
295/// Sign extension for the one case where the value can be wider than the field it came from.
296///
297/// After a `leastSignificantByteFirst` swap of a field whose width is not a whole number of
298/// bytes, the value carries bits above `width`: a twelve-bit `0x0AB` comes back as `0xAB00`.
299/// The reference does not mask those away. It tests bit `width - 1` and subtracts `2^width`
300/// if it is set, leaving the high bits in place — so a twelve-bit field can report 43274.
301///
302/// [`twos_complement`] masks, and for every value that fits its width the two agree exactly.
303/// This is a separate function rather than a change to that one because the masking form is
304/// the right answer everywhere else, and because it is branchless.
305///
306/// Returns `None` when the reference's answer does not fit an `i64`. That needs a width
307/// between 57 and 63 bits, not a whole number of bytes, whose swap widened it past `2^63` —
308/// where the reference's arbitrary-precision integers can hold a number this cannot.
309#[must_use]
310pub fn twos_complement_unmasked(value: u64, width: u32) -> Option<i64> {
311    // At 64 bits, and above, the swap cannot widen anything: the value already fills its
312    // field, and the two forms coincide.
313    if width == 0 || width >= 64 {
314        return Some(value as i64);
315    }
316    if value & (1u64 << (width - 1)) == 0 {
317        return i64::try_from(value).ok();
318    }
319    // In `i128` so that the range check is exact rather than a wrap that happens to be
320    // caught. `value` is at most `2^64 - 1` and the subtrahend at most `2^63`.
321    i64::try_from(i128::from(value) - (1i128 << width)).ok()
322}
323
324/// Reinterprets an unsigned field as sign-magnitude: top bit is the sign, rest the
325/// magnitude.
326#[must_use]
327pub fn sign_magnitude(value: u64, width: u32) -> i64 {
328    if width == 0 || width > 64 {
329        return value as i64;
330    }
331    let sign_bit = 1u64 << (width - 1);
332    let magnitude = (value & (sign_bit - 1)) as i64;
333    if value & sign_bit == 0 {
334        magnitude
335    } else {
336        -magnitude
337    }
338}
339
340/// Reinterprets an unsigned field as ones' complement.
341#[must_use]
342pub fn ones_complement(value: u64, width: u32) -> i64 {
343    if width == 0 || width > 64 {
344        return value as i64;
345    }
346    let sign_bit = 1u64 << (width - 1);
347    if value & sign_bit == 0 {
348        value as i64
349    } else {
350        let mask = if width == 64 {
351            u64::MAX
352        } else {
353            (1u64 << width) - 1
354        };
355        -(((!value) & mask) as i64)
356    }
357}
358
359/// Reverses the byte order of a field, for `leastSignificantByteFirst` encodings.
360///
361/// The field is first read MSB-first as an integer; this then reverses the
362/// `ceil(width / 8)` bytes of that integer, which is what the reference implementation does
363/// and what little-endian on the wire means for a byte-aligned field.
364#[must_use]
365pub fn swap_byte_order(value: u64, width: u32) -> u64 {
366    let bytes = (width as usize).div_ceil(8);
367    if bytes <= 1 {
368        return value;
369    }
370    let mut out = 0u64;
371    let mut remaining = value;
372    for _ in 0..bytes {
373        out = (out << 8) | (remaining & 0xFF);
374        remaining >>= 8;
375    }
376    out
377}
378
379#[cfg(test)]
380mod tests {
381    use super::*;
382
383    /// A deliberately naive reference: walk one bit at a time. Slow, obviously correct, and
384    /// the oracle the property tests compare against.
385    fn naive_read(data: &[u8], position: usize, width: u32) -> Option<u64> {
386        if position + width as usize > data.len() * 8 {
387            return None;
388        }
389        let mut value: u64 = 0;
390        for offset in 0..width as usize {
391            let bit_index = position + offset;
392            let byte = *data.get(bit_index / 8)?;
393            let bit = (byte >> (7 - (bit_index % 8))) & 1;
394            value = (value << 1) | u64::from(bit);
395        }
396        Some(value)
397    }
398
399    #[test]
400    fn documented_example_matches() {
401        // 0b00110101 0b11001010, start at bit 2, take 9 -> 0b110101110
402        let data = [0b0011_0101u8, 0b1100_1010];
403        let mut cursor = BitCursor::new(&data);
404        cursor.seek(2);
405        assert_eq!(cursor.read_uint(9), Ok(0b1_1010_1110));
406        assert_eq!(cursor.position(), 11);
407    }
408
409    #[test]
410    fn sixty_four_bits_at_a_bit_offset_spans_nine_bytes() {
411        // Nine bytes, so a 64-bit read starting at bit 1 needs all of them.
412        let data: [u8; 9] = [0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF];
413        for offset in 0..8 {
414            let mut cursor = BitCursor::new(&data);
415            cursor.seek(offset);
416            let got = cursor.read_uint(64).expect("in range");
417            let want = naive_read(&data, offset, 64).expect("in range");
418            assert_eq!(got, want, "offset {offset}");
419        }
420    }
421
422    #[test]
423    fn reads_past_the_end_are_errors_not_panics() {
424        let data = [0xAAu8; 2];
425        let mut cursor = BitCursor::new(&data);
426        cursor.seek(9);
427        assert!(matches!(
428            cursor.read_uint(8),
429            Err(BitError::OutOfBounds { .. })
430        ));
431        assert!(matches!(
432            cursor.read_uint(65),
433            Err(BitError::TooWide { .. })
434        ));
435
436        let mut empty = BitCursor::new(&[]);
437        assert!(matches!(
438            empty.read_uint(1),
439            Err(BitError::OutOfBounds { .. })
440        ));
441        assert_eq!(empty.read_uint(0), Ok(0));
442    }
443
444    #[test]
445    fn aligned_byte_reads_borrow() {
446        let data = [1u8, 2, 3, 4];
447        let mut cursor = BitCursor::new(&data);
448        let bytes = cursor.read_bytes(16).expect("in range");
449        assert!(matches!(bytes, Cow::Borrowed(_)));
450        assert_eq!(&*bytes, &[1, 2]);
451        assert_eq!(cursor.position(), 16);
452    }
453
454    #[test]
455    fn unaligned_bytes_are_right_aligned() {
456        // 12 bits starting at bit 4 of 0xAB 0xCD -> 0xBCD -> [0x0B, 0xCD]
457        let data = [0xABu8, 0xCD];
458        let mut cursor = BitCursor::new(&data);
459        cursor.seek(4);
460        let bytes = cursor.read_bytes(12).expect("in range");
461        assert_eq!(&*bytes, &[0x0B, 0xCD]);
462    }
463
464    #[test]
465    fn left_aligned_bytes_pad_on_the_right() {
466        // Same 12 bits, left-aligned -> [0xBC, 0xD0]
467        let data = [0xABu8, 0xCD];
468        let mut cursor = BitCursor::new(&data);
469        cursor.seek(4);
470        let bytes = cursor.read_bytes_left_aligned(12).expect("in range");
471        assert_eq!(&*bytes, &[0xBC, 0xD0]);
472    }
473
474    /// Sign extension written the slow, obvious way, as an oracle.
475    fn naive_twos_complement(value: u64, width: u32) -> i128 {
476        let modulus = 1i128 << width;
477        let value = i128::from(value) % modulus;
478        if value >= modulus / 2 {
479            value - modulus
480        } else {
481            value
482        }
483    }
484
485    #[test]
486    fn signed_interpretations() {
487        assert_eq!(twos_complement(0xFF, 8), -1);
488        assert_eq!(twos_complement(0x80, 8), -128);
489        assert_eq!(twos_complement(0x7F, 8), 127);
490        assert_eq!(twos_complement(u64::MAX, 64), -1);
491        // Width 63 is where subtracting 2^width overflows; nothing else reaches it.
492        assert_eq!(twos_complement(1 << 62, 63), -(1i64 << 62));
493        assert_eq!(twos_complement((1 << 62) - 1, 63), (1i64 << 62) - 1);
494        assert_eq!(twos_complement(u64::MAX >> 1, 63), -1);
495        assert_eq!(twos_complement(1, 1), -1);
496        assert_eq!(twos_complement(0, 1), 0);
497
498        assert_eq!(sign_magnitude(0b1000_0001, 8), -1);
499        assert_eq!(sign_magnitude(0b0000_0001, 8), 1);
500
501        assert_eq!(ones_complement(0b1111_1110, 8), -1);
502        assert_eq!(ones_complement(0b0000_0001, 8), 1);
503    }
504
505    #[test]
506    fn byte_order_swap() {
507        assert_eq!(swap_byte_order(0x1234, 16), 0x3412);
508        assert_eq!(swap_byte_order(0x12345678, 32), 0x78563412);
509        assert_eq!(swap_byte_order(0x12, 8), 0x12);
510    }
511
512    proptest::proptest! {
513        /// Every width at every offset, against the one-bit-at-a-time oracle.
514        ///
515        /// The generator is written so that width 64 at a non-byte-aligned offset — the
516        #[test]
517        fn matches_naive_reference(
518            data in proptest::collection::vec(proptest::num::u8::ANY, 1..24),
519            offset_seed in 0usize..200,
520            width in 0u32..=64,
521        ) {
522            let total_bits = data.len() * 8;
523            let offset = offset_seed % (total_bits + 1);
524            let mut cursor = BitCursor::new(&data);
525            cursor.seek(offset);
526            let got = cursor.read_uint(width);
527            match naive_read(&data, offset, width) {
528                Some(want) => {
529                    proptest::prop_assert_eq!(got, Ok(want));
530                    proptest::prop_assert_eq!(cursor.position(), offset + width as usize);
531                }
532                None => proptest::prop_assert!(got.is_err()),
533            }
534        }
535
536        #[test]
537        fn wide_reads_at_every_bit_offset(
538            data in proptest::collection::vec(proptest::num::u8::ANY, 9..17),
539            offset in 0usize..8,
540            width in 57u32..=64,
541        ) {
542            let mut cursor = BitCursor::new(&data);
543            cursor.seek(offset);
544            let want = naive_read(&data, offset, width).expect("buffer is long enough");
545            proptest::prop_assert_eq!(cursor.read_uint(width), Ok(want));
546        }
547
548        #[test]
549        fn bytes_and_integers_agree(
550            data in proptest::collection::vec(proptest::num::u8::ANY, 1..20),
551            offset_seed in 0usize..200,
552            width in 1usize..=64,
553        ) {
554            let total_bits = data.len() * 8;
555            let offset = offset_seed % (total_bits + 1);
556            if offset + width > total_bits {
557                return Ok(());
558            }
559            let mut as_int = BitCursor::new(&data);
560            as_int.seek(offset);
561            let integer = as_int.read_uint(width as u32).expect("in range");
562
563            let mut as_bytes = BitCursor::new(&data);
564            as_bytes.seek(offset);
565            let bytes = as_bytes.read_bytes(width).expect("in range");
566
567            let mut rebuilt = 0u64;
568            for byte in bytes.iter() {
569                rebuilt = (rebuilt << 8) | u64::from(*byte);
570            }
571            proptest::prop_assert_eq!(rebuilt, integer);
572            proptest::prop_assert_eq!(as_int.position(), as_bytes.position());
573        }
574
575        /// Sign extension at every width, against the arbitrary-precision oracle.
576        ///
577        #[test]
578        fn twos_complement_matches_naive_reference(
579            bits in proptest::num::u64::ANY,
580            width in 1u32..=64,
581        ) {
582            let mask = if width == 64 { u64::MAX } else { (1u64 << width) - 1 };
583            let value = bits & mask;
584            proptest::prop_assert_eq!(
585                i128::from(twos_complement(value, width)),
586                naive_twos_complement(value, width),
587                "value {} width {}", value, width
588            );
589        }
590
591        /// The unmasked form agrees with the masking one wherever the value fits its field,
592        /// and follows the reference wherever it does not.
593        #[test]
594        fn unmasked_sign_extension_agrees_within_the_field(
595            bits in proptest::num::u64::ANY,
596            width in 1u32..=64,
597        ) {
598            let mask = if width == 64 { u64::MAX } else { (1u64 << width) - 1 };
599            let value = bits & mask;
600            proptest::prop_assert_eq!(
601                twos_complement_unmasked(value, width),
602                Some(twos_complement(value, width)),
603                "value {} width {}", value, width
604            );
605        }
606
607        #[test]
608        fn unmasked_sign_extension_keeps_the_high_bits(
609            bits in proptest::num::u64::ANY,
610            width in 1u32..=56,
611        ) {
612            // What the reference computes, in arbitrary precision.
613            let expected = if bits & (1u64 << (width - 1)) == 0 {
614                i128::from(bits)
615            } else {
616                i128::from(bits) - (1i128 << width)
617            };
618            proptest::prop_assert_eq!(
619                twos_complement_unmasked(bits, width).map(i128::from),
620                i64::try_from(expected).ok().map(i128::from),
621                "value {} width {}", bits, width
622            );
623        }
624
625        #[test]
626        fn failures_leave_the_cursor_untouched(
627            data in proptest::collection::vec(proptest::num::u8::ANY, 0..8),
628            offset in 0usize..200,
629            width in 0u32..=80,
630        ) {
631            let mut cursor = BitCursor::new(&data);
632            cursor.seek(offset);
633            if cursor.read_uint(width).is_err() {
634                proptest::prop_assert_eq!(cursor.position(), offset);
635            }
636        }
637    }
638}