diff --git a/Lagrange.Core/Utility/Binary/BinaryPacket.cs b/Lagrange.Core/Utility/Binary/BinaryPacket.cs index 34c3e827b..89a36a3f5 100644 --- a/Lagrange.Core/Utility/Binary/BinaryPacket.cs +++ b/Lagrange.Core/Utility/Binary/BinaryPacket.cs @@ -292,12 +292,17 @@ private void Increment(int count) [MethodImpl(MethodImplOptions.NoInlining)] // NoInlining is used to prevent the method from being inlined as it is not used frequently private void GrowSize(int additional) { - while (_offset + additional > _capacity) _capacity *= 2; - _bytesToReturnToPool = ArrayPool.Shared.Rent(_capacity); + int requested = _offset + additional; + int desired = (int)BitOperations.RoundUpToPowerOf2((uint)requested); + int capacity = desired > requested ? desired : requested; - _span[.._offset].CopyTo(_bytesToReturnToPool.AsSpan()); + var rent = ArrayPool.Shared.Rent(capacity); + _span[.._offset].CopyTo(rent.AsSpan()); + if (_bytesToReturnToPool != null) ArrayPool.Shared.Return(_bytesToReturnToPool); + _capacity = capacity; + _bytesToReturnToPool = rent; - _span = _bytesToReturnToPool.AsSpan(); + _span = rent.AsSpan(); _buffer = ref Unsafe.Add(ref MemoryMarshal.GetReference(_span), _offset); }