module scheme const custom_binary_input_name = 'make-custom-binary-input-port' struct CustomPortInput { resource &CustomPortResource } fn (_ &CustomPortInput) read(mut _bytes []u8) !int { return failure('Scheme port operation needs the resumable I/O driver') } fn custom_input_resource(value Value) &CustomPortResource { if value.tag in [.input_port, .input_output_port] { port := value.input_pointer() if port.source is CustomPortInput { return port.source.resource } if port.source is CustomTranscodedInput { return port.source.resource } } return unsafe { nil } } fn custom_port_resource(value Value) &CustomPortResource { if value.tag == .input_output_port { input := custom_input_resource(value) return if isnil(input) { custom_output_resource(value) } else { input } } return if value.tag == .input_port { custom_input_resource(value) } else { custom_output_resource(value) } } fn custom_binary_input(mut vm VM, args []Value) !Value { check_arity(custom_binary_input_name, args.len, 5, 5)! return vm.make_custom_binary_input_port(args[0].as_string()!, args[1], args[2], args[3], args[4]) } pub fn (mut vm VM) make_custom_binary_input_port(id string, read_callback Value, get_position Value, set_position Value, close Value, options InputOptions) !Value { vm.ready()! vm.check_custom_port_callback(read_callback, false)! vm.check_custom_port_callback(get_position, true)! vm.check_custom_port_callback(set_position, true)! vm.check_custom_port_callback(close, true)! if options.read_size <= 0 { return failure('input read size must be positive') } resource := &CustomPortResource{ id: id, read: read_callback, get_position: get_position, set_position: set_position, close: close } return vm.input_port(&CustomPortInput{ resource: resource }, binary: true read_size: options.read_size ) } fn custom_input_closing(operation PortIoOperation) bool { return operation in [.close_input, .close_any] } fn (mut vm VM) prepare_custom_input_operation(operation PortIoOperation, target Value, args []Value) !&CustomPortOperation { if custom_output_only(operation) { return failure('expected an output port') } if !target.input_pointer().binary { return vm.prepare_custom_text_input(operation, target, args) } port := if custom_input_closing(operation) { vm.input_owner(target)! } else { vm.checked_binary_input(target)! } if port.busy { return failure('input port operation is already active') } mut destination := unspecified() mut start := 0 mut end := 0 mut position := unspecified() match operation { .read_bytes { end = allocation_count(args[0], 1)! } .get_bytes { count := args[1].as_integer()! if count < 0 || count > max_int { return failure('bytevector read count out of bounds') } end = int(count) } .read_into, .get_into { destination = args[if operation == .read_into { 0 } else { 1 }] destination.require_mutable(.bytevector)! data := destination.bytevector_pointer() start, end = if operation == .read_into { sequence_range(args, 2, data.bytes.len)! } else { port_get_put_range(args, data.bytes.len)! } } .read_all, .read_some { end = max_int } .set_position { position = args[1] } .get_u8, .lookahead_u8, .read_u8, .peek_u8, .input_eof, .get_position, .close_input, .close_any { } else { return failure('expected an output port') } } return new_custom_input_operation(operation, target, destination, start, end, position) } fn new_custom_input_operation(operation PortIoOperation, target Value, destination Value, start int, end int, position Value) !&CustomPortOperation { resource := custom_input_resource(target) if !isnil(resource.input_adapter) && operation in [.get_position, .set_position] { return failure('transcoded input port does not support positions') } if operation == .get_position && !resource.get_position.is_callable() { return failure('input port does not support positions') } if operation == .set_position { if target.input_pointer().binary { check_custom_binary_position(position)! } else { checked_custom_text_position(target, position)! } if !resource.set_position.is_callable() { return failure('input port does not support setting positions') } } mut state := &CustomPortOperation{ operation: operation target: target resource: resource source: destination start: start offset: start end: end position: position lease: &CustomPortLease{ port: target, resource: resource, closing: custom_input_closing(operation), input_cursor: operation != .get_position && !custom_input_closing(operation) && !zero_custom_text_read(operation, end) } } unsafe { state.bytes.flags.set(.noslices) } return state } fn (mut vm VM) custom_input_host_operation(operation PortIoOperation, target Value, destination Value, start int, end int, position Value) !Value { state := new_custom_input_operation(operation, custom_combined_facet(operation, target), destination, start, end, position)! return vm.call(procedure_value(&Procedure{ mode: .closure, name: 'custom input operation', owner: vm.owner, function: &custom_port_io_bridges[int(operation)] }), [payload_value(.port_operation, state)]) } // The prefix is immutable once a captured bridge freezes its current buffer. // New branches append to a fresh suffix; repeated capture never copies all // previous input. Materialization places each chunk at its known offset once. @[heap] struct CustomInputChunk { previous &CustomInputChunk = unsafe { nil } bytes []u8 offset int } fn (mut m Machine) detach_custom_port_state() &CustomPortOperation { mut state := custom_port_operation(m.env.slots[0]) if !m.env.escaped { return state } mut scope := m.detach_bridge() prefix := if state.bytes.len == 0 { state.chunks } else { &CustomInputChunk{ previous: state.chunks, bytes: unsafe { state.bytes }, offset: state.offset - state.bytes.len } } state = &CustomPortOperation{ ...state, bytes: []u8{}, chunks: prefix } if !isnil(state.frame) { state.frame = &CustomDatumFrame{ ...state.frame, stack: state.frame.stack.clone(), directive: state.frame.directive.clone() } } if !isnil(state.encoded) { state.encoded = &CustomEncodedState{ ...state.encoded } } if !isnil(state.position_cursor) { // Both records begin with this enum member. Access the compatible // member type directly instead of aliasing an unrelated header struct. kind := unsafe { *(&CustomCursorKind(state.position_cursor)) } if kind == .binary { cursor := state.binary_cursor() state.position_cursor = &CustomBinaryCursor{ ...cursor } } else if kind == .attached { cursor := state.attached_operation() state.position_cursor = &CustomAttachedOperation{ ...cursor } mut next := state.attached_operation() if !isnil(next.probe) { next.probe = &CustomAttachedProbePositions{ ...next.probe } } } else { cursor := state.text_operation() state.position_cursor = &CustomTextOperation{ ...cursor } mut next := state.text_operation() if !isnil(next.probe) { next.probe = &CustomTextProbePositions{ ...next.probe } } } } unsafe { state.bytes.flags.set(.noslices) } scope.slots[0] = payload_value(.port_operation, state) return state } fn (state &CustomPortOperation) input_bytes_result() Value { if state.offset == 0 && state.end != 0 { return eof_value() } if isnil(state.chunks) { return owned_bytevector(unsafe { state.bytes }) } mut result := []u8{len: state.offset} if state.bytes.len > 0 { unsafe { vmemcpy(&u8(result.data) + state.offset - state.bytes.len, state.bytes.data, state.bytes.len) } } mut cursor := state.chunks for !isnil(cursor) { unsafe { vmemcpy(&u8(result.data) + cursor.offset, cursor.bytes.data, cursor.bytes.len) } cursor = cursor.previous } return owned_bytevector(result) } fn (mut m Machine) request_custom_input(mut vm VM, direct bool) ! { mut state := custom_port_operation(m.env.slots[0]) port := state.target.input_pointer() if direct { state.pending = state.source state.request_start = state.offset state.request_count = int_min(port.read_size, state.end - state.offset) } else { mut resource := state.resource // This is the resource's real read-ahead storage, not a VM cache. Hosts // retain arenas backing published port mutations just like native ports. if resource.read_buffer.tag != .bytevector { resource.read_buffer = owned_bytevector([]u8{len: port.read_size}) } state.pending = resource.read_buffer state.request_start = 0 state.request_count = state.pending.bytevector_pointer().bytes.len } begin_custom_binary_callback(state, true) m.push(state.resource.read) m.push(state.pending) m.push(integer(state.request_start)) m.push(integer(state.request_count)) m.apply(mut vm, 3, false)! } fn (mut m Machine) step_custom_input_operation(mut vm VM) ! { mut state := custom_port_operation(m.env.slots[0]) mut port := state.target.input_pointer() match state.operation { .read_u8, .get_u8, .peek_u8, .lookahead_u8, .input_eof { if port.position < port.buffer.len { byte := port.buffer[port.position] if state.operation in [.read_u8, .get_u8] { port.position++ } m.finish_custom_port_operation(if state.operation == .input_eof { boolean(false) } else { integer(byte) }) } else if port.ended { m.finish_custom_port_operation(if state.operation == .input_eof { boolean(true) } else { eof_value() }) } else { m.request_custom_input(mut vm, false)! } } .read_bytes, .get_bytes, .read_all, .read_some { available := port.buffer.len - port.position length := int_min(state.end - state.offset, available) if length > 0 { state.bytes << unsafe { port.buffer[port.position..port.position + length] } port.position += length state.offset += length } if state.offset == state.end || port.ended || (state.operation == .read_some && state.offset > 0) { m.finish_custom_port_operation(state.input_bytes_result()) } else { m.request_custom_input(mut vm, false)! } } .read_into, .get_into { available := port.buffer.len - port.position length := int_min(state.end - state.offset, available) if length > 0 { data := state.source.bytevector_pointer() unsafe { vmemmove(&u8(data.bytes.data) + state.offset, &u8(port.buffer.data) + port.position, length) } port.position += length state.offset += length } if state.offset == state.end || port.ended { m.finish_custom_port_operation(if state.offset == state.start && state.end != state.start { eof_value() } else { integer(state.offset - state.start) }) } else { m.request_custom_input(mut vm, true)! } } .close_input, .close_any { if !claim_custom_combined_close(state.lease) { m.finish_custom_port_operation(unspecified()) return } m.push(state.resource.close) m.apply(mut vm, 0, false)! } .get_position { begin_custom_binary_callback(state, false) m.push(state.resource.get_position) m.apply(mut vm, 0, false)! } .set_position { begin_custom_binary_callback(state, true) m.push(state.resource.set_position) m.push(state.position) m.apply(mut vm, 1, false)! } else { return failure('invalid input port operation') } } } fn (mut m Machine) collect_custom_input_operation(result Value) ! { state := custom_port_operation(m.env.slots[0]) match state.operation { .get_position { raw := custom_port_single_result(result)! check_custom_binary_position(raw)! port := state.target.input_pointer() position := numeric_subtract(raw, integer(port.buffer.len - port.position))! if exact_sign(position) < 0 { return failure('source position precedes buffered input') } m.finish_custom_port_operation(position) } .set_position { mut port := state.target.input_pointer() port.buffer = []u8{} port.position = 0 port.mark = -1 port.ended = false port.location = unsafe { nil } m.finish_custom_port_operation(unspecified()) } .close_input, .close_any { m.finish_custom_port_operation(unspecified()) } else { count := custom_port_single_result(result)!.as_integer()! if count < 0 || count > state.request_count { return failure('custom reader returned an invalid count') } mut current := m.detach_custom_port_state() mut port := current.target.input_pointer() port.ended = count == 0 if current.operation in [.read_into, .get_into] { current.offset += int(count) } else { data := current.pending.bytevector_pointer() port.buffer = unsafe { data.bytes[..int(count)] } port.position = 0 } current.pending = unspecified() } } }