7 stable releases

1.2.0 Sep 30, 2024
1.1.0 Sep 29, 2024
1.0.5 Jul 30, 2018

#617 in Debugging

Download history 108/week @ 2025-10-27 24/week @ 2025-11-03 9/week @ 2025-11-10 123/week @ 2025-11-17 29/week @ 2025-11-24 42/week @ 2025-12-01 47/week @ 2025-12-08 204/week @ 2025-12-15 1137/week @ 2025-12-22 565/week @ 2025-12-29 43/week @ 2026-01-05 375/week @ 2026-01-12 808/week @ 2026-01-19 333/week @ 2026-01-26 500/week @ 2026-02-02 761/week @ 2026-02-09

2,710 downloads per month
Used in 2 crates (via ascom-alpaca)

MIT license

16KB
308 lines

serdebug

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:

use serde::Serialize;
use serdebug::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> {
    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

~0.3–0.9MB
~20K SLoC