erigon_seg/writer/
domain.rs1use std::path::{Path, PathBuf};
10
11use super::bt_writer::{BtOptions, build_bt_from_seg};
12use super::kvei_writer::build_kvei_from_seg;
13use super::seg_writer::SegWriter;
14use crate::error::{Error, Result};
15use crate::seg::Seg;
16
17#[derive(Debug, Clone, Copy, Default)]
19pub struct DomainOptions {
20 pub bt: BtOptions,
22 pub salt: Option<u32>,
25 pub compress: bool,
28}
29
30#[derive(Debug, Clone)]
32pub struct DomainPaths {
33 pub kv: PathBuf,
35 pub bt: PathBuf,
37 pub kvei: Option<PathBuf>,
39}
40
41pub struct DomainWriter {
43 kv_path: PathBuf,
44 seg: SegWriter,
45 opts: DomainOptions,
46 last_key: Option<Vec<u8>>,
47 key_count: u64,
48}
49
50impl DomainWriter {
51 pub fn create(kv_path: impl AsRef<Path>, opts: DomainOptions) -> Result<DomainWriter> {
53 let kv_path = kv_path.as_ref().to_path_buf();
54 let seg = SegWriter::create_with(&kv_path, opts.compress)?;
55 Ok(DomainWriter {
56 kv_path,
57 seg,
58 opts,
59 last_key: None,
60 key_count: 0,
61 })
62 }
63
64 pub fn add(&mut self, key: &[u8], value: &[u8]) -> Result<()> {
66 if let Some(last) = &self.last_key
67 && key <= last.as_slice()
68 {
69 return Err(Error::format(format!(
70 "DomainWriter: keys must be strictly increasing (got {:02x?} after {:02x?})",
71 key, last
72 )));
73 }
74 self.seg.add_word(key)?;
75 self.seg.add_word(value)?;
76 self.last_key = Some(key.to_vec());
77 self.key_count += 1;
78 Ok(())
79 }
80
81 pub fn key_count(&self) -> u64 {
83 self.key_count
84 }
85
86 pub fn finish(self) -> Result<DomainPaths> {
88 let kv_path = self.kv_path;
89 let bt_path = kv_path.with_extension("bt");
90 let opts = self.opts;
91
92 self.seg.finish()?;
93 let seg = Seg::open(&kv_path)?;
94
95 build_bt_from_seg(&seg, &bt_path, opts.bt)?;
96
97 let kvei = match opts.salt {
98 Some(salt) => {
99 let kvei_path = kv_path.with_extension("kvei");
100 build_kvei_from_seg(&seg, salt, &kvei_path)?;
101 Some(kvei_path)
102 }
103 None => None,
104 };
105
106 Ok(DomainPaths {
107 kv: kv_path,
108 bt: bt_path,
109 kvei,
110 })
111 }
112}