1 /*
2 * Copyright 2015 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
17 /*
18 * Copyright 2015 Twitter, Inc.
19 *
20 * Licensed under the Apache License, Version 2.0 (the "License");
21 * you may not use this file except in compliance with the License.
22 * You may obtain a copy of the License at
23 *
24 * https://www.apache.org/licenses/LICENSE-2.0
25 *
26 * Unless required by applicable law or agreed to in writing, software
27 * distributed under the License is distributed on an "AS IS" BASIS,
28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 * See the License for the specific language governing permissions and
30 * limitations under the License.
31 */
32 package io.netty5.handler.codec.http2;
33
34 import io.netty5.util.AsciiString;
35 import io.netty5.util.internal.UnstableApi;
36
37 import java.util.ArrayList;
38 import java.util.List;
39 import java.util.Random;
40
41 /**
42 * Helper class representing a single header entry. Used by the benchmarks.
43 */
44 @UnstableApi
45 public final class HpackHeader {
46 private static final String ALPHABET =
47 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
48
49 final CharSequence name;
50 final CharSequence value;
51
52 private HpackHeader(byte[] name, byte[] value) {
53 this.name = new AsciiString(name, false);
54 this.value = new AsciiString(value, false);
55 }
56
57 /**
58 * Creates a number of random headers with the given name/value lengths.
59 */
60 static List<HpackHeader> createHeaders(int numHeaders, int nameLength, int valueLength,
61 boolean limitToAscii) {
62 List<HpackHeader> hpackHeaders = new ArrayList<>(numHeaders);
63 for (int i = 0; i < numHeaders; ++i) {
64 // Force always ascii for header names
65 byte[] name = randomBytes(new byte[nameLength], true);
66 byte[] value = randomBytes(new byte[valueLength], limitToAscii);
67 hpackHeaders.add(new HpackHeader(name, value));
68 }
69 return hpackHeaders;
70 }
71
72 private static byte[] randomBytes(byte[] bytes, boolean limitToAscii) {
73 Random r = new Random();
74 if (limitToAscii) {
75 for (int index = 0; index < bytes.length; ++index) {
76 int charIndex = r.nextInt(ALPHABET.length());
77 bytes[index] = (byte) ALPHABET.charAt(charIndex);
78 }
79 } else {
80 r.nextBytes(bytes);
81 }
82 return bytes;
83 }
84 }