foundry_evm_core/
state_snapshot.rs

1//! Support for snapshotting different states
2
3use alloy_primitives::{U256, map::HashMap};
4
5/// Represents all state snapshots
6#[derive(Clone, Debug)]
7pub struct StateSnapshots<T> {
8    id: U256,
9    state_snapshots: HashMap<U256, T>,
10}
11
12impl<T> StateSnapshots<T> {
13    fn next_id(&mut self) -> U256 {
14        let id = self.id;
15        self.id = id.saturating_add(U256::from(1));
16        id
17    }
18
19    /// Returns the state snapshot with the given id `id`
20    pub fn get(&self, id: U256) -> Option<&T> {
21        self.state_snapshots.get(&id)
22    }
23
24    /// Removes the state snapshot with the given `id`.
25    ///
26    /// This will also remove any state snapshots taken after the state snapshot with the `id`.
27    /// e.g.: reverting to id 1 will delete snapshots with ids 1, 2, 3, etc.)
28    pub fn remove(&mut self, id: U256) -> Option<T> {
29        let snapshot_state = self.state_snapshots.remove(&id);
30
31        // Revert all state snapshots taken after the state snapshot with the `id`
32        let mut to_revert = id + U256::from(1);
33        while to_revert < self.id {
34            self.state_snapshots.remove(&to_revert);
35            to_revert += U256::from(1);
36        }
37
38        snapshot_state
39    }
40
41    /// Removes all state snapshots.
42    pub fn clear(&mut self) {
43        self.state_snapshots.clear();
44    }
45
46    /// Removes the state snapshot with the given `id`.
47    ///
48    /// Does not remove state snapshots after it.
49    pub fn remove_at(&mut self, id: U256) -> Option<T> {
50        self.state_snapshots.remove(&id)
51    }
52
53    /// Inserts the new state snapshot and returns the id.
54    pub fn insert(&mut self, state_snapshot: T) -> U256 {
55        let id = self.next_id();
56        self.state_snapshots.insert(id, state_snapshot);
57        id
58    }
59
60    /// Inserts the new state snapshot at the given `id`.
61    ///
62    ///  Does not auto-increment the next `id`.
63    pub fn insert_at(&mut self, state_snapshot: T, id: U256) {
64        self.state_snapshots.insert(id, state_snapshot);
65    }
66}
67
68impl<T> Default for StateSnapshots<T> {
69    fn default() -> Self {
70        Self { id: U256::ZERO, state_snapshots: HashMap::default() }
71    }
72}