-
Notifications
You must be signed in to change notification settings - Fork 169
Add borsh
serialization support
#313
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ae38b91
Add `borsh` dep to Cargo manifest
sug0 0804a16
Implement `borsh` serialization routines
sug0 c610e14
Add `borsh` serialization roundtrip tests
sug0 6ad3e42
Include `borsh` in CI workflow
sug0 b8b1f52
ci: reduce features on MSRV
cuviper 32793f1
Don't require BuildHasher in BorshSerialize
cuviper b81a4d2
Use S for the BuildHasher parameter
cuviper File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
#![cfg_attr(docsrs, doc(cfg(feature = "borsh")))] | ||
|
||
use alloc::vec::Vec; | ||
use core::hash::BuildHasher; | ||
use core::hash::Hash; | ||
use core::iter::ExactSizeIterator; | ||
use core::mem::size_of; | ||
|
||
use borsh::error::ERROR_ZST_FORBIDDEN; | ||
use borsh::io::{Error, ErrorKind, Read, Result, Write}; | ||
use borsh::{BorshDeserialize, BorshSerialize}; | ||
|
||
use crate::map::IndexMap; | ||
use crate::set::IndexSet; | ||
|
||
impl<K, V, S> BorshSerialize for IndexMap<K, V, S> | ||
where | ||
K: BorshSerialize, | ||
V: BorshSerialize, | ||
{ | ||
#[inline] | ||
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> { | ||
check_zst::<K>()?; | ||
|
||
let iterator = self.iter(); | ||
|
||
u32::try_from(iterator.len()) | ||
.map_err(|_| ErrorKind::InvalidData)? | ||
.serialize(writer)?; | ||
|
||
for (key, value) in iterator { | ||
key.serialize(writer)?; | ||
value.serialize(writer)?; | ||
} | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
impl<K, V, S> BorshDeserialize for IndexMap<K, V, S> | ||
where | ||
K: BorshDeserialize + Eq + Hash, | ||
V: BorshDeserialize, | ||
S: BuildHasher + Default, | ||
{ | ||
#[inline] | ||
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> { | ||
check_zst::<K>()?; | ||
let vec = <Vec<(K, V)>>::deserialize_reader(reader)?; | ||
Ok(vec.into_iter().collect::<IndexMap<K, V, S>>()) | ||
} | ||
} | ||
|
||
impl<T, S> BorshSerialize for IndexSet<T, S> | ||
where | ||
T: BorshSerialize, | ||
{ | ||
#[inline] | ||
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> { | ||
check_zst::<T>()?; | ||
|
||
let iterator = self.iter(); | ||
|
||
u32::try_from(iterator.len()) | ||
.map_err(|_| ErrorKind::InvalidData)? | ||
.serialize(writer)?; | ||
|
||
for item in iterator { | ||
item.serialize(writer)?; | ||
} | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
impl<T, S> BorshDeserialize for IndexSet<T, S> | ||
where | ||
T: BorshDeserialize + Eq + Hash, | ||
S: BuildHasher + Default, | ||
{ | ||
#[inline] | ||
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> { | ||
check_zst::<T>()?; | ||
let vec = <Vec<T>>::deserialize_reader(reader)?; | ||
Ok(vec.into_iter().collect::<IndexSet<T, S>>()) | ||
} | ||
} | ||
|
||
fn check_zst<T>() -> Result<()> { | ||
if size_of::<T>() == 0 { | ||
return Err(Error::new(ErrorKind::InvalidData, ERROR_ZST_FORBIDDEN)); | ||
} | ||
Ok(()) | ||
} | ||
|
||
#[cfg(test)] | ||
sug0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
mod borsh_tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn map_borsh_roundtrip() { | ||
let original_map: IndexMap<i32, i32> = { | ||
let mut map = IndexMap::new(); | ||
map.insert(1, 2); | ||
map.insert(3, 4); | ||
map.insert(5, 6); | ||
map | ||
}; | ||
let serialized_map = borsh::to_vec(&original_map).unwrap(); | ||
let deserialized_map: IndexMap<i32, i32> = | ||
BorshDeserialize::try_from_slice(&serialized_map).unwrap(); | ||
assert_eq!(original_map, deserialized_map); | ||
} | ||
|
||
#[test] | ||
fn set_borsh_roundtrip() { | ||
let original_map: IndexSet<i32> = [1, 2, 3, 4, 5, 6].into_iter().collect(); | ||
let serialized_map = borsh::to_vec(&original_map).unwrap(); | ||
let deserialized_map: IndexSet<i32> = | ||
BorshDeserialize::try_from_slice(&serialized_map).unwrap(); | ||
assert_eq!(original_map, deserialized_map); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.