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
//! Monolithic encoder and decoder.
use std::io::{self, Read, Write};

use bytes::BytesEncoder;
use {ByteCount, Decode, Encode, Eos, ErrorKind, Result};

/// This trait allows for decoding items monolithically from a source byte stream.
///
/// Although this has less flexibility than `Decode` trait, it has the merit of being easy to implement.
pub trait MonolithicDecode {
    /// The type of items to be monolithically decoded.
    type Item;

    /// Decodes an item from the given reader.
    fn monolithic_decode<R: Read>(&self, reader: R) -> Result<Self::Item>;
}

/// Monolithic decoder that implements `Decode` trait.
#[derive(Debug, Default)]
pub struct MonolithicDecoder<D> {
    inner: D,
    buf: Vec<u8>,
}
impl<D: MonolithicDecode> MonolithicDecoder<D> {
    /// Makes a new `MonolithicDecoder` instance.
    pub fn new(inner: D) -> Self {
        MonolithicDecoder {
            inner,
            buf: Vec::new(),
        }
    }

    /// Returns a reference to the inner decoder.
    pub fn inner_ref(&self) -> &D {
        &self.inner
    }

    /// Returns a mutable reference to the inner decoder.
    pub fn inner_mut(&mut self) -> &mut D {
        &mut self.inner
    }

    /// Takes ownership of `MonolithicDecoder` and returns the inner decoder.
    pub fn into_inner(self) -> D {
        self.inner
    }
}
impl<D: MonolithicDecode> Decode for MonolithicDecoder<D> {
    type Item = D::Item;

    fn decode(&mut self, mut buf: &[u8], eos: Eos) -> Result<(usize, Option<Self::Item>)> {
        if eos.is_reached() {
            let original_len = buf.len();
            let item = track!(
                self.inner.monolithic_decode(self.buf.as_slice().chain(buf.by_ref()));
                original_len, self.buf.len(), buf.len(), eos
            )?;
            self.buf.clear();
            Ok((original_len - buf.len(), Some(item)))
        } else {
            self.buf.extend_from_slice(buf);
            Ok((buf.len(), None))
        }
    }

    fn requiring_bytes(&self) -> ByteCount {
        ByteCount::Unknown
    }
}

/// This trait allows for encoding items monolithically to a destination byte stream.
///
/// Although this has less flexibility than `Encode` trait, it has the merit of being easy to implement.
pub trait MonolithicEncode {
    /// The type of items to be monolithically encoded.
    type Item;

    /// Encodes the item and writes the encoded bytes to the given writer.
    fn monolithic_encode<W: Write>(&self, item: &Self::Item, writer: W) -> Result<()>;
}

/// Monolithic encoder that implements `Encode` trait.
#[derive(Debug, Default)]
pub struct MonolithicEncoder<E: MonolithicEncode> {
    inner: E,
    item: Option<E::Item>,
    buf: BytesEncoder<Vec<u8>>,
}
impl<E: MonolithicEncode> MonolithicEncoder<E> {
    /// Makes a new `MonolithicEncoder` instance.
    pub fn new(inner: E) -> Self {
        MonolithicEncoder {
            inner,
            item: None,
            buf: BytesEncoder::new(),
        }
    }

    /// Returns a reference to the inner encoder.
    pub fn inner_ref(&self) -> &E {
        &self.inner
    }

    /// Returns a mutable reference to the inner encoder.
    pub fn inner_mut(&mut self) -> &mut E {
        &mut self.inner
    }

    /// Takes ownership of `MonolithicEncoder` and returns the inner encoder.
    pub fn into_inner(self) -> E {
        self.inner
    }
}
impl<E: MonolithicEncode> Encode for MonolithicEncoder<E> {
    type Item = E::Item;

    fn encode(&mut self, mut buf: &mut [u8], eos: Eos) -> Result<usize> {
        if let Some(item) = self.item.take() {
            let mut extra = Vec::new();
            let original_len = buf.len();
            {
                let writer = WriterChain::new(&mut buf, &mut extra);
                track!(self.inner.monolithic_encode(&item, writer))?;
            }
            if extra.is_empty() {
                Ok(original_len - buf.len())
            } else {
                track!(self.buf.start_encoding(extra))?;
                Ok(original_len)
            }
        } else {
            track!(self.buf.encode(buf, eos))
        }
    }

    fn start_encoding(&mut self, item: Self::Item) -> Result<()> {
        track_assert!(self.is_idle(), ErrorKind::EncoderFull);
        self.item = Some(item);
        Ok(())
    }

    fn is_idle(&self) -> bool {
        self.item.is_none() && self.buf.is_idle()
    }

    fn requiring_bytes(&self) -> ByteCount {
        if self.is_idle() {
            ByteCount::Finite(0)
        } else if self.item.is_some() {
            ByteCount::Unknown
        } else {
            self.buf.requiring_bytes()
        }
    }
}

#[derive(Debug)]
struct WriterChain<A, B> {
    a: A,
    b: B,
}
impl<A, B> WriterChain<A, B> {
    fn new(a: A, b: B) -> Self {
        WriterChain { a, b }
    }
}
impl<A: Write, B: Write> Write for WriterChain<A, B> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self.a.write(buf)? {
            0 => self.b.write(buf),
            n => Ok(n),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}