@amritk/nish-aarch64-linux 0.49.0 → 0.50.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/INSTALL.md +1 -1
- package/bin/nish +0 -0
- package/docs/AI.md +233 -159
- package/package.json +1 -1
- package/runtime/gfx/nish-gfx.h +373 -61
- package/runtime/nish.d.ts +12 -9
- package/std/README.md +8 -5
- package/std/base64.ts +74 -1
- package/std/bytes.ts +201 -93
- package/std/compress/deflate.ts +20 -15
- package/std/crypto/base64url.ts +93 -66
- package/std/crypto/bcrypt.ts +25 -21
- package/std/crypto/hmac.ts +1 -1
- package/std/crypto/jwt.ts +32 -19
- package/std/crypto/p256.ts +9 -12
- package/std/crypto/pki-roots.ts +7 -4
- package/std/crypto/pki.ts +43 -55
- package/std/crypto/rsa-sign.ts +1632 -0
- package/std/crypto/rsa.ts +26 -4
- package/std/crypto/sha256.ts +135 -68
- package/std/crypto/x25519.ts +12 -11
- package/std/crypto/x509.ts +164 -40
- package/std/gpu/sys.ts +490 -0
- package/std/json-equal.ts +33 -18
- package/std/json-format.ts +39 -8
- package/std/json-number.ts +15 -3
- package/std/json-tokenizer.ts +4 -3
- package/std/json-typed.ts +29 -12
- package/std/json-value.ts +222 -104
- package/std/json.ts +81 -46
- package/std/net/dns-config.ts +18 -5
- package/std/net/dns-message.ts +60 -27
- package/std/net/dns-resolver.ts +35 -16
- package/std/net/dns.ts +3 -2
- package/std/net/fetch.ts +120 -38
- package/std/net/handler.ts +178 -66
- package/std/net/hpack.ts +192 -98
- package/std/net/http-compress.ts +83 -30
- package/std/net/http-fields.ts +327 -31
- package/std/net/http-server.ts +317 -20
- package/std/net/http1-client-codec.ts +137 -40
- package/std/net/http1-codec.ts +391 -202
- package/std/net/http1-server.ts +220 -38
- package/std/net/http2-cleartext.ts +10 -4
- package/std/net/http2-frame.ts +2 -2
- package/std/net/http2-tls.ts +3 -3
- package/std/net/http2.ts +69 -15
- package/std/net/http3-frame.ts +11 -14
- package/std/net/http3-server.ts +12 -15
- package/std/net/http3.ts +41 -29
- package/std/net/multipart.ts +592 -0
- package/std/net/outbound.ts +24 -8
- package/std/net/postgres-async.ts +92 -54
- package/std/net/postgres-carrier.ts +28 -4
- package/std/net/postgres.ts +166 -65
- package/std/net/prefork.ts +86 -5
- package/std/net/protobuf.ts +6 -2
- package/std/net/qpack.ts +66 -25
- package/std/net/quic-conn-ack.ts +27 -7
- package/std/net/quic-conn-cid.ts +13 -7
- package/std/net/quic-datagram.ts +6 -5
- package/std/net/quic-frame.ts +67 -23
- package/std/net/quic-listener.ts +19 -12
- package/std/net/quic-recovery.ts +11 -9
- package/std/net/quic-stream.ts +7 -5
- package/std/net/quic.ts +36 -31
- package/std/net/router.ts +136 -24
- package/std/net/serve.ts +59 -5
- package/std/net/static.ts +81 -33
- package/std/net/tls/record.ts +26 -13
- package/std/net/tls/ticket.ts +6 -5
- package/std/net/tls-tcp.ts +69 -30
- package/std/net/tls.ts +152 -38
- package/std/net/upstream.ts +65 -19
- package/std/net/url.ts +97 -78
- package/std/net/websocket.ts +33 -15
- package/std/net/webtransport.ts +28 -12
- package/std/regex.ts +600 -388
- package/std/sqlite.ts +37 -19
- package/std/sync/ring.ts +232 -115
- package/std/sync/shm.ts +11 -4
- package/std/temporal.ts +232 -133
- package/std/term-io.ts +12 -6
- package/std/term-pixels.ts +158 -22
- package/std/term-rate.ts +8 -3
- package/std/term.ts +4 -4
- package/std/text.ts +33 -11
- package/std/threads.ts +52 -8
- package/std/yaml-json.ts +238 -106
- package/std/yaml-lines.ts +47 -27
- package/std/yaml-write.ts +58 -24
- package/std/yaml.ts +808 -395
package/std/README.md
CHANGED
|
@@ -34,7 +34,7 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
34
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
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
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
|
-
| [`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)) |
|
|
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, and `base64EncodeIfFits(src, off, len, dst, at)` answers -1 for it instead. 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_if_fits`, `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; `tryPlainDate`, `tryPlainDateFrom` and `PlainDate.tryAdd` answer the `RangeError`'s text as a `Result` `Err` (`tests/link/std_temporal_result`). 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
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, its wrapping add taken in `f64` on the state read as an unsigned count and its multiplies through `Math.imul`, 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)) |
|
|
@@ -45,7 +45,7 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
|
|
|
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)) |
|
|
47
47
|
| [`term-rate.ts`](https://github.com/amritk/nish/blob/main/std/term-rate.ts) | how fast the link to the terminal is, and the frame rate and detail a program keeps to under it. A `RateController` is told each frame sent (`frameSent(bytes, costNs, nowMs)`) and each acknowledgement — the answer to the DSR 5 query sent after a frame — (`ackReceived(nowMs)`), keeps running averages of the round trip, the bytes a second delivered and the cost of a frame, and answers `mayDraw(nowMs)` and a `RateDecision`: the frame interval, a resolution divisor, a backend cap and a palette, stepped down a tier when frames back up and up again when the link has room; `stats()` is the `TermStats` a program can show. Pure: no capability and no clock (`tests/link/std_term_rate`, `std_term_rate_f64`; [guide](../docs/guide/using-nish/terminal.md#how-the-frame-rate-adapts)) |
|
|
48
|
-
| [`term-pixels.ts`](https://github.com/amritk/nish/blob/main/std/term-pixels.ts) | a `Framebuffer` of `0xRRGGBB` pixels and the encoders that draw it with the backend the terminal has: `kittyFrame` (kitty graphics, one image id retransmitted each frame), `sixelFrame` (a fixed palette, optionally dithered), `drawHalfBlocks` onto a `Canvas` and `drawAscii` onto a `Screen`, each into the `PixelRect` `fitFramebuffer` letterboxes in the cells; `scaleFramebuffer` shrinks a frame by the controller's divisor. `PixelBytes` keeps the encoders' output and working arrays, so frame after frame allocates nothing. Pure (`tests/link/std_term_pixels`, `std_term_pixels_f64`; [guide](../docs/guide/using-nish/standard-library.md#nishterm-pixels)) |
|
|
48
|
+
| [`term-pixels.ts`](https://github.com/amritk/nish/blob/main/std/term-pixels.ts) | a `Framebuffer` of `0xRRGGBB` pixels, made and resized by `tryFramebuffer` and `tryResize` with an `Err` for a size the constructor and `resize` panic on, and the encoders that draw it with the backend the terminal has: `kittyFrame` (kitty graphics, one image id retransmitted each frame), `sixelFrame` (a fixed palette, optionally dithered), `drawHalfBlocks` onto a `Canvas` and `drawAscii` onto a `Screen`, each into the `PixelRect` `fitFramebuffer` letterboxes in the cells; `scaleFramebuffer` shrinks a frame by the controller's divisor. `PixelBytes` keeps the encoders' output and working arrays, so frame after frame allocates nothing. Pure (`tests/link/std_term_pixels`, `std_term_pixels_f64`, `std_term_pixels_try`; [guide](../docs/guide/using-nish/standard-library.md#nishterm-pixels)) |
|
|
49
49
|
| [`term-io.ts`](https://github.com/amritk/nish/blob/main/std/term-io.ts) | the term module that does the I/O. `runTerminal(options, state, update, render)` is a whole program loop: it opens the terminal, steps `update` at a fixed rate, calls `render` with a `Frame` (the `Screen`, the `Framebuffer`, the step `alpha`, `TermCaps` and `TermStats`) whenever the controller lets a frame go, and closes when `update` answers false or the user presses Ctrl-C. `openTerminal(options)` answers a `Terminal` for a program's own loop (`readEvents`, `present`, `stats`, `close`). Opening refuses a pipe, enters raw mode and the alternate screen, probes the terminal and turns on the kitty keyboard, mouse, paste and focus reports the options ask for, with the runtime's restore string set before each so a panic or signal leaves the terminal as it was; `present` sends the frame in the best backend the controller allows as one write and acknowledges it with DSR 5. Reaches `tty` (`tests/term-io/relay.mjs` drives it in a pseudo-terminal from `tests/run.js`'s `term-io` section; `tests/link/std_term_io_deny`; [guide](../docs/guide/using-nish/terminal.md)) |
|
|
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` |
|
|
@@ -91,7 +91,8 @@ closed), so `length` is right in both number modes, and the one-shot functions
|
|
|
91
91
|
below refuse a longer input as each row says.
|
|
92
92
|
|
|
93
93
|
**Private keys are `Secret`s.** `crypto/p256.ts`, `crypto/x25519.ts`,
|
|
94
|
-
`crypto/ed25519.ts`, `crypto/
|
|
94
|
+
`crypto/ed25519.ts`, `crypto/rsa-sign.ts`, `crypto/x509.ts` and
|
|
95
|
+
`crypto/x509-random.ts` take and give
|
|
95
96
|
a private key as a `Secret<u8[]>` from
|
|
96
97
|
`nish:secret`, compute on it only inside `expose`, and wipe every intermediate
|
|
97
98
|
the key reaches before they return, with a store the optimiser may not remove
|
|
@@ -121,7 +122,8 @@ is listed in [`SECURITY.md`](https://github.com/amritk/nish/blob/main/SECURITY.m
|
|
|
121
122
|
| [`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
123
|
| [`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` |
|
|
123
124
|
| [`crypto/p384.ts`](https://github.com/amritk/nish/blob/main/std/crypto/p384.ts) | ECDSA verification over P-384: `p384Verify(pub, digest, sig)` over a digest from any hash (one longer than 48 bytes is truncated to its leftmost 384 bits) and `p384VerifySha384(pub, msg, sig)` over a message; the key is 97-byte uncompressed SEC1 and the signature `r` and `s`, 48 big-endian bytes each, not DER. It only verifies, so it holds no `Secret`. A malformed key, a point off the curve, an `r` or `s` out of range and a sum at the identity answer `false`, never a panic. ECDSA is malleable, and `p384Verify` accepts a high `s` | RFC 6979 A.2.6, Wycheproof `ecdsa_secp384r1_sha384`, `_sha384_p1363`, `_sha256`, `_sha512` and `_sha512_p1363` |
|
|
124
|
-
| [`crypto/rsa.ts`](https://github.com/amritk/nish/blob/main/std/crypto/rsa.ts) | RSA signature verification under a public key
|
|
125
|
+
| [`crypto/rsa.ts`](https://github.com/amritk/nish/blob/main/std/crypto/rsa.ts) | RSA signature verification under a public key (`crypto/rsa-sign.ts` signs): `rsaParsePublicKey(der)` reads a PKCS#1 `RSAPublicKey` (strict DER, a 1,024-to-8,192-bit modulus, an odd exponent from 3 below 2^32) into an `RsaPublicKey`, and `rsaVerifyPkcs1v15(key, hash, msg, sig)` and `rsaVerifyPss(key, hash, saltLen, msg, sig)` verify RSASSA-PKCS1-v1_5 and RSASSA-PSS (MGF1 with the same hash) over a message, the hash one of `RSA_HASH_SHA256`, `RSA_HASH_SHA384` and `RSA_HASH_SHA512`. A malformed key answers `null` and a bad signature `false`, never a panic. Public inputs only, so nothing is a `Secret` and the arithmetic is not constant-time (RSA-2) | RFC 8017 §8.2.2, §9.1.2, §9.2; Wycheproof `rsa_signature_*` and `rsa_pss_*` |
|
|
126
|
+
| [`crypto/rsa-sign.ts`](https://github.com/amritk/nish/blob/main/std/crypto/rsa-sign.ts) | RSA-PSS signing with SHA-256, for a TLS 1.3 server's CertificateVerify (`rsa_pss_rsae_sha256`): `rsaParsePrivateKey(der, start, end)` reads a PKCS#1 `RSAPrivateKey` (strict DER, two-prime, a 2,048-to-4,096-bit modulus of whole bytes, `e` odd from 3 below 2^32) into a `Secret<u8[]>` and refuses a key whose private exponent or CRT values do not sign under its modulus; `crypto/x509.ts`'s `x509ParseRsaPrivateKey` reads one from PKCS#1 or PKCS#8 PEM. `rsaSignPssSha256(priv, msg)` signs with MGF1-SHA-256 and a 32-byte salt derived from the key and the message, so the same message always gets the same signature; `rsaSignPssSha256Into(scratch, priv, msg, off, len, out, at)` writes it into the caller's window in an `RsaSignScratch` made once; `rsaSignPssSha256Salted` takes the salt; `rsaSignRaw` is the bare private operation. Each signature is checked under the public exponent before it is returned. A bad key or a failed check answers `null`, never a panic. The private operation is two fixed-window half exponentiations joined by Garner's formula (CRT), with the key's CRT values checked at load and no blinding, checked for secret-dependent branches and addresses by `ct_asm` (RSA-S1, RSA-S2) | RFC 8017 §8.1.1, §9.1.1, §A.1.2; the keys and ciphertexts of Wycheproof `rsa_pkcs1_2048`, `_3072` and `_4096` for the raw operation; PSS known answers each verified by OpenSSL |
|
|
125
127
|
| [`crypto/x509.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x509.ts) | DER, PEM and X.509 over P-256: `pemToDer` / `derToPem` (RFC 7468, padded standard base64, strict labels), `x509ParseP256PrivateKey` (SEC1 or PKCS#8, answering a `Secret<u8[]>`), `x509ParseCertificate` / `x509ParseChain` into an `X509Certificate`, `x509VerifySignature` (ecdsa-with-SHA256 under an issuer's key), `x509DerSignatureRS` (a DER ECDSA-Sig-Value as the `r || s` `crypto/p256.ts` takes), `x509MintSelfSigned`, the 1-to-14-day self-signed P-256 certificate WebTransport's `serverCertificateHashes` accepts, and `x509CertificateHash`, its SHA-256. DER is read strictly — non-minimal lengths and integers, indefinite lengths and trailing bytes answer `null`. `x509ParseCertificate` names the signature algorithm (`X509_SIG_*`: ECDSA with SHA-256 or SHA-384, RSA PKCS#1 v1.5 with SHA-1 to SHA-512, RSASSA-PSS with its hash and salt, Ed25519) and key type (`X509_KEY_*`: P-256, P-384, RSA, Ed25519), each in its one strict spelling, and decodes subjectAltName, basicConstraints, keyUsage, extKeyUsage, nameConstraints and the subject and authority key identifiers; a repeated or malformed extension refuses the certificate, and an unknown critical one sets `unknownCritical`. `x509NameEqual` and `x509NameIsPrefix` compare Names byte for byte, not by RFC 5280 §7.1. It parses and does not validate: there is no path validation, nothing applies the extensions to a chain, and no clock is consulted; `x509VerifySignature` checks only ecdsa-with-SHA256 under a P-256 key, and `x509DerSignatureRSWidth` reads a P-384 signature. `pemToDer` refuses a file in which any block, of any label, is malformed. `x509MintSelfSigned` refuses a common name that is not UTF-8 or holds a NUL, and its key and serial must come from `crypto.getRandomValues`, which the module cannot call itself without refusing wasm32: `crypto/x509-random.ts` draws them (X509-6) | X.690, RFC 5280, RFC 7468, RFC 5915, RFC 5208 / 5958, RFC 4055, RFC 8410; certificates checked against OpenSSL |
|
|
126
128
|
| [`crypto/x509-random.ts`](https://github.com/amritk/nish/blob/main/std/crypto/x509-random.ts) | **Native only**: the key and serial `crypto/x509.ts`'s mint needs, drawn from `crypto.getRandomValues`, so a program that imports it does not compile for wasm32 and `crypto/x509.ts` imports nothing from it. `x509DrawP256Key()`, a `Secret<u8[]>` P-256 private key drawn again until it is a scalar in [1, n) (each refused draw wiped); `x509DrawSerial()`, twenty octets whose first is 0x40 to 0x7f, so a positive, non-zero, full-length serial; and `x509MintSelfSignedDrawn(priv, commonName, notBeforeMs, days)`, `x509MintSelfSigned` with a drawn serial | — |
|
|
127
129
|
| [`crypto/pki-roots.ts`](https://github.com/amritk/nish/blob/main/std/crypto/pki-roots.ts) | **Native only**: the trust anchors, read where OpenSSL and Go look. `pkiLoadSystemRoots()` gives a `PkiRoots` — `roots` (parsed `X509Certificate`s, no two with the same DER), `sources` (the files read) and `skipped` — from the file `SSL_CERT_FILE` and the `:`-separated directories `SSL_CERT_DIR` name when either is set and not empty, with no fallback, and otherwise from the first of `pkiSystemBundles()` (Go's six paths, in Go's order) that exists and `/etc/ssl/certs` (`PKI_SYSTEM_DIR`). `pkiLoadRoots(file, dirs, bundles)` and `pkiLoadRootsFor(certFile, certDir, dirs, bundles)` take the paths and the variables' values given. A directory gives its `*.pem`, `*.crt` and `xxxxxxxx.N` entries; only a regular file is read; a PEM block that is not a certificate `x509ParseCertificate` accepts, a file over `PKI_ROOTS_MAX_FILE_BYTES` and an entry past `PKI_ROOTS_MAX_FILES` or `PKI_ROOTS_MAX_ROOTS` count in `skipped` and are passed over. It does not read the macOS Keychain ([PKI-R7](../docs/security/crypto-pki.md#pki-r7-low-the-macos-keychain-is-not-read)) | — |
|
|
@@ -260,7 +262,8 @@ reads one, and it still takes its randomness as an argument.
|
|
|
260
262
|
| [`net/websocket.ts`](https://github.com/amritk/nish/blob/main/std/net/websocket.ts) | `WsDecoder(expectMasked, maxMessage)`, the same `feed` and `next()` over WebSocket frames: `WS_MESSAGE` (fragments joined, text checked as UTF-8 fragment by fragment), `WS_PING`, `WS_PONG`, and the final `WS_CLOSE` and `WS_ERROR`, whose `closeCode` is the 1002, 1007 or 1009 to close with. `websocketFrame` encodes a frame with the mask key the caller supplies (`websocketWriteFrame` into a caller's buffer, `websocketFrameSize` its length), `reset()` readies a decoder for the next connection, `websocketClosePayload` a close frame's code and reason, and `websocketIsUtf8` checks a window. The handshake is `websocketRequestKey(parser)` over an `Http1Parser`'s head, `websocketAcceptKey`, `websocketKeyIsValid`, `websocketOfferedProtocols` and `websocketUpgradeResponse`, the 101; `WsAcceptKey`, `websocketRequestKeyField` and `websocketWriteUpgradeResponse`, the same accept written into storage a server keeps, so a connection's later handshakes allocate nothing. The client's side is `websocketClientKey(nonce)` (a 16-byte nonce the caller draws; the module draws no randomness), `websocketUpgradeRequest(host, target, key, protocols)` and `websocketCheckResponse(parser, key, offered)` over an `Http1ResponseParser` told `expectUpgrade()`, answering a `WsHandshake` (`error`, a `WS_HS_*` code, and `protocol`) | RFC 6455 §1.3's accept key, the §5.7 example frames byte for byte, §5.5's control-frame rules, §7.4's close codes |
|
|
261
263
|
| [`net/http1-server.ts`](https://github.com/amritk/nish/blob/main/std/net/http1-server.ts) | The server side of HTTP/1.1: `Http1Connection`, sans-IO, drives an `Http1Parser` — `feed`, then `next()` answers `H1_REQUEST` (the parser's head), `H1_BODY` (at most `chunkSize` bytes, either framing), `H1_END`, `H1_WRITE` (a held-back write may go again), `H1_WS_MESSAGE`, `H1_WS_CLOSE` or the final `H1_ERROR`; the program answers with `respond(status, names, values, bodyLength)`, `write` and `end`, or `acceptWebSocket(protocol)` and then `sendFrame` and `closeWebSocket`. Keep-alive and pipelining one exchange at a time, a response with a length or chunked (unframed to an HTTP/1.0 client), `Connection` and the framing decided by the server, every parser refusal answered with its status and a close, pings and closes answered on a WebSocket. Two slot pools for a program that owns its loop: `Http1Server` on plain TCP and `Http1TlsServer` on `nish/net/tls-tcp` with ALPN `http/1.1` or none (`accept`, `readable` / `writable`, `next(slot)`, `flush(slot)`, `close`, `expire(now)` for the idle timeout and the deadline for a whole head, `headTimeout`, against a client that trickles its head). Both build a slot's connection on the first accept into it rather than at start-up. `Http1Server` reads a socket until a short read rather than until it would block, takes a free slot off a stack of released slots or the next never-used one rather than scanning for one, and answers `rearm(slot, wants)`, whether the interest changed and needs a `pollModify` at all: a keep-alive request is one `recv` and one `send`. The slots borrow their output from one `Http1OutputPool` while they write and give it back once sent, so a pool's memory follows the connections the socket is holding back, not its size: an idle slot holds no output buffer. Every final response carries a `Date` from `HttpDate`, which reads `Date.now()` and formats at most once a second, shared by a pool's slots; `pin(unixMs)` fixes it for a test, and a program's own `date` field replaces it. Every cap is an `Http1Config` number fixed at start-up, and a warmed slot allocates nothing per request (`docs/security/http1-codec.md`). Native only, as `nish:net` is | RFC 9112 §6, §7, §9; RFC 9110 §9.3.2, §15; RFC 6455 §4.2, §5.5. Nish clients over loopback against both carriers, requests cut at every byte, 2 MiB bodies each way, pipelining, a WebSocket echo, the arena flat over two hundred requests, the date formatted once a second, and every refusal (`tests/link/net_http1_server`); `curl` against its `serve` mode |
|
|
262
264
|
| [`net/url.ts`](https://github.com/amritk/nish/blob/main/std/net/url.ts) | The request target's path and query, read in place: `urlQueryStart` finds the `?`, `UrlPathSegments` splits a path on the raw `/` and `UrlQuery` yields a query's pairs as offsets, both reusable by `reset`; `percentDecode` and `percentDecodePathSegment` decode a window into the caller's array and answer the length or a `URL_DECODE_ERR_*` code, `percentDecodeErrorAt` answers the offset an error is at, and `urlQueryFind` finds a key. Decoding is strict by default (a malformed escape and `%00` are refused); `URL_DECODE_FORM`, `URL_DECODE_LENIENT` and `URL_DECODE_ALLOW_NUL` together decode valid UTF-8 as `URLSearchParams` does. A query yields at most `UrlQueryLimits.maxPairs` pairs (100 by default) and then answers `URL_QUERY_ERR_PAIRS`. The byte API allocates nothing; `urlDecode` and `urlQueryGet` answer strings and refuse what is not UTF-8. Whole URLs: `urlParse` splits an absolute URL into a `Url` (`scheme`, `hasAuthority`, `username`, `password`, `host`, `port`, `path`, `query`, `fragment`, each still percent-encoded, the scheme and host lower-cased), `urlResolve(base, ref)` resolves a reference against one, `urlSerialize` writes one back, and `urlDefaultPort` and `urlOrigin` answer the port and the origin a client connects to. Both refuse with null what two readers could take for different hosts: a byte outside printable ASCII, a backslash, a malformed `%`, a second `@`, a non-unreserved host byte, a numeric host that is not strict dotted-decimal IPv4, an IPv6 zone, a port past 65535. Records: [`docs/security/url.md`](../docs/security/url.md) | RFC 3986 §2.1 and §3.3, the WHATWG URL Standard's percent-decode and `application/x-www-form-urlencoded` parser; `decodeURIComponent` and `URLSearchParams` on 3,000 seeded inputs; RFC 3986 §3 and §5.2, every §5.4 example, 57 refusals and 4,000 seeded round trips in both number modes (`tests/link/net_url_parse`) |
|
|
263
|
-
| [`net/http-fields.ts`](https://github.com/amritk/nish/blob/main/std/net/http-fields.ts) | The header model HTTP/2 and HTTP/3 share, version-neutral: `HttpFields` reads a decoded section with `readRequest(names, values, extendedConnect)`, `readResponse` or `readTrailers` into `method`, `scheme`, `authority`, `path`, `protocol`, `status`, the regular fields in order (`get(name)`) and `contentLength`, answering `HTTP_FIELDS_OK` or the first refusal: a name that is empty, not a token or not lowercase; a value with NUL, CR or LF or whitespace at an end; a connection-specific field (`te` but `trailers` included); a pseudo-header unknown, repeated, after a regular field, forbidden by the shape or missing; a pseudo-header value of the wrong syntax; a `host` that disagrees with `:authority`; a bad or disagreeing `content-length`. `:protocol` (RFC 8441) is read only where the caller enabled extended CONNECT. `httpFieldNameValid`, `httpFieldValueValid`, `httpFieldConnectionSpecific` and `httpFieldsCheckOutgoing` check one name, one value or a section a program sends. `httpDateWrite(out, at, seconds)` writes a second since 1970 as the IMF-fixdate a `Date` field holds (`HTTP_DATE_SIZE` bytes, to 9999), reading no clock, so it compiles for wasm32 | RFC 9110 §5, RFC 9113 §8.2–§8.5, RFC 9114 §4.2–§4.3, RFC 8441 §4; every refusal in `tests/link/net_http_fields`; RFC 9110 §5.6.7, every day from 1970 to 2399 (`tests/link/net_http_date`) |
|
|
265
|
+
| [`net/http-fields.ts`](https://github.com/amritk/nish/blob/main/std/net/http-fields.ts) | The header model HTTP/2 and HTTP/3 share, version-neutral: `HttpFields` reads a decoded section with `readRequest(names, values, extendedConnect)`, `readResponse` or `readTrailers` into `method`, `scheme`, `authority`, `path`, `protocol`, `status`, the regular fields in order (`get(name)`) and `contentLength`, answering `HTTP_FIELDS_OK` or the first refusal: a name that is empty, not a token or not lowercase; a value with NUL, CR or LF or whitespace at an end; a connection-specific field (`te` but `trailers` included); a pseudo-header unknown, repeated, after a regular field, forbidden by the shape or missing; a pseudo-header value of the wrong syntax; a `host` that disagrees with `:authority`; a bad or disagreeing `content-length`. `:protocol` (RFC 8441) is read only where the caller enabled extended CONNECT. `httpFieldNameValid`, `httpFieldValueValid`, `httpFieldConnectionSpecific` and `httpFieldsCheckOutgoing` check one name, one value or a section a program sends. `httpDateWrite(out, at, seconds)` writes a second since 1970 as the IMF-fixdate a `Date` field holds (`HTTP_DATE_SIZE` bytes, to 9999), reading no clock, so it compiles for wasm32. `mediaTypeParse(value, from, to)` reads a `Content-Type` into a `MediaType` (`type`, `subtype` and its parameters, names lowercased) and `mediaTypeParam` finds one; `formDataDispositionParse` reads a form part's `Content-Disposition`, keeping a backslash as the HTML form submission algorithm writes it. Each answers null for a parameter given twice in any case or a 17th (`docs/security/multipart.md`) | RFC 9110 §5, RFC 9113 §8.2–§8.5, RFC 9114 §4.2–§4.3, RFC 8441 §4; every refusal in `tests/link/net_http_fields`; RFC 9110 §5.6.7, every day from 1970 to 2399 (`tests/link/net_http_date`); RFC 9110 §8.3.1 and every refusal in `tests/link/net_media_type` |
|
|
266
|
+
| [`net/multipart.ts`](https://github.com/amritk/nish/blob/main/std/net/multipart.ts) | `MultipartReader`, a `multipart/form-data` body read part by part in place: `next()` answers `MULTIPART_PART` with `name`, `filename` (as given, not a path), `contentType` and the data as `dataStart` and `dataLength` into the body, `MULTIPART_END` once the close delimiter is read, or a `MULTIPART_ERR_*` code it answers from then on: a bad boundary or window, a body cut short, a header line split by a lone CR or LF or folded, a second `Content-Disposition` or `Content-Type`, a disposition that is not `form-data` or has no `name`, and more parts, header lines or header octets than `MultipartLimits` allows (64, 16 and 8,192 by default). Copies no part's data and writes nothing to disk (`docs/security/multipart.md`) | RFC 7578 and RFC 2046 §5.1.1: six bodies Node's `FormData` wrote, every refusal code, every prefix of a body, and each cap at its limit and one past it (`tests/link/net_multipart_read`) |
|
|
264
267
|
| [`net/http2-frame.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-frame.ts) | HTTP/2's frames, sans-IO and allocation-free: `http2ReadHeader` and `http2ParseFrame` read any frame of RFC 9113 §6 into a reused `Http2Frame` (its content left in the buffer as a window), answering 0 or the connection error — FRAME_SIZE_ERROR past the reader's SETTINGS_MAX_FRAME_SIZE or for a frame of the wrong length, PROTOCOL_ERROR for a frame on the wrong stream, padding as long as its frame, or a WINDOW_UPDATE of zero on the connection — with a stream error (`streamError`) for a PRIORITY of the wrong length, a self-dependency or a WINDOW_UPDATE of zero on a stream. `http2SettingCount`, `http2SettingId`, `http2SettingValue` and `http2SettingError` read and check SETTINGS. The writers, one per type (`http2WriteData` … `http2WriteContinuation`, `http2WriteSettingsAck`), write into the caller's buffer at an offset and answer -1 when a frame does not fit | Every type against frames built by hand from §4.1 and §6, both directions, and every refusal (`tests/link/net_http2_frame`) |
|
|
265
268
|
| [`net/http2.ts`](https://github.com/amritk/nish/blob/main/std/net/http2.ts) | `Http2Connection`, the server side of HTTP/2, sans-IO: `feed(buf, off, len)`, then `next()` answers `H2_REQUEST` (`stream`, `fields`), `H2_DATA` (a window onto the input), `H2_TRAILERS`, `H2_RESET`, `H2_WINDOW` (a send window opened), `H2_GOAWAY` or the final `H2_ERROR`; send `output[outputStart .. outputEnd)` and `consume`. `respond`, `writeData` (as far as both windows and the output allow), `writeTrailers`, `reset`, `goaway` and `restart`. The §5.1 stream state machine, connection and stream flow control with WINDOW_UPDATE both ways, SETTINGS and the acknowledgement, PING, header blocks across CONTINUATION decoded by `HpackDecoder`, a 431 past the header-list cap, extended CONNECT behind SETTINGS_ENABLE_CONNECT_PROTOCOL, and every connection and stream error of RFC 9113 as GOAWAY or RST_STREAM. Every final head carries one `date` field from the connection's `date` bytes, when it has them, straight after `:status` and never on a 1xx or trailers, unless the program's fields hold one (matched ASCII case-insensitively). Every cap is an `Http2Config` number fixed at start-up; DATA and every control frame allocate nothing ([H2-1](../docs/security/http2.md)) | RFC 9113 §3–§8, RFC 8441; requests, streamed responses, flow control stalling and resuming, concurrent streams and the date on every final head from a scripted client (`tests/link/net_http2`), and a negative for each error class (`tests/link/net_http2_errors`) |
|
|
266
269
|
| [`net/http2-tls.ts`](https://github.com/amritk/nish/blob/main/std/net/http2-tls.ts) | `Http2TlsServer`: HTTP/2 over `nish/net/tls-tcp` for a program that owns its loop — a pool of `Http2Connection`s beside the TLS slots, slot 0's built by the constructor and every other on the first accept into its slot, each reused with `restart`; `accept`, `readable` / `writable`, `signP256`, `next(slot)` for the slot's next event, `flush(slot)`, `close`. A slot whose ALPN did not choose `h2` is shut down with `close_notify` (RFC 9113 §3.2). Every slot's final responses carry the pool's one `HttpDate` (`date`, from `nish/net/http1-server`), refreshed at `connection(slot)` and `next(slot)` and formatted at most once a second; `date.pin(unixMs)` fixes it for a test. Native only, as `nish:net` is | A Nish TLS client over loopback (`tests/link/net_http2_tls`): ALPN, a GET, an echoed POST, a hundred DATA frames with the arena flat, the date with the arena flat while the pinned clock crosses seconds and shared by two slots, GOAWAY, and the pool; `curl --http2` against its `serve` mode |
|
package/std/base64.ts
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
* - `base64EncodeInto(src, off, len, dst, at)` writes the encoding of
|
|
22
22
|
* `src[off..off+len)` into `dst` from `at` and allocates nothing, so a frame
|
|
23
23
|
* can be encoded chunk by chunk straight into its output buffer.
|
|
24
|
+
* - `base64EncodeIfFits(src, off, len, dst, at)` is the same write, answering
|
|
25
|
+
* -1 with nothing written where `base64EncodeInto` panics on its range.
|
|
24
26
|
* - `base64Encode(bytes)` is the whole array as a string.
|
|
25
27
|
*
|
|
26
28
|
* **This module only encodes**: what it is for writes base64 and never reads it
|
|
@@ -66,7 +68,8 @@ export const base64EncodedLength = (n: i32): i32 => {
|
|
|
66
68
|
* answer the index just past the last character written, which is
|
|
67
69
|
* `at + base64EncodedLength(len)`. Nothing is allocated. Panics when the source
|
|
68
70
|
* range is not inside `src` or the encoding does not fit in `dst` from `at`;
|
|
69
|
-
* both are checked before anything is written.
|
|
71
|
+
* both are checked before anything is written. `base64EncodeIfFits` answers -1
|
|
72
|
+
* for those instead.
|
|
70
73
|
*
|
|
71
74
|
* @param src The bytes to encode from; only `src[off..off+len)` is read.
|
|
72
75
|
* @param off Where in `src` the bytes to encode start.
|
|
@@ -126,6 +129,76 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
|
|
|
126
129
|
return o + 4
|
|
127
130
|
}
|
|
128
131
|
|
|
132
|
+
/**
|
|
133
|
+
* `base64EncodeInto` for a caller that has an answer for a range that does not
|
|
134
|
+
* fit: the same bytes written to the same place, or -1, with nothing written,
|
|
135
|
+
* when `src[off..off+len)` is not inside `src`, the encoding does not fit in
|
|
136
|
+
* `dst` from `at`, or either array is longer than 2^31 - 1 bytes. It never
|
|
137
|
+
* panics.
|
|
138
|
+
*
|
|
139
|
+
* @param src The bytes to encode from; only `src[off..off+len)` is read.
|
|
140
|
+
* @param off Where in `src` the bytes to encode start.
|
|
141
|
+
* @param len How many bytes of `src` to encode; zero writes nothing and
|
|
142
|
+
* answers `at` when `at` is inside `dst` or just past it.
|
|
143
|
+
* @param dst The buffer the characters are written into, one ASCII byte per
|
|
144
|
+
* character; bytes outside the written range are left as they were.
|
|
145
|
+
* @param at Where in `dst` the first character goes.
|
|
146
|
+
* @returns The index in `dst` just past the last character written, or -1
|
|
147
|
+
* when the range does not fit.
|
|
148
|
+
*/
|
|
149
|
+
export const base64EncodeIfFits = (src: u8[], off: i32, len: i32, dst: u8[], at: i32): i32 => {
|
|
150
|
+
// Refused before `toI32`, as in `base64EncodeInto`.
|
|
151
|
+
if (src.length > 2147483647 || dst.length > 2147483647) {
|
|
152
|
+
return -1
|
|
153
|
+
}
|
|
154
|
+
const srcLength: i32 = toI32(src.length)
|
|
155
|
+
const dstLength: i32 = toI32(dst.length)
|
|
156
|
+
if (off < 0 || len < 0 || off > srcLength - len) {
|
|
157
|
+
return -1
|
|
158
|
+
}
|
|
159
|
+
// Past this many bytes the encoding is longer than 2^31 - 1 characters, as
|
|
160
|
+
// in `base64EncodedLength`, which this restates without its panics.
|
|
161
|
+
if (len > 1610612733) {
|
|
162
|
+
return -1
|
|
163
|
+
}
|
|
164
|
+
const need: i32 = toI32((len + 2) / 3) * 4
|
|
165
|
+
if (at < 0 || need > dstLength - at) {
|
|
166
|
+
return -1
|
|
167
|
+
}
|
|
168
|
+
// A local, so that `abc.length >= 64` below is a fact about the string each
|
|
169
|
+
// character is read from.
|
|
170
|
+
const abc: string = BASE64_ALPHABET
|
|
171
|
+
let i: i32 = off
|
|
172
|
+
let o: i32 = at
|
|
173
|
+
let rest: i32 = len
|
|
174
|
+
// The checks above make every term after the first true; they are written out
|
|
175
|
+
// because they are what proves the loop's accesses in range.
|
|
176
|
+
while (rest >= 3 && i >= 0 && i < srcLength - 2 && o >= 0 && o < dstLength - 3 && abc.length >= 64) {
|
|
177
|
+
const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8) | toI32(src[i + 2])
|
|
178
|
+
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
179
|
+
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
180
|
+
dst[o + 2] = toU8(abc.charCodeAt((group >> 6) & 63))
|
|
181
|
+
dst[o + 3] = toU8(abc.charCodeAt(group & 63))
|
|
182
|
+
i = i + 3
|
|
183
|
+
o = o + 4
|
|
184
|
+
rest = rest - 3
|
|
185
|
+
}
|
|
186
|
+
// A short final group of one or two bytes, padded. As in the loop, the
|
|
187
|
+
// checks above make every term after the first false.
|
|
188
|
+
if (rest === 0 || i < 0 || i >= srcLength || o < 0 || o >= dstLength - 3 || abc.length < 64) {
|
|
189
|
+
return o
|
|
190
|
+
}
|
|
191
|
+
let group: i32 = toI32(src[i]) << 16
|
|
192
|
+
if (rest === 2 && i < srcLength - 1) {
|
|
193
|
+
group = group | (toI32(src[i + 1]) << 8)
|
|
194
|
+
}
|
|
195
|
+
dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
|
|
196
|
+
dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
|
|
197
|
+
dst[o + 2] = rest === 2 ? toU8(abc.charCodeAt((group >> 6) & 63)) : toU8(BASE64_PAD)
|
|
198
|
+
dst[o + 3] = toU8(BASE64_PAD)
|
|
199
|
+
return o + 4
|
|
200
|
+
}
|
|
201
|
+
|
|
129
202
|
/**
|
|
130
203
|
* `bytes` as padded base64. Panics past 1,610,612,733 bytes, whose encoding
|
|
131
204
|
* would not fit a string.
|