Skip to reference

std.net

wolf-std d58f9e1 · toolchain pin verified against wolf 0.2.41 (0261597). Source signatures and documentation; execution support is stated in each module.

All modules · Plain text · Stability tier: core

Module

std.net — blocking TCP over rows: bind a listener, accept or dial a connection, read and write text on it, and close it exactly once. Stability tier: core.

Errors are rows, never traps (D30, API-CONVENTIONS §2's trap rule and §14's restatement of it for the os tier): a refused connection, a peer that finished, a deadline, bytes that are not text and every other host failure are ORDINARY outcomes a caller handles with else or propagates with ?. Nothing here traps, and nothing returns a sentinel. The vocabulary is the s39 builtin tier's, adopted verbatim so that std adds no translation layer:

- refused — nobody is listening at that address - timeout — the operation's deadline expired. Declared from sc08 so the vocabulary would be stable, REACHABLE since sc29: set_deadline / set_listener_deadline arm the budget (s106's net_deadline) - closed — the peer finished: the socket's eof, an outcome rather than a failure, and the value that ends a read loop - utf8 — the bytes read are not well-formed UTF-8; a wolf str is UTF-8 by definition, so a read that cannot decode is a miss - io — every other host failure, including a forged, closed or wrong-kind handle, coarsened to one tag because no caller can act differently on them yet (§12's rule 3)

**Capability: net (I13).** Every function here except the two address helpers reaches the host's network stack, is tagged net in the toolchain's sandbox table, and is categorically refused at comptime (D33) — sockets are the loudest case of that rule: wolf add must never mean arbitrary code talks to the network with the builder's credentials. The refusal is E0701, and tests/net/comptime_refuses.lu holds it — one level down, at the builtin, because a comptime fn cannot call across a module boundary at this pin and so cannot reach this facade at all (F-0051).

Loopback and port 0, always — no external network, EVER. Every test and every doc example in this module binds 127.0.0.1:0: the host assigns an ephemeral port and the program learns it through port. Nothing here names a fixed port, a foreign host or a name to resolve. connect hands its address string to the host, which means a hostname WOULD be resolved by the host resolver — std does not do it, does not test it, and dns/resolve is not a function this module has (see below). Addr, the value a resolver will answer, is here (sc67), and its tests build their addresses by hand.

Two operations sc08 withdrew are HERE now (sc11): read_all and read_lines, with write_line as the sending half that pairs with them. All three need a loop that stops on closed and re-raises timeout/utf8/io unchanged, which needs a handler that can say WHICH tag fired — the shape that matched its first arm for every tag on the executing lane through all of sc08 and sc09 (F-0052, closed at s70; F-0043's payload half at s71). The version this module refused to ship for two sprints would have treated a read error as the end of the stream and handed back a truncated message with no indication, which is what §14's rule about an indistinguishable failure mode exists to prevent.

The three-way split (§8/§9's rule, applied to sockets). The IMPLEMENTATION owns the builtins this module delegates to (net_listen, net_port, net_accept, net_connect, net_read, net_write, net_read_bytes, net_write_bytes, net_deadline, net_close) — their semantics are therefore part of this module's contract and are documented per function. std owns everything else: the Listener and Socket values, the consuming closers, the pure address helpers and Addr. The LANGUAGE owns nothing here; there is no socket syntax.

**The SECOND address family lives in std.net.unix (sc36).** This module is TCP over "host:port"; [os.net.unix]'s stream socket over a filesystem PATH is std.net.unix.listen/connect, and it is a separate module for §1's reason — wolf has no overloading, so listen and connect cannot mean two things here. What that module returns is one of THESE types: a unix listener is a Listener, a unix connection is a Socket, and every function below serves them call for call (tests/net/unix/stream_surface.lu measures the byte pair and both deadlines over a socket path). Two functions behave differently on one, and both say so in their own docs: port answers io because a path has no port, and close_listener UNLINKS the path it bound.

Blocking, and what that means for a program. accept waits for a connection and read waits for bytes. write_some is the non-parking exception: it sends what fits or answers busy; std.poll waits for room. There is no reactor, no task parking and no select at this tier — X6's completion-io posture is the s35 reactor's story and reaches std when the builtin tier does. Two consequences a caller must design around: a server written over these functions serves one connection at a time, and an accept with no peer coming never returns UNLESS a deadline is armed (set_listener_deadline, sc29 — before it, never returns full stop, which is why every test in this module connects BEFORE it accepts; the dial-first discipline stays, a deadline is a net for a mistake rather than a license to block).

What is deliberately absent. Each of these is a reviewed contract with a filing behind it rather than an approximation:

- ~~set_deadline(mut s, millis)~~ — HERE now (sc29). For nine sprints the timeout tag was declared and unreachable (F-0049: the runtime held a per-socket deadline no builtin exposed); s106's net_deadline builtin (#45's builtin half) closed the gap, and set_deadline below wraps it on ALL THREE lanes — lupin 0.1.18 arms it too, measured. The pure-addition promise this bullet made was kept: no signature changed, the tag the vocabulary carried from day one is simply reachable at last, and tests/net/read_deadline_row.lu witnesses it firing. - read_line(mut s) -> str ! {closed, timeout, utf8, io} — ONE line, as it arrives. Still blocked, and this is now the module's only blocked read: a buffered reader is writable in principle (a str field mutated through a mut parameter works on both executing lanes, measured in sc08) but FILLING the buffer is a byte-count read, and a chunk that ends inside a code point is a utf8 miss whose bytes are already gone (F-0050). A line reader that corrupts the moment a stream carries a non-ASCII character is not a partial function, it is a broken one; §9's "refusal over approximation" decides it. read_lines below is NOT a substitute — it returns nothing until the peer closes — and the difference is stated on both. - write_all — **not shipped because write already is one.** The builtin writes the whole str or raises; a short write is not observable, so a write_all loop here would be ceremony documenting a hazard that does not exist at this pin. write_some is the partial complement; write and write_bytes still drain the whole input. - ~~write_some~~ — HERE now (sc83, wolf 0.2.40): one send, never parks, counts the bytes taken, busy when nothing fits. Both TCP and Unix streams use it, including PAX's 4096-byte Unix buffer. The server retains its queue and asks std.poll for WRITE until drained. lupin 0.1.62 serves this send too; the function below states its rows. - shutdown(mut s, half) — an orderly half-close. No builtin, so a writer cannot say "I am done sending" without closing the whole socket (F-0049). - peer_address / local_address — port is the only address information the builtin tier reports, and it reports it as an int for the LOCAL end (F-0049). - resolve(name, within) — a NAME turned into its addresses WITHOUT dialling it (wolf-std#4, lobo's ask since ws13). Re-measured at wolf 0.2.33 (sc67): the prelude's twenty net_* builtins hold no call that takes a name and answers addresses. net_connect resolves inside the dial, answers a socket, and bounds neither the resolve nor the handshake (wolf-lang#217); net_fetch is the s16 sandbox probe, unsupported on all four machines. A resolver in std over today's builtins would be a DNS client speaking for the host's resolver — ignoring /etc/hosts, nsswitch.conf and the windows resolver, and answering differently from connect for the same name — which §14 forbids a capability module. So the call is asked of wolf-lang (a bounded, synchronous net_resolve, its exact shape on Addr below) and the VALUE it will answer ships now: Addr, an address and its IP version, so a consumer (lobo's own stub client, today) can type its answers in the shape resolve will hand back. - UDP (send_to/recv_from) and any HTTP: no builtin surface at this pin, and the sprint's non-targets besides. TLS is never this tier's business. - ~~Byte-level read_bytes/write_bytes~~ — HERE now (sc29). F-0080 predicted the fix's exact shape from the fs tier's (s90) and s106 shipped it: net_read_bytes/net_write_bytes carry List[byte] with no utf8 row anywhere — a lone 0x80 is data — and the wrappers below adopt them verbatim. This is what makes a BINARY protocol over TCP writable at all (std.x.tls.client is the first consumer: a TLS record is not text). The one lane cost is lupin's: 0.1.18's is18 socket tier is the STR calls only, the byte pair does not resolve there (F-0102, filed), so the byte functions are compiler-lanes-only where the rest of the module is three-lane. read keeps its utf8 row for the callers that want text.

Lanes (re-measured at the sc29 pin, wolf v0.2.0 + lupin 0.1.18). The str tier and set_deadline run on ALL THREE lanes now: the checked tier since s39, the native rung since s106 crossed net (the "checked lane only at s39" refusal this paragraph used to record is history), and lupin since 0.1.18's is18 sockets (nonblocking polls under the baton). The byte tier (read_bytes/write_bytes) is the exception: both compiler rungs run it, lupin does not resolve it (F-0102) — a program that reaches it there is an honest unsupported at resolve, and because lupin resolves module bodies LAZILY the rest of the module keeps its lane. Comptime refuses the whole capability everywhere (D33).

Modules

Types and traits

Listener

struct · Source line 193

pub struct Listener { fd: int, }

A bound listener: the host socket this process accepts connections on.

TCP when listen made it, unix-domain when std.net.unix.listen did, and nothing in the value records which — the operations are identical once the socket exists, which is why there is one type (sc36). The two places the family shows through are port and close_listener, and both are documented where they are.

The field is an int because that is what the builtin tier hands out — a small non-negative index into the machine's socket table, never a pointer. Reading it is legal; passing a hand-built Listener to accept is not a trap but a miss (io), because a forged descriptor is a checkable condition rather than a contract violation, and a public struct's field cannot be private at this pin.

Staleness is prevented by the mode system, exactly as it is for std.fs.File: close_listener takes its Listener by take (X1), so using one after closing it is a static use-after-move rather than a row on every operation for a condition the compiler can see.

Socket

struct · Source line 207

pub struct Socket { fd: int, }

A connected socket: one end of an established stream, whichever side opened it and whichever address family carried it.

accept, connect and std.net.unix.connect all answer one of these, and nothing about the value records which — the operations are identical once the connection exists, which is the whole point of the type. No function here behaves differently on a unix-domain stream: close never touches a path, because the LISTENER owns the name. The field is an int for the reasons Listener's is, and close consumes the value for the same reason close_listener does.

Addr

struct · Source line 947

pub struct Addr { version: int, text: str, }

One address of a host: its IP version and its text — the element resolve will answer, and the part of a resolver std can fix before the call that makes one exists.

**Nothing in std makes or takes an Addr at this pin, and this doc says why rather than hiding it.** A name cannot be turned into its addresses without dialling it (wolf-std#4): no builtin at wolf 0.2.33 resolves (re-measured by sc67; the module header has the list), and a DNS client written here would speak for the host's resolver without being it. The builtin std is waiting for is asked of wolf-lang, the first half of wolf-lang#217 with its shape made exact:

net_resolve(name: str, within_ms: int) -> List[str] ! {invalid, not_found, timeout, io}

Synchronous and bounded: it returns inside within_ms with the host resolver's answer (/etc/hosts, nsswitch.conf, the windows resolver — the same addresses, in the same order, connect would try) or with timeout; not_found when the resolver says the name has no address, invalid for a name or budget refused before the host, io for every other failure, a temporary one included. Over it std ships resolve(name, within) -> List[Addr] ! {invalid, not_found, timeout, io} (the spelling is that lane's), and this type is its element, unchanged.

Two fields, both public, so a caller builds one directly — a consumer with its own stub client (lobo's, today) can type its answers in the shape resolve will hand back:

- version is the address family as its IP VERSION, 4 or 6 — the number the IP header itself carries, never the host's AF_INET/AF_INET6 constant, which differs between linux, macOS and windows. An int rather than an enum on purpose: at this pin no caller on any of the four machines can name an imported enum's variant, and lupin cannot match one (sc67's probes, F-0154). - text is the address as the resolver writes it: dotted-quad for version 4, RFC 5952 text for version 6, which always holds a :, so the two forms never meet. It is a HOST, not an endpoint: endpoint(a.text, port) makes the string connect dials, and brackets a version-6 address on the way.

Nothing is validated, as nothing is in endpoint: a hand-built Addr whose text the host cannot parse comes back as an io row from connect, where the host is the authority, and version is the builder's claim, which a resolver's answer always makes true. Pure data: no capability, comptime-safe.

let a = net.Addr { version: 6, text: "::1" }
a.version == 6 && net.endpoint(a.text, 443) == "[::1]:443"
let b = net.Addr { version: 4, text: "127.0.0.1" }
net.endpoint(b.text, 0) == net.loopback(0)

ListenOpts

struct · Source line 973

pub struct ListenOpts { reuse_port: bool, backlog: int, }

The options listen_with takes: what a prefork server needs and nothing else.

Two fields, both public and both meaningful on their own, so a caller writes the literal directly — net.ListenOpts { reuse_port: true, backlog: 128 } — or starts from listen_opts() below and edits. There is no builder here because there are two options; a Command-shaped builder for two booleans-and-an-int would be ceremony (§1).

reuse_port sets SO_REUSEPORT before the bind. That "before" is why this is a call and not a post-bind setter on a Listener: after the bind the option is too late, and a setter that silently did nothing is the API this shape exists to avoid.

backlog is the listen(2) queue hint. <= 0 asks for the runtime's default, which is 128 — std's own number, stated here so a caller who wants it can say so explicitly rather than by omission. The host clamps any hint to its own somaxconn, so this is a hint in the honest sense: you may ask, the kernel decides.

Functions and methods

listen

fn · Source line 230

pub fn listen(addr: str) -> Listener ! {io}

Bind a listening socket to addr and return it.

addr is "host:port" as the host understands it — write "127.0.0.1:0" and let the host choose the port, which is what port below is for. Rows: io when the address cannot be bound at all (already in use, not a local address, malformed), coarsened to one tag because the builtin tier reports one. Never traps.

The listener starts accepting immediately: a peer may connect before accept is ever called and waits in the host's backlog, which is what makes a single-process test deterministic.

Capability net; refused at comptime (D33). Delegates to net_listen.

var srv = net.listen(net.loopback(0))?
(net.port(srv) else 0) > 0
net.close_listener(take srv)?

port

fn · Source line 260

pub fn port(l: Listener) -> int ! {io}

The port l is bound to.

This is how a program learns the port the host chose for it after listen(":0") — the port-0 discipline every test in this module follows. Rows: io when the handle is closed, forged or the host cannot report the address. Never traps.

Read mode: asking a listener its port does not change it. The answer is the LOCAL port only; there is no peer or full-address accessor at this pin (see the module header).

**On a std.net.unix listener this is io, always** — a path has no port, and the io row is the builtin tier's own answer rather than a check std adds ([os.net.unix], measured on all three lanes and pinned in tests/net/unix/echo.lu). A program that binds either family and reports its address asks port and falls back to the path it passed.

Capability net; refused at comptime (D33). Delegates to net_port.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv) else 0
p > 0
net.close_listener(take srv)?

accept

fn · Source line 321

pub fn accept(mut l: Listener) -> Socket ! {timeout, io}

Take the next connection from l's backlog, waiting until one arrives.

Rows: timeout when an armed deadline expires — arm one with set_listener_deadline (reachable since sc29; it was declared-only under F-0049 for nine sprints) — and io when the handle is closed, forged or the host failed. Never traps.

This parks until a connection is yours, and an armed deadline BOUNDS the park ([os.net.accept], wolf-lang#242). With a budget armed by set_listener_deadline, the call returns inside it — the connection, or timeout. With no budget armed it parks indefinitely, in the runtime's own wait rather than the kernel's, so a program that accepts before anyone dials still waits; the dial-first test discipline stays and the doc example below keeps it.

**To ask WITHOUT committing to the wait, use net.wait** — thirty lines down this file, [os.net.wait]. A loop that multiplexes this listener with its open connections asks wait for the ready set and calls accept only when the answer names l.fd. That is the shape wait exists for, and it is the answer to "can I poll a listener".

**A readiness wake is not a claim, and a timeout here can mean someone else took it.** On a listener several processes share — the prefork arrangement [os.proc.inherit] invites, and the one wait's clause points at — one arriving connection wakes EVERY hand and exactly one of them takes it. A hand that loses the race finds nothing there and waits again against the same budget, the one computed when its call began and never a fresh one, so a lost race costs at most the budget it already armed. What it eventually answers is timeout, and on N hands that is the NORMAL outcome for N-1 of them: not a failure to report, not a state change, just the connection this hand did not get. A serving loop treats it as "go round again". This is why a shared-listener hand arms a SHORT budget: there, a deadline is the mechanism and not merely the net for a mistake that set_listener_deadline's own clause describes.

The accepted socket is BLOCKING whatever posture the listener holds, so nothing about read/write changes.

mut l because accepting ADVANCES the listener: the connection this call takes is one the next call will not see, which is state the value names even though its fd field does not change — the same rule std.fs.read follows for a file's position (§14).

Capability net; refused at comptime (D33). Delegates to net_accept.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
var conn = net.accept(mut srv)?
net.write(mut cli, "hi")?
(net.read(mut conn, 8) else "?") == "hi"
net.close(take cli)?
net.close(take conn)?
net.close_listener(take srv)?

connect

fn · Source line 353

pub fn connect(addr: str) -> Socket ! {refused, timeout, io}

Dial addr and return the connected socket.

Rows: refused when nobody is listening there — the commonest network outcome there is, and a row rather than a trap because the caller could not have checked; timeout when a deadline expires (a CONNECT deadline has no arming surface here — set_deadline needs the Socket this call has not yet produced, so on this function the tag is still vocabulary-only); io for every other host failure, including an address that does not parse. Never traps.

This blocks until the connection completes or fails, and the host decides how long that takes. addr is handed to the host as written, so a NAME would be resolved by the host resolver, on the calling thread and with no deadline (wolf-lang#217) — std neither resolves nor tests names, and every example here is loopback (see the module header on the no-external-network law, and Addr on the resolver std is waiting for).

Capability net; refused at comptime (D33). Delegates to net_connect.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect(net.loopback(p))?
net.close(take cli)?
net.close_listener(take srv)?

read

fn · Source line 394

pub fn read(mut s: Socket, max: int) -> str ! {closed, timeout, utf8, io}

Read up to max bytes from s, decoded as UTF-8, waiting for at least one byte.

Rows: closed when the peer finished — the socket's eof, an OUTCOME that ends a read loop rather than a failure, and the tag a reader stops on rather than reports; timeout when an armed deadline expires (set_deadline — reachable since sc29); utf8 when the bytes read are not well-formed UTF-8, WHICH INCLUDES a chunk boundary that lands inside a code point, and the bytes are consumed either way; io when the handle is closed, forged or the host failed. Never traps.

A byte-count read of text is not safe in general, exactly as std.fs.read is not: TCP delivers whatever has arrived, so a stream carrying non-ASCII text can split a code point across two reads and the second byte-sequence is a utf8 miss. ASCII is safe at any size, and the honest fix is byte-level io (F-0080, and the fs tier has had it since s90 — fs.read_chunk is the shape this one wants), filed rather than hidden. max at or below zero reads nothing and answers the empty string without touching the socket.

mut s because reading CONSUMES from the stream: the bytes this call takes are bytes the next call will not see (§14).

Capability net; refused at comptime (D33). Delegates to net_read.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.write(mut cli, "wolfpack")?
var conn = net.accept(mut srv)?
(net.read(mut conn, 4) else "?") == "wolf"
(net.read(mut conn, 4) else "?") == "pack"
net.close(take cli)?
net.close(take conn)?
net.close_listener(take srv)?

write

fn · Source line 448

pub fn write(mut s: Socket, text: str) -> () ! {closed, io}

Write all of text to s.

Rows: closed when the peer has gone away (a write to a finished connection is the row, never a trap), io when the handle is closed, forged or the host failed. Never traps, and there is no utf8 row: a str is already well-formed UTF-8.

The whole string is written or the call raises — the builtin loops internally, so a partial write is not an outcome this surface has, and that is why there is no write_all beside this function (see the module header). What it does NOT promise is delivery: bytes handed to the host may still be in flight, and only the peer's own read proves otherwise.

Writes are unbuffered: every call reaches the host, so a program writing a message in small pieces pays for each one.

Two writes are TWO SEGMENTS, and since v0.2.8 they stay that way. [os.net.nodelay] sets TCP_NODELAY on every stream, so the kernel no longer coalesces a small second write into the first — which is the point (the 40ms delayed-ACK stall is gone) and which also removes a coalescing a reader may once have leaned on without noticing. A peer calling read(mut s, 7) after these two writes may be handed "one " and nothing else: **read is one read of UP TO max bytes, never a promise of max**, and the module header's "a stream is bytes, not messages" is the whole of it. A reader that needs the whole thing calls read_all; a reader that needs a fixed count loops until it has one. F-0112 is where this cost a doc example that had been correct-by-Nagle since sc08.

A writer that wants one segment has writev, which is the better answer whenever the pieces are known together.

mut s because writing advances the stream, the same rule read follows (§14).

Capability net; refused at comptime (D33). Delegates to net_write.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.write(mut cli, "one ")?
net.write(mut cli, "two")?
net.close(take cli)?
var conn = net.accept(mut srv)?
(net.read_all(mut conn) else "?") == "one two"
net.close(take conn)?
net.close_listener(take srv)?

read_bytes

fn · Source line 490

pub fn read_bytes(mut s: Socket, max: int) -> List[byte] ! {closed, timeout, io}

Read up to max BYTES from s as a List[byte] — the binary read.

Bytes are bytes: there is no utf8 row here and can never be one (the fs byte tier's posture, adopted verbatim per F-0080's ask — a lone 0x80 is data, not a miss). This is the read a binary protocol builds on; read above is the one for text.

Rows: closed when the peer finished (the row that ends a read loop); timeout when an armed deadline expired (set_deadline); io for a host failure or a bad handle. Never traps.

A short read is normal: up to max means "what the host had", exactly as read's doc states for text — a caller that needs N bytes loops until it has them (std.x.tls.client.read_exact is the worked example).

mut s because reading consumes from the stream (§14).

Capability net; refused at comptime (D33). Delegates to net_read_bytes (s106) — both compiler lanes; lupin 0.1.18 does not resolve the byte tier (F-0102), so this example's lupin lane is an honest unsupported.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
var msg = List[byte]()
(mut msg).push(0 as byte)
(mut msg).push(255 as byte)
net.write_bytes(mut cli, msg)?
var conn = net.accept(mut srv)?
let got = net.read_bytes(mut conn, 8) else List[byte]()
got.len == 2
net.close(take cli)?
net.close(take conn)?
net.close_listener(take srv)?

write_bytes

fn · Source line 530

pub fn write_bytes(mut s: Socket, b: List[byte]) -> () ! {closed, invalid, io}

Write all of b — raw bytes — to s.

The binary twin of write, and the same completeness promise: the whole list is written or the call raises, so there is no partial write to observe.

Rows: closed when the peer has gone away; **invalid — declared and UNREACHABLE from typed code since sc35**, the same tag and the same posture as fs.write_bytes (§14's os-tier vocabulary, adopted verbatim). It named an element of b outside 0..255, rejected whole before anything reached the wire; b is a List[byte] now and cannot hold one, and the tag stays because the vocabulary is the toolchain's (wolf-lang#231 kept invalid on net_write_bytes for the FFI caller it is still true of). io for a host failure or a bad handle. Never traps.

mut s because writing advances the stream (§14).

Capability net; refused at comptime (D33). Delegates to net_write_bytes (s106) — both compiler lanes; lupin 0.1.18 does not resolve the byte tier (F-0102).

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
var msg = List[byte]()
(mut msg).push(128 as byte)
net.write_bytes(mut cli, msg)?
net.close(take cli)?
var conn = net.accept(mut srv)?
let got = net.read_bytes(mut conn, 8) else List[byte]()
got.len == 1
net.close(take conn)?
net.close_listener(take srv)?

write_some

fn · Source line 561

pub fn write_some(mut s: Socket, b: List[byte]) -> int ! {busy, closed, invalid, io}

Send a prefix of b in one non-parking send, returning its byte count: at least 1 for non-empty b, 0 for empty b (the handle is still checked). A socket deadline does not apply. The unsent suffix stays the caller's; retain it and enable std.poll.WRITE until the queue is drained.

Rows: busy when nothing fits now; closed for a peer gone, without SIGPIPE; invalid for a wrong-width list (unreachable for typed byte lists, retained for the builtin's FFI caller); io for a listener, forged/closed handle or other host failure. Never traps.

Capability net; refused at comptime. Delegates to net_write_some, one send with no list copy in the builtin. TCP and Unix streams, both compiler tiers and lupin 0.1.62. Unlike write_bytes, it never drains the whole list on the caller's behalf.

var srv = net.listen(net.loopback(0))?
var cli = net.connect(net.loopback(net.port(srv)?))?
var peer = net.accept(mut srv)?
let n = net.write_some(mut cli, [128 as byte])?
n == 1
let b = net.read_bytes(mut peer, 1)?
b.len == 1 && b[0] == 128 as byte
net.close(take cli)?
net.close(take peer)?
net.close_listener(take srv)?

set_deadline

fn · Source line 600

pub fn set_deadline(mut s: Socket, ms: int) -> () ! {io}

Arm (ms > 0) or clear (ms <= 0) a deadline BUDGET on s: every subsequent parking operation on this socket — read, read_bytes, write — resolves as its row's timeout tag when the budget fires first.

**This is what makes timeout reachable** — the tag every read and write signature has carried since sc08, declared against exactly this day (F-0049's deadline half, closed by s106's net_deadline). A socket with no deadline armed behaves as before: it blocks until the host answers. The budget is per-OPERATION arming, not a wall-clock alarm — it is consulted by each parking call, and clearing it returns the socket to plain blocking.

Rows: io — arming fails only on a forged, closed or wrong-kind handle (or a host that cannot hold a deadline). Never traps.

mut s because the socket's host state changes even though the value's field does not (§14's stream rule: the call site spells the mutation).

Capability net; refused at comptime (D33). Delegates to net_deadline (s106) — ALL THREE lanes, lupin 0.1.18 included (measured: an armed 200ms budget resolves a silent-peer read as timeout there too).

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.set_deadline(mut cli, 150)?
let missed = net.read(mut cli, 8) else "deadline"
missed == "deadline"
net.close(take cli)?
net.close_listener(take srv)?

set_listener_deadline

fn · Source line 635

pub fn set_listener_deadline(mut l: Listener, ms: int) -> () ! {io}

Arm (ms > 0) or clear (ms <= 0) a deadline budget on the LISTENER l: an accept whose peer never dials resolves timeout instead of blocking forever.

**Why the name is not set_deadline**: close_listener's reason — no overloading, one verb per type, and the vocabulary word goes to the connected socket (§1). This is the deadline that retires the "an accept with no peer coming never returns" hazard the module header documented from sc08 on; the dial-first test discipline stays (a deadline is a net for a mistake, not a license to block).

On a listener several processes accept from, it is the mechanism rather than the net. [os.net.accept] bounds a lost race by the budget armed when the call began, so a prefork hand arms a SHORT one deliberately: that budget is the most a connection taken by a sibling can cost it before it goes round its loop again. See accept's clause for what the timeout means there.

Rows: io — a forged, closed or wrong-kind handle. Never traps.

Capability net; refused at comptime (D33). Delegates to net_deadline (s106) — all three lanes.

Example (prose, because accept's success type is a Socket no deadline-firing example can produce — the fenced form would need a diverging handler around a value the block must still type, F-0040's monomorphic edge in one line): arm net.set_listener_deadline(mut srv, 150)? and an accept with no peer dialing resolves its timeout tag inside ~150ms instead of blocking forever. tests/net/accept_deadline_row.lu witnesses the tag riding out of main.

close

fn · Source line 665

pub fn close(take s: Socket) -> () ! {io}

Close s, consuming it.

Rows: io when the handle was already closed or is foreign. Never traps.

take is the mode of the operation's meaning (§3, and §14's handle rule): closing ends the socket's life, so the caller spells net.close(take s) and the compiler rejects every later use as a use-after-move. That is the whole staleness story for sockets, it costs nothing at run time, and tests/net/use_after_close.lu holds it as a rejection so it cannot rot.

Closing is also what tells the PEER the stream is finished: it is the only half-close this tier has, so it is what makes the other end's next read answer closed. A writer that wants to say "done sending" and keep reading wants shutdown, which is a contract at this pin (F-0049).

Capability net; refused at comptime (D33). Delegates to net_close.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.close(take cli)?
net.close_listener(take srv)?

close_listener

fn · Source line 695

pub fn close_listener(take l: Listener) -> () ! {io}

Close the listener l, consuming it.

Rows: io when it was already closed or is foreign. Never traps.

**Why the name is not close.** wolf has no overloading, so one module cannot spell one verb for two types (§1: one concept, one name — and the vocabulary word close goes to the value a program handles most, the connected socket). Closing a listener stops new connections; the ones already accepted are separate sockets and are unaffected.

take for close's reason: the handle is gone afterwards, and using it is a static use-after-move.

**On a std.net.unix listener this call also UNLINKS the socket path** — the runtime made the file, so the runtime removes it. Nothing about the signature changes and no row is added: the unlink is best effort, so a path that has already been moved or removed still closes clean (tests/net/unix/cleanup.lu and refused_row.lu). A TCP listener has no name and this sentence does not apply to one.

Capability net; refused at comptime (D33). Delegates to net_close.

var srv = net.listen("127.0.0.1:0")?
net.close_listener(take srv)?

read_all

fn · Source line 754

pub fn read_all(mut s: Socket) -> str ! {timeout, utf8, io}

Every byte the peer sends until it closes, decoded as UTF-8, as one str.

Rows: timeout when an armed deadline expires (set_deadline — reachable since sc29, and on THIS function it turns a peer that stops sending without closing from a hang into a row); utf8 when what arrived is not well-formed UTF-8, WHICH INCLUDES a chunk boundary that lands inside a code point (see below); io for a host failure or a bad handle. All three are RE-RAISED unchanged from the read they came from. closed is not in the row: the peer finishing is what makes this function RETURN, which is the whole difference between reading everything and failing to read something. Never traps.

This blocks until the peer CLOSES, not until it stops sending. A peer that writes a request and waits for a reply is a peer this function never returns from — so it is the right operation for a stream whose end is the message boundary (a one-shot response, a file transfer) and the wrong one for a conversation. read with a limit is the operation for a conversation.

**The utf8 hazard is inherited and is real**: the socket is read in 4096-byte chunks and a chunk boundary can split a code point, so a stream carrying non-ASCII text can raise utf8 even though every byte it sent was valid (F-0050 — the byte-level read that would fix it does not exist). ASCII is safe at any size. The bytes read before the miss are gone either way, which is why this function reports the tag rather than returning a partial answer beside it.

Why this function exists only now. It was written and withdrawn inside sc08: the loop must stop on closed and re-raise the other three unchanged, and no handler could tell tags apart — a bare binding catches everything (F-0043) and a match inside a handler matched its FIRST ARM for every tag on the executing lane (F-0052). Both are closed at this pin (s70's match tier, s71's payload pattern), so the handler below discriminates on every lane. The version std refused to ship is visible in what it would have done: treated a read error as the end of the stream and handed the caller a truncated message with no indication (§14's rule about a failure mode a module cannot distinguish).

mut s because reading consumes from the stream (§14).

Capability net; refused at comptime (D33). Delegates to net_read.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.write(mut cli, "the whole message")?
net.close(take cli)?
var conn = net.accept(mut srv)?
(net.read_all(mut conn) else "?") == "the whole message"
net.close(take conn)?
net.close_listener(take srv)?

write_line

fn · Source line 808

pub fn write_line(mut s: Socket, text: str) -> () ! {closed, io}

Write text to s followed by exactly one "\n".

Rows: write's exactly — closed when the peer has gone away, io for a host failure or a bad handle. Never traps, and there is no utf8 row: a str is already well-formed UTF-8.

This is the SENDING half of a line protocol, and it is one call rather than two so that a message and its terminator cannot be separated by an early return between them. The terminator is one "\n" on every platform — no "\r\n" translation anywhere, matching std.io's writers, because a protocol that wants the other terminator can write it with write and a program should never have to guess which one it got.

mut s because writing advances the stream (§14).

Capability net; refused at comptime (D33). Delegates to net_write.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.write_line(mut cli, "GET /")?
net.close(take cli)?
var conn = net.accept(mut srv)?
(net.read_all(mut conn) else "?") == "GET /\n"
net.close(take conn)?
net.close_listener(take srv)?

read_lines

fn · Source line 851

pub fn read_lines(mut s: Socket) -> List[str] ! {timeout, utf8, io}

Every line the peer sends until it closes, terminators stripped.

Rows: read_all's exactly — timeout (an armed deadline, set_deadline), utf8 (including a chunk boundary inside a code point), io — and closed is again the OUTCOME that ends the read rather than a tag. Never traps. Allocates the list.

This is the RECEIVING half of a line protocol, and its shape is the honest one available at this pin: read the whole stream, then split it. The alternative — a read_line that returns ONE line as it arrives — needs a buffer filled by a byte-count read, and a chunk that ends inside a code point loses those bytes with no way to report which line they belonged to (F-0050). That function is a reviewed contract in the module header, and this one is not a substitute for it: a caller who must react to each line as it arrives cannot use this, because nothing is returned until the peer closes.

A trailing terminator produces no final empty line ("a\nb\n" is two lines, not three), the empty stream is an empty list, and the split is std.str.lines's — Unicode line boundaries, which is the builtin's definition and therefore part of this contract.

mut s because reading consumes from the stream (§14).

Capability net; refused at comptime (D33). Delegates to net_read.

var srv = net.listen("127.0.0.1:0")?
let p = net.port(srv)?
var cli = net.connect("127.0.0.1:{p}")?
net.write_line(mut cli, "one")?
net.write_line(mut cli, "two")?
net.close(take cli)?
var conn = net.accept(mut srv)?
let got = net.read_lines(mut conn) else List[str]()
got.len == 2
net.close(take conn)?
net.close_listener(take srv)?

endpoint

fn · Source line 872

pub fn endpoint(host: str, port_number: int) -> str

host and port_number joined as the address string listen and connect take.

Total: no rows, no traps — and pure, so unlike everything above it is comptime-safe and reaches no host, which is why it is the one function here a comptime fn may call. An IPv6 host (one containing a :) is bracketed, because that is what makes "::1" and a port unambiguous; anything else is joined with a single :. Nothing is validated: an address the host cannot parse comes back as an io row from listen or connect, where the host is the authority.

net.endpoint("127.0.0.1", 8080) == "127.0.0.1:8080"
net.endpoint("::1", 8080) == "[::1]:8080"
net.endpoint("localhost", 0) == "localhost:0"

loopback

fn · Source line 889

pub fn loopback(port_number: int) -> str

The loopback address with port_number — endpoint("127.0.0.1", n).

Total, pure, comptime-safe. It exists to make the discipline this module tests itself under writable in one call: loopback(0) asks the host for an ephemeral port on the interface that cannot leave the machine, which is the only address a std test or doc example is ever allowed to name.

net.loopback(0) == "127.0.0.1:0"
net.loopback(8080) == "127.0.0.1:8080"

listen_opts

fn · Source line 993

pub fn listen_opts() -> ListenOpts

The options that make listen_with behave exactly like listen.

listen_with(addr, listen_opts()) is listen(addr) call for call — the clause says so of the builtin (net_listen_with(addr, false, 0) is net_listen(addr)), and this is that sentence made reachable. Use it as the base you edit one field of.

Total: no rows, no traps. Pure and comptime-safe — building options binds nothing.

let o = net.listen_opts()
o.reuse_port == false
o.backlog == 0

listen_with

fn · Source line 1046

pub fn listen_with(addr: str, opts: ListenOpts) -> Listener ! {unsupported, exists, denied, io}

Bind a listening socket to addr with opts and return it.

This is an ACQUISITION call and nothing else. What it answers is the ordinary Listener every other function in this module already serves — port, accept, set_listener_deadline, close_listener — so the surface does not grow by one function for one more way to get a listener. That is the same rule std.net.unix follows and the reason it needed only an address call.

**What reuse_port buys, and what it does NOT promise. With the option set, N listeners — in one process or across N processes — may hold one address at once, every member of the group carrying the option. What the KERNEL then does with the group is the host's, and this module states it rather than promising it: linux distributes accepts across the group by a 4-tuple hash, so every hand accepts; macOS hands every SYN to the newest bound socket and falls to a survivor when that socket closes — the port is shared and failover is gap-free, but accepts are NOT distributed. A program that assumes distribution is a program that works on one of this project's two serving hosts. Both hosts guarantee exactly two things, and they are the two a caller may build on: every dial is accepted by SOME member, and the survivor takes every dial after the others close**. tests/net/reuse_port.lu is the assertion about precisely those two and deliberately asserts nothing about which hand.

Rows, and this call has more of them than listen on purpose: unsupported when THE HOST does not serve an option asked for — windows, by name, for reuse_port, because its SO_REUSEADDR lets any process take a bound port and then delivers every dial to the first socket bound, so the second binds and serves nothing; that is refused rather than aliased. exists when another socket already holds the address without the option on both sides — the "already in use" answer, spelled in the vocabulary [os.net.unix] gave this family rather than a new tag. denied for a privileged port the caller may not bind. io for the rest. Never traps.

**listen's own row stays {io}** — its lowering coarsens — so a program that wants the distinction calls this one even with default options. That is a real reason to prefer listen_with, and the only one.

Capability net; refused at comptime (D33). Delegates to net_listen_with.

var srv = net.listen_with(net.loopback(0), net.listen_opts())?
(net.port(srv) else 0) > 0
net.close_listener(take srv)?

adopt_listener

fn · Source line 1113

pub fn adopt_listener(fd: int) -> Listener ! {unsupported, io}

Adopt a listening socket this process was HANDED rather than bound.

This is the child's half of descriptor inheritance: a parent spawns with a set of listeners and the child receives them as descriptors 3, 4, … in the order given, so adopt_listener(3) is "the first listener my parent handed me" and no number ever has to be told to the child out of band. An ACQUISITION call, like listen_with: what it answers is the ordinary Listener, so accept, both deadlines and the closer come free.

The runtime asks the KERNEL what the number is rather than trusting the caller: a stream socket with no peer, and, where the kernel keeps a listening flag, that flag. Anything else — not a socket, a connected stream, a family the table does not serve, a number this process already adopted, a negative or absurd number — is the io row. Never a trap, and never a wrapped stranger; a forged descriptor is a checkable condition, which is the same posture Listener's own doc takes about a hand-built handle.

Ownership at close, which is the sentence a prefork master needs. An adopted descriptor belongs to exactly one wolf handle, and close_listener on that handle does close the inherited fd. The adopter owns the number from the adopt on; a second adopt of a still-live number is io rather than a double close waiting to happen, and closing the handle releases the number so a freshly handed one adopts again.

What the adopter does NOT own is anything OUTSIDE the descriptor. An adopted AF_UNIX listener does not unlink its socket file at close. std.net.unix's cleanup posture belongs to the process that BOUND the path — for an inherited listener, the parent. A child that unlinked the path would delete the address its siblings are still serving on, and this is the one place where an adopted listener and a bound one behave differently at close_listener.

An adopted descriptor is marked close-on-exec on adoption, so this process's own children inherit only what it hands them in turn.

Rows: unsupported where the host or the tier does not serve the call, BY NAME — windows (a SOCKET is not a small stable number a parent can name by position) and the CHECKED machine, which refuses it because it is the wolf binary interpreting a program, so a descriptor handed to "the program's child" would be handed to the compiler's child. io for every failed check above. Never traps.

**The std.process half of this pair is process.start_with(c, inherit)** (sc39, wolf-std#9). This clause said there was none for two sprints, which was true when sc37 wrote it and stopped being true the day the wrapper landed — the pair is whole at the std tier now and a prefork handshake no longer splits across tiers. The Command question that held it up was answered by the consumer that needed it: the inherit set is an argument of the SPAWN, never a field of the builder, because the listeners belong to the master for its whole life and each spawn borrows them.

Capability net; refused at comptime (D33). Delegates to net_adopt_listener.

A prose example, because a doc example cannot spawn its own parent: a child started by os_spawn_with(exe, args, [srv]) reaches its inherited listener with let srv = net.adopt_listener(3)? and from there uses net.accept exactly as the binder would. tests/net/adopt_rows.lu is the witness.

wait

fn · Source line 1184

pub fn wait(fds: List[int], deadline_ms: int) -> List[int] ! {io}

Which of fds can be read WITHOUT blocking, as a subset in the caller's order.

Every other blocking call in this module waits on ONE socket. This is the one that waits on many, and it is what a serving loop that spawns no tasks has instead of a scheduler: without it a single-loop server must time-slice — a short deadline on the listener, another on every open connection, every idle pass — and spends its life waking up to learn that nothing happened.

An EMPTY answer is the deadline expiring with nothing ready. That is an ANSWER, not a failure, and a loop that treats it as one is the mistake this sentence exists to prevent. wait returns a possibly-empty List[int]; it does not raise when nothing is ready.

It takes raw descriptors, not handles, and that is deliberate. A ready set mixes listeners and streams — that is the whole point of it — and wolf has no sum type that could hold both at this pin. So the argument is the fd field both Listener and Socket publish, and the idiom is to build the list from them:

var set = List[int]() (mut set).push(srv.fd) (mut set).push(cli.fd) let ready = net.wait(set, 50)?

The answer is a list of those same numbers, so a caller matches each against the handle it came from. Reading .fd is legal by the Listener doc's own rule; nothing here forges one.

**deadline_ms**: negative waits until something is ready, 0 asks and returns at once, positive is milliseconds.

Readiness is level-triggered: asking consumes nothing, so two waits with the same set answer the same until the program actually reads or accepts. A stream whose peer has CLOSED is READY — the read that follows is what reports closed, which is how a loop learns to drop it.

Rows: io for a forged or closed handle anywhere in the set (nothing is waited on), for an EMPTY set with an unbounded deadline (nothing could ever end that wait — a program that means to sleep says time.sleep_ms), and for a failure of the poll itself. An empty set with a 0 or positive deadline is fine and answers empty. Never traps.

The call does not interact with the task layer: it neither parks a task nor disturbs the reactor's registrations, so a program may mix it with spawn freely. Every tier-1 host answers this question and every tier serves it.

The narrow form: sockets alone, read readiness alone, no signal. std.poll is the wide form: an owned waiter over files and sockets, their read/write/hangup/error facts, signal meanings and a deadline. It uses the runtime readiness set; this call remains unchanged and supplies poll's narrow Windows fallback.

Capability net; refused at comptime (D33). Delegates to net_wait.

var srv = net.listen(net.loopback(0))?
var set = List[int]()
(mut set).push(srv.fd)
let ready = net.wait(set, 0)?
net.close_listener(take srv)?
ready.len == 0

writev

fn · Source line 1254

pub fn writev(mut s: Socket, parts: List[List[byte]]) -> () ! {closed, io}

Write every part of parts to s, in order, as ONE write.

The gathered write, [os.net.writev]. writev(2) on unix and WSASend on windows take the vector as it stands: the kernel gathers the parts and the runtime never copies them, so a head and a body leave in one syscall and where two writes would have been two segments, this is one.

The shape it exists for is the response, which is why lobo asked for it: a header built in a strbuf and a body already in hand, sent without concatenating the two into a third list that is the size of both. Write

var parts = List[List[byte]]()
(mut parts).push(head)
(mut parts).push(body)
net.writev(mut conn, parts)?

and the bytes on the wire are head then body, once. write_bytes of head ++ body puts the same bytes there and allocates the sum to do it; two write_bytes calls allocate nothing and cost two syscalls, and — before [os.net.nodelay] — a 40ms delayed-ACK stall on linux for the second one. This call is the only one of the three that pays neither price.

Rows are write_bytes's minus one: closed when the peer has gone, io for a host failure, a bad handle or a fired budget. There is no invalid — that tag is net_write_bytes's refusal of a list holding an element outside 0..255, and a List[List[byte]] cannot present one, so this signature does not declare a row no typed caller can reach. Never traps.

**Completeness is write's**: the whole gather drains or the call raises, resumed after a park from the byte the kernel stopped at in whichever part it stopped in. Empty parts are permitted and send nothing; a call whose parts are ALL empty is a completed write that makes no syscall at all, which is the answer to "is an empty vector an error" — it is not.

mut s because writing advances the stream (§14).

Capability net; refused at comptime (D33). Delegates to net_writev (s141) — all three lanes, lupin 0.1.28 included (is40 mirrors it at the same pin this repository holds).

var srv = net.listen(net.loopback(0))?
let p = net.port(srv)?
var cli = net.connect(net.loopback(p))?
var head = List[byte]()
(mut head).push(72 as byte)
var body = List[byte]()
(mut body).push(105 as byte)
var parts = List[List[byte]]()
(mut parts).push(head)
(mut parts).push(body)
net.writev(mut cli, parts)?
net.close(take cli)?
var conn = net.accept(mut srv)?
let got = net.read_bytes(mut conn, 8) else List[byte]()
net.close(take conn)?
net.close_listener(take srv)?
got.len == 2

nodelay

fn · Source line 1319

pub fn nodelay(mut s: Socket, on: bool) -> () ! {io}

Set Nagle's algorithm off (on = true) or on (on = false) for s.

**TCP_NODELAY is already ON for every stream this module hands out** — accepted by accept, dialed by connect, on every tier-1 host and every tier, including the checked machine, whose streams enter its table under the same default ([os.net.nodelay]). A program that wants the default does not call this function. It is here so that the default is a STATED one rather than an undocumented posture, and so the other half is reachable.

Why that is the default. wolf-lang#254 measured it: a server that answers with a head and then a body — two writes, the second small — stalls on linux behind the peer's delayed ACK at 40ms per request, a 108x gap against nginx on the same runner, for a program that did nothing wrong. Nagle coalesces the small second write and the peer will not ACK until it has something to say. The posture Go, nginx and node take is the one that makes that naive two-write server correct without its author having to know this clause exists, and it is the one taken here.

**What off is for.** nodelay(mut s, false) puts Nagle back, and there is one shape that wants it: a program that writes many small pieces it does not need delivered individually — a log shipper, a metrics drain, a bulk feed — and would rather the kernel coalesce them into full segments than pay a packet per piece. That is a THROUGHPUT choice made against a LATENCY default, and a program making it should be able to say why. net.writev above is the other answer to the same problem and the better one when the pieces are known together: gather them and Nagle has nothing to coalesce.

Idempotent, and it takes effect after acquisition — a stream is a stream first and an option-carrying stream second, which is why this is a setter and reuse_port (which must precede the bind) is not.

Rows: io, and it is the whole row set. A LISTENER, a unix-domain stream (the option is TCP's), a closed handle and a forged one are each io; std adds no check of its own, so the tag is the host's answer. Never traps.

**This is not a generic setsockopt and none is planned.** An option reaches this module by clause, with its rows and its default stated, the way reuse_port did in listen_opts. That admits more options of the same kind — a keepalive switch is the obvious next — and admits nothing whose meaning differs per host without a measurement to state it (linger, buffer sizes).

mut s because the socket's host state changes even though the value's field does not (§14's stream rule).

Capability net; refused at comptime (D33). Delegates to net_nodelay (s141) — all three lanes, lupin 0.1.28 included.

var srv = net.listen(net.loopback(0))?
let p = net.port(srv)?
var cli = net.connect(net.loopback(p))?
net.nodelay(mut cli, false)?
net.nodelay(mut cli, true)?
net.close(take cli)?
net.close_listener(take srv)?

Constants

No public declarations in this section.

Errors and row tags

Tags named by public signatures: busy, closed, denied, exists, invalid, io, refused, timeout, unsupported, utf8. Their conditions are documented on the functions that return them.

No public declarations in this section.