mirror of
https://github.com/apple/swift-nio
synced 2026-11-24 04:37:54 +00:00
Motivation: ByteBuffer uses a synthetic UInt24 as the lower bound of the slice of memory that it can access. This necessitates a slow path when we create slices of ByteBuffers that would force the lower bound to be larger than a UInt24. This slow path has a bunch of math within it, and it turns out that some of it is invalid. This means in rare cases slicing a ByteBuffer can cause a crash. That's not great: the code should only crash if we broke an internal invariant, not because we did some invalid math. In particular, the relevant check is calculating the upper bound of the storage to be copied. This was: ``` min(storageRebaseAmount + _toCapacity(self._slice.count), self._slice.upperBound, storageRebaseAmount + capacity) ``` In this case, `storageRebaseAmount` is either `self._slice.lowerBound` or `self._slice.lowerBound + self._readerIndex`: that is, `storageRebaseAmount >= self._slice.lowerBound`. Given that `self._slice.count == self._slice.upperBound - self._slice.lowerBound`, we know that `storageRebaseAmount + self._slice.count` is always strictly greater than or equal to `self._slice.upperBound`. Calculating this is unnecessary. Unfortunately, it can also overflow: if `self._slice.upperBound + self._readerIndex` is greater than UInt32 then this will crash. Note that the other math, `storageRebaseAmount + capacity`, has been kept. `capacity` is always computed by us and this should only ever overflow if we are increasing the size of the buffer past UInt32.max, which we cannot handle anyway. Modifications: - Restructured and heavily commented _copyStorageAndRebase. - Removed the redundant crashing check. Result: Less trapping!