2024-05-12 01:02:55 +02:00
|
|
|
pub type Num = u128;
|
|
|
|
|
|
|
|
#[derive(Copy, Clone, Debug)]
|
|
|
|
pub enum Format {
|
|
|
|
Dec,
|
|
|
|
Hex,
|
|
|
|
Bin,
|
|
|
|
Octal,
|
2024-05-12 01:49:11 +02:00
|
|
|
Base64,
|
2024-05-12 01:55:56 +02:00
|
|
|
Base32,
|
2024-05-12 01:02:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Format {
|
|
|
|
pub fn prefix(&self) -> String {
|
|
|
|
match self {
|
2024-05-12 01:49:11 +02:00
|
|
|
// apperently used nowhere, sometimes 0 is used as a prefix but I
|
|
|
|
// think this makes it more clear that this is decimal
|
2024-05-12 01:02:55 +02:00
|
|
|
Format::Dec => "0d",
|
2024-05-12 01:49:11 +02:00
|
|
|
// very common
|
2024-05-12 01:02:55 +02:00
|
|
|
Format::Hex => "0x",
|
2024-05-12 01:49:11 +02:00
|
|
|
// very common
|
2024-05-12 01:02:55 +02:00
|
|
|
Format::Bin => "0b",
|
2024-05-12 01:49:11 +02:00
|
|
|
// somewhat common
|
2024-05-12 01:02:55 +02:00
|
|
|
Format::Octal => "0o",
|
2024-05-12 01:49:11 +02:00
|
|
|
// perl and a few other programs seem to use this too
|
|
|
|
Format::Base64 => "0s",
|
2024-05-12 01:55:56 +02:00
|
|
|
// no idea, I made this up
|
|
|
|
Format::Base32 => "032s",
|
2024-05-12 01:02:55 +02:00
|
|
|
}
|
|
|
|
.to_string()
|
|
|
|
}
|
|
|
|
pub fn format(&self, num: Num, prefix: bool) -> String {
|
|
|
|
let mut buf = String::new();
|
|
|
|
if prefix {
|
|
|
|
buf += &self.prefix();
|
|
|
|
}
|
|
|
|
match self {
|
|
|
|
Format::Hex => {
|
|
|
|
buf += &format!("{num:X}");
|
|
|
|
}
|
|
|
|
Format::Bin => {
|
|
|
|
buf += &format!("{num:b}");
|
|
|
|
}
|
|
|
|
Format::Octal => {
|
|
|
|
buf += &format!("{num:o}");
|
|
|
|
}
|
|
|
|
Format::Dec => {
|
|
|
|
buf += &format!("{num}");
|
|
|
|
}
|
2024-05-12 01:55:56 +02:00
|
|
|
Format::Base64 => buf += &fast32::base64::RFC4648.encode(&u128_to_u8_slice(num)),
|
|
|
|
Format::Base32 => buf += &fast32::base32::RFC4648.encode(&u128_to_u8_slice(num)),
|
2024-05-12 01:02:55 +02:00
|
|
|
}
|
|
|
|
buf
|
|
|
|
}
|
|
|
|
}
|
2024-05-12 01:49:11 +02:00
|
|
|
|
|
|
|
fn u128_to_u8_slice(mut num: u128) -> Vec<u8> {
|
|
|
|
if num == 0 {
|
|
|
|
return vec![0];
|
|
|
|
}
|
|
|
|
let mut buf: Vec<u8> = Vec::new();
|
|
|
|
while num > 0 {
|
|
|
|
buf.push(num as u8);
|
|
|
|
num >>= 8;
|
|
|
|
}
|
|
|
|
buf
|
|
|
|
}
|