Skip to main content

mdbx_derive_traits/
alloy.rs

1use alloy_primitives::aliases::U24;
2use alloy_primitives::{Address, B256, U8, U16, U64, U128, U160, U256};
3
4use crate::error::MDBXDeriveError;
5use crate::key::{KeyObjectDecode, KeyObjectEncode};
6
7impl KeyObjectEncode for Address {
8    fn key_encode(&self) -> Result<Vec<u8>, MDBXDeriveError> {
9        Ok(self.iter().copied().collect())
10    }
11}
12
13impl KeyObjectDecode for Address {
14    fn key_decode(val: &[u8]) -> Result<Self, MDBXDeriveError> {
15        Ok(Address::new(
16            val.try_into().map_err(|_| MDBXDeriveError::Corrupted)?,
17        ))
18    }
19}
20
21impl KeyObjectEncode for B256 {
22    fn key_encode(&self) -> Result<Vec<u8>, MDBXDeriveError> {
23        Ok(self.iter().copied().collect())
24    }
25}
26
27impl KeyObjectDecode for B256 {
28    fn key_decode(val: &[u8]) -> Result<Self, MDBXDeriveError> {
29        Ok(B256::new(
30            val.try_into().map_err(|_| MDBXDeriveError::Corrupted)?,
31        ))
32    }
33}
34
35macro_rules! impl_alloy {
36    ( $( $name:ident )+ ) => {
37        $(
38            impl KeyObjectEncode for $name {
39                fn key_encode(&self) -> Result<Vec<u8>, MDBXDeriveError> {
40                    // This converts to exactly Uint::BYTES
41                    Ok(self.to_be_bytes_vec())
42                }
43            }
44            impl KeyObjectDecode for $name {
45                const KEYSIZE: usize = $name::BYTES;
46                fn key_decode(val: &[u8]) -> Result<Self, MDBXDeriveError> {
47                    Ok($name::from_be_bytes::<{$name::BYTES}>(val.try_into().map_err(|_| MDBXDeriveError::Corrupted)?))
48                }
49            }
50        )+
51    };
52}
53
54impl_alloy! { U256 U160 U128 U64 U24 U16 U8 }