View Javadoc
1   /*
2    * Copyright 2014 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  
17  package io.netty.handler.codec.http;
18  
19  import io.netty.buffer.ByteBuf;
20  import io.netty.handler.codec.AsciiString;
21  import io.netty.handler.codec.TextHeaders.EntryVisitor;
22  
23  import java.util.Map.Entry;
24  
25  final class HttpHeadersEncoder implements EntryVisitor {
26  
27      private final ByteBuf buf;
28  
29      HttpHeadersEncoder(ByteBuf buf) {
30          this.buf = buf;
31      }
32  
33      @Override
34      public boolean visit(Entry<CharSequence, CharSequence> entry) throws Exception {
35          final CharSequence name = entry.getKey();
36          final CharSequence value = entry.getValue();
37          final ByteBuf buf = this.buf;
38          final int nameLen = name.length();
39          final int valueLen = value.length();
40          final int entryLen = nameLen + valueLen + 4;
41          int offset = buf.writerIndex();
42          buf.ensureWritable(entryLen);
43          writeAscii(buf, offset, name, nameLen);
44          offset += nameLen;
45          buf.setByte(offset ++, ':');
46          buf.setByte(offset ++, ' ');
47          writeAscii(buf, offset, value, valueLen);
48          offset += valueLen;
49          buf.setByte(offset ++, '\r');
50          buf.setByte(offset ++, '\n');
51          buf.writerIndex(offset);
52          return true;
53      }
54  
55      private static void writeAscii(ByteBuf buf, int offset, CharSequence value, int valueLen) {
56          if (value instanceof AsciiString) {
57              writeAsciiString(buf, offset, (AsciiString) value, valueLen);
58          } else {
59              writeCharSequence(buf, offset, value, valueLen);
60          }
61      }
62  
63      private static void writeAsciiString(ByteBuf buf, int offset, AsciiString value, int valueLen) {
64          value.copy(0, buf, offset, valueLen);
65      }
66  
67      private static void writeCharSequence(ByteBuf buf, int offset, CharSequence value, int valueLen) {
68          for (int i = 0; i < valueLen; i ++) {
69              buf.setByte(offset ++, c2b(value.charAt(i)));
70          }
71      }
72  
73      private static int c2b(char ch) {
74          return ch < 256? (byte) ch : '?';
75      }
76  }