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
use core::cmp;
use core::fmt;
use core::hash;
use core::ops;
use core::ptr;

use audio_core::{Buf, BufMut, ExactSizeBuf, ResizableBuf, Sample, UniformBuf};

use crate::buf::sequential::{IterChannels, IterChannelsMut};
use crate::channel::{LinearChannel, LinearChannelMut};
use crate::frame::{RawSequential, SequentialFrame, SequentialFramesIter};

/// A dynamically sized, multi-channel sequential audio buffer.
///
/// A *sequential* audio buffer stores all audio data sequentially in memory,
/// one channel after another.
///
/// An audio buffer can only be resized if it contains a type which is
/// sample-apt. For more information of what this means, see [Sample].
///
/// Resizing the buffer might therefore cause a fair bit of copying, and for the
/// worst cases, this might result in having to copy a memory region
/// byte-by-byte since they might overlap.
///
/// Resized regions also aren't zeroed, so certain operations might cause stale
/// data to be visible after a resize.
///
/// ```
/// let mut buf = audio::buf::Sequential::<f32>::with_topology(2, 4);
/// buf[0].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
/// buf[1].copy_from_slice(&[2.0, 3.0, 4.0, 5.0]);
///
/// buf.resize_frames(3);
///
/// assert_eq!(&buf[0], &[1.0, 2.0, 3.0]);
/// assert_eq!(&buf[1], &[2.0, 3.0, 4.0]);
///
/// buf.resize_frames(4);
///
/// assert_eq!(&buf[0], &[1.0, 2.0, 3.0, 2.0]); // <- 2.0 is stale data.
/// assert_eq!(&buf[1], &[2.0, 3.0, 4.0, 5.0]); // <- 5.0 is stale data.
/// ```
///
/// To access the full, currently assumed *valid* slice you can use
/// [Sequential::as_slice] or [Sequential::into_vec].
///
/// ```
/// let mut buf = audio::buf::Sequential::<f32>::with_topology(2, 4);
/// buf[0].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
/// buf[1].copy_from_slice(&[2.0, 3.0, 4.0, 5.0]);
///
/// buf.resize_frames(3);
///
/// assert_eq!(buf.as_slice(), &[1.0, 2.0, 3.0, 2.0, 3.0, 4.0]);
/// ```
#[derive(Default)]
pub struct Sequential<T> {
    data: Vec<T>,
    channels: usize,
    frames: usize,
}

impl<T> Sequential<T> {
    /// Construct a new empty audio buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// let buf = audio::buf::Sequential::<f32>::new();
    ///
    /// assert_eq!(buf.frames(), 0);
    /// ```
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            channels: 0,
            frames: 0,
        }
    }

    /// Allocate an audio buffer with the given topology. A "topology" is a
    /// given number of `channels` and the corresponding number of `frames` in
    /// their buffers.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::with_topology(4, 256);
    ///
    /// assert_eq!(buf.frames(), 256);
    /// assert_eq!(buf.channels(), 4);
    /// ```
    pub fn with_topology(channels: usize, frames: usize) -> Self
    where
        T: Sample,
    {
        Self {
            data: vec![T::ZERO; channels * frames],
            channels,
            frames,
        }
    }

    /// Allocate an audio buffer from a fixed-size array.
    ///
    /// See [sequential!].
    ///
    /// # Examples
    ///
    /// ```
    /// let buf = audio::sequential![[2.0; 256]; 4];
    ///
    /// assert_eq!(buf.frames(), 256);
    /// assert_eq!(buf.channels(), 4);
    ///
    /// for chan in &buf {
    ///     assert_eq!(chan.as_ref(), vec![2.0; 256]);
    /// }
    /// ```
    pub fn from_vec(data: Vec<T>, channels: usize, frames: usize) -> Self {
        Self {
            data,
            channels,
            frames,
        }
    }

    /// Allocate an audio buffer from a fixed-size array acting as a template
    /// for all the channels.
    ///
    /// See [sequential!].
    ///
    /// # Examples
    ///
    /// ```
    /// let buf = audio::buf::Sequential::from_frames([1.0, 2.0, 3.0, 4.0], 2);
    ///
    /// assert_eq!(buf.frames(), 4);
    /// assert_eq!(buf.channels(), 2);
    ///
    /// assert_eq!(buf.as_slice(), &[1.0, 2.0, 3.0, 4.0, 1.0, 2.0, 3.0, 4.0]);
    /// ```
    pub fn from_frames<const N: usize>(frames: [T; N], channels: usize) -> Self
    where
        T: Copy,
    {
        return Self {
            data: data_from_frames(frames, channels),
            channels,
            frames: N,
        };

        fn data_from_frames<T, const N: usize>(frames: [T; N], channels: usize) -> Vec<T>
        where
            T: Copy,
        {
            let mut data = Vec::with_capacity(N * channels);

            for _ in 0..channels {
                data.extend(frames);
            }

            data
        }
    }

    /// Allocate a sequential audio buffer from a fixed-size array.
    ///
    /// See [sequential!].
    ///
    /// # Examples
    ///
    /// ```
    /// let buf = audio::buf::Sequential::from_array([[1; 4]; 2]);
    ///
    /// assert_eq!(buf.frames(), 4);
    /// assert_eq!(buf.channels(), 2);
    ///
    /// assert_eq! {
    ///     buf.as_slice(),
    ///     &[1, 1, 1, 1, 1, 1, 1, 1],
    /// }
    /// ```
    ///
    /// Using a specific array topology.
    ///
    /// ```
    /// let buf = audio::buf::Sequential::from_array([[1, 2, 3, 4], [5, 6, 7, 8]]);
    ///
    /// assert_eq!(buf.frames(), 4);
    /// assert_eq!(buf.channels(), 2);
    ///
    /// assert_eq! {
    ///     buf.as_slice(),
    ///     &[1, 2, 3, 4, 5, 6, 7, 8],
    /// }
    /// ```
    pub fn from_array<const F: usize, const C: usize>(channels: [[T; F]; C]) -> Self
    where
        T: Copy,
    {
        return Self {
            data: data_from_array(channels),
            channels: C,
            frames: F,
        };

        #[inline]
        fn data_from_array<T, const F: usize, const C: usize>(channels: [[T; F]; C]) -> Vec<T> {
            let mut data = Vec::with_capacity(C * F);

            for frames in channels {
                for f in frames {
                    data.push(f);
                }
            }

            data
        }
    }

    /// Take ownership of the backing vector.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::with_topology(2, 4);
    /// buf[0].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
    /// buf[1].copy_from_slice(&[2.0, 3.0, 4.0, 5.0]);
    ///
    /// buf.resize_frames(3);
    ///
    /// assert_eq!(buf.into_vec(), vec![1.0, 2.0, 3.0, 2.0, 3.0, 4.0])
    /// ```
    pub fn into_vec(self) -> Vec<T> {
        self.data
    }

    /// Access the underlying vector as a slice.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::with_topology(2, 4);
    ///
    /// buf[0].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
    /// buf[1].copy_from_slice(&[2.0, 3.0, 4.0, 5.0]);
    ///
    /// buf.resize_frames(3);
    ///
    /// assert_eq!(buf.as_slice(), &[1.0, 2.0, 3.0, 2.0, 3.0, 4.0])
    /// ```
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Access the underlying vector as a mutable slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use audio::{Buf, Channel};
    ///
    /// let mut buf = audio::buf::Sequential::<u32>::with_topology(2, 4);
    /// buf.as_slice_mut().copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
    ///
    /// assert_eq! {
    ///     buf.get_channel(0).unwrap(),
    ///     [1u32, 2, 3, 4],
    /// };
    ///
    /// assert_eq! {
    ///     buf.get_channel(1).unwrap(),
    ///     [5u32, 6, 7, 8],
    /// };
    ///
    /// assert_eq!(buf.as_slice(), &[1, 2, 3, 4, 5, 6, 7, 8]);
    /// ```
    pub fn as_slice_mut(&mut self) -> &mut [T] {
        &mut self.data
    }

    /// Get the capacity of the buffer in number of frames.
    ///
    /// The underlying buffer over-allocates a bit, so this will report the
    /// exact capacity available in the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// assert_eq!(buf.capacity(), 0);
    ///
    /// buf.resize_frames(11);
    /// assert_eq!(buf.capacity(), 0);
    ///
    /// buf.resize_channels(2);
    /// assert_eq!(buf.capacity(), 22);
    ///
    /// buf.resize_frames(12);
    /// assert_eq!(buf.capacity(), 44);
    ///
    /// buf.resize_frames(24);
    /// assert_eq!(buf.capacity(), 44);
    /// ```
    pub fn capacity(&self) -> usize {
        self.data.capacity()
    }

    /// Get how many frames there are in the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// assert_eq!(buf.frames(), 0);
    /// buf.resize_frames(256);
    /// assert_eq!(buf.frames(), 256);
    /// ```
    pub fn frames(&self) -> usize {
        self.frames
    }

    /// Get how many channels there are in the buffer.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// assert_eq!(buf.channels(), 0);
    /// buf.resize_channels(2);
    /// assert_eq!(buf.channels(), 2);
    /// ```
    pub fn channels(&self) -> usize {
        self.channels
    }

    /// Construct an iterator over all available channels.
    ///
    /// # Examples
    ///
    /// ```
    /// use rand::Rng as _;
    ///
    /// let buf = audio::buf::Sequential::<f32>::with_topology(4, 256);
    ///
    /// let all_zeros = vec![0.0; 256];
    ///
    /// for chan in buf.iter_channels() {
    ///     assert_eq!(chan.as_ref(), &all_zeros[..]);
    /// }
    /// ```
    pub fn iter_channels(&self) -> IterChannels<'_, T> {
        IterChannels::new(&self.data, self.frames)
    }

    /// Construct a mutable iterator over all available channels.
    ///
    /// # Examples
    ///
    /// ```
    /// use rand::Rng as _;
    ///
    /// let mut buf = audio::buf::Sequential::<f32>::with_topology(4, 256);
    /// let mut rng = rand::thread_rng();
    ///
    /// for mut chan in buf.iter_channels_mut() {
    ///     rng.fill(chan.as_mut());
    /// }
    /// ```
    pub fn iter_channels_mut(&mut self) -> IterChannelsMut<'_, T> {
        IterChannelsMut::new(&mut self.data, self.frames)
    }

    /// Set the number of channels in use.
    ///
    /// If the size of the buffer increases as a result, the new channels will
    /// be zeroed. If the size decreases, the channels that falls outside of the
    /// new size will be dropped.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// assert_eq!(buf.channels(), 0);
    /// assert_eq!(buf.frames(), 0);
    ///
    /// buf.resize_channels(4);
    /// buf.resize_frames(256);
    ///
    /// assert_eq!(buf.channels(), 4);
    /// assert_eq!(buf.frames(), 256);
    /// ```
    pub fn resize_channels(&mut self, channels: usize)
    where
        T: Sample,
    {
        self.resize_inner(self.channels, self.frames, channels, self.frames);
    }

    /// Set the size of the buffer. The size is the size of each channel's
    /// buffer.
    ///
    /// If the size of the buffer increases as a result, the new regions in the
    /// frames will be zeroed. If the size decreases, the region will be left
    /// untouched. So if followed by another increase, the data will be "dirty".
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// assert_eq!(buf.channels(), 0);
    /// assert_eq!(buf.frames(), 0);
    ///
    /// buf.resize_channels(4);
    /// buf.resize_frames(256);
    ///
    /// assert_eq!(buf[1][128], 0.0);
    /// buf[1][128] = 42.0;
    ///
    /// assert_eq!(buf.channels(), 4);
    /// assert_eq!(buf.frames(), 256);
    /// ```
    ///
    /// Decreasing and increasing the size will modify the underlying buffer:
    ///
    /// ```
    /// # let mut buf = audio::buf::Sequential::<f32>::with_topology(4, 256);
    /// assert_eq!(buf[1][128], 0.0);
    /// buf[1][128] = 42.0;
    ///
    /// buf.resize_frames(64);
    /// assert!(buf[1].get(128).is_none());
    ///
    /// buf.resize_frames(256);
    /// assert_eq!(buf[1][128], 0.0);
    /// ```
    ///
    /// # Stale data
    ///
    /// Resizing a channel doesn't "free" the underlying data or zero previously
    /// initialized regions.
    ///
    /// Old regions which were previously sized out and ignored might contain
    /// stale data from previous uses. So this should be kept in mind when
    /// resizing this buffer dynamically.
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// buf.resize_channels(4);
    /// buf.resize_frames(128);
    ///
    /// let expected = (0..128).map(|v| v as f32).collect::<Vec<_>>();
    ///
    /// for mut chan in buf.iter_channels_mut() {
    ///     for (s, v) in chan.iter_mut().zip(&expected) {
    ///         *s = *v;
    ///     }
    /// }
    ///
    /// assert_eq!(buf.get_channel(0).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(1).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(2).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(3).unwrap(), &expected[..]);
    /// assert!(buf.get_channel(4).is_none());
    ///
    /// buf.resize_channels(2);
    ///
    /// assert_eq!(buf.get_channel(0).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(1).unwrap(), &expected[..]);
    /// assert!(buf.get_channel(2).is_none());
    ///
    /// // shrink
    /// buf.resize_frames(64);
    ///
    /// assert_eq!(buf.get_channel(0).unwrap(), &expected[..64]);
    /// assert_eq!(buf.get_channel(1).unwrap(), &expected[..64]);
    /// assert!(buf.get_channel(2).is_none());
    ///
    /// // increase - this causes some weirdness.
    /// buf.resize_frames(128);
    ///
    /// let first_overlapping = expected[..64]
    ///     .iter()
    ///     .chain(expected[..64].iter())
    ///     .copied()
    ///     .collect::<Vec<_>>();
    ///
    /// assert_eq!(buf.get_channel(0).unwrap(), &first_overlapping[..]);
    /// // Note: second channel matches perfectly up with an old channel that was
    /// // masked out.
    /// assert_eq!(buf.get_channel(1).unwrap(), &expected[..]);
    /// assert!(buf.get_channel(2).is_none());
    /// ```
    pub fn resize_frames(&mut self, frames: usize)
    where
        T: Sample,
    {
        self.resize_inner(self.channels, self.frames, self.channels, frames);
    }

    /// Get a reference to the buffer of the given channel.
    ///
    /// # Examples
    ///
    /// ```
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// buf.resize_channels(4);
    /// buf.resize_frames(256);
    ///
    /// let expected = vec![0.0; 256];
    ///
    /// assert_eq!(buf.get_channel(0).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(1).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(2).unwrap(), &expected[..]);
    /// assert_eq!(buf.get_channel(3).unwrap(), &expected[..]);
    /// assert!(buf.get_channel(4).is_none());
    /// ```
    pub fn get_channel(&self, channel: usize) -> Option<LinearChannel<'_, T>> {
        if channel >= self.channels {
            return None;
        }

        let data = self.data.get(channel * self.frames..)?.get(..self.frames)?;
        Some(LinearChannel::new(data))
    }

    /// Get a mutable reference to the buffer of the given channel.
    ///
    /// # Examples
    ///
    /// ```
    /// use rand::Rng as _;
    ///
    /// let mut buf = audio::buf::Sequential::<f32>::new();
    ///
    /// buf.resize_channels(2);
    /// buf.resize_frames(256);
    ///
    /// let mut rng = rand::thread_rng();
    ///
    /// if let Some(mut left) = buf.get_mut(0) {
    ///     rng.fill(left.as_mut());
    /// }
    ///
    /// if let Some(mut right) = buf.get_mut(1) {
    ///     rng.fill(right.as_mut());
    /// }
    /// ```
    pub fn get_mut(&mut self, channel: usize) -> Option<LinearChannelMut<'_, T>> {
        if channel >= self.channels {
            return None;
        }

        let data = self
            .data
            .get_mut(channel * self.frames..)?
            .get_mut(..self.frames)?;

        Some(LinearChannelMut::new(data))
    }

    /// Reserve the given capacity in this buffer ensuring it can take at least
    /// `capacity` elements in total before needing to re-allocate again.
    pub fn reserve(&mut self, capacity: usize) {
        let old_cap = self.data.capacity();

        if old_cap < capacity {
            self.data.reserve(capacity - old_cap);
        }
    }

    /// Access the raw sequential buffer.
    fn as_raw(&self) -> RawSequential<T> {
        // SAFETY: construction of the current buffer ensures this is safe.
        unsafe { RawSequential::new(&self.data, self.channels, self.frames) }
    }

    fn resize_inner(
        &mut self,
        from_channels: usize,
        from_frames: usize,
        to_channels: usize,
        to_frames: usize,
    ) where
        T: Sample,
    {
        if to_channels == 0 || to_frames == 0 {
            self.channels = to_channels;
            self.frames = to_frames;
            return;
        } else if self.channels == to_channels && self.frames == to_frames {
            return;
        }

        let old_cap = self.data.capacity();
        let new_len = to_channels * to_frames;

        if old_cap < new_len {
            let additional = new_len - self.data.capacity();
            self.data.reserve(additional);

            // zero the additional capacity.
            unsafe {
                ptr::write_bytes(
                    self.data.as_mut_ptr().add(old_cap),
                    0,
                    self.data.capacity() - old_cap,
                );
            }
        }

        if from_frames < to_frames {
            for chan in (0..from_channels).rev() {
                unsafe {
                    let src = self.data.as_mut_ptr().add(chan * from_frames);
                    let dst = self.data.as_mut_ptr().add(chan * to_frames);
                    ptr::copy(src, dst, from_frames);
                }
            }
        } else {
            for chan in 0..from_channels {
                unsafe {
                    let src = self.data.as_mut_ptr().add(chan * from_frames);
                    let dst = self.data.as_mut_ptr().add(chan * to_frames);
                    ptr::copy(src, dst, from_frames);
                }
            }
        }

        // Resize underlying storage.
        unsafe {
            self.data.set_len(new_len);
        }

        self.channels = to_channels;
        self.frames = to_frames;
    }
}

impl<T> fmt::Debug for Sequential<T>
where
    T: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter_channels()).finish()
    }
}

impl<T> cmp::PartialEq for Sequential<T>
where
    T: cmp::PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.iter_channels().eq(other.iter_channels())
    }
}

impl<T> cmp::Eq for Sequential<T> where T: cmp::Eq {}

impl<T> cmp::PartialOrd for Sequential<T>
where
    T: cmp::PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        self.iter_channels().partial_cmp(other.iter_channels())
    }
}

impl<T> cmp::Ord for Sequential<T>
where
    T: cmp::Ord,
{
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.iter_channels().cmp(other.iter_channels())
    }
}

impl<T> hash::Hash for Sequential<T>
where
    T: hash::Hash,
{
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        for channel in self.iter_channels() {
            channel.hash(state);
        }
    }
}

impl<'a, T> IntoIterator for &'a Sequential<T> {
    type IntoIter = IterChannels<'a, T>;
    type Item = <Self::IntoIter as Iterator>::Item;

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

impl<'a, T> IntoIterator for &'a mut Sequential<T> {
    type IntoIter = IterChannelsMut<'a, T>;
    type Item = <Self::IntoIter as Iterator>::Item;

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

impl<T> ops::Index<usize> for Sequential<T> {
    type Output = [T];

    fn index(&self, index: usize) -> &Self::Output {
        match self.get_channel(index) {
            Some(slice) => slice.into_ref(),
            None => panic!("index `{}` is not a channel", index),
        }
    }
}

impl<T> ops::IndexMut<usize> for Sequential<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        match self.get_mut(index) {
            Some(slice) => slice.into_mut(),
            None => panic!("index `{}` is not a channel", index,),
        }
    }
}

impl<T> ExactSizeBuf for Sequential<T>
where
    T: Copy,
{
    fn frames(&self) -> usize {
        self.frames
    }
}

impl<T> Buf for Sequential<T>
where
    T: Copy,
{
    type Sample = T;

    type Channel<'this> = LinearChannel<'this, Self::Sample>
    where
        Self::Sample: 'this;

    type IterChannels<'this> = IterChannels<'this, T>
    where
        Self: 'this;

    fn frames_hint(&self) -> Option<usize> {
        Some(self.frames)
    }

    fn channels(&self) -> usize {
        (*self).channels()
    }

    fn get_channel(&self, channel: usize) -> Option<Self::Channel<'_>> {
        (*self).get_channel(channel)
    }

    fn iter_channels(&self) -> Self::IterChannels<'_> {
        (*self).iter_channels()
    }
}

impl<T> UniformBuf for Sequential<T>
where
    T: Copy,
{
    type Frame<'this> = SequentialFrame<'this, T>
    where
        Self: 'this;

    type IterFrames<'this> = SequentialFramesIter<'this, T>
    where
        Self: 'this;

    #[inline]
    fn get_frame(&self, frame: usize) -> Option<Self::Frame<'_>> {
        if frame >= self.frames {
            return None;
        }

        Some(SequentialFrame::new(frame, self.as_raw()))
    }

    #[inline]
    fn iter_frames(&self) -> Self::IterFrames<'_> {
        SequentialFramesIter::new(0, self.as_raw())
    }
}

impl<T> ResizableBuf for Sequential<T>
where
    T: Sample,
{
    fn try_reserve(&mut self, capacity: usize) -> bool {
        self.reserve(capacity);
        true
    }

    fn resize_frames(&mut self, frames: usize) {
        Self::resize_frames(self, frames);
    }

    fn resize_topology(&mut self, channels: usize, frames: usize) {
        Self::resize_frames(self, frames);
        Self::resize_channels(self, channels);
    }
}

impl<T> BufMut for Sequential<T>
where
    T: Copy,
{
    type ChannelMut<'this> = LinearChannelMut<'this, Self::Sample>
    where
        Self: 'this;

    type IterChannelsMut<'this> = IterChannelsMut<'this, T>
    where
        Self: 'this;

    fn get_channel_mut(&mut self, channel: usize) -> Option<Self::ChannelMut<'_>> {
        (*self).get_mut(channel)
    }

    fn copy_channel(&mut self, from: usize, to: usize) {
        // Safety: We're calling the copy function with internal parameters
        // which are guaranteed to be correct.
        unsafe {
            crate::utils::copy_channels_sequential(
                ptr::NonNull::new_unchecked(self.data.as_mut_ptr()),
                self.channels,
                self.frames,
                from,
                to,
            )
        }
    }

    fn iter_channels_mut(&mut self) -> Self::IterChannelsMut<'_> {
        (*self).iter_channels_mut()
    }

    #[inline]
    fn fill(&mut self, value: T)
    where
        T: Copy,
    {
        self.data.fill(value);
    }
}