add gbk_to_utf8_bytes

This commit is contained in:
2020-05-01 20:40:09 +08:00
parent f5e9e1b13d
commit 3cd720c68e

View File

@@ -5,6 +5,13 @@ use encoding::{
DecoderTrap,
};
fn gbk_to_utf8_bytes(b: &[u8]) -> Option<Vec<u8>> {
match GBK.decode(b, DecoderTrap::Strict) {
Err(_) => None,
Ok(s) => Some(s.as_bytes().to_vec()),
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let h_china = GBK.encode("Hello 中国", EncoderTrap::Strict)?;
@@ -14,5 +21,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("{:?}", h_china);
println!("{:?}", d_china);
let utf8_vec = gbk_to_utf8_bytes(&h_china[..]);
if let Some(u8_vec) = utf8_vec {
println!("{:?}", String::from_utf8(u8_vec)?);
}
Ok(())
}