View Javadoc

1   /*
2    * Copyright 2013 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    *   http://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.http;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.util.CharsetUtil;
20  
21  final class HttpHeaderEntity implements CharSequence {
22  
23      private final String name;
24      private final int hash;
25      private final byte[] bytes;
26      private final int separatorLen;
27  
28      public HttpHeaderEntity(String name) {
29          this(name, null);
30      }
31  
32      public HttpHeaderEntity(String name, byte[] separator) {
33          this.name = name;
34          hash = HttpHeaders.hash(name);
35          byte[] nameBytes = name.getBytes(CharsetUtil.US_ASCII);
36          if (separator == null) {
37              bytes = nameBytes;
38              separatorLen = 0;
39          } else {
40              separatorLen = separator.length;
41              bytes = new byte[nameBytes.length + separator.length];
42              System.arraycopy(nameBytes, 0, bytes, 0, nameBytes.length);
43              System.arraycopy(separator, 0, bytes, nameBytes.length, separator.length);
44          }
45      }
46  
47      int hash() {
48          return hash;
49      }
50  
51      @Override
52      public int length() {
53          return bytes.length - separatorLen;
54      }
55  
56      @Override
57      public char charAt(int index) {
58          if ((bytes.length - separatorLen) <= index) {
59              throw new IndexOutOfBoundsException();
60          }
61          return (char) bytes[index];
62      }
63  
64      @Override
65      public CharSequence subSequence(int start, int end) {
66          return new HttpHeaderEntity(name.substring(start, end));
67      }
68  
69      @Override
70      public String toString() {
71          return name;
72      }
73  
74      boolean encode(ByteBuf buf) {
75          buf.writeBytes(bytes);
76          return separatorLen > 0;
77      }
78  }