| 1 | module scheme |
| 2 | |
| 3 | import os |
| 4 | |
| 5 | const standard_binary_port_names = 'standard-input-port standard-output-port standard-error-port' |
| 6 | |
| 7 | const standard_binary_port_descriptors = [ |
| 8 | NativeDescriptor{'standard-input-port', port_standard_input} |
| 9 | NativeDescriptor{'standard-output-port', port_standard_output} |
| 10 | NativeDescriptor{'standard-error-port', port_standard_error}, |
| 11 | ]! |
| 12 | |
| 13 | fn (mut vm VM) install_standard_binary_ports() { |
| 14 | for i in 0 .. standard_binary_port_descriptors.len { |
| 15 | entry := &standard_binary_port_descriptors[i] |
| 16 | vm.bind_global(entry.name, procedure_value(&Procedure{ mode: .native, owner: vm.owner, name: entry.name, native: entry.callback })) |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | // Stable owner storage is shared by fresh wrappers and the ordinary default |
| 21 | // ports. It contains only process stdio descriptors, never caller-arena buffers. |
| 22 | fn (mut vm VM) standard_stream(index int) &PortFileStream { |
| 23 | mut stream := &vm.owner.stdio.streams[index] |
| 24 | if !stream.file.is_opened { |
| 25 | stream.file = match index { |
| 26 | 0 { os.stdin() } |
| 27 | 1 { os.stdout() } |
| 28 | else { os.stderr() } |
| 29 | } |
| 30 | } |
| 31 | return stream |
| 32 | } |
| 33 | |
| 34 | // Each wrapper owns its lookahead and closed state. Shared C stdio read-ahead |
| 35 | // stays coherent when binary and default textual wrappers alternate reads. |
| 36 | pub fn (mut vm VM) standard_input_port() !Value { |
| 37 | vm.ready()! |
| 38 | $if windows { |
| 39 | return vm.windows_standard_input() |
| 40 | } $else { |
| 41 | return vm.input_port(vm.standard_stream(0), binary: true, read_size: 1) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | pub fn (mut vm VM) standard_output_port() !Value { |
| 46 | return vm.standard_output_value(1) |
| 47 | } |
| 48 | |
| 49 | pub fn (mut vm VM) standard_error_port() !Value { |
| 50 | return vm.standard_output_value(2) |
| 51 | } |
| 52 | |
| 53 | fn (mut vm VM) standard_output_value(index int) !Value { |
| 54 | vm.ready()! |
| 55 | $if windows { |
| 56 | return vm.windows_standard_output(index) |
| 57 | } $else { |
| 58 | return vm.output_port(vm.standard_stream(index), binary: true) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | fn port_standard_input(mut vm VM, args []Value) !Value { |
| 63 | check_arity('standard-input-port', args.len, 0, 0)! |
| 64 | return vm.standard_input_port() |
| 65 | } |
| 66 | |
| 67 | fn port_standard_output(mut vm VM, args []Value) !Value { |
| 68 | check_arity('standard-output-port', args.len, 0, 0)! |
| 69 | return vm.standard_output_port() |
| 70 | } |
| 71 | |
| 72 | fn port_standard_error(mut vm VM, args []Value) !Value { |
| 73 | check_arity('standard-error-port', args.len, 0, 0)! |
| 74 | return vm.standard_error_port() |
| 75 | } |
| 76 | |