@@ -18,6 +18,9 @@ pub struct SharedMemory {
18
18
checkpoints : Vec < usize > ,
19
19
/// How much memory has been used in the current context
20
20
current_len : usize ,
21
+ /// Memory limit. See [`crate::CfgEnv`].
22
+ #[ cfg( feature = "memory_limit" ) ]
23
+ pub memory_limit : u64 ,
21
24
}
22
25
23
26
impl fmt:: Debug for SharedMemory {
@@ -45,9 +48,29 @@ impl SharedMemory {
45
48
data : Vec :: with_capacity ( 4 * 1024 ) , // from evmone
46
49
checkpoints : Vec :: with_capacity ( 32 ) ,
47
50
current_len : 0 ,
51
+ #[ cfg( feature = "memory_limit" ) ]
52
+ memory_limit : u64:: MAX ,
48
53
}
49
54
}
50
55
56
+ /// Allocate memory to be shared between calls, with `memory_limit`
57
+ /// as upper bound for allocation size.
58
+ /// Initial capacity is 4KiB which is expanded if needed
59
+ #[ cfg( feature = "memory_limit" ) ]
60
+ pub fn new_with_memory_limit ( memory_limit : u64 ) -> Self {
61
+ Self {
62
+ memory_limit,
63
+ ..Self :: new ( )
64
+ }
65
+ }
66
+
67
+ /// Returns true if the `new_size` for the current context memory will
68
+ /// make the shared buffer length exceed the `memory_limit`
69
+ #[ cfg( feature = "memory_limit" ) ]
70
+ pub fn limit_reached ( & self , new_size : usize ) -> bool {
71
+ ( self . last_checkpoint ( ) + new_size) as u64 > self . memory_limit
72
+ }
73
+
51
74
/// Prepares the shared memory for a new context
52
75
pub fn new_context_memory ( & mut self ) {
53
76
let base_offset = self . last_checkpoint ( ) ;
@@ -221,7 +244,7 @@ impl SharedMemory {
221
244
/// Get the last memory checkpoint
222
245
#[ inline( always) ]
223
246
fn last_checkpoint ( & self ) -> usize {
224
- * self . checkpoints . last ( ) . unwrap_or ( & 0 )
247
+ self . checkpoints . last ( ) . cloned ( ) . unwrap_or_default ( )
225
248
}
226
249
}
227
250
0 commit comments