31 lines
773 B
Rust
31 lines
773 B
Rust
use encoding::{
|
|
all::GBK,
|
|
Encoding,
|
|
EncoderTrap,
|
|
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)?;
|
|
|
|
let d_china = GBK.decode(&h_china, DecoderTrap::Strict)?;
|
|
|
|
println!("Encoding name: {}, whatwg name: {}", GBK.name(), GBK.whatwg_name().unwrap_or("None"));
|
|
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(())
|
|
}
|