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 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 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 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 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 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 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 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 let meta_raw = serde_json::to_vec(&metadata_json)?;
600 push_small_section(&mut sections, SectionKind::Metadata, meta_raw)?;
601
602 let schema_raw = built_cols.schema.encode();
604 push_small_section(&mut sections, SectionKind::Schema, schema_raw)?;
605
606 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 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 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 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 if has_host_ext {
648 let he_raw = host_ext.encode();
649 push_small_section(&mut sections, SectionKind::Ipv6HostExt, he_raw)?;
650 }
651
652 {
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 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 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 §ions {
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}