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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
use std::collections::HashMap;
use std::iter::{Iterator, ExactSizeIterator};
use std::slice;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::fmt::{self, Debug, Display};

use error::{Error, ParserErrorRef};
use name::{Name, CHARSET, MULTIPART};
use value::{Value, UTF_8, UTF8};
use gen::{
    create_buffer_from,
    push_params_to_buffer,
    push_param_to_buffer
};

use parse::{Spec, ParseResult, ParamIndices, parse, validate};


#[derive(Clone, Debug)]
pub struct MediaType<S: Spec> {
    inner: AnyMediaType,
    _spec: PhantomData<S>
}

impl<S> MediaType<S>
    where S: Spec
{
    pub fn parse(input: &str) -> Result<Self, ParserErrorRef> {
        let parse_result: ParseResult = parse::<S>(input)?;
        let media_type: AnyMediaType = parse_result.into();
        Ok(MediaType { inner: media_type, _spec: PhantomData })
    }

    pub fn validate(input: &str) -> bool {
        validate::<S>(input)
    }

    pub fn new<T, ST>(type_: T, subtype: ST) -> Result<Self, Error>
        where T: AsRef<str>, ST: AsRef<str>
    {
        let (buffer, slash_idx, end_of_type) =
            create_buffer_from::<S>(type_.as_ref(), subtype.as_ref())?;
        Ok(MediaType {
            inner: AnyMediaType {
                buffer,
                slash_idx,
                end_of_type,
                params: Vec::new()
            },
            _spec: PhantomData
        })
    }

    pub fn new_with_params<T, ST, PI, IN, IV>(
        type_: T, subtype: ST, params: PI
    )-> Result<Self, Error>
        where T: AsRef<str>,
              ST: AsRef<str>,
              PI: IntoIterator<Item=(IN, IV)>,
              IN: AsRef<str>,
              IV: AsRef<str> //<- we would want something here which can take a Value
    {
        let (mut buffer, slash_idx, end_of_type) =
            create_buffer_from::<S>(type_.as_ref(), subtype.as_ref())?;

        let param_indices =
            push_params_to_buffer::<S, _, _, _>(&mut buffer, params)?;

        Ok(MediaType {
            inner: AnyMediaType {
                buffer,
                slash_idx,
                end_of_type,
                params: param_indices,
            },
            _spec: PhantomData
        })

    }

    /// removes the first param equal to `name`, returns true if a parameter was returned
    ///
    /// If PartialEq is implemented as excepted at only up to one parameter names can match
    /// the given name, through even if more would match the function removes the first match
    /// and returns.
    ///
    /// If no parameter matches `name` nothing is changed and `false` is returned.
    pub fn remove_param<N>(&mut self, name: N) -> bool
        where N: for<'a> PartialEq<Name<'a>>
    {
        let mut found = None;
        let mut previous_end = self.end_of_type;
        for (idx, indices) in self.params.iter().enumerate() {
            if name == Name::new_unchecked(&self.buffer[indices.start..indices.eq_idx]) {
                // indices.start is > previous_end, previous_end is before the
                // ; of the next param, indices.start is after, as we want to
                // remove everything accosiated with the param we use previous_end
                found = Some((idx, previous_end, indices.end));
                break;
            } else {
                previous_end = indices.end;
            }
        }

        if let Some((idx, start, end)) = found {
            let size_diff = end - start;
            let mut tail = self.buffer[end..].to_owned();
            self.buffer.truncate(start);
            self.buffer.push_str(&*tail);
            self.params.remove(idx);
            // idx now points on the first element which needs fixing or the end of the array
            for old_indices in self.params[idx..].iter_mut() {
                old_indices.start -= size_diff;
                old_indices.eq_idx -= size_diff;
                old_indices.end -= size_diff;
            }
            true
        } else {
            false
        }
    }

    //TODO handle encodeing (parameters ending in *)
    /// set a given parameter to a give value, overriding the old parameter
    ///
    /// If there already exists a parameter with the same name the
    /// parameter is overridden.
    ///
    /// If there the parameter is not part of the media type it is added.
    ///
    /// Note that parameters are order-independent given rfc2045, as such
    /// the order parameters will have after this function was used is
    /// implementation dependent and can change. Mainly this means that
    /// this function _could_ replace the parameter in place or _could_
    /// remove it and add the new parameter the end or insert it in the
    /// beginning.
    pub fn set_param<N, V>(&mut self, name: N, value: V)
        where N: AsRef<str>, V: AsRef<str>
    {
        //OPTIMIZE this can be done MUCH more efficient with unsafe writes,
        // e.g. replace_slice(&mut String, Slice, String) or
        //   overwrite_slice(&mut String, Slice, W) where FnOnce(&mut Writer) or so
        let name = name.as_ref();
        let value = value.as_ref();
        self.remove_param(name);
        let indices =
            push_param_to_buffer::<S>(&mut self.buffer, name, value)
                .expect("[BUG] parameter name matched existing parameter but was also invalid");
        self.params.push(indices);
    }
}


macro_rules! conversions {
    ($($tp:ty => $tp2:ty;)*) => (
        mod conversion_impl_ns { $(
            #[allow(unused_imports)]
            use spec::*;

            impl From<$crate::MediaType<$tp>> for $crate::MediaType<$tp2> {
                fn from(media_type: $crate::MediaType<$tp>) -> $crate::MediaType<$tp2> {
                    $crate::MediaType {
                        inner: media_type.inner,
                        _spec: ::std::marker::PhantomData
                    }
                }
            }
        )* }
    );
}

//FUTURE_TODO: once specialization lands and is aviable for From imple
// From<MediaType<S>> for MediaType<S2> where S2: From<S>, currently this
// won't work due to conflicting implementations
conversions! {
    MimeSpec<Ascii, Obs> => MimeSpec<Internationalized, Obs>;
    MimeSpec<Ascii, Modern> => MimeSpec<Ascii, Obs>;
    MimeSpec<Ascii, Modern> => MimeSpec<Internationalized, Obs>;
    MimeSpec<Ascii, Modern> => MimeSpec<Internationalized, Modern>;
    MimeSpec<Internationalized, Modern> => MimeSpec<Internationalized, Obs>;
    HttpSpec<Modern> => HttpSpec<Obs>;
    StrictSpec => HttpSpec<Modern>;
    StrictSpec => HttpSpec<Obs>;
    StrictSpec => MimeSpec<Ascii, Obs>;
    StrictSpec => MimeSpec<Ascii, Modern>;
    StrictSpec => MimeSpec<Internationalized, Obs>;
    StrictSpec => MimeSpec<Internationalized, Modern>;
    StrictSpec => AnySpec;
    HttpSpec<Modern> => AnySpec;
    HttpSpec<Obs> => AnySpec;
    MimeSpec<Ascii, Obs> => AnySpec;
    MimeSpec<Ascii, Modern> => AnySpec;
    MimeSpec<Internationalized, Obs> => AnySpec;
    MimeSpec<Internationalized, Modern> => AnySpec;
}

impl<S1, S2> PartialEq<MediaType<S2>> for MediaType<S1>
    where S1: Spec, S2: Spec
{
    // Spec is just about parsing/normalizing etc. we can compare independent of it
    fn eq(&self, other: &MediaType<S2>) -> bool {
        self.deref() == other.deref()
    }
}

impl<S> Deref for MediaType<S>
    where S: Spec
{
    type Target = AnyMediaType;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<S> DerefMut for MediaType<S>
    where S: Spec
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

impl<S> Into<AnyMediaType> for MediaType<S>
    where S: Spec
{
    fn into(self) -> AnyMediaType {
        self.inner
    }
}

impl<S> Display for MediaType<S>
    where S: Spec
{
    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        fter.write_str(self.as_str_repr())
    }
}


#[derive(Clone,  Debug)]
pub struct AnyMediaType {
    //idx layout
    //                              /plus_idx if there is no suffix, buffer.len() if there are no parameters
    //                             /
    //  type /  subtype  + suffix  ; <space>  param_name    =   param_value  ; <space> pn = pv
    //       \           \         \          \             \                \          \
    //        \slash_idx  \plus_idx \          \             \eon_idx         \ofv_idx   \prev eov_idx + 2
    //                               \eot_idx   \prev eov_idx +2 == eot_idx + 2 if first param
    buffer: String,
    slash_idx: usize,
    /// is equal the end_type_idx if there is no plus
    //plus_idx: usize,
    /// it is the index behind the last character of the subtype(inkl. suffix) which is equal to the
    /// index of the ";" of the first parameter or the len of the buffer if there are no parameter
    end_of_type: usize,
    params: Vec<ParamIndices>
}

impl AnyMediaType {

    pub fn type_(&self) -> Name {
        Name::new_unchecked(&self.buffer[..self.slash_idx])
    }

    pub fn subtype(&self) -> Name {
        Name::new_unchecked(&self.buffer[self.slash_idx+1..self.end_of_type])
        //Name::new_unchecked(&self.buffer[self.slash_idx+1..self.plus_idx])
    }

    pub fn full_type(&self) -> Name {
        Name::new_unchecked(&self.buffer[..self.end_of_type])
    }

//    pub fn suffix(&self) -> Option<Name> {
//        let suffix_start = self.plus_idx+1;
//        let end_idx = self.end_of_type;
//        if suffix_start < end_idx {
//            Some(Name::new_unchecked(&self.buffer[suffix_start..end_idx]))
//        } else {
//            None
//        }
//    }

    pub fn get_param<'a, N>(&'a self, attr: N) -> Option<Value<'a>>
        where N: PartialEq<Name<'a>>
    {
        self.params()
            .find(|nv| attr == nv.0)
            .map(|(_name, value)| value)
    }

    pub fn params(&self) -> Params {
        Params {
            iter: self.params.iter(),
            source: self.buffer.as_str()
        }
    }

    pub fn as_str_repr(&self) -> &str {
        self.buffer.as_str()
    }

    pub fn has_utf8_charset(&self) -> bool {
        self.get_param(CHARSET)
            .map(|cs_param| {
                //FIXME use eq_ascii_case_insensitive
                cs_param == UTF_8 || cs_param == UTF8
            })
            .unwrap_or(false)
    }

    pub fn is_multipart(&self) -> bool {
        self.type_() == MULTIPART
    }

}


impl PartialEq for AnyMediaType {
    fn eq(&self, other: &AnyMediaType) -> bool {
        if self.type_() != other.type_()
            || self.subtype() != other.subtype()
            //|| self.suffix() != other.suffix()
        {
            return false;
        } else {
            let len = self.params.len();
            let other_len = other.params.len();
            if len != other_len { return false; }
            match len {
                0 => true,

                //OPTIMIZATION: most media types have very little parameter, so we can avoid
                // the "costy order independent comparsion" for them
                1 => {
                    let (name, value) = self.params().next().unwrap();
                    let (other_name, other_value) = other.params().next().unwrap();
                    return name == other_name && value == other_value
                },
                2 => {
                    let mut params = self.params();
                    let mut other_params = other.params();
                    let (name1, value1) = params.next().unwrap();
                    let (other_name1, other_value1) = other_params.next().unwrap();
                    let (name2, value2) = params.next().unwrap();
                    let (other_name2, other_value2) = other_params.next().unwrap();
                    if name1 == other_name1 {
                        return value1 == other_value1
                            && name2 == other_name2 && value2 == other_value2
                    } else {
                        return
                            name1 == other_name2 && value1 == other_value2
                                && name2 == other_name1 && value2 == other_value1
                    }
                },
                _ => {
                    //TODO Optimized use on stack map, sort compare?
                    let map = self.params().collect::<HashMap<_, _>>();
                    // we already checked that the len of both is the same
                    // so if all params of other are in map they are equal
                    other.params()
                        .all(|(other_name, other_value)| {
                            map.get(&other_name)
                                .map(|value| other_value == *value)
                                .unwrap_or(false)
                        })
                }
            }
        }
    }
}


impl<'a> From<ParseResult<'a>> for AnyMediaType {

    fn from(pres: ParseResult) -> Self {
        let mut buffer;
        if pres.params.len() == 0 {
            buffer = pres.input[..pres.repr_len()].to_ascii_lowercase();
        } else {
            buffer = String::from(&pres.input[..pres.repr_len()]);

            buffer[0..pres.end_of_type_idx]
                .make_ascii_lowercase();

            for param_indices in pres.params.iter() {
                buffer[param_indices.start..param_indices.eq_idx].make_ascii_lowercase();
            }
        }

        AnyMediaType {
            buffer,
            slash_idx: pres.slash_idx,
            end_of_type: pres.end_of_type_idx,
            params: pres.params
        }
    }
}

impl Display for AnyMediaType {
    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        fter.write_str(self.as_str_repr())
    }
}




#[derive(Clone)]
pub struct Params<'a> {
    source: &'a str,
    iter: slice::Iter<'a, ParamIndices>
}

impl<'a> Iterator for Params<'a> {
    type Item = (Name<'a>, Value<'a>);

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
            .map(|pidx| {
                //TODO OPTIMIZE:
                //   using unsafe slace removes ca. 30% of the comparsion time
                //   (for text/plain; param=value)

                let name = &self.source[pidx.start..pidx.eq_idx];
                let value = &self.source[pidx.eq_idx+1..pidx.end];
                (Name::new_unchecked(name), Value::new_unchecked(value))
            })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl<'a> ExactSizeIterator for Params<'a> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl<'a> Debug for Params<'a> {

    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        let metoo = self.clone();
        fter.debug_list()
            .entries(metoo)
            .finish()
    }
}



#[cfg(test)]
mod test {
    use super::{AnyMediaType, MediaType};
    use parse::{AnySpec, StrictSpec};
    use spec::*;

    #[test]
    fn simple_parse() {
        let mt: MediaType<_> = assert_ok!(MediaType::<AnySpec>::parse("text/plain; charset=utf-8"));
        assert!(mt.has_utf8_charset());
        assert_eq!(mt.as_str_repr(), "text/plain; charset=utf-8");
    }

    #[test]
    fn parsing_does_not_normalizes_whitespaces() {
        let mt: MediaType<_> = assert_ok!(MediaType::<AnySpec>::parse("text/plain   ;charset=utf-8"));
        assert!(mt.has_utf8_charset());
        assert_eq!(mt.as_str_repr(), "text/plain   ;charset=utf-8");
    }

    #[test]
    fn parsing_does_not_normalized_utf8() {
        let mt: MediaType<_> = assert_ok!(MediaType::<AnySpec>::parse("text/plain; charset=utf8"));
        assert!(mt.has_utf8_charset());
        assert_eq!(mt.as_str_repr(), "text/plain; charset=utf8");
    }


    #[test]
    fn params_iter_behaviour() {
        let mt: MediaType<AnySpec> = assert_ok!(MediaType::parse("test/plain; c1=abc; c2=def"));
        let mut iter = mt.params();
        assert_eq!(iter.len(), 2);
        assert_eq!(iter.size_hint(), (2, Some(2)));

        let p1 = iter.next().unwrap();
        assert_eq!(p1.0, "c1");
        assert_eq!(p1.1, "abc");
        assert_eq!(iter.len(), 1);
        assert_eq!(iter.size_hint(), (1, Some(1)));

        let p1 = iter.next().unwrap();
        assert_eq!(p1.0, "c2");
        assert_eq!(p1.1, "def");
        assert_eq!(iter.len(), 0);
        assert_eq!(iter.size_hint(), (0, Some(0)));

        assert_eq!(iter.next(), None);
    }

    #[test]
    fn any_media_type_eq() {
        let mt1: AnyMediaType = assert_ok!(
            MediaType::<AnySpec>::parse("text/plain; p1=\"a\"; p2=b")).into();
        let mt2: AnyMediaType = assert_ok!(
            MediaType::<AnySpec>::parse("text/plain; p2=\"b\"; p1=a")).into();

        assert_eq!(mt1, mt2);
    }

    #[test]
    fn media_type_eq_different_spec() {
        let mt1 = assert_ok!(
            MediaType::<AnySpec>::parse("text/plain; p1=\"a\"; p2=b"));
        let mt2 = assert_ok!(
            MediaType::<StrictSpec>::parse("text/plain; p2=\"b\"; p1=a"));

        assert_eq!(mt1, mt2);
    }

    mod new {
        use super::super::MediaType;
        use error::{Error, ErrorKind, ExpectedChar};
        use spec::HttpSpec;

        #[test]
        fn accepts_name_struct() {
            use name::{TEXT, PLAIN};
            let mt = MediaType::<HttpSpec>::new(TEXT, PLAIN).unwrap();
            assert_eq!(mt.as_str_repr(), "text/plain");
        }

        #[test]
        fn validates_type() {
            let mt = MediaType::<HttpSpec>::new("ba{d", "ok");
            assert_eq!(mt, Err(Error::new("ba{d", ErrorKind::UnexpectedChar {
                pos: 2,
                expected: ExpectedChar::CharClass("token char")
            })))
        }

        #[test]
        fn validates_subtype() {
            let mt = MediaType::<HttpSpec>::new("text", "n[k");
            assert_eq!(mt, Err(Error::new("n[k", ErrorKind::UnexpectedChar {
                pos: 1,
                expected: ExpectedChar::CharClass("token char")
            })));
        }

        #[test]
        fn parses_typical_type() {
            let mt = MediaType::<HttpSpec>::new("text", "x.example.imagination.rawtext+xml")
                .unwrap();
            assert_eq!(mt.as_str_repr(), "text/x.example.imagination.rawtext+xml")
        }
    }

    mod new_with_params {
        use super::super::MediaType;
        use error::{Error, ErrorKind, ExpectedChar};
        use spec::{HttpSpec, MimeSpec, Ascii, Modern};

        fn empty() -> Vec<(&'static str, &'static str)> {
            Vec::new()
        }

        #[test]
        fn validates_type() {
            let mt = MediaType::<HttpSpec>::new_with_params("ba{d", "ok", empty());
            assert_eq!(mt, Err(Error::new("ba{d", ErrorKind::UnexpectedChar {
                pos: 2,
                expected: ExpectedChar::CharClass("token char")
            })))
        }

        #[test]
        fn validates_subtype() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "n[k", empty());
            assert_eq!(mt, Err(Error::new("n[k", ErrorKind::UnexpectedChar {
                pos: 1,
                expected: ExpectedChar::CharClass("token char")
            })));
        }

        #[test]
        fn validates_parameter_names() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "x.my", vec![
                ("good", "value"),
                ("b[ad]", "key")
            ]);
            assert_eq!(mt, Err(Error::new("b[ad]", ErrorKind::UnexpectedChar {
                pos: 1,
                expected: ExpectedChar::CharClass("token char")
            })))
        }


        #[test]
        fn simple_creation_works() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "plain", empty());
            assert_eq!(mt.unwrap().as_str_repr(), "text/plain")
        }

        #[test]
        fn creation_with_parameters_works() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "plain", vec![
                ("charset", "utf-8")
            ]);
            assert_eq!(mt.unwrap().as_str_repr(), "text/plain; charset=utf-8");
        }

        #[test]
        fn use_quoting_if_needed() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "x.plain", vec![
                ("charset", "utf-8"),
                ("source", "dat file")
            ]);
            assert_eq!(
                mt.unwrap().as_str_repr(),
                "text/x.plain; charset=utf-8; source=\"dat file\""
            );
        }

        #[test]
        fn use_quoted_pair_if_needed() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "x.mage", vec![
                ("comment", "it\"has")
            ]);
            assert_eq!(
                mt.unwrap().as_str_repr(),
                r#"text/x.mage; comment="it\"has""#
            );
        }

        #[test]
        fn use_perc_encode_for_values_if_needed() {
            let mt = MediaType::<HttpSpec>::new_with_params("text", "x.my", vec![
                ("key", "va\0lue")
            ]);
            assert_eq!(
                mt.unwrap().as_str_repr(),
                "text/x.my; key*=utf-8''va%00lue"
            )
        }

        #[test]
        fn in_mime_obs_0_is_quoted() {
            let mt = MediaType::<MimeSpec>::new_with_params("text", "x.my", vec![
                ("foo", "b\0r")
            ]);
            assert_eq!(
                mt.unwrap().as_str_repr(),
                "text/x.my; foo=\"b\\\0r\""
            );
        }

        #[test]
        fn in_mime_modern_0_is_pencoded() {
            let mt = MediaType::<MimeSpec<Ascii, Modern>>::new_with_params("text", "x.my", vec![
                ("foo", "b\0r")
            ]);
            assert_eq!(
                mt.unwrap().as_str_repr(),
                "text/x.my; foo*=utf-8''b%00r"
            );
        }
    }

    mod remove_param {
        use super::super::MediaType;
        use spec::HttpSpec;

        #[test]
        fn no_param() {
            let mut mt = MediaType::<HttpSpec>::new("text", "plain").unwrap();
            assert_eq!(mt.remove_param("charset"), false);
            assert_eq!(mt.as_str_repr(), "text/plain");
        }

        #[test]
        fn only_other_params() {
            let mut mt = MediaType::<HttpSpec>::new_with_params("text", "plain", vec![
                ("barset", "baromatish")
            ]).unwrap();
            assert_eq!(mt.remove_param("charset"), false);
            assert_eq!(mt.as_str_repr(), "text/plain; barset=baromatish");
        }

        #[test]
        fn at_the_end() {
            let mut mt = MediaType::<HttpSpec>::new_with_params("text", "plain", vec![
                ("charset", "NeoUtf8")
            ]).unwrap();
            assert_eq!(mt.remove_param("charset"), true);
            assert_eq!(mt.as_str_repr(), "text/plain");
        }

        #[test]
        fn in_between_other_params() {
            let mut mt = MediaType::<HttpSpec>::new_with_params("text", "plain", vec![
                ("foo", "bar"),
                ("charset", "NeoUtf8"),
                ("bar", "foot")
            ]).unwrap();
            assert_eq!(mt.remove_param("charset"), true);
            assert_eq!(mt.as_str_repr(), "text/plain; foo=bar; bar=foot");
        }
    }

    mod set_param {
        use super::super::MediaType;
        use spec::HttpSpec;

        #[test]
        fn add_to_empty() {
            let mut mt = MediaType::<HttpSpec>::new("text","plain").unwrap();
            mt.set_param("charset", "utf-8");
            assert_eq!(mt.as_str_repr(), "text/plain; charset=utf-8")
        }

        #[test]
        fn add_additional_one() {
            let mut mt = MediaType::<HttpSpec>::new_with_params("text","plain", vec![
                ("foo", "bar")
            ]).unwrap();
            mt.set_param("charset", "utf-8");
            assert_eq!(mt.as_str_repr(), "text/plain; foo=bar; charset=utf-8")
        }

        #[test]
        fn replace_at_end() {
            let mut mt = MediaType::<HttpSpec>::new_with_params("text","plain", vec![
                ("foo", "bar"),
                ("charset", "NeoUtf8")
            ]).unwrap();
            mt.set_param("charset", "utf-8");
            assert_eq!(mt.as_str_repr(), "text/plain; foo=bar; charset=utf-8")
        }

        #[test]
        fn replace_in_between_other_params() {
            let mut mt = MediaType::<HttpSpec>::new_with_params("text","plain", vec![
                ("foo", "bar"),
                ("charset", "NeoUtf8"),
                ("bar", "foot")
            ]).unwrap();
            mt.set_param("charset", "utf-8");
            assert_eq!(mt.as_str_repr(), "text/plain; foo=bar; bar=foot; charset=utf-8")
        }
    }

    #[test]
    fn media_type_conversion_mime() {
        let top = MediaType::<StrictSpec>::parse("text/plain").unwrap();

        let m_mam: MediaType<MimeSpec<Ascii, Modern>> = top.clone().into();
        assert_eq!(m_mam.as_str_repr(), "text/plain");
        let m_mao: MediaType<MimeSpec<Ascii, Obs>> = top.clone().into();
        assert_eq!(m_mao.as_str_repr(), "text/plain");
        let m_mim: MediaType<MimeSpec<Internationalized, Modern>> = m_mam.clone().into();
        assert_eq!(m_mim.as_str_repr(), "text/plain");
        let m_mio1: MediaType<MimeSpec<Internationalized, Obs>> = m_mao.clone().into();
        assert_eq!(m_mio1.as_str_repr(), "text/plain");
        let m_mio2: MediaType<MimeSpec<Internationalized, Obs>> = m_mim.clone().into();
        assert_eq!(m_mio2.as_str_repr(), "text/plain");
        let m_mio3: MediaType<MimeSpec<Internationalized, Obs>> = m_mam.clone().into();
        assert_eq!(m_mio3.as_str_repr(), "text/plain");

        let m_mim2: MediaType<MimeSpec<Internationalized, Modern>> = top.clone().into();
        assert_eq!(m_mam.as_str_repr(), "text/plain");
        let m_mio4: MediaType<MimeSpec<Internationalized, Obs>> = top.clone().into();
        assert_eq!(m_mao.as_str_repr(), "text/plain");

        let m_as: &[MediaType<AnySpec>] = &[
            m_mam.into(),
            m_mao.into(),
            m_mim.into(),
            m_mim2.into(),
            m_mio1.into(),
            m_mio2.into(),
            m_mio3.into(),
            m_mio4.into()
        ];
        for m_a in m_as.iter() {
            assert_eq!(m_a.as_str_repr(), "text/plain");
        }

    }

    #[test]
    fn media_type_conversion_http() {
        let top = MediaType::<StrictSpec>::parse("text/plain").unwrap();

        let m_o: MediaType<HttpSpec<Obs>> = top.clone().into();
        assert_eq!(m_o.as_str_repr(), "text/plain");
        let m_m: MediaType<HttpSpec<Modern>> = top.clone().into();
        assert_eq!(m_m.as_str_repr(), "text/plain");
        let m_o2: MediaType<HttpSpec<Obs>> = m_m.clone().into();
        assert_eq!(m_o2.as_str_repr(), "text/plain");

        let m_as: &[MediaType<AnySpec>] = &[
            m_m.into(),
            m_o.into(),
            m_o2.into()
        ];
        for m_a in m_as.iter() {
            assert_eq!(m_a.as_str_repr(), "text/plain");
        }

    }

    #[test]
    fn is_multipart() {
        let mt = MediaType::<HttpSpec>::new("multipart", "mixed").unwrap();
        assert_eq!(mt.is_multipart(), true);
        let mt = MediaType::<HttpSpec>::new("application", "text").unwrap();
        assert_eq!(mt.is_multipart(), false);
    }
}