Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions Sources/NIO/ByteBuffer-core.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@milseman I'm assuming String.UTF8View does never underestimate its count, right?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now it is equivalent to count because that's the default behavior and it doesn't override it. That's likely to change at some point (CC @moiseev). But, I think it can give a very good underestimate by just returning the number of code units.

https://bugs.swift.org/browse/SR-7618

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @milseman. I made another PR (#392) to actually remove the assertion because I don't think we win anything having it...

base = ensureCapacityAndReturnStorageBase(capacity: idx + 1)
base[idx] = b
idx += 1
}
Expand Down
8 changes: 4 additions & 4 deletions Tests/NIOTests/ByteBufferTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int> {
Expand All @@ -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)
}
Expand Down