1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
#![warn(missing_docs)]

//! # Attribute API.
//!
//! This module defines the API used to store and access attributes in meshes. Attributes are
//! stored inside `HashMap` data structures, and are accessed through the variety of getters
//! described below. The most efficient attribute access is through iterators which are standard
//! slice iterators, so slice operations work on attribute data. Alternatively, individual
//! attribute values can be accessed using `get`, `get_ref` and `get_mut`, but each call to such a
//! getter icurs a cost for runtime type checking. Since the type of the attribute being stored is
//! determined at runtime, you must provide the expected type and location of the attribute when
//! retrieving values. This is done using a "turbofish"; for example to retrieve a 3 float array
//! attribute stored at vertices we need to specify `::<[f32; 3], VertexIndex>` to the appropriate
//! accessor. See the `Attrib` trait for more details.
//!
//! ## New Mesh Types
//! When defining new meshes, simply "derive" the `Attrib` trait. The custom derive will look for
//! a field with type `AttribDict<_>` where `_` corresponds to an index type identifying the
//! location where the attribute lives. For example `AttribDict<VertexIndex>` is a `HashMap` that
//! stores attributes at vertices of the mesh. Any topology index can be used there. See the
//! implementations of `TetMesh` and `TriMesh` for more details.

use buffer::DataBuffer;
use crate::index::*;
use crate::mesh::topology::*;
#[cfg(feature = "rayon")]
use rayon::prelude::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::marker::PhantomData;
use std::slice;

// Expose the entry API for our AttribDict type.
pub use std::collections::hash_map::Entry;

/// Attribute map indexed by `I`.
pub type AttribDict<I> = HashMap<String, Attribute<I>>;

/// Mesh attribute type. This stores values that can be attached to mesh elements.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Attribute<I> {
    data: DataBuffer,
    // Bytes representing the default element of this attribute. This is useful for type
    // agnostic algorithms that change the size of the attribute data buffer.
    default_element: Box<[u8]>,
    phantom: PhantomData<I>,
}

/// Helper trait to interpret a slice of bytes representing a sized type.
/// Note: this trait is meant to be used transiently on the same platform, and so doesn't care
/// about endianness. In other words, the slice of bytes generated by this trait should not be
/// stored anywhere that outlives the lifetime of the program.
pub trait Bytes
where
    Self: Sized,
{
    /// Get a slice of bytes representing `Self`.
    #[inline]
    fn as_bytes(&self) -> &[u8] {
        let byte_ptr = self as *const Self as *const u8;
        unsafe { std::slice::from_raw_parts(byte_ptr, std::mem::size_of::<Self>()) }
    }

    /// Panics if the size of the given bytes slice is not equal to the size of `Self`.
    #[inline]
    fn interpret_bytes(bytes: &[u8]) -> &Self {
        assert_eq!(bytes.len(), std::mem::size_of::<Self>());
        let ptr = bytes.as_ptr() as *const Self;
        unsafe { &*ptr }
    }
}

impl<T: Sized> Bytes for T {}

#[test]
fn bytes_from_value_test() {
    let val = 10.2_f64;
    assert_eq!(&val, Bytes::interpret_bytes(val.as_bytes()));
}

/// This type wraps a `DataBuffer` to store attribute data. Having the type parameter `I` allows
/// the compiler verify that attributes are being indexed correctly.
impl<I> Attribute<I> {
    /// Construct an attribute with a given size.
    pub fn with_size<T: Any + Clone>(n: usize, def: T) -> Self {
        Attribute {
            data: DataBuffer::with_size(n, def.clone()),
            default_element: def.as_bytes().into(),
            phantom: PhantomData,
        }
    }

    /// Construct an attribute from a given `Vec<T>` of data reusing the space aready
    /// allocated by the `Vec`.
    pub fn from_vec<T: Any + Clone + Default>(vec: Vec<T>) -> Self {
        Attribute {
            data: DataBuffer::from_vec(vec),
            default_element: T::default().as_bytes().into(),
            phantom: PhantomData,
        }
    }

    /// Construct an attribute from a given `DataBuffer` of data reusing the space aready
    /// allocated.
    pub fn from_data_buffer(data: DataBuffer, def: &[u8]) -> Self {
        Attribute {
            data,
            default_element: def.into(),
            phantom: PhantomData,
        }
    }

    //    /// Construct an attribute from a given `IOBuffer` of data reusing the space aready
    //    /// allocated.
    //    #[cfg(feature = "io")]
    //    pub fn from_io_buffer(data: IOBuffer, def: &[u8]) -> Self {
    //        Attribute {
    //            data,
    //            default_element: def.into(),
    //            phantom: PhantomData,
    //        }
    //    }

    /// Construct an attribute from a given slice of data, by copying the data.
    #[inline]
    pub fn from_slice<T: Any + Clone + Default>(data: &[T]) -> Self {
        Self::from_vec(data.to_vec())
    }

    /// Get the type data stored within this attribute
    #[inline]
    pub fn check<T: Any>(&self) -> Result<&Self, Error> {
        match self.data.check_ref::<T>() {
            Some(_) => Ok(self),
            None => Err(Error::TypeMismatch),
        }
    }

    /// Get the mutable typed data stored within this attribute
    #[inline]
    pub fn check_mut<T: Any>(&mut self) -> Result<&mut Self, Error> {
        match self.data.check_mut::<T>() {
            Some(_) => Ok(self),
            None => Err(Error::TypeMismatch),
        }
    }

    /// Get the type data stored within this attribute
    #[inline]
    pub fn element_type_id(&self) -> TypeId {
        self.data.element_type_id()
    }

    /// Produce a slice to the underlying data.
    #[inline]
    pub fn as_slice<T: Any>(&self) -> Result<&[T], Error> {
        self.data.as_slice().ok_or(Error::TypeMismatch)
    }

    /// Produce a mutable slice to the underlying data.
    #[inline]
    pub fn as_mut_slice<T: Any>(&mut self) -> Result<&mut [T], Error> {
        self.data.as_mut_slice().ok_or(Error::TypeMismatch)
    }

    /// Convert the data stored by this attribute into a vector of the same size.
    #[inline]
    pub fn clone_into_vec<T: Any + Clone>(&self) -> Result<Vec<T>, Error> {
        self.data.clone_into_vec().ok_or(Error::TypeMismatch)
    }

    /// Convert the data stored by this attribute into a vector of the same size. This function is
    /// similar to `clone_into_vec` but assumes that elements are `Copy`. It may also be more
    /// performant than `clone_into_vec`.
    #[inline]
    pub fn copy_into_vec<T: Any + Copy>(&self) -> Result<Vec<T>, Error> {
        self.data.copy_into_vec().ok_or(Error::TypeMismatch)
    }

    /// Produce an iterator over the underlying data elements.
    #[inline]
    pub fn iter<'a, T: Any + 'a>(&'a self) -> Result<slice::Iter<T>, Error> {
        self.data.iter::<T>().ok_or(Error::TypeMismatch)
    }

    /// Produce a mutable iterator over the underlying data elements.
    #[inline]
    pub fn iter_mut<'a, T: Any + 'a>(&'a mut self) -> Result<slice::IterMut<T>, Error> {
        self.data.iter_mut::<T>().ok_or(Error::TypeMismatch)
    }

    /// Number of elements stored by this attribute. This is the same as the number of elements in
    /// the associated topology.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Check if there are any values in this attribute.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get `i`'th attribute value.
    #[inline]
    pub unsafe fn get_unchecked<T: Any + Copy>(&self, i: usize) -> T {
        self.data.get_unchecked(i)
    }

    /// Get a `const` reference to the `i`'th attribute value.
    #[inline]
    pub unsafe fn get_unchecked_ref<T: Any>(&self, i: usize) -> &T {
        self.data.get_unchecked_ref(i)
    }

    /// Get a mutable reference to the `i`'th attribute value.
    #[inline]
    pub unsafe fn get_unchecked_mut<T: Any>(&mut self, i: usize) -> &mut T {
        self.data.get_unchecked_mut(i)
    }

    /// Get a reference to the internal `DataBuffer`.
    #[inline]
    pub fn buffer_ref(&self) -> &DataBuffer {
        &self.data
    }

    /// Get a mutable reference to the internal `DataBuffer`.
    #[inline]
    pub fn buffer_mut(&mut self) -> &mut DataBuffer {
        &mut self.data
    }

    /// Convert this attribute into the underlying buffer. This consumes the attribute.
    #[inline]
    pub fn into_buffer(self) -> DataBuffer {
        self.data
    }

    /// Extend this attribute by `n` elements. Effectively, this function appends the default
    /// element `n` number of times to this attribute.
    #[inline]
    pub fn extend_by(&mut self, n: usize) {
        let Attribute {
            data,
            default_element,
            ..
        } = self;
        for _ in 0..n {
            data.push_bytes(&default_element);
        }
    }

    /// Rotate this attribute in-place such that the first `mid` elements of the underlying buffer
    /// move to the end while the last `self.len() - mid` elements move to the front. After
    /// calling `rotate_left`, the element previously at index `mid` will become the first element
    /// in the slice.
    #[inline]
    pub fn rotate_left(&mut self, mid: usize) {
        self.data.rotate_left(mid);
    }

    /// Rotate this attribute in-place such that the first `self.len() - k` elements of the
    /// underlying buffer move to the end while the last `k` elements move to the front. After
    /// calling `rotate_right`, the element previously at index `self.len() - k` will become the
    /// first element in the slice.
    #[inline]
    pub fn rotate_right(&mut self, k: usize) {
        self.data.rotate_right(k);
    }

    /// Get a reference to the defult element as a byte slice.
    #[inline]
    pub fn default_bytes(&self) -> &[u8] {
        &self.default_element
    }
}

/// An intrinsic attribute type. This differs from `Attribute<I>` in that it is explicitly typed
/// and it is intended to be used for attributes that are "intrinsic" to the specific mesh type.
/// For instance, the position attribute is intrinsic to polygonal or tetrahedral meshes and point
/// clouds. Intrinsic attributes define the geometry of the mesh type.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IntrinsicAttribute<T, I> {
    data: Vec<T>,
    phantom: PhantomData<I>,
}

impl<T, I> IntrinsicAttribute<T, I> {
    /// Construct an attribute with a given size.
    pub fn with_size(n: usize, def: T) -> Self
    where
        T: Clone,
    {
        IntrinsicAttribute {
            data: vec![def; n],
            phantom: PhantomData,
        }
    }

    /// Construct an attribute from a given `Vec<T>` of data reusing the space aready
    /// allocated by the `Vec`.
    pub fn from_vec(vec: Vec<T>) -> Self {
        IntrinsicAttribute {
            data: vec,
            phantom: PhantomData,
        }
    }

    //    /// Construct an attribute from a given `DataBuffer` of data reusing the space aready
    //    /// allocated.
    //    #[cfg(feature = "io")]
    //    pub fn from_io_buffer(data: IOBuffer) -> Option<Self>
    //    where
    //        T: Any,
    //    {
    //        data.into_vec::<T>().map(|vec| IntrinsicAttribute {
    //            data: vec,
    //            phantom: PhantomData,
    //        })
    //    }

    /// Construct an attribute from a given slice of data, by copying the data.
    #[inline]
    pub fn from_slice(data: &[T]) -> Self
    where
        T: Clone,
    {
        Self::from_vec(data.to_vec())
    }

    /// Produce a slice to the underlying data.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        self.data.as_slice()
    }

    /// Produce a mutable slice to the underlying data.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        self.data.as_mut_slice()
    }

    /// Move the contents of this attribute into a `Vec`. This is identical to using the `Into`
    /// trait.
    #[inline]
    pub fn into_vec(self) -> Vec<T> {
        self.data
    }

    /// Get the internal `Vec` storing the attribute data. Use this very carefully because it
    /// allows the user to modify the size of the internal vector which may violate intrinsic
    /// properties of
    /// the mesh that this attribute is part of.
    #[inline]
    pub fn as_mut_vec(&mut self) -> &mut Vec<T> {
        &mut self.data
    }

    /// Convert the data stored by this attribute into a vector of the same size.
    #[inline]
    pub fn clone_into_vec(&self) -> Vec<T>
    where
        T: Clone,
    {
        self.data.clone()
    }

    /// Convert the data stored by this attribute into a vector of the same size. This function is
    /// similar to `clone_into_vec` but assumes that elements are `Copy`. It may also be more performant
    /// than `clone_into_vec`.
    #[inline]
    pub fn copy_into_vec(&self) -> Vec<T>
    where
        T: Copy,
    {
        let mut vec = Vec::with_capacity(self.len());
        vec.extend(self.as_slice());
        vec
    }

    /// Produce an iterator over the underlying data elements.
    #[inline]
    pub fn iter(&self) -> slice::Iter<T> {
        self.data.iter()
    }

    /// Produce a parallel iterator over the underlying data elements.
    #[cfg(feature = "rayon")]
    #[inline]
    pub fn par_iter(&self) -> rayon::slice::Iter<T>
    where
        T: Sync,
    {
        self.data.par_iter()
    }

    /// Produce a mutable iterator over the underlying data elements.
    #[inline]
    pub fn iter_mut(&mut self) -> slice::IterMut<T> {
        self.data.iter_mut()
    }

    /// Produce a mutable parallel iterator over the underlying data elements.
    #[cfg(feature = "rayon")]
    #[inline]
    pub fn par_iter_mut(&mut self) -> rayon::slice::IterMut<T>
    where
        T: Sync + Send,
    {
        self.data.par_iter_mut()
    }

    /// Number of elements stored by this attribute. This is the same as the number of elements in
    /// the associated topology.
    #[inline]
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Check if there are any values in this attribute.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

impl<T, I> From<Vec<T>> for IntrinsicAttribute<T, I> {
    #[inline]
    fn from(vec: Vec<T>) -> Self {
        Self::from_vec(vec)
    }
}

impl<T, I> Into<Vec<T>> for IntrinsicAttribute<T, I> {
    #[inline]
    fn into(self) -> Vec<T> {
        self.into_vec()
    }
}

impl<T, I: Into<usize>, J: Into<I>> std::ops::Index<J> for IntrinsicAttribute<T, I> {
    type Output = T;
    fn index(&self, index: J) -> &T {
        &self.data[index.into().into()]
    }
}
impl<T, I: Into<usize>, J: Into<I>> std::ops::IndexMut<J> for IntrinsicAttribute<T, I> {
    fn index_mut(&mut self, index: J) -> &mut T {
        &mut self.data[index.into().into()]
    }
}

impl<T, I> std::iter::IntoIterator for IntrinsicAttribute<T, I> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;
    fn into_iter(self) -> Self::IntoIter {
        self.into_vec().into_iter()
    }
}

impl<T, I> std::iter::FromIterator<T> for IntrinsicAttribute<T, I> {
    fn from_iter<J>(iter: J) -> Self
    where
        J: IntoIterator<Item = T>,
    {
        Self::from_vec(Vec::from_iter(iter))
    }
}

#[cfg(feature = "rayon")]
impl<T: Send, I> rayon::iter::IntoParallelIterator for IntrinsicAttribute<T, I> {
    type Item = T;
    type Iter = rayon::vec::IntoIter<T>;
    fn into_par_iter(self) -> Self::Iter {
        self.into_vec().into_par_iter()
    }
}

/// This trait provides an interface for the implementer of `Attrib` to access attributes
/// associated with a specific topology within a mesh.
pub trait AttribIndex<M>
where
    Self: ::std::marker::Sized + Clone,
{
    /// Get the size of the attribute at the appropriate mesh location determined by `I`.
    fn attrib_size(mesh: &M) -> usize;

    /// Read only access to the attribute dictionary.
    fn attrib_dict(mesh: &M) -> &AttribDict<Self>;

    /// Read and write access to the attribute dictionary.
    fn attrib_dict_mut(mesh: &mut M) -> &mut AttribDict<Self>;
}

macro_rules! impl_attrib_index {
    ($topo_attrib:ident, $type:ty, $topo_num:ident) => {
        impl Attribute<$type> {
            /// Get `i`'th attribute value.
            #[inline]
            pub fn get<T: Any + Copy, I: Into<$type>>(&self, i: I) -> Result<T, Error> {
                Index::from(i.into())
                    .map_or(None, move |x| self.data.get(x))
                    .ok_or(Error::TypeMismatch)
            }

            /// Get a `const` reference to the `i`'th attribute value.
            #[inline]
            pub fn get_ref<T: Any, I: Into<$type>>(&self, i: I) -> Result<&T, Error> {
                Index::from(i.into())
                    .map_or(None, move |x| self.data.get_ref(x))
                    .ok_or(Error::TypeMismatch)
            }

            /// Get a mutable reference to the `i`'th attribute value.
            #[inline]
            pub fn get_mut<T: Any, I: Into<$type>>(&mut self, i: I) -> Result<&mut T, Error> {
                Index::from(i.into())
                    .map_or(None, move |x| self.data.get_mut(x))
                    .ok_or(Error::TypeMismatch)
            }
        }

        /// Topology specific attribute implementation trait. This trait exists to allow one to
        /// access mesh attributes using the `AttribIndex` trait, and should never be used
        /// explicitly.
        pub trait $topo_attrib {
            /// Mesh implementation of the attribute size getter.
            fn impl_attrib_size(&self) -> usize;
            /// Mesh implementation of the attribute dictionary getter.
            fn impl_attrib_dict(&self) -> &AttribDict<$type>;
            /// Mesh implementation of the attribute dictionary mutable getter.
            fn impl_attrib_dict_mut(&mut self) -> &mut AttribDict<$type>;
        }

        impl<M: $topo_attrib> AttribIndex<M> for $type {
            #[inline]
            fn attrib_size(mesh: &M) -> usize {
                mesh.impl_attrib_size()
            }

            #[inline]
            fn attrib_dict(mesh: &M) -> &AttribDict<Self> {
                mesh.impl_attrib_dict()
            }

            #[inline]
            fn attrib_dict_mut(mesh: &mut M) -> &mut AttribDict<Self> {
                mesh.impl_attrib_dict_mut()
            }
        }
    };
}

impl_attrib_index!(MeshAttrib, MeshIndex, num_meshes);
impl_attrib_index!(VertexAttrib, VertexIndex, num_verts);
impl_attrib_index!(EdgeAttrib, EdgeIndex, num_edges);
impl_attrib_index!(FaceAttrib, FaceIndex, num_faces);
impl_attrib_index!(CellAttrib, CellIndex, num_cells);
impl_attrib_index!(EdgeVertexAttrib, EdgeVertexIndex, num_edge_verts);
impl_attrib_index!(FaceVertexAttrib, FaceVertexIndex, num_face_verts);
impl_attrib_index!(FaceEdgeAttrib, FaceEdgeIndex, num_face_edges);
impl_attrib_index!(CellVertexAttrib, CellVertexIndex, num_cell_verts);
impl_attrib_index!(CellEdgeAttrib, CellEdgeIndex, num_cell_edges);
impl_attrib_index!(CellFaceAttrib, CellFaceIndex, num_cell_faces);
impl_attrib_index!(VertexEdgeAttrib, VertexEdgeIndex, num_vert_edges);
impl_attrib_index!(VertexFaceAttrib, VertexFaceIndex, num_vert_faces);
impl_attrib_index!(VertexCellAttrib, VertexCellIndex, num_vert_cell);
impl_attrib_index!(EdgeFaceAttrib, EdgeFaceIndex, num_edge_faces);
impl_attrib_index!(EdgeCellAttrib, EdgeCellIndex, num_edge_cells);
impl_attrib_index!(FaceCellAttrib, FaceCellIndex, num_face_cells);

///// Attribute Collector. This structure queries attributes from the mesh and collects references to
///// the data slices for further processing. This allows users to batch borrow mutable slices.
//pub struct AttribCollect {
//    refs: Vec<Attribute>
//
//}

/// Attribute interfaces for meshes. In order to derive this trait the mesh must have a field
/// called `attributes` with type `AttribDict`.
pub trait Attrib
where
    Self: ::std::marker::Sized,
{
    /// Get the size of the attribute at the appropriate mesh location determined by `I`.
    fn attrib_size<I: AttribIndex<Self>>(&self) -> usize;

    /// Read only access to the attribute dictionary.
    fn attrib_dict<I: AttribIndex<Self>>(&self) -> &AttribDict<I>;

    /// Read and write access to the attribute dictionary.
    fn attrib_dict_mut<I: AttribIndex<Self>>(&mut self) -> &mut AttribDict<I>;

    /// Add an attribute at the appropriate location with a given default.
    fn add_attrib<'a, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        def: T,
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone,
    {
        let n = self.attrib_size::<I>();
        match self.attrib_dict_mut().entry(name.to_owned()) {
            Entry::Occupied(_) => Err(Error::AlreadyExists(name.to_owned())),
            Entry::Vacant(entry) => Ok(entry.insert(Attribute::with_size(n, def))),
        }
    }

    /// Construct an attribute from a given data `Vec<T>`. `data` must have
    /// exactly the right size for the attribute to be added successfully.
    fn add_attrib_data<'a, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        data: Vec<T>,
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone + Default,
    {
        let expected_size = self.attrib_size::<I>();
        let given_size = data.len();
        if given_size != expected_size {
            Err(Error::WrongSize {
                expected_size,
                given_size,
            })
        } else {
            match self.attrib_dict_mut().entry(name.to_owned()) {
                Entry::Occupied(_) => Err(Error::AlreadyExists(name.to_owned())),
                Entry::Vacant(entry) => Ok(entry.insert(Attribute::from_vec(data))),
            }
        }
    }

    /// Sets the attribute to the specified default value whether or not it
    /// already exists.
    fn set_attrib<'a, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        def: T,
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone,
    {
        let n = self.attrib_size::<I>();
        Ok(match self.attrib_dict_mut().entry(name.to_owned()) {
            Entry::Occupied(mut entry) => {
                entry.insert(Attribute::with_size(n, def));
                entry.into_mut()
            }
            Entry::Vacant(entry) => entry.insert(Attribute::with_size(n, def)),
        })
    }

    /// Set an attribute to the given data slice. `data` must have exactly the
    /// right size for the attribute to be set successfully.
    fn set_attrib_data<'a, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        data: &[T],
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone + Default,
    {
        let expected_size = self.attrib_size::<I>();
        let given_size = data.len();
        if given_size != expected_size {
            Err(Error::WrongSize {
                expected_size,
                given_size,
            })
        } else {
            Ok(match self.attrib_dict_mut().entry(name.to_owned()) {
                Entry::Occupied(mut entry) => {
                    entry.insert(Attribute::from_slice(data));
                    entry.into_mut()
                }
                Entry::Vacant(entry) => entry.insert(Attribute::from_slice(data)),
            })
        }
    }

    /// Makes a copy of an existing attribute. Return a mutable reference to the
    /// new attribute if successful.
    fn duplicate_attrib<'a, 'b, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        new_name: &'b str,
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone,
    {
        let dup_attrib = self.attrib(name)?.clone();
        match self.attrib_check::<T, I>(new_name) {
            Ok(_) => Err(Error::AlreadyExists(new_name.to_owned())),
            Err(Error::DoesNotExist(_)) => Ok(self
                .attrib_dict_mut()
                .entry(new_name.to_owned())
                .or_insert(dup_attrib)),
            Err(err) => Err(err),
        }
    }

    /// Remove an attribute from the attribute dictionary. From there you can
    /// use methods defined on the returned attribute, and if desired return it back to the
    /// dictionary with `insert_attrib`.
    fn remove_attrib<'a, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
    ) -> Result<Attribute<I>, Error> {
        match self.attrib_dict_mut().remove(name) {
            Some(attrib) => Ok(attrib),
            None => Err(Error::DoesNotExist(name.to_owned())),
        }
    }

    /// Inserts an attribute into the dictionary with the usual `HashMap` semantics.
    /// This means that if an attribute with the same name exists, it will be returned and the
    /// current table entry is updated with the new value. If it doesn't already exist, `None` is
    /// returned.
    fn insert_attrib<'a, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        attrib: Attribute<I>,
    ) -> Result<Option<Attribute<I>>, Error> {
        let expected_size = self.attrib_size::<I>();
        let given_size = attrib.len();
        if given_size != expected_size {
            Err(Error::WrongSize {
                expected_size,
                given_size,
            })
        } else {
            Ok(self.attrib_dict_mut().insert(name.to_owned(), attrib))
        }
    }

    /// Retrieve the attribute with the given name and if it doesn't exist, add a new one and set
    /// it to a given default value. In either case the mutable reference to the attribute is
    /// returned.
    fn attrib_or_add<'a, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        def: T,
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone,
    {
        let n = self.attrib_size::<I>();
        match self.attrib_dict_mut().entry(name.to_owned()) {
            Entry::Occupied(entry) => entry.into_mut().check_mut::<T>(),
            Entry::Vacant(entry) => Ok(entry.insert(Attribute::with_size(n, def))),
        }
    }

    /// Retrieve the attribute with the given name and if it doesn't exist, set its data to
    /// what's in the given slice. In either case the mutable reference to the attribute is
    /// returned.
    fn attrib_or_add_data<'a, T, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
        data: &[T],
    ) -> Result<&mut Attribute<I>, Error>
    where
        T: Any + Clone + Default,
    {
        let expected_size = self.attrib_size::<I>();
        let given_size = data.len();
        if given_size != expected_size {
            Err(Error::WrongSize {
                expected_size,
                given_size,
            })
        } else {
            match self.attrib_dict_mut().entry(name.to_owned()) {
                Entry::Occupied(entry) => entry.into_mut().check_mut::<T>(),
                Entry::Vacant(entry) => Ok(entry.insert(Attribute::from_slice(data))),
            }
        }
    }

    /// Get the attribute iterator. This is essentially a safe version of
    /// `attrib(loc, name).unwrap().iter::<T>()`.
    fn attrib_iter<'a, 'b, T, I: 'b + AttribIndex<Self>>(
        &'b self,
        name: &'a str,
    ) -> Result<slice::Iter<T>, Error>
    where
        T: 'static + Clone,
    {
        self.attrib::<I>(name)?.iter::<T>()
    }

    /// Get the attribute mutable iterator. This is essentially a safe version of
    /// `attrib_mut(name).unwrap().iter_mut::<T>()`.
    fn attrib_iter_mut<'a, 'b, T, I: 'b + AttribIndex<Self>>(
        &'b mut self,
        name: &'a str,
    ) -> Result<slice::IterMut<T>, Error>
    where
        T: 'static + Clone,
    {
        self.attrib_mut::<I>(name)?.iter_mut::<T>()
    }

    /// Return `true` if the given attribute exists at the given location, and
    /// `false` otherwise, even if the specified attribute location is invalid
    /// for the mesh.
    fn attrib_exists<'a, I: AttribIndex<Self>>(&self, name: &'a str) -> bool {
        self.attrib_dict::<I>().contains_key(&name.to_owned())
    }

    /// Determine if the given attribute is valid and exists at the given
    /// location.
    fn attrib_check<'a, T: Any, I: AttribIndex<Self>>(&self, name: &'a str) -> Result<(), Error> {
        self.attrib::<I>(name)?.check::<T>()?;
        Ok(())
    }

    /// Expose the underlying attribute as a slice.
    fn attrib_as_slice<'a, 'b, T: 'static, I: 'b + AttribIndex<Self>>(
        &'b self,
        name: &'a str,
    ) -> Result<&'b [T], Error> {
        self.attrib::<I>(name)?.as_slice()
    }

    /// Expose the underlying attribute as a mutable slice.
    fn attrib_as_mut_slice<'a, 'b, T: 'static, I: 'b + AttribIndex<Self>>(
        &'b mut self,
        name: &'a str,
    ) -> Result<&'b mut [T], Error> {
        self.attrib_mut::<I>(name)?.as_mut_slice()
    }

    /// Clone attribute data into a `Vec<T>`.
    fn attrib_clone_into_vec<'a, 'b, T, I: 'b + AttribIndex<Self>>(
        &'b self,
        name: &'a str,
    ) -> Result<Vec<T>, Error>
    where
        T: 'static + Clone,
    {
        self.attrib::<I>(name)?.clone_into_vec()
    }

    /// Borrow the raw attribute from the attribute dictionary. From there you can
    /// use methods defined on the attribute itself.
    fn attrib<'a, I: AttribIndex<Self>>(&self, name: &'a str) -> Result<&Attribute<I>, Error> {
        match self.attrib_dict().get(name) {
            Some(attrib) => Ok(attrib),
            None => Err(Error::DoesNotExist(name.to_owned())),
        }
    }

    /// Get the raw mutable attribute from the attribute dictionary. From there
    /// you can use methods defined on the attribute itself.
    fn attrib_mut<'a, I: AttribIndex<Self>>(
        &mut self,
        name: &'a str,
    ) -> Result<&mut Attribute<I>, Error> {
        match self.attrib_dict_mut().get_mut(name) {
            Some(attrib) => Ok(attrib),
            None => Err(Error::DoesNotExist(name.to_owned())),
        }
    }
}

/// Error type specific to retrieving attributes from the attribute dictionary.
#[derive(Debug, PartialEq)]
pub enum Error {
    /// Attribute being added already exists.
    AlreadyExists(String),
    /// Attribute exists but the specified type is inaccurate.
    TypeMismatch,
    /// Couln't find the attribute with the given name and location.
    DoesNotExist(String),
    /// Given attribute size does not match expected attribute size.
    WrongSize {
        /// Attribute size of the underlying topology.
        expected_size: usize,
        /// Given data size, which must match the size of the underlying topology.
        given_size: usize,
    },
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Error::AlreadyExists(attrib_name) => {
                write!(f, "An attribute named \"{}\" already exists", attrib_name)
            }
            Error::TypeMismatch => write!(f, "Type mismatch"),
            Error::DoesNotExist(attrib_name) => {
                write!(f, "The attribute \"{}\" does not exist", attrib_name)
            }
            Error::WrongSize {
                expected_size,
                given_size,
            } => write!(
                f,
                "Given attribute size: {}, does not match expected size: {}",
                given_size, expected_size
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use num_traits::Zero;
    use crate::mesh::TriMesh;
    use crate::mesh::VertexPositions;

    /// Test that an attribute with a default value can be added, removed and reinserted.
    #[test]
    fn basic_test() {
        use math::Vector3;

        let pts = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let indices = vec![0, 1, 2, 1, 3, 2];

        let mut trimesh = TriMesh::new(pts, indices);

        {
            let nml_attrib = trimesh
                .add_attrib::<_, VertexIndex>("N", Vector3::<f64>::zero())
                .unwrap();
            assert_eq!(
                nml_attrib.get::<Vector3<f64>, _>(VertexIndex::from(1)),
                Ok(Vector3::zero())
            );
        }

        // check that the attribute indeed exists
        assert!(trimesh
            .attrib_check::<Vector3<f64>, VertexIndex>("N")
            .is_ok());

        // delete the attribute
        let mut nml_attrib = trimesh.remove_attrib::<VertexIndex>("N").unwrap();

        // check that the attribute was deleted
        assert!(!trimesh.attrib_exists::<VertexIndex>("N"));

        *nml_attrib.get_mut(2).unwrap() = Vector3::from([1.0, 2.0, 3.0]); // modify an element

        assert!(trimesh.insert_attrib("N", nml_attrib).unwrap().is_none());
        assert!(trimesh.attrib_exists::<VertexIndex>("N"));
        assert_eq!(
            trimesh
                .attrib::<VertexIndex>("N")
                .unwrap()
                .get::<Vector3<f64>, _>(2)
                .unwrap(),
            Vector3::from([1.0, 2.0, 3.0])
        );
    }

    /// Test setting of attributes
    #[test]
    fn set_attrib_test() {
        use math::Vector3;
        use num_traits::Zero;

        let pts = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let indices = vec![0, 1, 2, 1, 3, 2];

        let mut trimesh = TriMesh::new(pts, indices);

        // Attrib doesn't exist yet
        for nml in trimesh
            .set_attrib::<_, VertexIndex>("N", Vector3::<f64>::zero())
            .unwrap()
            .iter::<Vector3<f64>>()
            .unwrap()
        {
            assert_eq!(*nml, Vector3::zero());
        }
        // Attrib already exist, we expect it to be overwritten
        for nml in trimesh
            .set_attrib::<_, VertexIndex>("N", Vector3::from([1.0f64; 3]))
            .unwrap()
            .iter::<Vector3<f64>>()
            .unwrap()
        {
            assert_eq!(*nml, Vector3::from([1.0; 3]));
        }

        // Attrib already exist, we expect it to be overwritten
        let verts = trimesh.vertex_positions().to_vec();
        trimesh
            .set_attrib_data::<_, VertexIndex>("N", verts.as_slice())
            .unwrap();
        for (nml, p) in trimesh
            .attrib_iter::<[f64; 3], VertexIndex>("N")
            .unwrap()
            .zip(trimesh.vertex_positions())
        {
            assert_eq!(*nml, *p);
        }

        // Attrib doesn't exist yet
        let verts = trimesh.vertex_positions().to_vec();
        trimesh
            .set_attrib_data::<_, VertexIndex>("ref", verts.as_slice())
            .unwrap();
        for (r, p) in trimesh
            .attrib_iter::<[f64; 3], VertexIndex>("ref")
            .unwrap()
            .zip(trimesh.vertex_positions())
        {
            assert_eq!(*r, *p);
        }
    }

    /// Test attrib_or_add* methods.
    #[test]
    fn attrib_or_add_test() -> Result<(), Error> {
        let pts = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let indices = vec![0, 1, 2, 1, 3, 2];

        let mut trimesh = TriMesh::new(pts, indices);

        // Attrib doesn't exist yet
        for nml in trimesh
            .attrib_or_add::<_, VertexIndex>("N", [0.0f64; 3])?
            .iter::<[f64; 3]>()?
        {
            assert_eq!(*nml, [0.0; 3]);
        }

        // Attrib already exists, we expect it to be left intact
        for nml in trimesh
            .attrib_or_add::<_, VertexIndex>("N", [1.0f64; 3])?
            .iter::<[f64; 3]>()?
        {
            assert_eq!(*nml, [0.0; 3]);
        }

        // Attrib already exists, we expect it to be left intact
        let verts: Vec<_> = trimesh.vertex_positions().to_vec();
        for nml in trimesh
            .attrib_or_add_data::<_, VertexIndex>("N", verts.as_slice())?
            .iter::<[f64; 3]>()?
        {
            assert_eq!(*nml, [0.0; 3]);
        }

        // Attrib doesn't yet exist
        let verts = trimesh.vertex_positions().to_vec();
        trimesh.attrib_or_add_data::<_, VertexIndex>("ref", verts.as_slice())?;
        for (r, p) in trimesh
            .attrib_iter::<[f64; 3], VertexIndex>("ref")?
            .zip(trimesh.vertex_positions())
        {
            assert_eq!(*r, *p);
        }

        Ok(())
    }

    /// Test that multidimensional attributes can be added to the mesh from a `Vec`.
    /// Also test the `attrib_clone_into_vec` and `attrib_as_slice` functions for multidimensional
    /// attributes.
    #[test]
    fn multidim_test() {
        let pts = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let indices = vec![0, 1, 2, 1, 3, 2];

        let mut trimesh = TriMesh::new(pts, indices);

        let data = vec![[0i8, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]];
        {
            let attrib = trimesh
                .add_attrib_data::<_, VertexIndex>("attrib1", data.clone())
                .unwrap();
            for i in 0..data.len() {
                assert_eq!(attrib.get::<[i8; 3], _>(VertexIndex::from(i)), Ok(data[i]));
            }
        }
        assert_eq!(
            trimesh
                .attrib_clone_into_vec::<[i8; 3], VertexIndex>("attrib1")
                .unwrap(),
            data
        );
        assert_eq!(
            trimesh
                .attrib_as_slice::<[i8; 3], VertexIndex>("attrib1")
                .unwrap(),
            data.as_slice()
        );

        assert!(trimesh
            .attrib_check::<[i8; 3], VertexIndex>("attrib1")
            .is_ok());
        assert!(trimesh.remove_attrib::<VertexIndex>("attrib1").is_ok());
        assert!(!trimesh.attrib_exists::<VertexIndex>("attrib1"));
    }

    /// Test miscallenous attribute manipulation, like duplicating an attribute.
    #[test]
    fn misc_test() {
        let pts = vec![
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [1.0, 1.0, 0.0],
        ];
        let indices = vec![0, 1, 2, 1, 3, 2];

        let mut trimesh = TriMesh::new(pts, indices);

        let data = vec![[0i8, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]];
        {
            trimesh
                .add_attrib_data::<_, VertexIndex>("attrib1", data.clone())
                .unwrap();
        }

        {
            trimesh
                .duplicate_attrib::<[i8; 3], VertexIndex>("attrib1", "attrib2")
                .ok()
                .unwrap();
        }

        // Check that the duplicate attribute exists and has the right type.
        trimesh
            .attrib_check::<[i8; 3], VertexIndex>("attrib2")
            .ok()
            .unwrap();

        for (i, val) in trimesh
            .attrib_iter::<[i8; 3], VertexIndex>("attrib2")
            .unwrap()
            .enumerate()
        {
            assert_eq!(*val, data[i]);
        }

        assert!(trimesh.remove_attrib::<VertexIndex>("attrib1").is_ok());
        assert!(trimesh.remove_attrib::<VertexIndex>("attrib2").is_ok());
        assert!(!trimesh.attrib_exists::<VertexIndex>("attrib1"));
        assert!(!trimesh.attrib_exists::<VertexIndex>("attrib2"));
    }
}