Skip to content
This repository has been archived by the owner on Jun 8, 2021. It is now read-only.

Commit

Permalink
settings: add SettingsExtManual Trait for IsA<Settings>::get::<T>/set…
Browse files Browse the repository at this point in the history
…::<T> fn
  • Loading branch information
Cogitri committed Aug 13, 2019
1 parent fa45d55 commit 7abb199
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Expand Up @@ -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;
Expand Down
1 change: 1 addition & 0 deletions src/prelude.rs
Expand Up @@ -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"))]
Expand Down
58 changes: 58 additions & 0 deletions 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<U: FromVariant>(&self, key: &str) -> Result<U, GetError>;

fn set<U: ToVariant>(&self, key: &str, value: &U) -> Result<(), BoolError>;
}

impl<O: IsA<Settings>> SettingsExtManual for O {
fn get<U: FromVariant>(&self, key: &str) -> Result<U, GetError> {
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<U: ToVariant>(&self, key: &str, value: &U) -> Result<(), BoolError> {
self.set_value(key, &value.to_variant())
}
}

0 comments on commit 7abb199

Please sign in to comment.