5 stable releases

Uses old Rust 2015

1.0.5 Jul 30, 2018

#241 in Debugging

Download history 53/week @ 2022-05-22 62/week @ 2022-05-29 85/week @ 2022-06-05 72/week @ 2022-06-12 31/week @ 2022-06-19 44/week @ 2022-06-26 29/week @ 2022-07-03 29/week @ 2022-07-10 32/week @ 2022-07-17 36/week @ 2022-07-24 72/week @ 2022-07-31 42/week @ 2022-08-07 33/week @ 2022-08-14 43/week @ 2022-08-21 26/week @ 2022-08-28 29/week @ 2022-09-04

135 downloads per month
Used in 2 crates (via scte35-reader)

MIT license

15KB
335 lines

serdebug

Travis CI GitHub license Crates.io docs.rs

This is a drop-in replacement for #[derive(Debug)] that uses serde::Serialize under the hood to provide advanced control over output serialisation.

Usage

By default, the generated code will produce exactly same output as #[derive(Debug)] for compatibility.

However, this might be not very interesting, so let's add some serde attributes to see how we can control debug representation:

extern crate serde;

#[macro_use]
extern crate serde_derive;

#[macro_use]
extern crate serdebug;

pub struct CustomType(u32);

#[derive(Serialize, SerDebug)]
pub enum MyEnum {
    // renaming items works as expected
    #[serde(rename = "AAAAAAA!!!")]
    A,

    B(u32),

    C { flag: bool },
}

#[derive(Serialize, SerDebug)]
// so does bulk rename on containers
#[serde(rename_all = "PascalCase")]
pub struct MyStruct {
    number: u32,

    my_enum: Vec<MyEnum>,

    // we might want to hide some items from the output
    #[serde(skip_serializing)]
    hidden: bool,

    // or override serialisation for otherwise verbose wrappers or
    // third-party types that don't implement `Debug` and/or `Serialize`
    #[serde(serialize_with = "custom_serialize")]
    custom_type: CustomType,
}

fn custom_serialize<S: serde::Serializer>(value: &CustomType, ser: S) -> Result<S::Ok, S::Error> {
    use serde::Serialize;

    value.0.serialize(ser)
}

fn main() {
    let s = MyStruct {
        number: 42,
        my_enum: vec![MyEnum::A, MyEnum::B(10), MyEnum::C { flag: true }],
        hidden: true,
        custom_type: CustomType(20),
    };

    assert_eq!(format!("{:#?}", s), "
MyStruct {
    Number: 42,
    MyEnum: [
        AAAAAAA!!!,
        B(
            10
        ),
        C {
            flag: true
        }
    ],
    CustomType: 20
}
".trim());
}

Dependencies

~2MB
~49K SLoC