1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#![unstable(issue = "0", feature = "windows_stdio")]
use io::prelude::*;
use cmp;
use io::{self, Cursor};
use ptr;
use str;
use sync::Mutex;
use sys::c;
use sys::cvt;
use sys::handle::Handle;
use sys_common::io::read_to_end_uninitialized;
pub enum Output {
Console(c::HANDLE),
Pipe(c::HANDLE),
}
pub struct Stdin {
utf8: Mutex<io::Cursor<Vec<u8>>>,
}
pub struct Stdout;
pub struct Stderr;
pub fn get(handle: c::DWORD) -> io::Result<Output> {
let handle = unsafe { c::GetStdHandle(handle) };
if handle == c::INVALID_HANDLE_VALUE {
Err(io::Error::last_os_error())
} else if handle.is_null() {
Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32))
} else {
let mut out = 0;
match unsafe { c::GetConsoleMode(handle, &mut out) } {
0 => Ok(Output::Pipe(handle)),
_ => Ok(Output::Console(handle)),
}
}
}
fn write(handle: c::DWORD, data: &[u8]) -> io::Result<usize> {
let handle = match try!(get(handle)) {
Output::Console(c) => c,
Output::Pipe(p) => {
let handle = Handle::new(p);
let ret = handle.write(data);
handle.into_raw();
return ret
}
};
const OUT_MAX: usize = 8192;
let len = cmp::min(data.len(), OUT_MAX);
let utf8 = match str::from_utf8(&data[..len]) {
Ok(s) => s,
Err(ref e) if e.valid_up_to() == 0 => return Err(invalid_encoding()),
Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(),
};
let utf16 = utf8.encode_utf16().collect::<Vec<u16>>();
let mut written = 0;
cvt(unsafe {
c::WriteConsoleW(handle,
utf16.as_ptr() as c::LPCVOID,
utf16.len() as u32,
&mut written,
ptr::null_mut())
})?;
assert_eq!(written as usize, utf16.len());
Ok(utf8.len())
}
impl Stdin {
pub fn new() -> io::Result<Stdin> {
Ok(Stdin {
utf8: Mutex::new(Cursor::new(Vec::new())),
})
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
let handle = match try!(get(c::STD_INPUT_HANDLE)) {
Output::Console(c) => c,
Output::Pipe(p) => {
let handle = Handle::new(p);
let ret = handle.read(buf);
handle.into_raw();
return ret
}
};
let mut utf8 = self.utf8.lock().unwrap();
if utf8.position() as usize == utf8.get_ref().len() {
let mut utf16 = vec![0u16; 0x1000];
let mut num = 0;
let mut input_control = readconsole_input_control(CTRL_Z_MASK);
cvt(unsafe {
c::ReadConsoleW(handle,
utf16.as_mut_ptr() as c::LPVOID,
utf16.len() as u32,
&mut num,
&mut input_control as c::PCONSOLE_READCONSOLE_CONTROL)
})?;
utf16.truncate(num as usize);
let mut data = match String::from_utf16(&utf16) {
Ok(utf8) => utf8.into_bytes(),
Err(..) => return Err(invalid_encoding()),
};
if let Some(&last_byte) = data.last() {
if last_byte == CTRL_Z {
data.pop();
}
}
*utf8 = Cursor::new(data);
}
utf8.read(buf)
}
pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
let mut me = self;
(&mut me).read_to_end(buf)
}
}
#[unstable(reason = "not public", issue = "0", feature = "fd_read")]
impl<'a> Read for &'a Stdin {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
(**self).read(buf)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
unsafe { read_to_end_uninitialized(self, buf) }
}
}
impl Stdout {
pub fn new() -> io::Result<Stdout> {
Ok(Stdout)
}
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
write(c::STD_OUTPUT_HANDLE, data)
}
pub fn flush(&self) -> io::Result<()> {
Ok(())
}
}
impl Stderr {
pub fn new() -> io::Result<Stderr> {
Ok(Stderr)
}
pub fn write(&self, data: &[u8]) -> io::Result<usize> {
write(c::STD_ERROR_HANDLE, data)
}
pub fn flush(&self) -> io::Result<()> {
Ok(())
}
}
impl io::Write for Stderr {
fn write(&mut self, data: &[u8]) -> io::Result<usize> {
Stderr::write(self, data)
}
fn flush(&mut self) -> io::Result<()> {
Stderr::flush(self)
}
}
impl Output {
pub fn handle(&self) -> c::HANDLE {
match *self {
Output::Console(c) => c,
Output::Pipe(c) => c,
}
}
}
fn invalid_encoding() -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, "text was not valid unicode")
}
fn readconsole_input_control(wakeup_mask: c::ULONG) -> c::CONSOLE_READCONSOLE_CONTROL {
c::CONSOLE_READCONSOLE_CONTROL {
nLength: ::mem::size_of::<c::CONSOLE_READCONSOLE_CONTROL>() as c::ULONG,
nInitialChars: 0,
dwCtrlWakeupMask: wakeup_mask,
dwControlKeyState: 0,
}
}
const CTRL_Z: u8 = 0x1A;
const CTRL_Z_MASK: c::ULONG = 0x4000000;
pub const EBADF_ERR: i32 = ::sys::c::ERROR_INVALID_HANDLE as i32;
pub const STDIN_BUF_SIZE: usize = 8 * 1024;