diff --git a/Sources/NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift b/Sources/NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift index 83f640e2b..4fb0e7981 100644 --- a/Sources/NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift +++ b/Sources/NIOCore/ByteBuffer-quicBinaryEncodingStrategy.swift @@ -21,15 +21,54 @@ extension ByteBuffer { case two = 2 case four = 4 case eight = 8 + + /// The QUIC integer length closest to `value`. + /// + /// A QUIC variable-length integer occupies 1, 2, 4 or 8 bytes, so a value such as + /// 3 has no exact representation. Values below eight round up to the next valid + /// length; values above it saturate at ``IntegerLength/eight``. + @inlinable + public init(roundingFrom value: Int) { + switch value { + case ...1: self = .one + case 2: self = .two + case 3, 4: self = .four + default: self = .eight + } + } } + + /// The number of bytes used to write integers with this strategy. + /// + /// This is only relevant when calling ``ByteBuffer/writeLengthPrefixed(strategy:writeData:)``. + public var requiredBytesIntegerLength: IntegerLength + /// An estimate of the bytes required to write integers using this strategy - public var requiredBytesHint: Int + /// + /// A QUIC variable-length integer is 1, 2, 4 or 8 bytes long, so only those values are + /// representable. Prefer ``requiredBytesIntegerLength``, which can only hold a valid + /// length. Assigning a value here rounds to the closest valid length. + @inlinable + public var requiredBytesHint: Int { + get { + self.requiredBytesIntegerLength.rawValue + } + @available( + *, + deprecated, + message: + "Set requiredBytesIntegerLength instead: a QUIC integer is 1, 2, 4 or 8 bytes long, so other values cannot be represented exactly." + ) + set { + self.requiredBytesIntegerLength = IntegerLength(roundingFrom: newValue) + } + } /// Note: Prefer to use the APIs directly on ByteBuffer such as ``ByteBuffer/writeEncodedInteger(_:strategy:)`` and pass `.quic` rather than directly initialising an instance of this strategy /// - Parameter requiredBytesHint: An estimate of the bytes required to write integers using this strategy. This parameter is only relevant if calling ``ByteBuffer/writeLengthPrefixed(strategy:writeData:)`` @inlinable public init(requiredBytesHint: IntegerLength) { - self.requiredBytesHint = requiredBytesHint.rawValue + self.requiredBytesIntegerLength = requiredBytesHint } @inlinable @@ -106,24 +145,22 @@ extension ByteBuffer { // Use more space than necessary in order to fill the reserved space // This will avoid a memmove // If the needed space is more than the reserved, we can't avoid the move - switch max(reservedCapacity, Self.bytesNeededForInteger(integer)) { - case 1: + switch IntegerLength(roundingFrom: max(reservedCapacity, Self.bytesNeededForInteger(integer))) { + case .one: // Easy, store the value. The top two bits are 0 so we don't need to do any masking. return buffer.writeInteger(UInt8(truncatingIfNeeded: integer)) - case 2: + case .two: // Set the top two bit mask, then write the value. let value = UInt16(truncatingIfNeeded: integer) | (0x40 << 8) return buffer.writeInteger(value) - case 4: + case .four: // Set the top two bit mask, then write the value. let value = UInt32(truncatingIfNeeded: integer) | (0x80 << 24) return buffer.writeInteger(value) - case 8: + case .eight: // Set the top two bit mask, then write the value. let value = UInt64(truncatingIfNeeded: integer) | (0xC0 << 56) return buffer.writeInteger(value) - default: - fatalError("Unreachable") } } } diff --git a/Tests/NIOCoreTests/ByteBufferQUICBinaryEncodingStrategyTests.swift b/Tests/NIOCoreTests/ByteBufferQUICBinaryEncodingStrategyTests.swift index 68123f365..461eb50ec 100644 --- a/Tests/NIOCoreTests/ByteBufferQUICBinaryEncodingStrategyTests.swift +++ b/Tests/NIOCoreTests/ByteBufferQUICBinaryEncodingStrategyTests.swift @@ -147,6 +147,78 @@ final class ByteBufferQUICBinaryEncodingStrategyTests: XCTestCase { } } + // The typed `requiredBytesIntegerLength` closes the route through the strategy, but + // `writeInteger(_:reservedCapacity:to:)` is public and still takes a plain `Int`, so a + // caller can hand it a 3 directly. This covers that remaining entry point. + func testRoundtripWithNonPowerOfTwoReservedCapacity() { + for reservedCapacity in [3, 5, 6, 7] { + let testNumbers: [Int64] = [0, 63, 15293, 494_878_333, 151_288_809_941_952_652] + for testNumber in testNumbers { + var buffer = ByteBuffer() + let strategy = ByteBuffer.QUICBinaryEncodingStrategy.quic + let bytesWritten = strategy.writeInteger( + testNumber, + reservedCapacity: reservedCapacity, + to: &buffer + ) + let minRequiredBytes = ByteBuffer.QUICBinaryEncodingStrategy.bytesNeededForInteger(testNumber) + let wanted = max(minRequiredBytes, reservedCapacity) + let expectedUsedBytes = wanted <= 2 ? wanted : (wanted <= 4 ? 4 : 8) + XCTAssertEqual(bytesWritten, expectedUsedBytes) + XCTAssertEqual(strategy.readInteger(as: UInt64.self, from: &buffer), UInt64(testNumber)) + XCTAssertEqual(buffer.readableBytes, 0) + } + } + } + + @available(*, deprecated, message: "Tests the deprecated requiredBytesHint setter") + func testRequiredBytesHintSetterRoundsToAValidLength() { + typealias Length = ByteBuffer.QUICBinaryEncodingStrategy.IntegerLength + + // Grouped by expected length, and the strategy starts each case at a different + // length, so an assertion cannot pass on a value the setter never wrote. + let cases: [(expected: Length, inputs: [Int], startingFrom: Length)] = [ + (.one, [0, 1], .eight), + (.two, [2], .eight), + (.four, [3, 4], .one), + (.eight, [5, 6, 7, 8, 9, 64], .one), + ] + + for (expected, inputs, start) in cases { + for input in inputs { + var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: start) + XCTAssertNotEqual( + strategy.requiredBytesIntegerLength, + expected, + "input \(input) starts at its expected value" + ) + strategy.requiredBytesHint = input + XCTAssertEqual(strategy.requiredBytesIntegerLength, expected, "input \(input)") + } + } + + // A value that is already a valid length reads back unchanged. + for length in [Length.one, .two, .four, .eight] { + var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one) + strategy.requiredBytesHint = length.rawValue + XCTAssertEqual(strategy.requiredBytesHint, length.rawValue) + } + } + + @available(*, deprecated, message: "Tests the deprecated requiredBytesHint setter") + func testWriteLengthPrefixedWithRoundedHintDoesNotTrap() { + var strategy = ByteBuffer.QUICBinaryEncodingStrategy(requiredBytesHint: .one) + strategy.requiredBytesHint = 3 + + var buffer = ByteBuffer() + buffer.writeLengthPrefixed(strategy: strategy) { buffer in + buffer.writeString("hello") + } + + XCTAssertEqual(buffer.readLengthPrefixedSlice(strategy: strategy).map { String(buffer: $0) }, "hello") + XCTAssertEqual(buffer.readableBytes, 0) + } + // MARK: - readEncodedInteger tests func testReadEmptyQUICVariableLengthInteger() {