View Javadoc
1   /*
2    * Copyright 2015 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.netty.channel.epoll;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.channel.RecvByteBufAllocator.DelegatingHandle;
21  import io.netty.channel.RecvByteBufAllocator.ExtendedHandle;
22  import io.netty.channel.unix.PreferredDirectByteBufAllocator;
23  import io.netty.util.UncheckedBooleanSupplier;
24  
25  class EpollRecvByteAllocatorHandle extends DelegatingHandle implements ExtendedHandle {
26      private final PreferredDirectByteBufAllocator preferredDirectByteBufAllocator =
27              new PreferredDirectByteBufAllocator();
28      private final UncheckedBooleanSupplier defaultMaybeMoreDataSupplier = new UncheckedBooleanSupplier() {
29          @Override
30          public boolean get() {
31              return maybeMoreDataToRead();
32          }
33      };
34      private boolean receivedRdHup;
35  
36      EpollRecvByteAllocatorHandle(ExtendedHandle handle) {
37          super(handle);
38      }
39  
40      final void receivedRdHup() {
41          receivedRdHup = true;
42      }
43  
44      final boolean isReceivedRdHup() {
45          return receivedRdHup;
46      }
47  
48      boolean maybeMoreDataToRead() {
49          return lastBytesRead() == attemptedBytesRead();
50      }
51  
52      @Override
53      public final ByteBuf allocate(ByteBufAllocator alloc) {
54          // We need to ensure we always allocate a direct ByteBuf as we can only use a direct buffer to read via JNI.
55          preferredDirectByteBufAllocator.updateAllocator(alloc);
56          return delegate().allocate(preferredDirectByteBufAllocator);
57      }
58  
59      @Override
60      public final boolean continueReading(UncheckedBooleanSupplier maybeMoreDataSupplier) {
61          return isReceivedRdHup() || ((ExtendedHandle) delegate()).continueReading(maybeMoreDataSupplier);
62      }
63  
64      @Override
65      public final boolean continueReading() {
66          // We must override the supplier which determines if there maybe more data to read.
67          return continueReading(defaultMaybeMoreDataSupplier);
68      }
69  }