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
use std::{
    collections::HashMap,
    fmt::{Debug, Display},
    marker::PhantomData,
};

use crate::{
    BaseMoney, BaseOps, Currency, Decimal, Money, MoneyError, RawMoney,
    base::{Amount, DecimalNumber},
    macros::dec,
};

// ========================= Exchange =========================

/// Trait for currency exchange.
/// This does exchange from `From` into `To`.
///
/// This trait has blanket implementation for M where M implements `BaseMoney<C>` + `BaseOps<C>` + `Convert<C>`
/// with method `convert` that does the conversion.
pub trait Exchange<From: Currency> {
    /// Target conversion.
    type Target<T: Currency>
    where
        Self: Convert<T>;

    /// Method to do conversion from `Self<From>` into `Target<To>`.
    ///
    /// If `From` == `To`, immediately return `Target<To>` with Self's amount.
    ///
    /// # Arguments
    /// - To: Currency = Type parameter as the target of currency conversion.
    /// - rate: Rate<From, To> = exchange rate of From/To accepting value from these types:
    ///     - `Money<T>` where T is target currency
    ///     - `RawMoney<T>` where T is target currency
    ///     - `Decimal`
    ///     - `f64`
    ///     - `i32`
    ///     - `i64`
    ///     - `i128`
    ///     - `ExchangeRates<'a, C>` where C is base currency of exchange rates
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Money, RawMoney, BaseMoney, BaseOps, Exchange, ExchangeRates, Currency};
    /// use moneylib::iso::{EUR, IDR, IRR, USD, CAD};
    /// use moneylib::macros::dec;
    ///
    /// let money = Money::<USD>::new(123).unwrap();
    /// let ret = money.convert::<EUR>(dec!(0.8));
    /// assert_eq!(ret.unwrap().amount(), dec!(98.4));
    ///
    /// let money = Money::<USD>::new(123).unwrap();
    /// let ret = money.convert::<USD>(2); // rate 2 will be ignored since converting to the same currency.
    /// assert_eq!(ret.unwrap().amount(), dec!(123));
    ///
    /// let money = Money::<USD>::from_decimal(dec!(100));
    /// let ret = money.convert::<EUR>(0.888234);
    /// assert_eq!(ret.unwrap().amount(), dec!(88.82));
    ///
    /// let raw_money = RawMoney::<USD>::from_decimal(dec!(100));
    /// let ret = raw_money.convert::<EUR>(0.8882346);
    /// assert_eq!(ret.unwrap().amount(), dec!(88.82346));
    ///
    /// let money = Money::<USD>::new(123).unwrap();
    /// let mut rates = ExchangeRates::<USD>::new();
    /// rates.set(EUR::CODE, dec!(0.8));
    /// rates.set(IDR::CODE, 17_000);
    /// let ret = money.convert::<EUR>(&rates);
    /// assert_eq!(ret.unwrap().amount(), dec!(98.4));
    /// let ret = money.convert::<IDR>(&rates);
    /// assert_eq!(ret.unwrap().amount(), dec!(2_091_000));
    ///
    /// let money = Money::<EUR>::new(123).unwrap();
    /// let ret = money.convert::<IDR>(rates);
    /// assert_eq!(ret.unwrap().amount(), dec!(2_613_750));
    ///
    /// let rates = ExchangeRates::<USD>::from([
    ///     ("EUR", dec!(0.8)),
    ///     ("IDR", dec!(17_000)),
    ///     ("IRR", dec!(1_321_700)),
    ///     ("USD", dec!(123)), // will be ignored since base already in usd and forced into 1.
    /// ]);
    ///
    /// let money = Money::<USD>::from_decimal(dec!(1000));
    /// assert_eq!(money.convert::<USD>(&rates).unwrap().amount(), dec!(1000));
    /// assert_eq!(money.convert::<EUR>(&rates).unwrap().amount(), dec!(800));
    /// assert_eq!(
    ///     money.convert::<IRR>(&rates).unwrap().amount(),
    ///     dec!(1_321_700_000)
    /// );
    /// assert_eq!(
    ///     money.convert::<IDR>(&rates).unwrap().amount(),
    ///     dec!(17_000_000)
    /// );
    ///
    /// let money = Money::<EUR>::new(12).unwrap();
    /// assert_eq!(
    ///     money.convert::<IDR>(&rates).unwrap().amount(),
    ///     dec!(255_000)
    /// );
    /// let money = Money::<EUR>::new(1230).unwrap();
    /// assert_eq!(
    ///     money.convert::<USD>(&rates).unwrap().amount(),
    ///     dec!(1_537.5)
    /// );
    /// let money = Money::<IDR>::new(15_000_000).unwrap();
    /// assert_eq!(
    ///     money.convert::<IRR>(&rates).unwrap().amount(),
    ///     dec!(1_166_205_882.35)
    /// );
    /// let money = Money::<IRR>::new(5000).unwrap();
    /// assert_eq!(money.convert::<USD>(&rates).unwrap().amount(), dec!(0));
    /// let money = Money::<IRR>::new(10000).unwrap();
    /// assert_eq!(money.convert::<EUR>(&rates).unwrap().amount(), dec!(0.01));
    ///
    /// // CAD is not in the rates, so None returned.
    /// assert!(money.convert::<CAD>(rates).is_err());
    /// ```
    fn convert<To: Currency>(
        &self,
        rate: impl Rate<From, To>,
    ) -> Result<Self::Target<To>, MoneyError>
    where
        Self: Convert<To>;
}

impl<M, From> Exchange<From> for M
where
    M: BaseMoney<From> + BaseOps<From> + Convert<From>,
    From: Currency,
{
    type Target<T: Currency>
        = <M as Convert<T>>::Output
    where
        M: Convert<T>;

    fn convert<To: Currency>(
        &self,
        rate: impl Rate<From, To>,
    ) -> Result<Self::Target<To>, MoneyError>
    where
        M: Convert<To>,
    {
        match From::CODE == To::CODE {
            false => <M as Convert<To>>::Output::new(
                self.checked_mul(
                    rate.get_rate().ok_or(MoneyError::ExchangeError(
                        format!(
                            "overflowed or rate from {} to {} not found",
                            From::CODE,
                            To::CODE
                        )
                        .into(),
                    ))?,
                )
                .ok_or(MoneyError::OverflowError)?
                .amount(),
            ),
            true => <M as Convert<To>>::Output::new(self.amount()),
        }
    }
}

/// Trait to define target conversion type which implements BaseMoney<T> where T is target currency.
pub trait Convert<T: Currency> {
    type Output: BaseMoney<T>;
}

impl<C: Currency, T: Currency> Convert<T> for Money<C> {
    type Output = Money<T>;
}

impl<C: Currency, T: Currency> Convert<T> for RawMoney<C> {
    type Output = RawMoney<T>;
}

// ========================= Rate =========================

/// Trait to define rate amount for conversion input.
///
/// It accepts:
/// - Money<T> where T is target currency
/// - RawMoney<T> where T is target currency
/// - Decimal
/// - f64
/// - i32
/// - i64
/// - i128
/// - ExchangeRates<'a, C> where C is base currency of exchange rates
///
pub trait Rate<From: Currency, To: Currency>: Amount<To> {
    /// Get T's rate relative to C.
    fn get_rate(&self) -> Option<Decimal> {
        self.get_decimal()
    }
}

impl<From: Currency, To: Currency> Rate<From, To> for Money<To> {}

impl<From: Currency, To: Currency> Rate<From, To> for RawMoney<To> {}

impl<From: Currency, To: Currency> Rate<From, To> for Decimal {}

impl<From: Currency, To: Currency> Rate<From, To> for f64 {}

impl<From: Currency, To: Currency> Rate<From, To> for i32 {}

impl<From: Currency, To: Currency> Rate<From, To> for i64 {}

impl<From: Currency, To: Currency> Rate<From, To> for i128 {}

// ========================= ExchangeRates =========================

/// Contains list of rates with a Base currency.
///
/// It can be used as input for conversion with Exchange's trait convert method.
///
/// # Examples
///
/// ```
/// use moneylib::{Currency, Exchange, ExchangeRates, iso::{USD, EUR, IDR, IRR, CAD}, macros::dec};
///
/// let mut rates = ExchangeRates::<USD>::new();
/// rates.set(EUR::CODE, dec!(0.8));
/// rates.set(IDR::CODE, 17000);
/// rates.set(IRR::CODE, 1_321_700i128);
/// rates.set(CAD::CODE, 1.8);
///
/// assert_eq!(rates.get(USD::CODE).unwrap(), dec!(1));
/// assert_eq!(rates.get(EUR::CODE).unwrap(), dec!(0.8));
/// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(17_000));
/// assert_eq!(rates.get(IRR::CODE).unwrap(), dec!(1_321_700));
/// assert_eq!(rates.get(CAD::CODE).unwrap(), dec!(1.8));
///
/// // or you can initiate the rates with types implementing IntoIter<Item = (&'a str, Decimal)>
/// // where it's mapping currency code(&str) to its rate(Decimal).
///
/// let rates = ExchangeRates::<USD>::from([
///     (EUR::CODE, dec!(0.8)),
///     (IDR::CODE, dec!(17000)),
///     (IRR::CODE, dec!(1_321_700)),
///     (CAD::CODE, dec!(1.8)),
/// ]);
///
/// assert_eq!(rates.get(USD::CODE).unwrap(), dec!(1));
/// assert_eq!(rates.get(EUR::CODE).unwrap(), dec!(0.8));
/// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(17_000));
/// assert_eq!(rates.get(IRR::CODE).unwrap(), dec!(1_321_700));
/// assert_eq!(rates.get(CAD::CODE).unwrap(), dec!(1.8));
///
/// ```
#[derive(Clone)]
pub struct ExchangeRates<'a, Base: Currency> {
    rates: HashMap<&'a str, Decimal>,
    _base: PhantomData<Base>,
}

impl<'a, Base: Currency> ExchangeRates<'a, Base> {
    /// Initiate new ExchangeRates with base currency and 1 entry to the base with value 1.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{ExchangeRates, iso::USD};
    ///
    /// let rates = ExchangeRates::<USD>::new();
    /// assert_eq!(rates.len(), 1); // USD/USD = 1
    /// ```
    pub fn new() -> Self {
        Self {
            rates: HashMap::from([(Base::CODE, dec!(1))]),
            _base: PhantomData,
        }
    }

    /// Get base currency of exchange rates.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{ExchangeRates, iso::USD};
    ///
    /// let rates = ExchangeRates::<USD>::new();
    /// assert_eq!(rates.base(), "USD");
    /// ```
    #[inline]
    pub const fn base(&self) -> &'static str {
        Base::CODE
    }

    /// Upsert rate into exchange rates relative to Base rate.
    ///
    /// Return error if overflowed.
    ///
    /// # Argument
    /// - code: &str, currency code, e.g. "USD", "EUR", etc.
    /// - rate: DecimalNumber, accepts Decimal, f64, i32, i64, i128.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Currency, ExchangeRates, iso::{USD, IDR, EUR}, macros::dec};
    ///
    /// let mut rates = ExchangeRates::<USD>::new();
    /// rates.set(IDR::CODE, 16000).unwrap();
    /// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(16000));
    /// rates.set(IDR::CODE, dec!(17000.23)).unwrap();
    /// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(17000.23));
    /// rates.set(EUR::CODE, dec!(0.8)).unwrap();
    /// assert_eq!(rates.get(EUR::CODE).unwrap(), dec!(0.8));
    /// ```
    pub fn set(&mut self, code: &'a str, rate: impl DecimalNumber) -> Result<(), MoneyError> {
        if code != Base::CODE {
            self.rates
                .insert(code, rate.get_decimal().ok_or(MoneyError::OverflowError)?);
        }
        Ok(())
    }

    /// Upsert a rate of a pair.
    ///
    /// If value already exist, it got updated and old value returned.
    ///
    /// If one or both `from_code` and `to_code` not in the rates, nothing happen, None returned.
    ///
    /// If one of the rate not exist, it fills it by calculating existing rate against the base rate.
    ///
    /// If both rates exist, it updates the target/quote currency, indirectly updating Base/to_code.
    ///
    /// If both are not in the rates, error returned.
    ///
    /// The rate is updated relative to base currency.
    ///
    /// # Argument
    /// - from_code: currency's code of source conversion(base currency).
    /// - to_code: currency's code of target conversion(quote currency).
    ///
    /// # Examples
    /// ```rust
    /// use moneylib::{ExchangeRates, Exchange, iso::{USD, IDR, JPY, CNY}, dec, money, Currency};
    ///
    /// let mut rates = ExchangeRates::<USD>::new();
    /// assert_eq!(rates.len(), 1);
    /// assert_eq!(rates.get(USD::CODE).unwrap(), dec!(1));
    ///
    /// rates.set("EUR", dec!(0.8)).unwrap();
    /// rates.set("IDR", dec!(17_000)).unwrap();
    /// rates.set("CAD", dec!(1.2)).unwrap();
    /// assert_eq!(rates.len(), 4);
    ///
    /// rates.set_pair("CNY", "IDR", i128::MAX).unwrap_err(); // wont set
    /// rates.set_pair("CNY", "IDR", 2500).unwrap();
    /// assert_eq!(rates.len(), 5);
    /// assert_eq!(rates.get("CNY").unwrap(), dec!(6.8));
    ///
    /// let cny_idr_rate = money!(CNY, 5262.657).convert::<IDR>(2500).unwrap();
    /// let cny_idr_rates = money!(CNY, 5262.657).convert::<IDR>(&rates).unwrap();
    /// assert_eq!(cny_idr_rate, cny_idr_rates);
    ///
    /// rates.set_pair("CNY", "IDR", 3000).unwrap();
    /// let cny_idr_new_rate = money!(CNY, 34989.123).convert::<IDR>(3000).unwrap();
    /// let cny_idr_new_rates = money!(CNY, 34989.123).convert::<IDR>(&rates).unwrap();
    /// assert_eq!(cny_idr_new_rate, cny_idr_new_rates);
    /// ```
    pub fn set_pair(
        &mut self,
        from_code: &'a str,
        to_code: &'a str,
        rate: impl DecimalNumber,
    ) -> Result<(), MoneyError> {
        match (from_code, to_code) {
            // if setting the pair for Base/Base, do nothing
            (from_base, to_base) if from_base == Base::CODE && to_base == Base::CODE => Ok(()),
            (from_base, _) if from_base == Base::CODE => self.set(to_code, rate),
            (_, to_base) if to_base == Base::CODE => self.set(
                from_code,
                dec!(1)
                    .checked_div(rate.get_decimal().ok_or(MoneyError::OverflowError)?)
                    .ok_or(MoneyError::OverflowError)?,
            ),
            (from, to) => match (self.get(from), self.get(to)) {
                (Some(base_from_rate), None) => {
                    let base_to_rate = base_from_rate
                        .checked_mul(rate.get_decimal().ok_or(MoneyError::OverflowError)?)
                        .ok_or(MoneyError::OverflowError)?;
                    self.set(to, base_to_rate)
                }
                (None, Some(base_to_rate)) => {
                    let base_from_rate = base_to_rate
                        .checked_div(rate.get_decimal().ok_or(MoneyError::OverflowError)?)
                        .ok_or(MoneyError::OverflowError)?;
                    self.set(from, base_from_rate)
                }
                // update Base/to_code rate
                (Some(base_from_rate), Some(_)) => {
                    let new_base_to_rate = base_from_rate
                        .checked_mul(rate.get_decimal().ok_or(MoneyError::OverflowError)?)
                        .ok_or(MoneyError::OverflowError)?;
                    self.set(to, new_base_to_rate)
                }
                _ => Err(MoneyError::ExchangeError(
                    "both rates are not found inside exchange rates".into(),
                )),
            },
        }
    }

    /// Get a rate for a currency exists in rates by code, e.g "USD", "EUR", etc.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Currency, ExchangeRates, iso::{USD, IDR, EUR}, macros::dec};
    ///
    /// let mut rates = ExchangeRates::<USD>::new();
    /// rates.set(IDR::CODE, 16000);
    /// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(16000));
    /// rates.set(IDR::CODE, dec!(17000.23));
    /// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(17000.23));
    /// rates.set(EUR::CODE, dec!(0.8));
    /// assert_eq!(rates.get(EUR::CODE).unwrap(), dec!(0.8));
    /// ```
    pub fn get(&self, code: &str) -> Option<Decimal> {
        Some(*self.rates.get(code)?)
    }

    /// Get rate of a pair currencies <`from_code`> to <`to_code`>.
    ///
    /// E.g. from_code: USD, to_code: EUR -> get rate of USD/EUR.
    ///
    /// # Examples
    ///
    /// ```
    /// use moneylib::{Currency, ExchangeRates, iso::{USD, IDR, EUR, CAD}, macros::dec};
    ///
    /// let mut rates = ExchangeRates::<USD>::new();
    /// rates.set(IDR::CODE, 16000);
    /// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(16000));
    /// rates.set(IDR::CODE, dec!(17000.23));
    /// assert_eq!(rates.get(IDR::CODE).unwrap(), dec!(17000.23));
    /// rates.set(EUR::CODE, dec!(0.8));
    /// assert_eq!(rates.get(EUR::CODE).unwrap(), dec!(0.8));
    ///
    /// let usd_idr = rates.get_pair(USD::CODE, IDR::CODE).unwrap();
    /// assert_eq!(usd_idr, dec!(17000.23));
    ///
    /// let eur_usd = rates.get_pair(EUR::CODE, USD::CODE).unwrap();
    /// assert_eq!(eur_usd, dec!(1.25));
    ///
    /// let idr_usd = rates.get_pair(IDR::CODE, USD::CODE).unwrap();
    /// assert_eq!(idr_usd, dec!(0.0000588227335747810470799513));
    ///
    /// let idr_eur = rates.get_pair(IDR::CODE, EUR::CODE).unwrap();
    /// assert_eq!(idr_eur, dec!(0.0000470581868598248376639610));
    ///
    /// let cad_idr = rates.get_pair(CAD::CODE, IDR::CODE);
    /// assert!(cad_idr.is_none()); // CAD is not in the exchange rates `rates`
    /// ```
    pub fn get_pair(&self, from_code: &str, to_code: &str) -> Option<Decimal> {
        dec!(1)
            .checked_div(self.get(from_code)?)?
            .checked_mul(self.get(to_code)?)
    }

    #[allow(clippy::len_without_is_empty)]
    /// Get length of exchange rates list.
    pub fn len(&self) -> usize {
        self.rates.len()
    }
}

impl<'a, I, Base: Currency> From<I> for ExchangeRates<'a, Base>
where
    I: IntoIterator<Item = (&'a str, Decimal)>,
{
    /// Set exchange rates from list of rates.
    ///
    /// If some of the sets failed, will be skipped.
    fn from(value: I) -> Self {
        let mut exchange_rates = Self::new();
        for (k, v) in value {
            if k != Base::CODE {
                let _ = exchange_rates.set(k, v);
            }
        }

        exchange_rates
    }
}

impl<'a, Base: Currency> Default for ExchangeRates<'a, Base> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, Base: Currency, To: Currency> Amount<To> for ExchangeRates<'a, Base> {
    fn get_decimal(&self) -> Option<Decimal> {
        Some(*self.rates.get(To::CODE)?)
    }
}

impl<'a, Base: Currency, To: Currency> Amount<To> for &ExchangeRates<'a, Base> {
    fn get_decimal(&self) -> Option<Decimal> {
        <ExchangeRates<Base> as Amount<To>>::get_decimal(self)
    }
}

impl<'a, Base, From, To> Rate<From, To> for ExchangeRates<'a, Base>
where
    Base: Currency,
    From: Currency,
    To: Currency,
{
    fn get_rate(&self) -> Option<Decimal> {
        self.get_pair(From::CODE, To::CODE)
    }
}

impl<'a, Base, From, To> Rate<From, To> for &ExchangeRates<'a, Base>
where
    Base: Currency,
    From: Currency,
    To: Currency,
{
    fn get_rate(&self) -> Option<Decimal> {
        <ExchangeRates<Base> as Rate<From, To>>::get_rate(self)
    }
}

fn exchange_rates_display<Base: Currency>(rates: &ExchangeRates<Base>) -> String {
    let mut ret = format!("Base: {}", Base::CODE);
    ret.push_str(&format!("\n{}/{} = {}", Base::CODE, Base::CODE, dec!(1)));

    for (k, v) in rates.rates.iter() {
        if *k != Base::CODE {
            ret.push_str(&format!("\n{}/{} = {}", Base::CODE, k, v));
        }
    }

    ret
}

impl<Base: Currency> Display for ExchangeRates<'_, Base> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", exchange_rates_display::<Base>(self))
    }
}

impl<Base: Currency> Debug for ExchangeRates<'_, Base> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", exchange_rates_display::<Base>(self))
    }
}