Skip to content

Commit

Permalink
Impl Encode/Decode for smart pointers (Sovereign-Labs#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
preston-evans98 authored Feb 1, 2023
1 parent 5a1c096 commit 069fd53
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ proptest = { version = "1.0.0", optional = true }

[features]
fuzzing = ["proptest"]
sync = []
2 changes: 2 additions & 0 deletions src/node/db/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ pub enum CodecError {
DeserializationError(#[from] DeserializationError),
#[error(transparent)]
Wrapped(#[from] anyhow::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
}

pub fn convert_to_codec_error(e: impl Into<anyhow::Error>) -> CodecError {
Expand Down
38 changes: 38 additions & 0 deletions src/state_machine/serial.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#[cfg(feature = "sync")]
use std::sync::Arc;
use std::{ops::Deref, rc::Rc};

use thiserror::Error;

#[derive(Debug, PartialEq, Error)]
Expand Down Expand Up @@ -30,3 +34,37 @@ pub trait Decode: Sized {

fn decode(target: &mut &[u8]) -> Result<Self, Self::Error>;
}

// Automatically implement encode for smart pointers
impl<T, U> Encode for T
where
T: Deref<Target = U>,
U: Encode,
{
fn encode(&self, target: &mut impl std::io::Write) {
self.deref().encode(target)
}
}

#[cfg(feature = "sync")]
impl<T, E> Decode for Arc<T>
where
T: Decode<Error = E>,
{
type Error = E;

fn decode(target: &mut &[u8]) -> Result<Self, Self::Error> {
Ok(Arc::new(T::decode(target)?))
}
}

impl<T, E> Decode for Rc<T>
where
T: Decode<Error = E>,
{
type Error = E;

fn decode(target: &mut &[u8]) -> Result<Self, Self::Error> {
Ok(Rc::new(T::decode(target)?))
}
}

0 comments on commit 069fd53

Please sign in to comment.