coip-cli 0.2.0

CLI for converting, importing, exporting, diffing, inspecting, querying, verifying, and benchmarking COI (.coi) IP databases
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
//! Stage 3 CLI operations: `.coi -> .coi` repacking, `import`, `export`, and `diff`.

use std::collections::{BTreeMap, HashMap};
use std::io::{BufWriter, Write};
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::Path;
use std::time::Instant;

use coip_builder::{
    BuildOptions, BuildStats, ImportFormat, ImportOptions, V4Interval, V6HostInterval, V6Interval,
    build_from_parts, import_file_to_coi,
};
use coip_format::{MAGIC_HEADER, Value, range_to_cidrs_v4, range_to_cidrs_v6};
use coip_reader::{Projection, Reader, ReaderOptions};

use crate::{format_bytes, value_to_json};

/// Detect whether `path` starts with COI magic bytes `"COI\0"`.
pub fn is_coi_file(path: &Path) -> std::io::Result<bool> {
    use std::io::Read;
    let mut f = std::fs::File::open(path)?;
    let mut magic = [0u8; 4];
    if f.read(&mut magic)? < 4 {
        return Ok(false);
    }
    Ok(magic == MAGIC_HEADER)
}

/// Repack an existing `.coi` file into a new `.coi` file (switching profile, level, block size,
/// or applying `--keep-fields` pruning without needing the original `.mmdb`).
pub fn repack_coi_file(
    src_coi: &Path,
    dst_coi: &Path,
    options: &BuildOptions,
) -> Result<BuildStats, Box<dyn std::error::Error>> {
    let reader = Reader::open_with_options(
        src_coi,
        ReaderOptions {
            ipv4_block_cache_capacity: 64,
            ipv6_block_cache_capacity: 64,
            chunk_cache_capacity: 512,
            flat_dict_cache_capacity: 64,
            verify_all_checksums_on_open: false,
        },
    )?;

    // If `--keep-fields` was specified, compile a reader Projection so unrequested columns
    // aren't even decompressed while reading the source `.coi`!
    let read_proj: Option<Projection> =
        match options.prune.as_ref().and_then(|p| p.keep_fields.as_ref()) {
            Some(paths) => Some(reader.compile_projection(paths)?),
            None => None,
        };

    let record_count = reader.header().record_count as usize;
    let mut unique_records: Vec<BTreeMap<String, Value>> = Vec::with_capacity(record_count);
    let mut old_to_new = vec![0u32; record_count + 1];
    let mut dedup: HashMap<BTreeMap<String, Value>, u32> = HashMap::new();

    for rid in 1..=record_count as u64 {
        let opt_map = reader.get_record_by_id(rid, read_proj.as_ref())?;
        if let Some(map) = opt_map {
            // If projected to empty (and original wasn't empty), skip
            if read_proj.is_some() && map.is_empty() {
                old_to_new[rid as usize] = 0;
                continue;
            }
            let new_id = if let Some(&existing) = dedup.get(&map) {
                existing
            } else {
                let id = (unique_records.len() + 1) as u32;
                dedup.insert(map.clone(), id);
                unique_records.push(map);
                id
            };
            old_to_new[rid as usize] = new_id;
        }
    }

    let v4_intervals: Vec<V4Interval> = reader
        .ipv4_ranges()?
        .into_iter()
        .filter_map(|(start, end, rid)| {
            let new_rid = old_to_new[rid as usize];
            if new_rid == 0 {
                None
            } else {
                Some(V4Interval {
                    start,
                    end,
                    record_idx: new_rid,
                })
            }
        })
        .collect();

    let v6_intervals: Vec<V6Interval> = reader
        .ipv6_ranges()?
        .into_iter()
        .filter_map(|(start, end, rid)| {
            let new_rid = old_to_new[rid as usize];
            if new_rid == 0 {
                None
            } else {
                Some(V6Interval {
                    start,
                    end,
                    record_idx: new_rid,
                })
            }
        })
        .collect();

    let v6_host_ext: Vec<V6HostInterval> = reader
        .ipv6_host_ext()
        .entries
        .iter()
        .map(|e| V6HostInterval {
            start: e.start,
            end: e.end,
            record_idx: old_to_new[e.record_id as usize],
        })
        .collect();

    let (coi_bytes, stats) = build_from_parts(
        options,
        reader.header().build_epoch,
        reader.metadata().clone(),
        reader.ipv6_aliases().rules.clone(),
        v4_intervals,
        v6_intervals,
        v6_host_ext,
        unique_records,
    )?;

    std::fs::write(dst_coi, &coi_bytes)?;
    Ok(stats)
}

/// `coip import`: build a `.coi` database from JSONL or CSV.
#[allow(clippy::too_many_arguments)]
pub fn cmd_import(
    src: &Path,
    dst: &Path,
    format_str: &str,
    cidr_field: Option<String>,
    end_ip_field: Option<String>,
    flat_csv: bool,
    database_type: Option<String>,
    build_options: BuildOptions,
) -> Result<(), Box<dyn std::error::Error>> {
    let format = match format_str {
        "jsonl" | "ndjson" => ImportFormat::Jsonl,
        "csv" => ImportFormat::Csv,
        "auto" => {
            let ext = src
                .extension()
                .and_then(|s| s.to_str())
                .unwrap_or("")
                .to_ascii_lowercase();
            if ext == "csv" {
                ImportFormat::Csv
            } else {
                ImportFormat::Jsonl
            }
        }
        other => {
            return Err(format!("invalid --format '{other}': expected auto | jsonl | csv").into());
        }
    };

    let src_len = std::fs::metadata(src)?.len();
    let opts = ImportOptions {
        format,
        cidr_field,
        end_ip_field,
        unflatten_dots: !flat_csv,
        database_type,
        build_options,
    };

    let t0 = Instant::now();
    let stats = import_file_to_coi(src, dst, &opts)?;
    let elapsed = t0.elapsed();

    println!(
        "Imported {} ({format:?}) -> {}",
        src.display(),
        dst.display()
    );
    println!("  Elapsed:          {:.2}s", elapsed.as_secs_f64());
    println!("  Source size:      {}", format_bytes(src_len));
    println!(
        "  Output size:      {} ({:.2}x smaller)",
        format_bytes(stats.total_bytes),
        src_len as f64 / stats.total_bytes.max(1) as f64
    );
    println!("  Unique records:   {}", stats.record_count);
    println!("  IPv4 transitions: {}", stats.v4_transitions);
    println!("  IPv6 transitions: {}", stats.v6_transitions);
    println!("  IPv6 host ext:    {}", stats.v6_host_ext_entries);
    println!("  Dictionaries:     {}", stats.dict_count);
    Ok(())
}

/// `coip export`: stream CIDRs + JSONL records from a `.coi` file.
pub fn cmd_export(
    file: &Path,
    output: Option<&Path>,
    fields: Option<String>,
    ip_version: &str,
    limit: Option<usize>,
) -> Result<(), Box<dyn std::error::Error>> {
    let reader = Reader::open(file)?;
    let proj = match fields {
        Some(f) => {
            let paths: Vec<&str> = f
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .collect();
            Some(reader.compile_projection(&paths)?)
        }
        None => None,
    };

    let emit_v4 = matches!(ip_version, "all" | "v4" | "4");
    let emit_v6 = matches!(ip_version, "all" | "v6" | "6");
    if !emit_v4 && !emit_v6 {
        return Err(format!("invalid --ip-version '{ip_version}': expected all | v4 | v6").into());
    }

    let writer_box: Box<dyn Write> = match output {
        Some(p) => Box::new(std::fs::File::create(p)?),
        None => Box::new(std::io::stdout().lock()),
    };
    let mut out = BufWriter::new(writer_box);
    let mut emitted = 0usize;

    // Cache formatted JSON body per record_id so shared records serialize fast.
    let mut rec_cache: HashMap<u64, Option<serde_json::Map<String, serde_json::Value>>> =
        HashMap::new();

    let mut get_rec_obj = |rid: u64| -> Result<
        Option<serde_json::Map<String, serde_json::Value>>,
        Box<dyn std::error::Error>,
    > {
        if let Some(cached) = rec_cache.get(&rid) {
            return Ok(cached.clone());
        }
        let val = reader.get_record_by_id(rid, proj.as_ref())?;
        let obj = val.map(|m| {
            let mut obj = serde_json::Map::new();
            for (k, v) in m {
                obj.insert(k, value_to_json(&v));
            }
            obj
        });
        if rec_cache.len() < 16_384 {
            rec_cache.insert(rid, obj.clone());
        }
        Ok(obj)
    };

    if emit_v4 {
        for (start, end, rid) in reader.ipv4_ranges()? {
            let Some(base_obj) = get_rec_obj(rid)? else {
                continue;
            };
            for (net, plen) in range_to_cidrs_v4(start, end) {
                let mut obj = serde_json::Map::with_capacity(base_obj.len() + 1);
                obj.insert(
                    "cidr".into(),
                    serde_json::Value::String(format!("{}/{plen}", Ipv4Addr::from(net))),
                );
                for (k, v) in &base_obj {
                    obj.insert(k.clone(), v.clone());
                }
                serde_json::to_writer(&mut out, &serde_json::Value::Object(obj))?;
                out.write_all(b"\n")?;
                emitted += 1;
                if limit.is_some_and(|l| emitted >= l) {
                    out.flush()?;
                    return Ok(());
                }
            }
        }
    }

    if emit_v6 {
        for (start_hi, end_hi, rid) in reader.ipv6_ranges()? {
            let Some(base_obj) = get_rec_obj(rid)? else {
                continue;
            };
            let s128 = (start_hi as u128) << 64;
            let e128 = ((end_hi as u128) << 64) | (u64::MAX as u128);
            for (net, plen) in range_to_cidrs_v6(s128, e128) {
                let mut obj = serde_json::Map::with_capacity(base_obj.len() + 1);
                obj.insert(
                    "cidr".into(),
                    serde_json::Value::String(format!("{}/{plen}", Ipv6Addr::from(net))),
                );
                for (k, v) in &base_obj {
                    obj.insert(k.clone(), v.clone());
                }
                serde_json::to_writer(&mut out, &serde_json::Value::Object(obj))?;
                out.write_all(b"\n")?;
                emitted += 1;
                if limit.is_some_and(|l| emitted >= l) {
                    out.flush()?;
                    return Ok(());
                }
            }
        }

        for e in &reader.ipv6_host_ext().entries {
            if e.record_id == 0 {
                continue;
            }
            let Some(base_obj) = get_rec_obj(e.record_id)? else {
                continue;
            };
            for (net, plen) in range_to_cidrs_v6(e.start, e.end) {
                let mut obj = serde_json::Map::with_capacity(base_obj.len() + 1);
                obj.insert(
                    "cidr".into(),
                    serde_json::Value::String(format!("{}/{plen}", Ipv6Addr::from(net))),
                );
                for (k, v) in &base_obj {
                    obj.insert(k.clone(), v.clone());
                }
                serde_json::to_writer(&mut out, &serde_json::Value::Object(obj))?;
                out.write_all(b"\n")?;
                emitted += 1;
                if limit.is_some_and(|l| emitted >= l) {
                    out.flush()?;
                    return Ok(());
                }
            }
        }
    }

    out.flush()?;
    Ok(())
}

/// Exact two-pointer transition sweep statistics.
#[derive(Default)]
struct DiffStats {
    added: u128,
    removed: u128,
    changed: u128,
    unchanged: u128,
    samples: Vec<DiffSample>,
}

struct DiffSample {
    kind: &'static str,
    cidr: String,
    old_rid: u64,
    new_rid: u64,
}

/// `coip diff`: exact dual-stack IP range diff between two `.coi` databases.
pub fn cmd_diff(
    old_path: &Path,
    new_path: &Path,
    fields: Option<String>,
    max_samples: usize,
) -> Result<(), Box<dyn std::error::Error>> {
    let t0 = Instant::now();
    let old_r = Reader::open_with_options(
        old_path,
        ReaderOptions {
            chunk_cache_capacity: 1024,
            ..ReaderOptions::default()
        },
    )?;
    let new_r = Reader::open_with_options(
        new_path,
        ReaderOptions {
            chunk_cache_capacity: 1024,
            ..ReaderOptions::default()
        },
    )?;

    let (old_proj, new_proj) = match fields {
        Some(ref f) => {
            let paths: Vec<&str> = f
                .split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .collect();
            (
                Some(old_r.compile_projection(&paths)?),
                Some(new_r.compile_projection(&paths)?),
            )
        }
        None => (None, None),
    };

    // Memoize `(old_rid, new_rid) -> is_equal` across all millions of transitions!
    let mut eq_cache: HashMap<(u64, u64), bool> = HashMap::new();
    let mut old_rec_cache: HashMap<u64, Option<Value>> = HashMap::new();
    let mut new_rec_cache: HashMap<u64, Option<Value>> = HashMap::new();

    let mut records_equal =
        |old_rid: u64, new_rid: u64| -> Result<bool, Box<dyn std::error::Error>> {
            if old_rid == 0 && new_rid == 0 {
                return Ok(true);
            }
            if let Some(&eq) = eq_cache.get(&(old_rid, new_rid)) {
                return Ok(eq);
            }
            let ov = if old_rid == 0 {
                None
            } else if let Some(v) = old_rec_cache.get(&old_rid) {
                v.clone()
            } else {
                let v = old_r
                    .get_record_by_id(old_rid, old_proj.as_ref())?
                    .and_then(|m| {
                        if old_proj.is_some() && m.is_empty() {
                            None
                        } else {
                            Some(Value::Map(m))
                        }
                    });
                if old_rec_cache.len() < 100_000 {
                    old_rec_cache.insert(old_rid, v.clone());
                }
                v
            };
            let nv = if new_rid == 0 {
                None
            } else if let Some(v) = new_rec_cache.get(&new_rid) {
                v.clone()
            } else {
                let v = new_r
                    .get_record_by_id(new_rid, new_proj.as_ref())?
                    .and_then(|m| {
                        if new_proj.is_some() && m.is_empty() {
                            None
                        } else {
                            Some(Value::Map(m))
                        }
                    });
                if new_rec_cache.len() < 100_000 {
                    new_rec_cache.insert(new_rid, v.clone());
                }
                v
            };
            let eq = match (&ov, &nv) {
                (None, None) => true,
                (Some(a), Some(b)) => a.bit_eq(b),
                _ => false,
            };
            eq_cache.insert((old_rid, new_rid), eq);
            Ok(eq)
        };

    // Sweep IPv4 transitions
    let old_v4 = old_r.ipv4_transitions()?;
    let new_v4 = new_r.ipv4_transitions()?;
    let v4_stats = sweep_diff_u32(&old_v4, &new_v4, max_samples, &mut records_equal)?;

    // Sweep IPv6 /64 transitions
    let old_v6 = old_r.ipv6_transitions()?;
    let new_v6 = new_r.ipv6_transitions()?;
    let v6_stats = sweep_diff_u64(&old_v6, &new_v6, max_samples, &mut records_equal)?;

    println!(
        "=== COI Diff Report ({:.2}s) ===",
        t0.elapsed().as_secs_f64()
    );
    println!(
        "  Old: {} ({}, {} unique records)",
        old_path.display(),
        format_bytes(old_r.header().file_size),
        old_r.header().record_count
    );
    println!(
        "  New: {} ({}, {} unique records)",
        new_path.display(),
        format_bytes(new_r.header().file_size),
        new_r.header().record_count
    );
    if let Some(f) = &fields {
        println!("  Projected fields: {f}");
    }

    let total_v4 = (u32::MAX as u128) + 1;
    println!("\nIPv4 Space (4,294,967,296 addresses):");
    println!(
        "  Added:     {:>14} ({:.4}%)",
        v4_stats.added,
        (v4_stats.added as f64 / total_v4 as f64) * 100.0
    );
    println!(
        "  Removed:   {:>14} ({:.4}%)",
        v4_stats.removed,
        (v4_stats.removed as f64 / total_v4 as f64) * 100.0
    );
    println!(
        "  Changed:   {:>14} ({:.4}%)",
        v4_stats.changed,
        (v4_stats.changed as f64 / total_v4 as f64) * 100.0
    );
    println!(
        "  Unchanged: {:>14} ({:.4}%)",
        v4_stats.unchanged,
        (v4_stats.unchanged as f64 / total_v4 as f64) * 100.0
    );

    if !old_v6.is_empty() || !new_v6.is_empty() {
        println!("\nIPv6 /64 Subnets:");
        println!("  Added:     {:>20} /64s", v6_stats.added);
        println!("  Removed:   {:>20} /64s", v6_stats.removed);
        println!("  Changed:   {:>20} /64s", v6_stats.changed);
        println!("  Unchanged: {:>20} /64s", v6_stats.unchanged);
    }

    let all_samples: Vec<&DiffSample> = v4_stats
        .samples
        .iter()
        .chain(v6_stats.samples.iter())
        .take(max_samples)
        .collect();
    if !all_samples.is_empty() {
        println!("\nSample Differences (showing {}):", all_samples.len());
        for s in all_samples {
            let old_json = if s.old_rid == 0 {
                serde_json::Value::Null
            } else {
                old_r
                    .get_record_by_id(s.old_rid, old_proj.as_ref())?
                    .map(|m| value_to_json(&Value::Map(m)))
                    .unwrap_or(serde_json::Value::Null)
            };
            let new_json = if s.new_rid == 0 {
                serde_json::Value::Null
            } else {
                new_r
                    .get_record_by_id(s.new_rid, new_proj.as_ref())?
                    .map(|m| value_to_json(&Value::Map(m)))
                    .unwrap_or(serde_json::Value::Null)
            };
            println!("  [{}] {}", s.kind, s.cidr);
            if s.old_rid != 0 {
                println!("    - old: {}", serde_json::to_string(&old_json)?);
            }
            if s.new_rid != 0 {
                println!("    + new: {}", serde_json::to_string(&new_json)?);
            }
        }
    }

    Ok(())
}

fn sweep_diff_u32(
    old_t: &[(u32, u64)],
    new_t: &[(u32, u64)],
    max_samples: usize,
    eq_fn: &mut impl FnMut(u64, u64) -> Result<bool, Box<dyn std::error::Error>>,
) -> Result<DiffStats, Box<dyn std::error::Error>> {
    let mut stats = DiffStats::default();
    let max_ip = (u32::MAX as u64) + 1;
    let mut pos = 0u64;
    let mut i = 0usize;
    let mut j = 0usize;
    let mut cur_old = 0u64;
    let mut cur_new = 0u64;

    while pos < max_ip {
        while i < old_t.len() && (old_t[i].0 as u64) <= pos {
            cur_old = old_t[i].1;
            i += 1;
        }
        while j < new_t.len() && (new_t[j].0 as u64) <= pos {
            cur_new = new_t[j].1;
            j += 1;
        }
        let next_old = if i < old_t.len() {
            old_t[i].0 as u64
        } else {
            max_ip
        };
        let next_new = if j < new_t.len() {
            new_t[j].0 as u64
        } else {
            max_ip
        };
        let next_pos = next_old.min(next_new);
        let count = (next_pos - pos) as u128;

        if eq_fn(cur_old, cur_new)? {
            stats.unchanged += count;
        } else {
            let kind = match (cur_old, cur_new) {
                (0, _) => {
                    stats.added += count;
                    "ADDED"
                }
                (_, 0) => {
                    stats.removed += count;
                    "REMOVED"
                }
                _ => {
                    stats.changed += count;
                    "CHANGED"
                }
            };
            if stats.samples.len() < max_samples {
                let cidrs = range_to_cidrs_v4(pos as u32, (next_pos - 1) as u32);
                let (net, plen) = cidrs[0];
                stats.samples.push(DiffSample {
                    kind,
                    cidr: format!("{}/{plen}", Ipv4Addr::from(net)),
                    old_rid: cur_old,
                    new_rid: cur_new,
                });
            }
        }
        pos = next_pos;
    }
    Ok(stats)
}

fn sweep_diff_u64(
    old_t: &[(u64, u64)],
    new_t: &[(u64, u64)],
    max_samples: usize,
    eq_fn: &mut impl FnMut(u64, u64) -> Result<bool, Box<dyn std::error::Error>>,
) -> Result<DiffStats, Box<dyn std::error::Error>> {
    let mut stats = DiffStats::default();
    let max_ip = (u64::MAX as u128) + 1;
    let mut pos = 0u128;
    let mut i = 0usize;
    let mut j = 0usize;
    let mut cur_old = 0u64;
    let mut cur_new = 0u64;

    while pos < max_ip {
        while i < old_t.len() && (old_t[i].0 as u128) <= pos {
            cur_old = old_t[i].1;
            i += 1;
        }
        while j < new_t.len() && (new_t[j].0 as u128) <= pos {
            cur_new = new_t[j].1;
            j += 1;
        }
        let next_old = if i < old_t.len() {
            old_t[i].0 as u128
        } else {
            max_ip
        };
        let next_new = if j < new_t.len() {
            new_t[j].0 as u128
        } else {
            max_ip
        };
        let next_pos = next_old.min(next_new);
        let count = next_pos - pos;

        if eq_fn(cur_old, cur_new)? {
            stats.unchanged += count;
        } else {
            let kind = match (cur_old, cur_new) {
                (0, _) => {
                    stats.added += count;
                    "ADDED"
                }
                (_, 0) => {
                    stats.removed += count;
                    "REMOVED"
                }
                _ => {
                    stats.changed += count;
                    "CHANGED"
                }
            };
            if stats.samples.len() < max_samples {
                let s128 = pos << 64;
                let e128 = ((next_pos - 1) << 64) | (u64::MAX as u128);
                let cidrs = range_to_cidrs_v6(s128, e128);
                let (net, plen) = cidrs[0];
                stats.samples.push(DiffSample {
                    kind,
                    cidr: format!("{}/{plen}", Ipv6Addr::from(net)),
                    old_rid: cur_old,
                    new_rid: cur_new,
                });
            }
        }
        pos = next_pos;
    }
    Ok(stats)
}