lucre 0.5.1

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
//! Rendering of [`Money`] values as text.
//!
//! A [`Format`] value describes a rendering: how the currency is identified,
//! how digits are grouped and separated, how many fractional digits appear,
//! and how negative amounts are marked. [`Money::format_with`] applies one to
//! an amount. The vocabulary is deliberately locale-ignorant: it can express
//! most national conventions, but knows nothing about locales themselves.

use std::fmt::{self, Write as _};

use crate::{Money, RoundingMode};

/// A reusable recipe for rendering monetary amounts.
///
/// Start from [`Format::new`] (or [`Format::default`]) and refine it with the
/// builder methods; every combination of options is valid, so neither
/// construction nor formatting can fail. The starting recipe renders
/// `Money::from_minor(150000, &Currency::USD)` as `1,500.00 USD`: digits
/// grouped in threes by commas, a dot decimal mark, the fraction padded to
/// the currency's minor digits, a leading minus for negatives, and the ISO
/// code suffixed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Format {
    identifier: Identifier,
    position: Option<Position>,
    spaced: Option<bool>,
    negative: NegativeStyle,
    precision: Option<(u32, RoundingMode)>,
    grouping: &'static [u8],
    group_separator: char,
    decimal_separator: char,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Identifier {
    Code,
    Symbol,
    None,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Position {
    Prefix,
    Suffix,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum NegativeStyle {
    Minus,
    Parentheses,
}

impl Format {
    /// The starting recipe: `1,500.00 USD`.
    pub const fn new() -> Self {
        Self {
            identifier: Identifier::Code,
            position: None,
            spaced: None,
            negative: NegativeStyle::Minus,
            precision: None,
            grouping: &[3],
            group_separator: ',',
            decimal_separator: '.',
        }
    }

    /// Identify the currency by its three-letter ISO code, suffixed, with a
    /// space, unless overridden: `1,500.00 USD`.
    pub const fn code(mut self) -> Self {
        self.identifier = Identifier::Code;
        self
    }

    /// Identify the currency by its symbol, prefixed, without a space,
    /// unless overridden: `$1,500.00`.
    pub const fn symbol(mut self) -> Self {
        self.identifier = Identifier::Symbol;
        self
    }

    /// Show the bare amount with no currency identifier: `1,500.00`.
    pub const fn amount_only(mut self) -> Self {
        self.identifier = Identifier::None;
        self
    }

    /// Place the currency identifier before the amount.
    pub const fn prefix(mut self) -> Self {
        self.position = Some(Position::Prefix);
        self
    }

    /// Place the currency identifier after the amount.
    pub const fn suffix(mut self) -> Self {
        self.position = Some(Position::Suffix);
        self
    }

    /// Put a space between the amount and the currency identifier.
    pub const fn spaced(mut self) -> Self {
        self.spaced = Some(true);
        self
    }

    /// Join the currency identifier directly to the amount.
    pub const fn no_space(mut self) -> Self {
        self.spaced = Some(false);
        self
    }

    /// Mark negative amounts with a leading minus sign: `-$1,500.00`.
    pub const fn minus_sign(mut self) -> Self {
        self.negative = NegativeStyle::Minus;
        self
    }

    /// Mark negative amounts accounting-style, wrapping the whole rendering
    /// in parentheses: `($1,500.00)`.
    pub const fn parentheses(mut self) -> Self {
        self.negative = NegativeStyle::Parentheses;
        self
    }

    /// Render exactly `digits` fractional digits, rounding with `mode` when
    /// the amount carries more. Without this, the fraction is padded to the
    /// currency's minor digits, any excess digits are shown in full, and
    /// nothing is ever rounded.
    pub const fn precision(mut self, digits: u32, mode: RoundingMode) -> Self {
        self.precision = Some((digits, mode));
        self
    }

    /// Group the integer digits by `pattern`, counted from the decimal mark
    /// outward, with the last entry repeating: `&[3]` gives `1,234,567` and
    /// `&[3, 2]` gives the Indian-system `12,34,567`. An empty pattern (or a
    /// zero entry, once reached) leaves the remaining digits unbroken.
    pub const fn grouping(mut self, pattern: &'static [u8]) -> Self {
        self.grouping = pattern;
        self
    }

    /// Render the integer digits as one unbroken run.
    pub const fn no_grouping(mut self) -> Self {
        self.grouping = &[];
        self
    }

    /// The characters that 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
    }
}

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

impl Money {
    /// Renders this amount as `format` describes. The result is a value for
    /// `write!`/`format!`/`to_string`, so nothing is allocated until it is
    /// actually displayed. Width, fill, and alignment flags in the
    /// surrounding format string are honored (with no explicit alignment the
    /// amount aligns right, like the numeric types); the `{:.N}` flag is
    /// ignored — fractional digits are set via [`Format::precision`], which
    /// insists on a rounding mode.
    pub fn format_with(&self, format: &Format) -> impl fmt::Display + use<> {
        Formatted {
            money: *self,
            format: *format,
        }
    }
}

/// Renders as [`Format::default`] describes: `1,500.00 USD`.
impl fmt::Display for Money {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.format_with(&Format::default()), f)
    }
}

struct Formatted {
    money: Money,
    format: Format,
}

impl fmt::Display for Formatted {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let rendered = self.render();
        let Some(width) = f.width() else {
            return f.write_str(&rendered);
        };

        // Padding is done by hand rather than with `Formatter::pad`, which
        // would also apply the `{:.N}` flag and truncate mid-number.
        let length = rendered.chars().count();
        if length >= width {
            return f.write_str(&rendered);
        }
        let padding = width - length;
        let (left, right) = match f.align().unwrap_or(fmt::Alignment::Right) {
            fmt::Alignment::Left => (0, padding),
            fmt::Alignment::Right => (padding, 0),
            fmt::Alignment::Center => (padding / 2, padding - padding / 2),
        };
        let fill = f.fill();
        for _ in 0..left {
            f.write_char(fill)?;
        }
        f.write_str(&rendered)?;
        for _ in 0..right {
            f.write_char(fill)?;
        }
        Ok(())
    }
}

impl Formatted {
    fn render(&self) -> String {
        let currency = self.money.currency();
        let format = &self.format;

        let amount = match format.precision {
            Some((digits, mode)) => self.money.round(digits, mode).amount(),
            None => self.money.amount(),
        };
        // A sign is only rendered when it will precede nonzero digits, so an
        // amount that is (or rounds to) negative zero shows no sign at all.
        let negative = amount.is_sign_negative() && !amount.is_zero();

        let fraction_digits = match format.precision {
            Some((digits, _)) => digits,
            None => amount.scale().max(currency.minor_digits()),
        } as usize;

        let magnitude = amount.abs();
        let scale = magnitude.scale() as usize;
        let mut digits = magnitude.mantissa().to_string();
        while digits.len() <= scale {
            digits.insert(0, '0');
        }
        let (integer, fraction) = digits.split_at(digits.len() - scale);

        let mut number = group_digits(integer, format.grouping, format.group_separator);
        if fraction_digits > 0 {
            number.push(format.decimal_separator);
            number.push_str(fraction);
            for _ in fraction.len()..fraction_digits {
                number.push('0');
            }
        }

        let code = currency.alphabetic_code();
        let (identifier, position, spaced) = match format.identifier {
            Identifier::Code => (
                Some(code.as_str()),
                format.position.unwrap_or(Position::Suffix),
                format.spaced.unwrap_or(true),
            ),
            Identifier::Symbol => (
                Some(currency.symbol()),
                format.position.unwrap_or(Position::Prefix),
                format.spaced.unwrap_or(false),
            ),
            Identifier::None => (None, Position::Prefix, false),
        };

        let mut out = String::new();
        let parenthesized = negative && matches!(format.negative, NegativeStyle::Parentheses);
        if parenthesized {
            out.push('(');
        } else if negative {
            out.push('-');
        }
        match (identifier, position) {
            (Some(identifier), Position::Prefix) => {
                out.push_str(identifier);
                if spaced {
                    out.push(' ');
                }
                out.push_str(&number);
            }
            (Some(identifier), Position::Suffix) => {
                out.push_str(&number);
                if spaced {
                    out.push(' ');
                }
                out.push_str(identifier);
            }
            (None, _) => out.push_str(&number),
        }
        if parenthesized {
            out.push(')');
        }
        out
    }
}

/// Splits a run of integer digits into separator-joined groups sized by
/// `pattern`, working from the rightmost digit outward with the last pattern
/// entry repeating indefinitely.
fn group_digits(digits: &str, pattern: &[u8], separator: char) -> String {
    let mut groups = Vec::new();
    let mut rest = digits.as_bytes();
    let mut sizes = pattern.iter().copied();
    let mut size = sizes.next().unwrap_or(0) as usize;
    while size != 0 && rest.len() > size {
        let (head, group) = rest.split_at(rest.len() - size);
        groups.push(group);
        rest = head;
        size = sizes.next().map_or(size, |s| s as usize);
    }

    let ascii = |bytes| std::str::from_utf8(bytes).expect("digits are ASCII");
    let mut out = String::from(ascii(rest));
    for group in groups.into_iter().rev() {
        out.push(separator);
        out.push_str(ascii(group));
    }
    out
}

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

    #[test]
    fn default_format_test() {
        let money = Money::from_minor(150000, &Currency::USD);

        assert_eq!(money.to_string(), "1,500.00 USD");
    }

    #[test]
    fn pads_fraction_to_minor_digits_test() {
        assert_eq!(
            Money::from_major(-3, &Currency::USD).to_string(),
            "-3.00 USD"
        );
    }

    #[test]
    fn zero_minor_digits_omit_decimal_mark_test() {
        assert_eq!(Money::from_major(5, &Currency::JPY).to_string(), "5 JPY");
    }

    #[test]
    fn excess_precision_is_shown_in_full_test() {
        let money = Money::from_decimal(dec!(1.2345), &Currency::USD);

        assert_eq!(money.to_string(), "1.2345 USD");
    }

    #[test]
    fn symbol_test() {
        let money = Money::from_minor(150000, &Currency::USD);

        assert_eq!(
            money.format_with(&Format::new().symbol()).to_string(),
            "$1,500.00"
        );
    }

    #[test]
    fn symbol_suffix_spaced_test() {
        let money = Money::from_minor(150, &Currency::USD);
        let format = Format::new().symbol().suffix().spaced();

        assert_eq!(money.format_with(&format).to_string(), "1.50 $");
    }

    #[test]
    fn code_prefix_test() {
        let money = Money::from_minor(150000, &Currency::USD);
        let format = Format::new().prefix();

        assert_eq!(money.format_with(&format).to_string(), "USD 1,500.00");
    }

    #[test]
    fn code_no_space_test() {
        let money = Money::from_minor(150, &Currency::USD);
        let format = Format::new().no_space();

        assert_eq!(money.format_with(&format).to_string(), "1.50USD");
    }

    #[test]
    fn amount_only_test() {
        let money = Money::from_minor(150000, &Currency::USD);

        assert_eq!(
            money.format_with(&Format::new().amount_only()).to_string(),
            "1,500.00"
        );
    }

    #[test]
    fn negative_symbol_test() {
        let money = Money::from_minor(-150000, &Currency::USD);

        assert_eq!(
            money.format_with(&Format::new().symbol()).to_string(),
            "-$1,500.00"
        );
    }

    #[test]
    fn parentheses_test() {
        let format = Format::new().symbol().parentheses();
        let negative = Money::from_minor(-150000, &Currency::USD);
        let positive = Money::from_minor(150000, &Currency::USD);

        assert_eq!(negative.format_with(&format).to_string(), "($1,500.00)");
        assert_eq!(positive.format_with(&format).to_string(), "$1,500.00");
    }

    #[test]
    fn minus_sign_restores_default_test() {
        let money = Money::from_minor(-150, &Currency::USD);
        let format = Format::new().parentheses().minus_sign();

        assert_eq!(money.format_with(&format).to_string(), "-1.50 USD");
    }

    #[test]
    fn precision_rounds_test() {
        let money = Money::from_decimal(dec!(2.675), &Currency::USD);

        assert_eq!(
            money
                .format_with(&Format::new().precision(2, RoundingMode::HalfUp))
                .to_string(),
            "2.68 USD"
        );
        assert_eq!(
            money
                .format_with(&Format::new().precision(2, RoundingMode::HalfDown))
                .to_string(),
            "2.67 USD"
        );
    }

    #[test]
    fn precision_pads_test() {
        let money = Money::from_major(1, &Currency::USD);
        let format = Format::new().precision(4, RoundingMode::HalfEven);

        assert_eq!(money.format_with(&format).to_string(), "1.0000 USD");
    }

    #[test]
    fn precision_zero_digits_test() {
        let money = Money::from_decimal(dec!(1500.5), &Currency::USD);
        let format = Format::new().precision(0, RoundingMode::HalfUp);

        assert_eq!(money.format_with(&format).to_string(), "1,501 USD");
    }

    #[test]
    fn rounded_to_zero_shows_no_sign_test() {
        let money = Money::from_decimal(dec!(-0.004), &Currency::USD);

        assert_eq!(
            money
                .format_with(&Format::new().precision(2, RoundingMode::HalfEven))
                .to_string(),
            "0.00 USD"
        );
        assert_eq!(
            money
                .format_with(
                    &Format::new()
                        .parentheses()
                        .precision(2, RoundingMode::HalfEven)
                )
                .to_string(),
            "0.00 USD"
        );
    }

    #[test]
    fn indian_grouping_test() {
        let money = Money::from_decimal(dec!(12345678.90), &Currency::INR);
        let format = Format::new().grouping(&[3, 2]);

        assert_eq!(money.format_with(&format).to_string(), "1,23,45,678.90 INR");
    }

    #[test]
    fn no_grouping_test() {
        let money = Money::from_major(1234567, &Currency::USD);
        let format = Format::new().no_grouping();

        assert_eq!(money.format_with(&format).to_string(), "1234567.00 USD");
    }

    #[test]
    fn separators_test() {
        let money = Money::from_minor(150000, &Currency::EUR);
        let format = Format::new().separators('.', ',');

        assert_eq!(money.format_with(&format).to_string(), "1.500,00 EUR");
    }

    #[test]
    fn width_and_alignment_test() {
        let money = Money::from_minor(150, &Currency::USD);
        let bare = Format::new().amount_only();

        assert_eq!(format!("{:8}", money.format_with(&bare)), "    1.50");
        assert_eq!(format!("{:<8}", money.format_with(&bare)), "1.50    ");
        assert_eq!(format!("{:*^8}", money.format_with(&bare)), "**1.50**");
    }

    #[test]
    fn display_honors_width_test() {
        let money = Money::from_minor(150, &Currency::USD);

        assert_eq!(format!("{money:>12}"), "    1.50 USD");
    }

    #[test]
    fn fmt_precision_flag_is_ignored_test() {
        let money = Money::from_minor(150, &Currency::USD);

        assert_eq!(format!("{money:.1}"), "1.50 USD");
    }
}