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 instances for std Duration/SystemTime #267

Closed
wants to merge 1 commit into from
Closed
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
22 changes: 22 additions & 0 deletions borsh/src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,28 @@ where
}
}

#[cfg(feature = "std")]
impl BorshDeserialize for core::time::Duration {
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> {
let secs = <u64 as BorshDeserialize>::deserialize_reader(reader)?;
let nanos = <u32 as BorshDeserialize>::deserialize_reader(reader)?;
Ok(core::time::Duration::new(secs, nanos))
}
}

#[cfg(feature = "std")]
impl BorshDeserialize for std::time::SystemTime {
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> {
let duration_since_epoch = <core::time::Duration>::deserialize_reader(reader)?;
std::time::UNIX_EPOCH
.checked_add(duration_since_epoch)
.ok_or(Error::new(
ErrorKind::InvalidData,
"overflow deserializing SystemTime",
))
}
}

impl<T, const N: usize> BorshDeserialize for [T; N]
where
T: BorshDeserialize,
Expand Down
25 changes: 25 additions & 0 deletions borsh/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,31 @@ impl<T: BorshSerialize + ?Sized> BorshSerialize for Box<T> {
}
}

#[cfg(feature = "std")]
impl BorshSerialize for core::time::Duration {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
<u64 as BorshSerialize>::serialize(&self.as_secs(), writer)?;
<u32 as BorshSerialize>::serialize(&self.subsec_nanos(), writer)
}
}

#[cfg(feature = "std")]
impl BorshSerialize for std::time::SystemTime {
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
let duration_since_epoch = match self.duration_since(std::time::UNIX_EPOCH) {
Ok(duration_since_epoch) => duration_since_epoch,
Err(_) => {
return Err(Error::new(
ErrorKind::InvalidData,
"SystemTime must be later than UNIX_EPOCH",
))
}
};

<core::time::Duration>::serialize(&duration_since_epoch, writer)
}
}

impl<T, const N: usize> BorshSerialize for [T; N]
where
T: BorshSerialize,
Expand Down
Loading