Skip to content

Commit 5dc2a6b

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

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/method.rs

+60
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,31 @@ 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. Any remaining bytes are ignored.
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+
match src {
148+
b"OPTIONS" => Method::OPTIONS,
149+
b"GET" => Method::GET,
150+
b"POST" => Method::POST,
151+
b"PUT" => Method::PUT,
152+
b"DELETE" => Method::DELETE,
153+
b"HEAD" => Method::HEAD,
154+
b"TRACE" => Method::TRACE,
155+
b"CONNECT" => Method::CONNECT,
156+
b"PATCH" => Method::PATCH,
157+
_ => {
158+
let inline = InlineExtension::from_static(src);
159+
Method(ExtensionInline(inline))
160+
}
161+
}
162+
}
163+
139164
fn extension_inline(src: &[u8]) -> Result<Method, InvalidMethod> {
140165
let inline = InlineExtension::new(src)?;
141166

@@ -335,6 +360,29 @@ mod extension {
335360
Ok(InlineExtension(data, src.len() as u8))
336361
}
337362

363+
/// Convert static bytes into an `InlineExtension`.
364+
///
365+
/// Only the first 15 characters are used. Any remaining bytes are ignored.
366+
///
367+
/// # Panics
368+
///
369+
/// If the input bytes are not a valid method name.
370+
pub const fn from_static(src: &'static [u8]) -> InlineExtension {
371+
let mut i = 0;
372+
let mut dst = [0u8;15];
373+
while i < src.len() {
374+
let byte = src[i] ;
375+
let v = METHOD_CHARS[byte as usize];
376+
if v == 0 {
377+
panic!("Invalid byte for method name.");
378+
}
379+
dst[i] = byte;
380+
i += 1;
381+
}
382+
383+
InlineExtension(dst, src.len() as u8)
384+
}
385+
338386
pub fn as_str(&self) -> &str {
339387
let InlineExtension(ref data, len) = self;
340388
// Safety: the invariant of InlineExtension ensures that the first
@@ -440,6 +488,18 @@ mod test {
440488
assert_eq!(Method::GET, &Method::GET);
441489
}
442490

491+
#[test]
492+
fn test_from_static() {
493+
assert_eq!(Method::from_static(b"PROPFIND"), Method::from_bytes(b"PROPFIND").unwrap());
494+
assert_eq!(Method::from_static(b"GET"), Method::from_bytes(b"GET").unwrap());
495+
}
496+
497+
#[test]
498+
#[should_panic]
499+
fn test_from_static_bad() {
500+
Method::from_static(b"\0");
501+
}
502+
443503
#[test]
444504
fn test_invalid_method() {
445505
assert!(Method::from_str("").is_err());

0 commit comments

Comments
 (0)