1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use rocket::http::Status;
use rocket::response::{Response, Responder, NamedFile};
use rocket::request::Request;
use cache::Cache;
use std::path::Path;
use named_in_memory_file::NamedInMemoryFile;
#[derive(Debug)]
pub enum CachedFile<'a> {
InMemory(NamedInMemoryFile<'a>),
FileSystem(NamedFile),
NotFound
}
impl<'a> CachedFile<'a> {
pub fn open<P: AsRef<Path>>(path: P, cache: &'a Cache) -> CachedFile<'a> {
cache.get(path)
}
}
impl<'a> From<NamedInMemoryFile<'a>> for CachedFile<'a> {
fn from(cached_file: NamedInMemoryFile<'a>) -> CachedFile<'a> {
CachedFile::InMemory(cached_file)
}
}
impl From<NamedFile> for CachedFile<'static> {
fn from(named_file: NamedFile) -> Self {
CachedFile::FileSystem(named_file)
}
}
impl<'a> Responder<'a> for CachedFile<'a> {
fn respond_to(self, request: &Request) -> Result<Response<'a>, Status> {
match self {
CachedFile::InMemory(cached_file) => cached_file.respond_to(request),
CachedFile::FileSystem(named_file) => named_file.respond_to(request),
CachedFile::NotFound => {
error!("Response was `FileNotFound`.",);
Err(Status::NotFound)
}
}
}
}
impl<'a, 'b> PartialEq for CachedFile<'a> {
fn eq(&self, other: &CachedFile) -> bool {
match *self {
CachedFile::InMemory(ref lhs_cached_file) => {
match *other {
CachedFile::InMemory(ref rhs_cached_file) => (*rhs_cached_file.file).get() == (*lhs_cached_file.file).get(),
CachedFile::FileSystem(_) => false,
CachedFile::NotFound => false
}
}
CachedFile::FileSystem(ref lhs_named_file) => {
match *other {
CachedFile::InMemory(_) => false,
CachedFile::FileSystem(ref rhs_named_file) => {
*lhs_named_file.path() == *rhs_named_file.path()
}
CachedFile::NotFound => false
}
}
CachedFile::NotFound => {
match *other {
CachedFile::InMemory(_) => false,
CachedFile::FileSystem(_) => false,
CachedFile::NotFound => true
}
}
}
}
}