Last active
August 9, 2022 08:20
-
-
Save DutchGhost/1a74415b77f61b1b04168ce6ba71d986 to your computer and use it in GitHub Desktop.
Const table of 10's
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(const_type_name)] | |
#![feature(const_refs_to_cell)] | |
#![feature(const_trait_impl)] | |
#![feature(generic_const_exprs)] | |
use core::ops::{Div, Mul, Not}; | |
trait TableRaw<const SIZE: usize>: Sized + Copy { | |
const TABLE: [Self; SIZE]; | |
} | |
trait ConstProperties: Sized { | |
const MAX: Self; | |
const DIGITS10: usize; | |
} | |
impl<T, const SIZE: usize> const TableRaw<SIZE> for T | |
where | |
T: ~const Copy + ~const From<u8> + ~const Mul<Output = T> + ~const Default, | |
{ | |
const TABLE: [Self; SIZE] = { | |
let mut array: [Self; SIZE] = [Default::default(); SIZE]; | |
let multiplier: Self = Self::from(10u8); | |
let mut current: Self = Self::from(1u8); | |
let mut counter = 0; | |
while counter < (SIZE - 1) { | |
array[counter] = current; | |
current = current * multiplier; | |
counter += 1; | |
} | |
array[counter] = current; | |
array | |
}; | |
} | |
impl<T> const ConstProperties for T | |
where | |
T: ~const Eq | |
+ ~const From<u8> | |
+ ~const Copy | |
+ ~const Not<Output = T> | |
+ ~const Div<Output = Self> | |
+ ~const PartialOrd | |
+ ~const PartialEq | |
+ ~const Mul<Output = T>, | |
{ | |
const MAX: Self = { | |
let mut zero = Self::from(0u8); | |
!zero | |
}; | |
const DIGITS10: usize = { | |
let mut result: usize = 1; | |
let mut max = Self::MAX; | |
let mut ten: Self = Self::from(10u8); | |
// u8 has a length of 2...this is an ad-hoc solution! | |
if core::any::type_name::<T>().len() == 2 { | |
result + 2 | |
} else { | |
loop { | |
if max < ten { break result; } | |
if max < ten * ten { break result + 1; } | |
if max < ten * ten * ten { break result + 2; } | |
if max < ten * ten * ten * ten { break result + 3; } | |
max = max / (ten * ten * ten * ten); | |
result += 4; | |
} | |
} | |
}; | |
} | |
const fn t<T: ConstProperties + TableRaw<{ <T as ConstProperties>::DIGITS10 }>>( | |
) -> [T; <T as ConstProperties>::DIGITS10] { | |
T::TABLE | |
} | |
fn main() { | |
println!("{:?}", t::<u8>()); | |
println!("{:?}", t::<u16>()); | |
println!("{:?}", t::<u32>()); | |
println!("{:?}", t::<u64>()); | |
println!("{:?}", t::<usize>()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment