vecdb 0.10.2

High-performance mutable persistent vectors built on rawdb
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
use std::ops::Add;

use crate::{
    AnyVec, CheckedSub, Error, Exit, ReadableVec, Result, SaturatingAdd, StoredVec, VecIndex,
    VecValue, Version, WritableVec, unlikely,
};

use super::super::EagerVec;

impl<V> EagerVec<V>
where
    V: StoredVec,
{
    fn compute_aggregate_of_others<O, F>(
        &mut self,
        max_from: V::I,
        others: &[&O],
        exit: &Exit,
        aggregate: F,
    ) -> Result<()>
    where
        O: ReadableVec<V::I, V::T>,
        F: Fn(&[Vec<V::T>], usize) -> V::T,
    {
        if others.is_empty() {
            return Err(Error::InvalidArgument(
                "others must have at least one element",
            ));
        }

        self.compute_init(
            others.iter().map(|v| v.version()).sum(),
            max_from,
            exit,
            |this| {
                let skip = this.len();
                let source_end = others.iter().map(|v| v.len()).min().unwrap();
                let end = this.batch_end(source_end);
                if skip >= end {
                    return Ok(());
                }

                let batches: Vec<Vec<V::T>> = others
                    .iter()
                    .map(|v| v.collect_range_at(skip, end))
                    .collect();

                for j in 0..(end - skip) {
                    let i = skip + j;
                    this.checked_push_at(i, aggregate(&batches, j))?;
                }

                Ok(())
            },
        )
    }

    pub fn compute_sum_of_others<O>(
        &mut self,
        max_from: V::I,
        others: &[&O],
        exit: &Exit,
    ) -> Result<()>
    where
        O: ReadableVec<V::I, V::T>,
        V::T: Add<V::T, Output = V::T>,
    {
        self.compute_aggregate_of_others(max_from, others, exit, |batches, j| {
            batches
                .iter()
                .map(|b| b[j].clone())
                .reduce(|sum, v| sum + v)
                .unwrap()
        })
    }

    pub fn compute_min_of_others<O>(
        &mut self,
        max_from: V::I,
        others: &[&O],
        exit: &Exit,
    ) -> Result<()>
    where
        O: ReadableVec<V::I, V::T>,
        V::T: Add<V::T, Output = V::T> + Ord,
    {
        self.compute_aggregate_of_others(max_from, others, exit, |batches, j| {
            batches.iter().map(|b| &b[j]).min().unwrap().clone()
        })
    }

    pub fn compute_max_of_others<O>(
        &mut self,
        max_from: V::I,
        others: &[&O],
        exit: &Exit,
    ) -> Result<()>
    where
        O: ReadableVec<V::I, V::T>,
        V::T: Add<V::T, Output = V::T> + Ord,
    {
        self.compute_aggregate_of_others(max_from, others, exit, |batches, j| {
            batches.iter().map(|b| &b[j]).max().unwrap().clone()
        })
    }

    /// Computes weighted average: sum(weight_i * value_i) / sum(weight_i)
    ///
    /// Takes parallel slices of weight and value vecs from multiple sources.
    /// For each index, computes the weighted average across all sources.
    /// Returns zero if total weight is zero.
    pub fn compute_weighted_average_of_others<W, OW, OV>(
        &mut self,
        max_from: V::I,
        weights: &[&OW],
        values: &[&OV],
        exit: &Exit,
    ) -> Result<()>
    where
        W: VecValue + Into<f64>,
        OW: ReadableVec<V::I, W>,
        OV: ReadableVec<V::I, V::T>,
        V::T: Into<f64> + From<f64>,
    {
        if weights.len() != values.len() {
            return Err(Error::InvalidArgument(
                "weights and values must have same length",
            ));
        }

        if weights.is_empty() {
            return Err(Error::InvalidArgument(
                "weights and values must have at least one element",
            ));
        }

        self.compute_init(
            weights.iter().map(|v| v.version()).sum::<Version>()
                + values.iter().map(|v| v.version()).sum(),
            max_from,
            exit,
            |this| {
                let skip = this.len();

                let source_end = weights
                    .iter()
                    .map(|w| w.len())
                    .chain(values.iter().map(|v| v.len()))
                    .min()
                    .unwrap_or(0);
                let end = this.batch_end(source_end);

                if skip >= end {
                    return Ok(());
                }

                let weight_batches: Vec<Vec<W>> = weights
                    .iter()
                    .map(|w| w.collect_range_at(skip, end))
                    .collect();
                let value_batches: Vec<Vec<V::T>> = values
                    .iter()
                    .map(|v| v.collect_range_at(skip, end))
                    .collect();

                for j in 0..(end - skip) {
                    let i = skip + j;
                    let mut total_weight = 0.0_f64;
                    let mut weighted_sum = 0.0_f64;

                    for (w_batch, v_batch) in weight_batches.iter().zip(value_batches.iter()) {
                        let weight: f64 = w_batch[j].clone().into();
                        let value: f64 = v_batch[j].clone().into();

                        if weight > 0.0 {
                            total_weight += weight;
                            weighted_sum += weight * value;
                        }
                    }

                    let result = if total_weight > 0.0 {
                        V::T::from(weighted_sum / total_weight)
                    } else {
                        V::T::from(0.0)
                    };

                    this.checked_push_at(i, result)?;
                }

                Ok(())
            },
        )
    }

    pub fn compute_sum_from_indexes<A, B>(
        &mut self,
        max_from: V::I,
        first_indexes: &impl ReadableVec<V::I, A>,
        indexes_count: &impl ReadableVec<V::I, B>,
        source: &(impl ReadableVec<A, V::T> + Sized),
        exit: &Exit,
    ) -> Result<()>
    where
        V::T: Default + SaturatingAdd,
        A: VecIndex + VecValue,
        B: VecValue,
        usize: From<B>,
    {
        self.compute_init(
            first_indexes.version() + indexes_count.version() + source.version(),
            max_from,
            exit,
            |this| {
                let skip = this.len();
                let source_end = indexes_count.len();
                let end = this.batch_end(source_end);
                if skip >= end {
                    return Ok(());
                }

                let pos = if skip < first_indexes.len() {
                    first_indexes.collect_one_at(skip).unwrap().to_usize()
                } else {
                    return Ok(());
                };

                let counts_batch: Vec<usize> = indexes_count
                    .collect_range_at(skip, end)
                    .into_iter()
                    .map(usize::from)
                    .collect();
                let total_count: usize = counts_batch.iter().sum();

                let mut group_idx = 0usize;

                // Skip leading zero-count groups
                while group_idx < counts_batch.len() && counts_batch[group_idx] == 0 {
                    this.push(V::T::default());
                    group_idx += 1;
                }

                if group_idx < counts_batch.len() {
                    let mut remaining = counts_batch[group_idx];

                    source.fold_range_at(pos, pos + total_count, V::T::default(), |sum, val: V::T| {
                        let sum = sum.saturating_add(val);
                        remaining -= 1;
                        if unlikely(remaining == 0) {
                            this.push(sum);
                            group_idx += 1;
                            while group_idx < counts_batch.len() && counts_batch[group_idx] == 0 {
                                this.push(V::T::default());
                                group_idx += 1;
                            }
                            if group_idx < counts_batch.len() {
                                remaining = counts_batch[group_idx];
                            }
                            V::T::default()
                        } else {
                            sum
                        }
                    });
                }

                Ok(())
            },
        )
    }

    pub fn compute_filtered_sum_from_indexes<A, B>(
        &mut self,
        max_from: V::I,
        first_indexes: &impl ReadableVec<V::I, A>,
        indexes_count: &impl ReadableVec<V::I, B>,
        source: &(impl ReadableVec<A, V::T> + Sized),
        mut filter: impl FnMut(&V::T) -> bool,
        exit: &Exit,
    ) -> Result<()>
    where
        V::T: Default + SaturatingAdd,
        A: VecIndex + VecValue,
        B: VecValue,
        usize: From<B>,
    {
        self.compute_init(
            first_indexes.version() + indexes_count.version() + source.version(),
            max_from,
            exit,
            |this| {
                let skip = this.len();
                let source_end = indexes_count.len();
                let end = this.batch_end(source_end);
                if skip >= end {
                    return Ok(());
                }

                let pos = if skip < first_indexes.len() {
                    first_indexes.collect_one_at(skip).unwrap().to_usize()
                } else {
                    return Ok(());
                };

                let counts_batch: Vec<usize> = indexes_count
                    .collect_range_at(skip, end)
                    .into_iter()
                    .map(usize::from)
                    .collect();
                let total_count: usize = counts_batch.iter().sum();

                let mut group_idx = 0usize;

                while group_idx < counts_batch.len() && counts_batch[group_idx] == 0 {
                    this.push(V::T::default());
                    group_idx += 1;
                }

                if group_idx < counts_batch.len() {
                    let mut remaining = counts_batch[group_idx];

                    source.fold_range_at(pos, pos + total_count, V::T::default(), |sum, val: V::T| {
                        let sum = if filter(&val) {
                            sum.saturating_add(val)
                        } else {
                            sum
                        };
                        remaining -= 1;
                        if unlikely(remaining == 0) {
                            this.push(sum);
                            group_idx += 1;
                            while group_idx < counts_batch.len() && counts_batch[group_idx] == 0 {
                                this.push(V::T::default());
                                group_idx += 1;
                            }
                            if group_idx < counts_batch.len() {
                                remaining = counts_batch[group_idx];
                            }
                            V::T::default()
                        } else {
                            sum
                        }
                    });
                }

                Ok(())
            },
        )
    }

    pub fn compute_count_from_indexes<A, B>(
        &mut self,
        max_from: V::I,
        first_indexes: &impl ReadableVec<V::I, A>,
        other_to_else: &impl ReadableVec<A, B>,
        exit: &Exit,
    ) -> Result<()>
    where
        V::T: From<A>,
        A: VecValue
            + VecIndex
            + Copy
            + Add<usize, Output = A>
            + CheckedSub<A>
            + TryInto<V::T>
            + Default,
        <A as TryInto<V::T>>::Error: core::error::Error + 'static,
        B: VecValue,
    {
        self.compute_count_from_indexes_with(
            max_from,
            first_indexes,
            other_to_else,
            |first, next_first| next_first - first,
            exit,
        )
    }

    pub fn compute_filtered_count_from_indexes<A, B>(
        &mut self,
        max_from: V::I,
        first_indexes: &impl ReadableVec<V::I, A>,
        other_to_else: &impl ReadableVec<A, B>,
        mut filter: impl FnMut(A) -> bool,
        exit: &Exit,
    ) -> Result<()>
    where
        V::T: From<A>,
        A: VecValue
            + VecIndex
            + Copy
            + Add<usize, Output = A>
            + CheckedSub<A>
            + TryInto<V::T>
            + Default,
        B: VecValue,
        <A as TryInto<V::T>>::Error: core::error::Error + 'static,
    {
        self.compute_count_from_indexes_with(
            max_from,
            first_indexes,
            other_to_else,
            |first, next_first| (first..next_first).filter(|i| filter(A::from(*i))).count(),
            exit,
        )
    }

    fn compute_count_from_indexes_with<A, B>(
        &mut self,
        max_from: V::I,
        first_indexes: &(impl ReadableVec<V::I, A> + Sized),
        other_to_else: &impl ReadableVec<A, B>,
        mut count_fn: impl FnMut(usize, usize) -> usize,
        exit: &Exit,
    ) -> Result<()>
    where
        V::T: From<A>,
        A: VecValue
            + VecIndex
            + Copy
            + Add<usize, Output = A>
            + CheckedSub<A>
            + TryInto<V::T>
            + Default,
        B: VecValue,
        <A as TryInto<V::T>>::Error: core::error::Error + 'static,
    {
        self.compute_init(
            first_indexes.version() + other_to_else.version(),
            max_from,
            exit,
            |this| {
                let skip = this.len();
                let source_end = first_indexes.len();
                let end = this.batch_end(source_end);
                if skip >= end {
                    return Ok(());
                }

                let prev_val = first_indexes.collect_one_at(skip).unwrap().to_usize();

                let last_prev =
                    first_indexes.fold_range_at(skip + 1, end, prev_val, |prev, fi: A| {
                        let next = fi.to_usize();
                        this.push(V::T::from(A::from(count_fn(prev, next))));
                        next
                    });

                let next_first = if end < first_indexes.len() {
                    first_indexes.collect_one_at(end).unwrap().to_usize()
                } else {
                    other_to_else.len()
                };
                this.push(V::T::from(A::from(count_fn(last_prev, next_first))));

                Ok(())
            },
        )
    }
}