MCPcopy Index your code
hub / github.com/RustPython/RustPython / write_input

Function write_input

crates/stdlib/src/_testconsole.rs:13–69  ·  view source on GitHub ↗
(file: PyObjectRef, s: ArgBytesLike, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

11
12 #[pyfunction]
13 fn write_input(file: PyObjectRef, s: ArgBytesLike, vm: &VirtualMachine) -> PyResult<()> {
14 use windows_sys::Win32::System::Console::{INPUT_RECORD, KEY_EVENT, WriteConsoleInputW};
15
16 // Get the fd from the file object via fileno()
17 let fd_obj = vm.call_method(&file, "fileno", ())?;
18 let fd: i32 = fd_obj.try_into_value(vm)?;
19
20 let handle = unsafe { libc::get_osfhandle(fd) } as Handle;
21 if handle == INVALID_HANDLE_VALUE {
22 return Err(std::io::Error::last_os_error().into_pyexception(vm));
23 }
24
25 let data = s.borrow_buf();
26 let data = &*data;
27
28 // Interpret as UTF-16-LE pairs
29 if !data.len().is_multiple_of(2) {
30 return Err(vm.new_value_error("buffer must contain UTF-16-LE data (even length)"));
31 }
32 let wchars: Vec<u16> = data
33 .chunks_exact(2)
34 .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
35 .collect();
36
37 let size = wchars.len() as u32;
38
39 // Create INPUT_RECORD array
40 let mut records: Vec<INPUT_RECORD> = Vec::with_capacity(wchars.len());
41 for &wc in &wchars {
42 // SAFETY: zeroing and accessing the union field for KEY_EVENT
43 let mut rec: INPUT_RECORD = unsafe { core::mem::zeroed() };
44 rec.EventType = KEY_EVENT as u16;
45 rec.Event.KeyEvent.bKeyDown = 1; // TRUE
46 rec.Event.KeyEvent.wRepeatCount = 1;
47 rec.Event.KeyEvent.uChar.UnicodeChar = wc;
48 records.push(rec);
49 }
50
51 let mut total: u32 = 0;
52 while total < size {
53 let mut wrote: u32 = 0;
54 let res = unsafe {
55 WriteConsoleInputW(
56 handle,
57 records[total as usize..].as_ptr(),
58 size - total,
59 &mut wrote,
60 )
61 };
62 if res == 0 {
63 return Err(std::io::Error::last_os_error().into_pyexception(vm));
64 }
65 total += wrote;
66 }
67
68 Ok(())
69 }
70

Callers 4

assertStdinRoundTripMethod · 0.90
test_partial_readsMethod · 0.90
test_ctrl_zMethod · 0.90

Calls 11

get_osfhandleFunction · 0.85
try_into_valueMethod · 0.80
collectMethod · 0.80
ErrClass · 0.50
call_methodMethod · 0.45
into_pyexceptionMethod · 0.45
borrow_bufMethod · 0.45
lenMethod · 0.45
mapMethod · 0.45
pushMethod · 0.45
as_ptrMethod · 0.45

Tested by

no test coverage detected