deep-time 0.1.0-alpha.9

High-precision, no-std, no-alloc date-time library, leap-seconds, time scales, relativistic time, and a powerful date & duration parser
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
use crate::AsciiStr;
use core::fmt;
use core::panic::Location;

/// Iterator over the error trace levels of an [`AnErr`].
///
/// Yields `(kind, location, reason)` tuples **from most recent context to oldest**
/// (reverse chronological order). Only valid levels are returned.
///
/// The `reason` field is `Some` if a non-empty reason was supplied for that level,
/// otherwise `None`.
#[derive(Debug, Clone)]
pub struct TraceIter<'a, K, const DEPTH: usize, const REASON_LEN: usize>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
    error: &'a AnErr<K, DEPTH, REASON_LEN>,
    pos: usize,
}

impl<'a, K, const DEPTH: usize, const REASON_LEN: usize> Iterator
    for TraceIter<'a, K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
    type Item = (
        K,
        &'static Location<'static>,
        Option<&'a AsciiStr<REASON_LEN>>,
    );

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.error.len as usize {
            return None;
        }

        let idx = (self.error.len as usize) - 1 - self.pos;
        let kind = self.error.kinds[idx]?;
        let loc = self.error.locations[idx]?;
        let reason = self.error.reasons[idx].as_ref();

        self.pos += 1;
        Some((kind, loc, reason))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.error.len as usize).saturating_sub(self.pos);
        (remaining, Some(remaining))
    }
}

impl<'a, K, const DEPTH: usize, const REASON_LEN: usize> ExactSizeIterator
    for TraceIter<'a, K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
}

/// A compact, `Copy`, zero-allocation error type that records a parallel stack
/// of error kinds, source locations, and per-level human-readable reasons.
///
/// `AnErr` stores up to `DEPTH` levels of error context. Each level contains:
/// - an error kind of type `K`,
/// - the source location where the level was created,
/// - an optional reason specific to that level (`AsciiStr<REASON_LEN>`).
///
/// The kind enum provides the general error category while the per-level reason
/// carries concrete details (e.g. a bad value, file path, token, etc.).
///
/// The type implements `Copy` and performs no heap allocation. Default memory
/// footprint is small and fully controllable via the generic parameters.
///
/// # Type Parameters
///
/// - `K`: Error kind type. Must implement `Copy + Clone + Debug + PartialEq + Eq`.
/// - `DEPTH`: Maximum number of context levels (default `3`). Additional context
///   beyond this limit is silently discarded.
/// - `REASON_LEN`: Maximum length of each individual reason in bytes
///   (default `29`). Longer reasons are silently truncated.
///
/// # Construction
///
/// ```rust,ignore
/// use an_error::{AnErr, an_err};
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// pub enum MyKind {
///     Parse,
///     Io,
///     Validation,
/// }
///
/// pub type MyError = AnErr<MyKind, 4, 64>;
///
/// fn parse() -> Result<(), MyError> {
///     Err(an_err!(MyKind::Parse, "unexpected token at byte {}", 42))
/// }
///
/// fn load(path: &str) -> Result<(), MyError> {
///     let inner = parse()
///         .map_err(|e| an_err!(MyKind::Io, "while loading config from {}", path => e))?;
///     Ok(())
/// }
/// ```
///
/// All constructors and the `context` method capture the call site via `#[track_caller]`.
///
/// # Display
///
/// The `Display` implementation produces output of the following form:
///
/// ```text
/// --
/// • Trace (2 levels):
///    1. Io    @ src/io.rs:42:10    while loading config from /etc/foo
///    2. Parse @ src/parser.rs:17:5  unexpected token at byte 42
/// ```
///
/// Each trace level shows its own reason (if present) immediately after the location.
///
/// # Invariants
///
/// Maintained by all constructors and `context`:
///
/// - `len` is always in `1..=DEPTH`.
/// - For every `i` in `0..len`, `kinds[i]` and `locations[i]` are `Some`.
/// - `reasons[i]` is `Some` only if a non-empty reason was supplied for that level.
#[derive(Clone, Copy, PartialEq, Eq)]
#[must_use = "this error should be handled or converted to a different type"]
pub struct AnErr<K, const DEPTH: usize = 3, const REASON_LEN: usize = 29>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
    /// Per-level reasons. Only the first `len` entries are valid.
    /// `None` means no reason (or an empty reason) was provided for that level.
    pub reasons: [Option<AsciiStr<REASON_LEN>>; DEPTH],

    /// Parallel stack of source locations.
    /// Only the first `len` entries are valid.
    pub locations: [Option<&'static Location<'static>>; DEPTH],

    /// Parallel stack of error kinds (one per call-stack level).
    /// Only the first `len` entries are valid.
    pub kinds: [Option<K>; DEPTH],

    /// Current depth of the error trace (1 = original error).
    pub len: u8,
}

impl<K, const DEPTH: usize, const REASON_LEN: usize> AnErr<K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
    /// Creates a new error with the given kind and no reason.
    #[inline]
    #[track_caller]
    pub fn new(kind: K) -> Self {
        let mut kinds = [None; DEPTH];
        let mut locs = [None; DEPTH];
        let reasons = [None; DEPTH];

        kinds[0] = Some(kind);
        locs[0] = Some(Location::caller());

        Self {
            kinds,
            locations: locs,
            reasons,
            len: 1,
        }
    }

    /// Creates a new error with the given kind and reason.
    ///
    /// If the reason is empty, it is stored as `None`.
    #[inline]
    #[track_caller]
    pub fn with_reason(kind: K, reason: AsciiStr<REASON_LEN>) -> Self {
        let mut kinds = [None; DEPTH];
        let mut locs = [None; DEPTH];
        let mut reasons = [None; DEPTH];

        kinds[0] = Some(kind);
        locs[0] = Some(Location::caller());
        reasons[0] = if reason.is_empty() {
            None
        } else {
            Some(reason)
        };

        Self {
            kinds,
            locations: locs,
            reasons,
            len: 1,
        }
    }

    /// Creates a new error with the given kind and a formatted reason.
    ///
    /// The formatted string is truncated if it exceeds `REASON_LEN` bytes.
    #[inline]
    #[track_caller]
    pub fn with_fmt(kind: K, args: core::fmt::Arguments<'_>) -> Self {
        let mut kinds = [None; DEPTH];
        let mut locs = [None; DEPTH];
        let mut reasons = [None; DEPTH];

        kinds[0] = Some(kind);
        locs[0] = Some(Location::caller());
        let reason = AsciiStr::from_fmt(args);
        reasons[0] = if reason.is_empty() {
            None
        } else {
            Some(reason)
        };

        Self {
            kinds,
            locations: locs,
            reasons,
            len: 1,
        }
    }

    /// Returns the current depth of the error trace.
    #[inline]
    pub fn depth(&self) -> u8 {
        self.len
    }

    /// Returns the most recent error kind (the top of the trace).
    #[inline]
    pub fn kind(&self) -> Option<K> {
        if self.len == 0 {
            None
        } else {
            let idx = (self.len as usize) - 1;
            self.kinds[idx]
        }
    }

    /// Appends a new context level and optional reason to this error.
    ///
    /// If `new_reason` is empty, no reason is stored for the new level.
    /// If the maximum depth is already reached, the call is a no-op.
    #[inline]
    #[track_caller]
    pub fn context(&mut self, kind: K, new_reason: AsciiStr<REASON_LEN>) {
        let idx = self.len as usize;
        if idx < DEPTH {
            self.reasons[idx] = if new_reason.is_empty() {
                None
            } else {
                Some(new_reason)
            };
            self.push(kind, Location::caller());
        }
    }

    /// Appends a new context level with a formatted reason.
    ///
    /// Used internally by the `an_err!` macro. The formatted string is
    /// truncated if it exceeds `REASON_LEN` bytes.
    #[inline]
    #[track_caller]
    pub fn context_fmt(&mut self, kind: K, args: core::fmt::Arguments<'_>) {
        let idx = self.len as usize;
        if idx < DEPTH {
            let reason = AsciiStr::from_fmt(args);
            self.reasons[idx] = if reason.is_empty() {
                None
            } else {
                Some(reason)
            };
            self.push(kind, Location::caller());
        }
    }

    /// Returns an iterator over the error trace, from most recent context
    /// down to the original error.
    ///
    /// Each item is `(kind, location, reason)`. The iterator borrows `self`
    /// with zero copying.
    pub fn trace(&self) -> TraceIter<'_, K, DEPTH, REASON_LEN> {
        TraceIter {
            error: self,
            pos: 0,
        }
    }

    #[inline]
    fn push(&mut self, kind: K, loc: &'static Location<'static>) {
        if (self.len as usize) < DEPTH {
            let idx = self.len as usize;
            self.kinds[idx] = Some(kind);
            self.locations[idx] = Some(loc);
            self.len += 1;
        }
    }

    /// Serialize this error into a fixed-size byte buffer for transmission.
    ///
    /// The caller must provide a buffer that is at least `Self::WIRE_SIZE::<PATH_LEN>()` bytes long.
    /// Returns the number of bytes actually written (always the same for a given `PATH_LEN`).
    ///
    /// Recommended usage:
    /// ```rust,ignore
    /// #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    /// #[repr(u8)]   // or #[repr(u16)] for >256 variants
    /// pub enum MyKind { ... }
    ///
    /// let mut buf = [0u8; AnErr::<MyKind, 3, 29>::wire_size::<80>()];
    /// let written = my_error.to_wire_bytes::<80>(|k| k as u16, &mut buf);
    /// let packet = &buf[..written];
    /// ```
    #[cfg(feature = "wire")]
    pub fn to_wire_bytes<const PATH_LEN: usize>(
        &self,
        kind_to_u16: impl Fn(K) -> u16,
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let needed = Self::wire_size::<PATH_LEN>();
        if buf.len() < needed {
            return Err(());
        }

        let mut offset = 0;

        // Header
        buf[offset] = 1; // wire format version
        offset += 1;
        buf[offset] = self.len;
        offset += 1;

        for i in 0..DEPTH {
            if i < self.len as usize {
                // 1. Kind as u16
                let kind_val = self.kinds[i].map_or(0, &kind_to_u16);
                buf[offset..offset + 2].copy_from_slice(&kind_val.to_le_bytes());
                offset += 2;

                // 2. Reason
                let reason = self.reasons[i].as_ref().unwrap_or(&AsciiStr::DEFAULT);
                buf[offset..offset + REASON_LEN].copy_from_slice(&reason.to_wire_bytes());
                offset += REASON_LEN;

                // 3. Location
                if let Some(loc) = self.locations[i] {
                    let file = AsciiStr::<PATH_LEN>::from_str_truncate(loc.file());
                    buf[offset..offset + PATH_LEN].copy_from_slice(&file.to_wire_bytes());
                    offset += PATH_LEN;

                    buf[offset..offset + 4].copy_from_slice(&loc.line().to_le_bytes());
                    offset += 4;
                    buf[offset..offset + 4].copy_from_slice(&loc.column().to_le_bytes());
                    offset += 4;
                } else {
                    offset += PATH_LEN + 8; // pad
                }
            } else {
                // pad remaining levels
                offset += 2 + REASON_LEN + PATH_LEN + 8;
            }
        }

        Ok(needed)
    }

    /// Compile-time size of the wire representation for a given `PATH_LEN`.
    #[cfg(feature = "wire")]
    pub const fn wire_size<const PATH_LEN: usize>() -> usize {
        2 + DEPTH * (2 + REASON_LEN + PATH_LEN + 8)
    }
}

impl<K, const DEPTH: usize, const REASON_LEN: usize> From<K> for AnErr<K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
    /// Converts a kind into a new [`AnErr`] with no reason.
    #[inline]
    #[track_caller]
    fn from(kind: K) -> Self {
        Self::new(kind)
    }
}

impl<K, const DEPTH: usize, const REASON_LEN: usize> core::fmt::Display
    for AnErr<K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        writeln!(f)?;
        writeln!(f, "--")?;
        writeln!(f, "Error:")?;

        for (i, (kind, loc, reason_opt)) in self.trace().enumerate() {
            let num = i + 1;

            write!(f, "  {:>2}. {:?}", num, kind)?;

            if let Some(reason) = reason_opt {
                if let Ok(s) = reason.as_str() {
                    write!(f, ": {}", s)?;
                } else {
                    write!(f, ": <invalid ascii>")?;
                }
            }

            writeln!(f, " @ {}:{}:{}", loc.file(), loc.line(), loc.column())?;
        }

        Ok(())
    }
}

impl<K, const DEPTH: usize, const REASON_LEN: usize> fmt::Debug for AnErr<K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + fmt::Debug + PartialEq + Eq,
{
    /// Debug prints the same clean, human-readable trace as Display.
    /// This makes `unwrap()`, `dbg!()`, and panic messages readable instead of
    /// dumping giant byte arrays.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl<K, const DEPTH: usize, const REASON_LEN: usize> core::error::Error
    for AnErr<K, DEPTH, REASON_LEN>
where
    K: Copy + Clone + core::fmt::Debug + PartialEq + Eq,
{
}

/// Ergonomic constructor and chaining macro for [`AnErr`].
///
/// # Forms
///
/// | Form                                              | Equivalent to                                      |
/// |---------------------------------------------------|----------------------------------------------------|
/// | `an_err!(Kind)`                                   | `AnErr::new(Kind)`                               |
/// | `an_err!(Kind, "reason")`                         | `AnErr::with_fmt(Kind, ...)`                     |
/// | `an_err!(Kind, "reason {}", arg, ...)`            | `AnErr::with_fmt(Kind, ...)`                     |
/// | `an_err!(Kind, "reason" => inner)`                | `inner.context(Kind, ...)`                         |
/// | `an_err!(Kind, "reason {}", arg => inner)`        | `inner.context(Kind, ...)`                         |
///
/// All forms capture the call site via `#[track_caller]`.
#[macro_export]
macro_rules! an_err {
    // New error, no reason
    ($kind:expr) => {
        $crate::AnErr::new($kind)
    };

    // Chaining form (must appear before the new-error form)
    ($kind:expr, $fmt:literal $(, $arg:expr)* => $inner:expr $(,)?) => {{
        let mut e = $inner;
        e.context_fmt(
            $kind,
            format_args!($fmt $(, $arg)*)
        );
        e
    }};

    // New error with reason (literal or formatted)
    ($kind:expr, $fmt:literal $(, $arg:expr)* $(,)?) => {
        $crate::AnErr::with_fmt($kind, format_args!($fmt $(, $arg)*))
    };
}

/// Portable location for wire transmission.
#[cfg(feature = "wire")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireLocation<const N: usize> {
    pub file: AsciiStr<N>,
    pub line: u32,
    pub column: u32,
}

/// Fully portable, zero-allocation error for transmission/reception.
#[cfg(feature = "wire")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WireErr<const DEPTH: usize = 3, const REASON_LEN: usize = 29, const FILE_LEN: usize = 80>
{
    pub len: u8,
    pub kinds: [Option<u16>; DEPTH],
    pub reasons: [Option<AsciiStr<REASON_LEN>>; DEPTH],
    pub locations: [Option<WireLocation<FILE_LEN>>; DEPTH],
}

#[cfg(feature = "wire")]
impl<const DEPTH: usize, const REASON_LEN: usize, const FILE_LEN: usize>
    WireErr<DEPTH, REASON_LEN, FILE_LEN>
{
    /// Fixed wire size (exactly matches `AnErr::wire_size::<FILE_LEN>()`).
    pub const fn wire_size() -> usize {
        const fn compute_size<const D: usize, const R: usize, const F: usize>() -> usize {
            2 + D * (2 + R + F + 8)
        }
        compute_size::<DEPTH, REASON_LEN, FILE_LEN>()
    }

    /// Parse a wire buffer from `AnErr` into a `WireErr`.
    ///
    /// Returns `None` on any corruption, wrong size, unknown version,
    /// or invalid `AsciiStr` data.
    pub fn from_wire_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() != Self::wire_size() {
            return None;
        }

        let mut offset = 0;

        // Version
        let version = bytes[offset];
        if version != 1 {
            return None; // unknown wire format
        }
        offset += 1;

        let len = bytes[offset];
        if len == 0 || len as usize > DEPTH {
            return None;
        }
        offset += 1;

        let mut kinds = [None; DEPTH];
        let mut reasons = [None; DEPTH];
        let mut locations = [None; DEPTH];

        for i in 0..(len as usize) {
            // kind (u16)
            let kind_bytes = <[u8; 2]>::try_from(&bytes[offset..offset + 2]).ok()?;
            kinds[i] = Some(u16::from_le_bytes(kind_bytes));
            offset += 2;

            // reason
            let reason_bytes = &bytes[offset..offset + REASON_LEN];
            reasons[i] = AsciiStr::from_wire_bytes(reason_bytes);
            offset += REASON_LEN;

            // location
            let file_bytes = &bytes[offset..offset + FILE_LEN];
            let file = AsciiStr::from_wire_bytes(file_bytes)?;

            offset += FILE_LEN;

            let line_bytes = <[u8; 4]>::try_from(&bytes[offset..offset + 4]).ok()?;
            let line = u32::from_le_bytes(line_bytes);
            offset += 4;

            let col_bytes = <[u8; 4]>::try_from(&bytes[offset..offset + 4]).ok()?;
            let column = u32::from_le_bytes(col_bytes);
            offset += 4;

            locations[i] = Some(WireLocation { file, line, column });
        }

        // remaining bytes are padding (we already checked total length)

        Some(WireErr {
            len,
            kinds,
            reasons,
            locations,
        })
    }
}

#[cfg(feature = "alloc")]
#[cfg(test)]
mod tests {
    use super::*;
    use alloc::format;
    use alloc::vec::Vec;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[repr(u8)]
    enum TestKind {
        Root,
        Context1,
        Context2,
        Parse,
        Io,
    }

    /// Helper for creating `AsciiStr` reasons (turbofish required for const generic).
    fn r<const N: usize>(s: &str) -> AsciiStr<N> {
        AsciiStr::from_str_truncate(s)
    }

    // Use the crate's exact *default* parameters so the an_err! macro + constructors
    // match perfectly and inference is unambiguous.
    type E3 = AnErr<TestKind, 3, 29>;

    #[test]
    fn test_new_from_and_basic_properties() {
        let e1: E3 = AnErr::new(TestKind::Root);
        let e2: E3 = TestKind::Root.into();

        // NOTE: We cannot use assert_eq!(e1, e2) because #[track_caller]
        // captures different source locations (different lines in this test).
        // The rest of the data is identical.
        assert_eq!(e1.depth(), e2.depth());
        assert_eq!(e1.kind(), e2.kind());
        assert_eq!(e1.depth(), 1);
        assert_eq!(e1.kind(), Some(TestKind::Root));

        let mut trace = e1.trace();
        let (kind, _loc, reason) = trace.next().unwrap();
        assert_eq!(kind, TestKind::Root);
        assert!(reason.is_none());
        assert!(trace.next().is_none());
    }

    #[test]
    fn test_with_reason_and_with_fmt() {
        // Explicit type fixes const-generic inference (DEPTH cannot be inferred from AsciiStr alone)
        let e: E3 = AnErr::with_reason(TestKind::Parse, r::<29>("bad token"));
        assert_eq!(e.depth(), 1);

        let items: Vec<_> = e.trace().collect();
        assert_eq!(items[0].2.unwrap().as_str().unwrap(), "bad token");

        let e2: E3 = AnErr::with_fmt(
            TestKind::Io,
            format_args!("file not found: {}", "config.toml"),
        );
        let items2: Vec<_> = e2.trace().collect();
        assert_eq!(
            items2[0].2.unwrap().as_str().unwrap(),
            "file not found: config.toml"
        );
    }

    #[test]
    fn test_an_err_macro_all_forms() {
        let e1: E3 = an_err!(TestKind::Root);
        assert_eq!(e1.kind(), Some(TestKind::Root));

        let e2: E3 = an_err!(TestKind::Parse, "unexpected {}", "EOF");
        assert_eq!(
            e2.trace().next().unwrap().2.unwrap().as_str().unwrap(),
            "unexpected EOF"
        );

        // Chaining form
        let inner: E3 = an_err!(TestKind::Parse, "bad data");
        let outer: E3 = an_err!(TestKind::Io, "while reading file" => inner);

        assert_eq!(outer.depth(), 2);
        let mut t = outer.trace();
        let (k1, _, r1) = t.next().unwrap();
        assert_eq!(k1, TestKind::Io);
        assert_eq!(r1.unwrap().as_str().unwrap(), "while reading file");

        let (k2, _, r2) = t.next().unwrap();
        assert_eq!(k2, TestKind::Parse);
        assert_eq!(r2.unwrap().as_str().unwrap(), "bad data");
    }

    #[test]
    fn test_context_and_context_fmt() {
        let mut e: E3 = an_err!(TestKind::Root, "initial");
        e.context(TestKind::Context1, r::<29>("level 1"));
        e.context_fmt(TestKind::Context2, format_args!("level {}", 2));

        assert_eq!(e.depth(), 3);

        let trace: Vec<_> = e.trace().collect();
        // Most recent first
        assert_eq!(trace[0].0, TestKind::Context2);
        assert_eq!(trace[1].0, TestKind::Context1);
        assert_eq!(trace[2].0, TestKind::Root);

        assert_eq!(trace[0].2.unwrap().as_str().unwrap(), "level 2");
        assert_eq!(trace[1].2.unwrap().as_str().unwrap(), "level 1");
        assert_eq!(trace[2].2.unwrap().as_str().unwrap(), "initial");
    }

    #[test]
    fn test_max_depth_is_no_op() {
        let mut e: E3 = an_err!(TestKind::Root);
        for i in 0..10 {
            e.context(TestKind::Context1, r::<29>(&format!("extra {i}")));
        }
        assert_eq!(e.depth(), 3); // DEPTH limit reached, further calls ignored

        let trace: Vec<_> = e.trace().collect();
        assert_eq!(trace.len(), 3);
        assert_eq!(trace[0].0, TestKind::Context1); // last successful context
    }

    #[test]
    fn test_empty_reason_becomes_none() {
        let e: E3 = an_err!(TestKind::Parse, "");
        let (_, _, reason) = e.trace().next().unwrap();
        assert!(reason.is_none());

        let mut e2: E3 = an_err!(TestKind::Root);
        e2.context(TestKind::Io, r::<29>("")); // empty literal -> None
        let items: Vec<_> = e2.trace().collect();
        assert!(items[0].2.is_none());
    }

    #[test]
    fn test_trace_iter_order_exact_size_and_size_hint() {
        let e: E3 = an_err!(TestKind::Root, "a" => an_err!(TestKind::Io, "b" => an_err!(TestKind::Parse, "c")));

        let trace = e.trace();
        assert_eq!(trace.len(), 3); // ExactSizeIterator
        assert_eq!(trace.size_hint(), (3, Some(3)));

        let collected: Vec<_> = trace.collect();
        assert_eq!(collected.len(), 3);
        assert_eq!(collected[0].0, TestKind::Root); // most recent
        assert_eq!(collected[1].0, TestKind::Io);
        assert_eq!(collected[2].0, TestKind::Parse); // original
    }

    #[test]
    fn test_kind_returns_most_recent() {
        let mut e: E3 = an_err!(TestKind::Parse);
        e.context(TestKind::Context1, r::<29>("ctx1"));
        e.context(TestKind::Context2, r::<29>("ctx2"));

        assert_eq!(e.kind(), Some(TestKind::Context2)); // top of the trace
    }

    #[test]
    fn test_display() {
        let inner: E3 = an_err!(TestKind::Parse, "bad syntax");
        let e: E3 = an_err!(TestKind::Io, "while loading config" => inner);

        let display = format!("{}", e);
        assert!(display.contains("--"));
        assert!(display.contains("Error:"));
        assert!(display.contains("Io"));
        assert!(display.contains("while loading config"));
        assert!(display.contains("Parse"));
        assert!(display.contains("bad syntax"));
    }

    #[cfg(feature = "wire")]
    type E4 = AnErr<TestKind, 4, 29>;
    #[cfg(feature = "wire")]
    use alloc::vec;

    #[cfg(feature = "wire")]
    #[test]
    fn test_wire_roundtrip() {
        let inner: E4 = an_err!(TestKind::Parse, "unexpected char");
        let e: E4 = an_err!(TestKind::Io, "while processing file" => inner);

        const FILE_LEN: usize = 64;
        let wire_size = E4::wire_size::<FILE_LEN>();
        let mut buf = vec![0u8; wire_size];

        // Fixed: turbofish required for the const generic PATH_LEN
        let written = e.to_wire_bytes::<FILE_LEN>(|k| k as u16, &mut buf).unwrap();
        assert_eq!(written, wire_size);

        let wire_err = WireErr::<4, 29, FILE_LEN>::from_wire_bytes(&buf[..written]).unwrap();

        assert_eq!(wire_err.len, 2);

        // Wire stores levels oldest-first (index 0 = root)
        assert_eq!(wire_err.kinds[0], Some(TestKind::Parse as u16));
        assert_eq!(wire_err.kinds[1], Some(TestKind::Io as u16));

        assert_eq!(
            wire_err.reasons[0].as_ref().unwrap().as_str().unwrap(),
            "unexpected char"
        );
        assert_eq!(
            wire_err.reasons[1].as_ref().unwrap().as_str().unwrap(),
            "while processing file"
        );
    }

    #[cfg(feature = "wire")]
    #[test]
    fn test_wire_invalid_cases() {
        // Wrong size
        assert!(WireErr::<3, 29, 64>::from_wire_bytes(&[0u8; 10]).is_none());

        // Bad version
        let mut buf = vec![0u8; E4::wire_size::<64>()];
        buf[0] = 99; // invalid version
        assert!(WireErr::<4, 29, 64>::from_wire_bytes(&buf).is_none());
    }
}