kvtree 0.1.0

Heterogenous in memory key value tree storage
Documentation
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Container queries & iterators
mod filter;
mod iter;

pub use self::{filter::*, iter::*};
use crate::{
    data::Data,
    key::Key,
    table::{MaskIter, View},
    Match,
};
#[cfg(feature = "rayon")]
use rayon::prelude::*;
use std::{cell::UnsafeCell, fmt::Debug, hash::Hash, marker::PhantomData};

/// Trait used to read/write data from containers
pub trait Query: Filter {
    /// Data type returned by this query
    type Item<'a>;
    /// Is this query read only
    const READ_ONLY: bool;

    /// Get a single element from a [View] corresponding to this query and the given key
    fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash;

    /// applies this query to the given view
    ///
    /// Items iteration order should be the same as view.keys()
    ///
    /// returns an iterator to the values and the remaining view
    fn items<'a, K>(
        view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>);

    /// applies this query to the given view
    ///
    /// returns the remaining view and a function that returns a [Query::Item] for a given `row` index
    ///
    /// It's best to get the same index once
    ///
    /// to avoid UB: if this query is mutable, all references should be released before accessing the same index twice.
    fn by_index<'a, K>(
        view: View<'a, K>,
    ) -> (
        Option<impl (Fn(usize) -> Self::Item<'a>) + Send + Sync>,
        View<'a, K>,
    );

    /// Query parallel iterator over [Key]s and [Self::Item]
    #[cfg(feature = "rayon")]
    fn par_iter<'a, K>(
        view: View<'a, K>,
    ) -> Option<impl ParallelQueryIter<Item = (&'a Key<K>, Self::Item<'a>)>>
    where
        Self: 'a,
        K: Send + Sync,
        Self::Item<'a>: Send + Sync,
    {
        if let (Some(items), view) = Self::by_index(view) {
            Some(
                view.index()
                    .keys()
                    .par_iter()
                    .enumerate()
                    .map(move |(i, x)| (x, items(i))),
            )
        } else {
            None
        }
    }

    /// Query iterator over [Key]s and [Self::Item]
    fn iter<'a, K>(
        view: View<'a, K>,
    ) -> Box<dyn QueryIter<Item = (&'a Key<K>, Self::Item<'a>)> + 'a>
    where
        Self: 'a,
    {
        if let (Some(x), view) = Self::items(view) {
            Box::new(view.index().keys().iter().zip(x))
        } else {
            Box::new(std::iter::empty())
        }
    }

    /// Query iterator over [Key]s and [Self::Item] ordered by keys
    fn iter_indexed<'a, K>(
        view: View<'a, K>,
    ) -> Box<dyn QueryIter<Item = (&'a Key<K>, Self::Item<'a>)> + 'a>
    where
        Self: 'a,
    {
        if let (Some(x), view) = Self::by_index(view) {
            let ks = view.index().keys();
            Box::new(view.index().index().iter().map(move |i| (&ks[*i], x(*i))))
        } else {
            Box::new(std::iter::empty())
        }
    }
    /// Query iterator over [Key]s and [Self::Item] where keys are ordered and filtered by the given [mask](Match<K>)
    fn mask<'a, 'b, K>(
        view: View<'a, K>,
        mask: &'b impl Match<K>,
    ) -> impl QueryMaskIter<Item = (&'a Key<K>, Self::Item<'a>)>
    where
        Self: 'a,
        'b: 'a,
    {
        let index = view.index();
        let cols = match Self::by_index(view) {
            (Some(cols), _) => cols,
            (..) => return None.into_iter().flatten(),
        };
        Some(MaskIter::new(index, mask).map(move |(x, y)| (x, cols(y))))
            .into_iter()
            .flatten()
    }
}

fn any_value(_: usize) {}

impl Query for () {
    type Item<'a> = ();

    const READ_ONLY: bool = true;

    fn get<'a, K>(_: &mut View<'a, K>, _: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash,
    {
        Some(())
    }

    fn items<'a, K>(
        view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
        (Some(view.index().keys().iter().map(|_| ())), view)
    }

    fn by_index<'a, K>(
        view: View<'a, K>,
    ) -> (Option<impl (Fn(usize) -> Self::Item<'a>)>, View<'a, K>) {
        (Some(any_value), view)
    }
}

impl<T: Data> Query for &T {
    type Item<'a> = &'a T;

    const READ_ONLY: bool = true;

    fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash,
    {
        view.index_of(key).and_then(|x| Some(&view.read::<T>()?[x]))
    }

    fn items<'a, K>(
        mut view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
        (view.read::<T>().map(|x| x.iter()), view)
    }

    fn by_index<'a, K>(
        mut view: View<'a, K>,
    ) -> (Option<impl (Fn(usize) -> Self::Item<'a>)>, View<'a, K>) {
        (
            match view.read::<T>() {
                Some(rows) => Some(move |row_idx| &rows[row_idx]),
                None => None,
            },
            view,
        )
    }
}

impl<T: Data + Debug> Query for Option<&T> {
    type Item<'a> = Option<&'a T>;

    const READ_ONLY: bool = true;

    fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash,
    {
        view.index_of(key).map(|x| view.read::<T>().map(|y| &y[x]))
    }

    fn items<'a, K>(
        mut view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
        (
            view.read::<T>().map_or_else(
                || {
                    Some(Box::new((0..view.len_rows()).map(|_| None))
                        as Box<dyn QueryIter<Item = Self::Item<'_>>>)
                },
                |x| Some(Box::new(x.iter().map(Some)) as Box<dyn QueryIter<Item = Self::Item<'_>>>),
            ),
            view,
        )
    }

    fn by_index<'a, K>(
        mut view: View<'a, K>,
    ) -> (
        Option<impl (Fn(usize) -> Self::Item<'a>) + Send + Sync>,
        View<'a, K>,
    ) {
        (
            if let Some(rows) = view.read::<T>() {
                Some(Box::new(|row_idx| Some(&rows[row_idx]))
                    as Box<dyn (Fn(usize) -> Self::Item<'a>) + Send + Sync>)
            } else {
                Some(Box::new(|_| None))
            },
            view,
        )
    }
}

/// Wrapper over slice of [UnsafeCell]
///
/// Should only be used to access disjoint slice index
#[derive(Copy, Clone)]
struct UnsafeSlice<'a, T>(&'a [UnsafeCell<T>]);

unsafe impl<'a, T: Send + Sync> Send for UnsafeSlice<'a, T> {}
unsafe impl<'a, T: Send + Sync> Sync for UnsafeSlice<'a, T> {}

impl<'a, T> UnsafeSlice<'a, T> {
    fn new(slice: &'a mut [T]) -> Self {
        // SAFETY: `UnsafeCell` has the same layout as T
        Self(unsafe { &*(slice as *mut [T] as *const [UnsafeCell<T>]) })
    }

    /// get a mutable reference to the element at position `index`
    ///
    /// SAFETY: access to elements is safe for any unique index.
    unsafe fn get_mut(&self, index: usize) -> &'a mut T {
        &mut *self.0[index].get()
    }
}

#[inline(always)]
fn random_access_mut<'a, T: Send + Sync>(
    slice: &'a mut [T],
) -> impl (Fn(usize) -> &'a mut T) + Send + Sync {
    let slice = UnsafeSlice::new(slice);
    // Safety: access of elements is done by disjoint indices in a specific order
    #[inline(always)]
    move |idx| unsafe { slice.get_mut(idx) }
}

impl<T: Data> Query for &mut T {
    type Item<'a> = &'a mut T;

    const READ_ONLY: bool = false;

    fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash,
    {
        view.index_of(key)
            .and_then(|x| Some(&mut view.write::<T>()?[x]))
    }

    fn items<'a, K>(
        mut view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
        (view.write::<T>().map(|x| x.iter_mut()), view)
    }

    fn by_index<'a, K>(
        mut view: View<'a, K>,
    ) -> (Option<impl (Fn(usize) -> Self::Item<'a>)>, View<'a, K>) {
        (view.write::<T>().map(random_access_mut), view)
    }
}

fn none_opt<I>(_: usize) -> Option<I> {
    None
}

impl<T: Data> Query for Option<&mut T> {
    type Item<'a> = Option<&'a mut T>;

    const READ_ONLY: bool = false;

    fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash,
    {
        view.index_of(key)
            .map(|x| view.write::<T>().map(|y| &mut y[x]))
    }

    fn items<'a, K>(
        mut view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
        (
            view.write::<T>().map_or_else(
                || {
                    Some(Box::new((0..view.len_rows()).map(|_| None))
                        as Box<dyn QueryIter<Item = Self::Item<'_>>>)
                },
                |x| {
                    Some(Box::new(x.iter_mut().map(Some))
                        as Box<dyn QueryIter<Item = Self::Item<'_>>>)
                },
            ),
            view,
        )
    }

    fn by_index<'a, K>(
        mut view: View<'a, K>,
    ) -> (
        Option<impl (Fn(usize) -> Self::Item<'a>) + Send + Sync>,
        View<'a, K>,
    ) {
        (
            if let Some(rows) = view.write::<T>().map(random_access_mut) {
                Some(Box::new(move |row_idx| Some(rows(row_idx)))
                    as Box<dyn (Fn(usize) -> Self::Item<'a>) + Send + Sync>)
            } else {
                Some(Box::new(none_opt))
            },
            view,
        )
    }
}

impl<Q: Query + 'static> Query for (Q,) {
    type Item<'a> = (Q::Item<'a>,);

    const READ_ONLY: bool = Q::READ_ONLY;

    fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
    where
        Key<K>: Eq + Hash,
    {
        Q::get(view, key).map(|x| (x,))
    }

    fn items<'a, K>(
        view: View<'a, K>,
    ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
        let (q, view) = Q::items(view);
        (q.map(|x| x.map(|x| (x,))), view)
    }

    fn by_index<'a, K>(
        view: View<'a, K>,
    ) -> (Option<impl Fn(usize) -> Self::Item<'a>>, View<'a, K>) {
        match Q::by_index(view) {
            (Some(x), view) => (Some(move |y| (x(y),)), view),
            (None, view) => (None, view),
        }
    }
}

/// Query that returns an item if at least one of the inner queries returns an item
pub struct AnyOf<Q>(PhantomData<Q>);

macro_rules! query_impl {
    ($_head:ident) => {};
    ($head:ident $($tail:ident) *) => {
        query_impl!($($tail) *);

        impl<$head: Query + 'static, $($tail: Query + 'static), *> Query for ($head, $($tail), *)
        {
            type Item<'a> = ($head::Item<'a>, $($tail::Item<'a>), *);

            const READ_ONLY: bool = $head::READ_ONLY $(&& $tail::READ_ONLY) *;

            fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
            where
                Key<K>: Eq + Hash,
            {
                use tuplify::ValidateOpt;
                ($head::get(view, key), $($tail::get(view, key)), *).validate()
            }

            #[allow(non_snake_case)]
            fn items<'a, K>(
                view: View<'a, K>,
            ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
                use itertools::izip;
                let ($head, view) = match $head::items(view) {
                    (Some(x), y) => (x, y),
                    (None, x) => return (None, x)
                };
                $(let ($tail, view) = match $tail::items(view) {
                    (Some(x), y) => (x, y),
                    (None, x) => return (None, x)
                };) *
                (Some(izip!($head, $($tail), *)), view)
            }

            #[allow(non_snake_case)]
            fn by_index<'a, K>(
                view: View<'a, K>,
            ) -> (Option<impl (Fn(usize) -> Self::Item<'a>) + Send + Sync >, View<'a, K>) {
                let ($head, view) = match $head::by_index(view) {
                    (Some(x), y) => (x, y),
                    (None, x) => return (None, x)
                };
                $(let ($tail, view) = match $tail::by_index(view) {
                    (Some(x), y) => (x, y),
                    (None, x) => return (None, x)
                };) *
                (Some(move |index| ($head(index), $($tail(index)), *)), view)
            }
        }

        impl<$head: Filter + 'static, $($tail: Filter + 'static), *> Filter for AnyOf<($head, $($tail), *)> {
            fn match_view<K>(view: &View<K>) -> bool { $head::match_view(view) $(|| $tail::match_view(view)) * }
        }

        impl<$head: Query + 'static, $($tail: Query + 'static), *> Query for AnyOf<($head, $($tail), *)> {
            type Item<'a> = (Option<<$head as Query>::Item<'a>>, $(Option<<$tail as Query>::Item<'a>>), *);

            const READ_ONLY: bool = $head::READ_ONLY $(&& $tail::READ_ONLY) *;

            #[allow(non_snake_case)]
            fn get<'a, K>(view: &mut View<'a, K>, key: &Key<K>) -> Option<Self::Item<'a>>
            where
                Key<K>: Eq + Hash,
            {
                let ($head, $($tail), *) = ($head::get(view, key), $($tail::get(view, key)), *);
                if $head.is_some() $(|| $tail.is_some()) * {
                    Some(($head, $($tail), *))
                } else {
                    None
                }
            }

            #[allow(non_snake_case)]
            fn items<'a, K>(
                view: View<'a, K>,
            ) -> (Option<impl QueryIter<Item = Self::Item<'a>>>, View<'a, K>) {
                use itertools::izip;
                let mut any = true;
                let len_rows = view.len_rows();
                let ($head, view) = $head::items(view);
                let $head = if let Some(x) = $head {
                    any &= true;
                    Box::new(x.map(Some)) as Box<dyn QueryIter<Item = Option<<$head as Query>::Item<'_>>> + '_>
                } else {
                    Box::new((0..len_rows).map(|_| None))
                };
                $(
                    let ($tail, view) = $tail::items(view);
                    let $tail = if let Some(x) = $tail {
                        any &= true;
                        Box::new(x.map(Some)) as Box<dyn QueryIter<Item = Option<<$tail as Query>::Item<'_>>> + '_>
                    } else {
                        Box::new((0..len_rows).map(|_| None))
                    };
                ) *
                (if any { Some(izip!($head, $($tail), *)) } else { None }, view)
            }

            #[allow(non_snake_case)]
            fn by_index<'a, K>(
                view: View<'a, K>,
            ) -> (Option<impl (Fn(usize) -> Self::Item<'a>) + Send + Sync >, View<'a, K>) {
                let mut any = false;
                let ($head, view) = match $head::by_index(view) {
                    (None, x) => (Box::new(|_| None) as Box<dyn (Fn(usize) -> Option<$head::Item<'a>>) + Send + Sync >, x),
                    (Some(x), y) => ({ any |= true; Box::new(move |y| Some(x(y))) as Box<dyn (Fn(usize) -> Option<$head::Item<'a>>) + Send + Sync > }, y),
                };
                $(let ($tail, view) = match $tail::by_index(view) {
                    (None, x) => (Box::new(|_| None) as Box<dyn (Fn(usize) ->  Option<$tail::Item<'a>>) + Send + Sync >, x),
                    (Some(x), y) => ({ any |= true; Box::new(move |y| Some(x(y))) as Box<dyn (Fn(usize) ->  Option<$tail::Item<'a>>) + Send + Sync > }, y),
                };) *
                (if any { Some(move |index| ($head(index), $($tail(index)), *)) } else { None }, view)
            }
        }
    };
}

query_impl!(T1 T2 T3 T4 T5 T6 T7 T8 T9 T10 T11 T12 T13 T14 T15 T16 T17 T18 T19 T20 T21 T22 T23 T24 T25 T26 T27 T28 T29 T30 T31 T32);