@amritk/nish-aarch64-linux 0.36.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/INSTALL.md +92 -71
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +75 -14
  4. package/package.json +1 -1
  5. package/runtime/async.d.mts +2 -0
  6. package/runtime/async.mjs +7 -0
  7. package/runtime/core/arrays.d.ts +4 -0
  8. package/runtime/core/arrays.mjs +33 -0
  9. package/runtime/nish.d.ts +1045 -512
  10. package/runtime/nish.h +53 -6
  11. package/runtime/page.d.ts +53 -0
  12. package/runtime/page.mjs +146 -0
  13. package/runtime/runtime-async.c +740 -0
  14. package/runtime/runtime-cross.c +2 -1
  15. package/runtime/runtime-region.c +85 -7
  16. package/runtime/runtime-text.c +1068 -0
  17. package/runtime/runtime-wasm.c +65 -9
  18. package/runtime/runtime.c +50 -961
  19. package/runtime/vite.mjs +48 -11
  20. package/scripts/build.sh +231 -31
  21. package/std/LICENSE-fdlibm +8 -0
  22. package/std/README.md +109 -82
  23. package/std/array.ts +266 -0
  24. package/std/bytes.ts +23 -19
  25. package/std/compress/checksum.ts +1 -1
  26. package/std/crypto/aes.ts +48 -43
  27. package/std/crypto/base64url.ts +7 -5
  28. package/std/crypto/bcrypt-batch.ts +13 -13
  29. package/std/crypto/bcrypt.ts +33 -27
  30. package/std/crypto/chacha20poly1305.ts +16 -14
  31. package/std/crypto/ed25519.ts +19 -16
  32. package/std/crypto/hmac.ts +7 -6
  33. package/std/crypto/jwt.ts +23 -20
  34. package/std/crypto/p256.ts +63 -56
  35. package/std/crypto/p384.ts +23 -20
  36. package/std/crypto/pki.ts +18 -15
  37. package/std/crypto/rsa.ts +23 -19
  38. package/std/crypto/x25519.ts +11 -10
  39. package/std/crypto/x509.ts +69 -62
  40. package/std/host/ring.ts +124 -0
  41. package/std/host/text.ts +86 -0
  42. package/std/json-equal.ts +12 -11
  43. package/std/json-number.ts +12 -12
  44. package/std/json-tokenizer.ts +26 -22
  45. package/std/json-typed.ts +92 -78
  46. package/std/json-value.ts +38 -33
  47. package/std/json.ts +32 -28
  48. package/std/math.ts +743 -41
  49. package/std/net/dns-resolver.ts +46 -6
  50. package/std/net/dns.ts +50 -13
  51. package/std/net/fetch.ts +1744 -295
  52. package/std/net/handler.ts +30 -0
  53. package/std/net/hpack.ts +29 -26
  54. package/std/net/http-compress.ts +42 -28
  55. package/std/net/http-fields.ts +19 -4
  56. package/std/net/http1-client-codec.ts +29 -25
  57. package/std/net/http1-codec.ts +62 -91
  58. package/std/net/http1-server.ts +79 -57
  59. package/std/net/http2-frame.ts +17 -16
  60. package/std/net/http2-tls.ts +17 -15
  61. package/std/net/http2.ts +67 -54
  62. package/std/net/http3-frame.ts +11 -10
  63. package/std/net/http3-server.ts +36 -35
  64. package/std/net/http3.ts +70 -58
  65. package/std/net/postgres-async.ts +1005 -0
  66. package/std/net/postgres.ts +185 -164
  67. package/std/net/prefork.ts +38 -34
  68. package/std/net/qpack.ts +15 -14
  69. package/std/net/quic-conn-ack.ts +1 -0
  70. package/std/net/quic-conn-cid.ts +11 -0
  71. package/std/net/quic-conn-params.ts +41 -14
  72. package/std/net/quic-datagram.ts +7 -0
  73. package/std/net/quic-frame.ts +48 -12
  74. package/std/net/quic-listener.ts +61 -44
  75. package/std/net/quic-packet.ts +71 -52
  76. package/std/net/quic-recovery.ts +59 -21
  77. package/std/net/quic-stream.ts +83 -55
  78. package/std/net/quic.ts +204 -152
  79. package/std/net/serve.ts +763 -0
  80. package/std/net/tls/client.ts +1 -0
  81. package/std/net/tls/codec.ts +81 -12
  82. package/std/net/tls/record-client.ts +30 -18
  83. package/std/net/tls/record-server.ts +74 -46
  84. package/std/net/tls/record.ts +33 -24
  85. package/std/net/tls/ticket.ts +2 -0
  86. package/std/net/tls/verify.ts +8 -7
  87. package/std/net/tls-tcp.ts +58 -50
  88. package/std/net/tls.ts +55 -43
  89. package/std/net/url.ts +12 -9
  90. package/std/net/websocket.ts +23 -19
  91. package/std/net/webtransport.ts +24 -18
  92. package/std/random.ts +8 -6
  93. package/std/regex.ts +70 -59
  94. package/std/sync/ring.ts +24 -21
  95. package/std/sync/shm.ts +9 -7
  96. package/std/term-io.ts +17 -14
  97. package/std/term-probe.ts +11 -10
  98. package/std/term-rate.ts +71 -61
  99. package/std/term.ts +73 -59
  100. package/std/text.ts +242 -15
  101. package/std/threads.ts +19 -15
  102. package/std/yaml-json.ts +17 -15
  103. package/std/yaml-write.ts +21 -14
package/std/README.md CHANGED
@@ -47,21 +47,25 @@ whatever program imports it, and subject to the same rules as `examples/` or
47
47
  | [`threads.ts`](https://github.com/amritk/nish/blob/main/std/threads.ts) | `parallelMapInto(src, dst, f)` and `parallelReduce(src, f, identity)`: a function over every element of an array, on as many threads as the length is worth. Its bodies are the sequential meaning, which is what runs under Node; the compiler recognises the two templates by module and name, lowers the one loop in each onto `nish_parallel_range`, holds the function to the rules that make that safe, and compiles an importing program with `--threads` ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#data-parallelism-nishthreads)). `tests/link/par_*` are its programs. `scope()`, bound by `using s = scope()`, runs unlike tasks, each on a thread of its own, and joins them at every exit of the block; `s.spawn(entry, arg, dst, at)` stores a task's answer, and `s.spawn(entry, arg)` and `s.spawn(() => ...)`, whose arrow reads the function's `const` locals, run one that answers `void` (`spawnWith` and `spawnThunk` are the methods the compiler reads them as, and under Node `spawn` itself tells them apart) ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#scoped-tasks-using-s--scope)). `scopeWithStack(bytes)` is a scope whose tasks each run on a new thread with at least `bytes` of stack, for a task that recurses deeper than a thread's default allows; under Node and without threads the size is checked and otherwise ignored (`tests/link/thread_stack_deep`). `Mutex<T>` is a lock that owns its data: the value is reachable only through the guard `using g = m.lock()` binds, which releases it at every exit of the block, so a scope's tasks can share and update one value without a data race or a deadlock ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#a-lock-that-owns-its-data-mutext); `tests/link/thread_mutex_*`, and `examples/histogram.ts` measured). `Channel<T>` carries scalars to one receiver, a task of the scope or the parent after the join, from the scope's sender tasks and from the parent before the block that spawns them, and closes when every sending task has returned ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#channels-channelt); [`docs/wp29-thread-surface.md`](https://github.com/amritk/nish/blob/main/docs/wp29-thread-surface.md#44-stage-p3--channels-of-scalars) §4.4). Every body in the module is its meaning under Node, where a task runs at its `spawn` |
48
48
  | [`sync/shm.ts`](https://github.com/amritk/nish/blob/main/std/sync/shm.ts) | `createRegion(name, bytes)`, `openRegion(name)` and `unlinkRegion(name)`: a named region of memory that several processes of one user map at once, through `runtime/runtime-shm.c`. A `SharedRegion` is read and written through checked slots, `loadI32` to `compareExchangeI64` at an ordering the call names (`RELAXED` to `SEQ_CST`), and byte windows (`read`, `write`); an offset outside the region or not a multiple of the slot's width stops the program. `waitI32` and `wake` sleep and wake on a slot across processes (Linux futex; `SHM_UNSUPPORTED` elsewhere). Native only, and it reaches `ffi` ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#shared-memory-between-processes-nishsyncshm-and-nishsyncring); [`docs/wp47-shared-memory.md`](https://github.com/amritk/nish/blob/main/docs/wp47-shared-memory.md); [`docs/security/shm.md`](../docs/security/shm.md)) |
49
49
  | [`sync/ring.ts`](https://github.com/amritk/nish/blob/main/std/sync/ring.ts) | Lock-free rings of byte records in a `SharedRegion`: `SpscRing` (one producer, one consumer, records of any length) and `MpscRing` (many producers, one consumer, fixed slots), made with `initSpscRing` / `initMpscRing` and found from another process with `attachSpscRing` / `attachMpscRing`. `tryPush`, `tryPop` and `popBatch` never block; a ring made with a doorbell adds `popWait`, which sleeps on a futex that a push rings only when the consumer is asleep. A length a peer wrote that the ring cannot hold stops the program as corrupt. `tests/link/sync_ring`, `examples/prefork-jobs.ts` and `bench/ring-latency/` are its programs |
50
+ | [`host/text.ts`](https://github.com/amritk/nish/blob/main/std/host/text.ts) | Text in wasm module storage, for a module and its page (WP50 stage 4). `textWrite(buf, at, s)` writes a string's UTF-8 bytes into a `u8[]` at `at` and answers the offset after them, `textWriteInt` and `textWriteF64` a number as a template literal formats it; text that does not fit writes nothing and answers -1, which every writer passes through, so a chain fails as a whole and never traps. `textRead(buf, n)` is the first `n` bytes as a string, what the page's `encodeInto` wrote, or `null` for an `n` past the buffer. `tests/host-import/text` is its round trip |
50
51
 
51
52
  ## `nish/crypto` — the primitives under TLS 1.3
52
53
 
53
- The first lanes of [WP34](https://github.com/amritk/nish/blob/main/docs/wp34-hosting-cs.md) §5: K1's hashes, MACs and
54
- key derivation, K2's and K3's AEADs, K4's key exchange, K5's signatures and
55
- K6's certificates, in
56
- pure Nish (decision S1), each module imported by its own specifier. Every one
57
- is written from its specification, with three exceptions that keep their
58
- upstream notice: `crypto/aes.ts`'s `ghashMul32` is adapted from BearSSL,
59
- `crypto/p256.ts`'s field and scalar arithmetic is ported from fiat-crypto and
60
- its nonce's safegcd inversion from libsecp256k1, and `crypto/p384.ts`'s field
61
- and scalar arithmetic is ported from fiat-crypto
62
- ([`THIRD_PARTY_NOTICES.md`](https://github.com/amritk/nish/blob/main/THIRD_PARTY_NOTICES.md)). Each reproduces its
63
- specification's published vectors in its `tests/link/crypto_*` programs. The
64
- performance gate compiles every module with no diagnostics under both
54
+ The first lanes of
55
+ [WP34](https://github.com/amritk/nish/blob/main/docs/wp34-hosting-cs.md) §5:
56
+ K1's hashes, MACs and key derivation, K2's and K3's AEADs, K4's key exchange,
57
+ K5's signatures and K6's certificates, in pure Nish (decision S1), each module
58
+ imported by its own specifier. Every one is written from its specification,
59
+ with three exceptions that keep their upstream notice: `crypto/aes.ts`'s
60
+ `ghashMul32` is adapted from BearSSL, `crypto/p256.ts`'s field and scalar
61
+ arithmetic is ported from fiat-crypto and its nonce's safegcd inversion from
62
+ libsecp256k1, and `crypto/p384.ts`'s field and scalar arithmetic is ported from
63
+ fiat-crypto
64
+ ([`THIRD_PARTY_NOTICES.md`](https://github.com/amritk/nish/blob/main/THIRD_PARTY_NOTICES.md)).
65
+ Each reproduces its specification's published vectors in its
66
+ `tests/link/crypto_*` programs.
67
+
68
+ The performance gate compiles every module with no diagnostics under both
65
69
  `--number-mode i32` and `f64`, and the hashes, HMAC, HKDF, X25519,
66
70
  ChaCha20-Poly1305, AES-GCM, P-256 and X.509 also run their vectors in `f64`
67
71
  (`crypto_*_f64`). SHA-1 is here too, for one non-security use (its row says
@@ -70,13 +74,17 @@ which), and does both.
70
74
  Every module here was security-audited (#363); the records are in
71
75
  [`docs/security/`](../docs/security/README.md), and how to report a
72
76
  vulnerability is in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.md). Two limits hold across the
73
- modules. **Lengths stop at 2^31 − 1.** No array built by `push` or `new Array`,
74
- no array or string the runtime makes (a file read, a concatenation, a
75
- template) and no string built by `join` can pass 2^31 − 1 elements or bytes
76
- (K1-6, CG-3, closed), so `length` is right in both number modes, and the
77
- one-shot functions below refuse a longer input as each row says. **Private
78
- keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`, `crypto/ed25519.ts`,
79
- `crypto/x509.ts` and `crypto/x509-random.ts` take and give a private key as a `Secret<u8[]>` from
77
+ modules.
78
+
79
+ **Lengths stop at 2^31 − 1.** No array built by `push` or `new Array`, no array
80
+ or string the runtime makes (a file read, a concatenation, a template) and no
81
+ string built by `join` can pass 2^31 − 1 elements or bytes (K1-6, CG-3,
82
+ closed), so `length` is right in both number modes, and the one-shot functions
83
+ below refuse a longer input as each row says.
84
+
85
+ **Private keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`,
86
+ `crypto/ed25519.ts`, `crypto/x509.ts` and `crypto/x509-random.ts` take and give
87
+ a private key as a `Secret<u8[]>` from
80
88
  `nish:secret`, compute on it only inside `expose`, and wipe every intermediate
81
89
  the key reaches before they return, with a store the optimiser may not remove
82
90
  (ECC-2, X509-7, closed); `crypto/hmac.ts` (`hmacSha256Secret` and its two
@@ -130,7 +138,9 @@ Three rules hold across the modules:
130
138
  255 steps, AES reads no table, P-256's comb and window read every entry of
131
139
  a table and keep one by mask, and base64url maps characters by arithmetic on range masks
132
140
  rather than a table. Every branch is on a length, a loop counter or a bit
133
- position. WP34 N6 checks that the machine code kept that shape:
141
+ position.
142
+
143
+ WP34 N6 checks that the machine code kept that shape:
134
144
  `tests/ct-asm.js` disassembles golden fixtures on x86-64 and aarch64 and
135
145
  refuses a branch, a call, a secret-addressed load, or a divide or square
136
146
  root of a secret (whose latency follows its operands) in them. It reads what
@@ -159,18 +169,19 @@ Three rules hold across the modules:
159
169
  - `tests/cases/ct_asm_aes`: one full bitsliced round, one GHASH multiply and
160
170
  the tag compare. Packing, the key schedule and the loops over blocks
161
171
  remain discipline.
162
- - `tests/cases/ct_asm_p256`: fiat's field multiply, square, add and
163
- subtract, its scalar multiply and its conditional move; the sixteen-entry
164
- table read by a secret digit; the complete doubling and addition; and one
165
- window step of the scalar multiplication (four doublings, the table read
166
- and an addition); and the fixed-base comb that multiplies G for a public
167
- key or a signature: its digit, the fifteen-entry read of the precomputed
168
- table, the mixed addition, the masked keep, and one whole comb step; and
169
- the nonce's safegcd inversion: thirty divsteps, held to the module's loop
170
- body, and both matrix updates. The check follows each call into the field
171
- functions. The 64-window and 4-row loops, the window's table build, the
172
- field inversion, safegcd's limb conversions, the encodings and
173
- RFC 6979's nonce derivation remain discipline.
172
+ - `tests/cases/ct_asm_p256`: fiat's field multiply, square, add and subtract,
173
+ its scalar multiply and its conditional move; the sixteen-entry table read
174
+ by a secret digit; the complete doubling and addition; and one window step
175
+ of the scalar multiplication (four doublings, the table read and an
176
+ addition); and the fixed-base comb that multiplies G for a public key or a
177
+ signature: its digit, the fifteen-entry read of the precomputed table, the
178
+ mixed addition, the masked keep, and one whole comb step; and the nonce's
179
+ safegcd inversion: thirty divsteps, held to the module's loop body, and
180
+ both matrix updates. The check follows each call into the field functions.
181
+
182
+ The 64-window and 4-row loops, the window's table build, the field
183
+ inversion, safegcd's limb conversions, the encodings and RFC 6979's nonce
184
+ derivation remain discipline.
174
185
 
175
186
  The SHA-2 hashes and HKDF are additions, rotations and xors that branch
176
187
  only on lengths, and are not in a fixture either; nor is `crypto/x509.ts`,
@@ -253,6 +264,7 @@ reads one, and it still takes its randomness as an argument.
253
264
  | [`net/http-compress.ts`](https://github.com/amritk/nish/blob/main/std/net/http-compress.ts) | Content coding for HTTP responses: `httpAcceptEncoding(buf, start, end, offered)` reads an `Accept-Encoding` value (q-values, `*`, `identity`, `x-gzip`) into `HTTP_CODING_GZIP`, `HTTP_CODING_DEFLATE`, `HTTP_CODING_IDENTITY` or `HTTP_CODING_NONE`, allocating nothing; `HttpCompressor(level, minLength, maxLength)` gzips a body into its own buffer when it is worth it (-1 to send it as it is) and builds the response fields (`addFields`: `Content-Encoding: gzip` and, while `vary`, `Vary: Accept-Encoding`). It sends gzip only when it pays: `minLength`, `minSaving` bytes or `minSavingPercent`, and `segmentMode` (fewer TCP segments of `mss`, head included, than as it is); `decision` says why (`HTTP_COMPRESS_SENT`, `_NOT_ACCEPTED`, `_TOO_SMALL`, `_TOO_LARGE`, `_TOO_LITTLE_SAVED`, `_NO_FEWER_SEGMENTS`). Bodies up to `fixedLimit` use the fixed-Huffman encoder (`encoder`: `HTTP_ENCODER_AUTO`, `_FIXED`, `_LEVEL`). On HTTP/1.1, `Http1Connection.acceptEncoding()` and `respondEncoded(status, names, values, body, off, len, enc, coding)` answer a request in one call with the compressed `Content-Length`, or nothing at all (`H1_AGAIN`, `H1_INVALID`); `identity;q=0` is honoured. Opt-in; BREACH is the program's to avoid (`docs/security/compress.md`) | RFC 9110 §8.4 and §12.5.3: the negotiation table, and sans-IO responses gunzipped back (`tests/link/std_http_compress`) |
254
265
  | [`net/router.ts`](https://github.com/amritk/nish/blob/main/std/net/router.ts) | `Router`, a method and path router that knows no carrier and allocates nothing per match: `add(method, pattern)` answers the route's index (0, 1, 2 in the order added) or a refusal — `ROUTER_BAD_PATTERN`, `ROUTER_BAD_METHOD`, `ROUTER_TOO_LONG`, `ROUTER_AMBIGUOUS` (`*` not last), `ROUTER_DUPLICATE` (the same shape and method, whatever the parameter names) or `ROUTER_FULL`, against `RouterLimits`; `match(method, mStart, mEnd, target, tStart, tEnd, params)` answers the index, `ROUTER_NOT_FOUND` or `ROUTER_METHOD_NOT_ALLOWED`, writing each `:name` and a final `*` as a `[start, end)` pair into the caller's `params` (`ROUTER_TOO_MANY_PARAMS` when it is short). Literal before parameter before `*`, segment by segment, backtracking; a lookup enters each node at most once. The query is left unparsed and nothing is decoded: `routerDecode` decodes one parameter (`ROUTER_BAD_ESCAPE`, `ROUTER_NO_ROOM`) (`docs/security/router.md`) | Every refusal code, precedence and backtracking, 405 against 404, `%2F` kept in one segment, the query, `*` and authority-form targets, a target deeper than any route, the lookup bound, params past storage, and the arena flat over matches (`tests/link/net_router`, `net_router_f64`, five `net_router_negative_*`) |
255
266
  | [`net/handler.ts`](https://github.com/amritk/nish/blob/main/std/net/handler.ts) | `HttpHandler`, complete requests and their answers over the HTTP/1.1 carrier: it owns the readiness loop, routes each request through a `Router` at its head, gathers its body up to `HandlerLimits.http.maxBody` (1 MiB; past it the carrier answers 413), and hands it over whole. The program pulls — `wait(ms)`, `ready()`, `take()` — and switches on `req.route`; `HttpRequest` reads parameters, form-decoded query values and fields as ranges into its own buffers. Each request is answered once, now or in a later turn, by `send`, `sendFields`, `empty`, `json()` + `sendJson`, `problem` (RFC 9457), `refuse` (404, or 405 with `Allow`) or `start`/`write`/`end`; an answer whose connection closed first is `HANDLER_DROPPED` and reaches no later peer. `HEAD` takes a `GET` route. `watch`/`fired` add the program's own descriptors (`signalFd()`), and `drain` stops gracefully. Nothing is allocated per request once warm (`docs/security/handler.md`) | Routing, parameters and form-decoded queries, `HEAD`, 404 and 405 problems, chunked bodies in and out, the body cap at and one past it, pipelining order, late answers dropped across a reused slot, the arena and pool flat over two thousand requests, and the drain (`tests/link/net_handler`, and `net_http_app` over `examples/http-app`) |
267
+ | [`net/serve.ts`](https://github.com/amritk/nish/blob/main/std/net/serve.ts) | `serve(port, router, limits, handle)`, an HTTP/1.1 server for an `async` program over `HttpHandler`: each whole request is copied into a task of its own, which runs the program's `handle(req: Request): Promise<Response>` in its own region and writes the answer into the request slot's preallocated buffers; the loop sends answers in request order. `ServeLimits` caps connections (closed past it), requests in flight (503), the header section (431), the body (413) and the response (500), and closes a connection whose head takes past `headTimeout` or that idles past `idleTimeout`; `deadline` is held, not yet enforced. `Arena.used()` stays flat over thousands of pipelined requests (`tests/link/net_serve_pipelined_flat`). Native only: `--emit-ts` refuses `readable` (NL4017). Record: `docs/security/serve.md`. |
256
268
  | [`net/upstream.ts`](https://github.com/amritk/nish/blob/main/std/net/upstream.ts) | `Upstream`, outbound HTTP/1.1 calls from a route handler that never block it: a pool of keep-alive connections to one `http:` origin on the `HttpHandler`'s own loop (watch ids `UpstreamLimits.firstId` and up). `get(req, path)` returns at once, or `UPSTREAM_E_FULL` with nothing held; each call comes back once through `ready()`/`take()` tagged with `r.req`, `ok` with its status and `body[0 .. length)`, or failed with the codec's `HTTP1_E_` refusal or an `UPSTREAM_E_` code (timeout, closed, connect, origin, lookup, blocked, request), and goes back with `release`. The origin is looked up once at start-up and pinned; `UpstreamLimits.outbound` checks it against an `OutboundPolicy`. A failed call's connection is closed. Each connection keeps one codec in spans mode, so a warm pool allocates nothing per call | A slow upstream while other clients and a second upstream are answered, the timeout, keep-alive and tagging, five codec refusals as failures, the policy refusing loopback, origin and request-target refusals, three thousand warm calls on one connection with `Arena.used()` flat (`tests/link/net_upstream`), and a second `release` panicking (`net_upstream_release`) |
257
269
  | [`net/postgres.ts`](https://github.com/amritk/nish/blob/main/std/net/postgres.ts) | `PgConnection`, a PostgreSQL client that reads no socket: the program fills `inputBuffer()` and sends `outputBuffer()`, and `next()` answers `PG_NEED_MORE`, `PG_READY`, `PG_DESCRIBED`, `PG_ROW`, `PG_COMPLETE`, `PG_ERROR`, `PG_NOTICE`, `PG_GROUP_DONE` or the final `PG_FAILED` (`failure`, one of the `PG_ERR_*` codes). Protocol 3.0: startup, `trust` and SCRAM-SHA-256 with the server's signature checked (cleartext and MD5 refused), the extended query protocol — `prepare`, `bindStart`, `paramInt` / `paramText` / `paramBytes` / `paramTextArray` / `paramIntArray` / `paramNull`, an array built element by element into the Bind (`arrayStart`, `arrayElement`, `arrayInt`, `arrayNull`, `arrayEnd`), binary `int4[]` / `int8[]` parameters (`paramInt4Array` / `paramInt8Array` over an `i64[]` window, or `binaryArrayStart`, `binaryArrayInt`, `binaryArrayNull` and the same `arrayEnd`; per-parameter format codes only once a binary one is bound; an `int4` element out of range panics), `bindEnd`, `bindStartBinary` for a Bind whose result columns come in binary (read in place by `binaryInt`, `binaryBool`, `binaryFloat` and `PgBinary`'s `timestamp` and `iso`, and a one-dimensional `int2[]`, `int4[]` or `int8[]` by `PgBinaryArray`), `bindCancel` to drop a Bind not yet ended, `closeStatement`, `sync` — with up to `maxInFlight` groups pipelined. `PgBatcher` queues keyed reads of one statement shape (`addInt`, `addText`) and `take(conn)` binds up to `maxRequests` of them, each key once, as one execution over `unnest($1) with ordinality`; `row`, `end` and `fail` route its rows by their server-supplied ordinal, checked first (read with `binaryInt` when `PgBatchConfig.binary` is set, so the batch's rows come in binary too), to `next(run)`'s per-request `PG_BATCH_ROW` and `PG_BATCH_DONE` / `PG_BATCH_MISSING` / `PG_BATCH_FAILED`; with `PgBatchConfig.sorted` false the statement has no `order by q.ord`, so no Sort node, rows route as they come and each request's last event waits for `end`; `take` answers a fresh handle each time, so a server's late or repeated event on a spent one is counted in `stray`, never routed or panicked on. It reads no clock and allocates nothing per request or row. `PgBatchClock` says when to take, from times the program passes in: once max(`minCount`, the moving average of batch sizes × `factor`) wait, the oldest has waited `maxWaitUs`, or, with the idle bypass, nothing is in flight and the load is light (its defaults are the fixed window); `PgBatcher.takeDue` takes only then, and `PgBatchTurns` lets one free connection collect while the others execute. A row's columns are windows onto the receive buffer (`colStart`, `colLength`), read in place by `int`, `bool`, `isNull` and `PgText`'s decoders (`timestamptz`, `PgArrayWalker` for `text[]`); no per-row or per-column allocation. The password is a `Secret<u8[]>`, wiped once the proof is made. Caps on message size, columns, groups in flight and SCRAM iterations (`docs/security/postgres.md`) | PostgreSQL 18's frontend/backend protocol chapter, RFC 5802 and RFC 7677: every builder, event and refusal (`tests/link/std_postgres`), and exchanges recorded from PostgreSQL 18 by `tests/postgres/record.mjs` replayed byte for byte (`tests/link/std_postgres_replay`); the batcher's queueing, caps and ordinal refusals (`tests/link/std_postgres_batch`), and unsorted (`tests/link/std_postgres_batch_unsorted`); the clock's reasons, backlog and turns (`tests/link/std_postgres_batch_clock`) |
258
270
  | [`net/postgres-carrier.ts`](https://github.com/amritk/nish/blob/main/std/net/postgres-carrier.ts) | `PgCarrier`, a `PgPool`'s queries on an `HttpHandler`'s loop: its sockets sit in the handler's epoll set, a route handler hands a request to `run` (or `runInt` / `runText` for one of up to 8 attached `PgBatcher`s) and gets its number at once, and `next()` answers `PG_CARRIER_BUILD` to bind a plain query on `connection()`, `PG_CARRIER_ROW`, `PG_CARRIER_COMPLETE`, `PG_CARRIER_ERROR` and one final `PG_CARRIER_DONE`, `PG_CARRIER_MISSING` or `PG_CARRIER_FAILED` (`failure`, `socketError`) with `request()` the request to answer and `tag` the caller's. It connects the pool's slots itself (TCP or a Unix socket), times out a connect after `connectTimeoutMs`, sheds batched keys when no slot can connect, and sizes every table from `PgCarrierLimits` at construction: `run` answers `PG_CARRIER_FULL` rather than grow one, and once connections are up it allocates nothing per query. Kept apart from `net/postgres.ts` so that module reaches no capability (`docs/security/postgres.md`) | A loopback backend in the test itself: routing, a slow query not stalling another client, lost and refused connections, a connect timeout, and `Arena.used()` flat over thousands of queries (`tests/link/std_postgres_carrier`); a live server by `tests/postgres/live/run.mjs` |
@@ -265,6 +277,7 @@ through both Finished messages) and `TLS_LEVEL_APPLICATION`. A carrier hands
265
277
  `receive` the bytes it got at a level, in any split, and sends what
266
278
  `takeOutput(level)` answers under that level's keys: TLS over TCP (T2) in
267
279
  records, QUIC (Q2) in CRYPTO frames of the matching packet number space.
280
+
268
281
  `writeKnown(level)` and `readKnown(level)` say when the server's and the
269
282
  client's traffic secret for the Handshake and Application levels is known
270
283
  (the Initial level has none); the secrets themselves are `Secret` fields of
@@ -272,7 +285,9 @@ client's traffic secret for the Handshake and Application levels is known
272
285
  `clientHandshake`, `serverApplication`, `clientApplication` and `exporter` —
273
286
  which a carrier reads only through `expose` (`installHeld` turns one into a
274
287
  record key), and `wipeSecret(TLS_SECRET_*)` zeroes one once the carrier has
275
- what it needs. The state says what is due: `TLS_STATE_WAIT_SIGNATURE` after the
288
+ what it needs.
289
+
290
+ The state says what is due: `TLS_STATE_WAIT_SIGNATURE` after the
276
291
  first flight is written, `TLS_STATE_WAIT_FINISHED` once it is signed,
277
292
  `TLS_STATE_CONNECTED` when the client's Finished verified, and
278
293
  `TLS_STATE_FAILED` with `alert` set after a refusal. Over QUIC, set `quic` in
@@ -283,7 +298,9 @@ ways (`clientTransportParameters` holds the client's).
283
298
  computed with, are `Secret`s wiped on every path, and `tlsSignEcdsaP256` takes
284
299
  its key as a `Secret`. The one-shot key-schedule functions of
285
300
  `nish/net/tls/schedule` and `tlsNextTrafficSecret` take and answer their
286
- secrets as `Secret<u8[]>`s, so a plain array there is a compile error. What `TlsServer` keeps for an open connection —
301
+ secrets as `Secret<u8[]>`s, so a plain array there is a compile error.
302
+
303
+ What `TlsServer` keeps for an open connection —
287
304
  the caller's ephemeral key, copied in by `restart`, and the handshake,
288
305
  traffic, exporter and resumption secrets — and the four traffic secrets
289
306
  `TlsRecordServer` keeps for KeyUpdate are `Secret` fields, readonly and read
@@ -293,6 +310,7 @@ zeroed once the carrier has what it needs from it and at every end of the
293
310
  connection (TLS-1 in
294
311
  [`docs/security/tls.md`](../docs/security/tls.md), the record that also lists
295
312
  what each refusal is and the test that pins it).
313
+
296
314
  `tests/link/net_tls_*` are the module's programs, each also run under
297
315
  `--number-mode f64`.
298
316
 
@@ -302,18 +320,20 @@ test or another transport. The program is the loop: there are no callbacks,
302
320
  so each call answers the slot's interest and the program re-arms the
303
321
  descriptor with `pollModify(loop, tls.fd(slot), wants & 3, slot)`, signs on
304
322
  `TLS_RECORD_SIGN`, reads on `TLS_RECORD_DATA` and calls `close(slot)` on
305
- `TLS_RECORD_DONE`. A slot's buffers — about 136 KB of resident memory, measured over a 400-slot pool, with the handshake's own state in them — are
306
- allocated once, on the first accept into the slot, and after its handshake a connection allocates nothing that
307
- outlives a record. The handshake keeps its state in the slot, which `accept`
308
- restarts, and a KeyUpdate installs its keys in place, so neither leaves
309
- anything in the arena (TLS-3); a connection still takes at most
310
- `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier
311
- has no clock, so
312
- closing quiet slots is the program's (TLS-4). On this path the record layer
313
- wipes `TlsServer`'s traffic and handshake secrets and the ephemeral key once
314
- it has what it needs from them, which narrows TLS-1.
315
- `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block
316
- of `tests/run.js` drives the carrier with openssl and Node's `https`.
323
+ `TLS_RECORD_DONE`.
324
+
325
+ A slot's buffers — about 136 KB of resident memory, measured over a 400-slot
326
+ pool, with the handshake's own state in them — are allocated once, on the first
327
+ accept into the slot, and after its handshake a connection allocates nothing
328
+ that outlives a record. The handshake keeps its state in the slot, which
329
+ `accept` restarts, and a KeyUpdate installs its keys in place, so neither
330
+ leaves anything in the arena (TLS-3); a connection still takes at most
331
+ `TLS_RECORD_MAX_KEY_UPDATES` (64) KeyUpdates from its client. The carrier has
332
+ no clock, so closing quiet slots is the program's (TLS-4). On this path the
333
+ record layer wipes `TlsServer`'s traffic and handshake secrets and the
334
+ ephemeral key once it has what it needs from them, which narrows TLS-1.
335
+ `tests/link/net_tls_record_*` are its programs, and the `net_tls_tcp` block of
336
+ `tests/run.js` drives the carrier with openssl and Node's `https`.
317
337
 
318
338
  **How a server drives `QuicConnection`.** Keep one `QuicListener` for the
319
339
  server, with the same `QuicServerConfig` its connections use: two static keys
@@ -321,34 +341,37 @@ of `QUIC_CONN_STATIC_KEY_SIZE` bytes (the stateless reset key, which has to
321
341
  survive a restart to be any use, and the Retry token key) and whether to
322
342
  ask for Retry. `listener.release()` wipes the listener's seed and scratch
323
343
  when the server stops; the two keys are the caller's to wipe then, unless
324
- `Http3Server.stop` does it (QUIC-5). Route each datagram by
325
- its first packet's DCID: to the connection whose `ownsConnectionId` says it
326
- is its, and anything else to `listener.handle(datagram, address, now)`, which
327
- answers what to send back or says to make a connection — and must see nothing
328
- a live connection owns, or a stateless reset would end that connection.
329
- Make the connection when it says so, with `QUIC_CONN_ENTROPY_SIZE` bytes from
330
- `crypto.getRandomValues`: the TLS server random and x25519 key, the server's
331
- first connection ID and the seed its later IDs are derived from all come out
332
- of them, so a test injects fixed bytes and a recorded exchange replays byte
333
- for byte. Neither has a clock: `now` is the caller's monotonic time in
334
- milliseconds, and `deadline()` says when to call `handleTimer(now)` next.
335
- Hand the connection every datagram the client sends;
344
+ `Http3Server.stop` does it (QUIC-5).
345
+
346
+ Route each datagram by its first packet's DCID: to the connection whose
347
+ `ownsConnectionId` says it is its, and anything else to
348
+ `listener.handle(datagram, address, now)`, which answers what to send back or
349
+ says to make a connection — and must see nothing a live connection owns, or a
350
+ stateless reset would end that connection. Make the connection when it says so,
351
+ with `QUIC_CONN_ENTROPY_SIZE` bytes from `crypto.getRandomValues`: the TLS
352
+ server random and x25519 key, the server's first connection ID and the seed its
353
+ later IDs are derived from all come out of them, so a test injects fixed bytes
354
+ and a recorded exchange replays byte for byte. Neither has a clock: `now` is
355
+ the caller's monotonic time in milliseconds, and `deadline()` says when to call
356
+ `handleTimer(now)` next. Hand the connection every datagram the client sends;
336
357
  when `signatureInput()` answers bytes, sign them (`tlsSignEcdsaP256`) and hand
337
- the signature to `sign`; then send whatever `takeDatagram(now)` answers until it
338
- answers `null`, to the address the datagram came from. `ownsConnectionId`
339
- says whether a datagram's DCID is the connection's, which is how a server
340
- with many routes them. Stream data comes out of `readStream()` in order per
341
- stream, and `writeStream` queues a reply within the credit the client gave.
342
- `state` says where it is, and `error` why it closed. The keys of each level
343
- are wiped when the level is discarded, each key generation when an update
344
- replaces it, and the rest by `release()` or the idle timeout; what no wipe
345
- reaches is QUIC-2 in [`docs/security/quic.md`](../docs/security/quic.md).
358
+ the signature to `sign`; then send whatever `takeDatagram(now)` answers until
359
+ it answers `null`, to the address the datagram came from. `ownsConnectionId`
360
+ says whether a datagram's DCID is the connection's, which is how a server with
361
+ many routes them. Stream data comes out of `readStream()` in order per stream,
362
+ and `writeStream` queues a reply within the credit the client gave. `state`
363
+ says where it is, and `error` why it closed.
364
+
365
+ The keys of each level are wiped when the level is discarded, each key
366
+ generation when an update replaces it, and the rest by `release()` or the idle
367
+ timeout; what no wipe reaches is QUIC-2 in
368
+ [`docs/security/quic.md`](../docs/security/quic.md).
346
369
  `tests/link/net_quic_frame`, `net_quic_conn_parts`, `net_quic_conn`,
347
370
  `net_quic_conn_replay`, `net_quic_lifecycle` and `net_quic_lifecycle_replay`
348
371
  are its programs, each also run under `--number-mode f64`; the two replays
349
- send, over loopback from a Nish UDP client, exchanges recorded against
350
- aioquic by their `record.sh`: a handshake and echo, and Version Negotiation,
351
- Retry, key update both ways, the idle timeout and a stateless reset.
372
+ send, over loopback from a Nish UDP client, exchanges recorded against aioquic
373
+ by their `record.sh`: a handshake and echo, and Version Negotiation, Retry, key
374
+ update both ways, the idle timeout and a stateless reset.
352
375
 
353
376
  `net/http1-codec.ts`, `net/http1-server.ts` and `net/websocket.ts` run their checks
354
377
  again under `--number-mode f64` (`net_http1_f64`, `net_http1_server_f64`,
@@ -374,7 +397,9 @@ specifier works at any depth and from outside this repository.
374
397
  §2), so an import of a `std/` module is not a link against a built library: the
375
398
  module is compiled with the program that imports it, and the whole-program
376
399
  attribute pass sees through it exactly as it sees through the program's own
377
- functions. A `std/` function is inlined, specialised or dropped on the same
400
+ functions.
401
+
402
+ A `std/` function is inlined, specialised or dropped on the same
378
403
  terms as a local one — and a module you import but never call is dropped
379
404
  whole. Measured at the `speed` and `size` profiles, both of which link with
380
405
  `-flto -Wl,--gc-sections`: a program importing three `std/text` functions and
@@ -426,17 +451,18 @@ that are *not* this package.
426
451
 
427
452
  - **Spell the widths — and then convert what the builtins hand you.** `i32`,
428
453
  `i64`, `f64`, never `number`, so the module means the same thing under
429
- `--number-mode f64` as it does by default (`examples/arrays.ts` says that half
430
- for the same reason). It is necessary and **not sufficient**: `s.length`,
431
- `a.length` and `s.charCodeAt(i)` answer `number`, which *is* `f64` in that
432
- mode, so a module that declares every width of its own and still writes
433
- `let end: i32 = text.length` or `while (i < text.length)` does not compile
434
- there at all. Read each of those through `toI32` —
435
- `const length: i32 = toI32(text.length)`, once per function rather than once
436
- per iteration — and the module means one program in both modes. The default
437
- mode pays nothing for it, because `toI32` on an `i32` is identity.
438
- `tests/link/std_text_f64` is what keeps this from being prose;
439
- [`docs/wp26-stdlib.md`](https://github.com/amritk/nish/blob/main/docs/wp26-stdlib.md) §4 is the reasoning.
454
+ `--number-mode f64` as it does by default (`examples/arrays.ts` says that
455
+ half for the same reason). It is necessary and **not sufficient**:
456
+ `s.length`, `a.length` and `s.charCodeAt(i)` answer `number`, which *is*
457
+ `f64` in that mode, so a module that declares every width of its own and
458
+ still writes `let end: i32 = text.length` or `while (i < text.length)` does
459
+ not compile there at all. Read each of those through `toI32` — `const length:
460
+ i32 = toI32(text.length)`, once per function rather than once per iteration —
461
+ and the module means one program in both modes. The default mode pays nothing
462
+ for it, because `toI32` on an `i32` is identity. `tests/link/std_text_f64` is
463
+ what keeps this from being prose;
464
+ [`docs/wp26-stdlib.md`](https://github.com/amritk/nish/blob/main/docs/wp26-stdlib.md)
465
+ §4 is the reasoning.
440
466
  - **Name the private helpers as though they were exported.** A `std/` module
441
467
  belongs to package `nish`, so its symbols no longer collide with the
442
468
  importing program's (`tests/link/std_package_scope`), but every `std/` module
@@ -463,6 +489,7 @@ that are *not* this package.
463
489
  module into the corpus the stage1 oracles read
464
490
  ([`.claude/selfhost.md`](https://github.com/amritk/nish/blob/main/.claude/selfhost.md)): a `std/` module with no
465
491
  importer in `tests/link/` is compiled on no run.
492
+
466
493
  `testing.ts` has two, one per outcome — `tests/link/std_testing` (exit 0) and
467
494
  `tests/link/std_testing_fail` (exit 1, and the wording of every failure
468
495
  message) — and `text.ts` and `json.ts` have `tests/link/std_text` and
package/std/array.ts ADDED
@@ -0,0 +1,266 @@
1
+ /**
2
+ * `std/array` — the array methods that take a callback, and `slice`, in Nish:
3
+ * each a plain loop, compiled once per callback.
4
+ *
5
+ * export const main = (): i32 => {
6
+ * const xs: i32[] = [3, 1, 2];
7
+ * const doubled = xs.map((x) => x * 2); // [6, 2, 4]
8
+ * const big = xs.filter((x) => x > 1); // [3, 2]
9
+ * return doubled[0] + big.length + xs.findIndex((x) => x === 2); // 6 + 2 + 2
10
+ * };
11
+ *
12
+ * **A program does not need to import this module.** A `.map(...)`,
13
+ * `.filter(...)`, `.some(...)`, `.every(...)`, `.findIndex(...)` or
14
+ * `.slice(...)` call on an array is what loads it (the checker's
15
+ * `importArrayMethods`), and the checker routes the call to the template here
16
+ * that matches it: `xs.map(f)` is `map(xs, f)` when `f` takes one parameter
17
+ * and `mapIndexed(xs, f)` when it takes two. `f` is a compile-time function
18
+ * parameter, so each callback is an instantiation of its own whose body calls
19
+ * it directly — there is no function pointer, and importing a template here
20
+ * by name and calling it gives the same code as the method. Under Node,
21
+ * `--emit-ts` leaves `map`, `filter`, `some`, `every` and `findIndex` as the
22
+ * platform's own `Array.prototype` methods, writes `slice` as the runtime's
23
+ * checked `sliceArray`, and copies an answer that holds records inline with
24
+ * `copyRecords`, so nothing here runs there.
25
+ *
26
+ * **Same answers as Node.** Each walks the array from index 0 upward and
27
+ * calls the callback once per element, in order, until the length it had when
28
+ * the call began, as `Array.prototype` does; `some`, `every` and `findIndex`
29
+ * stop at the first element that decides the answer. A callback that shrinks
30
+ * the array ends the walk at the new length, where JavaScript goes on and
31
+ * skips the missing indices.
32
+ */
33
+
34
+ /**
35
+ * The elements of `xs`, each passed through `f`, in a new array of the same
36
+ * length: what `xs.map(f)` compiles to when `f` takes one parameter.
37
+ *
38
+ * @param xs the array read; it is not changed.
39
+ * @param f called once per element, in order.
40
+ * @returns a new array whose element `i` is `f(xs[i])`.
41
+ */
42
+ export const map = <T, U>(xs: readonly T[], f: (x: T) => U): U[] => {
43
+ const out: U[] = []
44
+ const n = xs.length
45
+ for (let i: number = 0; i < n && i < xs.length; i++) {
46
+ out.push(f(xs[i]))
47
+ }
48
+ return out
49
+ }
50
+
51
+ /**
52
+ * The elements of `xs`, each passed through `f` with its index: what
53
+ * `xs.map(f)` compiles to when `f` takes two parameters.
54
+ *
55
+ * @param xs the array read; it is not changed.
56
+ * @param f called once per element, in order, with the element and its index.
57
+ * @returns a new array whose element `i` is `f(xs[i], i)`.
58
+ */
59
+ export const mapIndexed = <T, U>(xs: readonly T[], f: (x: T, i: number) => U): U[] => {
60
+ const out: U[] = []
61
+ const n = xs.length
62
+ for (let i: number = 0; i < n && i < xs.length; i++) {
63
+ out.push(f(xs[i], i))
64
+ }
65
+ return out
66
+ }
67
+
68
+ /**
69
+ * The elements of `xs` for which `pred` answers `true`, in order, in a new
70
+ * array: what `xs.filter(pred)` compiles to when `pred` takes one parameter.
71
+ *
72
+ * @param xs the array read; it is not changed.
73
+ * @param pred called once per element, in order.
74
+ * @returns a new array of the elements kept.
75
+ */
76
+ export const filter = <T>(xs: readonly T[], pred: (x: T) => boolean): T[] => {
77
+ const out: T[] = []
78
+ const n = xs.length
79
+ for (let i: number = 0; i < n && i < xs.length; i++) {
80
+ const x = xs[i]
81
+ if (pred(x)) {
82
+ out.push(x)
83
+ }
84
+ }
85
+ return out
86
+ }
87
+
88
+ /**
89
+ * The elements of `xs` for which `pred` answers `true`, given each element and
90
+ * its index: what `xs.filter(pred)` compiles to when `pred` takes two
91
+ * parameters.
92
+ *
93
+ * @param xs the array read; it is not changed.
94
+ * @param pred called once per element, in order, with the element and its index.
95
+ * @returns a new array of the elements kept.
96
+ */
97
+ export const filterIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): T[] => {
98
+ const out: T[] = []
99
+ const n = xs.length
100
+ for (let i: number = 0; i < n && i < xs.length; i++) {
101
+ const x = xs[i]
102
+ if (pred(x, i)) {
103
+ out.push(x)
104
+ }
105
+ }
106
+ return out
107
+ }
108
+
109
+ /**
110
+ * Whether `pred` answers `true` for at least one element of `xs`, stopping at
111
+ * the first that does: what `xs.some(pred)` compiles to when `pred` takes one
112
+ * parameter. An empty array answers `false`.
113
+ *
114
+ * @param xs the array read; it is not changed.
115
+ * @param pred called in order until it answers `true`.
116
+ * @returns `true` when some element satisfies `pred`.
117
+ */
118
+ export const some = <T>(xs: readonly T[], pred: (x: T) => boolean): boolean => {
119
+ const n = xs.length
120
+ for (let i: number = 0; i < n && i < xs.length; i++) {
121
+ if (pred(xs[i])) {
122
+ return true
123
+ }
124
+ }
125
+ return false
126
+ }
127
+
128
+ /**
129
+ * Whether `pred` answers `true` for at least one element of `xs`, given each
130
+ * element and its index: what `xs.some(pred)` compiles to when `pred` takes
131
+ * two parameters.
132
+ *
133
+ * @param xs the array read; it is not changed.
134
+ * @param pred called in order, with the element and its index, until it answers `true`.
135
+ * @returns `true` when some element satisfies `pred`.
136
+ */
137
+ export const someIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): boolean => {
138
+ const n = xs.length
139
+ for (let i: number = 0; i < n && i < xs.length; i++) {
140
+ if (pred(xs[i], i)) {
141
+ return true
142
+ }
143
+ }
144
+ return false
145
+ }
146
+
147
+ /**
148
+ * Whether `pred` answers `true` for every element of `xs`, stopping at the
149
+ * first that does not: what `xs.every(pred)` compiles to when `pred` takes one
150
+ * parameter. An empty array answers `true`.
151
+ *
152
+ * @param xs the array read; it is not changed.
153
+ * @param pred called in order until it answers `false`.
154
+ * @returns `true` when no element fails `pred`.
155
+ */
156
+ export const every = <T>(xs: readonly T[], pred: (x: T) => boolean): boolean => {
157
+ const n = xs.length
158
+ for (let i: number = 0; i < n && i < xs.length; i++) {
159
+ if (!pred(xs[i])) {
160
+ return false
161
+ }
162
+ }
163
+ return true
164
+ }
165
+
166
+ /**
167
+ * Whether `pred` answers `true` for every element of `xs`, given each element
168
+ * and its index: what `xs.every(pred)` compiles to when `pred` takes two
169
+ * parameters.
170
+ *
171
+ * @param xs the array read; it is not changed.
172
+ * @param pred called in order, with the element and its index, until it answers `false`.
173
+ * @returns `true` when no element fails `pred`.
174
+ */
175
+ export const everyIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): boolean => {
176
+ const n = xs.length
177
+ for (let i: number = 0; i < n && i < xs.length; i++) {
178
+ if (!pred(xs[i], i)) {
179
+ return false
180
+ }
181
+ }
182
+ return true
183
+ }
184
+
185
+ /**
186
+ * The index of the first element of `xs` for which `pred` answers `true`:
187
+ * what `xs.findIndex(pred)` compiles to when `pred` takes one parameter.
188
+ *
189
+ * @param xs the array read; it is not changed.
190
+ * @param pred called in order until it answers `true`.
191
+ * @returns the first such index, or `-1` when there is none.
192
+ */
193
+ export const findIndex = <T>(xs: readonly T[], pred: (x: T) => boolean): number => {
194
+ const n = xs.length
195
+ for (let i: number = 0; i < n && i < xs.length; i++) {
196
+ if (pred(xs[i])) {
197
+ return i
198
+ }
199
+ }
200
+ return -1
201
+ }
202
+
203
+ /**
204
+ * The index of the first element of `xs` for which `pred` answers `true`,
205
+ * given each element and its index: what `xs.findIndex(pred)` compiles to when
206
+ * `pred` takes two parameters.
207
+ *
208
+ * @param xs the array read; it is not changed.
209
+ * @param pred called in order, with the element and its index, until it answers `true`.
210
+ * @returns the first such index, or `-1` when there is none.
211
+ */
212
+ export const findIndexIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): number => {
213
+ const n = xs.length
214
+ for (let i: number = 0; i < n && i < xs.length; i++) {
215
+ if (pred(xs[i], i)) {
216
+ return i
217
+ }
218
+ }
219
+ return -1
220
+ }
221
+
222
+ /**
223
+ * A copy of `xs[start..end)` in a new array: what `xs.slice(start, end)`
224
+ * compiles to, with string `slice`'s rule. The range must satisfy
225
+ * `0 <= start <= end <= xs.length`, and anything else panics with
226
+ * `slice out of range: [start, end) of length n` and exits 1, where
227
+ * JavaScript counts a negative end back from the length and clamps the rest.
228
+ * A float bound is truncated toward zero and saturates (NaN to 0, an infinity
229
+ * to the `i64` limit), natively and under Node alike.
230
+ *
231
+ * @param xs the array copied from; it is not changed.
232
+ * @param start the first index copied.
233
+ * @param end the index after the last copied.
234
+ * @returns a new array of `end - start` elements.
235
+ */
236
+ export const slice = <T>(xs: readonly T[], start: number, end: number): T[] => {
237
+ const from = toI64(start)
238
+ const to = toI64(end)
239
+ const len = toI64(xs.length)
240
+ if (from < 0 || from > to || to > len) {
241
+ panic(`slice out of range: [${from}, ${to}) of length ${len}`)
242
+ }
243
+ const out: T[] = []
244
+ for (let i: i32 = toI32(from); i >= 0 && i < toI32(to) && i < toI32(xs.length); i++) {
245
+ out.push(xs[i])
246
+ }
247
+ return out
248
+ }
249
+
250
+ /**
251
+ * A copy of `xs[start..)`: what `xs.slice(start)` compiles to. `start` must
252
+ * satisfy `0 <= start <= xs.length`, or the call panics as `slice` does.
253
+ *
254
+ * @param xs the array copied from; it is not changed.
255
+ * @param start the first index copied.
256
+ * @returns a new array of the elements from `start` on.
257
+ */
258
+ export const sliceFrom = <T>(xs: readonly T[], start: number): T[] => slice(xs, start, xs.length)
259
+
260
+ /**
261
+ * A copy of the whole of `xs`: what `xs.slice()` compiles to.
262
+ *
263
+ * @param xs the array copied; it is not changed.
264
+ * @returns a new array with the same elements.
265
+ */
266
+ export const sliceAll = <T>(xs: readonly T[]): T[] => slice(xs, 0, xs.length)