record last key in meta

Signed-off-by: Alex Chi Z <iskyzh@gmail.com>
This commit is contained in:
Alex Chi Z
2024-01-17 16:49:12 +08:00
parent e622bee18a
commit 81bd372524
2 changed files with 60 additions and 8 deletions

View File

@@ -12,6 +12,7 @@ use crate::lsm_storage::BlockCache;
pub struct SsTableBuilder {
builder: BlockBuilder,
first_key: Vec<u8>,
last_key: Vec<u8>,
data: Vec<u8>,
pub(super) meta: Vec<BlockMeta>,
block_size: usize,
@@ -24,6 +25,7 @@ impl SsTableBuilder {
data: Vec::new(),
meta: Vec::new(),
first_key: Vec::new(),
last_key: Vec::new(),
block_size,
builder: BlockBuilder::new(block_size),
}
@@ -32,18 +34,25 @@ impl SsTableBuilder {
/// Adds a key-value pair to SSTable
pub fn add(&mut self, key: &[u8], value: &[u8]) {
if self.first_key.is_empty() {
self.first_key = key.to_vec();
self.first_key.clear();
self.first_key.extend(key);
}
if self.builder.add(key, value) {
self.last_key.clear();
self.last_key.extend(key);
return;
}
// create a new block builder and append block data
self.finish_block();
// add the key-value pair to the next block
assert!(self.builder.add(key, value));
self.first_key = key.to_vec();
self.first_key.clear();
self.first_key.extend(key);
self.last_key.clear();
self.last_key.extend(key);
}
/// Get the estimated size of the SSTable.
@@ -57,6 +66,7 @@ impl SsTableBuilder {
self.meta.push(BlockMeta {
offset: self.data.len(),
first_key: std::mem::take(&mut self.first_key).into(),
last_key: std::mem::take(&mut self.last_key).into(),
});
self.data.extend(encoded_block);
}
@@ -78,6 +88,8 @@ impl SsTableBuilder {
Ok(SsTable {
id,
file,
first_key: self.meta.first().unwrap().first_key.clone(),
last_key: self.meta.last().unwrap().last_key.clone(),
block_metas: self.meta,
block_meta_offset: meta_offset,
block_cache,