ondas 2.1.0

Read-only, format-independent waveform analysis library
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
use std::{collections::HashMap, ops::ControlFlow};

use crate::{Hierarchy, Result, Signal, Time, TimeRange, Value, ValueRef, Waveform};

mod engine;

#[cfg(test)]
mod tests;

/// A reusable, ordered selection of waveform signals.
///
/// [`Waveform::select`] creates a selection. The selection mutably borrows the
/// waveform, validates the selected handles and groups their histories for reuse.
/// One-shot waveform methods have the same semantics as temporary selections.
///
/// Input order and duplicates are preserved. Each input position gets its own
/// sample, trace, or scan observations, even for equal aliases or repeated slices. Internal deduplication of base histories is not observable.
/// Candidate timestamps are the exception: they form a unique time union.
///
/// Clone [`Self::hierarchy`] before retaining hierarchy views across mutable
/// selection queries. See the [`Waveform`] example for ownership and borrowing.
pub struct Selection<'w> {
    waveform: &'w mut Waveform,
    signals: Vec<Signal>,
    bases: Vec<Signal>,
    groups: HashMap<usize, Vec<usize>>,
    slot_indices: Vec<usize>,
    retained_signals: Vec<Signal>,
    computations: Vec<engine::Computation>,
    replay: Option<engine::Replay>,
    checkpoint: Option<engine::Replay>,
}

/// Selective reads at one completed candidate tick of [`Selection::query`].
///
/// Only the current absolute tick and the tick immediately before it (`t - 1`)
/// are readable. The preceding tick is defined by tick count, not candidate order. The
/// preceding tick may lie before the query range. It does not exist at tick zero.
/// Reads can be repeated in any order. They return final states, never provisional
/// states. The caller defines conditions and interprets events and edges.
///
/// The context delivers samples only when requested. It does not provide a
/// prebuilt snapshot or access to arbitrary history. A sequential reader may
/// still decode records while advancing. Borrowed samples are valid only for
/// their visitor. Use [`ValueRef::to_owned`] to retain their contents.
///
/// # Borrowing rules
///
/// A context cannot escape its candidate callback:
///
/// ```compile_fail,E0521
/// use ondas::{Result, Selection, TimeRange};
/// use std::ops::ControlFlow;
/// fn escape(selection: &mut Selection<'_>) -> Result<()> {
///     let mut saved = None;
///     selection.query(TimeRange::all(), &[0], |context| {
///         saved = Some(context);
///         Ok(ControlFlow::<()>::Continue(()))
///     })?;
///     println!("{:?}", saved.unwrap().time());
///     Ok(())
/// }
/// ```
///
/// A sample cannot escape even into its surrounding candidate callback:
///
/// ```compile_fail,E0521
/// use ondas::{Result, Selection, TimeRange};
/// use std::ops::ControlFlow;
/// fn escape(selection: &mut Selection<'_>) -> Result<()> {
///     selection.query(TimeRange::all(), &[0], |context| {
///         let mut saved = None;
///         context.visit_samples(context.time(), &[0], |_, sample| {
///             saved = Some(sample);
///             Ok(ControlFlow::<()>::Continue(()))
///         })?;
///         println!("{:?}", saved.unwrap());
///         Ok(ControlFlow::<()>::Continue(()))
///     })?;
///     Ok(())
/// }
/// ```
pub struct QueryContext<'a> {
    time: Time,
    signals: &'a [Signal],
    slots: &'a [engine::Slot],
    slot_indices: &'a [usize],
    previous_tick: Option<Time>,
    previous_events: &'a [u64],
}

impl Selection<'_> {
    /// Returns the selected signals in input order, including duplicates.
    pub fn signals(&self) -> &[Signal] {
        &self.signals
    }

    /// Test probe: successful VCD position-index seeds for this retained selection.
    #[cfg(all(test, unix))]
    pub(crate) fn vcd_index_queries(&self) -> Option<usize> {
        match &self.waveform.reader {
            crate::backends::Reader::Vcd(reader) => Some(
                reader
                    .index_queries
                    .load(std::sync::atomic::Ordering::Relaxed),
            ),
            _ => None,
        }
    }

    /// Test probe: VCD indexed traversals for this retained selection.
    #[cfg(all(test, unix))]
    pub(crate) fn vcd_traversal_queries(&self) -> Option<usize> {
        match &self.waveform.reader {
            crate::backends::Reader::Vcd(reader) => Some(
                reader
                    .traversal_queries
                    .load(std::sync::atomic::Ordering::Relaxed),
            ),
            _ => None,
        }
    }

    /// Returns the hierarchy associated with the selected waveform.
    pub fn hierarchy(&self) -> &Hierarchy {
        self.waveform.hierarchy()
    }

    /// Returns an owned sample for each selected signal at `time`.
    ///
    /// Results retain selection order and duplicates. See [`Sample`] for final
    /// tick state, missing values, event counts, and sampling after EOF.
    /// On failure, returns [`Error`](crate::Error), not a partial vector.
    pub fn samples(&mut self, time: Time) -> Result<Vec<Sample>> {
        let mut samples = Vec::with_capacity(self.signals.len());
        let _ = self.visit_samples(time, |sample| {
            samples.push(sample.to_owned());
            ControlFlow::<()>::Continue(())
        })?;
        Ok(samples)
    }

    /// Returns an owned trace for each selected signal over `range`.
    ///
    /// Results retain selection order and duplicates and follow [`Self::scan`]
    /// semantics. Empty ranges produce traces with no initial state or changes.
    /// On failure, returns [`Error`](crate::Error), not a partial vector.
    pub fn traces(&mut self, range: TimeRange) -> Result<Vec<Trace>> {
        let mut traces = self
            .signals
            .iter()
            .map(|&signal| Trace {
                signal,
                range,
                initial: None,
                changes: Vec::new(),
            })
            .collect::<Vec<_>>();
        let _ = self.scan_each(range, |index, record| {
            match record {
                ScanRef::Initial {
                    value, changed_at, ..
                } => {
                    traces[index].initial = Some(Initial {
                        value: value.to_owned(),
                        changed_at,
                    })
                }
                ScanRef::Change { time, value, .. } => traces[index].changes.push(Change {
                    time,
                    value: value.to_owned(),
                }),
            }
            ControlFlow::<()>::Continue(())
        })?;
        Ok(traces)
    }

    /// Visits a borrowed sample for each signal in selection order at `time`.
    ///
    /// Includes duplicates and follows [`Sample`] semantics. A callback's borrowed
    /// values cannot outlive that callback. Copy a value with [`ValueRef::to_owned`]
    /// to retain it. Returning [`ControlFlow::Break`] ends successfully and returns
    /// that break value inside `Ok`. It does not report a query error.
    pub fn visit_samples<B>(
        &mut self,
        time: Time,
        visitor: impl for<'v> FnMut(SampleRef<'v>) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        self.sample_visit(time, visitor)
    }

    /// Visits entering states, then time-ordered changes, in inclusive `range`.
    ///
    /// For input-position indices that distinguish repeated entries, use
    /// [`Self::scan_each`]. This convenience form uses the same execution path.
    ///
    /// # Entering state
    ///
    /// For each selection entry with a known persistent state strictly before
    /// `range.start()`, emits at most one [`ScanRef::Initial`]. All initials come
    /// first in selection order, including duplicate entries. A known
    /// `changed_at` is strictly less than the start. Events have no initial state.
    /// No synthetic change at `start - 1` is created, including at tick zero.
    /// A nonempty range that starts after EOF emits known entering states and
    /// no changes. This includes unbounded ranges.
    ///
    /// # Changes and ordering
    ///
    /// Changes and event occurrences inside the closed range follow in
    /// nondecreasing time. Different signals have no defined order within one
    /// tick. Each persistent selection entry emits at most one net change per
    /// tick. This is its final recorded value, compared with the state entering the
    /// tick using [`ValueRef`] representation identity. If the value changes and
    /// returns to the entering state within one tick, it produces no net change.
    /// It does not advance `changed_at`. If no entering state is known, the final
    /// value establishes one. This includes HDL unknown.
    /// Samples, scans and traces use these same final tick states.
    ///
    /// Each [`ValueRef::Event`] change aggregates a positive `occurrences` count
    /// for one entry and tick, subject to the FST
    /// [first-tick initialization limitation](crate#fst).
    /// Counts preserve reader observations, not ordering within the tick or
    /// events omitted by the producer. Overflow returns an error. The count never wraps.
    /// Repeated selection entries each receive the same count. Slices emit
    /// only changes of their projected values. Unrelated base-bit activity produces
    /// no slice changes.
    /// Duplicate selection entries retain their observations. An empty range
    /// calls no visitor, including for initial states.
    ///
    /// # Borrowing, stopping, and errors
    ///
    /// Values can borrow backend buffers and are valid only during the callback.
    /// Use [`ValueRef::to_owned`] to retain them. [`ControlFlow::Break`] is a
    /// successful early stop, returned as `Ok(ControlFlow::Break(value))`.
    /// A completed scan returns `Ok(ControlFlow::Continue(()))`.
    ///
    /// A late backend failure returns [`Error`](crate::Error). Earlier visitor calls
    /// may already have delivered observations.
    /// It does not roll those observations back. Only completed ticks are
    /// published. A failure discards the unfinished pending tick. A sequential
    /// reader may need one record of the next tick to complete the preceding
    /// tick before calling the visitor. Owned [`Self::samples`] and
    /// [`Self::traces`] instead return no partial result on error.
    pub fn scan<B>(
        &mut self,
        range: TimeRange,
        mut visitor: impl for<'v> FnMut(ScanRef<'v>) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        self.scan_each(range, |_, record| visitor(record))
    }

    /// Visits a strictly increasing superset of selected change times in `range`.
    ///
    /// Every timestamp that could be emitted as [`ScanRef::Change`] by a full
    /// [`Self::scan`] of this selection and range must occur. Additional candidate
    /// times are allowed. For a slice, these may include changes to other bits of
    /// its base signal. A backend may use an activity index for these candidates,
    /// but callers must not assume that the operation avoids decoding values.
    ///
    /// Initial states do not contribute timestamps. The union does not identify the
    /// changing signal or event count. Repeated handles and multiple occurrences at
    /// one tick still yield that tick only once. Both bounds are included. An empty
    /// range produces no calls.
    ///
    /// [`ControlFlow::Break`] stops successfully with the visitor's break value
    /// inside `Ok`. Normal completion returns `Ok(ControlFlow::Continue(()))`.
    pub fn scan_candidate_times<B>(
        &mut self,
        range: TimeRange,
        mut visitor: impl FnMut(Time) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        let end = range
            .end()
            .or_else(|| self.waveform.metadata().time_span().map(|span| span.last()))
            .unwrap_or(Time::from_ticks(u64::MAX));
        if let crate::backends::Reader::Fst(reader) = &mut self.waveform.reader {
            return reader.read_candidate_times(&self.bases, range.start(), end, visitor);
        }
        if let crate::backends::Reader::Vcd(reader) = &self.waveform.reader
            && let Some(result) =
                reader.candidate_times(&self.bases, range.start(), end, &mut visitor)
        {
            return Ok(result);
        }
        let mut last = None;
        self.scan(range, |record| {
            if let ScanRef::Change { time, .. } = record
                && last != Some(time)
            {
                last = Some(time);
                return visitor(time);
            }
            ControlFlow::Continue(())
        })
    }
}

/// An owned value or event sample for a signal at one timestamp.
///
/// A persistent signal returns its final state after all of its changes at the
/// sampled tick. `changed_at`, when known, is the tick that established the
/// observed state and is no later than the sampled time. For a slice, it is the
/// last projected-value change. Activity in other base bits does not affect it.
/// An unreliable timestamp is `None`. Changes that return to the entering value
/// within one tick do not advance this timestamp.
///
/// [`Self::Missing`] means no persistent value is known at or before that time,
/// not a read error or an HDL unknown logic value. Events have no persistent
/// state and never use `Missing`. [`Self::Event`] counts occurrences at exactly
/// the requested tick, including zero. The FST reader can expose initialization
/// callbacks at the first recorded tick. See the
/// [reader limits](crate#reader-details) before interpreting that count.
///
/// Query times are not restricted by [`Metadata::time_span`](crate::Metadata::time_span).
/// After EOF, the last known persistent value is held. Event counts are zero.
/// Each result carries its selected [`Signal`], including a slice handle, so
/// batch results remain self-contained. Owned queries return no partial result
/// on a file or backend error.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Sample {
    /// No persistent value is known at or before the sampled time.
    Missing {
        /// The sampled signal.
        signal: Signal,
    },
    /// The final persistent value after all changes at the sampled time.
    Value {
        /// The sampled signal.
        signal: Signal,
        /// The sampled value.
        value: Value,
        /// The time that established this observed value, if known.
        changed_at: Option<Time>,
    },
    /// The number of event occurrences at the sampled time.
    Event {
        /// The sampled event signal.
        signal: Signal,
        /// The exact occurrence count, which may be zero.
        occurrences: u64,
    },
}

/// A borrowed sample with the same observation semantics as [`Sample`].
///
/// A view from [`Selection::visit_samples`] is valid only during its callback.
/// A view from [`Sample::as_ref`] instead borrows that owned sample.
/// A view from [`Trace::sample`] or [`Trace::samples_at`] borrows the saved trace.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum SampleRef<'a> {
    /// No persistent value is known at or before the sampled time.
    Missing {
        /// The sampled signal.
        signal: Signal,
    },
    /// The final persistent value after all changes at the sampled time.
    Value {
        /// The sampled signal.
        signal: Signal,
        /// The borrowed sampled value.
        value: ValueRef<'a>,
        /// The time that established this observed value, if known.
        changed_at: Option<Time>,
    },
    /// The number of event occurrences at the sampled time.
    Event {
        /// The sampled event signal.
        signal: Signal,
        /// The exact occurrence count, which may be zero.
        occurrences: u64,
    },
}

impl Sample {
    /// Returns the sampled signal.
    pub fn signal(&self) -> Signal {
        self.as_ref().signal()
    }

    /// Borrows this sample without copying its owned value.
    pub fn as_ref(&self) -> SampleRef<'_> {
        match self {
            Self::Missing { signal } => SampleRef::Missing { signal: *signal },
            Self::Value {
                signal,
                value,
                changed_at,
            } => SampleRef::Value {
                signal: *signal,
                value: value.as_ref(),
                changed_at: *changed_at,
            },
            Self::Event {
                signal,
                occurrences,
            } => SampleRef::Event {
                signal: *signal,
                occurrences: *occurrences,
            },
        }
    }
}

impl SampleRef<'_> {
    /// Copies this observation into an independent owned sample.
    ///
    /// The copy retains the signal, change time or occurrence count. Its value
    /// no longer borrows the callback, sample or trace that supplied this view.
    pub fn to_owned(self) -> Sample {
        match self {
            Self::Missing { signal } => Sample::Missing { signal },
            Self::Value {
                signal,
                value,
                changed_at,
            } => Sample::Value {
                signal,
                value: value.to_owned(),
                changed_at,
            },
            Self::Event {
                signal,
                occurrences,
            } => Sample::Event {
                signal,
                occurrences,
            },
        }
    }

    /// Returns the sampled signal.
    pub fn signal(self) -> Signal {
        match self {
            Self::Missing { signal } | Self::Value { signal, .. } | Self::Event { signal, .. } => {
                signal
            }
        }
    }
}

/// A borrowed record emitted by a range scan.
///
/// [`Selection::scan`] defines initial-state ordering, same-tick changes, event
/// multiplicity, duplicates, and partial observations. Values supplied by a scan
/// are valid only during the callback. Use [`ValueRef::to_owned`] to retain them.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum ScanRef<'a> {
    /// A persistent state established before the range start.
    Initial {
        /// The signal whose entering state is reported.
        signal: Signal,
        /// The borrowed entering value.
        value: ValueRef<'a>,
        /// The time that established the value, if known. It is strictly before range start.
        ///
        /// For a slice this describes the projected value, not unrelated base activity.
        changed_at: Option<Time>,
    },
    /// A value change or per-tick event aggregate within the range.
    Change {
        /// The signal that changed or produced the event.
        signal: Signal,
        /// The change or occurrence time.
        time: Time,
        /// The new persistent value, or a positive [`ValueRef::Event`] count.
        value: ValueRef<'a>,
    },
}

/// An owned persistent state established strictly before a trace range.
///
/// This is separate from actual changes in the range, not a synthetic timestamp.
/// Event signals have no entering state.
pub struct Initial {
    value: Value,
    changed_at: Option<Time>,
}

/// An owned value change or per-tick event aggregate within a trace range.
///
/// Each event record carries a positive count for one tick. Persistent changes
/// contain only a tick's final recorded state when it differs from the state
/// entering that tick, or first establishes a state.
pub struct Change {
    time: Time,
    value: Value,
}

/// An owned range scan for one signal.
///
/// Follows [`Selection::scan`] semantics. A state strictly before the range is
/// stored separately from changes inside the inclusive bounds. An empty range has
/// no initial state or changes. No changes in a nonempty range is a successful
/// empty change list. An entering state may still be present.
/// An unbounded range starting after EOF retains any known entering state.
/// [`Self::sample`] and [`Self::samples_at`] read this owned history without
/// source access, including ordinary EOF sampling for an unbounded range.
///
/// Owned trace queries return an error without a partial trace on read failure.
/// Views obtained from this trace's [`Initial`] and [`Change`] objects borrow
/// their owned storage, not a callback buffer.
pub struct Trace {
    signal: Signal,
    range: TimeRange,
    initial: Option<Initial>,
    changes: Vec<Change>,
}

impl Initial {
    /// Returns the entering value.
    pub fn value(&self) -> ValueRef<'_> {
        self.value.as_ref()
    }

    /// Returns the time that established the entering value, if known.
    ///
    /// Always strictly before the trace range start. For a slice this is the
    /// projected value's change time, or `None` if it cannot be determined reliably.
    pub fn changed_at(&self) -> Option<Time> {
        self.changed_at
    }
}

impl Change {
    /// Returns the change or event occurrence time.
    pub fn time(&self) -> Time {
        self.time
    }

    /// Returns the new persistent value, or a positive [`ValueRef::Event`] count.
    pub fn value(&self) -> ValueRef<'_> {
        self.value.as_ref()
    }
}

impl Trace {
    /// Samples this saved history without reading its source or copying values.
    ///
    /// Both finite bounds are included. An unbounded trace covers all ticks at
    /// or after its start, including after EOF. Those ticks follow [`Sample`]'s
    /// held-state and zero-event rules. A reversed range covers no ticks.
    /// Outside this coverage, returns [`Error::TraceCoverage`](crate::Error::TraceCoverage),
    /// not [`SampleRef::Missing`]. An entering state does not extend coverage
    /// before the start.
    ///
    /// Inside coverage, applies completed changes through `time` to the entering
    /// state. Events count only occurrences at exactly `time`. The first
    /// persistent change without an entering state has no known `changed_at`;
    /// its record time alone does not establish a preceding value.
    ///
    /// The view borrows this trace and can outlive this call. Use
    /// [`SampleRef::to_owned`] for an independent copy. Lookup takes logarithmic
    /// time in the number of saved changes and constant additional state.
    ///
    /// ```
    /// use ondas::{Error, Time, TimeRange, SampleRef, ValueRef};
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let t = Time::from_ticks;
    /// let input = b"$var wire 1 a a $end $enddefinitions $end #2 0a #6 1a #16";
    /// let mut wave = ondas::open_bytes("saved.vcd", input.as_slice().into())?;
    /// let a = wave.hierarchy().signal("a")?;
    /// let saved = wave.trace(a, TimeRange::closed(t(4), t(12)))?;
    /// let tail = wave.trace(a, TimeRange::from(t(17)))?;
    /// drop(wave);
    /// let rows = saved.samples_at(&[t(12), t(4), t(12), t(8)])?;
    /// assert_eq!(rows.len(), 4);
    /// assert!(matches!(saved.sample(t(13)), Err(Error::TraceCoverage { .. })));
    /// let SampleRef::Value { value: ValueRef::Bits(bits), changed_at, .. } =
    ///     tail.sample(t(u64::MAX))? else { panic!() };
    /// assert_eq!(bits.to_string(), "1");
    /// assert_eq!(changed_at, Some(t(6)));
    /// let retained = tail.sample(t(20))?.to_owned();
    /// drop(tail);
    /// assert_eq!(retained.signal(), a);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// A borrowed result cannot outlive its trace:
    ///
    /// ```compile_fail,E0515
    /// use ondas::{SampleRef, Time, Trace};
    /// fn escape(trace: Trace, time: Time) -> SampleRef<'static> {
    ///     trace.sample(time).unwrap()
    /// }
    /// ```
    pub fn sample(&self, time: Time) -> Result<SampleRef<'_>> {
        if self.range.is_empty()
            || time < self.range.start()
            || self.range.end().is_some_and(|end| time > end)
        {
            return Err(crate::Error::TraceCoverage {
                requested: time,
                range: self.range,
            });
        }
        let index = self.changes.partition_point(|change| change.time <= time);
        let change = index.checked_sub(1).map(|index| &self.changes[index]);
        if self.signal.encoding() == crate::Encoding::Event {
            let occurrences = match change
                .filter(|change| change.time == time)
                .map(Change::value)
            {
                Some(ValueRef::Event { occurrences }) => occurrences,
                _ => 0,
            };
            return Ok(SampleRef::Event {
                signal: self.signal,
                occurrences,
            });
        }
        if let Some(change) = change {
            return Ok(SampleRef::Value {
                signal: self.signal,
                value: change.value(),
                changed_at: (index > 1 || self.initial.is_some()).then_some(change.time),
            });
        }
        Ok(match &self.initial {
            Some(initial) => SampleRef::Value {
                signal: self.signal,
                value: initial.value(),
                changed_at: initial.changed_at,
            },
            None => SampleRef::Missing {
                signal: self.signal,
            },
        })
    }

    /// Samples several saved ticks in input order, including duplicates.
    ///
    /// Each row retains its requested time and follows [`Self::sample`]. Values
    /// borrow only this trace, not `times`. An empty list returns an empty vector.
    /// If any time is outside coverage, returns an error without a partial vector.
    pub fn samples_at(&self, times: &[Time]) -> Result<Vec<(Time, SampleRef<'_>)>> {
        times
            .iter()
            .map(|&time| self.sample(time).map(|sample| (time, sample)))
            .collect()
    }

    /// Returns the traced signal.
    pub fn signal(&self) -> Signal {
        self.signal
    }

    /// Returns the inclusive range covered by this trace.
    pub fn range(&self) -> TimeRange {
        self.range
    }

    /// Returns the persistent state established strictly before the range, if any.
    ///
    /// Returns `None` for an empty range, an event signal, or no known entering state.
    pub fn initial(&self) -> Option<&Initial> {
        self.initial.as_ref()
    }

    /// Returns the changes and event occurrences within the closed range.
    ///
    /// Times are nondecreasing. Each persistent signal has at most one net
    /// change per tick, representing its final recorded state. Redundant persistent
    /// writes are omitted. Event occurrences are combined into one positive count
    /// per tick. Events do not carry state between ticks.
    pub fn changes(&self) -> &[Change] {
        &self.changes
    }
}