Skip to content

Commit

Permalink
Refactor (#131)
Browse files Browse the repository at this point in the history
* Refactor EwasmAny parsing
- allow using path type
  • Loading branch information
yanganto committed Jul 26, 2021
1 parent 8c43935 commit f5bb497
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 62 deletions.
1 change: 1 addition & 0 deletions examples/rdb-contract/src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use sewup::rdb::Feature;
use thiserror::Error;

#[allow(dead_code)]
#[derive(Error, Debug, PartialEq)]
pub enum RDBError {
#[error("the DB version `{0}` is unexpected.")]
Expand Down
63 changes: 30 additions & 33 deletions examples/rdb-contract/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,104 +1,101 @@
use anyhow::Result;
use serde_derive::{Deserialize, Serialize};

use sewup::primitives::{Contract, EwasmAny};
use sewup::rdb::{errors::Error as LibError, Db, Feature};
use sewup_derive::{
ewasm_fn, ewasm_fn_sig, ewasm_input_from, ewasm_main, ewasm_output_from, ewasm_test,
};
use sewup::rdb::errors::Error as LibError;
use sewup_derive::{ewasm_fn, ewasm_fn_sig, ewasm_main, ewasm_test};

mod errors;
use errors::RDBError;

mod modules;
use modules::{person, Person, PERSON};

#[ewasm_fn]
fn init_db_with_tables() -> Result<EwasmAny> {
let mut db = Db::new()?;
fn init_db_with_tables() -> anyhow::Result<sewup::primitives::EwasmAny> {
let mut db = sewup::rdb::Db::new()?;
db.create_table::<Person>();
db.commit()?;
Ok(().into())
}

#[ewasm_fn]
fn check_version_and_features(version: u8, features: Vec<Feature>) -> Result<EwasmAny> {
let db = Db::load(None)?;
fn check_version_and_features(
version: u8,
features: Vec<sewup::rdb::Feature>,
) -> anyhow::Result<sewup::primitives::EwasmAny> {
let db = sewup::rdb::Db::load(None)?;
if db.version() != version {
return Err(RDBError::UnexpectVersion(db.version()).into());
return Err(errors::RDBError::UnexpectVersion(db.version()).into());
};
let current_features = db.features();
if current_features != features {
return Err(RDBError::IncompatibleFeatures(current_features).into());
return Err(errors::RDBError::IncompatibleFeatures(current_features).into());
};

Ok(().into())
}

#[ewasm_fn]
fn check_tables() -> Result<EwasmAny> {
let mut db = Db::load(None)?;
fn check_tables() -> anyhow::Result<sewup::primitives::EwasmAny> {
let mut db = sewup::rdb::Db::load(None)?;
let info = db.table_info::<Person>().unwrap();
if info.record_raw_size != 1 {
return Err(RDBError::SimpleError("Person record_raw_size not correct".into()).into());
return Err(
errors::RDBError::SimpleError("Person record_raw_size not correct".into()).into(),
);
}
if info.range.start != 2 {
return Err(RDBError::SimpleError("Person range start not correct".into()).into());
return Err(errors::RDBError::SimpleError("Person range start not correct".into()).into());
}
if info.range.end != 2 {
return Err(RDBError::SimpleError("Person range end not correct".into()).into());
return Err(errors::RDBError::SimpleError("Person range end not correct".into()).into());
}
Ok(().into())
}

#[ewasm_fn]
fn drop_table() -> Result<EwasmAny> {
let mut db = Db::load(None)?;
fn drop_table() -> anyhow::Result<sewup::primitives::EwasmAny> {
let mut db = sewup::rdb::Db::load(None)?;
db.drop_table::<Person>();
db.commit()?;
Ok(().into())
}

#[ewasm_fn]
fn check_tables_again() -> Result<EwasmAny> {
let mut db = Db::load(None)?;
fn check_tables_again() -> anyhow::Result<sewup::primitives::EwasmAny> {
let mut db = sewup::rdb::Db::load(None)?;
if db.table_info::<Person>().is_some() {
return Err(RDBError::SimpleError("Person table should be deleted".into()).into());
return Err(errors::RDBError::SimpleError("Person table should be deleted".into()).into());
}
Ok(().into())
}

#[ewasm_fn]
fn get_childern() -> Result<EwasmAny> {
use sewup::primitives::IntoEwasmAny;

fn get_childern() -> anyhow::Result<sewup::primitives::EwasmAny> {
let table = sewup::rdb::Db::load(None)?.table::<Person>()?;
let people = table.filter_records(&|p: &Person| p.age < 12)?;

// you can do much complicate filter logic here as you like

let protocol: person::Protocol = people.into();
Ok(EwasmAny::from(protocol))
Ok(sewup::primitives::EwasmAny::from(protocol))
}

#[ewasm_main(auto)]
fn main() -> Result<EwasmAny> {
let mut contract = Contract::new()?;
fn main() -> anyhow::Result<sewup::primitives::EwasmAny> {
use sewup_derive::ewasm_input_from;
let mut contract = sewup::primitives::Contract::new()?;

match contract.get_function_selector()? {
ewasm_fn_sig!(person::get) => ewasm_input_from!(contract move person::get),
ewasm_fn_sig!(person::create) => ewasm_input_from!(contract move person::create),
ewasm_fn_sig!(person::update) => ewasm_input_from!(contract move person::update),
ewasm_fn_sig!(person::delete) => ewasm_input_from!(contract move person::delete),
ewasm_fn_sig!(check_version_and_features) => {
check_version_and_features(0, vec![Feature::Default])
check_version_and_features(0, vec![sewup::rdb::Feature::Default])
}
ewasm_fn_sig!(get_childern) => get_childern(),
ewasm_fn_sig!(init_db_with_tables) => init_db_with_tables(),
ewasm_fn_sig!(check_tables) => check_tables(),
ewasm_fn_sig!(drop_table) => drop_table(),
ewasm_fn_sig!(check_tables_again) => check_tables_again(),
_ => return Err(RDBError::UnknownHandle.into()),
_ => return Err(errors::RDBError::UnknownHandle.into()),
}
}

Expand Down
59 changes: 35 additions & 24 deletions sewup-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,32 +60,43 @@ pub fn ewasm_main(attr: TokenStream, item: TokenStream) -> TokenStream {

let output_type = match input.sig.clone().output {
syn::ReturnType::Type(_, boxed) => match Box::into_inner(boxed) {
syn::Type::Path(syn::TypePath { path: p, .. }) => match p.segments.first() {
Some(syn::PathSegment {
arguments:
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
args: a,
syn::Type::Path(syn::TypePath { path: p, .. }) => {
let mut ok_type: Option<String> = None;
let mut segments = p.segments.clone();
while let Some(pair) = segments.pop() {
ok_type = match pair.into_value() {
syn::PathSegment {
arguments:
syn::PathArguments::AngleBracketed(
syn::AngleBracketedGenericArguments { args: a, .. },
),
..
}),
..
}) => match a.first() {
Some(a) => match a {
syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
path: p,
..
})) => {
if let Some(syn::PathSegment { ident: i, .. }) = p.segments.first() {
Some(i.to_string())
} else {
None
}
}
} => match a.first() {
Some(a) => match a {
syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
path: p,
..
})) => {
if let Some(syn::PathSegment { ident: i, .. }) =
p.segments.last()
{
Some(i.to_string())
} else {
None
}
}
_ => None,
},
_ => None,
},
_ => None,
},
_ => None,
},
_ => None,
},
};
if ok_type.is_some() {
break;
}
}
ok_type
}
_ => None,
},
_ => None,
Expand Down
7 changes: 5 additions & 2 deletions sewup/src/rdb/db.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(target_arch = "wasm32")]
use std::convert::TryInto;
use std::marker::PhantomData;
use std::ops::Range;
Expand All @@ -6,6 +7,7 @@ use crate::rdb::errors::Error;
use crate::rdb::table::Table;
use crate::rdb::traits::{Record, HEADER_SIZE};
use crate::rdb::Feature;
#[cfg(target_arch = "wasm32")]
use crate::utils::storage_index_to_addr;
use crate::{Deserialize, Serialize, SerializeTrait};

Expand Down Expand Up @@ -165,7 +167,7 @@ impl Db {
}

#[cfg(not(target_arch = "wasm32"))]
pub fn load(block_height: Option<i64>) -> Result<Self> {
pub fn load(_block_height: Option<i64>) -> Result<Self> {
unimplemented!()
}

Expand Down Expand Up @@ -271,6 +273,7 @@ impl Db {
Ok(())
}

#[cfg(any(target_arch = "wasm32", test))]
/// alloc storage space for table
pub(crate) fn alloc_table_storage(
&mut self,
Expand Down Expand Up @@ -316,7 +319,7 @@ impl Db {
}

#[cfg(not(target_arch = "wasm32"))]
fn migration_table(list: Vec<(Range<u32>, Range<u32>)>) -> Result<()> {
fn migration_table(mut _list: Vec<(Range<u32>, Range<u32>)>) -> Result<()> {
Ok(())
}

Expand Down
10 changes: 8 additions & 2 deletions sewup/src/rdb/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@ use anyhow::Result;
#[cfg(target_arch = "wasm32")]
use ewasm_api::{storage_load, storage_store};

use crate::rdb::db::{Db, TableInfo};
#[cfg(target_arch = "wasm32")]
use crate::rdb::db::Db;
use crate::rdb::db::TableInfo;
use crate::rdb::{
errors::Error,
traits::{Record, HEADER_SIZE},
};
use crate::types::{Raw, Row};
#[cfg(target_arch = "wasm32")]
use crate::types::Raw;
use crate::types::Row;
#[cfg(target_arch = "wasm32")]
use crate::utils::storage_index_to_addr;

pub struct Table<T: Record> {
Expand Down Expand Up @@ -55,6 +60,7 @@ impl<T: Record> Table<T> {
Ok(output)
}

#[allow(bare_trait_objects)]
/// Filter the records
pub fn filter_records(&self, filter: &Fn(&T) -> bool) -> Result<Vec<T>> {
let mut output: Vec<T> = Vec::new();
Expand Down
2 changes: 1 addition & 1 deletion sewup/src/rdb/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::rdb::errors::Error;
use crate::types::{Raw, Row};
use crate::types::Row;

//TODO make Header bigger for big object storage
pub const HEADER_SIZE: u32 = 1;
Expand Down

0 comments on commit f5bb497

Please sign in to comment.