diff --git a/Sources/NIO/ByteBuffer-core.swift b/Sources/NIO/ByteBuffer-core.swift index 730d086b1c5..0507cfc6c9e 100644 --- a/Sources/NIO/ByteBuffer-core.swift +++ b/Sources/NIO/ByteBuffer-core.swift @@ -383,11 +383,11 @@ public struct ByteBuffer { } var base = ensureCapacityAndReturnStorageBase(capacity: underestimatedByteCount) - var idx = 0 - for b in bytes { - if idx >= underestimatedByteCount { - base = ensureCapacityAndReturnStorageBase(capacity: idx + 1) - } + var (iterator, idx) = UnsafeMutableBufferPointer(start: base, count: underestimatedByteCount).initialize(from: bytes) + assert(idx == underestimatedByteCount) + while let b = iterator.next() { + assert(S.self != String.UTF8View.self) + base = ensureCapacityAndReturnStorageBase(capacity: idx + 1) base[idx] = b idx += 1 } diff --git a/Tests/NIOTests/ByteBufferTest.swift b/Tests/NIOTests/ByteBufferTest.swift index e448baf67b2..61e59cde539 100644 --- a/Tests/NIOTests/ByteBufferTest.swift +++ b/Tests/NIOTests/ByteBufferTest.swift @@ -1165,7 +1165,7 @@ class ByteBufferTest: XCTestCase { func testUnderestimatingSequenceWorks() throws { struct UnderestimatingSequence: Sequence { - let storage: [UInt8] = Array(0..<12) + let storage: [UInt8] = Array(0...255) typealias Element = UInt8 public var indices: CountableRange { @@ -1187,15 +1187,15 @@ class ByteBufferTest: XCTestCase { buf = self.allocator.buffer(capacity: 4) buf.clear() buf.write(bytes: UnderestimatingSequence()) - XCTAssertEqual(12, buf.readableBytes) - for i in 0..<12 { + XCTAssertEqual(256, buf.readableBytes) + for i in 0..<256 { let actual = Int(buf.readInteger()! as UInt8) XCTAssertEqual(i, actual) } buf = self.allocator.buffer(capacity: 4) buf.set(bytes: UnderestimatingSequence(), at: 0) XCTAssertEqual(0, buf.readableBytes) - for i in 0..<12 { + for i in 0..<256 { let actual = Int(buf.getInteger(at: i)! as UInt8) XCTAssertEqual(i, actual) }