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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use crate::{tx_read, Persistent, Ref, RefSytx, SRes, Structsy, StructsyImpl, Sytx};
use persy::{IndexType, Persy, PersyId, Transaction, Value};
use std::marker::PhantomData;
use std::ops::RangeBounds;
use std::sync::Arc;
use std::vec::IntoIter;

/// Trait implemented by all the values that can be directly indexed.
pub trait IndexableValue {
    fn puts<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()>;
    fn removes<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()>;
}

macro_rules! impl_indexable_value {
    ($t:ident) => {
        impl IndexableValue for $t {
            fn puts<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
                put_index(tx, name, self, id)
            }
            fn removes<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
                remove_index(tx, name, self, id)
            }
        }
    };
}
impl_indexable_value!(u8);
impl_indexable_value!(u16);
impl_indexable_value!(u32);
impl_indexable_value!(u64);
impl_indexable_value!(u128);
impl_indexable_value!(i8);
impl_indexable_value!(i16);
impl_indexable_value!(i32);
impl_indexable_value!(i64);
impl_indexable_value!(i128);
impl_indexable_value!(f32);
impl_indexable_value!(f64);
impl_indexable_value!(String);

impl<T: IndexableValue> IndexableValue for Option<T> {
    fn puts<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
        if let Some(x) = self {
            x.puts(tx, name, id)?;
        }
        Ok(())
    }
    fn removes<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
        if let Some(x) = self {
            x.removes(tx, name, id)?;
        }
        Ok(())
    }
}
impl<T: IndexableValue> IndexableValue for Vec<T> {
    fn puts<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
        for x in self {
            x.puts(tx, name, id)?;
        }
        Ok(())
    }
    fn removes<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
        for x in self {
            x.removes(tx, name, id)?;
        }
        Ok(())
    }
}
impl<T: Persistent> IndexableValue for Ref<T> {
    fn puts<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
        put_index(tx, name, &self.raw_id, id)?;
        Ok(())
    }
    fn removes<P: Persistent>(&self, tx: &mut dyn Sytx, name: &str, id: &Ref<P>) -> SRes<()> {
        remove_index(tx, name, &self.raw_id, id)?;
        Ok(())
    }
}

fn put_index<T: IndexType, P: Persistent>(tx: &mut dyn Sytx, name: &str, k: &T, id: &Ref<P>) -> SRes<()> {
    let persy = &tx.structsy().structsy_impl.persy;
    persy.put::<T, PersyId>(&mut tx.tx().trans, name, k.clone(), id.raw_id.clone())?;
    Ok(())
}

fn remove_index<T: IndexType, P: Persistent>(tx: &mut dyn Sytx, name: &str, k: &T, id: &Ref<P>) -> SRes<()> {
    let persy = &tx.structsy().structsy_impl.persy;
    persy.remove::<T, PersyId>(&mut tx.tx().trans, name, k.clone(), Some(id.raw_id.clone()))?;
    Ok(())
}

fn map_unique_entry<P: Persistent>(db: &Structsy, entry: Value<PersyId>) -> Option<(Ref<P>, P)> {
    if let Some(id) = entry.into_iter().next() {
        let r = Ref::new(id);
        if let Ok(val) = db.read(&r) {
            val.map(|c| (r, c))
        } else {
            None
        }
    } else {
        None
    }
}

fn map_entry<P: Persistent>(db: &Structsy, entry: Value<PersyId>) -> Vec<(Ref<P>, P)> {
    entry
        .into_iter()
        .filter_map(|id| {
            let r = Ref::new(id);
            if let Ok(x) = db.read(&r) {
                x.map(|c| (r, c))
            } else {
                None
            }
        })
        .collect()
}

fn map_unique_entry_tx<P: Persistent>(
    persy: &Persy,
    tx: &mut Transaction,
    entry: Value<PersyId>,
) -> Option<(Ref<P>, P)> {
    let name = P::get_description().name;
    if let Some(id) = entry.into_iter().next() {
        if let Ok(val) = tx_read::<P>(&persy, &name, tx, &id) {
            let r = Ref::new(id);
            val.map(|c| (r, c))
        } else {
            None
        }
    } else {
        None
    }
}

fn map_entry_tx<P: Persistent>(persy: &Persy, tx: &mut Transaction, entry: Value<PersyId>) -> Vec<(Ref<P>, P)> {
    let name = P::get_description().name;
    entry
        .into_iter()
        .filter_map(|id| {
            if let Ok(val) = tx_read::<P>(&persy, &name, tx, &id) {
                let r = Ref::new(id);
                val.map(|x| (r, x))
            } else {
                None
            }
        })
        .collect()
}

pub fn find_unique<K: IndexType, P: Persistent>(db: &Structsy, name: &str, k: &K) -> SRes<Option<(Ref<P>, P)>> {
    if let Some(id_container) = db.structsy_impl.persy.get::<K, PersyId>(name, k)? {
        Ok(map_unique_entry(db, id_container))
    } else {
        Ok(None)
    }
}

pub fn find_unique_range<K: IndexType, P: Persistent, R: RangeBounds<K>>(
    db: &Structsy,
    name: &str,
    range: R,
) -> SRes<impl Iterator<Item = (Ref<P>, P, K)>> {
    let db1: Structsy = db.clone();
    Ok(db
        .structsy_impl
        .persy
        .range::<K, PersyId, R>(name, range)?
        .filter_map(move |e| {
            let k = e.0;
            map_unique_entry(&db1, e.1).map(|(r, v)| (r, v, k))
        }))
}

pub fn find<K: IndexType, P: Persistent>(db: &Structsy, name: &str, k: &K) -> SRes<Vec<(Ref<P>, P)>> {
    if let Some(e) = db.structsy_impl.persy.get::<K, PersyId>(name, k)? {
        Ok(map_entry(db, e))
    } else {
        Ok(Vec::new())
    }
}

pub fn find_range<K: IndexType, P: Persistent, R: RangeBounds<K>>(
    db: &Structsy,
    name: &str,
    range: R,
) -> SRes<impl Iterator<Item = (Ref<P>, P, K)>> {
    let db1: Structsy = db.clone();
    Ok(db
        .structsy_impl
        .persy
        .range::<K, PersyId, R>(name, range)?
        .map(move |e| {
            map_entry(&db1, e.1.clone())
                .into_iter()
                .map(move |(id, val)| (id, val, e.0.clone()))
        })
        .flatten())
}

pub fn find_unique_tx<K: IndexType, P: Persistent>(db: &mut dyn Sytx, name: &str, k: &K) -> SRes<Option<(Ref<P>, P)>> {
    let persy = &db.structsy().structsy_impl.persy;
    if let Some(id_container) = persy.get_tx::<K, PersyId>(&mut db.tx().trans, name, k)? {
        Ok(map_unique_entry_tx(persy, &mut db.tx().trans, id_container))
    } else {
        Ok(None)
    }
}

pub fn find_tx<K: IndexType, P: Persistent>(db: &mut dyn Sytx, name: &str, k: &K) -> SRes<Vec<(Ref<P>, P)>> {
    let persy = &db.structsy().structsy_impl.persy;
    if let Some(e) = persy.get_tx::<K, PersyId>(&mut db.tx().trans, name, k)? {
        Ok(map_entry_tx(persy, &mut db.tx().trans, e))
    } else {
        Ok(Vec::new())
    }
}

/// Iterator implementation for Range of indexed persistent types
pub struct RangeIterator<'a, K: IndexType, P: Persistent> {
    structsy: Arc<StructsyImpl>,
    persy_iter: persy::TxIndexIter<'a, K, PersyId>,
    iter: Option<IntoIter<(Ref<P>, P, K)>>,
}

impl<'a, K: IndexType, P: Persistent> RangeIterator<'a, K, P> {
    fn new(structsy: Arc<StructsyImpl>, iter: persy::TxIndexIter<'a, K, PersyId>) -> RangeIterator<'a, K, P> {
        RangeIterator {
            structsy: structsy,
            persy_iter: iter,
            iter: None,
        }
    }
    pub fn tx(&'a mut self) -> RefSytx<'a> {
        RefSytx {
            structsy_impl: self.structsy.clone(),
            trans: self.persy_iter.tx(),
        }
    }

    pub fn next_tx<'b: 'a>(&'b mut self) -> Option<(Vec<(Ref<P>, P)>, K, RefSytx<'a>)> {
        if let Some((k, v, tx)) = self.persy_iter.next_tx() {
            let name = P::get_description().name;
            let mut pv = Vec::new();
            for id in v {
                if let Ok(Some(val)) = tx_read::<P>(&self.structsy.persy, &name, tx, &id) {
                    let r = Ref::new(id);
                    pv.push((r, val));
                }
            }
            let ref_tx = RefSytx {
                structsy_impl: self.structsy.clone(),
                trans: tx,
            };
            return Some((pv, k, ref_tx));
        } else {
            return None;
        }
    }
}

impl<'a, P: Persistent, K: IndexType> Iterator for RangeIterator<'a, K, P> {
    type Item = (Ref<P>, P, K);
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(it) = &mut self.iter {
                let next = it.next();
                if next.is_some() {
                    return next;
                }
            }

            if let Some((k, v)) = self.persy_iter.next() {
                let name = P::get_description().name;
                let mut pv = Vec::new();
                for id in v {
                    let tx = self.persy_iter.tx();
                    if let Ok(Some(val)) = tx_read::<P>(&self.structsy.persy, &name, tx, &id) {
                        let r = Ref::new(id);
                        pv.push((r, val, k.clone()));
                    }
                }
                self.iter = Some(pv.into_iter());
            } else {
                return None;
            }
        }
    }
}

/// Iterator implementation for Range of unique indexed persistent types
pub struct UniqueRangeIterator<'a, K: IndexType, P: Persistent> {
    structsy: Arc<StructsyImpl>,
    persy_iter: persy::TxIndexIter<'a, K, PersyId>,
    phantom: PhantomData<P>,
}

impl<'a, K: IndexType, P: Persistent> UniqueRangeIterator<'a, K, P> {
    fn new(structsy: Arc<StructsyImpl>, iter: persy::TxIndexIter<'a, K, PersyId>) -> UniqueRangeIterator<'a, K, P> {
        UniqueRangeIterator {
            structsy: structsy,
            persy_iter: iter,
            phantom: PhantomData,
        }
    }
    pub fn tx(&'a mut self) -> RefSytx<'a> {
        RefSytx {
            structsy_impl: self.structsy.clone(),
            trans: self.persy_iter.tx(),
        }
    }

    pub fn next_tx(&'a mut self) -> Option<(Ref<P>, P, K, RefSytx<'a>)> {
        let name = P::get_description().name;
        if let Some((k, v, tx)) = self.persy_iter.next_tx() {
            if let Some(id) = v.into_iter().next() {
                if let Ok(Some(val)) = tx_read::<P>(&self.structsy.persy.clone(), &name, tx, &id) {
                    let r = Ref::new(id);
                    Some((r, val, k, self.tx()))
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        }
    }
}

impl<'a, P: Persistent, K: IndexType> Iterator for UniqueRangeIterator<'a, K, P> {
    type Item = (Ref<P>, P, K);
    fn next(&mut self) -> Option<Self::Item> {
        let name = P::get_description().name;
        if let Some((k, v, tx)) = self.persy_iter.next_tx() {
            if let Some(id) = v.into_iter().next() {
                if let Ok(Some(val)) = tx_read::<P>(&self.structsy.persy.clone(), &name, tx, &id) {
                    let r = Ref::new(id);
                    Some((r, val, k))
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        }
    }
}

pub fn find_unique_range_tx<'a, K: IndexType, P: Persistent, R: RangeBounds<K>>(
    db: &'a mut dyn Sytx,
    name: &str,
    r: R,
) -> SRes<UniqueRangeIterator<'a, K, P>> {
    let p = &db.structsy().structsy_impl.persy;
    let p1 = db.structsy().structsy_impl.clone();
    let iter = p.range_tx::<K, PersyId, R>(db.tx().trans, &name, r)?;
    Ok(UniqueRangeIterator::new(p1, iter))
}

pub fn find_range_tx<'a, K: IndexType, P: Persistent, R: RangeBounds<K>>(
    db: &'a mut dyn Sytx,
    name: &str,
    r: R,
) -> SRes<RangeIterator<'a, K, P>> {
    let p = &db.structsy().structsy_impl.persy;
    let p1 = db.structsy().structsy_impl.clone();
    let iter = p.range_tx::<K, PersyId, R>(db.tx().trans, &name, r)?;
    Ok(RangeIterator::new(p1, iter))
}