1use std::borrow::Cow;
2use std::marker::PhantomData;
3use std::mem::size_of;
4
5use byteorder::{ByteOrder, ReadBytesExt};
6use heed_traits::{BoxedError, BytesDecode, BytesEncode};
7
8pub struct U8;
10
11impl BytesEncode<'_> for U8 {
12 type EItem = u8;
13
14 fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, BoxedError> {
15 Ok(Cow::from([*item].to_vec()))
16 }
17}
18
19impl BytesDecode<'_> for U8 {
20 type DItem = u8;
21
22 fn bytes_decode(mut bytes: &'_ [u8]) -> Result<Self::DItem, BoxedError> {
23 bytes.read_u8().map_err(Into::into)
24 }
25}
26
27pub struct I8;
29
30impl BytesEncode<'_> for I8 {
31 type EItem = i8;
32
33 fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, BoxedError> {
34 Ok(Cow::from([*item as u8].to_vec()))
35 }
36}
37
38impl BytesDecode<'_> for I8 {
39 type DItem = i8;
40
41 fn bytes_decode(mut bytes: &'_ [u8]) -> Result<Self::DItem, BoxedError> {
42 bytes.read_i8().map_err(Into::into)
43 }
44}
45
46macro_rules! define_type {
47 ($name:ident, $native:ident, $read_method:ident, $write_method:ident) => {
48 #[doc = "Encodable version of [`"]
49 #[doc = stringify!($native)]
50 #[doc = "`]."]
51
52 pub struct $name<O>(PhantomData<O>);
53
54 impl<O: ByteOrder> BytesEncode<'_> for $name<O> {
55 type EItem = $native;
56
57 fn bytes_encode(item: &Self::EItem) -> Result<Cow<[u8]>, BoxedError> {
58 let mut buf = vec![0; size_of::<Self::EItem>()];
59 O::$write_method(&mut buf, *item);
60 Ok(Cow::from(buf))
61 }
62 }
63
64 impl<O: ByteOrder> BytesDecode<'_> for $name<O> {
65 type DItem = $native;
66
67 fn bytes_decode(mut bytes: &'_ [u8]) -> Result<Self::DItem, BoxedError> {
68 bytes.$read_method::<O>().map_err(Into::into)
69 }
70 }
71 };
72}
73
74define_type!(U16, u16, read_u16, write_u16);
75define_type!(U32, u32, read_u32, write_u32);
76define_type!(U64, u64, read_u64, write_u64);
77define_type!(U128, u128, read_u128, write_u128);
78define_type!(I16, i16, read_i16, write_i16);
79define_type!(I32, i32, read_i32, write_i32);
80define_type!(I64, i64, read_i64, write_i64);
81define_type!(I128, i128, read_i128, write_i128);