1use ctb_utilities::math::exact_float::u64_to_f64_exact;
29
30#[allow(
31 unused_imports,
32 clippy::wildcard_imports,
33 reason = "Standard workspace module prelude"
34)]
35use crate::utilities::*;
36
37pub fn chr(code: u8) -> String {
39 ctb_formats_encoding::chr(
40 ctb_formats_encoding::CharEncoding::mac_roman(),
41 code,
42 )
43}
44
45pub fn asc(s: &str) -> Option<u8> {
47 ctb_formats_encoding::asc(
48 ctb_formats_encoding::CharEncoding::mac_roman(),
49 s,
50 )
51}
52
53pub fn bytepattern(bytes: i64) -> Result<String> {
55 if bytes < 0 {
56 bail!("bytepattern expects a non-negative byte count");
57 }
58
59 let bytes_u64 = u64::try_from(bytes).context("bytes out of range")?;
60
61 let (value, unit) = if bytes_u64 < 1_000 {
62 ((u64_to_f64_exact(bytes_u64)?), "bytes")
63 } else if bytes_u64 < 1_000_000 {
64 ((u64_to_f64_exact(bytes_u64)? / 1_000.0), "kB")
65 } else if bytes_u64 < 1_000_000_000 {
66 ((u64_to_f64_exact(bytes_u64)? / 1_000_000.0), "MB")
67 } else if bytes_u64 < 1_000_000_000_000 {
68 ((u64_to_f64_exact(bytes_u64)? / 1_000_000_000.0), "GB")
69 } else {
70 ((u64_to_f64_exact(bytes_u64)? / 1_000_000_000_000.0), "TB")
71 };
72
73 let rendered = if unit == "bytes" {
74 format!("{bytes_u64} {unit}")
75 } else {
76 let s = fmt_trim_trailing_zeros(format!("{value:.1}"));
77 format!("{s} {unit}")
78 };
79
80 Ok(rendered)
81}
82
83pub fn commastr(number: i64) -> String {
85 let (sign, abs) = if number < 0 {
86 ("-", number.saturating_abs().to_string())
87 } else {
88 ("", number.to_string())
89 };
90
91 format!("{sign}{}", commify_digits(&abs))
92}
93
94pub fn dollarsandcents(number: f64) -> Result<String> {
96 if !number.is_finite() {
97 bail!("dollarsandcents expects a finite number");
98 }
99
100 let cents_total = (number * 100.0).round();
102 if cents_total.abs() > 9_223_372_036_854_775_000.0 {
103 bail!("dollarsandcents number is out of supported range");
104 }
105
106 let cents_total_i64 =
107 f64_to_i64(cents_total).context("cents out of range")?;
108
109 let (neg, cents_total_u64) = if cents_total_i64 < 0 {
110 (
111 true,
112 u64::try_from(cents_total_i64.saturating_abs())
113 .context("abs out of range")?,
114 )
115 } else {
116 (
117 false,
118 u64::try_from(cents_total_i64).context("cents out of range")?,
119 )
120 };
121
122 let dollars = cents_total_u64 / 100;
123 let cents = u8::try_from(cents_total_u64 % 100)
124 .context("cents modulo out of range")?;
125
126 let mut dollars_words = number_to_words(dollars)?;
127 if dollars_words.is_empty() {
128 dollars_words = "zero".to_owned();
129 }
130 let dollars_words = capitalize_first(&dollars_words);
131
132 let dollar_word = if dollars == 1 { "dollar" } else { "dollars" };
133 let cents_word = if cents == 1 { "cent" } else { "cents" };
134
135 let prefix = if neg { "Minus " } else { "" };
136 Ok(format!(
137 "{prefix}{dollars_words} {dollar_word} and {cents:02} {cents_word}"
138 ))
139}
140
141pub fn exportcell<T: std::fmt::Display>(value: T) -> String {
143 value.to_string()
144}
145
146pub fn hex(text: &str) -> Option<u64> {
148 let t = text.trim();
149 if t.is_empty() {
150 return None;
151 }
152 u64::from_str_radix(t, 16).ok()
153}
154
155pub fn hexbyte(number: u8) -> String {
157 format!("{number:02X}")
158}
159
160pub fn hexlong(number: u32) -> String {
162 format!("{number:08X}")
163}
164
165pub fn hexstr(number: u64) -> String {
167 let s = format!("{number:X}");
168 let min_width = 8usize;
169 if s.len() >= min_width {
170 return s;
171 }
172 let pad_len = min_width.saturating_sub(s.len());
173 format!("{}{}", "0".repeat(pad_len), s)
174}
175
176pub fn hexword(number: u16) -> String {
178 format!("{number:04X}")
179}
180
181pub fn money(number: f64) -> Result<String> {
183 if !number.is_finite() {
184 bail!("money expects a finite number");
185 }
186
187 let sign = if number < 0.0 { "-" } else { "" };
188 let abs = number.abs();
189
190 let rounded = (abs * 100.0).round() / 100.0;
191 let whole = rounded.trunc();
192 let frac = (rounded - whole).abs();
193
194 let whole_i64 = f64_to_i64(whole).context("whole dollars out of range")?;
195 let cents =
196 f64_to_i64((frac * 100.0).round()).context("cents out of range")?;
197
198 let cents_u8 = u8::try_from(cents).context("cents out of range")?;
199 Ok(format!(
200 "{sign}{}.{}",
201 commastr(whole_i64),
202 format!("{cents_u8:02}")
203 ))
204}
205
206pub fn nth(number: i64) -> String {
208 let abs = number.saturating_abs();
209 let suffix = match abs % 100 {
210 11..=13 => "th",
211 _ => match abs % 10 {
212 1 => "st",
213 2 => "nd",
214 3 => "rd",
215 _ => "th",
216 },
217 };
218 format!("{number}{suffix}")
219}
220
221pub fn places(number: f64, places: usize) -> Result<String> {
223 if !number.is_finite() {
224 bail!("places expects a finite number");
225 }
226
227 let places_i32 = i32::try_from(places).context("places too large")?;
228 let factor = 10_f64
229 .powi(places_i32)
230 .min(1e18);
232
233 let sign = if number < 0.0 { "-" } else { "" };
234 let abs = number.abs();
235
236 let truncated = (abs * factor).trunc() / factor;
237 let mut s = format!("{truncated:.places$}",);
238
239 if places == 0 {
240 if let Some((int, _)) = s.split_once('.') {
242 s = int.to_owned();
243 }
244 }
245
246 Ok(format!("{sign}{s}"))
247}
248
249#[derive(Clone, Copy, Debug, Eq, PartialEq)]
250pub enum RadixSpec {
252 Base(u32),
254 Binary,
255 Octal,
256 Hex,
257}
258
259impl RadixSpec {
260 pub fn base(self) -> u32 {
262 match self {
263 Self::Base(b) => b,
264 Self::Binary => 2,
265 Self::Octal => 8,
266 Self::Hex => 16,
267 }
268 }
269}
270
271impl TryFrom<&str> for RadixSpec {
272 type Error = anyhow::Error;
273
274 fn try_from(value: &str) -> Result<Self> {
275 let v = value.trim().to_ascii_lowercase();
276 match v.as_str() {
277 "binary" => Ok(Self::Binary),
278 "octal" => Ok(Self::Octal),
279 "hex" => Ok(Self::Hex),
280 _ => {
281 let base = u32::from_str_radix(&v, 10)
282 .context("invalid radix string")?;
283 Ok(Self::Base(base))
284 }
285 }
286 }
287}
288
289#[derive(Clone, Debug, Eq, PartialEq)]
290pub enum RadixValue {
292 Number(i128),
293 RawBinary(Vec<u8>),
294}
295
296pub fn radix(radix: RadixSpec, text: &str) -> Result<RadixValue> {
300 let base = radix.base();
301 if !matches!(base, 2 | 4 | 8 | 16 | 32) {
302 bail!("unsupported radix base: {base}");
303 }
304
305 let t = text.trim();
306 if t.is_empty() {
307 bail!("radix expects non-empty text");
308 }
309
310 if base == 16 && t.len() > 8 {
312 let bytes = parse_hex_bytes(t)?;
313 return Ok(RadixValue::RawBinary(bytes));
314 }
315 if base == 2 && t.len() > 32 {
316 let bytes = parse_binary_bits_to_bytes(t)?;
317 return Ok(RadixValue::RawBinary(bytes));
318 }
319
320 let value = parse_int_custom_base(t, base)?;
321 Ok(RadixValue::Number(value))
322}
323
324pub enum RadixStrInput<'a> {
326 Number(i128),
327 RawBinary(&'a [u8]),
328}
329
330pub fn radixstr(radix: RadixSpec, input: RadixStrInput<'_>) -> Result<String> {
332 let base = radix.base();
333 if !matches!(base, 2 | 4 | 8 | 16 | 32) {
334 bail!("unsupported radix base: {base}");
335 }
336
337 match input {
338 RadixStrInput::Number(n) => format_number_in_base(radix, n),
339 RadixStrInput::RawBinary(bytes) => format_bytes_in_base(radix, bytes),
340 }
341}
342
343pub fn scientificnotation(number: f64) -> Result<String> {
345 if !number.is_finite() {
346 bail!("scientificnotation expects a finite number");
347 }
348
349 let s = format!("{number:.3e}");
350 let Some((mantissa, exp)) = s.split_once('e') else {
351 bail!("unexpected scientific format");
352 };
353
354 let exp_i32 =
355 i32::from_str_radix(exp, 10).context("unexpected exponent")?;
356 let sign = if exp_i32 < 0 { "-" } else { "+" };
357 let abs_exp = exp_i32.saturating_abs();
358
359 Ok(format!("{mantissa}e{sign}{abs_exp}"))
360}
361
362pub fn str_(number: f64) -> Result<String> {
364 if !number.is_finite() {
365 bail!("str expects a finite number");
366 }
367 Ok(fmt_trim_trailing_zeros(number.to_string()))
368}
369
370pub fn val(text: &str) -> Option<i64> {
372 let t = text.trim_start();
373 let mut digits = String::new();
374
375 for ch in t.chars() {
376 if ch.is_ascii_digit() {
377 digits.push(ch);
378 } else {
379 break;
380 }
381 }
382
383 if digits.is_empty() {
384 return None;
385 }
386
387 i64::from_str_radix(&digits, 10).ok()
388}
389
390fn fmt_trim_trailing_zeros(mut s: String) -> String {
393 if let Some((head, tail)) = s.split_once('.') {
394 let tail_trim = tail.trim_end_matches('0').to_owned();
395 if tail_trim.is_empty() {
396 return head.to_owned();
397 }
398 s = format!("{head}.{tail_trim}");
399 }
400 s
401}
402
403#[expect(
404 clippy::expect_used,
405 reason = "Division by constant 3 is non-zero and cannot fail"
406)]
407fn commify_digits(digits: &str) -> String {
408 let extra = digits.len().checked_div(3).expect("3 is non-zero");
409 let mut out = String::with_capacity(digits.len().saturating_add(extra));
410 let mut count = 0usize;
411
412 for ch in digits.chars().rev() {
413 if count == 3 {
414 out.push(',');
415 count = 0;
416 }
417 out.push(ch);
418 count = count.saturating_add(1);
419 }
420
421 out.chars().rev().collect()
422}
423
424fn f64_to_i64(n: f64) -> Option<i64> {
425 let truncated = n.trunc();
427 let s = fmt_trim_trailing_zeros(truncated.to_string());
428 i64::from_str_radix(&s, 10).ok()
429}
430
431fn capitalize_first(s: &str) -> String {
432 let mut chars = s.chars();
433 let Some(first) = chars.next() else {
434 return String::new();
435 };
436 let rest: String = chars.collect();
437 format!("{}{}", first.to_ascii_uppercase(), rest)
438}
439
440fn number_to_words(n: u64) -> Result<String> {
441 if n == 0 {
442 return Ok("zero".to_owned());
443 }
444
445 const SCALES: [&str; 5] =
446 ["", "thousand", "million", "billion", "trillion"];
447
448 let mut parts: Vec<String> = Vec::new();
449 let mut remaining = n;
450 let mut scale_idx = 0usize;
451
452 while remaining > 0 {
453 let chunk = u16::try_from(remaining % 1000)
454 .context("Number modulo 1000 must fit in u16")?;
455 if chunk != 0 {
456 let mut chunk_words = chunk_to_words(chunk);
457 let scale = SCALES
458 .get(scale_idx)
459 .copied()
460 .ok_or_else(|| anyhow::anyhow!("Scale index out of bounds"))?;
461 if !scale.is_empty() {
462 chunk_words.push(scale.to_owned());
463 }
464 parts.push(chunk_words.join(" "));
465 }
466
467 remaining /= 1000;
468 scale_idx = scale_idx.saturating_add(1);
469 }
470
471 parts.reverse();
472 Ok(parts.join(" "))
473}
474
475fn chunk_to_words(n: u16) -> Vec<String> {
476 let hundreds = n / 100;
477 let rem = n % 100;
478
479 let mut out: Vec<String> = Vec::new();
480
481 if hundreds != 0 {
482 out.push(unit_word(hundreds).to_owned());
483 out.push("hundred".to_owned());
484 }
485
486 if rem != 0 {
487 if rem < 10 {
488 out.push(unit_word(rem).to_owned());
489 } else if rem < 20 {
490 out.push(teen_word(rem).to_owned());
491 } else {
492 let tens = rem / 10;
493 let ones = rem % 10;
494 out.push(tens_word(tens).to_owned());
495 if ones != 0 {
496 out.push(unit_word(ones).to_owned());
497 }
498 }
499 }
500
501 out
502}
503
504fn unit_word(n: u16) -> &'static str {
505 match n {
506 0 => "zero",
507 1 => "one",
508 2 => "two",
509 3 => "three",
510 4 => "four",
511 5 => "five",
512 6 => "six",
513 7 => "seven",
514 8 => "eight",
515 9 => "nine",
516 _ => "zero",
517 }
518}
519
520fn teen_word(n: u16) -> &'static str {
521 match n {
522 10 => "ten",
523 11 => "eleven",
524 12 => "twelve",
525 13 => "thirteen",
526 14 => "fourteen",
527 15 => "fifteen",
528 16 => "sixteen",
529 17 => "seventeen",
530 18 => "eighteen",
531 19 => "nineteen",
532 _ => "ten",
533 }
534}
535
536fn tens_word(n: u16) -> &'static str {
537 match n {
538 2 => "twenty",
539 3 => "thirty",
540 4 => "forty",
541 5 => "fifty",
542 6 => "sixty",
543 7 => "seventy",
544 8 => "eighty",
545 9 => "ninety",
546 _ => "zero",
547 }
548}
549
550fn parse_hex_bytes(text: &str) -> Result<Vec<u8>> {
551 let t = text.trim();
552 if !t.len().is_multiple_of(2) {
553 bail!("hex raw binary input must have an even number of digits");
554 }
555
556 let mut out = Vec::with_capacity(t.len() / 2);
557 let mut it = t.as_bytes().chunks_exact(2);
558
559 for pair in &mut it {
560 let s = std::str::from_utf8(pair).context("non-utf8 hex")?;
561 let b = u8::from_str_radix(s, 16).context("invalid hex byte")?;
562 out.push(b);
563 }
564
565 Ok(out)
566}
567
568fn parse_binary_bits_to_bytes(text: &str) -> Result<Vec<u8>> {
569 let t = text.trim();
570 if t.chars().any(|c| c != '0' && c != '1') {
571 bail!("binary input contains non-bit characters");
572 }
573
574 #[expect(
576 clippy::expect_used,
577 reason = "Modulo by constant 8 is non-zero and cannot fail"
578 )]
579 let rem = t.len().checked_rem(8).expect("8 is non-zero");
580 let pad = if rem == 0 {
581 0
582 } else {
583 8_usize.saturating_sub(rem)
584 };
585 let padded = format!("{}{}", "0".repeat(pad), t);
586
587 let mut out = Vec::with_capacity(padded.len() / 8);
588 for chunk in padded.as_bytes().chunks_exact(8) {
589 let s = std::str::from_utf8(chunk).context("non-utf8 bits")?;
590 let b = u8::from_str_radix(s, 2).context("invalid byte bits")?;
591 out.push(b);
592 }
593
594 Ok(out)
595}
596
597fn parse_int_custom_base(text: &str, base: u32) -> Result<i128> {
598 let t = text.trim();
599 let mut value: i128 = 0;
600
601 for ch in t.chars() {
602 let digit =
603 digit_value(ch).with_context(|| format!("invalid digit '{ch}'"))?;
604 let digit_u32 = u32::from(digit);
605 if digit_u32 >= base {
606 bail!("digit '{ch}' out of range for base {base}");
607 }
608
609 let base_i128 =
610 i128::from_str_radix(&base.to_string(), 10).context("base conv")?;
611 value = value
612 .checked_mul(base_i128)
613 .context("overflow in radix parsing")?;
614 value = value
615 .checked_add(i128::from(digit))
616 .context("overflow in radix parsing")?;
617 }
618
619 Ok(value)
620}
621
622fn digit_value(ch: char) -> Result<u8> {
623 if ch.is_ascii_digit() {
624 let s = ch.to_string();
625 let v = u8::from_str_radix(&s, 10).context("digit parse")?;
626 return Ok(v);
627 }
628
629 let up = ch.to_ascii_uppercase();
630 if up.is_ascii_uppercase() {
631 let idx = u32::from(up)
632 .checked_sub(u32::from('A'))
633 .context("letter digit underflow")?;
634 let v_u8 = u8::try_from(idx)
635 .context("letter digit out of range")?
636 .saturating_add(10);
637 return Ok(v_u8);
638 }
639
640 bail!("unsupported digit character");
641}
642
643fn format_number_in_base(radix: RadixSpec, n: i128) -> Result<String> {
644 let base = radix.base();
645 if n < 0 {
646 bail!("radixstr does not support negative numbers");
647 }
648
649 let mut value = n;
650 let base_i128 =
651 i128::from_str_radix(&base.to_string(), 10).context("base conv")?;
652
653 if value == 0 {
654 return Ok("0".to_owned());
655 }
656
657 let mut digits: Vec<char> = Vec::new();
658 while value > 0 {
659 let rem = (value
660 .checked_rem(base_i128)
661 .context("remainder by base failed")?)
662 .try_into()
663 .context("remainder out of range")?;
664 digits.push(digit_char(rem)?);
665 value = value
666 .checked_div(base_i128)
667 .context("division by base failed")?;
668 }
669
670 digits.reverse();
671 let mut s: String = digits.into_iter().collect();
672
673 if base == 2 {
675 let max_bits = 32usize;
676 if s.len() < max_bits {
677 let pad = max_bits.saturating_sub(s.len());
678 s = format!("{}{}", "0".repeat(pad), s);
679 }
680 }
681
682 Ok(s)
683}
684
685fn format_bytes_in_base(radix: RadixSpec, bytes: &[u8]) -> Result<String> {
686 let base = radix.base();
687 match base {
688 16 => Ok(bytes.iter().map(|b| format!("{b:02X}")).collect()),
689 2 => Ok(bytes.iter().map(|b| format!("{b:08b}")).collect()),
690 8 | 4 | 32 => {
691 let mut n: i128 = 0;
693 for &b in bytes {
694 let shift = 8i32;
695 let n_next = n
696 .checked_mul(i128::from(1u16 << shift))
697 .context("overflow building integer from bytes")?;
698 n = n_next
699 .checked_add(i128::from(b))
700 .context("overflow building integer from bytes")?;
701 }
702 format_number_in_base(radix, n)
703 }
704 _ => bail!("unsupported base for bytes"),
705 }
706}
707
708fn digit_char(d: u8) -> Result<char> {
709 match d {
710 0..=9 => {
711 let ch_code = u32::from(b'0').saturating_add(u32::from(d));
712 std::char::from_u32(ch_code).ok_or_else(|| {
713 anyhow::anyhow!("Invalid ASCII digit codepoint {ch_code}")
714 })
715 }
716 10..=35 => {
717 let idx = u32::from(d.saturating_sub(10));
718 let ch_code = u32::from(b'A').saturating_add(idx);
719 std::char::from_u32(ch_code).ok_or_else(|| {
720 anyhow::anyhow!("Invalid ASCII letter codepoint {ch_code}")
721 })
722 }
723 _ => bail!("Digit value {d} is outside supported base range 0..35"),
724 }
725}
726
727#[cfg(test)]
728#[allow(
729 clippy::panic,
730 clippy::expect_used,
731 clippy::unwrap_used,
732 clippy::unwrap_in_result,
733 clippy::panic_in_result_fn,
734 clippy::indexing_slicing,
735 clippy::arithmetic_side_effects,
736 reason = "Standard repository test boilerplate"
737)]
738mod tests {
739 use super::*;
740
741 #[crate::ctb_test]
742 fn chr_asc_roundtrip_basic() {
743 let s = chr(65);
744 assert_eq!(asc(&s), Some(65));
745 }
746
747 #[crate::ctb_test]
748 fn commastr_formats() {
749 assert_eq!(commastr(1234567), "1,234,567");
750 assert_eq!(commastr(-987654), "-987,654");
751 }
752
753 #[crate::ctb_test]
754 fn hex_helpers() {
755 assert_eq!(hex("0C2"), Some(194));
756 assert_eq!(hexbyte(68), "44");
757 assert_eq!(hexword(68), "0044");
758 assert_eq!(hexlong(68), "00000044");
759 assert_eq!(hexstr(68), "00000044");
760 }
761
762 #[crate::ctb_test]
763 fn val_parses_leading_digits() {
764 assert_eq!(val("123 S. Main St."), Some(123));
765 assert_eq!(val(" 123 S. Main St."), Some(123));
766 assert_eq!(val("No digits"), None);
767 }
768
769 #[crate::ctb_test]
770 fn nth_ordinals() {
771 assert_eq!(nth(1), "1st");
772 assert_eq!(nth(2), "2nd");
773 assert_eq!(nth(3), "3rd");
774 assert_eq!(nth(4), "4th");
775 assert_eq!(nth(11), "11th");
776 assert_eq!(nth(12), "12th");
777 assert_eq!(nth(13), "13th");
778 assert_eq!(nth(21), "21st");
779 }
780
781 #[crate::ctb_test]
782 fn places_truncates() -> Result<()> {
783 assert_eq!(places(1.239, 2)?, "1.23");
784 assert_eq!(places(-1.2, 3)?, "-1.200");
785 assert_eq!(places(9.999, 0)?, "9");
786 Ok(())
787 }
788
789 #[crate::ctb_test]
790 fn scientificnotation_formats() -> Result<()> {
791 assert_eq!(scientificnotation(98120.0)?, "9.812e+4");
792 Ok(())
793 }
794
795 #[crate::ctb_test]
796 fn money_formats() -> Result<()> {
797 assert_eq!(money(98123.45)?, "98,123.45");
798 assert_eq!(money(-12.3)?, "-12.30");
799 Ok(())
800 }
801
802 #[crate::ctb_test]
803 fn dollarsandcents_words() -> Result<()> {
804 assert_eq!(
805 dollarsandcents(98123.45)?,
806 "Ninety eight thousand one hundred twenty three dollars and 45 cents"
807 );
808 assert_eq!(
809 dollarsandcents(98123.05)?,
810 "Ninety eight thousand one hundred twenty three dollars and 05 cents"
811 );
812 Ok(())
813 }
814
815 #[crate::ctb_test]
816 fn radix_number_and_raw_binary() -> Result<()> {
817 assert_eq!(radix(RadixSpec::Hex, "FF")?, RadixValue::Number(255));
818
819 assert_eq!(
821 radix(RadixSpec::Hex, "0102030405060708")?,
822 RadixValue::RawBinary(vec![1, 2, 3, 4, 5, 6, 7, 8])
823 );
824
825 assert_eq!(
826 radixstr(
827 RadixSpec::Hex,
828 RadixStrInput::RawBinary(&[1, 2, 3, 4, 5, 6, 7, 8])
829 )?,
830 "0102030405060708"
831 );
832
833 let v = radix(RadixSpec::Binary, "1".repeat(40).as_str())?;
835 let RadixValue::RawBinary(bytes) = v else {
836 bail!("expected raw binary from long binary input");
837 };
838 assert_eq!(bytes.len(), 5);
839
840 Ok(())
841 }
842}