ctb_formats_eite/util/
bitwise.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Bitwise operations and binary flag manipulation helpers for EITE.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use anyhow::{Result, anyhow};
30
31/// Equivalent to JS internal bitwise mask (force into 0..=255).
32#[expect(
33    clippy::expect_used,
34    reason = "v & 0xFF is <= 255 so it is guaranteed to fit in u8"
35)]
36fn mask_byte(v: i32) -> u8 {
37    u8::try_from(v & 0xFF).expect("v & 0xFF is <= 255")
38}
39
40/// Bitwise AND (8-bit) – direct translation of `bitAnd8`.
41pub fn bit_and_8(a: u8, b: u8) -> u8 {
42    mask_byte(i32::from(a & b))
43}
44
45/// Bitwise NOT (8-bit) – direct translation of `bitNot8`.
46pub fn bit_not_8(a: u8) -> u8 {
47    mask_byte(i32::from(!a))
48}
49
50/// Bitwise left shift (8-bit) – bounds restricted to 0..=8 like original.
51pub fn bit_lshift_8(a: u8, places: u8) -> u8 {
52    assert!(places <= 8);
53    let shifted = u32::from(a) << places;
54    // Reason for fallback: shifted max value is 65280 which fits in i32::MAX, so try_from conversion never fails.
55    mask_byte(i32::try_from(shifted).unwrap_or(0))
56}
57
58/// Bitwise logical right shift (8-bit).
59pub fn bit_rshift_8(a: u8, places: u8) -> u8 {
60    assert!(places <= 8);
61    let shifted = u32::from(a) >> places;
62    // Reason for fallback: shifted max value is 255 which fits in i32::MAX, so try_from conversion never fails.
63    mask_byte(i32::try_from(shifted).unwrap_or(0))
64}
65
66/// Return least significant byte from a 32-bit int (matches original intent).
67pub fn least_significant_byte(v: i32) -> u8 {
68    mask_byte(v)
69}
70
71/// Convert a single byte to an 8-length vector of bits (MSB first).
72///
73/// Original code padded leading zeros until length 8.
74pub fn byte_to_int_bit_array(byte: u8) -> Vec<u8> {
75    let mut bits = Vec::with_capacity(8);
76    for i in (0..8).rev() {
77        bits.push((byte >> i) & 1);
78    }
79    bits
80}
81
82/// Convert exactly 8 bits (0/1) into a single byte.
83///
84/// Returns error if:
85/// - `bits.len()` != 8
86/// - any bit is not 0 or 1
87pub fn byte_from_int_bit_array(bits: &[u8]) -> Result<u8> {
88    if bits.len() != 8 {
89        return Err(anyhow!(
90            "byte_from_int_bit_array: expected 8 bits, got {}",
91            bits.len()
92        ));
93    }
94    let mut val: u8 = 0;
95    for &b in bits {
96        if b > 1 {
97            return Err(anyhow!(
98                "byte_from_int_bit_array: invalid bit value {b}"
99            ));
100        }
101        val = (val << 1) | b;
102    }
103    Ok(val)
104}
105
106/// Flatten a byte slice into a vector of 0/1 bits (MSB first per byte).
107pub fn byte_array_to_int_bit_array(bytes: &[u8]) -> Vec<u8> {
108    let mut out = Vec::with_capacity(bytes.len().saturating_mul(8));
109    for &b in bytes {
110        out.extend(byte_to_int_bit_array(b));
111    }
112    out
113}
114
115/// Convert a flat bit array (length multiple of 8) into bytes.
116///
117/// Ignores trailing bits < 8 (i.e., requires perfect multiple). If leftover bits exist,
118/// returns error to mirror strictness of original logic.
119///
120/// Returns error if any bit is not 0 or 1.
121pub fn byte_array_from_int_bit_array(bits: &[u8]) -> Result<Vec<u8>> {
122    if !bits.len().is_multiple_of(8) {
123        return Err(anyhow!(
124            "byte_array_from_int_bit_array: bit length {} not divisible by 8",
125            bits.len()
126        ));
127    }
128    let mut out = Vec::with_capacity(bits.len() / 8);
129    for chunk in bits.chunks(8) {
130        out.push(byte_from_int_bit_array(chunk)?);
131    }
132    Ok(out)
133}
134
135#[cfg(test)]
136#[allow(
137    clippy::panic,
138    clippy::expect_used,
139    clippy::unwrap_used,
140    clippy::unwrap_in_result,
141    clippy::panic_in_result_fn,
142    clippy::indexing_slicing,
143    clippy::arithmetic_side_effects,
144    reason = "Standard repository test boilerplate"
145)]
146mod tests {
147    use super::*;
148
149    #[crate::ctb_test]
150    fn test_bitwise_ops() {
151        assert_eq!(bit_and_8(0b1111_0000, 0b1010_1010), 0b1010_0000);
152        assert_eq!(bit_not_8(0b0000_1111), 0b1111_0000);
153        assert_eq!(bit_lshift_8(0b0000_1111, 2), 0b0011_1100);
154        assert_eq!(bit_rshift_8(0b1111_0000, 4), 0b0000_1111);
155    }
156
157    #[crate::ctb_test]
158    fn test_byte_to_bits_and_back() -> Result<()> {
159        let cases = [
160            (0x00u8, [0, 0, 0, 0, 0, 0, 0, 0]),
161            (0xFFu8, [1, 1, 1, 1, 1, 1, 1, 1]),
162            (0x5Au8, [0, 1, 0, 1, 1, 0, 1, 0]), // 0x5A = 01011010
163            (0xC3u8, [1, 1, 0, 0, 0, 0, 1, 1]), // 0xC3 = 11000011
164        ];
165        for (byte, bits_expected) in cases.iter() {
166            let bits = byte_to_int_bit_array(*byte);
167            assert_eq!(bits.as_slice(), bits_expected);
168            let round = byte_from_int_bit_array(&bits)?;
169            assert_eq!(round, *byte);
170        }
171        Ok(())
172    }
173
174    #[crate::ctb_test]
175    fn test_bytes_to_bits_round_trip() -> Result<()> {
176        let data = b"\x00\x01\x7F\x80\xFF";
177        let bits = byte_array_to_int_bit_array(data);
178        assert_eq!(bits.len(), data.len() * 8);
179        let restored = byte_array_from_int_bit_array(&bits)?;
180        assert_eq!(restored, data);
181        Ok(())
182    }
183
184    #[crate::ctb_test]
185    fn test_byte_array_from_int_bit_array_invalid_length() {
186        let bits: Vec<u8> = vec![0u8, 1, 0]; // length 3
187        assert!(byte_array_from_int_bit_array(&bits).is_err());
188    }
189}