From 7abb1996c9de83c8abb0cb828f9348bc60fed013 Mon Sep 17 00:00:00 2001 From: Rasmus Thomsen Date: Sat, 6 Jul 2019 01:53:24 +0200 Subject: [PATCH] settings: add SettingsExtManual Trait for IsA::get::/set:: fn --- src/lib.rs | 1 + src/prelude.rs | 1 + src/settings.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 src/settings.rs diff --git a/src/lib.rs b/src/lib.rs index b29534e8..53086a7c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -42,6 +42,7 @@ mod output_stream; mod pollable_input_stream; mod pollable_output_stream; mod resource; +mod settings; mod socket; mod socket_listener; mod subprocess; diff --git a/src/prelude.rs b/src/prelude.rs index 23218f52..40f3a6b3 100644 --- a/src/prelude.rs +++ b/src/prelude.rs @@ -15,6 +15,7 @@ pub use list_store::ListStoreExtManual; pub use output_stream::OutputStreamExtManual; pub use pollable_input_stream::PollableInputStreamExtManual; pub use pollable_output_stream::PollableOutputStreamExtManual; +pub use settings::SettingsExtManual; pub use socket::*; pub use socket_listener::SocketListenerExtManual; #[cfg(any(unix, feature = "dox"))] diff --git a/src/settings.rs b/src/settings.rs new file mode 100644 index 00000000..913e9a75 --- /dev/null +++ b/src/settings.rs @@ -0,0 +1,58 @@ +use glib::variant::FromVariant; +use glib::{BoolError, IsA, ToVariant, VariantType}; +use {Settings, SettingsExt}; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GetError { + WrongType(VariantType, String), + KeyNotFound(String), +} + +impl std::fmt::Display for GetError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + GetError::WrongType(request_type, key_type) => write!( + f, + "GetError: Type mismatch. Requested type '{}', but key is of type '{}'", + request_type, key_type + ), + GetError::KeyNotFound(key) => write!(f, "GetError: Couldn't find key '{}'", key), + } + } +} + +impl std::error::Error for GetError { + fn description(&self) -> &str { + match self { + GetError::WrongType(_, _) => "GetError: Type mismatch", + GetError::KeyNotFound(_) => "GetError: Couldn't find key", + } + } +} + +pub trait SettingsExtManual { + fn get(&self, key: &str) -> Result; + + fn set(&self, key: &str, value: &U) -> Result<(), BoolError>; +} + +impl> SettingsExtManual for O { + fn get(&self, key: &str) -> Result { + if let Some(val) = self.get_value(key) { + if let Some(ret) = FromVariant::from_variant(&val) { + Ok(ret) + } else { + Err(GetError::WrongType( + val.type_().to_owned(), + U::static_variant_type().to_str().to_string(), + )) + } + } else { + Err(GetError::KeyNotFound(key.to_string())) + } + } + + fn set(&self, key: &str, value: &U) -> Result<(), BoolError> { + self.set_value(key, &value.to_variant()) + } +}