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

Implement Serialize and Deserialize #13

Open
zhengyi-yang opened this issue Feb 27, 2022 · 2 comments
Open

Implement Serialize and Deserialize #13

zhengyi-yang opened this issue Feb 27, 2022 · 2 comments

Comments

@zhengyi-yang
Copy link

It's helpful to implement serde's Serialize and Deserialize for Vec32

@ryanavella
Copy link
Contributor

I agree, it would be a useful trait to expose. Some users don't want to bring in all of Serde's machinery just to use Vec32, so we will need to either hide it behind a feature-gate or mark it as an optional dependency. And we want to make sure the semver requirements aren't overly restricted.

I think this is conventionally how it is done in other popular crates' Cargo.toml:

[dependencies]
serde = { version = "1", optional = true, default-features = false }

If you want a workaround for the short term, you can use serde_derive like this:

use mediumvec::Vec32;
use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer};
use serde_derive::{Deserialize, Serialize};

fn deserialize_vec32<'de, D, T>(de: D) -> Result<Vec32<T>, D::Error>
where
    D: Deserializer<'de>,
    T: Serialize + DeserializeOwned,
{
    Ok(Vec32::from_vec(Deserialize::deserialize(de)?))
}

fn serialize_vec32<S, T>(v: &Vec32<T>, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: Serialize,
{
    s.collect_seq(v)
}

#[derive(Deserialize, Serialize)]
struct Foo<T>
where
    T: Serialize + DeserializeOwned,
{
    #[serde(deserialize_with = "deserialize_vec32")]
    #[serde(serialize_with = "serialize_vec32")]
    v: Vec32<T>,
}

@zhengyi-yang
Copy link
Author

Thanks @ryanavella !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants