From 0945e25aff204b0f316f0e9b3aa8ac6ee6f86600 Mon Sep 17 00:00:00 2001 From: Mateusz Kowalczyk Date: Mon, 4 Dec 2023 13:26:09 +0900 Subject: [PATCH] Optional support for borsh serialisation --- Cargo.toml | 7 ++++++- src/lib.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 96a8623..0ecdedb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ exclude = ["/bors.toml", "/ci/*", "/.github/*"] edition = "2018" [package.metadata.docs.rs] -features = ["std", "num-bigint-std", "serde"] +features = ["std", "num-bigint-std", "serde", "borsh"] [dependencies] @@ -38,6 +38,11 @@ optional = true version = "1.0.0" default-features = false +[dependencies.borsh] +optional = true +version = "1.2.0" +default-features = false + [features] default = ["num-bigint-std", "std"] std = ["num-integer/std", "num-traits/std"] diff --git a/src/lib.rs b/src/lib.rs index 8992406..78413d7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1166,6 +1166,36 @@ where } } +#[cfg(feature = "borsh")] +impl borsh::BorshSerialize for Ratio +where + T: borsh::BorshSerialize, +{ + fn serialize(&self, writer: &mut W) -> borsh::io::Result<()> { + ::serialize(self.numer(), writer)?; + ::serialize(self.denom(), writer) + } +} + +#[cfg(feature = "borsh")] +impl borsh::BorshDeserialize for Ratio +where + T: borsh::BorshDeserialize + num_traits::Zero, +{ + fn deserialize_reader(reader: &mut R) -> borsh::io::Result { + let numer = ::deserialize_reader(reader)?; + let denom = ::deserialize_reader(reader)?; + if denom.is_zero() { + Err(borsh::io::Error::new( + borsh::io::ErrorKind::InvalidData, + "expected a ratio with non-zero denominator", + )) + } else { + Ok(Ratio::new_raw(numer, denom)) + } + } +} + // FIXME: Bubble up specific errors #[derive(Copy, Clone, Debug, PartialEq)] pub struct ParseRatioError {