From 96fd50f78c27eb718385dcf8107b4de57616e505 Mon Sep 17 00:00:00 2001 From: beneth Date: Mon, 13 Apr 2020 18:44:44 +0200 Subject: [PATCH] Documentation & replace hex_to_char to hex_to_string --- set1/chal1/src/main.rs | 39 ++++++++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/set1/chal1/src/main.rs b/set1/chal1/src/main.rs index 3b74cb7..38086f6 100644 --- a/set1/chal1/src/main.rs +++ b/set1/chal1/src/main.rs @@ -6,19 +6,34 @@ use std::env; -/// Convert Hex String to char +/// Convert Hexadecimal Vec 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 { - u8::from_str_radix(s, 16).map(|n| n as char) +fn hex_to_string(hex_char: &Vec) -> 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 = vec![0x41, 0x42]; +/// let b64_encode = base64_encode(&test); +/// assert_eq!(b64_encode, "QUI="); +/// ~~~ fn base64_encode(input: &Vec) -> 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) -> String { } fn main() { - let mut input_str = String::new(); + // Test Base64 encode + let test: Vec = vec![0x41, 0x42]; // "[A,B] in ascii" + let b64_encode = base64_encode(&test); + assert_eq!(b64_encode, "QUI="); + let args: Vec = env::args().collect(); let input = &args[1]; @@ -86,13 +105,7 @@ fn main() { .map(|chunk| chunk.iter().collect::()) .collect::>(); - // 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 into Vec // Warning: Panic if not base16