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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// License: see LICENSE file at root directory of `master` branch

//! # Status

use {
    core::{
        convert::TryFrom,
        fmt::{self, Display, Formatter},
        str::FromStr,
    },
    crate::Error,
};

const STATUS_CONTINUE: u16 = 100;
const STATUS_SWITCHING_PROTOCOLS: u16 = 101;
const STATUS_EARLY_HINTS: u16 = 103;
const STATUS_OK: u16 = 200;
const STATUS_CREATED: u16 = 201;
const STATUS_ACCEPTED: u16 = 202;
const STATUS_NON_AUTHORITATIVE_INFORMATION: u16 = 203;
const STATUS_NO_CONTENT: u16 = 204;
const STATUS_RESET_CONTENT: u16 = 205;
const STATUS_PARTIAL_CONTENT: u16 = 206;
const STATUS_MULTIPLE_CHOICES: u16 = 300;
const STATUS_MOVED_PERMANENTLY: u16 = 301;
const STATUS_FOUND: u16 = 302;
const STATUS_SEE_OTHER: u16 = 303;
const STATUS_NOT_MODIFIED: u16 = 304;
const STATUS_TEMPORARY_REDIRECT: u16 = 307;
const STATUS_PERMANENT_REDIRECT: u16 = 308;
const STATUS_BAD_REQUEST: u16 = 400;
const STATUS_UNAUTHORIZED: u16 = 401;
const STATUS_PAYMENT_REQUIRED: u16 = 402;
const STATUS_FORBIDDEN: u16 = 403;
const STATUS_NOT_FOUND: u16 = 404;
const STATUS_METHOD_NOT_ALLOWED: u16 = 405;
const STATUS_NOT_ACCEPTABLE: u16 = 406;
const STATUS_PROXY_AUTHENTICATION_REQUIRED: u16 = 407;
const STATUS_REQUEST_TIMEOUT: u16 = 408;
const STATUS_CONFLICT: u16 = 409;
const STATUS_GONE: u16 = 410;
const STATUS_LENGTH_REQUIRED: u16 = 411;
const STATUS_PRECONDITION_FAILED: u16 = 412;
const STATUS_PAYLOAD_TOO_LARGE: u16 = 413;
const STATUS_URI_TOO_LONG: u16 = 414;
const STATUS_UNSUPPORTED_MEDIA_TYPE: u16 = 415;
const STATUS_RANGE_NOT_SATISFIABLE: u16 = 416;
const STATUS_EXPECTATION_FAILED: u16 = 417;
const STATUS_IM_A_TEAPOT: u16 = 418;
const STATUS_UNPROCESSABLE_ENTITY: u16 = 422;
const STATUS_TOO_EARLY: u16 = 425;
const STATUS_UPGRADE_REQUIRED: u16 = 426;
const STATUS_PRECONDITION_REQUIRED: u16 = 428;
const STATUS_TOO_MANY_REQUESTS: u16 = 429;
const STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: u16 = 431;
const STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: u16 = 451;
const STATUS_INTERNAL_SERVER_ERROR: u16 = 500;
const STATUS_NOT_IMPLEMENTED: u16 = 501;
const STATUS_BAD_GATEWAY: u16 = 502;
const STATUS_SERVICE_UNAVAILABLE: u16 = 503;
const STATUS_GATEWAY_TIMEOUT: u16 = 504;
const STATUS_HTTP_VERSION_NOT_SUPPORTED: u16 = 505;
const STATUS_NETWORK_AUTHENTICATION_REQUIRED: u16 = 511;

/// # Status
///
/// ## References
///
/// - <https://developer.mozilla.org/en-US/docs/Web/HTTP/Status>
#[derive(Debug, Eq, PartialEq, Hash)]
pub enum Status {

    /// # `100` - Continue
    Continue,

    /// # `101` - Switching Protocols
    SwitchingProtocols,

    /// # `103` - Early Hints
    EarlyHints,

    /// # `200` - OK
    Ok,

    /// # `201` - Created
    Created,

    /// # `202` - Accepted
    Accepted,

    /// # `203` - Non-Authoritative Information
    NonAuthoritativeInformation,

    /// # `204` - No Content
    NoContent,

    /// # `205` - Reset Content
    ResetContent,

    /// # `206` - Partial Content
    PartialContent,

    /// # `300` - Multiple Choices
    MultipleChoices,

    /// # `301` - Moved Permanently
    MovedPermanently,

    /// # `302` - Found
    Found,

    /// # `303` - See Other
    SeeOther,

    /// # `304` - Not Modified
    NotModified,

    /// # `307` - Temporary Redirect
    TemporaryRedirect,

    /// # `308` - Permanent Redirect
    PermanentRedirect,

    /// # `400` - Bad Request
    BadRequest,

    /// # `401` - Unauthorized
    Unauthorized,

    /// # `402` - Payment Required
    PaymentRequired,

    /// # `403` - Forbidden
    Forbidden,

    /// # `404` - Not Found
    NotFound,

    /// # `405` - Method Not Allowed
    MethodNotAllowed,

    /// # `406` - Not Acceptable
    NotAcceptable,

    /// # `407` - Proxy Authentication Required
    ProxyAuthenticationRequired,

    /// # `408` - Request Timeout
    RequestTimeout,

    /// # `409` - Conflict
    Conflict,

    /// # `410` - Gone
    Gone,

    /// # `411` - Length Required
    LengthRequired,

    /// # `412` - Precondition Failed
    PreconditionFailed,

    /// # `413` - Payload Too Large
    PayloadTooLarge,

    /// # `414` - URI Too Long
    UriTooLong,

    /// # `415` - Unsupported Media Type
    UnsupportedMediaType,

    /// # `416` - Range Not Satisfiable
    RangeNotSatisfiable,

    /// # `417` - Expectation Failed
    ExpectationFailed,

    /// # `418` - I'm a teapot
    ImATeapot,

    /// # `422` - Unprocessable Entity
    UnprocessableEntity,

    /// # `425` - Too Early
    TooEarly,

    /// # `426` - Upgrade Required
    UpgradeRequired,

    /// # `428` - Precondition Required
    PreconditionRequired,

    /// # `429` - Too Many Requests
    TooManyRequests,

    /// # `431` - Request Header Fields Too Large
    RequestHeaderFieldsTooLarge,

    /// # `451` - Unavailable For Legal Reasons
    UnavailableForLegalReasons,

    /// # `500` - Internal Server Error
    InternalServerError,

    /// # `501` - Not Implemented
    NotImplemented,

    /// # `502` - Bad Gateway
    BadGateway,

    /// # `503` - Service Unavailable
    ServiceUnavailable,

    /// # `504` - Gateway Timeout
    GatewayTimeout,

    /// # `505` - HTTP Version Not Supported
    HttpVersionNotSupported,

    /// # `511` - Network Authentication Required
    NetworkAuthenticationRequired,

}

impl Status {

    /// # Gets code
    pub fn code(&self) -> u16 {
        match self {
            Status::Continue => STATUS_CONTINUE,
            Status::SwitchingProtocols => STATUS_SWITCHING_PROTOCOLS,
            Status::EarlyHints => STATUS_EARLY_HINTS,
            Status::Ok => STATUS_OK,
            Status::Created => STATUS_CREATED,
            Status::Accepted => STATUS_ACCEPTED,
            Status::NonAuthoritativeInformation => STATUS_NON_AUTHORITATIVE_INFORMATION,
            Status::NoContent => STATUS_NO_CONTENT,
            Status::ResetContent => STATUS_RESET_CONTENT,
            Status::PartialContent => STATUS_PARTIAL_CONTENT,
            Status::MultipleChoices => STATUS_MULTIPLE_CHOICES,
            Status::MovedPermanently => STATUS_MOVED_PERMANENTLY,
            Status::Found => STATUS_FOUND,
            Status::SeeOther => STATUS_SEE_OTHER,
            Status::NotModified => STATUS_NOT_MODIFIED,
            Status::TemporaryRedirect => STATUS_TEMPORARY_REDIRECT,
            Status::PermanentRedirect => STATUS_PERMANENT_REDIRECT,
            Status::BadRequest => STATUS_BAD_REQUEST,
            Status::Unauthorized => STATUS_UNAUTHORIZED,
            Status::PaymentRequired => STATUS_PAYMENT_REQUIRED,
            Status::Forbidden => STATUS_FORBIDDEN,
            Status::NotFound => STATUS_NOT_FOUND,
            Status::MethodNotAllowed => STATUS_METHOD_NOT_ALLOWED,
            Status::NotAcceptable => STATUS_NOT_ACCEPTABLE,
            Status::ProxyAuthenticationRequired => STATUS_PROXY_AUTHENTICATION_REQUIRED,
            Status::RequestTimeout => STATUS_REQUEST_TIMEOUT,
            Status::Conflict => STATUS_CONFLICT,
            Status::Gone => STATUS_GONE,
            Status::LengthRequired => STATUS_LENGTH_REQUIRED,
            Status::PreconditionFailed => STATUS_PRECONDITION_FAILED,
            Status::PayloadTooLarge => STATUS_PAYLOAD_TOO_LARGE,
            Status::UriTooLong => STATUS_URI_TOO_LONG,
            Status::UnsupportedMediaType => STATUS_UNSUPPORTED_MEDIA_TYPE,
            Status::RangeNotSatisfiable => STATUS_RANGE_NOT_SATISFIABLE,
            Status::ExpectationFailed => STATUS_EXPECTATION_FAILED,
            Status::ImATeapot => STATUS_IM_A_TEAPOT,
            Status::UnprocessableEntity => STATUS_UNPROCESSABLE_ENTITY,
            Status::TooEarly => STATUS_TOO_EARLY,
            Status::UpgradeRequired => STATUS_UPGRADE_REQUIRED,
            Status::PreconditionRequired => STATUS_PRECONDITION_REQUIRED,
            Status::TooManyRequests => STATUS_TOO_MANY_REQUESTS,
            Status::RequestHeaderFieldsTooLarge => STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE,
            Status::UnavailableForLegalReasons => STATUS_UNAVAILABLE_FOR_LEGAL_REASONS,
            Status::InternalServerError => STATUS_INTERNAL_SERVER_ERROR,
            Status::NotImplemented => STATUS_NOT_IMPLEMENTED,
            Status::BadGateway => STATUS_BAD_GATEWAY,
            Status::ServiceUnavailable => STATUS_SERVICE_UNAVAILABLE,
            Status::GatewayTimeout => STATUS_GATEWAY_TIMEOUT,
            Status::HttpVersionNotSupported => STATUS_HTTP_VERSION_NOT_SUPPORTED,
            Status::NetworkAuthenticationRequired => STATUS_NETWORK_AUTHENTICATION_REQUIRED,
        }
    }

}

impl Display for Status {

    fn fmt(&self, f: &mut Formatter) -> core::result::Result<(), fmt::Error> {
        f.write_str(match self {
            Status::Continue => "Continue",
            Status::SwitchingProtocols => "Switching Protocols",
            Status::EarlyHints => "Early Hints",
            Status::Ok => "OK",
            Status::Created => "Created",
            Status::Accepted => "Accepted",
            Status::NonAuthoritativeInformation => "Non-Authoritative Information",
            Status::NoContent => "No Content",
            Status::ResetContent => "Reset Content",
            Status::PartialContent => "Partial Content",
            Status::MultipleChoices => "Multiple Choices",
            Status::MovedPermanently => "Moved Permanently",
            Status::Found => "Found",
            Status::SeeOther => "See Other",
            Status::NotModified => "Not Modified",
            Status::TemporaryRedirect => "Temporary Redirect",
            Status::PermanentRedirect => "Permanent Redirect",
            Status::BadRequest => "Bad Request",
            Status::Unauthorized => "Unauthorized",
            Status::PaymentRequired => "Payment Required",
            Status::Forbidden => "Forbidden",
            Status::NotFound => "Not Found",
            Status::MethodNotAllowed => "Method Not Allowed",
            Status::NotAcceptable => "Not Acceptable",
            Status::ProxyAuthenticationRequired => "Proxy Authentication Required",
            Status::RequestTimeout => "Request Timeout",
            Status::Conflict => "Conflict",
            Status::Gone => "Gone",
            Status::LengthRequired => "Length Required",
            Status::PreconditionFailed => "Precondition Failed",
            Status::PayloadTooLarge => "Payload Too Large",
            Status::UriTooLong => "URI Too Long",
            Status::UnsupportedMediaType => "Unsupported Media Type",
            Status::RangeNotSatisfiable => "Range Not Satisfiable",
            Status::ExpectationFailed => "Expectation Failed",
            Status::ImATeapot => "I'm a teapot",
            Status::UnprocessableEntity => "Unprocessable Entity",
            Status::TooEarly => "Too Early",
            Status::UpgradeRequired => "Upgrade Required",
            Status::PreconditionRequired => "Precondition Required",
            Status::TooManyRequests => "Too Many Requests",
            Status::RequestHeaderFieldsTooLarge => "Request Header Fields Too Large",
            Status::UnavailableForLegalReasons => "Unavailable For Legal Reasons",
            Status::InternalServerError => "Internal Server Error",
            Status::NotImplemented => "Not Implemented",
            Status::BadGateway => "Bad Gateway",
            Status::ServiceUnavailable => "Service Unavailable",
            Status::GatewayTimeout => "Gateway Timeout",
            Status::HttpVersionNotSupported => "HTTP Version Not Supported",
            Status::NetworkAuthenticationRequired => "Network Authentication Required",
        })
    }

}

impl TryFrom<u16> for Status {

    type Error = Error;

    fn try_from(n: u16) -> Result<Self, Self::Error> {
        match n {
            STATUS_CONTINUE => Ok(Status::Continue),
            STATUS_SWITCHING_PROTOCOLS => Ok(Status::SwitchingProtocols),
            STATUS_EARLY_HINTS => Ok(Status::EarlyHints),
            STATUS_OK => Ok(Status::Ok),
            STATUS_CREATED => Ok(Status::Created),
            STATUS_ACCEPTED => Ok(Status::Accepted),
            STATUS_NON_AUTHORITATIVE_INFORMATION => Ok(Status::NonAuthoritativeInformation),
            STATUS_NO_CONTENT => Ok(Status::NoContent),
            STATUS_RESET_CONTENT => Ok(Status::ResetContent),
            STATUS_PARTIAL_CONTENT => Ok(Status::PartialContent),
            STATUS_MULTIPLE_CHOICES => Ok(Status::MultipleChoices),
            STATUS_MOVED_PERMANENTLY => Ok(Status::MovedPermanently),
            STATUS_FOUND => Ok(Status::Found),
            STATUS_SEE_OTHER => Ok(Status::SeeOther),
            STATUS_NOT_MODIFIED => Ok(Status::NotModified),
            STATUS_TEMPORARY_REDIRECT => Ok(Status::TemporaryRedirect),
            STATUS_PERMANENT_REDIRECT => Ok(Status::PermanentRedirect),
            STATUS_BAD_REQUEST => Ok(Status::BadRequest),
            STATUS_UNAUTHORIZED => Ok(Status::Unauthorized),
            STATUS_PAYMENT_REQUIRED => Ok(Status::PaymentRequired),
            STATUS_FORBIDDEN => Ok(Status::Forbidden),
            STATUS_NOT_FOUND => Ok(Status::NotFound),
            STATUS_METHOD_NOT_ALLOWED => Ok(Status::MethodNotAllowed),
            STATUS_NOT_ACCEPTABLE => Ok(Status::NotAcceptable),
            STATUS_PROXY_AUTHENTICATION_REQUIRED => Ok(Status::ProxyAuthenticationRequired),
            STATUS_REQUEST_TIMEOUT => Ok(Status::RequestTimeout),
            STATUS_CONFLICT => Ok(Status::Conflict),
            STATUS_GONE => Ok(Status::Gone),
            STATUS_LENGTH_REQUIRED => Ok(Status::LengthRequired),
            STATUS_PRECONDITION_FAILED => Ok(Status::PreconditionFailed),
            STATUS_PAYLOAD_TOO_LARGE => Ok(Status::PayloadTooLarge),
            STATUS_URI_TOO_LONG => Ok(Status::UriTooLong),
            STATUS_UNSUPPORTED_MEDIA_TYPE => Ok(Status::UnsupportedMediaType),
            STATUS_RANGE_NOT_SATISFIABLE => Ok(Status::RangeNotSatisfiable),
            STATUS_EXPECTATION_FAILED => Ok(Status::ExpectationFailed),
            STATUS_IM_A_TEAPOT => Ok(Status::ImATeapot),
            STATUS_UNPROCESSABLE_ENTITY => Ok(Status::UnprocessableEntity),
            STATUS_TOO_EARLY => Ok(Status::TooEarly),
            STATUS_UPGRADE_REQUIRED => Ok(Status::UpgradeRequired),
            STATUS_PRECONDITION_REQUIRED => Ok(Status::PreconditionRequired),
            STATUS_TOO_MANY_REQUESTS => Ok(Status::TooManyRequests),
            STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => Ok(Status::RequestHeaderFieldsTooLarge),
            STATUS_UNAVAILABLE_FOR_LEGAL_REASONS => Ok(Status::UnavailableForLegalReasons),
            STATUS_INTERNAL_SERVER_ERROR => Ok(Status::InternalServerError),
            STATUS_NOT_IMPLEMENTED => Ok(Status::NotImplemented),
            STATUS_BAD_GATEWAY => Ok(Status::BadGateway),
            STATUS_SERVICE_UNAVAILABLE => Ok(Status::ServiceUnavailable),
            STATUS_GATEWAY_TIMEOUT => Ok(Status::GatewayTimeout),
            STATUS_HTTP_VERSION_NOT_SUPPORTED => Ok(Status::HttpVersionNotSupported),
            STATUS_NETWORK_AUTHENTICATION_REQUIRED => Ok(Status::NetworkAuthenticationRequired),
            other => Err(e!("Unknown status: {}", other)),
        }
    }

}

impl FromStr for Status {

    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(u16::from_str(s).map_err(|_| e!("Invalid status: {:?}", s))?)
    }

}

impl TryFrom<&[u8]> for Status {

    type Error = Error;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        let err = e!("Invalid status: {:?}", bytes);

        if bytes.len() > 3 {
            return Err(err);
        }

        let mut n: u16 = 0;
        for (i, b) in bytes.iter().rev().enumerate() {
            match b {
                b'0'..=b'9' => n += u16::from(b - b'0') * 10_u16.pow(i as u32),
                _ => return Err(err),
            };
        }
        Self::try_from(n)
    }

}