6.61. kink/io/GENERATOR_INPUT¶
6.61.1. GENERATOR_INPUT.new($generator)¶
`new` returns an `input` whose bytes are written to an `output` within invocation of $generator.
Example
:BIN.require_from('kink/')
:CONTROL.require_from('kink/')
:GENERATOR_INPUT.require_from('kink/io/')
CONTROL.with_finally{(:finally)
:In = GENERATOR_INPUT.new{(:Out)
Out.write(BIN.of(1 2 3))
Out.write(BIN.of(4 5 6 7))
Out.write(BIN.of(8 9 10 11 12))
}
finally{ In.close }
:loop <- {
In.read(4){(:C)
C.on_success{(:Bin)
stdout.print_line(Bin.repr)
loop
}
C.on_eof{ stdout.print_line('EOF') }
}
}
loop
}
# Output:
# (bin 0x01 0x02 0x03)
# (bin 0x04 0x05 0x06 0x07)
# (bin 0x08 0x09 0x0a 0x0b)
# (bin 0x0c)
# EOF
Pass bytes
When `In.read` is called for the first time, $generator is called with an `output`.
When `Out.write` is called within the invocation of $generator, the invocation of $generator is suspended, and the bytes are given to the `input`.
When more bytes are required by the `input`, the invocation of $generator is resumed.
When the invocation of $generator returns, the `input` reaches EOF.
Close the `input`
The `input` made by `new` is recommended to be closed using CONTROL.with_finally, so that finalization is properly done in $generator.
If the `input` is closed before `In.read`, or after reaching EOF, it marks the input as the closed status.
If the `input` is closed when there is a suspended invocation of $generator, the invocation is resumed, then the current and subsequent invocations of `Out.write` will receive an IO error.
Exception raised from $generator
If $generator raises an exception, the current and subsequent invocations of `In.read`, or the current invocation of `In.close` will receive an IO error.
Should not close `output`
You should not close the `output` given to $generator. `Out.close` always receives an IO error.
Precondition
$generator must be a function which takes an `output`.