ttpkit-http 0.1.1

Simple HTTP client and server implementation based on ttpkit.
Documentation
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Response types.

use bytes::BytesMut;
use tokio_util::codec::{Decoder, Encoder};

use crate::{
    CodecError, Protocol, Version,
    header::{FieldIter, HeaderField, HeaderFieldValue, Iter},
    ttpkit::response::{
        ResponseHeader as GenericResponseHeader,
        ResponseHeaderBuilder as GenericResponseHeaderBuilder,
        ResponseHeaderDecoder as GenericResponseHeaderDecoder,
        ResponseHeaderEncoder as GenericResponseHeaderEncoder, Status as GenericStatus,
    },
};

pub use crate::ttpkit::response::{ResponseHeaderDecoderOptions, StatusMessage};

/// HTTP response status.
#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct Status {
    inner: GenericStatus,
}

impl Status {
    pub const CONTINUE: Self = Self::from_static_str(100, "Continue");
    pub const SWITCHING_PROTOCOLS: Self = Self::from_static_str(101, "Switching Protocols");
    pub const OK: Self = Self::from_static_str(200, "OK");
    pub const CREATED: Self = Self::from_static_str(201, "Created");
    pub const NO_CONTENT: Self = Self::from_static_str(204, "No Content");
    pub const MOVED_PERMANENTLY: Self = Self::from_static_str(301, "Moved Permanently");
    pub const SEE_OTHER: Self = Self::from_static_str(303, "See Other");
    pub const BAD_REQUEST: Self = Self::from_static_str(400, "Bad Request");
    pub const UNAUTHORIZED: Self = Self::from_static_str(401, "Unauthorized");
    pub const FORBIDDEN: Self = Self::from_static_str(403, "Forbidden");
    pub const NOT_FOUND: Self = Self::from_static_str(404, "Not Found");
    pub const METHOD_NOT_ALLOWED: Self = Self::from_static_str(405, "Method Not Allowed");
    pub const EXPECTATION_FAILED: Self = Self::from_static_str(417, "Expectation Failed");
    pub const INTERNAL_SERVER_ERROR: Self = Self::from_static_str(500, "Internal Server Error");
    pub const NOT_IMPLEMENTED: Self = Self::from_static_str(501, "Not Implemented");
    pub const BAD_GATEWAY: Self = Self::from_static_str(502, "Bad Gateway");
    pub const SERVICE_UNAVAILABLE: Self = Self::from_static_str(503, "Service Unavailable");
    pub const GATEWAY_TIMEOUT: Self = Self::from_static_str(504, "Gateway Timeout");

    /// Create a new status with a given code and a message.
    pub fn new<T>(code: u16, msg: T) -> Self
    where
        T: Into<StatusMessage>,
    {
        Self {
            inner: GenericStatus::new(code, msg.into()),
        }
    }

    /// Create a new status with a given code and a message.
    #[inline]
    pub const fn from_static_str(code: u16, msg: &'static str) -> Self {
        Self {
            inner: GenericStatus::from_static_str(code, msg),
        }
    }

    /// Create a new status with a given code and a message.
    #[inline]
    pub const fn from_static_bytes(code: u16, msg: &'static [u8]) -> Self {
        Self {
            inner: GenericStatus::from_static_bytes(code, msg),
        }
    }

    /// Create a status reference from a generic status reference.
    #[inline]
    const fn from_generic_ref(status: &GenericStatus) -> &Self {
        let ptr = status as *const GenericStatus;

        // SAFETY: `Self` is `repr(transparent)` over `GenericStatus`.
        unsafe { &*(ptr as *const Self) }
    }

    /// Get the status code.
    #[inline]
    pub fn code(&self) -> u16 {
        self.inner.code()
    }

    /// Get the status message.
    #[inline]
    pub fn message(&self) -> &StatusMessage {
        self.inner.message()
    }
}

/// HTTP response header.
pub struct ResponseHeader {
    inner: GenericResponseHeader<Protocol, Version>,
}

impl ResponseHeader {
    /// Create a new header.
    #[inline]
    pub(crate) const fn new(inner: GenericResponseHeader<Protocol, Version>) -> Self {
        Self { inner }
    }

    /// Get the response status.
    #[inline]
    pub fn status(&self) -> &Status {
        Status::from_generic_ref(self.inner.status())
    }

    /// Get the status code.
    #[inline]
    pub fn status_code(&self) -> u16 {
        self.inner.status_code()
    }

    /// Get the status message.
    #[inline]
    pub fn status_message(&self) -> &StatusMessage {
        self.inner.status_message()
    }

    /// Get all header fields.
    #[inline]
    pub fn get_all_header_fields(&self) -> Iter<'_> {
        self.inner.get_all_header_fields()
    }

    /// Get header fields corresponding to a given name.
    pub fn get_header_fields<'a, N>(&'a self, name: &'a N) -> FieldIter<'a>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.inner.get_header_fields(name)
    }

    /// Get the last header field of a given name.
    pub fn get_header_field<'a, N>(&'a self, name: &'a N) -> Option<&'a HeaderField>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.inner.get_header_field(name)
    }

    /// Get value of the last header field with a given name.
    pub fn get_header_field_value<'a, N>(&'a self, name: &'a N) -> Option<&'a HeaderFieldValue>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.inner.get_header_field_value(name)
    }
}

/// HTTP response builder.
pub struct ResponseBuilder {
    header: GenericResponseHeaderBuilder<Protocol, Version>,
}

impl ResponseBuilder {
    /// Create a new response builder.
    #[inline]
    const fn new() -> Self {
        Self {
            header: GenericResponseHeader::builder(
                Protocol,
                Version::Version11,
                GenericStatus::from_static_str(200, "OK"),
            ),
        }
    }

    /// Set the HTTP version.
    #[inline]
    pub fn set_version(mut self, version: Version) -> Self {
        self.header = self.header.set_version(version);
        self
    }

    /// Set the response status.
    #[inline]
    pub fn set_status(mut self, status: Status) -> Self {
        self.header = self.header.set_status(status.inner);
        self
    }

    /// Replace the current header fields having the same name (if any).
    pub fn set_header_field<T>(mut self, field: T) -> Self
    where
        T: Into<HeaderField>,
    {
        self.header = self.header.set_header_field(field);
        self
    }

    /// Add a given header field.
    pub fn add_header_field<T>(mut self, field: T) -> Self
    where
        T: Into<HeaderField>,
    {
        self.header = self.header.add_header_field(field);
        self
    }

    /// Remove all header fields with a given name.
    pub fn remove_header_fields<N>(mut self, name: &N) -> Self
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header = self.header.remove_header_fields(name);
        self
    }

    /// Build just the response header.
    #[inline]
    pub fn header(self) -> ResponseHeader {
        ResponseHeader::new(self.header.build())
    }

    /// Build the response.
    pub fn body<B>(self, body: B) -> Response<B> {
        Response::new(self.header(), body)
    }
}

impl From<ResponseHeader> for ResponseBuilder {
    #[inline]
    fn from(header: ResponseHeader) -> ResponseBuilder {
        Self {
            header: header.inner.into(),
        }
    }
}

/// HTTP response.
pub struct Response<B> {
    header: ResponseHeader,
    body: B,
}

impl Response<()> {
    /// Get a response builder.
    #[inline]
    pub const fn builder() -> ResponseBuilder {
        ResponseBuilder::new()
    }
}

impl<B> Response<B> {
    /// Create a new response.
    #[inline]
    pub(crate) const fn new(header: ResponseHeader, body: B) -> Self {
        Self { header, body }
    }

    /// Get the response header.
    #[inline]
    pub fn header(&self) -> &ResponseHeader {
        &self.header
    }

    /// Get the response status.
    #[inline]
    pub fn status(&self) -> &Status {
        self.header.status()
    }

    /// Get the status code.
    #[inline]
    pub fn status_code(&self) -> u16 {
        self.header.status_code()
    }

    /// Get the status message.
    #[inline]
    pub fn status_message(&self) -> &StatusMessage {
        self.header.status_message()
    }

    /// Get all header fields.
    #[inline]
    pub fn get_all_header_fields(&self) -> Iter<'_> {
        self.header.get_all_header_fields()
    }

    /// Get header fields corresponding to a given name.
    pub fn get_header_fields<'a, N>(&'a self, name: &'a N) -> FieldIter<'a>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header.get_header_fields(name)
    }

    /// Get the last header field of a given name.
    pub fn get_header_field<'a, N>(&'a self, name: &'a N) -> Option<&'a HeaderField>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header.get_header_field(name)
    }

    /// Get value of the last header field with a given name.
    pub fn get_header_field_value<'a, N>(&'a self, name: &'a N) -> Option<&'a HeaderFieldValue>
    where
        N: AsRef<[u8]> + ?Sized,
    {
        self.header.get_header_field_value(name)
    }

    /// Take the response body.
    #[inline]
    pub fn body(self) -> B {
        self.body
    }

    /// Deconstruct the response back into a response builder and the body.
    #[inline]
    pub fn deconstruct(self) -> (ResponseHeader, B) {
        (self.header, self.body)
    }
}

/// Response header decoder.
pub struct ResponseHeaderDecoder {
    inner: GenericResponseHeaderDecoder<Protocol, Version>,
}

impl ResponseHeaderDecoder {
    /// Create a new decoder.
    #[inline]
    pub fn new(options: ResponseHeaderDecoderOptions) -> Self {
        Self {
            inner: GenericResponseHeaderDecoder::new(options),
        }
    }

    /// Reset the decoder and make it ready for parsing a new response header.
    #[inline]
    pub fn reset(&mut self) {
        self.inner.reset();
    }

    /// Decode a given response header chunk.
    pub fn decode(&mut self, data: &mut BytesMut) -> Result<Option<ResponseHeader>, CodecError> {
        let res = self.inner.decode(data)?.map(ResponseHeader::new);

        Ok(res)
    }

    /// Decode a given response header chunk at the end of the stream.
    pub fn decode_eof(
        &mut self,
        data: &mut BytesMut,
    ) -> Result<Option<ResponseHeader>, CodecError> {
        let res = self.inner.decode_eof(data)?.map(ResponseHeader::new);

        Ok(res)
    }
}

impl Decoder for ResponseHeaderDecoder {
    type Item = ResponseHeader;
    type Error = CodecError;

    #[inline]
    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        Self::decode(self, buf)
    }

    #[inline]
    fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        Self::decode_eof(self, buf)
    }
}

/// Response header encoder.
pub struct ResponseHeaderEncoder {
    inner: GenericResponseHeaderEncoder,
}

impl ResponseHeaderEncoder {
    /// Create a new encoder.
    #[inline]
    pub const fn new() -> Self {
        Self {
            inner: GenericResponseHeaderEncoder::new(),
        }
    }

    /// Encode a given response header into a given buffer.
    #[inline]
    pub fn encode(&mut self, header: &ResponseHeader, dst: &mut BytesMut) {
        self.inner.encode(&header.inner, dst);
    }
}

impl Default for ResponseHeaderEncoder {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Encoder<&ResponseHeader> for ResponseHeaderEncoder {
    type Error = CodecError;

    #[inline]
    fn encode(&mut self, header: &ResponseHeader, dst: &mut BytesMut) -> Result<(), Self::Error> {
        Self::encode(self, header, dst);

        Ok(())
    }
}