rive_rs/
dyn_vec.rs

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
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::cell::RefCell;
use std::cmp::Ordering;

#[derive(Debug)]
pub struct DynVec<T> {
    vec: RefCell<Vec<T>>,
}

impl<T> DynVec<T> {
    pub fn new() -> Self {
        Self { vec: RefCell::new(Vec::new()) }
    }

    pub fn is_empty(&self) -> bool {
        self.vec.borrow().is_empty()
    }

    pub fn len(&self) -> usize {
        self.vec.borrow().len()
    }

    pub fn push(&self, val: T) {
        self.vec.borrow_mut().push(val);
    }

    pub fn truncate(&self, len: usize) {
        self.vec.borrow_mut().truncate(len);
    }

    pub fn sort_by<F>(&self, compare: F)
    where
        F: FnMut(&T, &T) -> Ordering,
    {
        self.vec.borrow_mut().sort_by(compare);
    }
}

impl<T: Clone> DynVec<T> {
    pub fn iter(&self) -> DynVecIter<'_, T> {
        DynVecIter { vec: &self.vec, index: 0 }
    }

    pub fn index(&self, index: usize) -> T {
        self.vec.borrow()[index].clone()
    }
}

impl<T> Default for DynVec<T> {
    fn default() -> Self {
        Self::new()
    }
}

pub struct DynVecIter<'v, T> {
    vec: &'v RefCell<Vec<T>>,
    index: usize,
}

impl<T: Clone> Iterator for DynVecIter<'_, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let val = self.vec.borrow().get(self.index).cloned();
        self.index += 1;
        val
    }
}