@@ -131,3 +131,69 @@ pub fn hash(
131131 }
132132 }
133133}
134+
135+ /// Implements the `binrw::BinWrite` trait for the given bitfield struct.
136+ pub fn binwrite (
137+ name : & syn:: Ident ,
138+ cfg : Option < TokenStream > ,
139+ ) -> TokenStream {
140+ let attr = cfg. map ( |cfg| quote ! ( #[ cfg( #cfg) ] ) ) ;
141+
142+ quote ! {
143+ #attr
144+ impl binrw:: BinWrite for #name {
145+ type Args <' a> = ( ) ;
146+
147+ fn write_options<W : binrw:: io:: Write + binrw:: io:: Seek >(
148+ & self ,
149+ writer: & mut W ,
150+ endian: binrw:: Endian ,
151+ args: Self :: Args <' _>,
152+ ) -> binrw:: BinResult <( ) > {
153+ let raw = self . into_bits( ) ;
154+
155+ let bytes = match endian {
156+ binrw:: Endian :: Big => raw. to_be_bytes( ) ,
157+ binrw:: Endian :: Little => raw. to_le_bytes( ) ,
158+ } ;
159+
160+ writer. write_all( & bytes) ?;
161+
162+ Ok ( ( ) )
163+ }
164+ }
165+ }
166+ }
167+
168+ /// Implements the `binrw::BinRead` trait for the given bitfield struct.
169+ pub fn binread (
170+ name : & syn:: Ident ,
171+ repr : & syn:: Type ,
172+ cfg : Option < TokenStream > ,
173+ ) -> TokenStream {
174+ let attr = cfg. map ( |cfg| quote ! ( #[ cfg( #cfg) ] ) ) ;
175+
176+ quote ! {
177+ #attr
178+ impl binrw:: BinRead for #name {
179+ type Args <' a> = ( ) ;
180+
181+ fn read_options<R : binrw:: io:: Read + binrw:: io:: Seek >(
182+ reader: & mut R ,
183+ endian: binrw:: Endian ,
184+ args: Self :: Args <' _>,
185+ ) -> binrw:: BinResult <Self > {
186+ let mut buf = [ 0u8 ; core:: mem:: size_of:: <#repr>( ) ] ;
187+
188+ reader. read_exact( & mut buf) ?;
189+
190+ let raw = match endian {
191+ binrw:: Endian :: Big => <#repr>:: from_be_bytes( buf) ,
192+ binrw:: Endian :: Little => <#repr>:: from_le_bytes( buf) ,
193+ } ;
194+
195+ Ok ( Self :: from_bits( raw) )
196+ }
197+ }
198+ }
199+ }
0 commit comments