Skip to content

Instantly share code, notes, and snippets.

@danielhenrymantilla
Last active July 12, 2019 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielhenrymantilla/a0dbb5ba76302d4e8dcae75d2dc7274d to your computer and use it in GitHub Desktop.
Save danielhenrymantilla/a0dbb5ba76302d4e8dcae75d2dc7274d to your computer and use it in GitHub Desktop.
Replace match by static map
use ::phf::{
phf_map,
Map,
};
#[derive(
Debug,
Clone, Copy,
)]
enum StandardHeader {
Te,
Age,
Via,
Dnt,
// ...
}
#[derive(Debug)]
pub
struct HdrName<'buf> {
inner: Repr<MaybeLower<'buf>>,
// ...
}
impl<'buf> HdrName<'buf> {
#[inline]
fn custom (buf: &'buf [u8], lower: bool) -> Self
{
Self {
inner: Repr::Custom(MaybeLower {
buf,
lower,
}),
}
}
}
#[derive(Debug)]
enum Repr<T> {
Standard(StandardHeader),
Custom(T),
}
#[derive(Debug)]
struct MaybeLower<'buf> {
buf: &'buf [u8],
lower: bool,
}
#[derive(
Debug,
Default,
)]
pub
struct InvalidHeaderName {
_priv: (),
}
const MAX_HEADER_NAME_LEN: usize = 1 << 16;
fn parse_hdr<'bytes> (
data: &'bytes [u8],
buf: &'bytes [u8; 64],
table: &'_ [u8; 256],
) -> Result<
HdrName<'bytes>,
InvalidHeaderName,
>
{
let len = data.len();
assert!(
len < MAX_HEADER_NAME_LEN,
"header name too long: max length is {}",
MAX_HEADER_NAME_LEN,
);
Ok(match len {
| 0 => {
return Err(InvalidHeaderName::default());
},
| len if len > 64 => {
HdrName::custom(data, false)
},
| _ => {
use self::StandardHeader::*;
static STANDARD_HEADERS: Map<&[u8], StandardHeader> = phf_map! {
b"te" => Te,
b"age" => Age,
b"via" => Via,
b"dnt" => Dnt,
// ...
};
let buf = &buf[.. len];
match STANDARD_HEADERS.get(buf) {
| Some(&standard_header) => {
standard_header.into()
},
| None => {
if buf.contains(&b'\0') {
return Err(InvalidHeaderName::default());
} else {
HdrName::custom(buf, true)
}
},
}
},
})
}
impl<'buf> From<StandardHeader> for HdrName<'buf> {
#[inline]
fn from (hdr: StandardHeader) -> HdrName<'buf>
{
HdrName {
inner: Repr::Standard(hdr),
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment