nish 0.44.0 → 0.46.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.
- package/README.md +1 -1
- package/docs/AI.md +18 -16
- package/docs/INSTALL.md +3 -1
- package/package.json +5 -5
- package/runtime/core/numbers.mjs +3 -1
- package/runtime/core/strings.mjs +90 -38
- package/runtime/core.d.ts +8 -0
- package/runtime/core.mjs +16 -0
- package/runtime/nish.d.ts +88 -5
- package/runtime/nish.h +10 -0
- package/runtime/nish.mjs +5 -0
- package/runtime/runtime-host.c +15 -0
- package/runtime/runtime-net.c +223 -4
- package/runtime/runtime-os.c +15 -1
- package/runtime/runtime-uring.c +291 -31
- package/runtime/sqlite/nish-sqlite.c +301 -128
- package/std/README.md +15 -15
- package/std/array.ts +10 -2
- package/std/bytes.ts +239 -26
- package/std/cli-args.ts +1072 -606
- package/std/cli-flags.ts +180 -98
- package/std/cli.ts +21 -13
- package/std/collections.ts +245 -127
- package/std/compress/checksum.ts +32 -37
- package/std/compress/deflate.ts +1102 -542
- package/std/compress/gzip.ts +290 -145
- package/std/compress/zlib.ts +57 -21
- package/std/crypto/aes.ts +153 -75
- package/std/crypto/base64url.ts +84 -61
- package/std/crypto/bcrypt-batch.ts +164 -90
- package/std/crypto/bcrypt.ts +185 -107
- package/std/crypto/chacha20poly1305.ts +84 -68
- package/std/crypto/ct.ts +9 -7
- package/std/crypto/ed25519.ts +64 -27
- package/std/crypto/hkdf.ts +105 -63
- package/std/crypto/hmac.ts +95 -89
- package/std/crypto/jwt.ts +248 -126
- package/std/crypto/p256.ts +758 -444
- package/std/crypto/p384.ts +20 -13
- package/std/crypto/pki-roots.ts +95 -38
- package/std/crypto/pki.ts +164 -60
- package/std/crypto/rsa.ts +266 -223
- package/std/crypto/scram.ts +3 -4
- package/std/crypto/sha1.ts +107 -65
- package/std/crypto/sha256.ts +502 -422
- package/std/crypto/sha512.ts +204 -135
- package/std/crypto/x509-random.ts +9 -3
- package/std/crypto/x509.ts +331 -171
- package/std/json-equal.ts +35 -19
- package/std/json-format.ts +215 -108
- package/std/json-number.ts +126 -72
- package/std/json-pointer.ts +42 -13
- package/std/json-tokenizer.ts +498 -307
- package/std/json-typed.ts +115 -36
- package/std/json-value.ts +341 -152
- package/std/json.ts +300 -158
- package/std/net/buffer-pool.ts +17 -7
- package/std/net/dns-config.ts +427 -236
- package/std/net/dns-message.ts +114 -47
- package/std/net/dns-resolver.ts +736 -237
- package/std/net/dns.ts +205 -52
- package/std/net/fetch.ts +320 -184
- package/std/net/grpc.ts +948 -0
- package/std/net/handler.ts +1315 -222
- package/std/net/hpack.ts +395 -180
- package/std/net/http-compress.ts +502 -65
- package/std/net/http-fields.ts +85 -49
- package/std/net/http-server.ts +1764 -602
- package/std/net/http1-client-codec.ts +372 -161
- package/std/net/http1-codec.ts +665 -331
- package/std/net/http1-server.ts +660 -278
- package/std/net/http2-cleartext.ts +165 -95
- package/std/net/http2-frame.ts +232 -89
- package/std/net/http2-tls.ts +42 -12
- package/std/net/http2.ts +327 -101
- package/std/net/http3-frame.ts +68 -33
- package/std/net/http3-server.ts +647 -192
- package/std/net/http3.ts +667 -189
- package/std/net/oidc.ts +63 -24
- package/std/net/outbound.ts +207 -142
- package/std/net/postgres-async.ts +1165 -443
- package/std/net/postgres-carrier.ts +575 -372
- package/std/net/postgres.ts +1459 -559
- package/std/net/prefork.ts +254 -98
- package/std/net/protobuf.ts +1017 -0
- package/std/net/qpack.ts +143 -92
- package/std/net/quic-conn-ack.ts +50 -18
- package/std/net/quic-conn-cid.ts +66 -26
- package/std/net/quic-conn-params.ts +13 -7
- package/std/net/quic-datagram.ts +90 -27
- package/std/net/quic-frame.ts +225 -124
- package/std/net/quic-listener.ts +197 -89
- package/std/net/quic-packet.ts +289 -163
- package/std/net/quic-recovery.ts +279 -128
- package/std/net/quic-stream.ts +466 -167
- package/std/net/quic.ts +568 -257
- package/std/net/router.ts +450 -99
- package/std/net/serve.ts +651 -232
- package/std/net/static.ts +1458 -0
- package/std/net/tls/client.ts +140 -45
- package/std/net/tls/codec.ts +510 -260
- package/std/net/tls/record-client.ts +268 -76
- package/std/net/tls/record-server.ts +236 -79
- package/std/net/tls/record.ts +173 -47
- package/std/net/tls/schedule.ts +58 -39
- package/std/net/tls/ticket.ts +295 -103
- package/std/net/tls/verify.ts +1 -1
- package/std/net/tls-tcp.ts +218 -75
- package/std/net/tls.ts +260 -152
- package/std/net/upstream.ts +283 -86
- package/std/net/url.ts +277 -102
- package/std/net/websocket.ts +370 -186
- package/std/net/webtransport.ts +755 -436
- package/std/regex.ts +1659 -829
- package/std/sqlite.ts +171 -0
- package/std/sync/ring.ts +320 -156
- package/std/sync/shm.ts +53 -6
- package/std/text.ts +205 -124
- package/std/threads.ts +22 -2
package/std/README.md
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
Nish modules written in Nish, for Nish programs to import. A module in this
|
|
4
4
|
directory is an ordinary Nish source file, compiled as part of whatever program
|
|
5
5
|
imports it and subject to the same rules as any other
|
|
6
|
-
([`docs/LANGUAGE.md`](
|
|
6
|
+
([`docs/LANGUAGE.md`](../docs/reference/language.md) is the style guide).
|
|
7
7
|
The compiler knows about a few of them, and each such row says how: the modules
|
|
8
8
|
a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
9
9
|
`math.ts`), the functions it lowers in place (`map.ts`, `threads.ts`,
|
|
@@ -13,14 +13,14 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
13
13
|
| Module | What it is |
|
|
14
14
|
| --- | --- |
|
|
15
15
|
| [`testing.ts`](https://github.com/amritk/nish/blob/main/std/testing.ts) | a test runner: a `Suite` a program drives with straight-line assertions, printing the `PASS` / `FAIL` / `SKIP` lines the repository's own harness prints, and answering the exit code |
|
|
16
|
-
| [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of
|
|
16
|
+
| [`text.ts`](https://github.com/amritk/nish/blob/main/std/text.ts) | the string operations a program would otherwise write inline: `split` and `splitLimit` (JavaScript's `split(sep, limit)`), `toFixed` (JavaScript's `x.toFixed(digits)`, rounded on the exact binary value), `splitLines`, `splitWhitespace`, `trim` and its halves, `contains`, `replaceAll`, `firstDifference` over two arrays of lines, `codePointLength`, the number of Unicode code points (what JSON Schema's `minLength` counts, where `.length` counts UTF-8 bytes natively and UTF-16 units under Node; it answers the same on both by asking which it is reading), and `indexOfAny(text, bytes, from)`, the first index at or after `from` whose byte is one of `bytes`. Its walker is the meaning and what runs under Node; natively the compiler replaces the one call to it with the runtime kernel `nish_str_index_of_any`, which reads 16 or 32 bytes at a time and is variable-time ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-search-indexofany-in-nishtext)). `tests/link/std_text_index_of_any*` are its programs |
|
|
17
17
|
| [`math.ts`](https://github.com/amritk/nish/blob/main/std/math.ts) | `Math.tan`, `Math.atan2` and `Math.hypot` on `f64`, ported from fdlibm (`LICENSE-fdlibm`) so that every target, wasm included, answers alike without libm. A program never imports it: a call to one of the three loads it, and the compiler copies the functions the call reaches into the calling module as `internal` ones. JavaScript's answer for every NaN, signed zero and infinity, and within one ulp elsewhere (0.83, 0.84 and 0.93 ulp measured against mpmath). `tests/cases/math_std_edges` pins the special values |
|
|
18
18
|
| [`sort.ts`](https://github.com/amritk/nish/blob/main/std/sort.ts) | `xs.sort(cmp)` on any array: `sortWith`, a stable merge sort over runs of 32 sorted by insertion — one scratch array released before it returns, a pair of runs already in order copied without merging, no bounds check left in it — so its order is element for element Node's `Array.prototype.sort`. Like `math.ts` it is one the compiler knows about: a program never imports it, a `.sort(cmp)` call loads it, the checker rewrites the call to `sortWith`, and each comparator's instantiation — the comparator called directly, no function pointer — is copied into the module that sorts. Under Node the call stays the platform's own. `tests/cases/arr_sort_cmp*` are its programs, a 10,000-element sort with ties among them |
|
|
19
19
|
| [`array.ts`](https://github.com/amritk/nish/blob/main/std/array.ts) | the array methods that take a callback, and `slice`: `xs.map(f)`, `filter`, `some`, `every`, `findIndex` and `slice`, each a plain loop compiled once per callback, with no function pointer. A program never imports it: a call to one of those methods on an array loads it, and the compiler routes `xs.map(f)` to `map` or `mapIndexed` by how many parameters `f` takes. Each walks the array in order up to the length it had when the call began, as `Array.prototype` does, and `some`, `every` and `findIndex` stop at the element that decides the answer; a callback that shrinks the array ends the walk at the new length, where JavaScript goes on. Under Node the methods are the platform's own (`tests/cases/arr_map`, `arr_filter` and their kin) |
|
|
20
20
|
| [`regex.ts`](https://github.com/amritk/nish/blob/main/std/regex.ts) | Regular expressions in JavaScript's syntax with the `u` flag's strictness, matched by a Pike VM in time linear in the input whatever the pattern; finding every match is one search per match, so `findAll` and its kin can be quadratic when a long branch is preferred to a short one that wins ([`docs/security/regex.md`](../docs/security/regex.md)). `regexCompile(pattern, flags)` answers a `Regex` or the error text; `test`, `exec` into a reused `RegexMatch`, `find`, `findAll`, `count`, `replace` and `replaceAll` with `$&`, `$1` and `$<name>`, and `split`. Flags `i`, `m`, `s` and `u`; `i` folds by Unicode's simple case folding, ASCII letters only to ASCII. `\p{…}` and `\P{…}` take Unicode 16.0's General_Category, Script, Script_Extensions and binary properties by JavaScript's names, from tables `scripts/gen-regex-unicode.mjs` generates into the module and checks against Node's `RegExp`; backreferences and lookaround are refused at compile time. Offsets are UTF-8 bytes. A search allocates nothing beyond its answer: the thread lists and capture tables are the `Regex`'s, so one `Regex` serves one thread at a time. A leading literal is found with `indexOf`, a small leading set with `indexOfAny`. `tests/link/std_regex` and `tests/link/std_regex_unicode` check it against JavaScript's own answers |
|
|
21
21
|
| [`json.ts`](https://github.com/amritk/nish/blob/main/std/json.ts) | `jsonField(object, name)`: the value of one field of one flat JSON object, which is the shape the compiler's own `--json` diagnostics have. A reader and not a parser — it answers text, answers `null` for a field that is not there, and does not validate. `JsonWriter` is the other direction: any JSON value written into a caller-owned `u8[]`, commas and colons included, byte for byte what `JSON.stringify` writes, and allocating nothing per call except an `f64`'s digits, a temporary string the call gives back before it returns (`text()` and `jsonStringifyString` build strings by design); misuse and a full buffer set a sticky negative `JSON_WRITE_*` code in `failed` rather than panicking. `setIndent(n)` and `setIndentTab()` write what `JSON.stringify(v, null, n)` or `(v, null, "\t")` writes, with no allocation for the indent, and `setStrict(true)` makes NaN and the infinities the sticky `JSON_WRITE_NON_FINITE` instead of `null`; both modes are off by default and kept by `reset`. `jsonStringifyString(s)` is the string rule answered as a string. `stringBytes(bytes, off, len)` and `keyBytes(bytes, off, len)` write a window of a byte array as `string` and `key` write a string of those bytes, allocating nothing, and refuse a window outside the array with `JSON_WRITE_BAD_WINDOW` |
|
|
22
22
|
| [`json-tokenizer.ts`](https://github.com/amritk/nish/blob/main/std/json-tokenizer.ts) | `JsonTokenizer`: a validating, streaming tokenizer for RFC 8259 JSON held in a window of a `u8[]`. `next()` answers one `JSON_TOK_*` token at a time — object and array openers and closers, keys, strings, numbers and the three literals — then `JSON_TOK_END`, or a negative `JSON_TOK_ERR_*` code that sticks in `failed`, with the byte in `errorAt`. Strings are checked as UTF-8 and a lone surrogate escape is refused; `stringInto` decodes the current string into the caller's array and `keyEquals` compares it with a name, neither allocating. `numberF64` is correctly rounded; `isInteger` and `numberI64` read an integer that fits an `i64`, and `isU64` and `numberU64` one that fits a `u64`. `isIntegral` asks whether a number's value is whole however it is written (`1.0`, `1e2`, `1e400`), JSON Schema's "integer", from the text and at any exponent. `skipValue` steps over a value. `JsonLimits` caps nesting depth, string, number and total bytes, each with its own code; `reset` reuses the tokenizer, so a reused body keeps the arena flat. Duplicate keys are reported as tokens. No input panics and no byte outside the window is read; [`docs/security/json.md`](../docs/security/json.md) is its record, and `tests/link/std_json_tokenizer` runs JSONTestSuite and a seeded fuzz |
|
|
23
|
-
| [`json-typed.ts`](https://github.com/amritk/nish/blob/main/std/json-typed.ts) | `jsonDecode(d, out)` and `jsonEncode(w, value)`: one JSON object read into a class and written back, with code the compiler writes at each call from the class's fields — scalars (`u64` exact to 2^64 - 1), strings, enums (a numeric one as its number, a string one as its member's string), nested classes, arrays of those, `Map<string, V>` of those and `\| null` — through `JsonDecoder` (a `JsonTokenizer` and a sticky error) and `JsonWriter`. A class's one `static readonly json` literal renames a field's key and makes a key optional, a missing one setting its field to the initializer; otherwise every field is required, each key once, an unknown key refused unless `ignoreUnknown`, and every outcome a sticky `JSON_DECODE_*` or `JSON_TOK_ERR_*` code with its byte in `errorAt`; decoding into a reused object reuses its objects, arrays and equal strings, so the arena stays flat (a map's entries are made anew, at most `maxMapKeys` over all the maps of one decode, 4,096 by default); a key is sent to its field by its length, then one byte. A `JsonNumber` field keeps a number's text byte for byte. Under Node the types are erased and both calls panic ([`docs/LANGUAGE.md`](
|
|
23
|
+
| [`json-typed.ts`](https://github.com/amritk/nish/blob/main/std/json-typed.ts) | `jsonDecode(d, out)` and `jsonEncode(w, value)`: one JSON object read into a class and written back, with code the compiler writes at each call from the class's fields — scalars (`u64` exact to 2^64 - 1), strings, enums (a numeric one as its number, a string one as its member's string), nested classes, arrays of those, `Map<string, V>` of those and `\| null` — through `JsonDecoder` (a `JsonTokenizer` and a sticky error) and `JsonWriter`. A class's one `static readonly json` literal renames a field's key and makes a key optional, a missing one setting its field to the initializer; otherwise every field is required, each key once, an unknown key refused unless `ignoreUnknown`, and every outcome a sticky `JSON_DECODE_*` or `JSON_TOK_ERR_*` code with its byte in `errorAt`; decoding into a reused object reuses its objects, arrays and equal strings, so the arena stays flat (a map's entries are made anew, at most `maxMapKeys` over all the maps of one decode, 4,096 by default); a key is sent to its field by its length, then one byte. A `JsonNumber` field keeps a number's text byte for byte. Under Node the types are erased and both calls panic ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#typed-json-nishjson-typed), [`docs/security/json.md`](../docs/security/json.md)) |
|
|
24
24
|
| [`json-value.ts`](https://github.com/amritk/nish/blob/main/std/json-value.ts) | `JsonDocument`: any JSON document parsed into a tree of `JsonValue` handles (`i32`s into the document), read with `kind`, `boolean`, `string`, `stringEquals`, `length`, `at`, `keyAt` and `get`, built with the `new*` methods, `push` and `set`, and written back through `JsonWriter` with `write`, or as text with `stringify`. A number keeps its source text and is read on request as an `i64` or `u64` that fits (`isI64`, `isU64`), the nearest `f64`, or the text, and `isIntegral` asks whether its value is whole however it is written (`1.0`, `1e2`), so integers and decimals wider than any type round-trip byte for byte. Objects keep insertion order; a repeated key is `JSON_VALUE_ERR_DUPLICATE` unless `duplicates` is `JSON_VALUE_DUPLICATE_LAST`, `JSON.parse`'s rule. Every parse error and limit is the tokenizer's, with the depth held to the writer's 64 so that whatever parses writes back, nothing panics, and a value is in at most one container, so a tree built through `push` and `set` cannot hold itself. A handle carries the generation of the document it came from, so one kept across a `parse` or `clear` reads as nothing; `maxValues` (262,144 by default, `JSON_VALUE_ERR_VALUES` past it) bounds the memory a document keeps. `parseRanged` and `parseTextRanged` also record each value's byte range (`start`, `end`) and each key's (`keyStart`, `keyEnd`), 20 bytes more per value, and `setRange` and `setKeyRange` give built values theirs; after `parse` or `parseText` every range reads `-1`. Each `parse` reuses the document's arrays, so a reused document keeps the arena flat. `tests/link/std_json_value` runs JSONTestSuite through it ([`docs/security/json.md`](../docs/security/json.md)) |
|
|
25
25
|
| [`json-pointer.ts`](https://github.com/amritk/nish/blob/main/std/json-pointer.ts) | RFC 6901 JSON Pointers over a `JsonDocument`: `jsonPointerParse` (the decoded tokens, or `null`), `jsonPointerEscape` (one token, `~0` and `~1`), and `jsonPointerResolve` (the value, `JSON_POINTER_NONE` when the pointer names nothing, `JSON_POINTER_ERR_SYNTAX` when it is not one); `isJsonPointer` and `isRelativeJsonPointer` check JSON Schema's `json-pointer` and `relative-json-pointer` forms, reading the text once and allocating nothing. A resolve costs the pointer's length plus each object step's size. `tests/link/std_json_pointer` runs the suite's two format files through it |
|
|
26
26
|
| [`json-equal.ts`](https://github.com/amritk/nish/blob/main/std/json-equal.ts) | JSON Schema's value equality for `const`, `enum` and `uniqueItems`: `jsonEqual` across two documents (numbers by value, `1` is `1.0`; member order ignored; `true` is not `1`), `jsonEqualCanonical` (a text equal for exactly the equal values), `jsonEqualHash` (64-bit FNV-1a of it, unkeyed) and `jsonEqualFirstDuplicate` (`-1` when the items are unique). Nothing recurses, so any depth a document holds compares; a call costs the values' sizes plus sorting object keys. `tests/link/std_json_equal` runs the suite's `const`, `enum` and `uniqueItems` |
|
|
@@ -31,16 +31,16 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
31
31
|
| [`yaml-lines.ts`](https://github.com/amritk/nish/blob/main/std/yaml-lines.ts) | `YamlLineIndex`: byte offsets turned into 1-based `line` and `column` (characters) or `byteColumn`, by binary search over line starts found once with `indexOf`. LF, CR LF and a lone CR each break a line; an offset is clamped to the text first. |
|
|
32
32
|
| [`yaml-write.ts`](https://github.com/amritk/nish/blob/main/std/yaml-write.ts) | `stringifyYaml(doc, v)`: a `json-value` value written as block-style YAML that `parseYaml` reads back as the same tree. A string YAML would read as something else (a null, bool or number word, an indicator, a `: ` or ` #`, an edge space, a control character) is double-quoted and escaped; a key over 1024 bytes is an explicit `? key`. `""` for a no-value handle or a tree deeper than `JSON_WRITER_MAX_DEPTH`. |
|
|
33
33
|
| [`pair.ts`](https://github.com/amritk/nish/blob/main/std/pair.ts) | `Pair<A, B>`: an interface with `first` and `second`, for a function that answers two values from one call. A type and nothing else — the caller writes an object literal at the return — and for returning two values rather than storing them side by side |
|
|
34
|
-
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](
|
|
35
|
-
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](
|
|
36
|
-
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](
|
|
34
|
+
| [`collections.ts`](https://github.com/amritk/nish/blob/main/std/collections.ts) | the global `Map<K, V>` and `Set<T>`: insertion-ordered tables whose buckets carry a hash fingerprint beside the entry index and whose entries keep their full hash, so every `get`, `set`, `add`, `has` and `delete` is one probe. `get` is not a method here: its `V | undefined` never crosses a call, so the compiler lowers it to `probe` and, where the key was found, `valueAt`. Nor are `keys()` and `values()`: an iterator is not a value, so a `for...of` over one is lowered to `walkOpen`, `walkNext`, `keyAt` or `valueAt`, and `walkClose`, and a count of live walks defers compaction until no loop is walking the table. A program never imports it: naming `Map` or `Set` loads it, and the compiler emits what a module uses of it into that module ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)). Its `hashKey`, `sameKey` and `storedKey` are lowered by the compiler per key type |
|
|
35
|
+
| [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)) |
|
|
36
|
+
| [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
|
|
37
37
|
| [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array panics before a byte is written. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
|
|
38
38
|
| [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin. There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
|
|
39
|
-
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](
|
|
39
|
+
| [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
|
|
40
40
|
| [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
|
|
41
41
|
| [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle and every mistake a panic at its call. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
|
|
42
42
|
| [`cli-flags.ts`](https://github.com/amritk/nish/blob/main/std/cli-flags.ts) | `nish/cli-flags`: a command line read against a declared table. `FlagTable` declares `string`, `number` (an `f64`), `boolean` (`--name` / `--no-name`) and `repeatable` flags and `command` paths of one or more words; `parse(args)` (or `parseFrom(process.argv, 1)`) answers a `ParsedFlags` with the longest matched `command`, the `positionals` and each flag by name (`str`, `num`, `bool`, `all`, `has`). `--name value`, `--name=value`, `--` and a lone `-` follow the GNU long-option grammar; there are no short options. A usage error (unknown flag, missing value, not a number, given twice, value on a boolean, unknown command) is carried as `code`, `message` and `argument`, and `exitUsage()` writes it to stderr and exits 2. `writeHelp(menu)` adds the table's rows to a `nish/cli` `HelpMenu`. Reaches `exit` only through `exitUsage` (`tests/link/std_cli_flags`, `std_cli_flags_bad_*`; [guide](../docs/guide/using-nish/standard-library.md#parsing-flags)) |
|
|
43
|
-
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](
|
|
43
|
+
| [`sqlite.ts`](https://github.com/amritk/nish/blob/main/std/sqlite.ts) | SQLite, vendored in `runtime/sqlite/` and linked into a program that imports the module, through the C adapter `runtime/sqlite/nish-sqlite.c`. `openDatabase(path, flags)` answers a `Database`: `exec`, `begin` / `commit` / `rollback`, `prepare` into a `Statement`, `lastInsertRowid`, `changes` and `close`, which finalizes the connection's statements. A `Statement` binds (`bindI64`, `bindF64`, `bindNull`, `bindText`, `bindTextBytes`, `bindBlob`), steps, resets and reads columns (`columnType`, `columnI64`, `columnF64`, `columnBytes`, `columnText`, and `columnInto`, a copy into the caller's `u8[]`), so a row allocates nothing. Every failure is a `Result` of SQLite's extended code, and `error(code)` builds the `SqliteError` with its message. A handle is an `i32` into the adapter's thread-local tables, and one used after `close` or `finalize` answers `SQLITE_MISUSE`. Reaches `ffi`; links natively and under `--profile wasi` (`tests/link/std_sqlite*`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#sqlite-nishsqlite)) |
|
|
44
44
|
| [`release.ts`](https://github.com/amritk/nish/blob/main/std/release.ts) | `nish/release`: whether a newer release of a project on GitHub is out, and its `install.sh`. `releaseLatest(base, timeoutMs)` asks `<base>/releases/latest` once without following the redirect and answers the version only when it goes to exactly `<base>/releases/tag/v<version>`, else null; `releaseIsNewer`, `releaseCompare` and `releaseParseVersion` order semantic versions (a prerelease below its release, build metadata ignored, nothing that does not parse ever newer); `releaseValidVersion` is `install.sh`'s rule for a version that may go in a URL. `releaseCheckCached(base, current, path, maxAgeMs, timeoutMs)` keeps the answer in a file believed only when it is a regular file this user owns that nobody else can write, and refreshed when stale or dated in the future; `releaseFetchInstaller` writes a tag's `install.sh` to a file, never to a shell. https only, or http to loopback. The compiler's update notice and `nish upgrade` run on it ([`docs/security/release.md`](../docs/security/release.md); `tests/run.js` "nish/release"; [guide](../docs/guide/using-nish/standard-library.md#nishrelease)) |
|
|
45
45
|
| [`term.ts`](https://github.com/amritk/nish/blob/main/std/term.ts) | a terminal UI with no I/O of its own. `Screen` holds `width × height` cells (code point, 24-bit foreground and background, bold and inverse) for the frame being drawn and the frame last sent; `flush()` answers the string that turns one into the other — cursor moves and only the cells that changed, a style sent only where it differs — for the caller to `write`. A `Screen` made with `palette256` sends the nearest 256-colour index instead. `Canvas` draws pixels on a screen, two to a cell with the half block "▀" (`setPixel`, `fillRect`, `line`, `text`). The escapes (`enterAltScreen`, `hideCursor`, `clearScreen`, `beginSync`, …) are functions answering strings, and a `Screen` with `sync` set wraps each flush that changes anything in synchronized output (mode 2026). `FixedStep` is a fixed-step clock: `advance(nowMs)` answers the whole steps of `1000 / stepsPerSecond` ms since the last call, at most `maxSteps`, and `alpha()` the remainder, for logic at 240 Hz and drawing at 120. `KeyDecoder` turns raw-mode bytes into `KeyEvent`s (arrows as `ESC [` or `ESC O`, Enter, Space, Escape, Ctrl-C, characters), carries a sequence a read cut short into the next `feed`, and decides a lone ESC on a timeout the caller's clock measures. `feedEvents` and `pollEvents` read the same bytes as `TermEvent`s, whose `type` is an `EVENT_` constant: keys with `MOD_` bits and an `ACTION_` (legacy, modifyOtherKeys and the kitty keyboard protocol), SGR mouse reports in cells or pixels, bracketed paste, focus, and the terminal's replies to queries, which never come out as keys. `KeyState` tracks which keys are held, making up the releases a terminal without the kitty protocol never sends and turning Ctrl-C into `EVENT_QUIT`. The size, raw mode and the clock are the caller's, so the module reaches no capability and prints the same bytes under Node (`tests/link/std_term`, `std_term_f64`; [guide](../docs/guide/using-nish/standard-library.md#nishterm)) |
|
|
46
46
|
| [`term-probe.ts`](https://github.com/amritk/nish/blob/main/std/term-probe.ts) | what the terminal can do, asked once at start. `probeQueries(env)` is every query as one string — XTVERSION, DECRQM for synchronized output and pixel mouse, kitty's keyboard flags and a kitty graphics query, XTSMGRAPHICS, the cell and text-area sizes, a true-colour read-back, and DA1 last, wrapped for tmux's or screen's passthrough where only the outer terminal can answer. `TermProbe` takes the replies a read at a time (`feed`), holds back any key typed meanwhile (`heldEvents`), is `done()` once DA1 is answered or `timedOut(now)` after 250 ms, and `result()` reads the replies and a `TermEnv` (the `TERM`, `COLORTERM`, `TMUX`, `SSH_*`, `NO_COLOR` and `NISH_TERM_*` variables) into a `TermCaps`: colours, graphics backend, sync, kitty keyboard, cell size, pixel mouse, multiplexer. Pure: the environment, the bytes and the clock are the caller's (`tests/link/std_term_probe`; [guide](../docs/guide/using-nish/terminal.md#what-it-detects-and-what-it-falls-back-to)) |
|
|
@@ -50,10 +50,10 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
50
50
|
| [`input.ts`](https://github.com/amritk/nish/blob/main/std/input.ts) | `nish/input`: what one fixed step reads from its player, for a program whose steps run the same behind a terminal, a page or a test. `StepInput` holds the step's `events` and the `KeyState` of which keys are down, which a host owns and points at what it read each step; `isDown(key, code)` reads a key. The events and the key state are `nish/term`'s. Pure: no capability, no I/O and no clock |
|
|
51
51
|
| [`raster.ts`](https://github.com/amritk/nish/blob/main/std/raster.ts) | `nish/raster`: drawing into a frame of `0xRRGGBB` pixels held as an `Int32Array` with its width and height, so the same draw fills a terminal's `Framebuffer` (`rasterFrame(fb.pixels)` lends its `i32[]`) and a wasm page's module storage with no copy. Colours (`rasterRgb`, `rasterMix`, `rasterAdd`, `rasterDim`, `rasterHue`, `rasterWeight`), a gradient, rectangles, anti-aliased discs, additive glows, 5×7 pixel text (`rasterText`, `rasterTextWidth`), a fading `RasterTrail` and a `RasterParticles` pool made once and stepped in place. Every shape clips to the frame and to the rows the array has. Pure: no capability, no I/O and no clock. `tests/link/std_raster` |
|
|
52
52
|
| [`synth.ts`](https://github.com/amritk/nish/blob/main/std/synth.ts) | `nish/synth`: short sounds as `f64` samples at the caller's rate. `synthSilence(seconds, rate)` makes the array; `synthTone(out, rate, start, length, f0, f1, wave, volume, decay)` adds a square, triangle or noise voice into it with a log pitch slide, an exponential decay and click-free ends; `synthSemitone` steps a pitch. Samples are not clipped. Pure, and noise is a fixed xorshift sequence, so a call gives the same samples every time. `tests/link/std_synth` |
|
|
53
|
-
| [`region.ts`](https://github.com/amritk/nish/blob/main/std/region.ts) | The source behind the builtin module `nish:region`, and imported only by that name: `Region<T>`, `region`, `regionWith`, `enter`, `enterWith` and `free`. A `Region<T>` is a handle, a 64-bit integer, to memory the program frees when it says so; `region(f)` allocates what `f` builds into a new region and keeps its answer as the root, `enter(r, f)` runs `f(root)` there again and answers its scalar, the `*With` forms pass one argument through, and `free(r)` gives all of it back. A handle used after `free`, entered twice or freed while entered stops the program. The bodies are the meaning; the allocator swap is the emitter's (`src/emit-region.ts`) and what may cross a region's edge is the checker's (`src/region-check.ts`), keyed on this file ([`docs/LANGUAGE.md`](
|
|
54
|
-
| [`secret.ts`](https://github.com/amritk/nish/blob/main/std/secret.ts) | The source behind the builtin module `nish:secret`, and imported only by that name: `Secret<T>`, `secret`, `expose`, `exposeWith` and `wipe`. The bodies are the meaning; what makes a `Secret` one is the checker's, keyed on this file ([`docs/LANGUAGE.md`](
|
|
55
|
-
| [`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`](
|
|
56
|
-
| [`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`](
|
|
53
|
+
| [`region.ts`](https://github.com/amritk/nish/blob/main/std/region.ts) | The source behind the builtin module `nish:region`, and imported only by that name: `Region<T>`, `region`, `regionWith`, `enter`, `enterWith` and `free`. A `Region<T>` is a handle, a 64-bit integer, to memory the program frees when it says so; `region(f)` allocates what `f` builds into a new region and keeps its answer as the root, `enter(r, f)` runs `f(root)` there again and answers its scalar, the `*With` forms pass one argument through, and `free(r)` gives all of it back. A handle used after `free`, entered twice or freed while entered stops the program. The bodies are the meaning; the allocator swap is the emitter's (`src/emit-region.ts`) and what may cross a region's edge is the checker's (`src/region-check.ts`), keyed on this file ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#regions-nishregion); [guide](../docs/guide/language/regions.md)) |
|
|
54
|
+
| [`secret.ts`](https://github.com/amritk/nish/blob/main/std/secret.ts) | The source behind the builtin module `nish:secret`, and imported only by that name: `Secret<T>`, `secret`, `expose`, `exposeWith` and `wipe`. The bodies are the meaning; what makes a `Secret` one is the checker's, keyed on this file ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#secrets-nishsecret)). `wipe`'s body is written by the emitter, one volatile `llvm.memset`, and like `collections.ts` the module writes no `.ll` of its own |
|
|
55
|
+
| [`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`](../docs/reference/language/declarations.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`](../docs/reference/language/declarations.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`](../docs/reference/language/declarations.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`](../docs/reference/language/declarations.md#channels-channelt)). Every body in the module is its meaning under Node, where a task runs at its `spawn` |
|
|
56
|
+
| [`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`](../docs/reference/language/declarations.md#shared-memory-between-processes-nishsyncshm-and-nishsyncring); [`docs/security/shm.md`](../docs/security/shm.md)) |
|
|
57
57
|
| [`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 |
|
|
58
58
|
| [`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. `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 |
|
|
59
59
|
| [`host/ring.ts`](https://github.com/amritk/nish/blob/main/std/host/ring.ts) | `nish/host/ring`: a single-producer, single-consumer ring of `i32` words in an `Int32Array` of module storage, shared by a wasm module and the page that drives it — word 0 the head, word 1 the tail, the slots after. `ringPush`, `ringShift`, `ringSize`, `ringFree`, `ringCapacity` and `ringClear`; the page's half is `nish/page`'s `ringOver`, over the same layout. It needs no atomics because the page and the module run on one thread and never at once. A zero-filled ring is empty, and a ring whose counts a buggy page wrote out of protocol is still never read out of bounds (`tests/link/std_host_ring`) |
|
|
@@ -116,7 +116,7 @@ is listed in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.m
|
|
|
116
116
|
| [`crypto/base64url.ts`](https://github.com/amritk/nish/blob/main/std/crypto/base64url.ts) | `base64urlEncode(data)` and `base64urlDecode(text)`, unpadded; `base64StdPadEncode(data)` and `base64StdPadDecode(text)`, the padded standard alphabet that SCRAM and PEM use, with the buffer forms `base64StdPadEncodeInto(data, start, length, out, at)` and `base64StdPadDecodedLength(text, start, length)` that allocate nothing, constant-time in both directions. These are not `nish/base64`, which encodes only, is not constant-time and is for pixels; the names differ because std modules share the program's one namespace. Decoding is strict, so every byte string has one spelling. `base64urlDecode` answers `null` for any `=`, a character outside the alphabet, a length of 1 mod 4 or nonzero unused low bits; `base64StdPadDecode` requires the padding, answering `null` unless the text is whole four-character groups with `=` only as the last one or two characters, every other character in the alphabet and the unused bits zero. Both refuse a text longer than 2^31 − 1 bytes, and `base64urlEncode` panics on such an array | RFC 4648 §4, §5, §10 (`tests/link/std_base64_padded`) |
|
|
117
117
|
| [`crypto/sha1.ts`](https://github.com/amritk/nish/blob/main/std/crypto/sha1.ts) | `sha1(data)`, a fresh 20-byte digest, `Sha1`, whose `digestInto(data, start, length, out, at)` hashes a slice into a caller's buffer and allocates nothing after it is built, and `SHA1_SIZE` and `SHA1_BLOCK`. **Not for security**: SHA-1 is broken for collisions, and it is here only because RFC 6455 §4.2.2's `Sec-WebSocket-Accept` is defined on it (`nish/net/websocket` is its importer). One-shot only, not streaming; it panics on an array longer than 2^31 − 1 bytes. It came after the #363 audit and has no record in `docs/security/` | FIPS 180-4 §6.1 |
|
|
118
118
|
| [`crypto/x25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x25519.ts) | `x25519(scalar, u)`, the shared secret as a `Secret<u8[]>`, and `x25519Base(scalar)`, the public key, each from a `Secret<u8[]>` scalar, on ten 25.5-bit limbs in `i64`. Either answers `null` unless its arguments are `X25519_SIZE` (32) bytes; the scalar is clamped on a copy, which is wiped | RFC 7748 §5.2, §6.1, Wycheproof `x25519_test` |
|
|
119
|
-
| [`crypto/ed25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ed25519.ts) | `ed25519PublicKey(seed)`, the 32-byte public key, `ed25519Sign(seed, msg)`, the 64-byte signature `R \|\| S`, each from a `Secret<u8[]>` seed of `ED25519_SEED_SIZE` (32) bytes or `null`, and `ed25519Verify(pub, msg, sig)`. Signing is deterministic and constant time; the seed's hash, the nonce and every intermediate the scalar reaches are wiped. Verify is cofactorless, refuses an S of L or more and a key that does not decode, and is variable time, since its inputs are public.
|
|
119
|
+
| [`crypto/ed25519.ts`](https://github.com/amritk/nish/blob/main/std/crypto/ed25519.ts) | `ed25519PublicKey(seed)`, the 32-byte public key, `ed25519Sign(seed, msg)`, the 64-byte signature `R \|\| S`, each from a `Secret<u8[]>` seed of `ED25519_SEED_SIZE` (32) bytes or `null`, and `ed25519Verify(pub, msg, sig)`. Signing is deterministic and constant time; the seed's hash, the nonce and every intermediate the scalar reaches are wiped. Verify is cofactorless, refuses an S of L or more and a key that does not decode, and is variable time, since its inputs are public. A message longer than 2^31 − 1 bytes makes sign answer `null` and verify answer `false`. It reuses `crypto/x25519.ts`'s field arithmetic | RFC 8032 §5.1, §7.1 |
|
|
120
120
|
| [`crypto/chacha20poly1305.ts`](https://github.com/amritk/nish/blob/main/std/crypto/chacha20poly1305.ts) | `chacha20Poly1305Seal(key, nonce, aad, plaintext)`, which answers the ciphertext followed by the 16-byte tag, and `chacha20Poly1305Open`, which checks the whole tag before it decrypts anything and answers `null` for a message that does not authenticate. Beneath them `chacha20Block`, `chacha20`, `chacha20QuarterRound`, `poly1305` and `poly1305KeyGen`, and `chacha20HeaderMask`, QUIC's 5-byte header-protection mask. Every input of the wrong length answers `null`. What a call derives from the key — the ChaCha20 state, the keystream, the Poly1305 key, `r` and accumulator, and on open the tag it compared — is wiped with `wipe`'s volatile stores before the call returns, the refusal path included. Natively, on x86-64 with AVX2 or on AArch64, the compiler sends the keystream of a message of 256 bytes or more to the runtime's kernel instead (`runtime/runtime-chacha20.c`), and `NISH_CHACHA20=soft` pins the Nish code | RFC 8439 §2, RFC 9001 §5.4.4, Wycheproof `chacha20_poly1305` (all 325 cases) |
|
|
121
121
|
| [`crypto/aes.ts`](https://github.com/amritk/nish/blob/main/std/crypto/aes.ts) | AES-128 and AES-256, bitsliced four blocks at a time with the Boyar–Peralta S-box circuit, so no table is read; natively, on a CPU with AES-NI and PCLMULQDQ or the ARMv8 AES and PMULL instructions, the compiler sends the key schedule, the block, GCTR and GHASH to the runtime's kernels instead (`runtime/runtime-aes.c`), and `NISH_AES=soft` pins the bitsliced code: `aesKey(key)` expands a 16- or 32-byte key into an `AesKey` (or `aesKeyInto(key, out)` into one the caller holds, allocating nothing that outlives the call), then `aesEncryptBlock`, `aesGcmSeal` / `aesGcmOpen` (tag last, checked in full before anything is decrypted; any non-empty IV) and `aesHeaderMask`. AES-192 is out of scope, and a wrong length answers `null`, as does an `AesKey` not made by `aesKey`; one whose H is zero opens nothing. An `AesKey` holds its round keys in `roundKeys` and H in `h`, two `u64` words (high, low); `aesKeyWipe(key)` zeroes both with `wipe`'s volatile stores, the kernels' powers of H after the schedule included, and is how a holder drops a key. The bitsliced schedule's, block's and GCTR's working copies, the tag's E(K, J0) block, the tag open compared and J0 itself are wiped the same way before they are released | FIPS 197, SP 800-38D, RFC 9001 §5.4.3, Wycheproof `aes_gcm` (all 316 cases; the 103 AES-192 ones check that the key is refused) |
|
|
122
122
|
| [`crypto/p256.ts`](https://github.com/amritk/nish/blob/main/std/crypto/p256.ts) | ECDSA over P-256 with RFC 6979's deterministic nonces: `p256PublicKey(priv)` (65-byte uncompressed SEC1) from a `Secret<u8[]>` private key, `p256Sign` / `p256Verify` over a digest and `p256SignSha256` / `p256VerifySha256` over a message, and `p256SignSha256Into(scratch, priv, msg, off, len, out, at)`, the same signature written into the caller's window in a `P256SignScratch` made once, keeping nothing in the arena; a signature is `r` and `s`, 32 big-endian bytes each, not DER (`crypto/x509.ts`'s `x509DerSignatureRS` converts one). A malformed key, a point off the curve or an `r` or `s` out of range answers `null` or `false`, never a panic. ECDSA is malleable, and `p256Verify` accepts a high `s`: when `(r, s)` verifies, so does `(r, n − s)` | RFC 6979 A.2.5, Wycheproof `ecdsa_secp256r1_sha256`, `_sha256_p1363`, `_sha512` and `_sha512_p1363` |
|
|
@@ -212,7 +212,7 @@ libdeflate: `bench/gzip/`; against Go, Rust, Java, Node, Bun and Python:
|
|
|
212
212
|
| Module | What it is | Reproduces |
|
|
213
213
|
| --- | --- | --- |
|
|
214
214
|
| [`compress/deflate.ts`](https://github.com/amritk/nish/blob/main/std/compress/deflate.ts) | `Deflater(level)` and `Inflater`, raw DEFLATE. Levels 0 (stored), 1 to 3 (greedy on a four-byte hash, `DEFLATE_FAST` = 1) and 4 to 9 (lazy, `DEFLATE_DEFAULT` = 6); each block is the smallest of dynamic, fixed and stored by its exact size. `compress(src, off, len, out, at)` answers the end or `DEFLATE_NO_ROOM` (-1); `deflateBound(n)` / `compressBound(n)` are the most any level writes. `decompress(src, off, len, out, at, limit)` answers the end or a `DEFLATE_ERR_*` code (truncated, block type, stored length, Huffman, symbol, distance, output limit, trailing) and never panics on a stream; `inflate` is the resumable step under it (`INFLATE_DONE`, `INFLATE_NEED_INPUT`, `INFLATE_NEED_OUTPUT`). `FixedDeflater` is the small-body encoder: one fixed-Huffman block, a 16 KB window, nothing kept between calls, two to four times faster than `DEFLATE_FAST` at about 1.35 times its size; `fixedDeflateBound(n)` is the most it writes | RFC 1951: every level against Node's zlib both ways (`tests/link/std_compress_node`), round trips of empty to 1 MB inputs, a 1,500-input fuzz, every prefix and random corruption refused (`tests/link/std_compress`) |
|
|
215
|
-
| [`compress/gzip.ts`](https://github.com/amritk/nish/blob/main/std/compress/gzip.ts) | `GzipCompressor(level)` / `GzipDecompressor` one-shot (the decompressor reads concatenated members, refuses trailing bytes, checks the header CRC, CRC-32 and length: `GZIP_ERR_HEADER`, `GZIP_ERR_CRC`, `GZIP_ERR_SIZE`), `gzipCompress` / `gzipDecompress`; `GzipFixedCompressor`, the same framing round `FixedDeflater` (`gzipFixedBound(n)`); `GzipWriter` (`write`, `flush`, `finish`, `bound`) and `GzipReader` (`feed` or `inputBuffer` / `commit`, `endInput`, `read` answering bytes, `GZIP_NEED_INPUT`, `GZIP_END` or an error, with a total `limit`) for bodies that arrive in pieces | RFC 1952: Node's gzip at every level, strategy and window, through both readers; the writer's output through Node's gunzip (`std_compress_node`, `std_compress`) |
|
|
215
|
+
| [`compress/gzip.ts`](https://github.com/amritk/nish/blob/main/std/compress/gzip.ts) | `GzipCompressor(level)` / `GzipDecompressor` one-shot (the decompressor reads concatenated members, refuses trailing bytes, checks the header CRC, CRC-32 and length: `GZIP_ERR_HEADER`, `GZIP_ERR_CRC`, `GZIP_ERR_SIZE`), `gzipCompress` / `gzipDecompress`; `GzipFixedCompressor`, the same framing round `FixedDeflater` (`gzipFixedBound(n)`); `GzipWriter` (`write`, `flush`, `finish`, `bound`, `start`; `GZIP_ERR_FINISHED` after `finish`) and `GzipReader` (`feed` or `inputBuffer` / `commit`, `endInput`, `read` answering bytes, `GZIP_NEED_INPUT`, `GZIP_END` or an error, with a total `limit`) for bodies that arrive in pieces | RFC 1952: Node's gzip at every level, strategy and window, through both readers; the writer's output through Node's gunzip (`std_compress_node`, `std_compress`) |
|
|
216
216
|
| [`compress/zlib.ts`](https://github.com/amritk/nish/blob/main/std/compress/zlib.ts) | `ZlibCompressor(level)` / `ZlibDecompressor`, `zlibCompress` / `zlibDecompress`: the two-byte header and Adler-32 trailer (`ZLIB_ERR_HEADER`, `ZLIB_ERR_ADLER`, `ZLIB_ERR_DICTIONARY` for `FDICT`) | RFC 1950, against Node's `deflateSync` / `inflateSync` (`std_compress_node`) |
|
|
217
217
|
| [`compress/checksum.ts`](https://github.com/amritk/nish/blob/main/std/compress/checksum.ts) | `Crc32` (slicing-by-8 tables built once; `update(crc, buf, off, len)`), `crc32` for a one-off, `adler32`, `adler32Update`. Natively the compiler sends `update`'s walk to `runtime/runtime-checksum.c` where the CPU has PCLMULQDQ or the ARMv8 CRC32 instructions, chosen once per process; `NISH_CRC32=soft` pins the tables | The check values of "123456789", pieces against the whole, Adler-32's deferred reduction against its definition (`std_compress`); every kernel against a bit-at-a-time reference (`tests/simd/crc32.c`); both paths on the same programs (`tests/link/std_compress_crc_paths`, `std_compress_crc_diff`) |
|
|
218
218
|
|
|
@@ -473,7 +473,7 @@ checklist in
|
|
|
473
473
|
three are what shape an API here more than any style preference — see the
|
|
474
474
|
header of `testing.ts` for what they did to that one, which has one
|
|
475
475
|
assertion per type. A new module can use
|
|
476
|
-
[generic functions and classes](
|
|
476
|
+
[generic functions and classes](../docs/reference/language/declarations.md#generic-functions);
|
|
477
477
|
`pair.ts` exports a generic type.
|
|
478
478
|
- **Ship it with a `tests/link/` case.** `tests/link/<name>/` is the only place a
|
|
479
479
|
multi-module program is exercised end to end, and it is also what puts the
|
package/std/array.ts
CHANGED
|
@@ -291,9 +291,17 @@ export const slice = <T>(xs: readonly T[], start: number, end: number): T[] => {
|
|
|
291
291
|
export const sliceFrom = <T>(xs: readonly T[], start: number): T[] => slice(xs, start, xs.length)
|
|
292
292
|
|
|
293
293
|
/**
|
|
294
|
-
* A copy of the whole of `xs`: what `xs.slice()` compiles to.
|
|
294
|
+
* A copy of the whole of `xs`: what `xs.slice()` compiles to. It copies
|
|
295
|
+
* directly rather than through `slice`, whose range check can panic and
|
|
296
|
+
* which a whole copy never needs, so it cannot panic but out of memory.
|
|
295
297
|
*
|
|
296
298
|
* @param xs the array copied; it is not changed.
|
|
297
299
|
* @returns a new array with the same elements.
|
|
298
300
|
*/
|
|
299
|
-
export const sliceAll = <T>(xs: readonly T[]): T[] =>
|
|
301
|
+
export const sliceAll = <T>(xs: readonly T[]): T[] => {
|
|
302
|
+
const out: T[] = []
|
|
303
|
+
for (let i: i32 = 0; i >= 0 && i < toI32(xs.length); i++) {
|
|
304
|
+
out.push(xs[i])
|
|
305
|
+
}
|
|
306
|
+
return out
|
|
307
|
+
}
|
package/std/bytes.ts
CHANGED
|
@@ -522,10 +522,31 @@ export const skipJsonPlain = (b: u8[], from: i32, to: i32): i32 => {
|
|
|
522
522
|
* @param count How many bytes to copy; zero copies nothing.
|
|
523
523
|
*/
|
|
524
524
|
export const copyBytes = (dst: u8[], at: i32, src: readonly u8[], from: i32, count: i32): void => {
|
|
525
|
-
if (
|
|
525
|
+
if (!tryCopyBytes(dst, at, src, from, count)) {
|
|
526
526
|
panic("copyBytes: the range lies outside an array")
|
|
527
527
|
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/**
|
|
531
|
+
* `copyBytes` that answers `false`, and writes nothing, where `copyBytes`
|
|
532
|
+
* panics: for a negative `count` or a range that does not lie inside its
|
|
533
|
+
* array. A caller a strict module reaches uses this one, so the out-of-range
|
|
534
|
+
* case is a value it handles rather than a panic site.
|
|
535
|
+
*
|
|
536
|
+
* @param dst The array written into; only `dst[at..at+count)` changes.
|
|
537
|
+
* @param at Where in `dst` the first copied byte goes.
|
|
538
|
+
* @param src The array copied from, which may be `dst` itself.
|
|
539
|
+
* @param from Where in `src` the copied bytes start.
|
|
540
|
+
* @param count How many bytes to copy; zero copies nothing.
|
|
541
|
+
* @returns `true` once the bytes are copied, or `false` when either range
|
|
542
|
+
* lies outside its array and nothing was written.
|
|
543
|
+
*/
|
|
544
|
+
export const tryCopyBytes = (dst: u8[], at: i32, src: readonly u8[], from: i32, count: i32): boolean => {
|
|
545
|
+
if (count < 0 || at < 0 || from < 0 || at > toI32(dst.length) - count || from > toI32(src.length) - count) {
|
|
546
|
+
return false
|
|
547
|
+
}
|
|
528
548
|
copyBytesWalk(dst, at, src, from, count)
|
|
549
|
+
return true
|
|
529
550
|
}
|
|
530
551
|
|
|
531
552
|
/**
|
|
@@ -562,11 +583,12 @@ const skipDigitsWalk = (b: u8[], from: i32, to: i32): i32 => {
|
|
|
562
583
|
}
|
|
563
584
|
|
|
564
585
|
/**
|
|
565
|
-
*
|
|
566
|
-
*
|
|
567
|
-
* second byte after `E0`, `ED`, `F0` and `F4`.
|
|
586
|
+
* Where the well-formed UTF-8 sequence whose lead byte is `b[i]` ends, when it
|
|
587
|
+
* ends at or before `to`, or `i` when there is none: RFC 3629's table, with the
|
|
588
|
+
* narrowed second byte after `E0`, `ED`, `F0` and `F4`. The end, not the
|
|
589
|
+
* length, so the caller steps to it without a sum.
|
|
568
590
|
*/
|
|
569
|
-
const
|
|
591
|
+
const bytesUtf8End = (b: u8[], i: i32, to: i32): i32 => {
|
|
570
592
|
const lead: i32 = toI32(b[i])
|
|
571
593
|
let low: i32 = BYTES_NON_ASCII
|
|
572
594
|
let high: i32 = BYTES_CONTINUATION_TOP
|
|
@@ -590,24 +612,29 @@ const bytesUtf8Length = (b: u8[], i: i32, to: i32): i32 => {
|
|
|
590
612
|
high = 0x8f
|
|
591
613
|
}
|
|
592
614
|
} else {
|
|
593
|
-
return
|
|
594
|
-
}
|
|
595
|
-
if (to - i < n) {
|
|
596
|
-
return 0
|
|
615
|
+
return i
|
|
597
616
|
}
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
617
|
+
// Each continuation byte is read only once it is known to lie before both
|
|
618
|
+
// `to` and the array's end; a sequence cut short by either is not one.
|
|
619
|
+
if (i < 0 || i >= toI32(b.length)) {
|
|
620
|
+
return i
|
|
601
621
|
}
|
|
602
|
-
let
|
|
622
|
+
let j: i32 = i + 1
|
|
623
|
+
let k: i32 = 1
|
|
603
624
|
while (k < n) {
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
return 0
|
|
625
|
+
if (j >= to || j >= toI32(b.length)) {
|
|
626
|
+
return i
|
|
607
627
|
}
|
|
628
|
+
const c: i32 = toI32(b[j])
|
|
629
|
+
const lowest: i32 = k === 1 ? low : BYTES_NON_ASCII
|
|
630
|
+
const highest: i32 = k === 1 ? high : BYTES_CONTINUATION_TOP
|
|
631
|
+
if (c < lowest || c > highest) {
|
|
632
|
+
return i
|
|
633
|
+
}
|
|
634
|
+
j += 1
|
|
608
635
|
k += 1
|
|
609
636
|
}
|
|
610
|
-
return
|
|
637
|
+
return j
|
|
611
638
|
}
|
|
612
639
|
|
|
613
640
|
/** `skipJsonText`'s walk, once its range is clamped. */
|
|
@@ -616,11 +643,11 @@ const skipJsonTextWalk = (b: u8[], from: i32, to: i32): i32 => {
|
|
|
616
643
|
while (i >= 0 && i < to && i < toI32(b.length)) {
|
|
617
644
|
const c: i32 = toI32(b[i])
|
|
618
645
|
if (c >= BYTES_NON_ASCII) {
|
|
619
|
-
const
|
|
620
|
-
if (
|
|
646
|
+
const end: i32 = bytesUtf8End(b, i, to)
|
|
647
|
+
if (end === i) {
|
|
621
648
|
return i
|
|
622
649
|
}
|
|
623
|
-
i
|
|
650
|
+
i = end
|
|
624
651
|
continue
|
|
625
652
|
}
|
|
626
653
|
if (c < BYTES_SPACE || c === BYTES_QUOTE || c === BYTES_BACKSLASH) {
|
|
@@ -644,19 +671,205 @@ const skipJsonPlainWalk = (b: u8[], from: i32, to: i32): i32 => {
|
|
|
644
671
|
return i
|
|
645
672
|
}
|
|
646
673
|
|
|
647
|
-
/**
|
|
674
|
+
/**
|
|
675
|
+
* `copyBytes`'s walk, once its ranges are checked: forward, or backward when
|
|
676
|
+
* `dst` is `src` and the bytes move up. Each index is tested against its array
|
|
677
|
+
* as the walk goes, which the checked ranges always pass; natively the walk is
|
|
678
|
+
* one `llvm.memmove` instead.
|
|
679
|
+
*/
|
|
648
680
|
const copyBytesWalk = (dst: u8[], at: i32, src: readonly u8[], from: i32, count: i32): void => {
|
|
681
|
+
const dstLength: i32 = toI32(dst.length)
|
|
682
|
+
const srcLength: i32 = toI32(src.length)
|
|
649
683
|
if (at <= from) {
|
|
684
|
+
let d: i32 = at
|
|
685
|
+
let s: i32 = from
|
|
650
686
|
let k: i32 = 0
|
|
651
|
-
while (k < count) {
|
|
652
|
-
dst[
|
|
687
|
+
while (k < count && d >= 0 && d < dstLength && s >= 0 && s < srcLength) {
|
|
688
|
+
dst[d] = src[s]
|
|
689
|
+
d += 1
|
|
690
|
+
s += 1
|
|
653
691
|
k += 1
|
|
654
692
|
}
|
|
655
693
|
return
|
|
656
694
|
}
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
695
|
+
// The last byte of each range, in i64 so the sum cannot overflow; the
|
|
696
|
+
// checked ranges make both fit an i32.
|
|
697
|
+
let d: i32 = toI32(toI64(at) + toI64(count) - toI64(1))
|
|
698
|
+
let s: i32 = toI32(toI64(from) + toI64(count) - toI64(1))
|
|
699
|
+
let k: i32 = count
|
|
700
|
+
while (k > 0 && d >= 0 && d < dstLength && s >= 0 && s < srcLength) {
|
|
701
|
+
dst[d] = src[s]
|
|
702
|
+
d -= 1
|
|
703
|
+
s -= 1
|
|
660
704
|
k -= 1
|
|
661
705
|
}
|
|
662
706
|
}
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* `getU32LE` that answers an offset whose four bytes do not all lie in `b`
|
|
710
|
+
* as `Err`, where `getU32LE` panics `index`: the form a strict module reads a
|
|
711
|
+
* record it did not size itself with.
|
|
712
|
+
*
|
|
713
|
+
* @param b The bytes the number is read from; they are not changed.
|
|
714
|
+
* @param off Where in `b` its first byte is; it covers `b[off]` to
|
|
715
|
+
* `b[off + 3]`.
|
|
716
|
+
* @returns The number read, or `Err` naming the offset and the array's length
|
|
717
|
+
* when a byte of the four lies outside `b`.
|
|
718
|
+
*/
|
|
719
|
+
export const tryGetU32LE = (b: u8[], off: i32): Result<u32, string> => {
|
|
720
|
+
if (off >= 0 && off < 2147483644 && off + 4 <= toI32(b.length)) {
|
|
721
|
+
// The last byte is read first: once it is in range the checker proves
|
|
722
|
+
// the three below it, where a first read of `b[off]` leaves them unproven.
|
|
723
|
+
const b3: u32 = toU32(b[off + 3])
|
|
724
|
+
const b2: u32 = toU32(b[off + 2])
|
|
725
|
+
const b1: u32 = toU32(b[off + 1])
|
|
726
|
+
const b0: u32 = toU32(b[off])
|
|
727
|
+
return Ok((b0 | (b1 << 8) | (b2 << 16)) + b3 * toU32(0x1000000))
|
|
728
|
+
}
|
|
729
|
+
return Err(bytesRangeError(off, 4, b))
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* `getU64LE` that answers an offset whose eight bytes do not all lie in `b`
|
|
734
|
+
* as `Err`, where `getU64LE` panics.
|
|
735
|
+
*
|
|
736
|
+
* @param b The bytes the number is read from; they are not changed.
|
|
737
|
+
* @param off Where in `b` its first byte is; it covers `b[off]` to
|
|
738
|
+
* `b[off + 7]`.
|
|
739
|
+
* @returns The number read, or `Err` naming the offset and the array's length
|
|
740
|
+
* when a byte of the eight lies outside `b`.
|
|
741
|
+
*/
|
|
742
|
+
export const tryGetU64LE = (b: u8[], off: i32): Result<u64, string> => {
|
|
743
|
+
if (off >= 0 && off < 2147483640 && off + 8 <= toI32(b.length)) {
|
|
744
|
+
// The last byte first, as in `tryGetU32LE`.
|
|
745
|
+
const b7: u64 = toU64(b[off + 7])
|
|
746
|
+
const b6: u64 = toU64(b[off + 6])
|
|
747
|
+
const b5: u64 = toU64(b[off + 5])
|
|
748
|
+
const b4: u64 = toU64(b[off + 4])
|
|
749
|
+
const b3: u64 = toU64(b[off + 3])
|
|
750
|
+
const b2: u64 = toU64(b[off + 2])
|
|
751
|
+
const b1: u64 = toU64(b[off + 1])
|
|
752
|
+
const b0: u64 = toU64(b[off])
|
|
753
|
+
return Ok(
|
|
754
|
+
b0 |
|
|
755
|
+
(b1 << toU64(8)) |
|
|
756
|
+
((b2 << toU64(16)) | (b3 << toU64(24))) |
|
|
757
|
+
((b4 << toU64(32)) | (b5 << toU64(40)) | ((b6 << toU64(48)) | (b7 << toU64(56))))
|
|
758
|
+
)
|
|
759
|
+
}
|
|
760
|
+
return Err(bytesRangeError(off, 8, b))
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* `getI32LE` that answers an offset whose four bytes do not all lie in `b`
|
|
765
|
+
* as `Err`, where `getI32LE` panics.
|
|
766
|
+
*
|
|
767
|
+
* @param b The bytes the number is read from; they are not changed.
|
|
768
|
+
* @param off Where in `b` its first byte is; it covers `b[off]` to
|
|
769
|
+
* `b[off + 3]`.
|
|
770
|
+
* @returns The number read, from -2^31 to 2^31 - 1, or `Err` naming the
|
|
771
|
+
* offset and the array's length when a byte of the four lies outside `b`.
|
|
772
|
+
*/
|
|
773
|
+
export const tryGetI32LE = (b: u8[], off: i32): Result<i32, string> => {
|
|
774
|
+
const v: Result<u32, string> = tryGetU32LE(b, off)
|
|
775
|
+
if (v.isErr()) {
|
|
776
|
+
return Err(v.error)
|
|
777
|
+
}
|
|
778
|
+
return Ok(toI32(v.value))
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
/**
|
|
782
|
+
* `getI64LE` that answers an offset whose eight bytes do not all lie in `b`
|
|
783
|
+
* as `Err`, where `getI64LE` panics.
|
|
784
|
+
*
|
|
785
|
+
* @param b The bytes the number is read from; they are not changed.
|
|
786
|
+
* @param off Where in `b` its first byte is; it covers `b[off]` to
|
|
787
|
+
* `b[off + 7]`.
|
|
788
|
+
* @returns The number read, from -2^63 to 2^63 - 1, or `Err` naming the
|
|
789
|
+
* offset and the array's length when a byte of the eight lies outside `b`.
|
|
790
|
+
*/
|
|
791
|
+
export const tryGetI64LE = (b: u8[], off: i32): Result<i64, string> => {
|
|
792
|
+
const v: Result<u64, string> = tryGetU64LE(b, off)
|
|
793
|
+
if (v.isErr()) {
|
|
794
|
+
return Err(v.error)
|
|
795
|
+
}
|
|
796
|
+
return Ok(toI64(v.value))
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* `setU32LE` that answers `false`, and writes nothing, where `setU32LE`
|
|
801
|
+
* panics: for an offset whose four bytes do not all lie in `b`.
|
|
802
|
+
*
|
|
803
|
+
* @param b The bytes written into; only the four at `off` change.
|
|
804
|
+
* @param off Where in `b` the first byte goes; it covers `b[off]` to
|
|
805
|
+
* `b[off + 3]`.
|
|
806
|
+
* @param v The number to store.
|
|
807
|
+
* @returns `true` once the bytes are written, or `false` when a byte of the
|
|
808
|
+
* four lies outside `b` and nothing was written.
|
|
809
|
+
*/
|
|
810
|
+
export const trySetU32LE = (b: u8[], off: i32, v: u32): boolean => {
|
|
811
|
+
if (off >= 0 && off < 2147483644 && off + 4 <= toI32(b.length)) {
|
|
812
|
+
b[off] = toU8(v & 255)
|
|
813
|
+
b[off + 1] = toU8((v >> 8) & 255)
|
|
814
|
+
b[off + 2] = toU8((v >> 16) & 255)
|
|
815
|
+
b[off + 3] = toU8((v >> 24) & 255)
|
|
816
|
+
return true
|
|
817
|
+
}
|
|
818
|
+
return false
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* `setU64LE` that answers `false`, and writes nothing, where `setU64LE`
|
|
823
|
+
* panics: for an offset whose eight bytes do not all lie in `b`.
|
|
824
|
+
*
|
|
825
|
+
* @param b The bytes written into; only the eight at `off` change.
|
|
826
|
+
* @param off Where in `b` the first byte goes; it covers `b[off]` to
|
|
827
|
+
* `b[off + 7]`.
|
|
828
|
+
* @param v The number to store.
|
|
829
|
+
* @returns `true` once the bytes are written, or `false` when a byte of the
|
|
830
|
+
* eight lies outside `b` and nothing was written.
|
|
831
|
+
*/
|
|
832
|
+
export const trySetU64LE = (b: u8[], off: i32, v: u64): boolean => {
|
|
833
|
+
if (off >= 0 && off < 2147483640 && off + 8 <= toI32(b.length)) {
|
|
834
|
+
b[off] = toU8(v & toU64(255))
|
|
835
|
+
b[off + 1] = toU8((v >> toU64(8)) & toU64(255))
|
|
836
|
+
b[off + 2] = toU8((v >> toU64(16)) & toU64(255))
|
|
837
|
+
b[off + 3] = toU8((v >> toU64(24)) & toU64(255))
|
|
838
|
+
b[off + 4] = toU8((v >> toU64(32)) & toU64(255))
|
|
839
|
+
b[off + 5] = toU8((v >> toU64(40)) & toU64(255))
|
|
840
|
+
b[off + 6] = toU8((v >> toU64(48)) & toU64(255))
|
|
841
|
+
b[off + 7] = toU8((v >> toU64(56)) & toU64(255))
|
|
842
|
+
return true
|
|
843
|
+
}
|
|
844
|
+
return false
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
/**
|
|
848
|
+
* `setI32LE` that answers `false`, and writes nothing, where `setI32LE`
|
|
849
|
+
* panics.
|
|
850
|
+
*
|
|
851
|
+
* @param b The bytes written into; only the four at `off` change.
|
|
852
|
+
* @param off Where in `b` the first byte goes; it covers `b[off]` to
|
|
853
|
+
* `b[off + 3]`.
|
|
854
|
+
* @param v The number to store, as its two's-complement bits.
|
|
855
|
+
* @returns `true` once the bytes are written, or `false` when a byte of the
|
|
856
|
+
* four lies outside `b` and nothing was written.
|
|
857
|
+
*/
|
|
858
|
+
export const trySetI32LE = (b: u8[], off: i32, v: i32): boolean => trySetU32LE(b, off, toU32(v))
|
|
859
|
+
|
|
860
|
+
/**
|
|
861
|
+
* `setI64LE` that answers `false`, and writes nothing, where `setI64LE`
|
|
862
|
+
* panics.
|
|
863
|
+
*
|
|
864
|
+
* @param b The bytes written into; only the eight at `off` change.
|
|
865
|
+
* @param off Where in `b` the first byte goes; it covers `b[off]` to
|
|
866
|
+
* `b[off + 7]`.
|
|
867
|
+
* @param v The number to store, as its two's-complement bits.
|
|
868
|
+
* @returns `true` once the bytes are written, or `false` when a byte of the
|
|
869
|
+
* eight lies outside `b` and nothing was written.
|
|
870
|
+
*/
|
|
871
|
+
export const trySetI64LE = (b: u8[], off: i32, v: i64): boolean => trySetU64LE(b, off, toU64(v))
|
|
872
|
+
|
|
873
|
+
/** The `Err` text of a checked read whose `width` bytes at `off` do not all lie in `b`. */
|
|
874
|
+
const bytesRangeError = (off: i32, width: i32, b: u8[]): string =>
|
|
875
|
+
`bytes ${off} to ${toI64(off) + toI64(width) - toI64(1)} lie outside an array of ${b.length}`
|