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