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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use std::ops::DerefMut;
use toml::Value;
use toml_query::read::TomlValueReadExt;
use toml_query::set::TomlValueSetExt;
use std::collections::BTreeMap;
use std::fmt;
use std::fmt::Display;
use libimagstore::store::Store;
use libimagstore::storeid::StoreIdIterator;
use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::storeid::IntoStoreId;
use libimagerror::into::IntoError;
use module_path::ModuleEntryPath;
use result::Result;
use error::CounterError as CE;
use error::CounterErrorKind as CEK;
use error::ResultExt;
pub type CounterName = String;
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub struct CounterUnit(String);
impl Display for CounterUnit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({})", self.0)
}
}
impl CounterUnit {
pub fn new<S: Into<String>>(unit: S) -> CounterUnit {
CounterUnit(unit.into())
}
}
pub struct Counter<'a> {
fle: FileLockEntry<'a>,
unit: Option<CounterUnit>,
}
impl<'a> Counter<'a> {
pub fn new(store: &Store, name: CounterName, init: i64) -> Result<Counter> {
use std::ops::DerefMut;
debug!("Creating new counter: '{}' with value: {}", name, init);
let fle = {
let id = try!(ModuleEntryPath::new(name.clone())
.into_storeid()
.chain_err(|| CEK::StoreWriteError));
let mut lockentry = try!(store.create(id).chain_err(|| CEK::StoreWriteError));
{
let entry = lockentry.deref_mut();
let header = entry.get_header_mut();
let setres = header.set(&String::from("counter"), Value::Table(BTreeMap::new()));
if setres.is_err() {
return Err(CEK::StoreWriteError.into_error());
}
let setres = header.set(&String::from("counter.name"), Value::String(name));
if setres.is_err() {
return Err(CEK::StoreWriteError.into_error())
}
let setres = header.set(&String::from("counter.value"), Value::Integer(init));
if setres.is_err() {
return Err(CEK::StoreWriteError.into_error())
}
}
lockentry
};
Ok(Counter { fle: fle, unit: None })
}
pub fn with_unit(mut self, unit: Option<CounterUnit>) -> Result<Counter<'a>> {
self.unit = unit;
if let Some(u) = self.unit.clone() {
let header = self.fle.deref_mut().get_header_mut();
let setres = header.set(&String::from("counter.unit"), Value::String(u.0));
if setres.is_err() {
self.unit = None;
return Err(CEK::StoreWriteError.into_error())
}
};
Ok(self)
}
pub fn inc(&mut self) -> Result<()> {
let header = self.fle.deref_mut().get_header_mut();
let query = String::from("counter.value");
match try!(header.read(&query).chain_err(|| CEK::StoreReadError)) {
Some(&Value::Integer(i)) => {
header.set(&query, Value::Integer(i + 1))
.chain_err(|| CEK::StoreWriteError)
.map(|_| ())
},
_ => Err(CE::from_kind(CEK::StoreReadError)),
}
}
pub fn dec(&mut self) -> Result<()> {
let header = self.fle.deref_mut().get_header_mut();
let query = String::from("counter.value");
match try!(header.read(&query).chain_err(|| CEK::StoreReadError)) {
Some(&Value::Integer(i)) => {
header.set(&query, Value::Integer(i - 1))
.chain_err(|| CEK::StoreWriteError)
.map(|_| ())
},
_ => Err(CE::from_kind(CEK::StoreReadError)),
}
}
pub fn reset(&mut self) -> Result<()> {
self.set(0)
}
pub fn set(&mut self, v: i64) -> Result<()> {
self.fle
.deref_mut()
.get_header_mut()
.set(&String::from("counter.value"), Value::Integer(v))
.chain_err(|| CEK::StoreWriteError)
.map(|_| ())
}
pub fn name(&self) -> Result<CounterName> {
self.read_header_at("counter.name", |v| match v {
Some(&Value::String(ref s)) => Ok(s.clone()),
Some(_) => Err(CEK::HeaderTypeError.into_error()),
_ => Err(CEK::StoreReadError.into_error()),
})
}
pub fn value(&self) -> Result<i64> {
self.read_header_at("counter.value", |v| match v {
Some(&Value::Integer(i)) => Ok(i),
Some(_) => Err(CEK::HeaderTypeError.into_error()),
_ => Err(CEK::StoreReadError.into_error()),
})
}
pub fn unit(&self) -> Option<&CounterUnit> {
self.unit.as_ref()
}
pub fn read_unit(&self) -> Result<Option<CounterUnit>> {
self.read_header_at("counter.unit", |s| match s {
Some(&Value::String(ref s)) => Ok(Some(CounterUnit::new(s.clone()))),
Some(_) => Err(CEK::HeaderTypeError.into_error()),
_ => Err(CEK::StoreReadError.into_error()),
})
}
fn read_header_at<T, F>(&self, name: &str, f: F) -> Result<T>
where F: FnOnce(Option<&Value>) -> Result<T>
{
self.fle
.get_header()
.read(&String::from(name))
.chain_err(|| CEK::StoreWriteError)
.and_then(f)
}
pub fn load(name: CounterName, store: &Store) -> Result<Counter> {
debug!("Loading counter: '{}'", name);
let id = try!(ModuleEntryPath::new(name)
.into_storeid()
.chain_err(|| CEK::StoreWriteError));
Counter::from_storeid(store, id)
}
pub fn delete(name: CounterName, store: &Store) -> Result<()> {
debug!("Deleting counter: '{}'", name);
let id = try!(ModuleEntryPath::new(name)
.into_storeid()
.chain_err(|| CEK::StoreWriteError));
store.delete(id).chain_err(|| CEK::StoreWriteError)
}
pub fn all_counters(store: &Store) -> Result<CounterIterator> {
store.retrieve_for_module("counter")
.map(|iter| CounterIterator::new(store, iter))
.chain_err(|| CEK::StoreReadError)
}
}
trait FromStoreId {
fn from_storeid(&Store, StoreId) -> Result<Counter>;
}
impl<'a> FromStoreId for Counter<'a> {
fn from_storeid(store: &Store, id: StoreId) -> Result<Counter> {
debug!("Loading counter from storeid: '{:?}'", id);
match
|