Skip to main content

dbc_parse/
bits.rs

1//! Signal bit coding — the two bit-numbering systems of the DBC format.
2//!
3//! DBC files number bits within the payload **per byte, LSB-first**: bit `b`
4//! lives in byte `b / 8` at in-byte mask `1 << (b % 8)`. That numbering is
5//! the same for both byte orders; what differs is *which* bit `start_bit`
6//! names and the direction of travel:
7//!
8//! # Intel (little-endian, `@1`)
9//!
10//! `start_bit` names the **least significant** bit of the signal; the value
11//! is spread over the following `bit_length` bits, ascending, straight
12//! through byte boundaries — a plain LSB-first linear field.
13//!
14//! # Motorola (big-endian, `@0`)
15//!
16//! `start_bit` names the **most significant** bit of the signal, in the
17//! classic "sawtooth" numbering: extraction descends within each byte
18//! (MSB → LSB), then jumps from bit 0 of one byte to bit 7 of the next
19//! (`+15` in DBC numbering — the sawtooth). This reproduces exactly what
20//! `Vector CANdb++`, `cantools`, and the `socketcan-cib` tools do for `@0`
21//! signals, including the famous layouts that straddle three bytes.
22//!
23//! Bits falling outside the buffer read as 0 on extraction
24//! ([`extract_raw`] is total); insertion reports the bytes it needs
25//! ([`max_bit_position`] → [`crate::DbcError::BufferTooShort`]).
26
27use crate::model::ByteOrder;
28
29/// Extracts `bit_length` raw bits laid out per `byte_order`, MSB-aligned
30/// into the low bits of the result.
31///
32/// Total: positions beyond the buffer contribute zero bits (partial frames
33/// decode as if the missing bytes were zero — documented semantics, chosen
34/// to match common CAN tooling on underrun payloads).
35#[must_use]
36pub fn extract_raw(start_bit: u16, bit_length: u8, byte_order: ByteOrder, data: &[u8]) -> u64 {
37    match byte_order {
38        ByteOrder::Intel => {
39            let start = usize::from(start_bit);
40            let mut value = 0_u64;
41            for i in 0..usize::from(bit_length) {
42                let pos = start + i;
43                let bit = u64::from((data.get(pos / 8).copied().unwrap_or(0) >> (pos % 8)) & 1);
44                value |= bit << i;
45            }
46            value
47        }
48        ByteOrder::Motorola => {
49            let mut pos = usize::from(start_bit);
50            let mut value = 0_u64;
51            for _ in 0..usize::from(bit_length) {
52                let bit = u64::from((data.get(pos / 8).copied().unwrap_or(0) >> (pos % 8)) & 1);
53                value = (value << 1) | bit;
54                // Sawtooth: descend within the byte, then jump to the MSB
55                // of the next byte (bit 0 → bit 15 in DBC numbering).
56                pos = if pos % 8 == 0 { pos + 15 } else { pos - 1 };
57            }
58            value
59        }
60    }
61}
62
63/// Inserts `value`'s low `bit_length` bits per `byte_order`, the exact
64/// inverse of [`extract_raw`].
65///
66/// # Errors
67///
68/// [`crate::DbcError::BufferTooShort`] when the buffer cannot hold the
69/// signal's highest bit position — insertion never writes out of bounds.
70pub fn insert_raw(
71    start_bit: u16,
72    bit_length: u8,
73    byte_order: ByteOrder,
74    data: &mut [u8],
75    value: u64,
76) -> Result<(), crate::DbcError> {
77    let need = max_bit_position(start_bit, bit_length, byte_order) / 8 + 1;
78    if data.len() < need {
79        return Err(crate::DbcError::BufferTooShort {
80            need,
81            have: data.len(),
82        });
83    }
84    match byte_order {
85        ByteOrder::Intel => {
86            let start = usize::from(start_bit);
87            for i in 0..usize::from(bit_length) {
88                let pos = start + i;
89                write_bit(data, pos, (value >> i) & 1 == 1);
90            }
91        }
92        ByteOrder::Motorola => {
93            let mut pos = usize::from(start_bit);
94            for i in (0..usize::from(bit_length)).rev() {
95                write_bit(data, pos, (value >> i) & 1 == 1);
96                pos = if pos % 8 == 0 { pos + 15 } else { pos - 1 };
97            }
98        }
99    }
100    Ok(())
101}
102
103/// The highest DBC bit number the signal layout touches.
104#[must_use]
105pub fn max_bit_position(start_bit: u16, bit_length: u8, byte_order: ByteOrder) -> usize {
106    if bit_length == 0 {
107        return usize::from(start_bit);
108    }
109    match byte_order {
110        ByteOrder::Intel => usize::from(start_bit) + usize::from(bit_length) - 1,
111        ByteOrder::Motorola => {
112            let mut pos = usize::from(start_bit);
113            let mut max = pos;
114            for _ in 1..usize::from(bit_length) {
115                pos = if pos % 8 == 0 { pos + 15 } else { pos - 1 };
116                max = max.max(pos);
117            }
118            max
119        }
120    }
121}
122
123/// Sets one bit, LSB-numbered, bounds-checked.
124fn write_bit(data: &mut [u8], pos: usize, set: bool) {
125    if let Some(byte) = data.get_mut(pos / 8) {
126        let mask = 1_u8 << (pos % 8);
127        if set {
128            *byte |= mask;
129        } else {
130            *byte &= !mask;
131        }
132    }
133}
134
135/// Sign-extends `raw` (the low `bit_length` bits) to `i64` two's
136/// complement.
137#[must_use]
138pub fn sign_extend(raw: u64, bit_length: u8) -> i64 {
139    // u64 → i64 reinterpretation is the point of two's-complement coding.
140    #[allow(clippy::cast_possible_wrap)]
141    if bit_length == 0 || bit_length >= 64 {
142        return raw as i64;
143    }
144    let bits = u32::from(bit_length);
145    let sign_bit = 1_u64 << (bits - 1);
146    #[allow(clippy::cast_possible_wrap)]
147    if raw & sign_bit != 0 {
148        // Fill the high bits above the signal with ones.
149        (raw | (!0_u64 << bits)) as i64
150    } else {
151        raw as i64
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    // Tests exercise edge values and index fixed-size buffers directly:
158    // unwrap/expect/indexing are lifted at test scope by design.
159    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
160    use super::*;
161
162    /// Motorola: `39|16@0+` is a big-endian u16 across bytes 4–5.
163    #[test]
164    fn motorola_big_endian_across_bytes() {
165        let data = [0x00, 0x00, 0x00, 0x00, 0xAB, 0xCD, 0x00, 0x00];
166        assert_eq!(extract_raw(39, 16, ByteOrder::Motorola, &data), 0xABCD);
167    }
168
169    /// Intel: `16|16@1+` is a little-endian u16 across bytes 2–3.
170    #[test]
171    fn intel_little_endian_across_bytes() {
172        let data = [0x00, 0x00, 0xAB, 0xCD, 0x00, 0x00, 0x00, 0x00];
173        assert_eq!(extract_raw(16, 16, ByteOrder::Intel, &data), 0xCDAB);
174    }
175
176    /// The sawtooth crosses byte boundaries with a +15 jump: a signal
177    /// starting at bit 0 descends through byte 1 and finishes in byte 2.
178    #[test]
179    fn motorola_sawtooth_jump() {
180        // start 0 len 12 visits bits: 0, 15..8, 23, 22 (DBC numbering).
181        let mut data = [0u8; 8];
182        insert_raw(0, 12, ByteOrder::Motorola, &mut data, 0b1101_0100_1001).unwrap();
183        // Walk positions: 0, 15, 14, 13, 12, 11, 10, 9, 8, 23, 22, 21.
184        // Value 0b110101001001, MSB first along that walk:
185        // data[0] bit0 = 1; data[1] = 1010_1001; data[2] top3 = 001.
186        assert_eq!(data[0], 0b0000_0001);
187        assert_eq!(data[1], 0b1010_1001, "byte 1 holds the 8 mid bits");
188        assert_eq!(data[2] >> 5, 0b001, "top 3 bits of byte 2 carry the tail");
189        // Round-trip:
190        assert_eq!(
191            extract_raw(0, 12, ByteOrder::Motorola, &data),
192            0b1101_0100_1001
193        );
194    }
195
196    /// Extraction beyond the buffer reads zero bits (totality).
197    #[test]
198    fn extract_is_total() {
199        let data = [0xFF_u8];
200        // Intel: bit 8+ read as zero.
201        assert_eq!(extract_raw(0, 16, ByteOrder::Intel, &data), 0x00FF);
202        // Motorola from bit 7 down through missing bytes.
203        assert_eq!(extract_raw(7, 16, ByteOrder::Motorola, &data), 0xFF00);
204        // Fully out of range:
205        assert_eq!(extract_raw(8, 8, ByteOrder::Intel, &data), 0);
206    }
207
208    /// Insertion refuses to write out of bounds.
209    #[test]
210    fn insert_bounds_checked() {
211        let mut data = [0u8; 2];
212        assert_eq!(
213            insert_raw(16, 1, ByteOrder::Intel, &mut data, 1),
214            Err(crate::DbcError::BufferTooShort { need: 3, have: 2 })
215        );
216        // Motorola need accounting: start 0, len 12 → touches byte 2.
217        let mut four = [0u8; 3];
218        assert!(insert_raw(0, 12, ByteOrder::Motorola, &mut four, 0xFFF).is_ok());
219        let mut two = [0u8; 2];
220        assert_eq!(
221            insert_raw(0, 12, ByteOrder::Motorola, &mut two, 0xFFF),
222            Err(crate::DbcError::BufferTooShort { need: 3, have: 2 })
223        );
224    }
225
226    /// `insert_raw` is the exact inverse of `extract_raw`, both orders.
227    #[test]
228    fn insert_extract_inverse() {
229        for &(start, len) in &[
230            (0_u16, 1_u8),
231            (7, 8),
232            (2, 6),
233            (39, 16),
234            (0, 12),
235            (15, 20),
236            (7, 64),
237        ] {
238            for order in [ByteOrder::Motorola, ByteOrder::Intel] {
239                let mut data = [0_u8; 9];
240                let value: u64 = 0x0123_4567_89AB_CDEF & (u64::MAX >> (64 - len).min(64));
241                insert_raw(start, len, order, &mut data, value).unwrap();
242                assert_eq!(
243                    extract_raw(start, len, order, &data),
244                    value,
245                    "round-trip failed at start={start} len={len} order={order:?}"
246                );
247            }
248        }
249    }
250
251    /// Sign extension of negative and positive raws.
252    #[test]
253    fn sign_extension() {
254        assert_eq!(sign_extend(0x7F, 8), 127);
255        assert_eq!(sign_extend(0xFF, 8), -1);
256        assert_eq!(sign_extend(0x800, 12), -2048);
257        assert_eq!(sign_extend(0x7FF, 12), 2047);
258        assert_eq!(sign_extend(1, 1), -1);
259        assert_eq!(sign_extend(0, 1), 0);
260    }
261
262    /// `max_bit_position` matches the walk for both orders.
263    #[test]
264    fn max_position() {
265        assert_eq!(max_bit_position(16, 16, ByteOrder::Intel), 31);
266        assert_eq!(max_bit_position(39, 16, ByteOrder::Motorola), 47);
267        assert_eq!(max_bit_position(0, 12, ByteOrder::Motorola), 23);
268        assert_eq!(max_bit_position(5, 0, ByteOrder::Intel), 5);
269    }
270}