MCPcopy Create free account
hub / github.com/dialog-db/dialog-db / encode

Function encode

rust/dialog-encoding/src/buffer.rs:99–147  ·  view source on GitHub ↗

Encodes a columnar data structure into a binary buffer with deduplication. This function takes a data structure that implements [`Cellular`] and encodes it into a compact binary format that enables zero-copy reading. Identical byte sequences are automatically deduplicated to minimize storage space. # Arguments `layout` - The data structure to encode, must implement [`Cellular`] `buffer` - The o

(
    layout: &'a Layout,
    mut buffer: Buffer,
)

Source from the content-addressed store, hash-verified

97/// // The encoded buffer will deduplicate the repeated "hello"
98/// ```
99pub fn encode<'a, Layout, Buffer>(
100 layout: &'a Layout,
101 mut buffer: Buffer,
102) -> Result<(), std::io::Error>
103where
104 Layout: Cellular<'a>,
105 Buffer: Write,
106{
107 let mut data = Cursor::new(Vec::new());
108 let mut ranges = Cursor::new(Vec::new());
109 let mut cells = Cursor::new(Vec::new());
110 let mut bytes_to_index = BTreeMap::<&'a [u8], u64>::new();
111 let mut next_index = 0u64;
112 let mut data_length = 0usize;
113
114 for cell in layout.cells() {
115 if let Some(index) = bytes_to_index.get(cell) {
116 leb128::write::unsigned(&mut cells, *index)?;
117 } else {
118 leb128::write::unsigned(&mut ranges, data_length as u64)?;
119 leb128::write::unsigned(&mut ranges, cell.len() as u64)?;
120
121 data_length += cell.len();
122 data.write_all(cell)?;
123 bytes_to_index.insert(cell, next_index);
124
125 leb128::write::unsigned(&mut cells, next_index)?;
126
127 next_index += 1;
128 }
129 }
130
131 let data = data.into_inner();
132 let ranges = ranges.into_inner();
133 let cells = cells.into_inner();
134
135 // [ data length ][ data ]
136 leb128::write::unsigned(&mut buffer, data.len() as u64)?;
137 buffer.write_all(&data)?;
138
139 // [ ranges length ][ ranges ]
140 leb128::write::unsigned(&mut buffer, ranges.len() as u64)?;
141 buffer.write_all(&ranges)?;
142
143 // [ cells ]
144 buffer.write_all(&cells)?;
145
146 Ok(())
147}
148
149/// Decodes a binary buffer into a columnar data structure with zero-copy access.
150///

Calls 5

cellsMethod · 0.80
into_innerMethod · 0.80
getMethod · 0.45
lenMethod · 0.45
insertMethod · 0.45