wasi_virt_layer_cli/wasm_stream/tracker.rs
1use std::collections::HashMap;
2
3/// Tracks indices for a specific Wasm entity space (e.g., functions, memories, globals, types).
4/// When we inject new elements (like VFS imports or new globals), the original indices
5/// in the Wasm file shift. This tracker maps original indices to new indices.
6#[derive(Debug, Default)]
7pub struct IndexTracker {
8 /// Number of elements that existed in the original module.
9 pub original_count: u32,
10 /// Number of injected elements so far.
11 pub injected_count: u32,
12 /// Maps an original index to its new index if it was explicitly remapped.
13 /// If not in the map, the new index is `original_index + injected_count_before_it`.
14 /// For simplicity, we can assume all injections happen BEFORE existing elements
15 /// (e.g. injecting imports pushes all internal functions up), or at the END.
16 /// Let's support both.
17 pub shift_offset: u32,
18 /// Explicit mapping of original index to new index.
19 pub explicit_map: HashMap<u32, u32>,
20}
21
22impl IndexTracker {
23 /// Creates a new index tracker.
24 pub fn new() -> Self {
25 Self::default()
26 }
27
28 /// Mark that we've seen `count` original elements.
29 pub fn set_original_count(&mut self, count: u32) {
30 self.original_count = count;
31 }
32
33 /// Register a new injected element. Returns its new assigned index.
34 pub fn inject(&mut self) -> u32 {
35 let new_idx = self.original_count + self.injected_count;
36 self.injected_count += 1;
37 new_idx
38 }
39
40 /// Remap an original index to its new index.
41 pub fn remap(&self, original_index: u32) -> u32 {
42 if let Some(&new_idx) = self.explicit_map.get(&original_index) {
43 new_idx
44 } else {
45 original_index + self.shift_offset
46 }
47 }
48}