Add Serialize attribute for input from a third-party library

I am trying to add serialization functions to one of my structures in Rust. This event is for the calendar and looks like this:

#[derive(PartialEq, Clone, Encodable, Decodable)] pub struct Event { pub id: Uuid, pub name: String, pub desc: String, pub location: String, pub start: DateTime<Local>, pub end: DateTime<Local>, } 

The structure uses two different types from third parties, Uuid from https://github.com/rust-lang/uuid and DateTime from https://github.com/lifthrasiir/rust-chrono .

If I try to build a project, the compiler complains that encode not found for Uuid and DateTime , because they both do not output Encodable and Decodeable from serialize crate.

So, the questions: Is there a way to add output to third-party structures without touching the libs code itself? If not, what is the best way to add serialization functions in this situation?

+4
source share
2 answers

First of all, you do not want to use Encodable and Decodable ; you want to use RustcEncodable and RustcDecodable from the rustc-serialize box.

Secondly, you cannot. If you did not specify the type in question or this symptom, you simply cannot: this is an intentional guarantee on the part of the compiler. (See also "Consistency.")

In this situation, you can do two things:

  • Implement traits manually. Sometimes derive does not work, so you need to write the implementation of the attributes manually. In this case, this will give you the opportunity to simply manually implement encoding / decoding for unsupported types directly.

  • Wrap unsupported types. This means something like struct UuidWrap(pub Uuid); . This gives you the new type you wrote, which means you can ... well, do # 1, but do it for less code. Of course, now you need to wrap and deploy the UUID, which is a little painful.

+5
source

I found this question when I was looking for a solution for the same problem. Chrono has included support for rustc-serialize. You should enable it by adding dependecy as follows.

 [dependencies.chrone] version = "*" features = ["rustc-serialize"] 

I found out about this from ker's answer to my question , I hope this helps you.

+1
source

All Articles