bitcoin-units 0.3.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
// SPDX-License-Identifier: CC0-1.0

//! Parsing utilities.

use core::convert::Infallible;
use core::fmt;
use core::str::FromStr;

use internals::error::InputString;
use internals::write_err;

/// Error with rich context returned when a string can't be parsed as an integer.
///
/// This is an extension of [`core::num::ParseIntError`], which carries the input that failed to
/// parse as well as type information. As a result it provides very informative error messages that
/// make it easier to understand the problem and correct mistakes.
///
/// Note that this is larger than the type from `core` so if it's passed through a deep call stack
/// in a performance-critical application you may want to box it or throw away the context by
/// converting to `core` type.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ParseIntError {
    pub(crate) input: InputString,
    // for displaying - see Display impl with nice error message below
    pub(crate) bits: u8,
    // We could represent this as a single bit, but it wouldn't actually decrease the cost of moving
    // the struct because String contains pointers so there will be padding of bits at least
    // pointer_size - 1 bytes: min 1B in practice.
    pub(crate) is_signed: bool,
    pub(crate) source: core::num::ParseIntError,
}

impl fmt::Display for ParseIntError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let signed = if self.is_signed { "signed" } else { "unsigned" };
        write_err!(f, "{} ({}, {}-bit)", self.input.display_cannot_parse("integer"), signed, self.bits; self.source)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseIntError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.source) }
}

impl From<ParseIntError> for core::num::ParseIntError {
    fn from(value: ParseIntError) -> Self { value.source }
}

impl AsRef<core::num::ParseIntError> for ParseIntError {
    fn as_ref(&self) -> &core::num::ParseIntError { &self.source }
}

/// Not strictly necessary but serves as a lint - avoids weird behavior if someone accidentally
/// passes non-integer to the `parse()` function.
// This trait is not dyn-compatible because `FromStr` is not dyn-compatible.
pub trait Integer:
    FromStr<Err = core::num::ParseIntError> + TryFrom<i8> + Sized + sealed::Sealed
{
}

macro_rules! impl_integer {
    ($($type:ty),* $(,)?) => {
        $(
        impl Integer for $type {}
        impl sealed::Sealed for $type {}
        )*
    }
}

impl_integer!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);

mod sealed {
    /// Seals the `Integer` trait.
    pub trait Sealed {}
}

/// Parses the input string as an integer returning an error carrying rich context.
///
/// Apart from the rich error context this function exists so that we can handle builds with and
/// without an allocator. If an allocator is available (`alloc` feature enabled) then this function
/// allocates to copy the input string into the error return. If `alloc` is not enabled the input
/// string is lost.
///
/// If the caller has a `String` or `Box<str>` which is not used later it's better to call
/// [`parse_int::int_from_string`] or [`parse_int::int_from_box`] respectively.
///
/// [`parse_int::int_from_string`]: crate::parse_int::int_from_string
/// [`parse_int::int_from_box`]: crate::parse_int::int_from_box
///
/// # Errors
///
/// On error this function allocates to copy the input string into the error return.
pub fn int_from_str<T: Integer>(s: &str) -> Result<T, ParseIntError> { int(s) }

/// Parses the input string as an integer returning an error carrying rich context.
///
/// # Errors
///
/// On error the input string is moved into the error return without allocating.
#[cfg(feature = "alloc")]
pub fn int_from_string<T: Integer>(s: alloc::string::String) -> Result<T, ParseIntError> { int(s) }

/// Parses the input string as an integer returning an error carrying rich context.
///
/// # Errors
///
/// On error the input string is converted into the error return without allocating.
#[cfg(feature = "alloc")]
pub fn int_from_box<T: Integer>(s: alloc::boxed::Box<str>) -> Result<T, ParseIntError> { int(s) }

// This must be private because we do not want `InputString` to appear in the public API.
fn int<T: Integer, S: AsRef<str> + Into<InputString>>(s: S) -> Result<T, ParseIntError> {
    s.as_ref().parse().map_err(|error| {
        ParseIntError {
            input: s.into(),
            bits: u8::try_from(core::mem::size_of::<T>() * 8).expect("max is 128 bits for u128"),
            // We detect if the type is signed by checking if -1 can be represented by it
            // this way we don't have to implement special traits and optimizer will get rid of the
            // computation.
            is_signed: T::try_from(-1i8).is_ok(),
            source: error,
        }
    })
}

/// Implements standard parsing traits for `$type` by calling `parse::int`.
///
/// Once the string is converted to an integer the infallible conversion function `fn` is used to
/// construct the type `to`.
///
/// Implements:
///
/// * `FromStr`
/// * `TryFrom<&str>`
///
/// And if `alloc` feature is enabled in calling crate:
///
/// * `TryFrom<Box<str>>`
/// * `TryFrom<String>`
///
/// # Parameters
///
/// * `to` - the type converted to e.g., `impl From<&str> for $to`.
/// * `err` - the error type returned by `$inner_fn` (implies returned by `FromStr` and `TryFrom`).
/// * `fn`: the infallible conversion function to call to convert from an integer.
///
/// # Errors
///
/// If parsing the string fails then a `units::parse::ParseIntError` is returned.
macro_rules! impl_parse_str_from_int_infallible {
    ($to:ident, $inner:ident, $fn:ident) => {
        impl $crate::_export::_core::str::FromStr for $to {
            type Err = $crate::parse_int::ParseIntError;

            fn from_str(s: &str) -> $crate::_export::_core::result::Result<Self, Self::Err> {
                $crate::_export::_core::convert::TryFrom::try_from(s)
            }
        }

        impl $crate::_export::_core::convert::TryFrom<&str> for $to {
            type Error = $crate::parse_int::ParseIntError;

            fn try_from(s: &str) -> $crate::_export::_core::result::Result<Self, Self::Error> {
                $crate::parse_int::int_from_str::<$inner>(s).map($to::$fn)
            }
        }

        #[cfg(feature = "alloc")]
        impl $crate::_export::_core::convert::TryFrom<alloc::string::String> for $to {
            type Error = $crate::parse_int::ParseIntError;

            fn try_from(
                s: alloc::string::String,
            ) -> $crate::_export::_core::result::Result<Self, Self::Error> {
                $crate::parse_int::int_from_string::<$inner>(s).map($to::$fn)
            }
        }

        #[cfg(feature = "alloc")]
        impl $crate::_export::_core::convert::TryFrom<alloc::boxed::Box<str>> for $to {
            type Error = $crate::parse_int::ParseIntError;

            fn try_from(
                s: alloc::boxed::Box<str>,
            ) -> $crate::_export::_core::result::Result<Self, Self::Error> {
                $crate::parse_int::int_from_box::<$inner>(s).map($to::$fn)
            }
        }
    };
}
pub(crate) use impl_parse_str_from_int_infallible;

/// Implements standard parsing traits for `$type` by calling through to `$inner_fn`.
///
/// Implements:
///
/// * `FromStr`
/// * `TryFrom<&str>`
///
/// And if `alloc` feature is enabled in calling crate:
///
/// * `TryFrom<Box<str>>`
/// * `TryFrom<String>`
///
/// # Parameters
///
/// * `to` - the type converted to e.g., `impl From<&str> for $to`.
/// * `err` - the error type returned by `$inner_fn` (implies returned by `FromStr` and `TryFrom`).
/// * `inner_fn`: the fallible conversion function to call to convert from a string reference.
///
/// # Errors
///
/// All functions use the error returned by `$inner_fn`.
macro_rules! impl_parse_str {
    ($to:ty, $err:ty, $inner_fn:expr) => {
        $crate::parse_int::impl_tryfrom_str!(&str, $to, $err, $inner_fn);
        #[cfg(feature = "alloc")]
        $crate::parse_int::impl_tryfrom_str!(alloc::string::String, $to, $err, $inner_fn; alloc::boxed::Box<str>, $to, $err, $inner_fn);

        impl $crate::_export::_core::str::FromStr for $to {
            type Err = $err;

            fn from_str(s: &str) -> $crate::_export::_core::result::Result<Self, Self::Err> {
                $inner_fn(s)
            }
        }
    }
}
pub(crate) use impl_parse_str;

/// Implements `TryFrom<$from> for $to`.
macro_rules! impl_tryfrom_str {
    ($($from:ty, $to:ty, $err:ty, $inner_fn:expr);*) => {
        $(
            impl $crate::_export::_core::convert::TryFrom<$from> for $to {
                type Error = $err;

                fn try_from(s: $from) -> $crate::_export::_core::result::Result<Self, Self::Error> {
                    $inner_fn(s)
                }
            }
        )*
    }
}
pub(crate) use impl_tryfrom_str;

/// Removes the prefix `0x` (or `0X`) from a hex string.
///
/// # Errors
///
/// If the input string does not contain a prefix.
pub fn hex_remove_prefix(s: &str) -> Result<&str, PrefixedHexError> {
    if let Some(checked) = s.strip_prefix("0x") {
        Ok(checked)
    } else if let Some(checked) = s.strip_prefix("0X") {
        Ok(checked)
    } else {
        Err(MissingPrefixError::new(s).into())
    }
}

/// Checks a hex string does not have a prefix `0x` (or `0X`).
///
/// # Errors
///
/// If the input string contains a prefix.
pub fn hex_check_unprefixed(s: &str) -> Result<&str, UnprefixedHexError> {
    if s.starts_with("0x") || s.starts_with("0X") {
        return Err(ContainsPrefixError::new(s).into());
    }
    Ok(s)
}

/// Parses a `u32` from a hex string.
///
/// Input string may or may not contain a `0x` (or `0X`) prefix.
///
/// # Errors
///
/// If the input string is not a valid hex encoding of a `u32`.
pub fn hex_u32(s: &str) -> Result<u32, ParseIntError> {
    let unchecked = hex_remove_optional_prefix(s);
    hex_u32_unchecked(unchecked)
}

/// Parses a `u32` from a prefixed hex string.
///
/// # Errors
///
/// - If the input string does not contain a `0x` (or `0X`) prefix.
/// - If the input string is not a valid hex encoding of a `u32`.
pub fn hex_u32_prefixed(s: &str) -> Result<u32, PrefixedHexError> {
    let checked = hex_remove_prefix(s)?;
    Ok(hex_u32_unchecked(checked)?)
}

/// Parses a `u32` from an unprefixed hex string.
///
/// # Errors
///
/// - If the input string contains a `0x` (or `0X`) prefix.
/// - If the input string is not a valid hex encoding of a `u32`.
pub fn hex_u32_unprefixed(s: &str) -> Result<u32, UnprefixedHexError> {
    let checked = hex_check_unprefixed(s)?;
    Ok(hex_u32_unchecked(checked)?)
}

/// Parses a `u32` from an unprefixed hex string without first checking for a prefix.
///
/// # Errors
///
/// - If the input string contains a `0x` (or `0X`) prefix, returns `InvalidDigit` due to the `x`.
/// - If the input string is not a valid hex encoding of a `u32`.
pub fn hex_u32_unchecked(s: &str) -> Result<u32, ParseIntError> {
    u32::from_str_radix(s, 16).map_err(|error| ParseIntError {
        input: s.into(),
        bits: 32,
        is_signed: false,
        source: error,
    })
}

/// Parses a `u128` from a hex string.
///
/// Input string may or may not contain a `0x` (or `0X`) prefix.
///
/// # Errors
///
/// If the input string is not a valid hex encoding of a `u128`.
pub fn hex_u128(s: &str) -> Result<u128, ParseIntError> {
    let unchecked = hex_remove_optional_prefix(s);
    hex_u128_unchecked(unchecked)
}

/// Parses a `u128` from a prefixed hex string.
///
/// # Errors
///
/// - If the input string does not contain a `0x` (or `0X`) prefix.
/// - If the input string is not a valid hex encoding of a `u128`.
pub fn hex_u128_prefixed(s: &str) -> Result<u128, PrefixedHexError> {
    let checked = hex_remove_prefix(s)?;
    Ok(hex_u128_unchecked(checked)?)
}

/// Parses a `u128` from an unprefixed hex string.
///
/// # Errors
///
/// - If the input string contains a `0x` (or `0X`) prefix.
/// - If the input string is not a valid hex encoding of a `u128`.
pub fn hex_u128_unprefixed(s: &str) -> Result<u128, UnprefixedHexError> {
    let checked = hex_check_unprefixed(s)?;
    Ok(hex_u128_unchecked(checked)?)
}

/// Parses a `u128` from an unprefixed hex string without first checking for a prefix.
///
/// # Errors
///
/// - If the input string contains a `0x` (or `0X`) prefix, returns `InvalidDigit` due to the `x`.
/// - If the input string is not a valid hex encoding of a `u128`.
pub fn hex_u128_unchecked(s: &str) -> Result<u128, ParseIntError> {
    u128::from_str_radix(s, 16).map_err(|error| ParseIntError {
        input: s.into(),
        bits: 128,
        is_signed: false,
        source: error,
    })
}

/// Strips the hex prefix off `s` if one is present.
pub(crate) fn hex_remove_optional_prefix(s: &str) -> &str {
    if let Some(stripped) = s.strip_prefix("0x") {
        stripped
    } else if let Some(stripped) = s.strip_prefix("0X") {
        stripped
    } else {
        s
    }
}

/// Error returned when parsing an integer from a hex string that is supposed to contain a prefix.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PrefixedHexError(PrefixedHexErrorInner);

/// Error returned when parsing an integer from a hex string that is supposed to contain a prefix.
#[derive(Debug, Clone, Eq, PartialEq)]
enum PrefixedHexErrorInner {
    /// Hex string is missing prefix.
    MissingPrefix(MissingPrefixError),
    /// Error parsing integer from hex string.
    ParseInt(ParseIntError),
}

impl From<Infallible> for PrefixedHexError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl From<Infallible> for PrefixedHexErrorInner {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for PrefixedHexError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use PrefixedHexErrorInner as E;

        match self.0 {
            E::MissingPrefix(ref e) => write_err!(f, "hex string is missing prefix"; e),
            E::ParseInt(ref e) => write_err!(f, "prefixed hex string invalid int"; e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for PrefixedHexError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use PrefixedHexErrorInner as E;

        match self.0 {
            E::MissingPrefix(ref e) => Some(e),
            E::ParseInt(ref e) => Some(e),
        }
    }
}

impl From<MissingPrefixError> for PrefixedHexError {
    fn from(e: MissingPrefixError) -> Self { Self(PrefixedHexErrorInner::MissingPrefix(e)) }
}

impl From<ParseIntError> for PrefixedHexError {
    fn from(e: ParseIntError) -> Self { Self(PrefixedHexErrorInner::ParseInt(e)) }
}

/// Error returned when parsing an integer from a hex string that is not supposed to contain a prefix.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct UnprefixedHexError(UnprefixedHexErrorInner);

#[derive(Debug, Clone, Eq, PartialEq)]
enum UnprefixedHexErrorInner {
    /// Hex string contains prefix.
    ContainsPrefix(ContainsPrefixError),
    /// Error parsing integer from string.
    ParseInt(ParseIntError),
}

impl From<Infallible> for UnprefixedHexError {
    fn from(never: Infallible) -> Self { match never {} }
}

impl From<Infallible> for UnprefixedHexErrorInner {
    fn from(never: Infallible) -> Self { match never {} }
}

impl fmt::Display for UnprefixedHexError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use UnprefixedHexErrorInner as E;

        match self.0 {
            E::ContainsPrefix(ref e) => write_err!(f, "hex string is contains prefix"; e),
            E::ParseInt(ref e) => write_err!(f, "hex string parse int"; e),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for UnprefixedHexError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        use UnprefixedHexErrorInner as E;

        match self.0 {
            E::ContainsPrefix(ref e) => Some(e),
            E::ParseInt(ref e) => Some(e),
        }
    }
}

impl From<ContainsPrefixError> for UnprefixedHexError {
    fn from(e: ContainsPrefixError) -> Self { Self(UnprefixedHexErrorInner::ContainsPrefix(e)) }
}

impl From<ParseIntError> for UnprefixedHexError {
    fn from(e: ParseIntError) -> Self { Self(UnprefixedHexErrorInner::ParseInt(e)) }
}

/// Error returned when a hex string is missing a prefix (e.g. `0x`).
#[derive(Debug, Clone, Eq, PartialEq)]
struct MissingPrefixError {
    hex: InputString,
}

impl MissingPrefixError {
    /// Constructs a new error from the string with the missing prefix.
    pub(crate) fn new(hex: &str) -> Self { Self { hex: hex.into() } }
}

impl fmt::Display for MissingPrefixError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} because it is missing the '0x' prefix", self.hex.display_cannot_parse("hex"))
    }
}

#[cfg(feature = "std")]
impl std::error::Error for MissingPrefixError {}

/// Error when hex string contains a prefix (e.g. 0x).
#[derive(Debug, Clone, Eq, PartialEq)]
struct ContainsPrefixError {
    hex: InputString,
}

impl ContainsPrefixError {
    /// Constructs a new error from the string that contains the prefix.
    pub(crate) fn new(hex: &str) -> Self { Self { hex: hex.into() } }
}

impl fmt::Display for ContainsPrefixError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} because it contains the '0x' prefix", self.hex.display_cannot_parse("hex"))
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ContainsPrefixError {}

#[cfg(test)]
mod tests {
    #[cfg(feature = "std")]
    use std::panic;

    use super::*;

    #[test]
    fn parse_int() {
        assert!(int_from_str::<u8>("1").is_ok());
        let _ = int_from_str::<i8>("not a number").map_err(|e| assert!(e.is_signed));
        let _ = int_from_str::<u8>("not a number").map_err(|e| assert!(!e.is_signed));
    }

    #[test]
    #[cfg(feature = "std")]
    fn parse_int_panic_when_populating_bits() {
        // Fields in the test type are never used
        #[allow(dead_code)]
        struct TestTypeLargerThanU128(u128, u128);
        impl_integer!(TestTypeLargerThanU128);
        impl FromStr for TestTypeLargerThanU128 {
            type Err = core::num::ParseIntError;

            fn from_str(_: &str) -> Result<Self, Self::Err> {
                "Always invalid for testing".parse::<u32>().map(|_| Self(0, 0))
            }
        }
        impl From<i8> for TestTypeLargerThanU128 {
            fn from(_: i8) -> Self { Self(0, 0) }
        }

        let result = panic::catch_unwind(|| int_from_str::<TestTypeLargerThanU128>("not a number"));
        assert!(result.is_err());
    }

    #[test]
    fn remove_prefix() {
        let lower = "0xhello";
        assert_eq!(hex_remove_prefix(lower).unwrap(), "hello");

        let upper = "0Xhello";
        assert_eq!(hex_remove_prefix(upper).unwrap(), "hello");

        let err = "error";
        assert!(hex_remove_prefix(err).is_err());
    }

    #[test]
    fn check_unprefixed() {
        let lower = "0xhello";
        assert!(hex_check_unprefixed(lower).is_err());

        let upper = "0Xhello";
        assert!(hex_check_unprefixed(upper).is_err());

        let valid = "hello";
        assert_eq!(hex_check_unprefixed(valid).unwrap(), "hello");
    }

    #[test]
    fn parse_u32_from_hex_prefixed() {
        let want = 171;
        let got = hex_u32("0xab").expect("failed to parse prefixed hex");
        assert_eq!(got, want);
    }

    #[test]
    fn parse_u32_from_hex_prefixed_upper() {
        let want = 171;
        let got = hex_u32("0XAB").expect("failed to parse prefixed hex");
        assert_eq!(got, want);
    }

    #[test]
    fn parse_u32_from_hex_no_prefix() {
        let want = 171;
        let got = hex_u32("ab").expect("failed to parse non-prefixed hex");
        assert_eq!(got, want);
    }

    #[test]
    fn parse_hex_u32_prefixed() {
        let want = 171; // 0xab
        assert_eq!(hex_u32_prefixed("0xab").unwrap(), want);
        assert!(hex_u32_unprefixed("0xab").is_err());
    }

    #[test]
    fn parse_hex_u32_upper_prefixed() {
        let want = 171; // 0xab
        assert_eq!(hex_u32_prefixed("0Xab").unwrap(), want);
        assert!(hex_u32_unprefixed("0Xab").is_err());
    }

    #[test]
    fn parse_hex_u32_unprefixed() {
        let want = 171; // 0xab
        assert_eq!(hex_u32_unprefixed("ab").unwrap(), want);
        assert!(hex_u32_prefixed("ab").is_err());
    }

    #[test]
    fn parse_u128_from_hex_prefixed() {
        let want = 3_735_928_559;
        let got = hex_u128("0xdeadbeef").expect("failed to parse prefixed hex");
        assert_eq!(got, want);
    }

    #[test]
    fn parse_u128_from_hex_upper_prefixed() {
        let want = 3_735_928_559;
        let got = hex_u128("0Xdeadbeef").expect("failed to parse prefixed hex");
        assert_eq!(got, want);
    }

    #[test]
    fn parse_u128_from_hex_no_prefix() {
        let want = 3_735_928_559;
        let got = hex_u128("deadbeef").expect("failed to parse non-prefixed hex");
        assert_eq!(got, want);
    }

    #[test]
    fn parse_hex_u128_prefixed() {
        let want = 3_735_928_559;
        assert_eq!(hex_u128_prefixed("0xdeadbeef").unwrap(), want);
        assert!(hex_u128_unprefixed("0xdeadbeef").is_err());
    }

    #[test]
    fn parse_hex_u128_upper_prefixed() {
        let want = 3_735_928_559;
        assert_eq!(hex_u128_prefixed("0Xdeadbeef").unwrap(), want);
        assert!(hex_u128_unprefixed("0Xdeadbeef").is_err());
    }

    #[test]
    fn parse_hex_u128_unprefixed() {
        let want = 3_735_928_559;
        assert_eq!(hex_u128_unprefixed("deadbeef").unwrap(), want);
        assert!(hex_u128_prefixed("deadbeef").is_err());
    }

    #[test]
    fn parse_u32_from_hex_unchecked_errors_on_prefix() {
        assert!(hex_u32_unchecked("0xab").is_err());
        assert!(hex_u32_unchecked("0Xab").is_err());
    }

    #[test]
    fn parse_u32_from_hex_unchecked_errors_on_overflow() {
        assert!(hex_u32_unchecked("1234abcd").is_ok());
        assert!(hex_u32_unchecked("1234abcd1").is_err());
    }

    #[test]
    fn parse_u128_from_hex_unchecked_errors_on_prefix() {
        assert!(hex_u128_unchecked("0xdeadbeef").is_err());
        assert!(hex_u128_unchecked("0Xdeadbeef").is_err());
    }

    #[test]
    fn parse_u128_from_hex_unchecked_errors_on_overflow() {
        assert!(hex_u128_unchecked("deadbeefabcdffffdeadbeefabcdffff").is_ok());
        assert!(hex_u128_unchecked("deadbeefabcdffffdeadbeefabcdffff1").is_err());
    }
}