From f722258ef0f8924830228ec89b96486c41ff21b3 Mon Sep 17 00:00:00 2001 From: Christian Kamm Date: Wed, 17 Nov 2021 14:19:00 +0100 Subject: [PATCH] Add support for borsh serialization --- Cargo.toml | 4 ++++ src/borshize.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 4 +++- 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/borshize.rs diff --git a/Cargo.toml b/Cargo.toml index dff8a90..0ce5948 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,5 +54,9 @@ version = "1.0.60" default-features = false optional = true +[dependencies.borsh] +version = "0.9.1" +optional = true + [package.metadata.docs.rs] features = ["arbitrary", "num-traits", "serde", "std"] diff --git a/src/borshize.rs b/src/borshize.rs new file mode 100644 index 0000000..2e10bd6 --- /dev/null +++ b/src/borshize.rs @@ -0,0 +1,50 @@ +// Copyright © 2018–2021 Trevor Spiteri + +// This library is free software: you can redistribute it and/or +// modify it under the terms of either +// +// * the Apache License, Version 2.0 or +// * the MIT License +// +// at your option. +// +// You should have recieved copies of the Apache License and the MIT +// License along with the library. If not, see +// and +// . + +use crate::{ + FixedI128, FixedI16, FixedI32, FixedI64, FixedI8, FixedU128, FixedU16, FixedU32, FixedU64, + FixedU8, +}; +use borsh::maybestd::io::{Result, Write}; +use borsh::{BorshDeserialize, BorshSerialize}; + +macro_rules! borsh_fixed { + ($Fixed:ident is $TBits:ident) => { + impl BorshSerialize for $Fixed { + #[inline] + fn serialize(&self, writer: &mut W) -> Result<()> { + <$TBits as BorshSerialize>::serialize(&self.bits, writer) + } + } + + impl BorshDeserialize for $Fixed { + #[inline] + fn deserialize(buf: &mut &[u8]) -> Result { + <$TBits as BorshDeserialize>::deserialize(buf).map($Fixed::from_bits) + } + } + }; +} + +borsh_fixed! { FixedI8 is i8 } +borsh_fixed! { FixedI16 is i16 } +borsh_fixed! { FixedI32 is i32 } +borsh_fixed! { FixedI64 is i64 } +borsh_fixed! { FixedI128 is i128 } +borsh_fixed! { FixedU8 is u8 } +borsh_fixed! { FixedU16 is u16 } +borsh_fixed! { FixedU32 is u32 } +borsh_fixed! { FixedU64 is u64 } +borsh_fixed! { FixedU128 is u128 } diff --git a/src/lib.rs b/src/lib.rs index 75023f2..13af69a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -302,6 +302,8 @@ extern crate std; mod macros; mod arith; +#[cfg(feature = "borsh")] +mod borshize; mod cast; mod cmp; pub mod consts; @@ -493,7 +495,7 @@ assert_eq!(two_point_75.to_string(), \"2.8\"); "; #[repr(transparent)] pub struct $Fixed { - bits: $Inner, + pub(crate) bits: $Inner, phantom: PhantomData, } } -- GitLab