Skip to content

Commit

Permalink
feat: impl BorshSchema for HashSet (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
tzemanovic authored Mar 18, 2022
1 parent 8ea295e commit 7325a0a
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion borsh/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use crate as borsh; // For `#[derive(BorshSerialize, BorshDeserialize)]`.
use crate::maybestd::{
boxed::Box,
collections::{hash_map::Entry, HashMap},
collections::{hash_map::Entry, HashMap, HashSet},
format,
string::{String, ToString},
vec,
Expand Down Expand Up @@ -282,6 +282,23 @@ where
}
}

impl<T> BorshSchema for HashSet<T>
where
T: BorshSchema,
{
fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
let definition = Definition::Sequence {
elements: <T>::declaration(),
};
Self::add_definition(Self::declaration(), definition, definitions);
<T>::add_definitions_recursively(definitions);
}

fn declaration() -> Declaration {
format!(r#"HashSet<{}>"#, T::declaration())
}
}

macro_rules! impl_tuple {
($($name:ident),+) => {
impl<$($name),+> BorshSchema for ($($name),+)
Expand Down Expand Up @@ -466,6 +483,20 @@ mod tests {
);
}

#[test]
fn simple_set() {
let actual_name = HashSet::<String>::declaration();
let mut actual_defs = map!();
HashSet::<String>::add_definitions_recursively(&mut actual_defs);
assert_eq!("HashSet<string>", actual_name);
assert_eq!(
map! {
"HashSet<string>" => Definition::Sequence { elements: "string".to_string()}
},
actual_defs
);
}

#[test]
fn simple_array() {
let actual_name = <[u64; 32]>::declaration();
Expand Down

0 comments on commit 7325a0a

Please sign in to comment.