dbsp 0.287.0

Continuous streaming analytics engine
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use std::{
    cmp::Ordering,
    marker::PhantomData,
    mem::take,
    ops::{Deref, DerefMut, Index, IndexMut},
};

use rand::{RngCore, thread_rng};

use crate::{
    DBData, declare_trait_object,
    dynamic::DataTraitTyped,
    utils::{
        dyn_advance, dyn_retreat, stable_sort, stable_sort_by, {self},
    },
};

use super::{Data, DataTrait, DowncastTrait, Erase, LeanVec, RawIter};

// TODO: `trait Slice`, move vector methods that operate on slices there.

/// A dynamically typed interface to `LeanVec`
pub trait Vector<T: DataTrait + ?Sized>: Data {
    /// Return the length of the vector.
    fn len(&self) -> usize;

    /// Return the total number of elements the vector can hold without reallocating.s
    fn capacity(&self) -> usize;

    /// Return the remaining spare capacity of the vector.
    fn spare_capacity(&self) -> usize {
        self.capacity() - self.len()
    }

    /// Check whether `self` has spare capacity for at least one element.
    fn has_spare_capacity(&self) -> bool {
        self.spare_capacity() > 0
    }

    /// Return `true` if the vector contains no elements.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clear the vector, removing all values.
    fn clear(&mut self);

    /// Shrink the capacity of the vector as much as possible.
    fn shrink_to_fit(&mut self);

    /// Append an element to the back of the vector without cloning.
    ///
    /// Sets `val` to the default value
    fn push_val(&mut self, val: &mut T);

    /// Append an element to the back of the vector.
    fn push_ref(&mut self, val: &T);

    /// Append an element to the back of the vector; call `f` to initialize the new element.
    fn push_with(&mut self, f: &mut dyn FnMut(&mut T));

    /// Return a reference to the element at `index`; panic if `index >= self.len()`.
    fn index(&self, index: usize) -> &T;

    /// Return a reference to the first element, or `None` if empty.
    fn first(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            Some(self.index(0))
        }
    }

    /// Return a mutable reference to the first element, or `None` if empty.
    fn first_mut(&mut self) -> Option<&mut T> {
        if self.is_empty() {
            None
        } else {
            Some(self.index_mut(0))
        }
    }

    /// Return a reference to the last element, or `None` if empty.
    fn last(&self) -> Option<&T> {
        if self.is_empty() {
            None
        } else {
            Some(self.index(self.len() - 1))
        }
    }

    /// Return a mutable reference to the last element, or `None` if empty.
    fn last_mut(&mut self) -> Option<&mut T> {
        if self.is_empty() {
            None
        } else {
            Some(self.index_mut(self.len() - 1))
        }
    }

    /// Return a reference to the element at `index`, eliding bounds checks.
    ///
    /// # Safety
    ///
    /// `index` must be within bounds.
    unsafe fn index_unchecked(&self, index: usize) -> &T;

    /// Return a mutable reference to the element at `index`; panic if `index >= self.len()`.
    fn index_mut(&mut self, index: usize) -> &mut T;

    /// Return a mutable reference to an element at `index`, eliding bounds
    /// checks.
    ///
    /// # Safety
    ///
    /// `index` must be within bounds.
    unsafe fn index_mut_unchecked(&mut self, index: usize) -> &mut T;

    /// Swap value at indexes `a` and `b`.
    fn swap(&mut self, a: usize, b: usize);

    /// Reserve capacity for at least `additional` more elements.
    ///
    /// May reserve more space to speculatively avoid frequent reallocations.  After calling
    /// `reserve`, capacity will be greater than or equal to `self.len() + additional`.
    /// Does nothing if capacity is already sufficient.
    fn reserve(&mut self, additional: usize);

    /// Reserve capacity for exactly `additional` more elements.
    ///
    /// Does nothing if capacity is already sufficient.
    fn reserve_exact(&mut self, additional: usize);

    /// Append values in the range `from..to` in `other` to `self`.
    fn extend_from_range(&mut self, other: &DynVec<T>, from: usize, to: usize);

    /// Append values in `other` to `self`.
    fn extend(&mut self, other: &DynVec<T>);

    /// Append the entire contents of `other` to `self`.
    ///
    /// Values in `other` are moved rather than cloned into `self`, leaving `other`
    /// empty.  The `capacity` of `other` is not affected by this function.
    fn append(&mut self, other: &mut DynVec<T>);

    /// Append the values in the range `from..to` in `other` to `self`.
    ///
    /// Values are moved rather than cloned, leaving default values in `other`.
    fn append_range(&mut self, other: &mut DynVec<T>, from: usize, to: usize);

    /// Return the number of elements in the `from..to` range where the predicate is true.
    ///
    /// Assumes that once the predicate doesn't hold for a value in the range, it
    /// also doesn't hold for all subsequent values.
    fn advance_while(&self, from: usize, to: usize, predicate: &dyn Fn(&T) -> bool) -> usize;

    /// Return the number of elements in the `from..to` range where the predicate is false.
    ///
    /// Assumes that once the predicate is `true` for a value in the range, it
    /// also holds for all subsequent values.
    fn advance_until(&self, from: usize, to: usize, predicate: &dyn Fn(&T) -> bool) -> usize;

    /// Return the number of elements in the `from..to` range that are smaller than `val`.
    ///
    /// Assumes that the vector is sorted in the ascending order.
    fn advance_to(&self, from: usize, to: usize, val: &T) -> usize;

    /// Returns the number of elements in the `from..=to` range where the predicate evaluates to
    /// true.
    ///
    /// Assumes that once the predicate doesn't hold for an index `i`, it also doesn't hold for
    /// any `j < i`.
    fn retreat_while(&self, from: usize, to: usize, predicate: &dyn Fn(&T) -> bool) -> usize;

    /// Returns the number of elements in the `from..=to` range where the predicate evaluates to
    /// false.
    ///
    /// Assumes that once the predicate holds for an index `i`, it also holds for
    /// any `j < i`.
    fn retreat_until(&self, from: usize, to: usize, predicate: &dyn Fn(&T) -> bool) -> usize;

    /// Returns the number of elements in the `from..=to` range that are greater than `val`.
    ///
    /// Assumes that the vector is sorted in the ascending order.
    fn retreat_to(&self, from: usize, to: usize, val: &T) -> usize;

    /// Forces the length of the vector to `new_len`.
    ///
    /// This is a low-level operation that maintains none of the normal
    /// invariants of the type. Normally changing the length of a vector is
    /// done using one of the safe operations instead, such as truncate,
    /// resize, extend, or clear.
    ///
    /// # Safety
    ///
    /// `new_len` must be less than or equal to `capacity()`.
    /// The elements at `old_len..new_len` must be initialized.
    unsafe fn set_len(&mut self, len: usize);

    /// Shortens the vector, keeping the first len elements and dropping the rest.
    ///
    /// If len is greater or equal to the vector’s current length, this has no effect.
    /// Note that this method has no effect on the allocated capacity of the vector.
    fn truncate(&mut self, len: usize);

    /// Sort the vector using a stable sorting algorithm.
    fn sort(&mut self) {
        self.sort_slice(0, self.len());
    }

    /// Sort a range of the vector using a stable sorting algorithm.
    fn sort_slice(&mut self, from: usize, to: usize);

    /// Sort the vector using an unstable sorting algorithm.
    fn sort_unstable(&mut self) {
        self.sort_slice_unstable(0, self.len())
    }

    /// Sort a range of the vector using an unstable sort algorithm.
    fn sort_slice_unstable(&mut self, from: usize, to: usize);

    /// Sort a range of the vector with a comparator function using a stable sort algorithm.
    fn sort_slice_by(&mut self, from: usize, to: usize, cmp: &dyn Fn(&T, &T) -> Ordering);

    /// Sort the vector with a comparator function using an unstable sort algorithm.
    fn sort_unstable_by(&mut self, cmp: &dyn Fn(&T, &T) -> Ordering) {
        self.sort_slice_unstable_by(0, self.len(), cmp)
    }

    /// Sort a range of the vector with a comparator function using an unstable sort algorithm.
    fn sort_slice_unstable_by(&mut self, from: usize, to: usize, cmp: &dyn Fn(&T, &T) -> Ordering);

    /// Check if the vector is sorted according to the ordering induced by `compare`.
    fn is_sorted_by(&self, compare: &dyn Fn(&T, &T) -> Ordering) -> bool;

    /// Remove all but the first of equal consecutive elements in the vector.
    fn dedup(&mut self);

    /// Return a read-only iterator over the vector.
    fn dyn_iter<'a>(&'a self) -> Box<dyn DoubleEndedIterator<Item = &'a T> + 'a>;

    /// Return a mutable iterator over the vector.
    fn dyn_iter_mut<'a>(&'a mut self) -> Box<dyn DoubleEndedIterator<Item = &'a mut T> + 'a>;

    /// Compute a uniform random sample of a range of the vector.
    fn sample_slice(
        &self,
        from: usize,
        to: usize,
        rng: &mut dyn RngCore,
        sample_size: usize,
        callback: &mut dyn FnMut(&T),
    );

    /// Cast any trait object that implements this trait to `&DynVec`.
    ///
    /// This method will not be needed once trait downcasting has been stabilized.
    fn as_vec(&self) -> &DynVec<T>;

    /// Cast any trait object that implements this trait to `&mut DynVec`.
    ///
    /// This method will not be needed once trait downcasting has been stabilized.
    fn as_vec_mut(&mut self) -> &mut DynVec<T>;
}

pub trait VecTrait<T: DataTrait + ?Sized>: Vector<T> + DataTrait {}

impl<V, T: DataTrait + ?Sized> VecTrait<T> for V where V: Vector<T> + DataTrait {}

declare_trait_object!(DynVec<T> = dyn Vector<T>
where
    T: DataTrait + ?Sized
);

const APPROXIMATE_BYTE_SIZE_SAMPLE_SIZE: usize = 100;

impl<T: DataTrait + ?Sized> DynVec<T> {
    pub fn approximate_byte_size(&self) -> usize {
        if self.len() <= APPROXIMATE_BYTE_SIZE_SAMPLE_SIZE {
            return self.size_of().total_bytes();
        }

        let mut acc = 0;

        self.sample_slice(
            0,
            self.len(),
            &mut thread_rng(),
            APPROXIMATE_BYTE_SIZE_SAMPLE_SIZE,
            &mut |x| acc += x.size_of().total_bytes(),
        );
        let average = (acc as f64) / (APPROXIMATE_BYTE_SIZE_SAMPLE_SIZE as f64);
        (average * self.len() as f64).round() as usize
    }
}

impl<T: DataTraitTyped + ?Sized> Deref for DynVec<T> {
    type Target = LeanVec<T::Type>;

    fn deref(&self) -> &Self::Target {
        // Safety: this is safe assuming `LeanVec` is the only type that implements
        // `trait Vector`.
        unsafe { self.downcast::<Self::Target>() }
    }
}

impl<T: DataTraitTyped + ?Sized> DerefMut for DynVec<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        // Safety: this is safe assuming `LeanVec` is the only type that implements
        // `trait Vector`.
        unsafe { self.downcast_mut::<Self::Target>() }
    }
}

impl<T: DataTrait + ?Sized> Index<usize> for DynVec<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        Vector::index(self, index)
    }
}

impl<T: DataTrait + ?Sized> IndexMut<usize> for DynVec<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        Vector::index_mut(self, index)
    }
}

impl<T, Trait> Vector<Trait> for LeanVec<T>
where
    Trait: DataTrait + ?Sized,
    T: DBData + Erase<Trait>,
{
    fn len(&self) -> usize {
        LeanVec::len(self)
    }

    fn capacity(&self) -> usize {
        LeanVec::capacity(self)
    }

    fn clear(&mut self) {
        LeanVec::clear(self)
    }

    fn shrink_to_fit(&mut self) {
        self.vec.shrink_to_fit()
    }

    fn push_val(&mut self, val: &mut Trait) {
        let val = take(unsafe { val.downcast_mut::<T>() });

        LeanVec::push(self, val);
    }

    fn push_ref(&mut self, val: &Trait) {
        let val = unsafe { val.downcast::<T>() }.clone();

        LeanVec::push(self, val);
    }

    fn push_with(&mut self, f: &mut dyn FnMut(&mut Trait)) {
        let mut val: T = Default::default();
        f(val.erase_mut());

        LeanVec::push(self, val);
    }

    fn index(&self, index: usize) -> &Trait {
        LeanVec::get(self, index).erase()
    }

    fn index_mut(&mut self, index: usize) -> &mut Trait {
        LeanVec::get_mut(self, index).erase_mut()
    }

    unsafe fn index_unchecked(&self, index: usize) -> &Trait {
        unsafe { LeanVec::get_unchecked(self, index).erase() }
    }

    unsafe fn index_mut_unchecked(&mut self, index: usize) -> &mut Trait {
        unsafe { LeanVec::get_mut_unchecked(self, index).erase_mut() }
    }

    fn swap(&mut self, a: usize, b: usize) {
        // TODO: implement `swap` as a method of `LeanVec` to reduce code size.
        self.as_mut_slice().swap(a, b)
    }

    fn reserve(&mut self, reservation: usize) {
        LeanVec::reserve(self, reservation)
    }

    fn reserve_exact(&mut self, reservation: usize) {
        LeanVec::reserve_exact(self, reservation)
    }

    fn extend_from_range(&mut self, other: &DynVec<Trait>, from: usize, to: usize) {
        let other = unsafe { other.downcast::<Self>() };

        LeanVec::extend_from_slice(self, &other[from..to])
    }

    fn extend(&mut self, other: &DynVec<Trait>) {
        let other = unsafe { other.downcast::<Self>() };

        LeanVec::extend_from_slice(self, &other[..])
    }

    fn append(&mut self, other: &mut DynVec<Trait>) {
        let other = unsafe { other.downcast_mut::<Self>() };

        LeanVec::append(self, other);
    }

    fn append_range(&mut self, other: &mut DynVec<Trait>, from: usize, to: usize) {
        let other = unsafe { other.downcast_mut::<Self>() };

        LeanVec::append_from_slice(self, &mut other[from..to])
    }

    fn advance_while(&self, from: usize, to: usize, predicate: &dyn Fn(&Trait) -> bool) -> usize {
        dyn_advance(&self[from..to], &|val| {
            predicate(unsafe { &*(val as *const T) }.erase())
        })
    }

    fn advance_until(&self, from: usize, to: usize, predicate: &dyn Fn(&Trait) -> bool) -> usize {
        dyn_advance(&self[from..to], &|val| {
            !predicate(unsafe { &*(val as *const T) }.erase())
        })
    }

    fn advance_to(&self, from: usize, to: usize, val: &Trait) -> usize {
        let val = unsafe { val.downcast::<T>() };

        dyn_advance(&self[from..to], &|x| unsafe { &*(x as *const T) } < val)
    }

    fn retreat_while(&self, from: usize, to: usize, predicate: &dyn Fn(&Trait) -> bool) -> usize {
        dyn_retreat(&self[from..=to], &|val| {
            predicate(unsafe { &*(val as *const T) }.erase())
        })
    }

    fn retreat_until(&self, from: usize, to: usize, predicate: &dyn Fn(&Trait) -> bool) -> usize {
        dyn_retreat(&self[from..=to], &|val| {
            !predicate(unsafe { &*(val as *const T) }.erase())
        })
    }

    fn retreat_to(&self, from: usize, to: usize, val: &Trait) -> usize {
        let val = unsafe { val.downcast::<T>() };

        dyn_retreat(&self[from..=to], &|x| unsafe { &*(x as *const T) } > val)
    }

    unsafe fn set_len(&mut self, len: usize) {
        unsafe { LeanVec::set_len(self, len) }
    }

    fn truncate(&mut self, len: usize) {
        LeanVec::truncate(self, len)
    }

    fn sort_slice(&mut self, from: usize, to: usize) {
        //self[from..to].sort()
        stable_sort(&mut self[from..to]);
    }

    fn sort_slice_by(&mut self, from: usize, to: usize, cmp: &dyn Fn(&Trait, &Trait) -> Ordering) {
        stable_sort_by(&mut self[from..to], |x, y| cmp(x.erase(), y.erase()))
    }

    fn sort_slice_unstable(&mut self, from: usize, to: usize) {
        // FIXME: The unstable sort implementation in `utils/sort.rs` requires additional testing
        // and benchmarking.  Use stable sort for now.
        stable_sort(&mut self[from..to]);

        //self[from..to].sort_unstable()
    }

    fn sort_slice_unstable_by(
        &mut self,
        from: usize,
        to: usize,
        cmp: &dyn Fn(&Trait, &Trait) -> Ordering,
    ) {
        // FIXME: The unstable sort implementation in `utils/sort.rs` requires additional testing
        // and benchmarking.  Use stable sort for now.
        stable_sort_by(&mut self[from..to], |x, y| cmp(x.erase(), y.erase()))
    }

    fn dedup(&mut self) {
        LeanVec::dedup(self);
    }
    fn dyn_iter<'a>(&'a self) -> Box<dyn DoubleEndedIterator<Item = &'a Trait> + 'a> {
        Box::new(VecIter::new(self))
    }

    fn dyn_iter_mut<'a>(&'a mut self) -> Box<dyn DoubleEndedIterator<Item = &'a mut Trait> + 'a> {
        Box::new(VecIterMut::new(self))
    }

    fn sample_slice(
        &self,
        from: usize,
        to: usize,
        rng: &mut dyn RngCore,
        sample_size: usize,
        callback: &mut dyn FnMut(&Trait),
    ) {
        utils::sample_slice(&self[from..to], rng, sample_size, &mut |x: &T| {
            callback(x.erase())
        });
    }

    fn as_vec(&self) -> &DynVec<Trait> {
        self
    }

    fn as_vec_mut(&mut self) -> &mut DynVec<Trait> {
        self
    }

    fn is_sorted_by(&self, compare: &dyn Fn(&Trait, &Trait) -> Ordering) -> bool {
        LeanVec::is_sorted_by(self, |x, y| compare(x.erase(), y.erase()))
    }
}

struct VecIter<'a, T, Trait: ?Sized> {
    iter: RawIter<'a>,
    phantom: PhantomData<(&'a T, &'a Trait)>,
}

impl<'a, T, Trait: ?Sized> VecIter<'a, T, Trait> {
    fn new(vec: &'a LeanVec<T>) -> Self {
        Self {
            iter: vec.raw_iter(),
            phantom: PhantomData,
        }
    }
}

impl<'a, T, Trait: DataTrait + ?Sized> Iterator for VecIter<'a, T, Trait>
where
    T: Erase<Trait>,
{
    type Item = &'a Trait;

    fn next(&mut self) -> Option<&'a Trait> {
        self.iter
            .next()
            .map(|x| unsafe { &*(x as *const T) }.erase())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.iter.count()
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.iter
            .nth(n)
            .map(|x| unsafe { &*(x as *const T) }.erase())
    }

    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.iter
            .last()
            .map(|x| unsafe { &*(x as *const T) }.erase())
    }
}

impl<'a, T, Trait: DataTrait + ?Sized> DoubleEndedIterator for VecIter<'a, T, Trait>
where
    T: Erase<Trait>,
{
    fn next_back(&mut self) -> Option<&'a Trait> {
        self.iter
            .next_back()
            .map(|x| unsafe { &*(x as *const T) }.erase())
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.iter
            .nth_back(n)
            .map(|x| unsafe { &*(x as *const T) }.erase())
    }
}

struct VecIterMut<'a, T, Trait: ?Sized> {
    iter: RawIter<'a>,
    phantom: PhantomData<(&'a mut T, &'a Trait)>,
}

impl<'a, T, Trait: ?Sized> VecIterMut<'a, T, Trait> {
    fn new(vec: &'a mut LeanVec<T>) -> Self {
        Self {
            iter: vec.raw_iter(),
            phantom: PhantomData,
        }
    }
}

impl<'a, T, Trait: DataTrait + ?Sized> Iterator for VecIterMut<'a, T, Trait>
where
    T: Erase<Trait>,
{
    type Item = &'a mut Trait;

    fn next(&mut self) -> Option<&'a mut Trait> {
        self.iter
            .next()
            .map(|x| unsafe { &mut *(x as *mut T) }.erase_mut())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.iter.count()
    }

    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.iter
            .nth(n)
            .map(|x| unsafe { &mut *(x as *mut T) }.erase_mut())
    }

    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.iter
            .last()
            .map(|x| unsafe { &mut *(x as *mut T) }.erase_mut())
    }
}

impl<'a, T, Trait: DataTrait + ?Sized> DoubleEndedIterator for VecIterMut<'a, T, Trait>
where
    T: Erase<Trait>,
{
    fn next_back(&mut self) -> Option<&'a mut Trait> {
        self.iter
            .next_back()
            .map(|x| unsafe { &mut *(x as *mut T) }.erase_mut())
    }

    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        self.iter
            .nth_back(n)
            .map(|x| unsafe { &mut *(x as *mut T) }.erase_mut())
    }
}

#[cfg(test)]
mod test {
    use crate::{
        dynamic::{DowncastTrait, DynData, DynVec, LeanVec, WithFactory},
        lean_vec,
    };

    #[test]
    fn dyn_vec_test() {
        let factory = <DynVec<DynData> as WithFactory<LeanVec<String>>>::FACTORY;

        let mut vec = factory.default_box();

        vec.push_val(&mut "foo".to_string());
        vec.push_ref(&"bar".to_string());
        let contents = vec
            .dyn_iter()
            .map(|x| x.downcast_checked::<String>().clone())
            .collect::<Vec<String>>();

        assert_eq!(
            LeanVec::from(contents),
            lean_vec!["foo".to_string(), "bar".to_string()]
        );
    }
}