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