ctb_formats_eite/encoding/
pack32.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//! 32-bit integer packing for EITE.
21//!
22//! Despite the name suggesting arbitrary 32-bit integers, `pack32` encodes
23//! integers as single WTF-8 codepoints. Consequently, the supported range of
24//! integers is restricted to the Unicode/WTF-8 codepoint range:
25//! `0x0000_0000..=0x0010_FFFF` (0 through 1,114,111).
26//!
27//! Values in this range, including surrogate codepoints (`0xD800..=0xDFFF`),
28//! are valid and round-trip successfully through `unpack32`.
29//!
30//! Any value exceeding `0x0010_FFFF` (i.e. `0x0011_0000..=u32::MAX`) will fail
31//! with an error when passed to `pack32`.
32
33#[allow(
34    unused_imports,
35    clippy::wildcard_imports,
36    reason = "Standard workspace module prelude"
37)]
38use crate::utilities::*;
39
40use anyhow::{Result, anyhow, bail};
41
42use ctb_formats_wtf8::{
43    decode_wtf8_single, encode_wtf8_single, is_unpackable_wtf8,
44};
45
46/// Minimum integer value supported by [`pack32`] (0).
47pub const PACK32_MIN: u32 = 0;
48
49/// Maximum integer value supported by [`pack32`] (`0x0010_FFFF`, 1,114,111).
50///
51/// Despite `pack32` accepting a `u32`, encoding uses single WTF-8 codepoints,
52/// which are bounded by the Unicode codespace limit `0x10FFFF`. Values greater
53/// than this will fail to encode.
54pub const PACK32_MAX: u32 = 0x0010_FFFF;
55
56/// Pack a 32-bit integer into a WTF-8 byte sequence representing a single
57/// logical codepoint.
58///
59/// # Supported Range
60///
61/// Despite taking a `u32`, only values in the Unicode / WTF-8 codepoint
62/// range `0x0000_0000..=0x0010_FFFF` (0 through 1,114,111, or
63/// [`PACK32_MIN`]..=[`PACK32_MAX`]) are supported. This includes surrogate
64/// codepoints `0xD800..=0xDFFF` supported by WTF-8.
65///
66/// Values strictly greater than `0x0010_FFFF` (up to `u32::MAX`) return an
67/// error.
68///
69/// Currently a thin wrapper around WTF-8 single-codepoint encoding.
70///
71/// (Original: pack32)
72pub fn pack32(value: u32) -> Result<Vec<u8>> {
73    encode_wtf8_single(value)
74}
75
76/// Unpack a single WTF-8 sequence into its codepoint (as u32).
77///
78/// Decoded values are guaranteed to be within `0x0000_0000..=0x0010_FFFF`
79/// ([`PACK32_MIN`]..=[`PACK32_MAX`]).
80///
81/// Errors if the input is not a single valid WTF-8 codepoint sequence
82/// or if extra bytes remain after the first decoded codepoint.
83///
84/// (Original: unpack32)
85pub fn unpack32(bytes: &[u8]) -> Result<u32> {
86    let (cp, used) =
87        decode_wtf8_single(bytes).map_err(|e| anyhow!("unpack32: {e}"))?;
88    if used != bytes.len() {
89        bail!(
90            "unpack32: input contains extra bytes (decoded {} used {}, total {}, input {:?})",
91            cp,
92            used,
93            bytes.len(),
94            bytes
95        );
96    }
97    Ok(cp)
98}
99
100/// Test whether the given byte slice is a valid single WTF-8 codepoint
101/// sequence (representing a value in [`PACK32_MIN`]..=[`PACK32_MAX`]).
102///
103/// (Original: isPack32Char)
104pub fn is_pack32_char(bytes: &[u8]) -> bool {
105    is_unpackable_wtf8(bytes)
106}
107
108#[cfg(test)]
109#[allow(
110    clippy::panic,
111    clippy::expect_used,
112    clippy::unwrap_used,
113    clippy::unwrap_in_result,
114    clippy::panic_in_result_fn,
115    clippy::indexing_slicing,
116    clippy::arithmetic_side_effects,
117    reason = "Standard repository test boilerplate"
118)]
119mod tests {
120    use super::*;
121
122    #[crate::ctb_test]
123    fn test_pack32_roundtrip_basic() {
124        // ASCII 'A'
125        let bytes = pack32(0x41).unwrap();
126        assert!(is_pack32_char(&bytes));
127        let cp = unpack32(&bytes).unwrap();
128        assert_eq!(cp, 0x41);
129
130        // BMP codepoint
131        let smile = 0x263A;
132        let bytes2 = pack32(smile).unwrap();
133        assert!(is_pack32_char(&bytes2));
134        let cp2 = unpack32(&bytes2).unwrap();
135        assert_eq!(cp2, smile);
136    }
137
138    #[crate::ctb_test]
139    fn test_pack32_surrogate_wtf8() {
140        // Surrogate (valid in WTF-8)
141        let hi = 0xD83D;
142        let bytes = pack32(hi).unwrap();
143        assert!(is_pack32_char(&bytes));
144        let round = unpack32(&bytes).unwrap();
145        assert_eq!(round, hi);
146    }
147
148    #[crate::ctb_test]
149    fn test_pack32_round_trip() {
150        for &val in &[0, 10, 100, 1000, 10_000] {
151            let packed = pack32(val).unwrap();
152            let unpacked = unpack32(&packed).expect("unpack32 failed");
153            assert_eq!(val, unpacked, "pack32/unpack32 mismatch for {}", val);
154        }
155    }
156
157    #[crate::ctb_test]
158    fn test_pack32_supported_range_boundaries() {
159        // Test key boundary values within the supported range [0, 0x10FFFF].
160        let boundary_values = [
161            PACK32_MIN, // 0x000000 (1-byte start)
162            0x7F,       // 1-byte end
163            0x80,       // 2-byte start
164            0x7FF,      // 2-byte end
165            0x800,      // 3-byte start
166            0xD7FF,     // Just before surrogate range
167            0xD800,     // Lead surrogate start (valid in WTF-8)
168            0xDBFF,     // Lead surrogate end
169            0xDC00,     // Trail surrogate start
170            0xDFFF,     // Trail surrogate end
171            0xE000,     // Just after surrogate range
172            0xFFFF,     // 3-byte end (BMP end)
173            0x10000,    // 4-byte start
174            0x100000,   // Supplementary plane
175            PACK32_MAX, // 0x10FFFF (4-byte end / max supported)
176        ];
177
178        for &val in &boundary_values {
179            let packed = pack32(val).unwrap_or_else(|e| {
180                panic!("failed to pack supported value 0x{val:X}: {e}")
181            });
182            assert!(
183                is_pack32_char(&packed),
184                "is_pack32_char returned false for packed 0x{val:X}"
185            );
186            let unpacked = unpack32(&packed)
187                .unwrap_or_else(|e| panic!("failed to unpack 0x{val:X}: {e}"));
188            assert_eq!(
189                val, unpacked,
190                "pack32/unpack32 roundtrip mismatch for 0x{val:X}"
191            );
192        }
193    }
194
195    #[crate::ctb_test]
196    fn test_pack32_unsupported_range_errors() {
197        // Values strictly above PACK32_MAX (0x10FFFF) must fail to pack.
198        let unsupported_values = [
199            PACK32_MAX.saturating_add(1), // 0x110000
200            0x110001,
201            0x120000,
202            0x1FFFFF,   // End of 4-byte UTF-8 space (historic)
203            0x200000,   // 5-byte UTF-8 space (historic)
204            0x03FFFFFF, // 5-byte UTF-8 end (historic)
205            0x04000000, // 6-byte UTF-8 space (historic)
206            0x7FFFFFFF, // UNICODE_HISTORIC_MAX / i32::MAX
207            0x80000000, // i32 sign bit set
208            0xDEADBEEF,
209            u32::MAX, // 0xFFFFFFFF
210        ];
211
212        for &val in &unsupported_values {
213            assert!(
214                pack32(val).is_err(),
215                "expected pack32(0x{val:X}) to fail, but it succeeded"
216            );
217        }
218    }
219
220    #[crate::ctb_test]
221    fn test_unpack32_invalid_and_out_of_range() {
222        // Empty slice
223        assert!(unpack32(&[]).is_err());
224
225        // Extra trailing bytes rejected by unpack32
226        let packed_a = pack32(0x41).unwrap();
227        assert!(unpack32(&packed_a).is_ok());
228        let mut with_extra = packed_a;
229        with_extra.push(0x42);
230        assert!(unpack32(&with_extra).is_err());
231
232        // Invalid WTF-8 bytes
233        assert!(unpack32(&[0xFF]).is_err());
234        assert!(!is_pack32_char(&[0xFF]));
235
236        // UTF-8 byte sequence encoding codepoint 0x110000 (F4 90 80 80),
237        // which exceeds PACK32_MAX. unpack32 and is_pack32_char must reject it.
238        let out_of_range_bytes = [0xF4, 0x90, 0x80, 0x80];
239        assert!(unpack32(&out_of_range_bytes).is_err());
240        assert!(!is_pack32_char(&out_of_range_bytes));
241    }
242}