foundry_evm_core/
state_snapshot.rs

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