icydb_core/key/
convert.rs

1use crate::{
2    key::core::Key,
3    traits::FieldValue,
4    types::{Account, Principal, Subaccount, Timestamp, Ulid, Unit},
5    value::Value,
6};
7use candid::Principal as WrappedPrincipal;
8
9impl FieldValue for Key {
10    fn to_value(&self) -> Value {
11        match self {
12            Self::Account(v) => Value::Account(*v),
13            Self::Int(v) => Value::Int(*v),
14            Self::Principal(v) => Value::Principal(*v),
15            Self::Subaccount(v) => Value::Subaccount(*v),
16            Self::Timestamp(v) => Value::Timestamp(*v),
17            Self::Uint(v) => Value::Uint(*v),
18            Self::Ulid(v) => Value::Ulid(*v),
19            Self::Unit => Value::Unit,
20        }
21    }
22}
23
24impl From<()> for Key {
25    fn from((): ()) -> Self {
26        Self::Unit
27    }
28}
29
30impl From<Unit> for Key {
31    fn from(_: Unit) -> Self {
32        Self::Unit
33    }
34}
35
36impl PartialEq<()> for Key {
37    fn eq(&self, (): &()) -> bool {
38        matches!(self, Self::Unit)
39    }
40}
41
42impl PartialEq<Key> for () {
43    fn eq(&self, other: &Key) -> bool {
44        other == self
45    }
46}
47
48/// Implements `From<T> for Key` for simple conversions.
49macro_rules! impl_from_key {
50    ( $( $ty:ty => $variant:ident ),* $(,)? ) => {
51        $(
52            impl From<$ty> for Key {
53                fn from(v: $ty) -> Self {
54                    Self::$variant(v.into())
55                }
56            }
57        )*
58    }
59}
60
61/// Implements symmetric PartialEq between Key and another type.
62macro_rules! impl_eq_key {
63    ( $( $ty:ty => $variant:ident ),* $(,)? ) => {
64        $(
65            impl PartialEq<$ty> for Key {
66                fn eq(&self, other: &$ty) -> bool {
67                    matches!(self, Self::$variant(val) if val == other)
68                }
69            }
70
71            impl PartialEq<Key> for $ty {
72                fn eq(&self, other: &Key) -> bool {
73                    other == self
74                }
75            }
76        )*
77    }
78}
79
80impl_from_key! {
81    Account => Account,
82    i8  => Int,
83    i16 => Int,
84    i32 => Int,
85    i64 => Int,
86    Principal => Principal,
87    WrappedPrincipal => Principal,
88    Subaccount => Subaccount,
89    Timestamp => Timestamp,
90    u8  => Uint,
91    u16 => Uint,
92    u32 => Uint,
93    u64 => Uint,
94    Ulid => Ulid,
95}
96
97impl_eq_key! {
98    Account => Account,
99    i64 => Int,
100    Principal => Principal,
101    Subaccount => Subaccount,
102    Timestamp => Timestamp,
103    u64  => Uint,
104    Ulid => Ulid,
105}