fuchsia_rcu_collections/
rcu_array.rs1use fuchsia_rcu::{RcuBox, RcuDroppable, RcuReadScope};
6
7#[derive(Default, Debug, RcuDroppable)]
14pub struct RcuArray<T: RcuDroppable + Sync> {
15 inner: RcuBox<Box<[T]>>,
16}
17
18impl<T: RcuDroppable + Sync> RcuArray<T> {
19 pub fn get<'a>(&self, scope: &'a RcuReadScope, index: usize) -> Option<&'a T> {
22 let array = self.inner.as_ref(scope);
23 array.get(index)
24 }
25
26 pub fn as_slice<'a>(&self, scope: &'a RcuReadScope) -> &'a [T] {
28 let array = self.inner.as_ref(scope);
29 array.as_ref()
30 }
31
32 pub unsafe fn ensure_at_least(&self, requested_size: usize)
43 where
44 T: Clone + Default,
45 {
46 let array = self.inner.read();
47 if array.len() >= requested_size {
48 return;
49 }
50 let new_size = std::cmp::max(requested_size, array.len() * 2);
51 self.copy_update(&array, new_size);
52 }
53
54 pub fn update(&self, new_array: Vec<T>) {
56 self.inner.update(new_array.into_boxed_slice());
57 }
58
59 fn copy_update(&self, array: &[T], new_size: usize)
60 where
61 T: Clone + Default,
62 {
63 let mut new_array = Vec::new();
64 new_array.reserve_exact(new_size);
65 for item in array.iter() {
66 new_array.push(item.clone());
67 }
68 for _ in array.len()..new_size {
69 new_array.push(T::default());
70 }
71 self.inner.update(new_array.into_boxed_slice());
72 }
73}
74
75impl<T: Clone + RcuDroppable + Sync> Clone for RcuArray<T> {
76 fn clone(&self) -> Self {
77 Self { inner: self.inner.clone() }
78 }
79}
80
81impl<T: RcuDroppable + Sync> From<Vec<T>> for RcuArray<T> {
83 fn from(value: Vec<T>) -> Self {
84 Self { inner: RcuBox::new(value.into_boxed_slice()) }
85 }
86}