1+ macro_rules! define_content_coding {
2+ ( $( $coding: ident; $str: expr, ) +) => {
3+ #[ derive( Copy , Clone , Debug , Eq , PartialEq ) ]
4+ /// Values that are used with headers like `Content-Encoding`
5+ /// [RFC7231](https://www.iana.org/assignments/http-parameters/http-parameters.xhtml)
6+ ///
7+ pub enum ContentCoding {
8+ $(
9+ #[ doc = $str]
10+ $coding,
11+ ) +
12+ }
13+
14+ impl ContentCoding {
15+ /// Returns a static str for a ContentCoding
16+ #[ inline]
17+ pub fn to_static( & self ) -> & ' static str {
18+ match * self {
19+ $( ContentCoding :: $coding => $str, ) +
20+ }
21+ }
22+ }
23+
24+ impl std:: string:: ToString for ContentCoding {
25+ #[ inline]
26+ fn to_string( & self ) -> String {
27+ match * self {
28+ $( ContentCoding :: $coding => $str. to_string( ) , ) +
29+ }
30+ }
31+ }
32+
33+ impl std:: str :: FromStr for ContentCoding {
34+ type Err = & ' static str ;
35+
36+ fn from_str( s: & str ) -> Result <Self , Self :: Err > {
37+ match s {
38+ $(
39+ stringify!( $coding)
40+ | $str => Ok ( ContentCoding :: $coding) ,
41+ ) +
42+ _ => Err ( "invalid content coding" )
43+ }
44+ }
45+ }
46+ }
47+ }
48+
49+ define_content_coding ! {
50+ BROTLI ; "br" ,
51+ COMPRESS ; "compress" ,
52+ DEFLATE ; "deflate" ,
53+ GZIP ; "gzip" ,
54+ IDENTITY ; "identity" ,
55+ }
56+
57+ #[ cfg( test) ]
58+ mod tests {
59+ use super :: ContentCoding ;
60+ use std:: str:: FromStr ;
61+
62+ #[ test]
63+ fn to_static ( ) {
64+ assert_eq ! ( ContentCoding :: GZIP . to_static( ) , "gzip" ) ;
65+ }
66+
67+ #[ test]
68+ fn to_string ( ) {
69+ assert_eq ! ( ContentCoding :: DEFLATE . to_string( ) , "deflate" . to_string( ) ) ;
70+ }
71+
72+ #[ test]
73+ fn from_str ( ) {
74+ assert_eq ! ( ContentCoding :: from_str( "br" ) , Ok ( ContentCoding :: BROTLI ) ) ;
75+ assert_eq ! ( ContentCoding :: from_str( "GZIP" ) , Ok ( ContentCoding :: GZIP ) ) ;
76+ assert_eq ! ( ContentCoding :: from_str( "blah blah" ) , Err ( "invalid content coding" ) ) ;
77+ }
78+ }
0 commit comments