@@ -480,24 +480,32 @@ public int Length
480
480
StringBuilder chunk = FindChunkForIndex ( value ) ;
481
481
if ( chunk != this )
482
482
{
483
- // We crossed a chunk boundary when reducing the Length. We must replace this middle-chunk with a new larger chunk,
484
- // to ensure the original capacity is preserved.
485
-
486
483
// Avoid possible infinite capacity growth. See https://github.com/dotnet/coreclr/pull/16926
487
484
int capacityToPreserve = Math . Min ( Capacity , Math . Max ( Length * 6 / 5 , m_ChunkChars . Length ) ) ;
488
485
int newLen = capacityToPreserve - chunk . m_ChunkOffset ;
489
- char [ ] newArray = new char [ newLen ] ;
490
-
491
- Debug . Assert ( newLen > chunk . m_ChunkChars . Length , "The new chunk should be larger than the one it is replacing." ) ;
492
- Array . Copy ( chunk . m_ChunkChars , 0 , newArray , 0 , chunk . m_ChunkLength ) ;
486
+ if ( newLen > chunk . m_ChunkChars . Length )
487
+ {
488
+ // We crossed a chunk boundary when reducing the Length. We must replace this middle-chunk with a new larger chunk,
489
+ // to ensure the capacity we want is preserved.
490
+ char [ ] newArray = new char [ newLen ] ;
491
+ Array . Copy ( chunk . m_ChunkChars , 0 , newArray , 0 , chunk . m_ChunkLength ) ;
492
+ m_ChunkChars = newArray ;
493
+ }
494
+ else
495
+ {
496
+ // Special case where the capacity we want to keep corresponds exactly to the size of the content.
497
+ // Just take ownership of the array.
498
+ Debug . Assert ( newLen == chunk . m_ChunkChars . Length , "The new chunk should be larger or equal to the one it is replacing." ) ;
499
+ m_ChunkChars = chunk . m_ChunkChars ;
500
+ }
493
501
494
- m_ChunkChars = newArray ;
495
502
m_ChunkPrevious = chunk . m_ChunkPrevious ;
496
503
m_ChunkOffset = chunk . m_ChunkOffset ;
497
504
}
498
505
m_ChunkLength = value - chunk . m_ChunkOffset ;
499
506
AssertInvariants ( ) ;
500
507
}
508
+ Debug . Assert ( Length == value , "Something went wrong setting Length." ) ;
501
509
}
502
510
}
503
511
0 commit comments