lexical_write_integer/
radix.rs

1//! Radix-generic, lexical integer-to-string conversion routines.
2//!
3//! These routines are decently optimized: they unroll 4 loops at a time,
4//! using pre-computed base^2 tables. However, due to static storage
5//! reasons, it makes no sense to pre-compute the number of digits,
6//! and therefore
7//!
8//! See [Algorithm.md](/docs/Algorithm.md) for a more detailed description of
9//! the algorithm choice here.
10
11#![cfg(not(feature = "compact"))]
12#![cfg(feature = "power-of-two")]
13#![doc(hidden)]
14
15use lexical_util::format;
16use lexical_util::num::{Integer, UnsignedInteger};
17
18use crate::algorithm::{algorithm, algorithm_u128};
19use crate::table::get_table;
20
21/// Write integer to radix string.
22pub trait Radix: UnsignedInteger {
23    /// # Safety
24    ///
25    /// Safe as long as buffer is at least `FORMATTED_SIZE` elements long,
26    /// (or `FORMATTED_SIZE_DECIMAL` for decimal), and the radix is valid.
27    fn radix<const FORMAT: u128, const MASK: u128, const SHIFT: i32>(
28        self,
29        buffer: &mut [u8],
30    ) -> usize;
31}
32
33// Implement radix for type.
34macro_rules! radix_impl {
35    ($($t:ty)*) => ($(
36        impl Radix for $t {
37            #[inline(always)]
38            fn radix<const FORMAT: u128, const MASK: u128, const SHIFT: i32>(
39                self,
40                buffer: &mut [u8]
41            ) -> usize {
42                debug_assert!(<Self as Integer>::BITS <= 64);
43                let radix = format::radix_from_flags(FORMAT, MASK, SHIFT);
44                let table = get_table::<FORMAT, MASK, SHIFT>();
45                algorithm(self, radix, table, buffer)
46            }
47        }
48    )*);
49}
50
51radix_impl! { u8 u16 u32 u64 usize }
52
53impl Radix for u128 {
54    #[inline(always)]
55    fn radix<const FORMAT: u128, const MASK: u128, const SHIFT: i32>(
56        self,
57        buffer: &mut [u8],
58    ) -> usize {
59        let table = get_table::<FORMAT, MASK, SHIFT>();
60        algorithm_u128::<FORMAT, MASK, SHIFT>(self, table, buffer)
61    }
62}