sync starter code

Signed-off-by: Alex Chi <iskyzh@gmail.com>
This commit is contained in:
Alex Chi
2024-01-20 11:11:09 +08:00
parent cfa7c0c2af
commit 9fd30f6aa8
15 changed files with 615 additions and 55 deletions

View File

@@ -4,6 +4,7 @@
mod builder;
mod iterator;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;
@@ -42,24 +43,37 @@ impl BlockMeta {
}
/// A file object.
pub struct FileObject(Bytes);
pub struct FileObject(Option<File>, u64);
impl FileObject {
pub fn read(&self, offset: u64, len: u64) -> Result<Vec<u8>> {
Ok(self.0[offset as usize..(offset + len) as usize].to_vec())
use std::os::unix::fs::FileExt;
let mut data = vec![0; len as usize];
self.0
.as_ref()
.unwrap()
.read_exact_at(&mut data[..], offset)?;
Ok(data)
}
pub fn size(&self) -> u64 {
self.0.len() as u64
self.1
}
/// Create a new file object (day 2) and write the file to the disk (day 4).
pub fn create(path: &Path, data: Vec<u8>) -> Result<Self> {
unimplemented!()
std::fs::write(path, &data)?;
File::open(path)?.sync_all()?;
Ok(FileObject(
Some(File::options().read(true).write(false).open(path)?),
data.len() as u64,
))
}
pub fn open(path: &Path) -> Result<Self> {
unimplemented!()
let file = File::options().read(true).write(false).open(path)?;
let size = file.metadata()?.len();
Ok(FileObject(Some(file), size))
}
}
@@ -75,6 +89,10 @@ pub struct SsTable {
block_metas: Vec<BlockMeta>,
/// The offset that indicates the start point of meta blocks in `file`.
block_meta_offset: usize,
id: usize,
block_cache: Option<Arc<BlockCache>>,
first_key: Bytes,
last_key: Bytes,
}
impl SsTable {
@@ -88,6 +106,19 @@ impl SsTable {
unimplemented!()
}
/// Create a mock SST with only first key + last key metadata
pub fn create_meta_only(id: usize, file_size: u64, first_key: Bytes, last_key: Bytes) -> Self {
Self {
file: FileObject(None, file_size),
block_metas: vec![],
block_meta_offset: 0,
id,
block_cache: None,
first_key,
last_key,
}
}
/// Read a block from the disk.
pub fn read_block(&self, block_idx: usize) -> Result<Arc<Block>> {
unimplemented!()