From c8080b9856b0c26c2f666e54683220be0c9860d4 Mon Sep 17 00:00:00 2001 From: Oleksandr Kozachuk Date: Sun, 11 Dec 2022 16:21:17 +0100 Subject: [PATCH] Add Radix structure to convert number to any radix up to 36. --- src/structs.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/structs.rs b/src/structs.rs index 4773ea2..e4a05a8 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -1,4 +1,5 @@ use crate::password::{Comment, Name, PasswordRef}; +use std::fmt; #[derive(thiserror::Error, Debug, PartialEq)] pub enum LKErr<'a> { @@ -57,3 +58,53 @@ impl std::fmt::Display for Mode { ) } } + +pub struct Radix { + x: i32, + radix: u32, +} + +impl Radix { + pub fn new(x: i32, radix: u32) -> Result { + if radix < 2 || radix > 36 { + Err("Unnsupported radix") + } else { + Ok(Self { x, radix }) + } + } +} + +impl fmt::Display for Radix { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut x = self.x; + // Good for binary formatting of `u128`s + let mut result = ['\0'; 128]; + let mut used = 0; + let negative = x < 0; + if negative { + x*=-1; + } + let mut x = x as u32; + loop { + let m = x % self.radix; + x /= self.radix; + + result[used] = std::char::from_digit(m, self.radix).unwrap(); + used += 1; + + if x == 0 { + break; + } + } + + if negative { + write!(f, "-")?; + } + + for c in result[..used].iter().rev() { + write!(f, "{}", c)?; + } + + Ok(()) + } +}