| 1 | module scheme |
| 2 | |
| 3 | import os |
| 4 | |
| 5 | #include "@VMODROOT/scheme/port_standard.h" |
| 6 | |
| 7 | $if windows { |
| 8 | fn C.vile_binary_standard_duplicate(int) int |
| 9 | fn C.vile_binary_standard_read(voidptr, u32) int |
| 10 | |
| 11 | struct WindowsBinaryStandardInput {} |
| 12 | |
| 13 | fn (_ &WindowsBinaryStandardInput) read(mut bytes []u8) !int { |
| 14 | count := C.vile_binary_standard_read(bytes.data, u32(int_min(bytes.len, max_i32))) |
| 15 | if count < 0 { return error_with_code('standard input failed (errno ${-count})', -count) } |
| 16 | return count |
| 17 | } |
| 18 | |
| 19 | fn (mut vm VM) windows_standard_input() !Value { |
| 20 | value := vm.input_port(&WindowsBinaryStandardInput{}, binary: true, read_size: 1)! |
| 21 | value.input_pointer().file_backed = true |
| 22 | return value |
| 23 | } |
| 24 | |
| 25 | fn (mut vm VM) windows_standard_output(index int) !Value { |
| 26 | mut reservation := vm.reserve_file_resource()! |
| 27 | defer { reservation.rollback() } |
| 28 | mut stream := &PortFileStream{ raw: true, descriptor_only: true, buffer_mode: .none } |
| 29 | reservation.attach(mut stream) |
| 30 | fd := C.vile_binary_standard_duplicate(index) |
| 31 | if fd < 0 { return error_with_code('standard port duplicate failed (errno ${-fd})', -fd) } |
| 32 | stream.file = os.File{fd: fd, is_opened: true} |
| 33 | register_port_file(stream) |
| 34 | value := vm.output_port(&WindowsBinaryStandardOutput{ stream: stream, standard: index }, |
| 35 | binary: true |
| 36 | )! |
| 37 | mut port := value.output_pointer() |
| 38 | port.file_backed = true |
| 39 | port.file = &stream.file |
| 40 | port.stream = stream |
| 41 | port.owns_file = true |
| 42 | reservation.commit() |
| 43 | return value |
| 44 | } |
| 45 | |
| 46 | struct WindowsBinaryStandardOutput { |
| 47 | standard int |
| 48 | mut: |
| 49 | stream &PortFileStream |
| 50 | } |
| 51 | |
| 52 | fn (mut sink WindowsBinaryStandardOutput) write(bytes []u8) !int { |
| 53 | // Drain earlier text output before bypassing C stdio through the binary |
| 54 | // duplicate. A failed drain has accepted none of this new byte slice. |
| 55 | flush_standard_output(sink.standard)! |
| 56 | return sink.stream.write(bytes) |
| 57 | } |
| 58 | |
| 59 | fn (mut sink WindowsBinaryStandardOutput) flush() ! { |
| 60 | flush_standard_output(sink.standard)! |
| 61 | sink.stream.flush()! |
| 62 | } |
| 63 | } |
| 64 | |