From 34cbd4218e758668b09e84b1df771aed8fd03c0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gianguido=20Sor=C3=A0?= Date: Thu, 27 Oct 2022 14:55:10 +0200 Subject: [PATCH] feat: create the `all()` method for prefs Returns an instance of `UserPrefs` with all the preferences filled in. --- libs/userprefs/prefsgenerator/src/lib.rs | 23 +++++++++++++++++++++++ libs/userprefs/src/lib.rs | 10 +++++----- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/libs/userprefs/prefsgenerator/src/lib.rs b/libs/userprefs/prefsgenerator/src/lib.rs index 9694b83f3..94acac785 100644 --- a/libs/userprefs/prefsgenerator/src/lib.rs +++ b/libs/userprefs/prefsgenerator/src/lib.rs @@ -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 = named.iter().map(|field| { + field.ident.as_ref().unwrap().clone() + }).collect(); + + let ident_fn_calls: Vec = 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 { + + Ok(UserPrefs { + #( #ident_map:self.#ident_fn_calls()? ),* + }) + } + } + }; + + rw_methods.extend(all); } _ => (), }, diff --git a/libs/userprefs/src/lib.rs b/libs/userprefs/src/lib.rs index 4b67044da..1b7e8d0b2 100644 --- a/libs/userprefs/src/lib.rs +++ b/libs/userprefs/src/lib.rs @@ -36,11 +36,11 @@ impl From 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 {