| 1 | use proc_macro2::{Ident, TokenStream}; |
| 2 | use quote::quote; |
| 3 | |
| 4 | use crate::generation::common::generate_setting_fields_from_bits_tokens; |
| 5 | use crate::parsing::bitfield_attribute::{BitfieldAttribute, Endian}; |
| 6 | use crate::parsing::bitfield_field::BitfieldField; |
| 7 | |
| 8 | /// Generates the `From` trait implementation. |
| 9 | pub(crate) fn generate_from_bitfield_type_for_bitfield_implementation_tokens( |
| 10 | bitfield_struct_name: Ident, |
| 11 | fields: &[BitfieldField], |
| 12 | ignored_fields: &[BitfieldField], |
| 13 | bitfield_type: &syn::Type, |
| 14 | ) -> TokenStream { |
| 15 | let setting_fields_from_bits_tokens = generate_setting_fields_from_bits_tokens( |
| 16 | bitfield_type, |
| 17 | fields, |
| 18 | Some(quote! { Self }), |
| 19 | false, |
| 20 | !ignored_fields.is_empty(), |
| 21 | ); |
| 22 | |
| 23 | let ignored_fields_defaults = ignored_fields.iter().map(|field| { |
| 24 | let field_name = &field.name; |
| 25 | let field_ty = &field.ty; |
| 26 | quote! { |
| 27 | #field_name: <#field_ty>::default(), |
| 28 | } |
| 29 | }); |
| 30 | |
| 31 | let initialize_struct_tokens = if !ignored_fields.is_empty() { |
| 32 | quote! { |
| 33 | Self { |
| 34 | val: 0, |
| 35 | #( #ignored_fields_defaults )* |
| 36 | } |
| 37 | } |
| 38 | } else { |
| 39 | quote! { |
| 40 | Self(0) |
| 41 | } |
| 42 | }; |
| 43 | |
| 44 | quote! { |
| 45 | impl From<#bitfield_type> for #bitfield_struct_name { |
| 46 | fn from(bits: #bitfield_type) -> Self { |
| 47 | let mut this = #initialize_struct_tokens; |
| 48 | #setting_fields_from_bits_tokens |
| 49 | this |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | pub(crate) fn generate_from_bitfield_for_bitfield_type_implementation_tokens( |
| 56 | bitfield_struct_name: Ident, |
| 57 | bitfield_attribute: &BitfieldAttribute, |
| 58 | ignored_fields_struct: bool, |
| 59 | ) -> TokenStream { |
| 60 | let bitfield_type = &bitfield_attribute.ty; |
| 61 | |
| 62 | let from_bitfield_impl = match bitfield_attribute.into_endian { |
| 63 | Endian::Big => { |
| 64 | if ignored_fields_struct { |
| 65 | quote! { |
| 66 | b.val |
| 67 | } |
| 68 | } else { |
| 69 | quote! { |
| 70 | b.0 |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | Endian::Little => { |
| 75 | if ignored_fields_struct { |
| 76 | quote! { |
| 77 | b.val.swap_bytes() |
| 78 | } |
| 79 | } else { |
| 80 | quote! { |
| 81 | b.0.swap_bytes() |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | }; |
| 86 | |
| 87 | quote! { |
| 88 | impl From<#bitfield_struct_name> for #bitfield_type { |
| 89 | fn from(b: #bitfield_struct_name) -> #bitfield_type { |
| 90 | #from_bitfield_impl |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | } |