ilusm.dev

strio

Reader/writer records - construct a reader from read(n) and read_all() functions, construct a writer from a write(s) function, check whether an object satisfies the reader or writer interface, read n bytes, read all, write a string, get a stdin reader, get a stdout writer, and pipe a reader into a writer in configurable chunks.

Load with: use strio

What this module does

strio defines a simple interface contract: a reader is any object with .read(n) and .read_all() fields that are functions; a writer is any object with a .write(s) function. This mirrors the Go io.Reader/io.Writer pattern. The pipe helper reads from any reader in chunks and writes to any writer, returning the total bytes transferred.

Quick example

use strio

# Custom reader and writer
buf = ""
r = strdr(\(n) txt.sub(source, pos, pos+n), \() source)
w = strwr(\(s) buf = buf + s)

# Pipe reader to writer (4096-byte chunks)
n = strpi(r, w, [4096])
prn("copied " + str(n) + " bytes")

# Stdin / stdout
in  = stdin()
out = stdou()

all = rdall(in)      # read all stdin
wr(out, all)         # write it to stdout

# Type checking
prn(isrd(in))   # tru
prn(iswr(out))  # tru

Functions

Construction

strdr(read_fn, read_all_fn)

Creates a reader record {read, read_all}. Both arguments must be functions.

strwr(write_fn)

Creates a writer record {write}. Argument must be a function.

stdin()

Returns a reader backed by __sys_stdin_read and __sys_stdin_all.

stdou()

Returns a writer backed by __sys_write_stdout.

Interface checks

isrd(r)

Returns tru if r is an object with read and read_all function fields.

iswr(w)

Returns tru if w is an object with a write function field.

Reading and writing

rd(r, n)

Reads up to n bytes from reader r. Returns a string or nil on EOF.

rdall(r)

Reads all remaining content from reader r.

wr(w, s)

Writes string s to writer w.

strpi(r, w, chunk)

Pipes all content from reader r to writer w in chunks of chunk[0] bytes (default 4096). Returns total bytes written.

Notes

  • Requires txt, trl, and eru.