lucre 0.10.0

An ergonomic library for handling money.
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
//! Rates between currencies, and the table a set of them forms.
//!
//! Rates are live data rather than a standard, so nothing here quotes one for
//! you: [`ExchangeRate`] states a quote you already have, and [`Exchange`]
//! keeps a set of them to look up by currency pair.

use std::collections::BTreeMap;

use thiserror::Error;

use crate::{Currency, Decimal, Money, MoneyError};

/// The rate at which one currency buys another.
///
/// A quote reads in one direction only — the rate turning dollars into euros
/// is not the rate turning them back — and multiplies rather than adds, so it
/// is always positive. Two quotes meeting at a shared currency compose with
/// [`cross_with`](ExchangeRate::cross_with), which is how a pair nobody quotes
/// directly gets priced.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, ExchangeRate, Money};
/// use rust_decimal::dec;
///
/// let rate = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
///
/// assert_eq!(
///     rate.convert(&Money::from_major(100, &Currency::USD))?,
///     Money::from_major(90, &Currency::EUR)
/// );
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct ExchangeRate {
    from: Currency,
    to: Currency,
    rate: Decimal,
}

impl ExchangeRate {
    /// Quote a rate between two currencies.
    ///
    /// The rate multiplies an amount of `from` to arrive at an amount of `to`.
    /// A currency may be quoted against itself, though
    /// [`identity`](ExchangeRate::identity) says that more plainly.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// assert!(ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9)).is_ok());
    /// assert!(ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0)).is_err());
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`InvalidRateError`] if the rate is zero or negative.
    pub fn new<R: Into<Decimal>>(
        from: Currency,
        to: Currency,
        rate: R,
    ) -> Result<Self, InvalidRateError> {
        let rate = rate.into();

        if rate <= Decimal::ZERO {
            return Err(InvalidRateError);
        }

        Ok(Self { from, to, rate })
    }

    /// The rate of a currency against itself, which leaves an amount as it is.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate, Money};
    ///
    /// let fare = Money::from_minor(275, &Currency::USD);
    ///
    /// assert_eq!(ExchangeRate::identity(Currency::USD).convert(&fare)?, fare);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn identity(currency: Currency) -> Self {
        Self {
            from: currency,
            to: currency,
            rate: Decimal::ONE,
        }
    }

    /// The currency this rate prices.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let rate = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
    ///
    /// assert_eq!(rate.from(), Currency::USD);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn from(&self) -> Currency {
        self.from
    }

    /// The currency this rate prices it in.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let rate = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
    ///
    /// assert_eq!(rate.to(), Currency::EUR);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn to(&self) -> Currency {
        self.to
    }

    /// The multiplier itself.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let rate = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
    ///
    /// assert_eq!(rate.rate(), dec!(0.9));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn rate(&self) -> Decimal {
        self.rate
    }

    /// Restate an amount in the currency this rate prices it in.
    ///
    /// The product is kept whole, at whatever scale multiplying reached, so a
    /// conversion carries its full precision into whatever it feeds. Cutting
    /// it back to the currency's minor units is [`Money::round`]'s job, best
    /// left until the amount is due to be paid.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate, Money, MoneyError};
    /// use rust_decimal::dec;
    ///
    /// let rate = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
    ///
    /// assert_eq!(
    ///     rate.convert(&Money::from_minor(2550, &Currency::USD))?,
    ///     Money::from_decimal(dec!(22.950), &Currency::EUR)
    /// );
    /// assert_eq!(
    ///     rate.convert(&Money::from_major(10, &Currency::GBP)),
    ///     Err(MoneyError::CurrencyMismatch)
    /// );
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`MoneyError::CurrencyMismatch`] if the amount is denominated in
    /// some currency other than the one this rate prices.
    /// Returns [`MoneyError::Overflow`] if the result falls outside the range a [`Decimal`] can hold.
    pub fn convert(&self, money: &Money) -> Result<Money, MoneyError> {
        if money.currency() != self.from {
            return Err(MoneyError::CurrencyMismatch);
        }

        let amount = money
            .amount()
            .checked_mul(self.rate)
            .ok_or(MoneyError::Overflow)?;

        Ok(Money::from_decimal(amount, &self.to))
    }

    /// Span both legs of a pair of rates that meet at a shared currency.
    ///
    /// Where this rate arrives is where `other` sets out, the two collapse into
    /// a single quote from one far end to the other — the usual way to price a
    /// pair quoted only against some third currency.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let usd_eur = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
    /// let eur_jpy = ExchangeRate::new(Currency::EUR, Currency::JPY, dec!(160))?;
    /// let usd_jpy = usd_eur.cross_with(&eur_jpy)?;
    ///
    /// assert_eq!(usd_jpy.from(), Currency::USD);
    /// assert_eq!(usd_jpy.to(), Currency::JPY);
    /// assert_eq!(usd_jpy.rate(), dec!(144.0));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`MoneyError::CurrencyMismatch`] unless the currency this rate
    /// arrives at is the one `other` prices.
    /// Returns [`MoneyError::Overflow`] if the composed rate falls outside what
    /// a [`Decimal`] holds — too large to write down, or too small to write
    /// down as anything but zero.
    pub fn cross_with(&self, other: &Self) -> Result<Self, MoneyError> {
        if self.to != other.from {
            return Err(MoneyError::CurrencyMismatch);
        }

        let rate = self
            .rate
            .checked_mul(other.rate)
            .filter(Decimal::is_sign_positive)
            .filter(|rate| !rate.is_zero())
            .ok_or(MoneyError::Overflow)?;

        Ok(Self {
            from: self.from,
            to: other.to,
            rate,
        })
    }
}

/// A set of exchange rates to look up by currency pair.
///
/// Rates are live data rather than a standard, so a table starts empty and
/// fills from wherever quotes come from. An ordered pair of currencies holds
/// one rate at a time and a fresh quote displaces the last, which is what
/// arriving quotes should do; the two directions of a pair are separate
/// entries, since a real market prices them separately.
///
/// A currency converts to itself at par whether the table says so or not.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Exchange, ExchangeRate, Money};
/// use rust_decimal::dec;
///
/// let mut desk = Exchange::new();
/// desk.set_rate(&ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?);
///
/// let quote = desk
///     .rate(&Currency::USD, &Currency::EUR)
///     .ok_or("the desk quotes USD against EUR")?;
///
/// assert_eq!(
///     quote.convert(&Money::from_major(100, &Currency::USD))?,
///     Money::from_major(90, &Currency::EUR)
/// );
/// assert!(desk.rate(&Currency::EUR, &Currency::USD).is_none());
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Exchange {
    rates: BTreeMap<(Currency, Currency), Decimal>,
}

impl Exchange {
    /// Create a table quoting nothing.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Exchange};
    ///
    /// assert!(
    ///     Exchange::new()
    ///         .rate(&Currency::USD, &Currency::EUR)
    ///         .is_none()
    /// );
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Take a quote into the table, displacing any the pair already had.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Exchange, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let mut desk = Exchange::new();
    /// desk.set_rate(&ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?);
    /// desk.set_rate(&ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.92))?);
    ///
    /// let quote = desk
    ///     .rate(&Currency::USD, &Currency::EUR)
    ///     .ok_or("the desk quotes USD against EUR")?;
    ///
    /// assert_eq!(quote.rate(), dec!(0.92));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn set_rate(&mut self, rate: &ExchangeRate) {
        self.rates.insert((rate.from, rate.to), rate.rate);
    }

    /// What the table quotes from one currency to another.
    ///
    /// A currency asked against itself answers [`ExchangeRate::identity`]
    /// unless the table quotes that pair outright, so restating an amount in
    /// the currency it already carries never wants for a rate.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Exchange, ExchangeRate};
    ///
    /// let desk = Exchange::new();
    ///
    /// assert_eq!(
    ///     desk.rate(&Currency::USD, &Currency::USD),
    ///     Some(ExchangeRate::identity(Currency::USD))
    /// );
    /// ```
    #[must_use]
    pub fn rate(&self, from: &Currency, to: &Currency) -> Option<ExchangeRate> {
        self.rates
            .get(&(*from, *to))
            .map(|&rate| ExchangeRate {
                from: *from,
                to: *to,
                rate,
            })
            .or_else(|| (from == to).then(|| ExchangeRate::identity(*from)))
    }

    /// Every quote the table holds, ordered by the currency priced and then by
    /// the currency it is priced in.
    ///
    /// Par for a currency against itself is among them only where it was quoted
    /// outright, since [`rate`](Exchange::rate) answers that pair from the rule
    /// rather than from the table.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Exchange, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let usd_eur = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
    /// let mut desk = Exchange::new();
    /// desk.set_rate(&usd_eur);
    ///
    /// assert_eq!(desk.quotes().collect::<Vec<_>>(), vec![usd_eur]);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn quotes(&self) -> impl ExactSizeIterator<Item = ExchangeRate> {
        self.rates
            .iter()
            .map(|(&(from, to), &rate)| ExchangeRate { from, to, rate })
    }
}

/// An error from quoting an [`ExchangeRate`].
///
/// The multiplier was zero or negative, and no exchange takes place at such a
/// rate.
#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
#[error("an exchange rate must be a positive, nonzero multiplier")]
pub struct InvalidRateError;

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

    fn usd_eur() -> ExchangeRate {
        ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9)).unwrap()
    }

    #[test]
    fn rate_refuses_a_zero_multiplier_test() {
        assert_eq!(
            ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0)),
            Err(InvalidRateError)
        );
    }

    #[test]
    fn rate_refuses_a_negative_multiplier_test() {
        assert_eq!(
            ExchangeRate::new(Currency::USD, Currency::EUR, dec!(-0.9)),
            Err(InvalidRateError)
        );
    }

    #[test]
    fn rate_quotes_a_currency_against_itself_test() {
        let rate = ExchangeRate::new(Currency::USD, Currency::USD, dec!(1)).unwrap();

        assert_eq!(rate, ExchangeRate::identity(Currency::USD));
    }

    #[test]
    fn identity_leaves_an_amount_alone_test() {
        let fare = Money::from_minor(275, &Currency::USD);

        assert_eq!(
            ExchangeRate::identity(Currency::USD).convert(&fare),
            Ok(fare)
        );
    }

    #[test]
    fn convert_multiplies_the_amount_test() {
        assert_eq!(
            usd_eur().convert(&Money::from_major(100, &Currency::USD)),
            Ok(Money::from_major(90, &Currency::EUR))
        );
    }

    #[test]
    fn convert_keeps_the_scale_multiplying_reached_test() {
        let converted = usd_eur()
            .convert(&Money::from_minor(2550, &Currency::USD))
            .unwrap();

        assert_eq!(converted.amount(), dec!(22.950));
        assert_eq!(converted.amount().scale(), 3);
    }

    #[test]
    fn convert_refuses_another_currency_test() {
        assert_eq!(
            usd_eur().convert(&Money::from_major(10, &Currency::GBP)),
            Err(MoneyError::CurrencyMismatch)
        );
    }

    #[test]
    fn convert_reports_an_unrepresentable_product_test() {
        let steep = ExchangeRate::new(Currency::USD, Currency::EUR, Decimal::MAX).unwrap();

        assert_eq!(
            steep.convert(&Money::from_decimal(Decimal::MAX, &Currency::USD)),
            Err(MoneyError::Overflow)
        );
    }

    #[test]
    fn cross_spans_both_legs_test() {
        let eur_jpy = ExchangeRate::new(Currency::EUR, Currency::JPY, dec!(160)).unwrap();
        let usd_jpy = usd_eur().cross_with(&eur_jpy).unwrap();

        assert_eq!(usd_jpy.from(), Currency::USD);
        assert_eq!(usd_jpy.to(), Currency::JPY);
        assert_eq!(usd_jpy.rate(), dec!(144));
    }

    #[test]
    fn cross_refuses_rates_that_do_not_meet_test() {
        let gbp_jpy = ExchangeRate::new(Currency::GBP, Currency::JPY, dec!(190)).unwrap();

        assert_eq!(
            usd_eur().cross_with(&gbp_jpy),
            Err(MoneyError::CurrencyMismatch)
        );
    }

    #[test]
    fn cross_reports_a_product_too_large_to_hold_test() {
        let steep = ExchangeRate::new(Currency::EUR, Currency::JPY, Decimal::MAX).unwrap();
        let steeper = ExchangeRate::new(Currency::USD, Currency::EUR, Decimal::MAX).unwrap();

        assert_eq!(steeper.cross_with(&steep), Err(MoneyError::Overflow));
    }

    #[test]
    fn cross_reports_a_product_too_small_to_hold_test() {
        let slight = Decimal::new(1, 28);
        let usd_eur = ExchangeRate::new(Currency::USD, Currency::EUR, slight).unwrap();
        let eur_jpy = ExchangeRate::new(Currency::EUR, Currency::JPY, slight).unwrap();

        assert_eq!(usd_eur.cross_with(&eur_jpy), Err(MoneyError::Overflow));
    }

    #[test]
    fn exchange_answers_a_rate_it_was_given_test() {
        let mut desk = Exchange::new();
        desk.set_rate(&usd_eur());

        assert_eq!(desk.rate(&Currency::USD, &Currency::EUR), Some(usd_eur()));
    }

    #[test]
    fn exchange_keeps_the_directions_of_a_pair_apart_test() {
        let mut desk = Exchange::new();
        desk.set_rate(&usd_eur());

        assert_eq!(desk.rate(&Currency::EUR, &Currency::USD), None);
    }

    #[test]
    fn exchange_displaces_an_earlier_quote_test() {
        let revised = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.92)).unwrap();
        let mut desk = Exchange::new();
        desk.set_rate(&usd_eur());
        desk.set_rate(&revised);

        assert_eq!(desk.rate(&Currency::USD, &Currency::EUR), Some(revised));
    }

    #[test]
    fn exchange_answers_par_for_a_currency_against_itself_test() {
        assert_eq!(
            Exchange::new().rate(&Currency::JPY, &Currency::JPY),
            Some(ExchangeRate::identity(Currency::JPY))
        );
    }

    #[test]
    fn exchange_lets_a_quoted_pair_outrank_par_test() {
        let discounted = ExchangeRate::new(Currency::USD, Currency::USD, dec!(0.99)).unwrap();
        let mut desk = Exchange::new();
        desk.set_rate(&discounted);

        assert_eq!(desk.rate(&Currency::USD, &Currency::USD), Some(discounted));
    }

    #[test]
    fn exchange_holds_nothing_to_begin_with_test() {
        assert_eq!(Exchange::new().rate(&Currency::USD, &Currency::EUR), None);
    }
}