I want to obtain the byte literal.
Imagine I get a hex from the web or somewhere. And I want to make a CLI tool to convert that hex to byte string literal. Then I can use it (b"xxxx") on my rust code.
Maybe I misunderstood what you try to achieve. If you want to create a string with corresponding escape sequences, maybe you rather want something like the following? (Just written down quickly, maybe there is an easier or more efficient way.)
use std::fmt::Write;
fn to_byte_string_literal(a: impl AsRef<[u8]>) -> String {
fn inner(bytes: &[u8]) -> String {
let mut lit = String::new();
for &byte in bytes {
if byte >= 40 && byte <= 126 {
lit.push(std::char::from_u32(byte as u32).unwrap());
} else {
write!(lit, "\\x{byte:02X}").unwrap();
}
}
lit
}
inner(a.as_ref())
}
fn main() {
assert_eq!(to_byte_string_literal([30, 31, 30, 30, 43]), r"\x1E\x1F\x1E\x1E+");
}
It's not "wrong", it's just different. In the "raw" string, all escape sequences are left as-is, i.e. it will contain characters '\', 'x', '1', 'E' etc. literally. In the byte string, all escape sequences are expanded, therefore the string contains characters '\x1E', '\x1F' etc. Do you want to expand escape sequences already existing in the string you've got (i.e. convert the former case to the latter)?
If I understand you right, the Google query you are after is unescape string.
It seems crates:unescape does the trick. According to src it supports \b, \f, \n, \r, \t, \", \', \\, \u and \x escapes.