Nimony

The road to Nim 3

streamio

nimony/lib/std/streamio.nim

Streams: one Reader, one Writer (nim-lang/nimony#2635).

A network connection is as unremarkable as a file. Every constructor returns a Reader, a Writer or both, and after construction the interface is the same whatever is underneath:

.. code-block:: nim var r = openReader(path"log.txt") echo r.readLine()

let (r, w) = connect("cache.local:6379", "PING\r\n") echo r.readLine() # +PONG

var w = openWriter() w.setAdapter gzipAdapter(fmtGzip) w.write data let gz = extract(w)

Pieces:

  • Reader and Writer are concrete, move-only values. A pair returned by

one constructor shares a Core, a ref to the descriptor and the TLS engine if any, which closes the descriptor when the last end is gone.

  • Each end has ONE adapter slot, adapter (compression, HTTP framing, …),

set with setAdapter. Encryption is not an adapter: a TlsEngine lives in the core, because TLS is a property of the connection, not of a direction. So the write path is caller -> adapter -> TLS -> descriptor and the read path the reverse; compression below encryption cannot be written.

  • read answering 0 is the end of the data. Everything that goes wrong

raises an ErrorCode.

  • Streams close themselves. A writer's destructor finishes it (adapter

trailer, TLS close_notify, shutdown(SHUT_WR)) and swallows errors; call close to see them. abort ends a writer without the clean finish.

  • deadline reads the standing I/O deadline; renew replaces it, or clears

it with never. A connection's reader and writer share that deadline. Connection constructors take dl for setup only; the returned streams start with never, so setup does not become a connection lifetime limit.

  • pipe is an in-process Reader/Writer pair over a ring; waiting on

it parks the task, it does not block a thread. std/channels builds typed channels on its record form, recordPipe.

Not here yet (see the issue): openReadWrite, startTls, deadlines for waits on a pipe, sendfile/splice/kTLS fast paths in copy, and cross-thread close of a descriptor another lane is parked on.