Skip to content

Sink[T]

Abstract type for sinks, whose instances have the methods below. Built-in sinks are Sink; a class that only implements (put) is not.

Sink is not constructible directly.

assert_eq (type $ [].sink()) $Sink

Inherits from: Sinkable[T]

Implements: BaseSink[T]

Methods

prechomp[U @ (Str | Bin)]() -> Sink[U]

Creates a wrapper Sink which removes a trailing line terminator (\n or \r\n) from each item, if present, before it is written.

Parameters

NameTypeDescription
self Sink[U] Receiver.

Errors

Putting an item raises TypeError if it is neither neither a Str nor a Bin.

Example

let acc = []
let out = acc.prechomp()
out.put "line\n"
assert_eq $acc ["line"]

precrimp[U @ (Str | Bin)] … -> Sink[U]

Creates a wrapper Sink that appends a terminator to each value before it is written. The append is unconditional, so an item that already ends in one gets a second.

Parameters

NameTypeDescription
self Sink[U] Receiver.
terminator? (Str | Bin)

Errors

Raises TypeError for a value, or a terminator, that is neither a Str nor a Bin, or if a Bin terminator would leave a Str value invalid UTF-8.

Example

let out = shell.stdout.precrimp()
out.put "hello"
# writes "hello\n"

open $path w do |file|
  file.precrimp(shell.line_ending()).put "native"

prefilter pred -> Sink[T]

Wraps the sink so only values for which pred is truthy are written.

Because each wrapper transforms values on the way in, the outermost wrapper sees a value first — the reverse of an iterator chain.

Parameters

NameTypeDescription
pred ((T) -> Value)

Example

let acc = []
let out = acc.prefilter (do |x| x % 2 == 0)
out.put 1
out.put 2
assert_eq $acc [2]

premap[U] func -> Sink[U]

Wraps the sink so each value is transformed before it is written.

The pre prefix marks the direction: unlike Iter.map, which transforms values on their way out, premap transforms values on their way into the sink. A value that is both Iterable and Sinkable — an Array, say — therefore offers map and premap as separate methods running in opposite directions.

Parameters

NameTypeDescription
func ((U) -> T)

Example

let acc = []
let out = acc.premap (do |x| x * 2)
out.put 3
assert_eq $acc [6]

put value

Writes a value to the sink.

Parameters

NameTypeDescription
value T