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
use std::fmt;

/// Checks decoded sample bytes, independently of their transport encoding.
pub(crate) fn ascii_string<'a>(
    bytes: &'a [u8],
    format: crate::Format,
    backend: &str,
    time: crate::Time,
) -> crate::Result<&'a str> {
    if !bytes.is_ascii() {
        return Err(crate::Error::NonAsciiString {
            format,
            backend: backend.into(),
            time,
        });
    }
    Ok(std::str::from_utf8(bytes).expect("ASCII is valid UTF-8"))
}

/// A borrowed view of a waveform value.
///
/// Views supplied to query callbacks can reference backend buffers and are valid
/// only during that callback. Use [`Self::to_owned`] to retain a value. Views from
/// [`Value::as_ref`], [`Initial::value`](crate::Initial::value), or
/// [`Change::value`](crate::Change::value) instead borrow owned storage and remain
/// valid for that borrow. Some views therefore remain valid outside callbacks.
///
/// Bit-vector signedness comes from the declaration. It does not add a value
/// variant. Persistent histories show final recorded states at source ticks,
/// with at most one net change per selection entry and tick. They do not show
/// intermediate changes within a tick. Events carry observed per-tick counts.
/// They have no persistent state and do not show the order of individual occurrences.
///
/// Queries detect persistent net changes by comparing representations. Each logic
/// state is distinct. Strings compare by exact contents. Reals compare by their
/// binary64 bit patterns. Signed zeros and different NaN patterns therefore differ.
/// This preserves the representation supplied by the reader. It cannot recover
/// source precision or NaN payloads lost during decoding. The caller defines
/// numerical equality.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum ValueRef<'a> {
    /// A borrowed bit-vector value whose signedness comes from its declaration.
    Bits(
        /// The bit-vector view.
        BitsRef<'a>,
    ),
    /// A floating-point value.
    Real(
        /// The floating-point payload.
        f64,
    ),
    /// A borrowed string value.
    ///
    /// Readers return exact ASCII (0 through 127), including NUL when the
    /// source transport supports it. Other bytes return
    /// [`Error::NonAsciiString`](crate::Error::NonAsciiString). This rule does
    /// not apply to hierarchy names, enum labels or diagnostics. Caller-created
    /// variants do not validate their contents.
    String(
        /// The string payload.
        &'a str,
    ),
    /// A total count of event observations at one tick.
    ///
    /// Scan and trace records have positive counts. Counts reflect reader
    /// observations, including [reader limitations](crate#reader-details),
    /// not events omitted by the producer.
    Event {
        /// The number of observed occurrences at this tick.
        occurrences: u64,
    },
}

/// An owned waveform value suitable for long-term storage.
///
/// [`ValueRef::to_owned`] retains a borrowed value independently of its source.
/// [`Self::as_ref`] borrows this owner's storage. See [`ValueRef`] for persistent
/// value, signedness, and event semantics.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Value {
    /// An owned bit-vector value whose signedness comes from its declaration.
    Bits(
        /// The bit-vector payload.
        Bits,
    ),
    /// A floating-point value.
    Real(
        /// The floating-point payload.
        f64,
    ),
    /// An owned string value. See [`ValueRef::String`] for reader limits.
    String(
        /// The string payload.
        Box<str>,
    ),
    /// A total count of event observations at one tick. See [`ValueRef::Event`].
    Event {
        /// The number of observed occurrences at this tick.
        occurrences: u64,
    },
}

impl ValueRef<'_> {
    pub(crate) fn same_value(self, other: ValueRef<'_>) -> bool {
        match (self, other) {
            (Self::Bits(left), ValueRef::Bits(right)) => left == right,
            (Self::Real(left), ValueRef::Real(right)) => left.to_bits() == right.to_bits(),
            (Self::String(left), ValueRef::String(right)) => left == right,
            (Self::Event { occurrences: left }, ValueRef::Event { occurrences: right }) => {
                left == right
            }
            _ => false,
        }
    }

    /// Copies this borrowed value into owned storage.
    pub fn to_owned(self) -> Value {
        match self {
            Self::Bits(bits) => Value::Bits(bits.to_owned()),
            Self::Real(real) => Value::Real(real),
            Self::String(string) => Value::String(string.into()),
            Self::Event { occurrences } => Value::Event { occurrences },
        }
    }
}

impl Value {
    #[cfg(test)]
    pub(crate) fn same_value(&self, other: &Self) -> bool {
        self.as_ref().same_value(other.as_ref())
    }

    /// Borrows this owned value without copying its payload.
    pub fn as_ref(&self) -> ValueRef<'_> {
        match self {
            Self::Bits(bits) => ValueRef::Bits(bits.as_ref()),
            Self::Real(real) => ValueRef::Real(*real),
            Self::String(string) => ValueRef::String(string),
            Self::Event { occurrences } => ValueRef::Event {
                occurrences: *occurrences,
            },
        }
    }
}

/// A resolved state in the supported nine-state logic domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Logic {
    /// Logic zero.
    Zero,
    /// Logic one.
    One,
    /// An unknown forcing value.
    X,
    /// High impedance.
    Z,
    /// A weak logic one.
    H,
    /// An uninitialized value.
    U,
    /// A weak unknown value.
    W,
    /// A weak logic zero.
    L,
    /// A don't-care value.
    DontCare,
}

impl Logic {
    fn from_ascii(byte: u8) -> Option<Self> {
        match byte.to_ascii_lowercase() {
            b'0' => Some(Self::Zero),
            b'1' => Some(Self::One),
            b'x' => Some(Self::X),
            b'z' => Some(Self::Z),
            b'h' => Some(Self::H),
            b'u' => Some(Self::U),
            b'w' => Some(Self::W),
            b'l' => Some(Self::L),
            b'-' => Some(Self::DontCare),
            _ => None,
        }
    }
}

/// A borrowed, opaque view of a bit-vector value.
///
/// Index zero is the least-significant, rightmost bit. [`Display`](fmt::Display)
/// writes a logic string from the most-significant bit to the least-significant
/// bit, using lowercase letters. Storage is opaque and can borrow native backend
/// data without an intermediate string. Views can also borrow [`Bits`] storage.
/// Copy callback views with [`Self::to_owned`] to keep them after the call.
///
/// Equality with another `BitsRef` or [`Bits`] requires the same width and the
/// same [`Logic`] state at each position. Each of the nine states equals only
/// itself: `X` and `DontCare` are not wildcards, `H` differs from `One`, and `L`
/// differs from `Zero`. Equality does not format text or copy the bit payload.
/// It is independent of storage and letter case in the source encoding.
///
/// Leading zeros count toward width: `10` differs from `0010`, and `11` differs
/// from `1111`. Two empty vectors are equal. This compares bit representations,
/// not numbers or HDL expressions. Signedness and logic domain belong to
/// [`Variable`](crate::Variable); equality does not infer them or extend widths.
///
/// ```
/// use ondas::{Sample, Time, Value};
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let data = b"$var wire 4 ! bus $end $enddefinitions $end #0 b0010 !";
/// let mut wave = ondas::open_bytes("bits.vcd", data.as_slice().into())?;
/// let bus = wave.hierarchy().signal("bus")?;
/// let Sample::Value { value: Value::Bits(whole), .. } = wave.sample(bus, Time::ZERO)?
/// else { panic!("expected bits") };
/// let Sample::Value { value: Value::Bits(low), .. } =
///     wave.sample(bus.slice(1, 0)?, Time::ZERO)?
/// else { panic!("expected bits") };
/// assert_eq!(whole, whole.as_ref()); // Owned and borrowed 0010.
/// assert_eq!(whole.as_ref(), whole); // Either operand order.
/// assert_eq!(whole, whole.clone());
/// assert_ne!(whole.as_ref(), low.as_ref()); // 0010 differs from 10.
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct BitsRef<'a> {
    data: &'a [u8],
}

/// An owned, opaque bit-vector value.
///
/// Equality with [`Bits`] or [`BitsRef`] uses the exact width and logic-state
/// rules of [`BitsRef`], without copying the bit payload.
#[derive(Debug, Clone)]
pub struct Bits {
    data: Box<[u8]>,
}

impl PartialEq<BitsRef<'_>> for BitsRef<'_> {
    fn eq(&self, other: &BitsRef<'_>) -> bool {
        self.data.eq_ignore_ascii_case(other.data)
    }
}

impl Eq for BitsRef<'_> {}

impl PartialEq for Bits {
    fn eq(&self, other: &Self) -> bool {
        self.as_ref() == other.as_ref()
    }
}

impl Eq for Bits {}

impl PartialEq<BitsRef<'_>> for Bits {
    fn eq(&self, other: &BitsRef<'_>) -> bool {
        self.as_ref() == *other
    }
}

impl PartialEq<Bits> for BitsRef<'_> {
    fn eq(&self, other: &Bits) -> bool {
        *self == other.as_ref()
    }
}

impl<'a> BitsRef<'a> {
    pub(crate) fn from_ascii(bytes: &'a [u8]) -> Option<Self> {
        u32::try_from(bytes.len()).ok()?;
        bytes
            .iter()
            .all(|&byte| {
                matches!(
                    byte.to_ascii_lowercase(),
                    b'0' | b'1' | b'x' | b'z' | b'h' | b'u' | b'w' | b'l' | b'-'
                )
            })
            .then_some(Self { data: bytes })
    }

    /// Borrows digits constructed from already validated logic bytes.
    pub(crate) fn from_validated_ascii(bytes: &'a [u8]) -> Self {
        debug_assert!(Self::from_ascii(bytes).is_some());
        Self { data: bytes }
    }

    pub(crate) fn ascii(self) -> &'a [u8] {
        self.data
    }

    /// Borrows an inclusive slice whose normalized bounds are already validated.
    pub(crate) fn slice(self, msb: u32, lsb: u32) -> Self {
        let end = self.data.len() - lsb as usize;
        let start = self.data.len() - msb as usize - 1;
        Self {
            data: &self.data[start..end],
        }
    }

    /// Returns the number of bits in the vector.
    pub fn width(self) -> u32 {
        self.data.len() as u32
    }

    /// Returns the bit at `index`, where zero is the least-significant bit.
    ///
    /// Returns `None` when `index` is outside the vector.
    pub fn bit(self, index: u32) -> Option<Logic> {
        let offset = self
            .data
            .len()
            .checked_sub(index as usize)?
            .checked_sub(1)?;
        Logic::from_ascii(self.data[offset])
    }

    /// Iterates over every bit from most to least significant.
    pub fn iter_msb(self) -> impl ExactSizeIterator<Item = Logic> + 'a {
        self.data
            .iter()
            .map(|&byte| Logic::from_ascii(byte).expect("validated logic byte"))
    }

    /// Iterates over every bit from least to most significant.
    pub fn iter_lsb(self) -> impl ExactSizeIterator<Item = Logic> + 'a {
        self.data
            .iter()
            .rev()
            .map(|&byte| Logic::from_ascii(byte).expect("validated logic byte"))
    }

    /// Copies this borrowed vector into owned storage.
    pub fn to_owned(self) -> Bits {
        Bits {
            data: self.data.iter().map(u8::to_ascii_lowercase).collect(),
        }
    }
}

impl fmt::Display for BitsRef<'_> {
    /// Formats the vector as a most-significant-bit-first logic string.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.data.iter().any(u8::is_ascii_uppercase) {
            return formatter
                .write_str(std::str::from_utf8(self.data).expect("validated logic bytes"));
        }
        let mut buffer = [0; 256];
        for chunk in self.data.chunks(buffer.len()) {
            let lowered = &mut buffer[..chunk.len()];
            lowered.copy_from_slice(chunk);
            lowered.make_ascii_lowercase();
            formatter.write_str(std::str::from_utf8(lowered).expect("validated logic bytes"))?;
        }
        Ok(())
    }
}

impl Bits {
    /// Takes ownership of digits constructed from validated logic bytes.
    pub(crate) fn from_validated_ascii(mut bytes: Vec<u8>) -> Self {
        debug_assert!(BitsRef::from_ascii(&bytes).is_some());
        bytes.make_ascii_lowercase();
        Self {
            data: bytes.into_boxed_slice(),
        }
    }

    #[cfg(test)]
    pub(crate) fn from_ascii(bytes: &[u8]) -> Option<Self> {
        BitsRef::from_ascii(bytes).map(BitsRef::to_owned)
    }

    /// Returns the number of bits in the vector.
    pub fn width(&self) -> u32 {
        self.as_ref().width()
    }

    /// Borrows this vector without copying its storage.
    pub fn as_ref(&self) -> BitsRef<'_> {
        BitsRef { data: &self.data }
    }
}

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

    #[test]
    fn sample_strings_preserve_all_ascii_and_reject_other_octets() {
        let bytes: Vec<_> = (0..=127).collect();
        assert_eq!(
            ascii_string(&bytes, crate::Format::Shm, "shm-lib", crate::Time::ZERO)
                .unwrap()
                .as_bytes(),
            bytes
        );
        for bytes in [
            vec![128],
            vec![255],
            "é".as_bytes().to_vec(),
            vec![b'a', 0, 128],
        ] {
            assert!(
                matches!(ascii_string(&bytes, crate::Format::Shm, "shm-lib", crate::Time::from_ticks(9)),
                Err(crate::Error::NonAsciiString { format: crate::Format::Shm, backend, time })
                if backend == "shm-lib" && time.ticks() == 9)
            );
        }
    }

    #[test]
    fn ascii_states_and_iteration() {
        let bits = BitsRef::from_ascii(b"01XZHUWL-").unwrap();
        let expected = [
            Logic::Zero,
            Logic::One,
            Logic::X,
            Logic::Z,
            Logic::H,
            Logic::U,
            Logic::W,
            Logic::L,
            Logic::DontCare,
        ];
        assert_eq!(bits.width(), 9);
        assert_eq!(bits.to_string(), "01xzhuwl-");
        assert_eq!(bits.iter_msb().collect::<Vec<_>>(), expected);
        assert_eq!(
            bits.iter_lsb().collect::<Vec<_>>(),
            expected.into_iter().rev().collect::<Vec<_>>()
        );
        let mut iter = bits.iter_msb();
        assert_eq!(iter.len(), 9);
        assert_eq!(iter.next(), Some(Logic::Zero));
        assert_eq!(iter.len(), 8);
        let mut iter = bits.iter_lsb();
        assert_eq!(iter.len(), 9);
        assert_eq!(iter.next(), Some(Logic::DontCare));
        assert_eq!(iter.len(), 8);
        for index in 0..9 {
            assert_eq!(bits.bit(index), Some(expected[8 - index as usize]));
        }
        assert_eq!(bits.bit(9), None);
        assert_eq!(bits.bit(u32::MAX), None);
        assert!(BitsRef::from_ascii(b"10?").is_none());
        assert!(Bits::from_ascii(b"\xff").is_none());
        for byte in u8::MIN..=u8::MAX {
            assert_eq!(
                BitsRef::from_ascii(&[byte]).is_some(),
                Logic::from_ascii(byte).is_some(),
                "byte {byte}"
            );
        }
        let empty = BitsRef::from_ascii(b"").unwrap();
        assert_eq!(empty.width(), 0);
        assert_eq!(empty.bit(0), None);
        assert_eq!(empty.iter_msb().len(), 0);
        assert_eq!(empty.iter_lsb().len(), 0);
        assert_eq!(empty.to_string(), "");
    }

    #[test]
    fn slices_and_owned_storage() {
        let mut source = b"01XZHUWL-".to_vec();
        let owned = {
            let bits = BitsRef::from_ascii(&source).unwrap();
            assert_eq!(bits.slice(8, 0).to_string(), "01xzhuwl-");
            assert_eq!(bits.slice(0, 0).to_string(), "-");
            assert_eq!(bits.slice(8, 8).to_string(), "0");
            assert_eq!(bits.slice(6, 2).to_string(), "xzhuw");
            let nested = bits.slice(6, 2).slice(3, 1);
            assert_eq!(nested.width(), 3);
            assert_eq!(nested.to_string(), "zhu");
            assert_eq!(nested.bit(0), Some(Logic::U));
            nested.to_owned()
        };
        source.fill(b'0');
        assert_eq!(owned.width(), 3);
        assert_eq!(owned.as_ref().to_string(), "zhu");
        assert_eq!(
            Bits::from_ascii(b"XzU").unwrap().as_ref().to_string(),
            "xzu"
        );
    }

    #[test]
    fn owned_validated_bits_keep_all_nine_states() {
        let bits = Bits::from_validated_ascii(b"01XZHUWL-".to_vec());
        assert_eq!(bits.width(), 9);
        assert_eq!(bits.as_ref().to_string(), "01xzhuwl-");
        assert_eq!(
            bits.as_ref().iter_msb().collect::<Vec<_>>(),
            [
                Logic::Zero,
                Logic::One,
                Logic::X,
                Logic::Z,
                Logic::H,
                Logic::U,
                Logic::W,
                Logic::L,
                Logic::DontCare
            ]
        );
        assert_eq!(bits, BitsRef::from_ascii(b"01xzhuwl-").unwrap());
    }

    #[test]
    fn values_round_trip_and_compare() {
        let bits = ValueRef::Bits(BitsRef::from_ascii(b"01X").unwrap()).to_owned();
        assert!(bits.same_value(&Value::Bits(Bits::from_ascii(b"01x").unwrap())));
        assert!(ValueRef::Bits(BitsRef::from_ascii(b"01X").unwrap()).same_value(bits.as_ref()));
        assert!(!bits.same_value(&Value::Bits(Bits::from_ascii(b"01z").unwrap())));
        assert!(!bits.same_value(&Value::Bits(Bits::from_ascii(b"1x").unwrap())));
        match bits.as_ref() {
            ValueRef::Bits(view) => assert_eq!(view.to_string(), "01x"),
            _ => panic!("expected bits"),
        }
        let text = {
            let source = String::from("retained string");
            ValueRef::String(&source).to_owned()
        };
        assert!(matches!(text.as_ref(), ValueRef::String("retained string")));
        assert!(text.same_value(&text.as_ref().to_owned()));
        assert!(!text.same_value(&Value::String("different".into())));
        let real = ValueRef::Real(3.5).to_owned();
        assert!(matches!(real.as_ref(), ValueRef::Real(3.5)));
        assert!(real.same_value(&real.as_ref().to_owned()));
        let event = ValueRef::Event { occurrences: 7 }.to_owned();
        assert!(matches!(event.as_ref(), ValueRef::Event { occurrences: 7 }));
        assert!(event.same_value(&event.as_ref().to_owned()));
        assert!(!event.same_value(&Value::Event { occurrences: 1 }));
        assert!(!real.same_value(&text));
        assert!(!event.same_value(&real));
    }

    #[test]
    fn real_identity_and_conversion_preserve_bits() {
        let patterns = [
            0x7ff8_0000_0000_0001, // Quiet NaN, first payload.
            0x7ff8_0000_0000_0002, // Different payload.
            0xfff8_0000_0000_0001, // Different sign.
            0x7ff0_0000_0000_0001, // Signaling NaN.
            0.0f64.to_bits(),
            (-0.0f64).to_bits(),
            f64::INFINITY.to_bits(),
            f64::NEG_INFINITY.to_bits(),
            3.5f64.to_bits(),
        ];
        for left in patterns {
            let value = ValueRef::Real(f64::from_bits(left));
            let owned = value.to_owned();
            let ValueRef::Real(real) = owned.as_ref() else {
                panic!("expected real")
            };
            assert_eq!(real.to_bits(), left);
            for right in patterns {
                let other = Value::Real(f64::from_bits(right));
                assert_eq!(value.same_value(other.as_ref()), left == right);
                assert_eq!(owned.same_value(&other), left == right);
            }
        }
    }

    #[test]
    fn bit_identity_handles_case_width_and_non_word_aligned_slices() {
        for width in [0, 1, 7, 9, 63, 65, 4095] {
            let upper = b"01XZHUWL-"
                .iter()
                .copied()
                .cycle()
                .take(width)
                .collect::<Vec<_>>();
            let lower = upper.to_ascii_lowercase();
            let left = BitsRef::from_ascii(&upper).unwrap();
            let right = BitsRef::from_ascii(&lower).unwrap();
            check_bit_equality(left, right, true);
            assert!(ValueRef::Bits(left).same_value(ValueRef::Bits(right)));
            if width > 1 {
                check_bit_equality(
                    left.slice(width as u32 - 2, 0),
                    right.slice(width as u32 - 2, 0),
                    true,
                );
                check_bit_equality(left, right.slice(width as u32 - 2, 0), false);
                assert!(
                    ValueRef::Bits(left.slice(width as u32 - 2, 0))
                        .same_value(ValueRef::Bits(right.slice(width as u32 - 2, 0)))
                );
                assert!(
                    !ValueRef::Bits(left)
                        .same_value(ValueRef::Bits(right.slice(width as u32 - 2, 0)))
                );
            }
        }
    }

    #[test]
    fn identity_distinguishes_every_logic_state() {
        for left in b"01xzhuwl-" {
            for right in b"01xzhuwl-" {
                let left_value = BitsRef::from_ascii(std::slice::from_ref(left)).unwrap();
                let right_value = BitsRef::from_ascii(std::slice::from_ref(right)).unwrap();
                check_bit_equality(left_value, right_value, left == right);
                assert_eq!(
                    ValueRef::Bits(left_value).same_value(ValueRef::Bits(right_value)),
                    left == right
                );
            }
        }
    }

    fn check_bit_equality(left: BitsRef<'_>, right: BitsRef<'_>, expected: bool) {
        fn requires_eq<T: Eq>(_: &T) {}
        let left_owned = left.to_owned();
        let right_owned = right.to_owned();
        requires_eq(&left);
        requires_eq(&left_owned);
        assert_eq!(left == right, expected);
        assert_eq!(right == left, expected);
        assert_eq!(left_owned == right_owned, expected);
        assert_eq!(right_owned == left_owned, expected);
        assert_eq!(left_owned == right, expected);
        assert_eq!(right == left_owned, expected);
        assert_eq!(left == right_owned, expected);
        assert_eq!(right_owned == left, expected);
        assert_eq!(PartialEq::eq(&left, &right), expected);
        assert_eq!(PartialEq::eq(&left_owned, &right_owned), expected);
    }

    #[test]
    fn wide_bit_display_preserves_logic_states_and_slices() {
        let source = b"01XZHUWL-".repeat(129);
        let expected = "01xzhuwl-".repeat(129);
        let bits = BitsRef::from_ascii(&source).unwrap();
        assert_eq!(bits.to_string(), expected);
        assert_eq!(bits.to_owned().as_ref().to_string(), expected);
        let sliced = bits.slice(1024, 3);
        assert_eq!(
            sliced.to_string(),
            expected[expected.len() - 1025..expected.len() - 3]
        );
    }

    #[test]
    fn bit_equality_distinguishes_width_and_leading_zeros() {
        for (left, right, expected) in [
            ("", "", true),
            ("", "0", false),
            ("0", "00", false),
            ("10", "0010", false),
            ("11", "1111", false),
            ("0010", "0010", true),
            ("0010", "0100", false),
            ("01XZHUWL-", "01xzhuwl-", true),
        ] {
            check_bit_equality(
                BitsRef::from_ascii(left.as_bytes()).unwrap(),
                BitsRef::from_ascii(right.as_bytes()).unwrap(),
                expected,
            );
        }
        let source = BitsRef::from_ascii(b"101XZHUWL-0").unwrap();
        let slice = source.slice(9, 1);
        let expected = Bits::from_ascii(b"01xzhuwl-").unwrap();
        assert_eq!(slice, expected);
        let retained = slice.to_owned();
        assert_eq!(retained, expected);
    }
}