From f6325798b1a6d465f4c8ae8784555390e7973c7e Mon Sep 17 00:00:00 2001 From: Sergio Benitez Date: Tue, 23 Oct 2018 01:23:11 -0700 Subject: [PATCH] Normalize paths in 'route_guard' test. --- core/lib/src/ext.rs | 38 ++++++++++++++++++++++++++++++++++- core/lib/src/lib.rs | 2 +- core/lib/tests/route_guard.rs | 5 +++-- 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/core/lib/src/ext.rs b/core/lib/src/ext.rs index 8813b741..aa68a935 100644 --- a/core/lib/src/ext.rs +++ b/core/lib/src/ext.rs @@ -1,4 +1,6 @@ -use std::io; +use std::{fmt, io}; +use std::borrow::Cow; +use std::path::{Path, PathBuf, Component}; pub trait ReadExt: io::Read { fn read_max(&mut self, mut buf: &mut [u8]) -> io::Result { @@ -17,3 +19,37 @@ pub trait ReadExt: io::Read { } impl ReadExt for T { } + +pub struct NormalizedPath<'a>(&'a Path); + +impl<'a> fmt::Display for NormalizedPath<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn to_str<'c>(c: &'c Component) -> Cow<'c, str> { + c.as_os_str().to_string_lossy() + } + + let mut components = self.0.components(); + match (components.next(), components.next()) { + (Some(Component::RootDir), Some(c)) => write!(f, "/{}", to_str(&c))?, + (Some(a), Some(b)) => write!(f, "{}/{}", to_str(&a), to_str(&b))?, + (Some(c), None) => write!(f, "{}", to_str(&c))?, + _ => return Ok(()) + }; + + for c in components { + write!(f, "/{}", to_str(&c))?; + } + + Ok(()) + } +} + +pub trait Normalize { + fn normalized(&self) -> NormalizedPath; +} + +impl> Normalize for T { + fn normalized(&self) -> NormalizedPath { + NormalizedPath(self.as_ref()) + } +} diff --git a/core/lib/src/lib.rs b/core/lib/src/lib.rs index 8a8a4fff..3a45bf12 100644 --- a/core/lib/src/lib.rs +++ b/core/lib/src/lib.rs @@ -116,6 +116,7 @@ extern crate isatty; #[cfg(test)] #[macro_use] extern crate lazy_static; #[doc(hidden)] #[macro_use] pub mod logger; +#[doc(hidden)] pub mod ext; pub mod local; pub mod request; pub mod response; @@ -141,7 +142,6 @@ mod router; mod rocket; mod codegen; mod catcher; -mod ext; #[doc(inline)] pub use response::Response; #[doc(inline)] pub use handler::{Handler, ErrorHandler}; diff --git a/core/lib/tests/route_guard.rs b/core/lib/tests/route_guard.rs index 07f8ea71..aa9a62e3 100644 --- a/core/lib/tests/route_guard.rs +++ b/core/lib/tests/route_guard.rs @@ -2,12 +2,13 @@ #[macro_use] extern crate rocket; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use rocket::ext::Normalize; use rocket::Route; #[get("/")] fn files(route: &Route, path: PathBuf) -> String { - format!("{}/{}", route.base(), path.to_string_lossy()) + Path::new(route.base()).join(path).normalized().to_string() } mod route_guard_tests {