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
use super::parse::*;
use std::{
    borrow::Cow,
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    iter,
};

/// A media-type parameter value.
///
/// The constructor accepts both an unquoted string and a quoted string like `"Hello Wold!"`.
/// If the string is not quoted, the allowed characters are
/// alphabets, numbers and `!#$&-^_.+%*'`.
///
/// ```
/// # use mediatype::Value;
/// let utf8 = Value::new("UTF-8").unwrap();
/// let utf8_quoted = Value::new("\"UTF-8\"").unwrap();
/// assert_eq!(utf8, utf8_quoted);
/// assert_eq!(utf8_quoted.as_str(), "\"UTF-8\"");
/// assert_eq!(utf8_quoted.unquoted_str(), "UTF-8");
///
/// let double_quoted = Value::new("\" \\\" \"").unwrap();
/// assert_eq!(double_quoted.as_str(), "\" \\\" \"");
/// assert_eq!(double_quoted.unquoted_str(), " \" ");
/// ```
#[derive(Debug, Copy, Clone)]
pub struct Value<'a>(&'a str);

impl<'a> Value<'a> {
    /// Constructs a `Value`.
    ///
    /// If the string is not valid as a value, returns `None`.
    #[must_use]
    pub fn new(s: &'a str) -> Option<Self> {
        if let Some(quoted) = s.strip_prefix('\"') {
            if quoted.len() > 1 && parse_quoted_value(quoted) == Ok(quoted.len()) {
                return Some(Self(s));
            }
        } else if is_restricted_str(s) {
            return Some(Self(s));
        }
        None
    }

    /// Returns the underlying string.
    #[must_use]
    pub const fn as_str(&self) -> &'a str {
        self.0
    }

    /// Returns the unquoted string.
    #[must_use]
    pub fn unquoted_str(&self) -> Cow<'_, str> {
        if self.0.starts_with('"') {
            let inner = &self.0[1..self.0.len() - 1];
            if inner.contains('\\') {
                let mut s = String::with_capacity(inner.len());
                let mut quoted = false;
                for c in inner.chars() {
                    match c {
                        _ if quoted => {
                            quoted = false;
                            s.push(c);
                        }
                        '\\' => {
                            quoted = true;
                        }
                        _ => {
                            s.push(c);
                        }
                    }
                }
                Cow::Owned(s)
            } else {
                Cow::Borrowed(inner)
            }
        } else {
            Cow::Borrowed(self.0)
        }
    }

    /// Generates a quoted string if necessary.
    ///
    /// ```
    /// # use mediatype::Value;
    /// assert_eq!(Value::quote("UTF-8"), "UTF-8");
    /// assert_eq!(Value::quote("Hello world!"), "\"Hello world!\"");
    /// assert_eq!(
    ///     Value::quote(r#" "What's wrong?" "#),
    ///     "\" \\\"What's wrong\\?\\\" \""
    /// );
    /// ```
    #[must_use]
    pub fn quote(s: &str) -> Cow<'_, str> {
        if is_restricted_str(s) {
            Cow::Borrowed(s)
        } else {
            let inner = s.chars().flat_map(|c| {
                if is_restricted_char(c) || c == ' ' {
                    vec![c]
                } else {
                    vec!['\\', c]
                }
            });
            let quoted = iter::once('"').chain(inner).chain(iter::once('"'));
            Cow::Owned(quoted.collect())
        }
    }

    pub(crate) const fn new_unchecked(s: &'a str) -> Self {
        Self(s)
    }
}

impl<'a> fmt::Display for Value<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0)
    }
}

impl<'a> PartialEq for Value<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.unquoted_str() == other.unquoted_str()
    }
}

impl<'a> Eq for Value<'a> {}

impl<'a> PartialOrd for Value<'a> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a> Ord for Value<'a> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.unquoted_str().cmp(&other.unquoted_str())
    }
}

impl<'a> Hash for Value<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.unquoted_str().hash(state);
    }
}

impl<'a> PartialEq<String> for Value<'a> {
    fn eq(&self, other: &String) -> bool {
        self.eq(other.as_str())
    }
}

impl<'a> PartialOrd<String> for Value<'a> {
    fn partial_cmp(&self, other: &String) -> Option<Ordering> {
        self.partial_cmp(other.as_str())
    }
}

impl<'a> PartialEq<&String> for Value<'a> {
    fn eq(&self, other: &&String) -> bool {
        self.eq(other.as_str())
    }
}

impl<'a> PartialOrd<&String> for Value<'a> {
    fn partial_cmp(&self, other: &&String) -> Option<Ordering> {
        self.partial_cmp(other.as_str())
    }
}

impl<'a> PartialEq<str> for Value<'a> {
    fn eq(&self, other: &str) -> bool {
        self.unquoted_str() == other
    }
}

impl<'a> PartialOrd<str> for Value<'a> {
    fn partial_cmp(&self, other: &str) -> Option<Ordering> {
        Some(self.unquoted_str().as_ref().cmp(other))
    }
}

impl<'a> PartialEq<&str> for Value<'a> {
    fn eq(&self, other: &&str) -> bool {
        self.eq(*other)
    }
}

impl<'a> PartialOrd<&str> for Value<'a> {
    fn partial_cmp(&self, other: &&str) -> Option<Ordering> {
        self.partial_cmp(*other)
    }
}

impl<'a> PartialEq<Cow<'_, str>> for Value<'a> {
    fn eq(&self, other: &Cow<'_, str>) -> bool {
        self.eq(other.as_ref())
    }
}

impl<'a> PartialOrd<Cow<'_, str>> for Value<'a> {
    fn partial_cmp(&self, other: &Cow<'_, str>) -> Option<Ordering> {
        self.partial_cmp(other.as_ref())
    }
}

impl<'a> PartialEq<&Cow<'_, str>> for Value<'a> {
    fn eq(&self, other: &&Cow<'_, str>) -> bool {
        self.eq(other.as_ref())
    }
}

impl<'a> PartialOrd<&Cow<'_, str>> for Value<'a> {
    fn partial_cmp(&self, other: &&Cow<'_, str>) -> Option<Ordering> {
        self.partial_cmp(other.as_ref())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn unquoted_str() {
        assert_eq!(Value::new("\"\\a\\\\\"").unwrap().unquoted_str(), "a\\");
        assert_eq!(Value::new("\"\\\"\"").unwrap().unquoted_str(), "\"");
        assert_eq!(Value::new("\"\\a\\b\\c\"").unwrap().unquoted_str(), "abc");
        assert_eq!(
            Value::new("\" \\\"What's wrong\\?\\\" \"")
                .unwrap()
                .unquoted_str(),
            r#" "What's wrong?" "#
        );
    }
}