/** * Creates an instance, not copying the array. * <p> * This method is inherently unsafe as it relies on good behavior by callers. * Callers must never make any changes to the passed in array after calling this method. * Doing so would violate the immutability of this class. * * @param array the array, not copied * @return the byte source */ public static ArrayByteSource ofUnsafe(byte[] array) { return new ArrayByteSource(array); }
/** * Creates an instance, copying the array. * * @param array the array, copied * @return the byte source */ public static ArrayByteSource copyOf(byte[] array) { return new ArrayByteSource(array.clone()); }
/** * Obtains an instance by copying part of an array. * <p> * The input array is copied and not mutated. * * @param array the array to copy * @param fromIndexInclusive the start index of the input array to copy from * @param toIndexExclusive the end index of the input array to copy to * @return an array containing the specified values * @throws IndexOutOfBoundsException if the index is invalid */ public static ArrayByteSource copyOf(byte[] array, int fromIndexInclusive, int toIndexExclusive) { if (fromIndexInclusive > array.length) { throw new IndexOutOfBoundsException("Array index out of bounds: " + fromIndexInclusive + " > " + array.length); } if (toIndexExclusive > array.length) { throw new IndexOutOfBoundsException("Array index out of bounds: " + toIndexExclusive + " > " + array.length); } if ((toIndexExclusive - fromIndexInclusive) == 0) { return EMPTY; } return new ArrayByteSource(Arrays.copyOfRange(array, fromIndexInclusive, toIndexExclusive)); }
/** * Creates an instance from another byte source. * * @param other the other byte source * @return the byte source * @throws UncheckedIOException if an IO error occurs */ public static ArrayByteSource from(ByteSource other) { if (other instanceof ArrayByteSource) { return (ArrayByteSource) other; } return new ArrayByteSource(Unchecked.wrap(() -> other.read())); }
/** * Creates an instance from an input stream. * <p> * This method use the supplier to open the input stream, extract the bytes and close the stream. * It is intended that invoking the supplier opens the stream. * It is not intended that an already open stream is supplied. * * @param inputStreamSupplier the supplier of the input stream * @return the byte source * @throws UncheckedIOException if an IO error occurs */ public static ArrayByteSource from(CheckedSupplier<InputStream> inputStreamSupplier) { return Unchecked.wrap(() -> { try (InputStream in = inputStreamSupplier.get()) { byte[] bytes = Unchecked.wrap(() -> ByteStreams.toByteArray(in)); return new ArrayByteSource(bytes); } }); }