Last active
August 10, 2020 20:34
-
-
Save badgateway666/19b260b2d8ae5b3dbe36dd1409e7c54e to your computer and use it in GitHub Desktop.
base64 encoding implemented in rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub fn hex2b64(s: &str) -> String { | |
assert_eq!(s.len() % 2, 0); | |
let bit_mask1 = 0x00FC_0000; | |
let bit_mask2 = 0x0003_F000; | |
let bit_mask3 = 0x0000_0FC0; | |
let bit_mask4 = 0x0000_003F; | |
let excess_bytes = s.len() / 2 % 3; | |
let mut buf = String::new(); | |
for i in (0..s.len() - (excess_bytes * 2)).step_by(6) { | |
let hex_substr_as_u32 = u32::from_str_radix(&s[i..i + 6], 16).unwrap(); | |
buf.push(single_u8_to_b64( | |
((hex_substr_as_u32 & bit_mask1) >> 18) as u8, | |
)); | |
buf.push(single_u8_to_b64( | |
((hex_substr_as_u32 & bit_mask2) >> 12) as u8, | |
)); | |
buf.push(single_u8_to_b64( | |
((hex_substr_as_u32 & bit_mask3) >> 6) as u8, | |
)); | |
buf.push(single_u8_to_b64((hex_substr_as_u32 & bit_mask4) as u8)); | |
} | |
match excess_bytes { | |
1 => { | |
let padded_excess = u32::from_str_radix(&s[s.len() - 2..s.len()], 16).unwrap() << 16; | |
buf.push(single_u8_to_b64(((padded_excess & bit_mask1) >> 18) as u8)); | |
buf.push(single_u8_to_b64(((padded_excess & bit_mask2) >> 12) as u8)); | |
buf.push('='); | |
buf.push('='); | |
buf | |
} | |
2 => { | |
let padded_excess = u32::from_str_radix(&s[s.len() - 4..s.len()], 16).unwrap() << 8; | |
buf.push(single_u8_to_b64(((padded_excess & bit_mask1) >> 18) as u8)); | |
buf.push(single_u8_to_b64(((padded_excess & bit_mask2) >> 12) as u8)); | |
buf.push(single_u8_to_b64(((padded_excess & bit_mask3) >> 6) as u8)); | |
buf.push('='); | |
buf | |
} | |
_ => buf, | |
} | |
} | |
pub fn single_u8_to_b64(i: u8) -> char { | |
assert!(i < 0x40); | |
match i { | |
0..=25 => (b'A' + i) as char, // lowerCase | |
26..=51 => (b'a' + (i - 26)) as char, // upperCase | |
52..=61 => (b'0' + (i - 52)) as char, // number | |
62 => '+', | |
63 => '/', | |
_ => unreachable!(""), | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment