Skip to main content

waveless_commons/
entry.rs

1// Waveless
2// Copyright (C) 2026 Oscar Alvarez Gonzalez
3
4use crate::*;
5
6pub trait Key: 'static + Send + Sync {
7    fn collect(&self) -> impl AsRef<[u8]>;
8
9    fn into_key(value: &[u8]) -> Result<Self>
10    where
11        Self: Sized;
12}
13
14pub trait Value:
15    'static + Clone + PartialEq + Send + Sync + Encode<Output = Bytes> + Decode<Input = [u8]>
16{
17}
18
19impl Key for u32 {
20    fn collect(&self) -> impl AsRef<[u8]> {
21        self.to_be_bytes()
22    }
23
24    fn into_key(value: &[u8]) -> Result<Self> {
25        Ok(u32::from_be_bytes(<[u8; 4]>::try_from(value)?))
26    }
27}
28
29impl Key for u64 {
30    fn collect(&self) -> impl AsRef<[u8]> {
31        self.to_be_bytes()
32    }
33
34    fn into_key(value: &[u8]) -> Result<Self> {
35        Ok(u64::from_be_bytes(<[u8; 8]>::try_from(value)?))
36    }
37}
38
39impl<const N: usize> Key for [u8; N] {
40    fn collect(&self) -> impl AsRef<[u8]> {
41        self.as_slice()
42    }
43
44    fn into_key(value: &[u8]) -> Result<Self> {
45        if value.len() != N {
46            bail!(
47                "Invalid size for [u8; {}]: expected {} bytes, got {}",
48                N,
49                N,
50                value.len()
51            );
52        }
53
54        let mut array = [0u8; N];
55        array.copy_from_slice(value);
56        Ok(array)
57    }
58}
59
60impl<T: 'static + Clone + PartialEq + Send + Sync + Encode<Output = Bytes> + Decode<Input = [u8]>>
61    Value for T
62{
63}