@@ -23,6 +23,7 @@ use crate::{
2323} ;
2424use alloc:: vec:: Vec ;
2525use core:: {
26+ cmp,
2627 mem,
2728 ptr:: { self , NonNull } ,
2829 slice,
@@ -419,6 +420,44 @@ impl ValueStack {
419420 }
420421 }
421422
423+ /// Grows the number of cells to `new_len` if the current number is less than `new_len`.
424+ ///
425+ /// Does nothing if the number of cells is already at least `new_len`.
426+ ///
427+ /// # Errors
428+ ///
429+ /// - Returns [`TrapCode::OutOfSystemMemory`] if the machine ran out of memory.
430+ /// - Returns [`TrapCode::StackOverflow`] if this exceeds the stack's predefined limits.
431+ fn grow_if_needed ( & mut self , new_len : usize ) -> Result < ( ) , TrapCode > {
432+ if new_len > self . max_height {
433+ return Err ( TrapCode :: StackOverflow ) ;
434+ }
435+ let capacity = self . cells . capacity ( ) ;
436+ let len = self . cells . len ( ) ;
437+ if new_len > capacity {
438+ debug_assert ! (
439+ self . cells. len( ) <= self . cells. capacity( ) ,
440+ "capacity must always be larger or equal to the actual number of the cells"
441+ ) ;
442+ let additional = new_len - len;
443+ self . cells
444+ . try_reserve ( additional)
445+ . map_err ( |_| TrapCode :: OutOfSystemMemory ) ?;
446+ debug_assert ! (
447+ self . cells. capacity( ) >= new_len,
448+ "capacity must now be at least as large as `new_len` ({new_len}) but found {}" ,
449+ self . cells. capacity( )
450+ ) ;
451+ }
452+ let max_len = cmp:: max ( new_len, len) ;
453+ // Safety: there is no need to initialize the cells since we are operating
454+ // on `UntypedVal` which only has valid bit patterns.
455+ // Note: non-security related initialization of function parameters
456+ // and zero-initialization of function locals happens elsewhere.
457+ unsafe { self . cells . set_len ( max_len) } ;
458+ Ok ( ( ) )
459+ }
460+
422461 /// # Note
423462 ///
424463 /// In the following code, `callee` represents the called host function frame
0 commit comments