rdml-qpcr 0.1.1

Read, write, and validate RDML (Real-time PCR Data Markup Language) qPCR data files
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
//! Core value types shared across the model: identifiers, references,
//! `;`-joined reason lists, date-times, and nucleotide sequences.

// Every fallible constructor here has exactly one failure condition,
// already stated in its one-line doc ("rejecting the empty string", …);
// a separate # Errors section per function would only repeat it.
#![allow(clippy::missing_errors_doc)]

use std::borrow::Borrow;
use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Deserializer, Serialize};

use crate::error::Error;

// ---------------------------------------------------------------------------
// Id
// ---------------------------------------------------------------------------

/// The identifier of a master element (`sample`, `target`, `dye`, …).
///
/// The schema requires an id to be at least one character. The format
/// notes additionally say ids should be short human-readable names
/// provided by the user, since software displays them (sample names in a
/// plate view, target names in a legend); generated strings such as
/// UUIDs should not be used. This crate provides no id generator.
///
/// ```
/// use rdml_qpcr::Id;
/// let id = Id::new("GAPDH")?;
/// assert_eq!(id.as_str(), "GAPDH");
/// assert!(Id::new("").is_err());
/// # Ok::<(), rdml_qpcr::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
#[serde(transparent)]
pub struct Id(String);

impl Id {
    /// Creates an id, rejecting the empty string and control characters.
    ///
    /// Control characters (including tab and newline) are rejected
    /// because ids are stored in XML attributes, where any conforming
    /// parser normalises them to spaces — the id would silently change
    /// across a write/read cycle.
    pub fn new(id: impl Into<String>) -> Result<Self, Error> {
        let id = id.into();
        if id.is_empty() {
            return Err(Error::InvalidValue(
                "an RDML id must be at least one character".into(),
            ));
        }
        if let Some(c) = id.chars().find(|c| c.is_control()) {
            return Err(Error::InvalidValue(format!(
                "an RDML id must not contain control characters \
                 (found {c:?} in `{}`)",
                id.escape_debug()
            )));
        }
        Ok(Id(id))
    }

    /// The id as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for Id {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for Id {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for Id {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl FromStr for Id {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Error> {
        Id::new(s)
    }
}

impl TryFrom<&str> for Id {
    type Error = Error;
    fn try_from(s: &str) -> Result<Self, Error> {
        Id::new(s)
    }
}

impl TryFrom<String> for Id {
    type Error = Error;
    fn try_from(s: String) -> Result<Self, Error> {
        Id::new(s)
    }
}

impl<'de> Deserialize<'de> for Id {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Id::new(s).map_err(serde::de::Error::custom)
    }
}

// ---------------------------------------------------------------------------
// Typed references
// ---------------------------------------------------------------------------

macro_rules! id_reference {
    ($(#[$doc:meta])* $name:ident => $target:literal) => {
        $(#[$doc])*
        ///
        /// A reference names a master element by id; it is a distinct type
        /// from [`Id`] so a reference cannot be confused with a definition,
        /// and distinct from the other reference kinds so, for example, a
        /// sample reference cannot be used where a target reference is
        /// expected. Whether the referent actually exists is checked by
        /// [`Rdml::validate`](crate::Rdml::validate), not at construction.
        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(Id);

        impl $name {
            /// Creates a reference to the
            #[doc = concat!("`", $target, "`")]
            /// with the given id. Rejects the empty string.
            pub fn new(id: impl Into<String>) -> Result<Self, Error> {
                Ok(Self(Id::new(id)?))
            }

            /// The referenced id.
            pub fn id(&self) -> &Id {
                &self.0
            }

            /// The referenced id as a string slice.
            pub fn as_str(&self) -> &str {
                self.0.as_str()
            }
        }

        impl fmt::Display for $name {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str(self.0.as_str())
            }
        }

        impl AsRef<str> for $name {
            fn as_ref(&self) -> &str {
                self.0.as_str()
            }
        }

        impl From<Id> for $name {
            fn from(id: Id) -> Self {
                Self(id)
            }
        }

        impl From<$name> for Id {
            fn from(r: $name) -> Id {
                r.0
            }
        }

        impl FromStr for $name {
            type Err = Error;
            fn from_str(s: &str) -> Result<Self, Error> {
                Self::new(s)
            }
        }

        impl PartialEq<str> for $name {
            fn eq(&self, other: &str) -> bool {
                self.as_str() == other
            }
        }

        impl PartialEq<&str> for $name {
            fn eq(&self, other: &&str) -> bool {
                self.as_str() == *other
            }
        }
    };
}

id_reference! {
    /// A reference to a [`Sample`](crate::Sample) master element.
    SampleRef => "sample"
}
id_reference! {
    /// A reference to a [`Target`](crate::Target) master element.
    TargetRef => "target"
}
id_reference! {
    /// A reference to a [`Dye`](crate::Dye) master element.
    DyeRef => "dye"
}
id_reference! {
    /// A reference to a [`Documentation`](crate::Documentation) master element.
    DocumentationRef => "documentation"
}
id_reference! {
    /// A reference to an [`Experimenter`](crate::Experimenter) master element.
    ExperimenterRef => "experimenter"
}
id_reference! {
    /// A reference to a
    /// [`ThermalCyclingConditions`](crate::ThermalCyclingConditions)
    /// master element.
    TccRef => "thermalCyclingConditions"
}

// ---------------------------------------------------------------------------
// Reasons (the `;`-joined string convention)
// ---------------------------------------------------------------------------

/// A list of reasons or notes, stored in RDML as a single `;`-joined string.
///
/// Used for `data/excl`, `data/note`, and the digital-PCR
/// `partitions/data/excluded` and `note` elements. The RDML format notes
/// state: *if several strings have to be combined, use a ";" semicolon as
/// separator*.
///
/// Exclusion semantics live in the surrounding `Option`, not in this
/// type: a reaction is excluded because the `excl` element is present,
/// even when it carries no text. To mean "not excluded", leave the field
/// `None`; `<excl>false</excl>` cannot be produced. An empty `Reasons`
/// is legal and means "excluded, no reason recorded".
///
/// ```
/// use rdml_qpcr::Reasons;
/// let mut r = Reasons::new();
/// r.push("no amplification");
/// r.push("bubble in well");
/// assert_eq!(r.to_string(), "no amplification;bubble in well");
///
/// let parsed: Reasons = "a; b ;c".parse()?;
/// assert_eq!(parsed.iter().collect::<Vec<_>>(), ["a", "b", "c"]);
/// # Ok::<(), rdml_qpcr::Error>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Reasons(Vec<String>);

impl Reasons {
    /// Creates an empty list (meaning: present, but no text recorded).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a single-entry list.
    pub fn one(reason: impl Into<String>) -> Self {
        Self(vec![reason.into()])
    }

    /// Appends a reason.
    pub fn push(&mut self, reason: impl Into<String>) {
        self.0.push(reason.into());
    }

    /// True if no reason text is recorded.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Number of recorded reasons.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Iterates over the individual reasons.
    pub fn iter(&self) -> impl Iterator<Item = &str> {
        self.0.iter().map(String::as_str)
    }

    /// Parses the RDML on-disk form: splits on `;`, trims whitespace,
    /// drops empty segments (so an empty element parses as an empty list).
    pub fn from_joined(s: &str) -> Self {
        Self(
            s.split(';')
                .map(str::trim)
                .filter(|p| !p.is_empty())
                .map(String::from)
                .collect(),
        )
    }

    /// The RDML on-disk form: reasons joined with `;`.
    #[must_use]
    pub fn to_joined(&self) -> String {
        self.0.join(";")
    }
}

impl fmt::Display for Reasons {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.to_joined())
    }
}

impl FromStr for Reasons {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Error> {
        Ok(Self::from_joined(s))
    }
}

impl<S: Into<String>> FromIterator<S> for Reasons {
    fn from_iter<I: IntoIterator<Item = S>>(iter: I) -> Self {
        Self(iter.into_iter().map(Into::into).collect())
    }
}

// ---------------------------------------------------------------------------
// DateTime
// ---------------------------------------------------------------------------

/// An XML Schema `xs:dateTime` value, e.g. `2026-08-14T09:30:00Z`,
/// `2026-08-14T09:30:00+02:00`, or (legal in XSD) the offset-less
/// `2026-08-14T09:30:00`.
///
/// Used by `rdml/dateMade`, `rdml/dateUpdated`, and `run/runDate`. The
/// value is stored as its lexical string, shape-validated on construction,
/// so documents round-trip byte-exactly regardless of offset conventions.
/// With the `time` cargo feature enabled, conversions to and from
/// [`time::OffsetDateTime`] and [`time::PrimitiveDateTime`] are provided.
///
/// ```
/// use rdml_qpcr::DateTime;
/// let dt = DateTime::new("2026-08-14T09:30:00Z")?;
/// assert_eq!(dt.as_str(), "2026-08-14T09:30:00Z");
/// assert!(DateTime::new("yesterday-ish").is_err());
/// # Ok::<(), rdml_qpcr::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct DateTime(String);

impl DateTime {
    /// Creates a date-time from its lexical `xs:dateTime` form.
    pub fn new(s: impl Into<String>) -> Result<Self, Error> {
        let s = s.into();
        if !is_valid_xs_datetime(&s) {
            return Err(Error::InvalidValue(format!(
                "`{s}` is not a valid xs:dateTime \
                 (expected YYYY-MM-DDThh:mm:ss[.fff][Z|±hh:mm])"
            )));
        }
        Ok(DateTime(s))
    }

    /// The lexical form as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for DateTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for DateTime {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Error> {
        DateTime::new(s)
    }
}

impl<'de> Deserialize<'de> for DateTime {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        DateTime::new(s).map_err(serde::de::Error::custom)
    }
}

/// Minimal lexical check for `xs:dateTime`:
/// `-?YYYY+-MM-DDThh:mm:ss(.f+)?(Z|[+-]hh:mm)?` with in-range components.
fn is_valid_xs_datetime(s: &str) -> bool {
    fn digits(s: &str, n: usize) -> Option<(&str, u32)> {
        let (d, rest) = s.split_at_checked(n)?;
        if d.len() == n && d.bytes().all(|b| b.is_ascii_digit()) {
            Some((rest, d.parse().ok()?))
        } else {
            None
        }
    }
    fn expect(s: &str, c: char) -> Option<&str> {
        s.strip_prefix(c)
    }
    let s = s.strip_prefix('-').unwrap_or(s);
    // Year: 4 or more digits.
    let year_len = s.bytes().take_while(u8::is_ascii_digit).count();
    if year_len < 4 {
        return false;
    }
    let s = &s[year_len..];
    let Some(s) = expect(s, '-') else {
        return false;
    };
    let Some((s, month)) = digits(s, 2) else {
        return false;
    };
    let Some(s) = expect(s, '-') else {
        return false;
    };
    let Some((s, day)) = digits(s, 2) else {
        return false;
    };
    let Some(s) = expect(s, 'T') else {
        return false;
    };
    let Some((s, hour)) = digits(s, 2) else {
        return false;
    };
    let Some(s) = expect(s, ':') else {
        return false;
    };
    let Some((s, min)) = digits(s, 2) else {
        return false;
    };
    let Some(s) = expect(s, ':') else {
        return false;
    };
    let Some((s, sec)) = digits(s, 2) else {
        return false;
    };
    if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return false;
    }
    // 24:00:00 is legal in xs:dateTime; keep the check simple and permissive.
    if hour > 24 || min > 59 || sec > 60 {
        return false;
    }
    // Optional fractional seconds.
    let s = if let Some(rest) = s.strip_prefix('.') {
        let frac = rest.bytes().take_while(u8::is_ascii_digit).count();
        if frac == 0 {
            return false;
        }
        &rest[frac..]
    } else {
        s
    };
    // Optional timezone.
    match s {
        "" | "Z" => true,
        _ => {
            let Some(rest) = s.strip_prefix(['+', '-']) else {
                return false;
            };
            let Some((rest, tzh)) = digits(rest, 2) else {
                return false;
            };
            let Some(rest) = expect(rest, ':') else {
                return false;
            };
            let Some(("", tzm)) = digits(rest, 2) else {
                return false;
            };
            tzh <= 14 && tzm <= 59
        }
    }
}

#[cfg(feature = "time")]
mod time_conversions {
    use super::DateTime;
    use crate::error::Error;
    use time::format_description::well_known::Rfc3339;
    use time::macros::format_description;

    impl From<time::OffsetDateTime> for DateTime {
        fn from(t: time::OffsetDateTime) -> Self {
            DateTime(
                t.format(&Rfc3339)
                    .expect("RFC 3339 formatting of an OffsetDateTime cannot fail"),
            )
        }
    }

    impl From<time::PrimitiveDateTime> for DateTime {
        fn from(t: time::PrimitiveDateTime) -> Self {
            let fmt = format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
            DateTime(
                t.format(&fmt)
                    .expect("fixed-format formatting of a PrimitiveDateTime cannot fail"),
            )
        }
    }

    impl TryFrom<&DateTime> for time::OffsetDateTime {
        type Error = Error;

        /// Fails if the value has no UTC offset (offset-less values are
        /// legal `xs:dateTime`); use [`time::PrimitiveDateTime`] for those.
        fn try_from(dt: &DateTime) -> Result<Self, Error> {
            time::OffsetDateTime::parse(dt.as_str(), &Rfc3339)
                .map_err(|e| Error::InvalidValue(format!("`{dt}`: {e}")))
        }
    }

    impl TryFrom<&DateTime> for time::PrimitiveDateTime {
        type Error = Error;

        /// Parses the date and time-of-day, ignoring any UTC offset.
        fn try_from(dt: &DateTime) -> Result<Self, Error> {
            let fmt = format_description!(
                "[year]-[month]-[day]T[hour]:[minute]:[second][optional [.[subsecond]]]"
            );
            let s = dt.as_str();
            // Strip a trailing offset if present so the fixed format matches.
            let core = s
                .find(['Z', '+'])
                .or_else(|| s.rfind('-').filter(|&i| i > 10))
                .map_or(s, |i| &s[..i]);
            time::PrimitiveDateTime::parse(core, &fmt)
                .map_err(|e| Error::InvalidValue(format!("`{dt}`: {e}")))
        }
    }
}

// ---------------------------------------------------------------------------
// Sequence
// ---------------------------------------------------------------------------

/// A nucleotide sequence restricted to the IUPAC alphabet
/// (`ACGT` plus ambiguity codes `RYSWKMBDHVN`, either case).
///
/// ```
/// use rdml_qpcr::Sequence;
/// let seq = Sequence::new("ACGTRYSWKMn")?;
/// assert_eq!(seq.as_str(), "ACGTRYSWKMn");
/// assert!(Sequence::new("ACGU").is_err()); // U is not in the RDML pattern
/// assert!(Sequence::new("").is_err());
/// # Ok::<(), rdml_qpcr::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct Sequence(String);

impl Sequence {
    /// Creates a sequence, validating every character against the IUPAC
    /// alphabet and rejecting the empty string.
    pub fn new(s: impl Into<String>) -> Result<Self, Error> {
        let s = s.into();
        if s.is_empty() {
            return Err(Error::InvalidValue(
                "a sequence must contain at least one base".into(),
            ));
        }
        if let Some(bad) = s
            .chars()
            .find(|c| !"acgtryswkmbdhvnACGTRYSWKMBDHVN".contains(*c))
        {
            return Err(Error::InvalidValue(format!(
                "`{bad}` is not an IUPAC nucleotide code (in sequence `{s}`)"
            )));
        }
        Ok(Sequence(s))
    }

    /// The sequence as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Number of bases.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Always false: empty sequences cannot be constructed.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        false
    }
}

impl fmt::Display for Sequence {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for Sequence {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self, Error> {
        Sequence::new(s)
    }
}

impl<'de> Deserialize<'de> for Sequence {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Sequence::new(s).map_err(serde::de::Error::custom)
    }
}

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

    #[test]
    fn id_rejects_empty() {
        assert!(Id::new("").is_err());
        assert!(Id::new("x").is_ok());
        assert!(Id::new("Sample 1 (dil 1:10)").is_ok());
    }

    #[test]
    fn id_rejects_control_characters() {
        // Ids live in XML attributes, where a conforming parser turns
        // tab/newline into spaces — accepting them would break the
        // write/read round-trip silently.
        assert!(Id::new("line\nbreak").is_err());
        assert!(Id::new("tab\there").is_err());
        assert!(Id::new("cr\rhere").is_err());
        assert!(Id::new("nul\0").is_err());
        assert!(Id::new("plain spaces are fine").is_ok());
        assert!(SampleRef::new("also\nchecked").is_err());
    }

    #[test]
    fn refs_are_distinct_types() {
        let s = SampleRef::new("a").unwrap();
        assert_eq!(s, "a");
        assert_eq!(s.to_string(), "a");
        // Compile-time property: SampleRef and TargetRef are different types;
        // no runtime assertion possible (nor needed).
    }

    #[test]
    fn reasons_join_and_split() {
        let r = Reasons::from_joined("no amplification; bubble ;");
        assert_eq!(r.len(), 2);
        assert_eq!(r.to_joined(), "no amplification;bubble");
        assert!(Reasons::from_joined("").is_empty());
        let single = Reasons::one("manual");
        assert_eq!(single.to_joined(), "manual");
    }

    #[test]
    fn datetime_lexical_validation() {
        for ok in [
            "2026-08-14T09:30:00",
            "2026-08-14T09:30:00Z",
            "2026-08-14T09:30:00.123Z",
            "2026-08-14T09:30:00+02:00",
            "2026-08-14T09:30:00-05:30",
            "12026-01-01T00:00:00",
        ] {
            assert!(DateTime::new(ok).is_ok(), "should accept {ok}");
        }
        for bad in [
            "",
            "2026-08-14",
            "09:30:00",
            "2026-8-14T09:30:00",
            "2026-08-14 09:30:00",
            "2026-13-14T09:30:00",
            "2026-08-14T09:30:00+2:00",
            "2026-08-14T09:30:00.",
            "not a date",
        ] {
            assert!(DateTime::new(bad).is_err(), "should reject {bad}");
        }
    }

    #[test]
    fn sequence_validation() {
        assert!(Sequence::new("ACGTacgtNRY").is_ok());
        assert!(Sequence::new("ACGU").is_err());
        assert!(Sequence::new("AC GT").is_err());
        assert!(Sequence::new("").is_err());
    }

    #[cfg(feature = "time")]
    #[test]
    fn time_conversions() {
        use time::macros::datetime;

        let dt: DateTime = datetime!(2026-08-14 09:30:00 UTC).into();
        assert_eq!(dt.as_str(), "2026-08-14T09:30:00Z");
        let back: time::OffsetDateTime = (&dt).try_into().unwrap();
        assert_eq!(back, datetime!(2026-08-14 09:30:00 UTC));

        let naive: DateTime = datetime!(2026-08-14 09:30:00).into();
        assert_eq!(naive.as_str(), "2026-08-14T09:30:00");
        let back: time::PrimitiveDateTime = (&naive).try_into().unwrap();
        assert_eq!(back, datetime!(2026-08-14 09:30:00));
        // Offset-less values cannot become an OffsetDateTime.
        assert!(time::OffsetDateTime::try_from(&naive).is_err());
        // An offset value still parses as its wall-clock time.
        let offset = DateTime::new("2026-08-14T09:30:00+02:00").unwrap();
        let back: time::PrimitiveDateTime = (&offset).try_into().unwrap();
        assert_eq!(back, datetime!(2026-08-14 09:30:00));
    }

    #[test]
    fn serde_transparency() {
        let id = Id::new("s1").unwrap();
        assert_eq!(serde_json::to_string(&id).unwrap(), "\"s1\"");
        let back: Id = serde_json::from_str("\"s1\"").unwrap();
        assert_eq!(back, id);
        assert!(serde_json::from_str::<Id>("\"\"").is_err());

        let r: Reasons = ["a", "b"].into_iter().collect();
        assert_eq!(serde_json::to_string(&r).unwrap(), "[\"a\",\"b\"]");
    }
}