rotary/
wrap.rs

1//! Wrap an external type to implement [Buf][crate::Buf] and
2//! [BufMut][crate::BufMut].
3
4mod interleaved;
5pub use self::interleaved::Interleaved;
6
7mod sequential;
8pub use self::sequential::Sequential;
9
10/// Wrap a `value` as an interleaved buffer with the given number of channels.
11///
12/// Certain interleaved buffers can be used conveniently as implementors of
13/// [ReadBuf][crate::ReadBuf] and [WriteBuf][crate::WriteBuf], due to the
14/// convenient nature of the buffer living linearly in memory.
15///
16/// * `&[T]` - implements [ReadBuf][crate::ReadBuf].
17/// * `&mut [T]` - implements [WriteBuf][crate::WriteBuf].
18///
19/// # Example using a buffer for linear I/O
20///
21/// ```rust
22/// use rotary::{wrap, io};
23/// use rotary::ReadBuf as _;
24///
25/// let mut read_from = wrap::interleaved(&[0, 1, 2, 4, 5, 6, 7, 8][..], 2);
26/// let mut write_to = io::Write::new(rotary::sequential![[0i16; 4]; 2]);
27///
28/// assert!(read_from.has_remaining());
29/// io::copy_remaining(&mut read_from, &mut write_to);
30/// assert!(!read_from.has_remaining());
31///
32/// assert_eq! {
33///     write_to.as_ref().as_slice(),
34///     &[0, 2, 5, 7, 1, 4, 6, 8],
35/// };
36/// ```
37///
38/// Or with a mutable slice for writing.
39///
40/// ```rust
41/// use rotary::{wrap, io};
42/// use rotary::WriteBuf as _;
43///
44/// let mut vec = vec![0, 1, 2, 4, 5, 6, 7, 8];
45///
46/// let mut read_from = io::Read::new(rotary::sequential![[0i16, 1i16, 2i16, 3i16]; 2]);
47/// let mut write_to = wrap::interleaved(&mut vec[..], 2);
48///
49/// assert!(write_to.has_remaining_mut());
50/// io::copy_remaining(&mut read_from, &mut write_to);
51/// assert!(!write_to.has_remaining_mut());
52///
53/// assert_eq! {
54///     &vec[..],
55///     &[0, 0, 1, 1, 2, 2, 3, 3],
56/// };
57/// ```
58pub fn interleaved<T>(value: T, channels: usize) -> Interleaved<T> {
59    Interleaved::new(value, channels)
60}
61
62/// Wrap a `value` as a sequential buffer with the given number of frames. The
63/// length of the buffer determines the number of channels it has.
64///
65/// Unlike [interleaved][interleaved()], wrapped sequential buffers cannot be
66/// used as implementations of [ReadBuf][crate::ReadBuf] or
67/// [WriteBuf][crate::WriteBuf].
68///
69/// You can instead use the [Read][crate::io::Read] or [Write][crate::io::Write]
70/// adapters available to accomplish this.
71pub fn sequential<T>(value: T, frames: usize) -> Sequential<T> {
72    Sequential::new(value, frames)
73}