Skip to content

Commit

Permalink
Use custom rend/ser for enum codes
Browse files Browse the repository at this point in the history
  • Loading branch information
novacrazy committed Jan 2, 2024
1 parent 7ba4b28 commit 20cbc25
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 7 deletions.
2 changes: 2 additions & 0 deletions common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ postgres-types = { version = "0.2.1", optional = true }
bytes = { version = "1", optional = true }
rusqlite = { version = "0.30.0", optional = true }
rkyv = { version = "0.7", optional = true, default-features = false, features = ["validation"] }
rend = { version = "0.4", optional = true, default-features = false }

[features]
default = ["std"]
pg = ["postgres-types", "bytes"]
std = ["rkyv?/std"]
rkyv = ["dep:rkyv", "rend"]
3 changes: 3 additions & 0 deletions common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ extern crate alloc;
#[cfg(feature = "rkyv")]
pub extern crate rkyv;

#[cfg(feature = "rkyv")]
pub extern crate rend;

pub extern crate serde_shims;

pub mod db;
Expand Down
14 changes: 7 additions & 7 deletions common/src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ macro_rules! impl_rkyv_for_enum_codes {
use $crate::rkyv::{Archive, Deserialize, Fallible, Serialize, Archived, bytecheck::{EnumCheckError, CheckBytes}};

impl Archive for $name {
type Archived = $repr;
type Archived = $crate::rend::LittleEndian<$repr>;
type Resolver = ();

#[inline]
unsafe fn resolve(&self, _pos: usize, _resolver: Self::Resolver, out: *mut Self::Archived) {
*out = *self as $repr;
*out = $crate::rend::LittleEndian::<$repr>::new(*self as $repr);
}
}

Expand All @@ -112,11 +112,11 @@ macro_rules! impl_rkyv_for_enum_codes {

impl<D: Fallible + ?Sized> Deserialize<$name, D> for Archived<$name> {
fn deserialize(&self, _deserializer: &mut D) -> Result<$name, D::Error> {
Ok(match *self {
Ok(match self.value() {
$($code => $name::$variant,)*
$(_ => $name::$unknown,)?

_ => panic!("Unknown code: {self}"),
u @ _ => panic!("Unknown code: {u}"),
})
}
}
Expand All @@ -128,12 +128,12 @@ macro_rules! impl_rkyv_for_enum_codes {
value: *const Self,
context: &mut C
) -> Result<&'a Self, Self::Error> {
let tag = *value.cast::<$repr>();
match tag {
let tag = *value.cast::<$crate::rend::LittleEndian<$repr>>();
match tag.value() {
$(| $code)* => Ok(&*value),
$(_ => Ok(&$name::$unknown),)?

_ => Err(EnumCheckError::InvalidTag(tag))
tag @ _ => Err(EnumCheckError::InvalidTag(tag))
}
}
}
Expand Down

0 comments on commit 20cbc25

Please sign in to comment.