From d326533170c35c017b0e2b127c096d12a0c2e367 Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Fri, 24 Sep 2021 17:43:12 +1000 Subject: [PATCH] Refactor `EmbeddedFileExt` to use combinators and ? This allows for the "happy-path" to stay on the same indentation-level, which makes the code easier to read. --- daemon/src/routes.rs | 24 ++++++++++-------------- 1 file changed, 10 insertions(+), 14 deletions(-) diff --git a/daemon/src/routes.rs b/daemon/src/routes.rs index 38f701d..85a8c89 100644 --- a/daemon/src/routes.rs +++ b/daemon/src/routes.rs @@ -1,7 +1,6 @@ use rocket::http::{ContentType, Status}; use rust_embed::EmbeddedFile; use std::borrow::Cow; -use std::ffi::OsStr; use std::path::PathBuf; pub trait EmbeddedFileExt { @@ -10,18 +9,15 @@ pub trait EmbeddedFileExt { impl EmbeddedFileExt for Option { fn into_response(self, file: PathBuf) -> Result<(ContentType, Cow<'static, [u8]>), Status> { - match self { - None => Err(Status::NotFound), - Some(embedded_file) => { - let ext = file - .as_path() - .extension() - .and_then(OsStr::to_str) - .ok_or_else(|| Status::new(400))?; - let content_type = - ContentType::from_extension(ext).ok_or_else(|| Status::new(400))?; - Ok::<(ContentType, Cow<[u8]>), Status>((content_type, embedded_file.data)) - } - } + let embedded_file = self.ok_or(Status::NotFound)?; + let ext = file + .as_path() + .extension() + .ok_or(Status::BadRequest)? + .to_str() + .ok_or(Status::InternalServerError)?; + let content_type = ContentType::from_extension(ext).ok_or(Status::InternalServerError)?; + + Ok((content_type, embedded_file.data)) } }