Skip to content

Commit

Permalink
Add Method::from_static
Browse files Browse the repository at this point in the history
Allows creating constant `Method` instances, e.g.:

    const PROPFIND: Method = Method::from_static(b"PROPFIND");

Fixes: hyperium#587
  • Loading branch information
WhyNotHugo committed Mar 27, 2023
1 parent 24bbec2 commit dbc1983
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/method.rs
Expand Up @@ -136,6 +136,18 @@ impl Method {
}
}

/// Convert static bytes into a `Method`.
///
/// The method name can only be up to 15 bytes long.
///
/// # Panics
///
/// If the input bytes are not a valid method name.
pub const fn from_static(src: &'static [u8]) -> Method {
let inline = InlineExtension::from_static(src);
Method(ExtensionInline(inline))
}

fn extension_inline(src: &[u8]) -> Result<Method, InvalidMethod> {
let inline = InlineExtension::new(src)?;

Expand Down Expand Up @@ -335,6 +347,29 @@ mod extension {
Ok(InlineExtension(data, src.len() as u8))
}

/// Convert static bytes into an `InlineExtension`.
///
/// Only the first 15 characters are used.
///
/// # Panics
///
/// If the input bytes are not a valid method name.
pub const fn from_static(src: &'static [u8]) -> InlineExtension {
let mut i = 0;
let mut dst = [0u8;15];
while i < src.len() {
let byte = src[i] ;
let v = METHOD_CHARS[byte as usize];
if v == 0 {
panic!("Invalid byte for method name.");
}
dst[i] = byte;
i += 1;
}

InlineExtension(dst, src.len() as u8)
}

pub fn as_str(&self) -> &str {
let InlineExtension(ref data, len) = self;
// Safety: the invariant of InlineExtension ensures that the first
Expand Down Expand Up @@ -440,6 +475,17 @@ mod test {
assert_eq!(Method::GET, &Method::GET);
}

#[test]
fn test_from_static() {
assert_eq!(Method::from_static(b"PROPFIND"), Method::from_bytes(b"PROPFIND").unwrap());
}

#[test]
#[should_panic]
fn test_from_static_bad() {
Method::from_static(b"\0");
}

#[test]
fn test_invalid_method() {
assert!(Method::from_str("").is_err());
Expand Down

0 comments on commit dbc1983

Please sign in to comment.