1use crate::reflect::Reflect;
13use arrayvec::ArrayVec;
14#[cfg(feature = "reflect")]
15use bevy_reflect;
16use bincode::BorrowDecode;
17use bincode::de::{BorrowDecoder, Decoder};
18use bincode::enc::Encoder;
19use bincode::error::{DecodeError, EncodeError};
20use bincode::{Decode, Encode};
21use serde_derive::{Deserialize, Serialize};
22
23#[cfg(not(feature = "std"))]
24pub use alloc::format;
25#[cfg(not(feature = "std"))]
26pub use alloc::vec::Vec;
27
28#[derive(Clone, Debug, Default, Serialize, Deserialize, Reflect)]
32#[reflect(opaque, from_reflect = false, no_field_bounds)]
33pub struct CuArray<T: Clone, const N: usize> {
34 inner: ArrayVec<T, N>,
35}
36
37impl<T: Clone, const N: usize> CuArray<T, N> {
38 pub fn new() -> Self {
39 Self {
40 inner: ArrayVec::new(),
41 }
42 }
43
44 pub fn fill_from_iter<I>(&mut self, iter: I)
45 where
46 I: IntoIterator<Item = T>,
47 {
48 self.inner.clear(); for value in iter.into_iter().take(N) {
50 self.inner.push(value);
51 }
52 }
53
54 pub fn len(&self) -> usize {
55 self.inner.len()
56 }
57
58 pub fn is_empty(&self) -> bool {
59 self.inner.len() == 0
60 }
61
62 pub fn as_slice(&self) -> &[T] {
63 &self.inner
64 }
65
66 pub fn capacity(&self) -> usize {
67 N
68 }
69}
70
71impl<T, const N: usize> Encode for CuArray<T, N>
72where
73 T: Encode + Clone,
74{
75 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
76 (self.inner.len() as u32).encode(encoder)?;
78
79 for elem in &self.inner {
81 elem.encode(encoder)?;
82 }
83
84 Ok(())
85 }
86}
87
88impl<T, const N: usize> Decode<()> for CuArray<T, N>
89where
90 T: Decode<()> + Clone,
91{
92 fn decode<D: Decoder<Context = ()>>(decoder: &mut D) -> Result<Self, DecodeError> {
93 let len = u32::decode(decoder)? as usize;
95 if len > N {
96 return Err(DecodeError::OtherString(format!(
97 "Decoded length {len} exceeds maximum capacity {N}"
98 )));
99 }
100
101 let mut inner = ArrayVec::new();
103 for _ in 0..len {
104 inner.push(T::decode(decoder)?);
105 }
106
107 Ok(Self { inner })
108 }
109}
110
111#[derive(Debug, Clone)]
119pub struct CuArrayVec<T, const N: usize>(pub ArrayVec<T, N>);
120
121impl<T, const N: usize> Default for CuArrayVec<T, N> {
122 fn default() -> Self {
123 Self(ArrayVec::new())
124 }
125}
126
127impl<T, const N: usize> Encode for CuArrayVec<T, N>
128where
129 T: Encode + 'static,
130{
131 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
132 let CuArrayVec(inner) = self;
133 inner.as_slice().encode(encoder)
134 }
135}
136
137impl<T, const N: usize> Decode<()> for CuArrayVec<T, N>
138where
139 T: Decode<()> + 'static,
140{
141 fn decode<D: Decoder<Context = ()>>(decoder: &mut D) -> Result<Self, DecodeError> {
142 let inner = Vec::<T>::decode(decoder)?;
143 let actual_len = inner.len();
144 if actual_len > N {
145 return Err(DecodeError::ArrayLengthMismatch {
146 required: N,
147 found: actual_len,
148 });
149 }
150
151 let mut array_vec = ArrayVec::new();
152 for item in inner {
153 array_vec.push(item); }
155 Ok(CuArrayVec(array_vec))
156 }
157}
158
159impl<'de, T, const N: usize> BorrowDecode<'de, ()> for CuArrayVec<T, N>
160where
161 T: BorrowDecode<'de, ()> + 'static,
162{
163 fn borrow_decode<D: BorrowDecoder<'de, Context = ()>>(
164 decoder: &mut D,
165 ) -> Result<Self, DecodeError> {
166 let inner = Vec::<T>::borrow_decode(decoder)?;
167 let actual_len = inner.len();
168 if actual_len > N {
169 return Err(DecodeError::ArrayLengthMismatch {
170 required: N,
171 found: actual_len,
172 });
173 }
174
175 let mut array_vec = ArrayVec::new();
176 for item in inner {
177 array_vec.push(item); }
179 Ok(CuArrayVec(array_vec))
180 }
181}
182
183#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Encode, Decode, Reflect)]
215#[reflect(opaque, from_reflect = false, no_field_bounds)]
216pub enum CuLatchedStateUpdate<T: Clone> {
217 #[default]
219 NoChange,
220 Set(T),
222 Clear,
224}
225
226impl<T: Clone> CuLatchedStateUpdate<T> {
227 pub fn is_no_change(&self) -> bool {
229 matches!(self, Self::NoChange)
230 }
231
232 pub fn is_set(&self) -> bool {
234 matches!(self, Self::Set(_))
235 }
236
237 pub fn is_clear(&self) -> bool {
239 matches!(self, Self::Clear)
240 }
241}
242
243impl<T: Clone> From<T> for CuLatchedStateUpdate<T> {
244 fn from(value: T) -> Self {
245 Self::Set(value)
246 }
247}
248
249#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Encode, Decode, Reflect)]
255#[reflect(opaque, from_reflect = false, no_field_bounds)]
256pub enum CuLatchedState<T: Clone> {
257 #[default]
259 Unset,
260 Set(T),
262}
263
264impl<T: Clone> CuLatchedState<T> {
265 pub fn new() -> Self {
267 Self::Unset
268 }
269
270 pub fn is_set(&self) -> bool {
272 matches!(self, Self::Set(_))
273 }
274
275 pub fn is_unset(&self) -> bool {
277 matches!(self, Self::Unset)
278 }
279
280 pub fn get(&self) -> Option<&T> {
282 match self {
283 Self::Unset => None,
284 Self::Set(value) => Some(value),
285 }
286 }
287
288 pub fn as_ref(&self) -> Option<&T> {
292 self.get()
293 }
294
295 pub fn set(&mut self, value: T) {
297 *self = Self::Set(value);
298 }
299
300 pub fn clear(&mut self) {
302 *self = Self::Unset;
303 }
304
305 pub fn take(&mut self) -> Option<T> {
307 let previous = core::mem::take(self);
308 match previous {
309 Self::Unset => None,
310 Self::Set(value) => Some(value),
311 }
312 }
313
314 pub fn update_owned(&mut self, update: CuLatchedStateUpdate<T>) {
316 match update {
317 CuLatchedStateUpdate::NoChange => {}
318 CuLatchedStateUpdate::Set(value) => self.set(value),
319 CuLatchedStateUpdate::Clear => self.clear(),
320 }
321 }
322}
323
324impl<T: Clone> CuLatchedState<T> {
325 pub fn update(&mut self, update: &CuLatchedStateUpdate<T>) {
327 match update {
328 CuLatchedStateUpdate::NoChange => {}
329 CuLatchedStateUpdate::Set(value) => self.set(value.clone()),
330 CuLatchedStateUpdate::Clear => self.clear(),
331 }
332 }
333}