feat: create the all() method for prefs

Returns an instance of `UserPrefs` with all the preferences filled in.
This commit is contained in:
Gianguido Sorà 2022-10-27 14:55:10 +02:00
parent c05bfce3f8
commit 34cbd4218e
2 changed files with 28 additions and 5 deletions

View file

@ -1,4 +1,5 @@
use proc_macro::{self, TokenStream};
use proc_macro2::Ident;
use proc_macro_error::{abort, proc_macro_error};
use quote::{format_ident, quote};
use syn::{parse_macro_input, DeriveInput, FieldsNamed};
@ -57,6 +58,28 @@ pub fn getter_setter(input: TokenStream) -> TokenStream {
rw_methods.extend(read);
}
let ident_map: Vec<Ident> = named.iter().map(|field| {
field.ident.as_ref().unwrap().clone()
}).collect();
let ident_fn_calls: Vec<Ident> = named.iter().map(|field| {
format_ident!("{}_or_default", field.ident.as_ref().unwrap().clone())
}).collect();
// create the "all" method
let all = quote! {
impl Manager {
pub fn all(&self) -> Result<UserPrefs, Error> {
Ok(UserPrefs {
#( #ident_map:self.#ident_fn_calls()? ),*
})
}
}
};
rw_methods.extend(all);
}
_ => (),
},

View file

@ -36,11 +36,11 @@ impl From<DecodeError> for Error {
/// The struct field type must be serializable by bincode.
#[derive(prefsgenerator::GetterSetter)]
#[allow(dead_code)] // Allowing dead code here because UserPrefs is used to generate getter/setters.
struct UserPrefs {
radio_on_on_boot: bool,
connect_known_networks_on_boot: bool,
autobacklight_on_boot: bool,
autobacklight_timeout: u64,
pub struct UserPrefs {
pub radio_on_on_boot: bool,
pub connect_known_networks_on_boot: bool,
pub autobacklight_on_boot: bool,
pub autobacklight_timeout: u64,
}
pub struct Manager {