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
//! Reading of [`Money`] values from text.

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

use miette::Diagnostic;
use rust_decimal::Decimal;
use thiserror::Error;

use crate::{Currency, Money};

/// A reusable set of options for reading monetary amounts from text.
///
/// Start from [`Parser::new`] (or [`Parser::default`]) and change it with the
/// builder methods. Building one cannot fail. [`Money`]'s [`FromStr`] impl
/// uses the starting options, so common text needs no `Parser` at all.
///
/// The options match [`Format`](crate::Format)'s. A `Parser` reads back
/// anything a `Format` writes, so long as it uses the same separators and, if
/// the text has no ISO code, assumes the right currency.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money, Parser};
///
/// let parser = Parser::new();
/// let expected = Money::from_minor(-150_000, Currency::USD);
///
/// // The starting options read an ISO code on either side of the digits,
/// // commas between digit groups, a dot for the decimal mark, and a minus
/// // sign or parentheses for negatives.
/// assert_eq!(parser.parse("-1,500.00 usd")?, expected);
/// assert_eq!(parser.parse("(USD 1,500.00)")?, expected);
/// #
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct Parser {
    assumed: Option<Currency>,
    group_separator: char,
    decimal_separator: char,
}

impl Parser {
    /// The starting options: commas between digit groups, a dot for the
    /// decimal mark, and no assumed currency, so the text must name an ISO
    /// code.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Money, Parser};
    ///
    /// let parser = Parser::new();
    ///
    /// assert_eq!(
    ///     parser.parse("1,500.00 USD")?,
    ///     Money::from_minor(150_000, Currency::USD)
    /// );
    /// assert!(parser.parse("1,500.00").is_err());
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            assumed: None,
            group_separator: ',',
            decimal_separator: '.',
        }
    }

    /// Set the characters that separate digit groups and mark the start of
    /// the fraction.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Money, Parser};
    ///
    /// let parser = Parser::new().separators('.', ',');
    ///
    /// assert_eq!(
    ///     parser.parse("1.500,00 EUR")?,
    ///     Money::from_minor(150_000, Currency::EUR)
    /// );
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn separators(mut self, group: char, decimal: char) -> Self {
        self.group_separator = group;
        self.decimal_separator = decimal;
        self
    }

    /// Use `currency` when the text names none.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Money, Parser};
    ///
    /// let parser = Parser::new().assume_currency(Currency::USD);
    ///
    /// assert_eq!(parser.parse("1.50")?, Money::from_minor(150, Currency::USD));
    ///
    /// // An assumed currency also lets the text name it by symbol.
    /// assert_eq!(parser.parse("$1.50")?, Money::from_minor(150, Currency::USD));
    ///
    /// // An ISO code in the text takes priority over the assumed currency.
    /// assert_eq!(parser.parse("1.50 EUR")?, Money::from_minor(150, Currency::EUR));
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    #[must_use]
    pub const fn assume_currency(mut self, currency: Currency) -> Self {
        self.assumed = Some(currency);
        self
    }

    /// Reads one monetary amount from `text`, ignoring surrounding
    /// whitespace.
    ///
    /// The digits are kept as written, as by [`Money::from_decimal`]. Nothing
    /// is rounded or padded to the currency's minor digits.
    ///
    /// A [`Decimal`] holds 29 digits at most, and no more than 28 of them
    /// after the decimal mark. Fraction digits past that are rounded away.
    ///
    /// ## Example
    ///
    /// ```
    /// # use std::error::Error;
    /// #
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use lucre::{Currency, Money, Parser};
    ///
    /// let parser = Parser::new().assume_currency(Currency::USD);
    /// let expected = Money::from_minor(150, Currency::USD);
    ///
    /// // The currency may be named before or after the digits, by ISO code
    /// // in any case or by the symbol of the currency that applies. Both
    /// // sides may name it as long as they agree. Text that names neither
    /// // uses the assumed currency.
    /// assert_eq!(parser.parse("1.50 usd")?, expected);
    /// assert_eq!(parser.parse("USD 1.50")?, expected);
    /// assert_eq!(parser.parse("$1.50 USD")?, expected);
    /// assert_eq!(parser.parse("1.50")?, expected);
    ///
    /// // A negative amount is marked by parentheses around the whole text,
    /// // or by one minus sign, at the front or right before the digits.
    /// let negative = Money::from_minor(-150, Currency::USD);
    /// assert_eq!(parser.parse("(1.50)")?, negative);
    /// assert_eq!(parser.parse("$-1.50")?, negative);
    ///
    /// // Group separators may appear anywhere before the decimal mark.
    /// // Their spacing is not checked.
    /// assert_eq!(
    ///     parser.parse("1,00,0.50")?,
    ///     Money::from_decimal("1000.50".parse()?, Currency::USD)
    /// );
    /// #
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns [`ParseMoneyError::MissingCurrency`] if the text names no currency and none is assumed.
    /// Returns [`ParseMoneyError::UnknownCurrency`] if a named currency matches no ISO code and no symbol of the currency that applies.
    /// Returns [`ParseMoneyError::ConflictingCurrencies`] if the text names two different currencies.
    /// Returns [`ParseMoneyError::InvalidAmount`] if the digits are missing, malformed, or too large for a [`Decimal`].
    pub fn parse(self, text: &str) -> Result<Money, ParseMoneyError> {
        let mut s = text.trim();
        let mut negative = false;

        if let Some(inner) = s.strip_prefix('(').and_then(|r| r.strip_suffix(')')) {
            negative = true;
            s = inner.trim();
        }
        if let Some(rest) = s.strip_prefix('-') {
            if negative {
                return Err(ParseMoneyError::InvalidAmount {
                    text: text.to_string(),
                    at: span_of(text, &s[..1]),
                });
            }
            negative = true;
            s = rest.trim_start();
        }

        let no_digits = || ParseMoneyError::InvalidAmount {
            text: text.to_string(),
            at: span_of(text, s),
        };
        let first = s.find(|c: char| c.is_ascii_digit()).ok_or_else(no_digits)?;
        let last = s
            .rfind(|c: char| c.is_ascii_digit())
            .ok_or_else(no_digits)?;

        let mut prefix = s[..first].trim_end();
        let suffix = s[last + 1..].trim_start();

        // A minus between a leading identifier and the digits, as in
        // `$-1.50`, ends up at the end of the prefix token. Take it as the
        // sign.
        if let Some(stripped) = prefix.strip_suffix('-') {
            if negative {
                return Err(ParseMoneyError::InvalidAmount {
                    text: text.to_string(),
                    at: span_of(text, &prefix[stripped.len()..]),
                });
            }
            negative = true;
            prefix = stripped.trim_end();
        }

        let currency = self.identify(text, prefix, suffix)?.ok_or_else(|| {
            ParseMoneyError::MissingCurrency {
                text: text.to_string(),
                at: span_of(text, s),
            }
        })?;
        let amount = self.read_amount(text, &s[first..=last], negative)?;
        Ok(Money::from_decimal(amount, currency))
    }

    /// Settles the tokens around the digits on one currency. ISO codes are
    /// read first, so a symbol on the other side is checked against the coded
    /// currency rather than the assumed one.
    ///
    /// Returns `None` if neither token names a currency and this `Parser`
    /// assumes none. `text` is what the spans in any error count from, and
    /// both tokens must be subslices of it.
    fn identify(
        self,
        text: &str,
        prefix: &str,
        suffix: &str,
    ) -> Result<Option<Currency>, ParseMoneyError> {
        let mut coded: Option<(Currency, Range<usize>)> = None;
        let mut symbols = [None, None];
        for (slot, token) in symbols.iter_mut().zip([prefix, suffix]) {
            if token.is_empty() {
                continue;
            }
            match Currency::from_alphabetic_code(&token.to_ascii_uppercase()) {
                Some(found) => {
                    if let Some((seen, first)) = &coded
                        && *seen != found
                    {
                        return Err(ParseMoneyError::ConflictingCurrencies {
                            text: text.to_string(),
                            first: first.clone(),
                            second: span_of(text, token),
                        });
                    }
                    coded = Some((found, span_of(text, token)));
                }
                None => *slot = Some(token),
            }
        }
        let mut currency = coded.map(|(found, _)| found);
        for token in symbols.into_iter().flatten() {
            let claimed = currency
                .or(self.assumed)
                .filter(|c| c.symbol() == token)
                .ok_or_else(|| ParseMoneyError::UnknownCurrency {
                    text: text.to_string(),
                    token: token.to_string(),
                    at: span_of(text, token),
                })?;
            currency = Some(claimed);
        }
        Ok(currency.or(self.assumed))
    }

    /// Reads the text from the first digit to the last as a `Decimal`,
    /// dropping group separators and replacing the decimal mark with a dot.
    ///
    /// `text` is what the spans in any error count from, and `digits` must be
    /// a subslice of it.
    fn read_amount(
        self,
        text: &str,
        digits: &str,
        negative: bool,
    ) -> Result<Decimal, ParseMoneyError> {
        let mut normalized = String::with_capacity(digits.len() + 1);
        if negative {
            normalized.push('-');
        }
        let mut in_fraction = false;
        for (i, c) in digits.char_indices() {
            if c.is_ascii_digit() {
                normalized.push(c);
            } else if c == self.decimal_separator && !in_fraction {
                in_fraction = true;
                normalized.push('.');
            } else if c == self.group_separator && !in_fraction {
                // Group separators add nothing to the value.
            } else {
                let start = span_of(text, digits).start + i;
                return Err(ParseMoneyError::InvalidAmount {
                    text: text.to_string(),
                    at: start..start + c.len_utf8(),
                });
            }
        }
        Decimal::from_str(&normalized).map_err(|_| ParseMoneyError::InvalidAmount {
            text: text.to_string(),
            at: span_of(text, digits),
        })
    }
}

/// The byte range that `inner` covers in `outer`.
///
/// `inner` must be a subslice of `outer`. A separate string that happens to
/// hold the same characters gives a meaningless answer.
fn span_of(outer: &str, inner: &str) -> Range<usize> {
    let start = inner.as_ptr().addr() - outer.as_ptr().addr();
    start..start + inner.len()
}

impl Default for Parser {
    fn default() -> Self {
        Self::new()
    }
}

/// Parses as [`Parser::new`] describes.
///
/// ## Example
///
/// ```
/// # use std::error::Error;
/// #
/// # fn main() -> Result<(), Box<dyn Error>> {
/// use lucre::{Currency, Money};
///
/// let expected = Money::from_minor(150_000, Currency::USD);
///
/// assert_eq!("1,500.00 USD".parse::<Money>()?, expected);
/// assert_eq!("USD 1,500.00".parse::<Money>()?, expected);
/// #
/// #     Ok(())
/// # }
/// ```
impl FromStr for Money {
    type Err = ParseMoneyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Parser::new().parse(s)
    }
}

/// An error from reading a monetary amount from text.
///
/// Every variant keeps the text the [`Parser`] read and points into it by
/// byte range. The ranges count from the start of that text, leading
/// whitespace included, so they index it as it was handed in.
#[derive(Clone, Debug, Diagnostic, Error, Eq, PartialEq)]
#[diagnostic(url(docsrs))]
#[non_exhaustive]
pub enum ParseMoneyError {
    /// The text named no currency, and the [`Parser`] assumes none.
    #[error("the text names no currency, and the parser assumes none")]
    #[diagnostic(
        code(lucre::money::parse::missing_currency),
        help("name a currency in the text, or give the `Parser` one to assume")
    )]
    MissingCurrency {
        /// The text the [`Parser`] read.
        #[source_code]
        text: String,
        /// Covers the text without its surrounding whitespace.
        #[label("no currency here")]
        at: Range<usize>,
    },

    /// The text named a currency that matches no ISO code and no symbol of
    /// the currency that applies.
    #[error("no currency matches {token:?}")]
    #[diagnostic(
        code(lucre::money::parse::unknown_currency),
        help("name a currency by its ISO 4217 code, or by the symbol of the one assumed")
    )]
    UnknownCurrency {
        /// The text the [`Parser`] read.
        #[source_code]
        text: String,
        /// The part that matched nothing.
        token: String,
        /// Covers `token`.
        #[label("matches no currency")]
        at: Range<usize>,
    },

    /// The text named two different currencies.
    #[error("the text names more than one currency")]
    #[diagnostic(
        code(lucre::money::parse::conflicting_currencies),
        help("an amount is in one currency; drop whichever of the two the text does not mean")
    )]
    ConflictingCurrencies {
        /// The text the [`Parser`] read.
        #[source_code]
        text: String,
        /// Covers the currency written first.
        #[label("one currency")]
        first: Range<usize>,
        /// Covers the currency written second.
        #[label("a different currency")]
        second: Range<usize>,
    },

    /// The digits are missing, malformed, or too large for a [`Decimal`].
    #[error("the amount is missing, malformed, or too large for a decimal")]
    #[diagnostic(
        code(lucre::money::parse::invalid_amount),
        help("a `Decimal` holds up to 28 significant digits")
    )]
    InvalidAmount {
        /// The text the [`Parser`] read.
        #[source_code]
        text: String,
        /// Covers the character at fault. Covers every digit when the amount
        /// is too large, and the text without its surrounding whitespace when
        /// the text holds no digits.
        #[label("not part of a valid amount")]
        at: Range<usize>,
    },
}

impl ParseMoneyError {
    /// The text the [`Parser`] read.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Money;
    ///
    /// let error = "  1.50 ZZZ".parse::<Money>().unwrap_err();
    ///
    /// assert_eq!(error.text(), "  1.50 ZZZ");
    /// assert_eq!(&error.text()[error.span()], "ZZZ");
    /// ```
    #[must_use]
    pub fn text(&self) -> &str {
        match self {
            Self::MissingCurrency { text, .. }
            | Self::UnknownCurrency { text, .. }
            | Self::ConflictingCurrencies { text, .. }
            | Self::InvalidAmount { text, .. } => text,
        }
    }

    /// The byte range the error points at.
    ///
    /// [`ConflictingCurrencies`](Self::ConflictingCurrencies) names two
    /// currencies. This returns the first of them.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Money;
    ///
    /// let error = "1.50 ZZZ".parse::<Money>().unwrap_err();
    ///
    /// assert_eq!(error.span(), 5..8);
    /// ```
    #[must_use]
    pub fn span(&self) -> Range<usize> {
        match self {
            Self::MissingCurrency { at, .. }
            | Self::UnknownCurrency { at, .. }
            | Self::InvalidAmount { at, .. } => at.clone(),
            Self::ConflictingCurrencies { first, .. } => first.clone(),
        }
    }
}

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

    #[test]
    fn code_suffix_test() {
        let money: Money = "1,500.00 USD".parse().unwrap();

        assert_eq!(money, Money::from_minor(150_000, Currency::USD));
    }

    #[test]
    fn code_prefix_test() {
        let money: Money = "USD 1,500.00".parse().unwrap();

        assert_eq!(money, Money::from_minor(150_000, Currency::USD));
    }

    #[test]
    fn code_without_space_test() {
        assert_eq!(
            "1.50USD".parse::<Money>().unwrap(),
            Money::from_minor(150, Currency::USD)
        );
        assert_eq!(
            "USD1.50".parse::<Money>().unwrap(),
            Money::from_minor(150, Currency::USD)
        );
    }

    #[test]
    fn code_is_case_insensitive_test() {
        assert_eq!(
            "1.50 usd".parse::<Money>().unwrap(),
            Money::from_minor(150, Currency::USD)
        );
    }

    #[test]
    fn surrounding_whitespace_test() {
        assert_eq!(
            "  1.50 USD  ".parse::<Money>().unwrap(),
            Money::from_minor(150, Currency::USD)
        );
    }

    #[test]
    fn negative_minus_placements_test() {
        let expected = Money::from_minor(-150, Currency::USD);

        assert_eq!("-1.50 USD".parse::<Money>().unwrap(), expected);
        assert_eq!("-USD 1.50".parse::<Money>().unwrap(), expected);
        assert_eq!("USD -1.50".parse::<Money>().unwrap(), expected);
    }

    #[test]
    fn negative_parentheses_test() {
        assert_eq!(
            "(1,500.00 USD)".parse::<Money>().unwrap(),
            Money::from_minor(-150_000, Currency::USD)
        );
    }

    #[test]
    fn doubled_sign_is_invalid_test() {
        assert_eq!(
            "--1.50 USD".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: "--1.50 USD".to_string(),
                at: 1..2
            })
        );
        assert_eq!(
            "(-1.50 USD)".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: "(-1.50 USD)".to_string(),
                at: 1..2
            })
        );
    }

    #[test]
    fn missing_currency_test() {
        assert_eq!(
            "1.50".parse::<Money>(),
            Err(ParseMoneyError::MissingCurrency {
                text: "1.50".to_string(),
                at: 0..4
            })
        );
    }

    #[test]
    fn unknown_currency_test() {
        assert_eq!(
            "1.50 ZZZ".parse::<Money>(),
            Err(ParseMoneyError::UnknownCurrency {
                text: "1.50 ZZZ".to_string(),
                token: "ZZZ".to_string(),
                at: 5..8
            })
        );
    }

    #[test]
    fn conflicting_currencies_test() {
        assert_eq!(
            "EUR 1.50 USD".parse::<Money>(),
            Err(ParseMoneyError::ConflictingCurrencies {
                text: "EUR 1.50 USD".to_string(),
                first: 0..3,
                second: 9..12
            })
        );
    }

    #[test]
    fn symbol_agreeing_with_code_test() {
        assert_eq!(
            "$1.50 USD".parse::<Money>().unwrap(),
            Money::from_minor(150, Currency::USD)
        );
        assert_eq!(
            "€1.50 USD".parse::<Money>(),
            Err(ParseMoneyError::UnknownCurrency {
                text: "€1.50 USD".to_string(),
                token: "€".to_string(),
                at: 0..3
            })
        );
    }

    #[test]
    fn symbol_without_assumption_is_unknown_test() {
        assert_eq!(
            "$1.50".parse::<Money>(),
            Err(ParseMoneyError::UnknownCurrency {
                text: "$1.50".to_string(),
                token: "$".to_string(),
                at: 0..1
            })
        );
    }

    #[test]
    fn assumed_currency_test() {
        let parser = Parser::new().assume_currency(Currency::USD);

        assert_eq!(
            parser.parse("1.50").unwrap(),
            Money::from_minor(150, Currency::USD)
        );
        assert_eq!(
            parser.parse("$1.50").unwrap(),
            Money::from_minor(150, Currency::USD)
        );
        assert_eq!(
            parser.parse("$-1.50").unwrap(),
            Money::from_minor(-150, Currency::USD)
        );
    }

    #[test]
    fn code_overrides_assumed_currency_test() {
        let parser = Parser::new().assume_currency(Currency::USD);

        assert_eq!(
            parser.parse("1.50 EUR").unwrap(),
            Money::from_minor(150, Currency::EUR)
        );
    }

    #[test]
    fn wrong_symbol_for_assumed_currency_test() {
        let parser = Parser::new().assume_currency(Currency::EUR);

        assert_eq!(
            parser.parse("$1.50"),
            Err(ParseMoneyError::UnknownCurrency {
                text: "$1.50".to_string(),
                token: "$".to_string(),
                at: 0..1
            })
        );
    }

    #[test]
    fn separators_test() {
        let parser = Parser::new().separators('.', ',');

        assert_eq!(
            parser.parse("1.500,00 EUR").unwrap(),
            Money::from_minor(150_000, Currency::EUR)
        );
    }

    #[test]
    fn grouping_spacing_is_not_checked_test() {
        assert_eq!(
            "1,00,0.50 USD".parse::<Money>().unwrap(),
            Money::from_decimal(dec!(1000.50), Currency::USD)
        );
    }

    #[test]
    fn group_separator_in_fraction_is_invalid_test() {
        assert_eq!(
            "1.5,0 USD".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: "1.5,0 USD".to_string(),
                at: 3..4
            })
        );
    }

    #[test]
    fn second_decimal_mark_is_invalid_test() {
        assert_eq!(
            "1.5.0 USD".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: "1.5.0 USD".to_string(),
                at: 3..4
            })
        );
    }

    #[test]
    fn no_digits_is_invalid_test() {
        assert_eq!(
            "USD".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: "USD".to_string(),
                at: 0..3
            })
        );
        assert_eq!(
            "".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: String::new(),
                at: 0..0
            })
        );
    }

    #[test]
    fn amount_beyond_decimal_range_is_invalid_test() {
        assert_eq!(
            "99999999999999999999999999999999999999 USD".parse::<Money>(),
            Err(ParseMoneyError::InvalidAmount {
                text: "99999999999999999999999999999999999999 USD".to_string(),
                at: 0..38
            })
        );
    }

    #[test]
    fn diagnostic_labels_the_token_that_matched_nothing_test() {
        let error = "1.50 ZZZ".parse::<Money>().unwrap_err();
        let labels: Vec<_> = error.labels().unwrap().collect();

        assert!(error.source_code().is_some());
        assert_eq!(labels.len(), 1);
        assert_eq!(labels[0].offset(), 5);
        assert_eq!(labels[0].len(), 3);
        assert_eq!(labels[0].label(), Some("matches no currency"));
    }

    #[test]
    fn diagnostic_labels_both_conflicting_currencies_test() {
        let error = "EUR 1.50 USD".parse::<Money>().unwrap_err();
        let labels: Vec<_> = error.labels().unwrap().collect();

        assert_eq!(labels.len(), 2);
        assert_eq!((labels[0].offset(), labels[0].len()), (0, 3));
        assert_eq!((labels[1].offset(), labels[1].len()), (9, 3));
    }

    #[test]
    fn spans_count_from_the_untrimmed_start_test() {
        assert_eq!(
            "   1.50 ZZZ  ".parse::<Money>(),
            Err(ParseMoneyError::UnknownCurrency {
                text: "   1.50 ZZZ  ".to_string(),
                token: "ZZZ".to_string(),
                at: 8..11
            })
        );
    }

    #[test]
    fn digits_are_kept_verbatim_test() {
        let money: Money = "1.2345 USD".parse().unwrap();

        assert_eq!(money.amount(), dec!(1.2345));
    }

    #[test]
    fn zero_minor_digit_currency_test() {
        assert_eq!(
            "5 JPY".parse::<Money>().unwrap(),
            Money::from_major(5, Currency::JPY)
        );
    }

    #[test]
    fn round_trips_format_renderings_test() {
        let money = Money::from_minor(-1_234_567, Currency::USD);
        let parser = Parser::new().assume_currency(Currency::USD);

        for format in [
            Format::new(),
            Format::new().symbol(),
            Format::new().amount_only(),
            Format::new().prefix().no_space(),
            Format::new().symbol().parentheses(),
            Format::new().no_grouping(),
            Format::new().grouping(3, 2),
        ] {
            let rendered = money.format_with(format).to_string();

            assert_eq!(
                parser.parse(&rendered).unwrap(),
                money,
                "rendering {rendered:?}"
            );
        }
    }
}