Introduce segments module

This commit is contained in:
Yuriy Dupyn 2024-02-05 03:35:43 +01:00
parent 1618bffb85
commit b13d2f04cd
8 changed files with 12 additions and 13 deletions

View file

@ -0,0 +1,60 @@
use bincode::{Decode, Encode};
use crate::binary_coding::{encode_sequence, encode_sequence_with_sizes, decode_sequence};
use crate::storage_engine::{Result, FilePosition};
use crate::error::{Error, DecodeErrorKind};
use crate::segments::entry_header::{EntryHeader, EntryHeaderWithDataSize};
#[derive(Debug)]
pub struct Entry<T> {
pub header: EntryHeader,
pub data: Vec<T>,
}
#[derive(Debug)]
pub struct EntryDetailed<T> {
pub header: EntryHeaderWithDataSize,
pub file_position: FilePosition,
pub data: Vec<T>,
}
impl <T>Entry<T> {
pub fn new(data: Vec<T>) -> Self {
Self { header: EntryHeader { is_deleted: false }, data }
}
pub fn new_deleted(data: Vec<T>) -> Self {
Self { header: EntryHeader { is_deleted: true}, data }
}
// FORMAT: [EntryHeaderWithDataSize, ..sequence of data]
pub fn encode(&self) -> Result<Vec<u8>>
where T: Encode
{
let mut result: Vec<u8> = self.header.encode()?;
let (mut encoded_data, sizes) = encode_sequence_with_sizes(&self.data[..])?;
result.append(&mut encode_sequence(&sizes)?); // sizes of data (fixed by number of columns)
result.append(&mut encoded_data); // data variable size
Ok(result)
}
}
impl <T>EntryDetailed<T> {
pub fn decode(header: EntryHeaderWithDataSize, file_position: FilePosition, number_of_columns: usize, bytes: &[u8]) -> Result<Self>
where T: Decode
{
let data = decode_sequence::<T>(number_of_columns, bytes)
.map_err(|e| Error::DecodeError(DecodeErrorKind::EntryData, e))?;
Ok(EntryDetailed { header, file_position, data })
}
pub fn forget(&self) -> Entry<T>
where T: Clone
{
Entry {
header: self.header.clone().into(),
data: self.data.clone(),
}
}
}