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, Serialize, Deserialize, Reflect)]
119#[reflect(opaque, from_reflect = false, no_field_bounds)]
120pub struct CuArrayVec<T: Clone, const N: usize>(pub ArrayVec<T, N>);
121
122impl<T: Clone, const N: usize> Default for CuArrayVec<T, N> {
123 fn default() -> Self {
124 Self(ArrayVec::new())
125 }
126}
127
128impl<T, const N: usize> Encode for CuArrayVec<T, N>
129where
130 T: Clone + Encode + 'static,
131{
132 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
133 let CuArrayVec(inner) = self;
134 inner.as_slice().encode(encoder)
135 }
136}
137
138impl<T, const N: usize> Decode<()> for CuArrayVec<T, N>
139where
140 T: Clone + Decode<()> + 'static,
141{
142 fn decode<D: Decoder<Context = ()>>(decoder: &mut D) -> Result<Self, DecodeError> {
143 let inner = Vec::<T>::decode(decoder)?;
144 let actual_len = inner.len();
145 if actual_len > N {
146 return Err(DecodeError::ArrayLengthMismatch {
147 required: N,
148 found: actual_len,
149 });
150 }
151
152 let mut array_vec = ArrayVec::new();
153 for item in inner {
154 array_vec.push(item); }
156 Ok(CuArrayVec(array_vec))
157 }
158}
159
160impl<'de, T, const N: usize> BorrowDecode<'de, ()> for CuArrayVec<T, N>
161where
162 T: Clone + BorrowDecode<'de, ()> + 'static,
163{
164 fn borrow_decode<D: BorrowDecoder<'de, Context = ()>>(
165 decoder: &mut D,
166 ) -> Result<Self, DecodeError> {
167 let inner = Vec::<T>::borrow_decode(decoder)?;
168 let actual_len = inner.len();
169 if actual_len > N {
170 return Err(DecodeError::ArrayLengthMismatch {
171 required: N,
172 found: actual_len,
173 });
174 }
175
176 let mut array_vec = ArrayVec::new();
177 for item in inner {
178 array_vec.push(item); }
180 Ok(CuArrayVec(array_vec))
181 }
182}
183
184#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Encode, Decode, Reflect)]
216#[reflect(opaque, from_reflect = false, no_field_bounds)]
217pub enum CuLatchedStateUpdate<T: Clone> {
218 #[default]
220 NoChange,
221 Set(T),
223 Clear,
225}
226
227impl<T: Clone> CuLatchedStateUpdate<T> {
228 pub fn is_no_change(&self) -> bool {
230 matches!(self, Self::NoChange)
231 }
232
233 pub fn is_set(&self) -> bool {
235 matches!(self, Self::Set(_))
236 }
237
238 pub fn is_clear(&self) -> bool {
240 matches!(self, Self::Clear)
241 }
242}
243
244impl<T: Clone> From<T> for CuLatchedStateUpdate<T> {
245 fn from(value: T) -> Self {
246 Self::Set(value)
247 }
248}
249
250#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Encode, Decode, Reflect)]
256#[reflect(opaque, from_reflect = false, no_field_bounds)]
257pub enum CuLatchedState<T: Clone> {
258 #[default]
260 Unset,
261 Set(T),
263}
264
265impl<T: Clone> CuLatchedState<T> {
266 pub fn new() -> Self {
268 Self::Unset
269 }
270
271 pub fn is_set(&self) -> bool {
273 matches!(self, Self::Set(_))
274 }
275
276 pub fn is_unset(&self) -> bool {
278 matches!(self, Self::Unset)
279 }
280
281 pub fn get(&self) -> Option<&T> {
283 match self {
284 Self::Unset => None,
285 Self::Set(value) => Some(value),
286 }
287 }
288
289 pub fn as_ref(&self) -> Option<&T> {
293 self.get()
294 }
295
296 pub fn set(&mut self, value: T) {
298 *self = Self::Set(value);
299 }
300
301 pub fn clear(&mut self) {
303 *self = Self::Unset;
304 }
305
306 pub fn take(&mut self) -> Option<T> {
308 let previous = core::mem::take(self);
309 match previous {
310 Self::Unset => None,
311 Self::Set(value) => Some(value),
312 }
313 }
314
315 pub fn update_owned(&mut self, update: CuLatchedStateUpdate<T>) {
317 match update {
318 CuLatchedStateUpdate::NoChange => {}
319 CuLatchedStateUpdate::Set(value) => self.set(value),
320 CuLatchedStateUpdate::Clear => self.clear(),
321 }
322 }
323}
324
325impl<T: Clone> CuLatchedState<T> {
326 pub fn update(&mut self, update: &CuLatchedStateUpdate<T>) {
328 match update {
329 CuLatchedStateUpdate::NoChange => {}
330 CuLatchedStateUpdate::Set(value) => self.set(value.clone()),
331 CuLatchedStateUpdate::Clear => self.clear(),
332 }
333 }
334}