#serialization #unit #deserialize #struct #no-alloc #name #string

no-std serde_unit_struct

(De)serialize a unit struct as its name

3 releases

0.1.3 Dec 16, 2023
0.1.2 Nov 8, 2023
0.1.1 Apr 15, 2022
0.1.0 Mar 1, 2022

#315 in Encoding

Download history 385/week @ 2024-01-03 482/week @ 2024-01-10 719/week @ 2024-01-17 676/week @ 2024-01-24 1053/week @ 2024-01-31 799/week @ 2024-02-07 653/week @ 2024-02-14 560/week @ 2024-02-21 811/week @ 2024-02-28 615/week @ 2024-03-06 672/week @ 2024-03-13 723/week @ 2024-03-20 770/week @ 2024-03-27 1173/week @ 2024-04-03 770/week @ 2024-04-10 596/week @ 2024-04-17

3,469 downloads per month
Used in midwest_mainline

MIT/Apache

10KB
126 lines

Serde Unit Struct Derive

This crate provides derive macros for Serde's Serialize and Deserialize traits on unit structs, such that the unit struct is represented by its name as a string. This is useful if you wish to maintain type information, i.e. differentiate between different unit structs.

Without serde_unit_struct:

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct Foo;

#[derive(Deserialize, Serialize)]
struct Bar;

fn main() {
    // Normally, unit structs serialize to null.
    let json = serde_json::to_string(&Foo).unwrap();
    assert_eq!(json, "null");

    // We can successfully deserialize them, but...
    let foo: Foo = serde_json::from_str(&json).unwrap();
    assert_eq!(foo, Foo);

    // ...this also works; the type information is lost.
    let bar: Bar = serde_json::from_str(&json).unwrap();
    assert_eq!(bar, Bar);
}

With serde_unit_struct:

use serde_unit_struct::{Deserialize_unit_struct, Serialize_unit_struct};

#[derive(Deserialize_unit_struct, Serialize_unit_struct)]
struct Foo;

#[derive(Deserialize_unit_struct, Serialize_unit_struct)]
struct Bar;

fn main() {
    // Now, unit structs serialise to their name as a string.
    let json = serde_json::to_string(&Foo).unwrap();
    assert_eq!(json, "\"Foo\"");

    // We can successfully deserialize them.
    let foo: Foo = serde_json::from_str(&json).unwrap();
    assert_eq!(foo, Foo);

    // Type information is maintained.
    let bar: Result<Bar, _> = serde_json::from_str(&json);
    assert!(bar.is_err());
}

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~305–760KB
~18K SLoC