@rbxts/netweave 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1272 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class CodecBuffer
6
+
7
+ The byte layer. Everything netweave sends passes through one outgoing buffer and everything it
8
+ receives through one incoming cursor.
9
+
10
+ This is internal — schemas and channels are the public surface — but it is documented because
11
+ its two rules explain shapes that look strange from the outside.
12
+
13
+ **Nothing here throws on incoming data.** A read past the end of the packet returns a zero and
14
+ records a rejection; the caller checks once at the packet boundary rather than after every
15
+ field. A malicious client must not be able to abort a batch by sending a short packet
16
+ (`docs/DESIGN-API.md` G4).
17
+
18
+ **Outgoing state is global, with an explicit save/load swap.** That is not an accident of
19
+ convenience: it is how per-player multiplexing works, and it is what Blink and Zap both do.
20
+ ]=]
21
+
22
+ --[[
23
+ Global rather than threaded through every call: a write is then one upvalue access instead of a
24
+ parameter push plus a field index, and per-player buffers are a `save`/`load` swap rather than
25
+ a parameter everything has to carry (`RESEARCH §3.7-I`).
26
+
27
+ ByteNet's mistake was doing this asymmetrically — global on write, cursor-passing on read — so
28
+ the two halves of its codec do not resemble each other. Both halves here are global.
29
+
30
+ Consequence: the compiled closures live in a *different* module and reach these through
31
+ function calls, so each primitive costs one call. ByteNet pays the same and M0 measured it
32
+ competitive.
33
+
34
+ **M1 phase 6 measured it and the call was not competitive on large payloads.** netweave encoded
35
+ `ArrayHeavy` at 85 FPS against Blink's 144, and the cause was one level below this note: every
36
+ primitive called `allocate` as well, so a 600-byte packet paid 1,200 calls rather than 600. The
37
+ `put*` family below removes the second one. Moving closure synthesis into this module, so the
38
+ buffer state becomes an upvalue and the first call goes too, remains available and remains a
39
+ measurement away rather than a guess away.
40
+ ]]
41
+
42
+ local Codec = {}
43
+
44
+ local INITIAL_SIZE = 64
45
+ local VARINT_MAX_BYTES = 5
46
+
47
+ local outgoing = buffer.create(INITIAL_SIZE)
48
+ local outgoingSize = INITIAL_SIZE
49
+ local outgoingUsed = 0
50
+ local outgoingInstances: { Instance } = {}
51
+ local outgoingInstanceCount = 0
52
+
53
+ local incoming = buffer.create(0)
54
+ local incomingCursor = 0
55
+ --[[ The end of the *packet*, not of the batch. A corrupt inner length must not read into the
56
+ next packet's bytes, let alone off the end of the buffer. ]]
57
+ local incomingLimit = 0
58
+ --[[ `{ unknown }`, not `{ Instance }`: this is the sidecar a peer sent, and what it holds is what
59
+ the read phase exists to check. `FireServer(buffer, { {} })` puts a table in it, and an
60
+ annotation asserting otherwise made `Serdes.isInstance` read as a contradiction of the signature
61
+ rather than as the narrowing it is (M4 report finding 50). ]]
62
+ local incomingInstances: { unknown } = {}
63
+ local incomingInstanceCursor = 0
64
+ local rejection: string? = nil
65
+
66
+ --[=[
67
+ @interface Save
68
+ @within CodecBuffer
69
+ .buffer buffer
70
+ .size number
71
+ .used number
72
+ .instances { Instance }
73
+ .instanceCount number
74
+
75
+ A parked outgoing buffer. The server keeps one of these per player and swaps between them.
76
+ ]=]
77
+ export type Save = {
78
+ buffer: buffer,
79
+ size: number,
80
+ used: number,
81
+ instances: { Instance },
82
+ instanceCount: number,
83
+ }
84
+
85
+ -- ---------------------------------------------------------------------------------------------
86
+ -- Outgoing
87
+ -- ---------------------------------------------------------------------------------------------
88
+
89
+ --[=[
90
+ @within CodecBuffer
91
+ @function allocate
92
+ @param length number
93
+ @return number -- the offset the caller may write at
94
+
95
+ Reserves `length` bytes and returns where they start.
96
+
97
+ :::caution
98
+ Allocate before you touch the buffer. `buffer.writeu16(outgoing, allocate(2), value)` evaluates
99
+ `outgoing` before the call that may replace it with a larger one, and then writes into the old
100
+ buffer — silently, until a growth happens to land mid-packet.
101
+ :::
102
+
103
+ Growth doubles. Blink grows by 1.5x (`_refsrc/blink/src/Templates/Base.luau:81`) and Zap by 2x
104
+ (`_refsrc/zap/zap/src/output/luau/base.luau:45`); doubling costs at most one wasted copy per
105
+ frame and keeps the amortised cost flat under the saturation loads the benchmark applies.
106
+ ]=]
107
+ local function allocate(length: number): number
108
+ local offset = outgoingUsed
109
+ local needed = offset + length
110
+
111
+ if needed > outgoingSize then
112
+ --[[
113
+ Doubling from the current size, but never from zero: `0 * 2` is `0`, so a buffer that
114
+ somehow has no capacity would spin here forever rather than grow. A zero-size buffer is
115
+ reachable — a parked record starts as one — and a growth loop that cannot terminate is a
116
+ hung server rather than a wrong answer.
117
+ ]]
118
+ local size = math.max(outgoingSize, INITIAL_SIZE)
119
+
120
+ while size < needed do
121
+ size *= 2
122
+ end
123
+
124
+ local grown = buffer.create(size)
125
+ buffer.copy(grown, 0, outgoing, 0, offset)
126
+
127
+ outgoing = grown
128
+ outgoingSize = size
129
+ end
130
+
131
+ outgoingUsed = needed
132
+ return offset
133
+ end
134
+
135
+ Codec.allocate = allocate
136
+
137
+ -- ---------------------------------------------------------------------------------------------
138
+ -- Blocks
139
+ -- ---------------------------------------------------------------------------------------------
140
+
141
+ --[[
142
+ A block is a run of bytes whose total size is known before the first one is written, claimed in
143
+ one `allocate` so that everything inside it can skip the bookkeeping.
144
+
145
+ This is `PLAN-M1` D-2's first layout pass, and it was missing until M2. `Ir.lower` has always
146
+ computed `fixedSize`; nothing read it, so a 100-entity `ArrayHeavy` packet made **600 separate
147
+ allocations** — six hundred bounds checks, growth checks and cursor stores for six hundred
148
+ bytes, and 120,000 of them a frame at the benchmark's load. Blink emits one allocation for a
149
+ block and then writes at `offset + k` (`RESEARCH §3.7-D`); Zap does not — its `push_writeu8`
150
+ calls `alloc(1)` per primitive (`§3.8-O`, `§3.9-V1`), which an earlier version of this comment
151
+ had the wrong way round and cited a section about named-type inlining for.
152
+
153
+ Inside a block the buffer cannot grow, because the space is already claimed. That is what makes
154
+ the `put*` writers below safe without a bounds check.
155
+
156
+ **A block does not survive an error, and it must not.** Encode raises on a value the schema
157
+ forbids — that is the security posture, not an exception — and a raise between `openBlock` and
158
+ `closeBlock` leaves the block open with no one to close it. Every later payload would then write
159
+ through a stale cursor into space nobody claimed. So the state is self-healing: `openBlock`
160
+ starts fresh rather than nesting, and `load` and `take` clear it, which covers the transport
161
+ because both are how a payload boundary is crossed. Found by `tests/serdes_runtime.luau`, which
162
+ has a refusal test immediately before a byte-count assertion.
163
+ ]]
164
+ local blockCursor = 0
165
+ local blockDepth = 0
166
+
167
+ --[=[
168
+ @within CodecBuffer
169
+ @function openBlock
170
+ @param length number -- exact bytes the block will contain
171
+ @return number -- the offset the block starts at
172
+
173
+ Claims `length` bytes and switches the `put*` writers on. Every write until the matching
174
+ [CodecBuffer.closeBlock] lands inside the claim, in order, with no further allocation.
175
+
176
+ Blocks do not nest. Opening one starts it fresh, which is what makes a block left open by a
177
+ raising encode harmless rather than corrupting.
178
+
179
+ :::caution
180
+ A block must be filled **exactly**. `closeBlock` raises if it was not, because a short block
181
+ leaves the cursor before the end of the claim and every subsequent byte lands one place too
182
+ early — which a symmetric reader would read back without complaint.
183
+ :::
184
+ ]=]
185
+ function Codec.openBlock(length: number): number
186
+ local base = allocate(length)
187
+ blockCursor = base
188
+ blockDepth = 1
189
+
190
+ return base
191
+ end
192
+
193
+ --[=[
194
+ @within CodecBuffer
195
+ @function closeBlock
196
+
197
+ Ends the innermost block, and checks that it was filled exactly.
198
+ ]=]
199
+ function Codec.closeBlock()
200
+ blockDepth = 0
201
+
202
+ --[[
203
+ `allocate` already moved `outgoingUsed` to the end of the claim, so the two agreeing is the
204
+ whole invariant. They disagree only if a writer wrote fewer bytes than the layout said it
205
+ would, which is a codec bug that corrupts the wire silently — the reader is symmetric and
206
+ would read the wrong bytes back from the same wrong place without failing (`PLAN-M2` R-4).
207
+ ]]
208
+ if blockCursor ~= outgoingUsed then
209
+ local shortfall = outgoingUsed - blockCursor
210
+ blockCursor = outgoingUsed
211
+ error(`[netweave] a fixed-size block was short by {shortfall} bytes; this is a codec bug`)
212
+ end
213
+ end
214
+
215
+ --[=[
216
+ @within CodecBuffer
217
+ @function discardBlock
218
+
219
+ Forgets any open block without checking that it was filled.
220
+
221
+ [CodecBuffer.closeBlock] is the ordinary way out and it verifies the claim; this is for the
222
+ other way out. An encode that raises on a value the schema forbids — the ordinary posture, not
223
+ an exception — leaves a block open with nobody to close it, and the next thing to call
224
+ [CodecBuffer.reserve] would then take its bytes from a stale cursor. A packet boundary is where
225
+ that gets cleaned up.
226
+ ]=]
227
+ function Codec.discardBlock()
228
+ blockDepth = 0
229
+ end
230
+
231
+ --[=[
232
+ @within CodecBuffer
233
+ @function writeU8
234
+ @param value number
235
+ ]=]
236
+ local function writeU8(value: number)
237
+ local offset = allocate(1)
238
+ buffer.writeu8(outgoing, offset, value)
239
+ end
240
+
241
+ Codec.writeU8 = writeU8
242
+
243
+ --[=[
244
+ @within CodecBuffer
245
+ @function writeU16
246
+ @param value number
247
+ ]=]
248
+ function Codec.writeU16(value: number)
249
+ local offset = allocate(2)
250
+ buffer.writeu16(outgoing, offset, value)
251
+ end
252
+
253
+ --[=[
254
+ @within CodecBuffer
255
+ @function writeU32
256
+ @param value number
257
+ ]=]
258
+ function Codec.writeU32(value: number)
259
+ local offset = allocate(4)
260
+ buffer.writeu32(outgoing, offset, value)
261
+ end
262
+
263
+ --[=[
264
+ @within CodecBuffer
265
+ @function writeI8
266
+ @param value number
267
+ ]=]
268
+ function Codec.writeI8(value: number)
269
+ local offset = allocate(1)
270
+ buffer.writei8(outgoing, offset, value)
271
+ end
272
+
273
+ --[=[
274
+ @within CodecBuffer
275
+ @function writeI16
276
+ @param value number
277
+ ]=]
278
+ function Codec.writeI16(value: number)
279
+ local offset = allocate(2)
280
+ buffer.writei16(outgoing, offset, value)
281
+ end
282
+
283
+ --[=[
284
+ @within CodecBuffer
285
+ @function writeI32
286
+ @param value number
287
+ ]=]
288
+ function Codec.writeI32(value: number)
289
+ local offset = allocate(4)
290
+ buffer.writei32(outgoing, offset, value)
291
+ end
292
+
293
+ --[=[
294
+ @within CodecBuffer
295
+ @function writeF32
296
+ @param value number
297
+ ]=]
298
+ function Codec.writeF32(value: number)
299
+ local offset = allocate(4)
300
+ buffer.writef32(outgoing, offset, value)
301
+ end
302
+
303
+ --[=[
304
+ @within CodecBuffer
305
+ @function writeF64
306
+ @param value number
307
+ ]=]
308
+ function Codec.writeF64(value: number)
309
+ local offset = allocate(8)
310
+ buffer.writef64(outgoing, offset, value)
311
+ end
312
+
313
+ --[=[
314
+ @within CodecBuffer
315
+ @function writeString
316
+ @param value string
317
+ @param length number -- byte count, already known to the caller
318
+
319
+ Writes the bytes only. The length prefix is the schema's business, because its width depends on
320
+ the declared bound.
321
+ ]=]
322
+ function Codec.writeString(value: string, length: number)
323
+ local offset = allocate(length)
324
+ buffer.writestring(outgoing, offset, value, length)
325
+ end
326
+
327
+ --[=[
328
+ @within CodecBuffer
329
+ @function writeBuffer
330
+ @param value buffer
331
+ @param length number
332
+ ]=]
333
+ function Codec.writeBuffer(value: buffer, length: number)
334
+ local offset = allocate(length)
335
+ buffer.copy(outgoing, offset, value, 0, length)
336
+ end
337
+
338
+ --[=[
339
+ @within CodecBuffer
340
+ @function writeVarint
341
+ @param value number -- a non-negative integer below 2^32
342
+
343
+ LEB128. One byte below 128, two below 16384.
344
+
345
+ Used for channel ids and packet lengths, which is what removes the 256-channel ceiling both
346
+ Blink and Zap have (`docs/WIRE-FORMAT.md` §3).
347
+ ]=]
348
+ function Codec.writeVarint(value: number)
349
+ while value >= 0x80 do
350
+ writeU8(bit32.bor(bit32.band(value, 0x7F), 0x80))
351
+ value = bit32.rshift(value, 7)
352
+ end
353
+
354
+ writeU8(value)
355
+ end
356
+
357
+ --[=[
358
+ @within CodecBuffer
359
+ @function writeInstance
360
+ @param value Instance
361
+
362
+ Appends to the sidecar array. Instances cannot live in a buffer, so they travel as the remote's
363
+ second argument and their position is implied by write order (`RESEARCH §3.6-B3`).
364
+ ]=]
365
+ function Codec.writeInstance(value: Instance)
366
+ outgoingInstanceCount += 1
367
+ outgoingInstances[outgoingInstanceCount] = value
368
+ end
369
+
370
+ -- ---------------------------------------------------------------------------------------------
371
+ -- Block writers
372
+ -- ---------------------------------------------------------------------------------------------
373
+
374
+ --[=[
375
+ @within CodecBuffer
376
+ @function putU8
377
+ @param value number
378
+
379
+ Writes at the block cursor. Valid only between [CodecBuffer.openBlock] and
380
+ [CodecBuffer.closeBlock], where the space is already claimed.
381
+
382
+ There is one of these for every `write*` that takes a fixed number of bytes. They exist to
383
+ remove a call, not a branch: `writeU8` costs a call into `allocate` on top of its own, and that
384
+ second call is charged six hundred times for one `ArrayHeavy` packet. `Serdes` picks between the
385
+ two families once, at closure-build time, from the layout.
386
+ ]=]
387
+ local function putU8(value: number)
388
+ local offset = blockCursor
389
+ blockCursor = offset + 1
390
+ buffer.writeu8(outgoing, offset, value)
391
+ end
392
+
393
+ Codec.putU8 = putU8
394
+
395
+ --[=[
396
+ @within CodecBuffer
397
+ @function putU16
398
+ @param value number
399
+ ]=]
400
+ function Codec.putU16(value: number)
401
+ local offset = blockCursor
402
+ blockCursor = offset + 2
403
+ buffer.writeu16(outgoing, offset, value)
404
+ end
405
+
406
+ --[=[
407
+ @within CodecBuffer
408
+ @function putU32
409
+ @param value number
410
+ ]=]
411
+ function Codec.putU32(value: number)
412
+ local offset = blockCursor
413
+ blockCursor = offset + 4
414
+ buffer.writeu32(outgoing, offset, value)
415
+ end
416
+
417
+ --[=[
418
+ @within CodecBuffer
419
+ @function putI8
420
+ @param value number
421
+ ]=]
422
+ function Codec.putI8(value: number)
423
+ local offset = blockCursor
424
+ blockCursor = offset + 1
425
+ buffer.writei8(outgoing, offset, value)
426
+ end
427
+
428
+ --[=[
429
+ @within CodecBuffer
430
+ @function putI16
431
+ @param value number
432
+ ]=]
433
+ function Codec.putI16(value: number)
434
+ local offset = blockCursor
435
+ blockCursor = offset + 2
436
+ buffer.writei16(outgoing, offset, value)
437
+ end
438
+
439
+ --[=[
440
+ @within CodecBuffer
441
+ @function putI32
442
+ @param value number
443
+ ]=]
444
+ function Codec.putI32(value: number)
445
+ local offset = blockCursor
446
+ blockCursor = offset + 4
447
+ buffer.writei32(outgoing, offset, value)
448
+ end
449
+
450
+ --[=[
451
+ @within CodecBuffer
452
+ @function putF32
453
+ @param value number
454
+ ]=]
455
+ local function putF32(value: number)
456
+ local offset = blockCursor
457
+ blockCursor = offset + 4
458
+ buffer.writef32(outgoing, offset, value)
459
+ end
460
+
461
+ Codec.putF32 = putF32
462
+
463
+ --[=[
464
+ @within CodecBuffer
465
+ @function putF64
466
+ @param value number
467
+ ]=]
468
+ function Codec.putF64(value: number)
469
+ local offset = blockCursor
470
+ blockCursor = offset + 8
471
+ buffer.writef64(outgoing, offset, value)
472
+ end
473
+
474
+ --[=[
475
+ @within CodecBuffer
476
+ @function putString
477
+ @param value string
478
+ @param length number
479
+ ]=]
480
+ function Codec.putString(value: string, length: number)
481
+ local offset = blockCursor
482
+ blockCursor = offset + length
483
+ buffer.writestring(outgoing, offset, value, length)
484
+ end
485
+
486
+ --[=[
487
+ @within CodecBuffer
488
+ @function putBuffer
489
+ @param value buffer
490
+ @param length number
491
+ ]=]
492
+ function Codec.putBuffer(value: buffer, length: number)
493
+ local offset = blockCursor
494
+ blockCursor = offset + length
495
+ buffer.copy(outgoing, offset, value, 0, length)
496
+ end
497
+
498
+ --[=[
499
+ @within CodecBuffer
500
+ @function claim
501
+ @param length number
502
+ @return buffer -- where to write
503
+ @return number -- the offset to write the first byte at
504
+
505
+ Takes `length` bytes and hands back the buffer and where they start, so a caller that knows its
506
+ own layout can write all of them itself.
507
+
508
+ ```lua
509
+ local out, at = Buffer.claim(6)
510
+ buffer.writeu8(out, at, entity.id)
511
+ buffer.writeu8(out, at + 1, entity.x)
512
+ ```
513
+
514
+ :::caution
515
+ The buffer is only valid until the next call that can grow it, which is any `write*` or another
516
+ `claim` outside a block. Write the bytes and drop the reference; never keep it across a field.
517
+ :::
518
+
519
+ :::note
520
+ This is the one primitive that pays a call **per struct** rather than per value, and that is the
521
+ whole of its reason to exist: `PLAN-M4` phase 7 measured a 100-entity payload spending half its
522
+ encode time in closure calls, and a struct of six numbers costs seven of them before a byte is
523
+ written. `Serdes` uses it for a struct whose fields are all fixed-size numbers.
524
+ :::
525
+ ]=]
526
+ function Codec.claim(length: number): (buffer, number)
527
+ if blockDepth > 0 then
528
+ local offset = blockCursor
529
+ blockCursor = offset + length
530
+ return outgoing, offset
531
+ end
532
+
533
+ --[[ `allocate` first and *then* read `outgoing`: growth replaces the buffer, so a reference
534
+ taken before the call would be the old one and the bytes would be written into a buffer
535
+ nothing is going to send. ]]
536
+ local offset = allocate(length)
537
+ return outgoing, offset
538
+ end
539
+
540
+ --[=[
541
+ @within CodecBuffer
542
+ @function reserve
543
+ @param length number
544
+ @return number -- the offset to patch later
545
+
546
+ Claims bytes now to fill in later. A bitfield's value is not known until every flag in its
547
+ scope has been visited, so its slot is reserved on the way in and written on the way out
548
+ (`docs/WIRE-FORMAT.md` §5).
549
+ ]=]
550
+ function Codec.reserve(length: number): number
551
+ if blockDepth > 0 then
552
+ --[[ Inside a block the space is already claimed, so a reservation is a cursor step. One
553
+ branch per scope rather than per field: scopes open at a payload root and at dynamic
554
+ array elements, never at a value. ]]
555
+ local offset = blockCursor
556
+ blockCursor = offset + length
557
+ return offset
558
+ end
559
+
560
+ return allocate(length)
561
+ end
562
+
563
+ --[=[
564
+ @within CodecBuffer
565
+ @function patchU8
566
+ @param offset number
567
+ @param value number
568
+ ]=]
569
+ function Codec.patchU8(offset: number, value: number)
570
+ buffer.writeu8(outgoing, offset, value)
571
+ end
572
+
573
+ --[=[
574
+ @within CodecBuffer
575
+ @function patchU16
576
+ @param offset number
577
+ @param value number
578
+ ]=]
579
+ function Codec.patchU16(offset: number, value: number)
580
+ buffer.writeu16(outgoing, offset, value)
581
+ end
582
+
583
+ --[=[
584
+ @within CodecBuffer
585
+ @function patchU32
586
+ @param offset number
587
+ @param value number
588
+ ]=]
589
+ function Codec.patchU32(offset: number, value: number)
590
+ buffer.writeu32(outgoing, offset, value)
591
+ end
592
+
593
+ --[=[
594
+ @within CodecBuffer
595
+ @function shift
596
+ @param from number -- absolute offset of the first byte to move
597
+ @param by number -- how many bytes to open up
598
+
599
+ Opens `by` bytes at `from`, moving everything after it along.
600
+
601
+ This exists for one case and should stay that way: a `counted` packet reserves one byte for its
602
+ length before the payload is written, and a payload of 128 bytes or more needs two. Widening
603
+ the reservation after the fact is cheaper than the alternatives — serialising into a scratch
604
+ buffer and copying costs a move on **every** counted packet, while this costs one only on the
605
+ large ones.
606
+
607
+ :::caution
608
+ Absolute offsets taken before the shift are stale afterwards if they sit at or past `from`.
609
+ :::
610
+ ]=]
611
+ function Codec.shift(from: number, by: number)
612
+ local moving = outgoingUsed - from
613
+
614
+ --[[ Grows first, so the destination exists before anything is moved into it. `buffer.copy`
615
+ handles an overlapping move on one buffer — verified under lune, not assumed. ]]
616
+ allocate(by)
617
+
618
+ if moving > 0 then
619
+ buffer.copy(outgoing, from + by, outgoing, from, moving)
620
+ end
621
+ end
622
+
623
+ --[=[
624
+ @within CodecBuffer
625
+ @function instancesWritten
626
+ @return number
627
+
628
+ How many instances the outgoing sidecar holds. A packet that wants to record its own instance
629
+ count reads this before and after writing its payload.
630
+ ]=]
631
+ function Codec.instancesWritten(): number
632
+ return outgoingInstanceCount
633
+ end
634
+
635
+ --[=[
636
+ @within CodecBuffer
637
+ @function seekInstances
638
+ @param position number
639
+
640
+ Moves the incoming sidecar cursor, the way [CodecBuffer.seek] moves the byte cursor. A refused
641
+ packet has to take its instances with it, or every instance after it is read against the wrong
642
+ field.
643
+ ]=]
644
+ function Codec.seekInstances(position: number)
645
+ incomingInstanceCursor = position
646
+ end
647
+
648
+ --[=[
649
+ @within CodecBuffer
650
+ @function used
651
+ @return number -- bytes written so far
652
+ ]=]
653
+ function Codec.used(): number
654
+ return outgoingUsed
655
+ end
656
+
657
+ --[=[
658
+ @within CodecBuffer
659
+ @function save
660
+ @return Save
661
+
662
+ Parks the outgoing buffer so another can take its place. The server serialises a broadcast once
663
+ and then swaps between per-player buffers to copy it (`RESEARCH §3.7-E`).
664
+ ]=]
665
+ function Codec.save(): Save
666
+ return {
667
+ buffer = outgoing,
668
+ size = outgoingSize,
669
+ used = outgoingUsed,
670
+ instances = outgoingInstances,
671
+ instanceCount = outgoingInstanceCount,
672
+ }
673
+ end
674
+
675
+ --[=[
676
+ @within CodecBuffer
677
+ @function emptySave
678
+ @return Save
679
+
680
+ A parked record with nothing in it, ready to be loaded.
681
+
682
+ The transport keeps one per recipient and refills it with [CodecBuffer.saveInto], so this is
683
+ called once per destination rather than per packet. It exists so that the record's shape is
684
+ defined here rather than copied into every caller that needs one.
685
+ ]=]
686
+ function Codec.emptySave(): Save
687
+ return {
688
+ buffer = buffer.create(INITIAL_SIZE),
689
+ size = INITIAL_SIZE,
690
+ used = 0,
691
+ instances = {},
692
+ instanceCount = 0,
693
+ }
694
+ end
695
+
696
+ --[=[
697
+ @within CodecBuffer
698
+ @function saveInto
699
+ @param record Save -- overwritten in place
700
+
701
+ [CodecBuffer.save] without the allocation.
702
+
703
+ `save` builds a table, and the transport parks one buffer per recipient and swaps between them
704
+ on the send path — so a `save` per swap is a table per packet, which is exactly the cost M1's
705
+ benchmark measured as a flat 609.3 B of encode allocation on every schema. A record owned by
706
+ the caller and refilled costs nothing after the first frame.
707
+ ]=]
708
+ function Codec.saveInto(record: Save)
709
+ record.buffer = outgoing
710
+ record.size = outgoingSize
711
+ record.used = outgoingUsed
712
+ record.instances = outgoingInstances
713
+ record.instanceCount = outgoingInstanceCount
714
+ end
715
+
716
+ --[=[
717
+ @within CodecBuffer
718
+ @function mark
719
+ @return number -- bytes written
720
+ @return number -- instances written
721
+
722
+ Where the buffer is, as two numbers rather than a record.
723
+
724
+ Paired with [CodecBuffer.rollback] this is an allocation-free rewind, which the send path needs
725
+ on every packet: an encode that raises has to leave the batch as it found it, and the batch
726
+ behind the half-written packet is a real player's real traffic.
727
+ ]=]
728
+ function Codec.mark(): (number, number)
729
+ return outgoingUsed, outgoingInstanceCount
730
+ end
731
+
732
+ --[=[
733
+ @within CodecBuffer
734
+ @function rollback
735
+ @param used number
736
+ @param instanceCount number
737
+
738
+ Rewinds to a [CodecBuffer.mark].
739
+
740
+ The buffer itself is not shrunk — it may have grown past the mark and that growth is worth
741
+ keeping. What is undone is the *content*: the bytes past `used` are unreachable and the sidecar
742
+ entries past `instanceCount` are cleared, so a retained Instance does not outlive the packet
743
+ that was abandoned.
744
+ ]=]
745
+ function Codec.rollback(used: number, instanceCount: number)
746
+ for index = instanceCount + 1, outgoingInstanceCount do
747
+ outgoingInstances[index] = nil
748
+ end
749
+
750
+ outgoingUsed = used
751
+ outgoingInstanceCount = instanceCount
752
+ blockDepth = 0
753
+ end
754
+
755
+ --[=[
756
+ @within CodecBuffer
757
+ @function load
758
+ @param saved Save? -- nil starts a fresh, empty buffer
759
+ ]=]
760
+ function Codec.load(saved: Save?)
761
+ blockDepth = 0
762
+
763
+ if saved then
764
+ outgoing = saved.buffer
765
+ outgoingSize = saved.size
766
+ outgoingUsed = saved.used
767
+ outgoingInstances = saved.instances
768
+ outgoingInstanceCount = saved.instanceCount
769
+ return
770
+ end
771
+
772
+ outgoing = buffer.create(INITIAL_SIZE)
773
+ outgoingSize = INITIAL_SIZE
774
+ outgoingUsed = 0
775
+ outgoingInstances = {}
776
+ outgoingInstanceCount = 0
777
+ end
778
+
779
+ --[=[
780
+ @within CodecBuffer
781
+ @function take
782
+ @return buffer -- an exact-size copy
783
+ @return { Instance }
784
+
785
+ Hands over what has been written and empties the buffer. The copy is unavoidable: the growable
786
+ buffer is larger than its contents, and a remote must not carry the slack.
787
+
788
+ :::note
789
+ The buffer itself stays, at the size it grew to, so a record saved after a `take` starts the
790
+ next frame with the capacity the last one needed. A destination that once sent a large batch
791
+ keeps a buffer that size until [Outbound.forget] drops the record.
792
+ :::
793
+ ]=]
794
+ function Codec.take(): (buffer, { Instance })
795
+ blockDepth = 0
796
+
797
+ local packed = buffer.create(outgoingUsed)
798
+ buffer.copy(packed, 0, outgoing, 0, outgoingUsed)
799
+
800
+ --[[ `table.create` yields `{unknown}`, and Luau arrays are invariant, so the cast is the only
801
+ way to pre-size the destination rather than growing it element by element. ]]
802
+ local instances = (table.create(outgoingInstanceCount) :: any) :: { Instance }
803
+ table.move(outgoingInstances, 1, outgoingInstanceCount, 1, instances)
804
+
805
+ --[[
806
+ Emptied, not replaced. This used to be `load(nil)`, which put a fresh 64-byte buffer here,
807
+ so the record `Outbound.flush` saved afterwards regrew through every doubling each frame to
808
+ reach the size it had the frame before — five `buffer.create` and copies per destination per
809
+ frame at 1.5 KB, while the comment at the call site said the record kept what it had
810
+ (SECURITY-REPORT-M4 76; `bench/residue` rung 76). The sidecar is cleared for the same reason
811
+ and one more: an `Instance` held past its frame is a reference the game cannot see.
812
+ ]]
813
+ table.clear(outgoingInstances)
814
+ outgoingUsed = 0
815
+ outgoingInstanceCount = 0
816
+
817
+ return packed, instances
818
+ end
819
+
820
+ -- ---------------------------------------------------------------------------------------------
821
+ -- Incoming
822
+ -- ---------------------------------------------------------------------------------------------
823
+
824
+ --[=[
825
+ @interface Read
826
+ @within CodecBuffer
827
+ .buffer buffer
828
+ .cursor number
829
+ .limit number
830
+ .instances { Instance }
831
+ .instanceCursor number
832
+ .rejection string?
833
+
834
+ Where the *read* side is, as a record — the incoming counterpart of [CodecBuffer.Save].
835
+ ]=]
836
+ export type Read = {
837
+ buffer: buffer,
838
+ cursor: number,
839
+ limit: number,
840
+ --[[ Wire data, so `{ unknown }`; see `incomingInstances`. ]]
841
+ instances: { unknown },
842
+ instanceCursor: number,
843
+ rejection: string?,
844
+ }
845
+
846
+ --[=[
847
+ @within CodecBuffer
848
+ @function saveRead
849
+ @return Read
850
+
851
+ Parks the read side so something else may read, and [CodecBuffer.loadRead] puts it back.
852
+
853
+ One caller: `nw.validate` round-trips a value through the codec to hand back a schema-shaped
854
+ copy, and a handler may call it *while a batch is being read*. Without this, that read would
855
+ move the batch's cursor and the packets behind it would decode from the wrong offset.
856
+
857
+ :::caution
858
+ It allocates a record. That is affordable exactly once, on the escape hatch it exists for; the
859
+ receive path never needs it, because a payload that decoded is valid by construction.
860
+ :::
861
+ ]=]
862
+ function Codec.saveRead(): Read
863
+ return {
864
+ buffer = incoming,
865
+ cursor = incomingCursor,
866
+ limit = incomingLimit,
867
+ instances = incomingInstances,
868
+ instanceCursor = incomingInstanceCursor,
869
+ rejection = rejection,
870
+ }
871
+ end
872
+
873
+ --[=[
874
+ @within CodecBuffer
875
+ @function loadRead
876
+ @param saved Read
877
+ ]=]
878
+ function Codec.loadRead(saved: Read)
879
+ incoming = saved.buffer
880
+ incomingCursor = saved.cursor
881
+ incomingLimit = saved.limit
882
+ incomingInstances = saved.instances
883
+ incomingInstanceCursor = saved.instanceCursor
884
+ rejection = saved.rejection
885
+ end
886
+
887
+ --[=[
888
+ @within CodecBuffer
889
+ @function beginRead
890
+ @param source buffer
891
+ @param instances { Instance }?
892
+
893
+ Points the reader at a freshly arrived batch and clears any previous rejection.
894
+ ]=]
895
+ function Codec.beginRead(source: buffer, instances: { unknown }?)
896
+ incoming = source
897
+ incomingCursor = 0
898
+ incomingLimit = buffer.len(source)
899
+ incomingInstances = instances or {}
900
+ incomingInstanceCursor = 0
901
+ rejection = nil
902
+ end
903
+
904
+ --[=[
905
+ @within CodecBuffer
906
+ @function setLimit
907
+ @param position number
908
+
909
+ Bounds every subsequent read at `position`, which is where the current packet ends.
910
+
911
+ Without this a corrupt inner length reads into the next packet — or past the buffer, where
912
+ `buffer.readu8` throws and takes the whole batch with it.
913
+ ]=]
914
+ function Codec.setLimit(position: number)
915
+ incomingLimit = math.min(position, buffer.len(incoming))
916
+ end
917
+
918
+ --[=[
919
+ @within CodecBuffer
920
+ @function limit
921
+ @return number
922
+ ]=]
923
+ function Codec.limit(): number
924
+ return incomingLimit
925
+ end
926
+
927
+ --[=[
928
+ @within CodecBuffer
929
+ @function cursor
930
+ @return number
931
+ ]=]
932
+ function Codec.cursor(): number
933
+ return incomingCursor
934
+ end
935
+
936
+ --[=[
937
+ @within CodecBuffer
938
+ @function seek
939
+ @param position number
940
+
941
+ Moves the cursor, clamped to the buffer. Used to skip a packet that failed to decode.
942
+ ]=]
943
+ function Codec.seek(position: number)
944
+ incomingCursor = math.clamp(position, 0, buffer.len(incoming))
945
+ end
946
+
947
+ --[=[
948
+ @within CodecBuffer
949
+ @function remaining
950
+ @return number -- readable bytes before the limit
951
+ ]=]
952
+ function Codec.remaining(): number
953
+ return incomingLimit - incomingCursor
954
+ end
955
+
956
+ --[=[
957
+ @within CodecBuffer
958
+ @function reject
959
+ @param reason string
960
+
961
+ Records that the packet being read is not decodable. The first reason wins, because it is the
962
+ one that describes what actually went wrong; everything after it is a consequence.
963
+ ]=]
964
+ function Codec.reject(reason: string)
965
+ if not rejection then
966
+ rejection = reason
967
+ end
968
+ end
969
+
970
+ --[=[
971
+ @within CodecBuffer
972
+ @function rejected
973
+ @return string? -- the reason, or nil if the packet is still good
974
+ ]=]
975
+ function Codec.rejected(): string?
976
+ return rejection
977
+ end
978
+
979
+ --[=[
980
+ @within CodecBuffer
981
+ @function clearRejection
982
+ ]=]
983
+ function Codec.clearRejection()
984
+ rejection = nil
985
+ end
986
+
987
+ --[=[
988
+ @within CodecBuffer
989
+ @function span
990
+ @param length number
991
+ @return buffer? -- the incoming buffer, or nil when the run does not fit
992
+ @return number -- where the run starts
993
+
994
+ [CodecBuffer.claim]'s mirror on the read side: the bytes and where they begin, one call for a run
995
+ whose size the layout already knows, in place of a bounds check per value.
996
+
997
+ ```lua
998
+ local src, at = Buffer.span(size)
999
+
1000
+ if src == nil then
1001
+ return fallback
1002
+ end
1003
+
1004
+ value.hp = buffer.readu8(src, at)
1005
+ ```
1006
+
1007
+ :::caution
1008
+ Every read after this must stay inside `length`. The bound was checked once, here, which is the
1009
+ whole point — so an offset computed from anything but the layout is a read this function has
1010
+ already promised was safe.
1011
+ :::
1012
+
1013
+ :::note
1014
+ ~~`ensure(length)` answered the same question as a boolean.~~ It did, and **nothing ever called
1015
+ it**: it was written in M2 for exactly this optimisation, the optimisation landed on the encode
1016
+ side only, and it sat unused until M4 phase 8 (`docs/SECURITY-REPORT-M4.md`). Returning the
1017
+ buffer and the offset is what a caller actually needs, because reading with a named
1018
+ `buffer.readu8` is the whole point and that needs both.
1019
+ :::
1020
+ ]=]
1021
+ function Codec.span(length: number): (buffer?, number)
1022
+ local offset = incomingCursor
1023
+
1024
+ if offset + length > incomingLimit then
1025
+ Codec.reject("truncated")
1026
+ return nil, 0
1027
+ end
1028
+
1029
+ incomingCursor = offset + length
1030
+ return incoming, offset
1031
+ end
1032
+
1033
+ --[=[
1034
+ @within CodecBuffer
1035
+ @function readU8
1036
+ @return number -- 0 if the read would run past the limit
1037
+ ]=]
1038
+ function Codec.readU8(): number
1039
+ if incomingCursor + 1 > incomingLimit then
1040
+ Codec.reject("truncated")
1041
+ return 0
1042
+ end
1043
+
1044
+ local value = buffer.readu8(incoming, incomingCursor)
1045
+ incomingCursor += 1
1046
+ return value
1047
+ end
1048
+
1049
+ --[=[
1050
+ @within CodecBuffer
1051
+ @function readU16
1052
+ @return number
1053
+ ]=]
1054
+ function Codec.readU16(): number
1055
+ if incomingCursor + 2 > incomingLimit then
1056
+ Codec.reject("truncated")
1057
+ return 0
1058
+ end
1059
+
1060
+ local value = buffer.readu16(incoming, incomingCursor)
1061
+ incomingCursor += 2
1062
+ return value
1063
+ end
1064
+
1065
+ --[=[
1066
+ @within CodecBuffer
1067
+ @function readU32
1068
+ @return number
1069
+ ]=]
1070
+ function Codec.readU32(): number
1071
+ if incomingCursor + 4 > incomingLimit then
1072
+ Codec.reject("truncated")
1073
+ return 0
1074
+ end
1075
+
1076
+ local value = buffer.readu32(incoming, incomingCursor)
1077
+ incomingCursor += 4
1078
+ return value
1079
+ end
1080
+
1081
+ --[=[
1082
+ @within CodecBuffer
1083
+ @function readI8
1084
+ @return number
1085
+ ]=]
1086
+ function Codec.readI8(): number
1087
+ if incomingCursor + 1 > incomingLimit then
1088
+ Codec.reject("truncated")
1089
+ return 0
1090
+ end
1091
+
1092
+ local value = buffer.readi8(incoming, incomingCursor)
1093
+ incomingCursor += 1
1094
+ return value
1095
+ end
1096
+
1097
+ --[=[
1098
+ @within CodecBuffer
1099
+ @function readI16
1100
+ @return number
1101
+ ]=]
1102
+ function Codec.readI16(): number
1103
+ if incomingCursor + 2 > incomingLimit then
1104
+ Codec.reject("truncated")
1105
+ return 0
1106
+ end
1107
+
1108
+ local value = buffer.readi16(incoming, incomingCursor)
1109
+ incomingCursor += 2
1110
+ return value
1111
+ end
1112
+
1113
+ --[=[
1114
+ @within CodecBuffer
1115
+ @function readI32
1116
+ @return number
1117
+ ]=]
1118
+ function Codec.readI32(): number
1119
+ if incomingCursor + 4 > incomingLimit then
1120
+ Codec.reject("truncated")
1121
+ return 0
1122
+ end
1123
+
1124
+ local value = buffer.readi32(incoming, incomingCursor)
1125
+ incomingCursor += 4
1126
+ return value
1127
+ end
1128
+
1129
+ --[=[
1130
+ @within CodecBuffer
1131
+ @function readF32
1132
+ @return number
1133
+ ]=]
1134
+ function Codec.readF32(): number
1135
+ if incomingCursor + 4 > incomingLimit then
1136
+ Codec.reject("truncated")
1137
+ return 0
1138
+ end
1139
+
1140
+ local value = buffer.readf32(incoming, incomingCursor)
1141
+ incomingCursor += 4
1142
+ return value
1143
+ end
1144
+
1145
+ --[=[
1146
+ @within CodecBuffer
1147
+ @function readF64
1148
+ @return number
1149
+ ]=]
1150
+ function Codec.readF64(): number
1151
+ if incomingCursor + 8 > incomingLimit then
1152
+ Codec.reject("truncated")
1153
+ return 0
1154
+ end
1155
+
1156
+ local value = buffer.readf64(incoming, incomingCursor)
1157
+ incomingCursor += 8
1158
+ return value
1159
+ end
1160
+
1161
+ --[=[
1162
+ @within CodecBuffer
1163
+ @function readString
1164
+ @param length number
1165
+ @return string -- empty if the read would run past the limit
1166
+ ]=]
1167
+ function Codec.readString(length: number): string
1168
+ if incomingCursor + length > incomingLimit then
1169
+ Codec.reject("truncated")
1170
+ return ""
1171
+ end
1172
+
1173
+ local value = buffer.readstring(incoming, incomingCursor, length)
1174
+ incomingCursor += length
1175
+ return value
1176
+ end
1177
+
1178
+ --[=[
1179
+ @within CodecBuffer
1180
+ @function readBuffer
1181
+ @param length number
1182
+ @return buffer
1183
+ ]=]
1184
+ function Codec.readBuffer(length: number): buffer
1185
+ if incomingCursor + length > incomingLimit then
1186
+ Codec.reject("truncated")
1187
+ return buffer.create(0)
1188
+ end
1189
+
1190
+ local value = buffer.create(length)
1191
+ buffer.copy(value, 0, incoming, incomingCursor, length)
1192
+ incomingCursor += length
1193
+ return value
1194
+ end
1195
+
1196
+ --[=[
1197
+ @within CodecBuffer
1198
+ @function readVarint
1199
+ @return number
1200
+
1201
+ Five bytes is all a 32-bit value can need, and the fifth carries four bits. A fifth byte with
1202
+ anything else set — the high bits, or the continuation bit that would ask for a sixth — is
1203
+ rejected rather than wrapped: `bit32.lshift` by 28 drops the high bits silently, so
1204
+ `ff ff ff ff 1f` used to read as 2^32 − 1 and a length or an id past the format's range came
1205
+ out as one inside it (M4 report, finding 8). A run of continuation bytes is the same case and
1206
+ does not loop.
1207
+ ]=]
1208
+ function Codec.readVarint(): number
1209
+ local result = 0
1210
+ local shift = 0
1211
+
1212
+ for _ = 1, VARINT_MAX_BYTES - 1 do
1213
+ local byte = Codec.readU8()
1214
+ result = bit32.bor(result, bit32.lshift(bit32.band(byte, 0x7F), shift))
1215
+
1216
+ if bit32.band(byte, 0x80) == 0 then
1217
+ return result
1218
+ end
1219
+
1220
+ shift += 7
1221
+ end
1222
+
1223
+ local last = Codec.readU8()
1224
+
1225
+ if last > 0x0F then
1226
+ Codec.reject("varint past 32 bits")
1227
+ return 0
1228
+ end
1229
+
1230
+ return bit32.bor(result, bit32.lshift(last, shift))
1231
+ end
1232
+
1233
+ --[=[
1234
+ @within CodecBuffer
1235
+ @function readInstance
1236
+ @return unknown -- nil when the sidecar is exhausted, and whatever the peer put there otherwise
1237
+
1238
+ Consumes the next entry in write order. A packet that is skipped must skip its instances too, or
1239
+ every later packet reads the wrong ones.
1240
+
1241
+ :::caution
1242
+ **`unknown`, not `Instance?`.** A sidecar entry is a client argument like any other:
1243
+ `FireServer(buffer, { {} })` puts a table there, and `value:IsA(class)` on a table raises on the
1244
+ receive path, which is guarantee G4 broken by the one piece of wire data that does not travel in
1245
+ the buffer. `Serdes` checks it with `isInstance` before asking anything else, and this type is
1246
+ what makes that check the narrowing rather than a contradiction (M4 report finding 50).
1247
+ :::
1248
+ ]=]
1249
+ function Codec.readInstance(): unknown
1250
+ incomingInstanceCursor += 1
1251
+ return incomingInstances[incomingInstanceCursor]
1252
+ end
1253
+
1254
+ --[=[
1255
+ @within CodecBuffer
1256
+ @function skipInstances
1257
+ @param count number
1258
+ ]=]
1259
+ function Codec.skipInstances(count: number)
1260
+ incomingInstanceCursor += count
1261
+ end
1262
+
1263
+ --[=[
1264
+ @within CodecBuffer
1265
+ @function instanceCursor
1266
+ @return number
1267
+ ]=]
1268
+ function Codec.instanceCursor(): number
1269
+ return incomingInstanceCursor
1270
+ end
1271
+
1272
+ return Codec