dlms-cosem-kit 0.4.0

DLMS/COSEM client and server for Rust with a no_std protocol core, selective profile reads, block transfer and AES-GCM protection
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
//! COSEM date and time.
//!
//! These are not calendar types. Every field may be a wildcard — a schedule says "the
//! last day of any month at 06:00" by putting `0xFF` in the year and `0xFE` in the day —
//! and the deviation from UTC may be absent. Converting one to a civil timestamp is
//! therefore fallible, and this crate refuses to guess: the conversions in this module
//! return `Option`, and the wildcard is preserved on the way back out.

use core::fmt;

/// Clock status flags carried by a date-time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ClockStatus(pub u8);

impl ClockStatus {
    /// The value meaning "no status information".
    pub const NOT_SPECIFIED: Self = Self(0xFF);

    /// The clock is not synchronised and its value must not be trusted.
    #[must_use]
    pub const fn invalid(self) -> bool {
        self.0 & 0x01 != 0
    }

    /// The clock may have drifted beyond the accepted tolerance.
    #[must_use]
    pub const fn doubtful(self) -> bool {
        self.0 & 0x02 != 0
    }

    /// The value comes from a different clock base than the meter's own.
    #[must_use]
    pub const fn different_clock_base(self) -> bool {
        self.0 & 0x04 != 0
    }

    /// The status bits themselves are unreliable.
    #[must_use]
    pub const fn invalid_clock_status(self) -> bool {
        self.0 & 0x08 != 0
    }

    /// Daylight saving is in effect, so the deviation includes the summer-time offset.
    #[must_use]
    pub const fn daylight_saving_active(self) -> bool {
        self.0 & 0x80 != 0
    }

    /// True when no status was given.
    #[must_use]
    pub const fn is_not_specified(self) -> bool {
        self.0 == 0xFF
    }
}

/// The twelve-byte COSEM date-time.
///
/// Fields are stored exactly as they arrived, wildcards included, so an encode after a
/// decode is byte-identical.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DateTime {
    /// Year, or `0xFFFF` for "not specified".
    pub year: u16,
    /// Month 1–12; `0xFD` daylight-saving end, `0xFE` daylight-saving begin, `0xFF` any.
    pub month: u8,
    /// Day 1–31; `0xFD` second-last day of month, `0xFE` last day of month, `0xFF` any.
    pub day_of_month: u8,
    /// Day of week 1 (Monday) – 7 (Sunday), or `0xFF` for any.
    pub day_of_week: u8,
    /// Hour 0–23, or `0xFF`.
    pub hour: u8,
    /// Minute 0–59, or `0xFF`.
    pub minute: u8,
    /// Second 0–59, or `0xFF`.
    pub second: u8,
    /// Hundredths of a second 0–99, or `0xFF`.
    pub hundredths: u8,
    /// Minutes *behind* UTC — local time = UTC − deviation — or `0x8000` when absent.
    pub deviation: i16,
    /// Clock status.
    pub status: ClockStatus,
}

impl DateTime {
    /// The value in which every field is a wildcard.
    pub const WILDCARD: Self = Self {
        year: 0xFFFF,
        month: 0xFF,
        day_of_month: 0xFF,
        day_of_week: 0xFF,
        hour: 0xFF,
        minute: 0xFF,
        second: 0xFF,
        hundredths: 0xFF,
        deviation: DEVIATION_NOT_SPECIFIED,
        status: ClockStatus::NOT_SPECIFIED,
    };

    /// Decode from the twelve wire bytes. Cannot fail: every bit pattern is a value.
    #[must_use]
    pub const fn from_bytes(b: [u8; 12]) -> Self {
        Self {
            year: u16::from_be_bytes([b[0], b[1]]),
            month: b[2],
            day_of_month: b[3],
            day_of_week: b[4],
            hour: b[5],
            minute: b[6],
            second: b[7],
            hundredths: b[8],
            deviation: i16::from_be_bytes([b[9], b[10]]),
            status: ClockStatus(b[11]),
        }
    }

    /// Encode to the twelve wire bytes.
    #[must_use]
    pub const fn to_bytes(self) -> [u8; 12] {
        let y = self.year.to_be_bytes();
        let d = self.deviation.to_be_bytes();
        [
            y[0],
            y[1],
            self.month,
            self.day_of_month,
            self.day_of_week,
            self.hour,
            self.minute,
            self.second,
            self.hundredths,
            d[0],
            d[1],
            self.status.0,
        ]
    }

    /// True when any field is a wildcard, which is what makes this a pattern rather
    /// than a timestamp.
    #[must_use]
    pub const fn has_wildcard(&self) -> bool {
        self.year == 0xFFFF
            || self.month >= 0xFD
            || self.day_of_month >= 0xFD
            || self.hour == 0xFF
            || self.minute == 0xFF
            || self.second == 0xFF
    }

    /// The offset from UTC in minutes, when one was given.
    #[must_use]
    pub const fn utc_offset_minutes(&self) -> Option<i16> {
        if self.deviation == DEVIATION_NOT_SPECIFIED { None } else { Some(-self.deviation) }
    }

    /// Seconds since the Unix epoch, when this is a complete civil timestamp with a
    /// known deviation.
    ///
    /// `None` for anything with a wildcard or without a deviation — a value that is
    /// missing its offset is not a point in time, and silently treating it as UTC is
    /// the bug this signature exists to prevent.
    #[must_use]
    pub fn to_unix_seconds(&self) -> Option<i64> {
        if self.has_wildcard() {
            return None;
        }
        let offset = self.utc_offset_minutes()?;
        if self.month == 0 || self.month > 12 || self.day_of_month == 0 {
            return None;
        }
        // "31 February" is not a date. Accepting it and letting the day-count arithmetic
        // roll it into March is how a meter reading lands on the wrong day rather than
        // being reported as the malformed value it is.
        if self.day_of_month > days_in_month(self.year, self.month) {
            return None;
        }
        // A leap second is not representable as a Unix timestamp: 23:59:60 and the
        // following 00:00:00 would have to be the same number. Refusing is the only
        // answer that does not silently claim a value is something it is not.
        if self.hour > 23 || self.minute > 59 || self.second > 59 {
            return None;
        }
        let days = days_from_civil(self.year, self.month, self.day_of_month);
        let secs = i64::from(days) * 86_400
            + i64::from(self.hour) * 3600
            + i64::from(self.minute) * 60
            + i64::from(self.second);
        Some(secs - i64::from(offset) * 60)
    }

    /// A complete timestamp from civil fields and an offset from UTC in minutes.
    ///
    /// `None` for anything that names no instant: a wildcard year, 31 February, 24:00, a
    /// leap second, or an offset of `i16::MIN`, whose deviation would collide with
    /// [`DEVIATION_NOT_SPECIFIED`]. Hundredths are 0 and the status is 0 (valid).
    ///
    /// ```
    /// # use dlms_cosem_kit::axdr::DateTime;
    /// let dt = DateTime::from_civil(2025, 1, 15, 12, 0, 0, 60).unwrap();
    /// assert_eq!(dt.to_unix_seconds(), Some(1_736_938_800));
    /// assert!(DateTime::from_civil(2025, 2, 29, 0, 0, 0, 0).is_none());
    /// ```
    #[must_use]
    pub const fn from_civil(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        utc_offset_minutes: i16,
    ) -> Option<Self> {
        if year == 0xFFFF
            || month == 0
            || day == 0
            || day > days_in_month(year, month)
            || hour > 23
            || minute > 59
            || second > 59
            || utc_offset_minutes == i16::MIN
        {
            return None;
        }
        Some(Self {
            year,
            month,
            day_of_month: day,
            day_of_week: day_of_week(year, month, day),
            hour,
            minute,
            second,
            hundredths: 0,
            deviation: -utc_offset_minutes,
            status: ClockStatus(0),
        })
    }

    /// The UTC timestamp `secs` seconds after the Unix epoch: deviation 0, hundredths 0,
    /// status 0, weekday filled in.
    ///
    /// `None` outside the years the field can carry: 0000-01-01T00:00:00Z
    /// ([`Self::MIN_UNIX_SECONDS`]) to 65534-12-31T23:59:59Z ([`Self::MAX_UNIX_SECONDS`]).
    /// Year 65535 is the wildcard.
    ///
    /// ```
    /// # use dlms_cosem_kit::axdr::DateTime;
    /// let dt = DateTime::from_unix_seconds(1_709_164_800).unwrap();
    /// assert_eq!((dt.year, dt.month, dt.day_of_month, dt.day_of_week), (2024, 2, 29, 4));
    /// assert_eq!(dt.to_unix_seconds(), Some(1_709_164_800));
    /// ```
    #[must_use]
    pub const fn from_unix_seconds(secs: i64) -> Option<Self> {
        if secs < Self::MIN_UNIX_SECONDS || secs > Self::MAX_UNIX_SECONDS {
            return None;
        }
        let days = secs.div_euclid(86_400);
        let rem = secs.rem_euclid(86_400);
        // In range: |days| < 2^25, so the narrowing below is exact.
        let (year, month, day) = civil_from_days(days as i32);
        let year = year as u16;
        Some(Self {
            year,
            month,
            day_of_month: day,
            day_of_week: day_of_week(year, month, day),
            hour: (rem / 3600) as u8,
            minute: (rem / 60 % 60) as u8,
            second: (rem % 60) as u8,
            hundredths: 0,
            deviation: 0,
            status: ClockStatus(0),
        })
    }

    /// 0000-01-01T00:00:00Z, the earliest instant [`Self::from_unix_seconds`] accepts.
    pub const MIN_UNIX_SECONDS: i64 = -62_167_219_200;

    /// 65534-12-31T23:59:59Z, the latest instant [`Self::from_unix_seconds`] accepts.
    pub const MAX_UNIX_SECONDS: i64 = 2_005_917_609_599;
}

/// The value of the deviation field that means "not specified".
pub const DEVIATION_NOT_SPECIFIED: i16 = -0x8000;

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = wildcard_or;
        if self.year == 0xFFFF {
            f.write_str("****")?;
        } else {
            write!(f, "{:04}", self.year)?;
        }
        f.write_str("-")?;
        n(self.month, 2, f)?;
        f.write_str("-")?;
        n(self.day_of_month, 2, f)?;
        f.write_str("T")?;
        n(self.hour, 2, f)?;
        f.write_str(":")?;
        n(self.minute, 2, f)?;
        f.write_str(":")?;
        n(self.second, 2, f)?;
        match self.utc_offset_minutes() {
            None => Ok(()),
            Some(0) => f.write_str("Z"),
            Some(m) => {
                let sign = if m < 0 { '-' } else { '+' };
                let a = m.unsigned_abs();
                write!(f, "{sign}{:02}:{:02}", a / 60, a % 60)
            }
        }
    }
}

/// The five-byte COSEM date.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Date {
    /// Year, or `0xFFFF`.
    pub year: u16,
    /// Month, with the same wildcards as [`DateTime::month`].
    pub month: u8,
    /// Day of month, with the same wildcards as [`DateTime::day_of_month`].
    pub day_of_month: u8,
    /// Day of week, or `0xFF`.
    pub day_of_week: u8,
}

impl Date {
    /// Decode from the five wire bytes.
    #[must_use]
    pub const fn from_bytes(b: [u8; 5]) -> Self {
        Self { year: u16::from_be_bytes([b[0], b[1]]), month: b[2], day_of_month: b[3], day_of_week: b[4] }
    }

    /// Encode to the five wire bytes.
    #[must_use]
    pub const fn to_bytes(self) -> [u8; 5] {
        let y = self.year.to_be_bytes();
        [y[0], y[1], self.month, self.day_of_month, self.day_of_week]
    }
}

impl fmt::Display for Date {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.year == 0xFFFF {
            f.write_str("****")?;
        } else {
            write!(f, "{:04}", self.year)?;
        }
        f.write_str("-")?;
        wildcard_or(self.month, 2, f)?;
        f.write_str("-")?;
        wildcard_or(self.day_of_month, 2, f)
    }
}

/// The four-byte COSEM time.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Time {
    /// Hour, or `0xFF`.
    pub hour: u8,
    /// Minute, or `0xFF`.
    pub minute: u8,
    /// Second, or `0xFF`.
    pub second: u8,
    /// Hundredths, or `0xFF`.
    pub hundredths: u8,
}

impl Time {
    /// Decode from the four wire bytes.
    #[must_use]
    pub const fn from_bytes(b: [u8; 4]) -> Self {
        Self { hour: b[0], minute: b[1], second: b[2], hundredths: b[3] }
    }

    /// Encode to the four wire bytes.
    #[must_use]
    pub const fn to_bytes(self) -> [u8; 4] {
        [self.hour, self.minute, self.second, self.hundredths]
    }
}

impl fmt::Display for Time {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        wildcard_or(self.hour, 2, f)?;
        f.write_str(":")?;
        wildcard_or(self.minute, 2, f)?;
        f.write_str(":")?;
        wildcard_or(self.second, 2, f)
    }
}

/// Print a field, or as many `*` as it is wide when it is a wildcard.
///
/// Every field that can be `0xFF` prints the same way, in every one of the three types.
/// A `Time` that printed `255:255:255` while a `DateTime` printed `**:**:**` for the
/// same bytes would be a display that has to be read twice.
fn wildcard_or(v: u8, width: usize, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    if v >= 0xFD {
        for _ in 0..width {
            f.write_str("*")?;
        }
        Ok(())
    } else {
        write!(f, "{v:0width$}")
    }
}

/// How many days the month has, leap years included.
const fn days_in_month(year: u16, month: u8) -> u8 {
    match month {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        2 => {
            let y = year as u32;
            if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) { 29 } else { 28 }
        }
        _ => 0,
    }
}

/// Days from 1970-01-01 to a civil date, by Howard Hinnant's algorithm.
const fn days_from_civil(year: u16, m: u8, d: u8) -> i32 {
    // Every input is a u16 or a u8, so no step below can overflow an i32 — and the
    // types, not a comment, are what let the compiler drop the overflow checks.
    let m = m as i32;
    let d = d as i32;
    let y = year as i32 - if m <= 2 { 1 } else { 0 };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400;
    let mp = (m + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// The civil date `days` after 1970-01-01, by Howard Hinnant's algorithm: the inverse of
/// [`days_from_civil`].
const fn civil_from_days(days: i32) -> (i32, u8, u8) {
    let z = days + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = (doy - (153 * mp + 2) / 5 + 1) as u8;
    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u8;
    let year = yoe + era * 400 + if month <= 2 { 1 } else { 0 };
    (year, month, day)
}

/// ISO day of week, 1 = Monday, of a real date.
const fn day_of_week(y: u16, m: u8, d: u8) -> u8 {
    // 1970-01-01 was a Thursday, ISO day 4.
    ((days_from_civil(y, m, d) + 3).rem_euclid(7) + 1) as u8
}

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

    #[test]
    fn wire_form_round_trips_including_wildcards() {
        let raw = [0x07, 0xE9, 0x0C, 0x1F, 0xFF, 0x17, 0x3B, 0x3B, 0xFF, 0x00, 0x3C, 0x00];
        let dt = DateTime::from_bytes(raw);
        assert_eq!(dt.year, 2025);
        assert_eq!(dt.month, 12);
        assert_eq!(dt.day_of_month, 31);
        assert_eq!(dt.hour, 23);
        assert_eq!(dt.deviation, 60);
        assert_eq!(dt.to_bytes(), raw);
    }

    /// 003-checked-clock-and-links/SR-005: known answers and both endpoints.
    #[test]
    fn unix_seconds_become_a_concrete_utc_clock() {
        // Known answers: the epoch, one second before it, a leap day, both endpoints.
        // (year, month, day, weekday, hour, minute, second)
        type Civil = (u16, u8, u8, u8, u8, u8, u8);
        let cases: [(i64, Civil); 5] = [
            (0, (1970, 1, 1, 4, 0, 0, 0)),
            (-1, (1969, 12, 31, 3, 23, 59, 59)),
            (1_709_164_800, (2024, 2, 29, 4, 0, 0, 0)),
            (DateTime::MIN_UNIX_SECONDS, (0, 1, 1, 6, 0, 0, 0)),
            (DateTime::MAX_UNIX_SECONDS, (65534, 12, 31, 1, 23, 59, 59)),
        ];
        for (secs, (y, mo, d, wd, h, mi, s)) in cases {
            let dt = DateTime::from_unix_seconds(secs).unwrap();
            assert_eq!(
                (dt.year, dt.month, dt.day_of_month, dt.day_of_week, dt.hour, dt.minute, dt.second),
                (y, mo, d, wd, h, mi, s),
                "{secs}"
            );
            assert_eq!((dt.hundredths, dt.deviation, dt.status), (0, 0, ClockStatus(0)));
            assert!(!dt.has_wildcard());
            assert_eq!(dt.to_unix_seconds(), Some(secs));
        }
        assert_eq!(DateTime::from_unix_seconds(DateTime::MIN_UNIX_SECONDS - 1), None);
        assert_eq!(
            DateTime::from_unix_seconds(DateTime::MAX_UNIX_SECONDS + 1),
            None,
            "year 65535 is the wildcard"
        );
        assert_eq!(DateTime::from_unix_seconds(i64::MIN), None);
        assert_eq!(DateTime::from_unix_seconds(i64::MAX), None);
    }

    #[test]
    fn from_unix_seconds_agrees_with_from_civil_every_day_for_a_cycle() {
        // 400 years is one full Gregorian cycle: every leap rule is exercised.
        let mut secs = DateTime::from_civil(1800, 1, 1, 13, 14, 15, 0).unwrap().to_unix_seconds().unwrap();
        for _ in 0..146_097 {
            let dt = DateTime::from_unix_seconds(secs).unwrap();
            let civil =
                DateTime::from_civil(dt.year, dt.month, dt.day_of_month, dt.hour, dt.minute, dt.second, 0);
            assert_eq!(civil, Some(dt));
            assert_eq!(dt.to_unix_seconds(), Some(secs));
            secs += 86_400;
        }
    }

    /// 003-checked-clock-and-links/SR-005
    #[test]
    fn from_civil_refuses_what_names_no_instant() {
        let ok = |y, mo, d, h, mi, s, off| DateTime::from_civil(y, mo, d, h, mi, s, off).is_some();
        assert!(ok(2024, 2, 29, 23, 59, 59, 0));
        assert!(!ok(2025, 2, 29, 0, 0, 0, 0), "2025 is not a leap year");
        assert!(!ok(2025, 2, 31, 0, 0, 0, 0));
        assert!(!ok(2025, 13, 1, 0, 0, 0, 0));
        assert!(!ok(2025, 0, 1, 0, 0, 0, 0));
        assert!(!ok(2025, 1, 0, 0, 0, 0, 0));
        assert!(!ok(2025, 1, 1, 24, 0, 0, 0));
        assert!(!ok(2025, 1, 1, 0, 60, 0, 0));
        assert!(!ok(2016, 12, 31, 23, 59, 60, 0), "a leap second has no Unix value");
        assert!(!ok(0xFFFF, 1, 1, 0, 0, 0, 0), "the wildcard year");
        assert!(!ok(2025, 1, 1, 0, 0, 0, i16::MIN), "its deviation is the not-specified marker");
        assert!(ok(2025, 1, 1, 0, 0, 0, i16::MAX));
    }

    #[test]
    fn deviation_is_minutes_behind_utc() {
        // Central European Time in winter is UTC+1, so the deviation is -60.
        let dt = DateTime::from_civil(2025, 1, 15, 12, 0, 0, 60).unwrap();
        assert_eq!(dt.deviation, -60);
        assert_eq!(dt.utc_offset_minutes(), Some(60));
        // 2025-01-15T12:00:00+01:00 is 11:00 UTC.
        assert_eq!(dt.to_unix_seconds(), Some(1_736_938_800));
    }

    #[test]
    fn an_absent_deviation_is_not_utc() {
        let mut dt = DateTime::from_civil(2025, 1, 15, 12, 0, 0, 0).unwrap();
        dt.deviation = DEVIATION_NOT_SPECIFIED;
        assert_eq!(dt.utc_offset_minutes(), None);
        assert_eq!(dt.to_unix_seconds(), None, "must refuse rather than assume UTC");
    }

    #[test]
    fn a_wildcard_is_not_a_timestamp() {
        assert!(DateTime::WILDCARD.has_wildcard());
        assert_eq!(DateTime::WILDCARD.to_unix_seconds(), None);
        let mut last_day = DateTime::from_civil(2025, 6, 1, 6, 0, 0, 120).unwrap();
        last_day.day_of_month = 0xFE; // last day of month
        assert!(last_day.has_wildcard());
        assert_eq!(last_day.to_unix_seconds(), None);
    }

    #[test]
    fn epoch_and_a_leap_day() {
        let epoch = DateTime::from_civil(1970, 1, 1, 0, 0, 0, 0).unwrap();
        assert_eq!(epoch.to_unix_seconds(), Some(0));
        assert_eq!(epoch.day_of_week, 4, "1970-01-01 was a Thursday");
        let leap = DateTime::from_civil(2024, 2, 29, 0, 0, 0, 0).unwrap();
        assert_eq!(leap.to_unix_seconds(), Some(1_709_164_800));
        assert_eq!(leap.day_of_week, 4, "2024-02-29 was a Thursday");
    }

    #[test]
    fn out_of_range_fields_are_refused() {
        let mut dt = DateTime::from_civil(2025, 1, 1, 0, 0, 0, 0).unwrap();
        dt.month = 13;
        assert_eq!(dt.to_unix_seconds(), None);
        let mut dt = DateTime::from_civil(2025, 1, 1, 0, 0, 0, 0).unwrap();
        dt.hour = 24;
        assert_eq!(dt.to_unix_seconds(), None);
    }

    #[test]
    fn a_day_that_does_not_exist_in_its_month_is_refused() {
        let mut dt = DateTime::from_civil(2025, 2, 28, 12, 0, 0, 0).unwrap();
        assert!(dt.to_unix_seconds().is_some());
        dt.day_of_month = 29;
        assert_eq!(dt.to_unix_seconds(), None, "2025 is not a leap year");
        let mut leap = DateTime::from_civil(2024, 2, 28, 12, 0, 0, 0).unwrap();
        leap.day_of_month = 29;
        assert!(leap.to_unix_seconds().is_some(), "2024 is");
        let mut april = DateTime::from_civil(2025, 4, 30, 12, 0, 0, 0).unwrap();
        assert!(april.to_unix_seconds().is_some());
        april.day_of_month = 31;
        assert_eq!(april.to_unix_seconds(), None, "April has thirty days");
        // The century rule.
        let mut y1900 = DateTime::from_civil(1900, 2, 28, 0, 0, 0, 0).unwrap();
        y1900.day_of_month = 29;
        assert_eq!(y1900.to_unix_seconds(), None);
        let mut y2000 = DateTime::from_civil(2000, 2, 28, 0, 0, 0, 0).unwrap();
        y2000.day_of_month = 29;
        assert!(y2000.to_unix_seconds().is_some());
    }

    #[test]
    fn a_leap_second_has_no_unix_timestamp() {
        let mut dt = DateTime::from_civil(2016, 12, 31, 23, 59, 59, 0).unwrap();
        assert!(dt.to_unix_seconds().is_some());
        dt.second = 60;
        assert_eq!(dt.to_unix_seconds(), None, "23:59:60 is not a Unix second");
    }

    #[test]
    fn every_type_prints_a_wildcard_the_same_way() {
        assert_eq!(
            alloc::format!("{}", Time { hour: 0xFF, minute: 30, second: 0xFF, hundredths: 0xFF }),
            "**:30:**"
        );
        assert_eq!(
            alloc::format!("{}", Date { year: 0xFFFF, month: 0xFF, day_of_month: 0xFE, day_of_week: 0xFF }),
            "****-**-**",
            "the last day of any month is a pattern, not the 254th"
        );
        assert_eq!(alloc::format!("{}", DateTime::WILDCARD), "****-**-**T**:**:**");
    }

    #[test]
    fn clock_status_bits() {
        let s = ClockStatus(0x81);
        assert!(s.invalid());
        assert!(s.daylight_saving_active());
        assert!(!s.doubtful());
        assert!(ClockStatus::NOT_SPECIFIED.is_not_specified());
    }
}