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

How to rename inner types when encoding/decoding foreign structs using serde? #667

Open
YizhePKU opened this issue Dec 14, 2024 · 1 comment
Labels

Comments

@YizhePKU
Copy link

YizhePKU commented Dec 14, 2024

Suppose I have a Rust struct like this:

#[derive(Serialize, Deserialize)]
#[serde(rename = "Elixir.MyPackage.Event")]
struct Event {
    name: String,
    duration: std::time::Duration,
}

And we create an instance like this:

Event { name: "foo".to_string(), duration: std::time::Duration::from_secs(10) }

Currently, rustler will convert it to this:

%{
  :__struct__ => MyPackage.Event,
  :name => "foo",
  :duration => %{:__struct__ => "Duration", "nanos" => 0, "secs" => 10}
}

Is there a way to map std::time::Duration to Elixir.MyPackage.Duration instead?

@YizhePKU
Copy link
Author

YizhePKU commented Dec 14, 2024

I got it working with a simple hack in src/serde/ser.rs:

fn serialize_struct(
    self,
    name: &'static str,
    len: usize,
) -> Result<Self::SerializeStruct, Self::Error> {
    let name = format!("Elixir.MyPackage.{name}"); // <---- SUPER HACK
    let name_term = util::str_to_term(&self.env, &name).or(Err(Error::InvalidStructName))?;
    Ok(MapSerializer::new(self, Some(len), Some(name_term)))
}

Do the same for src/serde/de.rs:

#[inline]
fn deserialize_struct<V>(
    self,
    name: &'static str,
    _fields: &'static [&'static str],
    visitor: V,
) -> Result<V::Value, Self::Error>
where
    V: Visitor<'de>,
{
    let name = format!("Elixir.Temporex.Core.{name}"); // <---- SUPER HACK
    let struct_name_term = util::validate_struct(&self.term, Some(&name))?;
    let iter = MapIterator::new(self.term).ok_or(Error::ExpectedStruct)?;
    visitor.visit_map(MapDeserializer::new(iter, Some(struct_name_term)))
}

With this hack, I also don't need #[serde(rename="...")] anymore. Perhaps it's useful as a general feature?

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

No branches or pull requests

2 participants