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
use bytecodec::{ByteCount, Decode, Eos, ErrorKind, Result};
use std::fmt;

use util;

/// HTTP method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Method<'a>(&'a str);
impl<'a> Method<'a> {
    /// Makes a new `Method` instance.
    ///
    /// # Errors
    ///
    /// `method` must be a "token" defined in [RFC 7230].
    /// Otherwise it will return an `ErrorKind::InvalidInput` error.
    ///
    /// [RFC 7230]: https://tools.ietf.org/html/rfc7230
    pub fn new(method: &'a str) -> Result<Self> {
        track_assert!(method.bytes().all(util::is_tchar), ErrorKind::InvalidInput);
        Ok(Method(method))
    }

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

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

#[derive(Debug, Default)]
pub(crate) struct MethodDecoder {
    size: usize,
    idle: bool,
}
impl Decode for MethodDecoder {
    type Item = usize;

    fn decode(&mut self, buf: &[u8], eos: Eos) -> Result<usize> {
        if self.idle {
            Ok(0)
        } else if let Some(n) = buf.iter().position(|b| !util::is_tchar(*b)) {
            track_assert_eq!(buf[n] as char, ' ', ErrorKind::InvalidInput);
            self.size += n;
            self.idle = true;
            Ok(n + 1)
        } else {
            track_assert!(!eos.is_reached(), ErrorKind::UnexpectedEos);
            self.size += buf.len();
            Ok(buf.len())
        }
    }

    fn finish_decoding(&mut self) -> Result<Self::Item> {
        track_assert!(self.idle, ErrorKind::IncompleteDecoding);
        let size = self.size;
        self.idle = false;
        self.size = 0;
        Ok(size)
    }

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

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

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

    use super::*;

    #[test]
    fn method_decoder_works() {
        let mut decoder = MethodDecoder::default();
        let item = track_try_unwrap!(decoder.decode_exact(b"GET / HTTP/1.1".as_ref()));
        assert_eq!(item, 3);

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