ghaladb/
core.rs

1use bincode::{Decode, Encode};
2
3#[cfg(test)]
4use rand::{distributions::Standard, thread_rng, Rng};
5
6pub type Bytes = Vec<u8>;
7pub type KeyRef<'a> = &'a [u8];
8pub type VlogNum = u64;
9pub type DataEntrySz = u32;
10
11/// A data pointer for data on disk.
12#[derive(
13    Debug, Clone, Copy, Encode, Decode, PartialEq, Hash, PartialOrd, Ord, Eq,
14)]
15pub struct DataPtr {
16    /// The value log number
17    pub vlog: VlogNum,
18    /// Data offset in the value log file.
19    pub offset: u64,
20    /// Data size
21    pub len: DataEntrySz,
22    /// Data compression flag.
23    pub compressed: bool,
24}
25impl DataPtr {
26    /// Create a data pointer.
27    pub fn new(vlog: VlogNum, offset: u64, len: u32, compressed: bool) -> Self {
28        Self {
29            vlog,
30            offset,
31            len,
32            compressed,
33        }
34    }
35
36    pub fn serde_sz() -> usize {
37        // u64 + u64 + u32 +bool
38        21
39    }
40}
41
42#[cfg(test)]
43pub trait FixtureGen<T> {
44    fn gen() -> T;
45}
46
47#[cfg(test)]
48impl FixtureGen<Bytes> for Bytes {
49    fn gen() -> Bytes {
50        let mut rng = thread_rng();
51        let len = rng.gen_range(32..4097);
52        rng.sample_iter(Standard).take(len).collect()
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use crate::{dec::Dec, error::GhalaDbResult};
59
60    use super::*;
61
62    #[test]
63    fn dp_serde_sz() -> GhalaDbResult<()> {
64        let dp = DataPtr::new(0, 0, 0, true);
65        let serde_sz = DataPtr::serde_sz();
66        let bytes = Dec::ser_raw(&dp)?;
67        assert_eq!(
68            bytes.len(),
69            serde_sz,
70            "dp bytes not match expected len. Got: {} Expected: {}",
71            serde_sz,
72            bytes.len()
73        );
74        Ok(())
75    }
76}