0xMiden / 0xMiden/protocol

perf(protocol): eliminate temporary heap allocation and double serialization in AccountCode::get_size_hint

Ouverte
#3,629 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub
Langage dominant
Rust
Étoiles
132
Forks
167
Merge moyen
1 j 23 h
PR mergées (30 j)
110

Description

### Problem Description

In `crates/miden-protocol/src/account/code/mod.rs` (lines 301–315), `AccountCode::get_size_hint` is implemented by fully serializing the internal `MastForest` into a temporary `Vec` on the heap simply to measure its byte length:

```rust
fn get_size_hint(&self) -> usize {
// TODO: Replace with proper calculation.
let mut mast_forest_target = Vec::new();
self.mast.write_into(&mut mast_forest_target);

// Size of the serialized procedures length.
let u8_size = 0u8.get_size_hint();
let mut size = u8_size + mast_forest_target.len();

for procedure in self.procedures() {
size += procedure.get_size_hint();
}

size
}
```

When `AccountCode::to_bytes()` is called:
1. `Serializable::to_bytes(&self)` calls `self.get_size_hint()` to pre-allocate capacity in the destination vector.
2. `get_size_hint()` allocates a fresh heap buffer, serializes the entire `MastForest`, reads its length, and immediately drops the allocation.
3. `to_bytes` then calls `self.write_into(&mut target)`, serializing the exact same `MastForest` a second time.

This causes redundant heap allocations and duplicate serialization overhead on every `AccountCode` serialization.

### Proposed Solution
- Provide an accurate and non-allocating size estimation for `AccountCode::get_size_hint` based on the procedure count and component structure, avoiding the temporary heap allocation and double serialization.
- Add unit tests verifying `get_size_hint` accuracy against actual `to_bytes().len()`.

I would like to work on this issue.

Guide de contribution

Ouvrir le guide de contribution

Évaluation

Cette issue n'a pas encore été évaluée.

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.