use crate::error::LiteError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, zerompk::ToMessagePack, zerompk::FromMessagePack)]
#[msgpack(c_enum)]
pub(crate) enum WindowKind {
None = 0,
Daily = 1,
Weekly = 2,
Monthly = 3,
Custom = 4,
}
#[derive(Debug, Clone, PartialEq, Eq, zerompk::ToMessagePack, zerompk::FromMessagePack)]
pub(crate) struct WindowDef {
pub kind: WindowKind,
pub timestamp_column: String,
pub timestamp_desc: bool,
pub start_ms: u64,
pub end_ms: u64,
}
impl WindowDef {
pub fn none() -> Self {
Self {
kind: WindowKind::None,
timestamp_column: String::new(),
timestamp_desc: false,
start_ms: 0,
end_ms: 0,
}
}
pub fn is_windowed(&self) -> bool {
self.kind != WindowKind::None
}
}
#[derive(Debug, Clone, PartialEq, Eq, zerompk::ToMessagePack, zerompk::FromMessagePack)]
pub(crate) struct SortedIndexDef {
pub name: String,
pub collection: String,
pub score_column: String,
pub score_desc: bool,
pub key_column: String,
pub window: WindowDef,
}
impl SortedIndexDef {
pub(crate) fn encode(&self) -> Result<Vec<u8>, LiteError> {
zerompk::to_msgpack_vec(self).map_err(|e| LiteError::Serialization {
detail: format!("encode sorted index definition '{}': {e}", self.name),
})
}
pub(crate) fn decode(bytes: &[u8]) -> Result<Self, LiteError> {
zerompk::from_msgpack(bytes).map_err(|e| LiteError::Corrupted {
detail: format!("stored sorted index definition does not decode: {e}"),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_definition_round_trips_with_its_window() {
let def = SortedIndexDef {
name: "lb".into(),
collection: "players".into(),
score_column: "score".into(),
score_desc: true,
key_column: "id".into(),
window: WindowDef {
kind: WindowKind::Custom,
timestamp_column: "ts".into(),
timestamp_desc: false,
start_ms: 10,
end_ms: 20,
},
};
let decoded = SortedIndexDef::decode(&def.encode().expect("encode")).expect("decode");
assert_eq!(decoded, def);
}
}