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

feat: BorshSerialize/BoshDeserialize/BorshSchema for Cell/RefCell #265

Merged
merged 5 commits into from
Feb 27, 2024
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
19 changes: 19 additions & 0 deletions borsh/src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,25 @@ impl<T: ?Sized> BorshDeserialize for PhantomData<T> {
Ok(PhantomData)
}
}

impl<T> BorshDeserialize for core::cell::Cell<T>
where
T: BorshDeserialize + Copy,
{
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> {
<T as BorshDeserialize>::deserialize_reader(reader).map(core::cell::Cell::new)
}
}

impl<T> BorshDeserialize for core::cell::RefCell<T>
where
T: BorshDeserialize,
{
fn deserialize_reader<R: Read>(reader: &mut R) -> Result<Self> {
<T as BorshDeserialize>::deserialize_reader(reader).map(core::cell::RefCell::new)
}
}

/// Deserializes an object from a slice of bytes.
/// # Example
/// ```
Expand Down
26 changes: 26 additions & 0 deletions borsh/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,32 @@ where
T::declaration()
}
}

impl<T> BorshSchema for core::cell::Cell<T>
where
T: BorshSchema + Copy,
{
fn add_definitions_recursively(definitions: &mut BTreeMap<Declaration, Definition>) {
T::add_definitions_recursively(definitions);
}

fn declaration() -> Declaration {
T::declaration()
}
}

impl<T> BorshSchema for core::cell::RefCell<T>
where
T: BorshSchema + Sized,
{
fn add_definitions_recursively(definitions: &mut BTreeMap<Declaration, Definition>) {
T::add_definitions_recursively(definitions);
}

fn declaration() -> Declaration {
T::declaration()
}
}
/// Module is available if borsh is built with `features = ["rc"]`.
#[cfg(feature = "rc")]
pub mod rc {
Expand Down
21 changes: 21 additions & 0 deletions borsh/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,3 +637,24 @@ impl<T: ?Sized> BorshSerialize for PhantomData<T> {
Ok(())
}
}

impl<T> BorshSerialize for core::cell::Cell<T>
where
T: BorshSerialize + Copy,
{
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
<T as BorshSerialize>::serialize(&self.get(), writer)
}
}

impl<T> BorshSerialize for core::cell::RefCell<T>
where
T: BorshSerialize + Sized,
{
fn serialize<W: Write>(&self, writer: &mut W) -> Result<()> {
match self.try_borrow() {
Ok(ref value) => value.serialize(writer),
Err(_) => Err(Error::new(ErrorKind::Other, "already mutably borrowed")),
}
}
}
36 changes: 36 additions & 0 deletions borsh/tests/common_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,39 @@ macro_rules! map_wrong_order_test [
}
]
];

#[allow(unused)]
macro_rules! schema_map(
() => { BTreeMap::new() };
{ $($key:expr => $value:expr),+ } => {
{
let mut m = BTreeMap::new();
$(
m.insert($key.to_string(), $value);
)+
m
}
};
);

#[allow(unused)]
#[cfg(feature = "unstable__schema")]
pub mod schema_imports {
#[cfg(feature = "std")]
pub use std::collections::BTreeMap;

#[cfg(not(feature = "std"))]
extern crate alloc;
#[cfg(not(feature = "std"))]
pub use alloc::{
boxed::Box,
collections::BTreeMap,
format,
string::{String, ToString},
vec,
vec::Vec,
};

pub use borsh::schema::{BorshSchemaContainer, Definition, Fields};
pub use borsh::{schema_container_of, BorshSchema};
}
28 changes: 9 additions & 19 deletions borsh/tests/test_ascii_strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,37 +84,27 @@ mod de_errors {
}
}

#[macro_use]
mod common_macro;

#[cfg(feature = "unstable__schema")]
mod schema {
use alloc::{collections::BTreeMap, string::ToString};
use borsh::schema::{BorshSchema, Definition};
macro_rules! map(
() => { BTreeMap::new() };
{ $($key:expr => $value:expr),+ } => {
{
let mut m = BTreeMap::new();
$(
m.insert($key.to_string(), $value);
)+
m
}
};
);
use super::common_macro::schema_imports::*;

#[test]
fn test_ascii_strings() {
assert_eq!("AsciiString", ascii::AsciiStr::declaration());
assert_eq!("AsciiString", ascii::AsciiString::declaration());
assert_eq!("AsciiChar", ascii::AsciiChar::declaration());

let want_char = map! {
let want_char = schema_map! {
"AsciiChar" => Definition::Primitive(1)
};
let mut actual_defs = map!();
let mut actual_defs = schema_map!();
ascii::AsciiChar::add_definitions_recursively(&mut actual_defs);
assert_eq!(want_char, actual_defs);

let want = map! {
let want = schema_map! {
"AsciiString" => Definition::Sequence {
length_width: Definition::DEFAULT_LENGTH_WIDTH,
length_range: Definition::DEFAULT_LENGTH_RANGE,
Expand All @@ -123,11 +113,11 @@ mod schema {
"AsciiChar" => Definition::Primitive(1)
};

let mut actual_defs = map!();
let mut actual_defs = schema_map!();
ascii::AsciiStr::add_definitions_recursively(&mut actual_defs);
assert_eq!(want, actual_defs);

let mut actual_defs = map!();
let mut actual_defs = schema_map!();
ascii::AsciiString::add_definitions_recursively(&mut actual_defs);
assert_eq!(want, actual_defs);
}
Expand Down
92 changes: 92 additions & 0 deletions borsh/tests/test_cells.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;
use alloc::string::{String, ToString};

#[test]
fn test_cell_roundtrip() {
let cell = core::cell::Cell::new(42u32);

let out = borsh::to_vec(&cell).unwrap();

let cell_round: core::cell::Cell<u32> = borsh::from_slice(&out).unwrap();

assert_eq!(cell, cell_round);
}

#[test]
fn test_ref_cell_roundtrip() {
let rcell = core::cell::RefCell::new("str".to_string());

let out = borsh::to_vec(&rcell).unwrap();

let rcell_round: core::cell::RefCell<String> = borsh::from_slice(&out).unwrap();

assert_eq!(rcell, rcell_round);
}

mod de_errors {

use alloc::string::ToString;

#[test]
fn test_ref_cell_try_borrow_error() {
let rcell = core::cell::RefCell::new("str");

let _active_borrow = rcell.try_borrow_mut().unwrap();

assert_eq!(
borsh::to_vec(&rcell).unwrap_err().to_string(),
"already mutably borrowed"
);
}
}

#[macro_use]
mod common_macro;

#[cfg(feature = "unstable__schema")]
mod schema {

use super::common_macro::schema_imports::*;
fn common_map_i32() -> BTreeMap<String, Definition> {
schema_map! {

"i32" => Definition::Primitive(4)
}
}

fn common_map_slice_i32() -> BTreeMap<String, Definition> {
schema_map! {
"Vec<i32>" => Definition::Sequence {
length_width: Definition::DEFAULT_LENGTH_WIDTH,
length_range: Definition::DEFAULT_LENGTH_RANGE,
elements: "i32".to_string()
},
"i32" => Definition::Primitive(4)
}
}

#[test]
fn test_cell() {
assert_eq!("i32", <core::cell::Cell<i32> as BorshSchema>::declaration());

let mut actual_defs = schema_map!();
<core::cell::Cell<i32> as BorshSchema>::add_definitions_recursively(&mut actual_defs);
assert_eq!(common_map_i32(), actual_defs);
}

#[test]
fn test_ref_cell_vec() {
assert_eq!(
"Vec<i32>",
<core::cell::RefCell<Vec<i32>> as BorshSchema>::declaration()
);

let mut actual_defs = schema_map!();
<core::cell::RefCell<Vec<i32>> as BorshSchema>::add_definitions_recursively(
&mut actual_defs,
);
assert_eq!(common_map_slice_i32(), actual_defs);
}
}
31 changes: 6 additions & 25 deletions borsh/tests/test_enum_discriminants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,31 +185,12 @@ fn test_discriminant_serde() {
}
}

#[macro_use]
mod common_macro;

#[cfg(feature = "unstable__schema")]
mod schema {
#[cfg(not(feature = "std"))]
use alloc::{collections::BTreeMap, string::ToString, vec};

#[cfg(feature = "std")]
use std::collections::BTreeMap;

macro_rules! map(
() => { BTreeMap::new() };
{ $($key:expr => $value:expr),+ } => {
{
let mut m = BTreeMap::new();
$(
m.insert($key.to_string(), $value);
)+
m
}
};
);

use borsh::{
schema::{Definition, Fields},
BorshSchema,
};
use super::common_macro::schema_imports::*;

#[allow(unused)]
#[derive(BorshSchema)]
Expand All @@ -230,7 +211,7 @@ mod schema {
let mut defs = Default::default();
XY::add_definitions_recursively(&mut defs);
assert_eq!(
map! {
schema_map! {
"XY" => Definition::Enum {
tag_width: 1,
variants: vec![
Expand Down Expand Up @@ -282,7 +263,7 @@ mod schema {
let mut defs = Default::default();
XYNoDiscriminant::add_definitions_recursively(&mut defs);
assert_eq!(
map! {
schema_map! {
"XYNoDiscriminant" => Definition::Enum {
tag_width: 1,
variants: vec![
Expand Down
Loading
Loading