diff --git a/Sources/NIO/ByteBuffer-core.swift b/Sources/NIO/ByteBuffer-core.swift index 7c7f9c0de..812139693 100644 --- a/Sources/NIO/ByteBuffer-core.swift +++ b/Sources/NIO/ByteBuffer-core.swift @@ -141,7 +141,7 @@ public struct ByteBuffer { // double the capacity until the requested capacity can be full-filled repeat { newCapacity = newCapacity << 1 - } while newCapacity - index < capacity + } while newCapacity < index || newCapacity - index < capacity self._storage.reallocStorage(capacity: newCapacity) self._slice = _slice.lowerBound..<_slice.lowerBound + newCapacity diff --git a/Tests/NIOTests/ByteBufferTest+XCTest.swift b/Tests/NIOTests/ByteBufferTest+XCTest.swift index efa6894de..ab84d11c3 100644 --- a/Tests/NIOTests/ByteBufferTest+XCTest.swift +++ b/Tests/NIOTests/ByteBufferTest+XCTest.swift @@ -97,6 +97,10 @@ extension ByteBufferTest { ("testWriteForNonContiguousCollections", testWriteForNonContiguousCollections), ("testReadStringOkay", testReadStringOkay), ("testReadStringTooMuch", testReadStringTooMuch), + ("testSetIntegerBeyondCapacity", testSetIntegerBeyondCapacity), + ("testGetIntegerBeyondCapacity", testGetIntegerBeyondCapacity), + ("testSetStringBeyondCapacity", testSetStringBeyondCapacity), + ("testGetStringBeyondCapacity", testGetStringBeyondCapacity), ] } } diff --git a/Tests/NIOTests/ByteBufferTest.swift b/Tests/NIOTests/ByteBufferTest.swift index 8fd823585..444fcce62 100644 --- a/Tests/NIOTests/ByteBufferTest.swift +++ b/Tests/NIOTests/ByteBufferTest.swift @@ -950,4 +950,44 @@ class ByteBufferTest: XCTestCase { XCTAssertEqual("a", buf.readString(length: 1)) } + func testSetIntegerBeyondCapacity() throws { + buf.clear() + buf.changeCapacity(to: 32) + XCTAssertLessThan(buf.capacity, 200) + + buf.set(integer: 17, at: 201) + let i: Int = buf.integer(at: 201)! + XCTAssertEqual(17, i) + XCTAssertGreaterThanOrEqual(buf.capacity, 200 + MemoryLayout.size(ofValue: i)) + } + + func testGetIntegerBeyondCapacity() throws { + buf.clear() + buf.changeCapacity(to: 32) + XCTAssertLessThan(buf.capacity, 200) + + let i: Int? = buf.integer(at: 201) + XCTAssertNil(i) + } + + func testSetStringBeyondCapacity() throws { + buf.clear() + buf.changeCapacity(to: 32) + XCTAssertLessThan(buf.capacity, 200) + + buf.set(string: "HW", at: 201) + let s = buf.string(at: 201, length: 2)! + XCTAssertEqual("HW", s) + XCTAssertGreaterThanOrEqual(buf.capacity, 202) + } + + func testGetStringBeyondCapacity() throws { + buf.clear() + buf.changeCapacity(to: 32) + XCTAssertLessThan(buf.capacity, 200) + + let i: String? = buf.string(at: 201, length: 1) + XCTAssertNil(i) + } + }