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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
use actix_web::http::header::{
    self, HeaderMap, HeaderValue, TryIntoHeaderPair, TryIntoHeaderValue,
};
use flate2::{read::GzDecoder, read::GzEncoder, Compression as GzCompression};
use std::io::{Cursor, Read};

/// Tile data compression
#[derive(Clone, PartialEq, Debug)]
pub enum Compression {
    // Unknown,
    None,
    Gzip,
    // Brotli,
    // Zstd,
}

/// Tile reader response
pub struct TileResponse {
    headers: HeaderMap,
    pub(crate) body: Box<dyn Read + Send + Sync>,
}

/// Tile response data
pub struct TileResponseData {
    headers: HeaderMap,
    pub body: Vec<u8>,
}

impl TileResponse {
    pub fn new() -> Self {
        TileResponse {
            headers: HeaderMap::new(),
            body: Box::new(std::io::empty()),
        }
    }
    /// Set response content type.
    pub fn set_content_type<V: TryIntoHeaderValue>(&mut self, value: V) -> &mut Self {
        if let Ok(value) = value.try_into_value() {
            self.headers.insert(header::CONTENT_TYPE, value);
        }
        self
    }
    /// Insert a header, replacing any that were set with an equivalent field name.
    pub fn insert_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self {
        if let Ok((key, value)) = header.try_into_pair() {
            self.headers.insert(key, value);
        }
        self
    }
    pub fn set_headers(&mut self, headers: &HeaderMap) -> &mut Self {
        for (key, value) in headers {
            self.insert_header((key, value));
        }
        self
    }
    pub fn with_body(mut self, body: Box<dyn Read + Send + Sync>) -> TileResponse {
        self.body = body;
        self
    }
    /// Apply optional de-/compression
    pub fn with_compression(mut self, compression: &Compression) -> TileResponse {
        match (self.compression(), compression) {
            (Compression::None, Compression::Gzip) => {
                let gz = GzEncoder::new(self.body, GzCompression::fast());
                self.body = Box::new(gz);
                self.insert_header(("Content-Encoding", "gzip"));
            }
            (Compression::Gzip, Compression::None) => {
                let gz = GzDecoder::new(self.body);
                self.body = Box::new(gz);
                self.headers.remove(header::CONTENT_ENCODING);
            }
            _ => {}
        }
        self
    }
    pub fn content_type(&self) -> Option<&HeaderValue> {
        self.headers.get(header::CONTENT_TYPE)
    }
    pub fn compression(&self) -> Compression {
        match self.headers.get(header::CONTENT_ENCODING) {
            Some(v) if v == HeaderValue::from_static("gzip") => Compression::Gzip,
            _ => Compression::None,
        }
    }
    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }
    /// Read tile body with optional compression
    pub fn read_bytes(
        mut self,
        compression: &Compression,
    ) -> Result<TileResponseData, std::io::Error> {
        let mut response = TileResponseData {
            headers: self.headers,
            body: Vec::new(),
        };
        match compression {
            Compression::Gzip => {
                let mut gz = GzEncoder::new(self.body, GzCompression::fast());
                gz.read_to_end(&mut response.body)?;
                response.insert_header(("Content-Encoding", "gzip"));
            }
            Compression::None => {
                self.body.read_to_end(&mut response.body)?;
            }
        }
        Ok(response)
    }
}

impl Default for TileResponse {
    fn default() -> Self {
        Self::new()
    }
}

impl TileResponseData {
    /// Insert a header, replacing any that were set with an equivalent field name.
    pub fn insert_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self {
        if let Ok((key, value)) = header.try_into_pair() {
            self.headers.insert(key, value);
        }
        self
    }
    pub fn compression(&self) -> Compression {
        match self.headers.get(header::CONTENT_ENCODING) {
            Some(v) if v == HeaderValue::from_static("gzip") => Compression::Gzip,
            _ => Compression::None,
        }
    }
    /// Read tile body with optional compression
    pub fn as_response(self, compression: &Compression) -> TileResponse {
        let mut response = TileResponse::new();
        response.set_headers(&self.headers);
        match (self.compression(), compression) {
            (Compression::None, Compression::Gzip) => {
                let gz = GzEncoder::new(Cursor::new(self.body), GzCompression::fast());
                response.body = Box::new(gz);
                response.insert_header(("Content-Encoding", "gzip"));
            }
            (Compression::Gzip, Compression::None) => {
                let gz = GzDecoder::new(Cursor::new(self.body));
                response.body = Box::new(gz);
                response.headers.remove(header::CONTENT_ENCODING);
            }
            _ => response.body = Box::new(Cursor::new(self.body)),
        }
        response
    }
}