#[cfg(windows)]
use windows::Win32::Foundation::INVALID_HANDLE_VALUE;
#[cfg(windows)]
use windows::Win32::System::Console::{
CONSOLE_MODE, ENABLE_VIRTUAL_TERMINAL_PROCESSING, GetConsoleMode, GetStdHandle,
STD_OUTPUT_HANDLE, SetConsoleCP, SetConsoleMode, SetConsoleOutputCP,
};
pub fn enable_utf8() -> std::io::Result<()> {
#[cfg(windows)]
{
unsafe {
SetConsoleCP(65001)?;
SetConsoleOutputCP(65001)?;
let h_out = GetStdHandle(STD_OUTPUT_HANDLE)?;
if h_out == INVALID_HANDLE_VALUE {
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"Invalid handle value",
));
}
let mut mode = CONSOLE_MODE(0);
GetConsoleMode(h_out, &mut mode)?;
let new_mode = mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING;
SetConsoleMode(h_out, new_mode)?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_enable_utf8_returns_ok() {
let result = enable_utf8();
assert!(
result.is_ok(),
"enable_utf8() should always return Ok on all platforms"
);
}
#[cfg(windows)]
#[test]
fn test_enable_utf8_on_windows() {
let result1 = enable_utf8();
let result2 = enable_utf8();
assert!(result1.is_ok(), "First call failed: {:?}", result1);
assert!(result2.is_ok(), "Second call failed: {:?}", result2);
}
#[cfg(not(windows))]
#[test]
fn test_enable_utf8_on_non_windows() {
let result = enable_utf8();
assert!(result.is_ok());
}
}