1 /* 2 * Copyright (C) 2014 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 libcore.tlswire.util; 18 19 import java.io.DataInput; 20 import java.io.IOException; 21 22 public class IoUtils { 23 24 public static int readUnsignedInt24(DataInput in) throws IOException { 25 return (in.readUnsignedByte() << 16) | in.readUnsignedShort(); 26 } 27 28 public static byte[] readTlsVariableLengthByteVector(DataInput in, int maxSizeBytes) 29 throws IOException { 30 int sizeBytes = readTlsVariableLengthVectorSizeBytes(in, maxSizeBytes); 31 byte[] result = new byte[sizeBytes]; 32 in.readFully(result); 33 return result; 34 } 35 36 public static int[] readTlsVariableLengthUnsignedShortVector(DataInput in, int maxSizeBytes) 37 throws IOException { 38 int sizeBytes = readTlsVariableLengthVectorSizeBytes(in, maxSizeBytes); 39 int elementCount = sizeBytes / 2; 40 int[] result = new int[elementCount]; 41 for (int i = 0; i < elementCount; i++) { 42 result[i] = in.readUnsignedShort(); 43 } 44 return result; 45 } 46 47 private static int readTlsVariableLengthVectorSizeBytes(DataInput in, int maxSizeBytes) 48 throws IOException { 49 if (maxSizeBytes < 0x100) { 50 return in.readUnsignedByte(); 51 } else if (maxSizeBytes < 0x10000) { 52 return in.readUnsignedShort(); 53 } else if (maxSizeBytes < 0x1000000) { 54 return readUnsignedInt24(in); 55 } else { 56 return in.readInt(); 57 } 58 } 59 } 60