Documentation & replace hex_to_char to hex_to_string

master
Benoît 2020-04-13 18:44:44 +02:00
parent e588ed13aa
commit 96fd50f78c
1 changed files with 26 additions and 13 deletions

View File

@ -6,19 +6,34 @@
use std::env;
/// Convert Hex String to char
/// Convert Hexadecimal Vec<String> to String
///
/// # Examples
///
/// ~~~
/// hex_to_char("49") => I
/// hex_to_string("49") => I
/// ~~~
/// TODO: the name is not accurate. Take a string and convert to u8
fn hex_to_char(s: &str) -> Result<char, std::num::ParseIntError> {
u8::from_str_radix(s, 16).map(|n| n as char)
fn hex_to_string(hex_char: &Vec<String>) -> String {
let mut output = String::new();
// Printing the string in Ascii format - for hexa to Ascii example
for (i, s) in hex_char.into_iter().enumerate() {
match u8::from_str_radix(&s, 16).map(|n| n as char) {
Ok(s) => output.push(s),
Err(e) => println!("\nError decoding char '{}' at index {}", e, i),
}
}
output
}
/// Encode a Vector of bytes to Base64 and return the base 64 String
///
/// # Examples
///
/// ~~~
/// let test: Vec<u8> = vec![0x41, 0x42];
/// let b64_encode = base64_encode(&test);
/// assert_eq!(b64_encode, "QUI=");
/// ~~~
fn base64_encode(input: &Vec<u8>) -> String {
static BASE64_TABLE: &'static [char] = &['A','B','C','D','E','F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O',
@ -76,7 +91,11 @@ fn base64_encode(input: &Vec<u8>) -> String {
}
fn main() {
let mut input_str = String::new();
// Test Base64 encode
let test: Vec<u8> = vec![0x41, 0x42]; // "[A,B] in ascii"
let b64_encode = base64_encode(&test);
assert_eq!(b64_encode, "QUI=");
let args: Vec<String> = env::args().collect();
let input = &args[1];
@ -86,13 +105,7 @@ fn main() {
.map(|chunk| chunk.iter().collect::<String>())
.collect::<Vec<_>>();
// Printing the string in Ascii format - for hexa to Ascii example
for (i, s) in hex_char.into_iter().enumerate() {
match hex_to_char(s) {
Ok(s) => input_str.push(s),
Err(e) => println!("\nError decoding char '{}' at index {}", e, i),
}
}
let input_str = hex_to_string(&hex_char);
// Convert hex_char : Vec<String> into Vec<u8>
// Warning: Panic if not base16