I'm re-doing a project in Rust this weekend and I need to convert an i32 to an ASCII character using it as the character code. All I have so far is a monstrous match
that I'm hiding at the end of a file. Unfortunately, std::ascii
does not support this conversion. Currently I'm just looking for a less ridiculous/more Rust-like(?) way to do this.
fn to_ascii(i: &i32) -> String {
let a = match *i {
0 => "NUL",
1 => "SOH",
2 => "STX",
// ...
125 => "}",
126 => "~",
127 => "DEL",
_ => "",
}
a
}
First, you don't need to return a String
, a &'static str
is sufficient. Second, you could simply set up an array of &'static str
s with all code representations you like, and use .get(_)
to get the relevant string slices, as long as all your char codes are consecutive (which they should be if I have my ASCII right). Even if they aren't, you can always put empty strings in the gaps.
The code should look like the following:
const CHARS: [&'static str; 128] = ["NUL", "SOH", "STX", .., "DEL"];
fn get_char_code(c: i32) -> &'static str {
CHARS.get(c as usize).unwrap_or("")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With