@@ -282,7 +282,8 @@ public void Push(T item)
282
282
[ MethodImpl ( MethodImplOptions . NoInlining ) ]
283
283
private void PushWithResize ( T item )
284
284
{
285
- Array . Resize ( ref _array , ( _array . Length == 0 ) ? DefaultCapacity : 2 * _array . Length ) ;
285
+ Debug . Assert ( _size == _array . Length ) ;
286
+ EnsureCapacityCore ( _size + 1 ) ;
286
287
_array [ _size ] = item ;
287
288
_version ++ ;
288
289
_size ++ ;
@@ -293,7 +294,7 @@ private void PushWithResize(T item)
293
294
/// If the current capacity of the Stack is less than specified <paramref name="capacity"/>,
294
295
/// the capacity is increased by continuously twice current capacity until it is at least the specified <paramref name="capacity"/>.
295
296
/// </summary>
296
- /// <param name="capacity">The minimum capacity to ensure</param>
297
+ /// <param name="capacity">The minimum capacity to ensure. </param>
297
298
public int EnsureCapacity ( int capacity )
298
299
{
299
300
if ( capacity < 0 )
@@ -303,30 +304,24 @@ public int EnsureCapacity(int capacity)
303
304
304
305
if ( _array . Length < capacity )
305
306
{
306
- int newCapacity = _array . Length == 0 ? DefaultCapacity : _array . Length << 1 ;
307
- while ( ( uint ) newCapacity < capacity )
308
- {
309
- newCapacity <<= 1 ;
310
- }
311
-
312
- // MaxArrayLength is defined in Array.MaxArrayLength and in gchelpers in CoreCLR.
313
- // It represents the maximum number of elements that can be in an array where
314
- // the size of the element is greater than one byte; a separate, slightly larger constant,
315
- // is used when the size of the element is one.
316
- const int MaxArrayLength = 0x7FEFFFFF ;
317
- if ( ( uint ) newCapacity > MaxArrayLength )
318
- {
319
- newCapacity = MaxArrayLength ;
320
- if ( newCapacity < capacity ) newCapacity = capacity ;
321
- }
322
-
323
- Array . Resize ( ref _array , newCapacity ) ;
307
+ EnsureCapacityCore ( capacity ) ;
324
308
_version ++ ;
325
309
}
326
310
327
311
return _array . Length ;
328
312
}
329
313
314
+ private void EnsureCapacityCore ( int capacity )
315
+ {
316
+ Debug . Assert ( _array . Length < capacity ) ;
317
+
318
+ int newcapacity = _array . Length == 0 ? DefaultCapacity : 2 * _array . Length ;
319
+ // ensure min capacity is respected and account for arithmetic overflow
320
+ if ( newcapacity < capacity ) newcapacity = capacity ;
321
+
322
+ Array . Resize ( ref _array , newcapacity ) ;
323
+ }
324
+
330
325
// Copies the Stack to an array, in the same order Pop would return the items.
331
326
public T [ ] ToArray ( )
332
327
{
0 commit comments