ondas 1.0.2

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
use std::{
    fs::File,
    io::{BufReader, Cursor},
    ops::ControlFlow,
    path::Path,
    sync::Arc,
};

use crate::{
    Error, Hierarchy, Result, Sample, ScanRef, Selection, Signal, Time, TimeRange, TimeSpan,
    Timescale, Trace,
    backends::{Input, Reader, fst, vcd},
};

/// Opens a waveform file with an automatically selected available backend.
///
/// FST uses `fst-lib`. VCD uses `vcd-native`. FSDB uses `fsdb-lib` when the
/// optional feature of the same name is enabled. Content recognition takes
/// priority over the filename. A recognized extension is a fallback hint.
/// A recognized format without a reader returns [`Error::NoBackend`].
/// Unrecognized input returns
/// [`Error::UnknownFormat`]. Each opened waveform uses one backend.
///
/// File and decoder errors are returned where the decoder reports them. See
/// the crate-level reader limitations for malformed inputs that can panic.
pub fn open(path: impl AsRef<Path>) -> Result<Waveform> {
    open_file(path.as_ref(), None)
}

/// Reads owned source metadata without retaining a waveform or hierarchy.
///
/// FSDB reads the SDK's file metadata without materializing declarations. FST and
/// VCD currently use their regular readers, so this is not a fast path for those
/// formats. Format detection matches [`open`], as do metadata values for files
/// that open successfully. Unlike [`open`], it does not validate an FSDB
/// declaration tree. Use [`open`] for validated hierarchy or signal access.
///
/// This function accepts file paths, not byte inputs.
pub fn read_metadata(path: impl AsRef<Path>) -> Result<Metadata> {
    let path = path.as_ref();
    let name = path.to_string_lossy().into_owned();
    let file = File::open(path)?;
    let vcd_file = file.try_clone().ok();
    let mut input: Box<dyn Input> = Box::new(BufReader::new(file));
    let format = detect_format(&mut *input, &name, Some(path))?;
    match format {
        Format::Fst => fst::Reader::open(input, name).map(|(_, _, metadata)| metadata),
        Format::Vcd => vcd::Reader::open(input, name, vcd_file).map(|(_, _, metadata)| metadata),
        #[cfg(feature = "fsdb-lib")]
        Format::Fsdb => crate::backends::fsdb::read_metadata(path, name),
        _ => Err(Error::NoBackend { format }),
    }
}

/// Opens a waveform file with only the named backend, without fallback.
///
/// Available names are `fst-lib`, `vcd-native`, and feature-enabled `fsdb-lib`.
/// A disabled optional backend is an unknown name. Unknown names return
/// [`Error::UnknownBackend`]. A format unsupported by the selected backend returns
/// [`Error::BackendDoesNotSupport`]. See [`open`] for detection and reader limits.
pub fn open_with(path: impl AsRef<Path>, backend: &str) -> Result<Waveform> {
    open_file(path.as_ref(), Some(backend))
}

/// Opens shared in-memory bytes with an automatically selected backend.
///
/// `name` is the logical [`Metadata::source_name`] and a format-detection hint.
/// The input stays alive through the shared ownership of `bytes`. Detection,
/// errors, and reader limitations are the same as [`open`]. Both FST and VCD readers
/// support file and byte input. `fsdb-lib` reads files only. FSDB selected by the
/// filename hint returns [`Error::UnsupportedInput`] when that feature is enabled.
/// The SDK's content probe is only available for file paths.
pub fn open_bytes(name: impl Into<String>, bytes: Arc<[u8]>) -> Result<Waveform> {
    open_input(name.into(), Box::new(Cursor::new(bytes)), None, None, None)
}

/// Opens shared in-memory bytes with only the named backend, without fallback.
///
/// Combines [`open_bytes`]' input ownership with [`open_with`]'s explicit reader
/// selection and error categories. Selecting enabled `fsdb-lib` always returns
/// [`Error::UnsupportedInput`] without creating a temporary file.
pub fn open_bytes_with(
    name: impl Into<String>,
    bytes: Arc<[u8]>,
    backend: &str,
) -> Result<Waveform> {
    open_input(
        name.into(),
        Box::new(Cursor::new(bytes)),
        Some(backend),
        None,
        None,
    )
}

fn check_backend(backend: Option<&str>) -> Result<()> {
    if let Some(backend) = backend
        && !matches!(backend, "fst-lib" | "vcd-native")
        && !(cfg!(feature = "fsdb-lib") && backend == "fsdb-lib")
    {
        return Err(Error::UnknownBackend {
            backend: backend.into(),
        });
    }
    Ok(())
}

fn open_file(path: &Path, backend: Option<&str>) -> Result<Waveform> {
    check_backend(backend)?;
    let file = File::open(path)?;
    let vcd_file = file.try_clone().ok();
    open_input(
        path.to_string_lossy().into_owned(),
        Box::new(BufReader::new(file)),
        backend,
        Some(path),
        vcd_file,
    )
}

fn open_input(
    name: String,
    mut input: Box<dyn Input>,
    backend: Option<&str>,
    _path: Option<&Path>,
    vcd_file: Option<File>,
) -> Result<Waveform> {
    check_backend(backend)?;
    #[cfg(feature = "fsdb-lib")]
    if backend == Some("fsdb-lib") && _path.is_none() {
        return Err(Error::UnsupportedInput {
            backend: "fsdb-lib".into(),
            input: crate::InputKind::Bytes,
        });
    }
    let format = detect_format(&mut *input, &name, _path)?;
    let (reader, hierarchy, metadata) = match (format, backend) {
        (Format::Fst, None | Some("fst-lib")) => {
            let (reader, hierarchy, metadata) = fst::Reader::open(input, name)?;
            (Reader::Fst(Box::new(reader)), hierarchy, metadata)
        }
        (Format::Vcd, None | Some("vcd-native")) => {
            let (reader, hierarchy, metadata) = vcd::Reader::open(input, name, vcd_file)?;
            (Reader::Vcd(Box::new(reader)), hierarchy, metadata)
        }
        #[cfg(feature = "fsdb-lib")]
        (Format::Fsdb, None | Some("fsdb-lib")) => {
            let path = _path.ok_or_else(|| Error::UnsupportedInput {
                backend: "fsdb-lib".into(),
                input: crate::InputKind::Bytes,
            })?;
            let (reader, hierarchy, metadata) = crate::backends::fsdb::Reader::open(path, name)?;
            (Reader::Fsdb(Box::new(reader)), hierarchy, metadata)
        }
        (_, Some(backend)) => {
            return Err(Error::BackendDoesNotSupport {
                backend: backend.into(),
                format,
            });
        }
        (_, None) => return Err(Error::NoBackend { format }),
    };
    Ok(Waveform {
        reader,
        hierarchy,
        metadata,
    })
}

fn detect_format(input: &mut dyn Input, name: &str, _path: Option<&Path>) -> Result<Format> {
    let prefix = input.fill_buf()?;
    // The uncompressed FST header section is 329 bytes (fst-reader 0.17).
    // Its first zero byte alone also matches FSDB and is not a signature.
    let mut detected =
        if prefix.starts_with(&[0, 0, 0, 0, 0, 0, 0, 1, 73]) || prefix.first() == Some(&254) {
            Some(Format::Fst)
        } else if prefix.starts_with(b"GHDLwave") {
            Some(Format::Ghw)
        } else {
            None
        };
    if detected.is_none() {
        if prefix.starts_with(b"\xef\xbb\xbf") {
            input.consume(3);
        }
        loop {
            let prefix = input.fill_buf()?;
            if prefix.is_empty() {
                break;
            }
            if let Some(&byte) = prefix.iter().find(|b| !b.is_ascii_whitespace()) {
                if byte == b'$' {
                    detected = Some(Format::Vcd);
                }
                break;
            }
            let length = prefix.len();
            input.consume(length);
        }
    }
    input.rewind()?;
    #[cfg(feature = "fsdb-lib")]
    if detected.is_none()
        && let Some(path) = _path
        && crate::backends::fsdb::probe(path)?
    {
        detected = Some(Format::Fsdb);
    }
    let extension = Path::new(name)
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    if let Some(format) = detected {
        Ok(format)
    } else {
        match extension.as_str() {
            "fst" => Ok(Format::Fst),
            "vcd" => Ok(Format::Vcd),
            "ghw" => Ok(Format::Ghw),
            "fsdb" => Ok(Format::Fsdb),
            "wlf" => Ok(Format::Wlf),
            _ => Err(Error::UnknownFormat),
        }
    }
}

/// A source format, distinct from the reader implementation.
///
/// A variant does not imply that its reader is compiled in or available.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Format {
    /// Value Change Dump.
    Vcd,
    /// Fast Signal Trace.
    Fst,
    /// GHDL Waveform.
    Ghw,
    /// Fast Signal Database.
    Fsdb,
    /// Wave Log Format.
    Wlf,
}

/// An opened, read-only waveform and its query interface.
///
/// Holds one private reader and exposes format-independent types. Queries need
/// mutable access for reader state. A [`Selection`] reuses a validated ordered
/// signal list. One-shot methods have the same semantics as temporary selections.
/// Input order and duplicates remain visible. Base-signal deduplication is private.
///
/// Handles from another source return [`Error::InvalidSignal`]. Querying an
/// unsupported value class returns [`Error::UnsupportedSignal`]. Ordinary decoder
/// errors are returned. Ondas does not intercept upstream panics. See crate docs.
///
/// # Example: resolve a declaration, sample a slice and read a trace
///
/// This example requires a file containing the named signal. Clone the hierarchy
/// before keeping a [`crate::Variable`] or [`crate::Scope`] view across mutable
/// waveform queries. These views borrow their hierarchy. [`Signal`] is copyable.
/// The clone lets the declaration view coexist with `&mut Waveform`.
///
/// [`crate::HierarchyPath`] handles exact names and escaping. After resolving the
/// signal, `slice(31, 28)` selects normalized value positions, not HDL indices.
/// The sample reports the value at one tick. The trace separates state before
/// the requested range from changes inside it.
///
/// ```no_run
/// use ondas::{HierarchyPath, Time, TimeRange};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut wave = ondas::open("dump.fst")?;
/// let hierarchy = wave.hierarchy().clone();
/// let path = HierarchyPath::parse(r"tb.\gen.blk[0] .data")?;
/// let declaration = hierarchy.variable_path(&path)?;
/// let data = hierarchy.signal_path(&path)?;
/// let opcode = data.slice(31, 28)?;
///
/// let sample = wave.sample(opcode, Time::from_ticks(1_000))?;
/// println!("{}: {sample:?}", declaration.name());
/// let trace = wave.trace(
///     opcode,
///     TimeRange::closed(Time::from_ticks(10_000), Time::from_ticks(20_000)),
/// )?;
/// if let Some(initial) = trace.initial() {
///     println!("entering: {:?}", initial.value());
/// }
/// for change in trace.changes() {
///     println!("{}: {:?}", change.time().ticks(), change.value());
/// }
/// # Ok(())
/// # }
/// ```
pub struct Waveform {
    pub(crate) reader: Reader,
    hierarchy: Hierarchy,
    metadata: Metadata,
}

impl Waveform {
    /// Returns the detected source format.
    pub fn format(&self) -> Format {
        match self.reader {
            Reader::Vcd(_) => Format::Vcd,
            Reader::Fst(_) => Format::Fst,
            #[cfg(feature = "fsdb-lib")]
            Reader::Fsdb(_) => Format::Fsdb,
            #[cfg(test)]
            Reader::Memory { .. } | Reader::Generated(_) => Format::Fst,
        }
    }

    /// Returns the selected implementation's stable lower-kebab-case name.
    ///
    /// `fst-lib` identifies the `fst-reader` adapter, independently of the
    /// source format. Use this name for diagnostics or explicit opening.
    pub fn backend(&self) -> &str {
        match self.reader {
            Reader::Fst(_) => "fst-lib",
            Reader::Vcd(_) => "vcd-native",
            #[cfg(feature = "fsdb-lib")]
            Reader::Fsdb(_) => "fsdb-lib",
            #[cfg(test)]
            Reader::Memory { .. } => "memory",
            #[cfg(test)]
            Reader::Generated(_) => "generated",
        }
    }

    /// Returns source metadata.
    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    /// Returns the immutable hierarchy.
    ///
    /// Clone it before retaining borrowed scopes or variables across mutable
    /// waveform queries. Handles from that clone still refer to this source.
    pub fn hierarchy(&self) -> &Hierarchy {
        &self.hierarchy
    }

    /// Prepares an ordered signal list for repeated queries.
    ///
    /// Preserves duplicates and separate slices of a base signal. Invalid or
    /// unsupported handles fail before reading values. The returned selection
    /// holds a mutable waveform borrow, not a cache of every selected history.
    pub fn select(&mut self, signals: &[Signal]) -> Result<Selection<'_>> {
        Selection::new(self, signals)
    }

    /// Samples one signal at an absolute tick.
    ///
    /// See [`Sample`] for final-tick state, missing values, events, slices, and
    /// sampling after EOF. Equivalent to a one-entry selection, without a partial
    /// result on error.
    pub fn sample(&mut self, signal: Signal, time: Time) -> Result<Sample> {
        Ok(self
            .samples(&[signal], time)?
            .pop()
            .expect("one sample for one signal"))
    }

    /// Samples signals in input order, retaining duplicates.
    ///
    /// Equivalent to [`Selection::samples`]. Returns no partial vector on error.
    pub fn samples(&mut self, signals: &[Signal], time: Time) -> Result<Vec<Sample>> {
        self.select(signals)?.samples(time)
    }

    /// Traces one signal over inclusive bounds.
    ///
    /// See [`Selection::scan`] for entering states, projections, same-tick order,
    /// and event multiplicity. Returns no partial trace on error.
    pub fn trace(&mut self, signal: Signal, range: TimeRange) -> Result<Trace> {
        Ok(self
            .traces(&[signal], range)?
            .pop()
            .expect("one trace for one signal"))
    }

    /// Traces signals in input order, retaining duplicates.
    ///
    /// Equivalent to [`Selection::traces`]. Returns no partial vector on error.
    pub fn traces(&mut self, signals: &[Signal], range: TimeRange) -> Result<Vec<Trace>> {
        self.select(signals)?.traces(range)
    }

    /// Visits entering states and changes over inclusive bounds.
    ///
    /// Equivalent to [`Selection::scan`], including duplicate entries, slice
    /// filtering, and same-signal ordering. Values are valid only during the callback.
    /// A break stops successfully. A late reader error may follow earlier observations.
    pub fn scan<B>(
        &mut self,
        signals: &[Signal],
        range: TimeRange,
        visitor: impl for<'v> FnMut(ScanRef<'v>) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        self.select(signals)?.scan(range, visitor)
    }

    /// Visits unique, increasing candidate change times over inclusive bounds.
    ///
    /// Equivalent to [`Selection::scan_candidate_times`]. Initial-state times
    /// are excluded. Extra candidates are allowed. A break stops successfully.
    pub fn scan_candidate_times<B>(
        &mut self,
        signals: &[Signal],
        range: TimeRange,
        visitor: impl FnMut(Time) -> ControlFlow<B>,
    ) -> Result<ControlFlow<B>> {
        self.select(signals)?.scan_candidate_times(range, visitor)
    }

    #[cfg(test)]
    pub(crate) fn memory(
        encodings: Vec<crate::Encoding>,
        mut records: Vec<(usize, u64, crate::Value)>,
        fail_after: Option<usize>,
    ) -> Self {
        records.sort_by_key(|(_, time, _)| *time);
        let span = records.first().zip(records.last()).map(|(first, last)| {
            TimeSpan::new(Time::from_ticks(first.1), Time::from_ticks(last.1))
        });
        Self {
            hierarchy: Hierarchy::new(vec![], vec![], encodings),
            metadata: Metadata {
                source_name: "memory".into(),
                timescale: None,
                time_span: span,
                writer: None,
                date: None,
                comments: vec![],
            },
            reader: Reader::Memory {
                records: records
                    .into_iter()
                    .map(|(id, t, v)| (id, Time::from_ticks(t), v))
                    .collect(),
                fail_after,
            },
        }
    }
}

/// Format-independent source metadata.
pub struct Metadata {
    pub(crate) source_name: String,
    pub(crate) timescale: Option<Timescale>,
    pub(crate) time_span: Option<TimeSpan>,
    pub(crate) writer: Option<String>,
    pub(crate) date: Option<String>,
    pub(crate) comments: Vec<String>,
}

impl Metadata {
    /// Returns the source path or caller-provided logical name.
    pub fn source_name(&self) -> &str {
        &self.source_name
    }

    /// Returns the exact tick duration when reliably available.
    pub fn timescale(&self) -> Option<Timescale> {
        self.timescale
    }

    /// Returns the first and last recorded ticks when reliably available.
    ///
    /// `None` means an empty source or unavailable metadata. These bounds do not
    /// restrict queries. Samples after EOF hold the last persistent value.
    /// Event counts are zero.
    pub fn time_span(&self) -> Option<TimeSpan> {
        self.time_span
    }

    /// Returns the source-declared writer, if present.
    pub fn writer(&self) -> Option<&str> {
        self.writer.as_deref()
    }

    /// Returns the source-declared date, if present.
    pub fn date(&self) -> Option<&str> {
        self.date.as_deref()
    }

    /// Iterates over source comments in stored order.
    pub fn comments(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
        self.comments.iter().map(String::as_str)
    }
}

#[cfg(test)]
mod semantics_tests;

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

    fn bytes(text: &[u8]) -> Arc<[u8]> {
        Arc::from(text)
    }

    #[test]
    fn detection_prefers_content_and_falls_back_to_case_insensitive_extensions() {
        for (name, content, format) in [
            ("dump.FST", &b" \n$version test $end"[..], Format::Vcd),
            ("dump.vcd", &b"GHDLwave"[..], Format::Ghw),
            ("dump.VCD", &b""[..], Format::Vcd),
            ("dump.GHW", &b""[..], Format::Ghw),
            ("dump.FSDB", &b""[..], Format::Fsdb),
            ("dump.WLF", &b""[..], Format::Wlf),
        ] {
            let result = open_bytes(name, bytes(content));
            if format == Format::Vcd {
                assert!(
                    matches!(
                        result,
                        Err(Error::Malformed {
                            format: Format::Vcd,
                            ..
                        })
                    ),
                    "{name}"
                );
            } else if cfg!(feature = "fsdb-lib") && format == Format::Fsdb {
                assert!(matches!(
                    result,
                    Err(Error::UnsupportedInput {
                        input: crate::InputKind::Bytes,
                        ..
                    })
                ));
            } else {
                assert!(
                    matches!(result, Err(Error::NoBackend { format: actual }) if actual == format),
                    "{name}"
                );
            }
            assert!(
                matches!(open_bytes_with(name, bytes(content), "fst-lib"), Err(Error::BackendDoesNotSupport { backend, format: actual }) if backend == "fst-lib" && actual == format),
                "{name}"
            );
        }
        // Invalid explicit selection is rejected before attempting filesystem I/O.
        assert!(
            matches!(open_with("", "unknown-reader"), Err(Error::UnknownBackend { backend }) if backend == "unknown-reader")
        );
        assert!(matches!(open_with("", "fst-lib"), Err(Error::Io(_))));
    }

    #[test]
    fn metadata_preserves_optional_fields_and_comment_order() {
        let mut wave = Waveform::memory(vec![], vec![], None);
        let metadata = wave.metadata();
        assert_eq!(metadata.source_name(), "memory");
        assert_eq!(metadata.timescale(), None);
        assert_eq!(metadata.time_span(), None);
        assert_eq!(metadata.writer(), None);
        assert_eq!(metadata.date(), None);
        assert_eq!(metadata.comments().len(), 0);
        wave.metadata = Metadata {
            source_name: "logical name".into(),
            timescale: Some(Timescale::new(10, crate::TimeUnit::Picosecond)),
            time_span: Some(TimeSpan::new(Time::from_ticks(7), Time::from_ticks(13))),
            writer: Some("writer".into()),
            date: Some("source date".into()),
            comments: vec!["second".into(), "".into(), "first".into(), "second".into()],
        };
        let metadata = wave.metadata();
        assert_eq!(metadata.source_name(), "logical name");
        assert_eq!(metadata.writer(), Some("writer"));
        assert_eq!(metadata.date(), Some("source date"));
        assert_eq!(metadata.timescale().unwrap().factor(), 10);
        assert_eq!(
            metadata.timescale().unwrap().unit(),
            crate::TimeUnit::Picosecond
        );
        assert_eq!(metadata.time_span().unwrap().first(), Time::from_ticks(7));
        assert_eq!(metadata.time_span().unwrap().last(), Time::from_ticks(13));
        let mut comments = metadata.comments();
        assert_eq!(comments.len(), 4);
        assert_eq!(comments.next(), Some("second"));
        assert_eq!(comments.len(), 3);
        assert_eq!(comments.collect::<Vec<_>>(), ["", "first", "second"]);
    }

    #[test]
    fn opening_errors_distinguish_detection_selection_and_io() {
        fn send_sync<T: Send + Sync>() {}
        send_sync::<Waveform>();
        send_sync::<Hierarchy>();
        assert!(matches!(open(""), Err(Error::Io(_))));
        assert!(matches!(
            open_bytes("unknown", bytes(b"not a waveform")),
            Err(Error::UnknownFormat)
        ));
        assert!(matches!(
            open_bytes("dump.vcd", bytes(b"$timescale 1 ns $end")),
            Err(Error::Malformed {
                format: Format::Vcd,
                ..
            })
        ));
        assert!(matches!(
            open_bytes_with("dump.vcd", bytes(b"$scope module tb $end"), "fst-lib"),
            Err(Error::BackendDoesNotSupport {
                format: Format::Vcd,
                ..
            })
        ));
        for backend in ["not-a-reader", "fst-native"] {
            assert!(matches!(
                open_bytes_with("dump.fst", bytes(b""), backend),
                Err(Error::UnknownBackend { backend: actual }) if actual == backend
            ));
            assert!(matches!(
                open_with("", backend),
                Err(Error::UnknownBackend { backend: actual }) if actual == backend
            ));
        }
        assert!(matches!(
            open_bytes("empty.fst", bytes(b"")),
            Err(Error::Malformed {
                format: Format::Fst,
                ..
            })
        ));
    }
}