marshallpierce / base64-serde

Integration between rust-base64 and serde

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Write a Visitor for deserialization

dtolnay opened this issue · comments

Not every data format is able to deserialize &str. It would be better to write a Visitor impl with a visit_str method that decodes the base64 string. The difference is visit_str receives a transient string while deserializing to &str requires a borrowed string. Check out https://serde.rs/lifetimes.html for the difference.

Also a Visitor allows you to give a more useful invalid type message. Like if the user tries decoding base64 from a boolean, your message can say expected a base64 string instead of expected a string.

It's not clear to me how to integrate a Visitor implementation with the rest of the moving parts.

https://serde.rs/data-model.html has:

When deserializing a data structure from some format, the Deserialize implementation for the data structure is responsible for mapping the data structure into the Serde data model by passing to the Deserializer a Visitor implementation that can receive the various types of the data model

But how do I do that if Deserialize is being derived for the struct to serialize?

Your job is to deserialize Vec<u8>, not the struct containing it. Check out the example code in https://serde.rs/stream-array.html.