@@ -22,6 +22,7 @@ pub use self::{
2222 ty:: { MemoryType , MemoryTypeBuilder } ,
2323} ;
2424use crate :: { Fuel , FuelError , ResourceLimiterRef } ;
25+ use core:: ops:: Range ;
2526
2627#[ cfg( feature = "simd" ) ]
2728pub use self :: access:: ExtendInto ;
@@ -278,17 +279,25 @@ impl Memory {
278279 self . bytes . len
279280 }
280281
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+
281290 /// Reads `n` bytes from `memory[offset..offset+n]` into `buffer`
282291 /// where `n` is the length of `buffer`.
283292 ///
284293 /// # Errors
285294 ///
286295 /// If this operation accesses out of bounds linear memory.
287296 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 ( ) ) ? ;
289298 let slice = self
290299 . data ( )
291- . get ( offset.. ( offset + len_buffer ) )
300+ . get ( span )
292301 . ok_or ( MemoryError :: OutOfBoundsAccess ) ?;
293302 buffer. copy_from_slice ( slice) ;
294303 Ok ( ( ) )
@@ -301,10 +310,10 @@ impl Memory {
301310 ///
302311 /// If this operation accesses out of bounds linear memory.
303312 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 ( ) ) ? ;
305314 let slice = self
306315 . data_mut ( )
307- . get_mut ( offset.. ( offset + len_buffer ) )
316+ . get_mut ( span )
308317 . ok_or ( MemoryError :: OutOfBoundsAccess ) ?;
309318 slice. copy_from_slice ( buffer) ;
310319 Ok ( ( ) )
0 commit comments