Skip to content

Commit dbc1983

Browse files
committed
Add Method::from_static
Allows creating constant `Method` instances, e.g.: const PROPFIND: Method = Method::from_static(b"PROPFIND"); Fixes: hyperium#587
1 parent 24bbec2 commit dbc1983

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/method.rs

+46
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,18 @@ impl Method {
136136
}
137137
}
138138

139+
/// Convert static bytes into a `Method`.
140+
///
141+
/// The method name can only be up to 15 bytes long.
142+
///
143+
/// # Panics
144+
///
145+
/// If the input bytes are not a valid method name.
146+
pub const fn from_static(src: &'static [u8]) -> Method {
147+
let inline = InlineExtension::from_static(src);
148+
Method(ExtensionInline(inline))
149+
}
150+
139151
fn extension_inline(src: &[u8]) -> Result<Method, InvalidMethod> {
140152
let inline = InlineExtension::new(src)?;
141153

@@ -335,6 +347,29 @@ mod extension {
335347
Ok(InlineExtension(data, src.len() as u8))
336348
}
337349

350+
/// Convert static bytes into an `InlineExtension`.
351+
///
352+
/// Only the first 15 characters are used.
353+
///
354+
/// # Panics
355+
///
356+
/// If the input bytes are not a valid method name.
357+
pub const fn from_static(src: &'static [u8]) -> InlineExtension {
358+
let mut i = 0;
359+
let mut dst = [0u8;15];
360+
while i < src.len() {
361+
let byte = src[i] ;
362+
let v = METHOD_CHARS[byte as usize];
363+
if v == 0 {
364+
panic!("Invalid byte for method name.");
365+
}
366+
dst[i] = byte;
367+
i += 1;
368+
}
369+
370+
InlineExtension(dst, src.len() as u8)
371+
}
372+
338373
pub fn as_str(&self) -> &str {
339374
let InlineExtension(ref data, len) = self;
340375
// Safety: the invariant of InlineExtension ensures that the first
@@ -440,6 +475,17 @@ mod test {
440475
assert_eq!(Method::GET, &Method::GET);
441476
}
442477

478+
#[test]
479+
fn test_from_static() {
480+
assert_eq!(Method::from_static(b"PROPFIND"), Method::from_bytes(b"PROPFIND").unwrap());
481+
}
482+
483+
#[test]
484+
#[should_panic]
485+
fn test_from_static_bad() {
486+
Method::from_static(b"\0");
487+
}
488+
443489
#[test]
444490
fn test_invalid_method() {
445491
assert!(Method::from_str("").is_err());

0 commit comments

Comments
 (0)