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

Avoid unnecessary heap allocation when parsing frame headers. #107

Merged
merged 1 commit into from
Apr 18, 2019
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
18 changes: 9 additions & 9 deletions Sources/NIOHTTP2/HTTP2FrameParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1159,17 +1159,17 @@ fileprivate struct FrameHeader {

fileprivate extension ByteBuffer {
mutating func readFrameHeader() -> FrameHeader? {
guard self.readableBytes >= 9 else {
return nil
let saveSelf = self
guard let lenHigh = self.readInteger(as: UInt16.self),
let lenLow = self.readInteger(as: UInt8.self),
let type = self.readInteger(as: UInt8.self),
let flags = self.readInteger(as: UInt8.self),
let rawStreamID = self.readInteger(as: UInt32.self) else {
self = saveSelf
return nil
}

let lenBytes: [UInt8] = self.readBytes(length: 3)!
Copy link
Member

Choose a reason for hiding this comment

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

I think you should keep the old code but replace

let lenBytes: [UInt8] = self.readBytes(length: 3)!

with

let lenHigh = self.readInteger(as: UInt16.self)
let lenLow = self.readInteger(as: UInt8.self)
let len = UInt32(lenHigh) << 16 | UInt32(lenLow)

let len = Int(lenBytes[0]) << 16 | Int(lenBytes[1]) << 8 | Int(lenBytes[2])
let type: UInt8 = self.readInteger()!
let flags: UInt8 = self.readInteger()!
let rawStreamID: UInt32 = self.readInteger()!

return FrameHeader(length: len, type: type, flags: FrameFlags(rawValue: flags), rawStreamID: rawStreamID)
return FrameHeader(length: Int(lenHigh) << 8 | Int(lenLow), type: type, flags: FrameFlags(rawValue: flags), rawStreamID: rawStreamID)
Copy link
Member

Choose a reason for hiding this comment

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

aren't we overwriting 8 bits here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

No: the UInt16 is converted to an Int and shifted left 8 bits. Then the UInt8 is converted to an Int and or'ed with it, fitting into the empty space from the previous left shift.

Copy link
Member

Choose a reason for hiding this comment

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

@Lukasa oops, thanks, brain fart :D

}

mutating func writePayloadSize(_ size: Int, at location: Int) {
Expand Down