lucre 0.13.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
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! What one currency costs in another, and the arithmetic over that.

use std::{fmt, ops::Range, str::FromStr};

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

use crate::{
    Currency, CurrencyError, Decimal, IsoAlphabeticCode, IsoAlphabeticCodeError, Money, MoneyError,
    format::write_padded,
};

const SEPARATOR: char = '/';

/// The rate at which one currency buys another.
///
/// A rate works in one direction only: the rate from dollars to euros is not
/// the rate back. It multiplies, so it is always positive. The currency being
/// priced is the [`base`](ExchangeRate::base), and the currency it is priced
/// in is the [`quote`](ExchangeRate::quote). Two rates that share a currency
/// combine with [`cross_with`](ExchangeRate::cross_with), which is how a pair
/// nobody prices 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 {
    pair: Pair,
    rate: Decimal,
}

impl ExchangeRate {
    /// Quote a rate over a currency pair.
    ///
    /// The pair may be given as a [`Pair`] or as the two currencies alone,
    /// base first. The rate multiplies an amount in the base currency to give
    /// an amount in the quote currency. A currency may be priced against
    /// itself, though [`identity`](ExchangeRate::identity) says that more
    /// plainly.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate, Pair};
    /// use rust_decimal::dec;
    ///
    /// let quoted = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?;
    ///
    /// assert_eq!(quoted, ExchangeRate::new("USD/EUR".parse::<Pair>()?, dec!(0.9))?);
    /// assert!(ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0)).is_err());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`ExchangeRateError::InvalidRate`] if the rate is zero or
    /// negative.
    pub fn new<P: Into<Pair>, R: Into<Decimal>>(
        pair: P,
        rate: R,
    ) -> Result<Self, ExchangeRateError> {
        let rate = rate.into();

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

        Ok(Self {
            pair: pair.into(),
            rate,
        })
    }

    /// The rate of a currency against itself. Converting leaves an amount
    /// unchanged.
    ///
    /// ## 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 {
            pair: Pair::new(currency, currency),
            rate: Decimal::ONE,
        }
    }

    /// Quote a rate without checking the multiplier. The caller must know it
    /// is positive.
    pub(super) fn new_unchecked(pair: Pair, rate: Decimal) -> Self {
        Self { pair, rate }
    }

    /// The currency being priced.
    ///
    /// ## 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.base(), Currency::USD);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn base(self) -> Currency {
        self.pair.base()
    }

    /// The currency it is priced 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.quote(), Currency::EUR);
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn quote(self) -> Currency {
        self.pair.quote()
    }

    /// Both currencies together, base first.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate, Pair};
    /// use rust_decimal::dec;
    ///
    /// let rate = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.9))?;
    ///
    /// assert_eq!(rate.pair(), Pair::new(Currency::USD, Currency::EUR));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn pair(self) -> Pair {
        self.pair
    }

    /// The multiplier.
    ///
    /// ## 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 quote currency.
    ///
    /// The result keeps every digit the multiplication produced. Rounding to
    /// the currency's minor units is [`Money::round`]'s job.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{ConvertError, Currency, ExchangeRate, Money};
    /// 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!(matches!(
    ///     rate.convert(Money::from_major(10, Currency::GBP)),
    ///     Err(ConvertError::CurrencyMismatch {
    ///         base: Currency::USD,
    ///         found: Currency::GBP,
    ///         ..
    ///     })
    /// ));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`ConvertError::CurrencyMismatch`] if the amount is not in the
    /// base currency.
    /// Returns [`ConvertError::Overflow`] if the result is too large for a
    /// [`Decimal`].
    pub fn convert(self, money: Money) -> Result<Money, ConvertError> {
        if money.currency() != self.base() {
            return Err(ConvertError::CurrencyMismatch {
                base: self.base(),
                found: money.currency(),
            });
        }

        let scaled = money
            .checked_mul(self.rate)
            .map_err(|source| ConvertError::Overflow {
                pair: self.pair,
                source,
            })?;

        Ok(Money::from_decimal(scaled.amount(), self.quote()))
    }

    /// Combine two rates that share a currency.
    ///
    /// This rate's quote currency must be `other`'s base currency. The result
    /// is one rate from this rate's base to `other`'s quote, which is 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.base(), Currency::USD);
    /// assert_eq!(usd_jpy.quote(), Currency::JPY);
    /// assert_eq!(usd_jpy.rate(), dec!(144.0));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`CrossRateError::CurrencyMismatch`] if this rate's quote
    /// currency is not `other`'s base currency.
    /// Returns [`CrossRateError::Overflow`] if the combined rate is too large
    /// for a [`Decimal`], and [`CrossRateError::Rate`] if the combined rate
    /// cannot be quoted.
    pub fn cross_with(self, other: Self) -> Result<Self, CrossRateError> {
        if self.quote() != other.base() {
            return Err(CrossRateError::CurrencyMismatch {
                first_quote: self.quote(),
                second_base: other.base(),
            });
        }

        let pair = Pair::new(self.base(), other.quote());
        let rate = self
            .rate
            .checked_mul(other.rate)
            .ok_or(CrossRateError::Overflow { pair })?;

        Self::new(pair, rate).map_err(|source| CrossRateError::Rate { pair, source })
    }

    /// The rate back the other way, over the inverted pair.
    ///
    /// The multiplier becomes one divided by this one, so the result prices
    /// the quote currency in the base. This treats both directions as priced
    /// alike. A desk that charges a spread quotes each direction separately
    /// instead.
    ///
    /// Dividing keeps 28 significant digits, so inverting twice need not give
    /// back the rate it started from.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, ExchangeRate, Money};
    /// use rust_decimal::dec;
    ///
    /// let usd_eur = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.8))?;
    /// let eur_usd = usd_eur.invert()?;
    ///
    /// assert_eq!(eur_usd.base(), Currency::EUR);
    /// assert_eq!(eur_usd.quote(), Currency::USD);
    /// assert_eq!(eur_usd.rate(), dec!(1.25));
    /// assert_eq!(
    ///     eur_usd.convert(Money::from_major(80, Currency::EUR))?,
    ///     Money::from_major(100, Currency::USD)
    /// );
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`InvertError::Underflow`] if the multiplier is `2e28` or
    /// above, since one divided by it rounds away to zero.
    pub fn invert(self) -> Result<Self, InvertError> {
        let inverted = Decimal::ONE
            .checked_div(self.rate)
            .filter(|inverted| inverted > &Decimal::ZERO)
            .ok_or(InvertError::Underflow {
                pair: self.pair,
                rate: self.rate,
            })?;

        Ok(Self::new_unchecked(self.pair.invert(), inverted))
    }
}

/// Writes the pair, a space, and the multiplier. The multiplier keeps the
/// digits it was quoted with, since a rate has no minor units to pad out to.
///
/// ## 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_string(), "USD/EUR 0.9");
///
/// // Width, fill, and alignment flags are honored. The default is right
/// // alignment, as it is for an amount.
/// assert_eq!(format!("{rate:>13}"), "  USD/EUR 0.9");
/// #
/// #     Ok(())
/// # }
/// ```
impl fmt::Display for ExchangeRate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write_padded(f, &format!("{} {}", self.pair, self.rate))
    }
}

/// The two currencies a rate covers: the currency being priced, a slash, and
/// the currency it is priced in.
///
/// Pairs sort by the currency being priced, then by the currency it is priced
/// in, which is the order an [`Exchange`](super::Exchange) is read in.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Pair};
///
/// let pair: Pair = "USD/EUR".parse()?;
///
/// assert_eq!(pair, Pair::new(Currency::USD, Currency::EUR));
/// assert_eq!(pair.base(), Currency::USD);
/// assert_eq!(pair.quote(), Currency::EUR);
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Pair {
    base: Currency,
    quote: Currency,
}

impl Pair {
    /// Pair two currencies, the one being priced first.
    ///
    /// The order matters: `USD/EUR` and `EUR/USD` are different pairs.
    ///
    /// A pair can be made at compile time, so the pairs a system quotes keep a
    /// `const` table of their own, the way the currencies themselves do.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Pair};
    ///
    /// const USD_EUR: Pair = Pair::new(Currency::USD, Currency::EUR);
    ///
    /// assert_ne!(USD_EUR, Pair::new(Currency::EUR, Currency::USD));
    /// ```
    #[must_use]
    pub const fn new(base: Currency, quote: Currency) -> Self {
        Self { base, quote }
    }

    /// The currency being priced.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Pair};
    ///
    /// const BASE: Currency = Pair::new(Currency::USD, Currency::EUR).base();
    ///
    /// assert_eq!(BASE, Currency::USD);
    /// ```
    #[must_use]
    pub const fn base(self) -> Currency {
        self.base
    }

    /// The currency it is priced in.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Pair};
    ///
    /// const QUOTE: Currency = Pair::new(Currency::USD, Currency::EUR).quote();
    ///
    /// assert_eq!(QUOTE, Currency::EUR);
    /// ```
    #[must_use]
    pub const fn quote(self) -> Currency {
        self.quote
    }

    /// The pair the other way round, pricing the quote currency in the base.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Pair};
    ///
    /// const EUR_USD: Pair = Pair::new(Currency::USD, Currency::EUR).invert();
    ///
    /// assert_eq!(EUR_USD, Pair::new(Currency::EUR, Currency::USD));
    /// ```
    #[must_use]
    pub const fn invert(self) -> Self {
        Self::new(self.quote, self.base)
    }
}

/// Takes the two currencies, the one being priced first, so the currencies
/// alone will do anywhere a pair is asked for.
///
/// ## Example
///
/// ```
/// use lucre::{Currency, Pair};
///
/// assert_eq!(
///     Pair::from((Currency::USD, Currency::EUR)),
///     Pair::new(Currency::USD, Currency::EUR)
/// );
/// ```
impl From<(Currency, Currency)> for Pair {
    fn from((base, quote): (Currency, Currency)) -> Self {
        Self::new(base, quote)
    }
}

impl From<&(Currency, Currency)> for Pair {
    fn from(currencies: &(Currency, Currency)) -> Self {
        Self::from(*currencies)
    }
}

impl From<&Pair> for Pair {
    fn from(pair: &Pair) -> Self {
        *pair
    }
}

/// Gives the two currencies back, the one being priced first, so a pair
/// survives a round trip through the tuple form.
///
/// ## Example
///
/// ```
/// use lucre::{Currency, Pair};
///
/// let pair = Pair::new(Currency::USD, Currency::EUR);
/// let (base, quote) = pair.into();
///
/// assert_eq!(base, Currency::USD);
/// assert_eq!(quote, Currency::EUR);
/// assert_eq!(Pair::from((base, quote)), pair);
/// ```
impl From<Pair> for (Currency, Currency) {
    fn from(Pair { base, quote }: Pair) -> Self {
        (base, quote)
    }
}

/// Writes the currency being priced, a slash, and the currency it is priced
/// in.
///
/// ## Example
///
/// ```
/// use lucre::{Currency, Pair};
///
/// assert_eq!(Pair::new(Currency::USD, Currency::EUR).to_string(), "USD/EUR");
/// ```
impl fmt::Display for Pair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self { base, quote } = self;

        write!(f, "{base}{SEPARATOR}{quote}")
    }
}

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

/// Reads two ISO 4217 codes over a slash, the notation
/// [`Display`](fmt::Display) writes. Codes must be capitals, and the first
/// slash divides them.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Pair, ParsePairError, Side};
///
/// assert_eq!("USD/EUR".parse::<Pair>()?, Pair::new(Currency::USD, Currency::EUR));
///
/// // Each kind of bad text gets its own error, and the error names the side
/// // at fault.
/// assert!(matches!(
///     "USDEUR".parse::<Pair>(),
///     Err(ParsePairError::MissingSeparator { .. })
/// ));
/// assert!(matches!(
///     "usd/EUR".parse::<Pair>(),
///     Err(ParsePairError::Code { side: Side::Base, .. })
/// ));
/// assert!(matches!(
///     "USD/ZZZ".parse::<Pair>(),
///     Err(ParsePairError::UnknownCurrency { side: Side::Quote, .. })
/// ));
/// #
/// #     Ok(())
/// # }
/// ```
impl FromStr for Pair {
    type Err = ParsePairError;

    /// ## Errors
    ///
    /// Returns [`ParsePairError::MissingSeparator`] if no slash divides the
    /// two currencies, [`ParsePairError::Code`] if either side is not three
    /// capitals, and [`ParsePairError::UnknownCurrency`] if either side is a
    /// code no currency uses. The latter two name the [`Side`] at fault, and
    /// the base is checked before the quote.
    fn from_str(notation: &str) -> Result<Self, Self::Err> {
        let Some(slash) = notation.find(SEPARATOR) else {
            return Err(ParsePairError::MissingSeparator {
                notation: notation.to_string(),
                at: 0..notation.len(),
            });
        };

        Ok(Self {
            base: read_currency(notation, Side::Base, 0..slash)?,
            quote: read_currency(
                notation,
                Side::Quote,
                slash + SEPARATOR.len_utf8()..notation.len(),
            )?,
        })
    }
}

/// Reads the same notation [`FromStr`](Pair::from_str) accepts, and rejects
/// text for the same reasons.
impl TryFrom<&str> for Pair {
    type Error = ParsePairError;

    fn try_from(notation: &str) -> Result<Self, Self::Error> {
        notation.parse()
    }
}

/// Reads the side of `notation` that `at` covers. Keeps a misspelled code
/// apart from a well-formed one no currency uses, and both apart from the same
/// fault on the other side.
fn read_currency(notation: &str, side: Side, at: Range<usize>) -> Result<Currency, ParsePairError> {
    let code = IsoAlphabeticCode::try_from(&notation[at.clone()]).map_err(|source| {
        ParsePairError::Code {
            notation: notation.to_string(),
            side,
            at: at.clone(),
            source,
        }
    })?;

    Currency::try_from(code).map_err(|source| ParsePairError::UnknownCurrency {
        notation: notation.to_string(),
        side,
        at,
        source,
    })
}

/// Which of a [`Pair`]'s two currencies is meant: the one being priced, or
/// the one it is priced in.
///
/// ## Example
///
/// ```
/// use lucre::{Pair, ParsePairError, Side};
///
/// let refused = "USD/ZZZ".parse::<Pair>().unwrap_err();
///
/// assert!(matches!(
///     refused,
///     ParsePairError::UnknownCurrency { side: Side::Quote, .. }
/// ));
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum Side {
    /// The currency being priced, written before the slash.
    Base,

    /// The currency it is priced in, written after the slash.
    Quote,
}

/// Writes the side's name in lower case, so an error message reads as a
/// sentence around it.
///
/// ## Example
///
/// ```
/// use lucre::Side;
///
/// assert_eq!(Side::Base.to_string(), "base");
/// assert_eq!(Side::Quote.to_string(), "quote");
/// ```
impl fmt::Display for Side {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Base => "base",
            Self::Quote => "quote",
        })
    }
}

/// An error from quoting an [`ExchangeRate`].
#[derive(Clone, Copy, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum ExchangeRateError {
    /// The multiplier was zero or negative.
    #[error("an exchange rate must be above zero, but got {rate}")]
    #[diagnostic(
        code(lucre::exchange::rate::invalid),
        help("to price the other direction, quote the inverse pair instead of a negative rate")
    )]
    #[non_exhaustive]
    InvalidRate {
        /// The rejected multiplier, as given.
        rate: Decimal,
    },
}

/// An error from restating an amount at an [`ExchangeRate`].
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum ConvertError {
    /// The amount is not in the currency the rate prices.
    #[error("the rate prices {base}, but the amount is in {found}")]
    #[diagnostic(
        code(lucre::exchange::convert::currency_mismatch),
        help("invert the rate to price {found} instead, or convert the amount to {base} first")
    )]
    #[non_exhaustive]
    CurrencyMismatch {
        /// The currency the rate prices.
        base: Currency,

        /// The currency the amount was in.
        found: Currency,
    },

    /// The converted amount is too large for a [`Decimal`]. Names the pair;
    /// the source error says what overflowed.
    #[error("converting at {pair} gives an amount too large for a decimal")]
    #[diagnostic(code(lucre::exchange::convert::overflow), forward(source))]
    #[non_exhaustive]
    Overflow {
        /// The pair the rate quotes.
        pair: Pair,

        /// The error [`Money::checked_mul`] gave.
        source: MoneyError,
    },
}

/// An error from reading a [`Pair`] out of text.
///
/// Every variant keeps the text it read and points into it by byte range. The
/// ranges count from the start of that text, so they index it as it was handed
/// in.
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum ParsePairError {
    /// No slash divides the text into two currencies.
    #[error("a currency pair is two codes split by a slash, but got {notation:?}")]
    #[diagnostic(
        code(lucre::exchange::pair::missing_separator),
        help("write the pair as `USD/EUR`")
    )]
    #[non_exhaustive]
    MissingSeparator {
        /// The whole text. With no slash there is no side to name.
        #[source_code]
        notation: String,

        /// Covers the whole text.
        #[label("no slash here")]
        at: Range<usize>,
    },

    /// One side is not spelled as an ISO 4217 code. Names that side; the
    /// source error quotes the text back.
    #[error("the {side} of the pair is not an ISO 4217 code")]
    #[diagnostic(code(lucre::exchange::pair::code), forward(source))]
    #[non_exhaustive]
    Code {
        /// The whole text, both sides and the slash between them.
        #[source_code]
        notation: String,

        /// The side whose code was misspelled.
        side: Side,

        /// Covers that side, the slash excluded.
        #[label("not an ISO 4217 code")]
        at: Range<usize>,

        /// The error from reading that side's text.
        source: IsoAlphabeticCodeError,
    },

    /// One side is a well-formed code that no currency uses. Names that side;
    /// the source error quotes the code back.
    #[error("the {side} of the pair names no ISO 4217 currency")]
    #[diagnostic(code(lucre::exchange::pair::unknown_currency), forward(source))]
    #[non_exhaustive]
    UnknownCurrency {
        /// The whole text, both sides and the slash between them.
        #[source_code]
        notation: String,

        /// The side whose code names no currency.
        side: Side,

        /// Covers that side, the slash excluded.
        #[label("names no currency")]
        at: Range<usize>,

        /// The error from looking that side's code up.
        source: CurrencyError,
    },
}

impl ParsePairError {
    /// The text that was read.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Pair;
    ///
    /// let error = "USD/ZZZ".parse::<Pair>().unwrap_err();
    ///
    /// assert_eq!(error.notation(), "USD/ZZZ");
    /// assert_eq!(&error.notation()[error.span()], "ZZZ");
    /// ```
    #[must_use]
    pub fn notation(&self) -> &str {
        match self {
            Self::MissingSeparator { notation, .. }
            | Self::Code { notation, .. }
            | Self::UnknownCurrency { notation, .. } => notation,
        }
    }

    /// The byte range the error points at.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Pair;
    ///
    /// let error = "usd/EUR".parse::<Pair>().unwrap_err();
    ///
    /// assert_eq!(error.span(), 0..3);
    /// ```
    #[must_use]
    pub fn span(&self) -> Range<usize> {
        match self {
            Self::MissingSeparator { at, .. }
            | Self::Code { at, .. }
            | Self::UnknownCurrency { at, .. } => at.clone(),
        }
    }
}

/// An error from combining two [`ExchangeRate`]s.
#[derive(Clone, Copy, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum CrossRateError {
    /// The first rate's quote currency is not the second rate's base
    /// currency, so there is no pair to cross to.
    #[error("the first rate prices into {first_quote}, but the second prices {second_base}")]
    #[diagnostic(
        code(lucre::exchange::cross::currency_mismatch),
        help("crossing needs the first rate to price into the currency the second prices")
    )]
    #[non_exhaustive]
    CurrencyMismatch {
        /// The currency the first rate prices into.
        first_quote: Currency,

        /// The currency the second rate prices.
        second_base: Currency,
    },

    /// The combined rate is too large for a [`Decimal`].
    #[error("the crossed {pair} rate is too large for a decimal")]
    #[diagnostic(
        code(lucre::exchange::cross::overflow),
        help("a `Decimal` holds up to 28 significant digits")
    )]
    #[non_exhaustive]
    Overflow {
        /// The pair the crossing prices.
        pair: Pair,
    },

    /// The combined rate cannot be quoted. The source error says why.
    #[error("the crossed {pair} rate cannot be quoted")]
    #[diagnostic(code(lucre::exchange::cross::rate), forward(source))]
    #[non_exhaustive]
    Rate {
        /// The pair the crossing prices.
        pair: Pair,

        /// The error [`ExchangeRate::new`] gave.
        source: ExchangeRateError,
    },
}

/// An error from turning an [`ExchangeRate`] around.
#[derive(Clone, Copy, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum InvertError {
    /// One divided by the multiplier rounds to zero, which no rate may be.
    #[error("the {pair} rate {rate} is too large to invert")]
    #[diagnostic(
        code(lucre::exchange::invert::underflow),
        help("a rate below `2e28` inverts; quote the other direction directly instead")
    )]
    #[non_exhaustive]
    Underflow {
        /// The pair the rate quotes.
        pair: Pair,

        /// The multiplier that could not be inverted.
        rate: Decimal,
    },
}

#[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(ExchangeRateError::InvalidRate { rate: dec!(0) })
        );
    }

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

    #[test]
    fn refusal_names_the_multiplier_it_turned_away_test() {
        let refused = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(-0.9)).unwrap_err();

        assert!(refused.to_string().contains("-0.9"));
    }

    #[test]
    fn rate_quotes_a_pair_named_in_advance_test() {
        let pair = Pair::new(Currency::USD, Currency::EUR);

        assert_eq!(ExchangeRate::new(pair, dec!(0.9)), Ok(usd_eur()));
    }

    #[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(ConvertError::CurrencyMismatch {
                base: Currency::USD,
                found: Currency::GBP
            })
        );
    }

    #[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(ConvertError::Overflow {
                pair: Pair::new(Currency::USD, Currency::EUR),
                source: MoneyError::Overflow
            })
        );
    }

    #[test]
    fn convert_overflow_names_the_pair_and_keeps_its_cause_test() {
        let steep = ExchangeRate::new((Currency::USD, Currency::EUR), Decimal::MAX).unwrap();
        let refused = steep
            .convert(Money::from_decimal(Decimal::MAX, Currency::USD))
            .unwrap_err();

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

    #[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.base(), Currency::USD);
        assert_eq!(usd_jpy.quote(), 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(CrossRateError::CurrencyMismatch {
                first_quote: Currency::EUR,
                second_base: Currency::GBP
            })
        );
    }

    #[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(CrossRateError::Overflow {
                pair: Pair::new(Currency::USD, Currency::JPY)
            })
        );
    }

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

        assert_eq!(
            vanished,
            Err(CrossRateError::Rate {
                pair: Pair::new(Currency::USD, Currency::JPY),
                source: ExchangeRateError::InvalidRate { rate: dec!(0) }
            })
        );

        let refused = vanished.unwrap_err();

        assert_eq!(
            refused.to_string(),
            "the crossed USD/JPY rate cannot be quoted"
        );
        assert_eq!(
            std::error::Error::source(&refused)
                .map(ToString::to_string)
                .as_deref(),
            Some("an exchange rate must be above zero, but got 0")
        );
    }

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

        assert_eq!(
            slight.cross_with(eur_jpy),
            Err(CrossRateError::Rate {
                pair: Pair::new(Currency::USD, Currency::JPY),
                source: ExchangeRateError::InvalidRate { rate: dec!(0) }
            })
        );
    }

    #[test]
    fn rate_displays_the_pair_and_the_multiplier_test() {
        assert_eq!(usd_eur().to_string(), "USD/EUR 0.9");
        assert_eq!(
            ExchangeRate::identity(Currency::JPY).to_string(),
            "JPY/JPY 1"
        );
    }

    #[test]
    fn rate_displays_the_multiplier_as_quoted_test() {
        let thousandths = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.900)).unwrap();

        assert_eq!(thousandths.to_string(), "USD/EUR 0.900");
    }

    #[test]
    fn rate_display_honors_width_test() {
        assert_eq!(format!("{:>13}", usd_eur()), "  USD/EUR 0.9");
        assert_eq!(format!("{:<13}", usd_eur()), "USD/EUR 0.9  ");
    }

    #[test]
    fn pair_names_two_currencies_with_no_rate_in_hand_test() {
        let pair = Pair::new(Currency::USD, Currency::EUR);

        assert_eq!(pair.base(), Currency::USD);
        assert_eq!(pair.quote(), Currency::EUR);
    }

    #[test]
    fn pair_is_named_before_the_program_runs_test() {
        const USD_EUR: Pair = Pair::new(Currency::USD, Currency::EUR);
        const BASE: Currency = USD_EUR.base();
        const QUOTE: Currency = USD_EUR.quote();

        assert_eq!(BASE, Currency::USD);
        assert_eq!(QUOTE, Currency::EUR);
    }

    #[test]
    fn pair_converts_from_a_borrow_test() {
        let quoted = [Pair::new(Currency::USD, Currency::EUR)];

        for pair in &quoted {
            assert_eq!(Pair::from(pair), quoted[0]);
            assert_eq!(ExchangeRate::new(pair, dec!(0.9)), Ok(usd_eur()));
        }
    }

    #[test]
    fn pair_reads_a_borrowed_tuple_test() {
        let quoted = [(Currency::USD, Currency::EUR)];

        for currencies in &quoted {
            assert_eq!(
                Pair::from(currencies),
                Pair::new(Currency::USD, Currency::EUR)
            );
            assert_eq!(ExchangeRate::new(currencies, dec!(0.9)), Ok(usd_eur()));
        }
    }

    #[test]
    fn pair_reads_a_tuple_in_the_order_a_board_speaks_test() {
        assert_eq!(
            Pair::from((Currency::USD, Currency::EUR)),
            Pair::new(Currency::USD, Currency::EUR)
        );
    }

    #[test]
    fn pair_splits_back_into_the_two_currencies_it_names_test() {
        let (base, quote) = Pair::new(Currency::USD, Currency::EUR).into();

        assert_eq!(base, Currency::USD);
        assert_eq!(quote, Currency::EUR);
    }

    #[test]
    fn pair_displays_the_two_currencies_over_a_slash_test() {
        assert_eq!(usd_eur().pair().to_string(), "USD/EUR");
    }

    #[test]
    fn pairs_sort_by_the_currency_priced_then_the_one_it_is_priced_in_test() {
        let mut pairs = [
            Pair::new(Currency::USD, Currency::JPY),
            Pair::new(Currency::EUR, Currency::USD),
            Pair::new(Currency::USD, Currency::EUR),
        ];
        pairs.sort();

        assert_eq!(
            pairs.map(|pair| pair.to_string()),
            ["EUR/USD", "USD/EUR", "USD/JPY"]
        );
    }

    #[test]
    fn pair_reads_back_what_it_writes_test() {
        let pair = usd_eur().pair();

        assert_eq!(pair.to_string().parse(), Ok(pair));
    }

    #[test]
    fn pair_reads_text_whichever_conversion_a_caller_reaches_for_test() {
        let pair = Pair::new(Currency::USD, Currency::EUR);

        assert_eq!(Pair::try_from("USD/EUR"), Ok(pair));
        assert_eq!("USD/EUR".parse(), Ok(pair));
    }

    #[test]
    fn pair_refuses_currencies_with_nothing_between_them_test() {
        assert_eq!(
            "USDEUR".parse::<Pair>(),
            Err(ParsePairError::MissingSeparator {
                notation: "USDEUR".to_string(),
                at: 0..6,
            })
        );
    }

    #[test]
    fn pair_refuses_a_code_no_currency_bears_test() {
        let unassigned = CurrencyError::UnknownAlphabeticCode {
            code: "ZZZ".to_owned(),
        };

        assert_eq!(
            "ZZZ/EUR".parse::<Pair>(),
            Err(ParsePairError::UnknownCurrency {
                notation: "ZZZ/EUR".to_string(),
                side: Side::Base,
                at: 0..3,
                source: unassigned.clone(),
            })
        );
        assert_eq!(
            "USD/ZZZ".parse::<Pair>(),
            Err(ParsePairError::UnknownCurrency {
                notation: "USD/ZZZ".to_string(),
                side: Side::Quote,
                at: 4..7,
                source: unassigned,
            })
        );
    }

    #[test]
    fn refusal_leaves_the_unassigned_code_to_the_error_it_wraps_test() {
        let refused = "USD/ZZZ".parse::<Pair>().unwrap_err();

        assert_eq!(
            std::error::Error::source(&refused)
                .map(ToString::to_string)
                .as_deref(),
            Some(r#"no ISO 4217 currency uses the code "ZZZ""#)
        );
    }

    #[test]
    fn pair_reads_codes_as_iso_writes_them_test() {
        assert_eq!(
            "usd/EUR".parse::<Pair>(),
            Err(ParsePairError::Code {
                notation: "usd/EUR".to_string(),
                side: Side::Base,
                at: 0..3,
                source: IsoAlphabeticCodeError::InvalidCode {
                    code: "usd".to_string()
                },
            })
        );
        assert_eq!(
            "USD/eur".parse::<Pair>(),
            Err(ParsePairError::Code {
                notation: "USD/eur".to_string(),
                side: Side::Quote,
                at: 4..7,
                source: IsoAlphabeticCodeError::InvalidCode {
                    code: "eur".to_string()
                },
            })
        );
    }

    #[test]
    fn pair_takes_the_first_separator_as_the_dividing_one_test() {
        assert_eq!(
            "USD/EUR/JPY".parse::<Pair>(),
            Err(ParsePairError::Code {
                notation: "USD/EUR/JPY".to_string(),
                side: Side::Quote,
                at: 4..11,
                source: IsoAlphabeticCodeError::InvalidCode {
                    code: "EUR/JPY".to_string()
                },
            })
        );
    }

    #[test]
    fn refusals_name_the_text_they_turned_away_test() {
        let unseparated = "USDEUR".parse::<Pair>().unwrap_err().to_string();
        let misspelled = "usd/eur".parse::<Pair>().unwrap_err().to_string();
        let unassigned = "USD/ZZZ".parse::<Pair>().unwrap_err().to_string();

        assert_eq!(
            unseparated,
            r#"a currency pair is two codes split by a slash, but got "USDEUR""#
        );
        assert_eq!(misspelled, "the base of the pair is not an ISO 4217 code");
        assert_eq!(
            unassigned,
            "the quote of the pair names no ISO 4217 currency"
        );
    }

    #[test]
    fn refusal_leaves_the_misspelling_to_the_error_it_wraps_test() {
        let refused = "usd/EUR".parse::<Pair>().unwrap_err();

        assert_eq!(
            std::error::Error::source(&refused)
                .map(ToString::to_string)
                .as_deref(),
            Some(r#"an alphabetic currency code is three capital letters, but got "usd""#)
        );
    }

    #[test]
    fn refusal_points_at_the_side_at_fault_test() {
        let misspelled = "USD/eur".parse::<Pair>().unwrap_err();
        let unassigned = "ZZZ/EUR".parse::<Pair>().unwrap_err();

        assert_eq!(&misspelled.notation()[misspelled.span()], "eur");
        assert_eq!(&unassigned.notation()[unassigned.span()], "ZZZ");
    }

    #[test]
    fn refusal_takes_its_advice_from_the_error_it_wraps_test() {
        let refused = "USD/ZZZ".parse::<Pair>().unwrap_err();

        assert_eq!(
            refused.help().map(|help| help.to_string()).as_deref(),
            CurrencyError::UnknownAlphabeticCode {
                code: "ZZZ".to_owned(),
            }
            .help()
            .map(|help| help.to_string())
            .as_deref()
        );
    }

    #[test]
    fn debug_spells_a_pair_test() {
        assert_eq!(
            format!("{:?}", Pair::new(Currency::USD, Currency::EUR)),
            "Pair(USD/EUR)"
        );
    }

    #[test]
    fn inverting_a_pair_swaps_its_sides_test() {
        assert_eq!(
            Pair::new(Currency::USD, Currency::EUR).invert(),
            Pair::new(Currency::EUR, Currency::USD)
        );
    }

    #[test]
    fn inverting_a_rate_prices_the_other_direction_test() {
        let usd_eur = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(0.8)).unwrap();

        assert_eq!(
            usd_eur.invert(),
            Ok(ExchangeRate::new((Currency::EUR, Currency::USD), dec!(1.25)).unwrap())
        );
    }

    #[test]
    fn inverting_the_identity_rate_leaves_it_alone_test() {
        let identity = ExchangeRate::identity(Currency::USD);

        assert_eq!(identity.invert(), Ok(identity));
    }

    #[test]
    fn inverting_twice_rounds_at_28_digits_test() {
        let usd_eur = ExchangeRate::new((Currency::USD, Currency::EUR), dec!(3)).unwrap();
        let round_trip = usd_eur.invert().unwrap().invert().unwrap();

        assert_eq!(round_trip.pair(), usd_eur.pair());
        assert_ne!(round_trip.rate(), usd_eur.rate());
    }

    #[test]
    fn inverting_refuses_a_multiplier_that_divides_away_test() {
        let huge = Decimal::from_str("20000000000000000000000000000").unwrap();
        let usd_eur = ExchangeRate::new((Currency::USD, Currency::EUR), huge).unwrap();

        assert_eq!(
            usd_eur.invert(),
            Err(InvertError::Underflow {
                pair: Pair::new(Currency::USD, Currency::EUR),
                rate: huge,
            })
        );
    }

    #[test]
    fn inverting_holds_on_to_the_largest_multiplier_it_can_test() {
        let large = Decimal::from_str("19999999999999999999999999999").unwrap();
        let usd_eur = ExchangeRate::new((Currency::USD, Currency::EUR), large).unwrap();

        assert!(usd_eur.invert().is_ok());
    }
}