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
use bytecodec::bytes::CopyableBytesDecoder;
use bytecodec::{ByteCount, Decode, Eos, Error, ErrorKind, Result};
use std;
use std::fmt;
use std::str;
use trackable::error::ErrorKindExt;

use util;

/// Status code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StatusCode(u16);
impl StatusCode {
    /// Makes a new `StatusCode` instance.
    ///
    /// # Errors
    ///
    /// `code` must be a integer between 200 and 999.
    /// Otherwise it will return an `ErrorKind::InvalidInput` error.
    pub fn new(code: u16) -> Result<Self> {
        track_assert!(100 <= code && code < 1000, ErrorKind::InvalidInput; code);
        Ok(StatusCode(code))
    }

    /// Makes a new `StatusCode` instance without any validation.
    pub unsafe fn new_unchecked(code: u16) -> Self {
        StatusCode(code)
    }

    /// Returns the status code as an `u16` value.
    pub fn as_u16(&self) -> u16 {
        self.0
    }

    pub(crate) fn as_bytes(&self) -> [u8; 3] {
        let a = ((self.0 / 100) % 10) as u8;
        let b = ((self.0 / 10) % 10) as u8;
        let c = (self.0 % 10) as u8;
        [a + b'0', b + b'0', c + b'0']
    }
}
impl fmt::Display for StatusCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Debug, Default)]
pub struct StatusCodeDecoder {
    code: CopyableBytesDecoder<[u8; 3]>,
    idle: bool,
}
impl Decode for StatusCodeDecoder {
    type Item = StatusCode;

    fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
        let mut offset = 0;
        bytecodec_try_decode!(self.code, offset, buf, eos);
        if offset < buf.len() {
            track_assert_eq!(buf[offset] as char, ' ', ErrorKind::InvalidInput);
            self.idle = true;
            return Ok(offset + 1);
        }
        track_assert!(!eos.is_reached(), ErrorKind::UnexpectedEos);
        Ok(offset)
    }

    fn finish_decoding(&mut self) -> Result<Self::Item> {
        let code = track!(self.code.finish_decoding())?;
        let code = track!(str::from_utf8(&code).map_err(into_invalid_input); code)?;
        let code = track!(code.parse().map_err(into_invalid_input); code)?;
        let code = track!(StatusCode::new(code))?;
        self.idle = false;
        Ok(code)
    }

    fn requiring_bytes(&self) -> ByteCount {
        if self.idle {
            ByteCount::Finite(0)
        } else {
            ByteCount::Finite(1).add_for_decoding(self.code.requiring_bytes())
        }
    }

    fn is_idle(&self) -> bool {
        self.idle
    }
}

/// Reason phrase of a response status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ReasonPhrase<'a>(&'a str);
impl<'a> ReasonPhrase<'a> {
    /// Makes a new `ReasonPhrase` instance.
    ///
    /// # Errors
    ///
    /// `phrase` must be composed of whitespaces (i.e., " " or "\t") or
    /// "VCHAR" characters that defined in [RFC 7230].
    /// If it contains any other characters,
    /// an `ErrorKind::InvalidInput` error will be returned.
    ///
    /// [RFC 7230]: https://tools.ietf.org/html/rfc7230
    pub fn new(phrase: &'a str) -> Result<Self> {
        track_assert!(phrase.bytes().all(is_phrase_char), ErrorKind::InvalidInput);
        Ok(ReasonPhrase(phrase))
    }

    /// Makes a new `ReasonPhrase` instance without any validation.
    pub unsafe fn new_unchecked(phrase: &'a str) -> Self {
        ReasonPhrase(phrase)
    }

    /// Returns a reference to the phrase string.
    pub fn as_str(&self) -> &'a str {
        self.0
    }
}
impl<'a> AsRef<str> for ReasonPhrase<'a> {
    fn as_ref(&self) -> &str {
        self.0
    }
}
impl<'a> fmt::Display for ReasonPhrase<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[derive(Debug, Default)]
pub struct ReasonPhraseDecoder {
    size: usize,
    remaining: ByteCount,
}
impl Decode for ReasonPhraseDecoder {
    type Item = usize;

    fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
        if self.is_idle() {
            return Ok(0);
        }

        let mut offset = 0;
        if self.remaining == ByteCount::Unknown {
            if let Some(n) = buf.iter().position(|b| !is_phrase_char(*b)) {
                track_assert_eq!(buf[n] as char, '\r', ErrorKind::InvalidInput);
                self.size += n;
                self.remaining = ByteCount::Finite(1);
                offset = n + 1;
            } else {
                self.size += buf.len();
                offset = buf.len();
            }
        }
        if self.remaining == ByteCount::Finite(1) && offset < buf.len() {
            track_assert_eq!(buf[offset] as char, '\n', ErrorKind::InvalidInput);
            self.remaining = ByteCount::Finite(0);
            Ok(offset + 1)
        } else {
            track_assert!(!eos.is_reached(), ErrorKind::UnexpectedEos);
            Ok(offset)
        }
    }

    fn finish_decoding(&mut self) -> Result<Self::Item> {
        track_assert_eq!(
            self.remaining,
            ByteCount::Finite(0),
            ErrorKind::IncompleteDecoding
        );
        let size = self.size;
        self.size = 0;
        self.remaining = ByteCount::Unknown;
        Ok(size)
    }

    fn requiring_bytes(&self) -> ByteCount {
        self.remaining
    }

    fn is_idle(&self) -> bool {
        self.remaining == ByteCount::Finite(0)
    }
}

fn is_phrase_char(b: u8) -> bool {
    util::is_vchar(b) || util::is_whitespace(b)
}

#[cfg(test)]
mod test {
    use bytecodec::io::IoDecodeExt;
    use bytecodec::ErrorKind;

    use super::*;

    #[test]
    fn status_code_decoder_works() {
        let mut decoder = StatusCodeDecoder::default();
        let item = track_try_unwrap!(decoder.decode_exact(b"200 OK\r\n".as_ref()));
        assert_eq!(item, StatusCode(200));

        assert_eq!(
            decoder
                .decode_exact(b"90 \r\n".as_ref())
                .err()
                .map(|e| *e.kind()),
            Some(ErrorKind::InvalidInput)
        );

        let mut decoder = StatusCodeDecoder::default();
        assert_eq!(
            decoder
                .decode_exact(b"1000 ".as_ref())
                .err()
                .map(|e| *e.kind()),
            Some(ErrorKind::InvalidInput)
        );

        let mut decoder = StatusCodeDecoder::default();
        assert_eq!(
            decoder
                .decode_exact(b"10a ".as_ref())
                .err()
                .map(|e| *e.kind()),
            Some(ErrorKind::InvalidInput)
        );

        let mut decoder = StatusCodeDecoder::default();
        assert_eq!(
            decoder
                .decode_exact(b"200\r\n".as_ref())
                .err()
                .map(|e| *e.kind()),
            Some(ErrorKind::InvalidInput)
        );

        let mut decoder = StatusCodeDecoder::default();
        assert_eq!(
            decoder
                .decode_exact(b"200".as_ref())
                .err()
                .map(|e| *e.kind()),
            Some(ErrorKind::UnexpectedEos)
        );
    }

    #[test]
    fn reason_phrase_decoder_works() {
        let mut decoder = ReasonPhraseDecoder::default();
        let item = track_try_unwrap!(decoder.decode_exact(b"Not Found\r\n".as_ref()));
        assert_eq!(item, 9);

        assert_eq!(
            decoder
                .decode_exact(b"Not\rFound".as_ref())
                .err()
                .map(|e| *e.kind()),
            Some(ErrorKind::InvalidInput)
        )
    }
}

fn into_invalid_input<E: std::error::Error + Send + Sync + 'static>(e: E) -> Error {
    ErrorKind::InvalidInput.cause(e).into()
}