use crate::uint::U256;
use core::{fmt, mem::MaybeUninit, ptr, slice, str};
pub(crate) trait GenericRadix: Sized {
const BASE: u8;
const PREFIX: &'static str;
fn digit(x: u8) -> u8;
fn fmt_u256(&self, mut x: U256, is_nonnegative: bool, f: &mut fmt::Formatter) -> fmt::Result {
let zero = U256::ZERO;
let mut buf = [MaybeUninit::<u8>::uninit(); 256];
let mut curr = buf.len();
let base = U256::from(Self::BASE);
for byte in buf.iter_mut().rev() {
let n = x % base; x /= base; byte.write(Self::digit(n.as_u8())); curr -= 1;
if x == zero {
break;
};
}
let buf = &buf[curr..];
let buf = unsafe {
str::from_utf8_unchecked(slice::from_raw_parts(
&buf[0] as *const _ as *const u8,
buf.len(),
))
};
f.pad_integral(is_nonnegative, Self::PREFIX, buf)
}
}
#[derive(Clone, PartialEq)]
pub(crate) struct Binary;
#[derive(Clone, PartialEq)]
pub(crate) struct Octal;
#[derive(Clone, PartialEq)]
pub(crate) struct LowerHex;
#[derive(Clone, PartialEq)]
pub(crate) struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
const BASE: u8 = $base;
const PREFIX: &'static str = $prefix;
fn digit(x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..={}: {}", Self::BASE - 1, x),
}
}
}
}
}
radix! { Binary, 2, "0b", x @ 0 ..= 1 => b'0' + x }
radix! { Octal, 8, "0o", x @ 0 ..= 7 => b'0' + x }
radix! { LowerHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, x @ 10 ..= 15 => b'a' + (x - 10) }
radix! { UpperHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, x @ 10 ..= 15 => b'A' + (x - 10) }
const DEC_DIGITS_LUT: &[u8; 200] = b"\
0001020304050607080910111213141516171819\
2021222324252627282930313233343536373839\
4041424344454647484950515253545556575859\
6061626364656667686970717273747576777879\
8081828384858687888990919293949596979899";
pub(crate) fn fmt_u256(mut n: U256, is_nonnegative: bool, f: &mut fmt::Formatter) -> fmt::Result {
let mut buf = [MaybeUninit::<u8>::uninit(); 79];
let mut curr = buf.len() as isize;
let buf_ptr = &mut buf[0] as *mut _ as *mut u8;
let lut_ptr = DEC_DIGITS_LUT.as_ptr();
unsafe {
while n >= 10000 {
let rem = (n % 10000).as_isize();
n /= 10000;
let d1 = (rem / 100) << 1;
let d2 = (rem % 100) << 1;
curr -= 4;
ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2);
ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(curr + 2), 2);
}
let mut n = n.as_isize();
if n >= 100 {
let d1 = (n % 100) << 1;
n /= 100;
curr -= 2;
ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2);
}
if n < 10 {
curr -= 1;
*buf_ptr.offset(curr) = (n as u8) + b'0';
} else {
let d1 = n << 1;
curr -= 2;
ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2);
}
}
let buf_slice = unsafe {
str::from_utf8_unchecked(slice::from_raw_parts(
buf_ptr.offset(curr),
buf.len() - curr as usize,
))
};
f.pad_integral(is_nonnegative, "", buf_slice)
}