nish 0.34.1 → 0.35.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/sync/ring.ts CHANGED
@@ -15,7 +15,8 @@
15
15
  *
16
16
  * **Two rings.** `SpscRing` has one producer and one consumer, and holds
17
17
  * records of any length up to its capacity back to back: a record costs its
18
- * length rounded up to 4, plus 4. `MpscRing` takes any number of producers
18
+ * length rounded up to 4, plus 4, and a record written with `reserve` may
19
+ * leave padding at a lap's end (a skip marker, below). `MpscRing` takes any number of producers
19
20
  * and one consumer, in fixed slots of `slotBytes` each (Vyukov's bounded
20
21
  * queue: a producer claims a slot with a compare-exchange on the enqueue
21
22
  * position, and each slot's sequence number says whose turn it is). Neither
@@ -31,6 +32,44 @@
31
32
  * multiple of 64 so the header's counters each have a cache line. Several
32
33
  * rings may share a region at different bases.
33
34
  *
35
+ * **In place.** An `SpscRing` producer may write a record into the ring
36
+ * itself instead of copying one in, and a consumer may read one there:
37
+ *
38
+ * const w: u8[] = ring.reserve(n) // empty when there is no room now
39
+ * copyBytes(w, 0, body, 0, k) // any u8[] writer, within w.length
40
+ * ring.commit(k) // publishes w[0, k) as one record
41
+ *
42
+ * const r: readonly u8[] = ring.peek() // the next record, in the ring
43
+ * if (r.length > 0) {
44
+ * use(r)
45
+ * ring.release() // frees it for the producer
46
+ * } else {
47
+ * ring.tryPop(buf, 0) // none, or one peek cannot lend
48
+ * }
49
+ *
50
+ * A window is a `SharedRegion.lend` window: the ring keeps one for its
51
+ * producer and one for its consumer and re-points them on every call, so
52
+ * neither path allocates or makes a system call. `commit`, `abandon` and
53
+ * `release` give the window back, which empties it: a reference kept past
54
+ * them indexes nothing (each index panics) until the next `reserve` or
55
+ * `peek` re-points it, and then sees that call's record. A reserved record
56
+ * is always contiguous: when the rest of the lap is too short, `commit`
57
+ * writes a skip marker there (a length word of -1, "the rest of this lap is
58
+ * padding") and the record starts at the next lap. Every pop steps over a
59
+ * marker. A record `tryPush` wrapped across the end cannot be lent, so `peek`
60
+ * answers an empty window for it and `tryPop` takes it, as it does for a
61
+ * record of length 0. A reservation is at most `capacity / 2 - 4` bytes, so
62
+ * a ring of 8 can never reserve (it panics) and one of 16 allows 4. The
63
+ * reserved bytes are not zeroed: `commit` only what was written. A consumer
64
+ * that polls `peek` on a doorbell ring has no wait call yet (`popWait` takes
65
+ * records, not windows).
66
+ *
67
+ * **The format keeps its magic.** A ring no producer `reserve`s into is
68
+ * byte for byte what it was, and a consumer built before the marker that
69
+ * meets one panics with "the ring is corrupt", never reads padding as a
70
+ * record. Both ends of a ring are normally one build, so a new magic would
71
+ * buy a clearer panic at the cost of every attach of an existing ring.
72
+ *
34
73
  * **Who may call what is not checked.** An `SpscRing` with two producers, or
35
74
  * either ring with two consumers, loses or repeats records; it never reads or
36
75
  * writes outside its region, because every access is a checked `SharedRegion`
@@ -79,6 +118,8 @@ const RING_MPSC_MAGIC: i32 = 0x6e726d31 // "nrm1"
79
118
  // of tens of microseconds. 256 put a ping-pong's p99 at 35 µs; 2048 put it at
80
119
  // 1.4 µs, and 8192 bought nothing more (docs/wp47-shared-memory.md).
81
120
  const RING_SPINS: i32 = 2048
121
+ // An SPSC length word that says the rest of the lap is padding.
122
+ const RING_SKIP: i32 = -1
82
123
  // An MPSC slot: [seq i64][len i32][4 unused][payload].
83
124
  const RING_SLOT_HEAD: i32 = 16
84
125
  // The consumer's sleep flag at RING_SLEEP_AT.
@@ -175,6 +216,18 @@ export class SpscRing {
175
216
  /** The other side's position, as last loaded. */
176
217
  seenHead: i64
177
218
  seenTail: i64
219
+ /** `reserve`'s window, re-pointed by each call; null until the first. */
220
+ wnd: u8[] | null = null
221
+ /** `peek`'s window, likewise. */
222
+ view: u8[] | null = null
223
+ /** The open reservation's bytes, or -1 for none. */
224
+ reserved: i32 = -1
225
+ /** The padding the open reservation skips at the tail. */
226
+ reservedPad: i32 = 0
227
+ /** The position past the record `peek` lent, or -1 for none. */
228
+ peekedEnd: i64 = -1
229
+ /** The position of the record `lengthAt` last read, past any skip marker. */
230
+ found: i64 = 0
178
231
 
179
232
  constructor(region: SharedRegion, base: i32) {
180
233
  this.region = region
@@ -189,9 +242,13 @@ export class SpscRing {
189
242
 
190
243
  /**
191
244
  * Appends `src[off, off + len)` as one record: false when the ring has no
192
- * room for it now. A record longer than the ring could ever hold panics.
245
+ * room for it now. A record longer than the ring could ever hold panics,
246
+ * and so does a call while a reservation is open.
193
247
  */
194
248
  tryPush(src: readonly u8[], off: i32, len: i32): boolean {
249
+ if (this.reserved >= 0) {
250
+ panic("nish/sync/ring: tryPush while a reservation is open; commit or abandon it first")
251
+ }
195
252
  const need: i32 = ringRecordBytes(len)
196
253
  if (len < 0 || need > this.capacity) {
197
254
  panic(`nish/sync/ring: a record of ${len} bytes does not fit a ring of ${this.capacity}`)
@@ -213,6 +270,12 @@ export class SpscRing {
213
270
  if (first < len) {
214
271
  this.region.write(data, src, off + first, len - first)
215
272
  }
273
+ this.publish(end)
274
+ return true
275
+ }
276
+
277
+ /** Moves the producer's position to `end`, which hands the consumer every byte before it. */
278
+ private publish(end: i64): void {
216
279
  this.tail = end
217
280
  if (this.doorbell) {
218
281
  this.region.storeI64(this.base + RING_TAIL_AT, end, SEQ_CST)
@@ -220,7 +283,98 @@ export class SpscRing {
220
283
  } else {
221
284
  this.region.storeI64(this.base + RING_TAIL_AT, end, RELEASE)
222
285
  }
223
- return true
286
+ }
287
+
288
+ /** `window` re-pointed at no bytes: length 0, no allocation once it exists. */
289
+ private emptyWindow(window: u8[] | null): u8[] {
290
+ if (window !== null && window.length === 0) {
291
+ return window
292
+ }
293
+ const none: i32 = 0
294
+ const w: u8[] = this.region.lend(this.base + RING_DATA_AT, none, window)
295
+ this.region.giveBack(w)
296
+ return w
297
+ }
298
+
299
+ /**
300
+ * A window of `n` bytes of the ring's own memory to write a record into,
301
+ * contiguous, without blocking: empty (length 0) when the ring has no room
302
+ * for it now. Nothing is published until `commit`; `abandon` drops it. `n`
303
+ * is from 1 (a window of 0 could not be told from no room; `tryPush` takes
304
+ * an empty record) to `capacity / 2 - 4`, so an empty ring always has room
305
+ * for one; outside that, or while a reservation is open, it panics. A ring
306
+ * of 8 has no such `n` and always panics; one of 16 allows 4. The bytes
307
+ * are not zeroed: they hold whatever the ring last held there.
308
+ */
309
+ reserve(n: i32): u8[] {
310
+ if (this.reserved >= 0) {
311
+ panic("nish/sync/ring: reserve while a reservation is open; commit or abandon it first")
312
+ }
313
+ const most: i32 = this.capacity / 2 - 4
314
+ if (most < 1) {
315
+ panic(
316
+ `nish/sync/ring: an SPSC ring of ${this.capacity} bytes cannot reserve; a reservation is at most half the ring less 4`
317
+ )
318
+ }
319
+ if (n < 1 || n > most) {
320
+ panic(`nish/sync/ring: a reservation of ${n} bytes is not from 1 to ${most}, half the ring less 4`)
321
+ }
322
+ const need: i32 = ringRecordBytes(n)
323
+ const at: i32 = toI32(this.tail & toI64(this.capacity - 1))
324
+ // The rest of the lap is padding when the record would cross the end.
325
+ const pad: i32 = need <= this.capacity - at ? 0 : this.capacity - at
326
+ const end: i64 = this.tail + toI64(pad + need)
327
+ if (end - this.seenHead > toI64(this.capacity)) {
328
+ this.seenHead = this.region.loadI64(this.base + RING_HEAD_AT, ACQUIRE)
329
+ if (end - this.seenHead > toI64(this.capacity)) {
330
+ const none: u8[] = this.emptyWindow(this.wnd)
331
+ this.wnd = none
332
+ return none
333
+ }
334
+ }
335
+ const from: i32 = pad > 0 ? 0 : at
336
+ const w: u8[] = this.region.lend(this.base + RING_DATA_AT + from + 4, n, this.wnd)
337
+ this.wnd = w
338
+ this.reserved = n
339
+ this.reservedPad = pad
340
+ return w
341
+ }
342
+
343
+ /** Ends the open reservation, giving its window back; panics without one. */
344
+ private endReservation(what: string): void {
345
+ const w: u8[] | null = this.wnd
346
+ if (this.reserved < 0 || w === null) {
347
+ panic(`nish/sync/ring: ${what} without a reservation`)
348
+ }
349
+ this.region.giveBack(w)
350
+ this.reserved = -1
351
+ }
352
+
353
+ /**
354
+ * Publishes the reserved window's first `len` bytes as one record, the
355
+ * store `tryPush` makes. The window is given back, so it is empty after.
356
+ * Panics without a reservation, for `len` outside `[0, n]`, or when a
357
+ * `push` moved the window out of the ring.
358
+ */
359
+ commit(len: i32): void {
360
+ const n: i32 = this.reserved
361
+ if (n >= 0 && (len < 0 || len > n)) {
362
+ panic(`nish/sync/ring: commit of ${len} bytes from a reservation of ${n}`)
363
+ }
364
+ this.endReservation("commit")
365
+ const mask: i32 = this.capacity - 1
366
+ const data: i32 = this.base + RING_DATA_AT
367
+ const at: i32 = toI32(this.tail & toI64(mask))
368
+ if (this.reservedPad > 0) {
369
+ this.region.storeI32(data + at, RING_SKIP, RELAXED)
370
+ }
371
+ this.region.storeI32(this.reservedPad > 0 ? data : data + at, len, RELAXED)
372
+ this.publish(this.tail + toI64(this.reservedPad + ringRecordBytes(len)))
373
+ }
374
+
375
+ /** Drops the open reservation, publishing nothing; panics without one. */
376
+ abandon(): void {
377
+ this.endReservation("abandon")
224
378
  }
225
379
 
226
380
  /** Whether a record is queued, loading the producer's position if the cache says none. */
@@ -232,18 +386,36 @@ export class SpscRing {
232
386
  return this.head !== this.seenTail
233
387
  }
234
388
 
235
- /** The length of the record at the consumer's position, checked against the ring. */
236
- private lengthAt(pos: i64, avail: i64): i32 {
389
+ /**
390
+ * The length of the record at `pos`, or at the next lap when a skip marker
391
+ * is at `pos`, checked against the ring and the producer's position `end`.
392
+ * `found` is set to where that record is.
393
+ */
394
+ private lengthAt(pos: i64, end: i64): i32 {
237
395
  const mask: i32 = this.capacity - 1
238
- const len: i32 = this.region.loadI32(this.base + RING_DATA_AT + toI32(pos & toI64(mask)), RELAXED)
396
+ const data: i32 = this.base + RING_DATA_AT
397
+ let at: i64 = pos
398
+ let len: i32 = this.region.loadI32(data + toI32(pos & toI64(mask)), RELAXED)
399
+ if (len === RING_SKIP) {
400
+ at = pos + toI64(this.capacity - toI32(pos & toI64(mask)))
401
+ len = this.region.loadI32(data + toI32(at & toI64(mask)), RELAXED)
402
+ }
239
403
  // The capacity first: a length a broken producer wrote near 2^31 would
240
404
  // overflow the rounding below and panic with the wrong reason.
241
- if (len < 0 || len > this.capacity - 4 || toI64(ringRecordBytes(len)) > avail) {
242
- panic(`nish/sync/ring: a record of length ${len} at position ${pos}: the ring is corrupt`)
405
+ if (len < 0 || len > this.capacity - 4 || toI64(ringRecordBytes(len)) > end - at) {
406
+ panic(`nish/sync/ring: a record of length ${len} at position ${at}: the ring is corrupt`)
243
407
  }
408
+ this.found = at
244
409
  return len
245
410
  }
246
411
 
412
+ /** Panics while `peek` has a record lent, which a pop would take from under it. */
413
+ private notPeeked(what: string): void {
414
+ if (this.peekedEnd >= toI64(0)) {
415
+ panic(`nish/sync/ring: ${what} while peek has a record lent; release it first`)
416
+ }
417
+ }
418
+
247
419
  /** Copies the record at `pos`, `len` bytes, into `dst` at `off`. */
248
420
  private copyOut(pos: i64, len: i32, dst: u8[], off: i32): void {
249
421
  const mask: i32 = this.capacity - 1
@@ -259,18 +431,20 @@ export class SpscRing {
259
431
  /**
260
432
  * Moves the next record into `dst` from `off` and answers its length:
261
433
  * `RING_EMPTY` when there is none, `RING_TOO_SMALL` (keeping it queued)
262
- * when it is longer than `dst.length - off`.
434
+ * when it is longer than `dst.length - off`. Panics while `peek` has a
435
+ * record lent.
263
436
  */
264
437
  tryPop(dst: u8[], off: i32): i32 {
438
+ this.notPeeked("tryPop")
265
439
  if (!this.ready(ACQUIRE)) {
266
440
  return RING_EMPTY
267
441
  }
268
- const len: i32 = this.lengthAt(this.head, this.seenTail - this.head)
442
+ const len: i32 = this.lengthAt(this.head, this.seenTail)
269
443
  if (len > toI32(dst.length) - off) {
270
444
  return RING_TOO_SMALL
271
445
  }
272
- this.copyOut(this.head, len, dst, off)
273
- this.head = this.head + toI64(ringRecordBytes(len))
446
+ this.copyOut(this.found, len, dst, off)
447
+ this.head = this.found + toI64(ringRecordBytes(len))
274
448
  this.region.storeI64(this.base + RING_HEAD_AT, this.head, RELEASE)
275
449
  return len
276
450
  }
@@ -279,9 +453,10 @@ export class SpscRing {
279
453
  * Moves up to `lens.length` records into `dst`, back to back from 0, while
280
454
  * they fit, and sets `lens[i]` to each one's length: how many it moved. One
281
455
  * load of the producer's position and one store of the consumer's, however
282
- * many records it moves.
456
+ * many records it moves. Panics while `peek` has a record lent.
283
457
  */
284
458
  popBatch(dst: u8[], lens: i32[]): i32 {
459
+ this.notPeeked("popBatch")
285
460
  // Always the producer's position now, not the cache: a cache that still
286
461
  // holds a record would hide every one pushed since it was loaded.
287
462
  this.seenTail = this.region.loadI64(this.base + RING_TAIL_AT, ACQUIRE)
@@ -289,17 +464,17 @@ export class SpscRing {
289
464
  let used: i32 = 0
290
465
  let pos: i64 = this.head
291
466
  while (count < toI32(lens.length) && pos !== this.seenTail) {
292
- const len: i32 = this.lengthAt(pos, this.seenTail - pos)
467
+ const len: i32 = this.lengthAt(pos, this.seenTail)
293
468
  if (len > toI32(dst.length) - used) {
294
469
  break
295
470
  }
296
- this.copyOut(pos, len, dst, used)
471
+ this.copyOut(this.found, len, dst, used)
297
472
  if (count >= 0 && count < toI32(lens.length)) {
298
473
  lens[count] = len
299
474
  }
300
475
  count = count + 1
301
476
  used = used + len
302
- pos = pos + toI64(ringRecordBytes(len))
477
+ pos = this.found + toI64(ringRecordBytes(len))
303
478
  }
304
479
  if (count > 0) {
305
480
  this.head = pos
@@ -313,6 +488,8 @@ export class SpscRing {
313
488
  * push rings the doorbell, for at most `timeoutMs` in all (negative: no
314
489
  * limit): `RING_EMPTY` only once that has passed. `SHM_UNSUPPORTED` for a
315
490
  * ring without a doorbell, or off Linux, where the caller polls `tryPop`.
491
+ * Panics while `peek` has a record lent, from `tryPop`, so the message
492
+ * names `tryPop`.
316
493
  */
317
494
  popWait(dst: u8[], off: i32, timeoutMs: i32): i32 {
318
495
  const deadline: i64 = ringDeadline(timeoutMs)
@@ -336,6 +513,49 @@ export class SpscRing {
336
513
  }
337
514
  }
338
515
  }
516
+
517
+ /**
518
+ * The next record, lent in place as the ring's own bytes, without copying
519
+ * or blocking; `release` frees it for the producer. Empty (length 0) when
520
+ * there is none, and also for a record peek cannot lend: one `tryPush`
521
+ * wrapped across the end of the ring, or one of length 0. On an empty
522
+ * answer nothing is lent, and `tryPop` takes the record if there is one.
523
+ * Panics while a record is lent.
524
+ */
525
+ peek(): readonly u8[] {
526
+ this.notPeeked("peek")
527
+ if (!this.ready(ACQUIRE)) {
528
+ const none: u8[] = this.emptyWindow(this.view)
529
+ this.view = none
530
+ return none
531
+ }
532
+ const len: i32 = this.lengthAt(this.head, this.seenTail)
533
+ const from: i32 = toI32((this.found + toI64(4)) & toI64(this.capacity - 1))
534
+ if (len === 0 || len > this.capacity - from) {
535
+ const none: u8[] = this.emptyWindow(this.view)
536
+ this.view = none
537
+ return none
538
+ }
539
+ const r: u8[] = this.region.lend(this.base + RING_DATA_AT + from, len, this.view)
540
+ this.view = r
541
+ this.peekedEnd = this.found + toI64(ringRecordBytes(len))
542
+ return r
543
+ }
544
+
545
+ /**
546
+ * Frees the record `peek` lent, the store `tryPop` makes, and gives the
547
+ * window back, so it is empty after. Panics when no record is lent.
548
+ */
549
+ release(): void {
550
+ const r: u8[] | null = this.view
551
+ if (this.peekedEnd < toI64(0) || r === null) {
552
+ panic("nish/sync/ring: release without a record peek lent")
553
+ }
554
+ this.region.giveBack(r)
555
+ this.head = this.peekedEnd
556
+ this.peekedEnd = -1
557
+ this.region.storeI64(this.base + RING_HEAD_AT, this.head, RELEASE)
558
+ }
339
559
  }
340
560
 
341
561
  /**
package/std/sync/shm.ts CHANGED
@@ -90,6 +90,17 @@ declare function nishshm_wait_i32(h: i32, at: i32, expected: i32, timeoutMs: i32
90
90
  declare function nishshm_wake(h: i32, at: i32, count: i32): i32
91
91
  declare function strerror(errnum: i32): string
92
92
 
93
+ // The window intrinsics (`src/shm-window.ts`): each body is a call of itself,
94
+ // which the compiler replaces with `nishshm_lend` or `nishshm_give_back`. They
95
+ // are not `declare function`s because C would be handed `data` and not the
96
+ // `nish_array` header, and could not answer a `u8[]`.
97
+
98
+ /** `nishshm_lend`: a `u8[]` whose bytes are the region's `[at, at + len)`. */
99
+ const shmLend = (h: i32, at: i32, len: i32, reuse: u8[] | null): u8[] => shmLend(h, at, len, reuse)
100
+
101
+ /** `nishshm_give_back`: empties `window` and answers the length it had. */
102
+ const shmGiveBack = (h: i32, window: u8[]): i32 => shmGiveBack(h, window)
103
+
93
104
  /** No ordering beyond the access itself being whole. */
94
105
  export const RELAXED: i32 = 0
95
106
  /** A load that sees everything written before the `RELEASE` store it reads. */
@@ -277,6 +288,24 @@ export class SharedRegion {
277
288
  return nishshm_wake(this.handle, at, count)
278
289
  }
279
290
 
291
+ /**
292
+ * A `u8[]` of length `len` whose bytes are the region's `[at, at + len)`, not
293
+ * a copy: an index or `copyBytes` into it reads and writes the region. A range
294
+ * outside the region panics. `giveBack` or `close` empties it (length 0), so
295
+ * an index after either panics. A `push` moves it into this process's own
296
+ * memory, after which it is no window and `giveBack` panics. Pass a window
297
+ * already given back as `reuse` to lend it again without a new header: each
298
+ * lend without one keeps a few bytes for the life of the process.
299
+ */
300
+ lend(at: i32, len: i32, reuse: u8[] | null = null): u8[] {
301
+ return shmLend(this.handle, at, len, reuse)
302
+ }
303
+
304
+ /** Empties `window`, which this region lent, and answers the length it had. */
305
+ giveBack(window: u8[]): i32 {
306
+ return shmGiveBack(this.handle, window)
307
+ }
308
+
280
309
  /** Unmaps the region; the handle names nothing after. The name stays until `unlinkRegion`. */
281
310
  close(): Result<void, ShmError> {
282
311
  return shmDone(nishshm_close(this.handle))