lexical_parse_float/
mask.rs

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
//! Utilities to generate bitmasks.

#![doc(hidden)]

/// Generate a bitwise mask for the lower `n` bits.
///
/// # Examples
///
/// ```rust
/// # use lexical_parse_float::mask::lower_n_mask;
/// # pub fn main() {
/// assert_eq!(lower_n_mask(2), 0b11);
/// # }
/// ```
#[must_use]
#[inline(always)]
#[allow(clippy::match_bool)] // reason="easier to visualize logic"
pub const fn lower_n_mask(n: u64) -> u64 {
    debug_assert!(n <= 64, "lower_n_mask() overflow in shl.");

    match n == 64 {
        true => u64::MAX,
        false => (1 << n) - 1,
    }
}

/// Calculate the halfway point for the lower `n` bits.
///
/// # Examples
///
/// ```rust
/// # use lexical_parse_float::mask::lower_n_halfway;
/// # pub fn main() {
/// assert_eq!(lower_n_halfway(2), 0b10);
/// # }
/// ```
#[must_use]
#[inline(always)]
#[allow(clippy::match_bool)] // reason="easier to visualize logic"
pub const fn lower_n_halfway(n: u64) -> u64 {
    debug_assert!(n <= 64, "lower_n_halfway() overflow in shl.");

    match n == 0 {
        true => 0,
        false => nth_bit(n - 1),
    }
}

/// Calculate a scalar factor of 2 above the halfway point.
///
/// # Examples
///
/// ```rust
/// # use lexical_parse_float::mask::nth_bit;
/// # pub fn main() {
/// assert_eq!(nth_bit(2), 0b100);
/// # }
/// ```
#[must_use]
#[inline(always)]
pub const fn nth_bit(n: u64) -> u64 {
    debug_assert!(n < 64, "nth_bit() overflow in shl.");
    1 << n
}