miden-debug-engine 0.6.1

Core debugger engine for miden-debug
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
use miden_core::{Word, field::PrimeField64};
use miden_processor::Felt as RawFelt;
#[cfg(feature = "proptest")]
use proptest::{
    arbitrary::Arbitrary,
    strategy::{BoxedStrategy, Strategy},
};
use serde::Deserialize;
use smallvec::{SmallVec, smallvec};

pub trait ToMidenRepr {
    /// Convert this type into its raw byte representation
    ///
    /// The order of bytes in the resulting vector should be little-endian, i.e. the least
    /// significant bytes come first.
    fn to_bytes(&self) -> SmallVec<[u8; 16]>;
    /// Convert this type into one or more field elements, where the order of the elements is such
    /// that the byte representation of `self` is in little-endian order, i.e. the least significant
    /// bytes come first.
    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        let bytes = self.to_bytes();
        let num_felts = bytes.len().div_ceil(4);
        let mut felts = SmallVec::<[RawFelt; 4]>::with_capacity(num_felts);
        let (chunks, remainder) = bytes.as_chunks::<4>();
        for chunk in chunks {
            felts.push(RawFelt::new(u32::from_ne_bytes(*chunk) as u64));
        }
        if !remainder.is_empty() {
            let mut chunk = [0u8; 4];
            for (i, byte) in remainder.iter().enumerate() {
                chunk[i] = *byte;
            }
            felts.push(RawFelt::new(u32::from_ne_bytes(chunk) as u64));
        }
        felts
    }
    /// Convert this type into one or more words, zero-padding as needed, such that:
    ///
    /// * The field elements within each word is in little-endian order, i.e. the least significant
    ///   bytes of come first.
    /// * Each word, if pushed on the operand stack element-by-element, would leave the element
    ///   with the most significant bytes on top of the stack (including padding)
    fn to_words(&self) -> SmallVec<[Word; 1]> {
        let felts = self.to_felts();
        let num_words = felts.len().div_ceil(4);
        let mut words = SmallVec::<[Word; 1]>::with_capacity(num_words);
        let (chunks, remainder) = felts.as_chunks::<4>();
        for mut word in chunks.iter().copied() {
            word.reverse();
            words.push(Word::new(word));
        }
        if !remainder.is_empty() {
            let mut word = [RawFelt::ZERO; 4];
            for (i, felt) in remainder.iter().enumerate() {
                word[i] = *felt;
            }
            word.reverse();
            words.push(Word::new(word));
        }
        words
    }

    /// Push this value on the given operand stack using [Self::to_felts] representation
    ///
    /// If pushing arguments for functions compiled from Wasm, consider using
    /// [`push_wasm_ty_to_operand_stack`] instead.
    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.extend(self.to_felts());
    }

    /// Push this value in its [Self::to_words] representation, on the given stack.
    ///
    /// This function is designed for encoding values that will be placed on the advice stack and
    /// copied into Miden VM memory by the compiler-emitted test harness.
    ///
    /// Returns the number of words that were pushed on the stack
    fn push_words_to_advice_stack(&self, stack: &mut Vec<RawFelt>) -> usize {
        let words = self.to_words();
        let num_words = words.len();
        for word in words.into_iter().rev() {
            for felt in word.into_iter() {
                stack.push(felt);
            }
        }
        num_words
    }
}

pub trait FromMidenRepr: Sized {
    /// Returns the size of this type as encoded by [ToMidenRepr::to_felts]
    fn size_in_felts() -> usize;
    /// Extract a value of this type from `bytes`, where:
    ///
    /// * It is assumed that bytes is always padded out to 4 byte alignment
    /// * It is assumed that the bytes are in little-endian order, as encoded by [ToMidenRepr]
    fn from_bytes(bytes: &[u8]) -> Self;
    /// Extract a value of this type as encoded in a vector of field elements, where:
    ///
    /// * The order of the field elements is little-endian, i.e. the element holding the least
    ///   significant bytes comes first.
    fn from_felts(felts: &[RawFelt]) -> Self {
        let mut bytes = SmallVec::<[u8; 16]>::with_capacity(felts.len() * 4);
        for felt in felts {
            let chunk = (felt.as_canonical_u64() as u32).to_ne_bytes();
            bytes.extend(chunk);
        }
        Self::from_bytes(&bytes)
    }
    /// Extract a value of this type as encoded in a vector of words, where:
    ///
    /// * The order of the words is little-endian, i.e. the word holding the least significant
    ///   bytes comes first.
    /// * The order of the field elements in each word is in big-endian order, i.e. the element
    ///   with the most significant byte is at the start of the word, and the element with the
    ///   least significant byte is at the end of the word. This corresponds to the order in
    ///   which elements are placed on the operand stack when preparing to read or write them
    ///   from Miden's memory.
    fn from_words(words: &[Word]) -> Self {
        let mut felts = SmallVec::<[RawFelt; 4]>::with_capacity(words.len() * 4);
        for word in words {
            for felt in word.iter().copied().rev() {
                felts.push(felt);
            }
        }
        Self::from_felts(&felts)
    }

    /// Pop a value of this type from `stack` based on the canonical representation of this type
    /// on the operand stack when writing it to memory (and as read from memory).
    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        let needed = Self::size_in_felts();
        let mut felts = SmallVec::<[RawFelt; 4]>::with_capacity(needed);
        for _ in 0..needed {
            felts.push(stack.pop().unwrap());
        }
        Self::from_felts(&felts)
    }
}

impl ToMidenRepr for bool {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        smallvec![*self as u8]
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u64));
    }
}

impl FromMidenRepr for bool {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        match bytes[0] {
            0 => false,
            1 => true,
            n => panic!("invalid byte representation for boolean: {n:0x}"),
        }
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        match felts[0].as_canonical_u64() {
            0 => false,
            1 => true,
            n => panic!("invalid byte representation for boolean: {n:0x}"),
        }
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        match stack.pop().unwrap().as_canonical_u64() {
            0 => false,
            1 => true,
            n => panic!("invalid byte representation for boolean: {n:0x}"),
        }
    }
}

impl ToMidenRepr for u8 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        smallvec![*self]
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u64));
    }
}

impl FromMidenRepr for u8 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    #[inline(always)]
    fn from_bytes(bytes: &[u8]) -> Self {
        bytes[0]
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0].as_canonical_u64() as u8
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        stack.pop().unwrap().as_canonical_u64() as u8
    }
}

impl ToMidenRepr for i8 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        smallvec![*self as u8]
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u8 as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u8 as u64));
    }
}

impl FromMidenRepr for i8 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    #[inline(always)]
    fn from_bytes(bytes: &[u8]) -> Self {
        bytes[0] as i8
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0].as_canonical_u64() as u8 as i8
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        stack.pop().unwrap().as_canonical_u64() as u8 as i8
    }
}

impl ToMidenRepr for u16 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_ne_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u64));
    }
}

impl FromMidenRepr for u16 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= 2);
        u16::from_ne_bytes([bytes[0], bytes[1]])
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0].as_canonical_u64() as u16
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        stack.pop().unwrap().as_canonical_u64() as u16
    }
}

impl ToMidenRepr for i16 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_ne_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u16 as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u16 as u64));
    }
}

impl FromMidenRepr for i16 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= 2);
        i16::from_ne_bytes([bytes[0], bytes[1]])
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0].as_canonical_u64() as u16 as i16
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        stack.pop().unwrap().as_canonical_u64() as u16 as i16
    }
}

impl ToMidenRepr for u32 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_ne_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u64));
    }
}

impl FromMidenRepr for u32 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= 4);
        u32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0].as_canonical_u64() as u32
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        stack.pop().unwrap().as_canonical_u64() as u32
    }
}

impl ToMidenRepr for i32 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_ne_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![RawFelt::new(*self as u32 as u64)]
    }

    fn push_to_operand_stack(&self, stack: &mut Vec<RawFelt>) {
        stack.push(RawFelt::new(*self as u32 as u64));
    }
}

impl FromMidenRepr for i32 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= 4);
        i32::from_ne_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0].as_canonical_u64() as u32 as i32
    }

    fn pop_from_stack(stack: &mut Vec<RawFelt>) -> Self {
        stack.pop().unwrap().as_canonical_u64() as u32 as i32
    }
}

impl ToMidenRepr for u64 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_le_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        let lo = (*self as u32) as u64;
        let hi = *self >> 32;
        smallvec![RawFelt::new(lo), RawFelt::new(hi)]
    }
}

impl FromMidenRepr for u64 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        2
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= 8);
        u64::from_le_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
        ])
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        assert!(felts.len() >= 2);
        let lo = felts[0].as_canonical_u64() as u32 as u64;
        let hi = felts[1].as_canonical_u64() as u32 as u64;
        lo | (hi << 32)
    }
}

impl ToMidenRepr for i64 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_le_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        (*self as u64).to_felts()
    }
}

impl FromMidenRepr for i64 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        2
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        u64::from_bytes(bytes) as i64
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        u64::from_felts(felts) as i64
    }
}

impl ToMidenRepr for u128 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_le_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        let lo_lo = RawFelt::new((*self as u32) as u64);
        let lo_hi = RawFelt::new(((*self >> 32) as u32) as u64);
        let hi_lo = RawFelt::new(((*self >> 64) as u32) as u64);
        let hi_hi = RawFelt::new(((*self >> 96) as u32) as u64);
        smallvec![lo_lo, lo_hi, hi_lo, hi_hi]
    }
}

impl FromMidenRepr for u128 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        4
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= 16);
        u128::from_le_bytes([
            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
        ])
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        assert!(felts.len() >= 4);
        let lo_lo = felts[0].as_canonical_u64() as u32 as u128;
        let lo_hi = felts[1].as_canonical_u64() as u32 as u128;
        let hi_lo = felts[2].as_canonical_u64() as u32 as u128;
        let hi_hi = felts[3].as_canonical_u64() as u32 as u128;
        lo_lo | (lo_hi << 32) | (hi_lo << 64) | (hi_hi << 96)
    }
}

impl ToMidenRepr for i128 {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(&self.to_le_bytes())
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        (*self as u128).to_felts()
    }
}

impl FromMidenRepr for i128 {
    #[inline(always)]
    fn size_in_felts() -> usize {
        4
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        u128::from_bytes(bytes) as i128
    }

    fn from_felts(felts: &[RawFelt]) -> Self {
        u128::from_felts(felts) as i128
    }
}

impl ToMidenRepr for RawFelt {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        panic!("field elements have no canonical byte representation")
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![*self]
    }

    fn to_words(&self) -> SmallVec<[Word; 1]> {
        let mut word = [RawFelt::ZERO; 4];
        word[0] = *self;
        smallvec![Word::new(word)]
    }
}

impl FromMidenRepr for RawFelt {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(_bytes: &[u8]) -> Self {
        panic!("field elements have no canonical byte representation")
    }

    #[inline(always)]
    fn from_felts(felts: &[RawFelt]) -> Self {
        felts[0]
    }

    #[inline(always)]
    fn from_words(words: &[Word]) -> Self {
        words[0][0]
    }
}

impl ToMidenRepr for Felt {
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        panic!("field elements have no canonical byte representation")
    }

    fn to_felts(&self) -> SmallVec<[RawFelt; 4]> {
        smallvec![self.0]
    }

    fn to_words(&self) -> SmallVec<[Word; 1]> {
        let mut word = [RawFelt::ZERO; 4];
        word[0] = self.0;
        smallvec![Word::new(word)]
    }
}

impl FromMidenRepr for Felt {
    #[inline(always)]
    fn size_in_felts() -> usize {
        1
    }

    fn from_bytes(_bytes: &[u8]) -> Self {
        panic!("field elements have no canonical byte representation")
    }

    #[inline(always)]
    fn from_felts(felts: &[RawFelt]) -> Self {
        Felt(felts[0])
    }

    #[inline(always)]
    fn from_words(words: &[Word]) -> Self {
        Felt(words[0][0])
    }
}

impl<const N: usize> ToMidenRepr for [u8; N] {
    #[inline]
    fn to_bytes(&self) -> SmallVec<[u8; 16]> {
        SmallVec::from_slice(self)
    }
}

impl<const N: usize> FromMidenRepr for [u8; N] {
    #[inline(always)]
    fn size_in_felts() -> usize {
        N.div_ceil(4)
    }

    fn from_bytes(bytes: &[u8]) -> Self {
        assert!(bytes.len() >= N, "insufficient bytes");
        Self::try_from(&bytes[..N]).unwrap()
    }
}

impl FromMidenRepr for [Felt; 4] {
    #[inline(always)]
    fn size_in_felts() -> usize {
        4
    }

    fn from_bytes(_bytes: &[u8]) -> Self {
        panic!("field elements have no canonical byte representation")
    }

    #[inline(always)]
    fn from_felts(felts: &[RawFelt]) -> Self {
        [Felt(felts[0]), Felt(felts[1]), Felt(felts[2]), Felt(felts[3])]
    }
}

/// Convert a byte array to an equivalent vector of words
///
/// Given a byte slice laid out like so:
///
/// [b0, b1, b2, b3, b4, b5, b6, b7, .., b31]
///
/// This will produce a vector of words laid out like so:
///
/// [[{b12, ..b15}, {b8..b11}, {b4, ..b7}, {b0, ..b3}], [{b31, ..}, ..]]
///
/// In short, it produces words that when placed on the stack and written to memory word-by-word,
/// the original bytes will be laid out in Miden's memory in the correct order.
pub fn bytes_to_words(bytes: &[u8]) -> Vec<[RawFelt; 4]> {
    // 1. Chunk bytes up into felts
    let (chunks, remainder) = bytes.as_chunks::<4>();
    let padded_bytes = bytes.len().next_multiple_of(16);
    let num_felts = padded_bytes / 4;
    let mut buf = Vec::with_capacity(num_felts);
    for chunk in chunks {
        let n = u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
        buf.push(n);
    }
    // Zero-pad the buffer to nearest whole element
    if !remainder.is_empty() {
        let mut n_buf = [0u8; 4];
        for (i, byte) in remainder.iter().enumerate() {
            n_buf[i] = *byte;
        }
        buf.push(u32::from_ne_bytes(n_buf));
    }
    // Zero-pad the buffer to nearest whole word
    buf.resize(num_felts, 0);
    // Chunk into words, and push them in largest-address first order
    let num_words = num_felts / 4;
    let mut words = Vec::with_capacity(num_words);
    let (chunks, remainder) = buf.as_chunks::<4>();
    for chunk in chunks {
        words.push([
            RawFelt::new(chunk[3] as u64),
            RawFelt::new(chunk[2] as u64),
            RawFelt::new(chunk[1] as u64),
            RawFelt::new(chunk[0] as u64),
        ]);
    }
    if !remainder.is_empty() {
        let mut word = [RawFelt::ZERO; 4];
        for (i, n) in remainder.iter().enumerate() {
            word[i] = RawFelt::new(*n as u64);
        }
        word.reverse();
        words.push(word);
    }
    words
}

/// Wrapper around `miden_processor::Felt` that implements useful traits that are not implemented
/// for that type.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Felt(pub RawFelt);
impl Felt {
    #[inline]
    pub fn new(value: u64) -> Self {
        Self(RawFelt::new(value))
    }
}

impl<'de> Deserialize<'de> for Felt {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        u64::deserialize(deserializer).and_then(|n| {
            if n >= RawFelt::ORDER_U64 {
                Err(serde::de::Error::custom(
                    "invalid field element value: exceeds the field modulus",
                ))
            } else {
                Ok(Felt(RawFelt::new(n)))
            }
        })
    }
}

impl clap::builder::ValueParserFactory for Felt {
    type Parser = FeltParser;

    fn value_parser() -> Self::Parser {
        FeltParser
    }
}

#[doc(hidden)]
#[derive(Clone)]
pub struct FeltParser;
impl clap::builder::TypedValueParser for FeltParser {
    type Value = Felt;

    fn parse_ref(
        &self,
        _cmd: &clap::Command,
        _arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, clap::error::Error> {
        use clap::error::{Error, ErrorKind};

        let value = value.to_str().ok_or_else(|| Error::new(ErrorKind::InvalidUtf8))?.trim();
        value.parse().map_err(|err| Error::raw(ErrorKind::ValueValidation, err))
    }
}

impl core::str::FromStr for Felt {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = if let Some(value) = s.strip_prefix("0x") {
            u64::from_str_radix(value, 16)
                .map_err(|err| format!("invalid field element value: {err}"))?
        } else {
            s.parse::<u64>().map_err(|err| format!("invalid field element value: {err}"))?
        };

        if value >= RawFelt::ORDER_U64 {
            Err("invalid field element value: exceeds the field modulus".to_string())
        } else {
            Ok(Felt(RawFelt::new(value)))
        }
    }
}

impl From<Felt> for miden_processor::Felt {
    fn from(f: Felt) -> Self {
        f.0
    }
}

impl From<bool> for Felt {
    fn from(b: bool) -> Self {
        Self(RawFelt::new(b as u64))
    }
}

impl From<u8> for Felt {
    fn from(t: u8) -> Self {
        Self(RawFelt::new(t as u64))
    }
}

impl From<i8> for Felt {
    fn from(t: i8) -> Self {
        Self(RawFelt::new(t as u8 as u64))
    }
}

impl From<i16> for Felt {
    fn from(t: i16) -> Self {
        Self(RawFelt::new(t as u16 as u64))
    }
}

impl From<u16> for Felt {
    fn from(t: u16) -> Self {
        Self(RawFelt::new(t as u64))
    }
}

impl From<i32> for Felt {
    fn from(t: i32) -> Self {
        Self(RawFelt::new(t as u32 as u64))
    }
}

impl From<u32> for Felt {
    fn from(t: u32) -> Self {
        Self(RawFelt::new(t as u64))
    }
}

impl From<u64> for Felt {
    fn from(t: u64) -> Self {
        Self(RawFelt::new(t))
    }
}

impl From<i64> for Felt {
    fn from(t: i64) -> Self {
        Self(RawFelt::new(t as u64))
    }
}

// Reverse Felt to Rust types conversion

impl From<Felt> for bool {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() != 0
    }
}

impl From<Felt> for u8 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as u8
    }
}

impl From<Felt> for i8 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as i8
    }
}

impl From<Felt> for u16 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as u16
    }
}

impl From<Felt> for i16 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as i16
    }
}

impl From<Felt> for u32 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as u32
    }
}

impl From<Felt> for i32 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as i32
    }
}

impl From<Felt> for u64 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64()
    }
}

impl From<Felt> for i64 {
    fn from(f: Felt) -> Self {
        f.0.as_canonical_u64() as i64
    }
}

#[cfg(feature = "proptest")]
impl Arbitrary for Felt {
    type Parameters = ();
    type Strategy = BoxedStrategy<Self>;

    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
        (0u64..RawFelt::ORDER_U64).prop_map(|v| Felt(RawFelt::new(v))).boxed()
    }
}

/// Converts `value` to its corresponding Wasm ABI type and pushes it to the stack.
///
/// It differs from [`ToMidenRepr::push_to_operand_stack`] because it sign-extends `i8` and `i16`
/// values to `i32` before pushing them to the stack.
pub fn push_wasm_ty_to_operand_stack<T>(value: T, stack: &mut Vec<RawFelt>)
where
    T: ToMidenRepr + num_traits::PrimInt,
{
    let ty_size = std::mem::size_of::<T>();
    if ty_size > 2 {
        value.push_to_operand_stack(stack);
        return;
    }

    let is_signed = T::min_value() < T::zero();
    // The unwraps below are safe because `value` is at most 16 bits wide.
    let value_u32 = if is_signed {
        value.to_i32().unwrap() as u32
    } else {
        value.to_u32().unwrap()
    };
    value_u32.push_to_operand_stack(stack);
}

#[cfg(test)]
mod tests {
    use miden_core::Word;

    use super::{FromMidenRepr, ToMidenRepr, bytes_to_words, push_wasm_ty_to_operand_stack};

    #[test]
    fn bool_roundtrip() {
        let encoded = true.to_bytes();
        let decoded = <bool as FromMidenRepr>::from_bytes(&encoded);
        assert!(decoded);

        let encoded = true.to_felts();
        let decoded = <bool as FromMidenRepr>::from_felts(&encoded);
        assert!(decoded);

        let encoded = true.to_words();
        let decoded = <bool as FromMidenRepr>::from_words(&encoded);
        assert!(decoded);

        let mut stack = Vec::default();
        true.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), true.to_felts().as_slice());

        stack.reverse();
        let popped = <bool as FromMidenRepr>::pop_from_stack(&mut stack);
        assert!(popped);
    }

    #[test]
    fn u8_roundtrip() {
        let encoded = u8::MAX.to_bytes();
        let decoded = <u8 as FromMidenRepr>::from_bytes(&encoded);
        assert_eq!(decoded, u8::MAX);

        let encoded = u8::MAX.to_felts();
        let decoded = <u8 as FromMidenRepr>::from_felts(&encoded);
        assert_eq!(decoded, u8::MAX);

        let encoded = u8::MAX.to_words();
        let decoded = <u8 as FromMidenRepr>::from_words(&encoded);
        assert_eq!(decoded, u8::MAX);

        let mut stack = Vec::default();
        u8::MAX.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), u8::MAX.to_felts().as_slice());

        stack.reverse();
        let popped = <u8 as FromMidenRepr>::pop_from_stack(&mut stack);
        assert_eq!(popped, u8::MAX);
    }

    #[test]
    fn u16_roundtrip() {
        let encoded = u16::MAX.to_bytes();
        let decoded = <u16 as FromMidenRepr>::from_bytes(&encoded);
        assert_eq!(decoded, u16::MAX);

        let encoded = u16::MAX.to_felts();
        let decoded = <u16 as FromMidenRepr>::from_felts(&encoded);
        assert_eq!(decoded, u16::MAX);

        let encoded = u16::MAX.to_words();
        let decoded = <u16 as FromMidenRepr>::from_words(&encoded);
        assert_eq!(decoded, u16::MAX);

        let mut stack = Vec::default();
        u16::MAX.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), u16::MAX.to_felts().as_slice());

        stack.reverse();
        let popped = <u16 as FromMidenRepr>::pop_from_stack(&mut stack);
        assert_eq!(popped, u16::MAX);
    }

    #[test]
    fn u32_roundtrip() {
        let encoded = u32::MAX.to_bytes();
        let decoded = <u32 as FromMidenRepr>::from_bytes(&encoded);
        assert_eq!(decoded, u32::MAX);

        let encoded = u32::MAX.to_felts();
        let decoded = <u32 as FromMidenRepr>::from_felts(&encoded);
        assert_eq!(decoded, u32::MAX);

        let encoded = u32::MAX.to_words();
        let decoded = <u32 as FromMidenRepr>::from_words(&encoded);
        assert_eq!(decoded, u32::MAX);

        let mut stack = Vec::default();
        u32::MAX.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), u32::MAX.to_felts().as_slice());

        stack.reverse();
        let popped = <u32 as FromMidenRepr>::pop_from_stack(&mut stack);
        assert_eq!(popped, u32::MAX);
    }

    #[test]
    fn u64_roundtrip() {
        let encoded = u64::MAX.to_bytes();
        let decoded = <u64 as FromMidenRepr>::from_bytes(&encoded);
        assert_eq!(decoded, u64::MAX);

        let encoded = u64::MAX.to_felts();
        let decoded = <u64 as FromMidenRepr>::from_felts(&encoded);
        assert_eq!(decoded, u64::MAX);

        let encoded = u64::MAX.to_words();
        let decoded = <u64 as FromMidenRepr>::from_words(&encoded);
        assert_eq!(decoded, u64::MAX);

        let mut stack = Vec::default();
        u64::MAX.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), u64::MAX.to_felts().as_slice());

        stack.reverse();
        let popped = <u64 as FromMidenRepr>::pop_from_stack(&mut stack);
        assert_eq!(popped, u64::MAX);
    }

    #[test]
    fn u128_roundtrip() {
        let encoded = u128::MAX.to_bytes();
        let decoded = <u128 as FromMidenRepr>::from_bytes(&encoded);
        assert_eq!(decoded, u128::MAX);

        let encoded = u128::MAX.to_felts();
        let decoded = <u128 as FromMidenRepr>::from_felts(&encoded);
        assert_eq!(decoded, u128::MAX);

        let encoded = u128::MAX.to_words();
        let decoded = <u128 as FromMidenRepr>::from_words(&encoded);
        assert_eq!(decoded, u128::MAX);

        let mut stack = Vec::default();
        u128::MAX.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), u128::MAX.to_felts().as_slice());

        stack.reverse();
        let popped = <u128 as FromMidenRepr>::pop_from_stack(&mut stack);
        assert_eq!(popped, u128::MAX);
    }

    #[test]
    fn byte_array_roundtrip() {
        let bytes = [0, 1, 2, 3, 4, 5, 6, 7];

        let encoded = bytes.to_felts();
        let decoded = <[u8; 8] as FromMidenRepr>::from_felts(&encoded);
        assert_eq!(decoded, bytes);

        let encoded = bytes.to_words();
        let decoded = <[u8; 8] as FromMidenRepr>::from_words(&encoded);
        assert_eq!(decoded, bytes);

        let mut stack = Vec::default();
        bytes.push_to_operand_stack(&mut stack);
        assert_eq!(stack.as_slice(), bytes.to_felts().as_slice());

        stack.reverse();
        let popped = <[u8; 8] as FromMidenRepr>::pop_from_stack(&mut stack);
        assert_eq!(popped, bytes);
    }

    #[test]
    fn bytes_to_words_test() {
        let bytes = [
            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,
        ];
        let words = bytes_to_words(&bytes);
        assert_eq!(words.len(), 2);
        // Words should be in little-endian order, elements of the word should be in big-endian
        assert_eq!(words[0][3].as_canonical_u64() as u32, u32::from_ne_bytes([1, 2, 3, 4]));
        assert_eq!(words[0][2].as_canonical_u64() as u32, u32::from_ne_bytes([5, 6, 7, 8]));
        assert_eq!(words[0][1].as_canonical_u64() as u32, u32::from_ne_bytes([9, 10, 11, 12]));
        assert_eq!(words[0][0].as_canonical_u64() as u32, u32::from_ne_bytes([13, 14, 15, 16]));

        // Make sure bytes_to_words and to_words agree
        let to_words_output = bytes.to_words();
        assert_eq!(Word::new(words[0]), to_words_output[0]);
    }

    #[test]
    fn bytes_from_words_test() {
        let bytes = [
            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,
        ];
        let words_as_bytes = bytes_to_words(&bytes);

        let words = vec![Word::new(words_as_bytes[0]), Word::new(words_as_bytes[1])];

        let out = <[u8; 32] as FromMidenRepr>::from_words(&words);

        assert_eq!(&out, &bytes);
    }

    #[test]
    fn push_wasm_ty_to_operand_stack_test() {
        let mut stack = Vec::default();
        push_wasm_ty_to_operand_stack(i8::MIN, &mut stack);
        push_wasm_ty_to_operand_stack(i16::MIN, &mut stack);
        push_wasm_ty_to_operand_stack(u32::MAX, &mut stack);

        assert_eq!(stack[0].as_canonical_u64(), ((i8::MIN as i32) as u32) as u64);
        assert_eq!(stack[1].as_canonical_u64(), ((i16::MIN as i32) as u32) as u64);
        assert_eq!(stack[2].as_canonical_u64(), u32::MAX as u64);
    }
}