|
| 1 | +/* |
| 2 | + * Copyright 2026 The Netty Project |
| 3 | + * |
| 4 | + * The Netty Project licenses this file to you under the Apache License, |
| 5 | + * version 2.0 (the "License"); you may not use this file except in compliance |
| 6 | + * with the License. You may obtain a copy of the License at: |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 12 | + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 13 | + * License for the specific language governing permissions and limitations |
| 14 | + * under the License. |
| 15 | + */ |
| 16 | +package io.netty.handler.codec.http3; |
| 17 | + |
| 18 | +import io.netty.buffer.ByteBuf; |
| 19 | +import io.netty.buffer.Unpooled; |
| 20 | +import org.junit.jupiter.api.Test; |
| 21 | + |
| 22 | +import static io.netty.handler.codec.http3.QpackUtil.decodePrefixedInteger; |
| 23 | +import static io.netty.handler.codec.http3.QpackUtil.encodePrefixedInteger; |
| 24 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 25 | +import static org.hamcrest.Matchers.is; |
| 26 | + |
| 27 | +public class QpackUtilTest { |
| 28 | + |
| 29 | + // A remainder of exactly 128 while encoding a multi-byte prefixed integer must still be encoded as a |
| 30 | + // continuation byte (it does not fit in the final, non-continuation byte, which can only hold 0-127). |
| 31 | + // For a 6-bit prefix (nbits = 63) this first happens at value 191 (63 + 128). |
| 32 | + @Test |
| 33 | + public void encodeDecodeRoundTripsAtContinuationByteBoundary() { |
| 34 | + ByteBuf buf = Unpooled.buffer(); |
| 35 | + try { |
| 36 | + for (int prefixLength = 1; prefixLength <= 8; prefixLength++) { |
| 37 | + int nbits = (1 << prefixLength) - 1; |
| 38 | + long value = nbits + 128; |
| 39 | + assertRoundTrip(buf, prefixLength, value); |
| 40 | + buf.clear(); |
| 41 | + } |
| 42 | + } finally { |
| 43 | + buf.release(); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + @Test |
| 48 | + public void encodeDecodeRoundTripsOverWideRange() { |
| 49 | + ByteBuf buf = Unpooled.buffer(); |
| 50 | + try { |
| 51 | + for (int prefixLength : new int[] { 4, 5, 6, 7, 8 }) { |
| 52 | + for (long value = 0; value <= 20_000; value++) { |
| 53 | + assertRoundTrip(buf, prefixLength, value); |
| 54 | + buf.clear(); |
| 55 | + } |
| 56 | + } |
| 57 | + } finally { |
| 58 | + buf.release(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + private static void assertRoundTrip(ByteBuf buf, int prefixLength, long value) { |
| 63 | + encodePrefixedInteger(buf, (byte) 0, prefixLength, value); |
| 64 | + assertThat("Round trip failed for prefixLength=" + prefixLength + ", value=" + value, |
| 65 | + decodePrefixedInteger(buf, prefixLength), is(value)); |
| 66 | + } |
| 67 | +} |