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
//! A reference to a channel in a buffer.

use std::cmp;
use std::fmt;
use std::hash;
use std::marker;

/// A reference to a channel in a buffer.
///
/// See [crate::Interleaved::get].
#[derive(Clone, Copy)]
pub struct Channel<'a, T> {
    pub(crate) inner: RawChannelRef<T>,
    pub(crate) _marker: marker::PhantomData<&'a T>,
}

// Safety: the iterator is simply a container of references to T's, any
// Send/Sync properties are inherited.
unsafe impl<T> Send for Channel<'_, T> where T: Sync {}
unsafe impl<T> Sync for Channel<'_, T> where T: Sync {}

impl<'a, T> Channel<'a, T> {
    /// Get a reference to a frame.
    pub fn get(&self, frame: usize) -> Option<T>
    where
        T: Copy,
    {
        Some(unsafe { *self.inner.frame_ref(frame)? })
    }

    /// Construct an iterator over the current channel.
    pub fn iter(&self) -> ChannelIter<'_, T> {
        ChannelIter {
            inner: self.inner,
            frame: 0,
            _marker: marker::PhantomData,
        }
    }
}

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

impl<T> cmp::PartialEq for Channel<'_, T>
where
    T: cmp::PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.iter().eq(other.iter())
    }
}

impl<T> cmp::Eq for Channel<'_, T> where T: cmp::Eq {}

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

impl<T> cmp::Ord for Channel<'_, T>
where
    T: cmp::Ord,
{
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.iter().cmp(other.iter())
    }
}

impl<T> hash::Hash for Channel<'_, T>
where
    T: hash::Hash,
{
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        for frame in self.iter() {
            frame.hash(state);
        }
    }
}

/// An iterator over a channel.
///
/// Created with [Channel::iter].
pub struct ChannelIter<'a, T> {
    inner: RawChannelRef<T>,
    frame: usize,
    _marker: marker::PhantomData<&'a T>,
}

// Safety: the iterator is simply a container of references to T's, any
// Send/Sync properties are inherited.
unsafe impl<T> Send for ChannelIter<'_, T> where T: Sync {}
unsafe impl<T> Sync for ChannelIter<'_, T> where T: Sync {}

impl<'a, T> Iterator for ChannelIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        let item = unsafe { &*self.inner.frame_ref(self.frame)? };
        self.frame += 1;
        Some(item)
    }
}

pub(crate) struct RawChannelRef<T: ?Sized> {
    pub(crate) buffer: *const T,
    pub(crate) channel: usize,
    pub(crate) channels: usize,
    pub(crate) frames: usize,
}

impl<T> RawChannelRef<T> {
    /// Get a pointer to the given frame.
    ///
    /// This performs bounds checking to make sure that the frame is in bounds
    /// with the underlying collection.
    #[inline]
    fn frame_ref(self, frame: usize) -> Option<*const T> {
        if frame < self.frames {
            let offset = self.channels * frame + self.channel;
            // Safety: We hold all the parameters necessary to perform bounds
            // checking.
            let frame = unsafe { self.buffer.add(offset) };
            Some(frame)
        } else {
            None
        }
    }
}

// Note: can't auto impl because `T`.
impl<T: ?Sized> Clone for RawChannelRef<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: ?Sized> Copy for RawChannelRef<T> {}

pub(crate) struct RawChannelMut<T: ?Sized> {
    pub(crate) buffer: *mut T,
    pub(crate) channel: usize,
    pub(crate) channels: usize,
    pub(crate) frames: usize,
}

impl<T> RawChannelMut<T> {
    #[inline]
    fn into_ref(self) -> RawChannelRef<T> {
        RawChannelRef {
            buffer: self.buffer as *const _,
            channel: self.channel,
            channels: self.channels,
            frames: self.frames,
        }
    }

    /// Get a mutable pointer to the given frame.
    ///
    /// This performs bounds checking to make sure that the frame is in bounds
    /// with the underlying collection.
    #[inline]
    fn frame_mut(self, frame: usize) -> Option<*mut T> {
        if frame < self.frames {
            let offset = self.channels * frame + self.channel;
            // Safety: We hold all the parameters necessary to perform bounds
            // checking.
            let frame = unsafe { self.buffer.add(offset) };
            Some(frame)
        } else {
            None
        }
    }
}

// Note: can't auto impl because `T`.
impl<T: ?Sized> Clone for RawChannelMut<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: ?Sized> Copy for RawChannelMut<T> {}

/// A mutable reference to a channel in a buffer.
///
/// See [crate::Interleaved::get_mut].
pub struct ChannelMut<'a, T> {
    pub(crate) inner: RawChannelMut<T>,
    pub(crate) _marker: marker::PhantomData<&'a mut T>,
}

// Safety: the iterator is simply a container of mutable references to T's, any
// Send/Sync properties are inherited.
unsafe impl<T> Send for ChannelMut<'_, T> where T: Send {}
unsafe impl<T> Sync for ChannelMut<'_, T> where T: Sync {}

impl<'a, T> ChannelMut<'a, T> {
    /// Get a reference to a frame.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let mut buffer = rotary::Interleaved::<f32>::with_topology(2, 256);
    ///
    /// let left = buffer.get(0).unwrap();
    ///
    /// assert_eq!(left.get(64), Some(0.0));
    /// assert_eq!(left.get(255), Some(0.0));
    /// assert_eq!(left.get(256), None);
    /// ```
    pub fn get(&self, frame: usize) -> Option<T>
    where
        T: Copy,
    {
        // Safety: The lifetime created is associated with the structure that
        // constructed this abstraction.
        unsafe { Some(*self.inner.into_ref().frame_ref(frame)?) }
    }

    /// Get a mutable reference to a frame.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let mut buffer = rotary::Interleaved::<f32>::with_topology(2, 256);
    ///
    /// let mut left = buffer.get_mut(0).unwrap();
    ///
    /// assert_eq!(left.get(64), Some(0.0));
    /// *left.get_mut(64).unwrap() = 1.0;
    /// assert_eq!(left.get(64), Some(1.0));
    /// ```
    pub fn get_mut(&mut self, frame: usize) -> Option<&mut T> {
        // Safety: The lifetime created is associated with the structure that
        // constructed this abstraction.
        unsafe { Some(&mut *self.inner.frame_mut(frame)?) }
    }

    /// Convert the mutable channel into a single mutable frame.
    ///
    /// This is necessary in case you need to build a structure which wraps a
    /// mutable channel and you want it to return the same lifetime as the
    /// mutable channel is associated with.
    ///
    /// # Examples
    ///
    /// This does not build:
    ///
    /// ```rust,compile_fail
    /// struct Foo<'a> {
    ///     left: rotary::interleaved::ChannelMut<'a, f32>,
    /// }
    ///
    /// impl<'a> Foo<'a> {
    ///     fn get_mut(&mut self, frame: usize) -> Option<&'a mut f32> {
    ///         self.left.get_mut(frame)
    ///     }
    /// }
    ///
    /// let mut buffer = rotary::Interleaved::<f32>::with_topology(2, 256);
    ///
    /// let mut foo = Foo {
    ///     left: buffer.get_mut(0).unwrap(),
    /// };
    ///
    /// *foo.get_mut(64).unwrap() = 1.0;
    /// assert_eq!(buffer.frame(0, 64), Some(1.0));
    /// ```
    ///
    /// ```text
    ///    error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
    ///    --> examples\compile-fail.rs:7:19
    ///     |
    ///   7 |         self.left.get_mut(frame)
    ///     |                   ^^^^^^^
    ///     |
    /// ```
    ///
    /// Because if it did, it would be permitted to extract multiple mutable
    /// references to potentially the same frame with the lifetime `'a`, because
    /// `Foo` holds onto the mutable channel.
    ///
    /// The way we can work around this is by allowing a function to consume the
    /// mutable channel. And we can do that with [ChannelMut::into_mut].
    ///
    /// ```rust
    /// # struct Foo<'a> {
    /// #     left: rotary::interleaved::ChannelMut<'a, f32>,
    /// # }
    ///
    /// impl<'a> Foo<'a> {
    ///     fn into_mut(self, frame: usize) -> Option<&'a mut f32> {
    ///         self.left.into_mut(frame)
    ///     }
    /// }
    ///
    /// let mut buffer = rotary::Interleaved::<f32>::with_topology(2, 256);
    ///
    /// let mut foo = Foo {
    ///     left: buffer.get_mut(0).unwrap(),
    /// };
    ///
    /// *foo.into_mut(64).unwrap() = 1.0;
    /// assert_eq!(buffer.frame(0, 64), Some(1.0));
    /// ```
    pub fn into_mut(self, frame: usize) -> Option<&'a mut T> {
        // Safety: The lifetime created is associated with the structure that
        // constructed this abstraction.
        //
        // We also discard the current channel, which would otherwise allow us
        // to create more `&'a mut T` references, which would be illegal.
        unsafe { Some(&mut *self.inner.frame_mut(frame)?) }
    }

    /// Construct an iterator over the current channel.
    pub fn iter(&self) -> ChannelIter<'_, T> {
        ChannelIter {
            inner: self.inner.into_ref(),
            frame: 0,
            _marker: marker::PhantomData,
        }
    }

    /// Construct a mutable iterator over the current channel.
    pub fn iter_mut(&mut self) -> ChannelIterMut<'_, T> {
        ChannelIterMut {
            inner: self.inner,
            frame: 0,
            _marker: marker::PhantomData,
        }
    }
}

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

impl<T> cmp::PartialEq for ChannelMut<'_, T>
where
    T: cmp::PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.iter().eq(other.iter())
    }
}

impl<T> cmp::Eq for ChannelMut<'_, T> where T: cmp::Eq {}

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

impl<T> cmp::Ord for ChannelMut<'_, T>
where
    T: cmp::Ord,
{
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.iter().cmp(other.iter())
    }
}

impl<T> hash::Hash for ChannelMut<'_, T>
where
    T: hash::Hash,
{
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        for frame in self.iter() {
            frame.hash(state);
        }
    }
}

/// A mutable iterator over a channel.
///
/// Created with [ChannelMut::iter_mut].
pub struct ChannelIterMut<'a, T> {
    inner: RawChannelMut<T>,
    frame: usize,
    _marker: marker::PhantomData<&'a mut T>,
}

// Safety: the iterator is simply a container of references to T's, any
// Send/Sync properties are inherited.
unsafe impl<T> Send for ChannelIterMut<'_, T> where T: Send {}
unsafe impl<T> Sync for ChannelIterMut<'_, T> where T: Sync {}

impl<'a, T> Iterator for ChannelIterMut<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<Self::Item> {
        let item = unsafe { &mut *self.inner.frame_mut(self.frame)? };
        self.frame += 1;
        Some(item)
    }
}