herolib_otoml 0.3.13

OTOML - Canonical TOML serialization format with compact binary representation.
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
//! # ocur - Canonical Currency/Asset Type
//!
//! A lossless, integer-safe monetary amount type that:
//! - Avoids floating-point errors
//! - Supports multiple currency/asset classes
//! - Is deterministic and machine-verifiable
//! - Remains human-auditable
//!
//! ## Format
//!
//! Text: `["asset", amount]` where amount is in micro-units (1/1,000,000)
//! Internal: `(String, u64)`
//!
//! ## Example
//!
//! ```rust
//! use herolib_otoml::OCur;
//!
//! // Create from asset and micro-units
//! let amount = OCur::new("usd", 1_250_000).unwrap(); // 1.25 USD
//!
//! // Display
//! assert_eq!(amount.to_string(), "[\"usd\", 1250000]");
//!
//! // Get human-readable value
//! assert_eq!(amount.as_units(), 1.25);
//! ```

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;

use super::error::{OtomlError, Result};

/// Scale factor: 1 unit = 1,000,000 micro-units
pub const MICRO_UNITS: u64 = 1_000_000;

/// Canonical currency/asset amount type.
///
/// Stores asset code and amount in micro-units (1/1,000,000).
/// This ensures lossless arithmetic without floating-point errors.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct OCur {
    asset: String,
    amount: u64,
}

impl OCur {
    /// Create a new OCur from asset code and micro-units amount.
    ///
    /// # Arguments
    /// * `asset` - Asset code (lowercase, 1-5 chars, alphanumeric)
    /// * `micro_units` - Amount in micro-units (1 unit = 1,000,000 micro-units)
    ///
    /// # Example
    /// ```
    /// use herolib_otoml::OCur;
    ///
    /// // 1.25 USD
    /// let amount = OCur::new("usd", 1_250_000).unwrap();
    ///
    /// // 10 USDC
    /// let amount = OCur::new("usdc", 10_000_000).unwrap();
    /// ```
    pub fn new(asset: &str, micro_units: u64) -> Result<Self> {
        let asset = validate_asset(asset)?;
        Ok(OCur {
            asset,
            amount: micro_units,
        })
    }

    /// Create an OCur from a decimal unit value.
    ///
    /// # Warning
    /// This converts from f64 which may introduce tiny precision errors.
    /// For exact values, prefer `new()` with micro-units.
    ///
    /// # Example
    /// ```
    /// use herolib_otoml::OCur;
    ///
    /// let amount = OCur::from_units("usd", 1.25).unwrap();
    /// assert_eq!(amount.micro_units(), 1_250_000);
    /// ```
    pub fn from_units(asset: &str, units: f64) -> Result<Self> {
        if units < 0.0 {
            return Err(OtomlError::InvalidCurrency(
                "amount cannot be negative".to_string(),
            ));
        }
        let micro_units = (units * MICRO_UNITS as f64).round() as u64;
        Self::new(asset, micro_units)
    }

    /// Get the asset code.
    pub fn asset(&self) -> &str {
        &self.asset
    }

    /// Get the amount in micro-units.
    pub fn micro_units(&self) -> u64 {
        self.amount
    }

    /// Get the amount as decimal units.
    ///
    /// Note: This converts to f64 for display purposes.
    /// For calculations, use `micro_units()` to avoid precision loss.
    pub fn as_units(&self) -> f64 {
        self.amount as f64 / MICRO_UNITS as f64
    }

    /// Create a zero amount for an asset.
    pub fn zero(asset: &str) -> Result<Self> {
        Self::new(asset, 0)
    }

    /// Check if amount is zero.
    pub fn is_zero(&self) -> bool {
        self.amount == 0
    }

    /// Add two amounts (must be same asset).
    pub fn add(&self, other: &OCur) -> Result<OCur> {
        if self.asset != other.asset {
            return Err(OtomlError::InvalidCurrency(format!(
                "cannot add {} and {} (different assets)",
                self.asset, other.asset
            )));
        }
        let sum = self
            .amount
            .checked_add(other.amount)
            .ok_or_else(|| OtomlError::InvalidCurrency("overflow".to_string()))?;
        Ok(OCur {
            asset: self.asset.clone(),
            amount: sum,
        })
    }

    /// Subtract two amounts (must be same asset).
    pub fn sub(&self, other: &OCur) -> Result<OCur> {
        if self.asset != other.asset {
            return Err(OtomlError::InvalidCurrency(format!(
                "cannot subtract {} and {} (different assets)",
                self.asset, other.asset
            )));
        }
        let diff = self
            .amount
            .checked_sub(other.amount)
            .ok_or_else(|| OtomlError::InvalidCurrency("underflow".to_string()))?;
        Ok(OCur {
            asset: self.asset.clone(),
            amount: diff,
        })
    }
}

impl Default for OCur {
    fn default() -> Self {
        OCur {
            asset: "usd".to_string(),
            amount: 0,
        }
    }
}

impl fmt::Display for OCur {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[\"{}\", {}]", self.asset, self.amount)
    }
}

impl FromStr for OCur {
    type Err = OtomlError;

    fn from_str(s: &str) -> Result<Self> {
        // Expected format: ["asset", amount]
        let s = s.trim();

        if !s.starts_with('[') || !s.ends_with(']') {
            return Err(OtomlError::InvalidCurrency(format!(
                "invalid format, expected [\"asset\", amount], got '{}'",
                s
            )));
        }

        let inner = &s[1..s.len() - 1];
        let parts: Vec<&str> = inner.splitn(2, ',').collect();

        if parts.len() != 2 {
            return Err(OtomlError::InvalidCurrency(format!(
                "invalid format, expected [\"asset\", amount], got '{}'",
                s
            )));
        }

        let asset_part = parts[0].trim();
        let amount_part = parts[1].trim();

        // Parse asset (should be quoted string)
        if !asset_part.starts_with('"') || !asset_part.ends_with('"') {
            return Err(OtomlError::InvalidCurrency(format!(
                "asset must be a quoted string, got '{}'",
                asset_part
            )));
        }
        let asset = &asset_part[1..asset_part.len() - 1];

        // Parse amount
        let amount: u64 = amount_part.parse().map_err(|_| {
            OtomlError::InvalidCurrency(format!("invalid amount '{}'", amount_part))
        })?;

        OCur::new(asset, amount)
    }
}

/// Validate and normalize asset code.
fn validate_asset(asset: &str) -> Result<String> {
    let asset = asset.trim().to_lowercase();

    if asset.is_empty() {
        return Err(OtomlError::InvalidCurrency(
            "asset code cannot be empty".to_string(),
        ));
    }

    if asset.len() > 5 {
        return Err(OtomlError::InvalidCurrency(format!(
            "asset code '{}' too long (max 5 chars)",
            asset
        )));
    }

    // Check all chars are lowercase alphanumeric
    for c in asset.chars() {
        if !c.is_ascii_lowercase() && !c.is_ascii_digit() {
            return Err(OtomlError::InvalidCurrency(format!(
                "asset code '{}' contains invalid character '{}' (only a-z and 0-9 allowed)",
                asset, c
            )));
        }
    }

    Ok(asset)
}

impl Serialize for OCur {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Serialize as a tuple [asset, amount]
        use serde::ser::SerializeTuple;
        let mut tup = serializer.serialize_tuple(2)?;
        tup.serialize_element(&self.asset)?;
        tup.serialize_element(&self.amount)?;
        tup.end()
    }
}

impl<'de> Deserialize<'de> for OCur {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        // Deserialize from a tuple [asset, amount]
        let (asset, amount): (String, u64) = Deserialize::deserialize(deserializer)?;
        OCur::new(&asset, amount).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn test_new() {
        let cur = OCur::new("usd", 1_000_000).unwrap();
        assert_eq!(cur.asset(), "usd");
        assert_eq!(cur.micro_units(), 1_000_000);
        assert_eq!(cur.as_units(), 1.0);
    }

    #[test]
    fn test_from_units() {
        let cur = OCur::from_units("usd", 1.25).unwrap();
        assert_eq!(cur.micro_units(), 1_250_000);
        assert_eq!(cur.as_units(), 1.25);
    }

    #[test]
    fn test_display() {
        let cur = OCur::new("usdc", 1_250_000).unwrap();
        assert_eq!(cur.to_string(), "[\"usdc\", 1250000]");
    }

    #[test]
    fn test_parse() {
        let cur: OCur = "[\"usd\", 1250000]".parse().unwrap();
        assert_eq!(cur.asset(), "usd");
        assert_eq!(cur.micro_units(), 1_250_000);
    }

    #[test]
    fn test_asset_validation() {
        // Valid assets
        assert!(OCur::new("usd", 0).is_ok());
        assert!(OCur::new("usdc", 0).is_ok());
        assert!(OCur::new("btc", 0).is_ok());
        assert!(OCur::new("eth", 0).is_ok());
        assert!(OCur::new("gold", 0).is_ok());
        assert!(OCur::new("abc12", 0).is_ok()); // 5 chars with digit

        // Invalid assets
        assert!(OCur::new("", 0).is_err()); // empty
        assert!(OCur::new("toolong", 0).is_err()); // > 5 chars
        assert!(OCur::new("USD", 0).is_ok()); // uppercase gets normalized
        assert!(OCur::new("us-d", 0).is_err()); // hyphen
        assert!(OCur::new("us d", 0).is_err()); // space
        assert!(OCur::new("us_d", 0).is_err()); // underscore
    }

    #[test]
    fn test_asset_normalization() {
        let cur = OCur::new("USD", 100).unwrap();
        assert_eq!(cur.asset(), "usd");

        let cur = OCur::new("BtC", 100).unwrap();
        assert_eq!(cur.asset(), "btc");
    }

    #[test]
    fn test_arithmetic() {
        let a = OCur::new("usd", 1_000_000).unwrap();
        let b = OCur::new("usd", 500_000).unwrap();

        let sum = a.add(&b).unwrap();
        assert_eq!(sum.micro_units(), 1_500_000);

        let diff = a.sub(&b).unwrap();
        assert_eq!(diff.micro_units(), 500_000);
    }

    #[test]
    fn test_arithmetic_different_assets() {
        let a = OCur::new("usd", 1_000_000).unwrap();
        let b = OCur::new("eur", 500_000).unwrap();

        assert!(a.add(&b).is_err());
        assert!(a.sub(&b).is_err());
    }

    #[test]
    fn test_underflow() {
        let a = OCur::new("usd", 100).unwrap();
        let b = OCur::new("usd", 200).unwrap();

        assert!(a.sub(&b).is_err());
    }

    #[test]
    fn test_zero() {
        let cur = OCur::zero("usd").unwrap();
        assert!(cur.is_zero());
        assert_eq!(cur.micro_units(), 0);
    }

    #[test]
    fn test_common_amounts() {
        // $1.00
        let one_dollar = OCur::new("usd", 1_000_000).unwrap();
        assert_eq!(one_dollar.as_units(), 1.0);

        // $0.01 (one cent)
        let one_cent = OCur::new("usd", 10_000).unwrap();
        assert_eq!(one_cent.as_units(), 0.01);

        // $0.25
        let quarter = OCur::new("usd", 250_000).unwrap();
        assert_eq!(quarter.as_units(), 0.25);

        // 1 satoshi (smallest BTC unit, but we use micro-units)
        let tiny_btc = OCur::new("btc", 1).unwrap();
        assert_eq!(tiny_btc.as_units(), 0.000001);
    }

    #[test]
    fn test_serde_roundtrip() {
        use serde::{Deserialize, Serialize};

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Invoice {
            total: OCur,
        }

        let invoice = Invoice {
            total: OCur::new("usdc", 1_250_000).unwrap(),
        };

        let otoml = crate::dump_otoml(&invoice).unwrap();
        // Should serialize as array: total = ["usdc", 1250000]
        assert!(otoml.contains("total = [\"usdc\", 1250000]"));

        let parsed: Invoice = crate::load_otoml(&otoml).unwrap();
        assert_eq!(invoice, parsed);
    }

    #[test]
    fn test_large_amounts() {
        // 1 billion dollars
        let billion = OCur::new("usd", 1_000_000_000_000_000).unwrap();
        assert_eq!(billion.as_units(), 1_000_000_000.0);

        // Max u64 micro-units
        let max = OCur::new("usd", u64::MAX).unwrap();
        assert_eq!(max.micro_units(), u64::MAX);
    }

    #[test]
    fn test_binary_roundtrip() {
        use serde::{Deserialize, Serialize};

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Wallet {
            balance: OCur,
            pending: Option<OCur>,
        }

        let wallet = Wallet {
            balance: OCur::new("usdc", 1_500_000_000).unwrap(),
            pending: Some(OCur::new("usdc", 250_000_000).unwrap()),
        };

        let bytes = crate::dump_obin(&wallet).unwrap();
        let parsed: Wallet = crate::load_obin(&bytes).unwrap();

        assert_eq!(wallet, parsed);
    }

    #[test]
    fn test_default() {
        let cur = OCur::default();
        assert_eq!(cur.asset(), "usd");
        assert_eq!(cur.micro_units(), 0);
        assert!(cur.is_zero());
    }

    #[test]
    fn test_hash() {
        use std::collections::HashSet;

        let c1 = OCur::new("usd", 1_000_000).unwrap();
        let c2 = OCur::new("usd", 1_000_000).unwrap();
        let c3 = OCur::new("usd", 2_000_000).unwrap();
        let c4 = OCur::new("eur", 1_000_000).unwrap(); // different asset

        let mut set = HashSet::new();
        set.insert(c1.clone());
        set.insert(c2); // duplicate
        set.insert(c3);
        set.insert(c4);

        assert_eq!(set.len(), 3);
    }

    #[test]
    fn test_clone() {
        let c1 = OCur::new("btc", 50_000_000).unwrap();
        let c2 = c1.clone();

        assert_eq!(c1, c2);
        assert_eq!(c1.asset(), c2.asset());
        assert_eq!(c1.micro_units(), c2.micro_units());
    }

    #[test]
    fn test_negative_from_units() {
        let result = OCur::from_units("usd", -10.0);
        assert!(result.is_err());
    }

    #[test]
    fn test_overflow_add() {
        let max = OCur::new("usd", u64::MAX).unwrap();
        let one = OCur::new("usd", 1).unwrap();

        let result = max.add(&one);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_edge_cases() {
        // Valid with spaces
        let c: OCur = "[ \"usd\" , 1000000 ]".parse().unwrap();
        assert_eq!(c.micro_units(), 1_000_000);

        // Invalid: no brackets
        assert!("\"usd\", 1000000".parse::<OCur>().is_err());

        // Invalid: wrong delimiter
        assert!("[\"usd\"; 1000000]".parse::<OCur>().is_err());

        // Invalid: negative amount
        assert!("[\"usd\", -1000000]".parse::<OCur>().is_err());
    }

    #[test]
    fn test_crypto_assets() {
        // All valid crypto asset codes
        let assets = ["btc", "eth", "usdc", "usdt", "sol", "matic"];
        for asset in assets {
            let cur = OCur::new(asset, 1_000_000).unwrap();
            assert_eq!(cur.asset(), asset);
        }
    }

    #[test]
    fn test_precision_preservation() {
        // Verify that micro-unit arithmetic is exact
        let mut total = OCur::zero("usd").unwrap();

        // Add $0.01 one hundred times
        for _ in 0..100 {
            let penny = OCur::new("usd", 10_000).unwrap(); // $0.01
            total = total.add(&penny).unwrap();
        }

        // Should be exactly $1.00 = 1,000,000 micro-units
        assert_eq!(total.micro_units(), 1_000_000);
        assert_eq!(total.as_units(), 1.0);
    }
}