Skip to content

Commit

Permalink
run rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
magiclen committed Sep 19, 2019
1 parent bbff316 commit 4303f50
Show file tree
Hide file tree
Showing 10 changed files with 139 additions and 95 deletions.
7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
[package]
name = "rocket-include-static-resources"
version = "0.9.2"
version = "0.9.3"
authors = ["Magic Len <len@magiclen.org>"]
edition = "2018"
repository = "https://github.com/magiclen/rocket-include-static-resources"
homepage = "https://magiclen.org/rocket-include-static-resources"
keywords = ["rocket", "server", "web", "static", "file"]
Expand All @@ -17,8 +18,8 @@ branch = "master"
[dependencies]
rocket = "0.4.2"
mime = "0.3.13"
mime_guess = " 2.0.0"
mime_guess = " 2"
crc-any = "2"
rc-u8-reader = "2.0.0"
rc-u8-reader = "2"

rocket-etag-if-none-match = "0.3"
13 changes: 7 additions & 6 deletions examples/readme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,15 @@ fn main() {
.attach(StaticResponse::fairing(|resources| {
static_resources_initialize!(
resources,

"favicon", "examples/front-end/images/favicon.ico",
"favicon-png", "examples/front-end/images/favicon-16.png",

"html-readme", "examples/front-end/html/README.html",
"favicon",
"examples/front-end/images/favicon.ico",
"favicon-png",
"examples/front-end/images/favicon-16.png",
"html-readme",
"examples/front-end/html/README.html",
);
}))
.mount("/", routes![favicon, favicon_png])
.mount("/", routes![index])
.launch();
}
}
15 changes: 15 additions & 0 deletions rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
brace_style = "PreferSameLine"
enum_discrim_align_threshold = 100
force_explicit_abi = false
force_multiline_blocks = true
format_code_in_doc_comments = true
format_macro_matchers = true
max_width = 100
newline_style = "Unix"
normalize_doc_attributes = true
overflow_delimited_expr = true
reorder_impl_items = true
struct_lit_single_line = false
use_field_init_shorthand = true
use_small_heuristics = "Off"
use_try_shorthand = true
10 changes: 5 additions & 5 deletions src/fairing.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#[cfg(debug_assertions)]
use std::sync::{Mutex, MutexGuard};

use crate::rocket::Rocket;
use crate::rocket::fairing::{Fairing, Info, Kind};
use crate::rocket::Rocket;

#[cfg(debug_assertions)]
use crate::FileResources;
Expand All @@ -12,18 +12,18 @@ use crate::StaticResources;

use crate::StaticContextManager;

const FAIRING_NAME: &'static str = "Static Resources";
const FAIRING_NAME: &str = "Static Resources";

/// The fairing of `StaticResponse`.
#[cfg(debug_assertions)]
pub struct StaticResponseFairing {
pub(crate) custom_callback: Box<dyn Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static>
pub(crate) custom_callback: Box<dyn Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static>,
}

/// The fairing of `StaticResponse`.
#[cfg(not(debug_assertions))]
pub struct StaticResponseFairing {
pub(crate) custom_callback: Box<dyn Fn(&mut StaticResources) + Send + Sync + 'static>
pub(crate) custom_callback: Box<dyn Fn(&mut StaticResources) + Send + Sync + 'static>,
}

impl Fairing for StaticResponseFairing {
Expand Down Expand Up @@ -55,4 +55,4 @@ impl Fairing for StaticResponseFairing {

Ok(rocket.manage(state))
}
}
}
92 changes: 51 additions & 41 deletions src/file_resources.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,36 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::SystemTime;
use std::fs;
use std::io::{self, ErrorKind};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::SystemTime;

use crate::{Mime, EntityTag};
use crate::functions::{compute_data_etag, guess_mime};
use crate::{EntityTag, Mime};

#[derive(Debug)]
#[allow(clippy::type_complexity)]
/// Reloadable file resources.
pub struct FileResources {
resources: HashMap<&'static str, (PathBuf, Mime, Arc<Vec<u8>>, EntityTag, Option<SystemTime>)>
resources: HashMap<&'static str, (PathBuf, Mime, Arc<Vec<u8>>, EntityTag, Option<SystemTime>)>,
}

impl FileResources {
#[inline]
/// Create an instance of `FileResources`.
pub fn new() -> FileResources {
FileResources {
resources: HashMap::new()
resources: HashMap::new(),
}
}

#[inline]
/// Register a resource from a path and it can be reloaded automatically.
pub fn register_resource_file<P: Into<PathBuf>>(&mut self, name: &'static str, file_path: P) -> Result<(), io::Error> {
pub fn register_resource_file<P: Into<PathBuf>>(
&mut self,
name: &'static str,
file_path: P,
) -> Result<(), io::Error> {
let file_path = file_path.into();

let metadata = file_path.metadata()?;
Expand All @@ -49,40 +54,28 @@ impl FileResources {
let name = name.as_ref();

match self.resources.remove(name) {
Some((file_path, _, _, _, _)) => {
Some(file_path)
}
None => {
None
}
Some((file_path, _, _, _, _)) => Some(file_path),
None => None,
}
}

#[inline]
/// Reload resources if needed.
pub fn reload_if_needed(&mut self) -> Result<(), io::Error> {
for (_, (file_path, _, data, etag, mtime)) in &mut self.resources {
for (file_path, _, data, etag, mtime) in self.resources.values_mut() {
let metadata = file_path.metadata()?;

let (reload, new_mtime) = match mtime {
Some(mtime) => {
match metadata.modified() {
Ok(new_mtime) => {
(new_mtime > *mtime, Some(new_mtime))
}
Err(_) => {
(true, None)
}
Ok(new_mtime) => (new_mtime > *mtime, Some(new_mtime)),
Err(_) => (true, None),
}
}
None => {
match metadata.modified() {
Ok(new_mtime) => {
(true, Some(new_mtime))
}
Err(_) => {
(true, None)
}
Ok(new_mtime) => (true, Some(new_mtime)),
Err(_) => (true, None),
}
}
};
Expand All @@ -105,33 +98,35 @@ impl FileResources {

#[inline]
/// Get the specific resource.
pub fn get_resource<S: AsRef<str>>(&mut self, name: S, reload_if_needed: bool) -> Result<(&Mime, Arc<Vec<u8>>, &EntityTag), io::Error> {
pub fn get_resource<S: AsRef<str>>(
&mut self,
name: S,
reload_if_needed: bool,
) -> Result<(&Mime, Arc<Vec<u8>>, &EntityTag), io::Error> {
let name = name.as_ref();

if reload_if_needed {
let (file_path, mime, data, etag, mtime) = self.resources.get_mut(name).ok_or(io::Error::new(ErrorKind::NotFound, format!("The name `{}` is not found.", name)))?;
let (file_path, mime, data, etag, mtime) =
self.resources.get_mut(name).ok_or_else(|| {
io::Error::new(
ErrorKind::NotFound,
format!("The name `{}` is not found.", name),
)
})?;

let metadata = file_path.metadata()?;

let (reload, new_mtime) = match mtime {
Some(mtime) => {
match metadata.modified() {
Ok(new_mtime) => {
(new_mtime > *mtime, Some(new_mtime))
}
Err(_) => {
(true, None)
}
Ok(new_mtime) => (new_mtime > *mtime, Some(new_mtime)),
Err(_) => (true, None),
}
}
None => {
match metadata.modified() {
Ok(new_mtime) => {
(true, Some(new_mtime))
}
Err(_) => {
(true, None)
}
Ok(new_mtime) => (true, Some(new_mtime)),
Err(_) => (true, None),
}
}
};
Expand All @@ -150,7 +145,22 @@ impl FileResources {

Ok((mime, data.clone(), etag))
} else {
self.resources.get(name).map(|(_, mime, data, etag, _)| (mime, data.clone(), etag)).ok_or(io::Error::new(ErrorKind::NotFound, format!("The name `{}` is not found.", name)))
self.resources
.get(name)
.map(|(_, mime, data, etag, _)| (mime, data.clone(), etag))
.ok_or_else(|| {
io::Error::new(
ErrorKind::NotFound,
format!("The name `{}` is not found.", name),
)
})
}
}
}
}

impl Default for FileResources {
#[inline]
fn default() -> Self {
FileResources::new()
}
}
12 changes: 4 additions & 8 deletions src/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::path::Path;
use crate::crc_any::CRCu64;
use crate::mime::APPLICATION_OCTET_STREAM;
use crate::mime_guess::from_ext;
use crate::{Mime, EntityTag};
use crate::{EntityTag, Mime};

#[inline]
pub(crate) fn compute_data_etag<B: AsRef<[u8]> + ?Sized>(data: &B) -> EntityTag {
Expand All @@ -18,11 +18,7 @@ pub(crate) fn guess_mime<P: AsRef<Path>>(path: P) -> Mime {
let path = path.as_ref();

match path.extension() {
Some(extension) => {
from_ext(extension.to_string_lossy().as_ref()).first_or_octet_stream()
}
None => {
APPLICATION_OCTET_STREAM
}
Some(extension) => from_ext(extension.to_string_lossy().as_ref()).first_or_octet_stream(),
None => APPLICATION_OCTET_STREAM,
}
}
}
44 changes: 26 additions & 18 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,16 @@ fn main() {
See `examples`.
*/

mod functions;
mod file_resources;
mod static_resources;
mod manager;
mod fairing;
mod file_resources;
mod functions;
mod macros;
mod manager;
mod static_resources;

extern crate crc_any;
extern crate mime;
extern crate mime_guess;
extern crate crc_any;
extern crate rc_u8_reader;

extern crate rocket;
Expand All @@ -80,18 +80,18 @@ use mime::Mime;
#[cfg(debug_assertions)]
use rc_u8_reader::ArcU8Reader;

use rocket::State;
use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket::http::Status;
use rocket::fairing::Fairing;
use rocket::http::Status;
use rocket::request::Request;
use rocket::response::{self, Responder, Response};
use rocket::State;

use rocket_etag_if_none_match::{EntityTag, EtagIfNoneMatch};

use fairing::StaticResponseFairing;
pub use file_resources::FileResources;
pub use static_resources::StaticResources;
pub use manager::StaticContextManager;
use fairing::StaticResponseFairing;
pub use static_resources::StaticResources;

#[derive(Debug)]
/// To respond a static resource.
Expand All @@ -113,18 +113,22 @@ impl StaticResponse {
#[cfg(debug_assertions)]
#[inline]
/// Create the fairing of `HandlebarsResponse`.
pub fn fairing<F>(f: F) -> impl Fairing where F: Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static {
pub fn fairing<F>(f: F) -> impl Fairing
where
F: Fn(&mut MutexGuard<FileResources>) + Send + Sync + 'static, {
StaticResponseFairing {
custom_callback: Box::new(f)
custom_callback: Box::new(f),
}
}

#[cfg(not(debug_assertions))]
#[inline]
/// Create the fairing of `HandlebarsResponse`.
pub fn fairing<F>(f: F) -> impl Fairing where F: Fn(&mut StaticResources) + Send + Sync + 'static {
pub fn fairing<F>(f: F) -> impl Fairing
where
F: Fn(&mut StaticResources) + Send + Sync + 'static, {
StaticResponseFairing {
custom_callback: Box::new(f)
custom_callback: Box::new(f),
}
}
}
Expand All @@ -136,7 +140,9 @@ impl<'a> Responder<'a> for StaticResponse {

let mut response = Response::build();

let cm = request.guard::<State<StaticContextManager>>().expect("StaticContextManager registered in on_attach");
let cm = request
.guard::<State<StaticContextManager>>()
.expect("StaticContextManager registered in on_attach");

let (mime, data, etag) = {
let mut resources = cm.resources.lock().unwrap();
Expand Down Expand Up @@ -173,7 +179,9 @@ impl<'a> Responder<'a> for StaticResponse {

let mut response = Response::build();

let cm = request.guard::<State<StaticContextManager>>().expect("StaticContextManager registered in on_attach");
let cm = request
.guard::<State<StaticContextManager>>()
.expect("StaticContextManager registered in on_attach");

let (mime, data, etag) = {
let resources: &StaticResources = &cm.resources;
Expand Down Expand Up @@ -203,4 +211,4 @@ impl<'a> Responder<'a> for StaticResponse {

response.ok()
}
}
}

0 comments on commit 4303f50

Please sign in to comment.