lexical_util/
assert.rs

1//! Debugging assertions to check a radix is valid.
2
3#[cfg(feature = "write")]
4use crate::constants::FormattedSize;
5use crate::format::NumberFormat;
6
7// RADIX
8
9/// Check radix is in range `[2, 36]` in debug builds.
10#[inline]
11#[cfg(feature = "radix")]
12pub fn debug_assert_radix(radix: u32) {
13    debug_assert!((2..=36).contains(&radix), "Numerical base must be from 2-36.");
14}
15
16/// Check radix is is 10 or a power of 2.
17#[inline]
18#[cfg(all(feature = "power-of-two", not(feature = "radix")))]
19pub fn debug_assert_radix(radix: u32) {
20    debug_assert!(matches!(radix, 2 | 4 | 8 | 10 | 16 | 32), "Numerical base must be from 2-36.");
21}
22
23/// Check radix is equal to 10.
24#[inline]
25#[cfg(not(feature = "power-of-two"))]
26pub fn debug_assert_radix(radix: u32) {
27    debug_assert!(radix == 10, "Numerical base must be 10.");
28}
29
30/// Assert radix is in range `[2, 36]`.
31#[inline]
32#[cfg(feature = "radix")]
33pub fn assert_radix<const FORMAT: u128>() {
34    assert!(
35        (2..=36).contains(&NumberFormat::<{ FORMAT }>::RADIX),
36        "Numerical base must be from 2-36."
37    );
38}
39
40/// Check radix is is 10 or a power of 2.
41#[inline]
42#[cfg(all(feature = "power-of-two", not(feature = "radix")))]
43pub fn assert_radix<const FORMAT: u128>() {
44    assert!(
45        matches!(NumberFormat::<{ FORMAT }>::RADIX, 2 | 4 | 8 | 10 | 16 | 32),
46        "Numerical base must be from 2, 4, 8, 10, 16, or 32."
47    );
48}
49
50/// Check radix is equal to 10.
51#[inline]
52#[cfg(not(feature = "power-of-two"))]
53pub fn assert_radix<const FORMAT: u128>() {
54    assert!(NumberFormat::<{ FORMAT }>::RADIX == 10, "Numerical base must be 10.");
55}
56
57// BUFFER
58
59/// Debug assertion the buffer has sufficient room for the output.
60#[inline]
61#[cfg(feature = "write")]
62pub fn debug_assert_buffer<T: FormattedSize>(radix: u32, len: usize) {
63    debug_assert!(
64        match radix {
65            10 => len >= T::FORMATTED_SIZE_DECIMAL,
66            _ => len >= T::FORMATTED_SIZE,
67        },
68        "Buffer is too small: may overwrite buffer in release builds."
69    );
70}
71
72/// Assertion the buffer has sufficient room for the output.
73#[inline]
74#[cfg(all(feature = "power-of-two", feature = "write"))]
75pub fn assert_buffer<T: FormattedSize>(radix: u32, len: usize) {
76    assert!(
77        match radix {
78            10 => len >= T::FORMATTED_SIZE_DECIMAL,
79            _ => len >= T::FORMATTED_SIZE,
80        },
81        "Buffer is too small: may overwrite buffer, panicking!"
82    );
83}
84
85/// Assertion the buffer has sufficient room for the output.
86#[inline]
87#[cfg(all(not(feature = "power-of-two"), feature = "write"))]
88pub fn assert_buffer<T: FormattedSize>(_: u32, len: usize) {
89    assert!(
90        len >= T::FORMATTED_SIZE_DECIMAL,
91        "Buffer is too small: may overwrite buffer, panicking!"
92    );
93}