//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Foundation import NIO import NIOHPACK /// This benchmark is mostly attempting to stress the Huffman Decoding implementation by /// way of using larger or more complex strings. final class HuffmanDecodingBenchmark { private let loopCount: Int private var decoder: HPACKDecoder private var buffer: ByteBuffer init(huffmanBytes: [UInt8], loopCount: Int) { self.loopCount = loopCount self.decoder = HPACKDecoder(allocator: .init(), maxDynamicTableSize: HPACKDecoder.maxDynamicTableSize, maxHeaderListSize: .max) self.buffer = ByteBufferAllocator().buffer(capacity: 1024) // We encode this header with both the name and value as a huffman string, never indexed. self.buffer.writeInteger(UInt8(0x10)) // Never indexed, non-indexed name self.buffer.encodeInteger(1, prefix: 7, prefixBits: 0x80) // Name length, huffman encoded, 7-bit integer self.buffer.writeInteger(UInt8(0x97)) // Huffman encoded "f" self.buffer.encodeInteger(UInt(huffmanBytes.count), prefix: 7, prefixBits: 0x80) // Value length, huffman encoded, 7-bit integer self.buffer.writeBytes(huffmanBytes) } } extension HuffmanDecodingBenchmark: Benchmark { func setUp() throws { // Run a single iteration of the loop. This warms up the encoder and decoder and ensures all the pages are mapped. try self.loopIteration() } func tearDown() { } func run() throws -> Int { for _ in 0..= 1) let k = (1 << prefix) - 1 var initialByte = prefixBits if value < k { // it fits already! initialByte |= UInt8(truncatingIfNeeded: value) self.writeInteger(initialByte) return } // if it won't fit in this byte altogether, fill in all the remaining bits and move // to the next byte. initialByte |= UInt8(truncatingIfNeeded: k) self.writeInteger(initialByte) // deduct the initial [prefix] bits from the value, then encode it seven bits at a time into // the remaining bytes. var n = value - UInt(k) while n >= 128 { let nextByte = (1 << 7) | UInt8(n & 0x7f) self.writeInteger(nextByte) n >>= 7 } self.writeInteger(UInt8(n)) } }