meshx/attrib/
attribute.rs

1use std::any::{Any, TypeId};
2use std::marker::PhantomData;
3use std::slice;
4
5use dync::{dync_mod, from_dyn, into_dyn, BoxValue, Slice, SliceMut, SmallValue, VecDyn};
6//use fnv::FnvHashSet as HashSet;
7use ahash::AHashSet as HashSet;
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10
11use crate::index::*;
12use crate::mesh::topology::*;
13
14use super::Error;
15
16pub use std::sync::Arc as Irc;
17
18/// A module defining traits for values stored at a mesh attribute.
19#[allow(missing_docs)]
20#[dync_mod]
21mod value_traits {
22    /// A basic value that can be stored as an attribute in a mesh type.
23    pub trait AttributeValue: Clone + PartialEq + std::fmt::Debug + Send + Sync + 'static {}
24    impl<T> AttributeValue for T where T: Clone + PartialEq + std::fmt::Debug + Send + Sync + 'static {}
25
26    /// A value that can be stored as an indirect attribute in a mesh type.
27    ///
28    /// This value is cached inside a `HashSet`, so it requires additional constraints beyond
29    /// those imposed on `AttributeValue`.
30    pub trait AttributeValueHash: AttributeValue + Eq + std::hash::Hash {}
31    impl<T> AttributeValueHash for T where T: AttributeValue + Eq + std::hash::Hash {}
32}
33
34pub use self::value_traits::*;
35
36/// A slice of attribute values belonging to a particular attribute.
37pub type DataSlice<'a> = Slice<'a, AttributeValueVTable>;
38/// A slice of attribute values belonging to a particular indirect attribute.
39pub type HDataSlice<'a> = Slice<'a, AttributeValueHashVTable>;
40/// A mutable slice of attribute values belonging to a particular attribute.
41pub type DataSliceMut<'a> = SliceMut<'a, AttributeValueVTable>;
42/// A mutable slice of attribute values belonging to a particular indirect attribute.
43pub type HDataSliceMut<'a> = SliceMut<'a, AttributeValueHashVTable>;
44/// A vector of values stored by a direct attribute.
45pub type DataVec = VecDyn<AttributeValueVTable>;
46/// A vector of values stored by an indirect attribute.
47pub type HDataVec = VecDyn<AttributeValueHashVTable>;
48/// An owned value stored at an attribute at some index.
49pub type Value = BoxValue<AttributeValueVTable>;
50/// A reference to a value stored at an attribute at some index.
51pub type ValueRef<'a> = dync::ValueRef<'a, AttributeValueVTable>;
52/// An reference to a value stored at an indirect attribute at some index.
53pub type HValue = SmallValue<AttributeValueHashVTable>;
54/// A reference to a value stored at an indirect attribute at some index.
55pub type HValueRef<'a> = dync::ValueRef<'a, AttributeValueHashVTable>;
56/// A mutable reference to a value stored at an indirect attribute at some index.
57pub type HValueMut<'a> = dync::ValueMut<'a, AttributeValueHashVTable>;
58
59/// A collection of indirect attribute values cached for improved memory usage.
60pub type AttribValueCache = HashSet<HValue>;
61
62// Common implementations for VecDyn data.
63macro_rules! impl_data_base {
64    ($vec_type:ty) => {
65        /// Get the type data stored within this attribute
66        #[inline]
67        pub fn check<T: Any>(&self) -> Result<&Self, Error> {
68            self.buf
69                .check_ref::<T>()
70                .map(|_| self)
71                .ok_or_else(|| Error::type_mismatch_from_buf::<T, _>(&self.buf))
72        }
73
74        /// Get the mutable typed data stored within this attribute
75        #[inline]
76        pub fn check_mut<T: Any>(&mut self) -> Result<&mut Self, Error> {
77            match self.buf.check_mut::<T>() {
78                Some(_) => Ok(self),
79                None => Err(Error::type_mismatch_from_buf::<T, _>(&self.buf)),
80            }
81        }
82
83        /// Get the type data stored within this attribute
84        #[inline]
85        pub fn element_type_id(&self) -> TypeId {
86            self.buf.element_type_id()
87        }
88
89        /// Get the number of bytes per element stored in this attribute.
90        #[inline]
91        pub fn element_size(&self) -> usize {
92            self.buf.element_size()
93        }
94
95        /// Number of elements stored by this attribute. This is the same as the number of elements in
96        /// the associated topology.
97        #[inline]
98        pub fn len(&self) -> usize {
99            self.buf.len()
100        }
101
102        /// Number of bytes stored by this attribute. This is the same as the number of elements
103        /// multiplied by the size of each element.
104        #[inline]
105        pub fn byte_len(&self) -> usize {
106            self.buf.len() * self.buf.element_size()
107        }
108
109        /// Check if there are any values in this attribute.
110        #[inline]
111        pub fn is_empty(&self) -> bool {
112            self.buf.is_empty()
113        }
114
115        /// Get a `const` reference to the `i`'th attribute value.
116        ///
117        /// # Safety
118        ///
119        /// Calling this method with an out-of-bounds index is [*undefined behavior*] even if the output is
120        /// not used. For a safe alternative use the `get_ref` method.
121        ///
122        /// [*undefined behavior*]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
123        #[inline]
124        pub unsafe fn get_unchecked_ref<T: Any>(&self, i: usize) -> &T {
125            self.buf.get_unchecked_ref(i)
126        }
127
128        /// Get a mutable reference to the `i`'th attribute value.
129        ///
130        /// # Safety
131        ///
132        /// Calling this method with an out-of-bounds index is [*undefined behavior*] even if the output is
133        /// not used. For a safe alternative use the `get_mut` method.
134        ///
135        /// [*undefined behavior*]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
136        #[inline]
137        pub unsafe fn get_unchecked_mut<T: Any>(&mut self, i: usize) -> &mut T {
138            self.buf.get_unchecked_mut(i)
139        }
140
141        /// Get a reference to the internal value vector.
142        #[inline]
143        #[deprecated(since = "0.2.1", note = "Please use data instead.")]
144        pub fn data_ref(&self) -> &$vec_type {
145            &self.buf
146        }
147
148        /// Get a reference to the internal value vector.
149        #[inline]
150        pub fn data(&self) -> &$vec_type {
151            &self.buf
152        }
153
154        /// Get a mutable reference to the internal value vector.
155        #[inline]
156        pub fn data_mut(&mut self) -> &mut $vec_type {
157            &mut self.buf
158        }
159
160        /// Convert this attribute into the underlying buffer. This consumes the attribute.
161        #[inline]
162        pub fn into_data(self) -> $vec_type {
163            self.buf
164        }
165
166        /// Extend this attribute by `n` elements. Effectively, this function appends the default
167        /// element `n` number of times to this attribute.
168        #[inline]
169        pub fn extend_by(&mut self, n: usize) {
170            let Self {
171                buf,
172                default_element,
173                ..
174            } = self;
175            for _ in 0..n {
176                buf.push_cloned(default_element.as_ref());
177            }
178        }
179
180        /// Rotates elements of this attribute in-place to the left.
181        ///
182        /// Rotate this attribute in-place such that the first `mid` elements of the underlying buffer
183        /// move to the end while the last `self.len() - mid` elements move to the front. After
184        /// calling `rotate_left`, the element previously at index `mid` will become the first element
185        /// in the slice.
186        #[inline]
187        pub fn rotate_left(&mut self, mid: usize) {
188            self.buf.rotate_left(mid);
189        }
190
191        /// Rotates elements of this attribute in-place to the right.
192        ///
193        /// Rotate this attribute in-place such that the first `self.len() - k` elements of the
194        /// underlying buffer move to the end while the last `k` elements move to the front. After
195        /// calling `rotate_right`, the element previously at index `self.len() - k` will become the
196        /// first element in the slice.
197        #[inline]
198        pub fn rotate_right(&mut self, k: usize) {
199            self.buf.rotate_right(k);
200        }
201    };
202}
203
204/// Mesh attribute data.
205///
206/// This stores unique values shared among mesh elements via smart pointers.
207/// This type doesn't store the location of the attribute.
208#[derive(Clone, Debug, PartialEq)]
209pub struct IndirectData {
210    /// Raw buffer of generic values.
211    buf: HDataVec,
212    /// Default element.
213    default_element: HValue,
214}
215
216impl IndirectData {
217    impl_data_base!(HDataVec);
218
219    /// Construct an attribute with a given size.
220    pub fn with_size<T: AttributeValueHash>(n: usize, def: T) -> Self {
221        let default_element = Irc::new(def);
222        IndirectData {
223            buf: HDataVec::with_size(n, Irc::clone(&default_element)),
224            default_element: HValue::new(default_element),
225        }
226    }
227
228    /// Get the value pointer from the value set corresponding to the given value and insert it in
229    /// to the values set if it doesn't already exist.
230    fn get_or_insert<T: AttributeValueHash>(set: &mut AttribValueCache, elem: T) -> Irc<T> {
231        let elem = HValue::new(Irc::new(elem));
232        if let Some(elem) = set.get(&elem) {
233            Irc::clone(elem.as_ref().downcast().unwrap())
234        } else {
235            assert!(set.insert(elem.clone()));
236            elem.downcast().unwrap()
237        }
238    }
239
240    /// Construct an attribute from a given `Vec<T>` of data.
241    pub fn from_vec<T: AttributeValueHash + Default>(
242        vec: Vec<T>,
243        cache: &mut AttribValueCache,
244    ) -> Self {
245        let default_element = Irc::new(T::default());
246        let buf: Vec<_> = vec
247            .into_iter()
248            .map(|elem| Self::get_or_insert(cache, elem))
249            .collect();
250
251        IndirectData {
252            buf: HDataVec::from_vec(buf),
253            default_element: HValue::new(default_element),
254        }
255    }
256
257    /// Construct an attribute from a given slice of data, by copying the data.
258    #[inline]
259    pub fn from_slice<T: AttributeValueHash + Default>(
260        buf: &[T],
261        cache: &mut AttribValueCache,
262    ) -> Self {
263        Self::from_vec(buf.to_vec(), cache)
264    }
265
266    /// Construct a new empty attribute with the same values and default element as `self`.
267    pub fn duplicate_empty(&self) -> Self {
268        IndirectData {
269            buf: HDataVec::with_type_from(&self.buf),
270            default_element: self.default_element.clone(),
271        }
272    }
273
274    /// Construct a new attribute with the same values and default element as `self`.
275    pub fn duplicate_with(
276        &self,
277        dup_data: impl FnOnce(HDataSlice) -> VecDyn<dyn HasAttributeValue>,
278    ) -> Self {
279        IndirectData {
280            buf: from_dyn![VecDyn<dyn HasAttributeValue as AttributeValueHashVTable>](dup_data(
281                self.data().as_slice(),
282            )),
283            default_element: self.default_element.clone(),
284        }
285    }
286
287    /// Construct a new attribute with the same values and default element as `self`.
288    ///
289    /// The attribute is first initialized with the default value by allocating `len` default
290    /// elements. Then the newly created buffer is expected to be modified by the `init` function.
291    /// The output `HDataVec` must be composed of values from the original `HDataVec` or the
292    /// default element.
293    ///
294    /// The `init` function is only allowed to clone data from the second argument into the first.
295    /// Adding new data will cause this attribute to go out of sync with the cache.
296    pub fn duplicate_with_len(
297        &self,
298        len: usize,
299        init: impl FnOnce(HDataSliceMut, HDataSlice),
300    ) -> Self {
301        let mut attrib = self.duplicate_empty();
302        attrib.extend_by(len);
303        init(attrib.data_mut().as_mut_slice(), self.data().as_slice());
304        attrib
305    }
306
307    /// Convert the data stored by this attribute into a vector of the same size.
308    #[inline]
309    pub fn clone_into_vec<T: AttributeValueHash>(&self) -> Result<Vec<T>, Error> {
310        let result = Vec::with_capacity(self.len());
311        self.buf
312            .iter_as::<Irc<T>>()
313            .unwrap()
314            .fold(Some(result), |mut acc, rc| {
315                if let Some(acc) = acc.as_mut() {
316                    acc.push((**rc).clone());
317                }
318                acc
319            })
320            .ok_or_else(|| Error::type_mismatch_from_buf::<Irc<T>, _>(&self.buf))
321    }
322
323    /// Produce an iterator over the underlying data elements.
324    #[inline]
325    pub fn iter<T: Any>(&self) -> Result<impl Iterator<Item = &T>, Error> {
326        self.buf
327            .iter_as::<Irc<T>>()
328            .map(|iter| iter.map(|rc| &**rc))
329            .ok_or_else(|| Error::type_mismatch_from_buf::<Irc<T>, _>(&self.buf))
330    }
331
332    /// Iterate over all the value in this attribute and update them as needed.
333    ///
334    /// This function takes a closure which takes an index and a smart pointer to the stored value and
335    /// produces an optional new value. The new value is then used to update the attribute using
336    /// the provided cache.
337    pub fn update_with<T, F>(
338        &mut self,
339        mut f: F,
340        cache: &mut AttribValueCache,
341    ) -> Result<&mut Self, Error>
342    where
343        T: AttributeValueHash,
344        F: FnMut(usize, &Irc<T>) -> Option<Irc<T>>,
345    {
346        let id = self.buf.element_type_id();
347        for (i, val) in self.buf.iter_mut().enumerate() {
348            let rc = val
349                .downcast::<Irc<T>>()
350                .ok_or_else(|| Error::type_mismatch_id::<Irc<T>>(id))?;
351            if let Some(new_rc) = f(i, &*rc) {
352                let new_value = HValue::new(new_rc);
353                if let Some(existing) = cache.get(&new_value) {
354                    HValueMut::new(rc).clone_from_other(existing.as_ref())?;
355                } else if new_value == self.default_element {
356                    HValueMut::new(rc).clone_from_other(self.default_element.as_ref())?;
357                } else {
358                    HValueMut::new(rc).clone_from_other(new_value.as_ref())?;
359                    assert!(cache.insert(new_value));
360                }
361            }
362        }
363        Ok(self)
364    }
365
366    /// Set the value of a particular element.
367    pub fn set_at<'a, T>(
368        &'a mut self,
369        i: usize,
370        new_value: T,
371        cache: &'a mut AttribValueCache,
372    ) -> Result<&'a mut Self, Error>
373    where
374        T: AttributeValueHash,
375    {
376        self.set_value_at(i, &HValue::new(Irc::new(new_value)), cache)
377    }
378
379    /// Set the value of a particular element.
380    pub fn set_value_at<'a>(
381        &'a mut self,
382        i: usize,
383        new_value: &HValue,
384        cache: &'a mut AttribValueCache,
385    ) -> Result<&'a mut Self, Error> {
386        let mut value_out = self.buf.get_mut(i);
387        if let Some(existing) = cache.get(new_value) {
388            value_out.clone_from_other(existing.as_ref())?;
389        } else if new_value == &self.default_element {
390            value_out.clone_from_other(self.default_element.as_ref())?;
391        } else {
392            value_out.clone_from_other(new_value.as_ref())?;
393            assert!(cache.insert((*new_value).clone()));
394        }
395        Ok(self)
396    }
397
398    /// Push a value onto the underlying data buffer.
399    pub fn push_cloned(
400        &mut self,
401        new_value_ref: HValueRef,
402        cache: &mut AttribValueCache,
403    ) -> Result<&mut Self, Error> {
404        let expected = self.buf.element_type_id();
405        let actual = new_value_ref.value_type_id();
406        let err = || Error::TypeMismatch { expected, actual };
407
408        let new_value = new_value_ref.clone_small_value();
409        if let Some(existing) = cache.get(&new_value) {
410            self.buf.push_cloned(existing.as_ref()).ok_or_else(err)?;
411        } else if new_value == self.default_element {
412            self.buf
413                .push_cloned(self.default_element.as_ref())
414                .ok_or_else(err)?;
415        } else {
416            self.buf.push_cloned(new_value.as_ref()).ok_or_else(err)?;
417            assert!(cache.insert(new_value));
418        }
419        Ok(self)
420    }
421
422    /// Produce a slice to the underlying data referenced by smart pointers.
423    #[inline]
424    pub fn as_rc_slice<T: Any>(&self) -> Result<&[Irc<T>], Error> {
425        self.buf
426            .as_slice_as()
427            .ok_or_else(|| Error::type_mismatch_from_buf::<T, _>(&self.buf))
428    }
429
430    /// Produce a mutable slice to the underlying data referenced by smart pointers.
431    #[inline]
432    pub fn as_mut_rc_slice<T: Any>(&mut self) -> Result<&mut [Irc<T>], Error> {
433        let element_id = self.buf.element_type_id();
434        self.buf
435            .as_mut_slice_as()
436            .ok_or_else(|| Error::type_mismatch_id::<Irc<T>>(element_id))
437    }
438
439    /// Get a reference to the default element.
440    #[inline]
441    pub fn default_element(&self) -> HValueRef {
442        self.default_element.as_ref()
443    }
444}
445
446/// Attribute data stored directly with each associated element.
447///
448/// This type doesn't store the location of the attribute.
449#[derive(Clone, Debug, PartialEq)]
450pub struct DirectData {
451    /// Raw buffer of generic values.
452    buf: DataVec,
453    /// Default element.
454    default_element: Value,
455}
456
457/// This type wraps a `DataVec` to store attribute data.
458impl DirectData {
459    impl_data_base!(DataVec);
460
461    /// Construct an attribute with a given size.
462    pub fn with_size<T: AttributeValue>(n: usize, def: T) -> Self {
463        DirectData {
464            buf: DataVec::with_size(n, def.clone()),
465            default_element: Value::new(def),
466        }
467    }
468
469    /// Construct an attribute from a given `Vec<T>` of data reusing the space already
470    /// allocated by the `Vec`.
471    pub fn from_vec<T: AttributeValue + Default>(vec: Vec<T>) -> Self {
472        DirectData {
473            buf: DataVec::from_vec(vec),
474            default_element: Value::new(T::default()),
475        }
476    }
477
478    /// Construct an attribute from a given `DataVec` of data reusing the space already
479    /// allocated.
480    ///
481    /// # Safety
482    ///
483    /// The given `def` must be a valid binary representation of an element stored in the given
484    /// `DataVec`.
485    pub unsafe fn from_raw_data(buf: DataVec, default_element: Value) -> Self {
486        DirectData {
487            buf,
488            default_element,
489        }
490    }
491
492    /// Construct an attribute from a given slice of data, by copying the data.
493    #[inline]
494    pub fn from_slice<T: AttributeValue + Default>(buf: &[T]) -> Self {
495        Self::from_vec(buf.to_vec())
496    }
497
498    /// Construct a new empty attribute with the same buffer type and default element as `self`.
499    pub fn duplicate_empty(&self) -> Self {
500        DirectData {
501            buf: DataVec::with_type_from(&self.buf),
502            default_element: self.default_element.clone(),
503        }
504    }
505
506    /// Construct a new attribute with the same buffer type and default element as `self`.
507    ///
508    /// The data within the newly created attribute is expected to be initialized with the given
509    /// function `dup_data`, which produces a `VecDyn` for the new attribute given the existing
510    /// `DataSlice` from `self`.
511    pub fn duplicate_with(
512        &self,
513        dup_data: impl FnOnce(DataSlice) -> VecDyn<dyn HasAttributeValue>,
514    ) -> Self {
515        DirectData {
516            buf: from_dyn![VecDyn<dyn HasAttributeValue as AttributeValueVTable>](dup_data(
517                self.data().as_slice(),
518            )),
519            default_element: self.default_element.clone(),
520        }
521    }
522
523    /// Construct a new attribute with the same buffer type, default element as `self`.
524    ///
525    /// The attribute is first initialized with the default value by allocating `len` default
526    /// elements. Then the newly created buffer is expected to be modified by the `init` function.
527    pub fn duplicate_with_len(
528        &self,
529        len: usize,
530        init: impl FnOnce(DataSliceMut, DataSlice),
531    ) -> Self {
532        let mut attrib = self.duplicate_empty();
533        attrib.extend_by(len);
534        init(attrib.data_mut().as_mut_slice(), self.data().as_slice());
535        attrib
536    }
537
538    /// Produce a slice to the underlying data.
539    #[inline]
540    pub fn as_slice<T: Any>(&self) -> Result<&[T], Error> {
541        self.buf
542            .as_slice_as()
543            .ok_or_else(|| Error::type_mismatch_from_buf::<T, _>(&self.buf))
544    }
545
546    /// Produce a mutable slice to the underlying data.
547    #[inline]
548    pub fn as_mut_slice<T: Any>(&mut self) -> Result<&mut [T], Error> {
549        let element_id = self.buf.element_type_id();
550        self.buf
551            .as_mut_slice_as()
552            .ok_or_else(|| Error::type_mismatch_id::<T>(element_id))
553    }
554
555    /// Convert the data stored by this attribute into a vector of the same size.
556    #[inline]
557    pub fn clone_into_vec<T: Any + Clone>(&self) -> Result<Vec<T>, Error> {
558        self.buf
559            .clone_into_vec()
560            .ok_or_else(|| Error::type_mismatch_from_buf::<T, _>(&self.buf))
561    }
562
563    /// Set the value of a particular element.
564    pub fn set_value_at(&mut self, i: usize, new_value: ValueRef) -> Result<&mut Self, Error> {
565        self.buf.get_mut(i).clone_from_other(new_value)?;
566        Ok(self)
567    }
568
569    /// Push a value onto the underlying data buffer.
570    pub fn push_cloned(&mut self, new_value_ref: ValueRef) -> Result<&mut Self, Error> {
571        let expected = self.buf.element_type_id();
572        let actual = new_value_ref.value_type_id();
573        self.data_mut()
574            .push_cloned(new_value_ref)
575            .ok_or(Error::TypeMismatch { expected, actual })?;
576        Ok(self)
577    }
578
579    /// Produce an iterator over the underlying data elements.
580    #[inline]
581    pub fn iter<T: Any>(&self) -> Result<slice::Iter<T>, Error> {
582        self.buf
583            .iter_as::<T>()
584            .ok_or_else(|| Error::type_mismatch_from_buf::<T, _>(&self.buf))
585    }
586
587    /// Produce a mutable iterator over the underlying data elements.
588    #[inline]
589    pub fn iter_mut<T: Any>(&mut self) -> Result<slice::IterMut<T>, Error> {
590        let element_id = self.buf.element_type_id();
591        self.buf
592            .iter_mut_as::<T>()
593            .ok_or_else(|| Error::type_mismatch_id::<T>(element_id))
594    }
595
596    /// Convert this attribute into a typed vector of `T`. This consumes the attribute.
597    #[inline]
598    pub fn into_vec<T: AttributeValue>(self) -> Result<Vec<T>, Error> {
599        let element_id = self.buf.element_type_id();
600        self.buf
601            .into_vec()
602            .ok_or_else(|| Error::type_mismatch_id::<T>(element_id))
603    }
604
605    /// Get a reference to the defult element as a byte slice.
606    #[inline]
607    pub fn default_element(&self) -> ValueRef {
608        self.default_element.as_ref()
609    }
610}
611
612/// Mesh attribute data.
613///
614/// An attribute could store attribute values directly with the corresponding mesh elements, or
615/// indirectly in a secondary storage indexed at each mesh element.
616#[derive(Clone, Debug, PartialEq)]
617pub enum AttributeData {
618    /// A direct attribute stores values located directly (and uniquely) for each mesh element.
619    Direct(DirectData),
620    /// An indirect attribute stores values located on the heap an referenced using smart pointers
621    /// (so non-uniquely) for each mesh element.
622    ///
623    /// Additionally these values are cached in an external cache data structure to make clones
624    /// cheaper and reduce memory usage.
625    Indirect(IndirectData),
626}
627
628impl AttributeData {
629    /// Returns true if the underlying attribute is a direct attribute and false otherwise.
630    pub fn is_direct(&self) -> bool {
631        matches!(self, AttributeData::Direct(_))
632    }
633
634    /// Returns true if the underlying attribute is an indirect attribute and false otherwise.
635    pub fn is_indirect(&self) -> bool {
636        matches!(self, AttributeData::Indirect(_))
637    }
638
639    /// Construct a direct attribute with a given size.
640    pub fn direct_with_size<T: AttributeValue>(n: usize, def: T) -> Self {
641        AttributeData::Direct(DirectData::with_size(n, def))
642    }
643
644    /// Construct an indirect attribute with a given size.
645    pub fn indirect_with_size<T: AttributeValueHash>(n: usize, def: T) -> Self {
646        AttributeData::Indirect(IndirectData::with_size(n, def))
647    }
648
649    /// Construct a direct attribute from a given `Vec<T>` of data reusing the space already
650    /// allocated by the `Vec`.
651    pub fn direct_from_vec<T: AttributeValue + Default>(vec: Vec<T>) -> Self {
652        AttributeData::Direct(DirectData::from_vec(vec))
653    }
654
655    /// Construct an indirect attribute from a given `Vec<T>` of data, while saving any repeated
656    /// values in the given cache.
657    pub fn indirect_from_vec<T: AttributeValueHash + Default>(
658        vec: Vec<T>,
659        cache: &mut AttribValueCache,
660    ) -> Self {
661        AttributeData::Indirect(IndirectData::from_vec(vec, cache))
662    }
663
664    /// Construct an indirect attribute from a given `IndirectData` instance. It is assumed that
665    /// the included data is already cached correctly in the associated cache.
666    pub fn indirect_from_data(data: IndirectData) -> Self {
667        AttributeData::Indirect(data)
668    }
669
670    /// Construct an attribute from a given slice of data, by copying the data.
671    #[inline]
672    pub fn direct_from_slice<T: AttributeValue + Default>(data: &[T]) -> Self {
673        Self::direct_from_vec(data.to_vec())
674    }
675
676    /// Construct an attribute from a given slice of data, by copying the data.
677    #[inline]
678    pub fn indirect_from_slice<T: AttributeValueHash + Default>(
679        data: &[T],
680        cache: &mut AttribValueCache,
681    ) -> Self {
682        Self::indirect_from_vec(data.to_vec(), cache)
683    }
684
685    // Helper function to map through the variants.
686    fn map(
687        &self,
688        direct: impl FnOnce(&DirectData) -> DirectData,
689        indirect: impl FnOnce(&IndirectData) -> IndirectData,
690    ) -> Self {
691        self.map_to(
692            |d| AttributeData::Direct(direct(d)),
693            |i| AttributeData::Indirect(indirect(i)),
694        )
695    }
696
697    /// A utility function to map over the direct and indirect attribute variants given the two
698    /// closures.
699    pub fn map_to<'a, O>(
700        &'a self,
701        direct: impl FnOnce(&'a DirectData) -> O,
702        indirect: impl FnOnce(&'a IndirectData) -> O,
703    ) -> O {
704        match self {
705            AttributeData::Direct(data) => direct(data),
706            AttributeData::Indirect(data) => indirect(data),
707        }
708    }
709
710    /// A utility function to mutably map over the direct and indirect attribute variants given the
711    /// two closures.
712    pub fn map_mut_to<'a, O>(
713        &'a mut self,
714        direct: impl FnOnce(&'a mut DirectData) -> O,
715        indirect: impl FnOnce(&'a mut IndirectData) -> O,
716    ) -> O {
717        match self {
718            AttributeData::Direct(data) => direct(data),
719            AttributeData::Indirect(data) => indirect(data),
720        }
721    }
722
723    /// Produce a slice to the underlying direct attribute data.
724    #[inline]
725    pub fn as_slice<T: Any>(&self) -> Result<&[T], Error> {
726        self.map_to(|d| d.as_slice(), |_| Err(Error::KindMismatchFoundIndirect))
727    }
728
729    /// Produce a mutable slice to the underlying direct attribute data.
730    #[inline]
731    pub fn as_mut_slice<T: Any>(&mut self) -> Result<&mut [T], Error> {
732        self.map_mut_to(
733            |d| d.as_mut_slice(),
734            |_| Err(Error::KindMismatchFoundIndirect),
735        )
736    }
737
738    /// Construct a new empty attribute with the same buffer type, default element and topology as
739    /// `self`.
740    pub fn duplicate_empty(&self) -> Self {
741        self.map(|d| d.duplicate_empty(), |i| i.duplicate_empty())
742    }
743
744    /// Construct a new attribute with the same buffer type, default element and topology type as
745    /// `self`.
746    pub fn duplicate_with(
747        &self,
748        dup_data: impl FnOnce(&mut VecDyn<dyn HasAttributeValue>, Slice<dyn HasAttributeValue>),
749    ) -> Self {
750        match self {
751            AttributeData::Direct(d) => AttributeData::Direct(d.duplicate_with(|input| {
752                let vec_drop = VecDyn::with_type_from(input.reborrow());
753                let mut vec_dyn = into_dyn![VecDyn<dyn HasAttributeValue>](vec_drop);
754                dup_data(&mut vec_dyn, into_dyn![Slice<dyn HasAttributeValue>](input));
755                vec_dyn
756            })),
757            AttributeData::Indirect(i) => AttributeData::Indirect(i.duplicate_with(|input| {
758                let vec_drop = VecDyn::with_type_from(input.reborrow());
759                let mut vec_dyn = into_dyn![VecDyn<dyn HasAttributeValue>](vec_drop);
760                dup_data(&mut vec_dyn, into_dyn![Slice<dyn HasAttributeValue>](input));
761                vec_dyn
762            })),
763        }
764    }
765
766    /// Construct a new attribute with the same buffer type, default element and topology type as
767    /// `self`.
768    ///
769    /// The attribute is first initialized with the default value by allocating `len` default
770    /// elements. Then the newly created buffer is expected to be modified by the `init` function.
771    pub fn duplicate_with_len(
772        &self,
773        len: usize,
774        init: impl FnOnce(DataSliceMut, DataSlice),
775    ) -> Self {
776        match self {
777            AttributeData::Direct(d) => AttributeData::Direct(d.duplicate_with_len(len, init)),
778            AttributeData::Indirect(i) => AttributeData::Indirect(
779                i.duplicate_with_len(len, |new, old| init(new.upcast(), old.upcast())),
780            ),
781        }
782    }
783
784    /// Get the type data stored within this attribute
785    #[inline]
786    pub fn check<T: Any>(&self) -> Result<&Self, Error> {
787        self.map_to(
788            |d| d.check::<T>().map(|_| self),
789            |i| i.check::<T>().map(|_| self),
790        )
791    }
792
793    /// Get the mutable typed data stored within this attribute
794    #[inline]
795    pub fn check_mut<T: Any>(&mut self) -> Result<&mut Self, Error> {
796        match self {
797            AttributeData::Direct(d) => match d.check_mut::<T>() {
798                Ok(_) => Ok(self),
799                Err(e) => Err(e),
800            },
801            AttributeData::Indirect(i) => match i.check_mut::<T>() {
802                Ok(_) => Ok(self),
803                Err(e) => Err(e),
804            },
805        }
806    }
807
808    /// Produce an iterator over the underlying data elements regardless of kind.
809    ///
810    /// This incurs an additional `Box` deref when iterating.
811    #[inline]
812    pub fn iter<'a, T: Any>(&'a self) -> Result<Box<dyn Iterator<Item = &'a T> + 'a>, Error> {
813        self.map_to(
814            |d| {
815                d.iter::<T>().map(|iter| {
816                    let b: Box<dyn Iterator<Item = &T>> = Box::new(iter);
817                    b
818                })
819            },
820            |i| {
821                i.iter::<T>().map(|iter| {
822                    let b: Box<dyn Iterator<Item = &T>> = Box::new(iter);
823                    b
824                })
825            },
826        )
827    }
828
829    /// Produce an iterator over the underlying data elements for a direct attribute.
830    #[inline]
831    pub fn direct_iter<T: Any>(&self) -> Result<slice::Iter<T>, Error> {
832        self.map_to(|d| d.iter::<T>(), |_| Err(Error::KindMismatchFoundIndirect))
833    }
834
835    /// Produce an iterator over the underlying data elements for an indirect attribute.
836    #[inline]
837    pub fn indirect_iter<T: Any>(&self) -> Result<impl Iterator<Item = &T>, Error> {
838        self.map_to(|_| Err(Error::KindMismatchFoundDirect), |i| i.iter::<T>())
839    }
840
841    /// Produce a mutable iterator over the underlying data elements for a direct attribute.
842    #[inline]
843    pub fn direct_iter_mut<T: Any>(&mut self) -> Result<slice::IterMut<T>, Error> {
844        self.map_mut_to(
845            |d| d.iter_mut::<T>(),
846            |_| Err(Error::KindMismatchFoundIndirect),
847        )
848    }
849
850    /// Iterate over all the value in this attribute and update them as needed.
851    ///
852    /// This function takes a closure which takes an index and a smart pointer to the stored value and
853    /// produces an optional new value. The new value is then used to update the attribute using
854    /// the provided cache.
855    #[inline]
856    pub fn indirect_update_with<T: AttributeValueHash>(
857        &mut self,
858        f: impl FnMut(usize, &Irc<T>) -> Option<Irc<T>>,
859        cache: &mut AttribValueCache,
860    ) -> Result<&mut Self, Error> {
861        match self {
862            AttributeData::Indirect(i) => match i.update_with::<T, _>(f, cache) {
863                Ok(_) => Ok(self),
864                Err(e) => Err(e),
865            },
866            _ => Err(Error::KindMismatchFoundDirect),
867        }
868    }
869
870    /// Get the type data stored within this attribute
871    #[inline]
872    pub fn element_type_id(&self) -> TypeId {
873        self.map_to(|d| d.element_type_id(), |i| i.element_type_id())
874    }
875
876    /// Convert the data stored by this attribute into a vector of the same size.
877    #[inline]
878    pub fn clone_into_vec<T: AttributeValueHash>(&self) -> Result<Vec<T>, Error> {
879        self.map_to(|d| d.clone_into_vec::<T>(), |i| i.clone_into_vec::<T>())
880    }
881
882    /// Convert the data stored by this direct attribute into a vector of the same size.
883    #[inline]
884    pub fn direct_clone_into_vec<T: Any + Clone>(&self) -> Result<Vec<T>, Error> {
885        self.map_to(
886            |d| d.clone_into_vec::<T>(),
887            |_| Err(Error::KindMismatchFoundIndirect),
888        )
889    }
890
891    /// Number of elements stored by this attribute. This is the same as the number of elements in
892    /// the associated topology.
893    #[inline]
894    pub fn len(&self) -> usize {
895        self.map_to(|d| d.len(), |i| i.len())
896    }
897
898    /// Check if there are any values in this attribute.
899    #[inline]
900    pub fn is_empty(&self) -> bool {
901        self.map_to(|d| d.is_empty(), |i| i.is_empty())
902    }
903
904    /// Get a reference to the internal data as a `DataSlice`.
905    #[inline]
906    pub fn data_slice(&self) -> DataSlice {
907        self.map_to(|d| d.data().as_slice(), |i| i.data().as_slice().upcast())
908    }
909
910    /// Get a mutable reference to the internal data as a `DataSliceMut`.
911    #[inline]
912    pub fn data_mut_slice(&mut self) -> DataSliceMut {
913        self.map_mut_to(
914            |d| d.data_mut().as_mut_slice(),
915            |i| i.data_mut().as_mut_slice().upcast(),
916        )
917    }
918
919    /// Get a reference to the internal indirect data as an `HDataVec`.
920    #[inline]
921    pub fn indirect_data(&self) -> Result<&IndirectData, Error> {
922        self.map_to(|_| Err(Error::KindMismatchFoundDirect), Ok)
923    }
924
925    /// Get a mutable reference to the internal indirect data as an `HDataVec`.
926    #[inline]
927    pub fn indirect_data_mut(&mut self) -> Result<&mut IndirectData, Error> {
928        self.map_mut_to(|_| Err(Error::KindMismatchFoundDirect), Ok)
929    }
930
931    /// Get a reference to the internal direct data as a `DirectData` struct.
932    #[inline]
933    pub fn direct_data(&self) -> Result<&DirectData, Error> {
934        self.map_to(Ok, |_| Err(Error::KindMismatchFoundDirect))
935    }
936
937    /// Get a mutable reference to the internal direct data as a `DirectData` struct.
938    #[inline]
939    pub fn direct_data_mut(&mut self) -> Result<&mut DirectData, Error> {
940        self.map_mut_to(Ok, |_| Err(Error::KindMismatchFoundDirect))
941    }
942
943    /// Convert this attribute into the underlying vector.
944    ///
945    /// This consumes the attribute.
946    #[inline]
947    pub fn into_data(self) -> DataVec {
948        match self {
949            AttributeData::Direct(d) => d.into_data(),
950            AttributeData::Indirect(i) => i.into_data().upcast(),
951        }
952    }
953
954    /// Extend this attribute by `n` elements. Effectively, this function appends the default
955    /// element `n` number of times to this attribute.
956    #[inline]
957    pub fn extend_by(&mut self, n: usize) {
958        self.map_mut_to(|d| d.extend_by(n), |i| i.extend_by(n))
959    }
960
961    /// Rotate this attribute in-place such that the first `mid` elements of the underlying buffer
962    /// move to the end while the last `self.len() - mid` elements move to the front. After
963    /// calling `rotate_left`, the element previously at index `mid` will become the first element
964    /// in the slice.
965    #[inline]
966    pub fn rotate_left(&mut self, mid: usize) {
967        self.map_mut_to(|d| d.rotate_left(mid), |i| i.rotate_left(mid))
968    }
969
970    /// Rotate this attribute in-place such that the first `self.len() - k` elements of the
971    /// underlying buffer move to the end while the last `k` elements move to the front. After
972    /// calling `rotate_right`, the element previously at index `self.len() - k` will become the
973    /// first element in the slice.
974    #[inline]
975    pub fn rotate_right(&mut self, k: usize) {
976        self.map_mut_to(|d| d.rotate_right(k), |i| i.rotate_right(k))
977    }
978
979    /// Get a reference to the default element as a byte slice.
980    #[inline]
981    pub fn default_element(&self) -> ValueRef {
982        match self {
983            AttributeData::Direct(d) => d.default_element(),
984            AttributeData::Indirect(i) => i.default_element().upcast(),
985        }
986    }
987}
988
989/// Mesh attribute with an associated topology `I`.
990///
991/// This stores values that can be attached to mesh elements.
992#[derive(Clone, Debug, PartialEq)]
993pub struct Attribute<I> {
994    /// Underlying attribute data.
995    ///
996    /// This can be used to manipulate attribute values or their references directly.
997    pub data: AttributeData,
998    phantom: PhantomData<I>,
999}
1000
1001/// This type wraps a `DataVec` to store attribute data. Having the type parameter `I` allows
1002/// the compiler verify that attributes are being indexed correctly.
1003impl<I> Attribute<I> {
1004    /// Construct a direct attribute with a given size.
1005    pub fn direct_with_size<T: AttributeValue>(n: usize, def: T) -> Self {
1006        Attribute {
1007            data: AttributeData::direct_with_size(n, def),
1008            phantom: PhantomData,
1009        }
1010    }
1011
1012    /// Construct an indirect attribute with a given size.
1013    pub fn indirect_with_size<T: AttributeValueHash>(n: usize, def: T) -> Self {
1014        Attribute {
1015            data: AttributeData::indirect_with_size(n, def),
1016            phantom: PhantomData,
1017        }
1018    }
1019
1020    /// Construct a direct attribute from a given `Vec<T>` of data reusing the space already
1021    /// allocated by the `Vec`.
1022    pub fn direct_from_vec<T: AttributeValue + Default>(vec: Vec<T>) -> Self {
1023        Attribute {
1024            data: AttributeData::direct_from_vec(vec),
1025            phantom: PhantomData,
1026        }
1027    }
1028
1029    /// Construct an indirect attribute from a given `Vec<T>` of data, while saving any repeated
1030    /// values in the given cache.
1031    pub fn indirect_from_vec<T: AttributeValueHash + Default>(
1032        vec: Vec<T>,
1033        cache: &mut AttribValueCache,
1034    ) -> Self {
1035        Attribute {
1036            data: AttributeData::indirect_from_vec(vec, cache),
1037            phantom: PhantomData,
1038        }
1039    }
1040
1041    /// Construct an indirect attribute from a given `IndirectData` instance. It is assumed that
1042    /// the included data is already cached correctly in the associated cache.
1043    pub fn indirect_from_data(data: IndirectData) -> Self {
1044        Attribute {
1045            data: AttributeData::indirect_from_data(data),
1046            phantom: PhantomData,
1047        }
1048    }
1049
1050    /// Produce a slice to the underlying direct attribute data.
1051    #[inline]
1052    pub fn as_slice<T: Any>(&self) -> Result<&[T], Error> {
1053        self.data.as_slice()
1054    }
1055
1056    /// Produce a mutable slice to the underlying direct attribute data.
1057    #[inline]
1058    pub fn as_mut_slice<T: Any>(&mut self) -> Result<&mut [T], Error> {
1059        self.data.as_mut_slice()
1060    }
1061
1062    /// Construct a new empty attribute with the same buffer type, default element and topology as
1063    /// `self`.
1064    #[inline]
1065    pub fn duplicate_empty(&self) -> Self {
1066        self.promote_empty()
1067    }
1068
1069    /// Construct a new attribute with the same buffer type, default element and topology type as
1070    /// `self`.
1071    ///
1072    /// The data within the newly created attribute is expected to be initialized with the given
1073    /// function `init`, which takes the output `DataSliceMut` for the new attribute and the existing
1074    /// `DataSlice` from `self`.
1075    #[inline]
1076    pub fn duplicate_with(
1077        &self,
1078        duplicate_data: impl FnOnce(&mut VecDyn<dyn HasAttributeValue>, Slice<dyn HasAttributeValue>),
1079    ) -> Self {
1080        self.promote_with(duplicate_data)
1081    }
1082
1083    /// Construct a new attribute with the same buffer type, default element and topology type as
1084    /// `self`.
1085    ///
1086    /// The attribute is first initialized with the default value by allocating `len` default
1087    /// elements. Then the newly created buffer is expected to be modified by the `init` function.
1088    #[inline]
1089    pub fn duplicate_with_len(
1090        &self,
1091        len: usize,
1092        init: impl FnOnce(DataSliceMut, DataSlice),
1093    ) -> Self {
1094        self.promote_with_len(len, init)
1095    }
1096
1097    /// Construct a new empty attribute with the same buffer type and default element as `self`.
1098    ///
1099    /// In contrast to `duplicate_empty` this function allows the new attribute to correspond with a
1100    /// different topology.
1101    #[inline]
1102    pub fn promote_empty<J>(&self) -> Attribute<J> {
1103        Attribute {
1104            data: self.data.duplicate_empty(),
1105            phantom: PhantomData,
1106        }
1107    }
1108
1109    /// Construct a new attribute with the same data and default element as
1110    /// `self`, but corresponding to a different topology.
1111    pub fn promote<J>(&self) -> Attribute<J> {
1112        Attribute {
1113            data: self.data.clone(),
1114            phantom: PhantomData,
1115        }
1116    }
1117
1118    /// Construct a new attribute with the same data and default element as
1119    /// `self`, but corresponding to a different topology.
1120    ///
1121    /// This function consumes the given attribute.
1122    pub fn promote_into<J>(self) -> Attribute<J> {
1123        Attribute {
1124            data: self.data,
1125            phantom: PhantomData,
1126        }
1127    }
1128
1129    /// Construct a new attribute with the same buffer type and default element as `self`.
1130    #[inline]
1131    pub fn promote_with<J>(
1132        &self,
1133        promote_data: impl FnOnce(&mut VecDyn<dyn HasAttributeValue>, Slice<dyn HasAttributeValue>),
1134    ) -> Attribute<J> {
1135        Attribute {
1136            data: self.data.duplicate_with(promote_data),
1137            phantom: PhantomData,
1138        }
1139    }
1140
1141    /// Construct a new attribute with the same buffer type and default element as `self`.
1142    ///
1143    /// The attribute is first initialized with the default value by allocating `len` default
1144    /// elements. Then the newly created buffer is expected to be modified by the `init` function.
1145    pub fn promote_with_len<J>(
1146        &self,
1147        len: usize,
1148        init: impl FnOnce(DataSliceMut, DataSlice),
1149    ) -> Attribute<J> {
1150        Attribute {
1151            data: self.data.duplicate_with_len(len, init),
1152            phantom: PhantomData,
1153        }
1154    }
1155
1156    /// Construct a direct attribute from a given slice of data, by copying the data.
1157    #[inline]
1158    pub fn direct_from_slice<T: AttributeValue + Default>(data: &[T]) -> Self {
1159        Self::direct_from_vec(data.to_vec())
1160    }
1161
1162    /// Construct an indirect attribute from a given slice of data, by copying the data.
1163    #[inline]
1164    pub fn indirect_from_slice<T: AttributeValueHash + Default>(
1165        data: &[T],
1166        cache: &mut AttribValueCache,
1167    ) -> Self {
1168        Self::indirect_from_vec(data.to_vec(), cache)
1169    }
1170
1171    /// Get the type data stored within this attribute
1172    #[inline]
1173    pub fn check<T: Any>(&self) -> Result<&Self, Error> {
1174        self.data.check::<T>().map(|_| self)
1175    }
1176
1177    /// Get the mutable typed data stored within this attribute
1178    #[inline]
1179    pub fn check_mut<T: Any>(&mut self) -> Result<&mut Self, Error> {
1180        match self.data.check_mut::<T>() {
1181            Ok(_) => Ok(self),
1182            Err(e) => Err(e),
1183        }
1184    }
1185
1186    /// Produce an iterator over the underlying data elements.
1187    #[inline]
1188    pub fn iter<'a, T: Any>(&'a self) -> Result<Box<dyn Iterator<Item = &'a T> + 'a>, Error> {
1189        self.data.iter::<T>()
1190    }
1191
1192    /// Produce an iterator over the underlying data elements for a direct attribute.
1193    #[inline]
1194    pub fn direct_iter<T: Any>(&self) -> Result<slice::Iter<T>, Error> {
1195        self.data.direct_iter()
1196    }
1197
1198    /// Produce an iterator over the underlying data elements for an indirect attribute.
1199    #[inline]
1200    pub fn indirect_iter<T: Any>(&self) -> Result<impl Iterator<Item = &T>, Error> {
1201        self.data.indirect_iter()
1202    }
1203
1204    /// Produce a mutable iterator over the underlying data elements for a direct attribute.
1205    #[inline]
1206    pub fn direct_iter_mut<T: Any>(&mut self) -> Result<slice::IterMut<T>, Error> {
1207        self.data.direct_iter_mut()
1208    }
1209
1210    /// Iterate over all the value in this attribute and update them as needed.
1211    ///
1212    /// This function takes a closure which takes an index and a smart pointer to the stored value and
1213    /// produces an optional new value. The new value is then used to update the attribute using
1214    /// the provided cache.
1215    #[inline]
1216    pub fn indirect_update_with<T, F>(
1217        &mut self,
1218        f: F,
1219        cache: &mut AttribValueCache,
1220    ) -> Result<&mut Self, Error>
1221    where
1222        T: AttributeValueHash,
1223        F: FnMut(usize, &Irc<T>) -> Option<Irc<T>>,
1224    {
1225        match self.data.indirect_update_with(f, cache) {
1226            Ok(_) => Ok(self),
1227            Err(e) => Err(e),
1228        }
1229    }
1230
1231    /// Convert the data stored by this attribute into a vector of the same size.
1232    #[inline]
1233    pub fn clone_into_vec<T: AttributeValueHash>(&self) -> Result<Vec<T>, Error> {
1234        self.data.clone_into_vec::<T>()
1235    }
1236
1237    /// Convert the data stored by this direct attribute into a vector of the same size.
1238    #[inline]
1239    pub fn direct_clone_into_vec<T: Any + Clone>(&self) -> Result<Vec<T>, Error> {
1240        self.data.direct_clone_into_vec::<T>()
1241    }
1242
1243    /// Number of elements stored by this attribute. This is the same as the number of elements in
1244    /// the associated topology.
1245    #[inline]
1246    pub fn len(&self) -> usize {
1247        self.data.len()
1248    }
1249
1250    /// Check if there are any values in this attribute.
1251    #[inline]
1252    pub fn is_empty(&self) -> bool {
1253        self.data.is_empty()
1254    }
1255
1256    /// Get a reference to the internal data as a `DataSlice`.
1257    #[inline]
1258    pub fn data_slice(&self) -> DataSlice {
1259        self.data.data_slice()
1260    }
1261
1262    /// Get a mutable reference to the internal data as a `DataSliceMut`.
1263    #[inline]
1264    pub fn data_mut_slice(&mut self) -> DataSliceMut {
1265        self.data.data_mut_slice()
1266    }
1267
1268    /// Convert this attribute into the underlying buffer. This consumes the attribute.
1269    #[inline]
1270    pub fn into_data(self) -> DataVec {
1271        self.data.into_data()
1272    }
1273
1274    /// Extend this attribute by `n` elements. Effectively, this function appends the default
1275    /// element `n` number of times to this attribute.
1276    #[inline]
1277    pub fn extend_by(&mut self, n: usize) {
1278        self.data.extend_by(n);
1279    }
1280
1281    /// Rotate this attribute in-place such that the first `mid` elements of the underlying buffer
1282    /// move to the end while the last `self.len() - mid` elements move to the front. After
1283    /// calling `rotate_left`, the element previously at index `mid` will become the first element
1284    /// in the slice.
1285    #[inline]
1286    pub fn rotate_left(&mut self, mid: usize) {
1287        self.data.rotate_left(mid);
1288    }
1289
1290    /// Rotate this attribute in-place such that the first `self.len() - k` elements of the
1291    /// underlying buffer move to the end while the last `k` elements move to the front. After
1292    /// calling `rotate_right`, the element previously at index `self.len() - k` will become the
1293    /// first element in the slice.
1294    #[inline]
1295    pub fn rotate_right(&mut self, k: usize) {
1296        self.data.rotate_right(k);
1297    }
1298
1299    /// Get a reference to the default element.
1300    #[inline]
1301    pub fn default_element(&self) -> ValueRef {
1302        self.data.default_element()
1303    }
1304}
1305
1306/*
1307 * Implement typed indexing into an attribute.
1308 * This is a costly operation, but it could be useful for debugging.
1309 */
1310
1311macro_rules! impl_attribute_get {
1312    ($type:ty) => {
1313        impl Attribute<$type> {
1314            /// Get `i`'th attribute value.
1315            #[inline]
1316            pub fn get<T: Any + Copy, I: Into<$type>>(&self, i: I) -> Result<T, Error> {
1317                let element_id = self.data.element_type_id();
1318                Index::from(i.into())
1319                    .map_or(None, move |x| {
1320                        self.data
1321                            .map_to(
1322                                |d| d.as_slice().map(|s| s[x]),
1323                                |i| i.as_rc_slice().map(|s| *s[x]),
1324                            )
1325                            .ok()
1326                    })
1327                    .ok_or(Error::type_mismatch_id::<T>(element_id))
1328            }
1329
1330            /// Get a `const` reference to the `i`'th attribute value.
1331            #[inline]
1332            pub fn get_ref<T: Any, I: Into<$type>>(&self, i: I) -> Result<&T, Error> {
1333                let element_id = self.data.element_type_id();
1334                Index::from(i.into())
1335                    .map_or(None, move |x| {
1336                        self.data
1337                            .map_to(
1338                                |d| d.as_slice().map(|s| &s[x]),
1339                                |i| i.as_rc_slice().map(|s| &*s[x]),
1340                            )
1341                            .ok()
1342                    })
1343                    .ok_or(Error::type_mismatch_id::<T>(element_id))
1344            }
1345
1346            /// Get a mutable reference to the `i`'th direct attribute value.
1347            ///
1348            /// This function works only on direct attributes. Indirect attributes cannot be
1349            /// modified via mutable references, since they employ a special caching mechanism
1350            /// which aliases each stored element.
1351            #[inline]
1352            pub fn get_mut<T: Any, I: Into<$type>>(&mut self, i: I) -> Result<&mut T, Error> {
1353                let element_id = self.data.element_type_id();
1354                Index::from(i.into())
1355                    .map_or(None, move |x| {
1356                        self.data
1357                            .map_mut_to(
1358                                |d| d.as_mut_slice().map(|s| &mut s[x]),
1359                                |_| Err(Error::KindMismatchFoundIndirect),
1360                            )
1361                            .ok()
1362                    })
1363                    .ok_or(Error::type_mismatch_id::<T>(element_id))
1364            }
1365        }
1366    };
1367}
1368
1369impl_attribute_get!(MeshIndex);
1370impl_attribute_get!(VertexIndex);
1371impl_attribute_get!(EdgeIndex);
1372impl_attribute_get!(FaceIndex);
1373impl_attribute_get!(CellIndex);
1374impl_attribute_get!(EdgeVertexIndex);
1375impl_attribute_get!(FaceVertexIndex);
1376impl_attribute_get!(FaceEdgeIndex);
1377impl_attribute_get!(CellVertexIndex);
1378impl_attribute_get!(CellEdgeIndex);
1379impl_attribute_get!(CellFaceIndex);
1380impl_attribute_get!(VertexEdgeIndex);
1381impl_attribute_get!(VertexFaceIndex);
1382impl_attribute_get!(VertexCellIndex);
1383impl_attribute_get!(EdgeFaceIndex);
1384impl_attribute_get!(EdgeCellIndex);
1385impl_attribute_get!(FaceCellIndex);
1386
1387/// An intrinsic attribute type. This differs from `Attribute<I>` in that it is explicitly typed
1388/// and it is intended to be used for attributes that are "intrinsic" to the specific mesh type.
1389/// For instance, the position attribute is intrinsic to polygonal or tetrahedral meshes and point
1390/// clouds. Intrinsic attributes define the geometry of the mesh type.
1391#[derive(Clone, Debug, PartialEq)]
1392#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
1393pub struct IntrinsicAttribute<T, I> {
1394    data: Vec<T>,
1395    phantom: PhantomData<I>,
1396}
1397
1398impl<T, I> IntrinsicAttribute<T, I> {
1399    /// Construct an attribute with a given size.
1400    pub fn with_size(n: usize, def: T) -> Self
1401    where
1402        T: Clone,
1403    {
1404        IntrinsicAttribute {
1405            data: vec![def; n],
1406            phantom: PhantomData,
1407        }
1408    }
1409
1410    /// Construct an attribute from a given `Vec<T>` of data reusing the space aready
1411    /// allocated by the `Vec`.
1412    pub fn from_vec(vec: Vec<T>) -> Self {
1413        IntrinsicAttribute {
1414            data: vec,
1415            phantom: PhantomData,
1416        }
1417    }
1418
1419    //    /// Construct an attribute from a given `DataVec` of data reusing the space aready
1420    //    /// allocated.
1421    //    #[cfg(feature = "io")]
1422    //    pub fn from_io_buffer(data: IOBuffer) -> Option<Self>
1423    //    where
1424    //        T: Any,
1425    //    {
1426    //        data.into_vec::<T>().map(|vec| IntrinsicAttribute {
1427    //            data: vec,
1428    //            phantom: PhantomData,
1429    //        })
1430    //    }
1431
1432    /// Construct an attribute from a given slice of data, by copying the data.
1433    #[inline]
1434    pub fn from_slice(data: &[T]) -> Self
1435    where
1436        T: Clone,
1437    {
1438        Self::from_vec(data.to_vec())
1439    }
1440
1441    /// Produce a slice to the underlying data.
1442    #[inline]
1443    pub fn as_slice(&self) -> &[T] {
1444        self.data.as_slice()
1445    }
1446
1447    /// Produce a mutable slice to the underlying data.
1448    #[inline]
1449    pub fn as_mut_slice(&mut self) -> &mut [T] {
1450        self.data.as_mut_slice()
1451    }
1452
1453    /// Move the contents of this attribute into a `Vec`. This is identical to using the `Into`
1454    /// trait.
1455    #[inline]
1456    pub fn into_vec(self) -> Vec<T> {
1457        self.data
1458    }
1459
1460    /// Get the internal `Vec` storing the attribute data.
1461    ///
1462    /// Use this very carefully because it allows the user to modify the size of the internal
1463    /// vector which may violate intrinsic properties of the mesh that this attribute is part of.
1464    #[inline]
1465    pub fn as_mut_vec(&mut self) -> &mut Vec<T> {
1466        &mut self.data
1467    }
1468
1469    /// Convert the data stored by this attribute into a vector of the same size.
1470    #[inline]
1471    pub fn clone_into_vec(&self) -> Vec<T>
1472    where
1473        T: Clone,
1474    {
1475        self.data.clone()
1476    }
1477
1478    /// Convert the data stored by this attribute into a vector of the same size. This function is
1479    /// similar to `clone_into_vec` but assumes that elements are `Copy`. It may also be more performant
1480    /// than `clone_into_vec`.
1481    #[inline]
1482    pub fn copy_into_vec(&self) -> Vec<T>
1483    where
1484        T: Copy,
1485    {
1486        let mut vec = Vec::with_capacity(self.len());
1487        vec.extend(self.as_slice());
1488        vec
1489    }
1490
1491    /// Produce an iterator over the underlying data elements.
1492    #[inline]
1493    pub fn iter(&self) -> slice::Iter<T> {
1494        self.data.iter()
1495    }
1496
1497    /// Produce a parallel iterator over the underlying data elements.
1498    #[cfg(feature = "rayon")]
1499    #[inline]
1500    pub fn par_iter(&self) -> rayon::slice::Iter<T>
1501    where
1502        T: Sync,
1503    {
1504        use rayon::iter::IntoParallelRefIterator;
1505        self.data.par_iter()
1506    }
1507
1508    /// Produce a mutable iterator over the underlying data elements.
1509    #[inline]
1510    pub fn iter_mut(&mut self) -> slice::IterMut<T> {
1511        self.data.iter_mut()
1512    }
1513
1514    /// Produce a mutable parallel iterator over the underlying data elements.
1515    #[cfg(feature = "rayon")]
1516    #[inline]
1517    pub fn par_iter_mut(&mut self) -> rayon::slice::IterMut<T>
1518    where
1519        T: Sync + Send,
1520    {
1521        use rayon::iter::IntoParallelRefMutIterator;
1522        self.data.par_iter_mut()
1523    }
1524
1525    /// Number of elements stored by this attribute. This is the same as the number of elements in
1526    /// the associated topology.
1527    #[inline]
1528    pub fn len(&self) -> usize {
1529        self.data.len()
1530    }
1531
1532    /// Check if there are any values in this attribute.
1533    #[inline]
1534    pub fn is_empty(&self) -> bool {
1535        self.data.is_empty()
1536    }
1537}
1538
1539impl<T, I> From<Vec<T>> for IntrinsicAttribute<T, I> {
1540    #[inline]
1541    fn from(vec: Vec<T>) -> Self {
1542        Self::from_vec(vec)
1543    }
1544}
1545
1546impl<T, I> From<IntrinsicAttribute<T, I>> for Vec<T> {
1547    #[inline]
1548    fn from(val: IntrinsicAttribute<T, I>) -> Self {
1549        val.into_vec()
1550    }
1551}
1552
1553impl<T, I: Into<usize>, J: Into<I>> std::ops::Index<J> for IntrinsicAttribute<T, I> {
1554    type Output = T;
1555    fn index(&self, index: J) -> &T {
1556        &self.data[index.into().into()]
1557    }
1558}
1559impl<T, I: Into<usize>, J: Into<I>> std::ops::IndexMut<J> for IntrinsicAttribute<T, I> {
1560    fn index_mut(&mut self, index: J) -> &mut T {
1561        &mut self.data[index.into().into()]
1562    }
1563}
1564
1565impl<T, I> std::iter::IntoIterator for IntrinsicAttribute<T, I> {
1566    type Item = T;
1567    type IntoIter = std::vec::IntoIter<T>;
1568    fn into_iter(self) -> Self::IntoIter {
1569        self.into_vec().into_iter()
1570    }
1571}
1572
1573impl<T, I> std::iter::FromIterator<T> for IntrinsicAttribute<T, I> {
1574    fn from_iter<J>(iter: J) -> Self
1575    where
1576        J: IntoIterator<Item = T>,
1577    {
1578        Self::from_vec(Vec::from_iter(iter))
1579    }
1580}
1581
1582#[cfg(feature = "rayon")]
1583impl<T: Send, I> rayon::iter::IntoParallelIterator for IntrinsicAttribute<T, I> {
1584    type Item = T;
1585    type Iter = rayon::vec::IntoIter<T>;
1586    fn into_par_iter(self) -> Self::Iter {
1587        self.into_vec().into_par_iter()
1588    }
1589}
1590
1591#[cfg(test)]
1592mod tests {
1593    use super::*;
1594
1595    #[test]
1596    fn indirect_set_value_at() {
1597        let mut cache = AttribValueCache::default();
1598        let mut data = IndirectData::with_size(3, String::from("default"));
1599        let val = HValue::new(Irc::new(String::from("default")));
1600        assert_eq!(&data.default_element, &val);
1601        data.set_at(1, String::from("default"), &mut cache).unwrap();
1602        assert!(cache.is_empty());
1603        data.set_at(1, String::from("New Value"), &mut cache)
1604            .unwrap();
1605        assert_eq!(cache.len(), 1);
1606    }
1607}