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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! Zero-copy, mmap-backed readers for `.cch-struct` and `.cch-metric` bundles.
//!
//! [`CchBundle`] opens a `.cch-struct` file and exposes its arrays as
//! borrowed slices via [`CchView`]; no data is copied — the OS page cache
//! backs the slices directly. Similarly, [`MetricBundle`] opens a
//! `.cch-metric-*` file and exposes forward + backward weight arrays via
//! [`MetricView`].
//!
//! The bundle format is fixed: `.cch-struct` uses magic `CCH_STRC` (version 1)
//! and `.cch-metric` uses magic `CCH_METR` (version 1). Any existing corpus of
//! 316 GB bundles depends on this exact layout; do not change it.
//!
//! Ported from `native/routing-core/src/cch_mmap.rs` in rapidonkey
//! (`CchBundleMmap` / `MetricBundleMmap` / `CchMmapView` / `MetricMmapView`).
/// `RoutingKit`'s `invalid_id` sentinel (`unsigned(-1)` in C++).
pub const INVALID_ID: u32 = u32::MAX;
/// Read-only view over the CCH fields needed for distance-matrix queries.
///
/// Holds borrowed slices — typically backed by mmap'd bundle pages
/// (zero-copy). The lifetime `'a` is tied to the [`CchBundle`] owner.
pub struct CchView<'a> {
/// `rank[external_node_id]` → CCH-internal node id. Length = `node_count`.
pub rank: &'a [u32],
/// `elimination_tree_parent[v]` → parent of v in the elimination tree,
/// or [`INVALID_ID`] for the root. Length = `node_count`.
pub elimination_tree_parent: &'a [u32],
/// CSR offsets for upward arcs. Length = `node_count` + 1.
pub up_first_out: &'a [u32],
/// Head endpoint of each upward arc. Length = `cch_arc_count`.
pub up_head: &'a [u32],
/// CSR offsets for downward arcs. Length = `node_count` + 1.
pub down_first_out: &'a [u32],
/// Head endpoint of each downward arc. Length = `cch_arc_count`.
pub down_head: &'a [u32],
/// Maps each downward arc index to its corresponding upward arc index.
/// Length = `cch_arc_count`.
pub down_to_up: &'a [u32],
}
impl CchView<'_> {
/// Number of nodes. Derived from `rank.len()`.
#[must_use]
#[allow(clippy::cast_possible_truncation)] // node_count fits u32 (CCH limit)
pub fn node_count(&self) -> u32 {
self.rank.len() as u32
}
/// Number of CCH arcs (the contracted graph's arc count, NOT the input
/// edge count). Derived from `up_head.len()`.
#[must_use]
#[allow(clippy::cast_possible_truncation)] // arc_count fits u32 (CCH limit)
pub fn cch_arc_count(&self) -> u32 {
self.up_head.len() as u32
}
}
/// Read-only view over a single customized metric's forward + backward weight
/// arrays. Lifetime `'a` is tied to the [`MetricBundle`] owner.
pub struct MetricView<'a> {
/// `forward[arc]` → shortcut weight for arc in the up→down direction.
pub forward: &'a [u32],
/// `backward[arc]` → shortcut weight for arc in the down→up direction.
pub backward: &'a [u32],
}
// ---------------------------------------------------------------
// Mmap loader — zero-copy via memmap2
// ---------------------------------------------------------------
/// Mmap-backed owner for a `.cch-struct` bundle. Holds the [`memmap2::Mmap`]
/// alive for its lifetime; the slices in [`Self::view`] borrow into the mapped
/// region (zero-copy). Process heap allocation is just offset bookkeeping
/// (~48 bytes); the actual CCH data lives in the OS page cache and is shared
/// across processes that mmap the same file.
pub struct CchBundle {
mmap: memmap2::Mmap,
rank_off: usize,
elim_off: usize,
up_first_out_off: usize,
up_head_off: usize,
down_first_out_off: usize,
down_head_off: usize,
down_to_up_off: usize,
node_count: usize,
cch_arc_count: usize,
}
impl CchBundle {
/// Open a `.cch-struct` bundle at `path`, memory-map it, and validate the
/// header + section layout. Returns an error on I/O failure or a malformed
/// bundle.
///
/// # Errors
///
/// Returns [`std::io::Error`] on I/O failure, bad magic, unsupported
/// version, truncated sections, or unaligned section data.
#[allow(clippy::cast_possible_truncation)] // bundle values fit usize (checked by section length guard)
#[allow(clippy::too_many_lines)] // linear header + per-section validation reads clearest inline
pub fn open(path: &std::path::Path) -> std::io::Result<Self> {
const STRUCT_MAGIC: u64 = 0x4343_485F_5354_5243;
let file = std::fs::File::open(path)?;
// SAFETY: requires the underlying file not be modified while the
// mapping is live. We open read-only; production artifacts are
// immutable (regenerated by `cch-spike build-cch-bundles` — never
// edited in place).
let mmap = unsafe { memmap2::Mmap::map(&file)? };
if mmap.len() < 40 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"bundle too small to contain header",
));
}
let bytes = &mmap[..];
let magic = read_u64_le_at(bytes, 0);
if magic != STRUCT_MAGIC {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"bad magic in {}: {magic:#x}, expected {STRUCT_MAGIC:#x}",
path.display()
),
));
}
let version = read_u32_le_at(bytes, 8);
if version != 1 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("unsupported struct version {version}"),
));
}
let node_count = read_u64_le_at(bytes, 16) as usize;
let cch_arc_count = read_u64_le_at(bytes, 24) as usize;
let _input_arc_count = read_u64_le_at(bytes, 32) as usize;
// Walk sections; capture offsets for the ones we need.
//
// For every section that `view()` later turns into a `&[u32]` slice we
// also assert its self-declared `byte_length` exactly matches
// `4 * expected_u32_count` (where the count is derived from the header).
// Without this, a corrupt/truncated file with an inflated header count
// but a short section would pass the truncation check here yet make
// `view()` read `4 * count` bytes past the section / past the mmap —
// an out-of-bounds read of unmapped pages (UB). Reconciling count vs.
// length here makes the `unsafe` slice construction in `view()` sound
// for arbitrary input. Sections that are only skipped (`order`,
// `up_tail`) pass `None` and keep the original length-only handling.
let mut pos = 40usize;
let mut data_off =
|label: &str, expected_u32_count: Option<usize>| -> std::io::Result<usize> {
if pos + 8 > bytes.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("truncated bundle at section '{label}'"),
));
}
let byte_length = read_u64_le_at(bytes, pos) as usize;
pos += 8;
let off = pos;
pos += byte_length;
if pos > bytes.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("section '{label}' extends past end of mmap"),
));
}
if let Some(count) = expected_u32_count {
let expected_bytes = count.checked_mul(4).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("section '{label}' expected element count {count} overflows"),
)
})?;
if byte_length != expected_bytes {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"section '{label}' byte_length {byte_length} does not match \
expected {expected_bytes} (= 4 * {count}); header count and \
section length disagree"
),
));
}
}
Ok(off)
};
let _order_off = data_off("order", None)?;
let rank_off = data_off("rank", Some(node_count))?;
let elim_off = data_off("elimination_tree_parent", Some(node_count))?;
let up_first_out_off = data_off("up_first_out", Some(node_count + 1))?;
let up_head_off = data_off("up_head", Some(cch_arc_count))?;
let _up_tail_off = data_off("up_tail", None)?;
let down_first_out_off = data_off("down_first_out", Some(node_count + 1))?;
let down_head_off = data_off("down_head", Some(cch_arc_count))?;
let down_to_up_off = data_off("down_to_up", Some(cch_arc_count))?;
// Verify u32 alignment of the slices we'll hand out. Bundles
// produced by the current writer should always be 4-byte aligned
// (mmap base is page-aligned; each section starts after a u64
// prefix + u32 vectors of bytes-length-multiple-of-4).
let base = mmap.as_ptr() as usize;
for (name, off) in [
("rank", rank_off),
("elimination_tree_parent", elim_off),
("up_first_out", up_first_out_off),
("up_head", up_head_off),
("down_first_out", down_first_out_off),
("down_head", down_head_off),
("down_to_up", down_to_up_off),
] {
let addr = base + off;
if addr % std::mem::align_of::<u32>() != 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"section '{name}' is not u32-aligned (offset {off}); \
bundle format would need padding or fall back to eager load"
),
));
}
}
Ok(CchBundle {
mmap,
rank_off,
elim_off,
up_first_out_off,
up_head_off,
down_first_out_off,
down_head_off,
down_to_up_off,
node_count,
cch_arc_count,
})
}
/// Return a zero-copy view over the mmap'd CCH arrays.
///
/// The returned [`CchView`] borrows from `self` — it cannot outlive the
/// bundle.
#[must_use]
pub fn view(&self) -> CchView<'_> {
// SAFETY: open() validated u32 alignment for each offset. The mmap
// outlives the slices (lifetime tied to &self). The mapped region is
// read-only and immutable for the lifetime of the Mmap. The alignment
// check in open() ensures the cast_ptr_alignment requirement is met.
#[allow(clippy::cast_ptr_alignment)] // alignment verified in open()
unsafe {
CchView {
rank: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.rank_off).cast::<u32>(),
self.node_count,
),
elimination_tree_parent: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.elim_off).cast::<u32>(),
self.node_count,
),
up_first_out: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.up_first_out_off).cast::<u32>(),
self.node_count + 1,
),
up_head: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.up_head_off).cast::<u32>(),
self.cch_arc_count,
),
down_first_out: std::slice::from_raw_parts(
self.mmap
.as_ptr()
.add(self.down_first_out_off)
.cast::<u32>(),
self.node_count + 1,
),
down_head: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.down_head_off).cast::<u32>(),
self.cch_arc_count,
),
down_to_up: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.down_to_up_off).cast::<u32>(),
self.cch_arc_count,
),
}
}
}
/// Number of nodes in the CCH.
#[must_use]
pub fn node_count(&self) -> usize {
self.node_count
}
/// Number of CCH arcs.
#[must_use]
pub fn cch_arc_count(&self) -> usize {
self.cch_arc_count
}
/// The raw mmap-backed file bytes.
///
/// Exposed for residency / telemetry use (e.g. `mincore(2)` over the
/// mapped region). The returned slice spans the entire mapping; its
/// `as_ptr()`/`len()` are the page-aligned base and length of the mmap.
#[must_use]
pub fn mmap_bytes(&self) -> &[u8] {
&self.mmap
}
}
/// Mmap-backed owner for a `.cch-metric-*` bundle.
pub struct MetricBundle {
mmap: memmap2::Mmap,
forward_off: usize,
backward_off: usize,
cch_arc_count: usize,
}
impl MetricBundle {
/// Open a `.cch-metric` bundle at `path`, memory-map it, and validate the
/// header + section layout.
///
/// # Errors
///
/// Returns [`std::io::Error`] on I/O failure, bad magic, unsupported
/// version, truncated sections, or unaligned section data.
#[allow(clippy::cast_possible_truncation)] // bundle values fit usize (checked by section length guard)
pub fn open(path: &std::path::Path) -> std::io::Result<Self> {
const METRIC_MAGIC: u64 = 0x4343_485F_4D45_5452;
let file = std::fs::File::open(path)?;
// SAFETY: requires the underlying file not be modified while the
// mapping is live. We open read-only; production artifacts are
// immutable.
let mmap = unsafe { memmap2::Mmap::map(&file)? };
if mmap.len() < 32 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"metric bundle too small to contain header",
));
}
let bytes = &mmap[..];
let magic = read_u64_le_at(bytes, 0);
if magic != METRIC_MAGIC {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("bad metric magic in {}: {magic:#x}", path.display()),
));
}
let version = read_u32_le_at(bytes, 8);
if version != 1 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("unsupported metric version {version}"),
));
}
let cch_arc_count = read_u64_le_at(bytes, 16) as usize;
// Header (24 bytes), then 2 sections each [u64 byte_length][bytes...].
// The mmap.len() >= 32 check above guarantees pos + 8 (= 32) <= bytes.len().
let mut pos = 24usize;
let forward_len = read_u64_le_at(bytes, pos) as usize;
pos += 8;
let forward_off = pos;
pos += forward_len;
if pos + 8 > bytes.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"truncated metric bundle at backward section",
));
}
let backward_len = read_u64_le_at(bytes, pos) as usize;
pos += 8;
let backward_off = pos;
pos += backward_len;
if pos > bytes.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"metric bundle extends past end of mmap",
));
}
// `view()` builds both slices with length `self.cch_arc_count` (the
// header count at offset 16), NOT from `forward_len`/`backward_len`.
// So the section byte-lengths must be reconciled against the header
// count or an inflated `cch_arc_count` with short sections would make
// `view()` read past the sections / past the mmap (OOB, UB). Enforce
// `forward_len == backward_len == 4 * cch_arc_count`. This subsumes the
// "both equal" and "both multiples of 4" checks and the offset bounds.
let expected_bytes = cch_arc_count.checked_mul(4).ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("metric cch_arc_count {cch_arc_count} overflows byte length"),
)
})?;
if forward_len != backward_len {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"metric forward/backward section lengths disagree: \
forward_len={forward_len}, backward_len={backward_len}"
),
));
}
if forward_len != expected_bytes {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!(
"metric section length {forward_len} does not match expected \
{expected_bytes} (= 4 * cch_arc_count {cch_arc_count}); \
header count and section length disagree"
),
));
}
// u32 alignment is guaranteed without a runtime check:
// - mmap base is page-aligned (multiple of 4096)
// - forward_off = 32 (header 24 B + one 8-B length prefix)
// - backward_off = forward_off + forward_len + 8 = 40 + forward_len
// forward_len == expected_bytes == 4 * cch_arc_count, always a multiple
// of 4, so backward_off is also a multiple of 4.
Ok(MetricBundle {
mmap,
forward_off,
backward_off,
cch_arc_count,
})
}
/// Return a zero-copy view over the mmap'd metric arrays.
#[must_use]
pub fn view(&self) -> MetricView<'_> {
// SAFETY: u32 alignment of each offset is guaranteed by open()'s
// arithmetic invariants (see comment there). The mmap outlives the
// slices (lifetime tied to &self). The mapped region is read-only
// and immutable for the lifetime of the Mmap.
#[allow(clippy::cast_ptr_alignment)] // alignment proven by arithmetic in open()
unsafe {
MetricView {
forward: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.forward_off).cast::<u32>(),
self.cch_arc_count,
),
backward: std::slice::from_raw_parts(
self.mmap.as_ptr().add(self.backward_off).cast::<u32>(),
self.cch_arc_count,
),
}
}
}
/// Number of CCH arcs.
#[must_use]
pub fn cch_arc_count(&self) -> usize {
self.cch_arc_count
}
/// The raw mmap-backed file bytes (see [`CchBundle::mmap_bytes`]).
#[must_use]
pub fn mmap_bytes(&self) -> &[u8] {
&self.mmap
}
}
// ---------------------------------------------------------------
// Byte-level helpers
// ---------------------------------------------------------------
fn read_u64_le_at(bytes: &[u8], off: usize) -> u64 {
let mut buf = [0u8; 8];
buf.copy_from_slice(&bytes[off..off + 8]);
u64::from_le_bytes(buf)
}
fn read_u32_le_at(bytes: &[u8], off: usize) -> u32 {
let mut buf = [0u8; 4];
buf.copy_from_slice(&bytes[off..off + 4]);
u32::from_le_bytes(buf)
}
// ---------------------------------------------------------------
// Tests
// ---------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn opens_bundle_and_down_adjacency_is_consistent() {
use routingkit_cch::ffi;
// Build a small path graph: 0→1→2→3→4 (5 nodes, 4 arcs).
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new returned null");
// Save the struct bundle into a temp directory.
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("tiny.cch-struct");
let path_str = path.to_str().expect("path is valid UTF-8");
unsafe { ffi::cch_save_struct(cch_ref, path_str) }.expect("cch_save_struct failed");
// Re-open with our mmap reader.
let bundle = CchBundle::open(&path).expect("CchBundle::open failed");
let v = bundle.view();
let node_count = v.up_first_out.len() - 1;
assert_eq!(v.down_first_out.len(), node_count + 1);
assert_eq!(v.down_head.len(), v.up_head.len());
assert_eq!(v.down_to_up.len(), v.up_head.len());
// Every down-arc points (via down_to_up) at a valid up-arc.
for &ua in v.down_to_up {
assert!(
(ua as usize) < v.up_head.len(),
"down_to_up entry {ua} out of range"
);
}
// Transpose property: for each node y, the set of down-neighbours
// must equal the set of nodes x that have an up-arc whose head is y.
#[allow(clippy::cast_possible_truncation)] // node_count fits u32 (CCH limit)
for y in 0..node_count {
let down_nbrs: std::collections::BTreeSet<u32> = (v.down_first_out[y]
..v.down_first_out[y + 1])
.map(|a| v.down_head[a as usize])
.collect();
let y_u32 = y as u32;
let up_into_y: std::collections::BTreeSet<u32> = (0..node_count as u32)
.filter(|&x| {
(v.up_first_out[x as usize]..v.up_first_out[x as usize + 1])
.any(|a| v.up_head[a as usize] == y_u32)
})
.collect();
assert_eq!(down_nbrs, up_into_y, "transpose mismatch at node {y}");
}
}
#[test]
fn open_rejects_inflated_count_without_oob() {
use routingkit_cch::ffi;
// Build the same valid path-graph struct bundle as the consistency
// test, then read its raw on-disk bytes.
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new returned null");
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("tiny.cch-struct");
let path_str = path.to_str().expect("path is valid UTF-8");
unsafe { ffi::cch_save_struct(cch_ref, path_str) }.expect("cch_save_struct failed");
// Sanity: the pristine bundle opens fine.
CchBundle::open(&path).expect("pristine bundle should open");
let mut bytes = std::fs::read(&path).expect("read bundle bytes");
// Inflate `cch_arc_count` (u64 LE at header offset 24) by a large
// amount. The `up_head`/`down_head`/`down_to_up` sections keep their
// real (now-too-short) byte_lengths, so header count != 4 * length.
// Pre-fix `open()` would accept this and `view()` would then read
// `4 * inflated_count` bytes — past the sections and past the mmap
// (OOB / segfault). Post-fix `open()` must reject it.
let real_arc_count = read_u64_le_at(&bytes, 24);
let inflated = real_arc_count + 1_000_000;
bytes[24..32].copy_from_slice(&inflated.to_le_bytes());
let corrupt_path = dir.path().join("corrupt.cch-struct");
std::fs::write(&corrupt_path, &bytes).expect("write corrupt bundle");
let result = CchBundle::open(&corrupt_path);
// Do NOT call .view() on the result — the whole point is that open()
// now rejects the file before any out-of-bounds slice is built.
// Use assert!(is_err()) + err().unwrap() instead of a match because
// CchBundle does not implement Debug (which unwrap_err() would require).
assert!(
result.is_err(),
"open() must reject a bundle whose header count exceeds its section length"
);
let e = result.err().unwrap();
assert_eq!(
e.kind(),
std::io::ErrorKind::InvalidData,
"rejection must be InvalidData"
);
// Analogous craft for the metric reader: inflate its header
// `cch_arc_count` (u64 LE at offset 16) so the forward/backward
// section lengths no longer match `4 * cch_arc_count`.
let metric_path = dir.path().join("tiny.cch-metric");
let metric_path_str = metric_path.to_str().expect("path is valid UTF-8");
#[allow(clippy::cast_possible_truncation)] // tail.len() is tiny (4) in this test
let weights: Vec<u32> = (0..tail.len() as u32).collect();
let mut metric = unsafe { ffi::cch_metric_new(cch_ref, &weights) };
unsafe { ffi::cch_metric_customize(metric.as_mut().expect("metric pin")) };
unsafe { ffi::cch_save_metric(metric.as_ref().expect("metric ref"), metric_path_str) }
.expect("cch_save_metric failed");
MetricBundle::open(&metric_path).expect("pristine metric bundle should open");
let mut mbytes = std::fs::read(&metric_path).expect("read metric bytes");
let real_metric_count = read_u64_le_at(&mbytes, 16);
let inflated_metric = real_metric_count + 1_000_000;
mbytes[16..24].copy_from_slice(&inflated_metric.to_le_bytes());
let corrupt_metric_path = dir.path().join("corrupt.cch-metric");
std::fs::write(&corrupt_metric_path, &mbytes).expect("write corrupt metric bundle");
let mresult = MetricBundle::open(&corrupt_metric_path);
assert!(
mresult.is_err(),
"metric open() must reject a bundle whose header count exceeds its section length"
);
let me = mresult.err().unwrap();
assert_eq!(
me.kind(),
std::io::ErrorKind::InvalidData,
"metric rejection must be InvalidData"
);
}
#[test]
fn opens_metric_bundle() {
use routingkit_cch::ffi;
// Build a small path graph: 0→1→2→3→4 (5 nodes, 4 arcs).
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new returned null");
let dir = tempfile::tempdir().expect("tempdir");
// Save struct bundle so we can cross-check the CCH arc count.
let struct_path = dir.path().join("tiny.cch-struct");
let struct_path_str = struct_path.to_str().expect("path is valid UTF-8");
unsafe { ffi::cch_save_struct(cch_ref, struct_path_str) }.expect("cch_save_struct failed");
let struct_bundle = CchBundle::open(&struct_path).expect("CchBundle::open failed");
let expected_arc_count = struct_bundle.view().up_head.len();
// Build and customize a metric; weights = arc index (one per input arc).
#[allow(clippy::cast_possible_truncation)] // tail.len() is tiny (4) in this test
let weights: Vec<u32> = (0..tail.len() as u32).collect();
let mut metric = unsafe { ffi::cch_metric_new(cch_ref, &weights) };
unsafe { ffi::cch_metric_customize(metric.as_mut().expect("metric pin")) };
// Save the metric bundle.
let metric_path = dir.path().join("tiny.cch-metric");
let metric_path_str = metric_path.to_str().expect("path is valid UTF-8");
unsafe { ffi::cch_save_metric(metric.as_ref().expect("metric ref"), metric_path_str) }
.expect("cch_save_metric failed");
// Re-open with our mmap reader.
let mbundle = MetricBundle::open(&metric_path).expect("MetricBundle::open failed");
let mv = mbundle.view();
// forward and backward arrays must be the same length.
assert_eq!(mv.forward.len(), mv.backward.len());
// Both must equal the CCH arc count from the struct bundle.
assert!(
!mv.forward.is_empty(),
"metric forward array must be non-empty"
);
assert_eq!(
mv.forward.len(),
expected_arc_count,
"metric forward len should match CCH arc count"
);
assert_eq!(
mv.backward.len(),
expected_arc_count,
"metric backward len should match CCH arc count"
);
// mmap_bytes() spans the entire mapped file (for residency/telemetry).
let struct_file_len =
usize::try_from(std::fs::metadata(&struct_path).unwrap().len()).unwrap();
assert_eq!(struct_bundle.mmap_bytes().len(), struct_file_len);
assert!(!struct_bundle.mmap_bytes().is_empty());
let metric_file_len =
usize::try_from(std::fs::metadata(&metric_path).unwrap().len()).unwrap();
assert_eq!(mbundle.mmap_bytes().len(), metric_file_len);
assert!(!mbundle.mmap_bytes().is_empty());
}
// ---- CchView::cch_arc_count and CchBundle node_count/cch_arc_count ----
#[test]
fn cch_view_cch_arc_count_and_bundle_accessors() {
use routingkit_cch::ffi;
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new returned null");
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("acc.cch-struct");
unsafe { ffi::cch_save_struct(cch_ref, path.to_str().unwrap()) }
.expect("cch_save_struct failed");
let bundle = CchBundle::open(&path).expect("CchBundle::open");
// CchBundle::node_count() and cch_arc_count()
assert_eq!(bundle.node_count(), n as usize);
assert!(bundle.cch_arc_count() > 0);
// CchView::cch_arc_count()
let v = bundle.view();
#[allow(clippy::cast_possible_truncation)]
let expected_arc_count = bundle.cch_arc_count() as u32;
assert_eq!(v.cch_arc_count(), expected_arc_count);
}
#[test]
fn metric_bundle_cch_arc_count() {
use routingkit_cch::ffi;
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new returned null");
let dir = tempfile::tempdir().expect("tempdir");
let struct_path = dir.path().join("macc.cch-struct");
let metric_path = dir.path().join("macc.cch-metric");
#[allow(clippy::cast_possible_truncation)]
let weights: Vec<u32> = (0..tail.len() as u32).collect();
let mut metric = unsafe { ffi::cch_metric_new(cch_ref, &weights) };
unsafe {
ffi::cch_save_struct(cch_ref, struct_path.to_str().unwrap()).unwrap();
ffi::cch_metric_customize(metric.as_mut().unwrap());
ffi::cch_save_metric(metric.as_ref().unwrap(), metric_path.to_str().unwrap()).unwrap();
}
let struct_bundle = CchBundle::open(&struct_path).unwrap();
let metric_bundle = MetricBundle::open(&metric_path).unwrap();
// MetricBundle::cch_arc_count() should match the struct's arc count.
assert_eq!(metric_bundle.cch_arc_count(), struct_bundle.cch_arc_count());
}
// ---- Struct bundle format error tests ----
#[test]
fn open_rejects_struct_too_small() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("small.cch-struct");
// Write only 10 bytes — too small for the 40-byte header.
std::fs::write(&path, [0u8; 10]).unwrap();
let err = CchBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("too small"));
}
#[test]
fn open_rejects_struct_bad_magic() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("badmagic.cch-struct");
// Write 40 bytes: first 8 bytes are wrong magic, rest zero.
let mut bytes = vec![0u8; 40];
bytes[0..8].copy_from_slice(&0xDEAD_BEEF_DEAD_BEEFu64.to_le_bytes());
// version = 1
bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
std::fs::write(&path, &bytes).unwrap();
let err = CchBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("bad magic"));
}
#[test]
fn open_rejects_struct_bad_version() {
const STRUCT_MAGIC: u64 = 0x4343_485F_5354_5243;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("badver.cch-struct");
let mut bytes = vec![0u8; 40];
bytes[0..8].copy_from_slice(&STRUCT_MAGIC.to_le_bytes());
bytes[8..12].copy_from_slice(&2u32.to_le_bytes()); // version 2
std::fs::write(&path, &bytes).unwrap();
let err = CchBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("unsupported struct version"));
}
#[test]
fn open_rejects_struct_truncated_at_first_section() {
// Build a valid bundle, then truncate it to exactly 40 bytes (the header),
// so the first section header (order) cannot be read.
use routingkit_cch::ffi;
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new");
let dir = tempfile::tempdir().expect("tempdir");
let full_path = dir.path().join("full.cch-struct");
unsafe { ffi::cch_save_struct(cch_ref, full_path.to_str().unwrap()) }.unwrap();
let full_bytes = std::fs::read(&full_path).unwrap();
// Truncate to just the 40-byte header (section 'order' needs pos+8 bytes which is 48).
let trunc = &full_bytes[..40];
let trunc_path = dir.path().join("trunc.cch-struct");
std::fs::write(&trunc_path, trunc).unwrap();
let err = CchBundle::open(&trunc_path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("truncated bundle at section"));
}
#[test]
fn open_rejects_struct_section_extends_past_end() {
// Build a valid bundle, then inflate the first section's byte_length so it
// extends past the end of the file.
use routingkit_cch::ffi;
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new");
let dir = tempfile::tempdir().expect("tempdir");
let full_path = dir.path().join("full2.cch-struct");
unsafe { ffi::cch_save_struct(cch_ref, full_path.to_str().unwrap()) }.unwrap();
let mut bytes = std::fs::read(&full_path).unwrap();
// At offset 40: the first section (order) byte_length u64 LE.
// Inflate it so pos (40 + 8 + inflated_len) > bytes.len().
let inflated_len = bytes.len() as u64 + 1_000_000;
bytes[40..48].copy_from_slice(&inflated_len.to_le_bytes());
let bad_path = dir.path().join("bad2.cch-struct");
std::fs::write(&bad_path, &bytes).unwrap();
let err = CchBundle::open(&bad_path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("extends past end of mmap"));
}
// ---- Metric bundle format error tests ----
#[test]
fn open_rejects_metric_too_small() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("small.cch-metric");
std::fs::write(&path, [0u8; 10]).unwrap();
let err = MetricBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("too small"));
}
#[test]
fn open_rejects_metric_bad_magic() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("badmagic.cch-metric");
let mut bytes = vec![0u8; 32];
bytes[0..8].copy_from_slice(&0xDEAD_BEEF_DEAD_BEEFu64.to_le_bytes());
bytes[8..12].copy_from_slice(&1u32.to_le_bytes());
std::fs::write(&path, &bytes).unwrap();
let err = MetricBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("bad metric magic"));
}
#[test]
fn open_rejects_metric_bad_version() {
const METRIC_MAGIC: u64 = 0x4343_485F_4D45_5452;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("badver.cch-metric");
let mut bytes = vec![0u8; 32];
bytes[0..8].copy_from_slice(&METRIC_MAGIC.to_le_bytes());
bytes[8..12].copy_from_slice(&2u32.to_le_bytes()); // version 2
std::fs::write(&path, &bytes).unwrap();
let err = MetricBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("unsupported metric version"));
}
#[test]
fn open_rejects_metric_truncated_at_backward_section() {
// Build a real metric, then truncate it so the forward section data is
// present but the backward section header is missing.
use routingkit_cch::ffi;
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new");
let dir = tempfile::tempdir().expect("tempdir");
let struct_path = dir.path().join("t.cch-struct");
let metric_path = dir.path().join("full.cch-metric");
#[allow(clippy::cast_possible_truncation)]
let weights: Vec<u32> = (0..tail.len() as u32).collect();
let mut metric = unsafe { ffi::cch_metric_new(cch_ref, &weights) };
unsafe {
ffi::cch_save_struct(cch_ref, struct_path.to_str().unwrap()).unwrap();
ffi::cch_metric_customize(metric.as_mut().unwrap());
ffi::cch_save_metric(metric.as_ref().unwrap(), metric_path.to_str().unwrap()).unwrap();
}
let full_bytes = std::fs::read(&metric_path).unwrap();
// The format is: 24-byte header, [u64 fwd_len][fwd data], [u64 bwd_len][bwd data]
// Truncate to 24 + 8 + forward_data (no backward section header).
#[allow(clippy::cast_possible_truncation)] // bundle sizes fit usize in test
let fwd_len = {
let mut buf = [0u8; 8];
buf.copy_from_slice(&full_bytes[24..32]);
u64::from_le_bytes(buf) as usize
};
// Keep header (24) + fwd_len_u64 (8) + fwd_data (fwd_len) - but NOT backward section header
let trunc_len = 24 + 8 + fwd_len; // exactly at boundary, backward header missing
let trunc = &full_bytes[..trunc_len];
let trunc_path = dir.path().join("trunc_bwd.cch-metric");
std::fs::write(&trunc_path, trunc).unwrap();
let err = MetricBundle::open(&trunc_path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(
err.to_string()
.contains("truncated metric bundle at backward")
);
}
#[test]
fn open_rejects_metric_extends_past_end() {
// Build a real metric bundle, then inflate the backward section length
// so pos > bytes.len() after reading it.
use routingkit_cch::ffi;
let n: u32 = 5;
let order: Vec<u32> = (0..n).collect();
let tail: Vec<u32> = (0..n - 1).collect();
let head: Vec<u32> = (1..n).collect();
let cch = unsafe { ffi::cch_new(&order, &tail, &head, |_| {}, false) };
let cch_ref = cch.as_ref().expect("cch_new");
let dir = tempfile::tempdir().expect("tempdir");
let struct_path = dir.path().join("t2.cch-struct");
let metric_path = dir.path().join("full2.cch-metric");
#[allow(clippy::cast_possible_truncation)]
let weights: Vec<u32> = (0..tail.len() as u32).collect();
let mut metric = unsafe { ffi::cch_metric_new(cch_ref, &weights) };
unsafe {
ffi::cch_save_struct(cch_ref, struct_path.to_str().unwrap()).unwrap();
ffi::cch_metric_customize(metric.as_mut().unwrap());
ffi::cch_save_metric(metric.as_ref().unwrap(), metric_path.to_str().unwrap()).unwrap();
}
let mut bytes = std::fs::read(&metric_path).unwrap();
// The backward section length is at offset 24 + 8 + fwd_len.
#[allow(clippy::cast_possible_truncation)] // bundle sizes fit usize in test
let fwd_len = {
let mut buf = [0u8; 8];
buf.copy_from_slice(&bytes[24..32]);
u64::from_le_bytes(buf) as usize
};
let bwd_off = 24 + 8 + fwd_len;
// Inflate backward length massively.
let inflated_bwd = bytes.len() as u64 + 1_000_000;
bytes[bwd_off..bwd_off + 8].copy_from_slice(&inflated_bwd.to_le_bytes());
let bad_path = dir.path().join("bad_ext.cch-metric");
std::fs::write(&bad_path, &bytes).unwrap();
let err = MetricBundle::open(&bad_path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("extends past end of mmap"));
}
#[test]
fn open_rejects_metric_forward_backward_len_mismatch() {
const METRIC_MAGIC: u64 = 0x4343_485F_4D45_5452;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("mismatch.cch-metric");
// Craft a metric bundle with cch_arc_count=2, forward_len=8, backward_len=12.
// Sizes: header(24) + fwd_header(8) + fwd_data(8) + bwd_header(8) + bwd_data(12) = 60 bytes.
let mut bytes = vec![0u8; 60];
bytes[0..8].copy_from_slice(&METRIC_MAGIC.to_le_bytes());
bytes[8..12].copy_from_slice(&1u32.to_le_bytes()); // version 1
// bytes 12-15: padding (zero)
bytes[16..24].copy_from_slice(&2u64.to_le_bytes()); // cch_arc_count = 2
// Forward section at offset 24: len=8 (= 4*2, correct)
bytes[24..32].copy_from_slice(&8u64.to_le_bytes());
// forward data at 32: 8 bytes (zeros)
// Backward section at offset 40: len=12 (≠ 8, mismatch)
bytes[40..48].copy_from_slice(&12u64.to_le_bytes());
// backward data at 48: 12 bytes (zeros) — total = 60 bytes
std::fs::write(&path, &bytes).unwrap();
let err = MetricBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(
err.to_string()
.contains("forward/backward section lengths disagree")
);
}
// ---- Struct section alignment failure ----
//
// Craft a struct bundle where the 'order' section has an odd byte_length (1),
// causing the 'rank' section's data to start at offset 57 (≡ 1 mod 4).
// The mmap base is page-aligned (≡ 0 mod 4), so the effective address is
// 0+57 ≡ 1 mod 4, failing the u32-alignment check.
//
// Layout (node_count=1, cch_arc_count=0):
// [0..40) header (magic, version=1, nc=1, cac=0, iac=0)
// [40..48) order section byte_length = 1 (u64 LE)
// [48) order data (1 byte) ← pos 49 after this
// [49..57) rank section byte_length = 4 (u64 LE) ← rank_off=57 (misaligned!)
// [57..61) rank data (4 bytes)
// [61..69) elim byte_length = 4 (u64 LE)
// [69..73) elim data (4 bytes)
// [73..81) up_first_out byte_length = 8 (u64 LE)
// [81..89) up_first_out data (8 bytes)
// [89..97) up_head byte_length = 0 (u64 LE)
// [97..105) up_tail byte_length = 0 (u64 LE)
// [105..113) down_first_out byte_length = 8 (u64 LE)
// [113..121) down_first_out data (8 bytes)
// [121..129) down_head byte_length = 0 (u64 LE)
// [129..137) down_to_up byte_length = 0 (u64 LE)
// Total: 137 bytes
#[test]
fn open_rejects_struct_misaligned_section() {
const STRUCT_MAGIC: u64 = 0x4343_485F_5354_5243;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("misalign.cch-struct");
let mut b = vec![0u8; 137];
// header
b[0..8].copy_from_slice(&STRUCT_MAGIC.to_le_bytes());
b[8..12].copy_from_slice(&1u32.to_le_bytes()); // version 1
// offset 12..16: padding (zero)
b[16..24].copy_from_slice(&1u64.to_le_bytes()); // node_count = 1
b[24..32].copy_from_slice(&0u64.to_le_bytes()); // cch_arc_count = 0
b[32..40].copy_from_slice(&0u64.to_le_bytes()); // input_arc_count = 0
// order section: byte_length = 1 (odd → next section at misaligned offset)
b[40..48].copy_from_slice(&1u64.to_le_bytes());
// order data: 1 byte at offset 48
// rank section header at offset 49; rank_off = 57 (57 % 4 = 1)
b[49..57].copy_from_slice(&4u64.to_le_bytes()); // rank byte_length = 4 (= 4 * nc=1)
// rank data at 57..61
// elim section at 61
b[61..69].copy_from_slice(&4u64.to_le_bytes()); // elim byte_length = 4
// elim data at 69..73
// up_first_out at 73
b[73..81].copy_from_slice(&8u64.to_le_bytes()); // up_first_out byte_length = 8 (= 4*(nc+1)=8)
// data at 81..89
// up_head at 89
b[89..97].copy_from_slice(&0u64.to_le_bytes()); // up_head byte_length = 0 (cac=0)
// up_tail at 97
b[97..105].copy_from_slice(&0u64.to_le_bytes()); // up_tail byte_length = 0
// down_first_out at 105
b[105..113].copy_from_slice(&8u64.to_le_bytes()); // down_first_out byte_length = 8
// data at 113..121
// down_head at 121
b[121..129].copy_from_slice(&0u64.to_le_bytes()); // down_head byte_length = 0
// down_to_up at 129
b[129..137].copy_from_slice(&0u64.to_le_bytes()); // down_to_up byte_length = 0
std::fs::write(&path, &b).unwrap();
let err = CchBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("not u32-aligned"));
}
// ---- Struct section count overflow (checked_mul path) ----
//
// Craft a bundle with node_count = u64::MAX so that, when the `rank`
// section is validated, `count.checked_mul(4)` overflows (returns None)
// and triggers the InvalidData error at lines 172-176.
//
// Layout:
// [0..8) STRUCT_MAGIC
// [8..12) version = 1
// [12..16) padding (zero)
// [16..24) node_count = u64::MAX ← causes overflow in checked_mul
// [24..32) cch_arc_count = 0
// [32..40) input_arc_count = 0
// [40..48) order byte_length = 0 ← empty order section, passes None check
// [48..56) rank byte_length = 0 ← triggers checked_mul(4) overflow for node_count
// Total: 56 bytes
#[test]
fn open_rejects_struct_section_count_overflow() {
const STRUCT_MAGIC: u64 = 0x4343_485F_5354_5243;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("overflow.cch-struct");
let mut b = vec![0u8; 56];
b[0..8].copy_from_slice(&STRUCT_MAGIC.to_le_bytes());
b[8..12].copy_from_slice(&1u32.to_le_bytes()); // version 1
// node_count = u64::MAX so checked_mul(4) overflows → error
b[16..24].copy_from_slice(&u64::MAX.to_le_bytes());
b[24..32].copy_from_slice(&0u64.to_le_bytes()); // cch_arc_count = 0
b[32..40].copy_from_slice(&0u64.to_le_bytes()); // input_arc_count = 0
// order section: byte_length = 0 (passes, no count check)
b[40..48].copy_from_slice(&0u64.to_le_bytes());
// rank section: byte_length = 0 (but count = usize::MAX → overflow)
b[48..56].copy_from_slice(&0u64.to_le_bytes());
std::fs::write(&path, &b).unwrap();
let err = CchBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("overflows"));
}
// ---- Metric section count overflow (checked_mul path) ----
//
// Craft a metric bundle with cch_arc_count = u64::MAX so that
// `cch_arc_count.checked_mul(4)` overflows and triggers lines 387-391.
//
// Layout:
// [0..8) METRIC_MAGIC
// [8..12) version = 1
// [12..16) padding (zero)
// [16..24) cch_arc_count = u64::MAX ← causes overflow in checked_mul
// [24..32) forward byte_length = 0
// [32..40) backward byte_length = 0
// Total: 40 bytes (>= 32-byte minimum; forward+backward sections present)
#[test]
fn open_rejects_metric_section_count_overflow() {
const METRIC_MAGIC: u64 = 0x4343_485F_4D45_5452;
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("overflow.cch-metric");
let mut b = vec![0u8; 40];
b[0..8].copy_from_slice(&METRIC_MAGIC.to_le_bytes());
b[8..12].copy_from_slice(&1u32.to_le_bytes()); // version 1
// cch_arc_count = u64::MAX → checked_mul(4) overflows → error
b[16..24].copy_from_slice(&u64::MAX.to_le_bytes());
// forward section: byte_length = 0 at offset 24
b[24..32].copy_from_slice(&0u64.to_le_bytes());
// backward section: byte_length = 0 at offset 32
b[32..40].copy_from_slice(&0u64.to_le_bytes());
std::fs::write(&path, &b).unwrap();
let err = MetricBundle::open(&path).map(|_| ()).unwrap_err();
assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
assert!(err.to_string().contains("overflows"));
}
}