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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*!
Simple persistent generic HashMap/Key-value store, using the Persy Index API.

This is in a beta state at the moment.

 usage:

```
use persawkv::XKV;
let test_store = persawkv::SingleKV::<String, String>::new("./raw.cab", "runint").unwrap();

let _ = test_store.insert("key".to_string(), "value".to_string());
println!("{:?}", test_store.get(&"key".to_string()));
let _ = test_store.remove("key".to_string());

# let _ = std::fs::remove_file("./raw.cab");
```
*/

#![deny(missing_docs)]
#![forbid(unsafe_code)]

pub use persy::PRes;
use persy::{IndexType, Persy, PersyError};
use std::{borrow::Cow, marker::PhantomData, ops::RangeBounds};

mod private {
    // mark traits as sealed
    pub trait Sealed {
    }
}

/// The type that represents a key--(value mode generic)-value store
pub struct BaseKV<K, V>(
    Persy,
    Cow<'static, str>,
    persy::ValueMode,
    PhantomData<(K, V)>,
);

/// The type that represents a key--multiple-value store
pub struct MultiKV<K, V>(BaseKV<K, V>);

/// The type that represents a key-value store
pub struct SingleKV<K, V>(BaseKV<K, V>);

impl<K, V> Clone for BaseKV<K, V> {
    fn clone(&self) -> Self {
        BaseKV(self.0.clone(), self.1.clone(), self.2.clone(), PhantomData)
    }
}
impl<K, V> private::Sealed for BaseKV<K, V> { }

impl<K, V> Clone for MultiKV<K, V> {
    fn clone(&self) -> Self {
        MultiKV(self.0.clone())
    }
}
impl<K, V> private::Sealed for MultiKV<K, V> { }

impl<K, V> Clone for SingleKV<K, V> {
    fn clone(&self) -> Self {
        SingleKV(self.0.clone())
    }
}
impl<K, V> private::Sealed for SingleKV<K, V> { }

/// This type represents a key-..-value iterator
pub struct Iter<K, V>(persy::IndexIter<K, V>)
where
    K: IndexType,
    V: IndexType;

impl<K, V> Iterator for Iter<K, V>
where
    K: IndexType,
    V: IndexType,
{
    type Item = (K, persy::Value<V>);
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

/// This type represents a keys iterator
pub struct KeysIter<K, V>(std::iter::Map<persy::IndexIter<K, V>, fn((K, persy::Value<V>)) -> K>)
where
    K: IndexType,
    V: IndexType;

impl<K, V> Iterator for KeysIter<K, V>
where
    K: IndexType,
    V: IndexType,
{
    type Item = K;
    #[inline]
    fn next(&mut self) -> Option<K> {
        self.0.next()
    }
}

/// Abstract over derived ..KV types
pub trait XKV<K, V> : private::Sealed
where
    K: IndexType,
    V: IndexType,
{
    /// Provides access to the underlying BaseKV
    #[doc(hidden)]
    fn underlying_base_kv(&self) -> &BaseKV<K, V>;

    /// Inserts a key, value pair into the KV store
    #[inline]
    fn insert(&self, key: K, value: V) -> PRes<()> {
        self.underlying_base_kv().insert(key, value)
    }

    /// Removes a key and associated value from the KV store
    #[inline]
    fn remove(&self, key: K) -> PRes<()> {
        self.underlying_base_kv().remove(key)
    }

    /// Removes all entries from the KV store
    #[inline]
    fn clear(&self) -> PRes<()> {
        self.underlying_base_kv().clear()
    }

    /// Gets all the keys contained in the KV store
    #[inline]
    fn keys(&self) -> PRes<KeysIter<K, V>> {
        self.underlying_base_kv().keys()
    }
}

impl<K, V> XKV<K, V> for MultiKV<K, V>
where
    K: IndexType,
    V: IndexType,
{
    #[doc(hidden)]
    fn underlying_base_kv(&self) -> &BaseKV<K, V> {
        &self.0
    }
}

impl<K, V> XKV<K, V> for SingleKV<K, V>
where
    K: IndexType,
    V: IndexType,
{
    #[doc(hidden)]
    fn underlying_base_kv(&self) -> &BaseKV<K, V> {
        &self.0
    }
}

fn first_of2<A, B>(x: (A, B)) -> A {
    x.0
}

impl<K, V> BaseKV<K, V>
where
    K: IndexType,
    V: IndexType,
{
    /// Creates a new instance of the value-mode-generic KV store
    pub fn new(p: &str, idxn: impl Into<Cow<'static, str>>, vm: persy::ValueMode) -> PRes<Self> {
        Self::new_intern(p, idxn.into(), vm)
    }

    pub(crate) fn new_intern(p: &str, idxn: Cow<'static, str>, vm: persy::ValueMode) -> PRes<Self> {
        match Persy::create(p) {
            Ok(_) => {}
            Err(PersyError::Io(ref e)) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(e) => return Err(e),
        }

        let persy = Persy::open(p, persy::Config::new())?;
        let ridxn = idxn.as_ref();

        if !persy.exists_index(ridxn)? {
            let mut tx = persy.begin()?;
            persy.create_index::<K, V>(&mut tx, ridxn, vm.clone())?;
            let prepared = persy.prepare_commit(tx)?;
            persy.commit(prepared)?;
        }

        Ok(BaseKV(persy, idxn, vm, PhantomData))
    }

    /// Inserts a key, value pair into the KV store
    pub fn insert(&self, key: K, value: V) -> PRes<()> {
        let mut tx = self.0.begin()?;
        self.0.put::<K, V>(&mut tx, self.1.as_ref(), key, value)?;
        let prepared = self.0.prepare_commit(tx)?;
        self.0.commit(prepared)
    }

    /// Removes a key and associated value from the KV store
    pub fn remove(&self, key: K) -> PRes<()> {
        let mut tx = self.0.begin()?;
        self.0.remove::<K, V>(&mut tx, self.1.as_ref(), key, None)?;
        let prepared = self.0.prepare_commit(tx)?;
        self.0.commit(prepared)
    }

    /// Removes all entries from the KV store
    pub fn clear(&self) -> PRes<()> {
        let mut tx = self.0.begin()?;
        self.0.drop_index(&mut tx, self.1.as_ref())?;
        self.0
            .create_index::<K, V>(&mut tx, self.1.as_ref(), self.2.clone())?;
        let prepared = self.0.prepare_commit(tx)?;
        self.0.commit(prepared)
    }

    /// Gets all the keys contained in the KV store
    #[inline]
    pub fn keys(&self) -> PRes<KeysIter<K, V>> {
        Ok(KeysIter(self.range(..)?.0.map(first_of2)))
    }

    /// Gets the associated value from a key
    pub fn get(&self, key: &K) -> PRes<Option<persy::Value<V>>> {
        self.0.get::<K, V>(self.1.as_ref(), key)
    }

    /// Returns an iterator visiting all key-value pairs inside the specified range in arbitrary order
    pub fn range<R>(&self, r: R) -> PRes<Iter<K, V>>
    where
        R: RangeBounds<K>,
    {
        self.0.range::<K, V, _>(self.1.as_ref(), r).map(Iter)
    }

    /// Returns an iterator visiting all key-value pairs in arbitrary order
    #[inline]
    pub fn iter(&self) -> PRes<Iter<K, V>> {
        self.range(..)
    }
}

fn sharpen_value<V>(v: persy::Value<V>) -> Vec<V> {
    use persy::Value;
    match v {
        Value::CLUSTER(x) => x,
        Value::SINGLE(x) => vec![x],
    }
}

fn flatten_value<V>(v: persy::Value<V>) -> Option<V> {
    use persy::Value;
    match v {
        Value::CLUSTER(x) => x.into_iter().next(),
        Value::SINGLE(x) => Some(x),
    }
}

impl<K, V> MultiKV<K, V>
where
    K: IndexType,
    V: IndexType,
{
    /// Creates a new instance of the MultiKV store
    pub fn new(p: &str, idxn: impl Into<Cow<'static, str>>) -> PRes<Self> {
        Ok(Self(BaseKV::new_intern(
            p,
            idxn.into(),
            persy::ValueMode::CLUSTER,
        )?))
    }

    /// Gets the associated value from a key
    pub fn get(&self, key: &K) -> PRes<Vec<V>> {
        Ok(self.0.get(key)?.map(sharpen_value).unwrap_or_else(Vec::new))
    }

    /// Returns an iterator visiting all key-value pairs in arbitrary order
    pub fn iter(&self) -> PRes<impl Iterator<Item = (K, Vec<V>)>> {
        Ok(self.0.range(..)?.map(|(k, v)| (k, sharpen_value(v))))
    }
}

impl<K, V> SingleKV<K, V>
where
    K: IndexType,
    V: IndexType,
{
    /// Creates a new instance of the SingleKV store
    pub fn new(p: &str, idxn: impl Into<Cow<'static, str>>) -> PRes<Self> {
        Ok(Self(BaseKV::new_intern(
            p,
            idxn.into(),
            persy::ValueMode::REPLACE,
        )?))
    }

    /// Gets the associated value from a key
    pub fn get(&self, key: &K) -> PRes<Option<V>> {
        Ok(self.0.get(key)?.and_then(flatten_value))
    }

    /// Returns an iterator visiting all key-value pairs in arbitrary order
    pub fn iter(&self) -> PRes<impl Iterator<Item = (K, V)>> {
        Ok(self
            .0
            .range(..)?
            .filter_map(|(k, v)| flatten_value(v).map(|v2| (k, v2))))
    }
}