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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
mod unchecked {
pub const fn u8(val: u8) -> u32 {
if val >= 100 {
2
} else if val >= 10 {
1
} else {
0
}
}
pub const fn u16(val: u16) -> u32 {
if val >= 10_000 {
4
} else if val >= 1000 {
3
} else if val >= 100 {
2
} else if val >= 10 {
1
} else {
0
}
}
const fn less_than_8(mut val: u32) -> u32 {
let mut log = 0;
if val >= 10_000 {
val /= 10_000;
log += 4;
}
log + if val >= 1000 {
3
} else if val >= 100 {
2
} else if val >= 10 {
1
} else {
0
}
}
pub const fn u32(mut val: u32) -> u32 {
let mut log = 0;
if val >= 100_000_000 {
val /= 100_000_000;
log += 8;
}
log + less_than_8(val)
}
const fn less_than_16(mut val: u64) -> u32 {
let mut log = 0;
if val >= 100_000_000 {
val /= 100_000_000;
log += 8;
}
log + less_than_8(val as u32)
}
pub const fn u64(mut val: u64) -> u32 {
let mut log = 0;
if val >= 10_000_000_000_000_000 {
val /= 10_000_000_000_000_000;
log += 16;
}
log + less_than_16(val)
}
pub const fn u128(mut val: u128) -> u32 {
let mut log = 0;
if val >= 100_000_000_000_000_000_000_000_000_000_000 {
val /= 100_000_000_000_000_000_000_000_000_000_000;
log += 32;
return log + less_than_8(val as u32);
}
if val >= 10_000_000_000_000_000 {
val /= 10_000_000_000_000_000;
log += 16;
}
log + less_than_16(val as u64)
}
pub const fn i8(val: i8) -> u32 {
u8(val as u8)
}
pub const fn i16(val: i16) -> u32 {
u16(val as u16)
}
pub const fn i32(val: i32) -> u32 {
u32(val as u32)
}
pub const fn i64(val: i64) -> u32 {
u64(val as u64)
}
pub const fn i128(val: i128) -> u32 {
u128(val as u128)
}
}
macro_rules! impl_checked {
($T:ident) => {
pub const fn $T(val: $T) -> Option<$T> {
if val > 0 { Some(unchecked::$T(val) as $T) } else { None }
}
};
}
impl_checked! { u8 }
impl_checked! { u16 }
impl_checked! { u32 }
impl_checked! { u64 }
impl_checked! { u128 }
impl_checked! { i8 }
impl_checked! { i16 }
impl_checked! { i32 }
impl_checked! { i64 }
impl_checked! { i128 }