]>
Commit | Line | Data |
---|---|---|
416331ca XL |
1 | #![unstable(issue = "0", feature = "windows_stdio")] |
2 | ||
3 | use crate::io; | |
4 | use crate::sys::c; | |
5 | use crate::sys::handle::Handle; | |
6 | use crate::mem::ManuallyDrop; | |
7 | ||
8 | pub struct Stdin { | |
9 | } | |
10 | pub struct Stdout; | |
11 | pub struct Stderr; | |
12 | ||
13 | const MAX_BUFFER_SIZE: usize = 8192; | |
14 | pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3; | |
15 | ||
16 | pub fn get_handle(handle_id: c::DWORD) -> io::Result<c::HANDLE> { | |
17 | let handle = unsafe { c::GetStdHandle(handle_id) }; | |
18 | if handle == c::INVALID_HANDLE_VALUE { | |
19 | Err(io::Error::last_os_error()) | |
20 | } else if handle.is_null() { | |
21 | Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32)) | |
22 | } else { | |
23 | Ok(handle) | |
24 | } | |
25 | } | |
26 | ||
27 | fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> { | |
28 | let handle = get_handle(handle_id)?; | |
29 | let handle = Handle::new(handle); | |
30 | ManuallyDrop::new(handle).write(data) | |
31 | } | |
32 | ||
33 | impl Stdin { | |
34 | pub fn new() -> io::Result<Stdin> { | |
35 | Ok(Stdin { }) | |
36 | } | |
37 | } | |
38 | ||
39 | impl io::Read for Stdin { | |
40 | fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { | |
41 | let handle = get_handle(c::STD_INPUT_HANDLE)?; | |
42 | let handle = Handle::new(handle); | |
43 | ManuallyDrop::new(handle).read(buf) | |
44 | } | |
45 | } | |
46 | ||
47 | impl Stdout { | |
48 | pub fn new() -> io::Result<Stdout> { | |
49 | Ok(Stdout) | |
50 | } | |
51 | } | |
52 | ||
53 | impl io::Write for Stdout { | |
54 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { | |
55 | write(c::STD_OUTPUT_HANDLE, buf) | |
56 | } | |
57 | ||
58 | fn flush(&mut self) -> io::Result<()> { | |
59 | Ok(()) | |
60 | } | |
61 | } | |
62 | ||
63 | impl Stderr { | |
64 | pub fn new() -> io::Result<Stderr> { | |
65 | Ok(Stderr) | |
66 | } | |
67 | } | |
68 | ||
69 | impl io::Write for Stderr { | |
70 | fn write(&mut self, buf: &[u8]) -> io::Result<usize> { | |
71 | write(c::STD_ERROR_HANDLE, buf) | |
72 | } | |
73 | ||
74 | fn flush(&mut self) -> io::Result<()> { | |
75 | Ok(()) | |
76 | } | |
77 | } | |
78 | ||
79 | pub fn is_ebadf(err: &io::Error) -> bool { | |
80 | err.raw_os_error() == Some(c::ERROR_INVALID_HANDLE as i32) | |
81 | } | |
82 | ||
83 | pub fn panic_output() -> Option<impl io::Write> { | |
84 | Stderr::new().ok() | |
85 | } |