moneylib 0.13.0

Library to deal with money in Rust.
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
use std::{
    fmt::{Debug, Display},
    iter::Sum,
    marker::PhantomData,
    str::FromStr,
};

#[cfg(feature = "accounting")]
use crate::AccountingOps;

use crate::{
    BaseMoney, BaseOps, Decimal, MoneyError, MoneyOps,
    base::{Amount, DecimalNumber},
    macros::dec,
    parse::{
        parse_code_locale_separator, parse_comma_thousands_separator,
        parse_dot_thousands_separator, parse_symbol_comma_thousands_separator,
        parse_symbol_dot_thousands_separator, parse_symbol_locale_separator,
    },
};
use crate::{Currency, MoneyFormatter};
use rust_decimal::{MathematicalOps, prelude::FromPrimitive};

/// Represents a monetary value with a specific currency and amount.
///
/// `Money` is a value type that represents amount of money along with its currency.
/// It's statically checked at compile time for currency match so it will not mixing with other currencies.
/// It automatically rounds the amount to the currency's minor unit precision using
/// bankers rounding rule.
///
/// # Key Features
///
/// - **Type Safety**: Provides compile-time and runtime checks to ensure valid state.
/// - **Precision**: Uses 128-bit fixed-precision decimal for accurate calculations.
/// - **Automatic Rounding**: Rounds to currency's minor unit after each operation.
/// - **Zero-Cost**: `Copy` type with no heap allocations and currency metadata is zero-sized type.
///
/// # Examples
///
/// ```
/// use moneylib::{Money, Currency, BaseMoney, macros::dec, iso::USD};
/// use std::str::FromStr;
///
/// // Create money from currency and amount
/// let money = Money::<USD>::new(dec!(100.50)).unwrap();
/// assert_eq!(money.amount(), dec!(100.50));
///
/// // Parse money from string
/// let money = Money::<USD>::from_str("1234.56").unwrap();
/// assert_eq!(money.amount(), dec!(1234.56));
/// ```
///
/// # See Also
///
/// - [`BaseMoney`] trait for core money operations and accessors
/// - [`BaseOps`] trait for arithmetic and comparison operations
/// - [`MoneyFormatter`] trait for custom formatting and rounding
#[derive(Copy, PartialEq, Eq)]
pub struct Money<C: Currency> {
    amount: Decimal,
    _currency: PhantomData<C>,
}

impl<C> Money<C>
where
    C: Currency,
{
    /// Creates a new `Money` instance from Decimal
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Money, Currency, macros::dec, BaseMoney, iso::USD};
    ///
    /// let money = Money::<USD>::from_decimal(dec!(123.309));
    /// assert_eq!(money.amount(), dec!(123.31));
    /// ```
    #[inline]
    pub fn from_decimal(amount: Decimal) -> Self {
        Self {
            amount,
            _currency: PhantomData,
        }
        .round()
    }

    /// Creates a new `Money` from minor amount i128.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Money, Currency, macros::dec, BaseMoney, iso::USD};
    ///
    /// let money = Money::<USD>::from_minor(12302).unwrap();
    /// assert_eq!(money.amount(), dec!(123.02));
    /// ```
    #[inline]
    pub fn from_minor(minor_amount: i128) -> Result<Self, MoneyError> {
        Ok(Self {
            amount: Decimal::from_i128(minor_amount)
                .ok_or(MoneyError::OverflowError)?
                .checked_div(
                    dec!(10)
                        .checked_powu(C::MINOR_UNIT.into())
                        .ok_or(MoneyError::OverflowError)?,
                )
                .ok_or(MoneyError::OverflowError)?,
            _currency: PhantomData,
        }
        .round())
    }

    /// Implementation of string parsing for `Money` using comma as the thousands separator
    /// and dot as the decimal separator.
    ///
    /// Parses a string representation of money in the format `"CCC amount"` where
    /// `CCC` is a currency code (1-15 letters) and `amount` uses commas for thousand grouping
    /// and an optional dot for the decimal separator (e.g., `"USD 1,234.56"`).
    ///
    /// The currency code must be a valid ISO 4217 alphabetic code.
    ///
    /// For strings that use dot as the thousands separator and comma as the decimal
    /// separator (e.g., `"EUR 1.234,56"`), use
    /// [`Money::from_code_dot_thousands`] instead.
    ///
    /// Accepts negative amount CCC -amount
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Money, macros::dec, BaseMoney, iso::{USD, GBP}};
    /// use std::str::FromStr;
    ///
    /// // Comma as thousand separator, dot as decimal
    /// let money = Money::<USD>::from_code_comma_thousands("USD 1,234.56").unwrap();
    /// assert_eq!(money.amount(), dec!(1234.56));
    /// assert_eq!(money.code(), "USD");
    ///
    /// // No thousand separator
    /// let money = Money::<GBP>::from_code_comma_thousands("GBP 123.45").unwrap();
    /// assert_eq!(money.amount(), dec!(123.45));
    ///
    /// // Large amount with multiple comma thousand separators
    /// let money = Money::<USD>::from_code_comma_thousands("USD 1,000,000.99").unwrap();
    /// assert_eq!(money.amount(), dec!(1000000.99));
    ///
    /// // Error: invalid format (currency must come first)
    /// assert!(Money::<USD>::from_code_comma_thousands("100.00 USD").is_err());
    ///
    /// // Error: currencies mismatch
    /// assert!(Money::<USD>::from_code_comma_thousands("EUR 100.00").is_err());
    ///
    /// // Error: dot thousands / comma decimal format not supported here
    /// assert!(Money::<USD>::from_code_comma_thousands("USD 1.234,56").is_err());
    /// ```
    pub fn from_code_comma_thousands(s: &str) -> Result<Self, MoneyError> {
        let s = s.trim();

        if let Some((currency_code, amount_str)) = parse_comma_thousands_separator(s) {
            if currency_code != C::CODE {
                return Err(MoneyError::CurrencyMismatchError(
                    currency_code.into(),
                    C::CODE.into(),
                ));
            }
            return Ok(Self::from_decimal(Decimal::from_str(&amount_str).map_err(
                |err| MoneyError::ParseStrError(err.to_string().into()),
            )?));
        }

        Err(MoneyError::ParseStrError(format!(
            "failed parsing {}, use format: <CODE> <AMOUNT> where <CODE> is defined and <AMOUNT> is comma-separated thousands(optional) and dot-separated decimal",
            s
        ).into()))
    }

    /// Creates a new `Money` instance by parsing a string that uses dot as the
    /// thousands separator and comma as the decimal separator.
    ///
    /// The format is `"CCC amount"` where `CCC` is a currency code (1-15 letters) and
    /// `amount` uses dots for thousand grouping and an optional comma for the decimal
    /// separator (e.g., `"EUR 1.234,56"`).
    ///
    /// # Arguments
    ///
    /// * `s` - A string slice in the format `"CCC amount"`, e.g. `"EUR 1.234,56"`
    ///
    /// # Errors
    ///
    /// Returns [`MoneyError::CurrencyMismatchError`] if the currency code in the string does
    /// not match the currency type parameter `C`.
    ///
    /// Returns [`MoneyError::ParseStrError`] if the string is not in the expected format.
    ///
    /// Accepts negative amount CCC -amount
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Money, macros::dec, BaseMoney, iso::{EUR, USD}};
    ///
    /// // Dot as thousand separator, comma as decimal
    /// let money = Money::<EUR>::from_code_dot_thousands("EUR 1.234,56").unwrap();
    /// assert_eq!(money.amount(), dec!(1234.56));
    /// assert_eq!(money.code(), "EUR");
    ///
    /// // Large amount with multiple dot thousand separators
    /// let money = Money::<EUR>::from_code_dot_thousands("EUR 1.000.000,99").unwrap();
    /// assert_eq!(money.amount(), dec!(1000000.99));
    ///
    /// // No thousand separator, only decimal comma
    /// let money = Money::<EUR>::from_code_dot_thousands("EUR 100,50").unwrap();
    /// assert_eq!(money.amount(), dec!(100.50));
    ///
    /// // Integer amount without decimal part
    /// let money = Money::<EUR>::from_code_dot_thousands("EUR 1.234").unwrap();
    /// assert_eq!(money.amount(), dec!(1234.00));
    ///
    /// // Error: currencies mismatch
    /// assert!(Money::<USD>::from_code_dot_thousands("EUR 1.234,56").is_err());
    ///
    /// // Error: invalid format (wrong separator style)
    /// assert!(Money::<EUR>::from_code_dot_thousands("EUR 1,234.56").is_err());
    /// ```
    pub fn from_code_dot_thousands(s: &str) -> Result<Self, MoneyError> {
        let s = s.trim();

        if let Some((currency_code, amount_str)) = parse_dot_thousands_separator(s) {
            if currency_code != C::CODE {
                return Err(MoneyError::CurrencyMismatchError(
                    currency_code.into(),
                    C::CODE.into(),
                ));
            }
            return Ok(Self::from_decimal(Decimal::from_str(&amount_str).map_err(
                |err| MoneyError::ParseStrError(err.to_string().into()),
            )?));
        }

        Err(MoneyError::ParseStrError(format!(
            "failed parsing {}, use format: <CODE> <AMOUNT> where <CODE> is defined and <AMOUNT> is dot-separated thousands(optional) and comma-separated decimal",
            s
        ).into()))
    }

    /// Parse from string with symbol, comma-separated thousands and dot-separated decimal.
    /// Example: $1,234.22 into USD 1234.22
    pub fn from_symbol_comma_thousands(s: &str) -> Result<Self, MoneyError> {
        let s = s.trim();

        if let Some((symbol, amount_str)) = parse_symbol_comma_thousands_separator::<C>(s) {
            if symbol != C::SYMBOL {
                return Err(MoneyError::CurrencyMismatchError(
                    symbol.into(),
                    C::SYMBOL.into(),
                ));
            }

            return Ok(Self::from_decimal(Decimal::from_str(&amount_str).map_err(
                |err| MoneyError::ParseStrError(err.to_string().into()),
            )?));
        }

        Err(MoneyError::ParseStrError(format!(
            "failed parsing {}, use format: <SYMBOL><AMOUNT> where <SYMBOL> is defined and <AMOUNT> is comma-separated thousands(optional) and dot-separated decimal",
            s
        ).into()))
    }

    /// Parse from string with symbol, dot-separated thousands and comma-separated decimal.
    /// Example: $1.234,22 into USD 1234.22
    pub fn from_symbol_dot_thousands(s: &str) -> Result<Self, MoneyError> {
        let s = s.trim();

        if let Some((symbol, amount_str)) = parse_symbol_dot_thousands_separator::<C>(s) {
            if symbol != C::SYMBOL {
                return Err(MoneyError::CurrencyMismatchError(
                    symbol.into(),
                    C::SYMBOL.into(),
                ));
            }

            return Ok(Self::from_decimal(Decimal::from_str(&amount_str).map_err(
                |err| MoneyError::ParseStrError(err.to_string().into()),
            )?));
        }

        Err(MoneyError::ParseStrError(format!(
            "failed parsing {}, use format: <SYMBOL><AMOUNT> where <SYMBOL> is defined and <AMOUNT> is dot-separated thousands(optional) and comma-separated decimal",
            s
        ).into()))
    }

    /// Parse from string with code, locale thousands and decimal separators.
    ///
    /// Code is space separated with amount.
    ///
    /// Currencies locale separators are from here: <https://docs.rs/currencylib>
    ///
    /// # Example
    /// ```
    /// use moneylib::{Money, money, iso::CHF, dec, BaseMoney};
    ///
    /// let money = Money::<CHF>::from_code_locale_separator("CHF 1'123'456.23").unwrap();
    /// assert_eq!(money.code(), "CHF");
    /// assert_eq!(money.symbol(), "â‚£");
    /// assert_eq!(money.amount(), dec!(1123456.23));
    /// assert_eq!(money, money!(CHF, 1123456.23));
    /// ```
    pub fn from_code_locale_separator(s: &str) -> Result<Self, MoneyError> {
        let s = s.trim();

        if let Some((code, amount_str)) = parse_code_locale_separator::<C>(s) {
            if code != C::CODE {
                return Err(MoneyError::CurrencyMismatchError(
                    code.into(),
                    C::CODE.into(),
                ));
            }

            return Self::from_str(&amount_str)
                .map_err(|err| MoneyError::ParseStrError(err.to_string().into()));
        }

        Err(MoneyError::ParseStrError(format!(
            "failed parsing {}, use format: <CODE> <AMOUNT> where <CODE> is defined and <AMOUNT> is separated by locale separators",
            s
        ).into()))
    }

    /// Parse from string with symbol, locale thousands and decimal separators.
    ///
    /// There's no space between symbol and amount.
    ///
    /// Currencies locale separators are from here: <https://docs.rs/currencylib>
    ///
    /// # Example
    /// ```
    /// use moneylib::{Money, money, iso::CHF, dec, BaseMoney};
    ///
    /// let money = Money::<CHF>::from_symbol_locale_separator("â‚£1'123'456.23").unwrap();
    /// assert_eq!(money.code(), "CHF");
    /// assert_eq!(money.symbol(), "â‚£");
    /// assert_eq!(money.amount(), dec!(1123456.23));
    /// assert_eq!(money, money!(CHF, 1123456.23));
    /// ```
    pub fn from_symbol_locale_separator(s: &str) -> Result<Self, MoneyError> {
        let s = s.trim();

        if let Some((symbol, amount_str)) = parse_symbol_locale_separator::<C>(s) {
            if symbol != C::SYMBOL {
                return Err(MoneyError::CurrencyMismatchError(
                    symbol.into(),
                    C::SYMBOL.into(),
                ));
            }

            return Self::from_str(&amount_str)
                .map_err(|err| MoneyError::ParseStrError(err.to_string().into()));
        }

        Err(MoneyError::ParseStrError(format!(
            "failed parsing {}, use format: <SYMBOL><AMOUNT> where <SYMBOL> is defined and <AMOUNT> is separated by locale separators",
            s
        ).into()))
    }
}

impl<C: Currency> Default for Money<C> {
    /// Returns money with zero amount.
    fn default() -> Self {
        Self {
            amount: Decimal::default(),
            _currency: PhantomData,
        }
    }
}

impl<C: Currency> Ord for Money<C>
where
    C: Currency + PartialEq + Eq,
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.amount.cmp(&other.amount)
    }
}

impl<C> PartialOrd for Money<C>
where
    C: Currency + PartialEq + Eq,
{
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<C> Amount<C> for Money<C>
where
    C: Currency,
{
    fn get_decimal(&self) -> Option<Decimal> {
        Some(self.amount())
    }
}

impl<C> FromStr for Money<C>
where
    C: Currency,
{
    type Err = MoneyError;

    /// Parse money from string number.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{BaseMoney, Money, iso::USD, money, dec};
    /// use std::str::FromStr;
    ///
    /// let money = Money::<USD>::from_str("12334.4439").unwrap();
    /// assert_eq!(money, money!(USD, 12334.44));
    /// assert_eq!(money.amount(), dec!(12334.44));
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        let dec_num = Decimal::from_str(s).map_err(|err| {
            MoneyError::ParseStrError(format!("failed parsing money from string: {}", err).into())
        })?;
        Ok(Self::from_decimal(dec_num))
    }
}

impl<C: Currency> Clone for Money<C> {
    fn clone(&self) -> Self {
        Self {
            amount: self.amount,
            _currency: PhantomData,
        }
    }
}

/// Implementation of formatted display for `Money`.
///
/// Displays the money using the default format, which is the currency code
/// followed by the amount with thousand and decimal separators.
///
/// # Examples
///
/// ```
/// use moneylib::{BaseMoney, Money, Currency, macros::dec, iso::{USD, JPY}};
///
/// let money = Money::<USD>::from_decimal(dec!(1234.56));
/// assert_eq!(format!("{}", money), "USD 1,234.56");
///
/// let money = Money::<JPY>::from_minor(1234).unwrap();
/// assert_eq!(format!("{}", money), "JPY 1,234");
///
/// // Negative amounts
/// let money = Money::<USD>::new(dec!(-1234.56)).unwrap();
/// assert_eq!(format!("{}", money), "USD -1,234.56");
/// ```
impl<C> Display for Money<C>
where
    C: Currency,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.display())
    }
}

impl<C> Debug for Money<C>
where
    C: Currency,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Money({}, {})", C::CODE, self.amount)
    }
}

impl<C: Currency> Sum for Money<C> {
    /// Sum all moneys
    ///
    /// WARN: PANIC!!! if overflowed.
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.fold(Money::default(), |acc, b| acc + b)
    }
}

impl<'a, C: Currency> Sum<&'a Money<C>> for Money<C> {
    /// Sum all moneys(borrowed)
    ///
    /// WARN: PANIC!!! if overflowed.
    fn sum<I: Iterator<Item = &'a Money<C>>>(iter: I) -> Self {
        iter.fold(Money::default(), |acc, b| acc + b.clone())
    }
}

impl<C> BaseMoney<C> for Money<C>
where
    C: Currency,
{
    #[inline]
    fn new(amount: impl DecimalNumber) -> Result<Self, MoneyError> {
        Ok(Self {
            amount: amount.get_decimal().ok_or(MoneyError::OverflowError)?,
            _currency: PhantomData,
        }
        .round())
    }

    #[inline]
    fn amount(&self) -> Decimal {
        self.amount
    }

    #[inline]
    fn round(self) -> Self {
        Self {
            amount: self.amount().round_dp(C::MINOR_UNIT.into()),
            _currency: PhantomData,
        }
    }

    #[inline]
    fn round_with(self, decimal_points: u32, strategy: crate::base::RoundingStrategy) -> Self {
        Self {
            amount: self
                .amount
                .round_dp_with_strategy(decimal_points, strategy.into()),
            _currency: PhantomData,
        }
    }

    #[inline]
    fn truncate(&self) -> Self {
        Self::from_decimal(self.amount.trunc())
    }

    #[inline]
    fn truncate_with(&self, scale: u32) -> Self {
        Self::from_decimal(self.amount.trunc_with_scale(scale))
    }
}

impl<C> BaseOps<C> for Money<C>
where
    C: Currency,
{
    #[inline]
    fn abs(&self) -> Self {
        Self::from_decimal(self.amount.abs())
    }

    #[inline]
    fn checked_add<RHS>(&self, rhs: RHS) -> Option<Self>
    where
        RHS: Amount<C>,
    {
        Some(Self::from_decimal(
            self.amount.checked_add(rhs.get_decimal()?)?,
        ))
    }

    #[inline]
    fn checked_sub<RHS>(&self, rhs: RHS) -> Option<Self>
    where
        RHS: Amount<C>,
    {
        Some(Self::from_decimal(
            self.amount.checked_sub(rhs.get_decimal()?)?,
        ))
    }

    #[inline]
    fn checked_mul<RHS>(&self, rhs: RHS) -> Option<Self>
    where
        RHS: DecimalNumber,
    {
        Some(Self::from_decimal(
            self.amount.checked_mul(rhs.get_decimal()?)?,
        ))
    }

    #[inline]
    fn checked_div<RHS>(&self, rhs: RHS) -> Option<Self>
    where
        RHS: DecimalNumber,
    {
        Some(Self::from_decimal(
            self.amount.checked_div(rhs.get_decimal()?)?,
        ))
    }
}

impl<C> MoneyFormatter<C> for Money<C> where C: Currency {}

#[cfg(feature = "accounting")]
impl<C> AccountingOps<C> for Money<C> where C: Currency {}

impl<C> MoneyOps<C> for Money<C> where C: Currency {}