pasture-core 0.5.0

A framework for working with point cloud data
Documentation
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
use anyhow::{anyhow, Result};
use std::{cell::RefCell, marker::PhantomData};

use crate::layout::{
    conversion::{convert_unit, get_converter_for_attributes, AttributeConversionFn},
    PointAttributeDefinition, PointAttributeMember, PointType, PrimitiveType,
};

use super::{
    attribute_iterators::{
        AttributeIteratorByMut, AttributeIteratorByRef, AttributeIteratorByValue,
    },
    point_buffer::{
        BorrowedBuffer, BorrowedMutBuffer, ColumnarBuffer, ColumnarBufferMut, InterleavedBuffer,
        InterleavedBufferMut,
    },
    point_iterators::{PointIteratorByMut, PointIteratorByRef, PointIteratorByValue},
    OwningBuffer,
};

/// A strongly typed view over the point data of a buffer. This allows accessing the point data in
/// the buffer using type `T` instead of only through raw memory (i.e. as `&[u8]`).
/// Depending on the memory layout of the buffer type `B`, this view supports accessing the point data
/// only by value (for non-interleaved buffers) or by immutable borrow (for interleaved buffers).
/// The `PointView` supports no type conversion, so `T::layout()` must match
/// the `PointLayout` of the buffer. You cannot create instances of `PointView` directly but instead
/// have to use [`BorrowedBuffer::view`] function and its variations, which perform the necessary type
/// checks internally!
///
/// # Lifetime bounds
///
/// Since the `PointView` borrows the buffer internally, and the buffer itself has a borrow lifetime,
/// `PointView` stores two lifetimes so that it can borrow its buffer for a potentially shorter lifetime
/// `'b` than the lifetime `'a` of the buffer itself.
#[derive(Debug, Copy, Clone)]
pub struct PointView<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PointType>
where
    'a: 'b,
{
    buffer: &'b B,
    _phantom: PhantomData<&'a T>,
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PointType> PointView<'a, 'b, B, T>
where
    'a: 'b,
{
    pub(crate) fn new(buffer: &'b B) -> Self {
        assert_eq!(
            T::layout(),
            *buffer.point_layout(),
            "Layout mismatch\nBuffer layout:\n{}\nRequested layout:\n{}",
            buffer.point_layout(),
            T::layout()
        );
        Self {
            buffer,
            _phantom: Default::default(),
        }
    }

    /// Access the point at `index`
    ///
    /// # Panics
    ///
    /// If `index` is out of bounds
    pub fn at(&self, index: usize) -> T {
        let mut point = T::zeroed();
        self.buffer
            .get_point(index, bytemuck::bytes_of_mut(&mut point));
        point
    }
}

impl<'a, 'b, B: InterleavedBuffer<'a> + ?Sized, T: PointType> PointView<'a, 'b, B, T>
where
    'a: 'b,
{
    /// Access the point at `index` by reference
    ///
    /// # Lifetime bounds
    ///
    /// Just as the `PointView` can borrow its underlying buffer for a shorter lifetime `'b` than
    /// the lifetime `'a` of the buffer, it should be possible to borrow a single point from a `PointView`
    /// for a shorter lifetime `'c` than the lifetime `'b` of the `PointView`, hence the additional
    /// lifetime bounds.
    ///
    /// # Panics
    ///
    /// If `index` is out of bounds
    pub fn at_ref<'c>(&'c self, index: usize) -> &'c T
    where
        'b: 'c,
    {
        bytemuck::from_bytes(self.buffer.get_point_ref(index))
    }

    /// Return an iterator over strongly typed point data by reference
    pub fn iter<'c>(&'c self) -> PointIteratorByRef<'c, T>
    where
        'b: 'c,
    {
        self.buffer.into()
    }
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized + 'a, T: PointType> IntoIterator
    for PointView<'a, 'b, B, T>
where
    'a: 'b,
{
    type Item = T;
    type IntoIter = PointIteratorByValue<'a, 'b, T, B>;

    fn into_iter(self) -> Self::IntoIter {
        self.buffer.into()
    }
}

impl<
        'a,
        'b,
        'c,
        'd,
        B1: BorrowedBuffer<'a> + ?Sized + 'a,
        B2: BorrowedBuffer<'c> + ?Sized + 'c,
        T: PointType + PartialEq,
    > PartialEq<PointView<'c, 'd, B2, T>> for PointView<'a, 'b, B1, T>
{
    fn eq(&self, other: &PointView<'c, 'd, B2, T>) -> bool {
        if self.buffer.len() != other.buffer.len() {
            false
        } else {
            (0..self.buffer.len()).all(|idx| self.at(idx) == other.at(idx))
        }
    }
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized + 'a, T: PointType + Eq> Eq
    for PointView<'a, 'b, B, T>
{
}

/// Like [`PointView`], but provides mutable access to the strongly typed point data. For buffers with unknown
/// memory layout, this means that you have to use [`PointViewMut::set_at`], but if the underlying buffer
/// implements [`InterleavedBufferMut`], you can also access strongly-typed points by mutable borrow!
#[derive(Debug)]
pub struct PointViewMut<'a, 'b, B: BorrowedMutBuffer<'a> + ?Sized, T: PointType>
where
    'a: 'b,
{
    buffer: &'b mut B,
    _phantom: PhantomData<&'a T>,
}

impl<'a, 'b, B: BorrowedMutBuffer<'a> + ?Sized, T: PointType> PointViewMut<'a, 'b, B, T> {
    pub(crate) fn new(buffer: &'b mut B) -> Self {
        assert_eq!(
            T::layout(),
            *buffer.point_layout(),
            "Layout mismatch\nBuffer layout:\n{}\nRequested layout:\n{}",
            buffer.point_layout(),
            T::layout()
        );
        Self {
            buffer,
            _phantom: Default::default(),
        }
    }

    /// Access the point at `index`
    ///
    /// # Panics
    ///
    /// If `index` is out of bounds
    pub fn at(&self, index: usize) -> T {
        let mut point = T::zeroed();
        self.buffer
            .get_point(index, bytemuck::bytes_of_mut(&mut point));
        point
    }

    /// Sets the data for the point at `index`
    ///
    /// # Panics
    ///
    /// If `index` is out of bounds
    pub fn set_at(&mut self, index: usize, point: T) {
        // Safe because `new` asserts that the point layout of `T` and `buffer` match
        unsafe {
            self.buffer.set_point(index, bytemuck::bytes_of(&point));
        }
    }
}

impl<'a, 'b, B: InterleavedBuffer<'a> + BorrowedMutBuffer<'a> + ?Sized, T: PointType>
    PointViewMut<'a, 'b, B, T>
{
    /// Access the point at `index` as an immutable reference
    ///
    /// # Panics
    ///
    /// If `index` is out of bounds
    pub fn at_ref<'c>(&'c self, index: usize) -> &'c T
    where
        'b: 'c,
    {
        bytemuck::from_bytes(self.buffer.get_point_ref(index))
    }

    /// Return an iterator over point data by immutable reference
    pub fn iter<'c>(&'c self) -> PointIteratorByRef<'c, T>
    where
        'b: 'c,
    {
        (&*self.buffer).into()
    }
}

impl<'a, 'b, B: InterleavedBufferMut<'a> + ?Sized, T: PointType> PointViewMut<'a, 'b, B, T> {
    /// Access the point at `index` as a mutable reference
    ///
    /// # Panics
    ///
    /// If `index` is out of bounds
    pub fn at_mut<'c>(&'c mut self, index: usize) -> &'c mut T
    where
        'b: 'c,
    {
        bytemuck::from_bytes_mut(self.buffer.get_point_mut(index))
    }

    /// Returns an iterator over point data by mutable reference
    pub fn iter_mut<'c>(&'c mut self) -> PointIteratorByMut<'c, T>
    where
        'b: 'c,
    {
        self.buffer.into()
    }

    /// Sorts the point buffer using the given `comparator` function
    pub fn sort_by<F: Fn(&T, &T) -> std::cmp::Ordering>(&mut self, comparator: F) {
        let typed_points: &mut [T] =
            bytemuck::cast_slice_mut(self.buffer.get_point_range_mut(0..self.buffer.len()));
        typed_points.sort_by(comparator);
    }
}

impl<'a, 'b, B: OwningBuffer<'a> + ?Sized, T: PointType> PointViewMut<'a, 'b, B, T> {
    /// Push the given `point` into the underlying buffer
    pub fn push_point(&mut self, point: T) {
        // Safe because we know that a `PointViewMut` can never be created for a `T` that is different from
        // the `PointLayout` of the underlying buffer (see the check in `new`)
        unsafe {
            self.buffer.push_points(bytemuck::bytes_of(&point));
        }
    }
}

impl<
        'a,
        'b,
        'c,
        'd,
        B1: BorrowedMutBuffer<'a> + ?Sized + 'a,
        B2: BorrowedMutBuffer<'c> + ?Sized + 'c,
        T: PointType + PartialEq,
    > PartialEq<PointViewMut<'c, 'd, B2, T>> for PointViewMut<'a, 'b, B1, T>
{
    fn eq(&self, other: &PointViewMut<'c, 'd, B2, T>) -> bool {
        if self.buffer.len() != other.buffer.len() {
            false
        } else {
            (0..self.buffer.len()).all(|idx| self.at(idx) == other.at(idx))
        }
    }
}

impl<'a, 'b, B: BorrowedMutBuffer<'a> + ?Sized + 'a, T: PointType + Eq> Eq
    for PointViewMut<'a, 'b, B, T>
{
}

/// A strongly typed view over attribute data of a point buffer. This allows accessing the data for a specific
/// attribute of a `PointType` using the strong type `T` instead of as raw memory (i.e. `&[u8]`). This type makes
/// no assumptions about the memory layout of the underlying buffer, so it only provides access to the attribute
/// data by value. Just as with the [`PointView`] type, you cannot create instances of `AttributeView` directly.
/// Instead, use the [`BorrowedBuffer::view_attribute`] function and its variations, which perform the necessary
/// type checking.
#[derive(Debug, Copy, Clone)]
pub struct AttributeView<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType>
where
    'a: 'b,
{
    buffer: &'b B,
    attribute: &'b PointAttributeMember,
    _phantom: PhantomData<&'a T>,
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType> AttributeView<'a, 'b, B, T> {
    pub(crate) fn new(buffer: &'b B, attribute: &PointAttributeDefinition) -> Self {
        assert_eq!(T::data_type(), attribute.datatype());
        Self {
            attribute: buffer
                .point_layout()
                .get_attribute(attribute)
                .expect("Attribute not found in PointLayout of buffer"),
            buffer,
            _phantom: Default::default(),
        }
    }

    /// Get the attribute value at `index`
    ///
    /// # Panics
    ///
    ///  If `index` is out of bounds
    pub fn at(&self, index: usize) -> T {
        let mut attribute = T::zeroed();
        // Is safe because we get the attribute_member from the PointLayout of the buffer in `new`
        unsafe {
            self.buffer.get_attribute_unchecked(
                self.attribute,
                index,
                bytemuck::bytes_of_mut(&mut attribute),
            );
        }
        attribute
    }
}

impl<'a, 'b, B: ColumnarBuffer<'a> + ?Sized, T: PrimitiveType> AttributeView<'a, 'b, B, T>
where
    'a: 'b,
{
    /// Get the attribute value at `index` as an immutable borrow
    ///
    /// # Panics
    ///
    ///  If `index` is out of bounds
    pub fn at_ref<'c>(&'c self, index: usize) -> &'c T
    where
        'b: 'c,
    {
        bytemuck::from_bytes(
            self.buffer
                .get_attribute_ref(self.attribute.attribute_definition(), index),
        )
    }

    /// Returns an iterator over attribute values by immutable reference
    pub fn iter<'c>(&'c self) -> AttributeIteratorByRef<'c, T>
    where
        'b: 'c,
    {
        AttributeIteratorByRef::new(self.buffer, self.attribute.attribute_definition())
    }
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized + 'a, T: PrimitiveType> IntoIterator
    for AttributeView<'a, 'b, B, T>
{
    type Item = T;
    type IntoIter = AttributeIteratorByValue<'a, 'b, T, B>;

    fn into_iter(self) -> Self::IntoIter {
        AttributeIteratorByValue::new(self.buffer, self.attribute.attribute_definition())
    }
}

impl<
        'a,
        'b,
        'c,
        'd,
        B1: BorrowedBuffer<'a> + ?Sized + 'a,
        B2: BorrowedBuffer<'c> + ?Sized + 'c,
        T: PrimitiveType + PartialEq,
    > PartialEq<AttributeView<'c, 'd, B2, T>> for AttributeView<'a, 'b, B1, T>
{
    fn eq(&self, other: &AttributeView<'c, 'd, B2, T>) -> bool {
        self.buffer.len() == other.buffer.len()
            && self.attribute.attribute_definition() == other.attribute.attribute_definition()
            && (0..self.buffer.len()).all(|idx| self.at(idx) == other.at(idx))
    }
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized + 'a, T: PrimitiveType + Eq> Eq
    for AttributeView<'a, 'b, B, T>
{
}

/// Like [`AttributeView`], but provides mutable access to the attribute data
#[derive(Debug)]
pub struct AttributeViewMut<'a, 'b, B: BorrowedMutBuffer<'a> + ?Sized, T: PrimitiveType>
where
    'a: 'b,
{
    buffer: &'b mut B,
    attribute: PointAttributeMember,
    _phantom: PhantomData<&'a T>,
}

impl<'a, 'b, B: BorrowedMutBuffer<'a> + ?Sized, T: PrimitiveType> AttributeViewMut<'a, 'b, B, T>
where
    'a: 'b,
{
    pub(crate) fn new(buffer: &'b mut B, attribute: &PointAttributeDefinition) -> Self {
        assert_eq!(T::data_type(), attribute.datatype());
        Self {
            attribute: buffer
                .point_layout()
                .get_attribute(attribute)
                .expect("Attribute not found in PointLayout of buffer")
                .clone(),
            buffer,
            _phantom: Default::default(),
        }
    }

    /// Get the attribute value at `index`
    ///
    /// # Panics
    ///
    ///  If `index` is out of bounds
    pub fn at(&self, index: usize) -> T {
        let mut attribute = T::zeroed();
        // Is safe because we get the attribute_member from the PointLayout of the buffer in `new`
        unsafe {
            self.buffer.get_attribute_unchecked(
                &self.attribute,
                index,
                bytemuck::bytes_of_mut(&mut attribute),
            );
        }
        attribute
    }

    /// Sets the value of the attribute at `index` to `attribute_value`
    ///
    /// # Panics
    ///
    ///  If `index` is out of bounds
    pub fn set_at(&mut self, index: usize, attribute_value: T) {
        // Safe because `new` checks that the data type of `T` and `self.attribute` match
        unsafe {
            self.buffer.set_attribute(
                self.attribute.attribute_definition(),
                index,
                bytemuck::bytes_of(&attribute_value),
            );
        }
    }
}

impl<'a, 'b, B: ColumnarBuffer<'a> + BorrowedMutBuffer<'a> + ?Sized, T: PrimitiveType>
    AttributeViewMut<'a, 'b, B, T>
where
    'a: 'b,
{
    /// Get the attribute value at `index` as an immutable borrow
    ///
    /// # Panics
    ///
    ///  If `index` is out of bounds
    pub fn at_ref<'c>(&'c self, index: usize) -> &'c T
    where
        'b: 'c,
    {
        bytemuck::from_bytes(
            self.buffer
                .get_attribute_ref(self.attribute.attribute_definition(), index),
        )
    }

    /// Returns an iterator over attribute values as immutable borrows
    pub fn iter<'c>(&'c self) -> AttributeIteratorByRef<'c, T>
    where
        'b: 'c,
    {
        AttributeIteratorByRef::new(self.buffer, self.attribute.attribute_definition())
    }
}

impl<'a, 'b, B: ColumnarBufferMut<'a> + BorrowedMutBuffer<'a> + ?Sized, T: PrimitiveType>
    AttributeViewMut<'a, 'b, B, T>
{
    /// Get the attribute value at `index` as a mutable borrow
    ///
    /// # Panics
    ///
    ///  If `index` is out of bounds
    pub fn at_mut(&'b mut self, index: usize) -> &'b mut T {
        bytemuck::from_bytes_mut(
            self.buffer
                .get_attribute_mut(self.attribute.attribute_definition(), index),
        )
    }

    /// Returns an iterator over attribute values as mutable borrows
    pub fn iter_mut(&'b mut self) -> AttributeIteratorByMut<'b, T> {
        AttributeIteratorByMut::new(self.buffer, self.attribute.attribute_definition())
    }
}

impl<
        'a,
        'b,
        'c,
        'd,
        B1: BorrowedMutBuffer<'a> + ?Sized + 'a,
        B2: BorrowedMutBuffer<'c> + ?Sized + 'c,
        T: PrimitiveType + PartialEq,
    > PartialEq<AttributeViewMut<'c, 'd, B2, T>> for AttributeViewMut<'a, 'b, B1, T>
{
    fn eq(&self, other: &AttributeViewMut<'c, 'd, B2, T>) -> bool {
        self.buffer.len() == other.buffer.len()
            && self.attribute.attribute_definition() == other.attribute.attribute_definition()
            && (0..self.buffer.len()).all(|idx| self.at(idx) == other.at(idx))
    }
}

impl<'a, 'b, B: BorrowedMutBuffer<'a> + ?Sized + 'a, T: PrimitiveType + Eq> Eq
    for AttributeViewMut<'a, 'b, B, T>
{
}

/// A view over a strongly typed point attribute that supports type conversion. This means that the
/// `PointAttributeDataType` of the attribute does not have to match the type `T` that this view returns.
/// For an explanation on how attribute type conversion works in pasture, see the [`conversion`](crate::layout::conversion)
/// module
#[derive(Debug)]
pub struct AttributeViewConverting<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType>
where
    'a: 'b,
{
    buffer: &'b B,
    attribute: PointAttributeMember,
    converter_fn: AttributeConversionFn,
    converter_buffer: RefCell<Vec<u8>>,
    _phantom: PhantomData<&'a T>,
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType>
    AttributeViewConverting<'a, 'b, B, T>
{
    pub(crate) fn new(buffer: &'b B, attribute: &PointAttributeDefinition) -> Result<Self> {
        assert_eq!(T::data_type(), attribute.datatype());
        let attribute_in_layout: &PointAttributeMember = buffer
            .point_layout()
            .get_attribute_by_name(attribute.name())
            .expect("Attribute not found in PointLayout of buffer");
        let converter_fn = if attribute_in_layout.datatype() == T::data_type() {
            convert_unit
        } else {
            get_converter_for_attributes(
                attribute_in_layout.attribute_definition(),
                &attribute.with_custom_datatype(T::data_type()),
            )
            .ok_or(anyhow!("Conversion between attribute types is impossible"))?
        };
        let converter_buffer = vec![0; attribute_in_layout.size() as usize];
        Ok(Self {
            attribute: attribute_in_layout.clone(),
            buffer,
            converter_fn,
            converter_buffer: RefCell::new(converter_buffer),
            _phantom: Default::default(),
        })
    }

    /// Get the attribute value at `index`
    pub fn at(&self, index: usize) -> T {
        let mut value = T::zeroed();
        // Is safe because we took 'attribute' from the point layout of the buffer
        // conversion is safe because we checked the source and destination types in `new`
        unsafe {
            self.buffer.get_attribute_unchecked(
                &self.attribute,
                index,
                self.converter_buffer.borrow_mut().as_mut_slice(),
            );
            (self.converter_fn)(
                self.converter_buffer.borrow().as_slice(),
                bytemuck::bytes_of_mut(&mut value),
            );
        }
        value
    }
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType> IntoIterator
    for AttributeViewConverting<'a, 'b, B, T>
{
    type Item = T;
    type IntoIter = AttributeViewConvertingIterator<'a, 'b, B, T>;

    fn into_iter(self) -> Self::IntoIter {
        AttributeViewConvertingIterator {
            current_index: 0,
            view: self,
        }
    }
}

impl<
        'a,
        'b,
        'c,
        'd,
        B1: BorrowedBuffer<'a> + ?Sized + 'a,
        B2: BorrowedBuffer<'c> + ?Sized + 'c,
        T: PrimitiveType + PartialEq,
    > PartialEq<AttributeViewConverting<'c, 'd, B2, T>> for AttributeViewConverting<'a, 'b, B1, T>
{
    fn eq(&self, other: &AttributeViewConverting<'c, 'd, B2, T>) -> bool {
        self.buffer.len() == other.buffer.len()
            && self.attribute.attribute_definition() == other.attribute.attribute_definition()
            && (0..self.buffer.len()).all(|idx| self.at(idx) == other.at(idx))
    }
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized + 'a, T: PrimitiveType + Eq> Eq
    for AttributeViewConverting<'a, 'b, B, T>
{
}

/// An iterator that performs attribute value conversion on the fly. This allows iterating over an
/// attribute that has internal datatype `U` as if it had datatype `T`
pub struct AttributeViewConvertingIterator<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType>
{
    view: AttributeViewConverting<'a, 'b, B, T>,
    current_index: usize,
}

impl<'a, 'b, B: BorrowedBuffer<'a> + ?Sized, T: PrimitiveType> Iterator
    for AttributeViewConvertingIterator<'a, 'b, B, T>
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_index == self.view.buffer.len() {
            None
        } else {
            let ret = self.view.at(self.current_index);
            self.current_index += 1;
            Some(ret)
        }
    }
}

#[cfg(test)]
mod tests {
    use nalgebra::Vector3;
    use rand::{thread_rng, Rng};

    use crate::{
        containers::{BorrowedBufferExt, BorrowedMutBufferExt, HashMapBuffer, VectorBuffer},
        layout::{attributes::POSITION_3D, PointAttributeDataType},
        test_utils::*,
    };

    #[test]
    fn test_sort_buffer() {
        let rng = thread_rng();
        let mut test_points = rng
            .sample_iter::<CustomPointTypeSmall, _>(DefaultPointDistribution)
            .take(10)
            .collect::<VectorBuffer>();

        test_points
            .view_mut::<CustomPointTypeSmall>()
            .sort_by(|a, b| a.classification.cmp(&b.classification));

        let points = test_points
            .view::<CustomPointTypeSmall>()
            .into_iter()
            .collect::<Vec<_>>();
        let are_sorted = points
            .iter()
            .zip(points.iter().skip(1))
            .all(|(low, high)| low.classification <= high.classification);
        assert!(are_sorted, "Points not sorted: {:#?}", test_points);
    }

    #[test]
    fn test_point_views_eq() {
        let rng = thread_rng();
        let test_points = rng
            .sample_iter::<CustomPointTypeSmall, _>(DefaultPointDistribution)
            .take(10)
            .collect::<Vec<_>>();

        let mut buffer1 = test_points.iter().copied().collect::<VectorBuffer>();
        let mut buffer2 = test_points.iter().copied().collect::<HashMapBuffer>();

        assert_eq!(
            buffer1.view::<CustomPointTypeSmall>(),
            buffer2.view::<CustomPointTypeSmall>()
        );
        assert_eq!(
            buffer1.view_mut::<CustomPointTypeSmall>(),
            buffer2.view_mut::<CustomPointTypeSmall>()
        );

        buffer2 = thread_rng()
            .sample_iter::<CustomPointTypeSmall, _>(DefaultPointDistribution)
            .take(10)
            .collect();
        assert_ne!(
            buffer1.view::<CustomPointTypeSmall>(),
            buffer2.view::<CustomPointTypeSmall>()
        );
        assert_ne!(
            buffer1.view_mut::<CustomPointTypeSmall>(),
            buffer2.view_mut::<CustomPointTypeSmall>()
        );
    }

    #[test]
    fn test_attribute_views_eq() {
        let rng = thread_rng();
        let test_points = rng
            .sample_iter::<CustomPointTypeSmall, _>(DefaultPointDistribution)
            .take(10)
            .collect::<Vec<_>>();

        let mut buffer1 = test_points.iter().copied().collect::<VectorBuffer>();
        let mut buffer2 = test_points.iter().copied().collect::<HashMapBuffer>();

        assert_eq!(
            buffer1.view_attribute::<Vector3<f64>>(&POSITION_3D),
            buffer2.view_attribute::<Vector3<f64>>(&POSITION_3D),
        );
        assert_eq!(
            buffer1.view_attribute_mut::<Vector3<f64>>(&POSITION_3D),
            buffer2.view_attribute_mut::<Vector3<f64>>(&POSITION_3D),
        );
        let f32_position = POSITION_3D.with_custom_datatype(PointAttributeDataType::Vec3f32);
        assert_eq!(
            buffer1
                .view_attribute_with_conversion::<Vector3<f32>>(&f32_position)
                .expect("Invalid attribute conversion"),
            buffer2
                .view_attribute_with_conversion::<Vector3<f32>>(&f32_position)
                .expect("Invalid attribute conversion"),
        );

        buffer2 = thread_rng()
            .sample_iter::<CustomPointTypeSmall, _>(DefaultPointDistribution)
            .take(10)
            .collect();

        assert_ne!(
            buffer1.view_attribute::<Vector3<f64>>(&POSITION_3D),
            buffer2.view_attribute::<Vector3<f64>>(&POSITION_3D),
        );
        assert_ne!(
            buffer1.view_attribute_mut::<Vector3<f64>>(&POSITION_3D),
            buffer2.view_attribute_mut::<Vector3<f64>>(&POSITION_3D),
        );
        assert_ne!(
            buffer1
                .view_attribute_with_conversion::<Vector3<f32>>(&f32_position)
                .expect("Invalid attribute conversion"),
            buffer2
                .view_attribute_with_conversion::<Vector3<f32>>(&f32_position)
                .expect("Invalid attribute conversion"),
        );
    }
}