Skip to content

Commit ff87d86

Browse files
fix: size dict elements buffer to HashMap capacity, not len (#1646)
When materializing a Felt252Dict value, the elements buffer was arena-allocated with room for `map.len()` slots. The runtime's `dict_get` only grows the buffer once the backing HashMap is full, so a runtime insert of a new key could write one slot past the end of the buffer and corrupt the arena. Allocate the buffer using the HashMap's capacity (read after `reserve`, which usually over-allocates) so there is always room for the runtime to fill every slot the HashMap can hold. Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 1c3473a commit ff87d86

1 file changed

Lines changed: 12 additions & 10 deletions

File tree

src/values.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -370,24 +370,26 @@ impl Value {
370370
let elem_ty = registry.get_type(&info.ty)?;
371371
let elem_layout = elem_ty.layout(registry)?;
372372

373-
// Arena-allocate the elements buffer.
373+
// Arena-allocate the FeltDict struct and register it.
374+
let dict_ptr = crate::runtime::cairo_native__dict_new(
375+
elem_layout.size() as u64,
376+
elem_layout.align() as u64,
377+
);
378+
let dict = &mut *dict_ptr;
379+
dict.mappings.reserve(map.len());
380+
381+
// Arena-allocate the elements buffer. It must be sized to the
382+
// HashMap's capacity (read *after* `reserve`).
383+
let capacity = dict.mappings.capacity();
374384
let elements = if map.is_empty() {
375385
null_mut()
376386
} else {
377387
crate::runtime::cairo_native__arena_alloc(
378-
(elem_layout.pad_to_align().size() * map.len()) as u64,
388+
(elem_layout.pad_to_align().size() * capacity) as u64,
379389
elem_layout.align() as u64,
380390
)
381391
.cast()
382392
};
383-
384-
// Arena-allocate the FeltDict struct and register it.
385-
let dict_ptr = crate::runtime::cairo_native__dict_new(
386-
elem_layout.size() as u64,
387-
elem_layout.align() as u64,
388-
);
389-
let dict = &mut *dict_ptr;
390-
dict.mappings.reserve(map.len());
391393
dict.elements = elements;
392394

393395
for (key, value) in map.iter() {

0 commit comments

Comments
 (0)