Repository: apple/swift-nio
File: Sources/NIOCore/ByteBuffer-core.swift (Swift)

Code before:
    @discardableResult public mutating func discardReadBytes() -> Bool {
        guard self._readerIndex > 0 else {
            return false
        }

        if self._readerIndex == self._writerIndex {
            // If the whole buffer was consumed we can just reset the readerIndex and writerIndex to 0 and move on.
            self._moveWriterIndex(to: 0)
            self._moveReaderIndex(to: 0)
            return true
        }

        if isKnownUniquelyReferenced(&self._storage) {
            self._storage.bytes.advanced(by: Int(self._slice.lowerBound))
                .copyMemory(from: self._storage.bytes.advanced(by: Int(self._slice.lowerBound + self._readerIndex)),
                            byteCount: self.readableBytes)
            let indexShift = self._readerIndex
            self._moveReaderIndex(to: 0)
            self._moveWriterIndex(to: self._writerIndex - indexShift)
        } else {
            self._copyStorageAndRebase(extraCapacity: 0, resetIndices: true)
        }
        return true
    }
    
    /// Shrinks the buffers capacity to a `desiredCapacity` without altering readably bytes.
    ///
    /// - Parameter desiredCapacity: The desired capacity for the buffers capacity to be shrunken to
    /// - Returns: Bool indicating whether the buffer capacity has been shrunk to the desiredCapacity.
    @inlinable
    @discardableResult public mutating func shrinkBufferCapacity(to desiredCapacity: Int) -> Bool {
        guard desiredCapacity < capacity, desiredCapacity > readableBytes else {
            return false
        }
        
        let shrunkenCapacity = _toCapacity(desiredCapacity)
        self._storage = self._storage.reallocSlice(self._slice.lowerBound..<self._slice.lowerBound + shrunkenCapacity, capacity: shrunkenCapacity)
        self._slice = self._storage.fullSlice

        return true
    }

    /// The reader index or the number of bytes previously read from this `ByteBuffer`. `readerIndex` is `0` for a
    /// newly allocated `ByteBuffer`.
    @inlinable
    public var readerIndex: Int {
        return Int(self._readerIndex)
    }

    /// The write index or the number of bytes previously written to this `ByteBuffer`. `writerIndex` is `0` for a
    /// newly allocated `ByteBuffer`.

Review comment (suggestion):
Let's elaborate on this by explaining the actual algorithm, just to save people from looking at the code. Something like:

```
/// The `ByteBuffer` will successfully be shrunk if the requested capacity is less than the current capacity, and the requested capacity is more than the number of readable bytes in the buffer. If either condition is not true, the buffer will not be shrunk.
```

Code after:
    /// - returns: A `ByteBuffer` containing the selected bytes as readable bytes or `nil` if the selected bytes were
    ///            not readable in the initial `ByteBuffer`.
    @inlinable
    public func getSlice(at index: Int, length: Int) -> ByteBuffer? {
        self.getSlice_inlineAlways(at: index, length: length)
    }

    @inline(__always)
    @inlinable
    internal func getSlice_inlineAlways(at index: Int, length: Int) -> ByteBuffer? {
        guard
            index >= 0 && length >= 0 && index >= self.readerIndex && length <= self.writerIndex
                && index <= self.writerIndex &- length
        else {
            return nil
        }
        let index = _toIndex(index)
        let length = _toCapacity(length)

        // The arithmetic below is safe because:
        // 1. maximum `writerIndex` <= self._slice.count (see `_moveWriterIndex`)
        // 2. `self._slice.lowerBound + self._slice.count` is always safe (because it's `self._slice.upperBound`)
        // 3. `index` is inside the range `self.readerIndex ... self.writerIndex` (the `guard` above)
        //
        // This means that the largest number that `index` could have is equal to
        // `self._slice_.upperBound = self._slice.lowerBound + self._slice.count` and that
        // is guaranteed to be expressible as a `UInt32` (because it's actually stored as such).
        let sliceStartIndex: UInt32 = self._slice.lowerBound + index

        guard sliceStartIndex <= ByteBuffer.Slice.maxSupportedLowerBound else {
            // the slice's begin is past the maximum supported slice begin value (16 MiB) so the only option we have
            // is copy the slice into a fresh buffer. The slice begin will then be at index 0.
            return self._copyIntoByteBufferWithSliceIndex0_slowPath(index: index, length: length)
        }
        var new = self
        assert(sliceStartIndex == self._slice.lowerBound &+ index)

        // - The arithmetic below is safe because
        //   1. `writerIndex` <= `self._slice.count` (see `_moveWriterIndex`)
        //   2. `length` <= `self.writerIndex` (see `guard`s)
        //   3. `sliceStartIndex` + `self._slice.count` is always safe (because that's `self._slice.upperBound`.
        // - The range construction is safe because `length` >= 0 (see `guard` at the beginning of the function).
        new._slice = _ByteBufferSlice(
            Range(
                uncheckedBounds: (
                    lower: sliceStartIndex,
                    upper: sliceStartIndex &+ length
                )
            )
        )
        new._moveReaderIndex(to: 0)