Chalard Jean | 48c6c7d | 2020-06-25 23:39:15 +0900 | [diff] [blame^] | 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 | // TODO : move this and FdEventsReader to com.android.net.module.util. |
| 18 | package android.net.util; |
| 19 | |
| 20 | import static java.lang.Math.max; |
| 21 | |
| 22 | import android.os.Handler; |
| 23 | import android.system.Os; |
| 24 | |
| 25 | import java.io.FileDescriptor; |
| 26 | |
| 27 | /** |
| 28 | * Specialization of {@link FdEventsReader} that reads packets into a byte array. |
| 29 | * |
| 30 | * TODO: rename this class to something more correctly descriptive (something |
| 31 | * like [or less horrible than] FdReadEventsHandler?). |
| 32 | */ |
| 33 | public abstract class PacketReader extends FdEventsReader<byte[]> { |
| 34 | |
| 35 | public static final int DEFAULT_RECV_BUF_SIZE = 2 * 1024; |
| 36 | |
| 37 | protected PacketReader(Handler h) { |
| 38 | this(h, DEFAULT_RECV_BUF_SIZE); |
| 39 | } |
| 40 | |
| 41 | protected PacketReader(Handler h, int recvBufSize) { |
| 42 | super(h, new byte[max(recvBufSize, DEFAULT_RECV_BUF_SIZE)]); |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | protected final int recvBufSize(byte[] buffer) { |
| 47 | return buffer.length; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Subclasses MAY override this to change the default read() implementation |
| 52 | * in favour of, say, recvfrom(). |
| 53 | * |
| 54 | * Implementations MUST return the bytes read or throw an Exception. |
| 55 | */ |
| 56 | @Override |
| 57 | protected int readPacket(FileDescriptor fd, byte[] packetBuffer) throws Exception { |
| 58 | return Os.read(fd, packetBuffer, 0, packetBuffer.length); |
| 59 | } |
| 60 | } |