1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
use std::borrow::Borrow;
use anyhow::Result;
use serde::de::DeserializeOwned;
use serde::Serialize;
use crate::rdb::errors::Error;
use crate::types::Row;
pub const HEADER_SIZE: u32 = 1;
pub trait Record: Sized + Serialize + DeserializeOwned {
fn from_row(r: &Row) -> Option<Self> {
let buffer: &[u8] = r.borrow();
let header = buffer[0] as usize;
return if header == 0 {
None
} else {
let instance: Self =
bincode::deserialize(&buffer[1..buffer.len() - header + 1]).expect("load a record");
Some(instance)
};
}
fn to_row(&self, row_length: u32) -> Result<Row> {
let mut bin = bincode::serialize(&self).expect("serialize a record fail");
let length = bin.len();
let header = ((length + 1) & 31) as u8;
let mut vec = vec![header];
vec.append(&mut bin);
let row: Row = vec.into();
return if row.len() as u32 == row_length {
Ok(row)
} else {
Err(Error::RecordNotSized.into())
};
}
}