bitcoin-units 0.6.0

Basic Bitcoin numeric units such as amount
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
// SPDX-License-Identifier: CC0-1.0

//! Bitcoin amounts.
//!
//! This module mainly introduces the [`Amount`] and [`SignedAmount`] types to express the bitcoin
//! amounts supporting arithmetic, conversions between denominations and other important
//! operations.
//!
//! # The 21M limit
//!
//! Since Bitcoin itself is limited to 2 100 000 000 000 000 satoshis (a bit less in practice)
//! this type also implements the same restriction. While this may be surprising it actually
//! provides many benefits:
//!
//! * Conversions from unsigned to signed are infallible.
//! * Negation is infallible.
//! * Absolute value is infallible (though `unsigned_abs` is usually better anyway).
//! * Conversion to float is lossless.
//! * Division cannot overflow, so a division error has to be div-by-zero; thus division by
//!   `NonZeroU64` is completely infallible.
//! * Infallible conversion to `i64` allows directly storing in SQL databases.
//! * It's possible to more efficiently sum amounts using SIMD (currently unimplemented in the
//!   library).
//! * Subtraction of unsigned amounts producing a signed amount is infallible.
//! * Conversion to msat is infallible.
//!
//! Note that the signed type also restricts the minimum to -21M BTC.
//!
//! While it might seem that this comes at a cost of littering the code with range checks it is not
//! actually that bad because if the limit was not 21M btc it would've still been `u64::MAX` and
//! require effectively the same kind of handling. This library exposes range checks as if they were
//! overflow checks, so the calling code looks the same.
//!
//! Additionally, whenever an amount enters the program from outside, it already needs to be parsed
//! or decoded, so the only thing this changes about it is the error type.
//!
//! # Numeric operations
//!
//! The types implement several arithmetic operations from [`core::ops`].
//! To prevent errors due to an overflow or division by zero when using these operations, they
//! return the [`NumOpResult`] type which enforces checked arithmetic. The resulting type itself
//! implements the traits so you can write code like `a + b + c` and only check the result at the
//! end.
//!
//! [`NumOpResult`]: super::NumOpResult

mod ops;
mod signed;
#[cfg(test)]
mod tests;
mod unsigned;
#[cfg(kani)]
mod verification;

pub mod error;
#[cfg(feature = "serde")]
pub mod serde;

use core::cmp::Ordering;
use core::convert::Infallible;
use core::fmt::{self, Write as _};
use core::str::FromStr;

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};

use self::error::{MissingDigitsKind, ParseAmountErrorInner, ParseErrorInner};

#[rustfmt::skip]                // Keep public re-exports separate.
#[doc(inline)]
pub use self::{
    signed::SignedAmount,
    unsigned::Amount,
};
#[cfg(feature = "encoding")]
#[doc(no_inline)]
pub use self::error::AmountDecoderError;
#[doc(no_inline)]
pub use self::error::{
    BadPositionError, InvalidCharacterError, MissingDenominationError, MissingDigitsError,
    OutOfRangeError, ParseAmountError, ParseDenominationError, ParseError,
    PossiblyConfusingDenominationError, TooPreciseError, UnknownDenominationError,
};
#[doc(inline)]
#[cfg(feature = "encoding")]
pub use self::unsigned::{AmountDecoder, AmountEncoder};

/// A set of denominations in which amounts can be expressed.
///
/// # Accepted Denominations
///
/// All upper or lower case, excluding SI prefixes c, m and u (or µ) which must be lower case.
/// - Singular: BTC, cBTC, mBTC, uBTC
/// - Plural or singular: sat, satoshi, bit
///
/// # Note
///
/// Due to ambiguity between mega and milli we prohibit usage of leading capital 'M'. It is
/// more important to protect users from incorrectly using a capital M to mean milli than to
/// allow Megabitcoin which is not a realistic denomination, and Megasatoshi which is
/// equivalent to cBTC which is allowed.
///
/// # Examples
///
/// ```
/// # use bitcoin_units::{amount, Amount};
///
/// let equal = [
///     ("1 BTC", 100_000_000),
///     ("1 cBTC", 1_000_000),
///     ("1 mBTC", 100_000),
///     ("1 uBTC", 100),
///     ("1 bit", 100),
///     ("1 sat", 1),
/// ];
/// for (string, sats) in equal {
///     assert_eq!(
///         string.parse::<Amount>().expect("valid bitcoin amount string"),
///         Amount::from_sat(sats)?,
///     )
/// }
/// # Ok::<_, amount::OutOfRangeError>(())
/// ```
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[non_exhaustive]
#[allow(clippy::doc_markdown)]
pub enum Denomination {
    /// BTC (1 BTC = 100,000,000 satoshi).
    Bitcoin,
    /// cBTC (1 cBTC = 1,000,000 satoshi).
    CentiBitcoin,
    /// mBTC (1 mBTC = 100,000 satoshi).
    MilliBitcoin,
    /// µBTC (1 µBTC = 100 satoshi).
    MicroBitcoin,
    /// bits (bits = µBTC).
    Bit,
    /// satoshi (1 BTC = 100,000,000 satoshi).
    Satoshi,
    /// Stops users from casting this enum to an integer.
    // May get removed if one day Rust supports disabling casts natively.
    #[doc(hidden)]
    _DoNotUse(Infallible),
}

impl Denomination {
    /// Convenience alias for [`Denomination::Bitcoin`].
    pub const BTC: Self = Self::Bitcoin;

    /// Convenience alias for [`Denomination::Satoshi`].
    pub const SAT: Self = Self::Satoshi;

    /// The number of decimal places more than a satoshi.
    #[inline]
    fn precision(self) -> i8 {
        match self {
            Self::Bitcoin => -8,
            Self::CentiBitcoin => -6,
            Self::MilliBitcoin => -5,
            Self::MicroBitcoin => -2,
            Self::Bit => -2,
            Self::Satoshi => 0,
            Self::_DoNotUse(infallible) => match infallible {},
        }
    }

    /// Returns a string representation of this denomination.
    #[inline]
    fn as_str(self) -> &'static str {
        match self {
            Self::Bitcoin => "BTC",
            Self::CentiBitcoin => "cBTC",
            Self::MilliBitcoin => "mBTC",
            Self::MicroBitcoin => "uBTC",
            Self::Bit => "bits",
            Self::Satoshi => "satoshi",
            Self::_DoNotUse(infallible) => match infallible {},
        }
    }

    /// The different [`str`] forms of denominations that are recognized.
    #[inline]
    fn forms(s: &str) -> Option<Self> {
        match s {
            "BTC" | "btc" => Some(Self::Bitcoin),
            "cBTC" | "cbtc" => Some(Self::CentiBitcoin),
            "mBTC" | "mbtc" => Some(Self::MilliBitcoin),
            "uBTC" | "ubtc" | "µBTC" | "µbtc" => Some(Self::MicroBitcoin),
            "bit" | "bits" | "BIT" | "BITS" => Some(Self::Bit),
            "SATOSHI" | "satoshi" | "SATOSHIS" | "satoshis" | "SAT" | "sat" | "SATS" | "sats" =>
                Some(Self::Satoshi),
            _ => None,
        }
    }
}

/// These forms are ambiguous and could have many meanings. For example, M could denote Mega or Milli.
/// If any of these forms are used, an error type [`PossiblyConfusingDenominationError`] is
/// returned.
const CONFUSING_FORMS: [&str; 6] = ["CBTC", "Cbtc", "MBTC", "Mbtc", "UBTC", "Ubtc"];

impl fmt::Display for Denomination {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.as_str()) }
}

impl FromStr for Denomination {
    type Err = ParseDenominationError;

    /// Converts from a [`str`] to a [`Denomination`].
    ///
    /// # Errors
    ///
    /// - [`ParseDenominationError::PossiblyConfusing`]: If the denomination begins with a capital
    ///   letter that could be confused with centi, milli, or micro-bitcoin.
    /// - [`ParseDenominationError::Unknown`]: If an unknown denomination is used.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use self::ParseDenominationError as E;

        if CONFUSING_FORMS.contains(&s) {
            return Err(PossiblyConfusingDenominationError(s.into())).map_err(E::PossiblyConfusing);
        }

        let form = Self::forms(s);

        form.ok_or_else(|| E::Unknown(UnknownDenominationError(s.into())))
    }
}

/// Returns [`Some(position)`] if the precision is not supported.
///
/// The position indicates the first digit that is too precise.
///
/// [`Some(position)`]: Some
fn is_too_precise(s: &str, precision: usize) -> Option<usize> {
    match s.find('.') {
        Some(pos) if precision >= pos => Some(0),
        Some(pos) => s[..pos]
            .char_indices()
            .rev()
            .take(precision)
            .find(|(_, d)| *d != '0')
            .map(|(i, _)| i)
            .or_else(|| {
                s[(pos + 1)..].char_indices().find(|(_, d)| *d != '0').map(|(i, _)| i + pos + 1)
            }),
        None if precision >= s.len() => Some(0),
        None => s.char_indices().rev().take(precision).find(|(_, d)| *d != '0').map(|(i, _)| i),
    }
}

/// Parses a decimal string in the given denomination into a satoshi value and a
/// [`bool`] indicator for a negative amount.
///
/// The [`bool`] is only needed to distinguish -0 from 0.
#[allow(clippy::too_many_lines)]
fn parse_signed_to_satoshi(
    mut s: &str,
    denom: Denomination,
) -> Result<(bool, SignedAmount), InnerParseError> {
    /// The previously parsed character, used to validate the position of underscores.
    #[derive(Clone, Copy)]
    enum PrevChar {
        Digit,
        Underscore,
        Dot,
    }

    if s.is_empty() {
        return Err(MissingDigitsError { kind: MissingDigitsKind::Empty })
            .map_err(InnerParseError::MissingDigits);
    }

    let is_negative = s.starts_with('-');
    if is_negative {
        if s.len() == 1 {
            return Err(MissingDigitsError { kind: MissingDigitsKind::OnlyMinusSign })
                .map_err(InnerParseError::MissingDigits);
        }
        s = &s[1..];
    }

    // Inputs of `.` and `-.` are invalid.
    // `-.` is reassigned above to `.` with `is_negative = true`.
    if s == "." {
        return Err(MissingDigitsError {
            kind: MissingDigitsKind::OnlyDot { with_minus_sign: is_negative },
        })
        .map_err(InnerParseError::MissingDigits);
    }

    let max_decimals = {
        // The difference in precision between native (satoshi)
        // and desired denomination.
        let precision_diff = -denom.precision();
        if precision_diff <= 0 {
            // If precision diff is negative, this means we are parsing
            // into a less precise amount. That is not allowed unless
            // there are no decimals and the last digits are zeroes as
            // many as the difference in precision.
            let last_n = precision_diff.unsigned_abs().into();
            if let Some(position) = is_too_precise(s, last_n) {
                match s.parse::<i64>() {
                    Ok(0) => return Ok((is_negative, SignedAmount::ZERO)),
                    _ =>
                        return Err(TooPreciseError {
                            position: position + usize::from(is_negative),
                        })
                        .map_err(InnerParseError::TooPrecise),
                }
            }
            s = &s[0..s.find('.').unwrap_or(s.len()) - last_n];
            0
        } else {
            precision_diff
        }
    };

    let mut decimals = None;
    let mut prev_char: Option<PrevChar> = None;
    let mut value: i64 = 0; // as satoshis
    for (i, c) in s.char_indices() {
        match (c, prev_char) {
            // More than one decimal dot is invalid.
            ('.', _) if decimals.is_some() =>
                return Err(InvalidCharacterError {
                    invalid_char: '.',
                    position: i + usize::from(is_negative),
                })
                .map_err(InnerParseError::InvalidCharacter),
            // Underscores immediately before the decimal separator are invalid.
            ('.', Some(PrevChar::Underscore)) =>
                return Err(BadPositionError {
                    char: '_',
                    position: (i - 1) + usize::from(is_negative),
                })
                .map_err(InnerParseError::BadPosition),
            // A valid digit.
            ('0'..='9', _) => {
                // Do `value = 10 * value + digit`, catching overflows.
                match 10_i64.checked_mul(value) {
                    None => return Err(InnerParseError::Overflow { is_negative }),
                    Some(val) => match val.checked_add(i64::from(c as u8 - b'0')) {
                        None => return Err(InnerParseError::Overflow { is_negative }),
                        Some(val) => value = val,
                    },
                }
                // Increment the decimal digit counter if past decimal.
                decimals = match decimals {
                    None => None,
                    Some(d) if d < max_decimals => Some(d + 1),
                    _ =>
                        return Err(TooPreciseError { position: i + usize::from(is_negative) })
                            .map_err(InnerParseError::TooPrecise),
                };
                prev_char = Some(PrevChar::Digit);
            }
            // A valid underscore must follow a digit.
            ('_', Some(PrevChar::Digit)) => prev_char = Some(PrevChar::Underscore),
            // Underscores not after a digit, i.e. '._', '__' and leading '_', are invalid.
            ('_', _) =>
                return Err(BadPositionError { char: '_', position: i + usize::from(is_negative) })
                    .map_err(InnerParseError::BadPosition),
            // A decimal dot with a denomination that does not allow decimals is invalid.
            ('.', _) if decimals.is_none() && max_decimals <= 0 => break,
            // A valid decimal dot.
            ('.', _) if decimals.is_none() => {
                decimals = Some(0);
                prev_char = Some(PrevChar::Dot);
            }
            // Any character that does not match an above digit, dot or underscore arm is invalid.
            (c, _) =>
                return Err(InvalidCharacterError {
                    invalid_char: c,
                    position: i + usize::from(is_negative),
                })
                .map_err(InnerParseError::InvalidCharacter),
        }
    }

    // The last character must not be an underscore.
    if matches!(prev_char, Some(PrevChar::Underscore)) {
        return Err(BadPositionError {
            char: '_',
            position: (s.len() - 1) + usize::from(is_negative),
        })
        .map_err(InnerParseError::BadPosition);
    }

    // Decimally shift left by `max_decimals - decimals`.
    let scale_factor = max_decimals - decimals.unwrap_or(0);
    for _ in 0..scale_factor {
        value = match 10_i64.checked_mul(value) {
            Some(v) => v,
            None => return Err(InnerParseError::Overflow { is_negative }),
        };
    }

    let mut ret =
        SignedAmount::from_sat(value).map_err(|_| InnerParseError::Overflow { is_negative })?;
    if is_negative {
        ret = -ret;
    }
    Ok((is_negative, ret))
}

#[derive(Debug)]
enum InnerParseError {
    Overflow { is_negative: bool },
    TooPrecise(TooPreciseError),
    MissingDigits(MissingDigitsError),
    InvalidCharacter(InvalidCharacterError),
    BadPosition(BadPositionError),
}

impl From<Infallible> for InnerParseError {
    #[inline]
    fn from(never: Infallible) -> Self { match never {} }
}

impl InnerParseError {
    #[inline]
    fn convert(self, is_signed: bool) -> ParseAmountError {
        match self {
            Self::Overflow { is_negative } =>
                ParseAmountError(ParseAmountErrorInner::OutOfRange(OutOfRangeError {
                    is_signed,
                    is_greater_than_max: !is_negative,
                })),
            Self::TooPrecise(e) => ParseAmountError(ParseAmountErrorInner::TooPrecise(e)),
            Self::MissingDigits(e) => ParseAmountError(ParseAmountErrorInner::MissingDigits(e)),
            Self::InvalidCharacter(e) =>
                ParseAmountError(ParseAmountErrorInner::InvalidCharacter(e)),
            Self::BadPosition(e) => ParseAmountError(ParseAmountErrorInner::BadPosition(e)),
        }
    }
}

fn split_amount_and_denomination(s: &str) -> Result<(&str, Denomination), ParseError> {
    let (i, j) = if let Some(i) = s.find(' ') {
        (i, i + 1)
    } else {
        let i = s
            .find(|c: char| c.is_alphabetic())
            .ok_or(MissingDenominationError)
            .map_err(ParseErrorInner::MissingDenomination)
            .map_err(ParseError)?;
        (i, i)
    };
    Ok((&s[..i], s[j..].parse().map_err(ParseErrorInner::Denomination).map_err(ParseError)?))
}

/// Options given by [`fmt::Formatter`]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
struct FormatOptions {
    fill: char,
    align: Option<fmt::Alignment>,
    width: Option<usize>,
    precision: Option<usize>,
    sign_plus: bool,
    sign_aware_zero_pad: bool,
}

impl FormatOptions {
    #[inline]
    fn from_formatter(f: &fmt::Formatter) -> Self {
        Self {
            fill: f.fill(),
            align: f.align(),
            width: f.width(),
            precision: f.precision(),
            sign_plus: f.sign_plus(),
            sign_aware_zero_pad: f.sign_aware_zero_pad(),
        }
    }
}

impl Default for FormatOptions {
    #[inline]
    fn default() -> Self {
        Self {
            fill: ' ',
            align: None,
            width: None,
            precision: None,
            sign_plus: false,
            sign_aware_zero_pad: false,
        }
    }
}

fn dec_width(mut num: u64) -> usize {
    let mut width = 1;
    loop {
        num /= 10;
        if num == 0 {
            break;
        }
        width += 1;
    }
    width
}

fn repeat_char(f: &mut fmt::Formatter, c: char, count: usize) -> fmt::Result {
    for _ in 0..count {
        f.write_char(c)?;
    }
    Ok(())
}

/// Formats the given satoshi amount in the given denomination.
fn fmt_satoshi_in(
    mut satoshi: u64,
    negative: bool,
    f: &mut fmt::Formatter,
    denom: Denomination,
    show_denom: bool,
    options: FormatOptions,
) -> fmt::Result {
    let precision = denom.precision();
    // First we normalize the number:
    // {num_before_decimal_point}{:0exp}{"." if nb_decimals > 0}{:0nb_decimals}{num_after_decimal_point}{:0trailing_decimal_zeros}
    let mut num_after_decimal_point = 0;
    let mut norm_nb_decimals = 0;
    let mut num_before_decimal_point = satoshi;
    let mut exp = 0;
    let trailing_decimal_zeros = match precision.cmp(&0) {
        // We add the number of zeroes to the end
        Ordering::Greater => {
            if satoshi > 0 {
                exp = precision as usize; // Cast ok, checked not negative above.
            }
            options.precision.unwrap_or(0)
        }
        Ordering::Less => {
            let precision = precision.unsigned_abs();
            // round the number if needed
            // rather than fiddling with chars, we just modify satoshi and let the simpler algorithm take over.
            if let Some(format_precision) = options.precision {
                if usize::from(precision) > format_precision {
                    // precision is u8 so in this branch options.precision() < 255 which fits in u32
                    let rounding_divisor =
                        10u64.pow(u32::from(precision) - format_precision as u32); // Cast ok, commented above.
                    let remainder = satoshi % rounding_divisor;
                    satoshi -= remainder;
                    if remainder / (rounding_divisor / 10) >= 5 {
                        satoshi += rounding_divisor;
                    }
                }
            }
            let divisor = 10u64.pow(precision.into());
            num_before_decimal_point = satoshi / divisor;
            num_after_decimal_point = satoshi % divisor;
            // normalize by stripping trailing zeros
            if num_after_decimal_point == 0 {
                norm_nb_decimals = 0;
            } else {
                norm_nb_decimals = usize::from(precision);
                while num_after_decimal_point % 10 == 0 {
                    norm_nb_decimals -= 1;
                    num_after_decimal_point /= 10;
                }
            }
            // compute requested precision
            let opt_precision = options.precision.unwrap_or(0);
            opt_precision.saturating_sub(norm_nb_decimals)
        }
        Ordering::Equal => options.precision.unwrap_or(0),
    };
    let total_decimals = norm_nb_decimals + trailing_decimal_zeros;
    // Compute expected width of the number
    let mut num_width = if total_decimals > 0 {
        // 1 for decimal point
        1 + total_decimals
    } else {
        0
    };
    num_width += dec_width(num_before_decimal_point) + exp;
    if options.sign_plus || negative {
        num_width += 1;
    }

    if show_denom {
        // + 1 for space
        num_width += denom.as_str().len() + 1;
    }

    let width = options.width.unwrap_or(0);
    let align = options.align.unwrap_or(fmt::Alignment::Right);
    let (left_pad, pad_right) = match (num_width < width, options.sign_aware_zero_pad, align) {
        (false, _, _) => (0, 0),
        // Alignment is always right (ignored) when zero-padding
        (true, true, _) | (true, false, fmt::Alignment::Right) => (width - num_width, 0),
        (true, false, fmt::Alignment::Left) => (0, width - num_width),
        // If the required padding is odd it needs to be skewed to the left
        (true, false, fmt::Alignment::Center) =>
            ((width - num_width) / 2, (width - num_width).div_ceil(2)),
    };

    if !options.sign_aware_zero_pad {
        repeat_char(f, options.fill, left_pad)?;
    }

    if negative {
        write!(f, "-")?;
    } else if options.sign_plus {
        write!(f, "+")?;
    }

    if options.sign_aware_zero_pad {
        repeat_char(f, '0', left_pad)?;
    }

    write!(f, "{}", num_before_decimal_point)?;

    repeat_char(f, '0', exp)?;

    if total_decimals > 0 {
        write!(f, ".")?;
    }
    if norm_nb_decimals > 0 {
        write!(f, "{:0width$}", num_after_decimal_point, width = norm_nb_decimals)?;
    }
    repeat_char(f, '0', trailing_decimal_zeros)?;

    if show_denom {
        write!(f, " {}", denom.as_str())?;
    }

    repeat_char(f, options.fill, pad_right)?;
    Ok(())
}

/// A helper/builder that displays amount with specified settings.
///
/// This provides richer interface than [`fmt::Formatter`]:
///
/// * Ability to select denomination
/// * Show or hide denomination
/// * Dynamically-selected denomination - show in sats if less than 1 BTC.
///
/// However, this can still be combined with [`fmt::Formatter`] options to precisely control zeros,
/// padding, alignment... The formatting works like floats from `core`.
///
/// Note: This implementation is currently **unstable**. The only thing that we can promise is that
/// unless the precision is changed, this will display an accurate, human-readable number, and the
/// default serialization (one with unmodified [`fmt::Formatter`] options) will round-trip with [`FromStr`].
///
/// See [`Amount::display_in`] and [`Amount::display_dynamic`] on how to construct this.
#[derive(Debug, Clone)]
pub struct Display {
    /// Absolute value of satoshis to display (sign is below)
    sats_abs: u64,
    /// The sign
    is_negative: bool,
    /// How to display the value
    style: DisplayStyle,
}

impl Display {
    /// Makes subsequent calls to [`Display::fmt`] display denomination.
    ///
    /// [`Display::fmt`]: fmt::Display::fmt
    #[inline]
    #[must_use]
    pub fn show_denomination(mut self) -> Self {
        match &mut self.style {
            DisplayStyle::FixedDenomination { show_denomination, .. } => *show_denomination = true,
            // No-op because dynamic denomination is always shown
            DisplayStyle::DynamicDenomination => (),
        }
        self
    }
}

impl fmt::Display for Display {
    #[inline]
    #[rustfmt::skip]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let format_options = FormatOptions::from_formatter(f);
        match &self.style {
            DisplayStyle::FixedDenomination { show_denomination, denomination } => {
                fmt_satoshi_in(self.sats_abs, self.is_negative, f, *denomination, *show_denomination, format_options)
            },
            DisplayStyle::DynamicDenomination if self.sats_abs >= Amount::ONE_BTC.to_sat() => {
                fmt_satoshi_in(self.sats_abs, self.is_negative, f, Denomination::Bitcoin, true, format_options)
            },
            DisplayStyle::DynamicDenomination => {
                fmt_satoshi_in(self.sats_abs, self.is_negative, f, Denomination::Satoshi, true, format_options)
            },
        }
    }
}

#[derive(Clone, Debug)]
enum DisplayStyle {
    FixedDenomination { denomination: Denomination, show_denomination: bool },
    DynamicDenomination,
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for Denomination {
    #[inline]
    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
        let choice = u.int_in_range(0..=5)?;
        match choice {
            0 => Ok(Self::Bitcoin),
            1 => Ok(Self::CentiBitcoin),
            2 => Ok(Self::MilliBitcoin),
            3 => Ok(Self::MicroBitcoin),
            4 => Ok(Self::Bit),
            _ => Ok(Self::Satoshi),
        }
    }
}