vpi 0.1.0

Safe and ergonomic Rust bindings to the Verilog and SystemVerilog VPI C API for writing VPI applications in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
use std::fmt::Display;

use num_derive::{FromPrimitive, ToPrimitive};
use num_traits::FromPrimitive;
use vpi_sys::{PLI_INT32, PLI_UINT32};

use crate::{Handle, Property, Time};

/// High-level value representation returned from or written to VPI objects.
#[derive(Debug)]
pub enum Value {
    /// Binary string value.
    BinStr(String),
    /// Octal string value.
    OctStr(String),
    /// Hexadecimal string value.
    HexStr(String),
    /// Decimal string value.
    DecStr(String),
    /// 4-state scalar value.
    Scalar(ScalarValue),
    /// 32-bit signed integer value.
    Int(i32),
    /// 64-bit floating-point value.
    Real(f64),
    /// Plain string value.
    String(String),
    /// Vector of scalar bits.
    Vector(Vec<ScalarValue>),
    /// Value with drive-strength information.
    Strength(StrengthValue),
    /// Time value.
    Time(Time),
    /// Raw object type value.
    ObjType(i32), // Placeholder, as object types are more complex
    /// Suppress value transfer.
    Suppress,
    /// 16-bit signed integer value.
    ShortInt(i16),
    /// 64-bit signed integer value.
    LongInt(i64),
    /// 32-bit floating-point value.
    ShortReal(f32),
    /// Raw 2-state packed bits.
    RawTwoState(Vec<bool>), // Each bit is either 0 or 1
    /// Raw 4-state packed bits.
    RawFourState(Vec<ScalarValue>), // Each bit can be 0, 1, X, or Z
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::BinStr(s) | Value::OctStr(s) | Value::HexStr(s) | Value::DecStr(s) => {
                write!(f, "{s}")
            }
            Value::Scalar(scalar) => write!(f, "{scalar}"),
            Value::Int(i) => write!(f, "{i}"),
            Value::Real(r) => write!(f, "{r}"),
            Value::String(s) => write!(f, "\"{s}\""),
            Value::Vector(vec) => {
                write!(
                    f,
                    "{}",
                    vec.iter().map(|s| format!("{s}")).collect::<String>()
                )
            }
            Value::Strength(strength) => write!(f, "{strength}"),
            Value::Time(time) => write!(f, "{time}"),
            Value::ObjType(obj_type) => write!(f, "ObjType({obj_type})"), // Placeholder
            Value::Suppress => write!(f, "Suppress"),
            Value::ShortInt(i) => write!(f, "{i}"),
            Value::LongInt(i) => write!(f, "{i}"),
            Value::ShortReal(r) => write!(f, "{r}"),
            Value::RawTwoState(vec) => {
                write!(
                    f,
                    "{}",
                    vec.iter()
                        .map(|b| if *b { '1' } else { '0' })
                        .collect::<String>()
                )
            }
            Value::RawFourState(vec) => {
                write!(
                    f,
                    "{}",
                    vec.iter().map(|s| format!("{s}")).collect::<String>()
                )
            }
        }
    }
}

#[repr(u32)]
#[derive(FromPrimitive, ToPrimitive, Debug, Copy, Clone)]
/// VPI value format tags used with `vpi_get_value` and related APIs.
pub enum ValueType {
    BinStr = vpi_sys::vpiBinStrVal,
    OctStr = vpi_sys::vpiOctStrVal,
    HexStr = vpi_sys::vpiHexStrVal,
    DecStr = vpi_sys::vpiDecStrVal,
    Scalar = vpi_sys::vpiScalarVal,
    Int = vpi_sys::vpiIntVal,
    Real = vpi_sys::vpiRealVal,
    String = vpi_sys::vpiStringVal,
    Vector = vpi_sys::vpiVectorVal,
    Strength = vpi_sys::vpiStrengthVal,
    Time = vpi_sys::vpiTimeVal,
    ObjType = vpi_sys::vpiObjTypeVal,
    Suppress = vpi_sys::vpiSuppressVal,
    ShortInt = vpi_sys::vpiShortIntVal,
    LongInt = vpi_sys::vpiLongIntVal,
    ShortReal = vpi_sys::vpiShortRealVal,
    RawTwoState = vpi_sys::vpiRawTwoStateVal,
    RawFourState = vpi_sys::vpiRawFourStateVal,
}

impl std::fmt::Display for ValueType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let type_name = match self {
            ValueType::BinStr => "Binary String",
            ValueType::OctStr => "Octal String",
            ValueType::HexStr => "Hexadecimal String",
            ValueType::DecStr => "Decimal String",
            ValueType::Scalar => "Scalar",
            ValueType::Int => "Integer",
            ValueType::Real => "Real",
            ValueType::String => "String",
            ValueType::Vector => "Vector",
            ValueType::Strength => "Strength",
            ValueType::Time => "Time",
            ValueType::ObjType => "Object Type",
            ValueType::Suppress => "Suppress",
            ValueType::ShortInt => "Short Integer",
            ValueType::LongInt => "Long Integer",
            ValueType::ShortReal => "Short Real",
            ValueType::RawTwoState => "Raw Two-State Vector",
            ValueType::RawFourState => "Raw Four-State Vector",
        };
        write!(f, "{type_name}")
    }
}

#[repr(u32)]
#[derive(FromPrimitive, ToPrimitive, Copy, Clone, Debug)]
/// 4-state scalar encodings used by VPI.
pub enum ScalarValue {
    Zero = vpi_sys::vpi0,
    One = vpi_sys::vpi1,
    X = vpi_sys::vpiX,
    Z = vpi_sys::vpiZ,
    H = vpi_sys::vpiH,
    L = vpi_sys::vpiL,
    DontCare = vpi_sys::vpiDontCare,
    NoChange = vpi_sys::vpiNoChange,
}

impl Display for ScalarValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let char_repr = match self {
            ScalarValue::Zero => '0',
            ScalarValue::One => '1',
            ScalarValue::X => 'X',
            ScalarValue::Z => 'Z',
            ScalarValue::H => 'H',
            ScalarValue::L => 'L',
            ScalarValue::DontCare => '-',
            ScalarValue::NoChange => 'N',
        };
        write!(f, "{char_repr}")
    }
}

#[derive(Debug)]
/// Scalar logic value plus drive strengths.
pub struct StrengthValue {
    logic: ScalarValue,
    strength0: StrengthEncoding,
    strength1: StrengthEncoding,
}

impl Display for StrengthValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({}, {})", self.logic, self.strength0, self.strength1)
    }
}

impl From<vpi_sys::t_vpi_strengthval> for StrengthValue {
    fn from(strength: vpi_sys::t_vpi_strengthval) -> Self {
        let logic = ScalarValue::from_u32(strength.logic as u32).unwrap_or(ScalarValue::DontCare);
        let strength0 = StrengthEncoding::from_bits_truncate(strength.s0 as u32);
        let strength1 = StrengthEncoding::from_bits_truncate(strength.s1 as u32);
        Self {
            logic,
            strength0,
            strength1,
        }
    }
}

bitflags::bitflags! {
    #[derive(Debug)]
    /// Drive-strength and charge encoding flags.
    pub struct StrengthEncoding: u32 {
        const SupplyDrive = vpi_sys::vpiSupplyDrive;
        const StrongDrive = vpi_sys::vpiStrongDrive;
        const PullDrive = vpi_sys::vpiPullDrive;
        const LargeCharge = vpi_sys::vpiLargeCharge;
        const WeakDrive = vpi_sys::vpiWeakDrive;
        const MediumCharge = vpi_sys::vpiMediumCharge;
        const SmallCharge = vpi_sys::vpiSmallCharge;
        const HiZ = vpi_sys::vpiHiZ;
    }
}

impl Display for StrengthEncoding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut strengths = Vec::new();
        if self.contains(StrengthEncoding::SupplyDrive) {
            strengths.push("SupplyDrive");
        }
        if self.contains(StrengthEncoding::StrongDrive) {
            strengths.push("StrongDrive");
        }
        if self.contains(StrengthEncoding::PullDrive) {
            strengths.push("PullDrive");
        }
        if self.contains(StrengthEncoding::LargeCharge) {
            strengths.push("LargeCharge");
        }
        if self.contains(StrengthEncoding::WeakDrive) {
            strengths.push("WeakDrive");
        }
        if self.contains(StrengthEncoding::MediumCharge) {
            strengths.push("MediumCharge");
        }
        if self.contains(StrengthEncoding::SmallCharge) {
            strengths.push("SmallCharge");
        }
        if self.contains(StrengthEncoding::HiZ) {
            strengths.push("HiZ");
        }
        write!(f, "{}", strengths.join(" | "))
    }
}

bitflags::bitflags! {
    /// Flags controlling behavior of `vpi_put_value`.
    pub struct PutValueFlags: u32 {
        const ReturnEvent = vpi_sys::vpiReturnEvent;
        const UserAllocFlag = vpi_sys::vpiUserAllocFlag;
        const OneValue = vpi_sys::vpiOneValue;
        const PropagateOff = vpi_sys::vpiPropagateOff;
    }
}

/// Convert VPI vector values to a vector of scalar values
///
/// The VPI vecval structure encodes each bit as a pair (aval, bval):
/// - ab: 00 = 0 (Zero)
/// - ab: 10 = 1 (One)
/// - ab: 11 = X (X)
/// - ab: 01 = Z (Z)
///
/// # Arguments
/// * `vec` - Array of `vpi_vecval` structures containing the encoded bits
/// * `size` - Number of bits to extract
#[must_use]
pub fn vector_value_to_scalar_vector(
    vec: &[vpi_sys::t_vpi_vecval],
    size: usize,
) -> Vec<ScalarValue> {
    let mut result = Vec::with_capacity(size);

    for bit_index in 0..size {
        // Which word in the vecval array contains this bit?
        let word_index = bit_index / 32;
        // Which bit position within that word?
        let bit_position = bit_index % 32;

        if word_index >= vec.len() {
            // If we've run out of vecval words, treat as 0
            result.push(ScalarValue::Zero);
            continue;
        }

        let vecval = &vec[word_index];

        // Extract the a and b bits
        let a_bit = (vecval.aval >> bit_position) & 1;
        let b_bit = (vecval.bval >> bit_position) & 1;

        // Combine into the encoding: (a << 1) | b
        // 00=0, 10=1, 11=X, 01=Z
        let encoded = (a_bit << 1) | b_bit;

        let scalar = match encoded {
            0 => ScalarValue::Zero,
            1 => ScalarValue::Z,
            2 => ScalarValue::One,
            3 => ScalarValue::X,
            _ => ScalarValue::DontCare, // Should never happen
        };

        result.push(scalar);
    }

    result.reverse(); // Reverse to match Verilog bit ordering (MSB at index 0)
    result
}

impl Handle {
    /// Reads a value from this handle in the requested format.
    ///
    /// Returns `None` for null handles or unsupported formats.
    #[must_use]
    pub fn get_value(&self, format: ValueType) -> Option<Value> {
        if self.is_null() {
            return None;
        }
        let mut value = vpi_sys::t_vpi_value {
            format: format as i32,
            value: vpi_sys::t_vpi_value__bindgen_ty_1 { integer: 0 },
        };
        unsafe { vpi_sys::vpi_get_value(self.as_raw(), &raw mut value) };
        let value = match value.format as u32 {
            vpi_sys::vpiBinStrVal
            | vpi_sys::vpiOctStrVal
            | vpi_sys::vpiHexStrVal
            | vpi_sys::vpiDecStrVal => {
                let c_str = unsafe { std::ffi::CStr::from_ptr(value.value.str_) };
                Value::BinStr(c_str.to_str().unwrap_or("").to_string())
            }
            vpi_sys::vpiScalarVal => Value::Scalar(
                ScalarValue::from_u32(unsafe { value.value.integer } as u32)
                    .unwrap_or(ScalarValue::DontCare),
            ),
            vpi_sys::vpiIntVal => Value::Int(unsafe { value.value.integer }),
            vpi_sys::vpiRealVal => Value::Real(unsafe { value.value.real }),
            vpi_sys::vpiStringVal => {
                let c_str = unsafe { std::ffi::CStr::from_ptr(value.value.str_) };
                Value::String(c_str.to_str().unwrap_or("").to_string())
            }
            vpi_sys::vpiObjTypeVal => Value::ObjType(unsafe { value.value.integer }),
            vpi_sys::vpiVectorVal => {
                let vec_ptr = unsafe { value.value.vector };
                if vec_ptr.is_null() {
                    Value::Vector(vec![])
                } else {
                    // Get the size (number of bits) from the object
                    let size = unsafe { vpi_sys::vpi_get(vpi_sys::vpiSize as i32, self.as_raw()) }
                        as usize;

                    // Calculate how many vecval words we need (32 bits per word)
                    let num_words = size.div_ceil(32);
                    let vec = unsafe { std::slice::from_raw_parts(vec_ptr, num_words) };
                    Value::Vector(vector_value_to_scalar_vector(vec, size))
                }
            }
            vpi_sys::vpiStrengthVal => {
                let strength: vpi_sys::t_vpi_strengthval = unsafe { *value.value.strength };
                Value::Strength(StrengthValue::from(strength))
            }
            vpi_sys::vpiTimeVal => {
                let vpi_time: vpi_sys::t_vpi_time = unsafe { *value.value.time };
                Value::Time(Time::from(vpi_time))
            }
            vpi_sys::vpiShortIntVal => Value::ShortInt(unsafe { value.value.integer } as i16),

            // For simplicity, other types are not fully implemented here
            _ => return None,
        };
        Some(value)
    }

    /// Retrieve an array of values from a Verilog object (e.g., memory array, packet array).
    ///
    /// This function calls `vpi_get_value_array` to fetch multiple values at once.
    /// It handles various value formats and automatically allocates the necessary memory.
    ///
    /// # Arguments
    /// * `format` - The format of values to retrieve (Int, Real, Time, etc.)
    ///
    /// # Returns
    /// * `Some(Vec<Value>)` - A vector of retrieved values
    /// * `None` - If the handle is null or the operation fails
    ///
    /// # Example
    /// ```ignore
    /// let mem = root.scan(vpi_sys::vpiMem)?;
    /// if let Some(values) = mem.get_value_array(ValueType::Int) {
    ///     for (i, val) in values.iter().enumerate() {
    ///         println!("Memory[{}] = {}", i, val);
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn get_value_array(&self, format: ValueType) -> Option<Vec<Value>> {
        if self.is_null() {
            return None;
        }

        let size =
            unsafe { vpi_sys::vpi_get(vpi_sys::vpiSize as PLI_INT32, self.as_raw()) } as usize;

        if size == 0 {
            return Some(Vec::new());
        }

        match format {
            ValueType::Int => {
                let mut integers: Vec<i32> = vec![0; size];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiIntVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        integers: integers.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(integers.into_iter().map(Value::Int).collect::<Vec<Value>>())
            }
            ValueType::Real => {
                let mut reals: Vec<f64> = vec![0.0; size];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiRealVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        reals: reals.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(reals.into_iter().map(Value::Real).collect::<Vec<Value>>())
            }
            ValueType::Time => {
                let mut times: Vec<vpi_sys::t_vpi_time> = vec![
                    vpi_sys::t_vpi_time {
                        type_: 0,
                        high: 0,
                        low: 0,
                        real: 0.0,
                    };
                    size
                ];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiTimeVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        times: times.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(
                    times
                        .into_iter()
                        .map(|t| {
                            let vpi_time = vpi_sys::s_vpi_time {
                                type_: t.type_,
                                high: t.high,
                                low: t.low,
                                real: t.real,
                            };
                            Value::Time(Time::from(vpi_time))
                        })
                        .collect::<Vec<Value>>(),
                )
            }
            ValueType::ShortInt => {
                let mut shortints: Vec<i16> = vec![0; size];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiShortIntVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        shortints: shortints.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(
                    shortints
                        .into_iter()
                        .map(Value::ShortInt)
                        .collect::<Vec<Value>>(),
                )
            }
            ValueType::LongInt => {
                let mut longints: Vec<i64> = vec![0; size];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiLongIntVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        longints: longints.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(
                    longints
                        .into_iter()
                        .map(Value::LongInt)
                        .collect::<Vec<Value>>(),
                )
            }
            ValueType::ShortReal => {
                let mut shortreals: Vec<f32> = vec![0.0; size];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiShortRealVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        shortreals: shortreals.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(
                    shortreals
                        .into_iter()
                        .map(Value::ShortReal)
                        .collect::<Vec<Value>>(),
                )
            }
            ValueType::Vector => {
                // For vector arrays, each element needs to be read individually
                // as the size calculation is different (bits per element vs. total bits)
                let mut values = Vec::with_capacity(size);
                for _ in 0..size {
                    if let Some(val) = self.get_value(ValueType::Vector) {
                        values.push(val);
                    }
                }
                Some(values)
            }
            ValueType::Scalar => {
                // For scalar arrays
                let mut rawvals: Vec<i8> = vec![0; size];
                let mut arrayvalue = vpi_sys::t_vpi_arrayvalue {
                    format: vpi_sys::vpiScalarVal,
                    flags: 0,
                    value: vpi_sys::t_vpi_arrayvalue__bindgen_ty_1 {
                        rawvals: rawvals.as_mut_ptr(),
                    },
                };
                let mut index = 0;

                unsafe {
                    vpi_sys::vpi_get_value_array(
                        self.as_raw(),
                        &raw mut arrayvalue,
                        &raw mut index,
                        size as PLI_UINT32,
                    );
                }

                Some(
                    rawvals
                        .into_iter()
                        .filter_map(|v| ScalarValue::from_u32(v as u32).map(Value::Scalar))
                        .collect::<Vec<Value>>(),
                )
            }
            _ => {
                // For unsupported types, return empty vector
                Some(Vec::new())
            }
        }
    }

    /// Returns whether this handle represents an array object.
    #[must_use]
    pub fn is_array(&self) -> bool {
        if self.is_null() {
            return false;
        }
        self.get_bool(Property::Array) == Some(true)
    }
}

#[cfg(test)]
mod tests {
    use super::{vector_value_to_scalar_vector, ScalarValue, StrengthEncoding, Value, ValueType};

    fn scalar_vec_to_string(values: Vec<ScalarValue>) -> String {
        values.into_iter().map(|value| value.to_string()).collect()
    }

    #[test]
    fn vector_value_decodes_ab_encoding_and_reverses_bit_order() {
        let vec = [vpi_sys::t_vpi_vecval {
            aval: 0b1010,
            bval: 0b1100,
        }];
        let decoded = vector_value_to_scalar_vector(&vec, 4);

        assert_eq!(scalar_vec_to_string(decoded), "XZ10");
    }

    #[test]
    fn vector_value_uses_zero_when_words_are_missing() {
        let decoded = vector_value_to_scalar_vector(&[], 3);

        assert_eq!(scalar_vec_to_string(decoded), "000");
    }

    #[test]
    fn raw_two_state_display_renders_binary_string() {
        let value = Value::RawTwoState(vec![true, false, true, true, false]);

        assert_eq!(value.to_string(), "10110");
    }

    #[test]
    fn raw_four_state_display_renders_scalar_symbols() {
        let value = Value::RawFourState(vec![
            ScalarValue::Zero,
            ScalarValue::One,
            ScalarValue::X,
            ScalarValue::Z,
            ScalarValue::DontCare,
            ScalarValue::NoChange,
        ]);

        assert_eq!(value.to_string(), "01XZ-N");
    }

    #[test]
    fn strength_encoding_display_joins_active_flags_in_order() {
        let strength = StrengthEncoding::StrongDrive | StrengthEncoding::HiZ;

        assert_eq!(strength.to_string(), "StrongDrive | HiZ");
    }

    #[test]
    fn value_type_display_has_human_readable_labels() {
        assert_eq!(ValueType::RawFourState.to_string(), "Raw Four-State Vector");
        assert_eq!(ValueType::ShortInt.to_string(), "Short Integer");
    }
}