rive_rs/
dyn_vec.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::cell::RefCell;
6use std::cmp::Ordering;
7
8#[derive(Debug)]
9pub struct DynVec<T> {
10    vec: RefCell<Vec<T>>,
11}
12
13impl<T> DynVec<T> {
14    pub fn new() -> Self {
15        Self { vec: RefCell::new(Vec::new()) }
16    }
17
18    pub fn is_empty(&self) -> bool {
19        self.vec.borrow().is_empty()
20    }
21
22    pub fn len(&self) -> usize {
23        self.vec.borrow().len()
24    }
25
26    pub fn push(&self, val: T) {
27        self.vec.borrow_mut().push(val);
28    }
29
30    pub fn truncate(&self, len: usize) {
31        self.vec.borrow_mut().truncate(len);
32    }
33
34    pub fn sort_by<F>(&self, compare: F)
35    where
36        F: FnMut(&T, &T) -> Ordering,
37    {
38        self.vec.borrow_mut().sort_by(compare);
39    }
40}
41
42impl<T: Clone> DynVec<T> {
43    pub fn iter(&self) -> DynVecIter<'_, T> {
44        DynVecIter { vec: &self.vec, index: 0 }
45    }
46
47    pub fn index(&self, index: usize) -> T {
48        self.vec.borrow()[index].clone()
49    }
50}
51
52impl<T> Default for DynVec<T> {
53    fn default() -> Self {
54        Self::new()
55    }
56}
57
58pub struct DynVecIter<'v, T> {
59    vec: &'v RefCell<Vec<T>>,
60    index: usize,
61}
62
63impl<T: Clone> Iterator for DynVecIter<'_, T> {
64    type Item = T;
65
66    fn next(&mut self) -> Option<Self::Item> {
67        let val = self.vec.borrow().get(self.index).cloned();
68        self.index += 1;
69        val
70    }
71}