@@ -22,6 +22,7 @@ pub use self::{
22
22
ty:: { MemoryType , MemoryTypeBuilder } ,
23
23
} ;
24
24
use crate :: { Fuel , FuelError , ResourceLimiterRef } ;
25
+ use core:: ops:: Range ;
25
26
26
27
#[ cfg( feature = "simd" ) ]
27
28
pub use self :: access:: ExtendInto ;
@@ -278,17 +279,25 @@ impl Memory {
278
279
self . bytes . len
279
280
}
280
281
282
+ /// Returns the index span for the memory access at `start..(start+len)`.
283
+ fn access_span ( start : usize , len : usize ) -> Result < Range < usize > , MemoryError > {
284
+ let Some ( end) = start. checked_add ( len) else {
285
+ return Err ( MemoryError :: OutOfBoundsAccess ) ;
286
+ } ;
287
+ Ok ( start..end)
288
+ }
289
+
281
290
/// Reads `n` bytes from `memory[offset..offset+n]` into `buffer`
282
291
/// where `n` is the length of `buffer`.
283
292
///
284
293
/// # Errors
285
294
///
286
295
/// If this operation accesses out of bounds linear memory.
287
296
pub fn read ( & self , offset : usize , buffer : & mut [ u8 ] ) -> Result < ( ) , MemoryError > {
288
- let len_buffer = buffer. len ( ) ;
297
+ let span = Self :: access_span ( offset , buffer. len ( ) ) ? ;
289
298
let slice = self
290
299
. data ( )
291
- . get ( offset.. ( offset + len_buffer ) )
300
+ . get ( span )
292
301
. ok_or ( MemoryError :: OutOfBoundsAccess ) ?;
293
302
buffer. copy_from_slice ( slice) ;
294
303
Ok ( ( ) )
@@ -301,10 +310,10 @@ impl Memory {
301
310
///
302
311
/// If this operation accesses out of bounds linear memory.
303
312
pub fn write ( & mut self , offset : usize , buffer : & [ u8 ] ) -> Result < ( ) , MemoryError > {
304
- let len_buffer = buffer. len ( ) ;
313
+ let span = Self :: access_span ( offset , buffer. len ( ) ) ? ;
305
314
let slice = self
306
315
. data_mut ( )
307
- . get_mut ( offset.. ( offset + len_buffer ) )
316
+ . get_mut ( span )
308
317
. ok_or ( MemoryError :: OutOfBoundsAccess ) ?;
309
318
slice. copy_from_slice ( buffer) ;
310
319
Ok ( ( ) )
0 commit comments