Skip to content
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

Add seriailize and deserialize usize #9

Merged
merged 6 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion borsh/src/de/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::{
convert::TryInto,
convert::{TryFrom, TryInto},
hash::Hash,
mem::{forget, size_of},
};
Expand All @@ -18,6 +18,7 @@ mod hint;

const ERROR_NOT_ALL_BYTES_READ: &str = "Not all bytes read";
const ERROR_UNEXPECTED_LENGTH_OF_INPUT: &str = "Unexpected length of input";
const ERROR_OVERFLOW_ON_MACHINE_WITH_32_BIT_USIZE: &str = "Overflow on machine with 32 bit usize";

/// A data-structure that can be de-serialized from binary format by NBOR.
pub trait BorshDeserialize: Sized {
Expand Down Expand Up @@ -95,6 +96,19 @@ impl_for_integer!(u32);
impl_for_integer!(u64);
impl_for_integer!(u128);

impl BorshDeserialize for usize {
fn deserialize(buf: &mut &[u8]) -> Result<Self> {
let u: u64 = BorshDeserialize::deserialize(buf)?;
let u = usize::try_from(u).map_err(|_| {
Error::new(
ErrorKind::InvalidInput,
ERROR_OVERFLOW_ON_MACHINE_WITH_32_BIT_USIZE,
)
})?;
Ok(u)
}
}

// Note NaNs have a portability issue. Specifically, signalling NaNs on MIPS are quiet NaNs on x86,
// and vice-versa. We disallow NaNs to avoid this issue.
macro_rules! impl_for_float {
Expand Down
6 changes: 6 additions & 0 deletions borsh/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ impl_for_integer!(u32);
impl_for_integer!(u64);
impl_for_integer!(u128);

impl BorshSerialize for usize {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
BorshSerialize::serialize(&(*self as u64), writer)
}
}

// Note NaNs have a portability issue. Specifically, signalling NaNs on MIPS are quiet NaNs on x86,
// and vice-versa. We disallow NaNs to avoid this issue.
macro_rules! impl_for_float {
Expand Down