rotary/dynamic.rs
1//! A dynamically sized, multi-channel audio buffer.
2
3use rotary_core::{Buf, BufMut, Channel, ChannelMut, ExactSizeBuf, ResizableBuf, Sample};
4use std::cmp;
5use std::fmt;
6use std::hash;
7use std::mem;
8use std::ops;
9use std::ptr;
10use std::slice;
11
12mod iter;
13pub use self::iter::{Iter, IterMut};
14
15/// A dynamically sized, multi-channel audio buffer.
16///
17/// An audio buffer can only be resized if it contains a type which is
18/// sample-apt For more information of what this means, see [Sample].
19///
20/// This kind of buffer stores each channel in its own heap-allocated slice of
21/// memory, meaning they can be manipulated more cheaply independently of each
22/// other than say [Interleaved][crate::Interleaved] or
23/// [Sequential][crate::Sequential]. These would have to re-organize every
24/// constituent channel when resizing, while [Dynamic] generally only requires
25/// [growing and shrinking][std::alloc::Allocator] of a memory region.
26///
27/// This kind of buffer is a good choice if you need to
28/// [resize][Dynamic::resize] frequently.
29pub struct Dynamic<T> {
30 /// The stored data for each channel.
31 data: RawSlice<RawSlice<T>>,
32 /// The number of channels stored.
33 channels: usize,
34 /// The capacity of channels stored.
35 channels_cap: usize,
36 /// The length of each channel.
37 frames: usize,
38 /// Allocated capacity of each channel. Each channel is guaranteed to be
39 /// filled with as many values as is specified in this capacity.
40 frames_cap: usize,
41}
42
43impl<T> Dynamic<T> {
44 /// Construct a new empty audio buffer.
45 ///
46 /// # Examples
47 ///
48 /// ```rust
49 /// let mut buffer = rotary::Dynamic::<f32>::new();
50 ///
51 /// assert_eq!(buffer.frames(), 0);
52 /// ```
53 pub fn new() -> Self {
54 Self {
55 // Safety: we know that a newly created vector is non-null.
56 data: RawSlice::empty(),
57 channels: 0,
58 channels_cap: 0,
59 frames: 0,
60 frames_cap: 0,
61 }
62 }
63
64 /// Allocate an audio buffer with the given topology. A "topology" is a
65 /// given number of `channels` and the corresponding number of `frames` in
66 /// their buffers.
67 ///
68 /// # Examples
69 ///
70 /// ```rust
71 /// let mut buffer = rotary::Dynamic::<f32>::with_topology(4, 256);
72 ///
73 /// assert_eq!(buffer.frames(), 256);
74 /// assert_eq!(buffer.channels(), 4);
75 /// ```
76 pub fn with_topology(channels: usize, frames: usize) -> Self
77 where
78 T: Sample,
79 {
80 let mut data = RawSlice::uninit(channels);
81
82 for n in 0..channels {
83 // Safety: We just allocated the vector w/ a capacity matching channels.
84 unsafe {
85 data.write(n, RawSlice::zeroed(frames));
86 }
87 }
88
89 Self {
90 // Safety: we just initialized the associated array with the
91 // expected topology.
92 data,
93 channels,
94 channels_cap: channels,
95 frames,
96 frames_cap: frames,
97 }
98 }
99
100 /// Allocate an audio buffer from a fixed-size array.
101 ///
102 /// See [dynamic!].
103 ///
104 /// # Examples
105 ///
106 /// ```rust
107 /// let mut buffer = rotary::Dynamic::<f32>::from_array([[2.0; 256]; 4]);
108 ///
109 /// assert_eq!(buffer.frames(), 256);
110 /// assert_eq!(buffer.channels(), 4);
111 ///
112 /// for chan in &buffer {
113 /// assert_eq!(chan, vec![2.0; 256]);
114 /// }
115 /// ```
116 pub fn from_array<const F: usize, const C: usize>(channels: [[T; F]; C]) -> Self
117 where
118 T: Copy,
119 {
120 return Self {
121 // Safety: We just created the box with the data so we know that
122 // it's initialized.
123 data: unsafe { data_from_array(channels) },
124 channels: C,
125 channels_cap: C,
126 frames: F,
127 frames_cap: F,
128 };
129
130 #[inline]
131 unsafe fn data_from_array<T, const F: usize, const C: usize>(
132 values: [[T; F]; C],
133 ) -> RawSlice<RawSlice<T>>
134 where
135 T: Copy,
136 {
137 let mut data = Vec::with_capacity(C);
138
139 for frames in std::array::IntoIter::new(values) {
140 let slice = Box::<[T]>::from(frames);
141 let slice = ptr::NonNull::new_unchecked(Box::into_raw(slice) as *mut T);
142 data.push(RawSlice { data: slice });
143 }
144
145 RawSlice {
146 data: ptr::NonNull::new_unchecked(mem::ManuallyDrop::new(data).as_mut_ptr()),
147 }
148 }
149 }
150
151 /// Allocate a dynamic audio buffer from a fixed-size array acting as a
152 /// template for all the channels.
153 ///
154 /// See [dynamic!].
155 ///
156 /// # Examples
157 ///
158 /// ```rust
159 /// let mut buffer = rotary::Dynamic::from_frames([1.0, 2.0, 3.0, 4.0], 4);
160 ///
161 /// assert_eq!(buffer.frames(), 4);
162 /// assert_eq!(buffer.channels(), 4);
163 /// ```
164 pub fn from_frames<const N: usize>(frames: [T; N], channels: usize) -> Self
165 where
166 T: Copy,
167 {
168 return Self {
169 data: data_from_frames(frames, channels),
170 channels,
171 channels_cap: channels,
172 frames: N,
173 frames_cap: N,
174 };
175
176 fn data_from_frames<T, const N: usize>(
177 frames: [T; N],
178 channels: usize,
179 ) -> RawSlice<RawSlice<T>>
180 where
181 T: Copy,
182 {
183 // Safety: we control and can trust all of the allocated buffer sizes.
184 unsafe {
185 let mut data = RawSlice::uninit(channels);
186
187 for c in 0..channels {
188 let slice = RawSlice::uninit(N);
189 ptr::copy_nonoverlapping(frames.as_ptr(), slice.as_ptr(), N);
190 data.write(c, slice);
191 }
192
193 data
194 }
195 }
196 }
197
198 /// Get the number of frames in the channels of an audio buffer.
199 ///
200 /// # Examples
201 ///
202 /// ```rust
203 /// let mut buffer = rotary::Dynamic::<f32>::new();
204 ///
205 /// assert_eq!(buffer.frames(), 0);
206 /// buffer.resize(256);
207 /// assert_eq!(buffer.frames(), 256);
208 /// ```
209 pub fn frames(&self) -> usize {
210 self.frames
211 }
212
213 /// Check how many channels there are in the buffer.
214 ///
215 /// # Examples
216 ///
217 /// ```rust
218 /// let mut buffer = rotary::Dynamic::<f32>::new();
219 ///
220 /// assert_eq!(buffer.channels(), 0);
221 /// buffer.resize_channels(2);
222 /// assert_eq!(buffer.channels(), 2);
223 /// ```
224 pub fn channels(&self) -> usize {
225 self.channels
226 }
227
228 /// Construct a mutable iterator over all available channels.
229 ///
230 /// # Examples
231 ///
232 /// ```
233 /// use rand::Rng as _;
234 ///
235 /// let mut buffer = rotary::Dynamic::<f32>::with_topology(4, 256);
236 ///
237 /// let all_zeros = vec![0.0; 256];
238 ///
239 /// for chan in buffer.iter() {
240 /// assert_eq!(chan, &all_zeros[..]);
241 /// }
242 /// ```
243 pub fn iter(&self) -> Iter<'_, T> {
244 // Safety: we're using a trusted length to build the slice.
245 unsafe { Iter::new(self.data.as_ref(self.channels), self.frames) }
246 }
247
248 /// Construct a mutable iterator over all available channels.
249 ///
250 /// # Examples
251 ///
252 /// ```
253 /// use rand::Rng as _;
254 ///
255 /// let mut buffer = rotary::Dynamic::<f32>::with_topology(4, 256);
256 /// let mut rng = rand::thread_rng();
257 ///
258 /// for chan in buffer.iter_mut() {
259 /// rng.fill(chan);
260 /// }
261 /// ```
262 pub fn iter_mut(&mut self) -> IterMut<'_, T> {
263 // Safety: we're using a trusted length to build the slice.
264 unsafe { IterMut::new(self.data.as_mut(self.channels), self.frames) }
265 }
266
267 /// Set the size of the buffer. The size is the size of each channel's
268 /// buffer.
269 ///
270 /// If the size of the buffer increases as a result, the new regions in the
271 /// frames will be zeroed. If the size decreases, the region will be left
272 /// untouched. So if followed by another increase, the data will be "dirty".
273 ///
274 /// # Examples
275 ///
276 /// ```rust
277 /// let mut buffer = rotary::Dynamic::<f32>::new();
278 ///
279 /// assert_eq!(buffer.channels(), 0);
280 /// assert_eq!(buffer.frames(), 0);
281 ///
282 /// buffer.resize_channels(4);
283 /// buffer.resize(256);
284 ///
285 /// assert_eq!(buffer[1][128], 0.0);
286 /// buffer[1][128] = 42.0;
287 ///
288 /// assert_eq!(buffer.channels(), 4);
289 /// assert_eq!(buffer.frames(), 256);
290 /// ```
291 ///
292 /// Decreasing and increasing the size will not touch a buffer that has
293 /// already been allocated.
294 ///
295 /// ```rust
296 /// # let mut buffer = rotary::Dynamic::<f32>::with_topology(4, 256);
297 /// assert_eq!(buffer[1][128], 0.0);
298 /// buffer[1][128] = 42.0;
299 ///
300 /// buffer.resize(64);
301 /// assert!(buffer[1].get(128).is_none());
302 ///
303 /// buffer.resize(256);
304 /// assert_eq!(buffer[1][128], 42.0);
305 /// ```
306 pub fn resize(&mut self, frames: usize)
307 where
308 T: Sample,
309 {
310 if self.frames_cap < frames {
311 let from = self.frames_cap;
312 let to = <RawSlice<T>>::next_cap(from, frames);
313
314 if self.channels_cap > 0 {
315 let additional = to - from;
316
317 for n in 0..self.channels_cap {
318 // Safety: We control the known sizes, so we can guarantee
319 // that the slice is allocated and sized tio exactly `from`.
320 unsafe {
321 self.data
322 .get_unchecked_mut(n)
323 .reserve_zeroed(from, additional)
324 };
325 }
326 }
327
328 self.frames_cap = to;
329 }
330
331 self.frames = frames;
332 }
333
334 /// Set the number of channels in use.
335 ///
336 /// If the size of the buffer increases as a result, the new channels will
337 /// be zeroed. If the size decreases, the channels that falls outside of the
338 /// new size will be dropped.
339 ///
340 /// # Examples
341 ///
342 /// ```rust
343 /// let mut buffer = rotary::Dynamic::<f32>::new();
344 ///
345 /// assert_eq!(buffer.channels(), 0);
346 /// assert_eq!(buffer.frames(), 0);
347 ///
348 /// buffer.resize_channels(4);
349 /// buffer.resize(256);
350 ///
351 /// assert_eq!(buffer.channels(), 4);
352 /// assert_eq!(buffer.frames(), 256);
353 /// ```
354 pub fn resize_channels(&mut self, channels: usize)
355 where
356 T: Sample,
357 {
358 if channels == self.channels {
359 return;
360 }
361
362 if channels > self.channels_cap {
363 let old_cap = self.channels_cap;
364 let new_cap = <RawSlice<RawSlice<T>>>::next_cap(old_cap, channels);
365
366 let additional = new_cap - old_cap;
367
368 // Safety: We trust that the old capacity is correct.
369 unsafe {
370 self.data.reserve_uninit(old_cap, additional);
371 }
372
373 for n in old_cap..new_cap {
374 let slice = RawSlice::zeroed(self.frames_cap);
375
376 // Safety: we control the capacity of channels and have just
377 // guranteed above that it is appropriate.
378 unsafe {
379 self.data.write(n, slice);
380 }
381 }
382
383 self.channels_cap = new_cap;
384 }
385
386 debug_assert!(channels <= self.channels_cap);
387 self.channels = channels;
388 }
389
390 /// Get a reference to the buffer of the given channel.
391 ///
392 /// # Examples
393 ///
394 /// ```rust
395 /// let mut buffer = rotary::Dynamic::<f32>::new();
396 ///
397 /// buffer.resize_channels(4);
398 /// buffer.resize(256);
399 ///
400 /// let expected = vec![0.0; 256];
401 ///
402 /// assert_eq!(Some(&expected[..]), buffer.get(0));
403 /// assert_eq!(Some(&expected[..]), buffer.get(1));
404 /// assert_eq!(Some(&expected[..]), buffer.get(2));
405 /// assert_eq!(Some(&expected[..]), buffer.get(3));
406 /// assert_eq!(None, buffer.get(4));
407 /// ```
408 pub fn get(&self, channel: usize) -> Option<&[T]> {
409 if channel < self.channels {
410 // Safety: We control the length of each channel so we can assert that
411 // it is both allocated and initialized up to `len`.
412 unsafe { Some(self.data.get_unchecked(channel).as_ref(self.frames)) }
413 } else {
414 None
415 }
416 }
417
418 /// Get the given channel or initialize the buffer with the default value.
419 ///
420 /// # Examples
421 ///
422 /// ```rust
423 /// let mut buffer = rotary::Dynamic::<f32>::new();
424 ///
425 /// buffer.resize(256);
426 ///
427 /// let expected = vec![0f32; 256];
428 ///
429 /// assert_eq!(buffer.get_or_default(0), &expected[..]);
430 /// assert_eq!(buffer.get_or_default(1), &expected[..]);
431 ///
432 /// assert_eq!(buffer.channels(), 2);
433 /// ```
434 pub fn get_or_default(&mut self, channel: usize) -> &[T]
435 where
436 T: Sample,
437 {
438 self.resize_channels(channel + 1);
439
440 // Safety: We initialized the given index just above and we know the
441 // trusted length.
442 unsafe { self.data.get_unchecked(channel).as_ref(self.frames) }
443 }
444
445 /// Get a mutable reference to the buffer of the given channel.
446 ///
447 /// # Examples
448 ///
449 /// ```rust
450 /// use rand::Rng as _;
451 ///
452 /// let mut buffer = rotary::Dynamic::<f32>::new();
453 ///
454 /// buffer.resize_channels(2);
455 /// buffer.resize(256);
456 ///
457 /// let mut rng = rand::thread_rng();
458 ///
459 /// if let Some(left) = buffer.get_mut(0) {
460 /// rng.fill(left);
461 /// }
462 ///
463 /// if let Some(right) = buffer.get_mut(1) {
464 /// rng.fill(right);
465 /// }
466 /// ```
467 pub fn get_mut(&mut self, channel: usize) -> Option<&mut [T]> {
468 if channel < self.channels {
469 // Safety: We control the length of each channel so we can assert that
470 // it is both allocated and initialized up to `len`.
471 unsafe { Some(self.data.get_unchecked_mut(channel).as_mut(self.frames)) }
472 } else {
473 None
474 }
475 }
476
477 /// Get the given channel or initialize the buffer with the default value.
478 ///
479 /// If a channel that is out of bound is queried, the buffer will be empty.
480 ///
481 /// # Examples
482 ///
483 /// ```rust
484 /// use rand::Rng as _;
485 ///
486 /// let mut buffer = rotary::Dynamic::<f32>::new();
487 ///
488 /// buffer.resize(256);
489 ///
490 /// let mut rng = rand::thread_rng();
491 ///
492 /// rng.fill(buffer.get_or_default_mut(0));
493 /// rng.fill(buffer.get_or_default_mut(1));
494 ///
495 /// assert_eq!(buffer.channels(), 2);
496 /// ```
497 pub fn get_or_default_mut(&mut self, channel: usize) -> &mut [T]
498 where
499 T: Sample,
500 {
501 self.resize_channels(channel + 1);
502
503 // Safety: We initialized the given index just above and we know the
504 // trusted length.
505 unsafe { self.data.get_unchecked_mut(channel).as_mut(self.frames) }
506 }
507
508 /// Convert into a vector of vectors.
509 ///
510 /// This is provided for the [Dynamic] type because it's a very cheap
511 /// oepration due to its memory topology. No copying of the underlying
512 /// buffers is necessary.
513 ///
514 /// # Examples
515 ///
516 /// ```rust
517 /// let mut buffer = rotary::Dynamic::<f32>::new();
518 /// buffer.resize_channels(4);
519 /// buffer.resize(512);
520 ///
521 /// let expected = vec![0.0; 512];
522 ///
523 /// let buffers = buffer.into_vectors();
524 /// assert_eq!(buffers.len(), 4);
525 /// assert_eq!(buffers[0], &expected[..]);
526 /// assert_eq!(buffers[1], &expected[..]);
527 /// assert_eq!(buffers[2], &expected[..]);
528 /// assert_eq!(buffers[3], &expected[..]);
529 /// ```
530 pub fn into_vectors(self) -> Vec<Vec<T>> {
531 self.into_vectors_if(|_| true)
532 }
533
534 /// Convert into a vector of vectors using a condition.
535 ///
536 /// This is provided for the [Dynamic] type because it's a very cheap
537 /// oepration due to its memory topology. No copying of the underlying
538 /// buffers is necessary.
539 ///
540 /// Channels which does not match the condition will be filled with an empty
541 /// vector.
542 ///
543 /// # Examples
544 ///
545 /// ```rust
546 /// let mut buffer = rotary::Dynamic::<f32>::new();
547 /// buffer.resize_channels(4);
548 /// buffer.resize(512);
549 ///
550 /// let expected = vec![0.0; 512];
551 ///
552 /// let buffers = buffer.into_vectors_if(|n| n != 1);
553 /// assert_eq!(buffers.len(), 4);
554 /// assert_eq!(buffers[0], &expected[..]);
555 /// assert_eq!(buffers[1], &[][..]);
556 /// assert_eq!(buffers[2], &expected[..]);
557 /// assert_eq!(buffers[3], &expected[..]);
558 /// ```
559 pub fn into_vectors_if(self, mut condition: impl FnMut(usize) -> bool) -> Vec<Vec<T>> {
560 let mut this = mem::ManuallyDrop::new(self);
561 let mut vecs = Vec::with_capacity(this.channels);
562
563 let frames_cap = this.frames_cap;
564
565 for n in 0..this.channels {
566 // Safety: The capacity end lengths are trusted since they're part
567 // of the audio buffer.
568 unsafe {
569 let mut slice = this.data.read(n);
570
571 if condition(n) {
572 vecs.push(slice.into_vec(this.frames, frames_cap));
573 } else {
574 slice.drop_in_place(frames_cap);
575 vecs.push(Vec::new());
576 }
577 }
578 }
579
580 // Drop the tail of the channels capacity which is not in use.
581 for n in this.channels..this.channels_cap {
582 // Safety: The capacity end lengths are trusted since they're part
583 // of the audio buffer.
584 unsafe {
585 this.data.get_unchecked_mut(n).drop_in_place(frames_cap);
586 }
587 }
588
589 // Drop the backing vector for all channels.
590 //
591 // Safety: we trust the capacity provided here.
592 unsafe {
593 let cap = this.channels_cap;
594 this.data.drop_in_place(cap);
595 }
596
597 vecs
598 }
599}
600
601// Safety: dynamic is simply a container of T's, any Send/Sync properties are
602// inherited.
603unsafe impl<T> Send for Dynamic<T> where T: Send {}
604unsafe impl<T> Sync for Dynamic<T> where T: Sync {}
605
606/// Allocate an audio buffer from a fixed-size array.
607///
608/// See [dynamic!].
609impl<T, const F: usize, const C: usize> From<[[T; F]; C]> for Dynamic<T>
610where
611 T: Copy,
612{
613 #[inline]
614 fn from(channels: [[T; F]; C]) -> Self {
615 Self::from_array(channels)
616 }
617}
618
619impl<T> fmt::Debug for Dynamic<T>
620where
621 T: fmt::Debug,
622{
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 f.debug_list().entries(self.iter()).finish()
625 }
626}
627
628impl<T> cmp::PartialEq for Dynamic<T>
629where
630 T: cmp::PartialEq,
631{
632 fn eq(&self, other: &Self) -> bool {
633 self.iter().eq(other.iter())
634 }
635}
636
637impl<T> cmp::Eq for Dynamic<T> where T: cmp::Eq {}
638
639impl<T> cmp::PartialOrd for Dynamic<T>
640where
641 T: cmp::PartialOrd,
642{
643 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
644 self.iter().partial_cmp(other.iter())
645 }
646}
647
648impl<T> cmp::Ord for Dynamic<T>
649where
650 T: cmp::Ord,
651{
652 fn cmp(&self, other: &Self) -> cmp::Ordering {
653 self.iter().cmp(other.iter())
654 }
655}
656
657impl<T> hash::Hash for Dynamic<T>
658where
659 T: hash::Hash,
660{
661 fn hash<H: hash::Hasher>(&self, state: &mut H) {
662 for channel in self.iter() {
663 channel.hash(state);
664 }
665 }
666}
667
668impl<'a, T> IntoIterator for &'a Dynamic<T> {
669 type IntoIter = Iter<'a, T>;
670 type Item = <Self::IntoIter as Iterator>::Item;
671
672 fn into_iter(self) -> Self::IntoIter {
673 self.iter()
674 }
675}
676
677impl<'a, T> IntoIterator for &'a mut Dynamic<T> {
678 type IntoIter = IterMut<'a, T>;
679 type Item = <Self::IntoIter as Iterator>::Item;
680
681 fn into_iter(self) -> Self::IntoIter {
682 self.iter_mut()
683 }
684}
685
686impl<T> ops::Index<usize> for Dynamic<T> {
687 type Output = [T];
688
689 fn index(&self, index: usize) -> &Self::Output {
690 match self.get(index) {
691 Some(slice) => slice,
692 None => panic!("index `{}` is not a channel", index),
693 }
694 }
695}
696
697impl<T> ops::IndexMut<usize> for Dynamic<T> {
698 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
699 match self.get_mut(index) {
700 Some(slice) => slice,
701 None => panic!("index `{}` is not a channel", index,),
702 }
703 }
704}
705
706impl<T> Drop for Dynamic<T> {
707 fn drop(&mut self) {
708 for n in 0..self.channels_cap {
709 // Safety: We're being dropped, so there's no subsequent access to
710 // the current collection.
711 unsafe {
712 self.data
713 .get_unchecked_mut(n)
714 .drop_in_place(self.frames_cap);
715 }
716 }
717
718 // Safety: We trust the length of the underlying array.
719 unsafe {
720 self.data.drop_in_place(self.channels_cap);
721 }
722 }
723}
724
725impl<T> ExactSizeBuf for Dynamic<T> {
726 fn frames(&self) -> usize {
727 self.frames
728 }
729}
730
731impl<T> Buf<T> for Dynamic<T> {
732 fn frames_hint(&self) -> Option<usize> {
733 Some(self.frames)
734 }
735
736 fn channels(&self) -> usize {
737 self.channels
738 }
739
740 fn channel(&self, channel: usize) -> Channel<'_, T> {
741 Channel::linear(&self[channel])
742 }
743}
744
745impl<T> ResizableBuf for Dynamic<T>
746where
747 T: Sample,
748{
749 fn resize(&mut self, frames: usize) {
750 Self::resize(self, frames);
751 }
752
753 fn resize_topology(&mut self, channels: usize, frames: usize) {
754 Self::resize(self, frames);
755 self.resize_channels(channels);
756 }
757}
758
759impl<T> BufMut<T> for Dynamic<T> {
760 fn channel_mut(&mut self, channel: usize) -> ChannelMut<'_, T> {
761 ChannelMut::linear(&mut self[channel])
762 }
763}
764
765/// A raw slice.
766#[repr(transparent)]
767struct RawSlice<T> {
768 data: ptr::NonNull<T>,
769}
770
771impl<T> RawSlice<T> {
772 const MIN_NON_ZERO_CAP: usize = if mem::size_of::<T>() == 1 {
773 8
774 } else if mem::size_of::<T>() <= 256 {
775 4
776 } else {
777 1
778 };
779
780 /// Calculate the next capacity.
781 fn next_cap(from: usize, to: usize) -> usize {
782 let to = usize::max(from * 2, to);
783 let to = usize::max(Self::MIN_NON_ZERO_CAP, to);
784 to
785 }
786
787 /// Construct an empty raw slice.
788 fn empty() -> Self {
789 Self {
790 data: unsafe { ptr::NonNull::new_unchecked(Vec::new().as_mut_ptr()) },
791 }
792 }
793
794 /// Construct a new raw slice with the given capacity leaving the memory
795 /// uninitialized.
796 fn uninit(cap: usize) -> Self {
797 // Safety: We're just allocating the vector so we knows it's correctly
798 // sized and aligned.
799 unsafe {
800 let data = Vec::with_capacity(cap);
801 let data = ptr::NonNull::new_unchecked(mem::ManuallyDrop::new(data).as_mut_ptr());
802 Self { data }
803 }
804 }
805
806 /// Construct a new raw slice with the given capacity.
807 fn zeroed(cap: usize) -> Self
808 where
809 T: Sample,
810 {
811 // Safety: the type constrain of `T` guarantees that an all-zeros bit
812 // pattern is legal.
813 unsafe {
814 let mut data = Vec::with_capacity(cap);
815 ptr::write_bytes(data.as_mut_ptr(), 0, cap);
816 let data = ptr::NonNull::new_unchecked(mem::ManuallyDrop::new(data).as_mut_ptr());
817 Self { data }
818 }
819 }
820
821 /// Resize the slice in place by reserving `additional` more elements in it.
822 ///
823 /// # Safety
824 ///
825 /// The provided `len` must watch the length for which it was allocated.
826 /// This will change the underlying allocation, so subsequent calls must
827 /// provide the new length of `len + additional`.
828 unsafe fn reserve_zeroed(&mut self, len: usize, additional: usize)
829 where
830 T: Sample,
831 {
832 // Note: we need to provide `len` for the `reserve_exact` calculation to
833 // below to be correct.
834 let mut channel = Vec::from_raw_parts(self.data.as_ptr(), len, len);
835 channel.reserve_exact(additional);
836 // Safety: the type constrain of `T` guarantees that an all-zeros bit pattern is legal.
837 ptr::write_bytes(channel.as_mut_ptr().add(len), 0, additional);
838 self.data = ptr::NonNull::new_unchecked(mem::ManuallyDrop::new(channel).as_mut_ptr());
839 }
840
841 /// Resize the slice in place by reserving `additional` more elements in it
842 /// without initializing them.
843 ///
844 /// # Safety
845 ///
846 /// The provided `len` must watch the length for which it was allocated.
847 /// This will change the underlying allocation, so subsequent calls must
848 /// provide the new length of `len + additional`.
849 unsafe fn reserve_uninit(&mut self, len: usize, additional: usize) {
850 // Note: we need to provide `len` for the `reserve_exact` calculation to
851 // below to be correct.
852 let mut channel = Vec::from_raw_parts(self.data.as_ptr(), len, len);
853 channel.reserve_exact(additional);
854 self.data = ptr::NonNull::new_unchecked(mem::ManuallyDrop::new(channel).as_mut_ptr());
855 }
856
857 /// Get a reference to the value at the given offset.
858 ///
859 /// # Safety
860 ///
861 /// The caller is resonsible for asserting that the value at the given
862 /// location has an initialized bit pattern and is not out of bounds.
863 unsafe fn get_unchecked(&self, n: usize) -> &T {
864 &*self.data.as_ptr().add(n)
865 }
866
867 /// Get a mutable reference to the value at the given offset.
868 ///
869 /// # Safety
870 ///
871 /// The caller is resonsible for asserting that the value at the given
872 /// location has an initialized bit pattern and is not out of bounds.
873 unsafe fn get_unchecked_mut(&mut self, n: usize) -> &mut T {
874 &mut *self.data.as_ptr().add(n)
875 }
876
877 /// Read the value at the given offset.
878 ///
879 /// # Safety
880 ///
881 /// The caller is resonsible for asserting that the value at the given
882 /// location has an initialized bit pattern and is not out of bounds.
883 unsafe fn read(&self, n: usize) -> T {
884 ptr::read(self.data.as_ptr().add(n))
885 }
886
887 /// Write a value at the given offset.
888 ///
889 /// # Safety
890 ///
891 /// The caller is responsible for asserting that the written to offset is
892 /// not out of bounds.
893 unsafe fn write(&mut self, n: usize, value: T) {
894 ptr::write(self.data.as_ptr().add(n), value)
895 }
896
897 /// Get the raw base pointer of the slice.
898 fn as_ptr(self) -> *mut T {
899 self.data.as_ptr()
900 }
901
902 /// Get the raw slice as a slice.
903 ///
904 /// # Safety
905 ///
906 /// The incoming len must represent a valid slice of initialized data.
907 /// The produced lifetime must be bounded to something valid!
908 unsafe fn as_ref<'a>(self, len: usize) -> &'a [T] {
909 slice::from_raw_parts(self.data.as_ptr() as *const _, len)
910 }
911
912 /// Get the raw slice as a mutable slice.
913 ///
914 /// # Safety
915 ///
916 /// The incoming len must represent a valid slice of initialized data.
917 /// The produced lifetime must be bounded to something valid!
918 unsafe fn as_mut<'a>(self, len: usize) -> &'a mut [T] {
919 slice::from_raw_parts_mut(self.data.as_ptr(), len)
920 }
921
922 /// Drop the slice in place.
923 ///
924 /// # Safety
925 ///
926 /// The provided `len` must match the allocated length of the raw slice.
927 ///
928 /// After calling drop, the slice must not be used every again because the
929 /// data it is pointing to have been dropped.
930 unsafe fn drop_in_place(&mut self, len: usize) {
931 let _ = Vec::from_raw_parts(self.data.as_ptr(), 0, len);
932 }
933
934 /// Convert into a vector.
935 ///
936 /// # Safety
937 ///
938 /// The provided `len` and `cap` must match the ones used when allocating
939 /// the slice.
940 ///
941 /// The underlying slices must be dropped and forgotten after this
942 /// operation.
943 pub(crate) unsafe fn into_vec(self, len: usize, cap: usize) -> Vec<T> {
944 Vec::from_raw_parts(self.data.as_ptr(), len, cap)
945 }
946}
947
948// Note: no auto impl cause of `T`.
949impl<T> Clone for RawSlice<T> {
950 #[inline]
951 fn clone(&self) -> Self {
952 *self
953 }
954}
955impl<T> Copy for RawSlice<T> {}