Skip to main content

trillium_http/
method.rs

1// originally from https://github.com/http-rs/http-types/blob/main/src/method.rs
2use crate::{Error, util::is_tchar};
3use std::{
4    fmt::{self, Display},
5    str::{self, FromStr},
6};
7
8/// HTTP request methods.
9///
10/// See also [Mozilla's documentation][Mozilla docs], the [RFC7231, Section 4][] and
11/// [IANA's Hypertext Transfer Protocol (HTTP) Method Registry][HTTP Method Registry].
12///
13/// [Mozilla docs]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
14/// [RFC7231, Section 4]: https://tools.ietf.org/html/rfc7231#section-4
15/// [HTTP Method Registry]: https://www.iana.org/assignments/http-methods/http-methods.xhtml
16#[non_exhaustive]
17#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19pub enum Method {
20    /// The ACL method modifies the access control list (which can be read via the DAV:acl
21    /// property) of a resource.
22    ///
23    /// See [RFC3744, Section 8.1][].
24    ///
25    /// [RFC3744, Section 8.1]: https://tools.ietf.org/html/rfc3744#section-8.1
26    Acl,
27
28    /// A collection can be placed under baseline control with a BASELINE-CONTROL request.
29    ///
30    /// See [RFC3253, Section 12.6][].
31    ///
32    /// [RFC3253, Section 12.6]: https://tools.ietf.org/html/rfc3253#section-12.6
33    BaselineControl,
34
35    /// The BIND method modifies the collection identified by the Request- URI, by adding a new
36    /// binding from the segment specified in the BIND body to the resource identified in the BIND
37    /// body.
38    ///
39    /// See [RFC5842, Section 4][].
40    ///
41    /// [RFC5842, Section 4]: https://tools.ietf.org/html/rfc5842#section-4
42    Bind,
43
44    /// A CHECKIN request can be applied to a checked-out version-controlled resource to produce a
45    /// new version whose content and dead properties are copied from the checked-out resource.
46    ///
47    /// See [RFC3253, Section 4.4][] and [RFC3253, Section 9.4][].
48    ///
49    /// [RFC3253, Section 4.4]: https://tools.ietf.org/html/rfc3253#section-4.4
50    /// [RFC3253, Section 9.4]: https://tools.ietf.org/html/rfc3253#section-9.4
51    Checkin,
52
53    /// A CHECKOUT request can be applied to a checked-in version-controlled resource to allow
54    /// modifications to the content and dead properties of that version-controlled resource.
55    ///
56    /// See [RFC3253, Section 4.3][] and [RFC3253, Section 8.8][].
57    ///
58    /// [RFC3253, Section 4.3]: https://tools.ietf.org/html/rfc3253#section-4.3
59    /// [RFC3253, Section 8.8]: https://tools.ietf.org/html/rfc3253#section-8.8
60    Checkout,
61
62    /// The CONNECT method requests that the recipient establish a tunnel to the destination origin
63    /// server identified by the request-target and, if successful, thereafter restrict its
64    /// behavior to blind forwarding of packets, in both directions, until the tunnel is closed.
65    ///
66    /// See [RFC7231, Section 4.3.6][].
67    ///
68    /// [RFC7231, Section 4.3.6]: https://tools.ietf.org/html/rfc7231#section-4.3.6
69    Connect,
70
71    /// The COPY method creates a duplicate of the source resource identified by the Request-URI,
72    /// in the destination resource identified by the URI in the Destination header.
73    ///
74    /// See [RFC4918, Section 9.8][].
75    ///
76    /// [RFC4918, Section 9.8]: https://tools.ietf.org/html/rfc4918#section-9.8
77    Copy,
78
79    /// The DELETE method requests that the origin server remove the association between the target
80    /// resource and its current functionality.
81    ///
82    /// See [RFC7231, Section 4.3.5][].
83    ///
84    /// [RFC7231, Section 4.3.5]: https://tools.ietf.org/html/rfc7231#section-4.3.5
85    Delete,
86
87    /// The GET method requests transfer of a current selected representation for the target
88    /// resource.
89    ///
90    /// See [RFC7231, Section 4.3.1][].
91    ///
92    /// [RFC7231, Section 4.3.1]: https://tools.ietf.org/html/rfc7231#section-4.3.1
93    Get,
94
95    /// The HEAD method is identical to GET except that the server MUST NOT send a message body in
96    /// the response.
97    ///
98    /// See [RFC7231, Section 4.3.2][].
99    ///
100    /// [RFC7231, Section 4.3.2]: https://tools.ietf.org/html/rfc7231#section-4.3.2
101    Head,
102
103    /// A LABEL request can be applied to a version to modify the labels that select that version.
104    ///
105    /// See [RFC3253, Section 8.2][].
106    ///
107    /// [RFC3253, Section 8.2]: https://tools.ietf.org/html/rfc3253#section-8.2
108    Label,
109
110    /// The LINK method establishes one or more Link relationships between the existing resource
111    /// identified by the Request-URI and other existing resources.
112    ///
113    /// See [RFC2068, Section 19.6.1.2][].
114    ///
115    /// [RFC2068, Section 19.6.1.2]: https://tools.ietf.org/html/rfc2068#section-19.6.1.2
116    Link,
117
118    /// The LOCK method is used to take out a lock of any access type and to refresh an existing
119    /// lock.
120    ///
121    /// See [RFC4918, Section 9.10][].
122    ///
123    /// [RFC4918, Section 9.10]: https://tools.ietf.org/html/rfc4918#section-9.10
124    Lock,
125
126    /// The MERGE method performs the logical merge of a specified version (the "merge source")
127    /// into a specified version-controlled resource (the "merge target").
128    ///
129    /// See [RFC3253, Section 11.2][].
130    ///
131    /// [RFC3253, Section 11.2]: https://tools.ietf.org/html/rfc3253#section-11.2
132    Merge,
133
134    /// A MKACTIVITY request creates a new activity resource.
135    ///
136    /// See [RFC3253, Section 13.5].
137    ///
138    /// [RFC3253, Section 13.5]: https://tools.ietf.org/html/rfc3253#section-13.5
139    MkActivity,
140
141    /// An HTTP request using the MKCALENDAR method creates a new calendar collection resource.
142    ///
143    /// See [RFC4791, Section 5.3.1][] and [RFC8144, Section 2.3][].
144    ///
145    /// [RFC4791, Section 5.3.1]: https://tools.ietf.org/html/rfc4791#section-5.3.1
146    /// [RFC8144, Section 2.3]: https://tools.ietf.org/html/rfc8144#section-2.3
147    MkCalendar,
148
149    /// MKCOL creates a new collection resource at the location specified by the Request-URI.
150    ///
151    /// See [RFC4918, Section 9.3][], [RFC5689, Section 3][] and [RFC8144, Section 2.3][].
152    ///
153    /// [RFC4918, Section 9.3]: https://tools.ietf.org/html/rfc4918#section-9.3
154    /// [RFC5689, Section 3]: https://tools.ietf.org/html/rfc5689#section-3
155    /// [RFC8144, Section 2.3]: https://tools.ietf.org/html/rfc5689#section-3
156    MkCol,
157
158    /// The MKREDIRECTREF method requests the creation of a redirect reference resource.
159    ///
160    /// See [RFC4437, Section 6][].
161    ///
162    /// [RFC4437, Section 6]: https://tools.ietf.org/html/rfc4437#section-6
163    MkRedirectRef,
164
165    /// A MKWORKSPACE request creates a new workspace resource.
166    ///
167    /// See [RFC3253, Section 6.3][].
168    ///
169    /// [RFC3253, Section 6.3]: https://tools.ietf.org/html/rfc3253#section-6.3
170    MkWorkspace,
171
172    /// The MOVE operation on a non-collection resource is the logical equivalent of a copy (COPY),
173    /// followed by consistency maintenance processing, followed by a delete of the source, where
174    /// all three actions are performed in a single operation.
175    ///
176    /// See [RFC4918, Section 9.9][].
177    ///
178    /// [RFC4918, Section 9.9]: https://tools.ietf.org/html/rfc4918#section-9.9
179    Move,
180
181    /// The OPTIONS method requests information about the communication options available for the
182    /// target resource, at either the origin server or an intervening intermediary.
183    ///
184    /// See [RFC7231, Section 4.3.7][].
185    ///
186    /// [RFC7231, Section 4.3.7]: https://tools.ietf.org/html/rfc7231#section-4.3.7
187    Options,
188
189    /// The ORDERPATCH method is used to change the ordering semantics of a collection, to change
190    /// the order of the collection's members in the ordering, or both.
191    ///
192    /// See [RFC3648, Section 7][].
193    ///
194    /// [RFC3648, Section 7]: https://tools.ietf.org/html/rfc3648#section-7
195    OrderPatch,
196
197    /// The PATCH method requests that a set of changes described in the request entity be applied
198    /// to the resource identified by the Request- URI.
199    ///
200    /// See [RFC5789, Section 2][].
201    ///
202    /// [RFC5789, Section 2]: https://tools.ietf.org/html/rfc5789#section-2
203    Patch,
204
205    /// The POST method requests that the target resource process the representation enclosed in
206    /// the request according to the resource's own specific semantics.
207    ///
208    /// For example, POST is used for the following functions (among others):
209    ///
210    ///   - Providing a block of data, such as the fields entered into an HTML form, to a
211    ///     data-handling process;
212    ///   - Posting a message to a bulletin board, newsgroup, mailing list, blog, or similar group
213    ///     of articles;
214    ///   - Creating a new resource that has yet to be identified by the origin server; and
215    ///   - Appending data to a resource's existing representation(s).
216    ///
217    /// See [RFC7231, Section 4.3.3][].
218    ///
219    /// [RFC7231, Section 4.3.3]: https://tools.ietf.org/html/rfc7231#section-4.3.3
220    Post,
221
222    /// This method is never used by an actual client. This method will appear to be used when an
223    /// HTTP/1.1 server or intermediary attempts to parse an HTTP/2 connection preface.
224    ///
225    /// See [RFC7540, Section 3.5][] and [RFC7540, Section 11.6][]
226    ///
227    /// [RFC7540, Section 3.5]: https://tools.ietf.org/html/rfc7540#section-3.5
228    /// [RFC7540, Section 11.6]: https://tools.ietf.org/html/rfc7540#section-11.6
229    Pri,
230
231    /// The PROPFIND method retrieves properties defined on the resource identified by the
232    /// Request-URI.
233    ///
234    /// See [RFC4918, Section 9.1][] and [RFC8144, Section 2.1][].
235    ///
236    /// [RFC4918, Section 9.1]: https://tools.ietf.org/html/rfc4918#section-9.1
237    /// [RFC8144, Section 2.1]: https://tools.ietf.org/html/rfc8144#section-2.1
238    PropFind,
239
240    /// The PROPPATCH method processes instructions specified in the request body to set and/or
241    /// remove properties defined on the resource identified by the Request-URI.
242    ///
243    /// See [RFC4918, Section 9.2][] and [RFC8144, Section 2.2][].
244    ///
245    /// [RFC4918, Section 9.2]: https://tools.ietf.org/html/rfc4918#section-9.2
246    /// [RFC8144, Section 2.2]: https://tools.ietf.org/html/rfc8144#section-2.2
247    PropPatch,
248
249    /// The PUT method requests that the state of the target resource be created or replaced with
250    /// the state defined by the representation enclosed in the request message payload.
251    ///
252    /// See [RFC7231, Section 4.3.4][].
253    ///
254    /// [RFC7231, Section 4.3.4]: https://tools.ietf.org/html/rfc7231#section-4.3.4
255    Put,
256
257    /// The QUERY method is used to initiate a server-side query. Unlike the HTTP GET method, which
258    /// requests that a server return a representation of the resource identified by the target
259    /// URI, the QUERY method is used to ask the server to perform a query operation (described
260    /// by the request payload) over some set of data scoped to the effective request URI.  See
261    /// [draft-ietf-httpbis-safe-method-w-body-03][]
262    ///
263    /// NOTE: As of January 2023, this draft has expired.
264    ///
265    /// [draft-ietf-httpbis-safe-method-w-body-03]: https://www.ietf.org/archive/id/draft-ietf-httpbis-safe-method-w-body-03.html
266    Query,
267
268    /// The REBIND method removes a binding to a resource from a collection, and adds a binding to
269    /// that resource into the collection identified by the Request-URI.
270    ///
271    /// See [RFC5842, Section 6][].
272    ///
273    /// [RFC5842, Section 6]: https://tools.ietf.org/html/rfc5842#section-6
274    Rebind,
275
276    /// A REPORT request is an extensible mechanism for obtaining information about a resource.
277    ///
278    /// See [RFC3253, Section 3.6][] and [RFC8144, Section 2.1][].
279    ///
280    /// [RFC3253, Section 3.6]: https://tools.ietf.org/html/rfc3253#section-3.6
281    /// [RFC8144, Section 2.1]: https://tools.ietf.org/html/rfc8144#section-2.1
282    Report,
283
284    /// The client invokes the SEARCH method to initiate a server-side search. The body of the
285    /// request defines the query.
286    ///
287    /// See [RFC5323, Section 2][].
288    ///
289    /// [RFC5323, Section 2]: https://tools.ietf.org/html/rfc5323#section-2
290    Search,
291
292    /// The TRACE method requests a remote, application-level loop-back of the request message.
293    ///
294    /// See [RFC7231, Section 4.3.8][].
295    ///
296    /// [RFC7231, Section 4.3.8]: https://tools.ietf.org/html/rfc7231#section-4.3.8
297    Trace,
298
299    /// The UNBIND method modifies the collection identified by the Request- URI by removing the
300    /// binding identified by the segment specified in the UNBIND body.
301    ///
302    /// See [RFC5842, Section 5][].
303    ///
304    /// [RFC5842, Section 5]: https://tools.ietf.org/html/rfc5842#section-5
305    Unbind,
306
307    /// An UNCHECKOUT request can be applied to a checked-out version-controlled resource to cancel
308    /// the CHECKOUT and restore the pre-CHECKOUT state of the version-controlled resource.
309    ///
310    /// See [RFC3253, Section 4.5][].
311    ///
312    /// [RFC3253, Section 4.5]: https://tools.ietf.org/html/rfc3253#section-4.5
313    Uncheckout,
314
315    /// The UNLINK method removes one or more Link relationships from the existing resource
316    /// identified by the Request-URI.
317    ///
318    /// See [RFC2068, Section 19.6.1.3][].
319    ///
320    /// [RFC2068, Section 19.6.1.3]: https://tools.ietf.org/html/rfc2068#section-19.6.1.3
321    Unlink,
322
323    /// The UNLOCK method removes the lock identified by the lock token in the Lock-Token request
324    /// header.
325    ///
326    /// See [RFC4918, Section 9.11][].
327    ///
328    /// [RFC4918, Section 9.11]: https://tools.ietf.org/html/rfc4918#section-9.11
329    Unlock,
330
331    /// The UPDATE method modifies the content and dead properties of a checked-in
332    /// version-controlled resource (the "update target") to be those of a specified version (the
333    /// "update source") from the version history of that version-controlled resource.
334    ///
335    /// See [RFC3253, Section 7.1][].
336    ///
337    /// [RFC3253, Section 7.1]: https://tools.ietf.org/html/rfc3253#section-7.1
338    Update,
339
340    /// The UPDATEREDIRECTREF method requests the update of a redirect reference resource.
341    ///
342    /// See [RFC4437, Section 7][].
343    ///
344    /// [RFC4437, Section 7]: https://tools.ietf.org/html/rfc4437#section-7
345    UpdateRedirectRef,
346
347    /// A VERSION-CONTROL request can be used to create a version-controlled resource at the
348    /// request-URL.
349    ///
350    /// See [RFC3253, Section 3.5].
351    ///
352    /// [RFC3253, Section 3.5]: https://tools.ietf.org/html/rfc3253#section-3.5
353    VersionControl,
354}
355
356impl Method {
357    /// Predicate that returns whether the method is "safe."
358    ///
359    /// > Request methods are considered "safe" if their defined semantics are
360    /// > essentially read-only; i.e., the client does not request, and does
361    /// > not expect, any state change on the origin server as a result of
362    /// > applying a safe method to a target resource.
363    ///
364    /// -- [rfc7231§4.2.1](https://tools.ietf.org/html/rfc7231#section-4.2.1)
365    pub const fn is_safe(&self) -> bool {
366        matches!(
367            self,
368            Method::Get
369                | Method::Head
370                | Method::Options
371                | Method::Pri
372                | Method::PropFind
373                | Method::Query
374                | Method::Report
375                | Method::Search
376                | Method::Trace
377        )
378    }
379
380    /// predicate that returns whether this method is considered "idempotent".
381    ///
382    /// > A request method is considered "idempotent" if the intended effect on
383    /// > the server of multiple identical requests with that method is the
384    /// > same as the effect for a single such request.
385    ///
386    /// -- [rfc7231§4.2.2](https://tools.ietf.org/html/rfc7231#section-4.2.2)
387    pub const fn is_idempotent(&self) -> bool {
388        self.is_safe() || matches!(self, Method::Put | Method::Delete)
389    }
390
391    /// returns the static str representation of this method
392    pub const fn as_str(&self) -> &'static str {
393        match self {
394            Self::Acl => "ACL",
395            Self::BaselineControl => "BASELINE-CONTROL",
396            Self::Bind => "BIND",
397            Self::Checkin => "CHECKIN",
398            Self::Checkout => "CHECKOUT",
399            Self::Connect => "CONNECT",
400            Self::Copy => "COPY",
401            Self::Delete => "DELETE",
402            Self::Get => "GET",
403            Self::Head => "HEAD",
404            Self::Label => "LABEL",
405            Self::Link => "LINK",
406            Self::Lock => "LOCK",
407            Self::Merge => "MERGE",
408            Self::MkActivity => "MKACTIVITY",
409            Self::MkCalendar => "MKCALENDAR",
410            Self::MkCol => "MKCOL",
411            Self::MkRedirectRef => "MKREDIRECTREF",
412            Self::MkWorkspace => "MKWORKSPACE",
413            Self::Move => "MOVE",
414            Self::Options => "OPTIONS",
415            Self::OrderPatch => "ORDERPATCH",
416            Self::Patch => "PATCH",
417            Self::Post => "POST",
418            Self::Pri => "PRI",
419            Self::PropFind => "PROPFIND",
420            Self::PropPatch => "PROPPATCH",
421            Self::Put => "PUT",
422            Self::Query => "QUERY",
423            Self::Rebind => "REBIND",
424            Self::Report => "REPORT",
425            Self::Search => "SEARCH",
426            Self::Trace => "TRACE",
427            Self::Unbind => "UNBIND",
428            Self::Uncheckout => "UNCHECKOUT",
429            Self::Unlink => "UNLINK",
430            Self::Unlock => "UNLOCK",
431            Self::Update => "UPDATE",
432            Self::UpdateRedirectRef => "UPDATEREDIRECTREF",
433            Self::VersionControl => "VERSION-CONTROL",
434        }
435    }
436
437    pub(crate) fn parse(bytes: &[u8]) -> crate::Result<Self> {
438        match bytes {
439            b"GET" => Ok(Self::Get),
440            b"OPTIONS" => Ok(Self::Options),
441            b"POST" => Ok(Self::Post),
442            b"PUT" => Ok(Self::Put),
443            b"PATCH" => Ok(Self::Patch),
444            b"DELETE" => Ok(Self::Delete),
445            b"HEAD" => Ok(Self::Head),
446            b"ACL" => Ok(Self::Acl),
447            b"BASELINE-CONTROL" => Ok(Self::BaselineControl),
448            b"BIND" => Ok(Self::Bind),
449            b"CHECKIN" => Ok(Self::Checkin),
450            b"CHECKOUT" => Ok(Self::Checkout),
451            b"CONNECT" => Ok(Self::Connect),
452            b"COPY" => Ok(Self::Copy),
453            b"LABEL" => Ok(Self::Label),
454            b"LINK" => Ok(Self::Link),
455            b"LOCK" => Ok(Self::Lock),
456            b"MERGE" => Ok(Self::Merge),
457            b"MKACTIVITY" => Ok(Self::MkActivity),
458            b"MKCALENDAR" => Ok(Self::MkCalendar),
459            b"MKCOL" => Ok(Self::MkCol),
460            b"MKREDIRECTREF" => Ok(Self::MkRedirectRef),
461            b"MKWORKSPACE" => Ok(Self::MkWorkspace),
462            b"MOVE" => Ok(Self::Move),
463            b"ORDERPATCH" => Ok(Self::OrderPatch),
464            b"PRI" => Ok(Self::Pri),
465            b"PROPFIND" => Ok(Self::PropFind),
466            b"PROPPATCH" => Ok(Self::PropPatch),
467            b"QUERY" => Ok(Self::Query),
468            b"REBIND" => Ok(Self::Rebind),
469            b"REPORT" => Ok(Self::Report),
470            b"SEARCH" => Ok(Self::Search),
471            b"TRACE" => Ok(Self::Trace),
472            b"UNBIND" => Ok(Self::Unbind),
473            b"UNCHECKOUT" => Ok(Self::Uncheckout),
474            b"UNLINK" => Ok(Self::Unlink),
475            b"UNLOCK" => Ok(Self::Unlock),
476            b"UPDATE" => Ok(Self::Update),
477            b"UPDATEREDIRECTREF" => Ok(Self::UpdateRedirectRef),
478            b"VERSION-CONTROL" => Ok(Self::VersionControl),
479            _ => {
480                if !bytes.is_empty() && bytes.iter().all(|&b| is_tchar(b)) {
481                    Err(Error::UnrecognizedMethod(
482                        String::from_utf8_lossy(bytes).into_owned(),
483                    ))
484                } else {
485                    Err(Error::InvalidHead)
486                }
487            }
488        }
489    }
490}
491
492impl Display for Method {
493    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494        f.write_str(self.as_ref())
495    }
496}
497
498impl FromStr for Method {
499    type Err = Error;
500
501    fn from_str(s: &str) -> Result<Self, Self::Err> {
502        Self::parse(s.to_ascii_uppercase().as_bytes())
503    }
504}
505
506impl<'a> TryFrom<&'a str> for Method {
507    type Error = Error;
508
509    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
510        Self::from_str(value)
511    }
512}
513
514impl AsRef<str> for Method {
515    fn as_ref(&self) -> &str {
516        self.as_str()
517    }
518}
519
520#[cfg(test)]
521mod test {
522    use super::Method;
523    use std::collections::HashSet;
524
525    #[test]
526    fn names() -> Result<(), crate::Error> {
527        let method_names = [
528            "ACL",
529            "BASELINE-CONTROL",
530            "BIND",
531            "CHECKIN",
532            "CHECKOUT",
533            "CONNECT",
534            "COPY",
535            "DELETE",
536            "GET",
537            "HEAD",
538            "LABEL",
539            "LINK",
540            "LOCK",
541            "MERGE",
542            "MKACTIVITY",
543            "MKCALENDAR",
544            "MKCOL",
545            "MKREDIRECTREF",
546            "MKWORKSPACE",
547            "MOVE",
548            "OPTIONS",
549            "ORDERPATCH",
550            "PATCH",
551            "POST",
552            "PRI",
553            "PROPFIND",
554            "PROPPATCH",
555            "PUT",
556            "QUERY",
557            "REBIND",
558            "REPORT",
559            "SEARCH",
560            "TRACE",
561            "UNBIND",
562            "UNCHECKOUT",
563            "UNLINK",
564            "UNLOCK",
565            "UPDATE",
566            "UPDATEREDIRECTREF",
567            "VERSION-CONTROL",
568        ];
569
570        let methods = method_names
571            .iter()
572            .map(|s| s.parse::<Method>())
573            .collect::<Result<HashSet<_>, _>>()?;
574
575        // check that we didn't accidentally map two methods to the same variant
576        assert_eq!(methods.len(), method_names.len());
577
578        // check that a method's name and the name it is parsed from match
579        for method in methods {
580            assert_eq!(method.as_ref().parse::<Method>()?, method);
581        }
582
583        Ok(())
584    }
585}