1 /* 2 * Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. 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 * A copy of the License is located at 7 * 8 * http://aws.amazon.com/apache2.0 9 * 10 * or in the "license" file accompanying this file. This file is distributed 11 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 * express or implied. See the License for the specific language governing 13 * permissions and limitations under the License. 14 */ 15 package software.amazon.eventstream; 16 17 import java.io.DataOutputStream; 18 import java.io.IOException; 19 import java.nio.ByteBuffer; 20 21 import static java.nio.charset.StandardCharsets.UTF_8; 22 23 final class Utils { Utils()24 private Utils() {} 25 readShortString(ByteBuffer buf)26 static String readShortString(ByteBuffer buf) { 27 int length = buf.get() & 0xFF; 28 checkStringBounds(length, 255); 29 byte[] bytes = new byte[length]; 30 buf.get(bytes); 31 return new String(bytes, UTF_8); 32 } 33 readString(ByteBuffer buf)34 static String readString(ByteBuffer buf) { 35 int length = buf.getShort() & 0xFFFF; 36 checkStringBounds(length, 32767); 37 byte[] bytes = new byte[length]; 38 buf.get(bytes); 39 return new String(bytes, UTF_8); 40 } 41 readBytes(ByteBuffer buf)42 static byte[] readBytes(ByteBuffer buf) { 43 int length = buf.getShort() & 0xFFFF; 44 checkByteArrayBounds(length); 45 byte[] bytes = new byte[length]; 46 buf.get(bytes); 47 return bytes; 48 } 49 writeShortString(DataOutputStream dos, String string)50 static void writeShortString(DataOutputStream dos, String string) throws IOException { 51 byte[] bytes = string.getBytes(UTF_8); 52 checkStringBounds(bytes.length, 255); 53 dos.writeByte(bytes.length); 54 dos.write(bytes); 55 } 56 writeString(DataOutputStream dos, String string)57 static void writeString(DataOutputStream dos, String string) throws IOException { 58 byte[] bytes = string.getBytes(UTF_8); 59 checkStringBounds(bytes.length, 32767); 60 writeBytes(dos, bytes); 61 } 62 writeBytes(DataOutputStream dos, byte[] bytes)63 static void writeBytes(DataOutputStream dos, byte[] bytes) throws IOException { 64 checkByteArrayBounds(bytes.length); 65 dos.writeShort((short) bytes.length); 66 dos.write(bytes); 67 } 68 checkByteArrayBounds(int length)69 private static void checkByteArrayBounds(int length) { 70 if (length == 0) { 71 throw new IllegalArgumentException("Byte arrays may not be empty"); 72 } 73 if (length > 32767) { 74 throw new IllegalArgumentException("Illegal byte array length: " + length); 75 } 76 } 77 checkStringBounds(int length, int maxLength)78 private static void checkStringBounds(int length, int maxLength) { 79 if (length == 0) { 80 throw new IllegalArgumentException("Strings may not be empty"); 81 } 82 if (length > maxLength) { 83 throw new IllegalArgumentException("Illegal string length: " + length); 84 } 85 } 86 } 87