1use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedSub, Num, One, Signed, Zero};
6use std::ops::{Add, Div, Mul, Sub};
7use std::{
8 fmt,
9 ops::{Neg, Rem},
10};
11
12#[derive(Clone, PartialEq, Eq, Debug)]
18pub struct TextCodedInteger {
19 text: String,
21}
22
23impl TextCodedInteger {
24 pub fn new<T: ToString>(value: T) -> Self {
30 let s = value.to_string();
31 let (negative, digits) = match s.strip_prefix('-') {
32 Some(rest) => (true, rest),
33 None => (false, s.as_str()),
34 };
35 if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
36 panic!("TextCodedInteger can only store decimal digits with an optional leading '-'");
37 }
38 let trimmed = digits.trim_start_matches('0');
39 let digits = if trimmed.is_empty() { "0" } else { trimmed };
40 if negative && digits != "0" {
41 Self { text: format!("-{digits}") }
42 } else {
43 Self { text: digits.to_string() }
44 }
45 }
46
47 fn is_negative(&self) -> bool {
49 self.text.starts_with('-')
50 }
51
52 fn digits(&self) -> &str {
54 if self.is_negative() {
55 &self.text[1..]
56 } else {
57 &self.text
58 }
59 }
60
61 fn add_strings(a: &str, b: &str) -> String {
63 let mut result = String::new();
64 let mut carry = 0;
65
66 let a_bytes = a.as_bytes();
67 let b_bytes = b.as_bytes();
68
69 let mut i = a_bytes.len() as isize - 1;
70 let mut j = b_bytes.len() as isize - 1;
71
72 while i >= 0 || j >= 0 || carry > 0 {
73 let digit_a = if i >= 0 {
74 a_bytes[i as usize] - b'0'
75 } else {
76 0
77 };
78 let digit_b = if j >= 0 {
79 b_bytes[j as usize] - b'0'
80 } else {
81 0
82 };
83
84 let sum = digit_a + digit_b + carry;
85 carry = sum / 10;
86 result.push(((sum % 10) + b'0') as char);
87
88 i -= 1;
89 j -= 1;
90 }
91
92 result.chars().rev().collect()
93 }
94
95 fn sub_strings(a: &str, b: &str) -> String {
97 let mut result = String::new();
98 let mut borrow = 0;
99
100 let a_bytes = a.as_bytes();
101 let b_bytes = b.as_bytes();
102
103 let mut i = a_bytes.len() as isize - 1;
104 let mut j = b_bytes.len() as isize - 1;
105
106 while i >= 0 {
107 let mut digit_a = (a_bytes[i as usize] - b'0') as i8 - borrow;
108 let digit_b = if j >= 0 {
109 (b_bytes[j as usize] - b'0') as i8
110 } else {
111 0
112 };
113
114 if digit_a < digit_b {
115 digit_a += 10;
116 borrow = 1;
117 } else {
118 borrow = 0;
119 }
120
121 result.push(((digit_a - digit_b) as u8 + b'0') as char);
122
123 i -= 1;
124 j -= 1;
125 }
126
127 while result.len() > 1 && result.ends_with('0') {
129 result.pop();
130 }
131
132 result.chars().rev().collect()
133 }
134
135 fn abs_ge(&self, other: &Self) -> bool {
137 let a = self.digits();
138 let b = other.digits();
139 if a.len() != b.len() {
140 a.len() > b.len()
141 } else {
142 a >= b
143 }
144 }
145
146 fn numeric_ge(a: &str, b: &str) -> bool {
149 if a.len() != b.len() {
150 return a.len() > b.len();
151 }
152 a >= b }
154}
155
156impl Default for TextCodedInteger {
157 fn default() -> Self {
158 Self::new("0")
159 }
160}
161
162impl PartialOrd for TextCodedInteger {
163 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
164 Some(self.cmp(other))
165 }
166}
167
168impl Ord for TextCodedInteger {
171 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
172 let magnitude = |a: &str, b: &str| a.len().cmp(&b.len()).then_with(|| a.cmp(b));
173 match (self.is_negative(), other.is_negative()) {
174 (false, true) => std::cmp::Ordering::Greater,
175 (true, false) => std::cmp::Ordering::Less,
176 (false, false) => magnitude(self.digits(), other.digits()),
177 (true, true) => magnitude(other.digits(), self.digits()),
178 }
179 }
180}
181
182impl fmt::Display for TextCodedInteger {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 write!(f, "{}", self.text)
186 }
187}
188
189impl Add for TextCodedInteger {
191 type Output = Self;
192 fn add(self, rhs: Self) -> Self::Output {
193 match (self.is_negative(), rhs.is_negative()) {
194 (false, false) => Self {
195 text: Self::add_strings(&self.text, &rhs.text),
196 },
197 (true, true) => Self {
198 text: format!("-{}", Self::add_strings(self.digits(), rhs.digits())),
199 },
200 (false, true) => {
201 if self.abs_ge(&rhs) {
202 Self {
203 text: Self::sub_strings(&self.text, rhs.digits()),
204 }
205 } else {
206 Self {
207 text: format!("-{}", Self::sub_strings(rhs.digits(), &self.text)),
208 }
209 }
210 }
211 (true, false) => {
212 if rhs.abs_ge(&self) {
213 Self {
214 text: Self::sub_strings(&rhs.text, self.digits()),
215 }
216 } else {
217 Self {
218 text: format!("-{}", Self::sub_strings(self.digits(), &rhs.text)),
219 }
220 }
221 }
222 }
223 }
224}
225
226impl Sub for TextCodedInteger {
227 type Output = Self;
228 fn sub(self, rhs: Self) -> Self::Output {
229 self.add(Self {
230 text: if rhs.is_negative() {
231 rhs.digits().to_string()
232 } else {
233 format!("-{}", rhs.text)
234 },
235 })
236 }
237}
238
239impl Mul for TextCodedInteger {
240 type Output = Self;
241
242 fn mul(self, rhs: Self) -> Self::Output {
243 let neg = self.is_negative() ^ rhs.is_negative();
244 let a = self.digits();
245 let b = rhs.digits();
246
247 let mut result = vec![0; a.len() + b.len()];
249
250 let a_bytes: Vec<u8> = a.bytes().rev().map(|b| b - b'0').collect();
251 let b_bytes: Vec<u8> = b.bytes().rev().map(|b| b - b'0').collect();
252
253 for i in 0..a_bytes.len() {
255 let mut carry = 0;
256 for j in 0..b_bytes.len() {
257 let sum = result[i + j] + a_bytes[i] * b_bytes[j] + carry;
258 result[i + j] = sum % 10;
259 carry = sum / 10;
260 }
261 if carry > 0 {
262 result[i + b_bytes.len()] += carry;
263 }
264 }
265
266 while result.len() > 1 && *result.last().unwrap() == 0 {
268 result.pop();
269 }
270
271 let s: String = result
272 .into_iter()
273 .rev()
274 .map(|d| (d + b'0') as char)
275 .collect();
276 if neg && s != "0" {
277 Self::new(format!("-{}", s))
278 } else {
279 Self::new(s)
280 }
281 }
282}
283
284impl Neg for TextCodedInteger {
285 type Output = Self;
286
287 fn neg(self) -> Self::Output {
288 if self.is_zero() {
289 self
290 } else if self.is_negative() {
291 Self::new(self.digits())
292 } else {
293 Self::new(format!("-{}", self.text))
294 }
295 }
296}
297
298impl Div for TextCodedInteger {
299 type Output = Self;
300
301 fn div(self, rhs: Self) -> Self::Output {
302 let (q, _) = Self::div_mod_manual(&self, &rhs);
303 q
304 }
305}
306
307impl Rem for TextCodedInteger {
308 type Output = Self;
309
310 fn rem(self, rhs: Self) -> Self::Output {
311 let (_, r) = Self::div_mod_manual(&self, &rhs);
312 r
313 }
314}
315
316impl TextCodedInteger {
317 pub fn div_mod_manual(dividend: &Self, divisor: &Self) -> (Self, Self) {
320 if divisor.is_zero() {
321 panic!("Division by zero");
322 }
323
324 let neg_quotient = dividend.is_negative() ^ divisor.is_negative();
325 let neg_remainder = dividend.is_negative();
326
327 let dividend_abs = dividend.digits().to_string();
328 let divisor_abs = divisor.digits();
329
330 if !Self::numeric_ge(÷nd_abs, divisor_abs) {
331 return (Self::zero(), dividend.clone());
332 }
333
334 let mut quotient = String::new();
335 let mut remainder = String::new();
336
337 for c in dividend_abs.chars() {
338 remainder.push(c);
339 while remainder.starts_with('0') && remainder.len() > 1 {
340 remainder.remove(0);
341 }
342
343 let mut q_digit = 0u8;
344 while Self::numeric_ge(&remainder, divisor_abs) {
345 remainder = Self::sub_strings(&remainder, divisor_abs);
346 q_digit += 1;
347 }
348
349 quotient.push((q_digit + b'0') as char);
350 }
351
352 while quotient.starts_with('0') && quotient.len() > 1 {
354 quotient.remove(0);
355 }
356
357 let quotient = if neg_quotient && quotient != "0" {
358 Self::new(format!("-{}", quotient))
359 } else {
360 Self::new(quotient)
361 };
362
363 let remainder = if neg_remainder && remainder != "0" {
364 Self::new(format!("-{}", remainder))
365 } else {
366 Self::new(remainder)
367 };
368
369 (quotient, remainder)
370 }
371}
372
373impl Zero for TextCodedInteger {
375 fn zero() -> Self {
376 Self::new("0")
377 }
378 fn is_zero(&self) -> bool {
379 self.digits() == "0"
380 }
381}
382
383impl One for TextCodedInteger {
384 fn one() -> Self {
385 Self::new("1")
386 }
387}
388
389impl Num for TextCodedInteger {
391 type FromStrRadixErr = std::num::ParseIntError;
392
393 fn from_str_radix(s: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
394 if radix != 10 {
395 panic!("TextCodedInteger only supports decimal strings for now");
396 }
397 Ok(Self::new(s))
398 }
399}
400
401impl Signed for TextCodedInteger {
403 fn abs(&self) -> Self {
404 if self.is_negative() {
405 Self::new(self.digits())
406 } else {
407 self.clone()
408 }
409 }
410 fn abs_sub(&self, rhs: &Self) -> Self {
412 if self <= rhs {
413 Self::zero()
414 } else {
415 self.clone() - rhs.clone()
416 }
417 }
418 fn signum(&self) -> Self {
419 if self.is_zero() {
420 Self::zero()
421 } else if self.is_negative() {
422 Self::new("-1")
423 } else {
424 Self::one()
425 }
426 }
427 fn is_positive(&self) -> bool {
428 !self.is_negative() && !self.is_zero()
429 }
430 fn is_negative(&self) -> bool {
431 self.is_negative()
432 }
433}
434
435impl CheckedAdd for TextCodedInteger {
437 fn checked_add(&self, rhs: &Self) -> Option<Self> {
438 Some(self.clone() + rhs.clone())
439 }
440}
441impl CheckedSub for TextCodedInteger {
442 fn checked_sub(&self, rhs: &Self) -> Option<Self> {
443 Some(self.clone() - rhs.clone())
444 }
445}
446impl CheckedMul for TextCodedInteger {
447 fn checked_mul(&self, rhs: &Self) -> Option<Self> {
449 Some(self.clone() * rhs.clone())
450 }
451}
452impl CheckedDiv for TextCodedInteger {
453 fn checked_div(&self, rhs: &Self) -> Option<Self> {
455 (!rhs.is_zero()).then(|| self.clone() / rhs.clone())
456 }
457}
458
459#[cfg(test)]
460mod test {
461 use super::*;
462
463 #[test]
464 fn values_compare_and_normalise_numerically() {
465 let t = |v: i64| TextCodedInteger::new(v);
466 assert!(t(9) < t(10), "9 < 10 (the text \"9\" sorts after \"10\")");
467 assert!(t(-5) < t(-3) && t(-3) < t(0) && t(0) < t(2));
468 assert_eq!(TextCodedInteger::new("007"), t(7));
469 assert_eq!(TextCodedInteger::new("-0"), t(0));
470 let mut v: Vec<TextCodedInteger> = [12, -7, 100, 3, -120, 0].iter().map(|&x| t(x)).collect();
471 v.sort();
472 assert_eq!(v, [-120, -7, 0, 3, 12, 100].iter().map(|&x| t(x)).collect::<Vec<_>>());
473 assert_eq!(TextCodedInteger::default(), t(0));
474 for bad in ["", "-", "5-", "--5", "1a"] {
475 assert!(std::panic::catch_unwind(|| TextCodedInteger::new(bad)).is_err(), "{bad:?}");
476 }
477 }
478
479 #[test]
480 fn abs_sub_and_checked_operations_follow_num_traits() {
481 let t = |v: i64| TextCodedInteger::new(v);
482 assert_eq!(t(7).abs_sub(&t(3)), t(4));
483 assert_eq!(t(3).abs_sub(&t(7)), t(0));
484 assert_eq!(t(-2).abs_sub(&t(-9)), t(7));
485 assert_eq!(t(12).checked_mul(&t(-11)), Some(t(-132)));
486 assert_eq!(t(12).checked_div(&t(5)), Some(t(2)));
487 assert_eq!(t(12).checked_div(&t(0)), None);
488 }
489
490 #[test]
491 fn test_text_coded_integer() {
492 let a_true = 12345;
493 let b_true = -6789;
494 let a = TextCodedInteger::new(a_true);
495 let b = TextCodedInteger::new(b_true);
496
497 let c = a.clone() + b.clone();
498 assert_eq!(c, TextCodedInteger::new(a_true + b_true));
499 let c = a.clone() - b.clone();
500 assert_eq!(c, TextCodedInteger::new(a_true - b_true));
501 let c = a.clone() * b.clone();
502 assert_eq!(c, TextCodedInteger::new(a_true * b_true));
503 let c = a.clone() / b.clone();
504 assert_eq!(c, TextCodedInteger::new(a_true / b_true));
505 }
506}