Refactor code based on clippy suggestions

This commit is contained in:
2022-08-25 17:45:16 -04:00
parent 9a9b5335f1
commit b97b2fe6d0
16 changed files with 145 additions and 204 deletions

View File

@@ -6,7 +6,31 @@ pub struct BytesBase64(pub Vec<u8>);
impl std::fmt::Display for BytesBase64 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Base64({})", self.to_string())
let BytesBase64(digits) = self;
let mut r: Vec<u8> = digits
.iter()
.map(|d| match d {
0..=25 => *d + b'A',
26..=51 => *d - 26 + b'a',
52..=61 => *d - 52 + b'0',
62 => b'+',
63 => b'/',
_ => panic!("Unexpected base64 digit '{}'", d),
})
.collect();
// Handle padding
let pad = b'=';
match r.len() % 4 {
0 => (),
2 => {
r.push(pad);
r.push(pad);
}
3 => r.push(pad),
_ => panic!("Unexpected lenght for padding '{}'", r.len()),
}
let s = str::from_utf8(r.as_slice()).unwrap().to_string();
write!(f, "{}", s)
}
}
@@ -22,7 +46,7 @@ impl BytesBase64 {
(v[0] & 0b11111100) >> 2,
(v[0] & 0b00000011) << 4 | (v[1] & 0b11110000) >> 4,
(v[1] & 0b00001111) << 2 | (v[2] & 0b11000000) >> 6,
(v[2] & 0b00111111) << 0,
(v[2] & 0b00111111),
];
// removed padded bytes
for _ in c.len()..3 {
@@ -30,7 +54,7 @@ impl BytesBase64 {
}
result
}
BytesBase64(bytes.chunks(3).map(|c| to_base64(c)).flatten().collect())
BytesBase64(bytes.chunks(3).flat_map(to_base64).collect())
}
pub fn to_bytes(&self) -> Bytes {
@@ -44,7 +68,7 @@ impl BytesBase64 {
let mut result: Vec<u8> = vec![
((v[0] & 0b00111111) << 2) | ((v[1] & 0b00110000) >> 4),
((v[1] & 0b00001111) << 4) | ((v[2] & 0b00111100) >> 2),
((v[2] & 0b00000011) << 6) | ((v[3] & 0b00111111) >> 0),
((v[2] & 0b00000011) << 6) | (v[3] & 0b00111111),
];
// removed padded bytes
for _ in c.len()..4 {
@@ -52,16 +76,16 @@ impl BytesBase64 {
}
result
}
Bytes(v.chunks(4).map(|c| to_bytes(c)).flatten().collect())
Bytes(v.chunks(4).flat_map(to_bytes).collect())
}
pub fn from_base64(s: &str) -> Result<BytesBase64, String> {
let mut r: Vec<u8> = Vec::with_capacity(s.len());
for c in s.chars() {
match c {
'A'..='Z' => r.push((c as u8) - ('A' as u8)),
'a'..='z' => r.push((c as u8) - ('a' as u8) + 26),
'0'..='9' => r.push((c as u8) - ('0' as u8) + 52),
'A'..='Z' => r.push((c as u8) - b'A'),
'a'..='z' => r.push((c as u8) - b'a' + 26),
'0'..='9' => r.push((c as u8) - b'0' + 52),
'+' => r.push(62),
'/' => r.push(63),
'\n' => (),
@@ -74,31 +98,4 @@ impl BytesBase64 {
}
Ok(BytesBase64(r))
}
pub fn to_string(&self) -> String {
let BytesBase64(digits) = self;
let mut r: Vec<u8> = digits
.iter()
.map(|d| match d {
0..=25 => *d + ('A' as u8),
26..=51 => *d - 26 + ('a' as u8),
52..=61 => *d - 52 + ('0' as u8),
62 => '+' as u8,
63 => '/' as u8,
_ => panic!("Unexpected base64 digit '{}'", d),
})
.collect();
// Handle padding
let pad = '=' as u8;
match r.len() % 4 {
0 => (),
2 => {
r.push(pad);
r.push(pad);
}
3 => r.push(pad),
_ => panic!("Unexpected lenght for padding '{}'", r.len()),
}
str::from_utf8(r.as_slice()).unwrap().to_string()
}
}