본문 바로가기

Rust/기타 팁

encoding, decoding 관련 crate

[1. 개요]

 


[2. 예제]

// Cargo.toml
// encoding_rs = "0.8.33"
#[cfg(test)]
mod tests {
use std::io::Read;
use std::process::Command;
#[test]
fn cmd_test() {
let mut out = Command::new("cmd")
.args(["/C", "ipconfig"])
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap();
let mut t = out.stdout.take().unwrap();
loop {
let mut buf: [u8; 1024] = [0; 1024];
// 윈도우인 경우 chcp 로, encoding 을 확인하고,
let read_bytes = t.read(&mut buf).unwrap();
if read_bytes == 0 {
break;
}
// buf 에 저장 된 값이 utf-8 로 encoding 되지 않은 경우,
// 문자열이 깨져서 출력 된다.
// println!("{}", String::from_utf8_lossy(&buf));
// 적절한 방식으로 decoding 한다.
let decode_result = encoding_rs::EUC_KR.decode(&buf);
let result = decode_result.0.to_string();
let encoded = encoding_rs::UTF_8.encode(result.as_str());
let result = String::from_utf8_lossy(encoded.0.as_ref());
println!("{}", result);
}
let _ = out.wait().unwrap();
}
}
view raw encoding.rs hosted with ❤ by GitHub

[3. 참조]

'Rust > 기타 팁' 카테고리의 다른 글