vhpi 0.3.1

Rust wrapper around the IEEE 1076 VHPI
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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
use crate::iso8859_1_val_to_string;
use crate::string_to_iso8859_1_cstring;
use crate::Error;
use crate::Handle;
use crate::LogicVal;
use crate::Physical;
use crate::Time;

use std::fmt;
use std::mem::size_of;

#[cfg(feature = "bigint")]
use num_bigint::{BigInt, BigUint};
#[cfg(feature = "bigint")]
use num_traits::One;
use num_traits::Zero;

#[derive(Debug, PartialEq, Clone)]
/// Strongly typed representation of values exchanged through VHPI.
pub enum Value {
    /// Binary string value.
    BinStr(String),
    /// Octal string value.
    OctStr(String),
    /// Hexadecimal string value.
    HexStr(String),
    /// Decimal string value.
    DecStr(String),
    /// Single character value.
    Char(char),
    /// Scalar integer value.
    Int(i32),
    /// Vector of integer values.
    IntVec(Vec<i32>),
    /// Scalar logic value.
    Logic(LogicVal),
    /// Vector of logic values.
    LogicVec(Vec<LogicVal>),
    /// Scalar small-enum value.
    SmallEnum(u8),
    /// Vector of small-enum values.
    SmallEnumVec(Vec<u8>),
    /// Scalar enum value.
    Enum(u32),
    /// Vector of enum values.
    EnumVec(Vec<u32>),
    /// String value.
    Str(String),
    /// Scalar real value.
    Real(f64),
    /// Vector of real values.
    RealVec(Vec<f64>),
    /// Scalar time value.
    Time(Time),
    /// Vector of time values.
    TimeVec(Vec<Time>),
    /// Scalar long integer value.
    LongInt(i64),
    /// Vector of long integer values.
    LongIntVec(Vec<i64>),
    /// Scalar small physical value.
    SmallPhysical(i32),
    /// Vector of small physical values.
    SmallPhysicalVec(Vec<i32>),
    /// Scalar physical value.
    Physical(Physical),
    /// Vector of physical values.
    PhysicalVec(Vec<Physical>),
    /// Unknown or unsupported value kind.
    Unknown,
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::BinStr(s) => write!(f, "{s}"),
            Value::OctStr(s) => write!(f, "{s}"),
            Value::HexStr(s) => write!(f, "{s}"),
            Value::DecStr(s) => write!(f, "{s}"),
            Value::Int(n) => write!(f, "{n}"),
            Value::Char(c) => write!(f, "{c}"),
            Value::Logic(n) => write!(f, "{n}"),
            Value::LogicVec(v) => {
                for val in v {
                    write!(f, "{val}")?;
                }
                Ok(())
            }
            Value::SmallEnum(n) => write!(f, "{n}"),
            Value::SmallEnumVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::Enum(n) => write!(f, "{n}"),
            Value::EnumVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::Str(s) => write!(f, "{s}"),
            Value::Real(n) => write!(f, "{n}"),
            Value::RealVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::IntVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::Time(t) => write!(f, "{t}"),
            Value::TimeVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::LongInt(n) => write!(f, "{n}"),
            Value::LongIntVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::SmallPhysical(n) => write!(f, "{n}"),
            Value::SmallPhysicalVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(std::string::ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::Physical(p) => write!(f, "{}", p.to_i64()),
            Value::PhysicalVec(v) => {
                write!(
                    f,
                    "[{}]",
                    v.iter()
                        .map(|p| p.to_i64().to_string())
                        .collect::<Vec<_>>()
                        .join(", ")
                )?;
                Ok(())
            }
            Value::Unknown => write!(f, "?"),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Requested VHPI data format for value transfers.
pub enum Format {
    /// Use the object's native value format.
    ///
    /// Passing this to `Handle::get_value` lets the simulator choose the
    /// concrete format and return the value using the correct representation.
    ObjType,
    /// Binary string format.
    BinStr,
    /// Octal string format.
    OctStr,
    /// Hex string format.
    HexStr,
    /// Decimal string format.
    DecStr,
    /// Character format.
    Char,
    /// Integer format.
    Int,
    /// Scalar logic format.
    Logic,
    /// Logic vector format.
    LogicVec,
    /// Scalar small-enum format.
    SmallEnum,
    /// Small-enum vector format.
    SmallEnumVec,
    /// Scalar enum format.
    Enum,
    /// Enum vector format.
    EnumVec,
    /// String format.
    Str,
    /// Scalar real format.
    Real,
    /// Real vector format.
    RealVec,
    /// Integer vector format.
    IntVec,
    /// Scalar long integer format.
    LongInt,
    /// Long-integer vector format.
    LongIntVec,
    /// Scalar small-physical format.
    SmallPhysical,
    /// Small-physical vector format.
    SmallPhysicalVec,
    /// Scalar physical format.
    Physical,
    /// Physical vector format.
    PhysicalVec,
    /// Scalar time format.
    Time,
    /// Time vector format.
    TimeVec,
    /// Unknown format value from the simulator.
    Unknown(vhpi_sys::vhpiFormatT),
}

impl From<vhpi_sys::vhpiFormatT> for Format {
    fn from(raw: vhpi_sys::vhpiFormatT) -> Self {
        match raw {
            vhpi_sys::vhpiFormatT_vhpiObjTypeVal => Format::ObjType,
            vhpi_sys::vhpiFormatT_vhpiBinStrVal => Format::BinStr,
            vhpi_sys::vhpiFormatT_vhpiOctStrVal => Format::OctStr,
            vhpi_sys::vhpiFormatT_vhpiHexStrVal => Format::HexStr,
            vhpi_sys::vhpiFormatT_vhpiDecStrVal => Format::DecStr,
            vhpi_sys::vhpiFormatT_vhpiIntVal => Format::Int,
            vhpi_sys::vhpiFormatT_vhpiCharVal => Format::Char,
            vhpi_sys::vhpiFormatT_vhpiLogicVal => Format::Logic,
            vhpi_sys::vhpiFormatT_vhpiLogicVecVal => Format::LogicVec,
            vhpi_sys::vhpiFormatT_vhpiSmallEnumVal => Format::SmallEnum,
            vhpi_sys::vhpiFormatT_vhpiSmallEnumVecVal => Format::SmallEnumVec,
            vhpi_sys::vhpiFormatT_vhpiEnumVal => Format::Enum,
            vhpi_sys::vhpiFormatT_vhpiEnumVecVal => Format::EnumVec,
            vhpi_sys::vhpiFormatT_vhpiStrVal => Format::Str,
            vhpi_sys::vhpiFormatT_vhpiRealVal => Format::Real,
            vhpi_sys::vhpiFormatT_vhpiRealVecVal => Format::RealVec,
            vhpi_sys::vhpiFormatT_vhpiIntVecVal => Format::IntVec,
            vhpi_sys::vhpiFormatT_vhpiLongIntVal => Format::LongInt,
            vhpi_sys::vhpiFormatT_vhpiLongIntVecVal => Format::LongIntVec,
            vhpi_sys::vhpiFormatT_vhpiSmallPhysVal => Format::SmallPhysical,
            vhpi_sys::vhpiFormatT_vhpiSmallPhysVecVal => Format::SmallPhysicalVec,
            vhpi_sys::vhpiFormatT_vhpiPhysVal => Format::Physical,
            vhpi_sys::vhpiFormatT_vhpiPhysVecVal => Format::PhysicalVec,
            vhpi_sys::vhpiFormatT_vhpiTimeVal => Format::Time,
            vhpi_sys::vhpiFormatT_vhpiTimeVecVal => Format::TimeVec,
            other => Format::Unknown(other),
        }
    }
}

impl From<Format> for vhpi_sys::vhpiFormatT {
    fn from(format: Format) -> Self {
        match format {
            Format::ObjType => vhpi_sys::vhpiFormatT_vhpiObjTypeVal,
            Format::BinStr => vhpi_sys::vhpiFormatT_vhpiBinStrVal,
            Format::OctStr => vhpi_sys::vhpiFormatT_vhpiOctStrVal,
            Format::HexStr => vhpi_sys::vhpiFormatT_vhpiHexStrVal,
            Format::DecStr => vhpi_sys::vhpiFormatT_vhpiDecStrVal,
            Format::Int => vhpi_sys::vhpiFormatT_vhpiIntVal,
            Format::Char => vhpi_sys::vhpiFormatT_vhpiCharVal,
            Format::Logic => vhpi_sys::vhpiFormatT_vhpiLogicVal,
            Format::LogicVec => vhpi_sys::vhpiFormatT_vhpiLogicVecVal,
            Format::SmallEnum => vhpi_sys::vhpiFormatT_vhpiSmallEnumVal,
            Format::SmallEnumVec => vhpi_sys::vhpiFormatT_vhpiSmallEnumVecVal,
            Format::Enum => vhpi_sys::vhpiFormatT_vhpiEnumVal,
            Format::EnumVec => vhpi_sys::vhpiFormatT_vhpiEnumVecVal,
            Format::Str => vhpi_sys::vhpiFormatT_vhpiStrVal,
            Format::Real => vhpi_sys::vhpiFormatT_vhpiRealVal,
            Format::RealVec => vhpi_sys::vhpiFormatT_vhpiRealVecVal,
            Format::IntVec => vhpi_sys::vhpiFormatT_vhpiIntVecVal,
            Format::LongInt => vhpi_sys::vhpiFormatT_vhpiLongIntVal,
            Format::LongIntVec => vhpi_sys::vhpiFormatT_vhpiLongIntVecVal,
            Format::SmallPhysical => vhpi_sys::vhpiFormatT_vhpiSmallPhysVal,
            Format::SmallPhysicalVec => vhpi_sys::vhpiFormatT_vhpiSmallPhysVecVal,
            Format::Physical => vhpi_sys::vhpiFormatT_vhpiPhysVal,
            Format::PhysicalVec => vhpi_sys::vhpiFormatT_vhpiPhysVecVal,
            Format::Time => vhpi_sys::vhpiFormatT_vhpiTimeVal,
            Format::TimeVec => vhpi_sys::vhpiFormatT_vhpiTimeVecVal,
            Format::Unknown(n) => n,
        }
    }
}

/// Write mode used by Handle::put_value.
pub enum PutValueMode {
    /// Deposit a value without forcing.
    Deposit,
    /// Deposit and request immediate propagation.
    DepositPropagate,
    /// Force a value.
    Force,
    /// Force and request immediate propagation.
    ForcePropagate,
    /// Release a previously forced value.
    Release,
    /// Enforce size constraints during assignment.
    SizeConstraint,
}

impl From<PutValueMode> for vhpi_sys::vhpiPutValueModeT {
    fn from(mode: PutValueMode) -> Self {
        match mode {
            PutValueMode::Deposit => vhpi_sys::vhpiPutValueModeT_vhpiDeposit,
            PutValueMode::DepositPropagate => vhpi_sys::vhpiPutValueModeT_vhpiDepositPropagate,
            PutValueMode::Force => vhpi_sys::vhpiPutValueModeT_vhpiForce,
            PutValueMode::ForcePropagate => vhpi_sys::vhpiPutValueModeT_vhpiForcePropagate,
            PutValueMode::Release => vhpi_sys::vhpiPutValueModeT_vhpiRelease,
            PutValueMode::SizeConstraint => vhpi_sys::vhpiPutValueModeT_vhpiSizeConstraint,
        }
    }
}

enum VectorBox {
    #[allow(dead_code)]
    Enum(Vec<vhpi_sys::vhpiEnumT>),
    #[allow(dead_code)]
    Int(Vec<vhpi_sys::vhpiIntT>),
    #[allow(dead_code)]
    Real(Vec<vhpi_sys::vhpiRealT>),
    #[allow(dead_code)]
    Time(Vec<vhpi_sys::vhpiTimeT>),
    #[allow(dead_code)]
    SmallEnum(Vec<vhpi_sys::vhpiSmallEnumT>),
    #[allow(dead_code)]
    LongInt(Vec<vhpi_sys::vhpiLongIntT>),
    #[allow(dead_code)]
    SmallPhys(Vec<vhpi_sys::vhpiSmallPhysT>),
    #[allow(dead_code)]
    Phys(Vec<vhpi_sys::vhpiPhysT>),
}

impl VectorBox {
    fn len(&self) -> usize {
        match self {
            VectorBox::Enum(values) => values.len(),
            VectorBox::Int(values) => values.len(),
            VectorBox::Real(values) => values.len(),
            VectorBox::Time(values) => values.len(),
            VectorBox::SmallEnum(values) => values.len(),
            VectorBox::LongInt(values) => values.len(),
            VectorBox::SmallPhys(values) => values.len(),
            VectorBox::Phys(values) => values.len(),
        }
    }

    fn byte_len(&self) -> usize {
        match self {
            VectorBox::Enum(values) => values.len() * size_of::<vhpi_sys::vhpiEnumT>(),
            VectorBox::Int(values) => values.len() * size_of::<vhpi_sys::vhpiIntT>(),
            VectorBox::Real(values) => values.len() * size_of::<vhpi_sys::vhpiRealT>(),
            VectorBox::Time(values) => values.len() * size_of::<vhpi_sys::vhpiTimeT>(),
            VectorBox::SmallEnum(values) => values.len() * size_of::<vhpi_sys::vhpiSmallEnumT>(),
            VectorBox::LongInt(values) => values.len() * size_of::<vhpi_sys::vhpiLongIntT>(),
            VectorBox::SmallPhys(values) => values.len() * size_of::<vhpi_sys::vhpiSmallPhysT>(),
            VectorBox::Phys(values) => values.len() * size_of::<vhpi_sys::vhpiPhysT>(),
        }
    }
}

impl Handle {
    /// Read a value from this handle using the requested format.
    ///
    /// For vector and string formats, this function performs the required
    /// two-pass buffer allocation expected by VHPI.
    ///
    /// Passing `Format::ObjType` requests automatic format selection based on
    /// the object's type.
    ///
    /// # Errors
    ///
    /// Returns an error when the simulator reports a failure for
    /// value retrieval.
    pub fn get_value(&self, format: Format) -> Result<Value, Error> {
        let mut val = vhpi_sys::vhpiValueT {
            format: format.into(),
            bufSize: 0,
            numElems: 0,
            unit: vhpi_sys::vhpiPhysS { high: 0, low: 0 },
            value: vhpi_sys::vhpiValueS__bindgen_ty_1 { longintg: 0 },
        };

        let mut rc = unsafe { vhpi_sys::vhpi_get_value(self.as_raw(), &raw mut val) };
        // Allocate buffer so that it is kept for the whole function
        let mut buffer: Vec<u8> = vec![];
        if rc > 0 {
            // Need to allocate buffer space
            let buf_size = match val.format {
                vhpi_sys::vhpiFormatT_vhpiBinStrVal
                | vhpi_sys::vhpiFormatT_vhpiStrVal
                | vhpi_sys::vhpiFormatT_vhpiOctStrVal
                | vhpi_sys::vhpiFormatT_vhpiHexStrVal
                | vhpi_sys::vhpiFormatT_vhpiDecStrVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiCharT>()
                }
                vhpi_sys::vhpiFormatT_vhpiLogicVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiEnumT>()
                }
                vhpi_sys::vhpiFormatT_vhpiRealVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiRealT>()
                }
                vhpi_sys::vhpiFormatT_vhpiIntVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiIntT>()
                }
                vhpi_sys::vhpiFormatT_vhpiLongIntVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiLongIntT>()
                }
                vhpi_sys::vhpiFormatT_vhpiSmallPhysVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiSmallPhysT>()
                }
                vhpi_sys::vhpiFormatT_vhpiPhysVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiPhysT>()
                }
                vhpi_sys::vhpiFormatT_vhpiTimeVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiTimeT>()
                }
                vhpi_sys::vhpiFormatT_vhpiSmallEnumVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiSmallEnumT>()
                }
                vhpi_sys::vhpiFormatT_vhpiEnumVecVal => {
                    rc as usize * size_of::<vhpi_sys::vhpiEnumT>()
                }
                _ => {
                    panic!("unsupported vector format {}", val.format);
                }
            };
            buffer = vec![0; buf_size];
            val.bufSize = buf_size;

            match val.format {
                vhpi_sys::vhpiFormatT_vhpiBinStrVal
                | vhpi_sys::vhpiFormatT_vhpiStrVal
                | vhpi_sys::vhpiFormatT_vhpiOctStrVal
                | vhpi_sys::vhpiFormatT_vhpiHexStrVal
                | vhpi_sys::vhpiFormatT_vhpiDecStrVal => {
                    val.value.str_ = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiCharT>();
                }
                vhpi_sys::vhpiFormatT_vhpiLogicVecVal => {
                    val.value.enumvs = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiEnumT>();
                }
                vhpi_sys::vhpiFormatT_vhpiRealVecVal => {
                    val.value.reals = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiRealT>();
                }
                vhpi_sys::vhpiFormatT_vhpiIntVecVal => {
                    val.value.intgs = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiIntT>();
                }
                vhpi_sys::vhpiFormatT_vhpiLongIntVecVal => {
                    val.value.longintgs = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiLongIntT>();
                }
                vhpi_sys::vhpiFormatT_vhpiEnumVecVal => {
                    val.value.enumvs = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiEnumT>();
                }
                vhpi_sys::vhpiFormatT_vhpiSmallEnumVecVal => {
                    val.value.smallenumvs = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiSmallEnumT>();
                }
                vhpi_sys::vhpiFormatT_vhpiSmallPhysVecVal => {
                    val.value.smallphyss = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiSmallPhysT>();
                }
                vhpi_sys::vhpiFormatT_vhpiPhysVecVal => {
                    val.value.physs = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiPhysT>();
                }
                vhpi_sys::vhpiFormatT_vhpiTimeVecVal => {
                    val.value.times = buffer.as_mut_ptr().cast::<vhpi_sys::vhpiTimeT>();
                }
                _ => {
                    panic!("unsupported vector format {}", val.format);
                }
            }

            rc = unsafe { vhpi_sys::vhpi_get_value(self.as_raw(), &raw mut val) };
        }

        if rc < 0 {
            return Err(
                crate::check_error().unwrap_or_else(|| "Unknown error in vhpi_get_value".into())
            );
        }

        let ret = match val.format {
            vhpi_sys::vhpiFormatT_vhpiIntVal => Ok(Value::Int(unsafe { val.value.intg })),
            vhpi_sys::vhpiFormatT_vhpiLogicVal => Ok(Value::Logic(LogicVal::from(unsafe {
                val.value.enumv as u8
            }))),
            vhpi_sys::vhpiFormatT_vhpiEnumVal => Ok(Value::Enum(unsafe { val.value.enumv })),
            vhpi_sys::vhpiFormatT_vhpiSmallEnumVal => {
                Ok(Value::SmallEnum(unsafe { val.value.smallenumv }))
            }
            vhpi_sys::vhpiFormatT_vhpiLongIntVal => {
                Ok(Value::LongInt(unsafe { val.value.longintg }))
            }
            vhpi_sys::vhpiFormatT_vhpiRealVal => Ok(Value::Real(unsafe { val.value.real })),
            vhpi_sys::vhpiFormatT_vhpiCharVal => Ok(Value::Char(unsafe { val.value.ch as char })),
            vhpi_sys::vhpiFormatT_vhpiBinStrVal => Ok(Value::BinStr(iso8859_1_val_to_string(&val))),
            vhpi_sys::vhpiFormatT_vhpiOctStrVal => Ok(Value::OctStr(iso8859_1_val_to_string(&val))),
            vhpi_sys::vhpiFormatT_vhpiHexStrVal => Ok(Value::HexStr(iso8859_1_val_to_string(&val))),
            vhpi_sys::vhpiFormatT_vhpiDecStrVal => Ok(Value::DecStr(iso8859_1_val_to_string(&val))),
            vhpi_sys::vhpiFormatT_vhpiStrVal => Ok(Value::Str(iso8859_1_val_to_string(&val))),
            vhpi_sys::vhpiFormatT_vhpiLogicVecVal => {
                let slice =
                    unsafe { std::slice::from_raw_parts(val.value.enumvs, val.numElems as usize) };
                let logic_vec: Vec<LogicVal> = slice
                    .iter()
                    .map(|&enumv| LogicVal::from(enumv as u8))
                    .collect();
                Ok(Value::LogicVec(logic_vec))
            }
            vhpi_sys::vhpiFormatT_vhpiRealVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(val.value.reals.cast::<f64>(), val.numElems as usize)
                };
                Ok(Value::RealVec(slice.to_vec()))
            }
            vhpi_sys::vhpiFormatT_vhpiIntVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(val.value.intgs.cast::<i32>(), val.numElems as usize)
                };
                Ok(Value::IntVec(slice.to_vec()))
            }
            vhpi_sys::vhpiFormatT_vhpiTimeVal => Ok(Value::Time(unsafe { val.value.time.into() })),
            vhpi_sys::vhpiFormatT_vhpiTimeVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(
                        val.value.times.cast::<vhpi_sys::vhpiTimeT>(),
                        val.numElems as usize,
                    )
                };
                let time_vec: Vec<Time> = slice.iter().map(|&t| t.into()).collect();
                Ok(Value::TimeVec(time_vec))
            }
            vhpi_sys::vhpiFormatT_vhpiSmallEnumVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(
                        val.value.smallenumvs.cast::<vhpi_sys::vhpiSmallEnumT>(),
                        val.numElems as usize,
                    )
                };
                Ok(Value::SmallEnumVec(slice.to_vec()))
            }
            vhpi_sys::vhpiFormatT_vhpiEnumVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(
                        val.value.enumvs.cast::<vhpi_sys::vhpiEnumT>(),
                        val.numElems as usize,
                    )
                };
                Ok(Value::EnumVec(slice.to_vec()))
            }
            vhpi_sys::vhpiFormatT_vhpiSmallPhysVal => {
                Ok(Value::SmallPhysical(unsafe { val.value.smallphys }))
            }
            vhpi_sys::vhpiFormatT_vhpiSmallPhysVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(
                        val.value.smallphyss.cast::<vhpi_sys::vhpiSmallPhysT>(),
                        val.numElems as usize,
                    )
                };
                Ok(Value::SmallPhysicalVec(slice.to_vec()))
            }
            vhpi_sys::vhpiFormatT_vhpiPhysVal => {
                Ok(Value::Physical(unsafe { val.value.phys.into() }))
            }
            vhpi_sys::vhpiFormatT_vhpiPhysVecVal => {
                let slice = unsafe {
                    std::slice::from_raw_parts(
                        val.value.physs.cast::<vhpi_sys::vhpiPhysT>(),
                        val.numElems as usize,
                    )
                };
                let phys_vec: Vec<Physical> = slice.iter().map(|&p| p.into()).collect();
                Ok(Value::PhysicalVec(phys_vec))
            }
            _ => Ok(Value::Unknown),
        };

        // Keep buffer alive until after the the pointer is used to be safe
        let _ = buffer;

        ret
    }

    /// Write a value to this handle using the selected put-value mode.
    ///
    /// # Errors
    ///
    /// Returns an error when the simulator rejects the value write.
    pub fn put_value(&self, value: Value, mode: PutValueMode) -> Result<(), Error> {
        // Create a holder for any allocated buffer
        let mut buffer_holder: Option<VectorBox> = None;

        let (format, val) = match value {
            Value::Int(n) => (Format::Int, vhpi_sys::vhpiValueS__bindgen_ty_1 { intg: n }),
            Value::Logic(n) => (
                Format::Logic,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { enumv: n.into() },
            ),
            Value::Enum(n) => (
                Format::Enum,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { enumv: n },
            ),
            Value::SmallEnum(n) => (
                Format::SmallEnum,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { smallenumv: n },
            ),
            Value::BinStr(s) => {
                let c_string = string_to_iso8859_1_cstring(s);
                let ptr = c_string.into_raw().cast::<vhpi_sys::vhpiCharT>();
                (
                    Format::BinStr,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { str_: ptr },
                )
            }
            Value::OctStr(s) => {
                let c_string = string_to_iso8859_1_cstring(s);
                let ptr = c_string.into_raw().cast::<vhpi_sys::vhpiCharT>();
                (
                    Format::OctStr,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { str_: ptr },
                )
            }
            Value::HexStr(s) => {
                let c_string = string_to_iso8859_1_cstring(s);
                let ptr = c_string.into_raw().cast::<vhpi_sys::vhpiCharT>();
                (
                    Format::HexStr,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { str_: ptr },
                )
            }
            Value::DecStr(s) => {
                let c_string = string_to_iso8859_1_cstring(s);
                let ptr = c_string.into_raw().cast::<vhpi_sys::vhpiCharT>();
                (
                    Format::DecStr,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { str_: ptr },
                )
            }
            Value::Str(s) => {
                let c_string = string_to_iso8859_1_cstring(s);
                let ptr = c_string.into_raw().cast::<vhpi_sys::vhpiCharT>();
                (
                    Format::Str,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { str_: ptr },
                )
            }
            Value::LogicVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiEnumT> =
                    vec.iter().map(|&val| val.into()).collect();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::Enum(buffer));
                (
                    Format::LogicVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { enumvs: ptr },
                )
            }
            Value::IntVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiIntT> = vec.clone();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::Int(buffer));
                (
                    Format::IntVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { intgs: ptr },
                )
            }
            Value::RealVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiRealT> = vec.clone();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::Real(buffer));
                (
                    Format::RealVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { reals: ptr },
                )
            }
            Value::Time(t) => (
                Format::Time,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { time: t.into() },
            ),
            Value::TimeVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiTimeT> =
                    vec.iter().map(|val| val.clone().into()).collect();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::Time(buffer));
                (
                    Format::TimeVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { times: ptr },
                )
            }
            Value::Real(n) => (Format::Real, vhpi_sys::vhpiValueS__bindgen_ty_1 { real: n }),
            Value::Char(c) => (
                Format::Char,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { ch: c as u8 },
            ),
            Value::SmallEnumVec(v) => {
                let mut buffer: Vec<vhpi_sys::vhpiSmallEnumT> = v.clone();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::SmallEnum(buffer));
                (
                    Format::SmallEnumVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { smallenumvs: ptr },
                )
            }
            Value::EnumVec(v) => {
                let mut buffer: Vec<vhpi_sys::vhpiEnumT> = v.clone();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::Enum(buffer));
                (
                    Format::EnumVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { enumvs: ptr },
                )
            }
            Value::LongInt(l) => (
                Format::LongInt,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { longintg: l },
            ),
            Value::LongIntVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiLongIntT> = vec.clone();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::LongInt(buffer));
                (
                    Format::LongIntVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { longintgs: ptr },
                )
            }
            Value::SmallPhysical(s) => (
                Format::SmallPhysical,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { smallphys: s },
            ),
            Value::SmallPhysicalVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiSmallPhysT> = vec.clone();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::SmallPhys(buffer));
                (
                    Format::SmallPhysicalVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { smallphyss: ptr },
                )
            }
            Value::Physical(p) => (
                Format::Physical,
                vhpi_sys::vhpiValueS__bindgen_ty_1 { phys: p.into() },
            ),
            Value::PhysicalVec(vec) => {
                let mut buffer: Vec<vhpi_sys::vhpiPhysT> =
                    vec.iter().map(|val| val.clone().into()).collect();
                let ptr = buffer.as_mut_ptr();
                buffer_holder = Some(VectorBox::Phys(buffer));
                (
                    Format::PhysicalVec,
                    vhpi_sys::vhpiValueS__bindgen_ty_1 { physs: ptr },
                )
            }
            Value::Unknown => return Err("Cannot put unknown value".into()),
        };

        let mut val_struct = vhpi_sys::vhpiValueT {
            format: format.into(),
            bufSize: 0,
            numElems: 0,
            unit: vhpi_sys::vhpiPhysS { high: 0, low: 0 },
            value: val,
        };

        if let Some(buffer) = buffer_holder.as_ref() {
            val_struct.bufSize = buffer.byte_len();
            val_struct.numElems = buffer
                .len()
                .try_into()
                .expect("vector element count does not fit into vhpi element count type");
        }

        let rc =
            unsafe { vhpi_sys::vhpi_put_value(self.as_raw(), &raw mut val_struct, mode.into()) };

        // Keep buffer_holder alive until after vhpi_put_value
        let _ = &buffer_holder;

        if rc.is_zero() {
            Ok(())
        } else {
            Err(crate::check_error().unwrap_or_else(|| "Unknown error in vhpi_put_value".into()))
        }
    }
}

/// Convert a string to a `Value::LogicVec` by mapping each character to a `LogicVal` using the character's byte value.
#[must_use]
pub fn string_to_logic_vec(s: &str) -> Value {
    Value::LogicVec(
        s.chars()
            .map(|c| LogicVal::try_from(c).unwrap_or(LogicVal::Unknown(c as u8)))
            .collect(),
    )
}

#[must_use]
/// Convert an unsigned integer to a `Value::LogicVec` of the specified width,
/// where each bit of the integer is mapped to a `LogicVal`.
/// If the integer cannot fit into the specified width, it will be truncated.
pub fn uint_to_logic_vec(mut value: u64, width: usize) -> Value {
    assert!(width <= 64, "Width must be 64 or less to fit into u64");
    let mut logic_vec = Vec::with_capacity(width);
    for _ in 0..width {
        let bit = (value & 1) as u8;
        logic_vec.push(if bit.is_zero() {
            LogicVal::Zero
        } else {
            LogicVal::One
        });
        value >>= 1;
    }
    logic_vec.reverse();
    Value::LogicVec(logic_vec)
}

#[must_use]
/// Convert a signed integer to a `Value::LogicVec` of the specified width,
/// where each bit of the integer is mapped to a `LogicVal`.
/// If the integer cannot fit into the specified width, it will be truncated.
pub fn int_to_logic_vec(mut value: i64, width: usize) -> Value {
    assert!(width <= 64, "Width must be 64 or less to fit into i64");
    let mut logic_vec = Vec::with_capacity(width);
    for _ in 0..width {
        let bit = (value & 1) as u8;
        logic_vec.push(if bit.is_zero() {
            LogicVal::Zero
        } else {
            LogicVal::One
        });
        value >>= 1;
    }
    logic_vec.reverse();
    Value::LogicVec(logic_vec)
}

#[must_use]
/// Convert a `LogicVec` to an unsigned integer by interpreting the vector as a binary number,
/// where `LogicVal::Zero` represents 0 and `LogicVal::One` represents 1.
/// If any value in the vector is not `Zero` or `One`, return `None`.
pub fn logic_vec_to_uint(logic_vec: &[LogicVal]) -> Option<u64> {
    let mut value = 0u64;
    for &logic_val in logic_vec {
        value <<= 1;
        match logic_val {
            LogicVal::Zero => {}
            LogicVal::One => value |= 1,
            _ => return None, // If any value is not 0 or 1, return None
        }
    }
    Some(value)
}

#[must_use]
/// Convert a `LogicVec` to a signed integer by interpreting the vector as a binary number,
/// where `LogicVal::Zero` represents 0 and `LogicVal::One` represents 1.
/// If any value in the vector is not `Zero` or `One`, return `None`.
pub fn logic_vec_to_int(logic_vec: &[LogicVal]) -> Option<i64> {
    if logic_vec.len() > 64 {
        return None;
    }

    let mut value = 0i64;
    for &logic_val in logic_vec {
        value <<= 1;
        match logic_val {
            LogicVal::Zero => {}
            LogicVal::One => value |= 1,
            _ => return None, // If any value is not 0 or 1, return None
        }
    }

    if matches!(logic_vec.first(), Some(LogicVal::One)) {
        let width = logic_vec.len();
        if width < 64 {
            value |= !0i64 << width;
        }
    }

    Some(value)
}

#[cfg(feature = "bigint")]
#[must_use]
/// Convert a `LogicVec` to a `BigInt` by interpreting the vector as a binary number,
/// where `LogicVal::Zero` represents 0 and `LogicVal::One` represents 1.
/// If any value in the vector is not `Zero` or `One`, return `None`.
pub fn logic_vec_to_bigint(logic_vec: &[LogicVal]) -> Option<BigInt> {
    let mut value = BigInt::ZERO;
    let one = BigInt::one();
    for &logic_val in logic_vec {
        value <<= 1;
        match logic_val {
            LogicVal::Zero => {}
            LogicVal::One => value |= &one,
            _ => return None, // If any value is not 0 or 1, return None
        }
    }

    if matches!(logic_vec.first(), Some(LogicVal::One)) && !logic_vec.is_empty() {
        let sign_base = &one << logic_vec.len();
        value -= sign_base;
    }

    Some(value)
}

#[cfg(feature = "bigint")]
#[must_use]
/// Convert a `LogicVec` to a `BigUint` by interpreting the vector as a binary number,
/// where `LogicVal::Zero` represents 0 and `LogicVal::One` represents 1.
/// If any value in the vector is not `Zero` or `One`, return `None`.
pub fn logic_vec_to_biguint(logic_vec: &[LogicVal]) -> Option<BigUint> {
    let mut value = BigUint::ZERO;
    let one = BigUint::one();
    for &logic_val in logic_vec {
        value <<= 1;
        match logic_val {
            LogicVal::Zero => {}
            LogicVal::One => value |= &one,
            _ => return None, // If any value is not 0 or 1, return None
        }
    }
    Some(value)
}

#[cfg(feature = "bigint")]
#[must_use]
/// Convert a `BigInt` to a `Value::LogicVec` of the specified width, where each bit of the integer is mapped to a `LogicVal`.
/// The most significant bit of the integer corresponds to the first element of the vector.
/// If the integer cannot fit into the specified width, it will be truncated.
pub fn bigint_to_logic_vec(value: &BigInt, width: usize) -> Value {
    let mut logic_vec = Vec::with_capacity(width);
    let mut temp = value.clone();
    let one = BigInt::one();
    for _ in 0..width {
        let bit = &temp & &one;
        logic_vec.push(if bit.is_zero() {
            LogicVal::Zero
        } else {
            LogicVal::One
        });
        temp >>= 1;
    }
    logic_vec.reverse();
    Value::LogicVec(logic_vec)
}

#[cfg(feature = "bigint")]
#[must_use]
/// Convert a `BigUint` to a `Value::LogicVec` of the specified width, where each bit of the integer is mapped to a `LogicVal`.
/// The most significant bit of the integer corresponds to the first element of the vector.
/// If the integer cannot fit into the specified width, it will be truncated.
pub fn biguint_to_logic_vec(value: &BigUint, width: usize) -> Value {
    let mut logic_vec = Vec::with_capacity(width);
    let mut temp = value.clone();
    let one = BigUint::one();
    for _ in 0..width {
        let bit = &temp & &one;
        logic_vec.push(if bit.is_zero() {
            LogicVal::Zero
        } else {
            LogicVal::One
        });
        temp >>= 1;
    }
    logic_vec.reverse();
    Value::LogicVec(logic_vec)
}

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

    #[test]
    fn string_to_logic_capital_letters() {
        let input = "UX01ZWLH-";

        let parsed = string_to_logic_vec(input);
        assert_eq!(
            parsed,
            Value::LogicVec(vec![
                LogicVal::U,
                LogicVal::X,
                LogicVal::Zero,
                LogicVal::One,
                LogicVal::Z,
                LogicVal::W,
                LogicVal::L,
                LogicVal::H,
                LogicVal::DontCare,
            ])
        );
    }

    #[test]
    fn string_to_logic_small_letters() {
        let input = "ux01zwlh-";

        let parsed = string_to_logic_vec(input);
        assert_eq!(
            parsed,
            Value::LogicVec(vec![
                LogicVal::U,
                LogicVal::X,
                LogicVal::Zero,
                LogicVal::One,
                LogicVal::Z,
                LogicVal::W,
                LogicVal::L,
                LogicVal::H,
                LogicVal::DontCare,
            ])
        );
    }

    #[test]
    fn string_to_logic_vec_returns_empty_for_empty_string() {
        assert_eq!(string_to_logic_vec(""), Value::LogicVec(vec![]));
    }

    #[test]
    fn string_to_logic_vec_maps_unknown_chars_to_unknown_logic_values() {
        assert_eq!(
            string_to_logic_vec("A"),
            Value::LogicVec(vec![LogicVal::Unknown(b'A')])
        );
    }

    #[test]
    fn uint_to_logic_vec_converts_correctly() {
        assert_eq!(
            uint_to_logic_vec(0b101, 3),
            Value::LogicVec(vec![LogicVal::One, LogicVal::Zero, LogicVal::One])
        );
    }

    #[test]
    fn logic_vec_to_uint_converts_correctly() {
        assert_eq!(
            logic_vec_to_uint(&[LogicVal::One, LogicVal::Zero, LogicVal::One]),
            Some(5)
        );
        assert_eq!(
            logic_vec_to_uint(&[LogicVal::One, LogicVal::Zero, LogicVal::Unknown(0)]),
            None
        );
    }

    #[test]
    fn logic_vec_to_int_converts_correctly() {
        assert_eq!(
            logic_vec_to_int(&[LogicVal::One, LogicVal::Zero, LogicVal::One]),
            Some(-3)
        );
        assert_eq!(
            logic_vec_to_int(&[LogicVal::One, LogicVal::Zero, LogicVal::Zero]),
            Some(-4)
        );
        assert_eq!(
            logic_vec_to_int(&[LogicVal::Zero, LogicVal::Zero, LogicVal::One]),
            Some(1)
        );
        assert_eq!(
            logic_vec_to_int(&[LogicVal::One, LogicVal::Zero, LogicVal::Unknown(0)]),
            None
        );
    }

    #[test]
    fn logic_vec_to_int_rejects_width_over_64_bits() {
        let bits = vec![LogicVal::Zero; 65];
        assert_eq!(logic_vec_to_int(&bits), None);
    }

    #[test]
    fn int_to_logic_vec_converts_correctly() {
        assert_eq!(
            int_to_logic_vec(-3, 3),
            Value::LogicVec(vec![LogicVal::One, LogicVal::Zero, LogicVal::One])
        );
        assert_eq!(
            int_to_logic_vec(-4, 3),
            Value::LogicVec(vec![LogicVal::One, LogicVal::Zero, LogicVal::Zero])
        );
        assert_eq!(
            int_to_logic_vec(1, 3),
            Value::LogicVec(vec![LogicVal::Zero, LogicVal::Zero, LogicVal::One])
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn logic_vec_to_bigint_converts_correctly() {
        assert_eq!(
            logic_vec_to_bigint(&[LogicVal::One, LogicVal::Zero, LogicVal::One]),
            Some(num_bigint::BigInt::from(-3i8))
        );
        assert_eq!(
            logic_vec_to_bigint(&[LogicVal::Zero, LogicVal::Zero, LogicVal::One]),
            Some(num_bigint::BigInt::from(1u8))
        );
        assert_eq!(
            logic_vec_to_bigint(&[LogicVal::One, LogicVal::Zero, LogicVal::Zero]),
            Some(num_bigint::BigInt::from(-4i8))
        );
        assert_eq!(
            logic_vec_to_bigint(&[]),
            Some(num_bigint::BigInt::from(0u8))
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn logic_vec_to_bigint_returns_none_for_non_binary_values() {
        assert_eq!(
            logic_vec_to_bigint(&[LogicVal::One, LogicVal::Unknown(0), LogicVal::Zero]),
            None
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn logic_vec_to_biguint_converts_correctly() {
        assert_eq!(
            logic_vec_to_biguint(&[LogicVal::One, LogicVal::Zero, LogicVal::One]),
            Some(num_bigint::BigUint::from(5u8))
        );
        assert_eq!(
            logic_vec_to_biguint(&[]),
            Some(num_bigint::BigUint::from(0u8))
        );
        assert_eq!(
            logic_vec_to_biguint(&[LogicVal::One, LogicVal::Unknown(0), LogicVal::Zero]),
            None
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn bigint_to_logic_vec_converts_signed_values() {
        assert_eq!(
            bigint_to_logic_vec(&num_bigint::BigInt::from(-3i8), 3),
            Value::LogicVec(vec![LogicVal::One, LogicVal::Zero, LogicVal::One])
        );
        assert_eq!(
            bigint_to_logic_vec(&num_bigint::BigInt::from(2u8), 3),
            Value::LogicVec(vec![LogicVal::Zero, LogicVal::One, LogicVal::Zero])
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn biguint_to_logic_vec_converts_values() {
        assert_eq!(
            biguint_to_logic_vec(&num_bigint::BigUint::from(5u8), 3),
            Value::LogicVec(vec![LogicVal::One, LogicVal::Zero, LogicVal::One])
        );
        assert_eq!(
            biguint_to_logic_vec(&num_bigint::BigUint::from(0u8), 4),
            Value::LogicVec(vec![
                LogicVal::Zero,
                LogicVal::Zero,
                LogicVal::Zero,
                LogicVal::Zero,
            ])
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn bigint_and_biguint_round_trip_with_logic_vec() {
        let signed_bits = vec![LogicVal::One, LogicVal::Zero, LogicVal::One, LogicVal::One];
        let signed_value = logic_vec_to_bigint(&signed_bits).unwrap();
        assert_eq!(
            bigint_to_logic_vec(&signed_value, signed_bits.len()),
            Value::LogicVec(signed_bits)
        );

        let unsigned_bits = vec![LogicVal::One, LogicVal::Zero, LogicVal::One, LogicVal::One];
        let unsigned_value = logic_vec_to_biguint(&unsigned_bits).unwrap();
        assert_eq!(
            biguint_to_logic_vec(&unsigned_value, unsigned_bits.len()),
            Value::LogicVec(unsigned_bits)
        );
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn biguint_large_round_trip_with_logic_vec() {
        use num_bigint::BigUint;
        use num_traits::Num;

        let original =
            BigUint::from_str_radix("1234567890abcdef1234567890abcdef1234567890abcdef", 16)
                .unwrap();
        let width = 192;

        let as_logic = biguint_to_logic_vec(&original, width);
        let round_trip = match as_logic {
            Value::LogicVec(bits) => logic_vec_to_biguint(&bits),
            _ => None,
        };

        assert_eq!(round_trip, Some(original));
    }

    #[cfg(feature = "bigint")]
    #[test]
    fn bigint_large_round_trip_with_logic_vec() {
        use num_bigint::BigInt;
        use num_traits::Num;

        let magnitude =
            BigInt::from_str_radix("1234567890abcdef1234567890abcdef1234567890abcdef", 16).unwrap();
        let original = -magnitude;
        let width = 193;

        let as_logic = bigint_to_logic_vec(&original, width);
        let round_trip = match as_logic {
            Value::LogicVec(bits) => logic_vec_to_bigint(&bits),
            _ => None,
        };

        assert_eq!(round_trip, Some(original));
    }
}