Last active
May 16, 2017 19:04
-
-
Save mmstick/bf5e23c6d81e34274093300894a370bd to your computer and use it in GitHub Desktop.
Rocket structure for attaining the values from Accept-Encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use rocket::request::{FromRequest, Request}; | |
use rocket::http::Status; | |
use rocket::Outcome; | |
const GZIP: u8 = 1; | |
const DEFLATE: u8 = 2; | |
const BROTLI: u8 = 4; | |
#[derive(Clone, Debug, PartialEq, Hash)] | |
pub enum PreferredEncoding { Brotli, Gzip, Uncompressed } | |
#[derive(Copy, Clone, Debug)] | |
pub struct AcceptEncoding { | |
supported: u8 | |
} | |
impl AcceptEncoding { | |
pub fn contains_gzip(self) -> bool { self.supported & GZIP != 0 } | |
pub fn contains_deflate(self) -> bool { self.supported & DEFLATE != 0 } | |
pub fn contains_brotli(self) -> bool { self.supported & BROTLI != 0 } | |
pub fn is_uncompressed(self) -> bool { self.supported == 0 } | |
pub fn preferred(self) -> PreferredEncoding { | |
if self.supported & BROTLI != 0 { | |
PreferredEncoding::Brotli | |
} else if self.supported & GZIP != 0 { | |
PreferredEncoding::Gzip | |
} else { | |
PreferredEncoding::Uncompressed | |
} | |
} | |
} | |
impl<'a, 'r> FromRequest<'a, 'r> for AcceptEncoding { | |
type Error = (); | |
fn from_request(request: &'a Request<'r>) -> Outcome<AcceptEncoding, (Status, ()), ()> { | |
let mut supported = 0u8; | |
if let Some(encoding) = request.headers().get("Accept-Encoding").next() { | |
if encoding.contains("gzip") { supported |= GZIP; } | |
if encoding.contains("deflate") { supported |= DEFLATE; } | |
if encoding.contains("br") { supported |= BROTLI; } | |
} | |
Outcome::Success(AcceptEncoding { supported: supported }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment