1use 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#[derive(Debug, Clone)]
27pub struct BuildOptions {
28 pub profile_codec: Codec,
30 pub zstd_level: i32,
32 pub train_zstd_dicts: bool,
34 pub index_block_size: u32,
36 pub ipv4_l1_bits: u8,
38 pub ipv6_l1_bits: u8,
40 pub row_group_size: u32,
42 pub struct_dict_row_group_size: u32,
44 pub dict_block_size: u32,
46 pub row_order: RowOrderStrategy,
48 pub prune: Option<PruneConfig>,
50}
51
52impl BuildOptions {
53 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 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#[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
107pub 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 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 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 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 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 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 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 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 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#[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
377pub 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
391pub 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 meta.insert(
404 "description".into(),
405 serde_json::to_value(&extracted.metadata.description)?,
406 );
407 meta.insert(
408 "languages".into(),
409 serde_json::to_value(&extracted.metadata.languages)?,
410 );
411 meta.insert(
412 "build_epoch".into(),
413 serde_json::Value::from(extracted.metadata.build_epoch),
414 );
415 meta.insert(
416 "ip_version".into(),
417 serde_json::Value::from(extracted.metadata.ip_version),
418 );
419 meta.insert(
420 "source_format".into(),
421 serde_json::Value::String(format!(
422 "mmdb-{}.{}",
423 extracted.metadata.binary_format_major_version,
424 extracted.metadata.binary_format_minor_version
425 )),
426 );
427 meta.insert(
428 "generator".into(),
429 serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
430 );
431
432 assemble_coi(
433 options,
434 extracted.metadata.build_epoch,
435 serde_json::Value::Object(meta),
436 extracted.ipv6_aliases,
437 extracted.v4_intervals,
438 extracted.v6_intervals,
439 extracted.v6_host_ext,
440 extracted.unique_records,
441 )
442}
443
444#[allow(clippy::too_many_arguments)]
445fn assemble_coi(
446 options: &BuildOptions,
447 build_epoch: u64,
448 mut metadata_json: serde_json::Value,
449 ipv6_aliases: Vec<AliasRule>,
450 v4_intervals: Vec<V4Interval>,
451 v6_intervals: Vec<V6Interval>,
452 v6_host_ext: Vec<V6HostInterval>,
453 mut unique_records: Vec<BTreeMap<String, Value>>,
454) -> Result<(Vec<u8>, BuildStats)> {
455 let codec = options.profile_codec;
456 let zstd_level = options.zstd_level;
457
458 let mut v4_intervals = resolve_lpm_v4(v4_intervals);
460 let mut v6_intervals = resolve_lpm_v6(v6_intervals);
461 let mut v6_host_ext = resolve_lpm_v6_host(v6_host_ext);
462
463 if let Some(ref prune) = options.prune {
465 unique_records = apply_pruning(
466 prune,
467 unique_records,
468 &mut v4_intervals,
469 &mut v6_intervals,
470 &mut v6_host_ext,
471 &mut metadata_json,
472 )?;
473 }
474
475 let mut ip_first_pos = vec![u64::MAX; unique_records.len()];
477 let mut seq = 0u64;
478 for iv in &v4_intervals {
479 let idx = (iv.record_idx as usize).saturating_sub(1);
480 if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
481 ip_first_pos[idx] = seq;
482 }
483 seq += 1;
484 }
485 for iv in &v6_intervals {
486 let idx = (iv.record_idx as usize).saturating_sub(1);
487 if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
488 ip_first_pos[idx] = seq;
489 }
490 seq += 1;
491 }
492 for iv in &v6_host_ext {
493 let idx = (iv.record_idx as usize).saturating_sub(1);
494 if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
495 ip_first_pos[idx] = seq;
496 }
497 seq += 1;
498 }
499
500 let col_cfg = ColumnarBuildConfig {
502 row_group_size: options.row_group_size,
503 struct_dict_row_group_size: options.struct_dict_row_group_size,
504 dict_block_size: options.dict_block_size,
505 codec,
506 zstd_level,
507 row_order: options.row_order,
508 };
509 let built_cols = infer_and_encode_records(&unique_records, &ip_first_pos, &col_cfg)?;
510
511 for iv in &mut v4_intervals {
513 iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
514 }
515 for iv in &mut v6_intervals {
516 iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
517 }
518 for iv in &mut v6_host_ext {
519 iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
520 }
521
522 let v4_transitions = merge_v4_transitions(&v4_intervals);
524 let v6_transitions = merge_v6_transitions(&v6_intervals);
525 let host_ext = build_host_ext(&v6_host_ext);
526
527 let has_ipv4 = !v4_transitions.is_empty();
528 let has_ipv6 =
529 !v6_transitions.is_empty() || !ipv6_aliases.is_empty() || !host_ext.entries.is_empty();
530 let has_host_ext = !host_ext.entries.is_empty();
531
532 let mut trained_zstd_dicts: Vec<Vec<u8>> = Vec::new();
533 let v4_blob = if has_ipv4 {
534 Some(
535 encode_ipv4_index(
536 &v4_transitions,
537 options.index_block_size,
538 options.ipv4_l1_bits,
539 codec,
540 zstd_level,
541 options.train_zstd_dicts,
542 &mut trained_zstd_dicts,
543 )?
544 .bytes,
545 )
546 } else {
547 None
548 };
549
550 let v6_blob = if !v6_transitions.is_empty() {
551 Some(
552 encode_ipv6_index(
553 &v6_transitions,
554 options.index_block_size,
555 options.ipv6_l1_bits,
556 codec,
557 zstd_level,
558 options.train_zstd_dicts,
559 &mut trained_zstd_dicts,
560 )?
561 .bytes,
562 )
563 } else {
564 None
565 };
566
567 let has_zstd_dicts = !trained_zstd_dicts.is_empty();
568
569 struct PendingSection {
570 kind: SectionKind,
571 flags: u16,
572 bytes: Vec<u8>,
573 uncompressed_len: u64,
574 }
575 let mut sections: Vec<PendingSection> = Vec::new();
576
577 let push_small_section =
578 |sections: &mut Vec<PendingSection>, kind: SectionKind, raw: Vec<u8>| -> Result<()> {
579 let uncompressed_len = raw.len() as u64;
580 if codec != Codec::None && raw.len() > 32 {
581 let comp = compress_with_codec(codec, &raw, zstd_level, None)?;
582 if comp.len() < raw.len() {
583 sections.push(PendingSection {
584 kind,
585 flags: codec as u16,
586 bytes: comp,
587 uncompressed_len,
588 });
589 return Ok(());
590 }
591 }
592 sections.push(PendingSection {
593 kind,
594 flags: Codec::None as u16,
595 bytes: raw,
596 uncompressed_len,
597 });
598 Ok(())
599 };
600
601 let meta_raw = serde_json::to_vec(&metadata_json)?;
603 push_small_section(&mut sections, SectionKind::Metadata, meta_raw)?;
604
605 let schema_raw = built_cols.schema.encode();
607 push_small_section(&mut sections, SectionKind::Schema, schema_raw)?;
608
609 if has_zstd_dicts {
611 let zd_raw = ZstdDicts {
612 dicts: trained_zstd_dicts,
613 }
614 .encode();
615 push_small_section(&mut sections, SectionKind::ZstdDicts, zd_raw)?;
616 }
617
618 if !ipv6_aliases.is_empty() {
620 let alias_raw = Ipv6Aliases {
621 rules: ipv6_aliases.clone(),
622 }
623 .encode();
624 push_small_section(&mut sections, SectionKind::Ipv6Aliases, alias_raw)?;
625 }
626
627 if let Some(blob) = v4_blob {
629 let len = blob.len() as u64;
630 sections.push(PendingSection {
631 kind: SectionKind::Ipv4Index,
632 flags: 0,
633 bytes: blob,
634 uncompressed_len: len,
635 });
636 }
637
638 if let Some(blob) = v6_blob {
640 let len = blob.len() as u64;
641 sections.push(PendingSection {
642 kind: SectionKind::Ipv6Index,
643 flags: 0,
644 bytes: blob,
645 uncompressed_len: len,
646 });
647 }
648
649 if has_host_ext {
651 let he_raw = host_ext.encode();
652 push_small_section(&mut sections, SectionKind::Ipv6HostExt, he_raw)?;
653 }
654
655 {
657 let len = built_cols.record_columns_blob.len() as u64;
658 sections.push(PendingSection {
659 kind: SectionKind::RecordColumns,
660 flags: 0,
661 bytes: built_cols.record_columns_blob,
662 uncompressed_len: len,
663 });
664 }
665
666 if !built_cols.dict_blobs.is_empty() {
668 let dict_section = encode_dict_tables_section(&built_cols.dict_blobs);
669 let len = dict_section.len() as u64;
670 sections.push(PendingSection {
671 kind: SectionKind::DictTables,
672 flags: 0,
673 bytes: dict_section,
674 uncompressed_len: len,
675 });
676 }
677
678 let section_count = sections.len();
680 let section_dir_offset = HEADER_SIZE as u64;
681 let dir_bytes_len = (section_count * SECTION_ENTRY_SIZE) as u64;
682
683 let mut cur_offset = align8(section_dir_offset + dir_bytes_len);
684 let mut dir_entries = Vec::with_capacity(section_count);
685 let mut section_sizes = Vec::with_capacity(section_count);
686
687 for sec in §ions {
688 let offset = align8(cur_offset);
689 let length = sec.bytes.len() as u64;
690 let checksum = crc32c(&sec.bytes);
691 dir_entries.push(SectionEntry {
692 kind: sec.kind,
693 flags: sec.flags,
694 crc32c: checksum,
695 offset,
696 length,
697 uncompressed_length: sec.uncompressed_len,
698 });
699 section_sizes.push((sec.kind, length));
700 cur_offset = offset + length;
701 }
702
703 let footer_offset = align8(cur_offset);
704 let file_size = footer_offset + (coip_format::FOOTER_SIZE as u64);
705
706 let mut dir_buf = Vec::with_capacity(dir_bytes_len as usize);
707 for entry in &dir_entries {
708 entry.encode(&mut dir_buf);
709 }
710 let dir_crc = crc32c(&dir_buf);
711
712 let mut flags = 0u32;
713 if has_ipv4 {
714 flags |= header_flags::HAS_IPV4;
715 }
716 if has_ipv6 {
717 flags |= header_flags::HAS_IPV6;
718 }
719 if has_host_ext {
720 flags |= header_flags::HAS_IPV6_HOST_EXT;
721 }
722 if has_zstd_dicts {
723 flags |= header_flags::HAS_ZSTD_DICTS;
724 }
725
726 let header = FileHeader {
727 format_major: FORMAT_MAJOR,
728 format_minor: FORMAT_MINOR,
729 flags,
730 profile_codec: options.profile_codec,
731 section_count: section_count as u8,
732 header_ext_len: 0,
733 build_epoch,
734 record_count: unique_records.len() as u64,
735 section_dir_offset,
736 file_size,
737 header_crc32c: 0,
738 };
739 let footer = FileFooter {
740 dir_crc32c: dir_crc,
741 section_dir_offset,
742 };
743
744 let mut out = Vec::with_capacity(file_size as usize);
745 out.extend_from_slice(&header.encode());
746 out.extend_from_slice(&dir_buf);
747 for (sec, entry) in sections.iter().zip(dir_entries.iter()) {
748 out.resize(entry.offset as usize, 0);
749 out.extend_from_slice(&sec.bytes);
750 }
751 out.resize(footer_offset as usize, 0);
752 out.extend_from_slice(&footer.encode());
753 debug_assert_eq!(out.len() as u64, file_size);
754
755 let stats = BuildStats {
756 total_bytes: file_size,
757 record_count: unique_records.len() as u64,
758 v4_transitions: v4_transitions.len(),
759 v6_transitions: v6_transitions.len(),
760 v6_host_ext_entries: host_ext.entries.len(),
761 ipv6_alias_count: ipv6_aliases.len(),
762 dict_count: built_cols.schema.dicts.len(),
763 section_sizes,
764 };
765
766 Ok((out, stats))
767}
768
769fn encode_dict_tables_section(dict_blobs: &[Vec<u8>]) -> Vec<u8> {
770 let count = dict_blobs.len();
771 let mut cur_off = 0u64;
772 let mut entries: Vec<(u64, u64)> = Vec::with_capacity(count);
773 for blob in dict_blobs {
774 let aligned = align8(cur_off);
775 entries.push((aligned, blob.len() as u64));
776 cur_off = aligned + blob.len() as u64;
777 }
778
779 let header_len = 8 + count * 16;
780 let mut out = Vec::with_capacity(header_len + cur_off as usize);
781 out.extend_from_slice(&(count as u16).to_le_bytes());
782 out.extend_from_slice(&[0u8; 6]);
783 for &(off, len) in &entries {
784 out.extend_from_slice(&off.to_le_bytes());
785 out.extend_from_slice(&len.to_le_bytes());
786 }
787 for (blob, &(off, _)) in dict_blobs.iter().zip(entries.iter()) {
788 out.resize(header_len + off as usize, 0);
789 out.extend_from_slice(blob);
790 }
791 out
792}