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

/// 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.
    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.
    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.data.eq_ignore_ascii_case(right.data),
            (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.
#[derive(Debug, Clone, Copy)]
pub struct BitsRef<'a> {
    data: &'a [u8],
}

/// An owned, opaque bit-vector value.
#[derive(Debug, Clone)]
pub struct Bits {
    data: Box<[u8]>,
}

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 }
    }

    #[cfg(unix)]
    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 {
        for byte in self.data {
            write!(formatter, "{}", byte.to_ascii_lowercase() as char)?;
        }
        Ok(())
    }
}

impl Bits {
    #[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 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 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();
            assert!(ValueRef::Bits(left).same_value(ValueRef::Bits(right)));
            if width > 1 {
                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();
                assert_eq!(
                    ValueRef::Bits(left_value).same_value(ValueRef::Bits(right_value)),
                    left == right
                );
            }
        }
    }
}