Debian Codegraph @

src/media_type_buf.rs

raw symbols SCIP
1 use super::{error::*, media_type::*, name::*, params::*, parse::*, value::*};
2 use alloc::{
3 borrow::Cow,
4 boxed::Box,
5 collections::BTreeMap,
6 string::{String, ToString},
7 vec::Vec,
8 };
9 use core::{
10 fmt,
11 hash::{Hash, Hasher},
12 str::FromStr,
13 };
14
15 /// An owned and immutable media type.
16 ///
17 /// ```
18 /// use mediatype::{names::*, values::*, MediaType, MediaTypeBuf, ReadParams};
19 ///
20 /// let text_plain: MediaTypeBuf = "text/plain; charset=UTF-8".parse().unwrap();
21 /// assert_eq!(text_plain.get_param(CHARSET).unwrap(), UTF_8);
22 ///
23 /// let mut text_markdown: MediaType = text_plain.to_ref();
24 /// text_markdown.subty = MARKDOWN;
25 /// assert_eq!(text_markdown.to_string(), "text/markdown; charset=UTF-8");
26 /// ```
27 #[derive(Debug, Clone)]
28 pub struct MediaTypeBuf {
29 data: Box<str>,
30 indices: Indices,
31 }
32
33 impl MediaTypeBuf {
34 /// Constructs a `MediaTypeBuf` from a top-level type and a subtype.
35 #[must_use]
36 pub fn new(ty: Name, subty: Name) -> Self {
37 Self::from_string([ty.as_str(), "/", subty.as_str()].concat())
38 .expect("`ty` and `subty` should be valid")
39 }
40
41 /// Constructs a `MediaTypeBuf` with an optional suffix and parameters.
42 #[must_use]
43 pub fn from_parts(
44 ty: Name,
45 subty: Name,
46 suffix: Option<Name>,
47 params: &[(Name, Value)],
48 ) -> Self {
49 use core::fmt::Write;
50 let mut s = String::new();
51 write!(s, "{}/{}", ty, subty).expect("`ty` and `subty` should be valid");
52 if let Some(suffix) = suffix {
53 write!(s, "+{}", suffix).unwrap();
54 }
55 for (name, value) in params {
56 write!(s, "; {}={}", name, value).unwrap();
57 }
58 Self::from_string(s).expect("all values should be valid")
59 }
60
61 /// Constructs a `MediaTypeBuf` from [`String`].
62 ///
63 /// Unlike [`FromStr::from_str`], this function takes the ownership of [`String`]
64 /// instead of making a new copy.
65 ///
66 /// # Errors
67 ///
68 /// Returns an error if the string fails to be parsed.
69 ///
70 /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html
71 /// [`FromStr::from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html
72 pub fn from_string(mut s: String) -> Result<Self, MediaTypeError> {
73 let (indices, len) = Indices::parse(&s)?;
74 s.truncate(len);
75 Ok(Self {
76 data: s.into(),
77 indices,
78 })
79 }
80
81 /// Returns the top-level type.
82 #[must_use]
83 pub fn ty(&self) -> Name<'_> {
84 Name::new_unchecked(&self.data[self.indices.ty()])
85 }
86
87 /// Returns the subtype.
88 #[must_use]
89 pub fn subty(&self) -> Name<'_> {
90 Name::new_unchecked(&self.data[self.indices.subty()])
91 }
92
93 /// Returns the suffix.
94 #[must_use]
95 pub fn suffix(&self) -> Option<Name<'_>> {
96 self.indices
97 .suffix()
98 .map(|range| Name::new_unchecked(&self.data[range]))
99 }
100
101 /// Returns a [`MediaType`] without parameters.
102 ///
103 /// ```
104 /// # use mediatype::MediaTypeBuf;
105 /// # use std::str::FromStr;
106 /// let media_type: MediaTypeBuf = "image/svg+xml; charset=UTF-8".parse().unwrap();
107 /// assert_eq!(media_type.essence().to_string(), "image/svg+xml");
108 /// ```
109 ///
110 /// [`MadiaType`]: ./struct.MediaType.html
111 #[must_use]
112 pub fn essence(&self) -> MediaType<'_> {
113 MediaType::from_parts(self.ty(), self.subty(), self.suffix(), &[])
114 }
115
116 /// Returns the underlying string.
117 #[must_use]
118 pub const fn as_str(&self) -> &str {
119 &self.data
120 }
121
122 /// Returns the canonicalized `MediaTypeBuf`.
123 ///
124 /// All strings except parameter values will be converted to lowercase.
125 ///
126 /// ```
127 /// # use mediatype::MediaTypeBuf;
128 /// let media_type: MediaTypeBuf = "IMAGE/SVG+XML; CHARSET=UTF-8; ".parse().unwrap();
129 /// assert_eq!(
130 /// media_type.canonicalize().to_string(),
131 /// "image/svg+xml; charset=UTF-8"
132 /// );
133 /// ```
134 #[must_use]
135 pub fn canonicalize(&self) -> Self {
136 use core::fmt::Write;
137 let mut s = String::with_capacity(self.data.len());
138 write!(
139 s,
140 "{}/{}",
141 self.ty().as_str().to_ascii_lowercase(),
142 self.subty().as_str().to_ascii_lowercase()
143 )
144 .unwrap();
145 if let Some(suffix) = self.suffix() {
146 write!(s, "+{}", suffix.as_str().to_ascii_lowercase())
147 .expect("`write` should not fail on a `String`");
148 }
149 for (name, value) in self.params() {
150 write!(s, "; {}={}", name.as_str().to_ascii_lowercase(), value)
151 .expect("`write` should not fail on a `String`");
152 }
153 s.shrink_to_fit();
154 Self::from_string(s).expect("all values should be valid")
155 }
156
157 /// Constructs a `MediaType` from `self`.
158 #[must_use]
159 pub fn to_ref(&self) -> MediaType<'_> {
160 let params = self.params().collect::<Vec<_>>();
161 let params = if params.is_empty() {
162 Cow::Borrowed([].as_slice())
163 } else {
164 Cow::Owned(params)
165 };
166 MediaType::from_parts_unchecked(self.ty(), self.subty(), self.suffix(), params)
167 }
168 }
169
170 impl ReadParams for MediaTypeBuf {
171 fn params(&self) -> Params<'_> {
172 Params::from_indices(&self.data, &self.indices)
173 }
174
175 fn get_param(&self, name: Name) -> Option<Value<'_>> {
176 self.indices
177 .params()
178 .iter()
179 .rev()
180 .find(|&&[start, end, _, _]| {
181 name == Name::new_unchecked(&self.data[start..end])
182 })
183 .map(|&[_, _, start, end]| {
184 Value::new_unchecked(&self.data[start..end])
185 })
186 }
187 }
188
189 impl FromStr for MediaTypeBuf {
190 type Err = MediaTypeError;
191
192 fn from_str(s: &str) -> Result<Self, Self::Err> {
193 let (indices, len) = Indices::parse(s)?;
194 Ok(Self {
195 data: s[..len].into(),
196 indices,
197 })
198 }
199 }
200
201 impl From<MediaType<'_>> for MediaTypeBuf {
202 fn from(t: MediaType) -> Self {
203 Self::from_string(t.to_string()).expect("`t` should be valid")
204 }
205 }
206
207 impl From<&MediaType<'_>> for MediaTypeBuf {
208 fn from(t: &MediaType) -> Self {
209 Self::from_string(t.to_string()).expect("`t` should be valid")
210 }
211 }
212
213 impl AsRef<str> for MediaTypeBuf {
214 fn as_ref(&self) -> &str {
215 &self.data
216 }
217 }
218
219 impl PartialEq for MediaTypeBuf {
220 fn eq(&self, other: &Self) -> bool {
221 self.ty() == other.ty()
222 && self.subty() == other.subty()
223 && self.suffix() == other.suffix()
224 && self.params().collect::<BTreeMap<_, _>>()
225 == other.params().collect::<BTreeMap<_, _>>()
226 }
227 }
228
229 impl Eq for MediaTypeBuf {}
230
231 impl PartialEq<MediaType<'_>> for MediaTypeBuf {
232 fn eq(&self, other: &MediaType) -> bool {
233 self.ty() == other.ty
234 && self.subty() == other.subty
235 && self.suffix() == other.suffix
236 && self.params().collect::<BTreeMap<_, _>>()
237 == other.params().collect::<BTreeMap<_, _>>()
238 }
239 }
240
241 impl PartialEq<&MediaType<'_>> for MediaTypeBuf {
242 fn eq(&self, other: &&MediaType) -> bool {
243 self == *other
244 }
245 }
246
247 impl PartialEq<MediaType<'_>> for &MediaTypeBuf {
248 fn eq(&self, other: &MediaType) -> bool {
249 *self == other
250 }
251 }
252
253 impl fmt::Display for MediaTypeBuf {
254 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255 write!(f, "{}/{}", self.ty(), self.subty())?;
256 if let Some(suffix) = self.suffix() {
257 write!(f, "+{}", suffix)?;
258 }
259 for (name, value) in self.params() {
260 write!(f, "; {}={}", name, value)?;
261 }
262 Ok(())
263 }
264 }
265
266 impl Hash for MediaTypeBuf {
267 fn hash<H: Hasher>(&self, state: &mut H) {
268 self.ty().hash(state);
269 self.subty().hash(state);
270 self.suffix().hash(state);
271 self.params()
272 .collect::<BTreeMap<_, _>>()
273 .into_iter()
274 .collect::<Vec<_>>()
275 .hash(state);
276 }
277 }
278
279 #[cfg(test)]
280 mod tests {
281 use super::*;
282 use crate::{media_type, names::*, values::*};
283 use alloc::string::ToString;
284 use std::collections::hash_map::DefaultHasher;
285
286 fn calculate_hash<T: Hash>(t: &T) -> u64 {
287 let mut s = DefaultHasher::new();
288 t.hash(&mut s);
289 s.finish()
290 }
291
292 #[test]
293 fn from_parts() {
294 assert_eq!(
295 MediaTypeBuf::from_parts(IMAGE, SVG, Some(XML), &[(CHARSET, UTF_8)]).to_string(),
296 "image/svg+xml; charset=UTF-8"
297 );
298 }
299
300 #[test]
301 fn get_param() {
302 assert_eq!(
303 MediaTypeBuf::from_str("image/svg+xml")
304 .unwrap()
305 .get_param(CHARSET),
306 None
307 );
308 assert_eq!(
309 MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8")
310 .unwrap()
311 .get_param(CHARSET),
312 Some(UTF_8)
313 );
314 assert_eq!(
315 MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8; HELLO=WORLD; HELLO=world")
316 .unwrap()
317 .get_param(Name::new("hello").unwrap()),
318 Some(Value::new("world").unwrap())
319 );
320 }
321
322 #[test]
323 fn essence() {
324 assert_eq!(
325 MediaTypeBuf::from_str("image/svg+xml")
326 .unwrap()
327 .essence()
328 .to_string(),
329 "image/svg+xml"
330 );
331 assert_eq!(
332 MediaTypeBuf::from_str("image/svg+xml; ")
333 .unwrap()
334 .essence()
335 .to_string(),
336 "image/svg+xml"
337 );
338 assert_eq!(
339 MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8")
340 .unwrap()
341 .essence()
342 .to_string(),
343 "image/svg+xml"
344 );
345 assert_eq!(
346 MediaTypeBuf::from_str("image/svg+xml ; charset=UTF-8")
347 .unwrap()
348 .essence()
349 .to_string(),
350 "image/svg+xml"
351 );
352 }
353
354 #[test]
355 fn canonicalize() {
356 assert_eq!(
357 MediaTypeBuf::from_str("IMAGE/SVG+XML; CHARSET=UTF-8; ")
358 .unwrap()
359 .canonicalize()
360 .to_string(),
361 "image/svg+xml; charset=UTF-8"
362 );
363 }
364
365 #[test]
366 fn cmp() {
367 assert_eq!(
368 MediaTypeBuf::from_str("text/plain").unwrap(),
369 MediaTypeBuf::from_str("TEXT/PLAIN").unwrap()
370 );
371 assert_eq!(
372 MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8").unwrap(),
373 MediaTypeBuf::from_str("IMAGE/SVG+XML; CHARSET=UTF-8").unwrap()
374 );
375 assert_eq!(
376 MediaTypeBuf::from_str("image/svg+xml; hello=WORLD; charset=UTF-8").unwrap(),
377 MediaTypeBuf::from_str("IMAGE/SVG+XML; HELLO=WORLD; CHARSET=UTF-8").unwrap()
378 );
379 assert_eq!(
380 MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8").unwrap(),
381 MediaType::from_parts(
382 IMAGE,
383 SVG,
384 Some(XML),
385 &[(CHARSET, US_ASCII), (CHARSET, UTF_8)]
386 ),
387 );
388 assert_eq!(
389 &MediaTypeBuf::from_str("image/svg+xml").unwrap(),
390 media_type!(IMAGE / SVG + XML)
391 );
392 }
393
394 #[test]
395 fn hash() {
396 assert_eq!(
397 calculate_hash(&MediaTypeBuf::from_str("text/plain").unwrap()),
398 calculate_hash(&MediaTypeBuf::from_str("TEXT/PLAIN").unwrap())
399 );
400 assert_eq!(
401 calculate_hash(&MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8").unwrap()),
402 calculate_hash(&MediaTypeBuf::from_str("IMAGE/SVG+XML; CHARSET=UTF-8").unwrap())
403 );
404 assert_eq!(
405 calculate_hash(
406 &MediaTypeBuf::from_str("image/svg+xml; hello=WORLD; charset=UTF-8").unwrap()
407 ),
408 calculate_hash(
409 &MediaTypeBuf::from_str("IMAGE/SVG+XML; HELLO=WORLD; CHARSET=UTF-8").unwrap()
410 )
411 );
412 assert_eq!(
413 calculate_hash(&MediaTypeBuf::from_str("image/svg+xml; charset=UTF-8").unwrap()),
414 calculate_hash(
415 &MediaTypeBuf::from_str("image/svg+xml; charset=US-ASCII; charset=UTF-8").unwrap()
416 ),
417 );
418 }
419 }