Skip to main content

core/num/imp/
int_log10.rs

1//! These functions compute the integer logarithm of their type, assuming
2//! that someone has already checked that the value is strictly positive.
3
4use crate::num::NonZero;
5
6// 0 < val <= u8::MAX
7#[inline]
8#[ferrocene::prevalidated]
9const fn u8_impl(val: u8) -> u32 {
10    let val = val as u32;
11
12    // For better performance, avoid branches by assembling the solution
13    // in the bits above the low 8 bits.
14
15    // Adding c1 to val gives 10 in the top bits for val < 10, 11 for val >= 10
16    const C1: u32 = 0b11_00000000 - 10; // 758
17    // Adding c2 to val gives 01 in the top bits for val < 100, 10 for val >= 100
18    const C2: u32 = 0b10_00000000 - 100; // 412
19
20    // Value of top bits:
21    //            +c1  +c2  1&2
22    //     0..=9   10   01   00 = 0
23    //   10..=99   11   01   01 = 1
24    // 100..=255   11   10   10 = 2
25    ((val + C1) & (val + C2)) >> 8
26}
27
28// 0 < val < 100_000
29#[inline]
30#[ferrocene::prevalidated]
31const fn less_than_5(val: u32) -> u32 {
32    // Similar to u8, when adding one of these constants to val,
33    // we get two possible bit patterns above the low 17 bits,
34    // depending on whether val is below or above the threshold.
35    const C1: u32 = 0b011_00000000000000000 - 10; // 393206
36    const C2: u32 = 0b100_00000000000000000 - 100; // 524188
37    const C3: u32 = 0b111_00000000000000000 - 1000; // 916504
38    const C4: u32 = 0b100_00000000000000000 - 10000; // 514288
39
40    // Value of top bits:
41    //                +c1  +c2  1&2  +c3  +c4  3&4   ^
42    //         0..=9  010  011  010  110  011  010  000 = 0
43    //       10..=99  011  011  011  110  011  010  001 = 1
44    //     100..=999  011  100  000  110  011  010  010 = 2
45    //   1000..=9999  011  100  000  111  011  011  011 = 3
46    // 10000..=99999  011  100  000  111  100  100  100 = 4
47    (((val + C1) & (val + C2)) ^ ((val + C3) & (val + C4))) >> 17
48}
49
50// 0 < val <= u16::MAX
51#[inline]
52#[ferrocene::prevalidated]
53const fn u16_impl(val: u16) -> u32 {
54    less_than_5(val as u32)
55}
56
57// 0 < val <= u32::MAX
58#[inline]
59#[ferrocene::prevalidated]
60const fn u32_impl(mut val: u32) -> u32 {
61    let mut log = 0;
62    if val >= 100_000 {
63        val /= 100_000;
64        log += 5;
65    }
66    log + less_than_5(val)
67}
68
69// 0 < val <= u64::MAX
70#[inline]
71#[ferrocene::prevalidated]
72const fn u64_impl(mut val: u64) -> u32 {
73    let mut log = 0;
74    if val >= 10_000_000_000 {
75        val /= 10_000_000_000;
76        log += 10;
77    }
78    if val >= 100_000 {
79        val /= 100_000;
80        log += 5;
81    }
82    log + less_than_5(val as u32)
83}
84
85// 0 < val <= u128::MAX
86#[inline]
87#[ferrocene::prevalidated]
88const fn u128_impl(mut val: u128) -> u32 {
89    let mut log = 0;
90    if val >= 100_000_000_000_000_000_000_000_000_000_000 {
91        val /= 100_000_000_000_000_000_000_000_000_000_000;
92        log += 32;
93        return log + u32_impl(val as u32);
94    }
95    if val >= 10_000_000_000_000_000 {
96        val /= 10_000_000_000_000_000;
97        log += 16;
98    }
99    log + u64_impl(val as u64)
100}
101
102macro_rules! define_unsigned_ilog10 {
103    ($($ty:ident => $impl_fn:ident,)*) => {$(
104        #[inline]
105        #[ferrocene::prevalidated]
106        pub(in crate::num) const fn $ty(val: NonZero<$ty>) -> u32 {
107            let result = $impl_fn(val.get());
108
109            // SAFETY: Integer logarithm is monotonic non-decreasing, so the computed `result` cannot
110            // exceed the value produced for the maximum input.
111            unsafe { crate::hint::assert_unchecked(result <= const { $impl_fn($ty::MAX) }) };
112
113            result
114        }
115    )*};
116}
117
118define_unsigned_ilog10! {
119    u8 => u8_impl,
120    u16 => u16_impl,
121    u32 => u32_impl,
122    u64 => u64_impl,
123    u128 => u128_impl,
124}
125
126#[inline]
127#[ferrocene::prevalidated]
128pub(in crate::num) const fn usize(val: NonZero<usize>) -> u32 {
129    #[cfg(target_pointer_width = "16")]
130    let impl_fn = u16;
131
132    #[cfg(target_pointer_width = "32")]
133    let impl_fn = u32;
134
135    #[cfg(target_pointer_width = "64")]
136    let impl_fn = u64;
137
138    // SAFETY: We have selected the correct `impl_fn`, so the converting `val` to the argument is
139    // safe.
140    impl_fn(unsafe { NonZero::new_unchecked(val.get() as _) })
141}
142
143macro_rules! define_signed_ilog10 {
144    ($($ty:ident => $impl_fn:ident,)*) => {$(
145        // 0 < val <= $ty::MAX
146        #[inline]
147        pub(in crate::num) const fn $ty(val: $ty) -> Option<u32> {
148            if val > 0 {
149                let result = $impl_fn(val.cast_unsigned());
150
151                // SAFETY: Integer logarithm is monotonic non-decreasing, so the computed `result`
152                // cannot exceed the value produced for the maximum input.
153                unsafe {
154                    crate::hint::assert_unchecked(result <= const { $impl_fn($ty::MAX.cast_unsigned()) });
155                }
156
157                Some(result)
158            } else {
159                None
160            }
161        }
162    )*};
163}
164
165define_signed_ilog10! {
166    i8 => u8_impl,
167    i16 => u16_impl,
168    i32 => u32_impl,
169    i64 => u64_impl,
170    i128 => u128_impl,
171}
172
173/// Instantiate this panic logic once, rather than for all the ilog methods
174/// on every single primitive type.
175#[cold]
176#[track_caller]
177#[ferrocene::prevalidated]
178pub(in crate::num) const fn panic_for_nonpositive_argument() -> ! {
179    panic!("argument of integer logarithm must be positive")
180}