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
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
//! What the `serde` feature puts on the wire. The crate docs state the shapes
//! under Features.
//!
//! JSON, TOML, YAML and their kin work. Formats that carry no type tags —
//! bincode, postcard — do not: an amount is read through `deserialize_any`,
//! and [`Money`] and [`ExchangeRate`] are read as maps with no sequence form to
//! fall back on.
//!
//! ## Example
//!
//! ```
//! # use std::error::Error;
//! #
//! # fn main() -> Result<(), Box<dyn Error>> {
//! use lucre::{Currency, Money, MoneyBag};
//!
//! let total = Money::from_minor(10475, &Currency::USD);
//! let document = serde_json::to_string(&total)?;
//!
//! assert_eq!(document, r#"{"amount":"104.75","currency":"USD"}"#);
//! assert_eq!(serde_json::from_str::<Money>(&document)?, total);
//!
//! let wallet: MoneyBag = serde_json::from_str(r#"{"EUR": "10.00", "USD": "30.00"}"#)?;
//!
//! assert_eq!(wallet.to_string(), "10.00 EUR, 30.00 USD");
//! #
//! #     Ok(())
//! # }
//! ```

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

use serde::{
    Deserialize, Deserializer, Serialize, Serializer,
    de::{self, MapAccess, Unexpected, Visitor},
    ser::{SerializeMap, SerializeStruct},
};

use crate::{
    Currency, Decimal, Exchange, ExchangeRate, IsoAlphabeticCode, IsoNumericCode, Money, MoneyBag,
    RoundingMode,
};

const AMOUNT_FIELD: &str = "amount";
const CURRENCY_FIELD: &str = "currency";
const MONEY_FIELDS: &[&str] = &[AMOUNT_FIELD, CURRENCY_FIELD];

const FROM_FIELD: &str = "from";
const TO_FIELD: &str = "to";
const RATE_FIELD: &str = "rate";
const EXCHANGE_RATE_FIELDS: &[&str] = &[FROM_FIELD, TO_FIELD, RATE_FIELD];

const PAIR_SEPARATOR: char = '/';

/// A figure on its way to or from a document — an amount or a rate — text
/// going out, text or a number coming in.
///
/// [`Decimal`] has serde impls of its own, but they answer to rust_decimal's
/// `serde-float` and `serde-str` features, which any crate sharing the build
/// can turn on. Encoding the figure here keeps lucre's shapes lucre's to
/// change.
struct Figure(Decimal);

impl Serialize for Figure {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for Figure {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(FigureVisitor)
    }
}

struct FigureVisitor;

impl Visitor<'_> for FigureVisitor {
    type Value = Figure;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a decimal figure, written as text or as a number")
    }

    fn visit_str<E: de::Error>(self, figure: &str) -> Result<Self::Value, E> {
        Decimal::from_str(figure)
            .or_else(|_| Decimal::from_scientific(figure))
            .map(Figure)
            .map_err(|_| E::invalid_value(Unexpected::Str(figure), &self))
    }

    fn visit_u64<E: de::Error>(self, figure: u64) -> Result<Self::Value, E> {
        Ok(Figure(Decimal::from(figure)))
    }

    fn visit_i64<E: de::Error>(self, figure: i64) -> Result<Self::Value, E> {
        Ok(Figure(Decimal::from(figure)))
    }

    /// Reads the digits a float prints rather than the binary fraction behind
    /// them, so `104.75` arrives as two decimal places and not as the nearest
    /// `f64` spelled out to the last bit.
    fn visit_f64<E: de::Error>(self, figure: f64) -> Result<Self::Value, E> {
        Decimal::from_str(&figure.to_string())
            .map(Figure)
            .map_err(|_| E::invalid_value(Unexpected::Float(figure), &self))
    }
}

/// Writes the amount and the currency it is denominated in as a pair of named
/// fields.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money};
///
/// let total = Money::from_minor(10475, &Currency::USD);
///
/// assert_eq!(
///     serde_json::to_string(&total)?,
///     r#"{"amount":"104.75","currency":"USD"}"#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for Money {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut money = serializer.serialize_struct("Money", MONEY_FIELDS.len())?;

        money.serialize_field(AMOUNT_FIELD, &Figure(self.amount()))?;
        money.serialize_field(CURRENCY_FIELD, &self.currency())?;
        money.end()
    }
}

/// Reads both fields, in either order. Neither may be left out, and fields
/// beyond the two are skipped, so a document may carry more than an amount
/// without being rewritten first.
///
/// The amount is taken verbatim, as by [`Money::from_decimal`]: nothing is
/// rounded or scaled to the currency's minor digits.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money};
///
/// let line = r#"{"description": "coffee", "amount": 4.75, "currency": "USD"}"#;
///
/// assert_eq!(
///     serde_json::from_str::<Money>(line)?,
///     Money::from_minor(475, &Currency::USD)
/// );
/// assert!(serde_json::from_str::<Money>(r#"{"amount": "4.75"}"#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for Money {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_struct("Money", MONEY_FIELDS, MoneyVisitor)
    }
}

struct MoneyVisitor;

impl<'de> Visitor<'de> for MoneyVisitor {
    type Value = Money;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("an amount and the currency it is denominated in")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
        let mut amount: Option<Figure> = None;
        let mut currency: Option<Currency> = None;

        while let Some(field) = map.next_key()? {
            match field {
                MoneyField::Amount if amount.is_some() => {
                    return Err(de::Error::duplicate_field(AMOUNT_FIELD));
                }
                MoneyField::Currency if currency.is_some() => {
                    return Err(de::Error::duplicate_field(CURRENCY_FIELD));
                }
                MoneyField::Amount => amount = Some(map.next_value()?),
                MoneyField::Currency => currency = Some(map.next_value()?),
                MoneyField::Other => {
                    map.next_value::<de::IgnoredAny>()?;
                }
            }
        }

        let Figure(amount) = amount.ok_or_else(|| de::Error::missing_field(AMOUNT_FIELD))?;
        let currency = currency.ok_or_else(|| de::Error::missing_field(CURRENCY_FIELD))?;

        Ok(Money::from_decimal(amount, &currency))
    }
}

/// A field of the serialized form, with everything unrecognized gathered into
/// one arm rather than refused.
enum MoneyField {
    Amount,
    Currency,
    Other,
}

impl<'de> Deserialize<'de> for MoneyField {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_identifier(MoneyFieldVisitor)
    }
}

struct MoneyFieldVisitor;

impl Visitor<'_> for MoneyFieldVisitor {
    type Value = MoneyField;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a field name")
    }

    fn visit_str<E: de::Error>(self, name: &str) -> Result<Self::Value, E> {
        Ok(match name {
            AMOUNT_FIELD => MoneyField::Amount,
            CURRENCY_FIELD => MoneyField::Currency,
            _ => MoneyField::Other,
        })
    }
}

/// Writes one entry per currency held, keyed by ISO alphabetic code and
/// ordered by it. A bag holding nothing writes an empty map.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money, MoneyBag};
///
/// let mut wallet = MoneyBag::new();
/// wallet += Money::from_major(30, &Currency::USD);
/// wallet += Money::from_major(10, &Currency::EUR);
///
/// assert_eq!(
///     serde_json::to_string(&wallet)?,
///     r#"{"EUR":"10.00","USD":"30.00"}"#
/// );
/// assert_eq!(serde_json::to_string(&MoneyBag::new())?, "{}");
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for MoneyBag {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut balances = serializer.serialize_map(Some(self.len()))?;

        for money in self {
            balances.serialize_entry(&money.currency(), &Figure(money.amount()))?;
        }

        balances.end()
    }
}

/// Reads entries the way a bag accumulates them rather than insisting the
/// document already be in the shape a bag would have written: a balance of
/// zero leaves no currency behind, and a currency named twice is totaled.
/// Whichever way such a document is read, the position it describes is the
/// same.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money, MoneyBag};
///
/// let ledger = r#"{"USD": "10.00", "EUR": "0.00"}"#;
/// let wallet: MoneyBag = serde_json::from_str(ledger)?;
///
/// assert_eq!(wallet, MoneyBag::from(Money::from_major(10, &Currency::USD)));
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for MoneyBag {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_map(MoneyBagVisitor)
    }
}

struct MoneyBagVisitor;

impl<'de> Visitor<'de> for MoneyBagVisitor {
    type Value = MoneyBag;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a balance per currency, keyed by ISO 4217 alphabetic code")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
        let mut bag = MoneyBag::new();

        while let Some((currency, Figure(amount))) = map.next_entry::<Currency, Figure>()? {
            bag = bag
                .checked_add(Money::from_decimal(amount, &currency))
                .map_err(|_| {
                    de::Error::custom(format!(
                        "the {currency} balance totals past what a decimal can hold"
                    ))
                })?;
        }

        Ok(bag)
    }
}

/// Writes the pair a quote spans and the multiplier between them as three
/// named fields.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, ExchangeRate};
/// use rust_decimal::dec;
///
/// let quote = ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?;
///
/// assert_eq!(
///     serde_json::to_string(&quote)?,
///     r#"{"from":"USD","to":"EUR","rate":"0.9"}"#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for ExchangeRate {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut quote = serializer.serialize_struct("ExchangeRate", EXCHANGE_RATE_FIELDS.len())?;

        quote.serialize_field(FROM_FIELD, &self.from())?;
        quote.serialize_field(TO_FIELD, &self.to())?;
        quote.serialize_field(RATE_FIELD, &Figure(self.rate()))?;
        quote.end()
    }
}

/// Reads all three fields, in any order, and holds the multiplier to what
/// [`ExchangeRate::new`] asks of it: a rate of zero or less is refused. None of
/// the three may be left out, and fields beyond them — the time of the quote,
/// the desk that gave it — are skipped.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, ExchangeRate};
/// use rust_decimal::dec;
///
/// let quoted = r#"{"as_of": "2026-08-14", "from": "USD", "to": "EUR", "rate": 0.9}"#;
///
/// assert_eq!(
///     serde_json::from_str::<ExchangeRate>(quoted)?,
///     ExchangeRate::new(Currency::USD, Currency::EUR, dec!(0.9))?
/// );
/// assert!(
///     serde_json::from_str::<ExchangeRate>(r#"{"from": "USD", "to": "EUR", "rate": 0}"#)
///         .is_err()
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for ExchangeRate {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_struct("ExchangeRate", EXCHANGE_RATE_FIELDS, ExchangeRateVisitor)
    }
}

struct ExchangeRateVisitor;

impl<'de> Visitor<'de> for ExchangeRateVisitor {
    type Value = ExchangeRate;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a pair of currencies and the rate between them")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
        let mut from: Option<Currency> = None;
        let mut to: Option<Currency> = None;
        let mut rate: Option<Figure> = None;

        while let Some(field) = map.next_key()? {
            match field {
                ExchangeRateField::From if from.is_some() => {
                    return Err(de::Error::duplicate_field(FROM_FIELD));
                }
                ExchangeRateField::To if to.is_some() => {
                    return Err(de::Error::duplicate_field(TO_FIELD));
                }
                ExchangeRateField::Rate if rate.is_some() => {
                    return Err(de::Error::duplicate_field(RATE_FIELD));
                }
                ExchangeRateField::From => from = Some(map.next_value()?),
                ExchangeRateField::To => to = Some(map.next_value()?),
                ExchangeRateField::Rate => rate = Some(map.next_value()?),
                ExchangeRateField::Other => {
                    map.next_value::<de::IgnoredAny>()?;
                }
            }
        }

        let from = from.ok_or_else(|| de::Error::missing_field(FROM_FIELD))?;
        let to = to.ok_or_else(|| de::Error::missing_field(TO_FIELD))?;
        let Figure(rate) = rate.ok_or_else(|| de::Error::missing_field(RATE_FIELD))?;

        ExchangeRate::new(from, to, rate).map_err(de::Error::custom)
    }
}

/// A field of the serialized form, with everything unrecognized gathered into
/// one arm rather than refused.
enum ExchangeRateField {
    From,
    To,
    Rate,
    Other,
}

impl<'de> Deserialize<'de> for ExchangeRateField {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_identifier(ExchangeRateFieldVisitor)
    }
}

struct ExchangeRateFieldVisitor;

impl Visitor<'_> for ExchangeRateFieldVisitor {
    type Value = ExchangeRateField;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a field name")
    }

    fn visit_str<E: de::Error>(self, name: &str) -> Result<Self::Value, E> {
        Ok(match name {
            FROM_FIELD => ExchangeRateField::From,
            TO_FIELD => ExchangeRateField::To,
            RATE_FIELD => ExchangeRateField::Rate,
            _ => ExchangeRateField::Other,
        })
    }
}

/// The two currencies of a quote written as one key, the way a rate board
/// names a pair: the currency priced, a slash, the currency it is priced in.
struct Pair(Currency, Currency);

impl Serialize for Pair {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let Self(from, to) = self;

        serializer.collect_str(&format_args!("{from}{PAIR_SEPARATOR}{to}"))
    }
}

impl<'de> Deserialize<'de> for Pair {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(PairVisitor)
    }
}

struct PairVisitor;

impl Visitor<'_> for PairVisitor {
    type Value = Pair;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "two currencies ISO 4217 assigns, separated by {PAIR_SEPARATOR:?}"
        )
    }

    fn visit_str<E: de::Error>(self, pair: &str) -> Result<Self::Value, E> {
        pair.split_once(PAIR_SEPARATOR)
            .and_then(|(from, to)| {
                Some(Pair(
                    Currency::from_alphabetic_code(from)?,
                    Currency::from_alphabetic_code(to)?,
                ))
            })
            .ok_or_else(|| E::invalid_value(Unexpected::Str(pair), &self))
    }
}

/// Writes one entry per pair quoted, keyed the way a rate board names a pair
/// and ordered by the currency priced, then by the currency it is priced in. A
/// table quoting nothing writes an empty map.
///
/// ## 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::JPY, dec!(144))?);
///
/// assert_eq!(
///     serde_json::to_string(&desk)?,
///     r#"{"USD/EUR":"0.9","USD/JPY":"144"}"#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for Exchange {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut table = serializer.serialize_map(Some(self.quotes().len()))?;

        for quote in self.quotes() {
            table.serialize_entry(&Pair(quote.from(), quote.to()), &Figure(quote.rate()))?;
        }

        table.end()
    }
}

/// Takes each quote in as [`Exchange::set_rate`] would, so a pair the document
/// names twice keeps the rate given last. A rate of zero or less is refused,
/// as it is of any [`ExchangeRate`].
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Exchange, Money};
///
/// let feed = r#"{"USD/EUR": "0.9", "EUR/USD": "1.1"}"#;
/// let desk: Exchange = serde_json::from_str(feed)?;
/// let quote = desk
///     .rate(&Currency::USD, &Currency::EUR)
///     .ok_or("the feed quotes USD against EUR")?;
///
/// assert_eq!(
///     quote.convert(&Money::from_major(100, &Currency::USD))?,
///     Money::from_major(90, &Currency::EUR)
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for Exchange {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_map(ExchangeVisitor)
    }
}

struct ExchangeVisitor;

impl<'de> Visitor<'de> for ExchangeVisitor {
    type Value = Exchange;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a rate per currency pair, keyed by the pair the rate spans")
    }

    fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Self::Value, M::Error> {
        let mut desk = Exchange::new();

        while let Some((Pair(from, to), Figure(rate))) = map.next_entry::<Pair, Figure>()? {
            let quote = ExchangeRate::new(from, to, rate).map_err(de::Error::custom)?;

            desk.set_rate(&quote);
        }

        Ok(desk)
    }
}

/// Writes the three-letter code, the same text [`Display`](std::fmt::Display)
/// writes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(serde_json::to_string(&Currency::JPY)?, r#""JPY""#);
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for Currency {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.alphabetic_code().as_str())
    }
}

/// Looks the code up in the ISO 4217 catalog, as
/// [`Currency::from_alphabetic_code`] does, so a code the standard leaves
/// unassigned is refused. Capitals only.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(serde_json::from_str::<Currency>(r#""JPY""#)?, Currency::JPY);
/// assert!(serde_json::from_str::<Currency>(r#""ZZZ""#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for Currency {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(CurrencyVisitor)
    }
}

struct CurrencyVisitor;

impl Visitor<'_> for CurrencyVisitor {
    type Value = Currency;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("the alphabetic code of a currency ISO 4217 assigns")
    }

    fn visit_str<E: de::Error>(self, code: &str) -> Result<Self::Value, E> {
        Currency::from_alphabetic_code(code)
            .ok_or_else(|| E::invalid_value(Unexpected::Str(code), &self))
    }
}

/// Writes the three letters, the same text [`Display`](std::fmt::Display)
/// writes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(
///     serde_json::to_string(&Currency::JPY.alphabetic_code())?,
///     r#""JPY""#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for IsoAlphabeticCode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// Takes any three capitals, as
/// [`TryFrom<&str>`](IsoAlphabeticCode::try_from) does, so a code ISO 4217
/// has yet to spend on a currency still reads.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::IsoAlphabeticCode;
///
/// let unassigned: IsoAlphabeticCode = serde_json::from_str(r#""ZZZ""#)?;
///
/// assert_eq!(unassigned.as_str(), "ZZZ");
/// assert!(serde_json::from_str::<IsoAlphabeticCode>(r#""usd""#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for IsoAlphabeticCode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(IsoAlphabeticCodeVisitor)
    }
}

struct IsoAlphabeticCodeVisitor;

impl Visitor<'_> for IsoAlphabeticCodeVisitor {
    type Value = IsoAlphabeticCode;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("three capital letters, as ISO 4217 spells its codes")
    }

    fn visit_str<E: de::Error>(self, code: &str) -> Result<Self::Value, E> {
        IsoAlphabeticCode::try_from(code)
            .map_err(|_| E::invalid_value(Unexpected::Str(code), &self))
    }
}

/// Writes a plain integer, leaving the leading zeroes
/// [`Display`](std::fmt::Display) pads with to text.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::Currency;
///
/// assert_eq!(serde_json::to_string(&Currency::ALL.numeric_code())?, "8");
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for IsoNumericCode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u32(self.value())
    }
}

/// Takes any integer of at most three digits, as
/// [`TryFrom<u32>`](IsoNumericCode::try_from) does, assigned or not.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, IsoNumericCode};
///
/// assert_eq!(
///     serde_json::from_str::<IsoNumericCode>("840")?,
///     Currency::USD.numeric_code()
/// );
/// assert!(serde_json::from_str::<IsoNumericCode>("1000").is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for IsoNumericCode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_u32(IsoNumericCodeVisitor)
    }
}

struct IsoNumericCodeVisitor;

impl Visitor<'_> for IsoNumericCodeVisitor {
    type Value = IsoNumericCode;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("an integer of at most three digits, as ISO 4217 numbers currencies")
    }

    fn visit_u64<E: de::Error>(self, code: u64) -> Result<Self::Value, E> {
        u32::try_from(code)
            .ok()
            .and_then(|code| IsoNumericCode::try_from(code).ok())
            .ok_or_else(|| E::invalid_value(Unexpected::Unsigned(code), &self))
    }

    fn visit_i64<E: de::Error>(self, code: i64) -> Result<Self::Value, E> {
        match u64::try_from(code) {
            Ok(code) => self.visit_u64(code),
            Err(_) => Err(E::invalid_value(Unexpected::Signed(code), &self)),
        }
    }
}

/// Names each strategy in lower case, hyphenated: `"half-up"`,
/// `"half-down"`, `"half-even"`.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::RoundingMode;
///
/// assert_eq!(
///     serde_json::to_string(&RoundingMode::HalfEven)?,
///     r#""half-even""#
/// );
/// #
/// #     Ok(())
/// # }
/// ```
impl Serialize for RoundingMode {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(match self {
            RoundingMode::HalfUp => "half-up",
            RoundingMode::HalfDown => "half-down",
            RoundingMode::HalfEven => "half-even",
        })
    }
}

/// Reads those three names, and nothing else — the Rust spelling of a variant
/// is not a name this recognizes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::RoundingMode;
///
/// assert_eq!(
///     serde_json::from_str::<RoundingMode>(r#""half-up""#)?,
///     RoundingMode::HalfUp
/// );
/// assert!(serde_json::from_str::<RoundingMode>(r#""HalfUp""#).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl<'de> Deserialize<'de> for RoundingMode {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_str(RoundingModeVisitor)
    }
}

struct RoundingModeVisitor;

impl Visitor<'_> for RoundingModeVisitor {
    type Value = RoundingMode;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(r#""half-up", "half-down", or "half-even""#)
    }

    fn visit_str<E: de::Error>(self, name: &str) -> Result<Self::Value, E> {
        match name {
            "half-up" => Ok(RoundingMode::HalfUp),
            "half-down" => Ok(RoundingMode::HalfDown),
            "half-even" => Ok(RoundingMode::HalfEven),
            _ => Err(E::invalid_value(Unexpected::Str(name), &self)),
        }
    }
}

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

    #[test]
    fn money_round_trips_test() {
        let total = Money::from_minor(10475, &Currency::USD);
        let document = serde_json::to_string(&total).unwrap();

        assert_eq!(document, r#"{"amount":"104.75","currency":"USD"}"#);
        assert_eq!(serde_json::from_str::<Money>(&document).unwrap(), total);
    }

    #[test]
    fn money_keeps_a_scale_finer_than_the_currency_test() {
        let share = Money::from_decimal(dec!(1.005), &Currency::USD);
        let document = serde_json::to_string(&share).unwrap();

        assert_eq!(document, r#"{"amount":"1.005","currency":"USD"}"#);
        assert_eq!(
            serde_json::from_str::<Money>(&document)
                .unwrap()
                .amount()
                .scale(),
            3
        );
    }

    #[test]
    fn money_reads_numeric_amounts_test() {
        let whole: Money = serde_json::from_str(r#"{"amount": 104, "currency": "USD"}"#).unwrap();
        let fraction: Money =
            serde_json::from_str(r#"{"amount": 104.75, "currency": "USD"}"#).unwrap();

        assert_eq!(whole, Money::from_major(104, &Currency::USD));
        assert_eq!(fraction, Money::from_minor(10475, &Currency::USD));
    }

    #[test]
    fn money_reads_an_amount_in_scientific_notation_test() {
        let thousand: Money =
            serde_json::from_str(r#"{"amount": "1e3", "currency": "USD"}"#).unwrap();

        assert_eq!(thousand.amount(), dec!(1000));
    }

    #[test]
    fn money_reads_its_fields_in_either_order_test() {
        let reversed: Money =
            serde_json::from_str(r#"{"currency": "EUR", "amount": "12.00"}"#).unwrap();

        assert_eq!(reversed, Money::from_major(12, &Currency::EUR));
    }

    #[test]
    fn money_skips_unknown_fields_test() {
        let annotated: Money = serde_json::from_str(
            r#"{"amount": "1.00", "note": {"paid": true}, "currency": "USD"}"#,
        )
        .unwrap();

        assert_eq!(annotated, Money::from_major(1, &Currency::USD));
    }

    #[test]
    fn money_needs_both_fields_test() {
        let no_currency = serde_json::from_str::<Money>(r#"{"amount": "1.00"}"#).unwrap_err();
        let no_amount = serde_json::from_str::<Money>(r#"{"currency": "USD"}"#).unwrap_err();

        assert!(no_currency.to_string().contains("missing field `currency`"));
        assert!(no_amount.to_string().contains("missing field `amount`"));
    }

    #[test]
    fn money_refuses_a_repeated_field_test() {
        let repeated = serde_json::from_str::<Money>(
            r#"{"amount": "1.00", "amount": "2.00", "currency": "USD"}"#,
        )
        .unwrap_err();

        assert!(repeated.to_string().contains("duplicate field `amount`"));
    }

    #[test]
    fn every_currency_round_trips_test() {
        for currency in Currency::all() {
            let document = serde_json::to_string(currency).unwrap();

            assert_eq!(document, format!("\"{currency}\""));
            assert_eq!(
                &serde_json::from_str::<Currency>(&document).unwrap(),
                currency
            );
        }
    }

    #[test]
    fn unassigned_currency_code_is_refused_test() {
        let error = serde_json::from_str::<Currency>(r#""ZZZ""#).unwrap_err();

        assert!(
            error
                .to_string()
                .contains(r#"invalid value: string "ZZZ", expected the alphabetic code"#)
        );
    }

    #[test]
    fn alphabetic_code_admits_unassigned_codes_test() {
        let unassigned: IsoAlphabeticCode = serde_json::from_str(r#""ZZZ""#).unwrap();

        assert_eq!(unassigned.as_str(), "ZZZ");
        assert_eq!(serde_json::to_string(&unassigned).unwrap(), r#""ZZZ""#);
        assert!(serde_json::from_str::<IsoAlphabeticCode>(r#""usd""#).is_err());
        assert!(serde_json::from_str::<IsoAlphabeticCode>(r#""USDD""#).is_err());
    }

    #[test]
    fn numeric_code_round_trips_test() {
        for currency in Currency::all() {
            let code = currency.numeric_code();
            let document = serde_json::to_string(&code).unwrap();

            assert_eq!(document, code.value().to_string());
            assert_eq!(
                serde_json::from_str::<IsoNumericCode>(&document).unwrap(),
                code
            );
        }
    }

    #[test]
    fn numeric_code_outside_three_digits_is_refused_test() {
        let too_many = serde_json::from_str::<IsoNumericCode>("1000").unwrap_err();
        let negative = serde_json::from_str::<IsoNumericCode>("-1").unwrap_err();

        assert!(
            too_many
                .to_string()
                .contains("invalid value: integer `1000`")
        );
        assert!(negative.to_string().contains("invalid value: integer `-1`"));
    }

    #[test]
    fn rounding_mode_round_trips_test() {
        let modes = [
            (RoundingMode::HalfUp, r#""half-up""#),
            (RoundingMode::HalfDown, r#""half-down""#),
            (RoundingMode::HalfEven, r#""half-even""#),
        ];

        for (mode, document) in modes {
            assert_eq!(serde_json::to_string(&mode).unwrap(), document);
            assert_eq!(
                serde_json::from_str::<RoundingMode>(document).unwrap(),
                mode
            );
        }

        assert!(serde_json::from_str::<RoundingMode>(r#""HalfUp""#).is_err());
    }

    #[test]
    fn bag_round_trips_test() {
        let wallet: MoneyBag = [
            Money::from_major(30, &Currency::USD),
            Money::from_major(10, &Currency::EUR),
        ]
        .into_iter()
        .collect();
        let document = serde_json::to_string(&wallet).unwrap();

        assert_eq!(document, r#"{"EUR":"10.00","USD":"30.00"}"#);
        assert_eq!(serde_json::from_str::<MoneyBag>(&document).unwrap(), wallet);
    }

    #[test]
    fn empty_bag_round_trips_test() {
        let document = serde_json::to_string(&MoneyBag::new()).unwrap();

        assert_eq!(document, "{}");
        assert!(
            serde_json::from_str::<MoneyBag>(&document)
                .unwrap()
                .is_empty()
        );
    }

    #[test]
    fn bag_drops_a_zero_balance_test() {
        let wallet: MoneyBag = serde_json::from_str(r#"{"EUR": "0.00", "USD": "10.00"}"#).unwrap();

        assert_eq!(wallet.len(), 1);
        assert_eq!(
            wallet,
            MoneyBag::from(Money::from_major(10, &Currency::USD))
        );
    }

    #[test]
    fn bag_sums_a_repeated_currency_test() {
        let wallet: MoneyBag = serde_json::from_str(r#"{"USD": "10.00", "USD": "5.00"}"#).unwrap();

        assert_eq!(
            wallet.balance(&Currency::USD),
            Money::from_major(15, &Currency::USD)
        );
    }

    #[test]
    fn bag_reports_a_balance_it_cannot_hold_test() {
        let document = format!(r#"{{"USD": "{}", "USD": "1"}}"#, Decimal::MAX);
        let error = serde_json::from_str::<MoneyBag>(&document).unwrap_err();

        assert!(
            error
                .to_string()
                .contains("the USD balance totals past what a decimal can hold")
        );
    }

    #[test]
    fn bag_refuses_an_unassigned_currency_test() {
        assert!(serde_json::from_str::<MoneyBag>(r#"{"ZZZ": "1.00"}"#).is_err());
    }

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

    #[test]
    fn rate_round_trips_test() {
        let document = serde_json::to_string(&usd_eur()).unwrap();

        assert_eq!(document, r#"{"from":"USD","to":"EUR","rate":"0.9"}"#);
        assert_eq!(
            serde_json::from_str::<ExchangeRate>(&document).unwrap(),
            usd_eur()
        );
    }

    #[test]
    fn rate_reads_a_numeric_multiplier_test() {
        let quoted: ExchangeRate =
            serde_json::from_str(r#"{"from": "USD", "to": "EUR", "rate": 0.9}"#).unwrap();

        assert_eq!(quoted, usd_eur());
    }

    #[test]
    fn rate_reads_its_fields_in_any_order_test() {
        let shuffled: ExchangeRate =
            serde_json::from_str(r#"{"rate": "0.9", "to": "EUR", "from": "USD"}"#).unwrap();

        assert_eq!(shuffled, usd_eur());
    }

    #[test]
    fn rate_skips_unknown_fields_test() {
        let annotated: ExchangeRate = serde_json::from_str(
            r#"{"as_of": "2026-08-14", "from": "USD", "to": "EUR", "rate": "0.9"}"#,
        )
        .unwrap();

        assert_eq!(annotated, usd_eur());
    }

    #[test]
    fn rate_needs_all_three_fields_test() {
        let no_rate =
            serde_json::from_str::<ExchangeRate>(r#"{"from": "USD", "to": "EUR"}"#).unwrap_err();
        let no_from =
            serde_json::from_str::<ExchangeRate>(r#"{"to": "EUR", "rate": "0.9"}"#).unwrap_err();
        let no_to =
            serde_json::from_str::<ExchangeRate>(r#"{"from": "USD", "rate": "0.9"}"#).unwrap_err();

        assert!(no_rate.to_string().contains("missing field `rate`"));
        assert!(no_from.to_string().contains("missing field `from`"));
        assert!(no_to.to_string().contains("missing field `to`"));
    }

    #[test]
    fn rate_refuses_a_repeated_field_test() {
        let repeated = serde_json::from_str::<ExchangeRate>(
            r#"{"from": "USD", "to": "EUR", "rate": "0.9", "rate": "0.92"}"#,
        )
        .unwrap_err();

        assert!(repeated.to_string().contains("duplicate field `rate`"));
    }

    #[test]
    fn rate_refuses_a_multiplier_no_exchange_takes_place_at_test() {
        let zero =
            serde_json::from_str::<ExchangeRate>(r#"{"from": "USD", "to": "EUR", "rate": "0"}"#)
                .unwrap_err();
        let negative =
            serde_json::from_str::<ExchangeRate>(r#"{"from": "USD", "to": "EUR", "rate": "-0.9"}"#)
                .unwrap_err();

        assert!(zero.to_string().contains(&InvalidRateError.to_string()));
        assert!(negative.to_string().contains(&InvalidRateError.to_string()));
    }

    #[test]
    fn identity_round_trips_test() {
        let par = ExchangeRate::identity(Currency::USD);
        let document = serde_json::to_string(&par).unwrap();

        assert_eq!(document, r#"{"from":"USD","to":"USD","rate":"1"}"#);
        assert_eq!(
            serde_json::from_str::<ExchangeRate>(&document).unwrap(),
            par
        );
    }

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

        let document = serde_json::to_string(&desk).unwrap();

        assert_eq!(
            document,
            r#"{"EUR/USD":"1.1","USD/EUR":"0.9","USD/JPY":"144"}"#
        );
        assert_eq!(serde_json::from_str::<Exchange>(&document).unwrap(), desk);
    }

    #[test]
    fn empty_exchange_round_trips_test() {
        let document = serde_json::to_string(&Exchange::new()).unwrap();

        assert_eq!(document, "{}");
        assert_eq!(
            serde_json::from_str::<Exchange>(&document).unwrap(),
            Exchange::new()
        );
    }

    #[test]
    fn exchange_keeps_the_last_quote_of_a_repeated_pair_test() {
        let desk: Exchange =
            serde_json::from_str(r#"{"USD/EUR": "0.9", "USD/EUR": "0.92"}"#).unwrap();
        let quote = desk.rate(&Currency::USD, &Currency::EUR).unwrap();

        assert_eq!(quote.rate(), dec!(0.92));
    }

    #[test]
    fn exchange_omits_the_par_it_answers_from_the_rule_test() {
        let desk: Exchange = serde_json::from_str(r#"{"USD/EUR": "0.9"}"#).unwrap();

        assert!(desk.rate(&Currency::USD, &Currency::USD).is_some());
        assert_eq!(
            serde_json::to_string(&desk).unwrap(),
            r#"{"USD/EUR":"0.9"}"#
        );
    }

    #[test]
    fn exchange_refuses_a_key_that_is_not_a_pair_test() {
        assert!(serde_json::from_str::<Exchange>(r#"{"USD": "0.9"}"#).is_err());
        assert!(serde_json::from_str::<Exchange>(r#"{"USD/ZZZ": "0.9"}"#).is_err());
        assert!(serde_json::from_str::<Exchange>(r#"{"usd/eur": "0.9"}"#).is_err());
    }

    #[test]
    fn exchange_refuses_a_multiplier_no_exchange_takes_place_at_test() {
        let error = serde_json::from_str::<Exchange>(r#"{"USD/EUR": "0"}"#).unwrap_err();

        assert!(error.to_string().contains(&InvalidRateError.to_string()));
    }
}