vile / scheme / port.v
443 lines · 401 sloc · 12.95 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import io
4import os
5
6// InputOptions controls read-ahead from a host Reader. A reader that waits for
7// its entire requested buffer should use read_size: 1 for interactive input.
8@[params]
9pub struct InputOptions {
10pub:
11 read_size int = 4096
12 binary bool
13 fold_case bool = true
14}
15
16@[params]
17pub struct OutputOptions {
18pub:
19 binary bool
20}
21
22@[heap]
23struct InputPort {
24 owner &Owner
25 read_size int
26mut:
27 source io.Reader
28 file &os.File = unsafe { nil }
29 stream &PortFileStream = unsafe { nil }
30 file_backed bool // source classification survives closing and transcoding
31 owns_file bool
32 closed bool
33 busy bool
34 ended bool
35 binary bool
36 no_fold bool
37 memory_input bool
38 transcoder_code u8
39 buffer []u8
40 position int
41 mark int = -1
42 location &InputLocation = unsafe { nil }
43}
44
45@[heap]
46struct OutputPort {
47 owner &Owner
48mut:
49 sink io.Writer
50 file &os.File = unsafe { nil }
51 stream &PortFileStream = unsafe { nil }
52 file_backed bool // source classification survives closing and transcoding
53 owns_file bool
54 closed bool
55 busy bool
56 binary bool
57 transcoder_code u8
58 buffer_mode PortBufferMode = .none
59 memory_output &MemoryPortOutput = unsafe { nil }
60}
61
62@[heap]
63struct PortState {
64mut:
65 bindings &PortBinding = unsafe { nil }
66 transcoder_symbols &TranscoderSymbols = unsafe { nil }
67}
68
69// Keep stdio's V descriptor in an explicit heap object. An interface and the
70// close/flush path refer to the same descriptor throughout the port's lifetime.
71@[heap]
72struct PortFileStream {
73mut:
74 file os.File
75 file_budget &FileResourceBudget = unsafe { nil }
76 bounded_link &BoundedFileLink = unsafe { nil }
77 raw bool
78 descriptor_only bool
79 buffer_mode PortBufferMode = .block
80 pending []u8
81}
82
83fn (mut stream PortFileStream) read(mut bytes []u8) !int {
84 if !stream.raw { return stream.file.read(mut bytes) }
85 return file_read_bytes(stream.file.fd, mut bytes)
86}
87
88fn (mut stream PortFileStream) write(bytes []u8) !int {
89 if !stream.raw { return stream.file.write(bytes) }
90 if stream.buffer_mode == .none { return file_write_bytes(stream.file.fd, bytes) }
91 if stream.pending.len == 0 && bytes.len >= 4096 {
92 return file_write_bytes(stream.file.fd, bytes)
93 }
94 if bytes.len > 4096 - stream.pending.len { stream.flush_pending()! }
95 if bytes.len >= 4096 { return file_write_bytes(stream.file.fd, bytes) }
96 if stream.pending.cap == 0 {
97 stream.pending = []u8{cap: 4096}
98 unsafe { stream.pending.flags.set(.noslices) }
99 }
100 stream.pending << bytes
101 return bytes.len
102}
103
104// input_port borrows a host Reader, keeping its interface object alive. Closing
105// this port does not close the host resource. Readers must not retain the
106// borrowed destination buffer, resize it, or reenter an operation on the same port.
107pub fn (mut vm VM) input_port(source io.Reader, options InputOptions) !Value {
108 vm.ready()!
109 if options.read_size <= 0 { return failure('input read size must be positive') }
110 mut port := &InputPort{ owner: vm.owner, source: source, file_backed: source is PortFileStream || source is os.File, read_size: options.read_size, binary: options.binary, no_fold: !options.fold_case }
111 // Buffer borrows exist only during Reader.read or completed datum decoding.
112 // Neither can overlap growth or compaction of this privately owned storage.
113 unsafe { port.buffer.flags.set(.noslices) }
114 return payload_value(.input_port, port)
115}
116
117// output_port borrows a host Writer. Each write must consume its byte slice
118// before returning; short writes are retried. Closing does not close the host.
119pub fn (mut vm VM) output_port(sink io.Writer, options OutputOptions) !Value {
120 vm.ready()!
121 return payload_value(.output_port, &OutputPort{ owner: vm.owner, sink: sink, file_backed: sink is PortFileStream || sink is os.File, binary: options.binary })
122}
123
124fn (mut vm VM) port_state() &PortState {
125 if isnil(vm.ports) { vm.ports = &vm.port_storage }
126 return vm.ports
127}
128
129pub fn (mut vm VM) current_input_port() !Value {
130 vm.ready()!
131 return vm.current_input_value()
132}
133
134fn (mut vm VM) current_input_value() !Value {
135 return vm.current_port_value(0)
136}
137
138pub fn (mut vm VM) current_output_port() !Value {
139 vm.ready()!
140 return vm.current_output_value()
141}
142
143fn (mut vm VM) current_output_value() !Value {
144 return vm.current_port_value(1)
145}
146
147pub fn (mut vm VM) set_input_port(value Value) ! {
148 vm.ready()!
149 vm.input_owner(value)!
150 vm.set_port_value(0, value)
151}
152
153pub fn (mut vm VM) set_output_port(value Value) ! {
154 vm.ready()!
155 vm.output_owner(value)!
156 vm.set_port_value(1, value)
157}
158
159fn (value Value) input_pointer() &InputPort {
160 return unsafe { &InputPort(value.pointer()) }
161}
162
163fn (value Value) output_pointer() &OutputPort {
164 if value.tag == .input_output_port {
165 port := unsafe { &InputOutputPort(value.pointer()) }
166 return &port.output
167 }
168 return unsafe { &OutputPort(value.pointer()) }
169}
170
171fn (vm &VM) input_owner(value Value) !&InputPort {
172 if value.tag !in [.input_port, .input_output_port] { return failure('expected an input port') }
173 port := value.input_pointer()
174 if voidptr(port.owner) != voidptr(vm.owner) {
175 return failure('input port belongs to another VM')
176 }
177 return port
178}
179
180fn (vm &VM) output_owner(value Value) !&OutputPort {
181 if value.tag !in [.output_port, .input_output_port] {
182 return failure('expected an output port')
183 }
184 port := value.output_pointer()
185 if voidptr(port.owner) != voidptr(vm.owner) {
186 return failure('output port belongs to another VM')
187 }
188 return port
189}
190
191fn (vm &VM) checked_input(value Value) !&InputPort {
192 port := vm.input_owner(value)!
193 check_combined_busy(value)!
194 if port.closed { return failure('input port is closed') }
195 if port.busy { return failure('input port operation is already active') }
196 return port
197}
198
199fn (vm &VM) checked_output(value Value) !&OutputPort {
200 port := vm.output_owner(value)!
201 check_combined_busy(value)!
202 if port.closed { return failure('output port is closed') }
203 if port.busy { return failure('output port operation is already active') }
204 return port
205}
206
207fn (vm &VM) checked_text_input(value Value) !&InputPort {
208 port := vm.checked_input(value)!
209 if port.binary { return failure('expected a textual input port') }
210 return port
211}
212
213fn (vm &VM) checked_text_output(value Value) !&OutputPort {
214 port := vm.checked_output(value)!
215 if port.binary { return failure('expected a textual output port') }
216 return port
217}
218
219pub fn (mut vm VM) close_input_port(value Value) ! {
220 vm.ready()!
221 mut port := vm.input_owner(value)!
222 check_combined_busy(value)!
223 if port.busy { return failure('input port operation is already active') }
224 if port.closed { return }
225 if !isnil(custom_input_resource(value)) {
226 vm.custom_input_host_operation(.close_input, value, unspecified(), 0, 0, unspecified())!
227 return
228 }
229 port.closed = true
230 defer {
231 port.buffer = []u8{}
232 port.source = &closed_port
233 }
234 mut group := combined_transcoded_resource(value)
235 mut file := combined_file_resource(value)
236 if !isnil(group) {
237 group.close_half(true)!
238 } else if !isnil(file) {
239 file.close_half(true)!
240 } else if port.transcoder_code != 0 {
241 if mut port.source is TranscodedResourceCloser {
242 mut source := port.source
243 source.close_original()!
244 }
245 } else if port.owns_file {
246 port.stream.close()!
247 }
248}
249
250pub fn (mut vm VM) close_output_port(value Value) ! {
251 vm.ready()!
252 mut port := vm.output_owner(value)!
253 check_combined_busy(value)!
254 if port.busy { return failure('output port operation is already active') }
255 if port.closed { return }
256 if !isnil(custom_output_resource(value)) {
257 vm.custom_output_host_operation(.close_output, value, unspecified(), 0, 0, unspecified())!
258 return
259 }
260 port.closed = true
261 port.busy = true
262 defer {
263 port.busy = false
264 port.sink = &closed_port
265 }
266 mut group := combined_transcoded_resource(value)
267 mut file := combined_file_resource(value)
268 if !isnil(group) {
269 group.close_half(false)!
270 } else if !isnil(file) {
271 file.close_half(false)!
272 } else if port.transcoder_code != 0 {
273 if mut port.sink is TranscodedResourceCloser {
274 mut sink := port.sink
275 sink.close_original()!
276 }
277 } else if port.owns_file {
278 port.stream.close()!
279 } else if mut port.sink is OutputFlusher {
280 mut sink := port.sink
281 sink.flush()!
282 }
283}
284
285fn (mut port InputPort) refill() ! {
286 port.fill_buffer(false)!
287}
288
289fn (mut port InputPort) fill_buffer(nonblocking bool) !bool {
290 if port.mark < 0 && port.position > 0 {
291 port.checkpoint_input()
292 remaining := port.buffer.len - port.position
293 if remaining > 0 {
294 unsafe { vmemmove(port.buffer.data, &u8(port.buffer.data) + port.position, remaining) }
295 }
296 unsafe { port.buffer.len = remaining }
297 port.position = 0
298 }
299 start := port.buffer.len
300 if port.read_size > max_int - start { return failure('input buffer exceeds supported range') }
301 port.buffer.ensure_cap(start + port.read_size)
302 // Only bytes live in this private range. Publish just the actual read count,
303 // including on EOF/error; the source callback cannot reenter this port.
304 unsafe { port.buffer.len = start + port.read_size }
305 mut published := start
306 defer { unsafe { port.buffer.len = published } }
307 mut destination := unsafe { port.buffer[start..] }
308 count := (if nonblocking {
309 if mut port.source is ReadyReader {
310 mut capable := port.source
311 capable.read_ready(mut destination)
312 } else {
313 return failure('host reader does not support nonblocking input')
314 }
315 } else {
316 port.source.read(mut destination)
317 }) or {
318 if err is io.Eof || err is os.Eof {
319 port.ended = true
320 return true
321 }
322 return err
323 }
324 if nonblocking && count == -1 { return false }
325 if count < 0 || count > port.read_size {
326 return failure('reader returned an invalid byte count')
327 }
328 published = start + count
329 if count == 0 { port.ended = true }
330 return true
331}
332
333fn (mut port InputPort) ensure_bytes(count int) !bool {
334 for port.buffer.len - port.position < count {
335 if port.ended { return false }
336 port.refill()!
337 }
338 return true
339}
340
341// Each cursor access follows ensure_bytes; a marked datum prevents relocation.
342@[direct_array_access]
343fn (mut port InputPort) peek_character() !(rune, int) {
344 if !port.ensure_bytes(1)! { return rune(0), 0 }
345 first := port.buffer[port.position]
346 if first < 0x80 { return rune(first), 1 }
347 width := if first >= 0xc2 && first <= 0xdf {
348 2
349 } else if first >= 0xe0 && first <= 0xef {
350 3
351 } else if first >= 0xf0 && first <= 0xf4 {
352 4
353 } else {
354 return port.input_error(port.position, 'input is not valid UTF-8')
355 }
356 if !port.ensure_bytes(width)! {
357 return port.input_error(port.position, 'incomplete UTF-8 character at end of input')
358 }
359 mut scalar := u32(first & u8((1 << (7 - width)) - 1))
360 for i in 1 .. width {
361 next := port.buffer[port.position + i]
362 if next & 0xc0 != 0x80 {
363 return port.input_error(port.position, 'input is not valid UTF-8')
364 }
365 scalar = (scalar << 6) | u32(next & 0x3f)
366 }
367 if (width == 3 && scalar < 0x800) || (width == 4 && scalar < 0x10000) || scalar > 0x10ffff || (scalar >= 0xd800 && scalar <= 0xdfff) {
368 return port.input_error(port.position, 'input is not valid UTF-8')
369 }
370 return rune(scalar), width
371}
372
373fn eof_value() Value {
374 return Value{ tag: .eof }
375}
376
377pub fn (mut vm VM) peek_char(value Value) !Value {
378 vm.ready()!
379 return vm.port_character(value, false)
380}
381
382pub fn (mut vm VM) read_char(value Value) !Value {
383 vm.ready()!
384 return vm.port_character(value, true)
385}
386
387fn (mut vm VM) port_character(value Value, advance bool) !Value {
388 mut port := vm.checked_text_input(value)!
389 if !isnil(custom_input_resource(value)) {
390 return vm.custom_text_input_host_operation(if advance {
391 PortIoOperation.read_char
392 } else {
393 PortIoOperation.peek_char
394 }, value, unspecified(), 0, 0, unspecified())
395 }
396 port.busy = true
397 defer { port.busy = false }
398 c, width := port.peek_character()!
399 if width == 0 { return eof_value() }
400 if advance { port.position += width }
401 // The decoder already validated this scalar at the stream boundary.
402 return Value{ tag: .character, bits: ValueBits{ whole: i64(c) } }
403}
404
405fn (mut port OutputPort) write_text(text string) ! {
406 port.write_bytes(unsafe { text.str.vbytes(text.len) })!
407}
408
409fn (mut port OutputPort) write_bytes(bytes []u8) ! {
410 port.busy = true
411 defer { port.busy = false }
412 mut offset := 0
413 for offset < bytes.len {
414 remaining := bytes.len - offset
415 count := port.sink.write(unsafe { bytes[offset..] })!
416 if count <= 0 || count > remaining {
417 return failure('writer returned an invalid byte count')
418 }
419 offset += count
420 }
421 // Flush after the Writer has acknowledged its bytes. A flush failure must
422 // not cause a transcoder to save an already-accepted batch for write retry.
423 if port.buffer_mode == .line && bytes.index(u8(`\n`)) >= 0 {
424 if mut port.sink is OutputFlusher {
425 mut sink := port.sink
426 sink.flush()!
427 }
428 }
429}
430
431// A closed wrapper keeps no potentially large host Reader or Writer graph alive.
432struct ClosedPort {}
433
434// closed_port drops a host I/O graph without allocating an interface box.
435const closed_port = ClosedPort{}
436
437fn (_ ClosedPort) read(mut _bytes []u8) !int {
438 return failure('input port is closed')
439}
440
441fn (_ ClosedPort) write(_bytes []u8) !int {
442 return failure('output port is closed')
443}
444