Skip to main content

icydb_core/db/
traits.rs

1use crate::key::Key;
2
3///
4/// FromKey
5/// Convert a stored [`Key`] into a concrete type.
6/// Returns `None` if the key cannot represent this type.
7///
8
9pub trait FromKey: Copy {
10    fn try_from_key(key: Key) -> Option<Self>;
11}
12
13#[macro_export]
14macro_rules! impl_from_key_int {
15    ( $( $ty:ty ),* $(,)? ) => {
16        $(
17            impl $crate::db::traits::FromKey for $ty {
18                fn try_from_key(key: $crate::key::Key) -> Option<Self> {
19                    match key {
20                        $crate::key::Key::Int(v) => Self::try_from(v).ok(),
21                        _ => None,
22                    }
23                }
24            }
25        )*
26    };
27}
28
29#[macro_export]
30macro_rules! impl_from_key_uint {
31    ( $( $ty:ty ),* $(,)? ) => {
32        $(
33            impl $crate::db::traits::FromKey for $ty {
34                fn try_from_key(key: $crate::key::Key) -> Option<Self> {
35                    match key {
36                        $crate::key::Key::Uint(v) => Self::try_from(v).ok(),
37                        _ => None,
38                    }
39                }
40            }
41        )*
42    };
43}
44
45impl_from_key_int!(i8, i16, i32, i64);
46impl_from_key_uint!(u8, u16, u32, u64);