1 /* Copyright 2015 Google Inc. All Rights Reserved. 2 3 Distributed under MIT license. 4 See file LICENSE for detail or copy at https://opensource.org/licenses/MIT 5 */ 6 7 package org.brotli.dec; 8 9 import java.io.IOException; 10 import java.io.InputStream; 11 import java.io.UnsupportedEncodingException; 12 import java.nio.Buffer; 13 14 /** 15 * A set of utility methods. 16 */ 17 final class Utils { 18 19 private static final byte[] BYTE_ZEROES = new byte[1024]; 20 21 private static final int[] INT_ZEROES = new int[1024]; 22 23 /** 24 * Fills byte array with zeroes. 25 * 26 * <p> Current implementation uses {@link System#arraycopy}, so it should be used for length not 27 * less than 16. 28 * 29 * @param dest array to fill with zeroes 30 * @param offset the first byte to fill 31 * @param length number of bytes to change 32 */ fillBytesWithZeroes(byte[] dest, int start, int end)33 static void fillBytesWithZeroes(byte[] dest, int start, int end) { 34 int cursor = start; 35 while (cursor < end) { 36 int step = Math.min(cursor + 1024, end) - cursor; 37 System.arraycopy(BYTE_ZEROES, 0, dest, cursor, step); 38 cursor += step; 39 } 40 } 41 42 /** 43 * Fills int array with zeroes. 44 * 45 * <p> Current implementation uses {@link System#arraycopy}, so it should be used for length not 46 * less than 16. 47 * 48 * @param dest array to fill with zeroes 49 * @param offset the first item to fill 50 * @param length number of item to change 51 */ fillIntsWithZeroes(int[] dest, int start, int end)52 static void fillIntsWithZeroes(int[] dest, int start, int end) { 53 int cursor = start; 54 while (cursor < end) { 55 int step = Math.min(cursor + 1024, end) - cursor; 56 System.arraycopy(INT_ZEROES, 0, dest, cursor, step); 57 cursor += step; 58 } 59 } 60 copyBytesWithin(byte[] bytes, int target, int start, int end)61 static void copyBytesWithin(byte[] bytes, int target, int start, int end) { 62 System.arraycopy(bytes, start, bytes, target, end - start); 63 } 64 readInput(InputStream src, byte[] dst, int offset, int length)65 static int readInput(InputStream src, byte[] dst, int offset, int length) { 66 try { 67 return src.read(dst, offset, length); 68 } catch (IOException e) { 69 throw new BrotliRuntimeException("Failed to read input", e); 70 } 71 } 72 closeInput(InputStream src)73 static void closeInput(InputStream src) throws IOException { 74 src.close(); 75 } 76 toUsAsciiBytes(String src)77 static byte[] toUsAsciiBytes(String src) { 78 try { 79 // NB: String#getBytes(String) is present in JDK 1.1, while other variants require JDK 1.6 and 80 // above. 81 return src.getBytes("US-ASCII"); 82 } catch (UnsupportedEncodingException e) { 83 throw new RuntimeException(e); // cannot happen 84 } 85 } 86 87 // Crazy pills factory: code compiled for JDK8 does not work on JRE9. flipBuffer(Buffer buffer)88 static void flipBuffer(Buffer buffer) { 89 buffer.flip(); 90 } 91 } 92