Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Serialize attribute to type from third-party lib

I'm trying to add serialization functionality to one of my structs in Rust. It's an event for a 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 struct uses two different types from third-parties, the Uuid is from https://github.com/rust-lang/uuid and the DateTime from https://github.com/lifthrasiir/rust-chrono.

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

So the questions are: Is there a way to add derives to third-party structs without touching the code of the libs itself? If not, what is the best way to add serialization functionality in a situation like this?

like image 418
0kp Avatar asked Jun 12 '15 00:06

0kp


1 Answers

First of all, you don't want to use Encodable and Decodable; you want to use RustcEncodable and RustcDecodable from the rustc-serialize crate.

Secondly, you can't. If you didn't write the type in question or the trait in question, you just can't: this is a deliberate guarantee on the part of the compiler. (See also "coherence".)

There are two things you can do in this situation:

  1. Implement the traits manually. Sometimes, derive doesn't work, so you have to write the trait implementation by hand. In this case, it would give you the opportunity to just manually implement encoding/decoding for the unsupported types directly.

  2. Wrap the unsupported types. This means doing something like struct UuidWrap(pub Uuid);. This gives you a new type that you wrote, which means you can... well, do #1, but do it for a smaller amount of code. Of course, now you have to wrap and unwrap the UUID, which is a bit of a pain.

like image 165
DK. Avatar answered Oct 04 '22 15:10

DK.