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
//! Constructs to reason about date and time in HLS
//!
//! The structs offered here don't provide much functionality. The purpose is primarily
//! informational. These types can be used with another date/time library (such as [chrono]) for
//! more feature rich date/time comparisons and operations.
//!
//! [chrono]: https://crates.io/crates/chrono

use crate::error::DateTimeSyntaxError;
#[cfg(not(feature = "chrono"))]
use crate::utils::parse_date_time_bytes;
#[cfg(not(feature = "chrono"))]
use std::fmt::Display;

#[cfg(feature = "chrono")]
/// A macro to help constructing a [`chrono::DateTime`] struct.
///
/// Given that there are a lot of fields to the `DateTime` struct, for convenience this macro is
/// provided, so a date can be constructed more easily. The syntax is intended to mimic [RFC3339].
/// For example:
/// ```
/// # use quick_m3u8::date_time;
/// assert_eq!(
///     date_time!(2025-07-30 T 22:44:38.718 -05:00),
///     chrono::NaiveDate::from_ymd_opt(2025, 7, 30).unwrap()
///         .and_hms_milli_opt(22, 44, 38, 718).unwrap()
///         .and_local_timezone(chrono::FixedOffset::west_opt(5 * 3600).unwrap())
///         .earliest().unwrap()
/// )
/// ```
///
/// ## Input validation
///
/// The macro is also able to validate input looks correct (with the exception of the `$D` parameter
/// which depends on which month is used, so it just validates that the value passed is less than
/// 31).
///
/// Each of the following will fail compilation (thus providing some compile-time safety to usage):
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-00-01 T 00:00:00.000);        // Month not greater than 0
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-13-01 T 00:00:00.000);        // Month greater than 12
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-00 T 00:00:00.000);        // Day not greater than 0
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-32 T 00:00:00.000);        // Day greater than 31
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 24:00:00.000);        // Hour greater than 23
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:60:00.000);        // Minute greater than 59
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:-1.000);        // Seconds negative
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:60.000);        // Seconds greater than 59
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:00.000 -24:00); // Hour offset less than -23
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:00.000 24:00);  // Hour offset more than 23
/// ```
///
/// [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
#[macro_export]
macro_rules! date_time {
    ($Y:literal-$M:literal-$D:literal T $h:literal:$m:literal:$s:literal) => {{
    const D: chrono::NaiveDate = date_time!(@INTERNAL @DATE $Y-$M-$D);
    const T: chrono::NaiveTime = date_time!(@INTERNAL @TIME $h:$m:$s);
        D.and_time(T).and_utc().fixed_offset()
    }};
    ($Y:literal-$M:literal-$D:literal T $h:literal:$m:literal:$s:literal $x:literal:$y:literal) => {{
    const D: chrono::NaiveDate = date_time!(@INTERNAL @DATE $Y-$M-$D);
    const T: chrono::NaiveTime = date_time!(@INTERNAL @TIME $h:$m:$s);
    const TZ: chrono::FixedOffset = date_time!(@INTERNAL @TIMEZONE $x:$y);
        // The rest may panic at runtime.
        D.and_time(T).and_local_timezone(TZ).earliest().unwrap()
    }};
    (@INTERNAL @DATE $Y:literal-$M:literal-$D:literal) => {{
        const D: Option<chrono::NaiveDate> = chrono::NaiveDate::from_ymd_opt($Y, $M, $D);
        const _: () = assert!(D.is_some(), "Invalid date");
        D.unwrap()
    }};
    (@INTERNAL @TIME $h:literal:$m:literal:$s:literal) => {{
        const _: () = assert!($s >= 0.0, "Seconds must be positive");
        const S: u32 = $s as u32;
        const MS: u32 = (($s * 1000.0 as f64).round() % 1000.0) as u32;
        const T: Option<chrono::NaiveTime> = chrono::NaiveTime::from_hms_milli_opt($h, $m, S, MS);
        const _: () = assert!(T.is_some(), "Invalid time");
        T.unwrap()
    }};
    (@INTERNAL @TIMEZONE $x:literal:$y:literal) => {{
        const _: () = assert!($y >= 0, "Minutes must be positive");
        const TZ_H: i32 = ($x as i32).abs() as i32;
        const TZ_M: i32 = $y as i32;
        const MULTIPLIER: i32 = if $x == TZ_H { 1 } else { -1 };
        const TZ: Option<chrono::FixedOffset> =
            chrono::FixedOffset::east_opt(MULTIPLIER * ((TZ_H * 3600) + (TZ_M * 60)));
        const _: () = assert!(TZ.is_some(), "Invalid timezone offset");
        TZ.unwrap()
    }};
}
#[cfg(not(feature = "chrono"))]
/// A macro to help constructing a [`DateTime`] struct.
///
/// Given that there are a lot of fields to the `DateTime` struct, for convenience this macro is
/// provided, so a date can be constructed more easily. The syntax is intended to mimic [RFC3339].
/// For example:
/// ```
/// # use quick_m3u8::{date_time, date::{DateTime, DateTimeTimezoneOffset}};
/// assert_eq!(
///     date_time!(2025-07-30 T 22:44:38.718 -05:00),
///     DateTime {
///         date_fullyear: 2025,
///         date_month: 7,
///         date_mday: 30,
///         time_hour: 22,
///         time_minute: 44,
///         time_second: 38.718,
///         timezone_offset: DateTimeTimezoneOffset {
///             time_hour: -5,
///             time_minute: 0,
///         },
///     }
/// )
/// ```
///
/// ## Input validation
///
/// The macro is also able to validate input looks correct (with the exception of the `$D` parameter
/// which depends on which month is used, so it just validates that the value passed is less than
/// 31).
///
/// Each of the following will fail compilation (thus providing some compile-time safety to usage):
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(10000-01-01 T 00:00:00.000);       // Year greater than 4 digits
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-00-01 T 00:00:00.000);        // Month not greater than 0
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-13-01 T 00:00:00.000);        // Month greater than 12
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-00 T 00:00:00.000);        // Day not greater than 0
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-32 T 00:00:00.000);        // Day greater than 31
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 24:00:00.000);        // Hour greater than 23
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:60:00.000);        // Minute greater than 59
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:-1.000);        // Seconds negative
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:60.000);        // Seconds greater than 59
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:00.000 -24:00); // Hour offset less than -23
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:00.000 24:00);  // Hour offset more than 23
/// ```
/// ```compile_fail
/// # use quick_m3u8::date_time;
/// let bad_date = date_time!(1970-01-01 T 00:00:00.000 00:60);  // Minute offset more than 59
/// ```
///
/// [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
#[macro_export]
macro_rules! date_time {
    ($Y:literal-$M:literal-$D:literal T $h:literal:$m:literal:$s:literal) => {
        date_time!($Y-$M-$D T $h:$m:$s 0:0)
    };
    ($Y:literal-$M:literal-$D:literal T $h:literal:$m:literal:$s:literal $x:literal:$y:literal) => {{
        const _: () = assert!($Y <= 9999, "Year must be at most 4 digits");
        const _: () = assert!($M > 0, "Month must be greater than 0");
        const _: () = assert!($M <= 12, "Month must be less than or equal to 12");
        const _: () = assert!($D > 0, "Day must be greater than 0");
        const _: () = assert!($D <= 31, "Day must be less than or equal to 31");
        const _: () = assert!($h < 24, "Hour must be less than 24");
        const _: () = assert!($m < 60, "Minute must be less than 60");
        const _: () = assert!($s >= 0.0, "Seconds must be positive");
        const _: () = assert!($s < 60.0, "Seconds must be less than 60.0");
        const _: () = assert!($x > -24, "Hour offset must be greater than -24");
        const _: () = assert!($x < 24, "Hour offset must be less than 24");
        const _: () = assert!($y < 60, "Minute offset must be less than 60");
        $crate::date::DateTime {
            date_fullyear: $Y,
            date_month: $M,
            date_mday: $D,
            time_hour: $h,
            time_minute: $m,
            time_second: $s,
            timezone_offset: $crate::date::DateTimeTimezoneOffset {
                time_hour: $x,
                time_minute: $y,
            },
        }
    }};
}

#[cfg(not(feature = "chrono"))]
/// A struct representing a date in the format of [RFC3339].
///
/// [RFC3339]: https://datatracker.ietf.org/doc/html/rfc3339#section-5.6
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct DateTime {
    /// The full year (must be `4DIGIT`).
    pub date_fullyear: u32,
    /// The month (`1-12`).
    pub date_month: u8,
    /// The day (`1-31`).
    pub date_mday: u8,
    /// The hour (`0-23`).
    pub time_hour: u8,
    /// The minute (`0-59`).
    pub time_minute: u8,
    /// The seconds, including millisconds (seconds are `0-59`, while the mantissa may be any
    /// length, though HLS recommends milliscond accuracy via the [EXT-X-PROGRAM-DATE-TIME]
    /// documentation).
    ///
    /// [EXT-X-PROGRAM-DATE-TIME]: https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-18#section-4.4.4.6
    pub time_second: f64,
    /// The timezone offset.
    pub timezone_offset: DateTimeTimezoneOffset,
}

#[cfg(not(feature = "chrono"))]
impl Display for DateTime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:06.3}{}",
            self.date_fullyear,
            self.date_month,
            self.date_mday,
            self.time_hour,
            self.time_minute,
            self.time_second,
            self.timezone_offset
        )
    }
}

#[cfg(not(feature = "chrono"))]
impl From<DateTime> for String {
    fn from(value: DateTime) -> Self {
        format!("{value}")
    }
}

#[cfg(not(feature = "chrono"))]
impl Default for DateTime {
    fn default() -> Self {
        Self {
            date_fullyear: 1970,
            date_month: 1,
            date_mday: 1,
            time_hour: 0,
            time_minute: 0,
            time_second: 0.0,
            timezone_offset: Default::default(),
        }
    }
}

#[cfg(not(feature = "chrono"))]
/// The timezone offset.
#[derive(Debug, PartialEq, Clone, Copy, Default)]
pub struct DateTimeTimezoneOffset {
    /// The hour offset (plus or minus `0-23`).
    pub time_hour: i8,
    /// The minute offset (`0-59`).
    pub time_minute: u8,
}

#[cfg(not(feature = "chrono"))]
impl Display for DateTimeTimezoneOffset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.time_hour == 0 && self.time_minute == 0 {
            write!(f, "Z")
        } else {
            write!(f, "{:+03}:{:02}", self.time_hour, self.time_minute)
        }
    }
}

#[cfg(not(feature = "chrono"))]
impl From<DateTimeTimezoneOffset> for String {
    fn from(value: DateTimeTimezoneOffset) -> Self {
        format!("{value}")
    }
}

#[cfg(feature = "chrono")]
/// Parses a string slice into a `DateTime`.
pub fn parse(input: &str) -> Result<chrono::DateTime<chrono::FixedOffset>, DateTimeSyntaxError> {
    chrono::DateTime::parse_from_rfc3339(input).map_err(DateTimeSyntaxError::from)
}
#[cfg(not(feature = "chrono"))]
/// Parses a string slice into a `DateTime`.
pub fn parse(input: &str) -> Result<DateTime, DateTimeSyntaxError> {
    parse_bytes(input.as_bytes())
}

#[cfg(feature = "chrono")]
/// Parses a byte slice into a `DateTime`.
pub fn parse_bytes(
    input: &[u8],
) -> Result<chrono::DateTime<chrono::FixedOffset>, DateTimeSyntaxError> {
    let input_str = str::from_utf8(input)?;
    parse(input_str)
}
#[cfg(not(feature = "chrono"))]
/// Parses a byte slice into a `DateTime`.
pub fn parse_bytes(input: &[u8]) -> Result<DateTime, DateTimeSyntaxError> {
    Ok(parse_date_time_bytes(input)?.parsed)
}

#[cfg(feature = "chrono")]
/// Provides a string representation of the DateTime.
pub fn string_from(date_time: &chrono::DateTime<chrono::FixedOffset>) -> String {
    let dt = date_time.naive_local();
    let date = dt.date();
    let time = dt.time();
    let offset = date_time.offset();
    if offset.local_minus_utc() == 0 {
        format!("{date}T{time}Z")
    } else {
        format!("{date}T{time}{offset}")
    }
}
#[cfg(not(feature = "chrono"))]
/// Provides a string representation of the DateTime.
pub fn string_from(date_time: &DateTime) -> String {
    format!("{date_time}")
}

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

    #[test]
    fn no_timezone() {
        assert_eq!(
            date_time!(2025-06-04 T 13:50:42.148),
            parse("2025-06-04T13:50:42.148Z").unwrap()
        );
    }

    #[test]
    fn plus_timezone() {
        assert_eq!(
            date_time!(2025-06-04 T 13:50:42.148 03:00),
            parse("2025-06-04T13:50:42.148+03:00").unwrap()
        );
    }

    #[test]
    fn negative_timezone() {
        assert_eq!(
            date_time!(2025-06-04 T 13:50:42.148 -01:30),
            parse("2025-06-04T13:50:42.148-01:30").unwrap()
        );
    }

    #[test]
    fn no_fractional_seconds() {
        assert_eq!(
            date_time!(2025-06-04 T 13:50:42.0),
            parse("2025-06-04T13:50:42Z").unwrap()
        );
    }

    #[test]
    fn string_from_single_digit_dates_should_be_valid() {
        assert_eq!(
            String::from("2025-06-04T13:50:42.123Z"),
            string_from(&date_time!(2025-06-04 T 13:50:42.123))
        )
    }

    #[ignore = "change to chrono breaks test but maybe the expectation is wrong anyway"]
    #[test]
    fn string_from_no_fractional_seconds_should_still_be_3_decimals_precise() {
        assert_eq!(
            String::from("2025-06-04T13:50:42.000Z"),
            string_from(&date_time!(2025-06-04 T 13:50:42.0))
        )
    }

    #[test]
    fn string_from_single_digit_times_should_be_valid() {
        assert_eq!(
            String::from("2025-12-25T04:00:02.001Z"),
            string_from(&date_time!(2025-12-25 T 04:00:02.001))
        )
    }

    #[test]
    fn string_from_negative_time_offset_should_be_valid() {
        assert_eq!(
            String::from("2025-06-04T13:50:42.123-05:00"),
            string_from(&date_time!(2025-06-04 T 13:50:42.123 -05:00))
        )
    }

    #[test]
    fn string_from_positive_offset_should_be_valid() {
        assert_eq!(
            String::from("2025-06-04T13:50:42.100+01:00"),
            string_from(&date_time!(2025-06-04 T 13:50:42.100 01:00))
        )
    }

    #[test]
    fn string_from_positive_offset_non_zero_minutes_should_be_valid() {
        assert_eq!(
            String::from("2025-06-04T13:50:42.010+06:30"),
            string_from(&date_time!(2025-06-04 T 13:50:42.010 06:30))
        )
    }

    #[cfg(not(feature = "chrono"))]
    #[test]
    fn date_time_macro_should_work_with_no_offset() {
        assert_eq!(
            date_time!(2025-06-22 T 22:13:42.000),
            DateTime {
                date_fullyear: 2025,
                date_month: 6,
                date_mday: 22,
                time_hour: 22,
                time_minute: 13,
                time_second: 42.0,
                timezone_offset: DateTimeTimezoneOffset {
                    time_hour: 0,
                    time_minute: 0
                }
            }
        );
    }

    #[cfg(not(feature = "chrono"))]
    #[test]
    fn date_time_macro_should_work_with_positive_offset() {
        assert_eq!(
            date_time!(2025-06-22 T 22:13:42.000 01:00),
            DateTime {
                date_fullyear: 2025,
                date_month: 6,
                date_mday: 22,
                time_hour: 22,
                time_minute: 13,
                time_second: 42.0,
                timezone_offset: DateTimeTimezoneOffset {
                    time_hour: 1,
                    time_minute: 0
                }
            }
        );
    }

    #[cfg(not(feature = "chrono"))]
    #[test]
    fn date_time_macro_should_work_with_negative_offset() {
        assert_eq!(
            date_time!(2025-06-22 T 22:13:42.000 -01:30),
            DateTime {
                date_fullyear: 2025,
                date_month: 6,
                date_mday: 22,
                time_hour: 22,
                time_minute: 13,
                time_second: 42.0,
                timezone_offset: DateTimeTimezoneOffset {
                    time_hour: -1,
                    time_minute: 30
                }
            }
        );
    }
}