diff --git a/encoding/src/main.rs b/encoding/src/main.rs index 2e0108b..2e038fd 100644 --- a/encoding/src/main.rs +++ b/encoding/src/main.rs @@ -5,6 +5,13 @@ use encoding::{ DecoderTrap, }; +fn gbk_to_utf8_bytes(b: &[u8]) -> Option> { + match GBK.decode(b, DecoderTrap::Strict) { + Err(_) => None, + Ok(s) => Some(s.as_bytes().to_vec()), + } +} + fn main() -> Result<(), Box> { let h_china = GBK.encode("Hello 中国", EncoderTrap::Strict)?; @@ -14,5 +21,10 @@ fn main() -> Result<(), Box> { 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(()) }