epoch_db/metadata/
mod.rs

1//! The `metadata` module defines the `Metadata` struct and its associated
2//! methods. `Metadata` is used to track information about each key-value
3//! pair, such as its creation time, access frequency, and TTL.
4
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use crate::Metadata;
8use bincode::{
9    error::{DecodeError, EncodeError},
10    serde::{decode_from_slice, encode_to_vec},
11};
12
13impl Metadata {
14    /// Creates a new `Metadata` instance with an optional TTL.
15    ///
16    /// The `created_at` timestamp is set to the current system time.
17    pub fn new(ttl: Option<u64>) -> Metadata {
18        let currtime = SystemTime::now()
19            .duration_since(UNIX_EPOCH)
20            .expect("Cant get the current time")
21            .as_secs();
22        Metadata {
23            freq: 0,
24            created_at: currtime,
25            ttl,
26        }
27    }
28
29    /// Increments the frequency counter.
30    pub fn freq_incretement(mut self) -> Metadata {
31        self.freq += 1;
32        self
33    }
34
35    /// Decrements the frequency counter.
36    pub fn freq_decretement(mut self) -> Metadata {
37        self.freq -= 1;
38        self
39    }
40
41    /// Serializes the `Metadata` instance into a byte vector using `bincode`.
42    ///
43    /// # Errors
44    ///
45    /// Returns an `EncodeError` if serialization fails.
46    pub fn to_u8(&self) -> Result<Vec<u8>, EncodeError> {
47        encode_to_vec(self, bincode::config::standard())
48    }
49
50    /// Deserializes a `Metadata` instance from a byte slice using `bincode`.
51    ///
52    /// # Errors
53    ///
54    /// Returns a `DecodeError` if deserialization fails.
55    pub fn from_u8(slice: &[u8]) -> Result<Metadata, DecodeError> {
56        Ok(decode_from_slice(slice, bincode::config::standard())?.0)
57    }
58}