Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve ByteBuffer.setSubstring(_:at:) performance #1975

Merged
merged 3 commits into from
Feb 7, 2022
Merged
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
24 changes: 15 additions & 9 deletions Sources/NIOCore/ByteBuffer-aux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,9 @@ extension ByteBuffer {
@discardableResult
@inlinable
public mutating func setString(_ string: String, at index: Int) -> Int {
// Do not implement setString via setSubstring. As of Swift version 5.1.3,
// Substring.UTF8View does not implement withContiguousStorageIfAvailable
// and therefore has no fast access to the backing storage.
// Do not implement setString via setSubstring. Before Swift version 5.3,
// Substring.UTF8View did not implement withContiguousStorageIfAvailable
// and therefore had no fast access to the backing storage.
if let written = string.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
Expand Down Expand Up @@ -236,16 +236,22 @@ extension ByteBuffer {
///
/// - parameters:
/// - substring: The substring to write.
/// - index: The index for the first serilized byte.
/// - index: The index for the first serialized byte.
/// - returns: The number of bytes written
@discardableResult
@inlinable
public mutating func setSubstring(_ substring: Substring, at index: Int) -> Int {
// As of Swift 5.1.3, Substring.UTF8View does not implement
// withContiguousStorageIfAvailable and therefore has no fast access
// to the backing storage. For now, convert to a String and call
// setString instead.
return self.setString(String(substring), at: index)
// Substring.UTF8View implements withContiguousStorageIfAvailable starting with
// Swift version 5.3.
if let written = substring.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
// fast path, directly available
return written
} else {
// slow path, convert to string
return self.setString(String(substring), at: index)
}
}

// MARK: DispatchData APIs
Expand Down