Refactor bytes and base64 module to make more sense.

This commit is contained in:
2022-03-26 11:57:24 -04:00
parent cb28436fce
commit 7a1c62c47e
6 changed files with 189 additions and 184 deletions

96
src/bytes.rs Normal file
View File

@@ -0,0 +1,96 @@
use std::fmt::Write; // need to import this trait
#[derive(PartialEq, PartialOrd, Debug)]
pub struct Bytes(pub Vec<u8>);
impl Bytes {
pub fn from_utf8(s: &str) -> Bytes {
Bytes(s.as_bytes().iter().map(|c| c.clone()).collect())
}
#[allow(dead_code)]
pub fn to_utf8(&self) -> String {
let Bytes(v) = self;
String::from(std::str::from_utf8(&v).unwrap())
}
pub fn from_hex(s: &str) -> Bytes {
if s.len() % 2 != 0 {
panic!("Input string has uneven number of characters");
}
let bytes_result: Result<Vec<u8>, std::num::ParseIntError> = (0..s.len())
.step_by(2)
.map(|i| u8::from_str_radix(&s[i..i + 2], 16))
.collect();
match bytes_result {
Ok(b) => Bytes(b),
Err(_) => panic!("Could not convert all digit pairs to hex."),
}
}
pub fn to_hex(&self) -> String {
let Bytes(v) = self;
let mut r = String::new();
for e in v.iter() {
write!(r, "{:02x}", e);
}
r
}
pub fn is_ascii(&self) -> bool {
let Bytes(v) = self;
for &c in v.iter() {
if c < 32 || c > 127 {
return false;
}
}
true
}
pub fn ascii_score(&self) -> u32 {
let Bytes(v) = self;
let mut r = 0;
for &c in v.iter() {
match c {
32 => r += 2,
33..=64 => r += 1,
65..=90 => r += 3,
91..=96 => r += 1,
97..=122 => r += 3,
123..=127 => r += 1,
_ => (),
}
}
r
}
pub fn xor(Bytes(a): &Bytes, Bytes(b): &Bytes) -> Bytes {
Bytes(
Iterator::zip(a.iter(), b.iter())
.map(|z| *(z.0) ^ *(z.1))
.collect(),
)
}
pub fn xor_byte(Bytes(a): &Bytes, byte: u8) -> Bytes {
Bytes(a.iter().map(|e| e ^ byte).collect())
}
pub fn xor_cycle(Bytes(msg): &Bytes, Bytes(key): &Bytes) -> Bytes {
Bytes(
Iterator::zip(msg.iter(), 0..msg.len())
.map(|z| *(z.0) ^ key[z.1 % key.len()])
.collect(),
)
}
#[allow(dead_code)]
pub fn hemming(Bytes(a): &Bytes, Bytes(b): &Bytes) -> u32 {
let v: Vec<u32> = Iterator::zip(a.iter(), b.iter())
.map(|z| (*(z.0) ^ *(z.1)).count_ones())
.collect();
v.iter().sum()
}
}