@amritk/nish-x86_64-linux 0.45.1 → 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/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
  /**
@@ -719,6 +781,12 @@ export class Statement {
719
781
  }
720
782
  }
721
783
 
784
+ // Cursor.countRange's two calls: the count, then each count read back.
785
+ declare function nishsqlite_cursor_count_range(h: i32, lo: i64, hi: i64, n: u64): i32
786
+ declare function nishsqlite_cursor_count_at(h: i32, i: u64): i64
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
789
+
722
790
  /**
723
791
  * A B-tree cursor on a table or index, which reads rows without a statement.
724
792
  * Columns count from 0 in the order `openCursor` named them. A call on a
@@ -726,8 +794,12 @@ export class Statement {
726
794
  * `columnI64`).
727
795
  */
728
796
  export class Cursor {
797
+ /** `readRow`'s answers from the adapter, sized by `selectRow`. */
798
+ private rowIo: u8[]
729
799
  /** The adapter's handle. */
730
800
  private handle: i32
801
+ /** The columns `selectRow` chose, -1 before it. */
802
+ private nsel: i32
731
803
 
732
804
  /**
733
805
  * Wraps an adapter handle. A program gets a `Cursor` from
@@ -737,6 +809,20 @@ export class Cursor {
737
809
  */
738
810
  constructor(handle: i32) {
739
811
  this.handle = handle
812
+ this.rowIo = []
813
+ this.nsel = -1
814
+ }
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
740
826
  }
741
827
 
742
828
  /**
@@ -854,6 +940,73 @@ export class Cursor {
854
940
  return moved(nishsqlite_cursor_seek(this.handle, op))
855
941
  }
856
942
 
943
+ /**
944
+ * Counts an index's entries whose first key column is `k`, for each `k`
945
+ * from `lo` to `hi`, into `out[k - lo]`, in one seek and one walk of the
946
+ * index, for an index whose first column has INTEGER or NUMERIC affinity.
947
+ * On a full index that is what `SELECT count(*) ... WHERE col = k` answers
948
+ * for each `k`; a partial index holds only the rows its WHERE admits, and
949
+ * counts only those. A count that reaches its walk clears the seek key and
950
+ * leaves the cursor on no row, whatever it answers; one refused first leaves
951
+ * both as they were. Copying the counts into `out` takes one call per key,
952
+ * and one more when `out` is longer than the span. `out` past the span, and
953
+ * all of it on an `Err`, is left as it was.
954
+ *
955
+ * @param lo The first key counted.
956
+ * @param hi The last key counted, at least `lo`.
957
+ * @param out Where the counts go; at least `hi - lo + 1` long.
958
+ * @returns The number of entries counted, or `Err` with `SQLITE_MISUSE` for
959
+ * a table cursor, `SQLITE_MISMATCH` for an index whose first column has
960
+ * another affinity, `SQLITE_RANGE` when `lo > hi` or the span is longer
961
+ * than `out`, or the code SQLite fails with, as for `first`.
962
+ */
963
+ countRange(lo: i64, hi: i64, out: i64[]): Result<i32, i32> {
964
+ const n: i32 = nishsqlite_cursor_count_range(this.handle, lo, hi, toU64(out.length))
965
+ if (n < 0) {
966
+ // The adapter answers minus a SQLite result code: `~n + 1` is `-n`,
967
+ // spelled in u32 so no negation of an i32 can overflow.
968
+ return Err(toI32(toU32(~n) + toU32(1)))
969
+ }
970
+ for (let i = 0; i < out.length; i++) {
971
+ const c: i64 = nishsqlite_cursor_count_at(this.handle, toU64(i))
972
+ if (c < 0) {
973
+ break
974
+ }
975
+ // The call above ends what the loop proved of `i`.
976
+ if (i < out.length) {
977
+ out[i] = c
978
+ }
979
+ }
980
+ return Ok(n)
981
+ }
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
+
857
1010
  /**
858
1011
  * The current row's rowid: a table row's key, an index entry's `rowid`.
859
1012
  *
@@ -914,6 +1067,126 @@ export class Cursor {
914
1067
  return Ok(n)
915
1068
  }
916
1069
 
1070
+ /**
1071
+ * Chooses the columns `readRow` reads, in order; a column may repeat. The
1072
+ * list holds until the next `selectRow`, so a loop chooses it once and
1073
+ * calls `readRow` per row. It allocates one buffer of 11 bytes per column
1074
+ * and checks no index: `readRow` answers `SQLITE_RANGE` for one outside the
1075
+ * cursor's columns.
1076
+ *
1077
+ * @param cols The columns' indices, from 0.
1078
+ * @returns `Ok()`, or `Err` with `SQLITE_MISUSE` for over 65535 columns,
1079
+ * which leaves the earlier list chosen.
1080
+ */
1081
+ selectRow(cols: readonly i32[]): Result<void, i32> {
1082
+ const k: i32 = toI32(cols.length)
1083
+ if (k > 0xffff) {
1084
+ return Err(SQLITE_MISUSE)
1085
+ }
1086
+ // Each index goes to the adapter as a little-endian u16; one outside
1087
+ // 0..65535 is sent as 65535, which no cursor has, so it is RANGE there.
1088
+ // A slot of 9 bytes per column follows, which `readRow` fills.
1089
+ const io: u8[] = []
1090
+ for (let i: i32 = 0; i < k && i < toI32(cols.length); i++) {
1091
+ const c: i32 = cols[i] < 0 || cols[i] > 0xffff ? 0xffff : cols[i]
1092
+ io.push(toU8(c & 0xff))
1093
+ io.push(toU8(c >> 8))
1094
+ }
1095
+ for (let i: i32 = 0; i < k; i++) {
1096
+ for (let b: i32 = 0; b < 9; b++) {
1097
+ io.push(0)
1098
+ }
1099
+ }
1100
+ this.rowIo = io
1101
+ this.nsel = k
1102
+ return Ok()
1103
+ }
1104
+
1105
+ /**
1106
+ * Reads the current row's `selectRow` columns in one call. For the `k`th
1107
+ * of them it writes `spans[3k]`, `spans[3k + 1]` and `spans[3k + 2]`: the
1108
+ * type `columnType` answers, then where its bytes start in `text` and how
1109
+ * many there are, which are the bytes `columnInto` copies (0 and 0 for a
1110
+ * number or NULL); and `ints[k]`, the value `columnI64` answers for an
1111
+ * INTEGER or FLOAT column and 0 for TEXT, BLOB and NULL, which it does not
1112
+ * convert. The row's text and blob bytes sit in `text` in column order. A
1113
+ * refusal, or an answer larger than `text.length`, writes no `ints` or
1114
+ * `spans`, and `text` may hold the first columns' bytes: grow `text` and
1115
+ * call again. An empty list answers `Ok(0)` on a row, and `SQLITE_MISUSE`
1116
+ * with no row or a closed cursor, as any list does. It allocates nothing.
1117
+ *
1118
+ * @param ints Receives each column's integer; at least as long as the list.
1119
+ * @param spans Receives each column's type, offset and length; at least
1120
+ * three times as long as the list.
1121
+ * @param text Receives the text and blob bytes.
1122
+ * @returns The text and blob bytes the row holds, or `Err` with the code
1123
+ * `columnType` answers for the first column it refuses (`SQLITE_RANGE`
1124
+ * for an index outside the cursor's columns, `SQLITE_SCHEMA` for a
1125
+ * record too short for it, `SQLITE_MISUSE` with no row or a closed
1126
+ * cursor), or `SQLITE_MISUSE` before `selectRow` or when `ints` or
1127
+ * `spans` is too short, or `SQLITE_TOOBIG` for over 2^31 - 1 bytes.
1128
+ */
1129
+ readRow(ints: i64[], spans: i32[], text: u8[]): Result<i32, i32> {
1130
+ const k: i32 = this.nsel
1131
+ const ni: i32 = toI32(ints.length)
1132
+ const ns: i32 = toI32(spans.length)
1133
+ if (k < 0 || ni < k || ns / 3 < k) {
1134
+ return Err(SQLITE_MISUSE)
1135
+ }
1136
+ const io: u8[] = this.rowIo
1137
+ const n: i32 = nishsqlite_cursor_read_row(this.handle, io, toU64(io.length), text, toU64(text.length))
1138
+ if (n < 0) {
1139
+ // The adapter answers minus a SQLite result code: `~n + 1` is `-n`,
1140
+ // spelled in u32 so no negation of an i32 can overflow.
1141
+ return Err(toI32(toU32(~n) + toU32(1)))
1142
+ }
1143
+ if (n > toI32(text.length)) {
1144
+ return Ok(n)
1145
+ }
1146
+ // The slots follow the 2k index bytes: a column's type, then 8
1147
+ // little-endian bytes, the integer, or a TEXT or BLOB column's length,
1148
+ // under 2^31 since the row's bytes fit `text`. Those bytes sit in `text`
1149
+ // one column after another, so each starts where the last one ended.
1150
+ const nio: i32 = toI32(io.length)
1151
+ let at: i32 = toI32(toI64(k) + toI64(k))
1152
+ let s: i32 = 0
1153
+ let off: i32 = 0
1154
+ for (
1155
+ let i: i32 = 0;
1156
+ i < k && i < toI32(ints.length) && s >= 0 && s <= toI32(spans.length) - 3 && at >= 0 && at <= nio - 9;
1157
+ i++
1158
+ ) {
1159
+ const ty: i32 = toI32(io[at])
1160
+ spans[s] = ty
1161
+ if (ty === SQLITE_TEXT || ty === SQLITE_BLOB) {
1162
+ const len: i32 =
1163
+ toI32(io[at + 1]) | (toI32(io[at + 2]) << 8) | (toI32(io[at + 3]) << 16) | (toI32(io[at + 4]) << 24)
1164
+ ints[i] = 0
1165
+ spans[s + 1] = off
1166
+ spans[s + 2] = len
1167
+ const end: i64 = toI64(off) + toI64(len)
1168
+ off = len >= 0 && end <= toI64(n) ? toI32(end) : n
1169
+ } else {
1170
+ ints[i] =
1171
+ ty === SQLITE_NULL
1172
+ ? 0
1173
+ : toI64(
1174
+ toU64(io[at + 1]) |
1175
+ (toU64(io[at + 2]) << toU64(8)) |
1176
+ ((toU64(io[at + 3]) << toU64(16)) | (toU64(io[at + 4]) << toU64(24))) |
1177
+ ((toU64(io[at + 5]) << toU64(32)) |
1178
+ (toU64(io[at + 6]) << toU64(40)) |
1179
+ ((toU64(io[at + 7]) << toU64(48)) | (toU64(io[at + 8]) << toU64(56))))
1180
+ )
1181
+ spans[s + 1] = 0
1182
+ spans[s + 2] = 0
1183
+ }
1184
+ s += 3
1185
+ at += 9
1186
+ }
1187
+ return Ok(n)
1188
+ }
1189
+
917
1190
  /**
918
1191
  * Closes the cursor; the handle names nothing after.
919
1192
  *
@@ -932,6 +1205,268 @@ export class Cursor {
932
1205
  * @returns The error, with SQLite's description of the code.
933
1206
  */
934
1207
  error(code: i32): SqliteError {
935
- 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
936
1471
  }
937
1472
  }
package/std/synth.ts CHANGED
@@ -101,11 +101,19 @@ export const synthTone = (
101
101
  }
102
102
  const from: i32 = toI32(start * rate)
103
103
  const n: i32 = toI32(length * rate)
104
+ // Never true: `start` is not negative here. The test is what proves `from + i`
105
+ // stays a sample index.
106
+ if (from < 0) {
107
+ return
108
+ }
109
+ const size: i32 = toI32(out.length)
104
110
  const ratio: f64 = Math.log(f1 / f0)
105
111
  let phase: f64 = 0.0
106
112
  let noise: i32 = SYNTH_NOISE_SEED
107
113
  let held: f64 = 0.0
108
- for (let i: i32 = 0; i < n && from + i < toI32(out.length); i++) {
114
+ // `at` is `from + i`, counted on its own so the test against `size` bounds it.
115
+ let at: i32 = from
116
+ for (let i: i32 = 0; i < n && at < size; i++) {
109
117
  const t: f64 = toF64(i) / rate
110
118
  const f: f64 = f0 * Math.exp((ratio * toF64(i)) / toF64(n))
111
119
  const before: f64 = phase
@@ -128,7 +136,8 @@ export const synthTone = (
128
136
  }
129
137
  const attack: f64 = Math.min(t / 0.002, 1.0)
130
138
  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)
139
+ out[at] = out[at] + v * volume * attack * release * Math.exp(-t * decay)
140
+ at = at + 1
132
141
  }
133
142
  }
134
143