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.channel;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufHolder;
20  
21  /**
22   * Default {@link MessageSizeEstimator} implementation which supports the estimation of the size of
23   * {@link ByteBuf}, {@link ByteBufHolder} and {@link FileRegion}.
24   */
25  public final class DefaultMessageSizeEstimator implements MessageSizeEstimator {
26  
27      private static final class HandleImpl implements Handle {
28          private final int unknownSize;
29  
30          private HandleImpl(int unknownSize) {
31              this.unknownSize = unknownSize;
32          }
33  
34          @Override
35          public int size(Object msg) {
36              if (msg instanceof ByteBuf) {
37                  return ((ByteBuf) msg).readableBytes();
38              }
39              if (msg instanceof ByteBufHolder) {
40                  return ((ByteBufHolder) msg).content().readableBytes();
41              }
42              if (msg instanceof FileRegion) {
43                  return 0;
44              }
45              return unknownSize;
46          }
47      }
48  
49      /**
50       * Return the default implementation which returns {@code 8} for unknown messages.
51       */
52      public static final MessageSizeEstimator DEFAULT = new DefaultMessageSizeEstimator(8);
53  
54      private final Handle handle;
55  
56      /**
57       * Create a new instance
58       *
59       * @param unknownSize       The size which is returned for unknown messages.
60       */
61      public DefaultMessageSizeEstimator(int unknownSize) {
62          if (unknownSize < 0) {
63              throw new IllegalArgumentException("unknownSize: " + unknownSize + " (expected: >= 0)");
64          }
65          handle = new HandleImpl(unknownSize);
66      }
67  
68      @Override
69      public Handle newHandle() {
70          return handle;
71      }
72  }