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
use std::sync::Arc;

use mime::Mime;
use rc_u8_reader::ArcU8Reader;

use crate::{
    rocket::{
        http::Status,
        request::Request,
        response::{self, Responder, Response},
    },
    EntityTag,
};

#[derive(Debug)]
struct StaticResponseInner {
    mime: String,
    data: Arc<Vec<u8>>,
    etag: String,
}

#[derive(Debug)]
/// To respond a static resource.
pub struct StaticResponse {
    inner: Option<StaticResponseInner>,
}

impl StaticResponse {
    #[inline]
    pub(crate) fn build(
        mime: &Mime,
        data: Arc<Vec<u8>>,
        etag: &EntityTag<'static>,
    ) -> StaticResponse {
        StaticResponse {
            inner: Some(StaticResponseInner {
                mime: mime.to_string(),
                data,
                etag: etag.to_string(),
            }),
        }
    }

    #[inline]
    pub(crate) const fn not_modified() -> StaticResponse {
        StaticResponse {
            inner: None
        }
    }
}

impl<'r, 'o: 'r> Responder<'r, 'o> for StaticResponse {
    #[inline]
    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'o> {
        let mut response = Response::build();

        if let Some(inner) = self.inner {
            response.raw_header("Etag", inner.etag);
            response.raw_header("Content-Type", inner.mime);

            response.sized_body(inner.data.len(), ArcU8Reader::new(inner.data));
        } else {
            response.status(Status::NotModified);
        }

        response.ok()
    }
}