Skip to main content

openqmc/
encode.rs

1//! Port of `oqmc/encode.h` — pack/unpack a 3-axis integer coordinate key into a
2//! single 16-bit value. Used to store pixel coordinates compactly. The sum of
3//! the per-axis bit precisions must not exceed 16.
4
5/// A 3-dimensional integer coordinate key.
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
7pub struct EncodeKey {
8    /// X-axis coordinate.
9    pub x: i32,
10    /// Y-axis coordinate.
11    pub y: i32,
12    /// Z-axis coordinate.
13    pub z: i32,
14}
15
16/// Encode a coordinate key into 16 bits with the given per-axis precisions.
17#[inline]
18pub fn encode_bits16<const XB: u32, const YB: u32, const ZB: u32>(key: EncodeKey) -> u16 {
19    const { assert!(XB + YB + ZB <= 16, "Precision sum must be <= 16") };
20
21    let mask_x = (1u32 << XB) - 1;
22    let mask_y = (1u32 << YB) - 1;
23    let mask_z = (1u32 << ZB) - 1;
24
25    let offset_x = 0;
26    let offset_y = XB;
27    let offset_z = XB + YB;
28
29    let mut value = 0u32;
30    value |= (key.x as u32 & mask_x) << offset_x;
31    value |= (key.y as u32 & mask_y) << offset_y;
32    value |= (key.z as u32 & mask_z) << offset_z;
33
34    value as u16
35}
36
37/// Decode a 16-bit value back into a coordinate key with the given precisions.
38#[inline]
39pub fn decode_bits16<const XB: u32, const YB: u32, const ZB: u32>(value: u16) -> EncodeKey {
40    const { assert!(XB + YB + ZB <= 16, "Precision sum must be <= 16") };
41
42    let value = value as u32;
43    let mask_x = (1u32 << XB) - 1;
44    let mask_y = (1u32 << YB) - 1;
45    let mask_z = (1u32 << ZB) - 1;
46
47    let offset_x = 0;
48    let offset_y = XB;
49    let offset_z = XB + YB;
50
51    EncodeKey {
52        x: ((value >> offset_x) & mask_x) as i32,
53        y: ((value >> offset_y) & mask_y) as i32,
54        z: ((value >> offset_z) & mask_z) as i32,
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61
62    #[test]
63    fn round_trips_within_precision() {
64        // 8/8/0 split (the pixel encoding used by State64Bit), values < 256.
65        for x in [0, 1, 5, 42, 200, 255] {
66            for y in [0, 3, 128, 255] {
67                let k = EncodeKey { x, y, z: 0 };
68                let e = encode_bits16::<8, 8, 0>(k);
69                assert_eq!(decode_bits16::<8, 8, 0>(e), k);
70            }
71        }
72    }
73
74    #[test]
75    fn masks_out_of_range_bits() {
76        // x is only 8 bits wide, so bit 8+ is dropped.
77        let e = encode_bits16::<8, 8, 0>(EncodeKey { x: 256, y: 0, z: 0 });
78        assert_eq!(e, 0);
79    }
80}