brillig_vm 1.0.0-beta.26

The virtual machine that processes Brillig bytecode, used to introduce non-determinism to the ACVM
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
//! Implementation of the VM's memory.
//!
//! # Memory Addressing Limits
//!
//! The VM uses u32 addresses, theoretically allowing up to 2^32 memory slots. However,
//! practical limits apply:
//!
//! - **Rust allocator limit**: All allocations are capped at `isize::MAX` bytes. On 32-bit
//!   systems, this limits addressable memory to approximately `i32::MAX / sizeof(MemoryValue)`
//!   elements (~44 million with typical element sizes).
//!
//! - **RAM limit**: On 64-bit systems, the allocator limit is not a concern, but allocating
//!   the full u32 address space would require ~200 GB of RAM.
use acir::{
    AcirField,
    brillig::{BitSize, IntegerBitSize, MemoryAddress},
};

use crate::assert_usize;

/// The bit size used for addressing memory within the Brillig VM.
///
/// All memory pointers are interpreted as `u32` values, meaning the VM can directly address up to 2^32 memory slots.
pub const MEMORY_ADDRESSING_BIT_SIZE: IntegerBitSize = IntegerBitSize::U32;

/// Maximum number of memory slots that can be allocated.
///
/// This limit is set to `i32::MAX` to ensure deterministic behavior across all architectures.
/// On 32-bit systems, Rust's allocator limits allocations to `isize::MAX` bytes, which would
/// restrict us to fewer elements anyway. By using `i32::MAX`, we ensure the same behavior
/// on both 32-bit and 64-bit systems.
///
/// See: <https://github.com/rust-lang/rust/pull/95295> and <https://doc.rust-lang.org/1.81.0/src/core/alloc/layout.rs.html>
pub const MAX_MEMORY_SIZE: usize = i32::MAX as usize;

/// The current stack pointer is always in slot 0.
///
/// It gets manipulated by opcodes laid down for calls by codegen.
pub const STACK_POINTER_ADDRESS: MemoryAddress = MemoryAddress::Direct(0);

/// The _free memory pointer_ is always in slot 1.
///
/// We added it here to be able to implement a workaround for wrapping around
/// the free memory, ie. to detect "out of memory" events, but the AVM is not,
/// and does not want to be aware of the _free memory pointer_, so we cannot,
/// in general, build much functionality in the VM around it.
pub const FREE_MEMORY_POINTER_ADDRESS: MemoryAddress = MemoryAddress::Direct(1);

/// Offset constants for arrays and vectors:
/// * Arrays are `[ref-count, ...items]`
/// * Vectors are `[ref-count, size, capacity, ...items]`
pub mod offsets {
    /// Number of prefix fields in an array: RC.
    pub const ARRAY_META_COUNT: u32 = 1;
    pub const ARRAY_ITEMS: u32 = 1;

    /// Number of prefix fields in a vector: RC, size, capacity.
    pub const VECTOR_META_COUNT: u32 = 3;
    pub const VECTOR_SIZE: u32 = 1;
    pub const VECTOR_CAPACITY: u32 = 2;
    pub const VECTOR_ITEMS: u32 = 3;
}

/// Wrapper for array addresses, with convenience methods for various offsets.
///
/// The array consists of a ref-count followed by a number of items according
/// the size indicated by the type.
pub(crate) struct ArrayAddress(MemoryAddress);

impl ArrayAddress {
    /// The start of the items, after the meta-data.
    pub(crate) fn items_start(&self) -> MemoryAddress {
        self.0.offset(offsets::ARRAY_ITEMS)
    }
}

impl From<MemoryAddress> for ArrayAddress {
    fn from(value: MemoryAddress) -> Self {
        Self(value)
    }
}

/// A single typed value in the Brillig VM's memory.
///
/// Memory in the VM is strongly typed and can represent either a native field element
/// or an integer of a specific bit width. This enum encapsulates all supported
/// in-memory types and allows conversion between representations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum MemoryValue<F> {
    Field(F),
    U1(bool),
    U8(u8),
    U16(u16),
    U32(u32),
    U64(u64),
    U128(u128),
}

/// Represents errors that can occur when interpreting or converting typed memory values.
#[derive(Debug, thiserror::Error)]
pub enum MemoryTypeError {
    /// The value's bit size does not match the expected bit size for the operation.
    #[error(
        "Bit size for value {value_bit_size} does not match the expected bit size {expected_bit_size}"
    )]
    MismatchedBitSize { value_bit_size: u32, expected_bit_size: u32 },
    /// The memory value is not an integer and cannot be interpreted as one.
    /// For example, this can be triggered when attempting to convert a field element to an integer such as in [`MemoryValue::to_u128`].
    #[error("Value is not an integer")]
    NotAnInteger,
}

impl<F: std::fmt::Display> MemoryValue<F> {
    /// Builds a field-typed memory value.
    pub fn new_field(value: F) -> Self {
        MemoryValue::Field(value)
    }

    /// Builds an integer-typed memory value.
    pub fn new_integer(value: u128, bit_size: IntegerBitSize) -> Self {
        match bit_size {
            IntegerBitSize::U1 => MemoryValue::U1(match value {
                0 => false,
                1 => true,
                _ => panic!("{value} is out of 1 bit range"),
            }),
            IntegerBitSize::U8 => {
                MemoryValue::U8(value.try_into().expect("{value} is out of 8 bits range"))
            }
            IntegerBitSize::U16 => {
                MemoryValue::U16(value.try_into().expect("{value} is out of 16 bits range"))
            }
            IntegerBitSize::U32 => {
                MemoryValue::U32(value.try_into().expect("{value} is out of 32 bits range"))
            }
            IntegerBitSize::U64 => {
                MemoryValue::U64(value.try_into().expect("{value} is out of 64 bits range"))
            }
            IntegerBitSize::U128 => MemoryValue::U128(value),
        }
    }

    pub fn bit_size(&self) -> BitSize {
        match self {
            MemoryValue::Field(_) => BitSize::Field,
            MemoryValue::U1(_) => BitSize::Integer(IntegerBitSize::U1),
            MemoryValue::U8(_) => BitSize::Integer(IntegerBitSize::U8),
            MemoryValue::U16(_) => BitSize::Integer(IntegerBitSize::U16),
            MemoryValue::U32(_) => BitSize::Integer(IntegerBitSize::U32),
            MemoryValue::U64(_) => BitSize::Integer(IntegerBitSize::U64),
            MemoryValue::U128(_) => BitSize::Integer(IntegerBitSize::U128),
        }
    }

    /// Expects a `U32` value and converts it into `usize`, otherwise panics.
    ///
    /// Primarily a convenience method for using values in memory operations as pointers, sizes and offsets.
    pub fn to_u32(&self) -> u32 {
        match self {
            MemoryValue::U32(value) => *value,
            other => panic!("value is not typed as Brillig usize: {other}"),
        }
    }
}

impl<F: AcirField> MemoryValue<F> {
    /// Builds a memory value from a field element, either field or integer type.
    ///
    /// If the bit size indicates an integer type, the value is downcast to fit into the specified size.
    pub fn new_from_field(value: F, bit_size: BitSize) -> Self {
        if let BitSize::Integer(bit_size) = bit_size {
            MemoryValue::new_integer(value.to_u128(), bit_size)
        } else {
            MemoryValue::new_field(value)
        }
    }

    /// Builds a memory value from a field element, checking that the value is within the bit size,
    /// otherwise returns `None`.
    pub fn new_checked(value: F, bit_size: BitSize) -> Option<Self> {
        if let BitSize::Integer(bit_size) = bit_size
            && value.num_bits() > bit_size.into()
        {
            return None;
        }

        Some(MemoryValue::new_from_field(value, bit_size))
    }

    /// Converts the memory value to a field element, independent of its type.
    pub fn to_field(&self) -> F {
        match self {
            MemoryValue::Field(value) => *value,
            MemoryValue::U1(value) => F::from(*value),
            MemoryValue::U8(value) => F::from(u128::from(*value)),
            MemoryValue::U16(value) => F::from(u128::from(*value)),
            MemoryValue::U32(value) => F::from(u128::from(*value)),
            MemoryValue::U64(value) => F::from(u128::from(*value)),
            MemoryValue::U128(value) => F::from(*value),
        }
    }

    /// Converts the memory value to U128, if the value is an integer.
    pub fn to_u128(&self) -> Result<u128, MemoryTypeError> {
        match self {
            MemoryValue::Field(..) => Err(MemoryTypeError::NotAnInteger),
            MemoryValue::U1(value) => Ok(u128::from(*value)),
            MemoryValue::U8(value) => Ok(u128::from(*value)),
            MemoryValue::U16(value) => Ok(u128::from(*value)),
            MemoryValue::U32(value) => Ok(u128::from(*value)),
            MemoryValue::U64(value) => Ok(u128::from(*value)),
            MemoryValue::U128(value) => Ok(*value),
        }
    }

    /// Extracts the field element from the memory value, if it is typed as field element.
    pub fn expect_field(self) -> Result<F, MemoryTypeError> {
        if let MemoryValue::Field(field) = self {
            Ok(field)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: F::max_num_bits(),
            })
        }
    }
    pub(crate) fn expect_u1(self) -> Result<bool, MemoryTypeError> {
        if let MemoryValue::U1(value) = self {
            Ok(value)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: 1,
            })
        }
    }

    pub(crate) fn expect_u8(self) -> Result<u8, MemoryTypeError> {
        if let MemoryValue::U8(value) = self {
            Ok(value)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: 8,
            })
        }
    }

    pub(crate) fn expect_u16(self) -> Result<u16, MemoryTypeError> {
        if let MemoryValue::U16(value) = self {
            Ok(value)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: 16,
            })
        }
    }

    pub(crate) fn expect_u32(self) -> Result<u32, MemoryTypeError> {
        if let MemoryValue::U32(value) = self {
            Ok(value)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: 32,
            })
        }
    }

    pub(crate) fn expect_u64(self) -> Result<u64, MemoryTypeError> {
        if let MemoryValue::U64(value) = self {
            Ok(value)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: 64,
            })
        }
    }

    pub(crate) fn expect_u128(self) -> Result<u128, MemoryTypeError> {
        if let MemoryValue::U128(value) = self {
            Ok(value)
        } else {
            Err(MemoryTypeError::MismatchedBitSize {
                value_bit_size: self.bit_size().to_u32::<F>(),
                expected_bit_size: 128,
            })
        }
    }
}

impl<F: std::fmt::Display> std::fmt::Display for MemoryValue<F> {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
        match self {
            MemoryValue::Field(value) => write!(f, "{value}: field"),
            MemoryValue::U1(value) => write!(f, "{value}: u1"),
            MemoryValue::U8(value) => write!(f, "{value}: u8"),
            MemoryValue::U16(value) => write!(f, "{value}: u16"),
            MemoryValue::U32(value) => write!(f, "{value}: u32"),
            MemoryValue::U64(value) => write!(f, "{value}: u64"),
            MemoryValue::U128(value) => write!(f, "{value}: u128"),
        }
    }
}

impl<F: AcirField> Default for MemoryValue<F> {
    fn default() -> Self {
        MemoryValue::new_field(F::zero())
    }
}

impl<F: AcirField> From<bool> for MemoryValue<F> {
    fn from(value: bool) -> Self {
        MemoryValue::U1(value)
    }
}

impl<F: AcirField> From<u8> for MemoryValue<F> {
    fn from(value: u8) -> Self {
        MemoryValue::U8(value)
    }
}

impl<F: AcirField> From<u32> for MemoryValue<F> {
    fn from(value: u32) -> Self {
        MemoryValue::U32(value)
    }
}

impl<F: AcirField> From<u64> for MemoryValue<F> {
    fn from(value: u64) -> Self {
        MemoryValue::U64(value)
    }
}

impl<F: AcirField> From<u128> for MemoryValue<F> {
    fn from(value: u128) -> Self {
        MemoryValue::U128(value)
    }
}

impl<F: AcirField> TryFrom<MemoryValue<F>> for bool {
    type Error = MemoryTypeError;

    fn try_from(memory_value: MemoryValue<F>) -> Result<Self, Self::Error> {
        memory_value.expect_u1()
    }
}

impl<F: AcirField> TryFrom<MemoryValue<F>> for u8 {
    type Error = MemoryTypeError;

    fn try_from(memory_value: MemoryValue<F>) -> Result<Self, Self::Error> {
        memory_value.expect_u8()
    }
}

impl<F: AcirField> TryFrom<MemoryValue<F>> for u32 {
    type Error = MemoryTypeError;

    fn try_from(memory_value: MemoryValue<F>) -> Result<Self, Self::Error> {
        memory_value.expect_u32()
    }
}

impl<F: AcirField> TryFrom<MemoryValue<F>> for u64 {
    type Error = MemoryTypeError;

    fn try_from(memory_value: MemoryValue<F>) -> Result<Self, Self::Error> {
        memory_value.expect_u64()
    }
}

impl<F: AcirField> TryFrom<MemoryValue<F>> for u128 {
    type Error = MemoryTypeError;

    fn try_from(memory_value: MemoryValue<F>) -> Result<Self, Self::Error> {
        memory_value.expect_u128()
    }
}
/// The VM's memory.
///
/// Memory is internally represented as a vector of values.
/// We grow the memory when values past the end are set, extending with 0s.
///
/// # Capacity Limits
///
/// The inner `Vec` is subject to Rust's allocator limit of `isize::MAX` bytes.
/// This means:
/// - On 64-bit: Practical limit is available RAM (~200 GB for full u32 range)
/// - On 32-bit: Hard limit of ~44 million addressable slots
///
/// Exceeding these limits will cause a panic with "capacity overflow".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Memory<F> {
    // Internal memory representation
    inner: Vec<MemoryValue<F>>,
    /// Cached stack pointer to avoid a memory read + enum match on every
    /// relative address resolution.
    ///
    /// The canonical value lives in memory slot [`STACK_POINTER_ADDRESS`]
    /// and must remain there for downstream ZK VM proving. We mirror it here
    /// because [`Self::resolve`] is called on every memory access
    /// with a relative address. Updated on writes to slot [`STACK_POINTER_ADDRESS`]
    /// which are more rare than reads.
    stack_pointer: u32,
}

impl<F> Default for Memory<F> {
    fn default() -> Self {
        Self { inner: Vec::new(), stack_pointer: STACK_POINTER_ADDRESS.to_u32() }
    }
}

impl<F: AcirField> Memory<F> {
    /// Resolve an address to either:
    /// * itself, if it's a direct address, or
    /// * the cached stack pointer plus the offset, if it's relative.
    ///
    /// Returns a memory slot index.
    fn resolve(&self, address: MemoryAddress) -> u32 {
        match address {
            MemoryAddress::Direct(address) => address,
            MemoryAddress::Relative(offset) => {
                self.stack_pointer.checked_add(offset).expect("stack pointer offset overflow")
            }
        }
    }

    /// Reads the numeric value at the address.
    ///
    /// If the address is beyond the size of memory, a default value is returned.
    pub fn read(&self, address: MemoryAddress) -> MemoryValue<F> {
        let resolved_addr = assert_usize(self.resolve(address));
        self.inner.get(resolved_addr).copied().unwrap_or_default()
    }

    /// Reads the value at the address and returns it as a direct memory address,
    /// without dereferencing the pointer itself to a numeric value.
    pub fn read_ref(&self, ptr: MemoryAddress) -> MemoryAddress {
        let resolved = assert_usize(self.resolve(ptr));
        if resolved >= self.inner.len() {
            panic!(
                "read_ref: address {ptr:?} (resolved to {resolved}) is out of bounds (memory size: {})",
                self.inner.len()
            );
        }
        let value = self.inner[resolved];
        let MemoryValue::U32(addr) = value else {
            panic!(
                "read_ref: expected a U32 pointer at address {ptr:?}, but found {value} ({})",
                value.bit_size()
            );
        };
        MemoryAddress::direct(addr)
    }

    /// Sets `ptr` to point at `address`.
    pub fn write_ref(&mut self, ptr: MemoryAddress, address: MemoryAddress) {
        self.write(ptr, MemoryValue::from(address.to_u32()));
    }

    /// Read a contiguous vector of memory starting at `address`, up to `len` slots.
    ///
    /// Panics if the end index is beyond the size of the memory.
    pub fn read_slice(&self, address: MemoryAddress, len: usize) -> &[MemoryValue<F>] {
        // Allows to read a vector of uninitialized memory if the length is zero.
        // Ideally we'd be able to read uninitialized memory in general (as read does)
        // but that's not possible if we want to return a vector instead of owned data.
        if len == 0 {
            return &[];
        }
        let resolved_addr = assert_usize(self.resolve(address));
        let end = resolved_addr.checked_add(len).expect("read_slice: address + len overflows");
        assert!(
            end <= self.inner.len(),
            "read_slice: out of bounds — reading {len} elements from address {resolved_addr} \
             exceeds memory size {}. Callers should validate sizes before calling read_slice.",
            self.inner.len()
        );
        &self.inner[resolved_addr..end]
    }

    /// Sets the value at `address` to `value`
    pub fn write(&mut self, address: MemoryAddress, value: MemoryValue<F>) {
        let resolved_addr = assert_usize(self.resolve(address));
        // Saturate avoids errors, and leave them to `resize_to_fit`
        self.resize_to_fit(resolved_addr.saturating_add(1));
        self.inner[resolved_addr] = value;
        if address == STACK_POINTER_ADDRESS
            && let MemoryValue::U32(sp) = value
        {
            self.stack_pointer = sp;
        }
    }

    /// Increase the size of memory fit `size` elements, or the current length, whichever is bigger.
    ///
    /// # Panics
    ///
    /// Panics if `size` exceeds [`MAX_MEMORY_SIZE`].
    fn resize_to_fit(&mut self, size: usize) {
        assert!(
            size <= MAX_MEMORY_SIZE,
            "Memory address space exceeded: requested {size} slots, maximum is {MAX_MEMORY_SIZE} (i32::MAX)"
        );
        // Calculate new memory size
        let new_size = std::cmp::max(self.inner.len(), size);
        // Expand memory to new size with default values if needed
        self.inner.resize(new_size, MemoryValue::default());
    }

    /// Sets the values after `address` to `values`
    pub fn write_slice(&mut self, address: MemoryAddress, values: &[MemoryValue<F>]) {
        let resolved_addr = assert_usize(self.resolve(address));
        let end_addr = resolved_addr + values.len();
        self.resize_to_fit(end_addr);
        self.inner[resolved_addr..end_addr].copy_from_slice(values);
        if address == STACK_POINTER_ADDRESS
            && let Some(MemoryValue::U32(sp)) = values.first()
        {
            self.stack_pointer = *sp;
        }
    }

    /// Returns the number of memory slots currently allocated.
    pub(crate) fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns the values of the memory
    pub fn values(&self) -> &[MemoryValue<F>] {
        &self.inner
    }
}

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

    #[test]
    fn direct_write_and_read() {
        let mut memory = Memory::<FieldElement>::default();
        let addr = MemoryAddress::direct(5);

        memory.write(addr, MemoryValue::U32(42));
        assert_eq!(memory.read(addr).to_u128().unwrap(), 42);
    }

    #[test]
    fn relative_write_and_read() {
        let mut memory = Memory::<FieldElement>::default();
        // Stack pointer = 10
        memory.write(MemoryAddress::direct(0), MemoryValue::U32(10));

        let addr = MemoryAddress::Relative(5);
        memory.write(addr, MemoryValue::U32(42));
        assert_eq!(memory.read(addr).to_u128().unwrap(), 42);

        let resolved_addr = memory.resolve(addr);
        // Stack pointer + offset
        // 10 + 5 = 15
        assert_eq!(resolved_addr, 15);
        assert_eq!(memory.values()[assert_usize(resolved_addr)].to_u128().unwrap(), 42);
    }

    #[test]
    fn memory_growth() {
        let mut memory = Memory::<FieldElement>::default();
        let addr = MemoryAddress::direct(10);

        memory.write(addr, MemoryValue::U32(123));

        let mut expected = vec![MemoryValue::default(); 10];
        expected.push(MemoryValue::U32(123));

        assert_eq!(memory.values(), &expected);
    }

    #[test]
    fn resize_to_fit_grows_memory() {
        let mut memory = Memory::<FieldElement>::default();
        memory.resize_to_fit(15);

        assert_eq!(memory.values().len(), 15);
        assert!(memory.values().iter().all(|v| *v == MemoryValue::default()));
    }

    #[test]
    fn write_and_read_slice() {
        let mut memory = Memory::<FieldElement>::default();
        // [1, 2, 3, 4, 5]
        let values: Vec<_> = (1..=5).map(MemoryValue::U32).collect();

        // Write at an address > 0 to show resizing
        memory.write_slice(MemoryAddress::direct(2), &values);
        assert_eq!(
            memory
                .read_slice(MemoryAddress::direct(2), 3)
                .iter()
                .map(|v| v.to_u128().unwrap())
                .collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
        assert_eq!(
            memory
                .read_slice(MemoryAddress::direct(5), 2)
                .iter()
                .map(|v| v.to_u128().unwrap())
                .collect::<Vec<_>>(),
            vec![4, 5]
        );
        let zero_field = FieldElement::zero();
        assert_eq!(
            memory
                .read_slice(MemoryAddress::direct(0), 2)
                .iter()
                .map(|v| v.to_field())
                .collect::<Vec<_>>(),
            vec![zero_field, zero_field]
        );
        assert_eq!(
            memory
                .read_slice(MemoryAddress::direct(2), 5)
                .iter()
                .map(|v| v.to_u128().unwrap())
                .collect::<Vec<_>>(),
            vec![1, 2, 3, 4, 5]
        );
    }

    #[test]
    fn read_ref_returns_expected_address_and_reads_slice() {
        let mut memory = Memory::<FieldElement>::default();

        // Imagine we have a heap array starting at address 10
        let heap_start = MemoryAddress::direct(10);
        // [1, 2, 3]
        let values: Vec<_> = (1..=3).map(MemoryValue::U32).collect();
        memory.write_slice(heap_start, &values);

        let array_pointer = MemoryAddress::direct(1);
        // Store a pointer to that array at address 1 (after the stack pointer)
        memory.write(array_pointer, MemoryValue::U32(10));

        // `read_ref` should read that pointer and returns MemoryAddress::direct(10)
        let array_start = memory.read_ref(array_pointer);
        assert_eq!(array_start, MemoryAddress::direct(10));

        // Use that reference to read the 3 element array
        let got_slice = memory.read_slice(array_start, 3);
        assert_eq!(got_slice, values);
    }

    #[test]
    fn zero_length_slice() {
        let memory = Memory::<FieldElement>::default();
        assert_eq!(memory.read_slice(MemoryAddress::direct(20), 0), &[]);
    }

    #[test]
    fn read_from_non_existent_memory() {
        let memory = Memory::<FieldElement>::default();
        let result = memory.read(MemoryAddress::direct(20));
        // `Memory::read` returns zero at out of bounds indices
        assert!(result.to_field().is_zero());
    }

    #[test]
    #[should_panic(expected = "read_slice: out of bounds")]
    fn read_vector_from_non_existent_memory() {
        let memory = Memory::<FieldElement>::default();
        let _ = memory.read_slice(MemoryAddress::direct(20), 10);
    }

    #[test]
    #[should_panic(expected = "Memory address space exceeded")]
    fn resize_to_fit_panics_when_exceeding_max_memory_size() {
        let mut memory = Memory::<FieldElement>::default();
        // Attempting to resize beyond i32::MAX should panic
        memory.resize_to_fit(MAX_MEMORY_SIZE + 1);
    }

    #[test_case(IntegerBitSize::U1, 2)]
    #[test_case(IntegerBitSize::U8, 256)]
    #[test_case(IntegerBitSize::U16, u128::from(u16::MAX) + 1)]
    #[test_case(IntegerBitSize::U32, u128::from(u32::MAX) + 1)]
    #[test_case(IntegerBitSize::U64, u128::from(u64::MAX) + 1)]
    #[should_panic(expected = "range")]
    fn memory_value_new_integer_out_of_range(bit_size: IntegerBitSize, value: u128) {
        let _ = MemoryValue::<FieldElement>::new_integer(value, bit_size);
    }

    #[test]
    #[should_panic = "stack pointer offset overflow"]
    fn memory_resolve_overflow() {
        let mut memory = Memory::<FieldElement>::default();
        memory.write(STACK_POINTER_ADDRESS, MemoryValue::from(u32::MAX - 10));
        let addr = MemoryAddress::relative(20);
        let _wrap = memory.resolve(addr);
    }
}