quick-m3u8 0.8.0

Parser for M3U8 Playlist format as defined in HLS draft-pantos-hls-rfc8216
Documentation
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
//! Collection of methods and types used to extract meaning from the value component of a tag line.
//!
//! The value of a tag (when not empty) is everything after the `:` and before the new line break.
//! This module provides types of values and methods for parsing into these types from input data.

#[cfg(not(feature = "chrono"))]
use crate::date::DateTime;
use crate::{
    date,
    error::{
        AttributeListParsingError, DateTimeSyntaxError, DecimalResolutionParseError,
        ParseDecimalFloatingPointWithTitleError, ParseDecimalIntegerRangeError, ParseFloatError,
        ParseNumberError, ParsePlaylistTypeError,
    },
    utils::parse_u64,
};
use memchr::{memchr, memchr3_iter};
use std::{borrow::Cow, collections::HashMap, fmt::Display};

/// A wrapper struct that provides many convenience methods for converting a tag value into a more
/// specialized type.
///
/// The `TagValue` is intended to wrap the bytes following the `:` and before the end of line (not
/// including the `\r` or `\n` characters). The constructor remains public (for convenience, as
/// described below) so bear this in mind if trying to use this struct directly. It is unlikely that
/// a user will need to construct this directly, and instead, should access this via
/// [`crate::tag::UnknownTag::value`] (`Tag` is via [`crate::custom_parsing::tag::parse`]). There
/// may be exceptions and so the library provides this flexibility.
///
/// For example, a (perhaps interesting) use case for using this struct directly can be to parse
/// information out of comment tags. For example, it has been noticed that the Unified Streaming
/// Packager seems to output a custom timestamp comment with its live playlists, that looks like a
/// tag; however, the library will not parse this as a tag because the syntax is
/// `#USP-X-TIMESTAMP-MAP:<attribute-list>`, so the lack of `#EXT` prefix means it is seen as a
/// comment only. Despite this, if we split on the `:`, we can use this struct to extract
/// information about the value.
/// ```
/// # use quick_m3u8::{
/// #     HlsLine, Reader,
/// #     config::ParsingOptions,
/// #     date, date_time,
/// #     custom_parsing::ParsedByteSlice,
/// #     tag::{TagValue, AttributeValue},
/// #     error::ValidationError,
/// # };
/// let pseudo_tag = "#USP-X-TIMESTAMP-MAP:MPEGTS=900000,LOCAL=1970-01-01T00:00:00Z";
/// let mut reader = Reader::from_str(pseudo_tag, ParsingOptions::default());
/// match reader.read_line() {
///     Ok(Some(HlsLine::Comment(tag))) => {
///         let mut tag_split = tag.splitn(2, ':');
///         if tag_split.next() != Some("USP-X-TIMESTAMP-MAP") {
///             return Err(format!("unexpected tag name").into());
///         }
///         let Some(value) = tag_split.next() else {
///             return Err(format!("unexpected no tag value").into());
///         };
///         let tag_value = TagValue(value.trim().as_bytes());
///         let list = tag_value.try_as_attribute_list()?;
///
///         // Prove that we can extract the value of MPEGTS
///         let mpegts = list
///             .get("MPEGTS")
///             .and_then(AttributeValue::unquoted)
///             .ok_or(ValidationError::MissingRequiredAttribute("MPEGTS"))?
///             .try_as_decimal_integer()?;
///         assert_eq!(900000, mpegts);
///
///         // Prove that we can extract the value of LOCAL
///         let local = list
///             .get("LOCAL")
///             .and_then(AttributeValue::unquoted)
///             .and_then(|v| date::parse_bytes(v.0).ok())
///             .ok_or(ValidationError::MissingRequiredAttribute("LOCAL"))?;
///         assert_eq!(date_time!(1970-01-01 T 00:00:00.000), local);
///     }
///     r => return Err(format!("unexpected result {r:?}").into()),
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct TagValue<'a>(pub &'a [u8]);
impl<'a> TagValue<'a> {
    /// Indicates whether the value is empty or not.
    ///
    /// This is only the case if the tag contained a `:` value separator but had no value content
    /// afterwards (before the new line). Under all known circumstances this is an error. If a tag
    /// value is empty then this is indicated via [`crate::tag::UnknownTag::value`] providing
    /// `None`.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Attempt to convert the tag value bytes into a decimal integer.
    ///
    /// For example:
    /// ```
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-EXAMPLE:100")?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(100, value.try_as_decimal_integer()?);
    /// }
    /// # else { panic!("unexpected empty value" ); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_integer(&self) -> Result<u64, ParseNumberError> {
        parse_u64(self.0)
    }

    /// Attempt to convert the tag value bytes into a decimal integer range (`<n>[@<o>]`).
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::tag::DecimalIntegerRange;
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-EXAMPLE:1024@512")?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(
    ///         DecimalIntegerRange {
    ///             length: 1024,
    ///             offset: Some(512)
    ///         },
    ///         value.try_as_decimal_integer_range()?
    ///     );
    /// }
    /// # else { panic!("unexpected empty value" ); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_integer_range(
        &self,
    ) -> Result<DecimalIntegerRange, ParseDecimalIntegerRangeError> {
        DecimalIntegerRange::try_from(self.0)
    }

    /// Attempt to convert the tag value bytes into a playlist type.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::tag::HlsPlaylistType;
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-EXAMPLE:VOD")?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(HlsPlaylistType::Vod, value.try_as_playlist_type()?);
    /// }
    /// # else { panic!("unexpected empty value" ); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_playlist_type(&self) -> Result<HlsPlaylistType, ParsePlaylistTypeError> {
        if self.0 == b"VOD" {
            Ok(HlsPlaylistType::Vod)
        } else if self.0 == b"EVENT" {
            Ok(HlsPlaylistType::Event)
        } else {
            Err(ParsePlaylistTypeError::InvalidValue)
        }
    }

    /// Attempt to convert the tag value bytes into a decimal floating point.
    ///
    /// For example:
    /// ```
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-EXAMPLE:3.14")?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(3.14, value.try_as_decimal_floating_point()?);
    /// }
    /// # else { panic!("unexpected empty value" ); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_floating_point(&self) -> Result<f64, ParseFloatError> {
        fast_float2::parse(self.0).map_err(|_| ParseFloatError)
    }

    /// Attempt to convert the tag value bytes into a decimal floating point with title.
    ///
    /// For example:
    /// ```
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-EXAMPLE:3.14,pi")?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!((3.14, "pi"), value.try_as_decimal_floating_point_with_title()?);
    /// }
    /// # else { panic!("unexpected empty value" ); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_floating_point_with_title(
        &self,
    ) -> Result<(f64, &'a str), ParseDecimalFloatingPointWithTitleError> {
        match memchr(b',', self.0) {
            Some(n) => {
                let duration = fast_float2::parse(&self.0[..n])?;
                let title = std::str::from_utf8(&self.0[(n + 1)..])?;
                Ok((duration, title))
            }
            None => {
                let duration = fast_float2::parse(self.0)?;
                Ok((duration, ""))
            }
        }
    }

    #[cfg(feature = "chrono")]
    /// Attempt to convert the tag value bytes into a date time.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::date_time;
    /// let tag = quick_m3u8::custom_parsing::tag::parse(
    ///     "#EXT-X-EXAMPLE:2025-08-10T17:27:42.213-05:00"
    /// )?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(date_time!(2025-08-10 T 17:27:42.213 -05:00), value.try_as_date_time()?);
    /// }
    /// # else { panic!("unexpected empty value"); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_date_time(
        &self,
    ) -> Result<chrono::DateTime<chrono::FixedOffset>, DateTimeSyntaxError> {
        date::parse_bytes(self.0)
    }
    #[cfg(not(feature = "chrono"))]
    /// Attempt to convert the tag value bytes into a date time.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::date_time;
    /// let tag = quick_m3u8::custom_parsing::tag::parse(
    ///     "#EXT-X-EXAMPLE:2025-08-10T17:27:42.213-05:00"
    /// )?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(date_time!(2025-08-10 T 17:27:42.213 -05:00), value.try_as_date_time()?);
    /// }
    /// # else { panic!("unexpected empty value"); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_date_time(&self) -> Result<DateTime, DateTimeSyntaxError> {
        date::parse_bytes(self.0)
    }

    /// Attempt to convert the tag value bytes into an attribute list.
    ///
    /// For example:
    /// ```
    /// # use std::collections::HashMap;
    /// # use quick_m3u8::tag::{AttributeValue, UnquotedAttributeValue};
    /// let tag = quick_m3u8::custom_parsing::tag::parse(
    ///     "#EXT-X-EXAMPLE:TYPE=LIST,VALUE=\"example\""
    /// )?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(
    ///         HashMap::from([
    ///             ("TYPE", AttributeValue::Unquoted(UnquotedAttributeValue(b"LIST"))),
    ///             ("VALUE", AttributeValue::Quoted("example"))
    ///         ]),
    ///         value.try_as_attribute_list()?
    ///     );
    /// }
    /// # else { panic!("unexpected empty value"); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_attribute_list(
        &self,
    ) -> Result<HashMap<&'a str, AttributeValue<'a>>, AttributeListParsingError> {
        self.try_as_ordered_attribute_list().map(HashMap::from_iter)
    }

    /// Attempt to convert the tag value bytes into an ordered attribute list.
    ///
    /// For example:
    /// ```
    /// # use std::collections::HashMap;
    /// # use quick_m3u8::tag::{AttributeValue, UnquotedAttributeValue};
    /// let tag = quick_m3u8::custom_parsing::tag::parse(
    ///     "#EXT-X-EXAMPLE:TYPE=LIST,VALUE=\"example\""
    /// )?.parsed;
    /// if let Some(value) = tag.value() {
    ///     assert_eq!(
    ///         vec![
    ///             ("TYPE", AttributeValue::Unquoted(UnquotedAttributeValue(b"LIST"))),
    ///             ("VALUE", AttributeValue::Quoted("example"))
    ///         ],
    ///         value.try_as_ordered_attribute_list()?
    ///     );
    /// }
    /// # else { panic!("unexpected empty value"); }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_ordered_attribute_list(
        &self,
    ) -> Result<Vec<(&'a str, AttributeValue<'a>)>, AttributeListParsingError> {
        let mut attribute_list = Vec::new();
        let mut list_iter = memchr3_iter(b'=', b',', b'"', self.0);
        // Name in first position is special because we want to capture the whole value from the
        // previous_match_index (== 0), rather than in the rest of cases, where we want to capture
        // the value at the index after the previous match (which should be b','). Therefore, we use
        // the `next` method to step through the first match and handle it specially, then proceed
        // to loop through the iterator for all others.
        let Some(first_match_index) = list_iter.next() else {
            return Err(AttributeListParsingError::EndOfLineWhileReadingAttributeName);
        };
        if self.0[first_match_index] != b'=' {
            return Err(AttributeListParsingError::UnexpectedCharacterInAttributeName);
        }
        let mut previous_match_index = first_match_index;
        let mut state = AttributeListParsingState::ReadingValue {
            name: std::str::from_utf8(&self.0[..first_match_index])?,
        };
        for i in list_iter {
            let byte = self.0[i];
            match state {
                AttributeListParsingState::ReadingName => {
                    if byte == b'=' {
                        // end of name section
                        let name = std::str::from_utf8(&self.0[(previous_match_index + 1)..i])?;
                        if name.is_empty() {
                            return Err(AttributeListParsingError::EmptyAttributeName);
                        }
                        state = AttributeListParsingState::ReadingValue { name };
                    } else {
                        // b',' and b'"' are both unexpected
                        return Err(AttributeListParsingError::UnexpectedCharacterInAttributeName);
                    }
                    previous_match_index = i;
                }
                AttributeListParsingState::ReadingQuotedValue { name } => {
                    if byte == b'"' {
                        // only byte that ends the quoted value is b'"'
                        let value = std::str::from_utf8(&self.0[(previous_match_index + 1)..i])?;
                        state =
                            AttributeListParsingState::FinishedReadingQuotedValue { name, value };
                        previous_match_index = i;
                    }
                }
                AttributeListParsingState::ReadingValue { name } => {
                    if byte == b'"' {
                        // must check that this is the first character of the value
                        if previous_match_index != (i - 1) {
                            // finding b'"' mid-value is unexpected
                            return Err(
                                AttributeListParsingError::UnexpectedCharacterInAttributeValue,
                            );
                        }
                        state = AttributeListParsingState::ReadingQuotedValue { name };
                    } else if byte == b',' {
                        let value = UnquotedAttributeValue(&self.0[(previous_match_index + 1)..i]);
                        if value.0.is_empty() {
                            // an empty unquoted value is unexpected (only quoted may be empty)
                            return Err(AttributeListParsingError::EmptyUnquotedValue);
                        }
                        attribute_list.push((name, AttributeValue::Unquoted(value)));
                        state = AttributeListParsingState::ReadingName;
                    } else {
                        // b'=' is unexpected while reading value (only b',' or b'"' are expected)
                        return Err(AttributeListParsingError::UnexpectedCharacterInAttributeValue);
                    }
                    previous_match_index = i;
                }
                AttributeListParsingState::FinishedReadingQuotedValue { name, value } => {
                    if byte == b',' {
                        attribute_list.push((name, AttributeValue::Quoted(value)));
                        state = AttributeListParsingState::ReadingName;
                    } else {
                        // b',' (or end of line) must come after end of quote - all else is invalid
                        return Err(AttributeListParsingError::UnexpectedCharacterAfterQuoteEnd);
                    }
                    previous_match_index = i;
                }
            }
        }
        // Need to check state at end of line as this will likely not be a match in the above
        // iteration.
        match state {
            AttributeListParsingState::ReadingName => {
                return Err(AttributeListParsingError::EndOfLineWhileReadingAttributeName);
            }
            AttributeListParsingState::ReadingValue { name } => {
                let value = UnquotedAttributeValue(&self.0[(previous_match_index + 1)..]);
                if value.0.is_empty() {
                    // an empty unquoted value is unexpected (only quoted may be empty)
                    return Err(AttributeListParsingError::EmptyUnquotedValue);
                }
                attribute_list.push((name, AttributeValue::Unquoted(value)));
            }
            AttributeListParsingState::ReadingQuotedValue { name: _ } => {
                return Err(AttributeListParsingError::EndOfLineWhileReadingQuotedValue);
            }
            AttributeListParsingState::FinishedReadingQuotedValue { name, value } => {
                attribute_list.push((name, AttributeValue::Quoted(value)));
            }
        }
        Ok(attribute_list)
    }
}

enum AttributeListParsingState<'a> {
    ReadingName,
    ReadingValue { name: &'a str },
    ReadingQuotedValue { name: &'a str },
    FinishedReadingQuotedValue { name: &'a str, value: &'a str },
}

/// An attribute value within an attribute list.
///
/// Values may be quoted or unquoted. In the case that they are unquoted they may be converted into
/// several other data types. This is done via use of convenience methods on
/// [`UnquotedAttributeValue`].
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum AttributeValue<'a> {
    /// An unquoted value (e.g. `TYPE=AUDIO`, `BANDWIDTH=10000000`, `SCORE=1.5`,
    /// `RESOLUTION=1920x1080`, `SCTE35-OUT=0xABCD`, etc.).
    Unquoted(UnquotedAttributeValue<'a>),
    /// A quoted value (e.g. `CODECS="avc1.64002a,mp4a.40.2"`).
    Quoted(&'a str),
}
impl<'a> AttributeValue<'a> {
    /// A convenience method to get the value of the `Unquoted` case.
    ///
    /// This can be useful when chaining on optional values. For example:
    /// ```
    /// # use std::collections::HashMap;
    /// # use quick_m3u8::tag::AttributeValue;
    /// fn get_bandwidth(list: &HashMap<&str, AttributeValue>) -> Option<u64> {
    ///     list
    ///         .get("BANDWIDTH")
    ///         .and_then(AttributeValue::unquoted)
    ///         .and_then(|v| v.try_as_decimal_integer().ok())
    /// }
    /// ```
    pub fn unquoted(&self) -> Option<UnquotedAttributeValue<'a>> {
        match self {
            AttributeValue::Unquoted(v) => Some(*v),
            AttributeValue::Quoted(_) => None,
        }
    }
    /// A convenience method to get the value of the `Quoted` case.
    ///
    /// This can be useful when chaining on optional values. For example:
    /// ```
    /// # use std::collections::HashMap;
    /// # use quick_m3u8::tag::AttributeValue;
    /// fn get_codecs<'a>(list: &HashMap<&'a str, AttributeValue<'a>>) -> Option<&'a str> {
    ///     list
    ///         .get("CODECS")
    ///         .and_then(AttributeValue::quoted)
    /// }
    /// ```
    pub fn quoted(&self) -> Option<&'a str> {
        match self {
            AttributeValue::Unquoted(_) => None,
            AttributeValue::Quoted(s) => Some(*s),
        }
    }
}

/// A wrapper struct that provides many convenience methods for converting an unquoted attribute
/// value into a specialized type.
///
/// It is very unlikely that this struct will need to be constructed directly. This is more normally
/// found when taking an attribute list tag value and accessing some of the internal attributes. For
/// example:
/// ```
/// # use std::collections::HashMap;
/// # use quick_m3u8::tag::{AttributeValue, UnquotedAttributeValue};
/// # use quick_m3u8::error::{ParseTagValueError, ValidationError};
/// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-EXAMPLE:TYPE=PI,NUMBER=3.14")?.parsed;
/// let list = tag
///     .value()
///     .ok_or(ParseTagValueError::UnexpectedEmpty)?
///     .try_as_attribute_list()?;
///
/// let type_value = list
///     .get("TYPE")
///     .and_then(AttributeValue::unquoted)
///     .ok_or(ValidationError::MissingRequiredAttribute("TYPE"))?;
/// assert_eq!(UnquotedAttributeValue(b"PI"), type_value);
/// assert_eq!(Ok("PI"), type_value.try_as_utf_8());
///
/// let number_value = list
///     .get("NUMBER")
///     .and_then(AttributeValue::unquoted)
///     .ok_or(ValidationError::MissingRequiredAttribute("NUMBER"))?;
/// assert_eq!(UnquotedAttributeValue(b"3.14"), number_value);
/// assert_eq!(Ok(3.14), number_value.try_as_decimal_floating_point());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct UnquotedAttributeValue<'a>(pub &'a [u8]);
impl<'a> UnquotedAttributeValue<'a> {
    /// Attempt to convert the attribute value bytes into a decimal integer.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::tag::AttributeValue;
    /// # use quick_m3u8::error::ParseTagValueError;
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-TEST:EXAMPLE=42")?.parsed;
    /// let list = tag
    ///     .value()
    ///     .ok_or(ParseTagValueError::UnexpectedEmpty)?
    ///     .try_as_attribute_list()?;
    /// assert_eq!(
    ///     Some(42),
    ///     list
    ///         .get("EXAMPLE")
    ///         .and_then(AttributeValue::unquoted)
    ///         .and_then(|v| v.try_as_decimal_integer().ok())
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_integer(&self) -> Result<u64, ParseNumberError> {
        parse_u64(self.0)
    }

    /// Attempt to convert the attribute value bytes into a decimal floating point.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::tag::AttributeValue;
    /// # use quick_m3u8::error::ParseTagValueError;
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-TEST:EXAMPLE=3.14")?.parsed;
    /// let list = tag
    ///     .value()
    ///     .ok_or(ParseTagValueError::UnexpectedEmpty)?
    ///     .try_as_attribute_list()?;
    /// assert_eq!(
    ///     Some(3.14),
    ///     list
    ///         .get("EXAMPLE")
    ///         .and_then(AttributeValue::unquoted)
    ///         .and_then(|v| v.try_as_decimal_floating_point().ok())
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_floating_point(&self) -> Result<f64, ParseFloatError> {
        fast_float2::parse(self.0).map_err(|_| ParseFloatError)
    }

    /// Attempt to convert the attribute value bytes into a decimal resolution.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::tag::{AttributeValue, DecimalResolution};
    /// # use quick_m3u8::error::ParseTagValueError;
    /// let tag = quick_m3u8::custom_parsing::tag::parse("#EXT-X-TEST:EXAMPLE=1920x1080")?.parsed;
    /// let list = tag
    ///     .value()
    ///     .ok_or(ParseTagValueError::UnexpectedEmpty)?
    ///     .try_as_attribute_list()?;
    /// assert_eq!(
    ///     Some(DecimalResolution { width: 1920, height: 1080 }),
    ///     list
    ///         .get("EXAMPLE")
    ///         .and_then(AttributeValue::unquoted)
    ///         .and_then(|v| v.try_as_decimal_resolution().ok())
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_decimal_resolution(
        &self,
    ) -> Result<DecimalResolution, DecimalResolutionParseError> {
        DecimalResolution::try_from(self.0)
    }

    /// Attempt to convert the attribute value bytes into a UTF-8 string.
    ///
    /// For example:
    /// ```
    /// # use quick_m3u8::tag::AttributeValue;
    /// # use quick_m3u8::error::ParseTagValueError;
    /// let tag = quick_m3u8::custom_parsing::tag::parse(
    ///     "#EXT-X-TEST:EXAMPLE=ENUMERATED-VALUE"
    /// )?.parsed;
    /// let list = tag
    ///     .value()
    ///     .ok_or(ParseTagValueError::UnexpectedEmpty)?
    ///     .try_as_attribute_list()?;
    /// assert_eq!(
    ///     Some("ENUMERATED-VALUE"),
    ///     list
    ///         .get("EXAMPLE")
    ///         .and_then(AttributeValue::unquoted)
    ///         .and_then(|v| v.try_as_utf_8().ok())
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_as_utf_8(&self) -> Result<&'a str, std::str::Utf8Error> {
        std::str::from_utf8(self.0)
    }
}

/// The HLS playlist type, as defined in [`#EXT-X-PLAYLIST-TYPE`].
///
/// [`#EXT-X-PLAYLIST-TYPE`]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.4.3.5
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum HlsPlaylistType {
    /// If the `EXT-X-PLAYLIST-TYPE` value is EVENT, Media Segments can only be added to the end of
    /// the Media Playlist.
    Event,
    /// If the `EXT-X-PLAYLIST-TYPE` value is Video On Demand (VOD), the Media Playlist cannot
    /// change.
    Vod,
}

/// Provides a writable version of [`TagValue`].
///
/// This is provided so that custom tag implementations may provide an output that does not depend
/// on having parsed data to derive the write output from. This helps with mutability as well as
/// allowing for custom tags to be constructed from scratch (without being parsed from source data).
///
/// While [`TagValue`] is just a wrapper around a borrowed slice of bytes, `WritableTagValue` is an
/// enumeration of different value types, as this helps keep converting from a custom tag more easy
/// (otherwise all users of the library would need to manage re-constructing the playlist line
/// directly).
#[derive(Debug, PartialEq)]
pub enum WritableTagValue<'a> {
    /// The value is empty.
    ///
    /// For example, the `#EXTM3U` tag has an `Empty` value.
    Empty,
    /// The value is a decimal integer.
    ///
    /// For example, the `#EXT-X-VERSION:<n>` tag has a `DecimalInteger` value (e.g.
    /// `#EXT-X-VERSION:9`).
    DecimalInteger(u64),
    /// The value is a decimal integer range.
    ///
    /// For example, the `#EXT-X-BYTERANGE:<n>[@<o>]` tag has a `DecimalIntegerRange` value (e.g.
    /// `#EXT-X-BYTERANGE:4545045@720`).
    DecimalIntegerRange(u64, Option<u64>),
    /// The value is a float with a string title.
    ///
    /// For example, the `#EXTINF:<duration>,[<title>]` tag has a
    /// `DecimalFloatingPointWithOptionalTitle` value (e.g. `#EXTINF:3.003,free-form text`).
    ///
    /// If the title provided is empty (`""`) then the comma will not be written.
    DecimalFloatingPointWithOptionalTitle(f64, Cow<'a, str>),
    /// The value is a date time.
    ///
    /// For example, the `#EXT-X-PROGRAM-DATE-TIME:<date-time-msec>` tag has a `DateTime` value
    /// (e.g. `#EXT-X-PROGRAM-DATE-TIME:2010-02-19T14:54:23.031+08:00`).
    #[cfg(feature = "chrono")]
    DateTime(chrono::DateTime<chrono::FixedOffset>),
    #[cfg(not(feature = "chrono"))]
    /// The value is a date time.
    ///
    /// For example, the `#EXT-X-PROGRAM-DATE-TIME:<date-time-msec>` tag has a `DateTime` value
    /// (e.g. `#EXT-X-PROGRAM-DATE-TIME:2010-02-19T14:54:23.031+08:00`).
    DateTime(DateTime),
    /// The value is an attribute list.
    ///
    /// For example, the `#EXT-X-MAP:<attribute-list>` tag has an `AttributeList` value (e.g.
    /// `#EXT-X-MAP:URI="init.mp4"`).
    AttributeList(HashMap<Cow<'a, str>, WritableAttributeValue<'a>>),
    /// The value is a UTF-8 string.
    ///
    /// For example, the `#EXT-X-PLAYLIST-TYPE:<type-enum>` tag has a `Utf8` value (e.g.
    /// `#EXT-X-PLAYLIST-TYPE:VOD`).
    ///
    /// Note, this effectively provides the user of the library an "escape hatch" to write any value
    /// that they want.
    ///
    /// Also note, the library does not validate for correctness of the input value, so take care to
    /// not introduce new lines or invalid characters (e.g. whitespace) as this will lead to an
    /// invalid HLS playlist.
    Utf8(Cow<'a, str>),
}
impl From<u64> for WritableTagValue<'_> {
    fn from(value: u64) -> Self {
        Self::DecimalInteger(value)
    }
}
impl From<(u64, Option<u64>)> for WritableTagValue<'_> {
    fn from(value: (u64, Option<u64>)) -> Self {
        Self::DecimalIntegerRange(value.0, value.1)
    }
}
impl<'a, T> From<(f64, T)> for WritableTagValue<'a>
where
    T: Into<Cow<'a, str>>,
{
    fn from(value: (f64, T)) -> Self {
        Self::DecimalFloatingPointWithOptionalTitle(value.0, value.1.into())
    }
}
#[cfg(feature = "chrono")]
impl From<chrono::DateTime<chrono::FixedOffset>> for WritableTagValue<'_> {
    fn from(value: chrono::DateTime<chrono::FixedOffset>) -> Self {
        Self::DateTime(value)
    }
}
#[cfg(not(feature = "chrono"))]
impl From<DateTime> for WritableTagValue<'_> {
    fn from(value: DateTime) -> Self {
        Self::DateTime(value)
    }
}
impl<'a, K, V> From<HashMap<K, V>> for WritableTagValue<'a>
where
    K: Into<Cow<'a, str>>,
    V: Into<WritableAttributeValue<'a>>,
{
    fn from(mut value: HashMap<K, V>) -> Self {
        let mut map = HashMap::new();
        for (key, value) in value.drain() {
            map.insert(key.into(), value.into());
        }
        Self::AttributeList(map)
    }
}
impl<'a, K, V, const N: usize> From<[(K, V); N]> for WritableTagValue<'a>
where
    K: Into<Cow<'a, str>>,
    V: Into<WritableAttributeValue<'a>>,
{
    fn from(value: [(K, V); N]) -> Self {
        let mut map = HashMap::new();
        for (key, value) in value {
            map.insert(key.into(), value.into());
        }
        Self::AttributeList(map)
    }
}
impl<'a> From<Cow<'a, str>> for WritableTagValue<'a> {
    fn from(value: Cow<'a, str>) -> Self {
        Self::Utf8(value)
    }
}
impl<'a> From<&'a str> for WritableTagValue<'a> {
    fn from(value: &'a str) -> Self {
        Self::Utf8(Cow::Borrowed(value))
    }
}
impl<'a> From<String> for WritableTagValue<'a> {
    fn from(value: String) -> Self {
        Self::Utf8(Cow::Owned(value))
    }
}

/// Provides a writable version of [`AttributeValue`].
///
/// This is provided so that custom tag implementations may provide an output that does not depend
/// on having parsed data to derive the write output from. This helps with mutability as well as
/// allowing for custom tags to be constructed from scratch (without being parsed from source data).
///
/// While [`AttributeValue`] is mostly just a wrapper around a borrowed slice of bytes,
/// `WritableAttributeValue` is an enumeration of more value types, as this helps keep converting
/// from a custom tag more easy (otherwise all users of the library would need to manage
/// re-constructing the playlist line directly).
#[derive(Debug, PartialEq, Clone)]
pub enum WritableAttributeValue<'a> {
    /// A decimal integer.
    ///
    /// From [Section 4.2], this represents:
    /// * decimal-integer
    ///
    /// [Section 4.2]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.2
    DecimalInteger(u64),
    /// A signed float.
    ///
    /// From [Section 4.2], this represents:
    /// * decimal-floating-point
    /// * signed-decimal-floating-point
    ///
    /// [Section 4.2]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.2
    SignedDecimalFloatingPoint(f64),
    /// A decimal resolution.
    ///
    /// From [Section 4.2], this represents:
    /// * decimal-resolution
    ///
    /// [Section 4.2]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.2
    DecimalResolution(DecimalResolution),
    /// A quoted string.
    ///
    /// From [Section 4.2], this represents:
    /// * quoted-string
    /// * enumerated-string-list
    ///
    /// [Section 4.2]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.2
    QuotedString(Cow<'a, str>),
    /// An unquoted string.
    ///
    /// From [Section 4.2], this represents:
    /// * hexadecimal-sequence
    /// * enumerated-string
    ///
    /// [Section 4.2]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.2
    ///
    /// Note, this case can be used as an "escape hatch" to write any of the other cases that
    /// resolve from unquoted, but those are provided as convenience.
    ///
    /// Also note, the library does not validate for correctness of the input value, so take care to
    /// not introduce new lines or invalid characters (e.g. whitespace) as this will lead to an
    /// invalid HLS playlist.
    UnquotedString(Cow<'a, str>),
}
impl From<u64> for WritableAttributeValue<'_> {
    fn from(value: u64) -> Self {
        Self::DecimalInteger(value)
    }
}
impl From<f64> for WritableAttributeValue<'_> {
    fn from(value: f64) -> Self {
        Self::SignedDecimalFloatingPoint(value)
    }
}
impl From<DecimalResolution> for WritableAttributeValue<'_> {
    fn from(value: DecimalResolution) -> Self {
        Self::DecimalResolution(value)
    }
}

/// A decimal resolution (`<width>x<height>`).
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DecimalResolution {
    /// A horizontal pixel dimension (width).
    pub width: u64,
    /// A vertical pixel dimension (height).
    pub height: u64,
}
impl Display for DecimalResolution {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}x{}", self.width, self.height)
    }
}
impl TryFrom<&[u8]> for DecimalResolution {
    type Error = DecimalResolutionParseError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let Some(i) = memchr(b'x', value) else {
            return Err(DecimalResolutionParseError::MissingSeparator);
        };
        let width =
            parse_u64(&value[..i]).map_err(|_| DecimalResolutionParseError::InvalidWidth)?;
        let height =
            parse_u64(&value[(i + 1)..]).map_err(|_| DecimalResolutionParseError::InvalidHeight)?;
        Ok(DecimalResolution { width, height })
    }
}
impl TryFrom<&str> for DecimalResolution {
    type Error = DecimalResolutionParseError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::try_from(s.as_bytes())
    }
}

/// Represents the decimal-integer-range that is found in several places, from tag values to
/// attribute values, and has structure `<n>[@<o>]`.
///
/// For example:
/// ```
/// # use quick_m3u8::tag::DecimalIntegerRange;
/// assert_eq!(
///     DecimalIntegerRange {
///         length: 1024,
///         offset: Some(512)
///     },
///     DecimalIntegerRange::try_from("1024@512")?
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DecimalIntegerRange {
    /// Corresponds to the length component in the value (`n` in `<n>@<o>`).
    pub length: u64,
    /// Corresponds to the offset component in the value (`o` in `<n>@<o>`).
    pub offset: Option<u64>,
}
impl Display for DecimalIntegerRange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(offset) = self.offset {
            write!(f, "{}@{}", self.length, offset)
        } else {
            write!(f, "{}", self.length)
        }
    }
}
impl TryFrom<&[u8]> for DecimalIntegerRange {
    type Error = ParseDecimalIntegerRangeError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        match memchr(b'@', value) {
            Some(n) => {
                let length =
                    parse_u64(&value[..n]).map_err(ParseDecimalIntegerRangeError::InvalidLength)?;
                let offset = parse_u64(&value[(n + 1)..])
                    .map_err(ParseDecimalIntegerRangeError::InvalidOffset)?;
                Ok(Self {
                    length,
                    offset: Some(offset),
                })
            }
            None => parse_u64(value)
                .map(|length| Self {
                    length,
                    offset: None,
                })
                .map_err(ParseDecimalIntegerRangeError::InvalidLength),
        }
    }
}
impl TryFrom<&str> for DecimalIntegerRange {
    type Error = ParseDecimalIntegerRangeError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::try_from(s.as_bytes())
    }
}

#[cfg(test)]
mod tests {
    use crate::date_time;

    use super::*;
    use pretty_assertions::assert_eq;

    #[test]
    fn type_enum() {
        let value = TagValue(b"EVENT");
        assert_eq!(Ok(HlsPlaylistType::Event), value.try_as_playlist_type());

        let value = TagValue(b"VOD");
        assert_eq!(Ok(HlsPlaylistType::Vod), value.try_as_playlist_type());
    }

    #[test]
    fn decimal_integer() {
        let value = TagValue(b"42");
        assert_eq!(Ok(42), value.try_as_decimal_integer());
    }

    #[test]
    fn decimal_integer_range() {
        let value = TagValue(b"42@42");
        assert_eq!(
            Ok(DecimalIntegerRange {
                length: 42,
                offset: Some(42)
            }),
            value.try_as_decimal_integer_range()
        );
    }

    #[test]
    fn decimal_floating_point_with_optional_title() {
        // Positive tests
        let value = TagValue(b"42.0");
        assert_eq!(
            Ok((42.0, "")),
            value.try_as_decimal_floating_point_with_title()
        );
        let value = TagValue(b"42.42");
        assert_eq!(
            Ok((42.42, "")),
            value.try_as_decimal_floating_point_with_title()
        );
        let value = TagValue(b"42,");
        assert_eq!(
            Ok((42.0, "")),
            value.try_as_decimal_floating_point_with_title()
        );
        let value = TagValue(b"42,=ATTRIBUTE-VALUE");
        assert_eq!(
            Ok((42.0, "=ATTRIBUTE-VALUE")),
            value.try_as_decimal_floating_point_with_title()
        );
        // Negative tests
        let value = TagValue(b"-42.0");
        assert_eq!(
            Ok((-42.0, "")),
            value.try_as_decimal_floating_point_with_title()
        );
        let value = TagValue(b"-42.42");
        assert_eq!(
            Ok((-42.42, "")),
            value.try_as_decimal_floating_point_with_title()
        );
        let value = TagValue(b"-42,");
        assert_eq!(
            Ok((-42.0, "")),
            value.try_as_decimal_floating_point_with_title()
        );
        let value = TagValue(b"-42,=ATTRIBUTE-VALUE");
        assert_eq!(
            Ok((-42.0, "=ATTRIBUTE-VALUE")),
            value.try_as_decimal_floating_point_with_title()
        );
    }

    #[test]
    fn date_time_msec() {
        let value = TagValue(b"2025-06-03T17:56:42.123Z");
        assert_eq!(
            Ok(date_time!(2025-06-03 T 17:56:42.123)),
            value.try_as_date_time(),
        );
        let value = TagValue(b"2025-06-03T17:56:42.123+01:00");
        assert_eq!(
            Ok(date_time!(2025-06-03 T 17:56:42.123 01:00)),
            value.try_as_date_time(),
        );
        let value = TagValue(b"2025-06-03T17:56:42.123-05:00");
        assert_eq!(
            Ok(date_time!(2025-06-03 T 17:56:42.123 -05:00)),
            value.try_as_date_time(),
        );
    }

    mod attribute_list {
        use super::*;

        macro_rules! unquoted_value_test {
            (TagValue is $tag_value:literal $($name_lit:literal=$val:literal expects $exp:literal from $method:ident)+) => {
                let value = TagValue($tag_value);
                assert_eq!(
                    value.try_as_attribute_list().expect("should be valid list"),
                    HashMap::from([
                        $(
                            ($name_lit, AttributeValue::Unquoted(UnquotedAttributeValue($val))),
                        )+
                    ])
                );
                assert_eq!(
                    value.try_as_ordered_attribute_list().expect("should be valid ordered list"),
                    vec![
                        $(
                            ($name_lit, AttributeValue::Unquoted(UnquotedAttributeValue($val))),
                        )+
                    ]
                );
                $(
                    assert_eq!(Ok($exp), UnquotedAttributeValue($val).$method());
                )+
            };
        }

        macro_rules! quoted_value_test {
            (TagValue is $tag_value:literal $($name_lit:literal expects $exp:literal)+) => {
                let value = TagValue($tag_value);
                assert_eq!(
                    value.try_as_attribute_list().expect("should be valid list"),
                    HashMap::from([
                        $(
                            ($name_lit, AttributeValue::Quoted($exp)),
                        )+
                    ])
                );
                assert_eq!(
                    value.try_as_ordered_attribute_list().expect("should be valid list"),
                    vec![
                        $(
                            ($name_lit, AttributeValue::Quoted($exp)),
                        )+
                    ]
                );
            };
        }

        mod decimal_integer {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn single_attribute() {
                unquoted_value_test!(
                    TagValue is b"NAME=123"
                    "NAME"=b"123" expects 123 from try_as_decimal_integer
                );
            }

            #[test]
            fn multi_attributes() {
                unquoted_value_test!(
                    TagValue is b"NAME=123,NEXT-NAME=456"
                    "NAME"=b"123" expects 123 from try_as_decimal_integer
                    "NEXT-NAME"=b"456" expects 456 from try_as_decimal_integer
                );
            }
        }

        mod signed_decimal_floating_point {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn positive_float_single_attribute() {
                unquoted_value_test!(
                    TagValue is b"NAME=42.42"
                    "NAME"=b"42.42" expects 42.42 from try_as_decimal_floating_point
                );
            }

            #[test]
            fn negative_integer_single_attribute() {
                unquoted_value_test!(
                    TagValue is b"NAME=-42"
                    "NAME"=b"-42" expects -42.0 from try_as_decimal_floating_point
                );
            }

            #[test]
            fn negative_float_single_attribute() {
                unquoted_value_test!(
                    TagValue is b"NAME=-42.42"
                    "NAME"=b"-42.42" expects -42.42 from try_as_decimal_floating_point
                );
            }

            #[test]
            fn positive_float_multi_attributes() {
                unquoted_value_test!(
                    TagValue is b"NAME=42.42,NEXT-NAME=84.84"
                    "NAME"=b"42.42" expects 42.42 from try_as_decimal_floating_point
                    "NEXT-NAME"=b"84.84" expects 84.84 from try_as_decimal_floating_point
                );
            }

            #[test]
            fn negative_integer_multi_attributes() {
                unquoted_value_test!(
                    TagValue is b"NAME=-42,NEXT-NAME=-84"
                    "NAME"=b"-42" expects -42.0 from try_as_decimal_floating_point
                    "NEXT-NAME"=b"-84" expects -84.0 from try_as_decimal_floating_point
                );
            }

            #[test]
            fn negative_float_multi_attributes() {
                unquoted_value_test!(
                    TagValue is b"NAME=-42.42,NEXT-NAME=-84.84"
                    "NAME"=b"-42.42" expects -42.42 from try_as_decimal_floating_point
                    "NEXT-NAME"=b"-84.84" expects -84.84 from try_as_decimal_floating_point
                );
            }
        }

        mod quoted_string {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn single_attribute() {
                quoted_value_test!(
                    TagValue is b"NAME=\"Hello, World!\""
                    "NAME" expects "Hello, World!"
                );
            }

            #[test]
            fn multi_attributes() {
                quoted_value_test!(
                    TagValue is b"NAME=\"Hello,\",NEXT-NAME=\"World!\""
                    "NAME" expects "Hello,"
                    "NEXT-NAME" expects "World!"
                );
            }
        }

        mod unquoted_string {
            use super::*;
            use pretty_assertions::assert_eq;

            #[test]
            fn single_attribute() {
                unquoted_value_test!(
                    TagValue is b"NAME=PQ"
                    "NAME"=b"PQ" expects "PQ" from try_as_utf_8
                );
            }

            #[test]
            fn multi_attributes() {
                unquoted_value_test!(
                    TagValue is b"NAME=PQ,NEXT-NAME=HLG"
                    "NAME"=b"PQ" expects "PQ" from try_as_utf_8
                    "NEXT-NAME"=b"HLG" expects "HLG" from try_as_utf_8
                );
            }
        }
    }
}