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};
6use 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#[allow(missing_docs)]
20#[dync_mod]
21mod value_traits {
22 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 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
36pub type DataSlice<'a> = Slice<'a, AttributeValueVTable>;
38pub type HDataSlice<'a> = Slice<'a, AttributeValueHashVTable>;
40pub type DataSliceMut<'a> = SliceMut<'a, AttributeValueVTable>;
42pub type HDataSliceMut<'a> = SliceMut<'a, AttributeValueHashVTable>;
44pub type DataVec = VecDyn<AttributeValueVTable>;
46pub type HDataVec = VecDyn<AttributeValueHashVTable>;
48pub type Value = BoxValue<AttributeValueVTable>;
50pub type ValueRef<'a> = dync::ValueRef<'a, AttributeValueVTable>;
52pub type HValue = SmallValue<AttributeValueHashVTable>;
54pub type HValueRef<'a> = dync::ValueRef<'a, AttributeValueHashVTable>;
56pub type HValueMut<'a> = dync::ValueMut<'a, AttributeValueHashVTable>;
58
59pub type AttribValueCache = HashSet<HValue>;
61
62macro_rules! impl_data_base {
64 ($vec_type:ty) => {
65 #[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 #[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 #[inline]
85 pub fn element_type_id(&self) -> TypeId {
86 self.buf.element_type_id()
87 }
88
89 #[inline]
91 pub fn element_size(&self) -> usize {
92 self.buf.element_size()
93 }
94
95 #[inline]
98 pub fn len(&self) -> usize {
99 self.buf.len()
100 }
101
102 #[inline]
105 pub fn byte_len(&self) -> usize {
106 self.buf.len() * self.buf.element_size()
107 }
108
109 #[inline]
111 pub fn is_empty(&self) -> bool {
112 self.buf.is_empty()
113 }
114
115 #[inline]
124 pub unsafe fn get_unchecked_ref<T: Any>(&self, i: usize) -> &T {
125 self.buf.get_unchecked_ref(i)
126 }
127
128 #[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 #[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 #[inline]
150 pub fn data(&self) -> &$vec_type {
151 &self.buf
152 }
153
154 #[inline]
156 pub fn data_mut(&mut self) -> &mut $vec_type {
157 &mut self.buf
158 }
159
160 #[inline]
162 pub fn into_data(self) -> $vec_type {
163 self.buf
164 }
165
166 #[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 #[inline]
187 pub fn rotate_left(&mut self, mid: usize) {
188 self.buf.rotate_left(mid);
189 }
190
191 #[inline]
198 pub fn rotate_right(&mut self, k: usize) {
199 self.buf.rotate_right(k);
200 }
201 };
202}
203
204#[derive(Clone, Debug, PartialEq)]
209pub struct IndirectData {
210 buf: HDataVec,
212 default_element: HValue,
214}
215
216impl IndirectData {
217 impl_data_base!(HDataVec);
218
219 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 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 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 #[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 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 pub fn duplicate_with(
276 &self,
277 dup_data: impl FnOnce(HDataSlice) -> VecDyn<dyn HasAttributeValue>,
278 ) -> Self {
279 IndirectData {
280 buf: from_dyn.as_slice(),
282 )),
283 default_element: self.default_element.clone(),
284 }
285 }
286
287 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 #[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 #[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 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 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 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 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 #[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 #[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 #[inline]
441 pub fn default_element(&self) -> HValueRef {
442 self.default_element.as_ref()
443 }
444}
445
446#[derive(Clone, Debug, PartialEq)]
450pub struct DirectData {
451 buf: DataVec,
453 default_element: Value,
455}
456
457impl DirectData {
459 impl_data_base!(DataVec);
460
461 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 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 pub unsafe fn from_raw_data(buf: DataVec, default_element: Value) -> Self {
486 DirectData {
487 buf,
488 default_element,
489 }
490 }
491
492 #[inline]
494 pub fn from_slice<T: AttributeValue + Default>(buf: &[T]) -> Self {
495 Self::from_vec(buf.to_vec())
496 }
497
498 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 pub fn duplicate_with(
512 &self,
513 dup_data: impl FnOnce(DataSlice) -> VecDyn<dyn HasAttributeValue>,
514 ) -> Self {
515 DirectData {
516 buf: from_dyn.as_slice(),
518 )),
519 default_element: self.default_element.clone(),
520 }
521 }
522
523 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 #[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 #[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 #[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 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 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 #[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 #[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 #[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 #[inline]
607 pub fn default_element(&self) -> ValueRef {
608 self.default_element.as_ref()
609 }
610}
611
612#[derive(Clone, Debug, PartialEq)]
617pub enum AttributeData {
618 Direct(DirectData),
620 Indirect(IndirectData),
626}
627
628impl AttributeData {
629 pub fn is_direct(&self) -> bool {
631 matches!(self, AttributeData::Direct(_))
632 }
633
634 pub fn is_indirect(&self) -> bool {
636 matches!(self, AttributeData::Indirect(_))
637 }
638
639 pub fn direct_with_size<T: AttributeValue>(n: usize, def: T) -> Self {
641 AttributeData::Direct(DirectData::with_size(n, def))
642 }
643
644 pub fn indirect_with_size<T: AttributeValueHash>(n: usize, def: T) -> Self {
646 AttributeData::Indirect(IndirectData::with_size(n, def))
647 }
648
649 pub fn direct_from_vec<T: AttributeValue + Default>(vec: Vec<T>) -> Self {
652 AttributeData::Direct(DirectData::from_vec(vec))
653 }
654
655 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 pub fn indirect_from_data(data: IndirectData) -> Self {
667 AttributeData::Indirect(data)
668 }
669
670 #[inline]
672 pub fn direct_from_slice<T: AttributeValue + Default>(data: &[T]) -> Self {
673 Self::direct_from_vec(data.to_vec())
674 }
675
676 #[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 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 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 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 #[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 #[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 pub fn duplicate_empty(&self) -> Self {
741 self.map(|d| d.duplicate_empty(), |i| i.duplicate_empty())
742 }
743
744 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;
754 dup_data(&mut vec_dyn, into_dyn);
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;
760 dup_data(&mut vec_dyn, into_dyn);
761 vec_dyn
762 })),
763 }
764 }
765
766 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
894 pub fn len(&self) -> usize {
895 self.map_to(|d| d.len(), |i| i.len())
896 }
897
898 #[inline]
900 pub fn is_empty(&self) -> bool {
901 self.map_to(|d| d.is_empty(), |i| i.is_empty())
902 }
903
904 #[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 #[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 #[inline]
921 pub fn indirect_data(&self) -> Result<&IndirectData, Error> {
922 self.map_to(|_| Err(Error::KindMismatchFoundDirect), Ok)
923 }
924
925 #[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 #[inline]
933 pub fn direct_data(&self) -> Result<&DirectData, Error> {
934 self.map_to(Ok, |_| Err(Error::KindMismatchFoundDirect))
935 }
936
937 #[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 #[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 #[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 #[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 #[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 #[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#[derive(Clone, Debug, PartialEq)]
993pub struct Attribute<I> {
994 pub data: AttributeData,
998 phantom: PhantomData<I>,
999}
1000
1001impl<I> Attribute<I> {
1004 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 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 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 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 pub fn indirect_from_data(data: IndirectData) -> Self {
1044 Attribute {
1045 data: AttributeData::indirect_from_data(data),
1046 phantom: PhantomData,
1047 }
1048 }
1049
1050 #[inline]
1052 pub fn as_slice<T: Any>(&self) -> Result<&[T], Error> {
1053 self.data.as_slice()
1054 }
1055
1056 #[inline]
1058 pub fn as_mut_slice<T: Any>(&mut self) -> Result<&mut [T], Error> {
1059 self.data.as_mut_slice()
1060 }
1061
1062 #[inline]
1065 pub fn duplicate_empty(&self) -> Self {
1066 self.promote_empty()
1067 }
1068
1069 #[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 #[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 #[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 pub fn promote<J>(&self) -> Attribute<J> {
1112 Attribute {
1113 data: self.data.clone(),
1114 phantom: PhantomData,
1115 }
1116 }
1117
1118 pub fn promote_into<J>(self) -> Attribute<J> {
1123 Attribute {
1124 data: self.data,
1125 phantom: PhantomData,
1126 }
1127 }
1128
1129 #[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 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 #[inline]
1158 pub fn direct_from_slice<T: AttributeValue + Default>(data: &[T]) -> Self {
1159 Self::direct_from_vec(data.to_vec())
1160 }
1161
1162 #[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 #[inline]
1173 pub fn check<T: Any>(&self) -> Result<&Self, Error> {
1174 self.data.check::<T>().map(|_| self)
1175 }
1176
1177 #[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 #[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 #[inline]
1194 pub fn direct_iter<T: Any>(&self) -> Result<slice::Iter<T>, Error> {
1195 self.data.direct_iter()
1196 }
1197
1198 #[inline]
1200 pub fn indirect_iter<T: Any>(&self) -> Result<impl Iterator<Item = &T>, Error> {
1201 self.data.indirect_iter()
1202 }
1203
1204 #[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 #[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 #[inline]
1233 pub fn clone_into_vec<T: AttributeValueHash>(&self) -> Result<Vec<T>, Error> {
1234 self.data.clone_into_vec::<T>()
1235 }
1236
1237 #[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 #[inline]
1246 pub fn len(&self) -> usize {
1247 self.data.len()
1248 }
1249
1250 #[inline]
1252 pub fn is_empty(&self) -> bool {
1253 self.data.is_empty()
1254 }
1255
1256 #[inline]
1258 pub fn data_slice(&self) -> DataSlice {
1259 self.data.data_slice()
1260 }
1261
1262 #[inline]
1264 pub fn data_mut_slice(&mut self) -> DataSliceMut {
1265 self.data.data_mut_slice()
1266 }
1267
1268 #[inline]
1270 pub fn into_data(self) -> DataVec {
1271 self.data.into_data()
1272 }
1273
1274 #[inline]
1277 pub fn extend_by(&mut self, n: usize) {
1278 self.data.extend_by(n);
1279 }
1280
1281 #[inline]
1286 pub fn rotate_left(&mut self, mid: usize) {
1287 self.data.rotate_left(mid);
1288 }
1289
1290 #[inline]
1295 pub fn rotate_right(&mut self, k: usize) {
1296 self.data.rotate_right(k);
1297 }
1298
1299 #[inline]
1301 pub fn default_element(&self) -> ValueRef {
1302 self.data.default_element()
1303 }
1304}
1305
1306macro_rules! impl_attribute_get {
1312 ($type:ty) => {
1313 impl Attribute<$type> {
1314 #[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 #[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 #[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#[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 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 pub fn from_vec(vec: Vec<T>) -> Self {
1413 IntrinsicAttribute {
1414 data: vec,
1415 phantom: PhantomData,
1416 }
1417 }
1418
1419 #[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 #[inline]
1443 pub fn as_slice(&self) -> &[T] {
1444 self.data.as_slice()
1445 }
1446
1447 #[inline]
1449 pub fn as_mut_slice(&mut self) -> &mut [T] {
1450 self.data.as_mut_slice()
1451 }
1452
1453 #[inline]
1456 pub fn into_vec(self) -> Vec<T> {
1457 self.data
1458 }
1459
1460 #[inline]
1465 pub fn as_mut_vec(&mut self) -> &mut Vec<T> {
1466 &mut self.data
1467 }
1468
1469 #[inline]
1471 pub fn clone_into_vec(&self) -> Vec<T>
1472 where
1473 T: Clone,
1474 {
1475 self.data.clone()
1476 }
1477
1478 #[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 #[inline]
1493 pub fn iter(&self) -> slice::Iter<T> {
1494 self.data.iter()
1495 }
1496
1497 #[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 #[inline]
1510 pub fn iter_mut(&mut self) -> slice::IterMut<T> {
1511 self.data.iter_mut()
1512 }
1513
1514 #[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 #[inline]
1528 pub fn len(&self) -> usize {
1529 self.data.len()
1530 }
1531
1532 #[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}