• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * 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,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.net.module.util;
18 
19 import static java.lang.Math.max;
20 
21 import android.os.Handler;
22 import android.system.Os;
23 
24 import java.io.FileDescriptor;
25 
26 /**
27  * Specialization of {@link FdEventsReader} that reads packets into a byte array.
28  *
29  * TODO: rename this class to something more correctly descriptive (something
30  * like [or less horrible than] FdReadEventsHandler?).
31  */
32 public abstract class PacketReader extends FdEventsReader<byte[]> {
33 
34     public static final int DEFAULT_RECV_BUF_SIZE = 2 * 1024;
35 
PacketReader(Handler h)36     protected PacketReader(Handler h) {
37         this(h, DEFAULT_RECV_BUF_SIZE);
38     }
39 
PacketReader(Handler h, int recvBufSize)40     protected PacketReader(Handler h, int recvBufSize) {
41         super(h, new byte[max(recvBufSize, DEFAULT_RECV_BUF_SIZE)]);
42     }
43 
44     @Override
recvBufSize(byte[] buffer)45     protected final int recvBufSize(byte[] buffer) {
46         return buffer.length;
47     }
48 
49     /**
50      * Subclasses MAY override this to change the default read() implementation
51      * in favour of, say, recvfrom().
52      *
53      * Implementations MUST return the bytes read or throw an Exception.
54      */
55     @Override
readPacket(FileDescriptor fd, byte[] packetBuffer)56     protected int readPacket(FileDescriptor fd, byte[] packetBuffer) throws Exception {
57         return Os.read(fd, packetBuffer, 0, packetBuffer.length);
58     }
59 }
60