serde support

pull/1/head
Shad Amethyst 2 years ago
parent f38cb4706a
commit 4ebd5fd666
Signed by: amethyst
GPG Key ID: D970C8DD1D6DEE36

@ -1,6 +1,6 @@
[package]
name = "veccell"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
authors = [ "Shad Amethyst <adrien.burgun@orange.fr>" ]
description = "Provides VecCell, a variant of Vec with interior mutability."
@ -10,3 +10,10 @@ keywords = ["vec", "refcell", "interior-mutability"]
categories = ["rust-patterns"]
[dependencies]
serde = { version = "1", optional = true }
[dev-dependencies]
serde_json = "1.0"
[features]
serde = ["dep:serde"]

@ -779,6 +779,28 @@ impl<T> From<VecCell<T>> for Vec<T> {
}
}
#[cfg(feature = "serde")]
impl<T: serde::Serialize> serde::Serialize for VecCell<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer
{
let range = self.borrow_range(..).expect("Cannot borrow immutably VecCell: already borrowed mutably.");
(*range).serialize(serializer)
}
}
#[cfg(feature = "serde")]
impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for VecCell<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>
{
let vec: Vec<T> = Vec::deserialize(deserializer)?;
Ok(Self::from(vec))
}
}
#[cfg(test)]
mod test;

@ -296,3 +296,26 @@ fn test_try_map() {
assert!(borrow.is_ok());
assert_eq!(borrow.unwrap(), -6);
}
#[cfg(feature = "serde")]
#[test]
fn test_serde() {
let mut vec: VecCell<usize> = VecCell::new();
vec.push(2);
vec.push(5);
let range = vec.borrow_range(..);
let s: String = serde_json::to_string(&vec).unwrap();
assert_eq!(serde_json::from_str::<Vec<usize>>(&s).unwrap(), vec![2, 5]);
let new_vec: VecCell<usize> = serde_json::from_str(&s).unwrap();
assert_eq!(new_vec.len(), 2);
assert_eq!(new_vec.borrows(), 0);
drop(range);
assert!(new_vec.mut_borrow().is_none());
assert_eq!(new_vec, vec![2, 5]);
}

Loading…
Cancel
Save