1#[allow(
41 unused_imports,
42 clippy::wildcard_imports,
43 reason = "Standard workspace module prelude"
44)]
45use crate::utilities::*;
46
47use anyhow::{Result, anyhow, bail};
48
49use crate::encoding::pack32::{is_pack32_char, pack32, unpack32};
50use crate::util::array::subset;
51use crate::util::bitwise::{
52 byte_array_from_int_bit_array, byte_array_to_int_bit_array,
53};
54use crate::util::math::int_is_between_u32;
55use crate::{bail_if_none, log};
56use ctb_formats_base16b as base16b;
57
58pub const ARMORED_BASE17B_UTF8_START_UUID_BYTES: [u8; 32] = [
60 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
61 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
62 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
63];
64
65pub const ARMORED_BASE17B_UTF8_END_UUID_BYTES: [u8; 32] = [
67 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
68 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
69 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
70];
71
72pub fn int_bit_array_to_basenb_no_remainder_marker(
75 base: u32,
76 input: &[u8],
77) -> Result<Vec<u8>> {
78 let encoded = base16b::encode(input, base)?;
79
80 Ok(encoded.into_bytes())
81}
82
83pub fn int_bit_array_from_basenb_string(
86 input_bytes: &[u8],
87 remainder_len: Option<u32>,
88) -> Result<Vec<u8>> {
89 let s = std::str::from_utf8(input_bytes).map_err(|e| {
90 anyhow!(
91 "utf8 error on input {:?}, from_lossy {:?}: {e}",
92 input_bytes,
93 String::from_utf8_lossy(input_bytes)
94 )
95 })?;
96 log!(
97 "Decoding with input str {:?}, remainder {:?}",
98 s,
99 remainder_len
100 );
101 base16b::decode(s, remainder_len)
102}
103
104pub fn is_basenb_base(base: u32) -> bool {
106 (7..=17).contains(&base)
107}
108
109pub fn is_basenb_char(packed_char: &[u8]) -> bool {
118 if !is_pack32_char(packed_char) {
119 return false;
120 }
121 if let Ok(cp) = unpack32(packed_char) {
122 if int_is_between_u32(cp, 983_040, 1_048_573) {
124 return true;
125 }
126 if int_is_between_u32(cp, 1_048_576, 1_114_109) {
128 return true;
129 }
130 if int_is_between_u32(cp, 63_481, 63_501) {
133 return true;
134 }
135 }
136 false
137}
138
139pub fn is_basenb_distinct_remainder_char(packed_char: &[u8]) -> bool {
142 if !is_pack32_char(packed_char) {
143 return false;
144 }
145 if let Ok(cp) = unpack32(packed_char) {
146 return int_is_between_u32(cp, 63_481, 63_497);
148 }
149 false
150}
151
152pub fn byte_array_to_basenb_no_remainder_marker(
153 base: u32,
154 input: &[u8],
155) -> Result<Vec<u8>> {
156 if !is_basenb_base(base) {
157 return Err(anyhow!(
158 "byte_array_to_basenb_no_remainder_marker: invalid base {base}, expected 7..=17"
159 ));
160 }
161 let bit_array = byte_array_to_int_bit_array(input);
162 let encoded =
163 int_bit_array_to_basenb_no_remainder_marker(base, &bit_array)?;
164 Ok(encoded)
165}
166
167pub fn byte_array_to_basenb_utf8(base: u32, input: &[u8]) -> Result<Vec<u8>> {
178 let mut encoded = byte_array_to_basenb_no_remainder_marker(base, input)?;
179 let total_bits = input.len().checked_mul(8).ok_or_else(|| {
181 anyhow!("Input length is too large to represent bits")
182 })?;
183 let base_usize = usize::try_from(base)?;
184 let remainder = total_bits
185 .checked_rem(base_usize)
186 .ok_or_else(|| anyhow!("Base cannot be zero"))?;
187 let remainder_u32 = u32::try_from(remainder)?;
189 let codepoint = 63_497_u32.checked_sub(remainder_u32).ok_or_else(|| {
190 anyhow!("Remainder too large for codepoint calculation")
191 })?;
192 encoded.extend(pack32(codepoint)?);
193 Ok(encoded)
194}
195
196pub const BYTE_ARRAY_FROM_BASENB_UTF8_INVALID_INPUT_EXCEPTION_BYTES: [u8; 16] = [
200 51, 98, 218, 163, 23, 5, 64, 236, 154, 151, 89, 208, 82, 253, 64, 55,
201];
202
203pub fn byte_array_from_basenb_utf8(input: &[u8]) -> Result<Vec<u8>> {
223 let remainder: u32;
225 let mut remainder_arr: Vec<u8>;
227 remainder_arr = bail_if_none!(subset(input, -3, -1)?);
228 if is_basenb_distinct_remainder_char(&remainder_arr) {
229 let raw_remainder = unpack32(&remainder_arr)?;
230 remainder = 63497_u32.checked_sub(raw_remainder).ok_or_else(|| {
231 anyhow!("Underflow in basenb remainder calculation")
232 })?;
233 } else {
234 remainder_arr = bail_if_none!(subset(input, -4, -1)?);
236 let remainder_decoded: Vec<u8> = byte_array_from_int_bit_array(
237 &int_bit_array_from_basenb_string(&remainder_arr, Some(8))?,
238 )?;
239 let temp: &u8 = bail_if_none!(remainder_decoded.first());
240 let temp: i16 = bail_if_none!(i16::from(*temp).checked_add(-2));
241 remainder = u32::try_from(temp)?;
242 }
243 if input.len() <= remainder_arr.len() {
244 return Ok(
246 BYTE_ARRAY_FROM_BASENB_UTF8_INVALID_INPUT_EXCEPTION_BYTES.to_vec()
247 );
248 }
249 let len_i64 = i64::try_from(remainder_arr.len())?;
250 let subset_end = len_i64
251 .checked_neg()
252 .and_then(|val| val.checked_sub(1))
253 .ok_or_else(|| {
254 anyhow!("Subset end calculation overflow/underflow")
255 })?;
256
257 let subset = bail_if_none!(subset(input, 0, subset_end)?);
258
259 log!("Getting bits from subset: {:?}, {:?}", &subset, remainder);
260
261 let bits = &int_bit_array_from_basenb_string(&subset, Some(remainder))?;
262 log!("Bits from decoder: {:?}", &bits);
263 byte_array_from_int_bit_array(bits)
264}
265
266pub fn byte_array_to_basenb_17_utf8(input: &[u8]) -> Result<Vec<u8>> {
272 byte_array_to_basenb_utf8(17, input)
273}
274
275pub fn byte_array_from_basenb_17_utf8(input: &[u8]) -> Result<Vec<u8>> {
279 byte_array_from_basenb_utf8(input)
280}
281
282pub fn byte_array_to_armored_base17b_utf8(input: &[u8]) -> Result<Vec<u8>> {
290 let encoded = byte_array_to_basenb_17_utf8(input)?;
292 let mut out = ARMORED_BASE17B_UTF8_START_UUID_BYTES.to_vec();
293 out.extend(encoded);
294 out.extend(ARMORED_BASE17B_UTF8_END_UUID_BYTES);
295 Ok(out)
296}
297
298pub fn byte_array_from_armored_base17b_utf8(input: &[u8]) -> Result<Vec<u8>> {
300 let start = ARMORED_BASE17B_UTF8_START_UUID_BYTES;
301 let end = ARMORED_BASE17B_UTF8_END_UUID_BYTES;
302
303 let min_len = start
304 .len()
305 .checked_add(end.len())
306 .ok_or_else(|| anyhow!("Overflow calculating min_len"))?;
307 if input.len() < min_len {
308 bail!(
309 "Armored Base17b input too short: {} < required framing {}",
310 input.len(),
311 min_len
312 );
313 }
314
315 if !input.starts_with(&start) {
316 bail!("Armored Base17b input missing or corrupt start UUID marker");
317 }
318 if !input.ends_with(&end) {
319 bail!("Armored Base17b input missing or corrupt end UUID marker");
320 }
321
322 let inner_len = input
323 .len()
324 .checked_sub(start.len())
325 .and_then(|val| val.checked_sub(end.len()))
326 .ok_or_else(|| {
327 anyhow!("Input length underflow relative to start/end delimiters")
328 })?;
329 let end_idx = start
330 .len()
331 .checked_add(inner_len)
332 .ok_or_else(|| anyhow!("End index overflow"))?;
333 let inner = input
334 .get(start.len()..end_idx)
335 .ok_or_else(|| anyhow!("Input slice out of bounds"))?;
336 let decoded = byte_array_from_basenb_17_utf8(inner)?;
338 Ok(decoded)
339}
340
341#[cfg(test)]
342#[allow(
343 clippy::panic,
344 clippy::expect_used,
345 clippy::unwrap_used,
346 clippy::unwrap_in_result,
347 clippy::panic_in_result_fn,
348 clippy::indexing_slicing,
349 clippy::arithmetic_side_effects,
350 reason = "Standard repository test boilerplate"
351)]
352mod tests {
353
354 use crate::formats::dcbasenb::DC_BASENB_EMBEDDED_START_BYTES;
355 use crate::utilities::{assert_vec_u8_eq, assert_vec_u8_ok_eq};
356 use crate::{
357 encoding::pack32::pack32, util::bitwise::byte_array_to_int_bit_array,
358 };
359
360 use super::*;
361
362 #[crate::ctb_test]
363 fn test_is_basenb_base() {
364 for b in 0..=30 {
365 let valid = is_basenb_base(b);
366 if (7..=17).contains(&b) {
367 assert!(valid);
368 } else {
369 assert!(!valid);
370 }
371 }
372 }
373
374 #[crate::ctb_test]
375 fn test_basenb_remainder_marker_range() {
376 for cp in 63_480..=63_500 {
378 let packed = pack32(cp).unwrap();
379 if (63_481..=63_497).contains(&cp) {
380 assert!(is_basenb_distinct_remainder_char(&packed));
381 } else {
382 assert!(!is_basenb_distinct_remainder_char(&packed));
383 }
384 }
385 }
386
387 #[crate::ctb_test]
388 fn test_basenb_char_ranges() {
389 for cp in [
391 63_480, 63_481, 63_495, 63_501, 63_502, 983_040, 983_100,
392 1_048_573, 1_048_574,
393 ] {
394 let packed = pack32(cp).unwrap();
395 let is_char = is_basenb_char(&packed);
396 let expected = (63_481..=63_501).contains(&cp)
397 || (983_040..=1_048_573).contains(&cp)
398 || (1_048_576..=1_114_109).contains(&cp);
399 assert_eq!(
400 is_char, expected,
401 "cp={} expected {} got {}",
402 cp, expected, is_char
403 );
404 }
405 }
406
407 #[crate::ctb_test]
408 fn test_byte_array_to_basenb_utf8_remainder_marker() {
409 let data = b"\xAB\xCD"; let bits = byte_array_to_int_bit_array(data);
413 assert_eq!(bits.len(), 16);
414 let base = 10;
415 let encoded_with_remainder =
416 byte_array_to_basenb_utf8(base, data).unwrap();
417 let encoded_b10b =
418 byte_array_to_basenb_no_remainder_marker(base, data).unwrap();
419 assert!(
420 encoded_with_remainder.len() >= 4,
421 "Expected at least one codepoint + remainder marker"
422 );
423 let len_diff = encoded_with_remainder
424 .len()
425 .checked_sub(encoded_b10b.len())
426 .expect("encoded_with_remainder is shorter than encoded_b10b");
427 let start_idx = encoded_with_remainder
428 .len()
429 .checked_sub(len_diff)
430 .expect("len_diff is greater than encoded_with_remainder length");
431 let lastn = &encoded_with_remainder[start_idx..];
432 assert!(is_basenb_distinct_remainder_char(lastn));
433 let cp = unpack32(lastn).unwrap();
434 let bits_len_u32 =
435 u32::try_from(bits.len()).expect("Could not fit length in u32");
436 let expected_rem =
437 bits_len_u32.checked_rem(base).expect("base is zero");
438 let expected = 63_497_u32
439 .checked_sub(expected_rem)
440 .expect("Remainder too large for expected codepoint");
441 assert_eq!(cp, expected);
442 assert_vec_u8_ok_eq(
443 data,
444 byte_array_from_basenb_utf8(&encoded_with_remainder),
445 );
446 }
447
448 #[crate::ctb_test]
449 fn test_byte_array_to_basenb_utf8_invalid_base() {
450 let data = b"abc";
451 assert!(byte_array_to_basenb_utf8(6, data).is_err());
452 assert!(byte_array_to_basenb_utf8(18, data).is_err());
453 }
454
455 fn is_sentinel(bytes: &[u8]) -> bool {
456 bytes == BYTE_ARRAY_FROM_BASENB_UTF8_INVALID_INPUT_EXCEPTION_BYTES
457 }
458
459 #[crate::ctb_test]
460 fn test_decode_empty_input() {
461 let enc = assert_vec_u8_ok_eq(
462 "\u{f80d}\u{f809}".as_bytes(),
463 byte_array_to_basenb_utf8(17, &[]),
464 );
465 let dec = byte_array_from_basenb_utf8(&enc);
466 assert_vec_u8_ok_eq(&[], dec);
467 }
468
469 #[crate::ctb_test]
470 fn test_decode_invalid_only_remainder() {
471 let dec = byte_array_from_basenb_utf8("\u{f809}".as_bytes()).unwrap();
472 assert!(
473 is_sentinel(&dec),
474 "Expected sentinel for empty input decode; got {:?}",
475 dec
476 );
477 }
478
479 #[crate::ctb_test]
480 fn test_round_trip_base17_small_samples() {
481 let samples: Vec<Vec<u8>> = vec![
482 vec![0u8],
483 vec![1, 2, 3],
484 vec![255],
485 b"hello".to_vec(),
486 b"\x00\x01\x02\x03\xFE\xFF".to_vec(),
487 (0u8..32u8).collect(),
488 ];
489
490 for sample in samples {
491 let enc = byte_array_to_basenb_17_utf8(&sample).unwrap();
492 crate::log!(
493 "Sample {:?} encoded to Basenb 17 UTF-8 bytes: {:?}",
494 sample.clone(),
495 enc.clone()
496 );
497 let dec = byte_array_from_basenb_17_utf8(&enc).unwrap();
498 if is_sentinel(&dec) && !sample.is_empty() {
499 panic!(
500 "Unexpected sentinel for non-empty sample {:?} (encoded {:?})",
501 sample, enc
502 );
503 }
504 if !sample.is_empty() {
505 assert_vec_u8_eq(&sample, &dec);
506 }
507 }
508 }
509
510 #[crate::ctb_test]
511 fn test_basenb_encode_uuid() {
512 let input: Vec<u8> = vec![
514 0xe8, 0x2e, 0xef, 0x60, 0x19, 0xbc, 0x4a, 0x00, 0xa4, 0x4a, 0x76, 0x3a, 0x34, 0x45, 0xc1, 0x6f,
518 ];
519
520 let expected_uuid = DC_BASENB_EMBEDDED_START_BYTES.to_vec();
526 let remainder = "\u{F800}".as_bytes().to_vec();
527 let expected = [expected_uuid, remainder].concat();
528
529 let enc = assert_vec_u8_ok_eq(
530 &expected,
531 byte_array_to_basenb_17_utf8(&input),
532 );
533
534 let dec = byte_array_from_basenb_17_utf8(&enc).unwrap();
535 if is_sentinel(&dec) && !input.is_empty() {
536 panic!(
537 "Unexpected exception UUID for {:?} (encoded {:?})",
538 input, enc
539 );
540 }
541
542 assert_vec_u8_eq(&input, &dec);
543 }
544
545 #[crate::ctb_test]
546 fn test_armored_round_trip() {
547 let payload = b"Hello Base17b Armored!";
548 let armored = byte_array_to_armored_base17b_utf8(payload).unwrap();
549 let start = ARMORED_BASE17B_UTF8_START_UUID_BYTES;
551 let end = ARMORED_BASE17B_UTF8_END_UUID_BYTES;
552 assert!(armored.starts_with(&start));
553 assert!(armored.ends_with(&end));
554
555 let decoded = byte_array_from_armored_base17b_utf8(&armored);
556 assert_vec_u8_ok_eq(payload, decoded);
557 }
558
559 #[crate::ctb_test]
560 fn test_armored_invalid_prefix() {
561 let payload = b"xyz";
562 let mut armored = byte_array_to_armored_base17b_utf8(payload).unwrap();
563 armored[0] ^= 0xFF;
565 let err = byte_array_from_armored_base17b_utf8(&armored).unwrap_err();
566 assert!(
567 err.to_string().contains("missing or corrupt start UUID"),
568 "Unexpected error: {err}"
569 );
570 }
571
572 #[crate::ctb_test]
573 fn test_armored_invalid_suffix() {
574 let payload = b"xyz";
575 let mut armored = byte_array_to_armored_base17b_utf8(payload).unwrap();
576 let last = armored
578 .len()
579 .checked_sub(1)
580 .expect("armored array is empty");
581 armored[last] ^= 0xAA;
582 let err = byte_array_from_armored_base17b_utf8(&armored).unwrap_err();
583 assert!(
584 err.to_string().contains("missing or corrupt end UUID"),
585 "Unexpected error: {err}"
586 );
587 }
588
589 #[crate::ctb_test]
590 fn test_armored_too_short() {
591 let data: Vec<u8> = vec![1, 2, 3, 4]; let err = byte_array_from_armored_base17b_utf8(&data).unwrap_err();
593 assert!(
594 err.to_string().contains("too short"),
595 "Unexpected error: {err}"
596 );
597 }
598}