Skip to content
Open
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
17 changes: 17 additions & 0 deletions Sources/SwiftNetwork/QUIC/QUICFrame.swift
Original file line number Diff line number Diff line change
Expand Up @@ -773,8 +773,24 @@ struct FramePadding: ~Copyable, QUICFrameProtocol {
private static func countLeadingZeroBytes(_ bytes: RawSpan) -> Int {
let count = bytes.byteCount
let wordSize = MemoryLayout<UInt64>.size
let vectorSize = 32

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I tried 16/64 as well, 32 seems to be the sweet spot.

var offset = 0

// 1. Speed through the zeros via vectorization.
while offset &+ vectorSize <= count {
var orResult: UInt8 = 0
// This loop is auto-vectorized.
for idx in 0..<vectorSize {
orResult |= bytes.unsafeLoad(fromUncheckedByteOffset: offset &+ idx, as: UInt8.self)
}
if orResult == 0 {
offset &+= vectorSize
} else {
break
}
}

// 2. Read the rest of the bytes in chunks of words.
while offset &+ wordSize <= count {
let word = bytes.unsafeLoadUnaligned(fromByteOffset: offset, as: UInt64.self)

Expand All @@ -785,6 +801,7 @@ struct FramePadding: ~Copyable, QUICFrameProtocol {
}
}

// 3. Scan the remaining bytes one by one.
while offset < count, bytes[offset] == 0x00 {
offset &+= 1
}
Expand Down
8 changes: 4 additions & 4 deletions Tests/QUICTests/QUICFrameTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,8 @@ class QUICFrameTests: XCTestCase {

func testPaddingInitStopsAtFirstNonZeroByte() throws {
// Offset 0 is the frame type byte, so start at 1
for sentinelOffset in 1..<23 {
var bytes = [UInt8](repeating: 0x00, count: 23)
for sentinelOffset in 1..<87 {
var bytes = [UInt8](repeating: 0x00, count: 87)
bytes[sentinelOffset] = 0xff

var frame = Frame(copyBuffer: bytes)
Expand All @@ -118,10 +118,10 @@ class QUICFrameTests: XCTestCase {
}

func testPaddingInitAllZeroes() throws {
let bytes = [UInt8](repeating: 0x00, count: 23)
let bytes = [UInt8](repeating: 0x00, count: 87)
var frame = Frame(copyBuffer: bytes)
let paddingFrame = try FramePadding(frame: &frame, packetNumberSpace: .applicationData)
XCTAssertEqual(paddingFrame.extraPadding, 22)
XCTAssertEqual(paddingFrame.extraPadding, 86)
frame.finalize(success: true)
}

Expand Down
Loading