From 99865e2efec88d87e2eaca58e7fadaaf5502235c Mon Sep 17 00:00:00 2001 From: "E. Almqvist" Date: Mon, 8 Aug 2022 15:26:34 +0200 Subject: [PATCH] Refactor & cleanup --- src/ipv4.rs | 12 +++++++++++- src/main.rs | 2 ++ src/util.rs | 9 +++------ 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/ipv4.rs b/src/ipv4.rs index a6dc6bc..cb98a98 100644 --- a/src/ipv4.rs +++ b/src/ipv4.rs @@ -22,7 +22,17 @@ impl IPv4 { let mut base = Convert::new(10, 256); let id_vec = util::number_to_vec(id); // push all digits into a vec - let ip = base.convert::(&id_vec); + let mut ip = base.convert::(&id_vec); + + // In case we are missing some digits + if ip.len() < 4 { + for i in 0..(4-ip.len()) { + ip.insert(0, 0); + } + } + + // Reverse it so that we start from the top + ip = ip.into_iter().rev().collect(); Self { id, ip } } diff --git a/src/main.rs b/src/main.rs index e7c0f98..245c5e0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,8 @@ fn main() { // scanner::start_scan(100); // permutations::ipv4(None); + let ip = IPv4::new((u32::max_value() - 256 - 255) as u64); + println!("{:?}", ip); let ip = IPv4::new(256); println!("{:?}", ip); } diff --git a/src/util.rs b/src/util.rs index 8d853e7..c602bd1 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,6 +1,5 @@ - /* -uint ulong_len(ulong n) { // get the digit length of a number +uint ulong_len(ulong n) { // get the nth_digit length of a number int len = 0; while (n != 0) { n = n / 10; @@ -10,7 +9,7 @@ uint ulong_len(ulong n) { // get the digit length of a number } */ -fn digit(num: u64, idx: u32) -> u8 { +fn nth_digit(num: u64, idx: u32) -> u8 { // ((num % (10**(idx+1))) - (num % (10**idx)))/(10**idx) (((num % (10_u64.pow(idx+1))) - (num % (10_u64.pow(idx))))/(10_u64.pow(idx))) as u8 } @@ -35,11 +34,9 @@ pub fn number_to_vec(num: u64) -> Vec { let len = numlen(num); for idx in 0..len { - let digit = digit(num, idx as u32); + let digit = nth_digit(num, idx as u32); out.push(digit); } - println!("{:?}", out); - out }