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