@amritk/nish-aarch64-linux 0.37.0 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/runtime/vite.mjs CHANGED
@@ -23,7 +23,7 @@
23
23
  * `resolveId`, `load`), so `tests/run.js` calls them directly, with no Vite.
24
24
  */
25
25
  import { execFile } from "node:child_process";
26
- import { mkdirSync, readFileSync } from "node:fs";
26
+ import { mkdirSync, readFileSync, statSync } from "node:fs";
27
27
  import path from "node:path";
28
28
  import { fileURLToPath } from "node:url";
29
29
  import { promisify } from "node:util";
@@ -68,6 +68,15 @@ function exportNames(dts) {
68
68
  return names;
69
69
  }
70
70
 
71
+ /** Vite's default `resolve.extensions`, in the order it tries them. */
72
+ const VITE_EXTENSIONS = [".mjs", ".js", ".mts", ".ts", ".jsx", ".tsx", ".json"];
73
+
74
+ /** Whether `p` is a file (`"file"`), a directory (`"dir"`) or neither. */
75
+ const kind = (p) => {
76
+ const st = statSync(p, { throwIfNoEntry: false });
77
+ return st?.isFile() ? "file" : st?.isDirectory() ? "dir" : undefined;
78
+ };
79
+
71
80
  /** The plugin. `compiler` and `buildScript` default to the ones in this package. */
72
81
  export default function nish(options = {}) {
73
82
  const compiler = options.compiler ?? path.join(packageDir, "bin", "nish");
@@ -77,9 +86,11 @@ export default function nish(options = {}) {
77
86
  let building = false;
78
87
  let cacheDir = path.join(root, "node_modules", ".vite");
79
88
  let entries = new Set();
89
+ let extensions = VITE_EXTENSIONS;
80
90
 
81
91
  const configure = (config) => {
82
92
  root = config.root ?? root;
93
+ extensions = config.resolve?.extensions ?? VITE_EXTENSIONS;
83
94
  building = config.command === "build";
84
95
  cacheDir = config.cacheDir ?? path.join(root, "node_modules", ".vite");
85
96
  entries = new Set((options.entries ?? []).map((e) => path.resolve(root, e)));
@@ -96,13 +107,26 @@ export default function nish(options = {}) {
96
107
  const host = (options.host ?? []).flatMap((h) => ["--host", path.resolve(root, h)]);
97
108
  await run(compiler, [entry, "--target", "wasm32", ...host, "--emit-dts", dts, "-o", ll], { cwd: root });
98
109
  const loader = path.join(dir, `${stem}.mjs`);
110
+ const loaderText = readFileSync(loader, "utf8");
111
+ // The generated module imports `loadSync`. A compiler older than it writes
112
+ // a loader without one, which Rollup would report only as a missing
113
+ // export of a file in the cache, naming neither the compiler nor the fix.
114
+ if (!/^export function loadSync\(/m.test(loaderText)) {
115
+ const version = await run(compiler, ["--version"], { cwd: root }).then(
116
+ (r) => r.stdout.trim(),
117
+ () => "an unknown version",
118
+ );
119
+ throw new Error(
120
+ `nish/vite: the compiler ${compiler} (${version}) wrote a loader with no \`loadSync\` export: ` +
121
+ "it predates `loadSync` (WP50 stage 1), which the generated module calls. " +
122
+ "Use a newer one: update the nish package, or pass its path as `nish({ compiler })`.",
123
+ );
124
+ }
99
125
  const ir = readFileSync(ll, "utf8");
100
126
  // runtime-wasm.c is linked when the IR needs a runtime function (a weak
101
127
  // `extern_weak` one, a panic stub wasm-ld writes itself, does not count)
102
128
  // or the loader calls the arena.
103
- const needsRuntime =
104
- /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) ||
105
- readFileSync(loader, "utf8").includes("raw.nish_arena_mark(");
129
+ const needsRuntime = /^declare (?!extern_weak)[^"\n]*@nish_/m.test(ir) || loaderText.includes("raw.nish_arena_mark(");
106
130
  const inline = path.join(dir, `${stem}.bytes.mjs`);
107
131
  const inputs = needsRuntime ? [ll, runtimeWasm] : [ll];
108
132
  await run("bash", [buildScript, ...inputs, "-o", path.join(dir, `${stem}.wasm`), "--profile", "wasm-host", "--inline", inline], {
@@ -117,16 +141,29 @@ export default function nish(options = {}) {
117
141
  enforce: "pre",
118
142
  configResolved: configure,
119
143
  async resolveId(source, importer) {
120
- if (!building) return null;
144
+ if (!building || entries.size === 0) return null;
121
145
  // The seam for a `./client.nish` specifier (the page's client module of a
122
146
  // later stage) is here; stage 1 resolves only the entries.
147
+ // A specifier may leave out the `.ts`, or name a directory for its
148
+ // `index.ts`. It is resolved as Vite would, file then extensions in
149
+ // order then the directory's index, so a sibling `add.js` keeps `./add`.
123
150
  const base = importer ? path.dirname(importer) : root;
124
- const candidates = source.startsWith(".")
125
- ? [path.resolve(base, source)]
126
- : path.isAbsolute(source)
127
- ? [source, path.join(root, source)]
128
- : [];
129
- const hit = candidates.find((c) => entries.has(c));
151
+ // A candidate that no entry's path starts with resolves to no entry, so
152
+ // it is dropped before anything is read from the disk.
153
+ const candidates = (
154
+ source.startsWith(".")
155
+ ? [path.resolve(base, source)]
156
+ : path.isAbsolute(source)
157
+ ? [source, path.join(root, source)]
158
+ : []
159
+ ).filter((c) => [...entries].some((e) => e.startsWith(c)));
160
+ if (candidates.length === 0) return null;
161
+ const withExtension = (stem) => extensions.map((e) => stem + e).find((f) => kind(f) === "file");
162
+ const resolve = (c) => {
163
+ if (entries.has(c) || kind(c) === "file") return c;
164
+ return withExtension(c) ?? (kind(c) === "dir" ? withExtension(path.join(c, "index")) : undefined);
165
+ };
166
+ const hit = candidates.map(resolve).find((c) => c !== undefined && entries.has(c));
130
167
  return hit === undefined ? null : PREFIX + hit;
131
168
  },
132
169
  async load(id) {
package/scripts/build.sh CHANGED
@@ -3,8 +3,9 @@
3
3
  #
4
4
  # scripts/build.sh <module.ll> [more .ll/.c files...] -o <out> [--profile debug|speed|size|wasm|wasm-host|wasi|napi]
5
5
  #
6
- # The C runtime is sixteen translation units and is named as one: an input
7
- # <dir>/runtime.c also compiles <dir>/runtime-os.c, the half that wraps the
6
+ # The C runtime is seventeen translation units and is named as one: an input
7
+ # <dir>/runtime.c also compiles <dir>/runtime-text.c, the strings and the digits
8
+ # of numbers, <dir>/runtime-os.c, the half that wraps the
8
9
  # system calls (files, directories, subprocesses, the environment, the clock),
9
10
  # <dir>/runtime-parallel.c, the half that divides a range of work across
10
11
  # threads, <dir>/runtime-cross.c, the copies that carry a string or an array
@@ -41,10 +42,13 @@
41
42
  # when runtime-wasm.c is linked, the arena entry points the
42
43
  # `--emit-dts` loader calls (nish_arena_mark, nish_arena_release,
43
44
  # nish_alloc_array, nish_reset_arena, nish_free_arena). The stack is
44
- # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz` on the
45
- # module when wasm-opt (binaryen) is on PATH; the build line says
46
- # whether it ran. Two flags take this profile alone, and any other
47
- # refuses them with exit 2:
45
+ # a fixed 64 KiB (-z stack-size=65536). Runs `wasm-opt -Oz
46
+ # --strip-target-features` on the module when wasm-opt (binaryen)
47
+ # is on PATH; the build line says whether it ran. NISH_WASM_OPT=0
48
+ # links without it even when it is installed (clang's own wasm-opt
49
+ # call too): the module a machine without binaryen builds, which
50
+ # the size guard measures. Two flags take this profile alone, and
51
+ # any other refuses them with exit 2:
48
52
  # --memory <MiB> memory fixed at <MiB> MiB (1 to 4096), the
49
53
  # initial size and the maximum both, so it
50
54
  # never grows and `memory.buffer` is one
@@ -122,7 +126,7 @@
122
126
  #
123
127
  # The runtime compiled once (the debug, speed and size profiles only; `nish
124
128
  # --link` and `nish run` use these through their runtime cache, src/compile.ts):
125
- # --runtime-objects <dir> compile the runtime.c input and its seven siblings,
129
+ # --runtime-objects <dir> compile the runtime.c input, its sixteen halves and runtime-async.c,
126
130
  # one $CC -c each and all at once, into
127
131
  # <dir>/<unit>.o with the profile's compile flags,
128
132
  # and link nothing. speed and size store LTO bitcode,
@@ -267,8 +271,8 @@ if [ -n "$sqlite_to" ] || [ -n "$sqlite_from" ]; then
267
271
  fi
268
272
  [ -n "$out" ] || [ -n "$objects_to" ] || [ -n "$sqlite_to" ] || { echo "error: -o <out> is required" >&2; exit 2; }
269
273
 
270
- # The runtime is sixteen translation units, and a caller names one: whoever passes
271
- # <dir>/runtime.c gets <dir>/runtime-os.c, <dir>/runtime-parallel.c,
274
+ # The runtime is seventeen translation units, and a caller names one: whoever passes
275
+ # <dir>/runtime.c gets <dir>/runtime-text.c, <dir>/runtime-os.c, <dir>/runtime-parallel.c,
272
276
  # <dir>/runtime-cross.c, <dir>/runtime-host.c, <dir>/runtime-net.c, <dir>/runtime-simd.c,
273
277
  # <dir>/runtime-aes.c, <dir>/runtime-sha256.c, <dir>/runtime-chacha20.c, <dir>/runtime-checksum.c, <dir>/runtime-term.c,
274
278
  # <dir>/runtime-bytes.c, <dir>/runtime-sandbox.c, <dir>/runtime-shm.c and <dir>/runtime-region.c compiled beside it, on every profile,
@@ -280,7 +284,7 @@ fi
280
284
  # compiles to two functions that refuse to run, which no wasm build calls, and
281
285
  # runtime-shm.c answers -95 for every region. They were one file until the
282
286
  # operating-system half was split out for its own size budget, and the parallel
283
- # half followed for the same reason (each file's header comment says why), and
287
+ # and text halves followed for the same reason (each file's header comment says why), and
284
288
  # a link line is where those splits
285
289
  # would otherwise leak: `nish --link` builds its command line in
286
290
  # src/compile.ts, the published package's recipe in every document and
@@ -288,7 +292,7 @@ fi
288
292
  # here keeps every one of those correct, and keeps "the runtime" one thing to
289
293
  # name from the outside. A caller that names one itself is left alone, because
290
294
  # naming one object twice is a duplicate-symbol error.
291
- halves="runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
295
+ halves="runtime-text.c runtime-os.c runtime-parallel.c runtime-cross.c runtime-host.c runtime-net.c runtime-simd.c runtime-aes.c runtime-sha256.c runtime-chacha20.c runtime-checksum.c runtime-term.c runtime-bytes.c runtime-sandbox.c runtime-shm.c runtime-region.c"
292
296
  for i in ${inputs[@]+"${inputs[@]}"}; do
293
297
  case "$i" in
294
298
  */runtime.c|runtime.c)
@@ -376,6 +380,12 @@ fi
376
380
 
377
381
  CC=${CC:-clang}
378
382
  common=(-Wno-override-module) # our IR is target-neutral; clang fills the triple in
383
+ # -ffp-contract=off on every unit, every profile (WP50 S5): clang's default
384
+ # contracts a*b+c in C into one fused multiply-add wherever the target has one
385
+ # (arm64 always, x86-64 at v3), which rounds once where the source rounds
386
+ # twice, so the runtime would print another float on arm64 than on x86-64.
387
+ # Nish's own IR asks for no contraction, so the flag changes only the C units.
388
+ common+=(-ffp-contract=off)
379
389
  elf=() # flags that only make sense for ELF targets
380
390
  lld=0 # 1 when the link goes through ld.lld
381
391
 
@@ -447,10 +457,10 @@ if [ "$debug" = 1 ]; then common+=(-g); strip_flag=(); fi
447
457
  # runtime-parallel.c compiles to its sequential fallback because it tests
448
458
  # __wasi__ and __wasm__ as well as the macro.
449
459
  # --cpu: every unit at the one level, so the module, the runtime and the link
450
- # (LTO generates code there) agree. -ffp-contract=off keeps the meaning fixed:
451
- # v3 has FMA, and contracting a*b+c into one rounding would print a different
452
- # float than the baseline build (docs/LANGUAGE.md, "The CPU level").
453
- if [ -n "$cpu" ]; then common+=(-march=x86-64-v3 -ffp-contract=off); fi
460
+ # (LTO generates code there) agree. v3 has FMA, and the -ffp-contract=off every
461
+ # unit has above keeps a*b+c two roundings, so it prints the float the baseline
462
+ # build does (docs/LANGUAGE.md, "The CPU level").
463
+ if [ -n "$cpu" ]; then common+=(-march=x86-64-v3); fi
454
464
 
455
465
  # Hardening, on every native profile (the wasm and wasi ones build their own
456
466
  # command line and have none of these to give). docs/security/runtime.md
@@ -808,6 +818,21 @@ case "$profile" in
808
818
  if [ "$bytes_wanted" = 1 ] && [ "$bytes_named" = 0 ]; then
809
819
  inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-bytes.c")
810
820
  fi
821
+ # IR that builds a string (`+`, a template, `String(x)`, a number's digits)
822
+ # calls runtime-text.c, which compiles freestanding for wasm32 (WP50 stage 4).
823
+ # It is added the same way, only for such IR and only when the caller has not
824
+ # named it; it allocates through runtime-wasm.c's arena, so that is linked too.
825
+ text_named=0
826
+ text_wanted=0
827
+ for i in ${inputs[@]+"${inputs[@]}"}; do
828
+ case "$i" in
829
+ */runtime-text.c|runtime-text.c) text_named=1 ;;
830
+ *.ll) if grep -qE '@nish_(str_|f64_format|json_put_f64)' "$i"; then text_wanted=1; fi ;;
831
+ esac
832
+ done
833
+ if [ "$text_wanted" = 1 ] && [ "$text_named" = 0 ]; then
834
+ inputs+=("$(cd "$(dirname "$0")/../runtime" && pwd)/runtime-text.c")
835
+ fi
811
836
  # IR compiled for the host rounds through runtime-simd.c's `nish_floor` and its
812
837
  # kin behind the constructor `nish_round_init` (#943). runtime-wasm.c has their
813
838
  # wasm32 bodies, and it is added the same way when such IR does not name it.
@@ -819,6 +844,7 @@ case "$profile" in
819
844
  *.ll) if grep -q '@nish_round_init' "$i"; then round_wanted=1; fi ;;
820
845
  esac
821
846
  done
847
+ if [ "$text_wanted" = 1 ]; then round_wanted=1; fi
822
848
  # Under wasm-host a program whose loader guards panics (one with module
823
849
  # storage or a host module: the compiler ends its IR with a
824
850
  # `; nish.sites <count>` line) reports each panic through the page's
@@ -849,7 +875,7 @@ case "$profile" in
849
875
  fi
850
876
  # -mbulk-memory lowers llvm.memset/memcpy (`new Array<T>(n)`, `push` growth) to the
851
877
  # memory.fill/memory.copy instructions instead of libc calls the freestanding link lacks.
852
- wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory)
878
+ wasm_compile=(-Wno-override-module --target=wasm32-unknown-unknown -Oz -nostdlib -mbulk-memory -ffp-contract=off)
853
879
  if [ "$profile" = wasm ]; then
854
880
  "$CC" "${wasm_compile[@]}" \
855
881
  ${tls[@]+"${tls[@]}"} \
@@ -967,17 +993,49 @@ case "$profile" in
967
993
  bytes=$((memory_mib * 1048576))
968
994
  memory+=("-Wl,--initial-memory=$bytes" "-Wl,--max-memory=$bytes")
969
995
  fi
970
- "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
971
- ${tls[@]+"${tls[@]}"} \
972
- -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
973
- "${host_inputs[@]}" -o "$out"
974
996
  # binaryen's size pass is optional: the module is complete without it.
975
- if command -v wasm-opt >/dev/null 2>&1; then
976
- wasm-opt -Oz --enable-bulk-memory "$out" -o "$out"
977
- wasm_opt="wasm-opt -Oz"
978
- else
979
- wasm_opt="no wasm-opt"
980
- fi
997
+ # It runs twice when wasm-opt is installed. clang 18 runs it itself after
998
+ # any link with an -O flag, finding it on PATH, and has wasm-ld keep the
999
+ # `target_features` section for it: 48 bytes or more that nothing at
1000
+ # run time reads, which put add.wasm at 150 bytes against 102 without
1001
+ # wasm-opt (#1257). The pass below drops that section again.
1002
+ # NISH_WASM_OPT=0 runs neither: each source is compiled alone and the
1003
+ # objects linked with no -O flag, so clang starts no wasm-opt and the
1004
+ # module is byte for byte the one a machine without binaryen links.
1005
+ # That is the build the size guard pins.
1006
+ case "${NISH_WASM_OPT:-1}" in
1007
+ 0)
1008
+ make_work
1009
+ host_objects=()
1010
+ for i in "${host_inputs[@]}"; do
1011
+ # What clang compiles in a one-step link is compiled here (.ll, .c,
1012
+ # .bc, .s, ...); what it hands straight to wasm-ld passes through.
1013
+ case "$i" in
1014
+ *.o|*.a) host_objects+=("$i") ;;
1015
+ *)
1016
+ object="$work/host-${#host_objects[@]}.o"
1017
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
1018
+ ${tls[@]+"${tls[@]}"} -c "$i" -o "$object"
1019
+ host_objects+=("$object") ;;
1020
+ esac
1021
+ done
1022
+ "$CC" --target=wasm32-unknown-unknown -nostdlib \
1023
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
1024
+ "${host_objects[@]}" -o "$out"
1025
+ wasm_opt="no wasm-opt, NISH_WASM_OPT=0" ;;
1026
+ 1)
1027
+ "$CC" "${wasm_compile[@]}" ${host_define[@]+"${host_define[@]}"} \
1028
+ ${tls[@]+"${tls[@]}"} \
1029
+ -Wl,--no-entry ${exports[@]+"${exports[@]}"} "${memory[@]}" -Wl,--strip-all -Wl,--gc-sections \
1030
+ "${host_inputs[@]}" -o "$out"
1031
+ if command -v wasm-opt >/dev/null 2>&1; then
1032
+ wasm-opt -Oz --enable-bulk-memory --strip-target-features "$out" -o "$out"
1033
+ wasm_opt="wasm-opt -Oz"
1034
+ else
1035
+ wasm_opt="no wasm-opt"
1036
+ fi ;;
1037
+ *) echo "error: NISH_WASM_OPT must be 0 or 1, not '$NISH_WASM_OPT'" >&2; exit 2 ;;
1038
+ esac
981
1039
  if [ -n "$inline_to" ]; then
982
1040
  # Decimal, one array literal: of the inline forms the smallest after
983
1041
  # compression (docs/wp50-wasm-host.md, Q10). od prints each byte as an
@@ -1027,9 +1085,9 @@ case "$profile" in
1027
1085
  fi
1028
1086
  # SQLite builds on wasi-libc as it is: the amalgamation sees __wasi__ and
1029
1087
  # takes dot-file locking, no mmap and no WAL shared memory.
1030
- sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
1088
+ sqlite_objects --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
1031
1089
  ${tls[@]+"${tls[@]}"} -ffunction-sections -fdata-sections
1032
- "$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG \
1090
+ "$CC" -Wno-override-module --target=wasm32-wasi --sysroot="$sysroot" -Oz -DNDEBUG -ffp-contract=off \
1033
1091
  ${tls[@]+"${tls[@]}"} \
1034
1092
  -ffunction-sections -fdata-sections -Wl,--gc-sections -Wl,--strip-all \
1035
1093
  "${inputs[@]}" ${libs[@]+"${libs[@]}"} -o "$out" ;;
@@ -6,3 +6,11 @@ Permission to use, copy, modify, and distribute this
6
6
  software is freely granted, provided that this notice
7
7
  is preserved.
8
8
  ====================================================
9
+
10
+ ====================================================
11
+ Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
12
+
13
+ Permission to use, copy, modify, and distribute this
14
+ software is freely granted, provided that this notice
15
+ is preserved.
16
+ ====================================================
package/std/README.md CHANGED
@@ -47,6 +47,7 @@ whatever program imports it, and subject to the same rules as `examples/` or
47
47
  | [`threads.ts`](https://github.com/amritk/nish/blob/main/std/threads.ts) | `parallelMapInto(src, dst, f)` and `parallelReduce(src, f, identity)`: a function over every element of an array, on as many threads as the length is worth. Its bodies are the sequential meaning, which is what runs under Node; the compiler recognises the two templates by module and name, lowers the one loop in each onto `nish_parallel_range`, holds the function to the rules that make that safe, and compiles an importing program with `--threads` ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#data-parallelism-nishthreads)). `tests/link/par_*` are its programs. `scope()`, bound by `using s = scope()`, runs unlike tasks, each on a thread of its own, and joins them at every exit of the block; `s.spawn(entry, arg, dst, at)` stores a task's answer, and `s.spawn(entry, arg)` and `s.spawn(() => ...)`, whose arrow reads the function's `const` locals, run one that answers `void` (`spawnWith` and `spawnThunk` are the methods the compiler reads them as, and under Node `spawn` itself tells them apart) ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#scoped-tasks-using-s--scope)). `scopeWithStack(bytes)` is a scope whose tasks each run on a new thread with at least `bytes` of stack, for a task that recurses deeper than a thread's default allows; under Node and without threads the size is checked and otherwise ignored (`tests/link/thread_stack_deep`). `Mutex<T>` is a lock that owns its data: the value is reachable only through the guard `using g = m.lock()` binds, which releases it at every exit of the block, so a scope's tasks can share and update one value without a data race or a deadlock ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#a-lock-that-owns-its-data-mutext); `tests/link/thread_mutex_*`, and `examples/histogram.ts` measured). `Channel<T>` carries scalars to one receiver, a task of the scope or the parent after the join, from the scope's sender tasks and from the parent before the block that spawns them, and closes when every sending task has returned ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#channels-channelt); [`docs/wp29-thread-surface.md`](https://github.com/amritk/nish/blob/main/docs/wp29-thread-surface.md#44-stage-p3--channels-of-scalars) §4.4). Every body in the module is its meaning under Node, where a task runs at its `spawn` |
48
48
  | [`sync/shm.ts`](https://github.com/amritk/nish/blob/main/std/sync/shm.ts) | `createRegion(name, bytes)`, `openRegion(name)` and `unlinkRegion(name)`: a named region of memory that several processes of one user map at once, through `runtime/runtime-shm.c`. A `SharedRegion` is read and written through checked slots, `loadI32` to `compareExchangeI64` at an ordering the call names (`RELAXED` to `SEQ_CST`), and byte windows (`read`, `write`); an offset outside the region or not a multiple of the slot's width stops the program. `waitI32` and `wake` sleep and wake on a slot across processes (Linux futex; `SHM_UNSUPPORTED` elsewhere). Native only, and it reaches `ffi` ([`docs/LANGUAGE.md`](https://github.com/amritk/nish/blob/main/docs/LANGUAGE.md#shared-memory-between-processes-nishsyncshm-and-nishsyncring); [`docs/wp47-shared-memory.md`](https://github.com/amritk/nish/blob/main/docs/wp47-shared-memory.md); [`docs/security/shm.md`](../docs/security/shm.md)) |
49
49
  | [`sync/ring.ts`](https://github.com/amritk/nish/blob/main/std/sync/ring.ts) | Lock-free rings of byte records in a `SharedRegion`: `SpscRing` (one producer, one consumer, records of any length) and `MpscRing` (many producers, one consumer, fixed slots), made with `initSpscRing` / `initMpscRing` and found from another process with `attachSpscRing` / `attachMpscRing`. `tryPush`, `tryPop` and `popBatch` never block; a ring made with a doorbell adds `popWait`, which sleeps on a futex that a push rings only when the consumer is asleep. A length a peer wrote that the ring cannot hold stops the program as corrupt. `tests/link/sync_ring`, `examples/prefork-jobs.ts` and `bench/ring-latency/` are its programs |
50
+ | [`host/text.ts`](https://github.com/amritk/nish/blob/main/std/host/text.ts) | Text in wasm module storage, for a module and its page (WP50 stage 4). `textWrite(buf, at, s)` writes a string's UTF-8 bytes into a `u8[]` at `at` and answers the offset after them, `textWriteInt` and `textWriteF64` a number as a template literal formats it; text that does not fit writes nothing and answers -1, which every writer passes through, so a chain fails as a whole and never traps. `textRead(buf, n)` is the first `n` bytes as a string, what the page's `encodeInto` wrote, or `null` for an `n` past the buffer. `tests/host-import/text` is its round trip |
50
51
 
51
52
  ## `nish/crypto` — the primitives under TLS 1.3
52
53
 
@@ -263,6 +264,7 @@ reads one, and it still takes its randomness as an argument.
263
264
  | [`net/http-compress.ts`](https://github.com/amritk/nish/blob/main/std/net/http-compress.ts) | Content coding for HTTP responses: `httpAcceptEncoding(buf, start, end, offered)` reads an `Accept-Encoding` value (q-values, `*`, `identity`, `x-gzip`) into `HTTP_CODING_GZIP`, `HTTP_CODING_DEFLATE`, `HTTP_CODING_IDENTITY` or `HTTP_CODING_NONE`, allocating nothing; `HttpCompressor(level, minLength, maxLength)` gzips a body into its own buffer when it is worth it (-1 to send it as it is) and builds the response fields (`addFields`: `Content-Encoding: gzip` and, while `vary`, `Vary: Accept-Encoding`). It sends gzip only when it pays: `minLength`, `minSaving` bytes or `minSavingPercent`, and `segmentMode` (fewer TCP segments of `mss`, head included, than as it is); `decision` says why (`HTTP_COMPRESS_SENT`, `_NOT_ACCEPTED`, `_TOO_SMALL`, `_TOO_LARGE`, `_TOO_LITTLE_SAVED`, `_NO_FEWER_SEGMENTS`). Bodies up to `fixedLimit` use the fixed-Huffman encoder (`encoder`: `HTTP_ENCODER_AUTO`, `_FIXED`, `_LEVEL`). On HTTP/1.1, `Http1Connection.acceptEncoding()` and `respondEncoded(status, names, values, body, off, len, enc, coding)` answer a request in one call with the compressed `Content-Length`, or nothing at all (`H1_AGAIN`, `H1_INVALID`); `identity;q=0` is honoured. Opt-in; BREACH is the program's to avoid (`docs/security/compress.md`) | RFC 9110 §8.4 and §12.5.3: the negotiation table, and sans-IO responses gunzipped back (`tests/link/std_http_compress`) |
264
265
  | [`net/router.ts`](https://github.com/amritk/nish/blob/main/std/net/router.ts) | `Router`, a method and path router that knows no carrier and allocates nothing per match: `add(method, pattern)` answers the route's index (0, 1, 2 in the order added) or a refusal — `ROUTER_BAD_PATTERN`, `ROUTER_BAD_METHOD`, `ROUTER_TOO_LONG`, `ROUTER_AMBIGUOUS` (`*` not last), `ROUTER_DUPLICATE` (the same shape and method, whatever the parameter names) or `ROUTER_FULL`, against `RouterLimits`; `match(method, mStart, mEnd, target, tStart, tEnd, params)` answers the index, `ROUTER_NOT_FOUND` or `ROUTER_METHOD_NOT_ALLOWED`, writing each `:name` and a final `*` as a `[start, end)` pair into the caller's `params` (`ROUTER_TOO_MANY_PARAMS` when it is short). Literal before parameter before `*`, segment by segment, backtracking; a lookup enters each node at most once. The query is left unparsed and nothing is decoded: `routerDecode` decodes one parameter (`ROUTER_BAD_ESCAPE`, `ROUTER_NO_ROOM`) (`docs/security/router.md`) | Every refusal code, precedence and backtracking, 405 against 404, `%2F` kept in one segment, the query, `*` and authority-form targets, a target deeper than any route, the lookup bound, params past storage, and the arena flat over matches (`tests/link/net_router`, `net_router_f64`, five `net_router_negative_*`) |
265
266
  | [`net/handler.ts`](https://github.com/amritk/nish/blob/main/std/net/handler.ts) | `HttpHandler`, complete requests and their answers over the HTTP/1.1 carrier: it owns the readiness loop, routes each request through a `Router` at its head, gathers its body up to `HandlerLimits.http.maxBody` (1 MiB; past it the carrier answers 413), and hands it over whole. The program pulls — `wait(ms)`, `ready()`, `take()` — and switches on `req.route`; `HttpRequest` reads parameters, form-decoded query values and fields as ranges into its own buffers. Each request is answered once, now or in a later turn, by `send`, `sendFields`, `empty`, `json()` + `sendJson`, `problem` (RFC 9457), `refuse` (404, or 405 with `Allow`) or `start`/`write`/`end`; an answer whose connection closed first is `HANDLER_DROPPED` and reaches no later peer. `HEAD` takes a `GET` route. `watch`/`fired` add the program's own descriptors (`signalFd()`), and `drain` stops gracefully. Nothing is allocated per request once warm (`docs/security/handler.md`) | Routing, parameters and form-decoded queries, `HEAD`, 404 and 405 problems, chunked bodies in and out, the body cap at and one past it, pipelining order, late answers dropped across a reused slot, the arena and pool flat over two thousand requests, and the drain (`tests/link/net_handler`, and `net_http_app` over `examples/http-app`) |
267
+ | [`net/serve.ts`](https://github.com/amritk/nish/blob/main/std/net/serve.ts) | `serve(port, router, limits, handle)`, an HTTP/1.1 server for an `async` program over `HttpHandler`: each whole request is copied into a task of its own, which runs the program's `handle(req: Request): Promise<Response>` in its own region and writes the answer into the request slot's preallocated buffers; the loop sends answers in request order. `ServeLimits` caps connections (closed past it), requests in flight (503), the header section (431), the body (413) and the response (500), and closes a connection whose head takes past `headTimeout` or that idles past `idleTimeout`; `deadline` is held, not yet enforced. `Arena.used()` stays flat over thousands of pipelined requests (`tests/link/net_serve_pipelined_flat`). Native only: `--emit-ts` refuses `readable` (NL4017). Record: `docs/security/serve.md`. |
266
268
  | [`net/upstream.ts`](https://github.com/amritk/nish/blob/main/std/net/upstream.ts) | `Upstream`, outbound HTTP/1.1 calls from a route handler that never block it: a pool of keep-alive connections to one `http:` origin on the `HttpHandler`'s own loop (watch ids `UpstreamLimits.firstId` and up). `get(req, path)` returns at once, or `UPSTREAM_E_FULL` with nothing held; each call comes back once through `ready()`/`take()` tagged with `r.req`, `ok` with its status and `body[0 .. length)`, or failed with the codec's `HTTP1_E_` refusal or an `UPSTREAM_E_` code (timeout, closed, connect, origin, lookup, blocked, request), and goes back with `release`. The origin is looked up once at start-up and pinned; `UpstreamLimits.outbound` checks it against an `OutboundPolicy`. A failed call's connection is closed. Each connection keeps one codec in spans mode, so a warm pool allocates nothing per call | A slow upstream while other clients and a second upstream are answered, the timeout, keep-alive and tagging, five codec refusals as failures, the policy refusing loopback, origin and request-target refusals, three thousand warm calls on one connection with `Arena.used()` flat (`tests/link/net_upstream`), and a second `release` panicking (`net_upstream_release`) |
267
269
  | [`net/postgres.ts`](https://github.com/amritk/nish/blob/main/std/net/postgres.ts) | `PgConnection`, a PostgreSQL client that reads no socket: the program fills `inputBuffer()` and sends `outputBuffer()`, and `next()` answers `PG_NEED_MORE`, `PG_READY`, `PG_DESCRIBED`, `PG_ROW`, `PG_COMPLETE`, `PG_ERROR`, `PG_NOTICE`, `PG_GROUP_DONE` or the final `PG_FAILED` (`failure`, one of the `PG_ERR_*` codes). Protocol 3.0: startup, `trust` and SCRAM-SHA-256 with the server's signature checked (cleartext and MD5 refused), the extended query protocol — `prepare`, `bindStart`, `paramInt` / `paramText` / `paramBytes` / `paramTextArray` / `paramIntArray` / `paramNull`, an array built element by element into the Bind (`arrayStart`, `arrayElement`, `arrayInt`, `arrayNull`, `arrayEnd`), binary `int4[]` / `int8[]` parameters (`paramInt4Array` / `paramInt8Array` over an `i64[]` window, or `binaryArrayStart`, `binaryArrayInt`, `binaryArrayNull` and the same `arrayEnd`; per-parameter format codes only once a binary one is bound; an `int4` element out of range panics), `bindEnd`, `bindStartBinary` for a Bind whose result columns come in binary (read in place by `binaryInt`, `binaryBool`, `binaryFloat` and `PgBinary`'s `timestamp` and `iso`, and a one-dimensional `int2[]`, `int4[]` or `int8[]` by `PgBinaryArray`), `bindCancel` to drop a Bind not yet ended, `closeStatement`, `sync` — with up to `maxInFlight` groups pipelined. `PgBatcher` queues keyed reads of one statement shape (`addInt`, `addText`) and `take(conn)` binds up to `maxRequests` of them, each key once, as one execution over `unnest($1) with ordinality`; `row`, `end` and `fail` route its rows by their server-supplied ordinal, checked first (read with `binaryInt` when `PgBatchConfig.binary` is set, so the batch's rows come in binary too), to `next(run)`'s per-request `PG_BATCH_ROW` and `PG_BATCH_DONE` / `PG_BATCH_MISSING` / `PG_BATCH_FAILED`; with `PgBatchConfig.sorted` false the statement has no `order by q.ord`, so no Sort node, rows route as they come and each request's last event waits for `end`; `take` answers a fresh handle each time, so a server's late or repeated event on a spent one is counted in `stray`, never routed or panicked on. It reads no clock and allocates nothing per request or row. `PgBatchClock` says when to take, from times the program passes in: once max(`minCount`, the moving average of batch sizes × `factor`) wait, the oldest has waited `maxWaitUs`, or, with the idle bypass, nothing is in flight and the load is light (its defaults are the fixed window); `PgBatcher.takeDue` takes only then, and `PgBatchTurns` lets one free connection collect while the others execute. A row's columns are windows onto the receive buffer (`colStart`, `colLength`), read in place by `int`, `bool`, `isNull` and `PgText`'s decoders (`timestamptz`, `PgArrayWalker` for `text[]`); no per-row or per-column allocation. The password is a `Secret<u8[]>`, wiped once the proof is made. Caps on message size, columns, groups in flight and SCRAM iterations (`docs/security/postgres.md`) | PostgreSQL 18's frontend/backend protocol chapter, RFC 5802 and RFC 7677: every builder, event and refusal (`tests/link/std_postgres`), and exchanges recorded from PostgreSQL 18 by `tests/postgres/record.mjs` replayed byte for byte (`tests/link/std_postgres_replay`); the batcher's queueing, caps and ordinal refusals (`tests/link/std_postgres_batch`), and unsorted (`tests/link/std_postgres_batch_unsorted`); the clock's reasons, backlog and turns (`tests/link/std_postgres_batch_clock`) |
268
270
  | [`net/postgres-carrier.ts`](https://github.com/amritk/nish/blob/main/std/net/postgres-carrier.ts) | `PgCarrier`, a `PgPool`'s queries on an `HttpHandler`'s loop: its sockets sit in the handler's epoll set, a route handler hands a request to `run` (or `runInt` / `runText` for one of up to 8 attached `PgBatcher`s) and gets its number at once, and `next()` answers `PG_CARRIER_BUILD` to bind a plain query on `connection()`, `PG_CARRIER_ROW`, `PG_CARRIER_COMPLETE`, `PG_CARRIER_ERROR` and one final `PG_CARRIER_DONE`, `PG_CARRIER_MISSING` or `PG_CARRIER_FAILED` (`failure`, `socketError`) with `request()` the request to answer and `tag` the caller's. It connects the pool's slots itself (TCP or a Unix socket), times out a connect after `connectTimeoutMs`, sheds batched keys when no slot can connect, and sizes every table from `PgCarrierLimits` at construction: `run` answers `PG_CARRIER_FULL` rather than grow one, and once connections are up it allocates nothing per query. Kept apart from `net/postgres.ts` so that module reaches no capability (`docs/security/postgres.md`) | A loopback backend in the test itself: routing, a slow query not stalling another client, lost and refused connections, a connect timeout, and `Arena.used()` flat over thousands of queries (`tests/link/std_postgres_carrier`); a live server by `tests/postgres/live/run.mjs` |
package/std/array.ts ADDED
@@ -0,0 +1,266 @@
1
+ /**
2
+ * `std/array` — the array methods that take a callback, and `slice`, in Nish:
3
+ * each a plain loop, compiled once per callback.
4
+ *
5
+ * export const main = (): i32 => {
6
+ * const xs: i32[] = [3, 1, 2];
7
+ * const doubled = xs.map((x) => x * 2); // [6, 2, 4]
8
+ * const big = xs.filter((x) => x > 1); // [3, 2]
9
+ * return doubled[0] + big.length + xs.findIndex((x) => x === 2); // 6 + 2 + 2
10
+ * };
11
+ *
12
+ * **A program does not need to import this module.** A `.map(...)`,
13
+ * `.filter(...)`, `.some(...)`, `.every(...)`, `.findIndex(...)` or
14
+ * `.slice(...)` call on an array is what loads it (the checker's
15
+ * `importArrayMethods`), and the checker routes the call to the template here
16
+ * that matches it: `xs.map(f)` is `map(xs, f)` when `f` takes one parameter
17
+ * and `mapIndexed(xs, f)` when it takes two. `f` is a compile-time function
18
+ * parameter, so each callback is an instantiation of its own whose body calls
19
+ * it directly — there is no function pointer, and importing a template here
20
+ * by name and calling it gives the same code as the method. Under Node,
21
+ * `--emit-ts` leaves `map`, `filter`, `some`, `every` and `findIndex` as the
22
+ * platform's own `Array.prototype` methods, writes `slice` as the runtime's
23
+ * checked `sliceArray`, and copies an answer that holds records inline with
24
+ * `copyRecords`, so nothing here runs there.
25
+ *
26
+ * **Same answers as Node.** Each walks the array from index 0 upward and
27
+ * calls the callback once per element, in order, until the length it had when
28
+ * the call began, as `Array.prototype` does; `some`, `every` and `findIndex`
29
+ * stop at the first element that decides the answer. A callback that shrinks
30
+ * the array ends the walk at the new length, where JavaScript goes on and
31
+ * skips the missing indices.
32
+ */
33
+
34
+ /**
35
+ * The elements of `xs`, each passed through `f`, in a new array of the same
36
+ * length: what `xs.map(f)` compiles to when `f` takes one parameter.
37
+ *
38
+ * @param xs the array read; it is not changed.
39
+ * @param f called once per element, in order.
40
+ * @returns a new array whose element `i` is `f(xs[i])`.
41
+ */
42
+ export const map = <T, U>(xs: readonly T[], f: (x: T) => U): U[] => {
43
+ const out: U[] = []
44
+ const n = xs.length
45
+ for (let i: number = 0; i < n && i < xs.length; i++) {
46
+ out.push(f(xs[i]))
47
+ }
48
+ return out
49
+ }
50
+
51
+ /**
52
+ * The elements of `xs`, each passed through `f` with its index: what
53
+ * `xs.map(f)` compiles to when `f` takes two parameters.
54
+ *
55
+ * @param xs the array read; it is not changed.
56
+ * @param f called once per element, in order, with the element and its index.
57
+ * @returns a new array whose element `i` is `f(xs[i], i)`.
58
+ */
59
+ export const mapIndexed = <T, U>(xs: readonly T[], f: (x: T, i: number) => U): U[] => {
60
+ const out: U[] = []
61
+ const n = xs.length
62
+ for (let i: number = 0; i < n && i < xs.length; i++) {
63
+ out.push(f(xs[i], i))
64
+ }
65
+ return out
66
+ }
67
+
68
+ /**
69
+ * The elements of `xs` for which `pred` answers `true`, in order, in a new
70
+ * array: what `xs.filter(pred)` compiles to when `pred` takes one parameter.
71
+ *
72
+ * @param xs the array read; it is not changed.
73
+ * @param pred called once per element, in order.
74
+ * @returns a new array of the elements kept.
75
+ */
76
+ export const filter = <T>(xs: readonly T[], pred: (x: T) => boolean): T[] => {
77
+ const out: T[] = []
78
+ const n = xs.length
79
+ for (let i: number = 0; i < n && i < xs.length; i++) {
80
+ const x = xs[i]
81
+ if (pred(x)) {
82
+ out.push(x)
83
+ }
84
+ }
85
+ return out
86
+ }
87
+
88
+ /**
89
+ * The elements of `xs` for which `pred` answers `true`, given each element and
90
+ * its index: what `xs.filter(pred)` compiles to when `pred` takes two
91
+ * parameters.
92
+ *
93
+ * @param xs the array read; it is not changed.
94
+ * @param pred called once per element, in order, with the element and its index.
95
+ * @returns a new array of the elements kept.
96
+ */
97
+ export const filterIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): T[] => {
98
+ const out: T[] = []
99
+ const n = xs.length
100
+ for (let i: number = 0; i < n && i < xs.length; i++) {
101
+ const x = xs[i]
102
+ if (pred(x, i)) {
103
+ out.push(x)
104
+ }
105
+ }
106
+ return out
107
+ }
108
+
109
+ /**
110
+ * Whether `pred` answers `true` for at least one element of `xs`, stopping at
111
+ * the first that does: what `xs.some(pred)` compiles to when `pred` takes one
112
+ * parameter. An empty array answers `false`.
113
+ *
114
+ * @param xs the array read; it is not changed.
115
+ * @param pred called in order until it answers `true`.
116
+ * @returns `true` when some element satisfies `pred`.
117
+ */
118
+ export const some = <T>(xs: readonly T[], pred: (x: T) => boolean): boolean => {
119
+ const n = xs.length
120
+ for (let i: number = 0; i < n && i < xs.length; i++) {
121
+ if (pred(xs[i])) {
122
+ return true
123
+ }
124
+ }
125
+ return false
126
+ }
127
+
128
+ /**
129
+ * Whether `pred` answers `true` for at least one element of `xs`, given each
130
+ * element and its index: what `xs.some(pred)` compiles to when `pred` takes
131
+ * two parameters.
132
+ *
133
+ * @param xs the array read; it is not changed.
134
+ * @param pred called in order, with the element and its index, until it answers `true`.
135
+ * @returns `true` when some element satisfies `pred`.
136
+ */
137
+ export const someIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): boolean => {
138
+ const n = xs.length
139
+ for (let i: number = 0; i < n && i < xs.length; i++) {
140
+ if (pred(xs[i], i)) {
141
+ return true
142
+ }
143
+ }
144
+ return false
145
+ }
146
+
147
+ /**
148
+ * Whether `pred` answers `true` for every element of `xs`, stopping at the
149
+ * first that does not: what `xs.every(pred)` compiles to when `pred` takes one
150
+ * parameter. An empty array answers `true`.
151
+ *
152
+ * @param xs the array read; it is not changed.
153
+ * @param pred called in order until it answers `false`.
154
+ * @returns `true` when no element fails `pred`.
155
+ */
156
+ export const every = <T>(xs: readonly T[], pred: (x: T) => boolean): boolean => {
157
+ const n = xs.length
158
+ for (let i: number = 0; i < n && i < xs.length; i++) {
159
+ if (!pred(xs[i])) {
160
+ return false
161
+ }
162
+ }
163
+ return true
164
+ }
165
+
166
+ /**
167
+ * Whether `pred` answers `true` for every element of `xs`, given each element
168
+ * and its index: what `xs.every(pred)` compiles to when `pred` takes two
169
+ * parameters.
170
+ *
171
+ * @param xs the array read; it is not changed.
172
+ * @param pred called in order, with the element and its index, until it answers `false`.
173
+ * @returns `true` when no element fails `pred`.
174
+ */
175
+ export const everyIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): boolean => {
176
+ const n = xs.length
177
+ for (let i: number = 0; i < n && i < xs.length; i++) {
178
+ if (!pred(xs[i], i)) {
179
+ return false
180
+ }
181
+ }
182
+ return true
183
+ }
184
+
185
+ /**
186
+ * The index of the first element of `xs` for which `pred` answers `true`:
187
+ * what `xs.findIndex(pred)` compiles to when `pred` takes one parameter.
188
+ *
189
+ * @param xs the array read; it is not changed.
190
+ * @param pred called in order until it answers `true`.
191
+ * @returns the first such index, or `-1` when there is none.
192
+ */
193
+ export const findIndex = <T>(xs: readonly T[], pred: (x: T) => boolean): number => {
194
+ const n = xs.length
195
+ for (let i: number = 0; i < n && i < xs.length; i++) {
196
+ if (pred(xs[i])) {
197
+ return i
198
+ }
199
+ }
200
+ return -1
201
+ }
202
+
203
+ /**
204
+ * The index of the first element of `xs` for which `pred` answers `true`,
205
+ * given each element and its index: what `xs.findIndex(pred)` compiles to when
206
+ * `pred` takes two parameters.
207
+ *
208
+ * @param xs the array read; it is not changed.
209
+ * @param pred called in order, with the element and its index, until it answers `true`.
210
+ * @returns the first such index, or `-1` when there is none.
211
+ */
212
+ export const findIndexIndexed = <T>(xs: readonly T[], pred: (x: T, i: number) => boolean): number => {
213
+ const n = xs.length
214
+ for (let i: number = 0; i < n && i < xs.length; i++) {
215
+ if (pred(xs[i], i)) {
216
+ return i
217
+ }
218
+ }
219
+ return -1
220
+ }
221
+
222
+ /**
223
+ * A copy of `xs[start..end)` in a new array: what `xs.slice(start, end)`
224
+ * compiles to, with string `slice`'s rule. The range must satisfy
225
+ * `0 <= start <= end <= xs.length`, and anything else panics with
226
+ * `slice out of range: [start, end) of length n` and exits 1, where
227
+ * JavaScript counts a negative end back from the length and clamps the rest.
228
+ * A float bound is truncated toward zero and saturates (NaN to 0, an infinity
229
+ * to the `i64` limit), natively and under Node alike.
230
+ *
231
+ * @param xs the array copied from; it is not changed.
232
+ * @param start the first index copied.
233
+ * @param end the index after the last copied.
234
+ * @returns a new array of `end - start` elements.
235
+ */
236
+ export const slice = <T>(xs: readonly T[], start: number, end: number): T[] => {
237
+ const from = toI64(start)
238
+ const to = toI64(end)
239
+ const len = toI64(xs.length)
240
+ if (from < 0 || from > to || to > len) {
241
+ panic(`slice out of range: [${from}, ${to}) of length ${len}`)
242
+ }
243
+ const out: T[] = []
244
+ for (let i: i32 = toI32(from); i >= 0 && i < toI32(to) && i < toI32(xs.length); i++) {
245
+ out.push(xs[i])
246
+ }
247
+ return out
248
+ }
249
+
250
+ /**
251
+ * A copy of `xs[start..)`: what `xs.slice(start)` compiles to. `start` must
252
+ * satisfy `0 <= start <= xs.length`, or the call panics as `slice` does.
253
+ *
254
+ * @param xs the array copied from; it is not changed.
255
+ * @param start the first index copied.
256
+ * @returns a new array of the elements from `start` on.
257
+ */
258
+ export const sliceFrom = <T>(xs: readonly T[], start: number): T[] => slice(xs, start, xs.length)
259
+
260
+ /**
261
+ * A copy of the whole of `xs`: what `xs.slice()` compiles to.
262
+ *
263
+ * @param xs the array copied; it is not changed.
264
+ * @returns a new array with the same elements.
265
+ */
266
+ export const sliceAll = <T>(xs: readonly T[]): T[] => slice(xs, 0, xs.length)