sankhya 1.0.0

sankhya — Ancient mathematical systems: Mayan, Babylonian, Egyptian, Vedic, Chinese, Greek, Roman, Islamic, and cross-civilizational epoch correlation
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Roman numeral system.
//!
//! Implements conversion between Roman numerals and decimal values,
//! Roman numeral arithmetic, and validation of proper subtractive notation.
//!
//! # Historical Context
//!
//! Roman numerals emerged in ancient Rome (c. 500 BCE) and remained the
//! dominant numeral system in Europe until the late Middle Ages. The system
//! is additive-subtractive: I=1, V=5, X=10, L=50, C=100, D=500, M=1000.
//! Subtractive pairs (IV=4, IX=9, XL=40, XC=90, CD=400, CM=900) were
//! standardized in medieval usage. The system has no zero and no place value,
//! making arithmetic cumbersome compared to positional systems — a key reason
//! Hindu-Arabic numerals eventually replaced it.

use serde::{Deserialize, Serialize};

use crate::error::{Result, SankhyaError};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// The maximum value representable in standard Roman numerals.
/// Values above 3999 require non-standard extensions (vinculum, etc.).
pub const MAX_VALUE: u32 = 3999;

/// Ordered table of Roman numeral symbols and their values (descending).
const ROMAN_TABLE: &[(u32, &str)] = &[
    (1000, "M"),
    (900, "CM"),
    (500, "D"),
    (400, "CD"),
    (100, "C"),
    (90, "XC"),
    (50, "L"),
    (40, "XL"),
    (10, "X"),
    (9, "IX"),
    (5, "V"),
    (4, "IV"),
    (1, "I"),
];

// ---------------------------------------------------------------------------
// Core type
// ---------------------------------------------------------------------------

/// A Roman numeral with its string representation and decimal value.
///
/// Guaranteed to be in the range 1–3999 and in canonical (standard
/// subtractive) form.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RomanNumeral {
    /// The decimal value (1–3999).
    value: u32,
    /// The canonical Roman numeral string.
    text: String,
}

impl RomanNumeral {
    /// Create a Roman numeral from a decimal value.
    ///
    /// # Errors
    ///
    /// Returns [`SankhyaError::InvalidBase`] if `value` is 0 or exceeds 3999.
    pub fn from_value(value: u32) -> Result<Self> {
        if value == 0 || value > MAX_VALUE {
            return Err(SankhyaError::InvalidBase(format!(
                "Roman numeral value {value} out of range 1..{MAX_VALUE}"
            )));
        }
        Ok(Self {
            text: to_roman(value),
            value,
        })
    }

    /// Parse a Roman numeral string.
    ///
    /// Accepts both uppercase and lowercase input. The string is validated
    /// for correct subtractive notation and character set.
    ///
    /// # Errors
    ///
    /// Returns [`SankhyaError::InvalidBase`] if the string contains invalid
    /// characters or is not a valid Roman numeral.
    pub fn parse(s: &str) -> Result<Self> {
        let value = from_roman(s)?;
        Ok(Self {
            text: to_roman(value),
            value,
        })
    }

    /// The decimal value of this numeral.
    #[must_use]
    #[inline]
    pub fn value(&self) -> u32 {
        self.value
    }

    /// The canonical Roman numeral string.
    #[must_use]
    #[inline]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Add two Roman numerals, returning a new numeral.
    ///
    /// # Errors
    ///
    /// Returns [`SankhyaError::OverflowError`] if the sum exceeds 3999.
    pub fn add(&self, other: &Self) -> Result<Self> {
        roman_add(self.value, other.value)
    }

    /// Subtract another Roman numeral from this one.
    ///
    /// # Errors
    ///
    /// Returns [`SankhyaError::ComputationError`] if the result would be
    /// zero or negative (Roman numerals have no zero).
    pub fn subtract(&self, other: &Self) -> Result<Self> {
        roman_subtract(self.value, other.value)
    }

    /// Multiply two Roman numerals.
    ///
    /// # Errors
    ///
    /// Returns [`SankhyaError::OverflowError`] if the product exceeds 3999.
    pub fn multiply(&self, other: &Self) -> Result<Self> {
        roman_multiply(self.value, other.value)
    }

    /// Divide this numeral by another, returning quotient and remainder.
    ///
    /// # Errors
    ///
    /// Returns [`SankhyaError::InvalidFraction`] if the divisor is zero
    /// (which cannot happen with valid `RomanNumeral` values, but guards
    /// against future API changes).
    pub fn divide(&self, other: &Self) -> Result<(Self, Option<Self>)> {
        roman_divide(self.value, other.value)
    }
}

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

// ---------------------------------------------------------------------------
// Conversion functions
// ---------------------------------------------------------------------------

/// Convert a decimal value (1–3999) to a Roman numeral string.
///
/// Returns the canonical subtractive form (e.g., 4 → "IV", not "IIII").
///
/// # Panics
///
/// This is an internal function that assumes valid input. Use
/// [`RomanNumeral::from_value`] for validated conversion.
#[must_use]
fn to_roman(mut n: u32) -> String {
    let mut result = String::new();
    for &(val, sym) in ROMAN_TABLE {
        while n >= val {
            result.push_str(sym);
            n -= val;
        }
    }
    result
}

/// Convert a decimal value to a Roman numeral string.
///
/// # Errors
///
/// Returns [`SankhyaError::InvalidBase`] if `value` is 0 or exceeds 3999.
pub fn to_roman_str(value: u32) -> Result<String> {
    if value == 0 || value > MAX_VALUE {
        return Err(SankhyaError::InvalidBase(format!(
            "Roman numeral value {value} out of range 1..{MAX_VALUE}"
        )));
    }
    Ok(to_roman(value))
}

/// Parse a Roman numeral string to its decimal value.
///
/// Accepts uppercase and lowercase. Validates that:
/// - All characters are valid Roman numeral symbols
/// - The string represents a value in the range 1–3999
/// - The parsed value round-trips to the canonical form
///
/// # Errors
///
/// Returns [`SankhyaError::InvalidBase`] if the input is empty, contains
/// invalid characters, or is not a valid Roman numeral.
pub fn from_roman(s: &str) -> Result<u32> {
    if s.is_empty() {
        return Err(SankhyaError::InvalidBase(
            "empty string is not a valid Roman numeral".into(),
        ));
    }

    let upper = s.to_uppercase();
    let mut total: u32 = 0;
    let mut prev_value: u32 = 0;

    for ch in upper.chars().rev() {
        let val = char_value(ch)?;
        if val < prev_value {
            total = total
                .checked_sub(val)
                .ok_or_else(|| SankhyaError::ComputationError("Roman numeral underflow".into()))?;
        } else {
            total = total
                .checked_add(val)
                .ok_or_else(|| SankhyaError::OverflowError("Roman numeral overflow".into()))?;
        }
        prev_value = val;
    }

    if total == 0 || total > MAX_VALUE {
        return Err(SankhyaError::InvalidBase(format!(
            "Roman numeral '{s}' produces value {total} out of range 1..{MAX_VALUE}"
        )));
    }

    // Validate canonical form: round-trip check
    let canonical = to_roman(total);
    if canonical != upper {
        return Err(SankhyaError::InvalidBase(format!(
            "'{s}' is not canonical Roman notation (expected '{canonical}' for {total})"
        )));
    }

    Ok(total)
}

/// Map a single Roman numeral character to its value.
fn char_value(ch: char) -> Result<u32> {
    match ch {
        'I' => Ok(1),
        'V' => Ok(5),
        'X' => Ok(10),
        'L' => Ok(50),
        'C' => Ok(100),
        'D' => Ok(500),
        'M' => Ok(1000),
        _ => Err(SankhyaError::InvalidBase(format!(
            "'{ch}' is not a valid Roman numeral character"
        ))),
    }
}

// ---------------------------------------------------------------------------
// Arithmetic
// ---------------------------------------------------------------------------

/// Add two values and return the result as a Roman numeral.
///
/// # Errors
///
/// Returns [`SankhyaError::OverflowError`] if the sum exceeds 3999.
pub fn roman_add(a: u32, b: u32) -> Result<RomanNumeral> {
    let sum = a.checked_add(b).ok_or_else(|| {
        SankhyaError::OverflowError(format!("Roman addition overflow: {a} + {b}"))
    })?;
    RomanNumeral::from_value(sum)
}

/// Subtract b from a and return the result as a Roman numeral.
///
/// # Errors
///
/// Returns [`SankhyaError::ComputationError`] if a ≤ b (Roman numerals
/// have no zero or negative values).
pub fn roman_subtract(a: u32, b: u32) -> Result<RomanNumeral> {
    if a <= b {
        return Err(SankhyaError::ComputationError(format!(
            "Roman subtraction would produce zero or negative: {a} - {b}"
        )));
    }
    RomanNumeral::from_value(a - b)
}

/// Multiply two values and return the result as a Roman numeral.
///
/// # Errors
///
/// Returns [`SankhyaError::OverflowError`] if the product exceeds 3999.
pub fn roman_multiply(a: u32, b: u32) -> Result<RomanNumeral> {
    let product = a.checked_mul(b).ok_or_else(|| {
        SankhyaError::OverflowError(format!("Roman multiplication overflow: {a} * {b}"))
    })?;
    RomanNumeral::from_value(product)
}

/// Divide a by b, returning (quotient, remainder) as Roman numerals.
///
/// The remainder is `None` if the division is exact.
///
/// # Errors
///
/// Returns [`SankhyaError::InvalidFraction`] if `b` is zero.
/// Returns [`SankhyaError::ComputationError`] if the quotient is zero
/// (i.e., a < b).
pub fn roman_divide(a: u32, b: u32) -> Result<(RomanNumeral, Option<RomanNumeral>)> {
    if b == 0 {
        return Err(SankhyaError::InvalidFraction("division by zero".into()));
    }

    let quotient = a / b;
    let remainder = a % b;

    if quotient == 0 {
        return Err(SankhyaError::ComputationError(format!(
            "Roman division {a} / {b} produces zero quotient"
        )));
    }

    let q = RomanNumeral::from_value(quotient)?;
    let r = if remainder > 0 {
        Some(RomanNumeral::from_value(remainder)?)
    } else {
        None
    };

    Ok((q, r))
}

// ---------------------------------------------------------------------------
// Utility functions
// ---------------------------------------------------------------------------

/// Check if a string is a valid Roman numeral in canonical form.
#[must_use]
pub fn is_valid_roman(s: &str) -> bool {
    from_roman(s).is_ok()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- Conversion --

    #[test]
    fn basic_values() {
        assert_eq!(to_roman_str(1).unwrap(), "I");
        assert_eq!(to_roman_str(4).unwrap(), "IV");
        assert_eq!(to_roman_str(5).unwrap(), "V");
        assert_eq!(to_roman_str(9).unwrap(), "IX");
        assert_eq!(to_roman_str(10).unwrap(), "X");
        assert_eq!(to_roman_str(40).unwrap(), "XL");
        assert_eq!(to_roman_str(50).unwrap(), "L");
        assert_eq!(to_roman_str(90).unwrap(), "XC");
        assert_eq!(to_roman_str(100).unwrap(), "C");
        assert_eq!(to_roman_str(400).unwrap(), "CD");
        assert_eq!(to_roman_str(500).unwrap(), "D");
        assert_eq!(to_roman_str(900).unwrap(), "CM");
        assert_eq!(to_roman_str(1000).unwrap(), "M");
    }

    #[test]
    fn compound_values() {
        assert_eq!(to_roman_str(14).unwrap(), "XIV");
        assert_eq!(to_roman_str(42).unwrap(), "XLII");
        assert_eq!(to_roman_str(99).unwrap(), "XCIX");
        assert_eq!(to_roman_str(399).unwrap(), "CCCXCIX");
        assert_eq!(to_roman_str(1776).unwrap(), "MDCCLXXVI");
        assert_eq!(to_roman_str(1999).unwrap(), "MCMXCIX");
        assert_eq!(to_roman_str(2024).unwrap(), "MMXXIV");
        assert_eq!(to_roman_str(3999).unwrap(), "MMMCMXCIX");
    }

    #[test]
    fn parse_roundtrip() {
        for n in 1..=3999 {
            let roman = to_roman_str(n).unwrap();
            let parsed = from_roman(&roman).unwrap();
            assert_eq!(parsed, n, "roundtrip failed for {n} = {roman}");
        }
    }

    #[test]
    fn parse_lowercase() {
        assert_eq!(from_roman("xiv").unwrap(), 14);
        assert_eq!(from_roman("mcmxcix").unwrap(), 1999);
    }

    #[test]
    fn parse_invalid_chars() {
        assert!(from_roman("ABC").is_err());
        assert!(from_roman("IVX2").is_err());
    }

    #[test]
    fn parse_non_canonical() {
        // IIII should be IV
        assert!(from_roman("IIII").is_err());
        // VV should be X
        assert!(from_roman("VV").is_err());
        // IC is not standard (should be XCIX for 99)
        assert!(from_roman("IC").is_err());
    }

    #[test]
    fn parse_empty() {
        assert!(from_roman("").is_err());
    }

    #[test]
    fn value_zero_errors() {
        assert!(to_roman_str(0).is_err());
        assert!(RomanNumeral::from_value(0).is_err());
    }

    #[test]
    fn value_too_large_errors() {
        assert!(to_roman_str(4000).is_err());
        assert!(RomanNumeral::from_value(4000).is_err());
    }

    // -- Arithmetic --

    #[test]
    fn add_basic() {
        let r = roman_add(10, 5).unwrap();
        assert_eq!(r.value(), 15);
        assert_eq!(r.text(), "XV");
    }

    #[test]
    fn add_overflow() {
        assert!(roman_add(3999, 1).is_err());
    }

    #[test]
    fn subtract_basic() {
        let r = roman_subtract(10, 3).unwrap();
        assert_eq!(r.value(), 7);
        assert_eq!(r.text(), "VII");
    }

    #[test]
    fn subtract_to_zero_errors() {
        assert!(roman_subtract(5, 5).is_err());
        assert!(roman_subtract(3, 7).is_err());
    }

    #[test]
    fn multiply_basic() {
        let r = roman_multiply(7, 8).unwrap();
        assert_eq!(r.value(), 56);
        assert_eq!(r.text(), "LVI");
    }

    #[test]
    fn multiply_overflow() {
        assert!(roman_multiply(100, 100).is_err());
    }

    #[test]
    fn divide_exact() {
        let (q, r) = roman_divide(10, 5).unwrap();
        assert_eq!(q.value(), 2);
        assert!(r.is_none());
    }

    #[test]
    fn divide_with_remainder() {
        let (q, r) = roman_divide(10, 3).unwrap();
        assert_eq!(q.value(), 3);
        let rem = r.unwrap();
        assert_eq!(rem.value(), 1);
    }

    #[test]
    fn divide_by_zero_errors() {
        assert!(roman_divide(10, 0).is_err());
    }

    #[test]
    fn divide_zero_quotient_errors() {
        assert!(roman_divide(3, 5).is_err());
    }

    // -- RomanNumeral type --

    #[test]
    fn numeral_methods() {
        let x = RomanNumeral::from_value(42).unwrap();
        assert_eq!(x.value(), 42);
        assert_eq!(x.text(), "XLII");
        assert_eq!(x.to_string(), "XLII");

        let y = RomanNumeral::parse("XIV").unwrap();
        assert_eq!(y.value(), 14);
    }

    #[test]
    fn numeral_arithmetic() {
        let a = RomanNumeral::from_value(100).unwrap();
        let b = RomanNumeral::from_value(50).unwrap();

        assert_eq!(a.add(&b).unwrap().value(), 150);
        assert_eq!(a.subtract(&b).unwrap().value(), 50);
        assert!(a.multiply(&b).is_err()); // 100 * 50 = 5000 > 3999

        let (q, r) = a.divide(&b).unwrap();
        assert_eq!(q.value(), 2);
        assert!(r.is_none());
    }

    #[test]
    fn is_valid() {
        assert!(is_valid_roman("XIV"));
        assert!(is_valid_roman("mcmxcix"));
        assert!(!is_valid_roman("IIII"));
        assert!(!is_valid_roman("ABC"));
        assert!(!is_valid_roman(""));
    }

    // -- Serde --

    #[test]
    fn serde_roundtrip() {
        let n = RomanNumeral::from_value(1776).unwrap();
        let json = serde_json::to_string(&n).unwrap();
        let back: RomanNumeral = serde_json::from_str(&json).unwrap();
        assert_eq!(n, back);
    }
}