Skip to content

Instantly share code, notes, and snippets.

@killercup
Created June 10, 2018 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killercup/f7ce24551a64299a138788909eeaceaa to your computer and use it in GitHub Desktop.
Save killercup/f7ce24551a64299a138788909eeaceaa to your computer and use it in GitHub Desktop.

Ideas for versioned serde struct

Goals

  • version external APIs
    • read (write?) data of older versions
  • be agnostic over protocol (but we'll actually use JSON in our examples)

First draft

{
  "version": 2,
  "bla": "foo",
  "blub": 5
}

And inspired by serde issue 1137:

#[derive(...)]
struct JsonStuff {
  bla: String,
  #[serde(added_in = 2)]
  blub: u32
}

How to implement?

Fork serde or something to add attrs?

lolnope

Ugly hack

generate code like

mod v1 {
    #[derive(Deserizalize)]
    struct JsonStuff {
        bla: String,
    }
}
mod v2 {
    #[derive(Deserizalize)]
    struct JsonStuff {
        bla: String,
        blub: u32
    }
}

#[derive(Deserizalize)]
enum JsonStuff {
    #[serde(rename = "1")]
    V1(v1::JsonStuff),
    #[serde(rename = "2")]
    V2(v2::JsonStuff),
}

Inspired by David on reddit and sozu issue 240.

Weird other ideas

  • Read (\w+).schema.json files and generate Rust structs
  • Read (\w+).v(\d+).schema.json files and generate versioned Rust structs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment