lucre 0.2.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
//! Reading of [`Money`] values from text.
//!
//! A [`Parser`] value describes what to expect of the text: which characters
//! group digits and mark the fraction, and which currency to assume when the
//! text names none. [`Money`]'s [`FromStr`] impl applies the default
//! expectations, so `"1,500.00 USD".parse()` needs no recipe at all. The
//! vocabulary mirrors [`Format`](crate::Format): any rendering a `Format`
//! produces can be read back by a `Parser` that shares its separators and,
//! when the rendering carries no ISO code, assumes the right currency.

use std::str::FromStr;

use rust_decimal::Decimal;
use thiserror::Error;

use crate::{Currency, Money};

/// A reusable recipe for reading monetary amounts from text.
///
/// Start from [`Parser::new`] (or [`Parser::default`]) and refine it with the
/// builder methods; construction cannot fail. The starting recipe reads
/// amounts like `1,500.00 USD`, `usd 1500`, `(1,500.00 USD)`, or `-1.50USD`:
/// an ISO code on either side of the digits, commas grouping them, a dot
/// decimal mark, negatives marked by a minus sign or by parentheses.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Parser {
    assumed: Option<Currency>,
    group_separator: char,
    decimal_separator: char,
}

impl Parser {
    /// The starting recipe: comma-grouped digits, a dot decimal mark, and no
    /// assumed currency, so the text must carry an ISO code.
    pub const fn new() -> Self {
        Self {
            assumed: None,
            group_separator: ',',
            decimal_separator: '.',
        }
    }

    /// The characters expected to separate digit groups and mark the start
    /// of the fraction, e.g. `separators('.', ',')` for `1.500,00`.
    pub const fn separators(mut self, group: char, decimal: char) -> Self {
        self.group_separator = group;
        self.decimal_separator = decimal;
        self
    }

    /// The currency to use when the text names none, which also lets the
    /// text identify the currency by this currency's symbol. An ISO code in
    /// the text still wins over the assumption.
    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 currency may be named on either side of the digits — by ISO code
    /// (case-insensitive) or by the applicable currency's symbol — or on both
    /// sides when they agree, as in `$1.50 USD`; text naming neither falls
    /// back to the assumed currency. Negative amounts are marked by
    /// enclosing parentheses or by one minus sign, either leading or
    /// directly before the digits. Group separators
    /// may appear anywhere left of the decimal mark; their spacing is not
    /// checked. The digits are kept verbatim, as by [`Money::from_decimal`]:
    /// nothing is rounded or scaled to the currency's minor digits.
    ///
    /// ## 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 applicable symbol.
    /// Returns `ParseMoneyError::ConflictingCurrencies` if the text names two different currencies.
    /// Returns `ParseMoneyError::InvalidAmount` if the digits are absent, malformed, or beyond `Decimal`'s range.
    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);
            }
            negative = true;
            s = rest.trim_start();
        }

        let first = s
            .find(|c: char| c.is_ascii_digit())
            .ok_or(ParseMoneyError::InvalidAmount)?;
        let last = s
            .rfind(|c: char| c.is_ascii_digit())
            .expect("a digit was found");

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

        // A minus written between a prefixed identifier and the digits, as
        // in `$-1.50`, lands on the prefix token; claim it as the sign.
        if let Some(stripped) = prefix.strip_suffix('-') {
            if negative {
                return Err(ParseMoneyError::InvalidAmount);
            }
            negative = true;
            prefix = stripped.trim_end();
        }

        let currency = self.identify(prefix, suffix)?;
        let amount = self.read_amount(&s[first..=last], negative)?;
        Ok(Money::from_decimal(amount, &currency))
    }

    /// Resolves the identifier tokens found around the digits into one
    /// currency, giving ISO codes priority so a symbol on the other side is
    /// checked against the coded currency rather than the assumed one.
    fn identify(&self, prefix: &str, suffix: &str) -> Result<Currency, ParseMoneyError> {
        let mut currency = 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(coded) => {
                    if currency.is_some_and(|c| c != coded) {
                        return Err(ParseMoneyError::ConflictingCurrencies);
                    }
                    currency = Some(coded);
                }
                None => *slot = Some(token),
            }
        }
        for token in symbols.into_iter().flatten() {
            let claimed = currency
                .or(self.assumed)
                .filter(|c| c.symbol() == token)
                .ok_or_else(|| ParseMoneyError::UnknownCurrency(token.to_string()))?;
            currency = Some(claimed);
        }
        currency
            .or(self.assumed)
            .ok_or(ParseMoneyError::MissingCurrency)
    }

    /// Turns the span between the first and last digit into a `Decimal`,
    /// dropping group separators and normalizing the decimal mark.
    fn read_amount(&self, span: &str, negative: bool) -> Result<Decimal, ParseMoneyError> {
        let mut normalized = String::with_capacity(span.len() + 1);
        if negative {
            normalized.push('-');
        }
        let mut in_fraction = false;
        for c in span.chars() {
            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 marks carry no value and are simply dropped.
            } else {
                return Err(ParseMoneyError::InvalidAmount);
            }
        }
        Decimal::from_str(&normalized).map_err(|_| ParseMoneyError::InvalidAmount)
    }
}

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

/// Parses as [`Parser::new`]'s recipe expects: `1,500.00 USD`, `USD 1,500.00`,
/// and the other shapes [`Parser::parse`] describes.
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 out of text.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
pub enum ParseMoneyError {
    #[error("no currency named and none assumed")]
    MissingCurrency,

    #[error("unrecognized currency {0:?}")]
    UnknownCurrency(String),

    #[error("more than one currency named")]
    ConflictingCurrencies,

    #[error("malformed or unrepresentable amount")]
    InvalidAmount,
}

#[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(150000, &Currency::USD));
    }

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

        assert_eq!(money, Money::from_minor(150000, &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(-150000, &Currency::USD)
        );
    }

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

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

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

    #[test]
    fn conflicting_currencies_test() {
        assert_eq!(
            "EUR 1.50 USD".parse::<Money>(),
            Err(ParseMoneyError::ConflictingCurrencies)
        );
    }

    #[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("".to_string()))
        );
    }

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

    #[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("$".to_string()))
        );
    }

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

        assert_eq!(
            parser.parse("1.500,00 EUR").unwrap(),
            Money::from_minor(150000, &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)
        );
    }

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

    #[test]
    fn no_digits_is_invalid_test() {
        assert_eq!("USD".parse::<Money>(), Err(ParseMoneyError::InvalidAmount));
        assert_eq!("".parse::<Money>(), Err(ParseMoneyError::InvalidAmount));
    }

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

    #[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(-1234567, &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:?}"
            );
        }
    }
}