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

Consider adding new-type marker types to simplify customization #224

Open
chmp opened this issue Aug 22, 2024 · 1 comment
Open

Consider adding new-type marker types to simplify customization #224

chmp opened this issue Aug 22, 2024 · 1 comment

Comments

@chmp
Copy link
Owner

chmp commented Aug 22, 2024

Serde does not allow to convey any extra metadata during serialization. Using special new type structs, it could be possible to work around it. Newtype structs can be serialized by an extra call to serialize_newtype_struct, this way it would be possible to inject additional metadata via the typename.

Possible uses:

  • Bool8
  • Datetimes

While the newtype could be ignored in array serialization and deserialization, it could be used during schema tracing.

This idea is motivated by this comment.

Possible API

#[derive(Serialize, Deserialize)]
struct S {
   #[serde(with = "serde_arrow::experimental::bool8")]
  value: bool,
}

// alternative
use serde_arrow::experimental::Bool8;

#[derive(Serialize, Deserialize)]
struct S {
   value: Bool8,
}

Mock Impl for Marker Type

// serde_arrow/src/experimental/bool8.rs

const BOOL8_TAG: str = "serde_arrow::experimental::bool8";

pub struct Bool8(pub bool);

impl Serialize for Bool8 {
  fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    serializer.serialize_newtype_struct(BOOL8_TAG, &self.0)
  }
}

impl<'de> Deserialize<'de> for Bool8 {
  fn deserialize<S: Deserializer<'de>>(deserializer: D) {
     deserializer.deserialize_newtype_struct(BOOL8_TAG, visitor)
  } 
}

pub fn serialize<S: Serializer>(value: &bool, serializer: S) -> Result<S::Ok, S::Error> {
  Bool8(*value).serialize(S)
}

pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D> -> Result<bool, D::Error> {
  Ok(Bool8::deserialize(deserializer)?.0)
}
@v1gnesh
Copy link

v1gnesh commented Aug 23, 2024

The alternate API is nicer, as attr annotations over fields can get "noisy" very quickly. Newtype hides it away as a one-time def.
Thank you for thinking through this!

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