#deserialize #proc-macro #serde #macro #serde-deserialize

macro serde-ordered

A procedural macro for deserializing ordered arrays into keyed structs using Serde

2 unstable releases

Uses new Rust 2024

new 0.2.0 Mar 30, 2025
0.1.0 Mar 28, 2025

#2318 in Parser implementations

Download history 64/week @ 2025-03-23

64 downloads per month

MIT/Apache

11KB
126 lines

serde-ordered

A procedural macro for deserializing un-keyed, ordered arrays into keyed structs using Serde.

Features

  • Deserialize ordered arrays into structs with named fields.
  • Supports optional fields and nested structures.
  • Works with JSON, MessagePack, and other Serde-compatible formats.

Motivation

Working with large, un-keyed array structures can be inconvenient. If a struct has upwards of 50 fields that include large nested structs, making sure every field is present can be tedious and slow down development time. Often times, typing out all 50 fields in not warranted, especially if the plan is to only leverage a small subset of those fields. serde-ordered lets you create a slimmed down version of the parent class, placing orders on the fields of interest

Here we have a parent struct Foo

#[derive(Deserialize, Serialize)]
struct Foo {
    pub buz: i32,
    pub biz: Option<String>,
    pub bar: Bar,
    pub bop: u64
}

#[derive(Deserialize, Serialize)]
struct Bar {
    pub buf: i32,
    pub bif: String
}

If we tried to deserialize Foo into a slimmed down struct like SlimFoo

#[derive(Deserialize, Serialize)]
struct SlimFoo {
    pub biz: Option<String>,
    pub bar: SlimBar,
}

#[derive(Deserialize, Serialize)]
struct SlimBar {
    pub bif: String
}

against an un-keyed MessagePack message like [1, null, [100, "100"], 1] it would error due to a length mismatchm, requring developers to ensure they have typed out every field. This could also introduce problems if an upstream provider changed the struct without notifying the consumer which would cause a length mismatch error, Hense serde-ordered

Installation

Add this to your Cargo.toml: the proc macro within serde-ordered and the dependency serde-value

[dependencies]
serde-ordered = "0.1"
serde-value = "0.7.0"

Usage

Simply derive the DeserializeOrdered trait on the struct and tag each field of interest with an index/order

#[derive(DeserializeOrdered)]
struct SlimFoo {
    #[order(1)]
    pub biz: Option<String>,

    #[order(2)]
    pub bar: SlimBar,
}

#[derive(DeserializeOrdered)]
struct SlimBar {
    #[order(1)]
    pub bif: String
}

This will automatically implement a custom deserializer that only attempts to deserialize the fields on the specified orders.

License

MIT

Dependencies

~0.5–1.2MB
~26K SLoC