Rust "thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'"

Viewed 1427

I'm learning some rust and do the challanges from cryptopals, https://cryptopals.com/sets/1/challenges/1 , I want to convert a hex String to Base64 String.

Therefor I wrote this programm, but it throws an error, when I execute it.

use std::io;

fn main() {
    let mut text_to_convert = String::new();
    println!("Please enter the string to convert!");
    io::stdin().read_line(&mut text_to_convert).expect("Failed to read line");

    println!("Base64: {}", string_to_base64(text_to_convert));
}

fn string_to_base64(text: String) -> String {
    let mut base64_string = String::new();
    for c in text.chars() {
        base64_string.push_str(&hex_to_bits(c));
    }
    base64_string
}

fn hex_to_bits(c: char) -> String {
    let mut result = String::new();
    let x = c.to_digit(16).unwrap();
    let mut tmp = x;
    while tmp != 0 {
        result = (tmp % 2).to_string() + &result;
        tmp = tmp/2;
    }
    while result.len() < 4 {
        result = "0".to_string() + &result;
    }
    print!("{}", result);
    result
}

To learn the language I want not to use crates and programm the functions I need by myself. So I started with a hex to bits converter.

When I start my program I get this error:

cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.0 secs
Running `target/debug/nr1`
Please enter the string to convert!
F
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value',     /checkout/src/libcore/option.rs:335:21
note: Run with `RUST_BACKTRACE=1` for a backtrace.
1010
0 Answers
Related