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
//! Reading and writing sequentially from buffers.
//!
//! This is called buffered I/O, and allow buffers to support sequential reading
//! and writing to and from buffer.

use crate::buf::Buf;
use crate::translate::Translate;

mod utils;

mod read;
pub use self::read::Read;

mod write;
pub use self::write::Write;

mod read_write;
pub use self::read_write::ReadWrite;

/// A buffer that can keep track of how much has been read from it.
pub trait ReadBuf {
    /// Test if this buffer has remaining frames.
    fn has_remaining(&self) -> bool {
        self.remaining() > 0
    }

    /// The number of frames remaining in the readable buffer.
    fn remaining(&self) -> usize;

    /// Advance the read number of frames by `n`.
    fn advance(&mut self, n: usize);
}

impl<B> ReadBuf for &'_ mut B
where
    B: ReadBuf,
{
    fn has_remaining(&self) -> bool {
        (**self).has_remaining()
    }

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

    fn advance(&mut self, n: usize) {
        (**self).advance(n);
    }
}

/// A buffer that can be written to.
pub trait WriteBuf<T> {
    /// Test if this buffer has remaining mutable frames.
    fn has_remaining_mut(&self) -> bool {
        self.remaining_mut() > 0
    }

    /// Remaining number of frames that can be written.
    fn remaining_mut(&self) -> usize;

    /// Read frames from the given read buffer into this buffer.
    ///
    /// Advances the read from buffer by the number of frames read through
    /// [Read::advance].
    fn copy<I>(&mut self, buf: I)
    where
        I: ReadBuf + Buf<T>,
        T: Copy;

    /// Read translated frames from the given read buffer into this buffer.
    ///
    /// Advances the read from buffer by the number of frames read through
    /// [Read::advance].
    fn translate<I, U>(&mut self, buf: I)
    where
        T: Translate<U>,
        I: ReadBuf + Buf<U>,
        U: Copy;
}