lucre 0.11.0

An ergonomic library for handling money.
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
//! A table of rates, one per currency pair, and the ways in and out of it.

use std::{
    collections::{BTreeMap, btree_map},
    iter::FusedIterator,
};

use miette::Diagnostic;
use thiserror::Error;

use super::{ConvertError, ExchangeRate, Pair};
use crate::{Currency, Decimal, Money};

/// A set of exchange rates to look up by currency pair.
///
/// A table starts empty and fills with the rates it is given. Each pair holds
/// one rate at a time, and a new rate displaces the old one. The two
/// directions of a pair are separate entries, priced separately. Rates leave
/// one pair at a time with [`remove_rate`](Exchange::remove_rate), or all at
/// once with [`clear`](Exchange::clear).
///
/// [`convert`](Exchange::convert) prices an amount without the caller ever
/// handling a rate. [`rate`](Exchange::rate) hands one over for the work the
/// table does not do itself, such as crossing a pair it does not quote.
///
/// Whatever reads a table whole — [`iter`](Exchange::iter), [`IntoIterator`],
/// serialization — reads it in *pair order*: by the currency being priced,
/// then by the currency it is priced in.
///
/// ## 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))?);
///
/// assert_eq!(
///     desk.convert(Money::from_major(100, Currency::USD), Currency::EUR)?,
///     Money::from_major(90, Currency::EUR)
/// );
/// assert!(desk.rate((Currency::EUR, Currency::USD)).is_none());
///
/// // A whole feed goes in the same way, one rate at a time.
/// let board: Exchange = [
///     ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92))?,
///     ExchangeRate::new((Currency::EUR, Currency::JPY), dec!(160))?,
/// ]
/// .into_iter()
/// .collect();
///
/// assert_eq!(board.len(), 2);
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
pub struct Exchange {
    rates: BTreeMap<Pair, Decimal>,
}

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

    /// Add a rate to the table, handing back the one it displaces.
    ///
    /// A pair quoted for the first time displaces nothing, so nothing comes
    /// back.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Exchange, ExchangeRate};
    /// use rust_decimal::dec;
    ///
    /// let opening = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?;
    /// let revised = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92))?;
    /// let mut desk = Exchange::new();
    ///
    /// assert_eq!(desk.set_rate(opening), None);
    /// assert_eq!(desk.set_rate(revised), Some(opening));
    /// assert_eq!(desk.rate((Currency::USD, Currency::EUR)), Some(revised));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn set_rate(&mut self, rate: ExchangeRate) -> Option<ExchangeRate> {
        self.rates
            .insert(rate.pair(), rate.rate())
            .map(|displaced| ExchangeRate::new_unchecked(rate.pair(), displaced))
    }

    /// Remove a pair's rate, handing back what the table held.
    ///
    /// The pair may be given as a [`Pair`] or as the two currencies alone,
    /// base first. The other direction of the pair stays where it is.
    ///
    /// ## 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.remove_rate((Currency::USD, Currency::EUR)), Some(usd_eur));
    /// assert_eq!(desk.remove_rate((Currency::USD, Currency::EUR)), None);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn remove_rate<P: Into<Pair>>(&mut self, pair: P) -> Option<ExchangeRate> {
        let pair = pair.into();

        self.rates
            .remove(&pair)
            .map(|rate| ExchangeRate::new_unchecked(pair, rate))
    }

    /// Remove every rate, leaving the table empty.
    ///
    /// ## 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.clear();
    ///
    /// assert!(desk.is_empty());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn clear(&mut self) {
        self.rates.clear();
    }

    /// The rate the table quotes over a pair.
    ///
    /// The pair may be given as a [`Pair`] or as the two currencies alone,
    /// base first.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Exchange, ExchangeRate, Pair};
    /// 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.rate((Currency::USD, Currency::EUR)), Some(usd_eur));
    /// assert_eq!(desk.rate("USD/EUR".parse::<Pair>()?), Some(usd_eur));
    /// assert_eq!(desk.rate((Currency::EUR, Currency::USD)), None);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn rate<P: Into<Pair>>(&self, pair: P) -> Option<ExchangeRate> {
        let pair = pair.into();

        self.rates
            .get(&pair)
            .map(|&rate| ExchangeRate::new_unchecked(pair, rate))
    }

    /// Restate an amount in another currency, at the rate the table quotes.
    ///
    /// The result keeps the full precision [`ExchangeRate::convert`] gives it.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Exchange, ExchangeError, ExchangeRate, Money};
    /// use rust_decimal::dec;
    ///
    /// let mut desk = Exchange::new();
    /// desk.set_rate(ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?);
    ///
    /// let fare = Money::from_major(100, Currency::USD);
    ///
    /// assert_eq!(desk.convert(fare, Currency::EUR)?, Money::from_major(90, Currency::EUR));
    /// assert!(matches!(
    ///     desk.convert(fare, Currency::JPY),
    ///     Err(ExchangeError::Unquoted { base: Currency::USD, quote: Currency::JPY, .. })
    /// ));
    ///
    /// desk.set_rate(ExchangeRate::identity(Currency::USD));
    ///
    /// assert_eq!(desk.convert(fare, Currency::USD)?, fare);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`ExchangeError::Unquoted`] if the table quotes no rate from
    /// the amount's currency to the one asked for. This includes a currency
    /// against itself; add [`ExchangeRate::identity`] to quote that pair.
    /// Returns [`ExchangeError::Convert`] if the rate the table quotes could
    /// not convert the amount.
    pub fn convert(&self, money: Money, into: Currency) -> Result<Money, ExchangeError> {
        Ok(self
            .rate((money.currency(), into))
            .ok_or(ExchangeError::Unquoted {
                base: money.currency(),
                quote: into,
            })?
            .convert(money)?)
    }

    /// Whether the table holds no rates.
    ///
    /// ## 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();
    /// assert!(desk.is_empty());
    ///
    /// desk.set_rate(ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?);
    /// assert!(!desk.is_empty());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.rates.is_empty()
    }

    /// How many pairs the table quotes.
    ///
    /// Each direction of a pair counts separately. A pair quoted again still
    /// counts once, since the new rate displaced the old one.
    ///
    /// ## 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::EUR, Currency::USD), dec!(1.1))?);
    /// assert_eq!(desk.len(), 2);
    ///
    /// desk.set_rate(ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92))?);
    /// assert_eq!(desk.len(), 2);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn len(&self) -> usize {
        self.rates.len()
    }

    /// Every rate the table holds, in pair order.
    ///
    /// ## 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.iter().collect::<Vec<_>>(), vec![usd_eur]);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn iter(&self) -> Rates<'_> {
        Rates(self.rates.iter())
    }

    /// Which pairs the table quotes, in [pair order](Exchange).
    ///
    /// A pair is quoted in one direction only, so a pair listed here does not
    /// put its reverse in the table.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Exchange, ExchangeRate, Pair};
    /// use rust_decimal::dec;
    ///
    /// let mut desk = Exchange::new();
    /// desk.set_rate(ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?);
    ///
    /// assert_eq!(
    ///     desk.pairs().collect::<Vec<_>>(),
    ///     [Pair::new(Currency::USD, Currency::EUR)]
    /// );
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    pub fn pairs(&self) -> Pairs<'_> {
        Pairs(self.rates.keys())
    }
}

/// One [`Pair`] per rate a borrowed table quotes, in [pair order](Exchange).
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Exchange, ExchangeRate, Pairs};
/// use rust_decimal::dec;
///
/// let desk: Exchange = [ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?]
///     .into_iter()
///     .collect();
/// let pairs: Pairs<'_> = desk.pairs();
///
/// assert_eq!(pairs.count(), 1);
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Pairs<'a>(btree_map::Keys<'a, Pair, Decimal>);

impl Iterator for Pairs<'_> {
    type Item = Pair;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().copied()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for Pairs<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().copied()
    }
}

impl ExactSizeIterator for Pairs<'_> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl FusedIterator for Pairs<'_> {}

/// What a borrowed table yields: one [`ExchangeRate`] per pair quoted, in
/// [pair order](Exchange).
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Exchange, ExchangeRate, Rates};
/// use rust_decimal::dec;
///
/// let desk: Exchange = [ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?]
///     .into_iter()
///     .collect();
/// let rates: Rates<'_> = desk.iter();
///
/// assert_eq!(rates.count(), 1);
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Rates<'a>(btree_map::Iter<'a, Pair, Decimal>);

impl Iterator for Rates<'_> {
    type Item = ExchangeRate;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(borrowed_entry_to_rate)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for Rates<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(borrowed_entry_to_rate)
    }
}

impl ExactSizeIterator for Rates<'_> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl FusedIterator for Rates<'_> {}

/// The same rates, out of a table consumed whole.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Exchange, ExchangeRate, IntoRates};
/// use rust_decimal::dec;
///
/// let desk: Exchange = [ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?]
///     .into_iter()
///     .collect();
/// let rates: IntoRates = desk.into_iter();
///
/// assert_eq!(rates.count(), 1);
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct IntoRates(btree_map::IntoIter<Pair, Decimal>);

impl Iterator for IntoRates {
    type Item = ExchangeRate;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(entry_to_rate)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.0.size_hint()
    }
}

impl DoubleEndedIterator for IntoRates {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.next_back().map(entry_to_rate)
    }
}

impl ExactSizeIterator for IntoRates {
    fn len(&self) -> usize {
        self.0.len()
    }
}

impl FusedIterator for IntoRates {}

fn entry_to_rate((pair, rate): (Pair, Decimal)) -> ExchangeRate {
    ExchangeRate::new_unchecked(pair, rate)
}

fn borrowed_entry_to_rate((pair, rate): (&Pair, &Decimal)) -> ExchangeRate {
    entry_to_rate((*pair, *rate))
}

impl IntoIterator for Exchange {
    type Item = ExchangeRate;
    type IntoIter = IntoRates;

    fn into_iter(self) -> Self::IntoIter {
        IntoRates(self.rates.into_iter())
    }
}

/// Borrowing a table still yields owned [`ExchangeRate`]s, which are [`Copy`].
impl<'a> IntoIterator for &'a Exchange {
    type Item = ExchangeRate;
    type IntoIter = Rates<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Adds each rate as [`set_rate`](Exchange::set_rate) does, so a pair quoted
/// more than once keeps the rate given last. This holds whether the rate it
/// displaces came from the same batch or was already in the table.
///
/// ## 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.extend([
///     ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92))?,
///     ExchangeRate::new((Currency::EUR, Currency::JPY), dec!(160))?,
/// ]);
///
/// assert_eq!(
///     desk.rate((Currency::USD, Currency::EUR)).map(|rate| rate.rate()),
///     Some(dec!(0.92))
/// );
/// assert_eq!(desk.iter().len(), 2);
/// #
/// #     Ok(())
/// # }
/// ```
impl Extend<ExchangeRate> for Exchange {
    fn extend<I: IntoIterator<Item = ExchangeRate>>(&mut self, iter: I) {
        for rate in iter {
            self.set_rate(rate);
        }
    }
}

impl<'a> Extend<&'a ExchangeRate> for Exchange {
    fn extend<I: IntoIterator<Item = &'a ExchangeRate>>(&mut self, iter: I) {
        self.extend(iter.into_iter().copied());
    }
}

/// Collects rates into a table, adding each one as [`Extend`] does.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Exchange, ExchangeRate, Money};
/// use rust_decimal::dec;
///
/// let feed = [
///     ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?,
///     ExchangeRate::new((Currency::EUR, Currency::JPY), dec!(160))?,
/// ];
///
/// let desk: Exchange = feed.into_iter().collect();
///
/// assert_eq!(
///     desk.convert(Money::from_major(100, Currency::USD), Currency::EUR)?,
///     Money::from_major(90, Currency::EUR)
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl FromIterator<ExchangeRate> for Exchange {
    fn from_iter<I: IntoIterator<Item = ExchangeRate>>(iter: I) -> Self {
        let mut desk = Self::new();
        desk.extend(iter);

        desk
    }
}

impl<'a> FromIterator<&'a ExchangeRate> for Exchange {
    fn from_iter<I: IntoIterator<Item = &'a ExchangeRate>>(iter: I) -> Self {
        iter.into_iter().copied().collect()
    }
}

/// An error from converting an amount against an [`Exchange`].
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum ExchangeError {
    /// The table holds no rate for the pair.
    #[error("the table quotes no rate from {base} to {quote}")]
    #[diagnostic(
        code(lucre::exchange::unquoted),
        help("set a rate for the pair, or cross two rates that meet at a shared currency")
    )]
    #[non_exhaustive]
    Unquoted {
        /// The currency the amount was in.
        base: Currency,

        /// The currency asked for.
        quote: Currency,
    },

    /// The table quotes the pair, but converting at that rate failed. The
    /// source error says why, and names the pair.
    #[error("the rate the table quotes could not convert the amount")]
    #[diagnostic(code(lucre::exchange::convert), forward(source))]
    #[non_exhaustive]
    Convert {
        /// The error [`ExchangeRate::convert`] gave.
        #[from]
        source: ConvertError,
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal::prelude::*;
    use std::{
        collections::{HashSet, hash_map::DefaultHasher},
        hash::{Hash, Hasher},
    };

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

    #[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_answers_a_pair_named_in_advance_test() {
        let mut desk = Exchange::new();
        desk.set_rate(usd_eur());

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

    #[test]
    fn exchange_takes_a_pair_by_borrow_test() {
        let quoted = [Pair::new(Currency::USD, Currency::EUR)];
        let mut desk = Exchange::new();
        desk.set_rate(usd_eur());

        for pair in &quoted {
            assert_eq!(desk.rate(pair), Some(usd_eur()));
            assert_eq!(desk.remove_rate(pair), 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_rate_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_hands_back_the_rate_it_displaces_test() {
        let revised = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92)).unwrap();
        let mut desk = Exchange::new();

        assert_eq!(desk.set_rate(usd_eur()), None);
        assert_eq!(desk.set_rate(revised), Some(usd_eur()));
    }

    #[test]
    fn exchange_takes_par_in_as_it_takes_any_pair_test() {
        let par = ExchangeRate::identity(Currency::USD);
        let mut desk = Exchange::new();

        assert_eq!(desk.set_rate(par), None);
        assert_eq!(desk.set_rate(par), Some(par));
    }

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

    #[test]
    fn exchange_converts_at_the_rate_it_quotes_test() {
        let desk = Exchange::from_iter([usd_eur()]);

        assert_eq!(
            desk.convert(Money::from_major(100, Currency::USD), Currency::EUR),
            Ok(Money::from_major(90, Currency::EUR))
        );
    }

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

        assert_eq!(
            Exchange::new().convert(fare, Currency::USD),
            Err(ExchangeError::Unquoted {
                base: Currency::USD,
                quote: Currency::USD,
            })
        );
    }

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

        assert_eq!(desk.rate((Currency::USD, Currency::USD)), Some(discounted));
        assert_eq!(
            desk.convert(Money::from_minor(275, Currency::USD), Currency::USD),
            Ok(Money::from_decimal(dec!(2.7225), Currency::USD))
        );
    }

    #[test]
    fn exchange_refuses_to_convert_across_an_unquoted_pair_test() {
        let desk = Exchange::from_iter([usd_eur()]);

        assert_eq!(
            desk.convert(Money::from_major(100, Currency::USD), Currency::JPY),
            Err(ExchangeError::Unquoted {
                base: Currency::USD,
                quote: Currency::JPY
            })
        );
    }

    #[test]
    fn refusal_names_the_pair_it_could_not_price_test() {
        let refused = ExchangeError::Unquoted {
            base: Currency::USD,
            quote: Currency::JPY,
        };

        assert!(refused.to_string().contains("USD"));
        assert!(refused.to_string().contains("JPY"));
    }

    #[test]
    fn exchange_reports_an_unrepresentable_conversion_test() {
        let steep = ExchangeRate::new((Currency::USD, Currency::EUR), Decimal::MAX).unwrap();
        let desk = Exchange::from_iter([steep]);
        let fortune = Money::from_decimal(Decimal::MAX, Currency::USD);

        let refused = desk.convert(fortune, Currency::EUR).unwrap_err();

        assert!(matches!(refused, ExchangeError::Convert { .. }));
        assert_eq!(
            std::error::Error::source(&refused)
                .map(ToString::to_string)
                .as_deref(),
            Some("converting at USD/EUR gives an amount too large for a decimal")
        );
    }

    #[test]
    fn exchange_is_empty_until_a_pair_is_quoted_test() {
        let mut desk = Exchange::new();

        assert!(desk.is_empty());

        desk.set_rate(usd_eur());

        assert!(!desk.is_empty());
    }

    #[test]
    fn exchange_counts_one_rate_per_pair_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let revised = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92)).unwrap();
        let mut desk = Exchange::new();

        assert_eq!(desk.len(), 0);

        desk.set_rate(usd_eur());
        desk.set_rate(eur_usd);
        desk.set_rate(revised);

        assert_eq!(desk.len(), 2);
    }

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

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

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

        assert_eq!(
            desk.remove_rate(Pair::new(Currency::USD, Currency::EUR)),
            Some(usd_eur())
        );
    }

    #[test]
    fn exchange_withdraws_one_direction_of_a_pair_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let mut desk = Exchange::from_iter([usd_eur(), eur_usd]);

        desk.remove_rate((Currency::USD, Currency::EUR));

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

    #[test]
    fn exchange_withdraws_nothing_from_an_unquoted_pair_test() {
        let mut desk = Exchange::new();

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

    #[test]
    fn exchange_clears_every_rate_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let mut desk = Exchange::from_iter([usd_eur(), eur_usd]);

        desk.clear();

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

    #[test]
    fn exchange_iterates_in_pair_order_test() {
        let usd_jpy = ExchangeRate::new((Currency::USD, Currency::JPY), dec!(144)).unwrap();
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let mut desk = Exchange::new();
        desk.set_rate(usd_jpy);
        desk.set_rate(usd_eur());
        desk.set_rate(eur_usd);

        assert_eq!(
            desk.iter().collect::<Vec<_>>(),
            [eur_usd, usd_eur(), usd_jpy]
        );
    }

    #[test]
    fn exchange_collects_from_rates_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let rates = [usd_eur(), eur_usd];

        let owned: Exchange = rates.into_iter().collect();
        let borrowed: Exchange = rates.iter().collect();

        assert_eq!(owned.rate((Currency::USD, Currency::EUR)), Some(usd_eur()));
        assert_eq!(owned.rate((Currency::EUR, Currency::USD)), Some(eur_usd));
        assert_eq!(owned, borrowed);
    }

    #[test]
    fn exchange_collects_a_later_rate_over_an_earlier_one_test() {
        let revised = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.92)).unwrap();

        let desk: Exchange = [usd_eur(), revised].into_iter().collect();

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

    #[test]
    fn exchange_extends_from_rates_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let usd_jpy = ExchangeRate::new((Currency::USD, Currency::JPY), dec!(144)).unwrap();
        let mut desk = Exchange::from_iter([usd_eur()]);
        desk.extend([eur_usd]);
        desk.extend([&usd_jpy]);

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

    #[test]
    fn into_iterator_yields_rates_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let desk: Exchange = [usd_eur(), eur_usd].into_iter().collect();

        let borrowed: Vec<ExchangeRate> = (&desk).into_iter().collect();
        let owned: Vec<ExchangeRate> = desk.into_iter().collect();

        assert_eq!(owned, [eur_usd, usd_eur()]);
        assert_eq!(owned, borrowed);
    }

    #[test]
    fn rates_count_and_reverse_without_walking_forward_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let desk: Exchange = [usd_eur(), eur_usd].into_iter().collect();

        assert_eq!(desk.iter().len(), 2);
        assert_eq!(desk.iter().rev().collect::<Vec<_>>(), [usd_eur(), eur_usd]);
        assert_eq!(
            desk.into_iter().rev().collect::<Vec<_>>(),
            [usd_eur(), eur_usd]
        );
    }

    #[test]
    fn equal_tables_hash_alike_test() {
        let eur_usd = ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.1)).unwrap();
        let one = Exchange::from_iter([usd_eur(), eur_usd]);
        let other = Exchange::from_iter([eur_usd, usd_eur()]);

        let hash_of = |desk: &Exchange| {
            let mut hasher = DefaultHasher::new();
            desk.hash(&mut hasher);
            hasher.finish()
        };

        assert_eq!(one, other);
        assert_eq!(hash_of(&one), hash_of(&other));
        assert_eq!(HashSet::from([one, other]).len(), 1);
    }
}