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
//! Utilities for working with interleaved channels.

use core::cmp;
use core::fmt;
use core::marker;
use core::mem;
use core::ptr;

use audio_core::{Channel, ChannelMut};

#[macro_use]
mod macros;

#[cfg(test)]
mod tests;

#[inline(always)]
fn size_from_ptr<T>(_: *const T) -> usize {
    mem::size_of::<T>()
}

interleaved_channel!('a, T, const, InterleavedChannel, align_iterable_ref);
interleaved_channel!('a, T, mut, InterleavedChannelMut, align_iterable_mut);

comparisons!({'a, T}, InterleavedChannel<'a, T>, InterleavedChannelMut<'a, T>);
comparisons!({'a, T}, InterleavedChannelMut<'a, T>, InterleavedChannel<'a, T>);

slice_comparisons!({'a, T, const N: usize}, InterleavedChannel<'a, T>, [T; N]);
slice_comparisons!({'a, T}, InterleavedChannel<'a, T>, [T]);
slice_comparisons!({'a, T}, InterleavedChannel<'a, T>, &[T]);
slice_comparisons!(#[cfg(feature = "std")] {'a, T}, InterleavedChannel<'a, T>, Vec<T>);
slice_comparisons!({'a, T, const N: usize}, InterleavedChannelMut<'a, T>, [T; N]);
slice_comparisons!({'a, T}, InterleavedChannelMut<'a, T>, [T]);
slice_comparisons!({'a, T}, InterleavedChannelMut<'a, T>, &[T]);
slice_comparisons!(#[cfg(feature = "std")] {'a, T}, InterleavedChannelMut<'a, T>, Vec<T>);

/// Read-only access to a single channel of audio within an interleaved,
/// multichannel audio buffer. This struct does not own the audio data; it
/// provides an API for accessing data owned by something else.
///
/// See also [crate::buf::Interleaved].
pub struct InterleavedChannel<'a, T> {
    /// The base pointer of the buffer.
    ptr: ptr::NonNull<T>,
    /// The end pointer of the buffer.
    end: *const T,
    /// The number of channels in the interleaved buffer.
    step: usize,
    /// The market indicating the kind of the channel.
    _marker: marker::PhantomData<&'a [T]>,
}

impl<'a, T> InterleavedChannel<'a, T> {
    /// Construct an interleaved channel buffer from a slice.
    ///
    /// This is a safe function since the data being referenced is both bounds
    /// checked and is associated with the lifetime of the structure.
    ///
    /// Returns `None` if the channel configuration is not valid. That is either
    /// true if the given number of `channels` cannot fit within it or if the
    /// selected `channel` does not fit within the specified `channels`.
    ///
    /// ```
    /// use audio::channel::InterleavedChannel;
    ///
    /// let buf: &[u32] = &[1, 2];
    /// assert!(InterleavedChannel::from_slice(buf, 1, 4).is_none());
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use audio::channel::InterleavedChannel;
    ///
    /// let buf: &[u32] = &[1, 2, 3, 4, 5, 6, 7, 8];
    /// let channel = InterleavedChannel::from_slice(buf, 1, 2).unwrap();
    ///
    /// assert_eq!(channel.get(1), Some(4));
    /// assert_eq!(channel.get(2), Some(6));
    /// ```
    pub fn from_slice(data: &'a [T], channel: usize, channels: usize) -> Option<Self> {
        if data.len().checked_rem(channels)? != 0 || channel >= channels {
            return None;
        }

        Some(unsafe {
            Self::new_unchecked(
                ptr::NonNull::new_unchecked(data.as_ptr() as *mut _),
                data.len(),
                channel,
                channels,
            )
        })
    }
}

/// Read-write access to a single channel of audio within an interleaved,
/// multichannel audio buffer. This struct does not own the audio data; it
/// provides an API for accessing data owned by something else.
///
/// See also [crate::buf::Interleaved].
pub struct InterleavedChannelMut<'a, T> {
    /// The base pointer of the buffer.
    ptr: ptr::NonNull<T>,
    /// The size of the buffer.
    end: *mut T,
    /// The number of channels in the interleaved buffer.
    step: usize,
    /// The market indicating the kind of the channel.
    _marker: marker::PhantomData<&'a mut [T]>,
}

impl<'a, T> InterleavedChannelMut<'a, T> {
    /// Construct an interleaved channel buffer from a slice.
    ///
    /// This is a safe function since the data being referenced is both bounds
    /// checked and is associated with the lifetime of the structure.
    ///
    /// Returns `None` if the channel configuration is not valid. That is either true if
    /// the given number of `channels` cannot fit within it or if the selected
    /// `channel` does not fit within the specified `channels`.
    ///
    /// ```
    /// use audio::channel::InterleavedChannelMut;
    ///
    /// let buf: &mut [u32] = &mut [1, 2];
    /// assert!(InterleavedChannelMut::from_slice(buf, 1, 4).is_none());
    /// ```
    ///
    /// # Examples
    ///
    /// ```
    /// use audio::channel::InterleavedChannelMut;
    ///
    /// let buf: &mut [u32] = &mut [1, 2, 3, 4, 5, 6, 7, 8];
    /// let channel = InterleavedChannelMut::from_slice(buf, 1, 2).unwrap();
    ///
    /// assert_eq!(channel.get(1), Some(4));
    /// assert_eq!(channel.get(2), Some(6));
    /// ```
    pub fn from_slice(data: &'a mut [T], channel: usize, channels: usize) -> Option<Self> {
        if data.len().checked_rem(channels)? != 0 || channel >= channels {
            return None;
        }

        Some(unsafe {
            Self::new_unchecked(
                ptr::NonNull::new_unchecked(data.as_mut_ptr()),
                data.len(),
                channel,
                channels,
            )
        })
    }

    /// Get the given frame if it's in bound.
    pub fn into_mut(self, frame: usize) -> Option<&'a mut T> {
        if frame < len!(self) {
            if mem::size_of::<T>() == 0 {
                Some(unsafe { &mut *(self.ptr.as_ptr() as *mut _) })
            } else {
                let add = frame.saturating_mul(self.step);
                Some(unsafe { &mut *(self.ptr.as_ptr() as *mut T).add(add) })
            }
        } else {
            None
        }
    }

    /// Get the given frame mutably if it's in bound.
    pub fn get_mut(&mut self, n: usize) -> Option<&mut T> {
        if n < len!(self) {
            if mem::size_of::<T>() == 0 {
                Some(unsafe { &mut *(self.ptr.as_ptr() as *mut _) })
            } else {
                let add = n.saturating_mul(self.step);
                Some(unsafe { &mut *(self.ptr.as_ptr() as *mut T).add(add) })
            }
        } else {
            None
        }
    }

    /// Construct a mutable iterator over the channel.
    #[inline]
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        IterMut {
            ptr: self.ptr,
            end: self.end,
            step: self.step,
            _marker: marker::PhantomData,
        }
    }
}

impl<'a, T> ChannelMut for InterleavedChannelMut<'a, T>
where
    T: Copy,
{
    type ChannelMut<'this> = InterleavedChannelMut<'this, Self::Sample>
    where
        Self: 'this;

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

    #[inline]
    fn as_channel_mut(&mut self) -> Self::ChannelMut<'_> {
        InterleavedChannelMut {
            ptr: self.ptr,
            end: self.end,
            step: self.step,
            _marker: marker::PhantomData,
        }
    }

    #[inline]
    fn get_mut(&mut self, n: usize) -> Option<&mut T> {
        (*self).get_mut(n)
    }

    #[inline]
    fn iter_mut(&mut self) -> Self::IterMut<'_> {
        (*self).iter_mut()
    }

    #[inline]
    fn try_as_linear_mut(&mut self) -> Option<&mut [T]> {
        None
    }
}

impl<T> Clone for InterleavedChannel<'_, T> {
    fn clone(&self) -> Self {
        Self {
            ptr: self.ptr,
            end: self.end,
            step: self.step,
            _marker: marker::PhantomData,
        }
    }
}

/// Note: InterleavedChannel is always Copy since it represents an immutable
/// buffer.
impl<T> Copy for InterleavedChannel<'_, T> {}

/// An immutable iterator.
pub struct Iter<'a, T> {
    ptr: ptr::NonNull<T>,
    end: *const T,
    step: usize,
    _marker: marker::PhantomData<&'a [T]>,
}

impl<'a, T> Iter<'a, T> {
    /// Construct a new aligned iterator.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the provided pointer points to an appropriately sized buffer.
    #[inline]
    pub(crate) unsafe fn new_aligned(
        ptr: ptr::NonNull<T>,
        len: usize,
        offset: usize,
        channels: usize,
        step: usize,
    ) -> Self {
        let (ptr, end) = align_iterable_ref(ptr, len, offset, channels);

        Self {
            ptr,
            end,
            step,
            _marker: marker::PhantomData,
        }
    }
}

/// Allign an iterable reference with the given length.
///
/// # Safety
///
/// The caller is responsible for ensuring that the buffer is valid up until the
/// maximum of `len` and `offset` and that no exclusive access to the specified
/// range (by step) is already in use.
unsafe fn align_iterable_ref<T>(
    ptr: ptr::NonNull<T>,
    len: usize,
    offset: usize,
    max: usize,
) -> (ptr::NonNull<T>, *const T) {
    debug_assert!(
        offset <= max,
        "referencing channel out of bounds; offset={}, max={}",
        offset,
        max,
    );
    debug_assert!(
        len % max == 0,
        "number of channels misaligned with length; max={}, len={}",
        max,
        len,
    );
    debug_assert!(max <= len, "max out of bounds; max={}, len={}", max, len,);

    let ptr = ptr.as_ptr();

    let (ptr, end) = if mem::size_of::<T>() == 0 {
        let end = (ptr as *const u8).wrapping_add(len / max) as *const T;
        (ptr, end)
    } else {
        let ptr = ptr.add(offset);
        let end = ptr.wrapping_add(len) as *const T;
        (ptr, end)
    };

    let ptr = ptr::NonNull::new_unchecked(ptr);
    (ptr, end)
}

/// Allign a mutable reference with the given length.
///
/// # Safety
///
/// The caller is responsible for ensuring that the buffer is valid up until the
/// maximum of `len` and `offset` and that no exclusive access to the specified
/// range (by step) is already in use.
unsafe fn align_iterable_mut<T>(
    ptr: ptr::NonNull<T>,
    len: usize,
    offset: usize,
    max: usize,
) -> (ptr::NonNull<T>, *mut T) {
    debug_assert!(
        offset <= max,
        "referencing channel out of bounds; offset={}, max={}",
        offset,
        max,
    );
    debug_assert!(
        len % max == 0,
        "number of channels misaligned with length; max={}, len={}",
        max,
        len,
    );
    debug_assert!(max <= len, "max out of bounds; max={}, len={}", max, len,);

    let ptr = ptr.as_ptr();

    let (ptr, end) = if mem::size_of::<T>() == 0 {
        let end = (ptr as *mut u8).wrapping_add(len / max) as *mut T;
        (ptr, end)
    } else {
        let ptr = ptr.add(offset);
        let end = ptr.wrapping_add(len) as *mut T;
        (ptr, end)
    };

    let ptr = ptr::NonNull::new_unchecked(ptr);
    (ptr, end)
}

/// A mutable iterator.
pub struct IterMut<'a, T> {
    ptr: ptr::NonNull<T>,
    end: *mut T,
    step: usize,
    _marker: marker::PhantomData<&'a mut [T]>,
}

iterator!(struct Iter -> *const T, T, const, {/* no mut */});
iterator!(struct IterMut -> *mut T, &'a mut T, mut, {&mut});