nish 0.46.0 → 0.47.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/std/regex.ts CHANGED
@@ -101,8 +101,6 @@
101
101
  * `Regex` is used by one thread at a time.
102
102
  */
103
103
 
104
- import { uncheckedGet } from "nish:unsafe"
105
-
106
104
  // Derived from the Unicode Character Database 16.0.0 (https://www.unicode.org/Public/16.0.0/ucd/), the files scripts/gen-regex-unicode.mjs names. Copyright © 1991-2026 Unicode, Inc. Used under the Unicode License v3, whose text follows.
107
105
  //
108
106
  // UNICODE LICENSE V3
@@ -2100,16 +2098,29 @@ const regexLoadSlots = (dst: i32[], src: i32[], base: i32, ns: i32): void => {
2100
2098
  }
2101
2099
  }
2102
2100
 
2101
+ /**
2102
+ * `n` zeros, or none when `n` is not above 0. Pushed one at a time: an `i32`
2103
+ * length is a checked `new Array`, and every count here is a compile's table
2104
+ * size, made once per pattern.
2105
+ */
2103
2106
  const regexZeros = (n: i32): i32[] => {
2104
- const a: i32[] = new Array<i32>(n)
2105
- a.fill(0)
2107
+ const a: i32[] = []
2108
+ let k: i32 = 0
2109
+ while (k < n) {
2110
+ a.push(0)
2111
+ k += 1
2112
+ }
2106
2113
  return a
2107
2114
  }
2108
2115
 
2109
2116
  /** `n` zero bytes, for the reason `regexZeros` gives. */
2110
2117
  const regexZeroBytes = (n: i32): u8[] => {
2111
- const a: u8[] = new Array<u8>(n)
2112
- a.fill(toU8(0))
2118
+ const a: u8[] = []
2119
+ let k: i32 = 0
2120
+ while (k < n) {
2121
+ a.push(toU8(0))
2122
+ k += 1
2123
+ }
2113
2124
  return a
2114
2125
  }
2115
2126
 
@@ -4889,9 +4900,19 @@ export class Regex {
4889
4900
  const cls: i32[] = this.dCls
4890
4901
  while (true) {
4891
4902
  // The hot loop: an ASCII byte and a transition already computed.
4903
+ // `dCls` has an entry for every byte and a state's row one for every
4904
+ // class, so the slot is in the table; were either not, giving up hands
4905
+ // the search to the NFA.
4892
4906
  while (p >= 0 && p < len) {
4893
4907
  const b: i32 = toI32(text.charCodeAt(p))
4894
- const e: i32 = uncheckedGet(trans, off | uncheckedGet(cls, b))
4908
+ if (b >= toI32(cls.length)) {
4909
+ return DFA_GAVE_UP
4910
+ }
4911
+ const slot: i32 = off | cls[b]
4912
+ if (slot < 0 || slot >= toI32(trans.length)) {
4913
+ return DFA_GAVE_UP
4914
+ }
4915
+ const e: i32 = trans[slot]
4895
4916
  if (e > 0) {
4896
4917
  off = e
4897
4918
  p += 1
@@ -4915,13 +4936,14 @@ export class Regex {
4915
4936
  let w: i32 = 1
4916
4937
  if (p >= 0 && p < len) {
4917
4938
  const b: i32 = toI32(text.charCodeAt(p))
4918
- if (b < 128) {
4919
- // `dCls` has an entry for every byte.
4920
- c = uncheckedGet(cls, b)
4921
- } else {
4939
+ if (b >= 128) {
4922
4940
  const packed: i32 = regexDecodeAt(text, p)
4923
4941
  c = this.dWideClass(packed >> 3)
4924
4942
  w = packed & 7
4943
+ } else if (b < toI32(cls.length)) {
4944
+ c = cls[b]
4945
+ } else {
4946
+ return DFA_GAVE_UP
4925
4947
  }
4926
4948
  }
4927
4949
  // States and classes are both non-negative, and a state's row holds
@@ -5017,7 +5039,15 @@ export class Regex {
5017
5039
  let q: i32 = toI32(toU32(p) - 1)
5018
5040
  while (q >= from && q >= 0 && q < len) {
5019
5041
  const b: i32 = toI32(text.charCodeAt(q))
5020
- const t: i32 = uncheckedGet(trans, off | uncheckedGet(cls, b))
5042
+ // A byte or a slot outside its table gives up, as in `dfaForward`.
5043
+ if (b >= toI32(cls.length)) {
5044
+ return DFA_GAVE_UP
5045
+ }
5046
+ const slot: i32 = off | cls[b]
5047
+ if (slot < 0 || slot >= toI32(trans.length)) {
5048
+ return DFA_GAVE_UP
5049
+ }
5050
+ const t: i32 = trans[slot]
5021
5051
  if (t > 0) {
5022
5052
  off = t
5023
5053
  q -= 1
@@ -5043,9 +5073,10 @@ export class Regex {
5043
5073
  let w: i32 = 1
5044
5074
  if (q >= 0 && q < len) {
5045
5075
  const b: i32 = toI32(text.charCodeAt(q))
5046
- if (b < 128) {
5047
- // `dCls` has an entry for every byte.
5048
- c = uncheckedGet(cls, b)
5076
+ if (b < 128 && b < toI32(cls.length)) {
5077
+ c = cls[b]
5078
+ } else if (b < 128) {
5079
+ return DFA_GAVE_UP
5049
5080
  } else {
5050
5081
  const lim: i32 = p > from ? from : 0
5051
5082
  let cp: i32 = REGEX_INVALID + b
package/std/release.ts CHANGED
@@ -75,7 +75,8 @@ export class ReleaseCache {
75
75
  */
76
76
  export const releaseValidVersion = (v: string): boolean => {
77
77
  const n: i32 = toI32(v.length)
78
- if (n === 0 || n > 64) {
78
+ // biome-ignore lint/style/useExplicitLengthCheck: the panic prover reads `length < 1` as a bound for the charCodeAt(0) after it and does not read `=== 0`
79
+ if (v.length < 1 || n > 64) {
79
80
  return false
80
81
  }
81
82
  const first: i32 = toI32(v.charCodeAt(0))
@@ -99,18 +100,19 @@ export const releaseValidVersion = (v: string): boolean => {
99
100
  /** A run of ASCII digits as a number, or -1 when it is empty, too long, has a leading zero or holds anything else. */
100
101
  const releaseNumber = (s: string): i64 => {
101
102
  const n: i32 = toI32(s.length)
102
- if (n === 0 || n > 15 || (n > 1 && s.charCodeAt(0) === 48)) {
103
+ if (n === 0 || n > 15 || (s.length > 1 && s.charCodeAt(0) === 48)) {
103
104
  return -1
104
105
  }
105
- let value: i64 = 0
106
+ // At most 15 digits, below 2^53, so every step is exact in an `f64`.
107
+ let value: f64 = 0
106
108
  for (let i: i32 = 0; i < n; i++) {
107
109
  const c: i32 = toI32(s.charCodeAt(i))
108
110
  if (c < 48 || c > 57) {
109
111
  return -1
110
112
  }
111
- value = value * 10 + toI64(c - 48)
113
+ value = value * 10.0 + toF64(c - 48)
112
114
  }
113
- return value
115
+ return toI64(value)
114
116
  }
115
117
 
116
118
  /**
@@ -155,15 +157,15 @@ export const releaseParseVersion = (v: string): ReleaseVersion | null => {
155
157
  }
156
158
  let core: string = v
157
159
  const plus: i32 = toI32(core.indexOf("+"))
158
- if (plus >= 0) {
159
- if (plus + 1 === toI32(core.length) || !releasePreWellFormed(core.slice(plus + 1), false)) {
160
+ if (plus >= 0 && plus < toI32(core.length)) {
161
+ if (plus === toI32(core.length) - 1 || !releasePreWellFormed(core.slice(plus + 1), false)) {
160
162
  return null
161
163
  }
162
164
  core = core.slice(0, plus)
163
165
  }
164
166
  let pre: string = ""
165
167
  const dash: i32 = toI32(core.indexOf("-"))
166
- if (dash >= 0) {
168
+ if (dash >= 0 && dash < toI32(core.length)) {
167
169
  pre = core.slice(dash + 1)
168
170
  core = core.slice(0, dash)
169
171
  if (!releasePreWellFormed(pre, true)) {
@@ -325,7 +327,8 @@ export const releaseTagFromLocation = (base: string, location: string): string |
325
327
  /** Whether `rest`, what follows a host, is empty, a path, or a port of digits then nothing or a path. */
326
328
  const releasePortThenPath = (rest: string): boolean => {
327
329
  const n: i32 = toI32(rest.length)
328
- if (n === 0 || rest.charCodeAt(0) === 47) {
330
+ // biome-ignore lint/style/useExplicitLengthCheck: the panic prover reads `length < 1` as a bound for the charCodeAt(0) after it and does not read `=== 0`
331
+ if (rest.length < 1 || rest.charCodeAt(0) === 47) {
329
332
  return true
330
333
  }
331
334
  if (rest.charCodeAt(0) !== 58) {
@@ -335,7 +338,7 @@ const releasePortThenPath = (rest: string): boolean => {
335
338
  while (i < n && rest.charCodeAt(i) >= 48 && rest.charCodeAt(i) <= 57) {
336
339
  i++
337
340
  }
338
- return i > 1 && (i === n || rest.charCodeAt(i) === 47)
341
+ return i > 1 && (i === n || (i < n && rest.charCodeAt(i) === 47))
339
342
  }
340
343
 
341
344
  /**
@@ -518,15 +521,18 @@ export const releaseCacheParse = (text: string): ReleaseCache | null => {
518
521
  /**
519
522
  * Whether a cache checked at `checkedMs` still answers at `nowMs`: younger
520
523
  * than `maxAgeMs`, and not dated in the future, which a clock set back or a
521
- * planted file would give.
524
+ * planted file would give, which covers a clock before 1970. A cache dated
525
+ * before 1970, which only a hand-built one can be, is not fresh either.
522
526
  *
523
527
  * @param cache The cache.
524
528
  * @param nowMs The time now, in milliseconds since 1970.
525
529
  * @param maxAgeMs How long an answer stays fresh.
526
530
  * @returns True when the cache need not be refreshed.
527
531
  */
528
- export const releaseCacheFresh = (cache: ReleaseCache, nowMs: i64, maxAgeMs: i64): boolean =>
529
- cache.checkedMs <= nowMs && nowMs - cache.checkedMs < maxAgeMs
532
+ export const releaseCacheFresh = (cache: ReleaseCache, nowMs: i64, maxAgeMs: i64): boolean => {
533
+ const checked: i64 = cache.checkedMs
534
+ return checked >= 0 && nowMs >= 0 && checked <= nowMs && nowMs - checked < maxAgeMs
535
+ }
530
536
 
531
537
  /**
532
538
  * Writes the cache at `path`: its directory is created mode 0700 when missing
package/std/sqlite.ts CHANGED
@@ -80,14 +80,14 @@
80
80
  // runtime's (NL2202). scripts/build.sh links SQLite for a module that declares
81
81
  // an `sqlite3_` or a `nishsqlite_` function, as this one does.
82
82
  declare function nishsqlite_open(path: string, flags: i32): i32
83
- declare function nishsqlite_open_errmsg(): string
83
+ declare function nishsqlite_open_errmsg(): string | null
84
84
  declare function nishsqlite_close(h: i32): i32
85
85
  declare function nishsqlite_exec(h: i32, sql: string): i32
86
- declare function nishsqlite_errmsg(h: i32): string
86
+ declare function nishsqlite_errmsg(h: i32): string | null
87
87
  declare function nishsqlite_last_insert_rowid(h: i32): i64
88
88
  declare function nishsqlite_changes(h: i32): i64
89
89
  declare function nishsqlite_prepare(h: i32, sql: string): i32
90
- declare function nishsqlite_stmt_errmsg(h: i32): string
90
+ declare function nishsqlite_stmt_errmsg(h: i32): string | null
91
91
  declare function nishsqlite_finalize(h: i32): i32
92
92
  declare function nishsqlite_step(h: i32): i32
93
93
  declare function nishsqlite_reset(h: i32): i32
@@ -130,8 +130,8 @@ declare function nishsqlite_cursor_column_type(h: i32, c: i32): i32
130
130
  declare function nishsqlite_cursor_column_i64(h: i32, c: i32): i64
131
131
  declare function nishsqlite_cursor_column_into(h: i32, c: i32, buf: u8[], n: u64, at: i32): i32
132
132
  declare function nishsqlite_cursor_rowid(h: i32): i64
133
- declare function sqlite3_errstr(code: i32): string
134
- declare function sqlite3_libversion(): string
133
+ declare function sqlite3_errstr(code: i32): string | null
134
+ declare function sqlite3_libversion_number(): i32
135
135
 
136
136
  /** Success. */
137
137
  export const SQLITE_OK: i32 = 0
@@ -216,7 +216,12 @@ export const SEEK_LT: i32 = 4
216
216
  *
217
217
  * @returns The version string, such as `3.50.4`.
218
218
  */
219
- export const sqliteVersion = (): string => sqlite3_libversion()
219
+ export const sqliteVersion = (): string => {
220
+ // SQLite numbers 3.50.4 as 3050004, the major times a million plus the minor
221
+ // times a thousand plus the patch.
222
+ const n: i32 = sqlite3_libversion_number()
223
+ return `${n / 1000000}.${(n / 1000) % 1000}.${n % 1000}`
224
+ }
220
225
 
221
226
  /** A failure, with SQLite's message for it. Built only when asked for, by `error(code)`. */
222
227
  export class SqliteError {
@@ -249,16 +254,32 @@ const done = (rc: i32): Result<void, i32> => {
249
254
  return Ok()
250
255
  }
251
256
 
257
+ /**
258
+ * SQLite's description of `code`, such as `constraint failed`. The C type lets
259
+ * `sqlite3_errstr` answer NULL, so the code stands in for the text then, as
260
+ * `error 19`, rather than stop the program over a message.
261
+ */
262
+ const describe = (code: i32): string => {
263
+ const text = sqlite3_errstr(code)
264
+ return text === null ? `error ${code}` : text
265
+ }
266
+
252
267
  /**
253
268
  * The message for `code`: the connection's own, unless the code is one the
254
269
  * adapter can answer without SQLite (`MISUSE`, `RANGE`, `NOMEM` for a full
255
270
  * handle table or a failed conversion), where the connection's message may
256
- * still be that of some earlier failure.
271
+ * still be that of some earlier failure, or the connection has no message
272
+ * (NULL), where SQLite's description of the code stands in.
257
273
  */
258
- const messageFor = (code: i32, connection: string): string => {
274
+ const messageFor = (code: i32, connection: string | null): string => {
259
275
  const primary: i32 = code & 0xff
260
- if (primary === SQLITE_MISUSE || primary === SQLITE_RANGE || primary === SQLITE_NOMEM) {
261
- return sqlite3_errstr(code)
276
+ if (
277
+ connection === null ||
278
+ primary === SQLITE_MISUSE ||
279
+ primary === SQLITE_RANGE ||
280
+ primary === SQLITE_NOMEM
281
+ ) {
282
+ return describe(code)
262
283
  }
263
284
  return connection
264
285
  }
@@ -286,7 +307,9 @@ const moved = (r: i32): Result<boolean, i32> => {
286
307
  export const openDatabase = (path: string, flags: i32): Result<Database, SqliteError> => {
287
308
  const h: i32 = nishsqlite_open(path, flags)
288
309
  if (h < 0) {
289
- return Err(new SqliteError(-h, nishsqlite_open_errmsg()))
310
+ const code: i32 = -h
311
+ const message = nishsqlite_open_errmsg()
312
+ return Err(new SqliteError(code, message === null ? describe(code) : message))
290
313
  }
291
314
  return Ok(new Database(h))
292
315
  }
@@ -389,16 +412,55 @@ export class Database {
389
412
  * a cursor reads, or has columns other than `columns`.
390
413
  */
391
414
  openCursor(name: string, columns: string): Result<Cursor, SqliteError> {
415
+ const h = this.cursorHandle(name, columns)
416
+ if (h.isErr()) {
417
+ return Err(h.error)
418
+ }
419
+ return Ok(new Cursor(h.value))
420
+ }
421
+
422
+ /** The adapter's cursor on `name`, as `openCursor` opens it, or its refusal. */
423
+ private cursorHandle(name: string, columns: string): Result<i32, SqliteError> {
392
424
  const h: i32 = nishsqlite_cursor_open(this.handle, name, columns)
393
425
  if (h < 0) {
394
- if (-h === SQLITE_SCHEMA) {
426
+ const code: i32 = -h
427
+ if (code === SQLITE_SCHEMA) {
395
428
  return Err(
396
- new SqliteError(-h, `no table or index ${name} with columns "${columns}" that a cursor reads`)
429
+ new SqliteError(code, `no table or index ${name} with columns "${columns}" that a cursor reads`)
397
430
  )
398
431
  }
399
- return Err(this.error(-h))
432
+ return Err(this.error(code))
433
+ }
434
+ return Ok(h)
435
+ }
436
+
437
+ /**
438
+ * `openCursor` into a `Cursor` the program already holds, which then reads
439
+ * the new cursor: the one it held before, open or already ended with its
440
+ * read, is closed first. There is no garbage collector, so a loop that
441
+ * opens the same cursors in every read transaction keeps one `Cursor` each
442
+ * this way and allocates nothing, where `openCursor`'s new object a time
443
+ * would stay allocated for good.
444
+ *
445
+ * @param cur The cursor to reopen.
446
+ * @param name The table or index, as `openCursor` takes it.
447
+ * @param columns Its columns, as `openCursor` takes them.
448
+ * @returns `Ok()`, or `Err` as `openCursor` answers, when `cur` is left
449
+ * closed.
450
+ */
451
+ reopenCursor(cur: Cursor, name: string, columns: string): Result<void, SqliteError> {
452
+ // A cursor whose read has ended is gone already, and its close answers
453
+ // SQLITE_MISUSE: nothing is open to lose either way.
454
+ const closed = cur.close()
455
+ if (closed.isErr() && closed.error !== SQLITE_MISUSE) {
456
+ return Err(this.error(closed.error))
400
457
  }
401
- return Ok(new Cursor(h))
458
+ const h = this.cursorHandle(name, columns)
459
+ if (h.isErr()) {
460
+ return Err(h.error)
461
+ }
462
+ cur.rebind(h.value)
463
+ return Ok()
402
464
  }
403
465
 
404
466
  /**
@@ -723,6 +785,7 @@ export class Statement {
723
785
  declare function nishsqlite_cursor_count_range(h: i32, lo: i64, hi: i64, n: u64): i32
724
786
  declare function nishsqlite_cursor_count_at(h: i32, i: u64): i64
725
787
  declare function nishsqlite_cursor_read_row(h: i32, io: u8[], n: u64, text: u8[], ntext: u64): i32
788
+ declare function nishsqlite_cursor_record(h: i32, buf: u8[], n: u64): i32
726
789
 
727
790
  /**
728
791
  * A B-tree cursor on a table or index, which reads rows without a statement.
@@ -750,6 +813,18 @@ export class Cursor {
750
813
  this.nsel = -1
751
814
  }
752
815
 
816
+ /**
817
+ * Points this object at the adapter's cursor `handle`, forgetting the
818
+ * columns `selectRow` chose. `Database.reopenCursor` calls it; a program
819
+ * calls that instead.
820
+ *
821
+ * @param handle The adapter's cursor handle.
822
+ */
823
+ rebind(handle: i32): void {
824
+ this.handle = handle
825
+ this.nsel = -1
826
+ }
827
+
753
828
  /**
754
829
  * Moves to the first row, in the index's order for an index.
755
830
  *
@@ -905,6 +980,33 @@ export class Cursor {
905
980
  return Ok(n)
906
981
  }
907
982
 
983
+ /**
984
+ * Copies the current row's record into `buf`: SQLite's record format,
985
+ * whole, as it is stored (https://sqlite.org/fileformat2.html#record_format),
986
+ * a header of varints giving each field's serial type, then the fields'
987
+ * bytes. It converts nothing, so a program that decodes the format itself
988
+ * reads a row with one call and one copy. An index entry's record ends with
989
+ * its rowid; a table row's holds NULL for an INTEGER PRIMARY KEY column,
990
+ * whose value is the row's key (`rowid`). It allocates nothing.
991
+ *
992
+ * @param buf Receives the record.
993
+ * @returns The record's length. When that is more than `buf.length`,
994
+ * nothing is copied: grow `buf` and call again. `Err` with the code:
995
+ * `SQLITE_MISUSE` with no row or a closed cursor, `SQLITE_ABORT` when the
996
+ * row has moved, `SQLITE_CORRUPT` for a record longer than SQLite allows,
997
+ * or SQLite's, such as `SQLITE_IOERR`, when an overflow page cannot be
998
+ * read.
999
+ */
1000
+ record(buf: u8[]): Result<i32, i32> {
1001
+ const n: i32 = nishsqlite_cursor_record(this.handle, buf, toU64(buf.length))
1002
+ if (n < 0) {
1003
+ // The adapter answers minus a SQLite result code: `~n + 1` is `-n`,
1004
+ // spelled in u32 so no negation of an i32 can overflow.
1005
+ return Err(toI32(toU32(~n) + toU32(1)))
1006
+ }
1007
+ return Ok(n)
1008
+ }
1009
+
908
1010
  /**
909
1011
  * The current row's rowid: a table row's key, an index entry's `rowid`.
910
1012
  *
@@ -1103,6 +1205,268 @@ export class Cursor {
1103
1205
  * @returns The error, with SQLite's description of the code.
1104
1206
  */
1105
1207
  error(code: i32): SqliteError {
1106
- return new SqliteError(code, sqlite3_errstr(code))
1208
+ return new SqliteError(code, describe(code))
1209
+ }
1210
+ }
1211
+
1212
+ /** Serial types 0 to 9's lengths in bytes (https://sqlite.org/fileformat2.html#record_format); 10 and 11 are reserved, and 12 up are `(t - 12) / 2`. */
1213
+ const RECORD_SMALL_SIZES: readonly i32[] = [0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0]
1214
+
1215
+ /**
1216
+ * A row as SQLite stores it, copied whole by `Cursor.record` and decoded
1217
+ * here: the record format's header of varints, one serial type a field, and
1218
+ * the fields' bytes after it. One `read` is one call into the adapter and one
1219
+ * copy, and the fields are then read from this object's own buffer, so a loop
1220
+ * that reads many columns of many rows pays for the record once a row rather
1221
+ * than once a column. It allocates only when a record is longer than its
1222
+ * buffer, which then grows to fit.
1223
+ *
1224
+ * Fields are the record's, in its order: a table row's columns as declared,
1225
+ * with NULL for an INTEGER PRIMARY KEY column, whose value is the row's key
1226
+ * (`Cursor.rowid`), and an index entry's key columns and then its rowid. A
1227
+ * record written before `ALTER TABLE ADD COLUMN` holds fewer fields than the
1228
+ * table has columns; `fields` says how many it holds.
1229
+ *
1230
+ * const row = new RowRecord(256, 8)
1231
+ * let on = cur.first().expect("first")
1232
+ * while (on) {
1233
+ * row.read(cur).expect("record")
1234
+ * if (row.type(1) === SQLITE_TEXT) {
1235
+ * console.log(String.fromBytes(row.buf, row.start(1), row.size(1)))
1236
+ * }
1237
+ * on = cur.next().expect("next")
1238
+ * }
1239
+ */
1240
+ export class RowRecord {
1241
+ /** The record's bytes, from 0 to `length`. */
1242
+ buf: u8[]
1243
+ /** How long the record last read is. */
1244
+ length: i32 = 0
1245
+ /** How many fields its header gives, at most the `maxFields` it was made with. */
1246
+ fields: i32 = 0
1247
+ /** Each field's serial type. */
1248
+ private types: i32[]
1249
+ /** Where each field's bytes start in `buf`. */
1250
+ private offs: i32[]
1251
+
1252
+ /**
1253
+ * A decoder with a buffer of `capacity` bytes, which reads at most
1254
+ * `maxFields` fields of each record.
1255
+ *
1256
+ * @param capacity The buffer's first length, grown when a record is longer.
1257
+ * @param maxFields How many fields to decode; a record's fields past them are not read.
1258
+ */
1259
+ constructor(capacity: i32, maxFields: i32) {
1260
+ this.buf = capacity > 0 ? new Array<u8>(capacity) : new Array<u8>(0)
1261
+ this.types = maxFields > 0 ? new Array<i32>(maxFields) : new Array<i32>(0)
1262
+ this.offs = maxFields > 0 ? new Array<i32>(maxFields) : new Array<i32>(0)
1263
+ }
1264
+
1265
+ /**
1266
+ * Copies `cur`'s current row and reads its header, as SQLite's own
1267
+ * `sqlite3VdbeRecordUnpack` reads it: the fields it would find and no
1268
+ * others, and a last field whose bytes would run past the record's end
1269
+ * reads as NULL.
1270
+ *
1271
+ * @param cur The cursor, on a row.
1272
+ * @returns `Ok()`, or `Err` with the code: `Cursor.record`'s, or
1273
+ * `SQLITE_CORRUPT` for a header SQLite never writes (a varint past the
1274
+ * record, a serial type past 2^31, or a header longer than the record),
1275
+ * when `fields` is 0.
1276
+ */
1277
+ read(cur: Cursor): Result<void, i32> {
1278
+ this.length = 0
1279
+ this.fields = 0
1280
+ let r = cur.record(this.buf)
1281
+ if (r.isOk() && r.value > toI32(this.buf.length)) {
1282
+ const need: i32 = r.value
1283
+ if (need > 0) {
1284
+ this.buf = new Array<u8>(need)
1285
+ }
1286
+ r = cur.record(this.buf)
1287
+ }
1288
+ if (r.isErr()) {
1289
+ return Err(r.error)
1290
+ }
1291
+ if (r.value > toI32(this.buf.length)) {
1292
+ return Err(SQLITE_CORRUPT)
1293
+ }
1294
+ this.length = r.value
1295
+ return this.header() ? Ok() : Err(SQLITE_CORRUPT)
1296
+ }
1297
+
1298
+ /** The varint at `at`, at most 5 bytes and below 2^31, with its length in `vlen`; -1 when there is none. */
1299
+ private vlen: i32 = 0
1300
+ private varint(at: i32): i64 {
1301
+ const b: u8[] = this.buf
1302
+ let v: i64 = 0
1303
+ let k: i32 = at
1304
+ let n: i32 = 0
1305
+ while (n < 5 && k >= 0 && k < this.length && k < toI32(b.length)) {
1306
+ const c: i32 = toI32(b[k])
1307
+ v = (v << toI64(7)) | toI64(c & 127)
1308
+ k = k + 1
1309
+ n = n + 1
1310
+ if (c < 128) {
1311
+ this.vlen = n
1312
+ return v <= toI64(2147483647) ? v : toI64(-1)
1313
+ }
1314
+ }
1315
+ return toI64(-1)
1316
+ }
1317
+
1318
+ /** Reads the header of the record in `buf` into `types` and `offs`; false when it is not one SQLite writes. */
1319
+ private header(): boolean {
1320
+ if (this.length === 0) {
1321
+ return true
1322
+ }
1323
+ const h: i64 = this.varint(toI32(0))
1324
+ if (h < toI64(0) || h > toI64(this.length)) {
1325
+ return false
1326
+ }
1327
+ const hdr: i32 = toI32(h)
1328
+ let idx: i32 = this.vlen & 7
1329
+ // `d` is where the next field's bytes start; a field longer than 2^31
1330
+ // leaves the record behind, which the loop's test finds.
1331
+ let d: i64 = h
1332
+ let u: i32 = 0
1333
+ const types: i32[] = this.types
1334
+ const offs: i32[] = this.offs
1335
+ const sizes: readonly i32[] = RECORD_SMALL_SIZES
1336
+ for (let k: i32 = 0; k >= 0 && k < toI32(types.length) && k < toI32(offs.length); k += 1) {
1337
+ if (idx >= hdr || d > toI64(this.length)) {
1338
+ break
1339
+ }
1340
+ const t: i64 = this.varint(idx)
1341
+ if (t < toI64(0)) {
1342
+ return false
1343
+ }
1344
+ // A varint is at most 5 bytes, so the mask keeps its length.
1345
+ // In u32: idx is below hdr, so the sum is at most 2^31 + 4, and one
1346
+ // that wraps negative ends the walk at the next varint, which refuses it.
1347
+ idx = toI32(toU32(idx) + toU32(this.vlen & 7))
1348
+ const ty: i32 = toI32(t)
1349
+ types[k] = ty
1350
+ offs[k] = toI32(d)
1351
+ let sz: i32 = 0
1352
+ if (ty >= 12) {
1353
+ sz = (ty - 12) >> 1
1354
+ } else if (ty >= 0 && ty < toI32(sizes.length)) {
1355
+ sz = sizes[ty] & 15
1356
+ }
1357
+ // In u64, which cannot wrap: d is at most the record's length here.
1358
+ d = toI64(toU64(d) + toU64(sz))
1359
+ u = k + 1
1360
+ }
1361
+ if (d > toI64(this.length) && u > 0 && u <= toI32(types.length)) {
1362
+ types[u - 1] = 0
1363
+ }
1364
+ this.fields = u
1365
+ return true
1366
+ }
1367
+
1368
+ /** Field `k`'s serial type, or 0 (NULL) past the fields read. */
1369
+ private serial(k: i32): i32 {
1370
+ if (k < 0 || k >= this.fields || k >= toI32(this.types.length)) {
1371
+ return 0
1372
+ }
1373
+ return this.types[k]
1374
+ }
1375
+
1376
+ /**
1377
+ * Field `k`'s type, as `Cursor.columnType` answers it.
1378
+ *
1379
+ * @param k The field, from 0.
1380
+ * @returns `SQLITE_INTEGER`, `SQLITE_FLOAT`, `SQLITE_TEXT`, `SQLITE_BLOB`,
1381
+ * or `SQLITE_NULL`, which a field past `fields` is too.
1382
+ */
1383
+ type(k: i32): i32 {
1384
+ const t: i32 = this.serial(k)
1385
+ if (t >= 12) {
1386
+ return (t & 1) === 1 ? SQLITE_TEXT : SQLITE_BLOB
1387
+ }
1388
+ if (t === 7) {
1389
+ return SQLITE_FLOAT
1390
+ }
1391
+ return t === 0 || t === 10 || t === 11 ? SQLITE_NULL : SQLITE_INTEGER
1392
+ }
1393
+
1394
+ /**
1395
+ * Where field `k`'s bytes start in `buf`: a text's or a blob's first byte,
1396
+ * an integer's or a float's big-endian bytes.
1397
+ *
1398
+ * @param k The field, from 0.
1399
+ * @returns The offset in `buf`, or 0 past the fields read.
1400
+ */
1401
+ start(k: i32): i32 {
1402
+ if (k < 0 || k >= this.fields || k >= toI32(this.offs.length)) {
1403
+ return 0
1404
+ }
1405
+ return this.offs[k]
1406
+ }
1407
+
1408
+ /**
1409
+ * How many bytes field `k` holds in `buf` from `start(k)`: a text's or a
1410
+ * blob's length, which is what a program copies or compares.
1411
+ *
1412
+ * @param k The field, from 0.
1413
+ * @returns The length for TEXT or BLOB, 0 for any other type.
1414
+ */
1415
+ size(k: i32): i32 {
1416
+ const t: i32 = this.serial(k)
1417
+ return t >= 12 ? (t - 12) >> 1 : 0
1418
+ }
1419
+
1420
+ /**
1421
+ * Field `k`'s integer: big-endian, two's complement, as SQLite stores it.
1422
+ *
1423
+ * @param k The field, from 0.
1424
+ * @returns The value of an `SQLITE_INTEGER` field, 0 for any other type.
1425
+ */
1426
+ int(k: i32): i64 {
1427
+ const t: i32 = this.serial(k)
1428
+ if (t === 8 || t === 9) {
1429
+ return t === 8 ? toI64(0) : toI64(1)
1430
+ }
1431
+ if (t < 1 || t > 6) {
1432
+ return toI64(0)
1433
+ }
1434
+ return this.bigEndian(this.start(k), RECORD_SMALL_SIZES[t], true)
1435
+ }
1436
+
1437
+ /**
1438
+ * Field `k`'s number as a float: an `SQLITE_FLOAT`'s IEEE 754 value, an
1439
+ * `SQLITE_INTEGER`'s value converted.
1440
+ *
1441
+ * @param k The field, from 0.
1442
+ * @returns The value, or 0 for TEXT, BLOB and NULL.
1443
+ */
1444
+ float(k: i32): f64 {
1445
+ if (this.serial(k) === 7) {
1446
+ return bitsToF64(this.bigEndian(this.start(k), toI32(8), false))
1447
+ }
1448
+ return toF64(this.int(k))
1449
+ }
1450
+
1451
+ /** The `n` bytes at `at` as a big-endian integer, its sign from the first when `signed`; 0 when they lie outside the record. */
1452
+ private bigEndian(at: i32, n: i32, signed: boolean): i64 {
1453
+ const b: u8[] = this.buf
1454
+ if (
1455
+ n < 1 ||
1456
+ at < 0 ||
1457
+ at >= toI32(b.length) ||
1458
+ toI64(at) + toI64(n) > toI64(this.length) ||
1459
+ at > toI32(b.length) - n
1460
+ ) {
1461
+ return toI64(0)
1462
+ }
1463
+ const first: i32 = toI32(b[at])
1464
+ let v: i64 = signed && first >= 128 ? toI64(first - 256) : toI64(first)
1465
+ // In u32, which cannot wrap: the window was checked to lie inside `buf`.
1466
+ const stop: i32 = toI32(toU32(at) + toU32(n))
1467
+ for (let i: i32 = at + 1; i >= 0 && i < stop && i < toI32(b.length); i += 1) {
1468
+ v = (v << toI64(8)) | toI64(b[i])
1469
+ }
1470
+ return v
1107
1471
  }
1108
1472
  }