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 android.net.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 * @hide 33 */ 34 public abstract class PacketReader extends FdEventsReader<byte[]> { 35 36 public static final int DEFAULT_RECV_BUF_SIZE = 2 * 1024; 37 PacketReader(Handler h)38 protected PacketReader(Handler h) { 39 this(h, DEFAULT_RECV_BUF_SIZE); 40 } 41 PacketReader(Handler h, int recvBufSize)42 protected PacketReader(Handler h, int recvBufSize) { 43 super(h, new byte[max(recvBufSize, DEFAULT_RECV_BUF_SIZE)]); 44 } 45 46 @Override recvBufSize(byte[] buffer)47 protected final int recvBufSize(byte[] buffer) { 48 return buffer.length; 49 } 50 51 /** 52 * Subclasses MAY override this to change the default read() implementation 53 * in favour of, say, recvfrom(). 54 * 55 * Implementations MUST return the bytes read or throw an Exception. 56 */ 57 @Override readPacket(FileDescriptor fd, byte[] packetBuffer)58 protected int readPacket(FileDescriptor fd, byte[] packetBuffer) throws Exception { 59 return Os.read(fd, packetBuffer, 0, packetBuffer.length); 60 } 61 } 62