1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
pub use crate::json_reading::FromJsonError;
pub use crate::persist::{CurrentValue, Persist};
pub use crate::{FeattleDefinition, Feattles, FeattlesPrivate};
pub use parking_lot::{MappedRwLockReadGuard, RwLockReadGuard, RwLockWriteGuard};
use crate::last_reload::LastReload;
use crate::persist::CurrentValues;
use crate::FeattleValue;
use parking_lot::RwLock;
use std::error::Error;
use std::{fmt, mem};
#[derive(Debug)]
pub struct FeattlesImpl<P, FS> {
pub persistence: P,
pub inner_feattles: RwLock<InnerFeattles<FS>>,
}
#[derive(Debug, Clone)]
pub struct InnerFeattles<FS> {
pub last_reload: LastReload,
pub current_values: Option<CurrentValues>,
pub feattles_struct: FS,
}
#[derive(Debug, Clone)]
pub struct Feattle<T> {
key: &'static str,
description: &'static str,
value: T,
default: T,
current_value: Option<CurrentValue>,
}
#[derive(Copy, Clone, Debug)]
pub struct ParseError;
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Matching variant not found")
}
}
impl Error for ParseError {}
pub trait FeattlesStruct: 'static {
fn try_update(
&mut self,
key: &str,
value: Option<CurrentValue>,
) -> Result<Option<CurrentValue>, FromJsonError>;
}
impl<P, FS> FeattlesImpl<P, FS> {
pub fn new(persistence: P, feattles_struct: FS) -> Self {
FeattlesImpl {
persistence,
inner_feattles: RwLock::new(InnerFeattles {
last_reload: LastReload::Never,
current_values: None,
feattles_struct,
}),
}
}
}
impl<T: Clone + FeattleValue> Feattle<T> {
pub fn new(key: &'static str, description: &'static str, default: T) -> Self {
Feattle {
key,
description,
value: default.clone(),
default,
current_value: None,
}
}
pub fn definition(&self) -> FeattleDefinition {
FeattleDefinition {
key: self.key,
description: self.description.to_owned(),
format: T::serialized_format(),
value: self.value.as_json(),
value_overview: self.value.overview(),
default: self.default.as_json(),
modified_at: self.current_value.as_ref().map(|v| v.modified_at),
modified_by: self.current_value.as_ref().map(|v| v.modified_by.clone()),
}
}
pub fn try_update(
&mut self,
value: Option<CurrentValue>,
) -> Result<Option<CurrentValue>, FromJsonError> {
self.value = match &value {
None => self.default.clone(),
Some(value) => FeattleValue::try_from_json(&value.value)?,
};
Ok(mem::replace(&mut self.current_value, value))
}
pub fn value(&self) -> &T {
&self.value
}
}