Is there a way to turn a &str into a unicode?

⚓ Rust    📅 2025-09-01    👤 surdeus    👁️ 3      

surdeus

I have this code:

fn parse_str(string: &str) -> String {
    let mut result = String::new();
    let mut i = 0;
    while i < string.len()-1 {
	match string.chars().nth(i).unwrap() {
	    '\\' => {result.push_str(match string.chars().nth(i+1).unwrap() {
		'n' => "\n",
		't' => "\t",
		'r' => "\r",
		'0' => "\0",
		'\\' => "\\",
		'\'' => "\'",
		'"' => "\"",
		'x' => {
                    let hex = &string[i + 2..i + 4];
                    let decoded = u8::from_str_radix(hex, 16)
                        .map(|num| num as char)
                        .unwrap_or('\0'); 
                    return decoded.to_string(); 
		}
		'u' => {
		    /* ??? */
		}
		_ => panic!("Invalid escape code.")
	    }); i += 1}
	    _ => result.push(string.chars().nth(i).unwrap())
	}
	i += 1
    }
    result
}

I was wondering how I would parse the u? It does not have a fixed length, instead relying on \u{xxxx} and I'm not sure if there is a function like from_str_radix.

14 posts - 3 participants

Read full topic

🏷️ Rust_feed