-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelta.rs
More file actions
3211 lines (3031 loc) · 107 KB
/
delta.rs
File metadata and controls
3211 lines (3031 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Delta snapshot encoding/decoding.
use std::cmp::Ordering;
use bitstream::{BitReader, BitWriter};
use schema::{schema_hash, ChangePolicy, ComponentDef, ComponentId, FieldDef};
use wire::{decode_packet, encode_header, SectionTag, WirePacket};
use crate::baseline::BaselineStore;
use crate::error::{CodecError, CodecResult, LimitKind, MaskKind, MaskReason, ValueReason};
use crate::limits::CodecLimits;
use crate::scratch::CodecScratch;
use crate::snapshot::{
ensure_known_components, read_field_value, read_field_value_sparse, read_mask, required_bits,
write_field_value, write_field_value_sparse, write_section, ComponentSnapshot, EntitySnapshot,
FieldValue, Snapshot,
};
use crate::types::{EntityId, SnapshotTick};
/// Selects the latest baseline tick at or before the ack tick.
#[must_use]
pub fn select_baseline_tick<T>(
store: &BaselineStore<T>,
ack_tick: SnapshotTick,
) -> Option<SnapshotTick> {
store.latest_at_or_before(ack_tick).map(|(tick, _)| tick)
}
/// Encodes a delta snapshot into the provided output buffer.
///
/// This is the scan-based path and is kept as a convenience/fallback. For
/// production engines with dirty/change lists, prefer `encode_delta_from_changes`.
/// Baseline and current snapshots must have entities sorted by `EntityId`.
pub fn encode_delta_snapshot(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
out: &mut [u8],
) -> CodecResult<usize> {
let mut scratch = CodecScratch::default();
encode_delta_snapshot_with_scratch(
schema,
tick,
baseline_tick,
baseline,
current,
limits,
&mut scratch,
out,
)
}
/// Encodes a delta snapshot using reusable scratch buffers.
#[allow(clippy::too_many_arguments)]
pub fn encode_delta_snapshot_with_scratch(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
scratch: &mut CodecScratch,
out: &mut [u8],
) -> CodecResult<usize> {
encode_delta_snapshot_with_scratch_mode(
schema,
tick,
baseline_tick,
baseline,
current,
limits,
scratch,
out,
EncodeUpdateMode::Auto,
)
}
/// Encodes a delta snapshot for a client-specific view.
///
/// This assumes `baseline` and `current` are already filtered for the client interest set.
/// Updates are encoded in sparse mode to optimize for small per-client packets.
pub fn encode_delta_snapshot_for_client(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
out: &mut [u8],
) -> CodecResult<usize> {
let mut scratch = CodecScratch::default();
encode_delta_snapshot_for_client_with_scratch(
schema,
tick,
baseline_tick,
baseline,
current,
limits,
&mut scratch,
out,
)
}
/// Encoder context for delta packets that use caller-provided change lists.
///
/// This avoids scanning baseline/current snapshots and is preferred for
/// production engines that already track dirty state.
pub struct SessionEncoder<'a> {
schema: &'a schema::Schema,
limits: &'a CodecLimits,
#[allow(dead_code)]
scratch: CodecScratch,
}
impl<'a> SessionEncoder<'a> {
#[must_use]
pub fn new(schema: &'a schema::Schema, limits: &'a CodecLimits) -> Self {
Self {
schema,
limits,
scratch: CodecScratch::default(),
}
}
#[must_use]
pub fn schema(&self) -> &'a schema::Schema {
self.schema
}
#[must_use]
pub fn limits(&self) -> &'a CodecLimits {
self.limits
}
}
/// Encodes a delta snapshot from precomputed change lists.
///
/// Preferred for production engines (dirty/change-list driven). The scan-based
/// encode paths remain as a convenience/fallback.
pub fn encode_delta_from_changes(
session: &mut SessionEncoder<'_>,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
creates: &[EntitySnapshot],
destroys: &[EntityId],
updates: &[DeltaUpdateEntity],
out: &mut [u8],
) -> CodecResult<usize> {
encode_delta_snapshot_from_updates(
session.schema,
tick,
baseline_tick,
destroys,
creates,
updates,
session.limits,
out,
)
}
/// Encodes a delta snapshot using precomputed change lists.
///
/// This is a lower-level helper. Prefer `encode_delta_from_changes` with a
/// `SessionEncoder` for production use.
#[allow(clippy::too_many_arguments)]
pub fn encode_delta_snapshot_from_updates(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
destroys: &[EntityId],
creates: &[EntitySnapshot],
updates: &[DeltaUpdateEntity],
limits: &CodecLimits,
out: &mut [u8],
) -> CodecResult<usize> {
if out.len() < wire::HEADER_SIZE {
return Err(CodecError::OutputTooSmall {
needed: wire::HEADER_SIZE,
available: out.len(),
});
}
let payload_len = encode_delta_payload_from_updates(
schema,
destroys,
creates,
updates,
limits,
&mut out[wire::HEADER_SIZE..],
)?;
let header = wire::PacketHeader::delta_snapshot(
schema_hash(schema),
tick.raw(),
baseline_tick.raw(),
payload_len as u32,
);
encode_header(&header, &mut out[..wire::HEADER_SIZE]).map_err(|_| {
CodecError::OutputTooSmall {
needed: wire::HEADER_SIZE,
available: out.len(),
}
})?;
Ok(wire::HEADER_SIZE + payload_len)
}
/// Encodes a client delta snapshot using a compact session header.
#[allow(clippy::too_many_arguments)]
pub fn encode_delta_snapshot_for_client_session(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
last_tick: &mut SnapshotTick,
out: &mut [u8],
) -> CodecResult<usize> {
let mut scratch = CodecScratch::default();
encode_delta_snapshot_for_client_session_with_scratch(
schema,
tick,
baseline_tick,
baseline,
current,
limits,
&mut scratch,
last_tick,
out,
)
}
/// Encodes a delta snapshot for a client-specific view using reusable scratch buffers.
#[allow(clippy::too_many_arguments)]
pub fn encode_delta_snapshot_for_client_with_scratch(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
scratch: &mut CodecScratch,
out: &mut [u8],
) -> CodecResult<usize> {
encode_delta_snapshot_with_scratch_mode(
schema,
tick,
baseline_tick,
baseline,
current,
limits,
scratch,
out,
EncodeUpdateMode::Sparse,
)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum EncodeUpdateMode {
Auto,
Sparse,
}
/// Encodes a client delta snapshot using a compact session header.
#[allow(clippy::too_many_arguments)]
pub fn encode_delta_snapshot_for_client_session_with_scratch(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
scratch: &mut CodecScratch,
last_tick: &mut SnapshotTick,
out: &mut [u8],
) -> CodecResult<usize> {
let max_header = wire::SESSION_MAX_HEADER_SIZE;
if out.len() < max_header {
return Err(CodecError::OutputTooSmall {
needed: max_header,
available: out.len(),
});
}
if tick.raw() <= last_tick.raw() {
return Err(CodecError::InvalidEntityOrder {
previous: last_tick.raw(),
current: tick.raw(),
});
}
if baseline_tick.raw() > tick.raw() {
return Err(CodecError::BaselineTickMismatch {
expected: baseline_tick.raw(),
found: tick.raw(),
});
}
let payload_len = encode_delta_payload_with_mode(
schema,
baseline_tick,
baseline,
current,
limits,
scratch,
&mut out[max_header..],
EncodeUpdateMode::Sparse,
)?;
let tick_delta = tick.raw() - last_tick.raw();
let baseline_delta = tick.raw() - baseline_tick.raw();
let header_len = wire::encode_session_header(
&mut out[..max_header],
wire::SessionFlags::delta_snapshot(),
tick_delta,
baseline_delta,
payload_len as u32,
)
.map_err(|_| CodecError::OutputTooSmall {
needed: max_header,
available: out.len(),
})?;
if header_len < max_header {
let payload_start = max_header;
let payload_end = max_header + payload_len;
out.copy_within(payload_start..payload_end, header_len);
}
*last_tick = tick;
Ok(header_len + payload_len)
}
#[allow(clippy::too_many_arguments)]
fn encode_delta_snapshot_with_scratch_mode(
schema: &schema::Schema,
tick: SnapshotTick,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
scratch: &mut CodecScratch,
out: &mut [u8],
mode: EncodeUpdateMode,
) -> CodecResult<usize> {
if out.len() < wire::HEADER_SIZE {
return Err(CodecError::OutputTooSmall {
needed: wire::HEADER_SIZE,
available: out.len(),
});
}
let payload_len = encode_delta_payload_with_mode(
schema,
baseline_tick,
baseline,
current,
limits,
scratch,
&mut out[wire::HEADER_SIZE..],
mode,
)?;
let header = wire::PacketHeader::delta_snapshot(
schema_hash(schema),
tick.raw(),
baseline_tick.raw(),
payload_len as u32,
);
encode_header(&header, &mut out[..wire::HEADER_SIZE]).map_err(|_| {
CodecError::OutputTooSmall {
needed: wire::HEADER_SIZE,
available: out.len(),
}
})?;
Ok(wire::HEADER_SIZE + payload_len)
}
#[allow(clippy::too_many_arguments)]
fn encode_delta_payload_with_mode(
schema: &schema::Schema,
baseline_tick: SnapshotTick,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
scratch: &mut CodecScratch,
out: &mut [u8],
mode: EncodeUpdateMode,
) -> CodecResult<usize> {
if baseline.tick != baseline_tick {
return Err(CodecError::BaselineTickMismatch {
expected: baseline.tick.raw(),
found: baseline_tick.raw(),
});
}
ensure_entities_sorted(&baseline.entities)?;
ensure_entities_sorted(¤t.entities)?;
let mut counts = DiffCounts::default();
diff_counts(schema, baseline, current, limits, &mut counts)?;
if counts.creates > limits.max_entities_create {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesCreate,
limit: limits.max_entities_create,
actual: counts.creates,
});
}
if counts.updates > limits.max_entities_update {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesUpdate,
limit: limits.max_entities_update,
actual: counts.updates,
});
}
if counts.destroys > limits.max_entities_destroy {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesDestroy,
limit: limits.max_entities_destroy,
actual: counts.destroys,
});
}
let mut offset = 0;
if counts.destroys > 0 {
let written = write_section(
SectionTag::EntityDestroy,
&mut out[offset..],
limits,
|writer| encode_destroy_body(baseline, current, counts.destroys, limits, writer),
)?;
offset += written;
}
if counts.creates > 0 {
let written = write_section(
SectionTag::EntityCreate,
&mut out[offset..],
limits,
|writer| encode_create_body(schema, baseline, current, counts.creates, limits, writer),
)?;
offset += written;
}
if counts.updates > 0 {
let update_encoding = match mode {
EncodeUpdateMode::Auto => {
select_update_encoding(schema, baseline, current, limits, scratch)?
}
EncodeUpdateMode::Sparse => UpdateEncoding::Sparse,
};
let section_tag = match update_encoding {
UpdateEncoding::Masked => SectionTag::EntityUpdate,
UpdateEncoding::Sparse => SectionTag::EntityUpdateSparsePacked,
};
let written =
write_section(
section_tag,
&mut out[offset..],
limits,
|writer| match update_encoding {
UpdateEncoding::Masked => encode_update_body_masked(
schema,
baseline,
current,
counts.updates,
limits,
scratch,
writer,
),
UpdateEncoding::Sparse => encode_update_body_sparse_packed(
schema,
baseline,
current,
counts.updates,
limits,
scratch,
writer,
),
},
)?;
offset += written;
}
Ok(offset)
}
#[allow(clippy::too_many_arguments)]
fn encode_delta_payload_from_updates(
schema: &schema::Schema,
destroys: &[EntityId],
creates: &[EntitySnapshot],
updates: &[DeltaUpdateEntity],
limits: &CodecLimits,
out: &mut [u8],
) -> CodecResult<usize> {
if destroys.len() > limits.max_entities_destroy {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesDestroy,
limit: limits.max_entities_destroy,
actual: destroys.len(),
});
}
if creates.len() > limits.max_entities_create {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesCreate,
limit: limits.max_entities_create,
actual: creates.len(),
});
}
if updates.len() > limits.max_entities_update {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesUpdate,
limit: limits.max_entities_update,
actual: updates.len(),
});
}
ensure_entity_ids_sorted(destroys)?;
ensure_entities_sorted(creates)?;
let lookup = build_component_lookup(schema);
validate_updates_for_encoding(schema, updates, limits, &lookup)?;
let mut offset = 0;
if !destroys.is_empty() {
let written = write_section(
SectionTag::EntityDestroy,
&mut out[offset..],
limits,
|writer| encode_destroy_body_from_list(destroys, limits, writer),
)?;
offset += written;
}
if !creates.is_empty() {
let written = write_section(
SectionTag::EntityCreate,
&mut out[offset..],
limits,
|writer| encode_create_body_from_list(schema, creates, limits, writer),
)?;
offset += written;
}
if !updates.is_empty() {
let written = write_section(
SectionTag::EntityUpdateSparsePacked,
&mut out[offset..],
limits,
|writer| {
encode_update_body_sparse_packed_from_updates(
schema, updates, limits, &lookup, writer,
)
},
)?;
offset += written;
}
Ok(offset)
}
/// Applies a delta snapshot to a baseline snapshot.
pub fn apply_delta_snapshot(
schema: &schema::Schema,
baseline: &Snapshot,
bytes: &[u8],
wire_limits: &wire::Limits,
limits: &CodecLimits,
) -> CodecResult<Snapshot> {
let packet = decode_packet(bytes, wire_limits)?;
apply_delta_snapshot_from_packet(schema, baseline, &packet, limits)
}
/// Applies a delta snapshot from a parsed wire packet.
pub fn apply_delta_snapshot_from_packet(
schema: &schema::Schema,
baseline: &Snapshot,
packet: &WirePacket<'_>,
limits: &CodecLimits,
) -> CodecResult<Snapshot> {
let header = packet.header;
if !header.flags.is_delta_snapshot() {
return Err(CodecError::Wire(wire::DecodeError::InvalidFlags {
flags: header.flags.raw(),
}));
}
if header.baseline_tick == 0 {
return Err(CodecError::Wire(wire::DecodeError::InvalidBaselineTick {
baseline_tick: header.baseline_tick,
flags: header.flags.raw(),
}));
}
if header.baseline_tick != baseline.tick.raw() {
return Err(CodecError::BaselineTickMismatch {
expected: baseline.tick.raw(),
found: header.baseline_tick,
});
}
let expected_hash = schema_hash(schema);
if header.schema_hash != expected_hash {
return Err(CodecError::SchemaMismatch {
expected: expected_hash,
found: header.schema_hash,
});
}
let (destroys, creates, updates) = decode_delta_sections(schema, packet, limits)?;
ensure_entities_sorted(&baseline.entities)?;
ensure_entities_sorted(&creates)?;
let mut remaining = apply_destroys(&baseline.entities, &destroys)?;
remaining = apply_creates(remaining, creates)?;
if remaining.len() > limits.max_total_entities_after_apply {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::TotalEntitiesAfterApply,
limit: limits.max_total_entities_after_apply,
actual: remaining.len(),
});
}
apply_updates(&mut remaining, &updates)?;
Ok(Snapshot {
tick: SnapshotTick::new(header.tick),
entities: remaining,
})
}
/// Decodes a delta packet without applying it to a baseline.
pub fn decode_delta_packet(
schema: &schema::Schema,
packet: &WirePacket<'_>,
limits: &CodecLimits,
) -> CodecResult<DeltaDecoded> {
let header = packet.header;
if !header.flags.is_delta_snapshot() {
return Err(CodecError::Wire(wire::DecodeError::InvalidFlags {
flags: header.flags.raw(),
}));
}
if header.baseline_tick == 0 {
return Err(CodecError::Wire(wire::DecodeError::InvalidBaselineTick {
baseline_tick: header.baseline_tick,
flags: header.flags.raw(),
}));
}
let expected_hash = schema_hash(schema);
if header.schema_hash != expected_hash {
return Err(CodecError::SchemaMismatch {
expected: expected_hash,
found: header.schema_hash,
});
}
let (destroys, creates, updates) = decode_delta_sections(schema, packet, limits)?;
Ok(DeltaDecoded {
tick: SnapshotTick::new(header.tick),
baseline_tick: SnapshotTick::new(header.baseline_tick),
destroys,
creates,
updates,
})
}
#[derive(Default)]
struct DiffCounts {
creates: usize,
updates: usize,
destroys: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum UpdateEncoding {
Masked,
Sparse,
}
fn diff_counts(
schema: &schema::Schema,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
counts: &mut DiffCounts,
) -> CodecResult<()> {
let mut i = 0usize;
let mut j = 0usize;
while i < baseline.entities.len() || j < current.entities.len() {
let base = baseline.entities.get(i);
let curr = current.entities.get(j);
match (base, curr) {
(Some(b), Some(c)) => {
if b.id.raw() < c.id.raw() {
counts.destroys += 1;
i += 1;
} else if b.id.raw() > c.id.raw() {
counts.creates += 1;
j += 1;
} else {
if entity_has_updates(schema, b, c, limits)? {
counts.updates += 1;
}
i += 1;
j += 1;
}
}
(Some(_), None) => {
counts.destroys += 1;
i += 1;
}
(None, Some(_)) => {
counts.creates += 1;
j += 1;
}
(None, None) => break,
}
}
Ok(())
}
fn select_update_encoding(
schema: &schema::Schema,
baseline: &Snapshot,
current: &Snapshot,
limits: &CodecLimits,
scratch: &mut CodecScratch,
) -> CodecResult<UpdateEncoding> {
let component_count = schema.components.len();
let mut mask_bits = 0usize;
let mut sparse_bits = 0usize;
let mut baseline_iter = baseline.entities.iter();
let mut current_iter = current.entities.iter();
let mut baseline_next = baseline_iter.next();
let mut current_next = current_iter.next();
while let (Some(base), Some(curr)) = (baseline_next, current_next) {
match base.id.cmp(&curr.id) {
Ordering::Less => {
baseline_next = baseline_iter.next();
}
Ordering::Greater => {
current_next = current_iter.next();
}
Ordering::Equal => {
for component in &schema.components {
let base_component = find_component(base, component.id);
let curr_component = find_component(curr, component.id);
if base_component.is_some() != curr_component.is_some() {
return Err(CodecError::InvalidMask {
kind: MaskKind::ComponentMask,
reason: MaskReason::ComponentPresenceMismatch {
component: component.id,
},
});
}
if let (Some(base_component), Some(curr_component)) =
(base_component, curr_component)
{
if base_component.fields.len() != component.fields.len()
|| curr_component.fields.len() != component.fields.len()
{
return Err(CodecError::InvalidMask {
kind: MaskKind::FieldMask {
component: component.id,
},
reason: MaskReason::FieldCountMismatch {
expected: component.fields.len(),
actual: base_component
.fields
.len()
.max(curr_component.fields.len()),
},
});
}
if component.fields.len() > limits.max_fields_per_component {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::FieldsPerComponent,
limit: limits.max_fields_per_component,
actual: component.fields.len(),
});
}
let (_, field_mask) = scratch
.component_and_field_masks_mut(component_count, component.fields.len());
// Use the same change predicate as masked/sparse encoding.
let field_mask = compute_field_mask_into(
component,
base_component,
curr_component,
field_mask,
)?;
let changed = field_mask.iter().filter(|bit| **bit).count();
if changed > 0 {
let field_count = component.fields.len();
let index_bits =
required_bits(field_count.saturating_sub(1) as u64) as usize;
// Compare per-component mask bits vs packed sparse index bits.
// Values are sent in both encodings, so we only estimate index/mask + id overhead.
mask_bits += field_count;
sparse_bits += index_bits * changed;
sparse_bits += varu32_len(curr.id.raw()) * 8;
sparse_bits += varu32_len(component.id.get() as u32) * 8;
sparse_bits += varu32_len(changed as u32) * 8;
}
}
}
baseline_next = baseline_iter.next();
current_next = current_iter.next();
}
}
}
if mask_bits == 0 {
return Ok(UpdateEncoding::Masked);
}
if sparse_bits <= mask_bits {
Ok(UpdateEncoding::Sparse)
} else {
Ok(UpdateEncoding::Masked)
}
}
fn varu32_len(value: u32) -> usize {
if value < (1 << 7) {
1
} else if value < (1 << 14) {
2
} else if value < (1 << 21) {
3
} else if value < (1 << 28) {
4
} else {
5
}
}
fn ensure_entity_ids_sorted(ids: &[EntityId]) -> CodecResult<()> {
let mut prev: Option<u32> = None;
for id in ids {
let raw = id.raw();
if let Some(prev_id) = prev {
if raw <= prev_id {
return Err(CodecError::InvalidEntityOrder {
previous: prev_id,
current: raw,
});
}
}
prev = Some(raw);
}
Ok(())
}
fn encode_destroy_body_from_list(
destroys: &[EntityId],
limits: &CodecLimits,
writer: &mut BitWriter<'_>,
) -> CodecResult<()> {
if destroys.len() > limits.max_entities_destroy {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesDestroy,
limit: limits.max_entities_destroy,
actual: destroys.len(),
});
}
writer.align_to_byte()?;
writer.write_varu32(destroys.len() as u32)?;
for id in destroys {
writer.align_to_byte()?;
writer.write_u32_aligned(id.raw())?;
}
writer.align_to_byte()?;
Ok(())
}
fn encode_create_body_from_list(
schema: &schema::Schema,
creates: &[EntitySnapshot],
limits: &CodecLimits,
writer: &mut BitWriter<'_>,
) -> CodecResult<()> {
if creates.len() > limits.max_entities_create {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesCreate,
limit: limits.max_entities_create,
actual: creates.len(),
});
}
writer.align_to_byte()?;
writer.write_varu32(creates.len() as u32)?;
for entity in creates {
write_create_entity(schema, entity, limits, writer)?;
}
writer.align_to_byte()?;
Ok(())
}
fn validate_updates_for_encoding(
schema: &schema::Schema,
updates: &[DeltaUpdateEntity],
limits: &CodecLimits,
lookup: &ComponentLookup,
) -> CodecResult<()> {
let mut prev: Option<u32> = None;
for entity_update in updates {
let id = entity_update.id.raw();
if let Some(prev_id) = prev {
if id <= prev_id {
return Err(CodecError::InvalidEntityOrder {
previous: prev_id,
current: id,
});
}
}
prev = Some(id);
if entity_update.components.len() > limits.max_components_per_entity {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::ComponentsPerEntity,
limit: limits.max_components_per_entity,
actual: entity_update.components.len(),
});
}
for component_update in &entity_update.components {
let component = lookup.component(schema, component_update.id)?;
if component_update.fields.is_empty() {
return Err(CodecError::InvalidMask {
kind: MaskKind::FieldMask {
component: component_update.id,
},
reason: MaskReason::EmptyFieldMask {
component: component_update.id,
},
});
}
if component_update.fields.len() > limits.max_fields_per_component {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::FieldsPerComponent,
limit: limits.max_fields_per_component,
actual: component_update.fields.len(),
});
}
let max_index = component.fields.len().saturating_sub(1);
for (field_idx, _value) in &component_update.fields {
if *field_idx >= component.fields.len() {
return Err(CodecError::InvalidMask {
kind: MaskKind::FieldMask {
component: component_update.id,
},
reason: MaskReason::InvalidFieldIndex {
field_index: *field_idx,
max: max_index,
},
});
}
}
}
}
Ok(())
}
fn encode_update_body_sparse_packed_from_updates(
schema: &schema::Schema,
updates: &[DeltaUpdateEntity],
limits: &CodecLimits,
lookup: &ComponentLookup,
writer: &mut BitWriter<'_>,
) -> CodecResult<()> {
if updates.len() > limits.max_entities_update {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesUpdate,
limit: limits.max_entities_update,
actual: updates.len(),
});
}
let entry_count: usize = updates.iter().map(|entity| entity.components.len()).sum();
let entry_limit = limits
.max_entities_update
.saturating_mul(limits.max_components_per_entity);
if entry_count > entry_limit {
return Err(CodecError::LimitsExceeded {
kind: LimitKind::EntitiesUpdate,
limit: entry_limit,
actual: entry_count,
});
}
writer.align_to_byte()?;
writer.write_varu32(entry_count as u32)?;
for entity_update in updates {
let entity_id = entity_update.id.raw();
for component_update in &entity_update.components {
let component = lookup.component(schema, component_update.id)?;
writer.align_to_byte()?;
writer.write_varu32(entity_id)?;
writer.write_varu32(component.id.get() as u32)?;
writer.write_varu32(component_update.fields.len() as u32)?;
let index_bits = lookup.index_bits(component.id);
for (field_idx, value) in &component_update.fields {
if index_bits > 0 {
writer.write_bits(*field_idx as u64, index_bits)?;
}
write_field_value_sparse(
component.id,
component.fields[*field_idx],
*value,
writer,
)?;
}