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 12 /** 13 * A set of utility methods. 14 */ 15 final class Utils { 16 17 private static final byte[] BYTE_ZEROES = new byte[1024]; 18 19 private static final int[] INT_ZEROES = new int[1024]; 20 21 /** 22 * Fills byte array with zeroes. 23 * 24 * <p> Current implementation uses {@link System#arraycopy}, so it should be used for length not 25 * less than 16. 26 * 27 * @param dest array to fill with zeroes 28 * @param offset the first byte to fill 29 * @param length number of bytes to change 30 */ 31 static void fillBytesWithZeroes(byte[] dest, int start, int end) { 32 int cursor = start; 33 while (cursor < end) { 34 int step = Math.min(cursor + 1024, end) - cursor; 35 System.arraycopy(BYTE_ZEROES, 0, dest, cursor, step); 36 cursor += step; 37 } 38 } 39 40 /** 41 * Fills int array with zeroes. 42 * 43 * <p> Current implementation uses {@link System#arraycopy}, so it should be used for length not 44 * less than 16. 45 * 46 * @param dest array to fill with zeroes 47 * @param offset the first item to fill 48 * @param length number of item to change 49 */ 50 static void fillIntsWithZeroes(int[] dest, int start, int end) { 51 int cursor = start; 52 while (cursor < end) { 53 int step = Math.min(cursor + 1024, end) - cursor; 54 System.arraycopy(INT_ZEROES, 0, dest, cursor, step); 55 cursor += step; 56 } 57 } 58 59 static void copyBytesWithin(byte[] bytes, int target, int start, int end) { 60 System.arraycopy(bytes, start, bytes, target, end - start); 61 } 62 63 static int readInput(InputStream src, byte[] dst, int offset, int length) { 64 try { 65 return src.read(dst, offset, length); 66 } catch (IOException e) { 67 throw new BrotliRuntimeException("Failed to read input", e); 68 } 69 } 70 71 static void closeInput(InputStream src) throws IOException { 72 src.close(); 73 } 74 } 75