Skip to content

Commit

Permalink
Move some impls into a new module
Browse files Browse the repository at this point in the history
Move `impl<T> Value for Option<T>` into its own file.
  • Loading branch information
adamchalmers committed Dec 21, 2023
1 parent 70e6863 commit 584b245
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 42 deletions.
44 changes: 44 additions & 0 deletions execution-plan-traits/src/containers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//! Impl Value for various container types, if the inner type implements Value.
use crate::{MemoryError, Primitive, Value};
const NONE: &str = "None";
const SOME: &str = "Some";

impl<T> Value for Option<T>
where
T: Value,
{
fn into_parts(self) -> Vec<Primitive> {
match self {
Some(v) => {
let mut parts = Vec::new();
parts.push(SOME.to_owned().into());
parts.extend(v.into_parts());
parts
}
None => vec![NONE.to_owned().into()],
}
}

fn from_parts<I>(values: &mut I) -> Result<Self, MemoryError>
where
I: Iterator<Item = Option<Primitive>>,
{
let variant: String = values
.next()
.flatten()
.ok_or(MemoryError::MemoryWrongSize)?
.try_into()?;
match variant.as_str() {
NONE => Ok(None),
SOME => {
let val = T::from_parts(values)?;
Ok(Some(val))
}
other => Err(MemoryError::InvalidEnumVariant {
expected_type: "option".to_owned(),
actual: other.to_owned(),
}),
}
}
}
43 changes: 1 addition & 42 deletions execution-plan-traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub use self::primitive::{NumericPrimitive, Primitive};

#[macro_use]
mod primitive;
mod containers;

/// Types that can be written to or read from KCEP program memory.
/// If they require multiple memory addresses, they will be laid out
Expand All @@ -18,48 +19,6 @@ pub trait Value: Sized {
I: Iterator<Item = Option<Primitive>>;
}

const NONE: &str = "None";
const SOME: &str = "Some";

impl<T> Value for Option<T>
where
T: Value,
{
fn into_parts(self) -> Vec<Primitive> {
match self {
Some(v) => {
let mut parts = Vec::new();
parts.push(SOME.to_owned().into());
parts.extend(v.into_parts());
parts
}
None => vec![NONE.to_owned().into()],
}
}

fn from_parts<I>(values: &mut I) -> Result<Self, MemoryError>
where
I: Iterator<Item = Option<Primitive>>,
{
let variant: String = values
.next()
.flatten()
.ok_or(MemoryError::MemoryWrongSize)?
.try_into()?;
match variant.as_str() {
NONE => Ok(None),
SOME => {
let val = T::from_parts(values)?;
Ok(Some(val))
}
other => Err(MemoryError::InvalidEnumVariant {
expected_type: "option".to_owned(),
actual: other.to_owned(),
}),
}
}
}

/// TODO
#[derive(Debug, thiserror::Error, Default)]
pub enum MemoryError {
Expand Down

0 comments on commit 584b245

Please sign in to comment.