Skip to content

Commit a9aa7d8

Browse files
authored
Handle possible errors in set_virtual_terminal (#105)
1 parent 58fc5de commit a9aa7d8

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Unreleased
22
- Document crate MSRV of `1.70`.
3+
- Handle errors in `set_virtual_terminal`.
34

45
# 2.0.4
56
- Switch from `winapi` to `windows-sys`.

src/control.rs

+11-4
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,6 @@ use std::sync::atomic::{AtomicBool, Ordering};
1010
/// This is primarily used for Windows 10 environments which will not correctly colorize
1111
/// the outputs based on ANSI escape codes.
1212
///
13-
/// The returned `Result` is _always_ `Ok(())`, the return type was kept to ensure backwards
14-
/// compatibility.
15-
///
1613
/// # Notes
1714
/// > Only available to `Windows` build targets.
1815
///
@@ -28,15 +25,25 @@ use std::sync::atomic::{AtomicBool, Ordering};
2825
#[allow(clippy::result_unit_err)]
2926
#[cfg(windows)]
3027
pub fn set_virtual_terminal(use_virtual: bool) -> Result<(), ()> {
28+
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
3129
use windows_sys::Win32::System::Console::{
3230
GetConsoleMode, GetStdHandle, SetConsoleMode, ENABLE_VIRTUAL_TERMINAL_PROCESSING,
3331
STD_OUTPUT_HANDLE,
3432
};
3533

3634
unsafe {
3735
let handle = GetStdHandle(STD_OUTPUT_HANDLE);
36+
if handle == INVALID_HANDLE_VALUE {
37+
return Err(());
38+
}
39+
3840
let mut original_mode = 0;
39-
GetConsoleMode(handle, &mut original_mode);
41+
// Return value of 0 means that the function failed:
42+
// https://learn.microsoft.com/en-us/windows/console/getconsolemode#return-value
43+
if GetConsoleMode(handle, &mut original_mode) == 0 {
44+
// TODO: It would be prudent to get the error using `GetLastError` here.
45+
return Err(());
46+
}
4047

4148
let enabled = original_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING
4249
== ENABLE_VIRTUAL_TERMINAL_PROCESSING;

0 commit comments

Comments
 (0)