@amritk/nish-aarch64-linux 0.38.0 → 0.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
package/std/secret.ts CHANGED
@@ -1,44 +1,20 @@
1
1
  /**
2
- * `nish:secret` — key material, and the rules that keep it in
3
- * (docs/LANGUAGE.md, "Secrets").
2
+ * `nish:secret` — the source behind the builtin module.
4
3
  *
5
- * import { Secret, exposeWith, secret, wipe } from "nish:secret"
6
- * import { hmacSha256 } from "nish/crypto/hmac"
4
+ * **What the module means is documented once, in `runtime/nish.d.ts`**: the
5
+ * `declare module "nish:secret"` block there is what an editor shows and what
6
+ * `docs/reference/nish-secret.md` is generated from, and `docs/LANGUAGE.md`
7
+ * ("Secrets") holds the rules. The comments in this file say only how the
8
+ * module is built; change a meaning there, not here.
7
9
  *
8
- * const tag = (k: u8[], message: u8[]): u8[] => hmacSha256(k, message)
9
- *
10
- * const raw: u8[] = new Array<u8>(32)
11
- * crypto.getRandomValues(raw)
12
- * const key: Secret<u8[]> = secret(raw) // `raw` is moved: not read again
13
- * const message: u8[] = [1, 2, 3]
14
- * const mac: u8[] = exposeWith(key, message, tag)
15
- * wipe(key)
16
- *
17
- * **This file is the source behind the builtin module**, and it is imported
18
- * only by that name: `nish/secret` is refused, so there is one spelling for the
19
- * checker's rules to be read under. What is written here is the meaning; what
20
- * makes a `Secret` worth having is in `src/secret.ts`, which knows this module
21
- * by its path and package:
22
- *
23
- * - a `Secret` is opaque. Nothing outside this file reads its field, builds
24
- * one with `new`, prints it, interpolates it, compares it with anything but
25
- * another `Secret` or `null`, branches on it, indexes it, stores it in a
26
- * field, an array or a `Result`, or hands it to a builtin;
27
- * - a `Secret` a function makes leaves it returned or wiped, on every path;
28
- * - `expose` is the one way in, and the function it runs may reach no I/O and
29
- * no C, may not keep the value, may not write the argument `exposeWith`
30
- * hands it, and returns a declared type that holds no `Secret`;
31
- * - `wipe` is a volatile store of zeros over the value's whole storage,
32
- * which no optimiser may remove (`src/emit-secret.ts`).
33
- *
34
- * **Under Node the module is answered by `runtime/shim.mjs`**, where a
35
- * `Secret` is a plain wrapper and `wipe` zero-fills it.
10
+ * It is imported only by its builtin name: `nish/secret` is refused, so there
11
+ * is one spelling for the checker's rules to be read under. Those rules are
12
+ * `src/secret.ts`, which knows this module by its path and package, and the
13
+ * volatile store `wipe` lowers to is `src/emit-secret.ts`. Under Node the
14
+ * module is answered by `runtime/nish.mjs`.
36
15
  */
37
16
 
38
- /**
39
- * Key material: an array of integers (`u8[]`, `u32[]`, ...) or a record whose
40
- * every field is an integer. Made by `secret`, read only through `expose`.
41
- */
17
+ /** Key material, held opaque (`runtime/nish.d.ts`). Here, a box around one field. */
42
18
  export class Secret<T> {
43
19
  /** @internal Used by `expose` and `exposeWith`. The wrapped value. Only this module reads or writes it (`src/secret.ts`). */
44
20
  value: T
@@ -55,48 +31,39 @@ export class Secret<T> {
55
31
  }
56
32
 
57
33
  /**
58
- * `value`, wrapped. The argument is moved: a local handed in is not read again.
34
+ * `value`, wrapped (`runtime/nish.d.ts`). The box holds `value` itself, not a
35
+ * copy, so its storage is the storage `wipe` later zeroes.
59
36
  *
60
- * @param value the key material: an array of integers or a record whose every
61
- * field is an integer, that nothing else holds (NL2512).
62
- * @returns a `Secret` holding `value` itself, not a copy, so its storage is
63
- * the storage `wipe` later zeroes.
37
+ * @param value the key material, kept as it is.
38
+ * @returns the box.
64
39
  */
65
40
  export const secret = <T>(value: T): Secret<T> => new Secret<T>(value)
66
41
 
67
42
  /**
68
- * `f(value)`: the one way to compute with what a `Secret` holds.
43
+ * `f(value)` (`runtime/nish.d.ts`): the field read, the one this module makes.
69
44
  *
70
- * @param s the secret to read. It is not used up: it can be exposed again,
71
- * and is still to be wiped.
72
- * @param f the computation, handed the held value itself. The checker holds
73
- * it to the rules in the module header: no I/O, no C, it does not keep the
74
- * value, and its declared result type holds no `Secret`.
45
+ * @param s the box to read.
46
+ * @param f handed the held value itself.
75
47
  * @returns what `f` returns.
76
48
  */
77
49
  export const expose = <T, R>(s: Secret<T>, f: (value: T) => R): R => f(s.value)
78
50
 
79
51
  /**
80
- * `f(value, arg)`: `expose` with one more argument, because the arrow `expose`
81
- * runs captures nothing.
52
+ * `f(value, arg)` (`runtime/nish.d.ts`): `expose` with one more argument.
82
53
  *
83
- * @param s the secret to read, as for `expose`.
84
- * @param arg handed to `f` as its second argument. `f` may read it but not
85
- * write it.
86
- * @param f the computation, under the same rules as `expose`'s.
54
+ * @param s the box to read.
55
+ * @param arg handed to `f` as its second argument.
56
+ * @param f handed the held value itself and `arg`.
87
57
  * @returns what `f` returns.
88
58
  */
89
59
  export const exposeWith = <T, A, R>(s: Secret<T>, arg: A, f: (value: T, arg: A) => R): R => f(s.value, arg)
90
60
 
91
61
  /**
92
- * Zero every byte of `target`'s storage: a `Secret`'s value, or an array or
93
- * record of integers that `expose`'s function holds. Natively the compiler
94
- * gives each instance a body of its own, one volatile `llvm.memset`
62
+ * Zero every byte of `target`'s storage (`runtime/nish.d.ts`). Natively the
63
+ * compiler gives each instance a body of its own, one volatile `llvm.memset`
95
64
  * (`src/emit-secret.ts`); this one is never emitted.
96
65
  *
97
- * @param _target what to zero: a `Secret`, never a nullable one (narrow it
98
- * first), or an array or record of integers that `expose`'s function
99
- * holds.
66
+ * @param _target what to zero.
100
67
  */
101
68
  export const wipe = <T>(_target: T): void => {
102
69
  // Lowered by the compiler: see above.
package/std/synth.ts ADDED
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `nish/synth` — short sounds made from nothing: square, triangle and noise
3
+ * voices with a pitch slide and a decaying envelope, mixed into an array of
4
+ * `f64` samples. Nothing is sampled or copied; a sound is arithmetic.
5
+ *
6
+ * A sound starts as silence of its length and gains voices one at a time,
7
+ * each added into the samples already there:
8
+ *
9
+ * import { SYNTH_SQUARE, SYNTH_TRIANGLE, synthSemitone, synthSilence, synthTone } from "nish/synth";
10
+ *
11
+ * const RATE: i32 = 22050;
12
+ * const out: f64[] = synthSilence(0.2, RATE);
13
+ * synthTone(out, RATE, 0.0, 0.2, 440.0, 220.0, SYNTH_SQUARE, 0.25, 8.0);
14
+ * synthTone(out, RATE, 0.05, 0.1, synthSemitone(440.0, 7), synthSemitone(440.0, 7), SYNTH_TRIANGLE, 0.2, 12.0);
15
+ *
16
+ * The samples are not clipped: a voice stays inside `-volume..volume`, so
17
+ * voices whose volumes sum to at most 1 stay inside `-1..1`, and what plays
18
+ * them (a WAV writer, a page's audio buffer) clips the rest. The sample rate
19
+ * is the caller's, passed to every function, so one program can make sounds
20
+ * for a 22050 Hz file and a 48000 Hz page alike.
21
+ *
22
+ * Pure: no capability, no I/O and no clock. The noise voice is a fixed
23
+ * xorshift sequence, so the same call gives the same samples every time.
24
+ */
25
+
26
+ /** A square wave: +1 for the first half of each period, -1 for the second. */
27
+ export const SYNTH_SQUARE: i32 = 0
28
+
29
+ /** A triangle wave: a straight rise from -1 to +1 and a straight fall back. */
30
+ export const SYNTH_TRIANGLE: i32 = 1
31
+
32
+ /** Noise: a fresh random level each period of the pitch, so a falling pitch rumbles. */
33
+ export const SYNTH_NOISE: i32 = 2
34
+
35
+ /** The noise voice's starting state. */
36
+ const SYNTH_NOISE_SEED: i32 = 22695477
37
+
38
+ /** A position or length in samples past this is refused rather than converted. */
39
+ const SYNTH_SAMPLE_LIMIT: f64 = 2147483647.0
40
+
41
+ /**
42
+ * `seconds` of silence: an array of zero samples, one at least.
43
+ *
44
+ * @param seconds - how long; zero, negative or NaN is one sample
45
+ * @param sampleRate - samples a second
46
+ * @returns `seconds × sampleRate` samples of 0.0, at least one
47
+ */
48
+ export const synthSilence = (seconds: f64, sampleRate: i32): f64[] => {
49
+ const want: f64 = seconds * toF64(sampleRate)
50
+ const n: i32 = want >= 1.0 && want < SYNTH_SAMPLE_LIMIT ? toI32(want) : 1
51
+ const out: f64[] = new Array<f64>(n)
52
+ out.fill(0.0)
53
+ return out
54
+ }
55
+
56
+ /** The next value of the noise voice's xorshift generator. */
57
+ const synthXorshift = (x: i32): i32 => {
58
+ let y: i32 = x ^ (x << 13)
59
+ y = y ^ (y >> 17)
60
+ return y ^ (y << 5)
61
+ }
62
+
63
+ /**
64
+ * Add a voice into `out` from `start` seconds for `length` seconds. Its pitch
65
+ * slides from `f0` to `f1` Hz on a log scale, and its loudness starts at
66
+ * `volume` and falls by a factor of e every `1 / decay` seconds. A 2 ms attack
67
+ * and a 5 ms release keep the ends from clicking. The voice stops at the end
68
+ * of `out`; it never grows the array.
69
+ *
70
+ * Nothing is added for a sample rate, start or length that is not positive
71
+ * (a start of 0 is fine), for a frequency that is not positive, or for a
72
+ * start or length too long to count in samples.
73
+ *
74
+ * @param out - the samples to add into
75
+ * @param sampleRate - samples a second that `out` is at
76
+ * @param start - where the voice begins, in seconds from the first sample
77
+ * @param length - how long the voice lasts, in seconds
78
+ * @param f0 - the starting pitch in Hz
79
+ * @param f1 - the ending pitch in Hz
80
+ * @param wave - `SYNTH_SQUARE`, `SYNTH_TRIANGLE` or `SYNTH_NOISE`; any other value is noise
81
+ * @param volume - the starting peak level; a negative level inverts the wave
82
+ * @param decay - how fast the level falls, per second; 0 holds it
83
+ */
84
+ export const synthTone = (
85
+ out: f64[],
86
+ sampleRate: i32,
87
+ start: f64,
88
+ length: f64,
89
+ f0: f64,
90
+ f1: f64,
91
+ wave: i32,
92
+ volume: f64,
93
+ decay: f64
94
+ ): void => {
95
+ const rate: f64 = toF64(sampleRate)
96
+ if (!(rate > 0.0 && start >= 0.0 && length > 0.0 && f0 > 0.0 && f1 > 0.0)) {
97
+ return
98
+ }
99
+ if (!(start * rate < SYNTH_SAMPLE_LIMIT && length * rate < SYNTH_SAMPLE_LIMIT)) {
100
+ return
101
+ }
102
+ const from: i32 = toI32(start * rate)
103
+ const n: i32 = toI32(length * rate)
104
+ const ratio: f64 = Math.log(f1 / f0)
105
+ let phase: f64 = 0.0
106
+ let noise: i32 = SYNTH_NOISE_SEED
107
+ let held: f64 = 0.0
108
+ for (let i: i32 = 0; i < n && from + i < toI32(out.length); i++) {
109
+ const t: f64 = toF64(i) / rate
110
+ const f: f64 = f0 * Math.exp((ratio * toF64(i)) / toF64(n))
111
+ const before: f64 = phase
112
+ phase = phase + f / rate
113
+ if (phase >= 1.0) {
114
+ phase = phase - Math.floor(phase)
115
+ }
116
+ let v: f64 = 0.0
117
+ if (wave === SYNTH_SQUARE) {
118
+ v = phase < 0.5 ? 1.0 : -1.0
119
+ } else if (wave === SYNTH_TRIANGLE) {
120
+ const rise: f64 = 4.0 * phase
121
+ v = phase < 0.5 ? rise - 1.0 : 3.0 - rise
122
+ } else {
123
+ if (phase < before || i === 0) {
124
+ noise = synthXorshift(noise)
125
+ held = toF64(noise & 65535) / 32767.5 - 1.0
126
+ }
127
+ v = held
128
+ }
129
+ const attack: f64 = Math.min(t / 0.002, 1.0)
130
+ const release: f64 = Math.min((length - t) / 0.005, 1.0)
131
+ out[from + i] = out[from + i] + v * volume * attack * release * Math.exp(-t * decay)
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The frequency `semitones` equal-tempered steps above `base`.
137
+ *
138
+ * @param base - the starting frequency in Hz
139
+ * @param semitones - how many steps up; negative steps go down
140
+ * @returns `base × 2^(semitones / 12)`
141
+ */
142
+ export const synthSemitone = (base: f64, semitones: i32): f64 =>
143
+ base * Math.exp((toF64(semitones) * Math.log(2.0)) / 12.0)
package/std/text.ts CHANGED
@@ -243,6 +243,239 @@ export const split = (text: string, sep: string): string[] => {
243
243
  }
244
244
  }
245
245
 
246
+ /**
247
+ * The first `limit` pieces of `text` between the occurrences of `sep`:
248
+ * JavaScript's `text.split(sep, limit)`. The pieces past the limit are
249
+ * dropped, not joined into the last one, so `splitLimit("a,b,c", ",", 2)` is `["a", "b"]`, and a
250
+ * limit of 0 gives `[]`.
251
+ *
252
+ * **A negative limit keeps every piece**, as it does under Node: JavaScript
253
+ * reads the limit with `ToUint32`, so `-1` is 4294967295, and any negative
254
+ * `i32` is at least 2147483648 there, more pieces than a string can split
255
+ * into. So `splitLimit(text, sep, -1)` is `split(text, sep)`, and the two
256
+ * readings agree on every `i32`. Refusing a negative limit would have been a
257
+ * panic where JavaScript answers.
258
+ *
259
+ * **An empty separator panics**, whatever the limit, for the reason `split`
260
+ * gives; JavaScript would answer `[]` for a limit of 0, and its UTF-16 units
261
+ * otherwise.
262
+ *
263
+ * @param text The text to split.
264
+ * @param sep The separator, compared byte for byte; it must not be empty.
265
+ * Occurrences are found left to right and do not overlap.
266
+ * @param limit The most pieces kept; a negative one keeps them all.
267
+ * @returns A fresh array of at most `limit` pieces, in order.
268
+ */
269
+ export const splitLimit = (text: string, sep: string, limit: i32): string[] => {
270
+ const sepLength: i32 = toI32(sep.length)
271
+ if (sepLength === 0) {
272
+ panic("splitLimit: an empty separator")
273
+ }
274
+ const length: i32 = toI32(text.length)
275
+ const parts: string[] = []
276
+ if (limit === 0) {
277
+ return parts
278
+ }
279
+ let start: i32 = 0
280
+ while (true) {
281
+ // Searching from `start` rather than cutting `text` down after each match
282
+ // copies nothing until the piece is taken.
283
+ const at: i32 = toI32(text.indexOf(sep, start))
284
+ // `start` is 0 or one past a match, so it is never negative and never
285
+ // past `length`, and a hit starts at or after `start` and a whole
286
+ // separator before `length`. The tests around the `substring`s therefore
287
+ // always hold, but for the empty tail after a final separator; they are
288
+ // written because they are what proves both bounds within `text`, as in
289
+ // `splitLines`.
290
+ if (at < 0) {
291
+ parts.push(start >= 0 && start < length ? text.substring(start, length) : "")
292
+ return parts
293
+ }
294
+ if (start >= 0 && start < length && at >= 0 && at < length) {
295
+ parts.push(text.substring(start, at))
296
+ }
297
+ if (toI32(parts.length) === limit) {
298
+ return parts
299
+ }
300
+ start = at + sepLength
301
+ }
302
+ }
303
+
304
+ /** The most digits `toFixed` takes after the point; JavaScript throws a `RangeError` past it. */
305
+ const TO_FIXED_MAX_DIGITS: i32 = 100
306
+
307
+ /** Where `toFixed` stops writing fixed notation and answers `String(x)`, as JavaScript does. */
308
+ const TO_FIXED_LIMIT: f64 = 1e21
309
+
310
+ /** 2^52 and 2^53: an `f64` from the first up to the second is an integer, and its whole significand. */
311
+ const TWO_TO_52: f64 = 4503599627370496
312
+ const TWO_TO_53: f64 = 9007199254740992
313
+
314
+ /** The byte `0`; a decimal digit `d` is written as this plus `d`. */
315
+ const ASCII_ZERO: i32 = 48
316
+
317
+ /** The byte `.`. */
318
+ const ASCII_DOT: i32 = 46
319
+
320
+ /** The byte `-`. */
321
+ const ASCII_MINUS: i32 = 45
322
+
323
+ /**
324
+ * `digits`, a decimal number with its units digit first, halved in place,
325
+ * reading only its lowest `count` digits (the rest are zero). The answer is
326
+ * the bit the halving dropped, 0 or 1.
327
+ *
328
+ * It is written with `>>` and `&` rather than `/` and `%` because under Node
329
+ * an `i32` is a JavaScript number, and `/` there would give a fraction. The
330
+ * name is long for the reason `isTextBlankByte`'s is.
331
+ */
332
+ const fixedDigitsHalve = (digits: i32[], count: i32): i32 => {
333
+ let carry: i32 = 0
334
+ let i: i32 = count - 1
335
+ while (i >= 0 && i < toI32(digits.length)) {
336
+ const value: i32 = carry * 10 + digits[i]
337
+ digits[i] = value >> 1
338
+ carry = value & 1
339
+ i -= 1
340
+ }
341
+ return carry
342
+ }
343
+
344
+ /**
345
+ * `digits`, a decimal number with its units digit first, doubled in place when
346
+ * `doubling` is set, and then with `amount`, 0 or 1, added at the units. The
347
+ * array grows by a digit when the answer carries out of the top. The name is
348
+ * long for the reason `isTextBlankByte`'s is.
349
+ */
350
+ const fixedDigitsAdd = (digits: i32[], doubling: boolean, amount: i32): void => {
351
+ let carry: i32 = amount
352
+ let i: i32 = 0
353
+ const length: i32 = toI32(digits.length)
354
+ while (i < length) {
355
+ const value: i32 = (doubling ? digits[i] * 2 : digits[i]) + carry
356
+ digits[i] = value >= 10 ? value - 10 : value
357
+ carry = value >= 10 ? 1 : 0
358
+ i += 1
359
+ }
360
+ if (carry > 0) {
361
+ digits.push(carry)
362
+ }
363
+ }
364
+
365
+ /**
366
+ * `x` written with exactly `digits` digits after the point: JavaScript's
367
+ * `x.toFixed(digits)`, and the same text natively and under Node.
368
+ *
369
+ * The answer is the decimal closest to the **exact binary value** of `x`, and
370
+ * a tie between two takes the larger, as ECMA-262 says. That is not rounding
371
+ * the shortest printed decimal: `1.005` is stored as a little less than
372
+ * 1.005, so `toFixed(1.005, 2)` is `"1.00"`, while `2.5` is exact and a tie, so
373
+ * `toFixed(2.5, 0)` is `"3"` and `toFixed(-2.5, 0)` is `"-3"`. The digits are
374
+ * worked out in full, one decimal digit per array element, so the value is
375
+ * never rounded on the way; that is why this is written here and not with a
376
+ * multiplication by a power of ten, which rounds twice.
377
+ *
378
+ * The edges are JavaScript's. `NaN` gives `"NaN"`. `x` at or beyond 1e21 in
379
+ * size gives `String(x)`, the text a template hole gives, so
380
+ * `toFixed(1e21, 2)` is `"1e+21"`, and the infinities give `"Infinity"` and
381
+ * `"-Infinity"`. `-0` loses its sign, `"0.00"`, but a negative value that
382
+ * rounds to zero keeps it: `toFixed(-0.0001, 2)` is `"-0.00"`.
383
+ *
384
+ * **`digits` outside 0 to 100 panics**, where JavaScript throws a
385
+ * `RangeError`: the count is almost always a literal the caller chose, so a
386
+ * bad one is a mistake in the program, as `split`'s empty separator is.
387
+ *
388
+ * @param x The number to write.
389
+ * @param digits How many digits to write after the point, from 0 to 100; with
390
+ * 0 there is no point.
391
+ * @returns `x` in fixed notation, or `String(x)` when `x` is NaN or at least
392
+ * 1e21 in size.
393
+ */
394
+ export const toFixed = (x: f64, digits: i32): string => {
395
+ if (digits < 0 || digits > TO_FIXED_MAX_DIGITS) {
396
+ panic("toFixed: digits must be 0 to 100")
397
+ }
398
+ // biome-ignore lint/suspicious/noSelfCompare: NaN is the only value that is not itself; Nish has no Number.isNaN
399
+ if (x !== x || x >= TO_FIXED_LIMIT || x <= -TO_FIXED_LIMIT) {
400
+ return `${x}`
401
+ }
402
+ const negative: boolean = x < 0
403
+ // `x` is `m * 2^exponent` for an integer `m` below 2^53: scaling it into
404
+ // [2^52, 2^53) by twos is exact, a subnormal included, and says `exponent`.
405
+ let m: f64 = negative ? -x : x
406
+ let exponent: i32 = 0
407
+ if (m > 0) {
408
+ while (m < TWO_TO_52) {
409
+ m *= 2
410
+ exponent -= 1
411
+ }
412
+ while (m >= TWO_TO_53) {
413
+ m /= 2
414
+ exponent += 1
415
+ }
416
+ }
417
+ // The number written is `m * 10^digits * 2^exponent`, rounded to an
418
+ // integer, with its last `digits` digits after the point. Multiplying by
419
+ // `10^digits` is that many zeros under the units; `m`'s own digits are exact
420
+ // to take out, since every step stays an integer below 2^53.
421
+ const decimal: i32[] = []
422
+ let i: i32 = 0
423
+ while (i < digits) {
424
+ decimal.push(0)
425
+ i += 1
426
+ }
427
+ while (m > 0) {
428
+ const last: f64 = m % 10
429
+ decimal.push(toI32(last))
430
+ m = (m - last) / 10
431
+ }
432
+ while (exponent > 0) {
433
+ fixedDigitsAdd(decimal, true, 0)
434
+ exponent -= 1
435
+ }
436
+ // A negative exponent halves the number that many times. The integer part
437
+ // is what is left; it rounds up exactly when the last bit dropped is 1,
438
+ // which is a remainder of at least a half, a tie included. Once the number
439
+ // is zero every bit still to drop is zero too, so the walk stops there.
440
+ let count: i32 = toI32(decimal.length)
441
+ let dropped: i32 = 0
442
+ while (exponent < 0 && count > 0) {
443
+ dropped = fixedDigitsHalve(decimal, count)
444
+ while (count > 0 && count <= toI32(decimal.length) && decimal[count - 1] === 0) {
445
+ count -= 1
446
+ }
447
+ exponent += 1
448
+ }
449
+ if (exponent === 0 && dropped === 1) {
450
+ fixedDigitsAdd(decimal, false, 1)
451
+ }
452
+ while (toI32(decimal.length) <= digits) {
453
+ decimal.push(0)
454
+ }
455
+ // The text is the digits from the highest that is not zero down, but never
456
+ // from below the units, which is index `digits`; the halving leaves zeros
457
+ // above the number. The point goes before the last `digits` of them, and a
458
+ // minus in front of any negative `x`.
459
+ let at: i32 = toI32(decimal.length) - 1
460
+ while (at > digits && at >= 0 && at < toI32(decimal.length) && decimal[at] === 0) {
461
+ at -= 1
462
+ }
463
+ const bytes: u8[] = []
464
+ if (negative) {
465
+ bytes.push(toU8(ASCII_MINUS))
466
+ }
467
+ while (at >= 0 && at < toI32(decimal.length)) {
468
+ // Read before the pushes: a push may move an array, so it ends the proof.
469
+ const digit: i32 = decimal[at]
470
+ if (at === digits - 1) {
471
+ bytes.push(toU8(ASCII_DOT))
472
+ }
473
+ bytes.push(toU8(ASCII_ZERO + digit))
474
+ at -= 1
475
+ }
476
+ return String.fromBytes(bytes, 0, toI32(bytes.length))
477
+ }
478
+
246
479
  /**
247
480
  * `text` with every occurrence of `needle` replaced by `replacement`.
248
481
  *