| 1 |
use std::convert::TryInto; |
| 2 |
use std::io; |
| 3 |
use std::os::windows::io::AsHandle; |
| 4 |
use std::os::windows::io::AsRawHandle; |
| 5 |
use std::os::windows::io::BorrowedHandle; |
| 6 |
use std::ptr; |
| 7 |
|
| 8 |
use windows_sys::Win32::Foundation::BOOL; |
| 9 |
use windows_sys::Win32::Foundation::HANDLE; |
| 10 |
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; |
| 11 |
use windows_sys::Win32::System::Console::GetConsoleMode; |
| 12 |
use windows_sys::Win32::System::Console::WriteConsoleW; |
| 13 |
|
| 14 |
const TRUE: BOOL = 1; |
| 15 |
|
| 16 |
fn check_syscall(result: BOOL) -> io::Result<()> { |
| 17 |
if result == TRUE { |
| 18 |
Ok(()) |
| 19 |
} else { |
| 20 |
Err(io::Error::last_os_error()) |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
fn raw_handle(handle: BorrowedHandle<'_>) -> HANDLE { |
| 25 |
handle.as_raw_handle() as _ |
| 26 |
} |
| 27 |
|
| 28 |
#[derive(Clone, Copy)] |
| 29 |
pub struct Console<'a>(BorrowedHandle<'a>); |
| 30 |
|
| 31 |
impl<'a> Console<'a> { |
| 32 |
pub(super) fn from_handle<T>(handle: &'a T) -> Option<Self> |
| 33 |
where |
| 34 |
T: AsHandle + ?Sized, |
| 35 |
{ |
| 36 |
let handle = handle.as_handle(); |
| 37 |
let raw_handle = raw_handle(handle); |
| 38 |
if matches!(raw_handle, 0 | INVALID_HANDLE_VALUE) { |
| 39 |
return None; |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
let mut mode = 0; |
| 45 |
check_syscall(unsafe { GetConsoleMode(raw_handle, &mut mode) }) |
| 46 |
.ok() |
| 47 |
.map(|()| Self(handle)) |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
#[cfg(test)] |
| 52 |
pub(super) const unsafe fn null() -> Self { |
| 53 |
|
| 54 |
Self(unsafe { BorrowedHandle::borrow_raw(ptr::null_mut()) }) |
| 55 |
} |
| 56 |
|
| 57 |
fn write_wide(&mut self, string: &[u16]) -> io::Result<usize> { |
| 58 |
let length = string.len().try_into().unwrap_or(u32::MAX); |
| 59 |
let mut written_length = 0; |
| 60 |
check_syscall(unsafe { |
| 61 |
WriteConsoleW( |
| 62 |
raw_handle(self.0), |
| 63 |
string.as_ptr().cast(), |
| 64 |
length, |
| 65 |
&mut written_length, |
| 66 |
ptr::null_mut(), |
| 67 |
) |
| 68 |
}) |
| 69 |
.map(|()| written_length as usize) |
| 70 |
} |
| 71 |
|
| 72 |
pub(super) fn write_wide_all( |
| 73 |
&mut self, |
| 74 |
mut string: &[u16], |
| 75 |
) -> io::Result<()> { |
| 76 |
while !string.is_empty() { |
| 77 |
match self.write_wide(string) { |
| 78 |
Ok(written_length) => { |
| 79 |
if written_length == 0 { |
| 80 |
return Err(io::Error::new( |
| 81 |
io::ErrorKind::WriteZero, |
| 82 |
"failed to write whole buffer", |
| 83 |
)); |
| 84 |
} |
| 85 |
string = &string[written_length..]; |
| 86 |
} |
| 87 |
Err(error) => { |
| 88 |
if error.kind() != io::ErrorKind::Interrupted { |
| 89 |
return Err(error); |
| 90 |
} |
| 91 |
} |
| 92 |
} |
| 93 |
} |
| 94 |
Ok(()) |
| 95 |
} |
| 96 |
} |