nish 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +1 -1
  2. package/docs/AI.md +18 -16
  3. package/docs/INSTALL.md +3 -1
  4. package/package.json +5 -5
  5. package/runtime/core/numbers.mjs +3 -1
  6. package/runtime/core/strings.mjs +90 -38
  7. package/runtime/core.d.ts +8 -0
  8. package/runtime/core.mjs +16 -0
  9. package/runtime/nish.d.ts +88 -5
  10. package/runtime/nish.h +10 -0
  11. package/runtime/nish.mjs +5 -0
  12. package/runtime/runtime-host.c +15 -0
  13. package/runtime/runtime-net.c +223 -4
  14. package/runtime/runtime-os.c +15 -1
  15. package/runtime/runtime-uring.c +291 -31
  16. package/runtime/sqlite/nish-sqlite.c +301 -128
  17. package/std/README.md +15 -15
  18. package/std/array.ts +10 -2
  19. package/std/bytes.ts +239 -26
  20. package/std/cli-args.ts +1072 -606
  21. package/std/cli-flags.ts +180 -98
  22. package/std/cli.ts +21 -13
  23. package/std/collections.ts +245 -127
  24. package/std/compress/checksum.ts +32 -37
  25. package/std/compress/deflate.ts +1102 -542
  26. package/std/compress/gzip.ts +290 -145
  27. package/std/compress/zlib.ts +57 -21
  28. package/std/crypto/aes.ts +153 -75
  29. package/std/crypto/base64url.ts +84 -61
  30. package/std/crypto/bcrypt-batch.ts +164 -90
  31. package/std/crypto/bcrypt.ts +185 -107
  32. package/std/crypto/chacha20poly1305.ts +84 -68
  33. package/std/crypto/ct.ts +9 -7
  34. package/std/crypto/ed25519.ts +64 -27
  35. package/std/crypto/hkdf.ts +105 -63
  36. package/std/crypto/hmac.ts +95 -89
  37. package/std/crypto/jwt.ts +248 -126
  38. package/std/crypto/p256.ts +758 -444
  39. package/std/crypto/p384.ts +20 -13
  40. package/std/crypto/pki-roots.ts +95 -38
  41. package/std/crypto/pki.ts +164 -60
  42. package/std/crypto/rsa.ts +266 -223
  43. package/std/crypto/scram.ts +3 -4
  44. package/std/crypto/sha1.ts +107 -65
  45. package/std/crypto/sha256.ts +502 -422
  46. package/std/crypto/sha512.ts +204 -135
  47. package/std/crypto/x509-random.ts +9 -3
  48. package/std/crypto/x509.ts +331 -171
  49. package/std/json-equal.ts +35 -19
  50. package/std/json-format.ts +215 -108
  51. package/std/json-number.ts +126 -72
  52. package/std/json-pointer.ts +42 -13
  53. package/std/json-tokenizer.ts +498 -307
  54. package/std/json-typed.ts +115 -36
  55. package/std/json-value.ts +341 -152
  56. package/std/json.ts +300 -158
  57. package/std/net/buffer-pool.ts +17 -7
  58. package/std/net/dns-config.ts +427 -236
  59. package/std/net/dns-message.ts +114 -47
  60. package/std/net/dns-resolver.ts +736 -237
  61. package/std/net/dns.ts +205 -52
  62. package/std/net/fetch.ts +320 -184
  63. package/std/net/grpc.ts +948 -0
  64. package/std/net/handler.ts +1315 -222
  65. package/std/net/hpack.ts +395 -180
  66. package/std/net/http-compress.ts +502 -65
  67. package/std/net/http-fields.ts +85 -49
  68. package/std/net/http-server.ts +1764 -602
  69. package/std/net/http1-client-codec.ts +372 -161
  70. package/std/net/http1-codec.ts +665 -331
  71. package/std/net/http1-server.ts +660 -278
  72. package/std/net/http2-cleartext.ts +165 -95
  73. package/std/net/http2-frame.ts +232 -89
  74. package/std/net/http2-tls.ts +42 -12
  75. package/std/net/http2.ts +327 -101
  76. package/std/net/http3-frame.ts +68 -33
  77. package/std/net/http3-server.ts +647 -192
  78. package/std/net/http3.ts +667 -189
  79. package/std/net/oidc.ts +63 -24
  80. package/std/net/outbound.ts +207 -142
  81. package/std/net/postgres-async.ts +1165 -443
  82. package/std/net/postgres-carrier.ts +575 -372
  83. package/std/net/postgres.ts +1459 -559
  84. package/std/net/prefork.ts +254 -98
  85. package/std/net/protobuf.ts +1017 -0
  86. package/std/net/qpack.ts +143 -92
  87. package/std/net/quic-conn-ack.ts +50 -18
  88. package/std/net/quic-conn-cid.ts +66 -26
  89. package/std/net/quic-conn-params.ts +13 -7
  90. package/std/net/quic-datagram.ts +90 -27
  91. package/std/net/quic-frame.ts +225 -124
  92. package/std/net/quic-listener.ts +197 -89
  93. package/std/net/quic-packet.ts +289 -163
  94. package/std/net/quic-recovery.ts +279 -128
  95. package/std/net/quic-stream.ts +466 -167
  96. package/std/net/quic.ts +568 -257
  97. package/std/net/router.ts +450 -99
  98. package/std/net/serve.ts +651 -232
  99. package/std/net/static.ts +1458 -0
  100. package/std/net/tls/client.ts +140 -45
  101. package/std/net/tls/codec.ts +510 -260
  102. package/std/net/tls/record-client.ts +268 -76
  103. package/std/net/tls/record-server.ts +236 -79
  104. package/std/net/tls/record.ts +173 -47
  105. package/std/net/tls/schedule.ts +58 -39
  106. package/std/net/tls/ticket.ts +295 -103
  107. package/std/net/tls/verify.ts +1 -1
  108. package/std/net/tls-tcp.ts +218 -75
  109. package/std/net/tls.ts +260 -152
  110. package/std/net/upstream.ts +283 -86
  111. package/std/net/url.ts +277 -102
  112. package/std/net/websocket.ts +370 -186
  113. package/std/net/webtransport.ts +755 -436
  114. package/std/regex.ts +1659 -829
  115. package/std/sqlite.ts +171 -0
  116. package/std/sync/ring.ts +320 -156
  117. package/std/sync/shm.ts +53 -6
  118. package/std/text.ts +205 -124
  119. package/std/threads.ts +22 -2
package/std/json.ts CHANGED
@@ -112,7 +112,7 @@
112
112
  * (`docs/wp26-stdlib.md` §4).
113
113
  */
114
114
 
115
- import { copyBytes, skipJsonPlain } from "nish/bytes"
115
+ import { skipJsonPlain, tryCopyBytes } from "nish/bytes"
116
116
 
117
117
  const JSON_BACKSPACE: i32 = 8
118
118
  const JSON_TAB: i32 = 9
@@ -148,8 +148,6 @@ const JSON_UTF8_LOW_SIX: i32 = 63
148
148
  /** The first code point that needs two UTF-8 bytes, and the first that needs three. */
149
149
  const JSON_UTF8_TWO_BYTE_FLOOR: i32 = 128
150
150
  const JSON_UTF8_THREE_BYTE_FLOOR: i32 = 2048
151
- /** The base `jsonHex4` accumulates in. */
152
- const JSON_HEX_BASE: i32 = 16
153
151
 
154
152
  /** The four bytes JSON allows between tokens. */
155
153
  const jsonIsBlankByte = (code: i32): boolean =>
@@ -206,8 +204,9 @@ const jsonClosingQuote = (text: string, start: i32): i32 => {
206
204
  return -1
207
205
  }
208
206
  let quote: i32 = toI32(text.indexOf('"', start))
209
- // `quote >= start` is false for the `-1` of a miss.
210
- while (quote >= start && quote < length) {
207
+ // `quote >= start` is false for the `-1` of a miss, and implies `quote >= 0`,
208
+ // which is spelled out because the bounds proof does not chain the two.
209
+ while (quote >= 0 && quote >= start && quote < length) {
211
210
  // The count stops at the opening quote at the latest, so `j >= 0` always
212
211
  // holds, and `j < length` does because `j` starts below `quote`; both are
213
212
  // spelled out because the bounds proof reads neither from a decrement of a
@@ -216,7 +215,9 @@ const jsonClosingQuote = (text: string, start: i32): i32 => {
216
215
  while (j >= 0 && j < length && toI32(text.charCodeAt(j)) === JSON_BACKSLASH) {
217
216
  j -= 1
218
217
  }
219
- if (((quote - 1 - j) & 1) === 0) {
218
+ // The run of backslashes is `quote - 1 - j` long, which is even exactly
219
+ // when `quote` and `j` differ in their lowest bit.
220
+ if (((quote ^ j) & 1) === 1) {
220
221
  return quote
221
222
  }
222
223
  quote = toI32(text.indexOf('"', quote + 1))
@@ -235,15 +236,20 @@ const jsonClosingQuote = (text: string, start: i32): i32 => {
235
236
  */
236
237
  const jsonEndOfString = (text: string, at: i32): i32 => {
237
238
  const length: i32 = toI32(text.length)
238
- if (at < 0) {
239
+ if (at < 0 || at >= length) {
239
240
  return -1
240
241
  }
241
- const stop: i32 = at + 1 + JSON_INLINE_SCAN < length ? at + 1 + JSON_INLINE_SCAN : length
242
242
  let i: i32 = at + 1
243
+ // The sum is below `length` where it is taken, so it cannot wrap.
244
+ const stop: i32 = i < length - JSON_INLINE_SCAN ? toI32(toU32(i) + toU32(JSON_INLINE_SCAN)) : length
243
245
  // `i < length` follows from `i < stop`, and is there for the bounds proof.
244
246
  while (i < stop && i < length) {
245
247
  const code: i32 = toI32(text.charCodeAt(i))
246
248
  if (code === JSON_BACKSLASH) {
249
+ // A backslash in the last two bytes leaves no byte for a closing quote.
250
+ if (i >= length - 2) {
251
+ return -1
252
+ }
247
253
  i += 2
248
254
  continue
249
255
  }
@@ -256,7 +262,8 @@ const jsonEndOfString = (text: string, at: i32): i32 => {
256
262
  return -1
257
263
  }
258
264
  const quote: i32 = jsonClosingQuote(text, i)
259
- return quote < 0 ? -1 : quote + 1
265
+ // An index of `text`, so one past it cannot wrap.
266
+ return quote < 0 ? -1 : toI32(toU32(quote) + 1)
260
267
  }
261
268
 
262
269
  /**
@@ -284,7 +291,11 @@ const jsonEndOfValue = (text: string, at: i32): i32 => {
284
291
  }
285
292
  const first: i32 = toI32(text.charCodeAt(at))
286
293
  if (first === JSON_QUOTE || first === JSON_OPEN_BRACE || first === JSON_OPEN_BRACKET) {
287
- let depth: i32 = 0
294
+ // Unsigned, because it cannot wrap either way: each opener is a byte of
295
+ // `text`, so the count stays below `length`, and a closer is only ever met
296
+ // at depth 1 or more, since the value's first byte is the only one read at
297
+ // depth 0 and is an opener or a quote.
298
+ let depth: u32 = 0
288
299
  let i: i32 = at
289
300
  // `i >= 0` always holds — `i` starts at `at` and only moves forward — and
290
301
  // is in the test because a long string moves `i` to where
@@ -293,12 +304,17 @@ const jsonEndOfValue = (text: string, at: i32): i32 => {
293
304
  while (i >= 0 && i < length) {
294
305
  const code: i32 = toI32(text.charCodeAt(i))
295
306
  if (code === JSON_QUOTE) {
296
- const stop: i32 = i + 1 + JSON_INLINE_SCAN < length ? i + 1 + JSON_INLINE_SCAN : length
297
307
  let j: i32 = i + 1
308
+ // The sum is below `length` where it is taken, so it cannot wrap.
309
+ const stop: i32 = j < length - JSON_INLINE_SCAN ? toI32(toU32(j) + toU32(JSON_INLINE_SCAN)) : length
298
310
  let close: i32 = -1
299
311
  while (j < stop && j < length) {
300
312
  const inner: i32 = toI32(text.charCodeAt(j))
301
313
  if (inner === JSON_BACKSLASH) {
314
+ // A backslash in the last two bytes leaves no byte for a closing quote.
315
+ if (j >= length - 2) {
316
+ return -1
317
+ }
302
318
  j += 2
303
319
  continue
304
320
  }
@@ -317,10 +333,12 @@ const jsonEndOfValue = (text: string, at: i32): i32 => {
317
333
  return -1
318
334
  }
319
335
  }
336
+ // An index of `text`, so one past it cannot wrap.
337
+ const after: i32 = toI32(toU32(close) + 1)
320
338
  if (depth === 0) {
321
- return close + 1
339
+ return after
322
340
  }
323
- i = close + 1
341
+ i = after
324
342
  continue
325
343
  }
326
344
  if (code === JSON_OPEN_BRACE || code === JSON_OPEN_BRACKET) {
@@ -365,20 +383,22 @@ const jsonHexDigit = (code: i32): i32 => {
365
383
 
366
384
  /** The four hex digits at `at` as one code point, or `-1` when they are not four hex digits. */
367
385
  const jsonHex4 = (text: string, at: i32, end: i32): i32 => {
368
- if (at + 4 > end) {
386
+ // Fewer than four bytes before `end`; with `at >= 0`, every `end` below 4 is.
387
+ // Both callers pass `at >= 0` and `end <= text.length`, and the guard says so
388
+ // because it is what proves the four reads below in range.
389
+ if (at < 0 || end < 4 || end > toI32(text.length) || at > end - 4) {
369
390
  return -1
370
391
  }
371
- let value: i32 = 0
372
- let i: i32 = 0
373
- while (i < 4) {
374
- const digit: i32 = jsonHexDigit(toI32(text.charCodeAt(at + i)))
375
- if (digit < 0) {
376
- return -1
377
- }
378
- value = value * JSON_HEX_BASE + digit
379
- i += 1
392
+ const d0: i32 = jsonHexDigit(toI32(text.charCodeAt(at)))
393
+ const d1: i32 = jsonHexDigit(toI32(text.charCodeAt(at + 1)))
394
+ const d2: i32 = jsonHexDigit(toI32(text.charCodeAt(at + 2)))
395
+ const d3: i32 = jsonHexDigit(toI32(text.charCodeAt(at + 3)))
396
+ // A digit is 0 to 15 and a miss is `-1`, so the `or` is negative exactly
397
+ // when one of them missed, and the shifts place four nibbles without overlap.
398
+ if ((d0 | d1 | d2 | d3) < 0) {
399
+ return -1
380
400
  }
381
- return value
401
+ return (d0 << 12) | (d1 << 8) | (d2 << 4) | d3
382
402
  }
383
403
 
384
404
  /**
@@ -420,7 +440,9 @@ const jsonUtf8Width = (code: i32): i32 => {
420
440
  * byte at a time, for a caller that compares the bytes rather than keeps them.
421
441
  */
422
442
  const jsonUtf8Byte = (code: i32, width: i32, k: i32): i32 => {
423
- if (width === 1) {
443
+ // `width` is 1, 2 or 3; `<= 1` reads the same and keeps `width - 1` below
444
+ // from wrapping.
445
+ if (width <= 1) {
424
446
  return code
425
447
  }
426
448
  if (k === 0) {
@@ -448,9 +470,10 @@ const jsonUtf8Byte = (code: i32, width: i32, k: i32): i32 => {
448
470
  */
449
471
  const jsonUnescape = (text: string, at: i32, end: i32): string => {
450
472
  // Both callers pass the inside of a literal the scanners found, so
451
- // `0 <= at` and `end <= text.length` always hold. Saying so here is what
452
- // proves every read below in range and drops the `substring` clamps.
453
- if (at < 0 || end > toI32(text.length)) {
473
+ // `0 <= at <= end <= text.length` always holds. Saying so here (the proof
474
+ // reads `end >= 0` from its own test, not from `at`) is what proves every
475
+ // read and step below in range and drops the `substring` clamps.
476
+ if (at < 0 || end < 0 || end > toI32(text.length)) {
454
477
  return ""
455
478
  }
456
479
  let i: i32 = at
@@ -475,9 +498,14 @@ const jsonUnescape = (text: string, at: i32, end: i32): string => {
475
498
  if (start >= 0 && start < i) {
476
499
  parts.push(text.substring(start, i))
477
500
  }
478
- // A trailing backslash has nothing after it: `0` is no escape letter, so it
479
- // falls to the default below and stands for itself.
480
- const letter: i32 = i + 1 < end ? toI32(text.charCodeAt(i + 1)) : 0
501
+ // A trailing backslash has nothing after it, and stands for itself.
502
+ if (i + 1 >= end) {
503
+ parts.push("\\")
504
+ i += 1
505
+ start = i
506
+ continue
507
+ }
508
+ const letter: i32 = toI32(text.charCodeAt(i + 1))
481
509
  if (letter === 110) {
482
510
  parts.push("\n")
483
511
  i += 2
@@ -494,17 +522,21 @@ const jsonUnescape = (text: string, at: i32, end: i32): string => {
494
522
  parts.push(String.fromCharCode(12))
495
523
  i += 2
496
524
  } else if (letter === 117) {
497
- const code: i32 = jsonHex4(text, i + 2, end)
498
- if (code < 0) {
525
+ // `jsonHex4` answers `-1` for fewer than four bytes after the `u`; the
526
+ // room is tested here too because it is what proves the step past them.
527
+ const code: i32 = i < end - 5 ? jsonHex4(text, i + 2, end) : -1
528
+ if (code >= 0 && i < end - 5) {
529
+ parts.push(jsonUtf8(code))
530
+ i += 6
531
+ } else {
499
532
  // Not four hex digits after the `u`: the escape is broken, and copying it
500
533
  // through unchanged is the reading that loses nothing.
501
534
  parts.push("\\u")
502
535
  i += 2
503
- } else {
504
- parts.push(jsonUtf8(code))
505
- i += 6
506
536
  }
507
537
  } else if (letter === 0) {
538
+ // A NUL after the backslash: the backslash stands for itself, as a
539
+ // trailing one does, and the NUL is read next as a byte of its own.
508
540
  parts.push("\\")
509
541
  i += 1
510
542
  } else {
@@ -537,12 +569,20 @@ const jsonNameHas = (name: string, j: i32, code: i32): boolean =>
537
569
  const jsonKeyEquals = (text: string, at: i32, end: i32, name: string): boolean => {
538
570
  // `jsonUnescape`'s guard, for the same reason: every caller passes the
539
571
  // inside of a key `jsonReadMember` found with `jsonEndOfString`.
540
- if (at < 0 || end > toI32(text.length)) {
572
+ if (at < 0 || end < 0 || end > toI32(text.length)) {
541
573
  return false
542
574
  }
575
+ const nameLength: i32 = toI32(name.length)
543
576
  let i: i32 = at
544
577
  let j: i32 = 0
545
578
  while (i < end) {
579
+ // Every step below matches at least one more byte of `name`, so a `j`
580
+ // already at its end is a mismatch whatever comes next. `j >= 0` always
581
+ // holds and is spelled out for the bounds proof, as is the test, which
582
+ // the `jsonNameHas` below would answer the same way.
583
+ if (j < 0 || j >= nameLength) {
584
+ return false
585
+ }
546
586
  const code: i32 = toI32(text.charCodeAt(i))
547
587
  if (code !== JSON_BACKSLASH) {
548
588
  if (!jsonNameHas(name, j, code)) {
@@ -552,11 +592,26 @@ const jsonKeyEquals = (text: string, at: i32, end: i32, name: string): boolean =
552
592
  j += 1
553
593
  continue
554
594
  }
555
- const letter: i32 = i + 1 < end ? toI32(text.charCodeAt(i + 1)) : 0
595
+ // A backslash with no letter after it is one byte of the literal, and
596
+ // stands for itself.
597
+ if (i + 1 >= end) {
598
+ if (!jsonNameHas(name, j, JSON_BACKSLASH)) {
599
+ return false
600
+ }
601
+ i += 1
602
+ j += 1
603
+ continue
604
+ }
605
+ const letter: i32 = toI32(text.charCodeAt(i + 1))
556
606
  if (letter === JSON_LETTER_U) {
557
- const point: i32 = jsonHex4(text, i + 2, end)
558
- if (point < 0) {
559
- if (!jsonNameHas(name, j, JSON_BACKSLASH) || !jsonNameHas(name, j + 1, JSON_LETTER_U)) {
607
+ // `jsonUnescape`'s reading of a `\u`, and its test of the room.
608
+ const point: i32 = i < end - 5 ? jsonHex4(text, i + 2, end) : -1
609
+ if (point < 0 || i >= end - 5) {
610
+ if (
611
+ j >= nameLength - 1 ||
612
+ !jsonNameHas(name, j, JSON_BACKSLASH) ||
613
+ !jsonNameHas(name, j + 1, JSON_LETTER_U)
614
+ ) {
560
615
  return false
561
616
  }
562
617
  i += 2
@@ -564,15 +619,13 @@ const jsonKeyEquals = (text: string, at: i32, end: i32, name: string): boolean =
564
619
  continue
565
620
  }
566
621
  const width: i32 = jsonUtf8Width(point)
567
- let k: i32 = 0
568
- while (k < width) {
569
- if (!jsonNameHas(name, j + k, jsonUtf8Byte(point, width, k))) {
622
+ for (let k: i32 = 0; k < width; k += 1) {
623
+ if (j >= nameLength || !jsonNameHas(name, j, jsonUtf8Byte(point, width, k))) {
570
624
  return false
571
625
  }
572
- k += 1
626
+ j += 1
573
627
  }
574
628
  i += 6
575
- j += width
576
629
  continue
577
630
  }
578
631
  // Every other escape decodes to one byte.
@@ -593,9 +646,11 @@ const jsonKeyEquals = (text: string, at: i32, end: i32, name: string): boolean =
593
646
  if (!jsonNameHas(name, j, decoded)) {
594
647
  return false
595
648
  }
596
- // A backslash with no letter after it is one byte of the literal and every
597
- // other escape two. The steps are constants rather than a variable because
598
- // a cursor moved by a variable is one the bounds proof stops following.
649
+ // A NUL after the backslash leaves the backslash standing for itself and
650
+ // is read next as a byte of its own, so that step is one byte and every
651
+ // other escape's two. The steps are constants rather than a variable
652
+ // because a cursor moved by a variable is one the bounds proof stops
653
+ // following.
599
654
  if (letter === 0) {
600
655
  i += 1
601
656
  } else {
@@ -603,7 +658,7 @@ const jsonKeyEquals = (text: string, at: i32, end: i32, name: string): boolean =
603
658
  }
604
659
  j += 1
605
660
  }
606
- return j === toI32(name.length)
661
+ return j === nameLength
607
662
  }
608
663
 
609
664
  /**
@@ -638,7 +693,9 @@ class JsonMember {
638
693
  const jsonFirstKey = (object: string): i32 => {
639
694
  const length: i32 = toI32(object.length)
640
695
  const i: i32 = jsonSkipBlank(object, 0)
641
- if (i >= length || toI32(object.charCodeAt(i)) !== JSON_OPEN_BRACE) {
696
+ // `i < 0` never holds, and is tested for the bounds proof, which does not
697
+ // look inside `jsonSkipBlank`.
698
+ if (i < 0 || i >= length || toI32(object.charCodeAt(i)) !== JSON_OPEN_BRACE) {
642
699
  return -1
643
700
  }
644
701
  return jsonSkipBlank(object, i + 1)
@@ -699,12 +756,18 @@ const jsonValueText = (object: string, member: JsonMember): string => {
699
756
  const valueEnd: i32 = member.valueEnd
700
757
  // `jsonReadMember` only fills in a value `jsonEndOfValue` ended, which starts
701
758
  // inside the object and never ends past it, so this changes no answer: it is
702
- // the range the value's first byte and its `substring` are proved in.
703
- if (valueAt < 0 || valueAt >= valueEnd || valueEnd > toI32(object.length)) {
759
+ // the range the value's first byte and its `substring` are proved in. The
760
+ // proof reads `valueAt < valueEnd` against the length only once the length
761
+ // test has passed, hence the two `if`s.
762
+ if (valueAt < 0 || valueEnd > toI32(object.length)) {
763
+ return ""
764
+ }
765
+ if (valueAt >= valueEnd) {
704
766
  return ""
705
767
  }
706
768
  if (toI32(object.charCodeAt(valueAt)) === JSON_QUOTE) {
707
- return jsonUnescape(object, valueAt + 1, valueEnd - 1)
769
+ // `valueEnd > valueAt >= 0`, so one before it cannot wrap.
770
+ return jsonUnescape(object, valueAt + 1, toI32(toU32(valueEnd) - 1))
708
771
  }
709
772
  return object.substring(valueAt, valueEnd)
710
773
  }
@@ -757,8 +820,8 @@ export const jsonField = (object: string, name: string): string | null => {
757
820
  *
758
821
  * The answer is a fresh array and the only allocation besides the values. Each
759
822
  * value is stored into it by a plain `values[k] = text` statement, and the
760
- * array is only stored into, tested and returned, so the values travel with the
761
- * array: the call lets nothing else out (LANGUAGE.md, "Memory model", a value
823
+ * array is only pushed and stored into, tested and returned, so the values
824
+ * travel with the array: the call lets nothing else out (LANGUAGE.md, "Memory model", a value
762
825
  * stored into an array that is returned with it). A loop calling this keeps its
763
826
  * per-pass release on a line older than the pass, as `jsonField`'s does, and a
764
827
  * `using a = arena()` block may hold the call.
@@ -774,10 +837,16 @@ export const jsonField = (object: string, name: string): string | null => {
774
837
  * field is missing.
775
838
  */
776
839
  export const jsonFields = (object: string, names: string[]): (string | null)[] => {
777
- const count: i32 = toI32(names.length)
778
- const values: (string | null)[] = new Array<string | null>(count)
840
+ // Filled by `push` rather than sized by `new Array(n)`, whose `i32` length
841
+ // is checked for a negative count that `names.length` can never be.
842
+ const values: (string | null)[] = []
843
+ for (let k: i32 = 0; k < toI32(names.length); k += 1) {
844
+ values.push(null)
845
+ }
779
846
  const member: JsonMember = new JsonMember()
780
- let missing: i32 = count
847
+ // Unsigned because it cannot wrap: it is counted down once per slot, when
848
+ // the slot goes from `null` to a value, which happens once at most.
849
+ let missing: u32 = toU32(names.length)
781
850
  let at: i32 = jsonFirstKey(object)
782
851
  while (missing > 0 && jsonReadMember(object, at, member)) {
783
852
  // A value is built once per member however many names it answers, and
@@ -883,25 +952,21 @@ const jsonShortEscape = (code: i32): i32 => {
883
952
  return 0
884
953
  }
885
954
 
886
- /** One lower-case hex digit, as `JSON.stringify` writes the last two of a `\u00xx`. */
887
- const jsonHexByte = (nibble: i32): i32 =>
888
- nibble < JSON_DECIMAL_BASE ? JSON_DIGIT_ZERO + nibble : JSON_LOWER_A + nibble - JSON_DECIMAL_BASE
955
+ /**
956
+ * One lower-case hex digit, as `JSON.stringify` writes the last two of a
957
+ * `\u00xx`: the digit of `nibble`'s low four bits, which every caller's
958
+ * `code >> 4` or `code & 15` already is, and whose range lets the compiler
959
+ * prove the sum.
960
+ */
961
+ const jsonHexByte = (nibble: i32): i32 => {
962
+ const digit = nibble & 15
963
+ return digit < JSON_DECIMAL_BASE ? JSON_DIGIT_ZERO + digit : JSON_LOWER_A + digit - JSON_DECIMAL_BASE
964
+ }
889
965
 
890
966
  /** Whether byte `code` of a string goes inside the quotes as itself: JSON escapes only `"`, `\` and the bytes below a space. */
891
967
  const jsonIsPlainByte = (code: i32): boolean =>
892
968
  code >= JSON_SPACE && code !== JSON_QUOTE && code !== JSON_BACKSLASH
893
969
 
894
- /**
895
- * How many bytes byte `code` of a string takes inside the quotes: itself, a
896
- * two-byte short escape, or the six bytes of `\u00xx`.
897
- */
898
- const jsonEscapedWidth = (code: i32): i32 => {
899
- if (jsonIsPlainByte(code)) {
900
- return 1
901
- }
902
- return jsonShortEscape(code) !== 0 ? 2 : 6
903
- }
904
-
905
970
  /**
906
971
  * A JSON text written into a byte buffer the caller owns: `buf[start ..)`,
907
972
  * up to `buf.length`, with `end` the cursor. Every comma and colon is the
@@ -1078,7 +1143,9 @@ export class JsonWriter {
1078
1143
  * @returns the byte count, `end - start`.
1079
1144
  */
1080
1145
  written(): i32 {
1081
- return this.end - this.start
1146
+ // In u32: `end` never falls below `start`, so the difference is the
1147
+ // count itself and fits an `i32`.
1148
+ return toI32(toU32(this.end) - toU32(this.start))
1082
1149
  }
1083
1150
 
1084
1151
  /**
@@ -1202,15 +1269,19 @@ export class JsonWriter {
1202
1269
  this.afterKey ||
1203
1270
  !jsonWriterInObject(this) ||
1204
1271
  at < 0 ||
1205
- at > cap - sep - n
1272
+ // In u32, which cannot wrap: `at` and `n` are at most `2^31 - 1` and
1273
+ // `sep`, by the tests before it, at most 1.
1274
+ toU32(at) + toU32(sep) + toU32(n) > toU32(cap)
1206
1275
  ) {
1207
1276
  this.key(name)
1208
1277
  return
1209
1278
  }
1210
- if (sep === JSON_WRITER_SEP_COMMA && at < cap) {
1211
- buf[at] = toU8(JSON_COMMA)
1279
+ // The test above leaves `at` at most `cap - sep - n`, so the comma fits.
1280
+ let j: i32 = at
1281
+ if (sep === JSON_WRITER_SEP_COMMA && j < cap) {
1282
+ buf[j] = toU8(JSON_COMMA)
1283
+ j += 1
1212
1284
  }
1213
- let j: i32 = at + sep
1214
1285
  let k: i32 = 0
1215
1286
  while (k < n && j >= 0 && j < cap) {
1216
1287
  buf[j] = toU8(quoted.charCodeAt(k))
@@ -1392,7 +1463,7 @@ export class JsonWriter {
1392
1463
  * fragment the caller encoded already, such as a cached object. Nothing in
1393
1464
  * it is checked, so a fragment that is not one whole JSON value makes a
1394
1465
  * text that is not JSON either. The bytes are copied in one move
1395
- * (`copyBytes`), as if all were read before any was written, so a window
1466
+ * (`tryCopyBytes`), as if all were read before any was written, so a window
1396
1467
  * of the writer's own buffer comes out as it was.
1397
1468
  * In an indented text the fragment goes in where a value would, after its
1398
1469
  * line break and indent, but its own bytes are not re-indented: an object
@@ -1419,8 +1490,14 @@ export class JsonWriter {
1419
1490
  this.failed = JSON_WRITE_FULL
1420
1491
  return
1421
1492
  }
1422
- copyBytes(buf, at, bytes, off, len)
1423
- this.end = at + len
1493
+ // Both windows are checked above, so this copies; were one not, nothing
1494
+ // is written and the writer stops as full.
1495
+ if (!tryCopyBytes(buf, at, bytes, off, len)) {
1496
+ this.failed = JSON_WRITE_FULL
1497
+ return
1498
+ }
1499
+ // In u32, which cannot wrap: the test above keeps the sum within `buf`.
1500
+ this.end = toI32(toU32(at) + toU32(len))
1424
1501
  jsonWriterValueDone(this)
1425
1502
  }
1426
1503
  }
@@ -1494,8 +1571,12 @@ const jsonWriterValueDone = (w: JsonWriter): void => {
1494
1571
 
1495
1572
  /** `beginObject` and `beginArray`: the opener, and a slot for the new container. */
1496
1573
  const jsonWriterOpen = (w: JsonWriter, object: boolean, opener: i32): void => {
1497
- if (w.failed === JSON_WRITE_OK && w.depth >= JSON_WRITER_MAX_DEPTH) {
1498
- w.failed = JSON_WRITE_TOO_DEEP
1574
+ // A writer that has already failed writes nothing, deep or not.
1575
+ const depth: i32 = w.depth
1576
+ if (depth >= JSON_WRITER_MAX_DEPTH) {
1577
+ if (w.failed === JSON_WRITE_OK) {
1578
+ w.failed = JSON_WRITE_TOO_DEEP
1579
+ }
1499
1580
  return
1500
1581
  }
1501
1582
  if (!jsonWriterValueDue(w) || !jsonWriterPutByte(w, opener)) {
@@ -1504,7 +1585,7 @@ const jsonWriterOpen = (w: JsonWriter, object: boolean, opener: i32): void => {
1504
1585
  const low: i32 = w.objectsLow
1505
1586
  w.objectsHigh = (w.objectsHigh << JSON_WRITER_BIT) | (low >>> JSON_WRITER_TOP_BIT)
1506
1587
  w.objectsLow = (low << JSON_WRITER_BIT) | (object ? JSON_WRITER_BIT : 0)
1507
- w.depth = w.depth + 1
1588
+ w.depth = depth + 1
1508
1589
  w.sep = w.sep & JSON_WRITER_SEP_INDENTED
1509
1590
  }
1510
1591
 
@@ -1513,7 +1594,9 @@ const jsonWriterClose = (w: JsonWriter, object: boolean, closer: i32): void => {
1513
1594
  if (w.failed !== JSON_WRITE_OK) {
1514
1595
  return
1515
1596
  }
1516
- if (w.depth === 0 || jsonWriterInObject(w) !== object) {
1597
+ // `depth` is never negative; `<= 0` is `=== 0` in the form that bounds the step down.
1598
+ const depth: i32 = w.depth
1599
+ if (depth <= 0 || jsonWriterInObject(w) !== object) {
1517
1600
  w.failed = JSON_WRITE_UNBALANCED
1518
1601
  return
1519
1602
  }
@@ -1522,7 +1605,7 @@ const jsonWriterClose = (w: JsonWriter, object: boolean, closer: i32): void => {
1522
1605
  return
1523
1606
  }
1524
1607
  if (jsonWriterPutByte(w, closer)) {
1525
- w.depth -= 1
1608
+ w.depth = depth - 1
1526
1609
  const high: i32 = w.objectsHigh
1527
1610
  w.objectsLow = (w.objectsLow >>> JSON_WRITER_BIT) | ((high & JSON_WRITER_BIT) << JSON_WRITER_TOP_BIT)
1528
1611
  w.objectsHigh = high >>> JSON_WRITER_BIT
@@ -1539,12 +1622,13 @@ const jsonWriterClose = (w: JsonWriter, object: boolean, closer: i32): void => {
1539
1622
  * stays `main`'s code and small enough for LLVM to inline into every `end*`.
1540
1623
  */
1541
1624
  const jsonWriterCloseIndented = (w: JsonWriter, object: boolean, closer: i32): void => {
1625
+ const depth: i32 = w.depth
1542
1626
  if (
1543
1627
  w.failed === JSON_WRITE_OK &&
1544
- w.depth !== 0 &&
1628
+ depth > 0 &&
1545
1629
  jsonWriterInObject(w) === object &&
1546
1630
  !w.afterKey &&
1547
- !jsonWriterIndented(w, w.depth - 1, "")
1631
+ !jsonWriterIndented(w, depth - 1, "")
1548
1632
  ) {
1549
1633
  return
1550
1634
  }
@@ -1608,11 +1692,14 @@ const jsonWriterIndented = (w: JsonWriter, level: i32, name: string): boolean =>
1608
1692
  }
1609
1693
  const buf: u8[] = w.buf
1610
1694
  const at: i32 = w.end
1611
- const stop: i32 = at + 1 + w.indentWidth * level
1612
- if (at < 0 || stop > toI32(buf.length)) {
1695
+ // In u32, which cannot wrap here: `at` is below the buffer's length, and
1696
+ // `setIndent` and `JSON_WRITER_MAX_DEPTH` keep width and level small.
1697
+ const end: u32 = toU32(at) + 1 + toU32(w.indentWidth) * toU32(level)
1698
+ if (at < 0 || at >= toI32(buf.length) || end > toU32(buf.length)) {
1613
1699
  w.failed = JSON_WRITE_FULL
1614
1700
  return false
1615
1701
  }
1702
+ const stop: i32 = toI32(end)
1616
1703
  buf[at] = toU8(JSON_NEWLINE)
1617
1704
  buf.fill(toU8(w.indentByte), at + 1, stop)
1618
1705
  w.end = stop
@@ -1650,11 +1737,14 @@ const jsonWriterBreakBeforeKey = (w: JsonWriter): boolean => {
1650
1737
  }
1651
1738
  const buf: u8[] = w.buf
1652
1739
  const at: i32 = w.end
1653
- const stop: i32 = at + 1 + w.indentWidth * w.depth
1654
- if (at < 0 || stop > toI32(buf.length)) {
1740
+ // In u32, which cannot wrap here: `at` is below the buffer's length, and
1741
+ // `setIndent` and `JSON_WRITER_MAX_DEPTH` keep width and level small.
1742
+ const end: u32 = toU32(at) + 1 + toU32(w.indentWidth) * toU32(w.depth)
1743
+ if (at < 0 || at >= toI32(buf.length) || end > toU32(buf.length)) {
1655
1744
  w.failed = JSON_WRITE_FULL
1656
1745
  return false
1657
1746
  }
1747
+ const stop: i32 = toI32(end)
1658
1748
  buf[at] = toU8(JSON_NEWLINE)
1659
1749
  buf.fill(toU8(w.indentByte), at + 1, stop)
1660
1750
  w.end = stop
@@ -1673,12 +1763,13 @@ const jsonWriterPutText = (w: JsonWriter, text: string): boolean => {
1673
1763
  w.failed = JSON_WRITE_FULL
1674
1764
  return false
1675
1765
  }
1676
- for (let k: i32 = 0; k < n && at + k < toI32(buf.length); k += 1) {
1677
- if (at + k >= 0) {
1678
- buf[at + k] = toU8(text.charCodeAt(k))
1679
- }
1766
+ // The test above leaves room for all `n` bytes, so `j` ends at `at + n`.
1767
+ let j: i32 = at
1768
+ for (let k: i32 = 0; k < n && j < toI32(buf.length); k += 1) {
1769
+ buf[j] = toU8(text.charCodeAt(k))
1770
+ j += 1
1680
1771
  }
1681
- w.end = at + n
1772
+ w.end = j
1682
1773
  return true
1683
1774
  }
1684
1775
 
@@ -1720,7 +1811,7 @@ const jsonWriterPutString = (w: JsonWriter, s: string): boolean => {
1720
1811
  }
1721
1812
  const letter: i32 = jsonShortEscape(code)
1722
1813
  if (letter !== 0) {
1723
- if (at < 0 || at + 1 >= cap) {
1814
+ if (at < 0 || at >= cap - 1) {
1724
1815
  w.failed = JSON_WRITE_FULL
1725
1816
  return false
1726
1817
  }
@@ -1729,7 +1820,7 @@ const jsonWriterPutString = (w: JsonWriter, s: string): boolean => {
1729
1820
  at += 2
1730
1821
  continue
1731
1822
  }
1732
- if (at < 0 || at + 5 >= cap) {
1823
+ if (at < 0 || at >= cap - 5) {
1733
1824
  w.failed = JSON_WRITE_FULL
1734
1825
  return false
1735
1826
  }
@@ -1779,7 +1870,8 @@ const jsonWriterPutBytes = (w: JsonWriter, bytes: u8[], off: i32, len: i32): boo
1779
1870
  }
1780
1871
  buf[at] = toU8(JSON_QUOTE)
1781
1872
  at += 1
1782
- const stop: i32 = off + len
1873
+ // In u32, which cannot wrap: the caller checked the window lies inside `bytes`.
1874
+ const stop: i32 = toI32(toU32(off) + toU32(len))
1783
1875
  for (let i: i32 = off; i >= 0 && i < stop && i < toI32(bytes.length); i += 1) {
1784
1876
  const code: i32 = toI32(bytes[i])
1785
1877
  if (jsonIsPlainByte(code)) {
@@ -1793,7 +1885,7 @@ const jsonWriterPutBytes = (w: JsonWriter, bytes: u8[], off: i32, len: i32): boo
1793
1885
  }
1794
1886
  const letter: i32 = jsonShortEscape(code)
1795
1887
  if (letter !== 0) {
1796
- if (at < 0 || at + 1 >= cap) {
1888
+ if (at < 0 || at >= cap - 1) {
1797
1889
  w.failed = JSON_WRITE_FULL
1798
1890
  return false
1799
1891
  }
@@ -1802,7 +1894,7 @@ const jsonWriterPutBytes = (w: JsonWriter, bytes: u8[], off: i32, len: i32): boo
1802
1894
  at += 2
1803
1895
  continue
1804
1896
  }
1805
- if (at < 0 || at + 5 >= cap) {
1897
+ if (at < 0 || at >= cap - 5) {
1806
1898
  w.failed = JSON_WRITE_FULL
1807
1899
  return false
1808
1900
  }
@@ -1840,18 +1932,25 @@ const jsonWriterPutRuns = (w: JsonWriter, bytes: u8[], off: i32, len: i32): bool
1840
1932
  }
1841
1933
  buf[at] = toU8(JSON_QUOTE)
1842
1934
  at += 1
1843
- const stop: i32 = off + len
1935
+ // In u32, which cannot wrap: the caller checked the window lies inside `bytes`.
1936
+ const stop: i32 = toI32(toU32(off) + toU32(len))
1844
1937
  let i: i32 = off
1845
1938
  while (i >= 0 && i < stop && i < toI32(bytes.length)) {
1846
1939
  const run: i32 = skipJsonPlain(bytes, i, stop)
1847
- const count: i32 = run - i
1940
+ // In u32, which cannot wrap: `skipJsonPlain` answers an index in
1941
+ // `[i, stop]`, so the count is the run's length.
1942
+ const count: i32 = toI32(toU32(run) - toU32(i))
1848
1943
  if (count > 0) {
1849
1944
  if (at > cap - count) {
1850
1945
  w.failed = JSON_WRITE_FULL
1851
1946
  return false
1852
1947
  }
1853
- copyBytes(buf, at, bytes, i, count)
1854
- at += count
1948
+ if (!tryCopyBytes(buf, at, bytes, i, count)) {
1949
+ w.failed = JSON_WRITE_FULL
1950
+ return false
1951
+ }
1952
+ // In u32, which cannot wrap: the test above keeps the sum within `buf`.
1953
+ at = toI32(toU32(at) + toU32(count))
1855
1954
  i = run
1856
1955
  }
1857
1956
  if (i < 0 || i >= stop || i >= toI32(bytes.length)) {
@@ -1861,7 +1960,7 @@ const jsonWriterPutRuns = (w: JsonWriter, bytes: u8[], off: i32, len: i32): bool
1861
1960
  i += 1
1862
1961
  const letter: i32 = jsonShortEscape(code)
1863
1962
  if (letter !== 0) {
1864
- if (at < 0 || at + 1 >= cap) {
1963
+ if (at < 0 || at >= cap - 1) {
1865
1964
  w.failed = JSON_WRITE_FULL
1866
1965
  return false
1867
1966
  }
@@ -1870,7 +1969,7 @@ const jsonWriterPutRuns = (w: JsonWriter, bytes: u8[], off: i32, len: i32): bool
1870
1969
  at += 2
1871
1970
  continue
1872
1971
  }
1873
- if (at < 0 || at + 5 >= cap) {
1972
+ if (at < 0 || at >= cap - 5) {
1874
1973
  w.failed = JSON_WRITE_FULL
1875
1974
  return false
1876
1975
  }
@@ -1882,7 +1981,10 @@ const jsonWriterPutRuns = (w: JsonWriter, bytes: u8[], off: i32, len: i32): bool
1882
1981
  buf[at + 5] = toU8(jsonHexByte(code & 15))
1883
1982
  at += 6
1884
1983
  }
1885
- if (at >= cap) {
1984
+ // `at < 0` never holds — the cursor only moves forward from `w.end` — and
1985
+ // is tested because a cursor moved by a run's length is one the bounds
1986
+ // proof stops following.
1987
+ if (at < 0 || at >= cap) {
1886
1988
  w.failed = JSON_WRITE_FULL
1887
1989
  return false
1888
1990
  }
@@ -1896,81 +1998,96 @@ const jsonWriterPutRuns = (w: JsonWriter, bytes: u8[], off: i32, len: i32): bool
1896
1998
  * negative, at the cursor; all of them or, with `JSON_WRITE_FULL`, none.
1897
1999
  *
1898
2000
  * The digits are counted first and then written right to left, straight into
1899
- * the buffer. A negative `v` is never negated, so `-2147483648` needs no case
1900
- * of its own: each step takes the remainder, which is zero or negative, and
1901
- * divides what is left exactly. The exact division is also what keeps the
1902
- * step the same under Node, where `/` does not truncate.
2001
+ * the buffer, from `|v|` as a `u32`, which holds the magnitude of every `i32`:
2002
+ * `-2147483648` needs no case of its own, and unsigned arithmetic cannot
2003
+ * overflow. Each step divides exactly, after taking the remainder off, which
2004
+ * keeps the step the same under Node, where `/` does not truncate.
1903
2005
  */
1904
2006
  const jsonWriterPutDigits = (w: JsonWriter, v: i32, suffix: i32): boolean => {
1905
- // Counted against powers of ten on `-|v|`, as `jsonWriterPutDigits64` counts.
1906
- const negative: i32 = v < 0 ? v : -v
2007
+ const ten: u32 = 10
2008
+ // `~v` is `-v - 1`, which is never negative for a negative `v`, so the
2009
+ // magnitude is found without a wrap, the same natively and under Node.
2010
+ let rest: u32 = v < 0 ? toU32(~v) + 1 : toU32(v)
1907
2011
  let digits: i32 = 1
1908
- let bound: i32 = -JSON_DECIMAL_BASE
1909
- while (digits < JSON_I32_DIGITS && negative <= bound) {
2012
+ let bound: u32 = ten
2013
+ while (digits < JSON_I32_DIGITS && rest >= bound) {
1910
2014
  digits += 1
1911
2015
  if (digits < JSON_I32_DIGITS) {
1912
- bound = bound * JSON_DECIMAL_BASE
2016
+ bound = bound * ten
1913
2017
  }
1914
2018
  }
1915
2019
  const sign: i32 = v < 0 ? 1 : 0
1916
- let rest: i32 = v
1917
2020
  const extra: i32 = suffix >= 0 ? 1 : 0
1918
2021
  const buf: u8[] = w.buf
2022
+ const cap: i32 = toI32(buf.length)
1919
2023
  const at: i32 = w.end
1920
- const width: i32 = sign + digits + extra
1921
- if (at < 0 || at > toI32(buf.length) - width) {
2024
+ // In u32, as every sum with `width` below, which cannot wrap: `width` is
2025
+ // at most 12 bytes and `at` below `2^31`.
2026
+ const width: u32 = toU32(sign) + toU32(digits) + toU32(extra)
2027
+ if (at < 0 || at >= cap || toU32(at) + width > toU32(cap)) {
1922
2028
  w.failed = JSON_WRITE_FULL
1923
2029
  return false
1924
2030
  }
1925
2031
  if (sign === 1) {
1926
2032
  buf[at] = toU8(JSON_MINUS)
1927
2033
  }
1928
- if (extra === 1 && at + width - 1 < toI32(buf.length) && at + width - 1 >= 0) {
1929
- buf[at + width - 1] = toU8(JSON_DIGIT_ZERO + suffix)
1930
- }
1931
- for (let k: i32 = at + sign + digits - 1; k >= at + sign && k >= 0 && k < toI32(buf.length); k -= 1) {
1932
- const digit: i32 = rest % JSON_DECIMAL_BASE
1933
- buf[k] = toU8(JSON_DIGIT_ZERO + (digit < 0 ? -digit : digit))
1934
- rest = (rest - digit) / JSON_DECIMAL_BASE
1935
- }
1936
- w.end = at + width
2034
+ // The last byte of the number. The test above keeps every byte of it
2035
+ // inside `buf`, so each `k` below is too, and the tests of `k` in the loop
2036
+ // always hold.
2037
+ let k: i32 = toI32(toU32(at) + width - 1)
2038
+ if (extra === 1 && k >= 0 && k < toI32(buf.length)) {
2039
+ buf[k] = toU8(toU32(JSON_DIGIT_ZERO) + toU32(suffix))
2040
+ k -= 1
2041
+ }
2042
+ for (let left: i32 = digits; left > 0 && k >= 0 && k < toI32(buf.length); left -= 1) {
2043
+ const digit: u32 = rest % ten
2044
+ buf[k] = toU8(toU32(JSON_DIGIT_ZERO) + digit)
2045
+ rest = (rest - digit) / ten
2046
+ k -= 1
2047
+ }
2048
+ w.end = toI32(toU32(at) + width)
1937
2049
  return true
1938
2050
  }
1939
2051
 
1940
- /** `jsonWriterPutDigits` in 64 bits, for `i64`, whose minimum likewise needs no case of its own. */
2052
+ /** `jsonWriterPutDigits` in 64 bits, for `i64`, from `|v|` as a `u64`, which likewise holds every magnitude. */
1941
2053
  const jsonWriterPutDigits64 = (w: JsonWriter, v: i64): boolean => {
1942
- // Built with `toI64`: under Node an `i64` is a BigInt, and a bare `10` would
2054
+ // Built with `toU64`: under Node a `u64` is a BigInt, and a bare `10` would
1943
2055
  // stay a number that `%` and `/` refuse to mix with one.
1944
- // The digits are counted against powers of ten on `-|v|`, which every `i64`
1945
- // has, so the count costs a compare and a multiply per digit, not a divide.
1946
- const ten: i64 = toI64(10)
1947
- const negative: i64 = v < 0 ? v : -v
2056
+ // The digits are counted against powers of ten, so the count costs a
2057
+ // compare and a multiply per digit, not a divide.
2058
+ const ten: u64 = toU64(10)
2059
+ // `~v` is `-v - 1`, never negative for a negative `v`: no wrap, as above.
2060
+ let rest: u64 = v < 0 ? toU64(~v) + toU64(1) : toU64(v)
1948
2061
  let digits: i32 = 1
1949
- let bound: i64 = -ten
1950
- while (digits < JSON_I64_DIGITS && negative <= bound) {
2062
+ let bound: u64 = ten
2063
+ while (digits < JSON_I64_DIGITS && rest >= bound) {
1951
2064
  digits += 1
1952
2065
  if (digits < JSON_I64_DIGITS) {
1953
2066
  bound = bound * ten
1954
2067
  }
1955
2068
  }
1956
2069
  const sign: i32 = v < 0 ? 1 : 0
1957
- let rest: i64 = v
1958
2070
  const buf: u8[] = w.buf
2071
+ const cap: i32 = toI32(buf.length)
1959
2072
  const at: i32 = w.end
1960
- const width: i32 = sign + digits
1961
- if (at < 0 || at > toI32(buf.length) - width) {
2073
+ // In u32, as `jsonWriterPutDigits` sums it: at most 20 bytes.
2074
+ const width: u32 = toU32(sign) + toU32(digits)
2075
+ if (at < 0 || at >= cap || toU32(at) + width > toU32(cap)) {
1962
2076
  w.failed = JSON_WRITE_FULL
1963
2077
  return false
1964
2078
  }
1965
2079
  if (sign === 1) {
1966
2080
  buf[at] = toU8(JSON_MINUS)
1967
2081
  }
1968
- for (let k: i32 = at + width - 1; k >= at + sign && k >= 0 && k < toI32(buf.length); k -= 1) {
1969
- const digit: i32 = toI32(rest % ten)
1970
- buf[k] = toU8(JSON_DIGIT_ZERO + (digit < 0 ? -digit : digit))
1971
- rest = rest / ten
2082
+ // The last byte of the number, as `jsonWriterPutDigits` finds it.
2083
+ let k: i32 = toI32(toU32(at) + width - 1)
2084
+ for (let left: i32 = digits; left > 0 && k >= 0 && k < toI32(buf.length); left -= 1) {
2085
+ const digit: u64 = rest % ten
2086
+ buf[k] = toU8(toU32(JSON_DIGIT_ZERO) + toU32(digit))
2087
+ rest = (rest - digit) / ten
2088
+ k -= 1
1972
2089
  }
1973
- w.end = at + width
2090
+ w.end = toI32(toU32(at) + width)
1974
2091
  return true
1975
2092
  }
1976
2093
 
@@ -1998,10 +2115,13 @@ const jsonPutF64Walk = (buf: u8[], at: i32, v: f64): i32 => {
1998
2115
  if (at < 0 || at > toI32(buf.length) - n) {
1999
2116
  return -1
2000
2117
  }
2001
- for (let k: i32 = 0; k < n && at + k < toI32(buf.length); k += 1) {
2002
- buf[at + k] = toU8(text.charCodeAt(k))
2118
+ // The test above leaves room for all `n` bytes, so `j` ends at `at + n`.
2119
+ let j: i32 = at
2120
+ for (let k: i32 = 0; k < n && j < toI32(buf.length); k += 1) {
2121
+ buf[j] = toU8(text.charCodeAt(k))
2122
+ j += 1
2003
2123
  }
2004
- return at + n
2124
+ return j
2005
2125
  }
2006
2126
 
2007
2127
  /** The digits `${v}` spells for a finite `v`, at the cursor; all of them or, with `JSON_WRITE_FULL`, none. */
@@ -2017,23 +2137,45 @@ const jsonWriterPutF64 = (w: JsonWriter, v: f64): boolean => {
2017
2137
 
2018
2138
  /**
2019
2139
  * `s` as `JSON.stringify(s)` writes it — quoted, with the escapes
2020
- * `JsonWriter.string` writes — as a string. A thin layer on the writer: it
2021
- * sizes a buffer to fit exactly, writes into it and reads it back. A string
2022
- * with nothing to escape skips the writer and is only quoted.
2140
+ * `JsonWriter.string` writes — as a string. A string with nothing to escape
2141
+ * is only quoted; otherwise the runs between escapes are copied out whole and
2142
+ * joined with the escapes.
2023
2143
  *
2024
2144
  * @param s - the text to quote.
2025
2145
  * @returns the quoted, escaped text.
2026
2146
  */
2027
2147
  export const jsonStringifyString = (s: string): string => {
2028
2148
  const n: i32 = toI32(s.length)
2029
- let width: i32 = 2
2149
+ const parts: string[] = ['"']
2150
+ // The first byte of the plain run not yet copied into `parts`.
2151
+ let run: i32 = 0
2030
2152
  for (let i: i32 = 0; i < n; i += 1) {
2031
- width += jsonEscapedWidth(toI32(s.charCodeAt(i)))
2153
+ const code: i32 = toI32(s.charCodeAt(i))
2154
+ if (jsonIsPlainByte(code)) {
2155
+ continue
2156
+ }
2157
+ // `run === i` is an escape straight after another, and the empty run adds
2158
+ // nothing. `run >= 0` always holds and is spelled out because `run` is
2159
+ // reassigned in the loop, where the bounds proof stops following it.
2160
+ if (run >= 0 && run < i) {
2161
+ parts.push(s.substring(run, i))
2162
+ }
2163
+ const letter: i32 = jsonShortEscape(code)
2164
+ if (letter !== 0) {
2165
+ parts.push(`\\${String.fromCharCode(letter)}`)
2166
+ } else {
2167
+ const high: string = String.fromCharCode(jsonHexByte(code >> 4))
2168
+ const low: string = String.fromCharCode(jsonHexByte(code & 15))
2169
+ parts.push(`\\u00${high}${low}`)
2170
+ }
2171
+ run = i + 1
2032
2172
  }
2033
- if (width === n + 2) {
2173
+ if (run === 0) {
2034
2174
  return `"${s}"`
2035
2175
  }
2036
- const w: JsonWriter = new JsonWriter(new Array<u8>(width), 0)
2037
- w.string(s)
2038
- return w.text()
2176
+ if (run >= 0 && run < n) {
2177
+ parts.push(s.substring(run, n))
2178
+ }
2179
+ parts.push('"')
2180
+ return parts.join("")
2039
2181
  }