Skip to main content

coip_builder/
builder.rs

1//! High-level generic `CoipBuilder` and `.mmdb` -> `.coi` converter.
2
3use std::collections::{BTreeMap, HashMap};
4use std::io::Write;
5use std::net::{Ipv4Addr, Ipv6Addr};
6use std::path::Path;
7
8use coip_format::{
9    AliasRule, Codec, FORMAT_MAJOR, FORMAT_MINOR, FileFooter, FileHeader, HEADER_SIZE, Ipv6Aliases,
10    SECTION_ENTRY_SIZE, SectionEntry, SectionKind, Value, ZstdDicts, align8, crc32c, header_flags,
11    range_to_cidrs_v4, range_to_cidrs_v6,
12};
13
14use crate::column_writer::compress_with_codec;
15use crate::error::{BuilderError, Result};
16use crate::index_writer::{
17    build_host_ext, encode_ipv4_index, encode_ipv6_index, merge_v4_transitions,
18    merge_v6_transitions,
19};
20use crate::lpm::{resolve_lpm_v4, resolve_lpm_v6, resolve_lpm_v6_host};
21use crate::mmdb::{V4Interval, V6HostInterval, V6Interval, extract_mmdb};
22use crate::prune::{PruneConfig, apply_pruning};
23use crate::schema_infer::{ColumnarBuildConfig, RowOrderStrategy, infer_and_encode_records};
24
25/// Build options for creating `.coi` files.
26#[derive(Debug, Clone)]
27pub struct BuildOptions {
28    /// Compression profile codec (`Codec::Zstd` for Compact, `Codec::Lz4` for UltraFast, `Codec::None` for raw).
29    pub profile_codec: Codec,
30    /// Zstd compression level (1..=19, default 9; ignored for non-Zstd profiles).
31    pub zstd_level: i32,
32    /// Whether to automatically train `Section 3: ZstdDicts` for IP index blocks (Compact profile).
33    pub train_zstd_dicts: bool,
34    /// Granule block size for IPv4/IPv6 transition indexes (default 2048 for Compact, 512 for UltraFast).
35    pub index_block_size: u32,
36    /// L1 direct bucket prefix bits for IPv4 index (default 16).
37    pub ipv4_l1_bits: u8,
38    /// L1 direct bucket prefix bits for IPv6 index (default 0; sparse index is ~11 KB in L1 cache).
39    pub ipv6_l1_bits: u8,
40    /// RowGroup size for `RecordColumns` (default 4096 for Compact, 1024 for UltraFast).
41    pub row_group_size: u32,
42    /// RowGroup size for `StructDict` tables (default 2048 for Compact, 512 for UltraFast).
43    pub struct_dict_row_group_size: u32,
44    /// Block size for large `FlatDict` tables (> 8192 entries, default 4096).
45    pub dict_block_size: u32,
46    /// Row ordering strategy for unique records.
47    pub row_order: RowOrderStrategy,
48    /// Optional build-time field pruning (auto-deduplicates records & collapses IP transitions).
49    pub prune: Option<PruneConfig>,
50}
51
52impl BuildOptions {
53    /// Default **`Compact`** profile: Zstd blocks + trained Zstd dictionaries for maximum compression (~4.5–5.5×).
54    pub fn compact() -> Self {
55        Self {
56            profile_codec: Codec::Zstd,
57            zstd_level: 9,
58            train_zstd_dicts: true,
59            index_block_size: 2048,
60            ipv4_l1_bits: 16,
61            ipv6_l1_bits: 0,
62            row_group_size: 4096,
63            struct_dict_row_group_size: 2048,
64            dict_block_size: 4096,
65            row_order: RowOrderStrategy::GeoLocality,
66            prune: None,
67        }
68    }
69
70    /// **`UltraFast`** profile: pure-Rust LZ4 blocks + fine-grained 512/1024 chunks for microsecond cold lookups.
71    pub fn ultrafast() -> Self {
72        Self {
73            profile_codec: Codec::Lz4,
74            zstd_level: 1,
75            train_zstd_dicts: false,
76            index_block_size: 512,
77            ipv4_l1_bits: 16,
78            ipv6_l1_bits: 0,
79            row_group_size: 1024,
80            struct_dict_row_group_size: 512,
81            dict_block_size: 1024,
82            row_order: RowOrderStrategy::GeoLocality,
83            prune: None,
84        }
85    }
86}
87
88impl Default for BuildOptions {
89    fn default() -> Self {
90        Self::compact()
91    }
92}
93
94/// Statistics returned after building a `.coi` file.
95#[derive(Debug, Clone)]
96pub struct BuildStats {
97    pub total_bytes: u64,
98    pub record_count: u64,
99    pub v4_transitions: usize,
100    pub v6_transitions: usize,
101    pub v6_host_ext_entries: usize,
102    pub ipv6_alias_count: usize,
103    pub dict_count: usize,
104    pub section_sizes: Vec<(SectionKind, u64)>,
105}
106
107/// Generic builder for arbitrary IPv4/IPv6 columnar `.coi` databases.
108pub struct CoipBuilder {
109    options: BuildOptions,
110    build_epoch: u64,
111    metadata: serde_json::Map<String, serde_json::Value>,
112    ipv6_aliases: Vec<AliasRule>,
113    v4_intervals: Vec<V4Interval>,
114    v6_intervals: Vec<V6Interval>,
115    v6_host_ext: Vec<V6HostInterval>,
116    record_dedup: HashMap<BTreeMap<String, Value>, u32>,
117    unique_records: Vec<BTreeMap<String, Value>>,
118}
119
120impl CoipBuilder {
121    pub fn new(options: BuildOptions) -> Self {
122        let mut metadata = serde_json::Map::new();
123        metadata.insert(
124            "generator".into(),
125            serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
126        );
127        Self {
128            options,
129            build_epoch: 0,
130            metadata,
131            ipv6_aliases: Vec::new(),
132            v4_intervals: Vec::new(),
133            v6_intervals: Vec::new(),
134            v6_host_ext: Vec::new(),
135            record_dedup: HashMap::new(),
136            unique_records: Vec::new(),
137        }
138    }
139
140    pub fn set_build_epoch(&mut self, epoch: u64) -> &mut Self {
141        self.build_epoch = epoch;
142        self.metadata
143            .insert("build_epoch".into(), serde_json::Value::from(epoch));
144        self
145    }
146
147    pub fn set_metadata_field(
148        &mut self,
149        key: impl Into<String>,
150        val: serde_json::Value,
151    ) -> &mut Self {
152        self.metadata.insert(key.into(), val);
153        self
154    }
155
156    pub fn add_ipv6_alias(&mut self, rule: AliasRule) -> &mut Self {
157        self.ipv6_aliases.push(rule);
158        self
159    }
160
161    fn intern_record(&mut self, record: BTreeMap<String, Value>) -> u32 {
162        if let Some(&id) = self.record_dedup.get(&record) {
163            return id;
164        }
165        let id = (self.unique_records.len() + 1) as u32;
166        self.record_dedup.insert(record.clone(), id);
167        self.unique_records.push(record);
168        id
169    }
170
171    /// Insert an IPv4 CIDR block (`addr/prefix_len`) mapped to `record`.
172    /// Overlapping CIDRs are automatically resolved via Longest-Prefix-Match (last-insert-wins on ties).
173    pub fn insert_ipv4_cidr(
174        &mut self,
175        addr: Ipv4Addr,
176        prefix_len: u8,
177        record: BTreeMap<String, Value>,
178    ) -> Result<&mut Self> {
179        let rid = self.intern_record(record);
180        self.push_ipv4_cidr_rid(addr, prefix_len, rid)
181    }
182
183    /// Punch an explicit NotFound hole (`record_id = 0`) at an IPv4 CIDR (overrides broader prefixes via LPM).
184    pub fn delete_ipv4_cidr(&mut self, addr: Ipv4Addr, prefix_len: u8) -> Result<&mut Self> {
185        self.push_ipv4_cidr_rid(addr, prefix_len, 0)
186    }
187
188    fn push_ipv4_cidr_rid(
189        &mut self,
190        addr: Ipv4Addr,
191        prefix_len: u8,
192        rid: u32,
193    ) -> Result<&mut Self> {
194        if prefix_len > 32 {
195            return Err(BuilderError::InvalidInput(format!(
196                "invalid IPv4 prefix length {prefix_len}"
197            )));
198        }
199        let ip = u32::from(addr);
200        let (start, end) = if prefix_len == 0 {
201            (0u32, u32::MAX)
202        } else if prefix_len == 32 {
203            (ip, ip)
204        } else {
205            let mask = !((1u32 << (32 - prefix_len)) - 1);
206            let s = ip & mask;
207            let e = s | !mask;
208            (s, e)
209        };
210        self.v4_intervals.push(V4Interval {
211            start,
212            end,
213            record_idx: rid,
214        });
215        Ok(self)
216    }
217
218    /// Insert an inclusive IPv4 address range `[start..=end]` (auto-decomposed into aligned CIDRs).
219    pub fn insert_ipv4_range(
220        &mut self,
221        start: Ipv4Addr,
222        end: Ipv4Addr,
223        record: BTreeMap<String, Value>,
224    ) -> Result<&mut Self> {
225        let s = u32::from(start);
226        let e = u32::from(end);
227        if s > e {
228            return Err(BuilderError::InvalidInput(format!(
229                "IPv4 start {start} > end {end}"
230            )));
231        }
232        let rid = self.intern_record(record);
233        for (net, plen) in range_to_cidrs_v4(s, e) {
234            self.push_ipv4_cidr_rid(Ipv4Addr::from(net), plen, rid)?;
235        }
236        Ok(self)
237    }
238
239    /// Insert an IPv6 CIDR block (`addr/prefix_len`) mapped to `record`.
240    /// Overlapping CIDRs are automatically resolved via Longest-Prefix-Match (last-insert-wins on ties).
241    pub fn insert_ipv6_cidr(
242        &mut self,
243        addr: Ipv6Addr,
244        prefix_len: u8,
245        record: BTreeMap<String, Value>,
246    ) -> Result<&mut Self> {
247        let rid = self.intern_record(record);
248        self.push_ipv6_cidr_rid(addr, prefix_len, rid)
249    }
250
251    /// Punch an explicit NotFound hole (`record_id = 0`) at an IPv6 CIDR (including `> /64` holes inside a broader `<= /64` prefix).
252    pub fn delete_ipv6_cidr(&mut self, addr: Ipv6Addr, prefix_len: u8) -> Result<&mut Self> {
253        self.push_ipv6_cidr_rid(addr, prefix_len, 0)
254    }
255
256    fn push_ipv6_cidr_rid(
257        &mut self,
258        addr: Ipv6Addr,
259        prefix_len: u8,
260        rid: u32,
261    ) -> Result<&mut Self> {
262        if prefix_len > 128 {
263            return Err(BuilderError::InvalidInput(format!(
264                "invalid IPv6 prefix length {prefix_len}"
265            )));
266        }
267        let ip = u128::from(addr);
268        if prefix_len <= 64 {
269            let hi = (ip >> 64) as u64;
270            let (start, end) = if prefix_len == 0 {
271                (0u64, u64::MAX)
272            } else if prefix_len == 64 {
273                (hi, hi)
274            } else {
275                let mask = !((1u64 << (64 - prefix_len)) - 1);
276                let s = hi & mask;
277                let e = s | !mask;
278                (s, e)
279            };
280            self.v6_intervals.push(V6Interval {
281                start,
282                end,
283                record_idx: rid,
284            });
285        } else {
286            let (start, end) = if prefix_len == 128 {
287                (ip, ip)
288            } else {
289                let mask = !((1u128 << (128 - prefix_len)) - 1);
290                let s = ip & mask;
291                let e = s | !mask;
292                (s, e)
293            };
294            self.v6_host_ext.push(V6HostInterval {
295                start,
296                end,
297                record_idx: rid,
298            });
299        }
300        Ok(self)
301    }
302
303    /// Insert an inclusive IPv6 address range `[start..=end]` (auto-decomposed into aligned CIDRs).
304    pub fn insert_ipv6_range(
305        &mut self,
306        start: Ipv6Addr,
307        end: Ipv6Addr,
308        record: BTreeMap<String, Value>,
309    ) -> Result<&mut Self> {
310        let s = u128::from(start);
311        let e = u128::from(end);
312        if s > e {
313            return Err(BuilderError::InvalidInput(format!(
314                "IPv6 start {start} > end {end}"
315            )));
316        }
317        let rid = self.intern_record(record);
318        for (net, plen) in range_to_cidrs_v6(s, e) {
319            self.push_ipv6_cidr_rid(Ipv6Addr::from(net), plen, rid)?;
320        }
321        Ok(self)
322    }
323
324    /// Convenience helper accepting a CIDR or single IP string (e.g. `"1.1.1.0/24"`, `"2001:db8::1"`).
325    pub fn insert_cidr_str(
326        &mut self,
327        cidr: &str,
328        record: BTreeMap<String, Value>,
329    ) -> Result<&mut Self> {
330        let (addr, plen) = crate::import::parse_cidr_or_ip(cidr)?;
331        match addr {
332            std::net::IpAddr::V4(v4) => self.insert_ipv4_cidr(v4, plen, record),
333            std::net::IpAddr::V6(v6) => self.insert_ipv6_cidr(v6, plen, record),
334        }
335    }
336
337    /// Build the complete `.coi` binary image in memory.
338    pub fn build(self) -> Result<(Vec<u8>, BuildStats)> {
339        assemble_coi(
340            &self.options,
341            self.build_epoch,
342            serde_json::Value::Object(self.metadata),
343            self.ipv6_aliases,
344            self.v4_intervals,
345            self.v6_intervals,
346            self.v6_host_ext,
347            self.unique_records,
348        )
349    }
350}
351
352/// Low-level entry point to assemble a `.coi` file from pre-extracted intervals and unique records
353/// (used by `.coi -> .coi` repacking, profile switching, and build-time pruning).
354#[allow(clippy::too_many_arguments)]
355pub fn build_from_parts(
356    options: &BuildOptions,
357    build_epoch: u64,
358    metadata_json: serde_json::Value,
359    ipv6_aliases: Vec<AliasRule>,
360    v4_intervals: Vec<V4Interval>,
361    v6_intervals: Vec<V6Interval>,
362    v6_host_ext: Vec<V6HostInterval>,
363    unique_records: Vec<BTreeMap<String, Value>>,
364) -> Result<(Vec<u8>, BuildStats)> {
365    assemble_coi(
366        options,
367        build_epoch,
368        metadata_json,
369        ipv6_aliases,
370        v4_intervals,
371        v6_intervals,
372        v6_host_ext,
373        unique_records,
374    )
375}
376
377/// Convert a `.mmdb` file on disk directly into a `.coi` file on disk.
378pub fn convert_mmdb_file(
379    src_mmdb: impl AsRef<Path>,
380    dst_coi: impl AsRef<Path>,
381    options: &BuildOptions,
382) -> Result<BuildStats> {
383    let mmdb_bytes = std::fs::read(src_mmdb)?;
384    let (coi_bytes, stats) = build_from_mmdb_bytes(&mmdb_bytes, options)?;
385    let mut f = std::fs::File::create(dst_coi)?;
386    f.write_all(&coi_bytes)?;
387    f.flush()?;
388    Ok(stats)
389}
390
391/// Convert an in-memory `.mmdb` byte slice into `.coi` bytes.
392pub fn build_from_mmdb_bytes(
393    mmdb_bytes: &[u8],
394    options: &BuildOptions,
395) -> Result<(Vec<u8>, BuildStats)> {
396    let extracted = extract_mmdb(mmdb_bytes)?;
397
398    let mut meta = serde_json::Map::new();
399    meta.insert(
400        "database_type".into(),
401        serde_json::Value::String(extracted.metadata.database_type.clone()),
402    );
403    if let Some(en_desc) = extracted.metadata.description.get("en") {
404        meta.insert(
405            "description".into(),
406            serde_json::Value::String(en_desc.clone()),
407        );
408    }
409    meta.insert(
410        "build_epoch".into(),
411        serde_json::Value::from(extracted.metadata.build_epoch),
412    );
413    meta.insert(
414        "ip_version".into(),
415        serde_json::Value::from(extracted.metadata.ip_version),
416    );
417    meta.insert(
418        "source_format".into(),
419        serde_json::Value::String(format!(
420            "mmdb-{}.{}",
421            extracted.metadata.binary_format_major_version,
422            extracted.metadata.binary_format_minor_version
423        )),
424    );
425    meta.insert(
426        "generator".into(),
427        serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
428    );
429
430    assemble_coi(
431        options,
432        extracted.metadata.build_epoch,
433        serde_json::Value::Object(meta),
434        extracted.ipv6_aliases,
435        extracted.v4_intervals,
436        extracted.v6_intervals,
437        extracted.v6_host_ext,
438        extracted.unique_records,
439    )
440}
441
442#[allow(clippy::too_many_arguments)]
443fn assemble_coi(
444    options: &BuildOptions,
445    build_epoch: u64,
446    metadata_json: serde_json::Value,
447    ipv6_aliases: Vec<AliasRule>,
448    v4_intervals: Vec<V4Interval>,
449    v6_intervals: Vec<V6Interval>,
450    v6_host_ext: Vec<V6HostInterval>,
451    mut unique_records: Vec<BTreeMap<String, Value>>,
452) -> Result<(Vec<u8>, BuildStats)> {
453    let codec = options.profile_codec;
454    let zstd_level = options.zstd_level;
455
456    // 0a. Resolve any overlapping CIDRs or explicit delete holes via exact LPM sweep.
457    let mut v4_intervals = resolve_lpm_v4(v4_intervals);
458    let mut v6_intervals = resolve_lpm_v6(v6_intervals);
459    let mut v6_host_ext = resolve_lpm_v6_host(v6_host_ext);
460
461    // 0b. Apply optional build-time field pruning & re-deduplicate records.
462    if let Some(ref prune) = options.prune {
463        unique_records = apply_pruning(
464            prune,
465            unique_records,
466            &mut v4_intervals,
467            &mut v6_intervals,
468            &mut v6_host_ext,
469        )?;
470    }
471
472    // 1. Compute first-appearance IP position for each unique record (for IP-locality ordering).
473    let mut ip_first_pos = vec![u64::MAX; unique_records.len()];
474    let mut seq = 0u64;
475    for iv in &v4_intervals {
476        let idx = (iv.record_idx as usize).saturating_sub(1);
477        if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
478            ip_first_pos[idx] = seq;
479        }
480        seq += 1;
481    }
482    for iv in &v6_intervals {
483        let idx = (iv.record_idx as usize).saturating_sub(1);
484        if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
485            ip_first_pos[idx] = seq;
486        }
487        seq += 1;
488    }
489    for iv in &v6_host_ext {
490        let idx = (iv.record_idx as usize).saturating_sub(1);
491        if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
492            ip_first_pos[idx] = seq;
493        }
494        seq += 1;
495    }
496
497    // 2. Infer schema, normalize dicts, compute row ordering, encode RecordColumns & DictTables.
498    let col_cfg = ColumnarBuildConfig {
499        row_group_size: options.row_group_size,
500        struct_dict_row_group_size: options.struct_dict_row_group_size,
501        dict_block_size: options.dict_block_size,
502        codec,
503        zstd_level,
504        row_order: options.row_order,
505    };
506    let built_cols = infer_and_encode_records(&unique_records, &ip_first_pos, &col_cfg)?;
507
508    // 3. Remap all IP intervals to ordered record_ids!
509    for iv in &mut v4_intervals {
510        iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
511    }
512    for iv in &mut v6_intervals {
513        iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
514    }
515    for iv in &mut v6_host_ext {
516        iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
517    }
518
519    // 4. Merge transitions & encode IP index sections (with optional trained ZstdDicts)
520    let v4_transitions = merge_v4_transitions(&v4_intervals);
521    let v6_transitions = merge_v6_transitions(&v6_intervals);
522    let host_ext = build_host_ext(&v6_host_ext);
523
524    let has_ipv4 = !v4_transitions.is_empty();
525    let has_ipv6 =
526        !v6_transitions.is_empty() || !ipv6_aliases.is_empty() || !host_ext.entries.is_empty();
527    let has_host_ext = !host_ext.entries.is_empty();
528
529    let mut trained_zstd_dicts: Vec<Vec<u8>> = Vec::new();
530    let v4_blob = if has_ipv4 {
531        Some(
532            encode_ipv4_index(
533                &v4_transitions,
534                options.index_block_size,
535                options.ipv4_l1_bits,
536                codec,
537                zstd_level,
538                options.train_zstd_dicts,
539                &mut trained_zstd_dicts,
540            )?
541            .bytes,
542        )
543    } else {
544        None
545    };
546
547    let v6_blob = if !v6_transitions.is_empty() {
548        Some(
549            encode_ipv6_index(
550                &v6_transitions,
551                options.index_block_size,
552                options.ipv6_l1_bits,
553                codec,
554                zstd_level,
555                options.train_zstd_dicts,
556                &mut trained_zstd_dicts,
557            )?
558            .bytes,
559        )
560    } else {
561        None
562    };
563
564    let has_zstd_dicts = !trained_zstd_dicts.is_empty();
565
566    struct PendingSection {
567        kind: SectionKind,
568        flags: u16,
569        bytes: Vec<u8>,
570        uncompressed_len: u64,
571    }
572    let mut sections: Vec<PendingSection> = Vec::new();
573
574    let push_small_section =
575        |sections: &mut Vec<PendingSection>, kind: SectionKind, raw: Vec<u8>| -> Result<()> {
576            let uncompressed_len = raw.len() as u64;
577            if codec != Codec::None && raw.len() > 32 {
578                let comp = compress_with_codec(codec, &raw, zstd_level, None)?;
579                if comp.len() < raw.len() {
580                    sections.push(PendingSection {
581                        kind,
582                        flags: codec as u16,
583                        bytes: comp,
584                        uncompressed_len,
585                    });
586                    return Ok(());
587                }
588            }
589            sections.push(PendingSection {
590                kind,
591                flags: Codec::None as u16,
592                bytes: raw,
593                uncompressed_len,
594            });
595            Ok(())
596        };
597
598    // Section 1: Metadata
599    let meta_raw = serde_json::to_vec(&metadata_json)?;
600    push_small_section(&mut sections, SectionKind::Metadata, meta_raw)?;
601
602    // Section 2: Schema
603    let schema_raw = built_cols.schema.encode();
604    push_small_section(&mut sections, SectionKind::Schema, schema_raw)?;
605
606    // Section 3: ZstdDicts (optional)
607    if has_zstd_dicts {
608        let zd_raw = ZstdDicts {
609            dicts: trained_zstd_dicts,
610        }
611        .encode();
612        push_small_section(&mut sections, SectionKind::ZstdDicts, zd_raw)?;
613    }
614
615    // Section 4: Ipv6Aliases (optional)
616    if !ipv6_aliases.is_empty() {
617        let alias_raw = Ipv6Aliases {
618            rules: ipv6_aliases.clone(),
619        }
620        .encode();
621        push_small_section(&mut sections, SectionKind::Ipv6Aliases, alias_raw)?;
622    }
623
624    // Section 5: Ipv4Index (optional)
625    if let Some(blob) = v4_blob {
626        let len = blob.len() as u64;
627        sections.push(PendingSection {
628            kind: SectionKind::Ipv4Index,
629            flags: 0,
630            bytes: blob,
631            uncompressed_len: len,
632        });
633    }
634
635    // Section 6: Ipv6Index (optional)
636    if let Some(blob) = v6_blob {
637        let len = blob.len() as u64;
638        sections.push(PendingSection {
639            kind: SectionKind::Ipv6Index,
640            flags: 0,
641            bytes: blob,
642            uncompressed_len: len,
643        });
644    }
645
646    // Section 7: Ipv6HostExt (optional)
647    if has_host_ext {
648        let he_raw = host_ext.encode();
649        push_small_section(&mut sections, SectionKind::Ipv6HostExt, he_raw)?;
650    }
651
652    // Section 8: RecordColumns
653    {
654        let len = built_cols.record_columns_blob.len() as u64;
655        sections.push(PendingSection {
656            kind: SectionKind::RecordColumns,
657            flags: 0,
658            bytes: built_cols.record_columns_blob,
659            uncompressed_len: len,
660        });
661    }
662
663    // Section 9: DictTables (optional)
664    if !built_cols.dict_blobs.is_empty() {
665        let dict_section = encode_dict_tables_section(&built_cols.dict_blobs);
666        let len = dict_section.len() as u64;
667        sections.push(PendingSection {
668            kind: SectionKind::DictTables,
669            flags: 0,
670            bytes: dict_section,
671            uncompressed_len: len,
672        });
673    }
674
675    // 5. Layout Header + Section Directory + 8-byte aligned Sections + 8-byte aligned Footer
676    let section_count = sections.len();
677    let section_dir_offset = HEADER_SIZE as u64;
678    let dir_bytes_len = (section_count * SECTION_ENTRY_SIZE) as u64;
679
680    let mut cur_offset = align8(section_dir_offset + dir_bytes_len);
681    let mut dir_entries = Vec::with_capacity(section_count);
682    let mut section_sizes = Vec::with_capacity(section_count);
683
684    for sec in &sections {
685        let offset = align8(cur_offset);
686        let length = sec.bytes.len() as u64;
687        let checksum = crc32c(&sec.bytes);
688        dir_entries.push(SectionEntry {
689            kind: sec.kind,
690            flags: sec.flags,
691            crc32c: checksum,
692            offset,
693            length,
694            uncompressed_length: sec.uncompressed_len,
695        });
696        section_sizes.push((sec.kind, length));
697        cur_offset = offset + length;
698    }
699
700    let footer_offset = align8(cur_offset);
701    let file_size = footer_offset + (coip_format::FOOTER_SIZE as u64);
702
703    let mut dir_buf = Vec::with_capacity(dir_bytes_len as usize);
704    for entry in &dir_entries {
705        entry.encode(&mut dir_buf);
706    }
707    let dir_crc = crc32c(&dir_buf);
708
709    let mut flags = 0u32;
710    if has_ipv4 {
711        flags |= header_flags::HAS_IPV4;
712    }
713    if has_ipv6 {
714        flags |= header_flags::HAS_IPV6;
715    }
716    if has_host_ext {
717        flags |= header_flags::HAS_IPV6_HOST_EXT;
718    }
719    if has_zstd_dicts {
720        flags |= header_flags::HAS_ZSTD_DICTS;
721    }
722
723    let header = FileHeader {
724        format_major: FORMAT_MAJOR,
725        format_minor: FORMAT_MINOR,
726        flags,
727        profile_codec: options.profile_codec,
728        section_count: section_count as u8,
729        header_ext_len: 0,
730        build_epoch,
731        record_count: unique_records.len() as u64,
732        section_dir_offset,
733        file_size,
734        header_crc32c: 0,
735    };
736    let footer = FileFooter {
737        dir_crc32c: dir_crc,
738        section_dir_offset,
739    };
740
741    let mut out = Vec::with_capacity(file_size as usize);
742    out.extend_from_slice(&header.encode());
743    out.extend_from_slice(&dir_buf);
744    for (sec, entry) in sections.iter().zip(dir_entries.iter()) {
745        out.resize(entry.offset as usize, 0);
746        out.extend_from_slice(&sec.bytes);
747    }
748    out.resize(footer_offset as usize, 0);
749    out.extend_from_slice(&footer.encode());
750    debug_assert_eq!(out.len() as u64, file_size);
751
752    let stats = BuildStats {
753        total_bytes: file_size,
754        record_count: unique_records.len() as u64,
755        v4_transitions: v4_transitions.len(),
756        v6_transitions: v6_transitions.len(),
757        v6_host_ext_entries: host_ext.entries.len(),
758        ipv6_alias_count: ipv6_aliases.len(),
759        dict_count: built_cols.schema.dicts.len(),
760        section_sizes,
761    };
762
763    Ok((out, stats))
764}
765
766fn encode_dict_tables_section(dict_blobs: &[Vec<u8>]) -> Vec<u8> {
767    let count = dict_blobs.len();
768    let mut cur_off = 0u64;
769    let mut entries: Vec<(u64, u64)> = Vec::with_capacity(count);
770    for blob in dict_blobs {
771        let aligned = align8(cur_off);
772        entries.push((aligned, blob.len() as u64));
773        cur_off = aligned + blob.len() as u64;
774    }
775
776    let header_len = 8 + count * 16;
777    let mut out = Vec::with_capacity(header_len + cur_off as usize);
778    out.extend_from_slice(&(count as u16).to_le_bytes());
779    out.extend_from_slice(&[0u8; 6]);
780    for &(off, len) in &entries {
781        out.extend_from_slice(&off.to_le_bytes());
782        out.extend_from_slice(&len.to_le_bytes());
783    }
784    for (blob, &(off, _)) in dict_blobs.iter().zip(entries.iter()) {
785        out.resize(header_len + off as usize, 0);
786        out.extend_from_slice(blob);
787    }
788    out
789}