@@ -10,7 +10,7 @@ use crate::util;
1010
1111use super :: sorted;
1212
13- pub fn render ( _opts : & super :: Options , _ir : & IR , e : & Enum , path : & str ) -> Result < TokenStream > {
13+ pub fn render ( opts : & super :: Options , _ir : & IR , e : & Enum , path : & str ) -> Result < TokenStream > {
1414 let span = Span :: call_site ( ) ;
1515
1616 // For very "sparse" enums, generate a newtype wrapping the uX.
@@ -33,17 +33,39 @@ pub fn render(_opts: &super::Options, _ir: &IR, e: &Enum, path: &str) -> Result<
3333
3434 if newtype {
3535 let mut items = TokenStream :: new ( ) ;
36+ let mut item_names_str = Vec :: with_capacity ( e. variants . len ( ) ) ;
37+ let mut item_values = Vec :: with_capacity ( e. variants . len ( ) ) ;
3638
3739 for f in sorted ( & e. variants , |f| ( f. value , f. name . clone ( ) ) ) {
3840 let name = Ident :: new ( & f. name , span) ;
3941 let value = util:: hex ( f. value ) ;
42+
43+ item_names_str. push ( & f. name ) ;
44+ item_values. push ( value. clone ( ) ) ;
45+
4046 let doc = util:: doc ( & f. description ) ;
4147 items. extend ( quote ! (
4248 #doc
4349 pub const #name: Self = Self ( #value) ;
4450 ) ) ;
4551 }
4652
53+ let defmt = opts. defmt_feature . as_ref ( ) . map ( |defmt_feature| {
54+ quote ! {
55+ #[ cfg( feature = #defmt_feature) ]
56+ impl defmt:: Format for #name {
57+ fn format( & self , f: defmt:: Formatter ) {
58+ match self . 0 {
59+ #(
60+ #item_values => defmt:: write!( f, #item_names_str) ,
61+ ) *
62+ other => defmt:: write!( f, "0x{:02X}" , other) ,
63+ }
64+ }
65+ }
66+ }
67+ } ) ;
68+
4769 out. extend ( quote ! {
4870 #doc
4971 #[ repr( transparent) ]
@@ -63,6 +85,20 @@ pub fn render(_opts: &super::Options, _ir: &IR, e: &Enum, path: &str) -> Result<
6385 self . 0
6486 }
6587 }
88+
89+ impl core:: fmt:: Debug for #name {
90+ fn fmt( & self , f: & mut core:: fmt:: Formatter ) -> core:: fmt:: Result {
91+ match self . 0 {
92+ #(
93+ #item_values => f. write_str( #item_names_str) ,
94+ ) *
95+ other => core:: write!( f, "0x{:02X}" , other) ,
96+ }
97+ }
98+ }
99+
100+ #defmt
101+
66102 } ) ;
67103 } else {
68104 let variants: BTreeMap < _ , _ > = e. variants . iter ( ) . map ( |v| ( v. value , v) ) . collect ( ) ;
@@ -85,10 +121,17 @@ pub fn render(_opts: &super::Options, _ir: &IR, e: &Enum, path: &str) -> Result<
85121 }
86122 }
87123
124+ let defmt = opts. defmt_feature . as_ref ( ) . map ( |defmt_feature| {
125+ quote ! {
126+ #[ cfg_attr( feature = #defmt_feature, derive( defmt:: Format ) ) ]
127+ }
128+ } ) ;
129+
88130 out. extend ( quote ! {
89131 #doc
90132 #[ repr( #ty) ]
91- #[ derive( Copy , Clone , Eq , PartialEq , Ord , PartialOrd ) ]
133+ #[ derive( Copy , Clone , Debug , Eq , PartialEq , Ord , PartialOrd ) ]
134+ #defmt
92135 pub enum #name {
93136 #items
94137 }
0 commit comments