@rbxts/netweave 0.0.0-stage → 0.1.1

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,2694 @@
1
+ --!strict
2
+ --!optimize 2
3
+
4
+ --[=[
5
+ @class Serdes
6
+
7
+ Turns an [Ir.Layout] into a pair of closures that write and read one payload.
8
+
9
+ **Closure synthesis, not code generation.** netweave has no build step and emits no source.
10
+ Every decision a layout already made — which encoding a number narrowed to, which bit of which
11
+ chunk a boolean owns, whether a length needs a prefix at all — is bound into a function once,
12
+ at definition time, so nothing is re-decided per packet (`RESEARCH §3.6-B5`).
13
+
14
+ Internal. Schemas and channels are the public surface.
15
+ ]=]
16
+
17
+ --[[
18
+ The asymmetry in this file is deliberate and is the whole security posture:
19
+
20
+ encode errors loudly. The value came from the game's own code, so a number outside its
21
+ declared range is a bug, and the alternative is silent wraparound on the wire.
22
+ decode never errors. The value came off the wire, and a malicious client must not be able
23
+ to abort a batch by sending a byte (`RESEARCH §3.8-R`, `DESIGN-API` G4). Every
24
+ failure is routed through `Buffer.reject` and surfaces as a value from `read`.
25
+
26
+ `assert` appears nowhere below. CLAUDE.md §4 reserves it for programmer error, and on this
27
+ path programmer error is already covered by `error` with a message naming the field.
28
+ ]]
29
+
30
+ local Buffer = require("./Buffer")
31
+ local Ir = require("./Ir")
32
+ local Types = require("../types")
33
+
34
+ type Node = Ir.Node
35
+ type Field = Ir.Field
36
+ type Scope = Ir.Scope
37
+ type Encoding = Types.Encoding
38
+
39
+ --[[
40
+ Flags are threaded as a parameter rather than held in module state so that a scope is entered
41
+ and left by an ordinary call, and so nothing has to be unwound when a decode is abandoned.
42
+ ]]
43
+ type Flags = { number }
44
+ type Writer = (value: any, flags: Flags) -> ()
45
+ type Reader = (flags: Flags) -> any
46
+
47
+ local bor = bit32.bor
48
+ local band = bit32.band
49
+ local rshift = bit32.rshift
50
+
51
+ --[[ A node with no flags still takes the parameter; it is cheaper than branching on nil. ]]
52
+ local NO_FLAGS: Flags = table.freeze({}) :: any
53
+
54
+ local UNIT_TOLERANCE = 1e-3
55
+
56
+ --[[
57
+ A compact cframe's three kept quaternion components are at most 1/sqrt(2) in magnitude, so an
58
+ `i16` is scaled to exactly that bound.
59
+
60
+ And their squares sum to at most **3/4**, not to 1: the component that was dropped is the
61
+ largest, so it is at least 1/2, and the other three carry what is left. A reader that allowed 1
62
+ would accept a packing whose "largest" was not the largest — measured while writing
63
+ `spike/additions/f_quaternion.luau`, whose worst honest sum over 200,000 random rotations is
64
+ 0.7417. The slack is what three half-steps of rounding can add to a sum that was exactly 3/4.
65
+ ]]
66
+ local QUATERNION_SCALE = 32767 * math.sqrt(2)
67
+ local QUATERNION_MAX_REST = 0.75 + 3 * (1 / QUATERNION_SCALE)
68
+
69
+ --[[ `table.create` is `{unknown}`, and Luau arrays are invariant. Centralised so the cast is
70
+ written once rather than at every call site. Same helper as `Ir.sized`. ]]
71
+ local function sized(count: number): any
72
+ return table.create(count)
73
+ end
74
+
75
+ --[[ A double put through the rounding `buffer.writef32` will do to it. Four bytes of scratch rather
76
+ than the outgoing buffer, because this runs while closures are being built and the outgoing
77
+ buffer may be holding a batch. ]]
78
+ local rounding = buffer.create(4)
79
+
80
+ local function asF32(value: number): number
81
+ buffer.writef32(rounding, 0, value)
82
+ return buffer.readf32(rounding, 0)
83
+ end
84
+
85
+ local function isFinite(value: number): boolean
86
+ --[[ `value == value` is the NaN test; a rejected NaN would otherwise pass a range check by
87
+ failing every comparison in the wrong direction. ]]
88
+ return value == value and value ~= math.huge and value ~= -math.huge
89
+ end
90
+
91
+ local WRITE_NUMBER: { [Encoding]: (value: number) -> () } = {
92
+ u8 = Buffer.writeU8,
93
+ u16 = Buffer.writeU16,
94
+ u32 = Buffer.writeU32,
95
+ i8 = Buffer.writeI8,
96
+ i16 = Buffer.writeI16,
97
+ i32 = Buffer.writeI32,
98
+ f32 = Buffer.writeF32,
99
+ f64 = Buffer.writeF64,
100
+ }
101
+
102
+ --[[
103
+ The same eight writers, for bytes an enclosing block has already claimed. `Serdes` chooses
104
+ between the two families once per node at closure-build time, from the layout, so nothing
105
+ branches per packet (`src/codec/Buffer.luau`, Blocks).
106
+ ]]
107
+ local PUT_NUMBER: { [Encoding]: (value: number) -> () } = {
108
+ u8 = Buffer.putU8,
109
+ u16 = Buffer.putU16,
110
+ u32 = Buffer.putU32,
111
+ i8 = Buffer.putI8,
112
+ i16 = Buffer.putI16,
113
+ i32 = Buffer.putI32,
114
+ f32 = Buffer.putF32,
115
+ f64 = Buffer.putF64,
116
+ }
117
+
118
+ local READ_NUMBER: { [Encoding]: () -> number } = {
119
+ u8 = Buffer.readU8,
120
+ u16 = Buffer.readU16,
121
+ u32 = Buffer.readU32,
122
+ i8 = Buffer.readI8,
123
+ i16 = Buffer.readI16,
124
+ i32 = Buffer.readI32,
125
+ f32 = Buffer.readF32,
126
+ f64 = Buffer.readF64,
127
+ }
128
+
129
+ --[[ Bitfield chunks are patched after the fact, so they need the by-width dispatch too. ]]
130
+ local PATCH_CHUNK: { [number]: (offset: number, value: number) -> () } = {
131
+ [1] = Buffer.patchU8,
132
+ [2] = Buffer.patchU16,
133
+ [4] = Buffer.patchU32,
134
+ }
135
+
136
+ local READ_CHUNK: { [number]: () -> number } = {
137
+ [1] = Buffer.readU8,
138
+ [2] = Buffer.readU16,
139
+ [4] = Buffer.readU32,
140
+ }
141
+
142
+ local claim = Buffer.claim
143
+ local span = Buffer.span
144
+ local reserve = Buffer.reserve
145
+ local reject = Buffer.reject
146
+ local remaining = Buffer.remaining
147
+ local rejected = Buffer.rejected
148
+ local openBlock = Buffer.openBlock
149
+ local closeBlock = Buffer.closeBlock
150
+ local writeString = Buffer.writeString
151
+ local readString = Buffer.readString
152
+ local writeBuffer = Buffer.writeBuffer
153
+ local readBuffer = Buffer.readBuffer
154
+ local writeInstance = Buffer.writeInstance
155
+ local readInstance = Buffer.readInstance
156
+
157
+ --[[
158
+ Is this sidecar entry an Instance, asked in a way that works in both places this code runs.
159
+
160
+ Inside Roblox the question is exact: `typeof` separates an Instance from a table, and a table is
161
+ precisely what a hostile `FireServer(buffer, { {} })` puts in the slot. Under lune there are no
162
+ Instances at all and the suite stands them in with tables (`CLAUDE.md` §6 on why
163
+ `roblox_runtime` exists), so the strict question would refuse every test that carries one.
164
+
165
+ The lune half asks the only thing this reader ever asks of an Instance: **does it answer
166
+ `:IsA`.** That is not an approximation chosen for convenience — it is the exact precondition the
167
+ line below needs, so a stand-in that satisfies it is a stand-in the reader cannot tell from the
168
+ real thing, and a hostile bare table fails it in both places rather than only in Studio.
169
+ `tests/harness.luau` builds the stand-ins so the suite cannot drift from that contract.
170
+ ]]
171
+ local ROBLOX = typeof(game) == "Instance"
172
+
173
+ local function isInstance(value: any): boolean
174
+ if ROBLOX then
175
+ return typeof(value) == "Instance"
176
+ end
177
+
178
+ return type(value) == "table" and type((value :: any).IsA) == "function"
179
+ end
180
+ local putU8 = Buffer.putU8
181
+ local putF32 = Buffer.putF32
182
+ local putString = Buffer.putString
183
+ local putBuffer = Buffer.putBuffer
184
+ local writeF32 = Buffer.writeF32
185
+ local readF32 = Buffer.readF32
186
+ local writeU8 = Buffer.writeU8
187
+ local readU8 = Buffer.readU8
188
+ local putI16 = Buffer.putI16
189
+ local writeI16 = Buffer.writeI16
190
+ local readI16 = Buffer.readI16
191
+
192
+ --[[
193
+ Whether the subtree currently being built sits inside a claimed block.
194
+
195
+ A build-time flag rather than a parameter threaded through nine builders, and safe because
196
+ synthesis is synchronous: `Serdes.build` runs to completion before anything else can call it. It
197
+ selects `PUT_NUMBER` over `WRITE_NUMBER` and `putString` over `writeString`, and is read only
198
+ while closures are being made — never while one runs.
199
+ ]]
200
+ local blocked = false
201
+
202
+ local Serdes = {}
203
+
204
+ local buildWriter: (node: Node) -> Writer
205
+ local buildReader: (node: Node) -> Reader
206
+
207
+ -- -------------------------------------------------------------------------------------------------
208
+ -- Scopes
209
+ -- -------------------------------------------------------------------------------------------------
210
+
211
+ --[[
212
+ Reserve, accumulate, backfill. The bitfield sits at the front of its scope but its bits are
213
+ only known once every value in the scope has been visited, so the bytes are reserved first and
214
+ patched last. Doing it the other way — a pre-pass to collect flags, then a write pass — walks
215
+ the value twice.
216
+
217
+ The accumulator is allocated once per scope-opening node and reused, which is safe because a
218
+ schema is a tree: a scope is never entered while it is already open. Writers and readers get
219
+ separate arrays anyway, so that reading a packet inside a send is not a hazard.
220
+ ]]
221
+ local function scopedWriter(scope: Scope, inner: Writer): Writer
222
+ local chunks = scope.chunks
223
+ local count = #chunks
224
+ local bytes = scope.bytes
225
+ local accumulator: Flags = table.create(count, 0)
226
+
227
+ local patches: { (offset: number, value: number) -> () } = sized(count)
228
+ local offsets: { number } = sized(count)
229
+
230
+ for index, chunk in chunks do
231
+ patches[index] = PATCH_CHUNK[chunk.width]
232
+ offsets[index] = chunk.offset
233
+ end
234
+
235
+ return function(value: any, _outer: Flags)
236
+ local base = reserve(bytes)
237
+
238
+ for index = 1, count do
239
+ accumulator[index] = 0
240
+ end
241
+
242
+ inner(value, accumulator)
243
+
244
+ for index = 1, count do
245
+ patches[index](base + offsets[index], accumulator[index])
246
+ end
247
+ end
248
+ end
249
+
250
+ local function scopedReader(scope: Scope, inner: Reader): Reader
251
+ local chunks = scope.chunks
252
+ local count = #chunks
253
+ local accumulator: Flags = table.create(count, 0)
254
+
255
+ local reads: { () -> number } = sized(count)
256
+
257
+ for index, chunk in chunks do
258
+ reads[index] = READ_CHUNK[chunk.width]
259
+ end
260
+
261
+ return function(_outer: Flags): any
262
+ --[[ Chunks are contiguous and emitted in offset order, so reading them in order leaves
263
+ the cursor exactly at the first value. ]]
264
+ for index = 1, count do
265
+ accumulator[index] = reads[index]()
266
+ end
267
+
268
+ return inner(accumulator)
269
+ end
270
+ end
271
+
272
+ --[[ Wraps a child that opens a bitfield of its own: a dynamic array's element, a map's key or
273
+ value. Everything else inherits the enclosing scope. ]]
274
+ local function writerFor(node: Node): Writer
275
+ local writer = buildWriter(node)
276
+ local scope = node.scope
277
+ return if scope then scopedWriter(scope, writer) else writer
278
+ end
279
+
280
+ local function readerFor(node: Node): Reader
281
+ local reader = buildReader(node)
282
+ local scope = node.scope
283
+ return if scope then scopedReader(scope, reader) else reader
284
+ end
285
+
286
+ -- -------------------------------------------------------------------------------------------------
287
+ -- Lengths
288
+ -- -------------------------------------------------------------------------------------------------
289
+
290
+ --[[
291
+ A length that survives the round trip. The prefix is narrowed against the declared span, so a
292
+ byte can carry a count the schema forbids; `checkLength` is where that is caught, and it is
293
+ the single most load-bearing rejection in the codec — everything downstream of it allocates.
294
+ ]]
295
+ local function lengthWriter(node: Node): (count: number, label: string) -> ()
296
+ local exact = node.count
297
+
298
+ if exact then
299
+ return function(count: number, label: string)
300
+ if count ~= exact then
301
+ error(`[netweave] {label} must hold exactly {exact}, got {count}`)
302
+ end
303
+ end
304
+ end
305
+
306
+ local family: { [Encoding]: (value: number) -> () } = if blocked then PUT_NUMBER else WRITE_NUMBER
307
+ local write = family[node.lengthStorage :: Encoding]
308
+ local offset = node.lengthOffset :: number
309
+ local min = node.min :: number
310
+ local max = node.max :: number
311
+
312
+ return function(count: number, label: string)
313
+ if count < min or count > max then
314
+ error(`[netweave] {label} holds {count}, outside the declared {min}..{max}`)
315
+ end
316
+
317
+ write(count - offset)
318
+ end
319
+ end
320
+
321
+ --[[ Returns the count, or -1 when the stream did not justify one. -1 rather than nil so callers
322
+ stay on a single numeric path. ]]
323
+ local function lengthReader(node: Node): () -> number
324
+ local exact = node.count
325
+
326
+ if exact then
327
+ return function(): number
328
+ return exact
329
+ end
330
+ end
331
+
332
+ local read = READ_NUMBER[node.lengthStorage :: Encoding]
333
+ local offset = node.lengthOffset :: number
334
+ local min = node.min :: number
335
+ local max = node.max :: number
336
+
337
+ return function(): number
338
+ local count = read() + offset
339
+
340
+ if count < min or count > max then
341
+ reject("length out of range")
342
+ return -1
343
+ end
344
+
345
+ return count
346
+ end
347
+ end
348
+
349
+ -- -------------------------------------------------------------------------------------------------
350
+ -- Writers
351
+ -- -------------------------------------------------------------------------------------------------
352
+
353
+ --[[
354
+ Which encodings cannot hold a fraction.
355
+
356
+ `buffer.writeu8(3.7)` truncates, and with an offset it is not even truncation: `-0.4` on
357
+ `t.i16(-100, 100)` becomes `99.6`, stores as `99` and reads back as `-1`. The range check passed
358
+ both, so a game that sent a float where it meant an integer got a different number on the far
359
+ side and no report — under a module header that promises the alternative to raising is "silent
360
+ wraparound", which is exactly what it was doing (`PLAN-M3` phase 9).
361
+
362
+ The test is captured per node rather than branched per value: a `f32` field pays one upvalue
363
+ read, an integer field pays a modulo, and neither pays a `type()` call.
364
+ ]]
365
+ local FRACTIONAL: { [string]: boolean } = { f32 = true, f64 = true }
366
+ table.freeze(FRACTIONAL)
367
+
368
+ local function numberWriter(node: Node): Writer
369
+ local family: { [Encoding]: (value: number) -> () } = if blocked then PUT_NUMBER else WRITE_NUMBER
370
+ local storage = node.storage :: Encoding
371
+ local write = family[storage]
372
+ local offset = node.offset :: number
373
+ local min = node.min :: number
374
+ local max = node.max :: number
375
+ --[[ Asked of the node rather than derived from the storage a second time. A `u53` lands on `f64`
376
+ storage and is still a whole number; a `t.f64` lands on the same storage and is not, and the
377
+ difference is a property of the declaration that only `Ir.lowerNumber` can see. ]]
378
+ local integral = node.whole == true
379
+ local step = node.step
380
+
381
+ --[[
382
+ Quantised: the wire carries the number of steps from the declared minimum, so the value is
383
+ divided rather than only shifted, and no whole-number check applies — carrying a fraction is
384
+ what it is for.
385
+
386
+ The rounding is `+ 0.5` and the primitive's own truncation rather than `math.round`, which is
387
+ a call this would pay per value. `value >= min` is checked one line above, so the quotient is
388
+ never negative and round-half-up is round-to-nearest here.
389
+ ]]
390
+ if step then
391
+ local inverse = 1 / step
392
+
393
+ return function(value: any, _flags: Flags)
394
+ if not (value >= min and value <= max) then
395
+ error(`[netweave] {value} is outside the declared range {min}..{max}`)
396
+ end
397
+
398
+ write((value - offset) * inverse + 0.5)
399
+ end
400
+ end
401
+
402
+ if offset == 0 then
403
+ return function(value: any, _flags: Flags)
404
+ if not (value >= min and value <= max) then
405
+ error(`[netweave] {value} is outside the declared range {min}..{max}`)
406
+ end
407
+
408
+ if integral and value % 1 ~= 0 then
409
+ error(`[netweave] {value} is not a whole number, and this field is stored as {storage}`)
410
+ end
411
+
412
+ write(value)
413
+ end
414
+ end
415
+
416
+ return function(value: any, _flags: Flags)
417
+ if not (value >= min and value <= max) then
418
+ error(`[netweave] {value} is outside the declared range {min}..{max}`)
419
+ end
420
+
421
+ if integral and value % 1 ~= 0 then
422
+ error(`[netweave] {value} is not a whole number, and this field is stored as {storage}`)
423
+ end
424
+
425
+ write(value - offset)
426
+ end
427
+ end
428
+
429
+ local function enumWriter(node: Node): Writer
430
+ local lookup = node.lookup :: { [string]: number }
431
+ local bits = node.bits
432
+
433
+ if bits == 0 then
434
+ --[[ One variant carries no information, so it costs no bits. The value is still checked,
435
+ because sending the wrong name is a bug worth naming. ]]
436
+ return function(value: any, _flags: Flags)
437
+ if lookup[value] == nil then
438
+ error(`[netweave] "{tostring(value)}" is not a variant of this enum`)
439
+ end
440
+ end
441
+ end
442
+
443
+ local chunks = node.tagChunks :: { number }
444
+ local masks = node.tagMasks :: { number }
445
+
446
+ return function(value: any, flags: Flags)
447
+ local index = lookup[value]
448
+
449
+ if index == nil then
450
+ error(`[netweave] "{tostring(value)}" is not a variant of this enum`)
451
+ end
452
+
453
+ local tag = index - 1
454
+
455
+ for bit = 1, bits do
456
+ if band(rshift(tag, bit - 1), 1) == 1 then
457
+ local chunk = chunks[bit]
458
+ flags[chunk] = bor(flags[chunk], masks[bit])
459
+ end
460
+ end
461
+ end
462
+ end
463
+
464
+ -- -------------------------------------------------------------------------------------------------
465
+ -- A struct of numbers, written in one claim
466
+ -- -------------------------------------------------------------------------------------------------
467
+
468
+ --[[
469
+ `PLAN-M4` phase 7, and the only optimisation in this file that came from a measurement rather
470
+ than from reading the generated output of a competitor.
471
+
472
+ `bench/profile.luau` takes one `ArrayHeavy` packet — 100 entities of six `u8` — apart rung by
473
+ rung. The ceiling, what Blink and Zap emit, is 2.1 us. netweave was 24.0 us, and the attribution
474
+ is not subtle: 10% is the range and whole-number checks the schema promises, 30% is one call per
475
+ value, and **52% is the closure per value and the struct walk that finds the field to hand it**.
476
+ A field of a six-field struct costs seven calls before a byte is written: the struct's, the
477
+ writer's, and the primitive's under that.
478
+
479
+ netweave cannot answer this the way they do. `loadstring` is off in Roblox and a build step is
480
+ the thing this library exists not to need, so there is no generated source to fall back on. What
481
+ is left is to **make the primitive wider rather than the loop shorter**: claim the struct's bytes
482
+ once and write them all, with the offsets computed at declaration time.
483
+
484
+ One other shape was priced first and lost outright, and it is written down so it is not tried
485
+ again: claim once but **keep the loop**, reading each field's offset and bounds out of parallel
486
+ arrays. 25.5 us — slower than doing nothing, because the array reads cost more than the calls
487
+ they save. That is what makes the unroll below non-negotiable rather than a matter of taste.
488
+
489
+ This lands at 12.7 us against 24.0 under lune, and 29.3 against 38.4 in Studio — **1.9x and
490
+ 1.31x**, both measured on the VM they are quoted for.
491
+
492
+ ~~It predicts the `ArrayHeavy` framerate gap closing from 1.55x to 1.28x.~~ **It did not.** The
493
+ Studio matrix that followed measured 85 FPS against Blink's 133, exactly where it was before.
494
+
495
+ The frame probe added afterwards says the frame *is* dominated by this path — 6.27 ms of an
496
+ 11.58 ms frame is the send loop, and the whole gap against Blink lives there — and that the
497
+ saving here is 1.96 ms of it. Those two do not add up to 0.3 ms of frame, and the probe that
498
+ settles it has not been run on the pre-phase-7 tree yet (`bench/RESULTS.md`, M4 phase 7).
499
+
500
+ So: this comment is a claim about **this function**, measured twice, on two VMs. It is not a
501
+ framerate claim, and the file that is allowed to make one is `bench/RESULTS.md`.
502
+
503
+ The unroll is eight blocks in one closure with an early return at each boundary, rather than
504
+ eight builders selected by arity. It is the same code either way; this way it is one thing to
505
+ read and one thing to get right.
506
+ ]]
507
+ --[[
508
+ **A storage as a number, so the write below can be a literal.**
509
+
510
+ This is the whole reason the unrolled body reads the way it does, and it took the probe three
511
+ tries to find it. `buffer.writeu8(out, offset, value)` written out is compiled to a *fastcall*:
512
+ the VM performs it inline, without building a call frame. The same function reached through a
513
+ table — held in an upvalue, which is what a schema-driven builder reaches for first — is an
514
+ ordinary call. `bench/profile.luau` keeps that version as its `dispatched` rung, identical in
515
+ every other respect, and prices the difference at **1.6x on the whole packet**: more than every
516
+ other layer of the encode put together, and the reason the first implementation of this returned
517
+ 10% against a probe promising 170%.
518
+
519
+ So the call site has to name the function, and the schema has to be a branch. Five branches, in
520
+ the order the encodings actually occur, and each of them a fastcall.
521
+
522
+ That is also the honest answer to why a code generator wins here at all, and it is checkable
523
+ rather than folklore: Blink's output writes `buffer.writeu8(...)` in as many words
524
+ (`bench/vendor/blink/Client.luau:187`) and so does Zap's (`bench/vendor/zap/Client.luau:1140`).
525
+ It is not that they avoid closures — netweave can too, and `fusedStructWriter` does. It is that a
526
+ generator emits the *name* of the primitive, and until this file did the same, netweave could
527
+ not (`RESEARCH §3.11-GG`).
528
+ ]]
529
+ --[[ Keyed by `Encoding` for the reason `Ir.ENCODING_SIZE` gives: the `code == nil` guard below
530
+ exists for an encoding missing from this table, and the analyser can see it now. ]]
531
+ local STORAGE_CODE: { [Encoding]: number } = {
532
+ u8 = 1,
533
+ u16 = 2,
534
+ u32 = 3,
535
+ f32 = 4,
536
+ f64 = 5,
537
+ }
538
+
539
+ --[[ Beyond this the unroll below stops and the general loop takes over. Eight covers an entity, a
540
+ transform, a stat block and an inventory row; a forty-field struct is a different shape of
541
+ problem and pays one call per field as it always did. ]]
542
+ local FUSED_MAX = 8
543
+
544
+ type Row = {
545
+ name: string,
546
+ at: number,
547
+ min: number,
548
+ max: number,
549
+ --[[ The same two bounds as the reader compares against, which for `f32` are not the same
550
+ numbers. The writer validates what the game passed, exactly as declared; the reader has to
551
+ accept what `buffer.writef32` rounded that to, or a schema refuses its own sender. See
552
+ `numberReader`, which carries the measurement. ]]
553
+ lo: number,
554
+ hi: number,
555
+ offset: number,
556
+ --[[ Quantisation. `scale` is `1/step` on the way out and `unit` is `step` on the way back; both
557
+ are 1 for an ordinary number, where neither is read. They are not folded into the arithmetic
558
+ above the branch chain — `bench/profile.luau` priced that at **6.7%** on every struct in the
559
+ library, control group flat — so the chain carries three more arms instead and a plain field
560
+ pays nothing for a feature it does not use. ]]
561
+ scale: number,
562
+ unit: number,
563
+ integral: boolean,
564
+ storage: Encoding,
565
+ code: number,
566
+ }
567
+
568
+ local BLANK: Row = {
569
+ name = "",
570
+ at = 0,
571
+ min = 0,
572
+ max = 0,
573
+ lo = 0,
574
+ hi = 0,
575
+ offset = 0,
576
+ scale = 1,
577
+ unit = 1,
578
+ integral = false,
579
+ storage = "u8",
580
+ code = 1,
581
+ }
582
+
583
+ --[[ Every field, or nothing. A struct with one string in it is not half fusable — the offsets after
584
+ that field are not known until it is written — so the test is over the whole struct. ]]
585
+ local function rowsOf(fields: { Field }): ({ Row }?, number)
586
+ local count = #fields
587
+
588
+ if count == 0 or count > FUSED_MAX then
589
+ return nil, 0
590
+ end
591
+
592
+ local rows: { Row } = sized(count)
593
+ local at = 0
594
+
595
+ for index, field in fields do
596
+ local node = field.node
597
+ local size = node.fixedSize
598
+ local storage = node.storage
599
+ local code = if storage then STORAGE_CODE[storage] else nil
600
+
601
+ --[[ `bits ~= 0` is the flag-carrying case — a boolean, an enum, an optional's presence bit —
602
+ and those are written into a scope rather than into bytes, so their position here is not
603
+ a byte offset at all.
604
+
605
+ A storage with no code is one the branch chain below cannot name, and the fallback is
606
+ the general writer rather than a guess: `Ir.lowerNumber` produces five of the eight, and
607
+ a sixth arriving later must be added there deliberately or it keeps today's speed. ]]
608
+ if node.kind ~= "number" or size == nil or size == 0 or node.bits ~= 0 or code == nil then
609
+ return nil, 0
610
+ end
611
+
612
+ --[[ A `u53` or `i53` whose range did not narrow is carried in an `f64` and still has to be a
613
+ whole number, which is a check the unroll below does not make. Folding it in would be a
614
+ test per field on every struct in the library for a shape few have — the same trade the
615
+ quantised arms are the answer to, and here the honest answer is the loop writer, which
616
+ asks it already. ]]
617
+ if node.whole and FRACTIONAL[storage :: string] then
618
+ return nil, 0
619
+ end
620
+
621
+ local min = node.min :: number
622
+ local max = node.max :: number
623
+ local step = node.step
624
+
625
+ rows[index] = {
626
+ name = field.name,
627
+ at = at,
628
+ min = min,
629
+ max = max,
630
+ lo = if storage == "f32" then asF32(min) else min,
631
+ hi = if storage == "f32" then asF32(max) else max,
632
+ offset = node.offset :: number,
633
+ scale = if step then 1 / step else 1,
634
+ unit = step or 1,
635
+ integral = node.whole == true,
636
+ --[[ `code == nil` above rejects a node with no storage, so this is narrowed by that guard
637
+ rather than by the annotation; the solver does not carry the narrowing across the
638
+ table literal. ]]
639
+ storage = storage :: Encoding,
640
+ --[[ Quantised codes are the plain ones plus five, so the chain keeps `u8` first and a field
641
+ that is not quantised never reaches the three arms that are. ]]
642
+ code = if step then code + 5 else code,
643
+ }
644
+
645
+ at += size
646
+ end
647
+
648
+ return rows, at
649
+ end
650
+
651
+ --[[
652
+ The cold half of every check below, so the hot half is one branch that is almost always false.
653
+
654
+ It re-asks the question rather than being told which test failed, because getting here at all
655
+ means an `error` is about to be raised and the answer is a string built from an interpolation.
656
+ The messages are `numberWriter`'s, word for word: a schema that refuses a value has to say the
657
+ same thing whichever writer refused it.
658
+ ]]
659
+ local function refuseField(row: Row, value: any): ()
660
+ if value == nil then
661
+ error(`[netweave] field "{row.name}" is missing`)
662
+ end
663
+
664
+ if not (value >= row.min and value <= row.max) then
665
+ error(`[netweave] {value} is outside the declared range {row.min}..{row.max}`)
666
+ end
667
+
668
+ error(`[netweave] {value} is not a whole number, and this field is stored as {row.storage}`)
669
+ end
670
+
671
+ local function fusedStructWriter(fields: { Field }): Writer?
672
+ local rows, size = rowsOf(fields)
673
+
674
+ if rows == nil then
675
+ return nil
676
+ end
677
+
678
+ local count = #rows
679
+
680
+ local r1, r2 = rows[1], rows[2] or BLANK
681
+ local r3, r4 = rows[3] or BLANK, rows[4] or BLANK
682
+ local r5, r6 = rows[5] or BLANK, rows[6] or BLANK
683
+ local r7, r8 = rows[7] or BLANK, rows[8] or BLANK
684
+
685
+ local n1, a1, i1, o1, s1, lo1, hi1 = r1.name, r1.at, r1.integral, r1.offset, r1.code, r1.min, r1.max
686
+ local k1 = r1.scale
687
+ local n2, a2, i2, o2, s2, lo2, hi2 = r2.name, r2.at, r2.integral, r2.offset, r2.code, r2.min, r2.max
688
+ local k2 = r2.scale
689
+ local n3, a3, i3, o3, s3, lo3, hi3 = r3.name, r3.at, r3.integral, r3.offset, r3.code, r3.min, r3.max
690
+ local k3 = r3.scale
691
+ local n4, a4, i4, o4, s4, lo4, hi4 = r4.name, r4.at, r4.integral, r4.offset, r4.code, r4.min, r4.max
692
+ local k4 = r4.scale
693
+ local n5, a5, i5, o5, s5, lo5, hi5 = r5.name, r5.at, r5.integral, r5.offset, r5.code, r5.min, r5.max
694
+ local k5 = r5.scale
695
+ local n6, a6, i6, o6, s6, lo6, hi6 = r6.name, r6.at, r6.integral, r6.offset, r6.code, r6.min, r6.max
696
+ local k6 = r6.scale
697
+ local n7, a7, i7, o7, s7, lo7, hi7 = r7.name, r7.at, r7.integral, r7.offset, r7.code, r7.min, r7.max
698
+ local k7 = r7.scale
699
+ local n8, a8, i8, o8, s8, lo8, hi8 = r8.name, r8.at, r8.integral, r8.offset, r8.code, r8.min, r8.max
700
+ local k8 = r8.scale
701
+
702
+ --[[
703
+ The claim happens before the first check, so a struct that raises half way through has moved
704
+ the cursor past bytes it never wrote. That is the same contract `Serdes.build` already
705
+ documents — a write that raises leaves the buffer where it left it and the caller rewinds —
706
+ and every caller on the send path does exactly that (`Batch.writeBody`, `Serdes.check`).
707
+ ]]
708
+ return function(value: any, _flags: Flags)
709
+ local out, at = claim(size)
710
+
711
+ local v1 = value[n1]
712
+
713
+ if v1 == nil or not (v1 >= lo1 and v1 <= hi1) or (i1 and v1 % 1 ~= 0) then
714
+ refuseField(r1, v1)
715
+ end
716
+
717
+ local to1 = at + a1
718
+ local raw1 = v1 - o1
719
+
720
+ if s1 == 1 then
721
+ buffer.writeu8(out, to1, raw1)
722
+ elseif s1 == 2 then
723
+ buffer.writeu16(out, to1, raw1)
724
+ elseif s1 == 3 then
725
+ buffer.writeu32(out, to1, raw1)
726
+ elseif s1 == 4 then
727
+ buffer.writef32(out, to1, raw1)
728
+ elseif s1 == 5 then
729
+ buffer.writef64(out, to1, raw1)
730
+ elseif s1 == 6 then
731
+ buffer.writeu8(out, to1, raw1 * k1 + 0.5)
732
+ elseif s1 == 7 then
733
+ buffer.writeu16(out, to1, raw1 * k1 + 0.5)
734
+ else
735
+ buffer.writeu32(out, to1, raw1 * k1 + 0.5)
736
+ end
737
+
738
+ if count < 2 then
739
+ return
740
+ end
741
+
742
+ local v2 = value[n2]
743
+
744
+ if v2 == nil or not (v2 >= lo2 and v2 <= hi2) or (i2 and v2 % 1 ~= 0) then
745
+ refuseField(r2, v2)
746
+ end
747
+
748
+ local to2 = at + a2
749
+ local raw2 = v2 - o2
750
+
751
+ if s2 == 1 then
752
+ buffer.writeu8(out, to2, raw2)
753
+ elseif s2 == 2 then
754
+ buffer.writeu16(out, to2, raw2)
755
+ elseif s2 == 3 then
756
+ buffer.writeu32(out, to2, raw2)
757
+ elseif s2 == 4 then
758
+ buffer.writef32(out, to2, raw2)
759
+ elseif s2 == 5 then
760
+ buffer.writef64(out, to2, raw2)
761
+ elseif s2 == 6 then
762
+ buffer.writeu8(out, to2, raw2 * k2 + 0.5)
763
+ elseif s2 == 7 then
764
+ buffer.writeu16(out, to2, raw2 * k2 + 0.5)
765
+ else
766
+ buffer.writeu32(out, to2, raw2 * k2 + 0.5)
767
+ end
768
+
769
+ if count < 3 then
770
+ return
771
+ end
772
+
773
+ local v3 = value[n3]
774
+
775
+ if v3 == nil or not (v3 >= lo3 and v3 <= hi3) or (i3 and v3 % 1 ~= 0) then
776
+ refuseField(r3, v3)
777
+ end
778
+
779
+ local to3 = at + a3
780
+ local raw3 = v3 - o3
781
+
782
+ if s3 == 1 then
783
+ buffer.writeu8(out, to3, raw3)
784
+ elseif s3 == 2 then
785
+ buffer.writeu16(out, to3, raw3)
786
+ elseif s3 == 3 then
787
+ buffer.writeu32(out, to3, raw3)
788
+ elseif s3 == 4 then
789
+ buffer.writef32(out, to3, raw3)
790
+ elseif s3 == 5 then
791
+ buffer.writef64(out, to3, raw3)
792
+ elseif s3 == 6 then
793
+ buffer.writeu8(out, to3, raw3 * k3 + 0.5)
794
+ elseif s3 == 7 then
795
+ buffer.writeu16(out, to3, raw3 * k3 + 0.5)
796
+ else
797
+ buffer.writeu32(out, to3, raw3 * k3 + 0.5)
798
+ end
799
+
800
+ if count < 4 then
801
+ return
802
+ end
803
+
804
+ local v4 = value[n4]
805
+
806
+ if v4 == nil or not (v4 >= lo4 and v4 <= hi4) or (i4 and v4 % 1 ~= 0) then
807
+ refuseField(r4, v4)
808
+ end
809
+
810
+ local to4 = at + a4
811
+ local raw4 = v4 - o4
812
+
813
+ if s4 == 1 then
814
+ buffer.writeu8(out, to4, raw4)
815
+ elseif s4 == 2 then
816
+ buffer.writeu16(out, to4, raw4)
817
+ elseif s4 == 3 then
818
+ buffer.writeu32(out, to4, raw4)
819
+ elseif s4 == 4 then
820
+ buffer.writef32(out, to4, raw4)
821
+ elseif s4 == 5 then
822
+ buffer.writef64(out, to4, raw4)
823
+ elseif s4 == 6 then
824
+ buffer.writeu8(out, to4, raw4 * k4 + 0.5)
825
+ elseif s4 == 7 then
826
+ buffer.writeu16(out, to4, raw4 * k4 + 0.5)
827
+ else
828
+ buffer.writeu32(out, to4, raw4 * k4 + 0.5)
829
+ end
830
+
831
+ if count < 5 then
832
+ return
833
+ end
834
+
835
+ local v5 = value[n5]
836
+
837
+ if v5 == nil or not (v5 >= lo5 and v5 <= hi5) or (i5 and v5 % 1 ~= 0) then
838
+ refuseField(r5, v5)
839
+ end
840
+
841
+ local to5 = at + a5
842
+ local raw5 = v5 - o5
843
+
844
+ if s5 == 1 then
845
+ buffer.writeu8(out, to5, raw5)
846
+ elseif s5 == 2 then
847
+ buffer.writeu16(out, to5, raw5)
848
+ elseif s5 == 3 then
849
+ buffer.writeu32(out, to5, raw5)
850
+ elseif s5 == 4 then
851
+ buffer.writef32(out, to5, raw5)
852
+ elseif s5 == 5 then
853
+ buffer.writef64(out, to5, raw5)
854
+ elseif s5 == 6 then
855
+ buffer.writeu8(out, to5, raw5 * k5 + 0.5)
856
+ elseif s5 == 7 then
857
+ buffer.writeu16(out, to5, raw5 * k5 + 0.5)
858
+ else
859
+ buffer.writeu32(out, to5, raw5 * k5 + 0.5)
860
+ end
861
+
862
+ if count < 6 then
863
+ return
864
+ end
865
+
866
+ local v6 = value[n6]
867
+
868
+ if v6 == nil or not (v6 >= lo6 and v6 <= hi6) or (i6 and v6 % 1 ~= 0) then
869
+ refuseField(r6, v6)
870
+ end
871
+
872
+ local to6 = at + a6
873
+ local raw6 = v6 - o6
874
+
875
+ if s6 == 1 then
876
+ buffer.writeu8(out, to6, raw6)
877
+ elseif s6 == 2 then
878
+ buffer.writeu16(out, to6, raw6)
879
+ elseif s6 == 3 then
880
+ buffer.writeu32(out, to6, raw6)
881
+ elseif s6 == 4 then
882
+ buffer.writef32(out, to6, raw6)
883
+ elseif s6 == 5 then
884
+ buffer.writef64(out, to6, raw6)
885
+ elseif s6 == 6 then
886
+ buffer.writeu8(out, to6, raw6 * k6 + 0.5)
887
+ elseif s6 == 7 then
888
+ buffer.writeu16(out, to6, raw6 * k6 + 0.5)
889
+ else
890
+ buffer.writeu32(out, to6, raw6 * k6 + 0.5)
891
+ end
892
+
893
+ if count < 7 then
894
+ return
895
+ end
896
+
897
+ local v7 = value[n7]
898
+
899
+ if v7 == nil or not (v7 >= lo7 and v7 <= hi7) or (i7 and v7 % 1 ~= 0) then
900
+ refuseField(r7, v7)
901
+ end
902
+
903
+ local to7 = at + a7
904
+ local raw7 = v7 - o7
905
+
906
+ if s7 == 1 then
907
+ buffer.writeu8(out, to7, raw7)
908
+ elseif s7 == 2 then
909
+ buffer.writeu16(out, to7, raw7)
910
+ elseif s7 == 3 then
911
+ buffer.writeu32(out, to7, raw7)
912
+ elseif s7 == 4 then
913
+ buffer.writef32(out, to7, raw7)
914
+ elseif s7 == 5 then
915
+ buffer.writef64(out, to7, raw7)
916
+ elseif s7 == 6 then
917
+ buffer.writeu8(out, to7, raw7 * k7 + 0.5)
918
+ elseif s7 == 7 then
919
+ buffer.writeu16(out, to7, raw7 * k7 + 0.5)
920
+ else
921
+ buffer.writeu32(out, to7, raw7 * k7 + 0.5)
922
+ end
923
+
924
+ if count < 8 then
925
+ return
926
+ end
927
+
928
+ local v8 = value[n8]
929
+
930
+ if v8 == nil or not (v8 >= lo8 and v8 <= hi8) or (i8 and v8 % 1 ~= 0) then
931
+ refuseField(r8, v8)
932
+ end
933
+
934
+ local to8 = at + a8
935
+ local raw8 = v8 - o8
936
+
937
+ if s8 == 1 then
938
+ buffer.writeu8(out, to8, raw8)
939
+ elseif s8 == 2 then
940
+ buffer.writeu16(out, to8, raw8)
941
+ elseif s8 == 3 then
942
+ buffer.writeu32(out, to8, raw8)
943
+ elseif s8 == 4 then
944
+ buffer.writef32(out, to8, raw8)
945
+ elseif s8 == 5 then
946
+ buffer.writef64(out, to8, raw8)
947
+ elseif s8 == 6 then
948
+ buffer.writeu8(out, to8, raw8 * k8 + 0.5)
949
+ elseif s8 == 7 then
950
+ buffer.writeu16(out, to8, raw8 * k8 + 0.5)
951
+ else
952
+ buffer.writeu32(out, to8, raw8 * k8 + 0.5)
953
+ end
954
+ end
955
+ end
956
+
957
+ --[[
958
+ A tag, then whichever branch it names.
959
+
960
+ The tag half is `enumWriter`'s, bit for bit, because that is what it is — the difference is only
961
+ that a union's index also selects a writer. The bits go into the *enclosing* scope, and so do the
962
+ chosen branch's, forked so that branch A's first flag and branch B's first flag are the same bit
963
+ (`Ir.assignBits`). Nothing here has to know that: `flags` is the same accumulator either way.
964
+
965
+ A single-branch union carries no tag at all — the index is known — which is why `tagChunks` may
966
+ be absent rather than empty.
967
+ ]]
968
+ local function unionWriter(node: Node): Writer
969
+ local lookup = node.lookup :: { [string]: number }
970
+ local branches = node.branches :: { Field }
971
+
972
+ local writers: { Writer } = sized(#branches)
973
+
974
+ for index, branch in branches do
975
+ writers[index] = buildWriter(branch.node)
976
+ end
977
+
978
+ local chunks = node.tagChunks
979
+ local masks = node.tagMasks
980
+ local bits = if chunks then #chunks else 0
981
+
982
+ return function(value: any, flags: Flags)
983
+ if type(value) ~= "table" then
984
+ error(
985
+ `[netweave] a union field was given {typeof(value)}, and it takes a tag and a value: `
986
+ .. `\{ tag = "move", value = ... \}`
987
+ )
988
+ end
989
+
990
+ local index = lookup[value.tag]
991
+
992
+ if index == nil then
993
+ error(`[netweave] "{tostring(value.tag)}" is not a branch of this union`)
994
+ end
995
+
996
+ if bits > 0 then
997
+ local tag = index - 1
998
+ local positions = chunks :: { number }
999
+ local bitmasks = masks :: { number }
1000
+
1001
+ for bit = 1, bits do
1002
+ if band(rshift(tag, bit - 1), 1) == 1 then
1003
+ local chunk = positions[bit]
1004
+ flags[chunk] = bor(flags[chunk], bitmasks[bit])
1005
+ end
1006
+ end
1007
+ end
1008
+
1009
+ writers[index](value.value, flags)
1010
+ end
1011
+ end
1012
+
1013
+ local function structWriter(node: Node): Writer
1014
+ local fields = node.fields :: { Field }
1015
+ local count = #fields
1016
+
1017
+ local fused = fusedStructWriter(fields)
1018
+
1019
+ if fused then
1020
+ return fused
1021
+ end
1022
+
1023
+ local names: { string } = sized(count)
1024
+ local writers: { Writer } = sized(count)
1025
+ local required: { boolean } = sized(count)
1026
+
1027
+ for index, field in fields do
1028
+ names[index] = field.name
1029
+ writers[index] = buildWriter(field.node)
1030
+ required[index] = field.node.kind ~= "optional"
1031
+ end
1032
+
1033
+ return function(value: any, flags: Flags)
1034
+ for index = 1, count do
1035
+ local field = value[names[index]]
1036
+
1037
+ --[[ Without this the failure is a native error inside `buffer.write*` that names a
1038
+ byte offset instead of a field, which is useless in a schema of forty fields. ]]
1039
+ if field == nil and required[index] then
1040
+ error(`[netweave] field "{names[index]}" is missing`)
1041
+ end
1042
+
1043
+ writers[index](field, flags)
1044
+ end
1045
+ end
1046
+ end
1047
+
1048
+ local function arrayWriter(node: Node): Writer
1049
+ local writeLength = lengthWriter(node)
1050
+ local exact = node.count
1051
+ local elements = node.elements
1052
+
1053
+ --[[
1054
+ An exact array of optionals is never measured. `#` on a table with nils is a border the VM
1055
+ chooses, so `{1, 2, 3, nil}` on a length of four was refused as "got 3" while
1056
+ `{1, nil, nil, 4}` was accepted — the same shape, decided by how the table was built (M4-1).
1057
+ Every position is written, and a missing one is what the element's flag is for. A
1058
+ non-optional element keeps the count check, because there `#` is exact and the message
1059
+ names the length rather than a nil three fields in.
1060
+ ]]
1061
+ local sparse = (node.element :: Node).kind == "optional"
1062
+
1063
+ if elements then
1064
+ --[[ An exact length whose element carries flags was unrolled: one node per position, each
1065
+ owning its own bit slots, so the writers are not interchangeable. ]]
1066
+ local count = #elements
1067
+ local writers: { Writer } = sized(count)
1068
+
1069
+ for index, element in elements do
1070
+ writers[index] = buildWriter(element)
1071
+ end
1072
+
1073
+ return function(value: any, flags: Flags)
1074
+ if not sparse then
1075
+ writeLength(#value, "array")
1076
+ end
1077
+
1078
+ for index = 1, count do
1079
+ writers[index](value[index], flags)
1080
+ end
1081
+ end
1082
+ end
1083
+
1084
+ local writeElement = writerFor(node.element :: Node)
1085
+
1086
+ if exact then
1087
+ return function(value: any, flags: Flags)
1088
+ if not sparse then
1089
+ writeLength(#value, "array")
1090
+ end
1091
+
1092
+ for index = 1, exact do
1093
+ writeElement(value[index], flags)
1094
+ end
1095
+ end
1096
+ end
1097
+
1098
+ return function(value: any, flags: Flags)
1099
+ local count = #value
1100
+ writeLength(count, "array")
1101
+
1102
+ for index = 1, count do
1103
+ writeElement(value[index], flags)
1104
+ end
1105
+ end
1106
+ end
1107
+
1108
+ local function mapWriter(node: Node): Writer
1109
+ local writeLength = lengthWriter(node)
1110
+ local writeKey = writerFor(node.key :: Node)
1111
+ local writeValue = writerFor(node.value :: Node)
1112
+
1113
+ return function(value: any, flags: Flags)
1114
+ --[[ A map has no `#`, so the count is a pass of its own. It is written before the entries
1115
+ because the reader has to size its loop before it sees one. ]]
1116
+ local count = 0
1117
+ for _ in value do
1118
+ count += 1
1119
+ end
1120
+
1121
+ writeLength(count, "map")
1122
+
1123
+ for key, entry in value do
1124
+ writeKey(key, flags)
1125
+ writeValue(entry, flags)
1126
+ end
1127
+ end
1128
+ end
1129
+
1130
+ function buildWriter(node: Node): Writer
1131
+ local kind = node.kind
1132
+
1133
+ if kind == "boolean" then
1134
+ local chunk = node.chunkIndex :: number
1135
+ local mask = node.mask :: number
1136
+
1137
+ --[[
1138
+ A boolean field takes a boolean, and this used to take anything.
1139
+
1140
+ `if value then` is truthiness, so `t.boolean` accepted `0`, `""` and `"false"` and put
1141
+ `true` on the wire for two of them. That is a silent type coercion across a wire whose
1142
+ whole purpose is that the type on the far side is the type that was declared — and
1143
+ `nw.validate` decides "conforms" by running this writer, so a DataStore row reading
1144
+ `{ admin = "false" }` came back branded `Trusted<T>` and truthy (`PLAN-M3` phase 9).
1145
+
1146
+ Written as two comparisons rather than a `type()` call: the common path is one, `false`
1147
+ is two, and nothing else reaches the wire.
1148
+ ]]
1149
+ return function(value: any, flags: Flags)
1150
+ if value == true then
1151
+ flags[chunk] = bor(flags[chunk], mask)
1152
+ elseif value ~= false then
1153
+ error(`[netweave] a boolean field was given {typeof(value)}`)
1154
+ end
1155
+ end
1156
+ elseif kind == "number" then
1157
+ return numberWriter(node)
1158
+ elseif kind == "string" then
1159
+ local writeLength = lengthWriter(node)
1160
+ local bytes: (value: string, length: number) -> () = if blocked then putString else writeString
1161
+
1162
+ --[[
1163
+ A string that says what it may contain gets a second closure. Built at declaration and
1164
+ only when something was declared, so a plain `t.string` is exactly what it was — the same
1165
+ trade `numberWriter` makes for an offset of zero.
1166
+
1167
+ The pattern is anchored here rather than stored anchored, so the descriptor and the
1168
+ protocol signature carry what the author wrote.
1169
+ ]]
1170
+ local anchored = if node.pattern then `^{node.pattern}$` else nil
1171
+ local unicode = node.utf8
1172
+
1173
+ if anchored or unicode then
1174
+ return function(value: any, _flags: Flags)
1175
+ local length = #value
1176
+
1177
+ if unicode and utf8.len(value) == nil then
1178
+ error(`[netweave] this string is not valid UTF-8, and the schema says it must be`)
1179
+ end
1180
+
1181
+ if anchored and not string.find(value, anchored :: string) then
1182
+ error(
1183
+ `[netweave] "{value}" does not match the pattern {node.pattern} the schema declares`
1184
+ )
1185
+ end
1186
+
1187
+ writeLength(length, "string")
1188
+ bytes(value, length)
1189
+ end
1190
+ end
1191
+
1192
+ return function(value: any, _flags: Flags)
1193
+ local length = #value
1194
+ writeLength(length, "string")
1195
+ bytes(value, length)
1196
+ end
1197
+ elseif kind == "buffer" then
1198
+ local writeLength = lengthWriter(node)
1199
+ local bytes: (value: buffer, length: number) -> () = if blocked then putBuffer else writeBuffer
1200
+
1201
+ return function(value: any, _flags: Flags)
1202
+ local length = buffer.len(value)
1203
+ writeLength(length, "buffer")
1204
+ bytes(value, length)
1205
+ end
1206
+ elseif kind == "vector2" then
1207
+ --[[ A named component is a number node like any other, so its writer already carries the
1208
+ range check, the offset and the quantisation. Bare stays the two named `f32` calls it
1209
+ was, because that is the common case and a component writer is a call per axis. ]]
1210
+ local component = node.element
1211
+
1212
+ if component then
1213
+ local axis = buildWriter(component)
1214
+
1215
+ return function(value: any, flags: Flags)
1216
+ axis(value.X, flags)
1217
+ axis(value.Y, flags)
1218
+ end
1219
+ end
1220
+
1221
+ local f32: (value: number) -> () = if blocked then putF32 else writeF32
1222
+
1223
+ return function(value: any, _flags: Flags)
1224
+ f32(value.X)
1225
+ f32(value.Y)
1226
+ end
1227
+ elseif kind == "vector3" then
1228
+ local component = node.element
1229
+
1230
+ if component then
1231
+ local axis = buildWriter(component)
1232
+
1233
+ return function(value: any, flags: Flags)
1234
+ axis(value.X, flags)
1235
+ axis(value.Y, flags)
1236
+ axis(value.Z, flags)
1237
+ end
1238
+ end
1239
+
1240
+ local f32: (value: number) -> () = if blocked then putF32 else writeF32
1241
+
1242
+ return function(value: any, _flags: Flags)
1243
+ f32(value.X)
1244
+ f32(value.Y)
1245
+ f32(value.Z)
1246
+ end
1247
+ elseif kind == "color3" then
1248
+ local u8: (value: number) -> () = if blocked then putU8 else writeU8
1249
+
1250
+ return function(value: any, _flags: Flags)
1251
+ u8(math.clamp(math.round(value.R * 255), 0, 255))
1252
+ u8(math.clamp(math.round(value.G * 255), 0, 255))
1253
+ u8(math.clamp(math.round(value.B * 255), 0, 255))
1254
+ end
1255
+ elseif kind == "cframe" then
1256
+ local component = node.element
1257
+
1258
+ if component then
1259
+ local axis = buildWriter(component)
1260
+ local chunks = node.tagChunks :: { number }
1261
+ local masks = node.tagMasks :: { number }
1262
+ local i16: (value: number) -> () = if blocked then putI16 else writeI16
1263
+
1264
+ --[[
1265
+ Smallest three. A unit quaternion's largest component is at least 1/2 in magnitude
1266
+ and the other three are at most 1/sqrt(2), so with the largest dropped the rest fit
1267
+ an `i16` scaled to that bound, and the sign of the dropped one is fixed positive by
1268
+ negating the whole quaternion — the same rotation either way. The index of the one
1269
+ left out is two bits in the bitfield.
1270
+ ]]
1271
+ return function(value: any, flags: Flags)
1272
+ local position = value.Position
1273
+ axis(position.X, flags)
1274
+ axis(position.Y, flags)
1275
+ axis(position.Z, flags)
1276
+
1277
+ local direction, angle = value:ToAxisAngle()
1278
+ local half = angle / 2
1279
+ local s = math.sin(half)
1280
+ local qx, qy, qz, qw = direction.X * s, direction.Y * s, direction.Z * s, math.cos(half)
1281
+
1282
+ local ax, ay, az, aw = math.abs(qx), math.abs(qy), math.abs(qz), math.abs(qw)
1283
+ local largest = 0
1284
+ local magnitude = ax
1285
+
1286
+ if ay > magnitude then
1287
+ largest, magnitude = 1, ay
1288
+ end
1289
+
1290
+ if az > magnitude then
1291
+ largest, magnitude = 2, az
1292
+ end
1293
+
1294
+ if aw > magnitude then
1295
+ largest = 3
1296
+ end
1297
+
1298
+ local sign = if (largest == 0 and qx < 0)
1299
+ or (largest == 1 and qy < 0)
1300
+ or (largest == 2 and qz < 0)
1301
+ or (largest == 3 and qw < 0)
1302
+ then -1
1303
+ else 1
1304
+
1305
+ for bit = 1, 2 do
1306
+ if band(rshift(largest, bit - 1), 1) == 1 then
1307
+ local chunk = chunks[bit]
1308
+ flags[chunk] = bor(flags[chunk], masks[bit])
1309
+ end
1310
+ end
1311
+
1312
+ if largest ~= 0 then
1313
+ i16(math.clamp(math.round(qx * sign * QUATERNION_SCALE), -32767, 32767))
1314
+ end
1315
+
1316
+ if largest ~= 1 then
1317
+ i16(math.clamp(math.round(qy * sign * QUATERNION_SCALE), -32767, 32767))
1318
+ end
1319
+
1320
+ if largest ~= 2 then
1321
+ i16(math.clamp(math.round(qz * sign * QUATERNION_SCALE), -32767, 32767))
1322
+ end
1323
+
1324
+ if largest ~= 3 then
1325
+ i16(math.clamp(math.round(qw * sign * QUATERNION_SCALE), -32767, 32767))
1326
+ end
1327
+ end
1328
+ end
1329
+
1330
+ local f32: (value: number) -> () = if blocked then putF32 else writeF32
1331
+
1332
+ return function(value: any, _flags: Flags)
1333
+ local position = value.Position
1334
+ f32(position.X)
1335
+ f32(position.Y)
1336
+ f32(position.Z)
1337
+
1338
+ --[[ Axis times angle: one vector carries the whole rotation, and the identity falls
1339
+ out as the zero vector rather than needing a special case on either side. ]]
1340
+ local axis, angle = value:ToAxisAngle()
1341
+ f32(axis.X * angle)
1342
+ f32(axis.Y * angle)
1343
+ f32(axis.Z * angle)
1344
+ end
1345
+ elseif kind == "instance" then
1346
+ local class = node.class
1347
+ local root = node.descendantOf
1348
+
1349
+ return function(value: any, _flags: Flags)
1350
+ if value == nil then
1351
+ error("[netweave] a non-optional instance field is nil")
1352
+ end
1353
+
1354
+ --[[ Anything non-nil used to go into the sidecar, so `nw.validate` said a number
1355
+ conformed to `t.instance("Player")` and branded it. The reader refuses the same
1356
+ shape on the way in; this is the send side of that check. ]]
1357
+ if not isInstance(value) then
1358
+ error(`[netweave] an instance field was given {typeof(value)}`)
1359
+ end
1360
+
1361
+ --[[ The class and the container, on the way out as well as in. The reader has always
1362
+ asked both; the writer asked only "is it an Instance", so `nw.validate` branded a
1363
+ `BasePart` as conforming to `t.instance("Sound")` and DESIGN-API's "exactly as strict
1364
+ as the encoder" was true and useless (M4 report, finding 23; M4-1). ]]
1365
+ if class and not value:IsA(class) then
1366
+ error(`[netweave] an instance field declared {class} was given a {value.ClassName}`)
1367
+ end
1368
+
1369
+ if root and not value:IsDescendantOf(root) then
1370
+ error(`[netweave] an instance field declared inside {root.Name} was given one outside it`)
1371
+ end
1372
+
1373
+ writeInstance(value)
1374
+ end
1375
+ elseif kind == "enum" then
1376
+ return enumWriter(node)
1377
+ elseif kind == "literal" then
1378
+ local literal = node.literal
1379
+
1380
+ --[[ Checked though nothing is written, for the same reason a one-variant enum checks its
1381
+ name: sending the wrong constant is a bug worth naming where it happens. ]]
1382
+ return function(value: any, _flags: Flags)
1383
+ if value ~= literal then
1384
+ error(
1385
+ `[netweave] {tostring(value)} is not the literal {tostring(literal)} this field declares`
1386
+ )
1387
+ end
1388
+ end
1389
+ elseif kind == "optional" then
1390
+ local chunk = node.chunkIndex :: number
1391
+ local mask = node.mask :: number
1392
+ local writeInner = buildWriter(node.inner :: Node)
1393
+ local default = node.default
1394
+
1395
+ if default ~= nil then
1396
+ --[[ The default is never sent: the reader hands it back for a clear bit, so writing it
1397
+ would spend the field's bytes on the value the other side already has. ]]
1398
+ return function(value: any, flags: Flags)
1399
+ if value == nil or value == default then
1400
+ return
1401
+ end
1402
+
1403
+ flags[chunk] = bor(flags[chunk], mask)
1404
+ writeInner(value, flags)
1405
+ end
1406
+ end
1407
+
1408
+ return function(value: any, flags: Flags)
1409
+ if value == nil then
1410
+ return
1411
+ end
1412
+
1413
+ flags[chunk] = bor(flags[chunk], mask)
1414
+ writeInner(value, flags)
1415
+ end
1416
+ elseif kind == "array" then
1417
+ return arrayWriter(node)
1418
+ elseif kind == "map" then
1419
+ return mapWriter(node)
1420
+ elseif kind == "struct" then
1421
+ return structWriter(node)
1422
+ elseif kind == "union" then
1423
+ return unionWriter(node)
1424
+ end
1425
+
1426
+ error(`[netweave] no writer for a "{kind}"`)
1427
+ end
1428
+
1429
+ -- -------------------------------------------------------------------------------------------------
1430
+ -- Readers
1431
+ -- -------------------------------------------------------------------------------------------------
1432
+
1433
+ local function numberReader(node: Node): Reader
1434
+ local read = READ_NUMBER[node.storage :: Encoding]
1435
+ local offset = node.offset :: number
1436
+ local min = node.min :: number
1437
+ local max = node.max :: number
1438
+ local storage = node.storage
1439
+ local step = node.step
1440
+
1441
+ --[[ Quantised, so the count of steps comes back multiplied. `max` is the reconstructed top
1442
+ (`Ir.lowerNumber`), which is exactly what the top level produces — so this refuses a count
1443
+ past the last level the schema declared and nothing that is inside it. ]]
1444
+ if step then
1445
+ return function(_flags: Flags): any
1446
+ local value = read() * step + offset
1447
+
1448
+ if value > max then
1449
+ reject("number out of range")
1450
+ return min
1451
+ end
1452
+
1453
+ return value
1454
+ end
1455
+ end
1456
+
1457
+ if storage == "f32" or storage == "f64" then
1458
+ --[[
1459
+ **The bound the reader compares against is the one the encoding can hold.**
1460
+
1461
+ The writer validates the value the game passed, as a double, against the bounds the game
1462
+ declared — that is the author's contract and it stays exact. Then `buffer.writef32`
1463
+ rounds, and if the bound itself is not an f32 value the rounding can land *outside* it:
1464
+ f32(pi) is 3.14159274 against pi's 3.14159265, so `t.f32(-pi, pi)` refused pi at
1465
+ `parse`, against its own sender, on a value the writer had just accepted.
1466
+
1467
+ It is not an edge: 2,054 of 4,000 random f32 ranges refused their own bounds when sent
1468
+ back, and the clamped value a game sends — `math.clamp(yaw, -math.pi, math.pi)` — is
1469
+ exactly the one that lands there. The worked example's `t.f32(-90, 90)` survived only
1470
+ because 90 happens to be dyadic.
1471
+
1472
+ Rounding to nearest is monotone, so comparing against `f32(min)` and `f32(max)` accepts
1473
+ everything the writer accepted and nothing wider than one ulp beyond the declaration.
1474
+ `f64` is exact for a double and is left alone.
1475
+ ]]
1476
+ if storage == "f32" then
1477
+ min = asF32(min)
1478
+ max = asF32(max)
1479
+ end
1480
+
1481
+ --[[
1482
+ **A `u53` is checked for wholeness on the way in as well as on the way out**, which is the
1483
+ gap it was added to close: the widest integer was `u32`, so a `UserId` had to be declared
1484
+ `t.f64` — a float, whose fractional-ness only the *writer* refused. A peer sending 1.5 on
1485
+ a field a game reads as an id got 1.5 delivered, and `Instance` lookups, table keys and
1486
+ datastore writes all behave differently for it.
1487
+
1488
+ Only on this branch, because a narrowed `u53` lands on an unsigned storage where the value
1489
+ is an integer by construction.
1490
+ ]]
1491
+ if node.whole then
1492
+ return function(_flags: Flags): any
1493
+ local value = read()
1494
+
1495
+ if not (value >= min and value <= max) or value % 1 ~= 0 then
1496
+ reject("number out of range")
1497
+ return min
1498
+ end
1499
+
1500
+ return value
1501
+ end
1502
+ end
1503
+
1504
+ return function(_flags: Flags): any
1505
+ local value = read()
1506
+
1507
+ --[[ A float arrives unnarrowed, so the range is a claim about the sender rather than a
1508
+ property of the encoding. NaN fails this comparison in both directions, which is
1509
+ the intent — it is the value that makes every downstream check pass by accident. ]]
1510
+ if not (value >= min and value <= max) then
1511
+ reject("number out of range")
1512
+ return min
1513
+ end
1514
+
1515
+ return value
1516
+ end
1517
+ end
1518
+
1519
+ return function(_flags: Flags): any
1520
+ --[[ Storage is unsigned and offset is the declared minimum, so the lower bound cannot be
1521
+ violated. The upper one can: a span of 200 is carried in a byte that holds 255. ]]
1522
+ local value = read() + offset
1523
+
1524
+ if value > max then
1525
+ reject("number out of range")
1526
+ return min
1527
+ end
1528
+
1529
+ return value
1530
+ end
1531
+ end
1532
+
1533
+ local function enumReader(node: Node): Reader
1534
+ local variants = node.variants :: { string }
1535
+ local bits = node.bits
1536
+ local first = variants[1]
1537
+
1538
+ if bits == 0 then
1539
+ return function(_flags: Flags): any
1540
+ return first
1541
+ end
1542
+ end
1543
+
1544
+ local chunks = node.tagChunks :: { number }
1545
+ local masks = node.tagMasks :: { number }
1546
+
1547
+ return function(flags: Flags): any
1548
+ local tag = 0
1549
+
1550
+ for bit = 1, bits do
1551
+ if band(flags[chunks[bit]], masks[bit]) ~= 0 then
1552
+ tag = bor(tag, bit32.lshift(1, bit - 1))
1553
+ end
1554
+ end
1555
+
1556
+ --[[ The tag has room the schema does not use whenever the variant count is not a power of
1557
+ two: three variants are two bits, and a sender can put 3 in them. ]]
1558
+ local name = variants[tag + 1]
1559
+
1560
+ if name == nil then
1561
+ reject("unknown enum variant")
1562
+ return first
1563
+ end
1564
+
1565
+ return name
1566
+ end
1567
+ end
1568
+
1569
+ --[[
1570
+ `fusedStructWriter`'s mirror, and the half of M2's block optimisation that never happened.
1571
+
1572
+ `Buffer.span` bounds the whole struct once, against a size the layout pass already knew, and the
1573
+ fields are then read with `buffer.readu8` **named** — so the general reader's three costs per
1574
+ value all go at once: the closure call, the `READ_NUMBER` lookup behind it, and the per-primitive
1575
+ bounds check that asked the same question the span already answered.
1576
+
1577
+ Measured by `bench/decode.luau` on the tree before this existed, 100 entities of six `u8` fields:
1578
+ the real reader 32,731 ns a packet against 8,100 for the same read written out with the range
1579
+ guard kept — **4.0x** — where the encode of the same payload was already fused. Decode is what a
1580
+ server pays per client per packet for a whole session, and it had never been taken apart.
1581
+
1582
+ The branch chain is not a matter of taste here either. `dispatched` in that file is this shape
1583
+ with the primitive fetched from a table instead of named, and it costs **2.6x** — worse than the
1584
+ 1.6x the same substitution costs on the write side (`RESEARCH §3.11-GG`).
1585
+
1586
+ Two things differ from the writer, and both come from G4 — wire data never reaches `error()`:
1587
+
1588
+ * a run that does not fit returns a struct of declared minimums rather than nil, and the packet
1589
+ is refused. **Not nil**, because a fused struct nested in a larger payload handing one up
1590
+ would drop its key, and the next field access on it raises — which is precisely what G4
1591
+ forbids. The contents are never seen either way: `Serdes.build`'s reader drops the value the
1592
+ moment a rejection exists, and `Buffer.reject` keeps the first reason, so what a peer is told
1593
+ is unchanged.
1594
+ * the range check compares against `lo`/`hi` rather than `min`/`max`, which for `f32` are the
1595
+ bounds the *encoding* can hold. `numberReader` carries the measurement that forced that.
1596
+ ]]
1597
+ local function fusedStructReader(node: Node): Reader?
1598
+ local rows, size = rowsOf(node.fields :: { Field })
1599
+
1600
+ if rows == nil then
1601
+ return nil
1602
+ end
1603
+
1604
+ local template = node.template :: { [string]: boolean }
1605
+ local count = #rows
1606
+
1607
+ --[[ What a truncated run comes back as, built once at declaration rather than per packet. Every
1608
+ field at the minimum its schema declared, which is what the per-value reader returned for a
1609
+ value it had to refuse. ]]
1610
+ local blank: { [string]: any } = table.clone(template) :: any
1611
+
1612
+ for _, row in rows do
1613
+ blank[row.name] = row.lo
1614
+ end
1615
+
1616
+ local r1, r2 = rows[1], rows[2] or BLANK
1617
+ local r3, r4 = rows[3] or BLANK, rows[4] or BLANK
1618
+ local r5, r6 = rows[5] or BLANK, rows[6] or BLANK
1619
+ local r7, r8 = rows[7] or BLANK, rows[8] or BLANK
1620
+
1621
+ local n1, a1, o1, s1, lo1, hi1, u1 = r1.name, r1.at, r1.offset, r1.code, r1.lo, r1.hi, r1.unit
1622
+ local n2, a2, o2, s2, lo2, hi2, u2 = r2.name, r2.at, r2.offset, r2.code, r2.lo, r2.hi, r2.unit
1623
+ local n3, a3, o3, s3, lo3, hi3, u3 = r3.name, r3.at, r3.offset, r3.code, r3.lo, r3.hi, r3.unit
1624
+ local n4, a4, o4, s4, lo4, hi4, u4 = r4.name, r4.at, r4.offset, r4.code, r4.lo, r4.hi, r4.unit
1625
+ local n5, a5, o5, s5, lo5, hi5, u5 = r5.name, r5.at, r5.offset, r5.code, r5.lo, r5.hi, r5.unit
1626
+ local n6, a6, o6, s6, lo6, hi6, u6 = r6.name, r6.at, r6.offset, r6.code, r6.lo, r6.hi, r6.unit
1627
+ local n7, a7, o7, s7, lo7, hi7, u7 = r7.name, r7.at, r7.offset, r7.code, r7.lo, r7.hi, r7.unit
1628
+ local n8, a8, o8, s8, lo8, hi8, u8 = r8.name, r8.at, r8.offset, r8.code, r8.lo, r8.hi, r8.unit
1629
+
1630
+ return function(_flags: Flags): any
1631
+ local src, at = span(size)
1632
+
1633
+ if src == nil then
1634
+ return table.clone(blank)
1635
+ end
1636
+
1637
+ local result: any = table.clone(template)
1638
+
1639
+ local at1 = at + a1
1640
+ local v1: number
1641
+
1642
+ if s1 == 1 then
1643
+ v1 = buffer.readu8(src, at1) + o1
1644
+ elseif s1 == 2 then
1645
+ v1 = buffer.readu16(src, at1) + o1
1646
+ elseif s1 == 3 then
1647
+ v1 = buffer.readu32(src, at1) + o1
1648
+ elseif s1 == 4 then
1649
+ v1 = buffer.readf32(src, at1) + o1
1650
+ elseif s1 == 5 then
1651
+ v1 = buffer.readf64(src, at1) + o1
1652
+ elseif s1 == 6 then
1653
+ v1 = buffer.readu8(src, at1) * u1 + o1
1654
+ elseif s1 == 7 then
1655
+ v1 = buffer.readu16(src, at1) * u1 + o1
1656
+ else
1657
+ v1 = buffer.readu32(src, at1) * u1 + o1
1658
+ end
1659
+
1660
+ if not (v1 >= lo1 and v1 <= hi1) then
1661
+ reject("number out of range")
1662
+ v1 = lo1
1663
+ end
1664
+
1665
+ result[n1] = v1
1666
+
1667
+ if count < 2 then
1668
+ return result
1669
+ end
1670
+
1671
+ local at2 = at + a2
1672
+ local v2: number
1673
+
1674
+ if s2 == 1 then
1675
+ v2 = buffer.readu8(src, at2) + o2
1676
+ elseif s2 == 2 then
1677
+ v2 = buffer.readu16(src, at2) + o2
1678
+ elseif s2 == 3 then
1679
+ v2 = buffer.readu32(src, at2) + o2
1680
+ elseif s2 == 4 then
1681
+ v2 = buffer.readf32(src, at2) + o2
1682
+ elseif s2 == 5 then
1683
+ v2 = buffer.readf64(src, at2) + o2
1684
+ elseif s2 == 6 then
1685
+ v2 = buffer.readu8(src, at2) * u2 + o2
1686
+ elseif s2 == 7 then
1687
+ v2 = buffer.readu16(src, at2) * u2 + o2
1688
+ else
1689
+ v2 = buffer.readu32(src, at2) * u2 + o2
1690
+ end
1691
+
1692
+ if not (v2 >= lo2 and v2 <= hi2) then
1693
+ reject("number out of range")
1694
+ v2 = lo2
1695
+ end
1696
+
1697
+ result[n2] = v2
1698
+
1699
+ if count < 3 then
1700
+ return result
1701
+ end
1702
+
1703
+ local at3 = at + a3
1704
+ local v3: number
1705
+
1706
+ if s3 == 1 then
1707
+ v3 = buffer.readu8(src, at3) + o3
1708
+ elseif s3 == 2 then
1709
+ v3 = buffer.readu16(src, at3) + o3
1710
+ elseif s3 == 3 then
1711
+ v3 = buffer.readu32(src, at3) + o3
1712
+ elseif s3 == 4 then
1713
+ v3 = buffer.readf32(src, at3) + o3
1714
+ elseif s3 == 5 then
1715
+ v3 = buffer.readf64(src, at3) + o3
1716
+ elseif s3 == 6 then
1717
+ v3 = buffer.readu8(src, at3) * u3 + o3
1718
+ elseif s3 == 7 then
1719
+ v3 = buffer.readu16(src, at3) * u3 + o3
1720
+ else
1721
+ v3 = buffer.readu32(src, at3) * u3 + o3
1722
+ end
1723
+
1724
+ if not (v3 >= lo3 and v3 <= hi3) then
1725
+ reject("number out of range")
1726
+ v3 = lo3
1727
+ end
1728
+
1729
+ result[n3] = v3
1730
+
1731
+ if count < 4 then
1732
+ return result
1733
+ end
1734
+
1735
+ local at4 = at + a4
1736
+ local v4: number
1737
+
1738
+ if s4 == 1 then
1739
+ v4 = buffer.readu8(src, at4) + o4
1740
+ elseif s4 == 2 then
1741
+ v4 = buffer.readu16(src, at4) + o4
1742
+ elseif s4 == 3 then
1743
+ v4 = buffer.readu32(src, at4) + o4
1744
+ elseif s4 == 4 then
1745
+ v4 = buffer.readf32(src, at4) + o4
1746
+ elseif s4 == 5 then
1747
+ v4 = buffer.readf64(src, at4) + o4
1748
+ elseif s4 == 6 then
1749
+ v4 = buffer.readu8(src, at4) * u4 + o4
1750
+ elseif s4 == 7 then
1751
+ v4 = buffer.readu16(src, at4) * u4 + o4
1752
+ else
1753
+ v4 = buffer.readu32(src, at4) * u4 + o4
1754
+ end
1755
+
1756
+ if not (v4 >= lo4 and v4 <= hi4) then
1757
+ reject("number out of range")
1758
+ v4 = lo4
1759
+ end
1760
+
1761
+ result[n4] = v4
1762
+
1763
+ if count < 5 then
1764
+ return result
1765
+ end
1766
+
1767
+ local at5 = at + a5
1768
+ local v5: number
1769
+
1770
+ if s5 == 1 then
1771
+ v5 = buffer.readu8(src, at5) + o5
1772
+ elseif s5 == 2 then
1773
+ v5 = buffer.readu16(src, at5) + o5
1774
+ elseif s5 == 3 then
1775
+ v5 = buffer.readu32(src, at5) + o5
1776
+ elseif s5 == 4 then
1777
+ v5 = buffer.readf32(src, at5) + o5
1778
+ elseif s5 == 5 then
1779
+ v5 = buffer.readf64(src, at5) + o5
1780
+ elseif s5 == 6 then
1781
+ v5 = buffer.readu8(src, at5) * u5 + o5
1782
+ elseif s5 == 7 then
1783
+ v5 = buffer.readu16(src, at5) * u5 + o5
1784
+ else
1785
+ v5 = buffer.readu32(src, at5) * u5 + o5
1786
+ end
1787
+
1788
+ if not (v5 >= lo5 and v5 <= hi5) then
1789
+ reject("number out of range")
1790
+ v5 = lo5
1791
+ end
1792
+
1793
+ result[n5] = v5
1794
+
1795
+ if count < 6 then
1796
+ return result
1797
+ end
1798
+
1799
+ local at6 = at + a6
1800
+ local v6: number
1801
+
1802
+ if s6 == 1 then
1803
+ v6 = buffer.readu8(src, at6) + o6
1804
+ elseif s6 == 2 then
1805
+ v6 = buffer.readu16(src, at6) + o6
1806
+ elseif s6 == 3 then
1807
+ v6 = buffer.readu32(src, at6) + o6
1808
+ elseif s6 == 4 then
1809
+ v6 = buffer.readf32(src, at6) + o6
1810
+ elseif s6 == 5 then
1811
+ v6 = buffer.readf64(src, at6) + o6
1812
+ elseif s6 == 6 then
1813
+ v6 = buffer.readu8(src, at6) * u6 + o6
1814
+ elseif s6 == 7 then
1815
+ v6 = buffer.readu16(src, at6) * u6 + o6
1816
+ else
1817
+ v6 = buffer.readu32(src, at6) * u6 + o6
1818
+ end
1819
+
1820
+ if not (v6 >= lo6 and v6 <= hi6) then
1821
+ reject("number out of range")
1822
+ v6 = lo6
1823
+ end
1824
+
1825
+ result[n6] = v6
1826
+
1827
+ if count < 7 then
1828
+ return result
1829
+ end
1830
+
1831
+ local at7 = at + a7
1832
+ local v7: number
1833
+
1834
+ if s7 == 1 then
1835
+ v7 = buffer.readu8(src, at7) + o7
1836
+ elseif s7 == 2 then
1837
+ v7 = buffer.readu16(src, at7) + o7
1838
+ elseif s7 == 3 then
1839
+ v7 = buffer.readu32(src, at7) + o7
1840
+ elseif s7 == 4 then
1841
+ v7 = buffer.readf32(src, at7) + o7
1842
+ elseif s7 == 5 then
1843
+ v7 = buffer.readf64(src, at7) + o7
1844
+ elseif s7 == 6 then
1845
+ v7 = buffer.readu8(src, at7) * u7 + o7
1846
+ elseif s7 == 7 then
1847
+ v7 = buffer.readu16(src, at7) * u7 + o7
1848
+ else
1849
+ v7 = buffer.readu32(src, at7) * u7 + o7
1850
+ end
1851
+
1852
+ if not (v7 >= lo7 and v7 <= hi7) then
1853
+ reject("number out of range")
1854
+ v7 = lo7
1855
+ end
1856
+
1857
+ result[n7] = v7
1858
+
1859
+ if count < 8 then
1860
+ return result
1861
+ end
1862
+
1863
+ local at8 = at + a8
1864
+ local v8: number
1865
+
1866
+ if s8 == 1 then
1867
+ v8 = buffer.readu8(src, at8) + o8
1868
+ elseif s8 == 2 then
1869
+ v8 = buffer.readu16(src, at8) + o8
1870
+ elseif s8 == 3 then
1871
+ v8 = buffer.readu32(src, at8) + o8
1872
+ elseif s8 == 4 then
1873
+ v8 = buffer.readf32(src, at8) + o8
1874
+ elseif s8 == 5 then
1875
+ v8 = buffer.readf64(src, at8) + o8
1876
+ elseif s8 == 6 then
1877
+ v8 = buffer.readu8(src, at8) * u8 + o8
1878
+ elseif s8 == 7 then
1879
+ v8 = buffer.readu16(src, at8) * u8 + o8
1880
+ else
1881
+ v8 = buffer.readu32(src, at8) * u8 + o8
1882
+ end
1883
+
1884
+ if not (v8 >= lo8 and v8 <= hi8) then
1885
+ reject("number out of range")
1886
+ v8 = lo8
1887
+ end
1888
+
1889
+ result[n8] = v8
1890
+
1891
+ return result
1892
+ end
1893
+ end
1894
+
1895
+ --[[
1896
+ `unionWriter`'s mirror, with the one asymmetry every reader in this file has: the tag is a number
1897
+ a peer chose, and a tag naming no branch has to be refused rather than raised (G4).
1898
+
1899
+ The tag has room the schema does not use whenever the branch count is not a power of two — three
1900
+ branches are two bits, and a peer can put 3 in them — which is `enumReader`'s case exactly.
1901
+
1902
+ What comes back on that path is a shared frozen table rather than nil, for the reason
1903
+ `fusedStructReader` returns a struct of minimums: a union nested in a larger payload handing up
1904
+ nil would drop its key, and the next `.tag` read on it raises. It is never seen — the rejection
1905
+ makes `Serdes.build`'s reader drop the whole value — and it reads no bytes, because there is no
1906
+ branch to read them with.
1907
+ ]]
1908
+ local function unionReader(node: Node): Reader
1909
+ local variants = node.variants :: { string }
1910
+ local branches = node.branches :: { Field }
1911
+
1912
+ local readers: { Reader } = sized(#branches)
1913
+
1914
+ for index, branch in branches do
1915
+ readers[index] = buildReader(branch.node)
1916
+ end
1917
+
1918
+ local chunks = node.tagChunks
1919
+ local masks = node.tagMasks
1920
+ local bits = if chunks then #chunks else 0
1921
+
1922
+ local refused = table.freeze({ tag = variants[1] })
1923
+
1924
+ if bits == 0 then
1925
+ --[[ One branch carries no tag, so there is nothing a peer can say about which it is. ]]
1926
+ local only = readers[1]
1927
+ local name = variants[1]
1928
+
1929
+ return function(flags: Flags): any
1930
+ return { tag = name, value = only(flags) }
1931
+ end
1932
+ end
1933
+
1934
+ local positions = chunks :: { number }
1935
+ local bitmasks = masks :: { number }
1936
+
1937
+ return function(flags: Flags): any
1938
+ local tag = 0
1939
+
1940
+ for bit = 1, bits do
1941
+ if band(flags[positions[bit]], bitmasks[bit]) ~= 0 then
1942
+ tag = bor(tag, bit32.lshift(1, bit - 1))
1943
+ end
1944
+ end
1945
+
1946
+ local index = tag + 1
1947
+ local name = variants[index]
1948
+
1949
+ if name == nil then
1950
+ reject("unknown union branch")
1951
+ return refused
1952
+ end
1953
+
1954
+ return { tag = name, value = readers[index](flags) }
1955
+ end
1956
+ end
1957
+
1958
+ local function structReader(node: Node): Reader
1959
+ local fields = node.fields :: { Field }
1960
+ local count = #fields
1961
+ local template = node.template :: { [string]: boolean }
1962
+
1963
+ local fused = fusedStructReader(node)
1964
+
1965
+ if fused then
1966
+ return fused
1967
+ end
1968
+
1969
+ local names: { string } = sized(count)
1970
+ local readers: { Reader } = sized(count)
1971
+
1972
+ for index, field in fields do
1973
+ names[index] = field.name
1974
+ readers[index] = buildReader(field.node)
1975
+ end
1976
+
1977
+ return function(flags: Flags): any
1978
+ --[[ Cloning a pre-sized template is why decode never rehashes. ByteNet does the same and
1979
+ it is the one axis where it beat both code generators in M0 (`RESEARCH §3.8-S`; the 389 B figure is `RESEARCH-AND-PLAN.md:1237`). An
1980
+ absent optional assigns nil, which drops the key without resizing. ]]
1981
+ local result = table.clone(template) :: any
1982
+
1983
+ for index = 1, count do
1984
+ result[names[index]] = readers[index](flags)
1985
+ end
1986
+
1987
+ return result
1988
+ end
1989
+ end
1990
+
1991
+ local function arrayReader(node: Node): Reader
1992
+ local readLength = lengthReader(node)
1993
+ local elements = node.elements
1994
+
1995
+ if elements then
1996
+ local count = #elements
1997
+ local readers: { Reader } = sized(count)
1998
+
1999
+ for index, element in elements do
2000
+ readers[index] = buildReader(element)
2001
+ end
2002
+
2003
+ return function(flags: Flags): any
2004
+ local result = sized(count)
2005
+
2006
+ for index = 1, count do
2007
+ result[index] = readers[index](flags)
2008
+ end
2009
+
2010
+ return result
2011
+ end
2012
+ end
2013
+
2014
+ local element = node.element :: Node
2015
+ local readElement = readerFor(element)
2016
+
2017
+ --[[
2018
+ The smallest number of bytes one element can occupy, when that is known at build time. A
2019
+ static element has an exact size; a dynamic one does not, and answers nil.
2020
+ ]]
2021
+ local perElement = element.fixedSize
2022
+
2023
+ return function(flags: Flags): any
2024
+ local count = readLength()
2025
+
2026
+ if count < 0 then
2027
+ return {}
2028
+ end
2029
+
2030
+ --[[
2031
+ A claim is not paid for until the bytes behind it exist.
2032
+
2033
+ ~~The length was already bounded, so this is a cost question, not a safety one.~~
2034
+ **Struck through in M3 phase 0.** A cost an attacker controls and does not pay for is an
2035
+ amplification: a two-byte packet claiming 65535 elements bought a 65535-slot table, at
2036
+ 839x the cost of an honest packet, and *was then correctly rejected*. The rejection was
2037
+ free. The allocation was not (`PLAN-M3` D-4).
2038
+
2039
+ Bounding the claim against the bytes that remain costs one comparison on the honest path
2040
+ and turns the hostile one into a refusal before anything is allocated. Zap has the same
2041
+ shape without the recovery — `_refsrc/zap/zap/src/irgen/des.rs:298` allocates from the
2042
+ claimed length too, and its generated `read` does no bounds checking at all, so the
2043
+ equivalent packet raises and takes the batch.
2044
+ ]]
2045
+ local available = remaining()
2046
+
2047
+ if perElement and perElement > 0 and count * perElement > available then
2048
+ reject(
2049
+ `array claims {count} elements, needing {count * perElement} bytes, and {available} remain`
2050
+ )
2051
+ return {}
2052
+ end
2053
+
2054
+ --[[
2055
+ For a dynamic element there is no size to multiply by, so the *allocation* is capped at
2056
+ the bytes available instead. An element cannot be conjured from no bytes, so this never
2057
+ shortens an honest decode — and it bounds the hostile one to the packet's own length,
2058
+ which is what the amplification was.
2059
+ ]]
2060
+ local result = sized(if count < available then count else available)
2061
+
2062
+ for index = 1, count do
2063
+ --[[ Bail on the first rejection rather than reading `max` elements of garbage. ]]
2064
+ if rejected() then
2065
+ return result
2066
+ end
2067
+
2068
+ result[index] = readElement(flags)
2069
+ end
2070
+
2071
+ return result
2072
+ end
2073
+ end
2074
+
2075
+ local function mapReader(node: Node): Reader
2076
+ local readLength = lengthReader(node)
2077
+ local key = node.key :: Node
2078
+ local value = node.value :: Node
2079
+ local readKey = readerFor(key)
2080
+ local readValue = readerFor(value)
2081
+
2082
+ --[[ A map never had the allocation bug an array had — it starts from `{}` and grows — but the
2083
+ same bound gives the same refusal, so a claim past the packet is reported the same way
2084
+ whichever container it arrived in (`PLAN-M3` D-4). ]]
2085
+ local perEntry = if key.fixedSize and value.fixedSize then key.fixedSize + value.fixedSize else nil
2086
+
2087
+ return function(flags: Flags): any
2088
+ local count = readLength()
2089
+
2090
+ if count < 0 then
2091
+ return {}
2092
+ end
2093
+
2094
+ local available = remaining()
2095
+
2096
+ if perEntry and perEntry > 0 and count * perEntry > available then
2097
+ reject(`map claims {count} entries, needing {count * perEntry} bytes, and {available} remain`)
2098
+ return {}
2099
+ end
2100
+
2101
+ local result: any = {}
2102
+
2103
+ for _ = 1, count do
2104
+ if rejected() then
2105
+ return result
2106
+ end
2107
+
2108
+ local entryKey = readKey(flags)
2109
+ local entryValue = readValue(flags)
2110
+
2111
+ --[[
2112
+ **A nil key is a rejection, not an assignment.**
2113
+
2114
+ `t.map(t.optional(K), V)` type-checks, lowers, and encodes honestly — a Lua table has
2115
+ no nil key, so the presence bit the optional adds is dead weight that only a hostile
2116
+ packet can clear. When it does, `readKey` answers nil with no rejection of its own and
2117
+ `result[nil] = value` **raises**: the one path in this codec where wire data reaches a
2118
+ Luau error rather than `Buffer.reject`, against everything the header of this file
2119
+ says (M4 report, finding 3).
2120
+
2121
+ `t.map` refuses that key type now, so the honest route to here is closed. This stays
2122
+ because `isType` is a duck check — any table with a string `kind` passes it — and
2123
+ because G4 is structural: the reader is not allowed to depend on the constructor
2124
+ having been used.
2125
+ ]]
2126
+ if entryKey == nil then
2127
+ reject("a map key is missing")
2128
+ return result
2129
+ end
2130
+
2131
+ --[[ A rejected key is a default, and defaults collide: writing them would fabricate an
2132
+ entry the sender never sent. ]]
2133
+ if not rejected() then
2134
+ result[entryKey] = entryValue
2135
+ end
2136
+ end
2137
+
2138
+ return result
2139
+ end
2140
+ end
2141
+
2142
+ function buildReader(node: Node): Reader
2143
+ local kind = node.kind
2144
+
2145
+ if kind == "boolean" then
2146
+ local chunk = node.chunkIndex :: number
2147
+ local mask = node.mask :: number
2148
+
2149
+ return function(flags: Flags): any
2150
+ return band(flags[chunk], mask) ~= 0
2151
+ end
2152
+ elseif kind == "number" then
2153
+ return numberReader(node)
2154
+ elseif kind == "string" then
2155
+ local readLength = lengthReader(node)
2156
+
2157
+ --[[ The half the finding is actually about: a *peer's* string is the one that reaches
2158
+ `SetAsync`, `Instance.Name` and chat, and invalid UTF-8 or a control character surfaces
2159
+ there as an error in game code with no packet to point at. Refused rather than raised —
2160
+ it is wire data (G4). ]]
2161
+ local anchored = if node.pattern then `^{node.pattern}$` else nil
2162
+ local unicode = node.utf8
2163
+
2164
+ if anchored or unicode then
2165
+ return function(_flags: Flags): any
2166
+ local length = readLength()
2167
+
2168
+ if length < 0 then
2169
+ return ""
2170
+ end
2171
+
2172
+ local value = readString(length)
2173
+
2174
+ if unicode and utf8.len(value) == nil then
2175
+ reject("string is not valid UTF-8")
2176
+ return ""
2177
+ end
2178
+
2179
+ if anchored and not string.find(value, anchored :: string) then
2180
+ reject("string does not match the declared pattern")
2181
+ return ""
2182
+ end
2183
+
2184
+ return value
2185
+ end
2186
+ end
2187
+
2188
+ return function(_flags: Flags): any
2189
+ local length = readLength()
2190
+
2191
+ if length < 0 then
2192
+ return ""
2193
+ end
2194
+
2195
+ return readString(length)
2196
+ end
2197
+ elseif kind == "buffer" then
2198
+ local readLength = lengthReader(node)
2199
+
2200
+ return function(_flags: Flags): any
2201
+ local length = readLength()
2202
+
2203
+ if length < 0 then
2204
+ return buffer.create(0)
2205
+ end
2206
+
2207
+ return readBuffer(length)
2208
+ end
2209
+ elseif kind == "vector2" then
2210
+ local component = node.element
2211
+
2212
+ if component then
2213
+ local axis = buildReader(component)
2214
+
2215
+ return function(flags: Flags): any
2216
+ local x, y = axis(flags), axis(flags)
2217
+
2218
+ --[[ Still asked, because a component the schema narrowed cannot be non-finite but a
2219
+ bare `f32` one named through `t.vector2(t.f32)` can. One branch either way. ]]
2220
+ if not (isFinite(x) and isFinite(y)) then
2221
+ reject("non-finite vector2")
2222
+ return Vector2.zero
2223
+ end
2224
+
2225
+ return Vector2.new(x, y)
2226
+ end
2227
+ end
2228
+
2229
+ return function(_flags: Flags): any
2230
+ local x, y = readF32(), readF32()
2231
+
2232
+ if not (isFinite(x) and isFinite(y)) then
2233
+ reject("non-finite vector2")
2234
+ return Vector2.zero
2235
+ end
2236
+
2237
+ return Vector2.new(x, y)
2238
+ end
2239
+ elseif kind == "vector3" then
2240
+ local unit = node.unit
2241
+ local component = node.element
2242
+
2243
+ --[[
2244
+ **A quantised direction does not land on the unit sphere**, so the length check widens by
2245
+ what the step can move it: each axis is off by at most half a step, and three of those
2246
+ compose to `sqrt(3)` half-steps in the worst case.
2247
+
2248
+ Derived rather than guessed, and zero for every encoding that is not quantised — so a
2249
+ bare `t.unitVector3` keeps exactly the tolerance it had. Without it, the compact spelling
2250
+ the docstring recommends would be refused by its own reader on most values.
2251
+ ]]
2252
+ local slack = UNIT_TOLERANCE
2253
+ + if component and component.step then math.sqrt(3) * (component.step :: number) / 2 else 0
2254
+
2255
+ if component then
2256
+ local axis = buildReader(component)
2257
+
2258
+ return function(flags: Flags): any
2259
+ local x, y, z = axis(flags), axis(flags), axis(flags)
2260
+
2261
+ if not (isFinite(x) and isFinite(y) and isFinite(z)) then
2262
+ reject("non-finite vector3")
2263
+ return Vector3.zero
2264
+ end
2265
+
2266
+ local value = Vector3.new(x, y, z)
2267
+
2268
+ if unit and math.abs(value.Magnitude - 1) > slack then
2269
+ reject("vector3 is not a unit vector")
2270
+ return Vector3.zAxis
2271
+ end
2272
+
2273
+ return value
2274
+ end
2275
+ end
2276
+
2277
+ return function(_flags: Flags): any
2278
+ local x, y, z = readF32(), readF32(), readF32()
2279
+
2280
+ if not (isFinite(x) and isFinite(y) and isFinite(z)) then
2281
+ reject("non-finite vector3")
2282
+ return Vector3.zero
2283
+ end
2284
+
2285
+ local value = Vector3.new(x, y, z)
2286
+
2287
+ --[[
2288
+ A direction that is not a direction is an exploit primitive: a caller that trusts
2289
+ `t.unitVector3` and multiplies by a range gets an arbitrary displacement out of a
2290
+ magnitude of 400. The schema said unit, so the decoder enforces unit.
2291
+ ]]
2292
+ if unit and math.abs(value.Magnitude - 1) > UNIT_TOLERANCE then
2293
+ reject("vector3 is not a unit vector")
2294
+ return Vector3.zAxis
2295
+ end
2296
+
2297
+ return value
2298
+ end
2299
+ elseif kind == "color3" then
2300
+ return function(_flags: Flags): any
2301
+ return Color3.fromRGB(readU8(), readU8(), readU8())
2302
+ end
2303
+ elseif kind == "cframe" then
2304
+ local component = node.element
2305
+
2306
+ if component then
2307
+ local axis = buildReader(component)
2308
+ local chunks = node.tagChunks :: { number }
2309
+ local masks = node.tagMasks :: { number }
2310
+
2311
+ return function(flags: Flags): any
2312
+ local px, py, pz = axis(flags), axis(flags), axis(flags)
2313
+
2314
+ if not (isFinite(px) and isFinite(py) and isFinite(pz)) then
2315
+ reject("non-finite cframe")
2316
+ return CFrame.identity
2317
+ end
2318
+
2319
+ local largest = 0
2320
+
2321
+ for bit = 1, 2 do
2322
+ if band(flags[chunks[bit]], masks[bit]) ~= 0 then
2323
+ largest = bor(largest, bit32.lshift(1, bit - 1))
2324
+ end
2325
+ end
2326
+
2327
+ local a = readI16() / QUATERNION_SCALE
2328
+ local b = readI16() / QUATERNION_SCALE
2329
+ local c = readI16() / QUATERNION_SCALE
2330
+ local rest = a * a + b * b + c * c
2331
+
2332
+ --[[ Three components of a unit quaternion, none of them the largest, sum to at
2333
+ most 3/4; past that, with the step's slack, the bytes were not a rotation. ]]
2334
+ if rest > QUATERNION_MAX_REST then
2335
+ reject("cframe rotation is not a unit quaternion")
2336
+ return CFrame.identity
2337
+ end
2338
+
2339
+ local d = math.sqrt(math.max(0, 1 - rest))
2340
+ local qx, qy, qz, qw
2341
+
2342
+ if largest == 0 then
2343
+ qx, qy, qz, qw = d, a, b, c
2344
+ elseif largest == 1 then
2345
+ qx, qy, qz, qw = a, d, b, c
2346
+ elseif largest == 2 then
2347
+ qx, qy, qz, qw = a, b, d, c
2348
+ else
2349
+ qx, qy, qz, qw = a, b, c, d
2350
+ end
2351
+
2352
+ return CFrame.new(px, py, pz, qx, qy, qz, qw)
2353
+ end
2354
+ end
2355
+
2356
+ return function(_flags: Flags): any
2357
+ local px, py, pz = readF32(), readF32(), readF32()
2358
+ local ax, ay, az = readF32(), readF32(), readF32()
2359
+
2360
+ if
2361
+ not (
2362
+ isFinite(px)
2363
+ and isFinite(py)
2364
+ and isFinite(pz)
2365
+ and isFinite(ax)
2366
+ and isFinite(ay)
2367
+ and isFinite(az)
2368
+ )
2369
+ then
2370
+ reject("non-finite cframe")
2371
+ return CFrame.identity
2372
+ end
2373
+
2374
+ local rotation = Vector3.new(ax, ay, az)
2375
+ local angle = rotation.Magnitude
2376
+
2377
+ if angle < 1e-6 then
2378
+ return CFrame.new(px, py, pz)
2379
+ end
2380
+
2381
+ return CFrame.new(px, py, pz) * CFrame.fromAxisAngle(rotation / angle, angle)
2382
+ end
2383
+ elseif kind == "instance" then
2384
+ local class = node.class
2385
+ local root = node.descendantOf
2386
+
2387
+ --[[ Both sentences once, here, rather than concatenated on each refusal: they are constants
2388
+ per schema, and the refusal is the path a peer takes by naming an instance of the
2389
+ wrong class, which costs it nothing (SECURITY-REPORT-M4-1; `bench/residue`). The
2390
+ root's name is read now, so a container renamed after the declaration is named here as
2391
+ it was declared. ]]
2392
+ local notClass = if class then "instance is not a " .. class else nil
2393
+ local notInside = if root then "instance is not inside " .. root.Name else nil
2394
+
2395
+ return function(_flags: Flags): any
2396
+ local value = readInstance()
2397
+
2398
+ --[[
2399
+ Three failures, not one. A nil means the sidecar ran out, which is a framing problem.
2400
+ A wrong class means the sender picked an instance the schema does not admit, which
2401
+ is the whole reason `t.instance("Sound")` exists — a client can reference anything
2402
+ it can see, so the class is checked here or it is not checked at all.
2403
+
2404
+ And the entry has to **be** an Instance before either of those questions can be
2405
+ asked. `FireServer(buffer, { {} })` puts a table in the slot, and `value:IsA(class)`
2406
+ on a table raises — on the receive path, out of the read phase, which is guarantee
2407
+ G4 broken by the one piece of wire data that does not travel in the buffer. The
2408
+ sidecar is a client argument like any other and had no check at all until M3 phase 9.
2409
+
2410
+ A bare `t.instance` was worse: with no class to test, whatever the client sent was
2411
+ handed to the handler as an Instance. `12345` reached game code with no report.
2412
+ ]]
2413
+ if value == nil then
2414
+ reject("missing instance")
2415
+ return nil
2416
+ end
2417
+
2418
+ if not isInstance(value) then
2419
+ reject(`the sidecar holds a {typeof(value)} where an instance was declared`)
2420
+ return nil
2421
+ end
2422
+
2423
+ --[[ The cast says what `isInstance` has just established: the sidecar arrives as
2424
+ `{ unknown }` since M4 report finding 50, and a `boolean`-returning check does not
2425
+ narrow it. Same shape as `Recipients.positionOf` one module over. ]]
2426
+ local instance = value :: Instance
2427
+
2428
+ if notClass and not instance:IsA(class :: string) then
2429
+ reject(notClass)
2430
+ return nil
2431
+ end
2432
+
2433
+ --[[
2434
+ And where it is. A class says *what* a client handed over; it says nothing about
2435
+ where the client got it, and the sidecar admits anything the sender can reference —
2436
+ a `BasePart` out of its own `PlayerGui`, a `Model` in `ReplicatedStorage` a script
2437
+ parented there a frame ago (M4 report).
2438
+
2439
+ Not in the protocol hash, and that is deliberate: this is enforcement one endpoint
2440
+ does over its own tree, like a rate limit. Two peers naming their own `workspace`
2441
+ mean the same thing and hold different objects, and a hash that moved for it would
2442
+ force a client redeploy for a server-side edit.
2443
+ ]]
2444
+ if notInside and not instance:IsDescendantOf(root :: Instance) then
2445
+ reject(notInside)
2446
+ return nil
2447
+ end
2448
+
2449
+ return instance
2450
+ end
2451
+ elseif kind == "enum" then
2452
+ return enumReader(node)
2453
+ elseif kind == "literal" then
2454
+ local literal = node.literal
2455
+
2456
+ return function(_flags: Flags): any
2457
+ return literal
2458
+ end
2459
+ elseif kind == "optional" then
2460
+ local chunk = node.chunkIndex :: number
2461
+ local mask = node.mask :: number
2462
+ local readInner = buildReader(node.inner :: Node)
2463
+ local default = node.default
2464
+
2465
+ return function(flags: Flags): any
2466
+ if band(flags[chunk], mask) == 0 then
2467
+ return default
2468
+ end
2469
+
2470
+ return readInner(flags)
2471
+ end
2472
+ elseif kind == "array" then
2473
+ return arrayReader(node)
2474
+ elseif kind == "map" then
2475
+ return mapReader(node)
2476
+ elseif kind == "struct" then
2477
+ return structReader(node)
2478
+ elseif kind == "union" then
2479
+ return unionReader(node)
2480
+ end
2481
+
2482
+ error(`[netweave] no reader for a "{kind}"`)
2483
+ end
2484
+
2485
+ -- -------------------------------------------------------------------------------------------------
2486
+
2487
+ --[=[
2488
+ @interface Codec
2489
+ @within Serdes
2490
+ .framing "static" | "counted" -- whether the transport has to length-prefix this payload
2491
+ .fixedSize number? -- payload bytes, when they never vary
2492
+ .instances number? -- sidecar entries always consumed, when that never varies
2493
+ .write (value: any) -> ()
2494
+ .read () -> (any, string?)
2495
+ .check (value: any) -> string? -- nil when the value satisfies the schema
2496
+ ]=]
2497
+ export type Codec = {
2498
+ framing: "static" | "counted",
2499
+ fixedSize: number?,
2500
+ maxSize: number,
2501
+ instances: number?,
2502
+ --[[ Kept rather than discarded, because the protocol hash is taken over the lowered tree
2503
+ (`src/api/Protocol.luau`) and lowering a second time at seal would be the same work done
2504
+ twice to save one field. ]]
2505
+ layout: Ir.Layout,
2506
+ write: (value: any) -> (),
2507
+ read: () -> (any, string?),
2508
+ check: (value: any) -> string?,
2509
+ }
2510
+
2511
+ --[=[
2512
+ @within Serdes
2513
+ @function build
2514
+ @param layout Layout -- from `Ir.lower`
2515
+ @return Codec
2516
+
2517
+ Binds a layout into a write/read pair. Call this once per channel, at definition time.
2518
+
2519
+ ```lua
2520
+ local codec = Serdes.build(Ir.lower(t.struct({ x = t.u8, y = t.u8 })))
2521
+
2522
+ codec.write({ x = 1, y = 2 })
2523
+ local bytes, instances = Buffer.take()
2524
+
2525
+ Buffer.beginRead(bytes, instances)
2526
+ local value, failure = codec.read()
2527
+ ```
2528
+
2529
+ `write` appends to the outgoing buffer and leaves framing to the transport, which is what
2530
+ `framing` and `fixedSize` are for.
2531
+
2532
+ :::caution
2533
+ `write` raises on a value the schema forbids — that is game code passing a bad number, and
2534
+ silent wraparound would be worse. `read` never raises: it returns `nil` and a reason.
2535
+ :::
2536
+
2537
+ :::caution
2538
+ A `write` that raises leaves behind whatever bytes it emitted before the bad field. The caller
2539
+ owns the rewind: park the buffer with `Buffer.save` first, or `take` and discard. `check` below
2540
+ does the former, and a transport must do one of them — a partial payload left in the batch is a
2541
+ packet nobody can decode.
2542
+ :::
2543
+ ]=]
2544
+ function Serdes.build(layout: Ir.Layout): Codec
2545
+ local root = layout.root
2546
+ local scope = layout.scope
2547
+ local fixedSize = layout.fixedSize
2548
+
2549
+ --[[
2550
+ A payload whose size is known claims all of it in one `allocate` and fills it with the
2551
+ `put*` writers, which skip the bounds and growth checks the space has already paid for.
2552
+
2553
+ `blocked` is set for the whole of synthesis and cleared after, so every closure below this
2554
+ point is built against the right family. It is restored rather than assigned `false`
2555
+ because `Serdes.build` can be re-entered — `Trust.validate` builds a codec lazily, and a
2556
+ schema can be lowered while another is being built.
2557
+ ]]
2558
+ local outer = blocked
2559
+ blocked = fixedSize ~= nil
2560
+
2561
+ local write = buildWriter(root)
2562
+ local read = buildReader(root)
2563
+
2564
+ if scope then
2565
+ write = scopedWriter(scope, write)
2566
+ read = scopedReader(scope, read)
2567
+ end
2568
+
2569
+ blocked = outer
2570
+
2571
+ if fixedSize then
2572
+ local inner = write
2573
+ local size = fixedSize
2574
+
2575
+ --[[ Annotated `Writer` rather than left to inference: an anonymous function whose return
2576
+ type is exactly `()` makes `pcall(write, ...)` in `check` below resolve to one value. ]]
2577
+ local blockWrite: Writer = function(value: any, flags: Flags)
2578
+ openBlock(size)
2579
+ inner(value, flags)
2580
+ closeBlock()
2581
+ end
2582
+
2583
+ write = blockWrite
2584
+ end
2585
+
2586
+ --[[
2587
+ `pcall` of a function whose return pack is empty is typed as returning `boolean` alone, so
2588
+ destructuring the error out of it does not check. The alias widens the pack without changing
2589
+ what runs, and is hoisted here so `check` does not build one per call.
2590
+ ]]
2591
+ local attempt: (...any) -> ...any = write
2592
+
2593
+ return {
2594
+ framing = layout.framing,
2595
+ fixedSize = layout.fixedSize,
2596
+ maxSize = layout.maxSize,
2597
+ instances = layout.instances,
2598
+ layout = layout,
2599
+
2600
+ write = function(value: any)
2601
+ write(value, NO_FLAGS)
2602
+ end,
2603
+
2604
+ read = function(): (any, string?)
2605
+ --[[ Cleared per payload, not per batch: G5 says one malformed packet must not stop the
2606
+ rest, and a rejection carried forward would do exactly that. ]]
2607
+ Buffer.clearRejection()
2608
+
2609
+ local value = read(NO_FLAGS)
2610
+ local failure = rejected()
2611
+
2612
+ if failure then
2613
+ return nil, failure
2614
+ end
2615
+
2616
+ return value, nil
2617
+ end,
2618
+
2619
+ --[[
2620
+ The encoder is the only statement of what a value must satisfy, so `check` runs it rather
2621
+ than restating its rules. A second implementation drifts, and the two disagree exactly
2622
+ where it matters: on the boundary cases nobody re-tests.
2623
+
2624
+ The cost is a real serialisation into a parked buffer, which is why this is not on the hot
2625
+ path. The receive path never needs it — a payload that decoded is valid by construction.
2626
+ ]]
2627
+ check = function(value: any): string?
2628
+ --[[ `mark`/`rollback` rather than `save`/`load`, because only one of the two clears the
2629
+ sidecar. `load` restores `instanceCount` and leaves the entries the trial write
2630
+ appended past it, so validating a payload carrying an Instance kept a reference to
2631
+ it until the next write happened to overwrite that slot — found by an external
2632
+ review (M3 phase 9). It also stops allocating a record per call. ]]
2633
+ local used, instances = Buffer.mark()
2634
+ local ok, failure = pcall(attempt, value, NO_FLAGS)
2635
+ Buffer.rollback(used, instances)
2636
+
2637
+ if ok then
2638
+ return nil
2639
+ end
2640
+
2641
+ --[[ `error()` prefixes a script position; the caller wants the reason, not the line. ]]
2642
+ local reason = tostring(failure)
2643
+ return (string.gsub(reason, "^.-:%d+: ", "", 1))
2644
+ end,
2645
+ }
2646
+ end
2647
+
2648
+ --[=[
2649
+ @within Serdes
2650
+ @function fromSchema
2651
+ @param descriptor Descriptor -- a type from `netweave.types`
2652
+ @return Codec
2653
+
2654
+ `Serdes.build(Ir.lower(descriptor))`, for callers that have a schema rather than a layout.
2655
+ ]=]
2656
+ function Serdes.fromSchema(descriptor: Types.Descriptor): Codec
2657
+ return Serdes.build(Ir.lower(descriptor))
2658
+ end
2659
+
2660
+ --[=[
2661
+ @within Serdes
2662
+ @function nodeCodec
2663
+ @param node Node -- a node from a lowered layout, with its bits already assigned
2664
+ @return (value: any, flags: { number }) -> ()
2665
+ @return (flags: { number }) -> any
2666
+ @private
2667
+
2668
+ The writer and reader for **one node**, for a caller that is assembling a payload this module
2669
+ does not know the shape of.
2670
+
2671
+ `src/replication/Delta.luau` is the only such caller: a patch interleaves its own decisions —
2672
+ did this field change, is it there now — with ordinary values, so it walks the tree itself and
2673
+ asks for a codec at each leaf rather than reimplementing fourteen kinds.
2674
+
2675
+ :::caution
2676
+ The block optimisation is **off** for these. `Serdes.build` turns it on when a layout is
2677
+ statically sized, because then one `allocate` covers the whole payload and every writer below it
2678
+ can skip its own bounds check. A patch is never statically sized — that is what a patch is — so
2679
+ a node built here uses the growth-checked writers, and mixing one built here into a blocked
2680
+ layout would write past the block.
2681
+ :::
2682
+ ]=]
2683
+ function Serdes.nodeCodec(node: Ir.Node): (Writer, Reader)
2684
+ local outer = blocked
2685
+ blocked = false
2686
+
2687
+ local write = writerFor(node)
2688
+ local read = readerFor(node)
2689
+
2690
+ blocked = outer
2691
+ return write, read
2692
+ end
2693
+
2694
+ return Serdes