compa_decimal 0.2.0

A compact and efficient decimal system using a custom character set for representing large numbers in fewer characters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use num::{PrimInt, ToPrimitive, Unsigned, Zero};
use num_bigint::BigUint;
use std::{any::type_name_of_val, fmt::Display, str::FromStr};

use crate::{error::*, utils::*};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompaDecimal {
    value: String,
}

impl Ord for CompaDecimal {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let compa_digits = get_compa_digits();
        if self.value.len() != other.value.len() {
            return self.value.len().cmp(&other.value.len());
        }
        for (ac, bc) in self.value.chars().zip(other.value.chars()) {
            let ai = compa_digits.iter().position(|&x| x == ac).unwrap();
            let bi = compa_digits.iter().position(|&x| x == bc).unwrap();
            if ai != bi {
                return ai.cmp(&bi);
            }
        }
        std::cmp::Ordering::Equal
    }
}

impl PartialOrd for CompaDecimal {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.value.cmp(&other.value))
    }
}

impl Display for CompaDecimal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.value)
    }
}

impl Default for CompaDecimal {
    fn default() -> Self {
        Self {
            value: "0".to_string(),
        }
    }
}

impl TryFrom<&str> for CompaDecimal {
    type Error = CompaDecimalError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        if !valid_str(value) {
            return Err(CompaDecimalError {
                error_message: "All chars have to be valid compa digits".to_string(),
            });
        }
        Ok(CompaDecimal {
            value: value.to_string(),
        })
    }
}

impl FromStr for CompaDecimal {
    type Err = CompaDecimalError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !valid_str(s) {
            return Err(CompaDecimalError {
                error_message: "All chars have to be valid compa digits".to_string(),
            });
        }
        Ok(CompaDecimal {
            value: s.to_string(),
        })
    }
}

impl PartialEq<&str> for CompaDecimal {
    fn eq(&self, other: &&str) -> bool {
        self.value == *other
    }
}

impl CompaDecimal {
    pub fn new() -> CompaDecimal {
        CompaDecimal {
            value: "0".to_string(),
        }
    }

    pub fn get_value(&self) -> &str {
        &self.value
    }

    pub fn decimal_to_compa<T>(mut num: T) -> Result<CompaDecimal, CompaDecimalError>
    where
        T: PrimInt + Unsigned,
    {
        let compa_digits = get_compa_digits();
        let base = T::from(compa_digits.len()).ok_or_else(|| CompaDecimalError {
            error_message: "Failed to initialise generic type".to_string(),
        })?;
        let mut result = String::new();

        if num == T::zero() {
            return Ok(CompaDecimal::new());
        }

        while num > T::zero() {
            let reminder = (num % base).to_usize().ok_or_else(|| CompaDecimalError {
                error_message: "Failed to convert reminder result to usize".to_string(),
            })?;
            result.push(compa_digits[reminder]);
            num = num / base;
        }

        Ok(CompaDecimal {
            value: result.chars().rev().collect(),
        })
    }

    pub fn biguint_to_compa(num: &BigUint) -> Result<CompaDecimal, CompaDecimalError> {
        let compa_digits = get_compa_digits();
        let base = BigUint::from(compa_digits.len());
        let mut num = num.clone();
        let mut result = String::new();

        if num.is_zero() {
            return Ok(CompaDecimal::new());
        }

        while num > BigUint::zero() {
            let reminder = (&num % &base).to_usize().ok_or_else(|| CompaDecimalError {
                error_message: "Failed to convert reminder to usize".to_string(),
            })?;

            result.push(compa_digits[reminder]);
            num /= &base;
        }

        Ok(CompaDecimal {
            value: result.chars().rev().collect(),
        })
    }

    pub fn to_decimal<T>(&self) -> Result<T, CompaDecimalError>
    where
        T: PrimInt + Unsigned,
    {
        let value_digits: Vec<char> = self.value.chars().collect();
        let compa_digits = get_compa_digits();
        let base = T::from(compa_digits.len()).ok_or_else(|| CompaDecimalError {
            error_message: "Failed to initialise generic type".to_string(),
        })?;
        let mut result: T = T::zero();

        for digit in value_digits {
            match compa_digits.iter().position(|x| x == &digit) {
                Some(position) => {
                    result = T::checked_mul(&result, &base).ok_or_else(|| CompaDecimalError {
                        error_message: format!(
                            "Overflow error! The compa value was too big to store in a {} data type",
                            type_name_of_val(&result)
                        ),
                    })?;
                    result = T::checked_add(&result, &T::from(position).unwrap()).ok_or_else(|| CompaDecimalError {
                        error_message: format!(
                            "Overflow error! The compa value was too big to store in a {} data type",
                            type_name_of_val(&result)
                        ),
                    })?;
                }
                None => {
                    return Err(CompaDecimalError {
                        error_message: format!("Invalid character: {}", digit),
                    });
                }
            }
        }

        Ok(result)
    }

    pub fn to_biguint(&self) -> Result<BigUint, CompaDecimalError> {
        let compa_digits = get_compa_digits();
        let base = BigUint::from(compa_digits.len());
        let mut result = BigUint::zero();

        for digit in self.value.chars() {
            let pos = compa_digits
                .iter()
                .position(|compa_digit| compa_digit == &digit);
            let index = match pos {
                Some(i) => i,
                None => {
                    return Err(CompaDecimalError {
                        error_message: format!("Invalid character: {}", digit),
                    });
                }
            };
            result = &result * &base + BigUint::from(index);
        }
        Ok(result)
    }

    pub fn len(&self) -> usize {
        self.value.len()
    }

    pub fn plus_one(&self) -> Result<CompaDecimal, CompaDecimalError> {
        let compa_digits = get_compa_digits();
        let base = compa_digits.len();
        let mut digits: Vec<char> = self.value.chars().collect();
        let mut carry = true;

        for i in (0..digits.len()).rev() {
            if carry {
                let idx = compa_digits
                    .iter()
                    .position(|&x| x == digits[i])
                    .ok_or_else(|| CompaDecimalError {
                        error_message: format!(
                            "Unexpected error! invalid char found - {}",
                            digits[i]
                        ),
                    })?;
                if idx + 1 == base {
                    digits[i] = compa_digits[0];
                    carry = true;
                } else {
                    digits[i] = compa_digits[idx + 1];
                    carry = false;
                }
            }
        }

        if carry {
            digits.insert(0, compa_digits[1]);
        }

        Ok(CompaDecimal {
            value: digits.into_iter().collect(),
        })
    }

    pub fn minus_one(&self) -> Result<CompaDecimal, CompaDecimalError> {
        let compa_digits = get_compa_digits();
        let mut digits: Vec<char> = self.value.chars().collect();

        if digits.iter().all(|&c| c == '0') {
            return Err(CompaDecimalError {
                error_message: "Cannot decrement below zero".to_string(),
            });
        }

        let mut borrow = true;
        for i in (0..digits.len()).rev() {
            if borrow {
                let idx = compa_digits
                    .iter()
                    .position(|&x| x == digits[i])
                    .ok_or_else(|| CompaDecimalError {
                        error_message: format!(
                            "Unexpected error! invalid char found - {}",
                            digits[i]
                        ),
                    })?;
                if idx == 0 {
                    digits[i] = compa_digits[compa_digits.len() - 1];
                    borrow = true;
                } else {
                    digits[i] = compa_digits[idx - 1];
                    borrow = false;
                }
            }
        }

        while digits.len() > 1 && digits[0] == '0' {
            digits.remove(0);
        }

        Ok(CompaDecimal {
            value: digits.into_iter().collect(),
        })
    }

    pub fn increase_by<T>(&self, amount: T) -> Result<CompaDecimal, CompaDecimalError>
    where
        T: PrimInt + Unsigned,
    {
        let compa_amount = CompaDecimal::decimal_to_compa::<T>(amount)?;
        self.add(compa_amount.get_value())
    }

    pub fn decrease_by<T>(&self, amount: T) -> Result<CompaDecimal, CompaDecimalError>
    where
        T: PrimInt + Unsigned,
    {
        let compa_amount = CompaDecimal::decimal_to_compa::<T>(amount)?;
        self.subtract(compa_amount.get_value())
    }

    pub fn add(&self, additional_value: &str) -> Result<CompaDecimal, CompaDecimalError> {
        if !valid_str(additional_value) {
            return Err(CompaDecimalError {
                error_message: "All chars have to be valid compa digits".to_string(),
            });
        }
        let compa_digits = get_compa_digits();
        let base = compa_digits.len();

        let mut a: Vec<char> = self.value.chars().collect();
        let mut b: Vec<char> = additional_value.chars().collect();

        while a.len() < b.len() {
            a.insert(0, '0');
        }
        while b.len() < a.len() {
            b.insert(0, '0');
        }

        let mut carry = 0;
        let mut result = Vec::with_capacity(a.len() + 1);

        for i in (0..a.len()).rev() {
            let ai = compa_digits.iter().position(|&x| x == a[i]).unwrap();
            let bi = compa_digits.iter().position(|&x| x == b[i]).unwrap();
            let sum = ai + bi + carry;
            result.push(compa_digits[sum % base]);
            carry = sum / base;
        }

        if carry > 0 {
            result.push(compa_digits[carry]);
        }

        result.reverse();
        Ok(CompaDecimal {
            value: result.into_iter().collect(),
        })
    }

    pub fn subtract(&self, subtrahend: &str) -> Result<CompaDecimal, CompaDecimalError> {
        if !valid_str(subtrahend) {
            return Err(CompaDecimalError {
                error_message: "All chars have to be valid compa digits".to_string(),
            });
        }
        let compa_digits = get_compa_digits();
        let base = compa_digits.len();
        match self.cmp_str(subtrahend) {
            Ok(cmp_result) => {
                if cmp_result == std::cmp::Ordering::Less {
                    return Err(CompaDecimalError {
                        error_message: "Result would be negative".to_string(),
                    });
                }
            }
            Err(error) => return Err(error),
        }

        let mut a: Vec<char> = self.value.chars().collect();
        let mut b: Vec<char> = subtrahend.chars().collect();

        while a.len() < b.len() {
            a.insert(0, '0');
        }
        while b.len() < a.len() {
            b.insert(0, '0');
        }

        let mut result = Vec::with_capacity(a.len());
        let mut borrow = 0;

        for i in (0..a.len()).rev() {
            let ai = compa_digits.iter().position(|&x| x == a[i]).unwrap() as isize;
            let bi = compa_digits.iter().position(|&x| x == b[i]).unwrap() as isize;
            let mut diff = ai - bi - borrow;
            if diff < 0 {
                diff += base as isize;
                borrow = 1;
            } else {
                borrow = 0;
            }
            result.push(compa_digits[diff as usize]);
        }

        while result.len() > 1 && result.last() == Some(&'0') {
            result.pop();
        }

        result.reverse();
        Ok(CompaDecimal {
            value: result.into_iter().collect(),
        })
    }

    pub fn cmp_str(&self, comparand: &str) -> Result<std::cmp::Ordering, CompaDecimalError> {
        if !valid_str(comparand) {
            return Err(CompaDecimalError {
                error_message: "All chars have to be valid compa digits".to_string(),
            });
        }
        let compa_digits = get_compa_digits();
        if self.value.len() != comparand.len() {
            return Ok(self.value.len().cmp(&comparand.len()));
        }
        for (ac, bc) in self.value.chars().zip(comparand.chars()) {
            let ai = compa_digits.iter().position(|&x| x == ac).unwrap();
            let bi = compa_digits.iter().position(|&x| x == bc).unwrap();
            if ai != bi {
                return Ok(ai.cmp(&bi));
            }
        }
        Ok(std::cmp::Ordering::Equal)
    }
}