lucre 0.11.0

An ergonomic library for handling money.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
//! ISO 4217 currencies, and the codes that name them.

use std::{
    cmp::Ordering,
    fmt::{Debug, Display},
    str::FromStr,
};

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

/// The ISO 4217 numeric code for a currency.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct IsoNumericCode(u32);

impl IsoNumericCode {
    /// The code as a plain number.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.numeric_code().value(), 840);
    /// assert_eq!(Currency::ALL.numeric_code().value(), 8);
    /// ```
    #[must_use]
    pub fn value(self) -> u32 {
        self.0
    }
}

/// Writes the code as the three digits ISO 4217 uses, adding leading zeroes
/// to smaller numbers.
///
/// ## Example
///
/// ```
/// use lucre::Currency;
///
/// assert_eq!(Currency::USD.numeric_code().to_string(), "840");
/// assert_eq!(Currency::ALL.numeric_code().to_string(), "008");
/// ```
impl Display for IsoNumericCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:03}", self.0)
    }
}

impl From<IsoNumericCode> for u32 {
    fn from(code: IsoNumericCode) -> Self {
        code.0
    }
}

/// Accepts any number of three digits or fewer, whether or not ISO 4217 has
/// given it to a currency.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, IsoNumericCode};
///
/// assert_eq!(IsoNumericCode::try_from(840)?, Currency::USD.numeric_code());
///
/// // Four digits is one more than a code has.
/// assert!(IsoNumericCode::try_from(1000).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl TryFrom<u32> for IsoNumericCode {
    type Error = IsoNumericCodeError;

    /// ## Errors
    ///
    /// Returns [`IsoNumericCodeError::InvalidCode`], carrying the number, if
    /// it is above `999`.
    fn try_from(code: u32) -> Result<Self, Self::Error> {
        if code > 999 {
            return Err(IsoNumericCodeError::InvalidCode { code });
        }

        Ok(Self(code))
    }
}

/// The ISO 4217 alphabetic code for a currency.
///
/// Codes sort alphabetically.
#[derive(Clone, Copy, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct IsoAlphabeticCode([u8; 3]);

impl IsoAlphabeticCode {
    /// The code as a string slice.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.alphabetic_code().as_str(), "USD");
    /// ```
    #[must_use]
    #[expect(
        clippy::missing_panics_doc,
        reason = "the stored bytes are always valid UTF-8"
    )]
    pub fn as_str(&self) -> &str {
        std::str::from_utf8(&self.0).expect("only ASCII letters are ever stored")
    }
}

/// Accepts three capital letters, the way ISO 4217 writes a code, and nothing
/// else.
///
/// ## Example
///
/// ```
/// use lucre::IsoAlphabeticCode;
///
/// assert!(IsoAlphabeticCode::try_from(*b"USD").is_ok());
/// assert!(IsoAlphabeticCode::try_from(*b"usd").is_err());
/// assert!(IsoAlphabeticCode::try_from(*b"840").is_err());
/// ```
impl TryFrom<[u8; 3]> for IsoAlphabeticCode {
    type Error = IsoAlphabeticCodeError;

    /// ## Errors
    ///
    /// Returns [`IsoAlphabeticCodeError::InvalidCode`], carrying the bytes,
    /// unless all three are capital ASCII letters.
    fn try_from(code: [u8; 3]) -> Result<Self, Self::Error> {
        if !code.iter().all(u8::is_ascii_uppercase) {
            return Err(IsoAlphabeticCodeError::invalid(&code));
        }

        Ok(Self(code))
    }
}

/// Accepts a string of exactly three capital letters.
///
/// ## Example
///
/// ```
/// use lucre::{IsoAlphabeticCode, IsoAlphabeticCodeError};
///
/// assert!(IsoAlphabeticCode::try_from("USD").is_ok());
///
/// let error = IsoAlphabeticCode::try_from("US").unwrap_err();
///
/// assert!(matches!(error, IsoAlphabeticCodeError::InvalidCode { code, .. } if code == "US"));
/// ```
impl TryFrom<&str> for IsoAlphabeticCode {
    type Error = IsoAlphabeticCodeError;

    /// ## Errors
    ///
    /// Returns [`IsoAlphabeticCodeError::InvalidCode`], carrying the text,
    /// unless it is three capital ASCII letters.
    fn try_from(code: &str) -> Result<Self, Self::Error> {
        let bytes: [u8; 3] = code
            .as_bytes()
            .try_into()
            .map_err(|_| IsoAlphabeticCodeError::invalid(code.as_bytes()))?;

        Self::try_from(bytes)
    }
}

/// Reads the same text [`TryFrom<&str>`](IsoAlphabeticCode::try_from) takes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, IsoAlphabeticCode};
///
/// let code: IsoAlphabeticCode = "USD".parse()?;
///
/// assert_eq!(code, Currency::USD.alphabetic_code());
/// #
/// #     Ok(())
/// # }
/// ```
impl FromStr for IsoAlphabeticCode {
    type Err = IsoAlphabeticCodeError;

    fn from_str(code: &str) -> Result<Self, Self::Err> {
        Self::try_from(code)
    }
}

impl AsRef<str> for IsoAlphabeticCode {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl From<IsoAlphabeticCode> for [u8; 3] {
    fn from(code: IsoAlphabeticCode) -> Self {
        code.0
    }
}

impl Display for IsoAlphabeticCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

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

/// An ISO 4217 currency.
///
/// Currencies sort by their alphabetic code.
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct Currency {
    alphabetic_code: IsoAlphabeticCode,
    numeric_code: IsoNumericCode,
    minor_digits: u32,
    symbol: &'static str,
}

impl Currency {
    /// The three-letter code for this currency.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.alphabetic_code().as_str(), "USD");
    /// ```
    #[must_use]
    pub fn alphabetic_code(self) -> IsoAlphabeticCode {
        self.alphabetic_code
    }

    /// The numeric code for this currency.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.numeric_code().value(), 840);
    /// ```
    #[must_use]
    pub fn numeric_code(self) -> IsoNumericCode {
        self.numeric_code
    }

    /// How many decimal places the currency uses.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.minor_digits(), 2);
    /// assert_eq!(Currency::BHD.minor_digits(), 3);
    ///
    /// // Some currencies have no smaller unit at all.
    /// assert_eq!(Currency::JPY.minor_digits(), 0);
    /// ```
    #[must_use]
    pub fn minor_digits(self) -> u32 {
        self.minor_digits
    }

    /// The sign usually written next to amounts.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.symbol(), "$");
    /// assert_eq!(Currency::GBP.symbol(), "£");
    /// ```
    #[must_use]
    pub fn symbol(self) -> &'static str {
        self.symbol
    }
}

// The ISO 4217 catalog, generated by build.rs from isodata.tsv.
include!(concat!(env!("OUT_DIR"), "/iso_currencies.rs"));

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

impl Debug for Currency {
    // The numeric code, minor digits, and symbol are a catalog row this code
    // keys, not state a reader has to be handed to recover them.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Currency({self})")
    }
}

impl Ord for Currency {
    fn cmp(&self, other: &Self) -> Ordering {
        self.alphabetic_code.cmp(&other.alphabetic_code)
    }
}

impl PartialOrd for Currency {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl From<Currency> for IsoAlphabeticCode {
    fn from(currency: Currency) -> Self {
        currency.alphabetic_code
    }
}

impl From<Currency> for IsoNumericCode {
    fn from(currency: Currency) -> Self {
        currency.numeric_code
    }
}

/// Looks up the currency ISO 4217 gives a well-formed code to, if any.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, IsoAlphabeticCode};
///
/// let code = IsoAlphabeticCode::try_from(*b"USD")?;
///
/// assert_eq!(Currency::try_from(code)?, Currency::USD);
///
/// // Well-formed, but no currency uses it.
/// assert!(Currency::try_from(IsoAlphabeticCode::try_from(*b"ZZZ")?).is_err());
/// #
/// #     Ok(())
/// # }
/// ```
impl TryFrom<IsoAlphabeticCode> for Currency {
    type Error = CurrencyError;

    /// ## Errors
    ///
    /// Returns [`CurrencyError::UnknownAlphabeticCode`] if no ISO 4217
    /// currency uses the code.
    fn try_from(code: IsoAlphabeticCode) -> Result<Self, Self::Error> {
        Currency::from_alphabetic_code(code.as_str()).ok_or_else(|| {
            CurrencyError::UnknownAlphabeticCode {
                code: code.as_str().to_owned(),
            }
        })
    }
}

impl TryFrom<IsoNumericCode> for Currency {
    type Error = CurrencyError;

    /// ## Errors
    ///
    /// Returns [`CurrencyError::UnknownNumericCode`] if no ISO 4217 currency
    /// uses the code.
    fn try_from(code: IsoNumericCode) -> Result<Self, Self::Error> {
        Currency::from_numeric_code(code.0)
            .ok_or(CurrencyError::UnknownNumericCode { code: code.0 })
    }
}

/// Reads a three-letter code, capitals only, and looks up the currency using
/// it.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, ParseCurrencyError};
///
/// assert_eq!("USD".parse::<Currency>()?, Currency::USD);
///
/// // Codes must match how ISO 4217 writes them. To take text in any case,
/// // uppercase it first, or use `Parser`, which reads an amount and its
/// // currency together.
/// assert!(matches!(
///     "usd".parse::<Currency>(),
///     Err(ParseCurrencyError::Code { .. })
/// ));
///
/// // Well-formed, but no currency uses it.
/// assert!(matches!(
///     "ZZZ".parse::<Currency>(),
///     Err(ParseCurrencyError::UnknownCurrency { .. })
/// ));
/// #
/// #     Ok(())
/// # }
/// ```
impl FromStr for Currency {
    type Err = ParseCurrencyError;

    /// ## Errors
    ///
    /// Returns [`ParseCurrencyError::Code`] if the text is not three capitals,
    /// and [`ParseCurrencyError::UnknownCurrency`] if it is a code no currency
    /// uses.
    fn from_str(code: &str) -> Result<Self, Self::Err> {
        let code = IsoAlphabeticCode::try_from(code)
            .map_err(|source| ParseCurrencyError::Code { source })?;

        Currency::try_from(code).map_err(|source| ParseCurrencyError::UnknownCurrency { source })
    }
}

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

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

/// An error from working with a [`Currency`].
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum CurrencyError {
    /// No currency uses the letters. Carries what was given.
    #[error("no ISO 4217 currency uses the code {code:?}")]
    #[diagnostic(
        code(lucre::currency::unknown_alphabetic_code),
        help("`Currency::all()` lists every currency this crate knows")
    )]
    #[non_exhaustive]
    UnknownAlphabeticCode {
        /// The code as given.
        code: String,
    },

    /// No currency uses the number. Carries what was given.
    #[error("no ISO 4217 currency uses the number {code}")]
    #[diagnostic(
        code(lucre::currency::unknown_numeric_code),
        help("`Currency::all()` lists every currency this crate knows")
    )]
    #[non_exhaustive]
    UnknownNumericCode {
        /// The number as given.
        code: u32,
    },
}

/// An error from reading a [`Currency`] from text.
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum ParseCurrencyError {
    /// The text is not spelled as an ISO 4217 code. The source error quotes
    /// the text back.
    #[error("not an ISO 4217 code")]
    #[diagnostic(code(lucre::currency::parse::code), forward(source))]
    #[non_exhaustive]
    Code {
        /// The error from reading the text as a code.
        source: IsoAlphabeticCodeError,
    },

    /// The text is a well-formed code that no currency uses. The source error
    /// quotes the code back.
    #[error("names no ISO 4217 currency")]
    #[diagnostic(code(lucre::currency::parse::unknown_currency), forward(source))]
    #[non_exhaustive]
    UnknownCurrency {
        /// The error from looking the code up.
        source: CurrencyError,
    },
}

/// An error from constructing an [`IsoAlphabeticCode`].
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum IsoAlphabeticCodeError {
    /// The bytes are not three capital ASCII letters. Carries what was given.
    #[error("an alphabetic currency code is three capital letters, but got {code:?}")]
    #[diagnostic(
        code(lucre::currency::alphabetic_code::invalid),
        help("codes are written in capitals, as in `USD` or `EUR`")
    )]
    #[non_exhaustive]
    InvalidCode {
        /// The text as given, or one `\xNN` escape per byte if the bytes are
        /// not text.
        code: String,
    },
}

impl IsoAlphabeticCodeError {
    /// Rejects `code`. Escaping bytes that are not text, rather than dropping
    /// them, keeps any two rejections apart.
    fn invalid(code: &[u8]) -> Self {
        let code = std::str::from_utf8(code)
            .map_or_else(|_| code.escape_ascii().to_string(), str::to_owned);

        Self::InvalidCode { code }
    }
}

/// An error from constructing an [`IsoNumericCode`].
#[derive(Clone, Copy, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum IsoNumericCodeError {
    /// The number is above `999`, so it does not fit in a three-digit code.
    #[error("a numeric currency code is at most 999, but got {code}")]
    #[diagnostic(
        code(lucre::currency::numeric_code::invalid),
        help("codes run from 0 to 999, as in `840` for `USD`")
    )]
    #[non_exhaustive]
    InvalidCode {
        /// The whole number, not trimmed to three digits.
        code: u32,
    },
}

#[cfg(test)]
mod tests {
    use std::error::Error as _;

    use super::*;

    #[test]
    fn currency_accessors_test() {
        let currency = Currency::USD;

        assert_eq!(currency.alphabetic_code().as_str(), "USD");
        assert_eq!(currency.numeric_code().value(), 840);
        assert_eq!(currency.minor_digits(), 2);
        assert_eq!(currency.symbol(), "$");
    }

    #[test]
    fn currency_lookup_test() {
        assert_eq!(Currency::from_alphabetic_code("USD"), Some(Currency::USD));
        assert_eq!(Currency::from_alphabetic_code("ZZZ"), None);
        assert_eq!(Currency::from_numeric_code(978), Some(Currency::EUR));
        assert_eq!(Currency::from_numeric_code(1), None);
    }

    #[test]
    fn currency_catalog_test() {
        assert!(Currency::all().contains(&Currency::USD));
        assert!(Currency::all().contains(&Currency::XAU));
        assert_eq!(Currency::BHD.minor_digits(), 3);
        assert_eq!(Currency::XAU.minor_digits(), 0);
    }

    #[test]
    fn alphabetic_code_try_from_bytes_test() {
        assert_eq!(
            IsoAlphabeticCode::try_from(*b"USD"),
            Ok(Currency::USD.alphabetic_code())
        );
        assert_eq!(
            IsoAlphabeticCode::try_from(*b"usd"),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: "usd".to_owned()
            })
        );
        assert_eq!(
            IsoAlphabeticCode::try_from(*b"840"),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: "840".to_owned()
            })
        );
        assert_eq!(
            IsoAlphabeticCode::try_from([0xC3, 0xA9, b'A']),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: "éA".to_owned()
            })
        );

        // Bytes spelling no text still tell the two refusals apart.
        assert_eq!(
            IsoAlphabeticCode::try_from([0xFF, 0xFE, 0xFD]),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: r"\xff\xfe\xfd".to_owned()
            })
        );
        assert_eq!(
            IsoAlphabeticCode::try_from([0xFF, 0xFF, 0xFF]),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: r"\xff\xff\xff".to_owned()
            })
        );
    }

    #[test]
    fn alphabetic_code_try_from_str_test() {
        assert_eq!(
            IsoAlphabeticCode::try_from("USD"),
            Ok(Currency::USD.alphabetic_code())
        );
        assert_eq!("USD".parse(), Ok(Currency::USD.alphabetic_code()));

        // Anything but three bytes fails on length alone.
        assert_eq!(
            "US".parse::<IsoAlphabeticCode>(),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: "US".to_owned()
            })
        );
        assert_eq!(
            "USDD".parse::<IsoAlphabeticCode>(),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: "USDD".to_owned()
            })
        );
        assert_eq!(
            "€UR".parse::<IsoAlphabeticCode>(),
            Err(IsoAlphabeticCodeError::InvalidCode {
                code: "€UR".to_owned()
            })
        );
    }

    #[test]
    fn code_error_messages_quote_the_input_test() {
        let alphabetic = IsoAlphabeticCode::try_from("us").unwrap_err();
        let numeric = IsoNumericCode::try_from(1000).unwrap_err();

        assert_eq!(
            alphabetic.to_string(),
            "an alphabetic currency code is three capital letters, but got \"us\""
        );
        assert_eq!(
            numeric.to_string(),
            "a numeric currency code is at most 999, but got 1000"
        );
    }

    #[test]
    fn code_conversions_test() {
        let currency = Currency::USD;

        assert_eq!(
            IsoAlphabeticCode::from(currency),
            currency.alphabetic_code()
        );
        assert_eq!(IsoNumericCode::from(currency), currency.numeric_code());
        assert_eq!(<[u8; 3]>::from(currency.alphabetic_code()), *b"USD");
        assert_eq!(u32::from(currency.numeric_code()), 840);
        assert_eq!(currency.alphabetic_code().as_ref() as &str, "USD");
    }

    #[test]
    fn numeric_code_try_from_u32_test() {
        assert_eq!(
            IsoNumericCode::try_from(840),
            Ok(Currency::USD.numeric_code())
        );

        // The bounds of what three digits can spell.
        assert_eq!(
            IsoNumericCode::try_from(0).map(IsoNumericCode::value),
            Ok(0)
        );
        assert_eq!(
            IsoNumericCode::try_from(999).map(IsoNumericCode::value),
            Ok(999)
        );
        assert_eq!(
            IsoNumericCode::try_from(1000),
            Err(IsoNumericCodeError::InvalidCode { code: 1000 })
        );
    }

    #[test]
    fn every_numeric_code_round_trips_through_u32_test() {
        for currency in Currency::all() {
            let code = currency.numeric_code();

            assert_eq!(IsoNumericCode::try_from(code.value()), Ok(code));
        }
    }

    // The catalog is generated straight into the private fields, so the
    // constructors never see it. This checks the codes against the rule they
    // would have been held to.
    #[test]
    fn every_alphabetic_code_round_trips_through_bytes_test() {
        for currency in Currency::all() {
            let code = currency.alphabetic_code();
            let bytes: [u8; 3] = code.into();

            assert_eq!(IsoAlphabeticCode::try_from(bytes), Ok(code));
        }
    }

    #[test]
    fn currency_try_from_codes_test() {
        let usd = Currency::USD.alphabetic_code();

        assert_eq!(Currency::try_from(usd), Ok(Currency::USD));
        assert_eq!(
            Currency::try_from(Currency::EUR.numeric_code()),
            Ok(Currency::EUR)
        );

        let unassigned = IsoAlphabeticCode::try_from(*b"ZZZ").unwrap();
        assert_eq!(
            Currency::try_from(unassigned),
            Err(CurrencyError::UnknownAlphabeticCode {
                code: "ZZZ".to_owned()
            })
        );
        assert_eq!(
            Currency::try_from(IsoNumericCode::try_from(1).unwrap()),
            Err(CurrencyError::UnknownNumericCode { code: 1 })
        );
    }

    #[test]
    fn currency_from_str_test() {
        assert_eq!("USD".parse(), Ok(Currency::USD));
        assert_eq!(Currency::try_from("EUR"), Ok(Currency::EUR));
    }

    #[test]
    fn currency_from_str_keeps_a_misspelled_code_from_an_unassigned_one_test() {
        assert_eq!(
            "ZZZ".parse::<Currency>(),
            Err(ParseCurrencyError::UnknownCurrency {
                source: CurrencyError::UnknownAlphabeticCode {
                    code: "ZZZ".to_owned()
                }
            })
        );

        // Codes are matched exactly as ISO 4217 writes them.
        assert_eq!(
            "usd".parse::<Currency>(),
            Err(ParseCurrencyError::Code {
                source: IsoAlphabeticCodeError::InvalidCode {
                    code: "usd".to_owned()
                }
            })
        );
    }

    #[test]
    fn currency_refusal_quotes_the_code_back_test() {
        let misspelled = "usd".parse::<Currency>().unwrap_err();
        let unassigned = "ZZZ".parse::<Currency>().unwrap_err();
        let unassigned_number =
            Currency::try_from(IsoNumericCode::try_from(1).unwrap()).unwrap_err();

        assert_eq!(
            misspelled.source().unwrap().to_string(),
            r#"an alphabetic currency code is three capital letters, but got "usd""#
        );
        assert_eq!(
            unassigned.source().unwrap().to_string(),
            r#"no ISO 4217 currency uses the code "ZZZ""#
        );
        assert_eq!(
            unassigned_number.to_string(),
            "no ISO 4217 currency uses the number 1"
        );
    }

    #[test]
    fn currency_display_round_trips_through_from_str_test() {
        for currency in Currency::all() {
            assert_eq!(currency.to_string().parse(), Ok(*currency));
        }
    }

    #[test]
    fn debug_spells_a_code_test() {
        assert_eq!(
            format!("{:?}", Currency::USD.alphabetic_code()),
            "IsoAlphabeticCode(USD)"
        );
    }

    #[test]
    fn debug_spells_a_currency_test() {
        assert_eq!(format!("{:?}", Currency::USD), "Currency(USD)");
    }
}