1 /*
   2  * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.io.*;
  29 import java.nio.*;
  30 import java.util.*;
  31 import java.util.stream.*;
  32 
  33 /**
  34  * Converts binary data to and from its hexadecimal (base 16) string
  35  * representation. It can also generate the classic Unix {@code hexdump(1)}
  36  * format.
  37  * <p>
  38  * <b>Example usages:</b>
  39  * <pre>{@code    // Initialize a 16-byte array from a hexadecimal string
  40  *   byte[] bytes = Hex.fromString("a1a2a3a4a5a6a7a8a9aaabacadaeaf");
  41  *
  42  *   // Display the hexadecimal representation of a file's 256-bit hash code
  43  *   MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
  44  *   System.out.println(
  45  *       Hex.toString(sha256.digest(Files.readAllBytes(Paths.get("mydata")))));
  46  *
  47  *   // Write the printable representation of a file to the standard output stream
  48  *   // in 64-byte chunks formatted according to the supplied Formatter function
  49  *   Hex.dumpAsStream(Files.newInputStream(Paths.get("mydata")), 64,
  50  *       (offset, chunk, fromIndex, toIndex) ->
  51  *           String.format("%d %s",
  52  *               offset / 64 + 1,
  53  *               Hex.toPrintableString(chunk, fromIndex, toIndex)))
  54  *       .forEachOrdered(System.out::println);
  55  *
  56  *   // Write the standard input stream to the standard output stream in hexdump format
  57  *   Hex.dump(System.in, System.out);
  58  * }</pre>
  59  *
  60  * @since 12
  61  */
  62 public final class Hex {
  63 
  64     private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
  65     private static final int NEWLINE_LENGTH = System.lineSeparator().length();
  66     private static final int DEFAULT_CHUNK_SIZE = 16;
  67 
  68     /**
  69      * Formatter that generates the classic Unix {@code hexdump(1)} format.
  70      */
  71     public static final Formatter HEXDUMP_FORMATTER = new Formatter() {
  72         public String format(long offset, byte[] chunk, int fromIndex, int toIndex) {
  73             return String.format("%08x  %s  |%s|",
  74                 offset,
  75                 Hex.toFormattedHexString(chunk, fromIndex, toIndex),
  76                 Hex.toPrintableString(chunk, fromIndex, toIndex));
  77         }
  78     };
  79 
  80     private Hex() {}
  81 
  82     /**
  83      * Returns a hexadecimal string representation of the contents of the
  84      * provided byte array, with no additional formatting.
  85      * <p>
  86      * The binary value is converted to a string comprising pairs of
  87      * hexadecimal digits that use only the following ASCII characters:
  88      * <blockquote>
  89      *  {@code 0123456789abcdef}
  90      * </blockquote>
  91      *
  92      * @param bytes a binary buffer
  93      * @return a hexadecimal string representation of the binary buffer.
  94      *         The string length is twice the buffer length.
  95      * @throws NullPointerException if {@code bytes} is {@code null}
  96      */
  97     public static String toString(byte[] bytes) {
  98         Objects.requireNonNull(bytes, "bytes");
  99         return toString(bytes, 0, bytes.length);
 100     }
 101 
 102     /**
 103      * Returns a hexadecimal string representation of a <i>range</i> within the
 104      * provided byte array, with no additional formatting.
 105      * <p>
 106      * The binary value is converted to a string comprising pairs of
 107      * hexadecimal digits that use only the following ASCII characters:
 108      * <blockquote>
 109      *  {@code 0123456789abcdef}
 110      * </blockquote>
 111      * The range to be converted extends from index {@code fromIndex},
 112      * inclusive, to index {@code toIndex}, exclusive.
 113      * (If {@code fromIndex==toIndex}, the range to be converted is empty.)
 114      *
 115      * @param bytes a binary buffer
 116      * @param fromIndex the index of the first byte (inclusive) to be converted
 117      * @param toIndex the index of the last byte (exclusive) to be converted
 118      * @return a hexadecimal string representation of the binary buffer.
 119      *         The string length is twice the number of bytes converted.
 120      * @throws NullPointerException if {@code bytes} is {@code null}
 121      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 122      * @throws ArrayIndexOutOfBoundsException
 123      *     if {@code fromIndex < 0} or {@code toIndex > bytes.length}
 124      */
 125     public static String toString(byte[] bytes, int fromIndex, int toIndex) {
 126         Objects.requireNonNull(bytes, "bytes");
 127         Arrays.rangeCheck(bytes.length, fromIndex, toIndex);
 128         return toFormattedString(bytes, fromIndex, toIndex, toIndex - fromIndex,
 129             1, false);
 130     }
 131 
 132     /**
 133      * Returns a formatted hexadecimal string representation of the contents of
 134      * the provided byte array.
 135      * <p>
 136      * The binary value is converted to a string in the canonical hexdump
 137      * format of two columns of eight space-separated pairs of hexadecimal
 138      * digits that use only the following ASCII characters:
 139      * <blockquote>
 140      *  {@code 0123456789abcdef}
 141      * </blockquote>
 142      * <p>
 143      * If the number of bytes to be converted is greater than 16 then
 144      * line-separator characters are inserted after each 16-byte chunk.
 145      * If the final chunk is less than 16 then it is padded with spaces
 146      * to match the length of the preceding chunks.
 147      * The general output format is as follows:
 148      * <pre>
 149      * 00 11 22 33 44 55 66 77  88 99 aa bb cc dd ee ff
 150      * </pre>
 151      *
 152      * @param bytes a binary buffer
 153      * @return a formatted hexadecimal string representation of the binary buffer
 154      * @throws NullPointerException if {@code bytes} is {@code null}
 155      */
 156     public static String toFormattedHexString(byte[] bytes) {
 157         Objects.requireNonNull(bytes, "bytes");
 158         return toFormattedHexString(bytes, 0, bytes.length);
 159     }
 160 
 161     /**
 162      * Returns a formatted hexadecimal string representation of the contents of
 163      * a <i>range</i> within the provided byte array.
 164      * <p>
 165      * The binary value is converted to a string in the canonical hexdump
 166      * format of two columns of eight space-separated pairs of hexadecimal
 167      * digits that use only the following ASCII characters:
 168      * <blockquote>
 169      *  {@code 0123456789abcdef}
 170      * </blockquote>
 171      * <p>
 172      * The range to be converted extends from index {@code fromIndex},
 173      * inclusive, to index {@code toIndex}, exclusive.
 174      * (If {@code fromIndex==toIndex}, the range to be converted is empty.)
 175      * <p>
 176      * If the number of bytes to be converted is greater than 16 then
 177      * line-separator characters are inserted after each 16-byte chunk.
 178      * If the final chunk is less than 16 then it is padded with spaces
 179      * to match the length of the preceding chunks.
 180      * The general output format is as follows:
 181      * <pre>
 182      * 00 11 22 33 44 55 66 77  88 99 aa bb cc dd ee ff
 183      * </pre>
 184      *
 185      * @param bytes a binary buffer
 186      * @param fromIndex the index of the first byte (inclusive) to be converted
 187      * @param toIndex the index of the last byte (exclusive) to be converted
 188      * @return a formatted hexadecimal string representation of the binary buffer
 189      * @throws NullPointerException if {@code bytes} is {@code null}
 190      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 191      * @throws ArrayIndexOutOfBoundsException
 192      *     if {@code fromIndex < 0} or {@code toIndex > bytes.length}
 193      */
 194     public static String toFormattedHexString(byte[] bytes, int fromIndex,
 195         int toIndex) {
 196         Objects.requireNonNull(bytes, "bytes");
 197         Arrays.rangeCheck(bytes.length, fromIndex, toIndex);
 198         return toFormattedString(bytes, fromIndex, toIndex, DEFAULT_CHUNK_SIZE, 2, true);
 199     }
 200 
 201     /**
 202      * Returns the printable ASCII representation of the contents of the
 203      * provided byte array.
 204      * <p>
 205      * The binary value is converted to a string comprising printable ASCII
 206      * characters, or {@code '.'} if the byte maps to a non-printable character.
 207      * A non-printable character is one outside of the ASCII range
 208      * {@code ' '} through {@code '~'}
 209      * ({@code '\u005Cu0020'} through {@code '\u005Cu007E'}).
 210      *
 211      * @param bytes a binary buffer
 212      * @return a printable ASCII representation of the binary buffer
 213      * @throws NullPointerException if {@code bytes} is {@code null}
 214      */
 215     public static String toPrintableString(byte[] bytes) {
 216         Objects.requireNonNull(bytes, "bytes");
 217         return toPrintableString(bytes, 0, bytes.length);
 218     }
 219 
 220     /**
 221      * Returns the printable ASCII representation of the contents of a
 222      * <i>range</i> within the provided byte array.
 223      * <p>
 224      * The binary value is converted to a string comprising printable ASCII
 225      * characters, or {@code '.'} if the byte maps to a non-printable character.
 226      * A non-printable character is one outside of the ASCII range
 227      * {@code ' '} through {@code '~'}
 228      * ({@code '\u005Cu0020'} through {@code '\u005Cu007E'}).
 229      *
 230      * @param bytes a binary buffer
 231      * @param fromIndex the index of the first byte (inclusive) to be converted
 232      * @param toIndex the index of the last byte (exclusive) to be converted
 233      * @return a printable ASCII representation of the binary buffer
 234      * @throws NullPointerException if {@code bytes} is {@code null}
 235      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 236      * @throws ArrayIndexOutOfBoundsException
 237      *     if {@code fromIndex < 0} or {@code toIndex > bytes.length}
 238      */
 239     public static String toPrintableString(byte[] bytes, int fromIndex,
 240             int toIndex) {
 241         Objects.requireNonNull(bytes, "bytes");
 242         Arrays.rangeCheck(bytes.length, fromIndex, toIndex);
 243 
 244         StringBuilder ascii = new StringBuilder(toIndex - fromIndex);
 245         // Printable ASCII
 246         for (int i = fromIndex; i < toIndex; i++) {
 247             if (bytes[i] < ' ' || bytes[i] > '~') {
 248                 ascii.append('.');
 249             } else {
 250                 ascii.append((char) bytes[i]);
 251             }
 252         }
 253 
 254         return ascii.toString();
 255     }
 256 
 257     /**
 258      * Returns a byte array containing the provided sequence of hexadecimal
 259      * digits. The sequence may be prefixed with the hexadecimal indicator
 260      * {@code "0x"}.
 261      * <p>
 262      * The binary value is generated from pairs of hexadecimal digits that use
 263      * only the following ASCII characters:
 264      * <blockquote>
 265      *  {@code 0123456789abcdefABCDEF}
 266      * </blockquote>
 267      *
 268      * @param hexString an even numbered sequence of hexadecimal digits
 269      * @return a binary buffer
 270      * @throws IllegalArgumentException if {@code hexString} has an odd number
 271      *         of digits or contains an illegal hexadecimal character
 272      * @throws NullPointerException if {@code hexString} is {@code null}
 273      */
 274     public static byte[] fromString(CharSequence hexString) {
 275         Objects.requireNonNull(hexString, "hexString");
 276         return hexToBytes(hexString, 0, hexString.length());
 277     }
 278 
 279     /**
 280      * Returns a byte array containing a <i>range</i> within the provided
 281      * sequence of hexadecimal digits. The sequence may be prefixed with the
 282      * hexadecimal indicator {@code "0x"}.
 283      * <p>
 284      * The binary value is generated from pairs of hexadecimal digits that use
 285      * only the following ASCII characters:
 286      * <blockquote>
 287      *  {@code 0123456789abcdefABCDEF}
 288      * </blockquote>
 289      *
 290      * @param hexString an even numbered sequence of hexadecimal digits
 291      * @param fromIndex the index of the first digit (inclusive) to be converted
 292      * @param toIndex the index of the last digit (exclusive) to be converted
 293      * @return a binary buffer
 294      * @throws IllegalArgumentException if {@code hexString} has an odd number
 295      *         of digits or contains an illegal hexadecimal character,
 296      *         or if {@code fromIndex > toIndex}
 297      * @throws NullPointerException if {@code hexString} is {@code null}
 298      * @throws ArrayIndexOutOfBoundsException
 299      *     if {@code fromIndex < 0} or {@code toIndex > hexString.length()}
 300      */
 301     public static byte[] fromString(CharSequence hexString, int fromIndex,
 302             int toIndex) {
 303         Objects.requireNonNull(hexString, "hexString");
 304         Arrays.rangeCheck(hexString.length(), fromIndex, toIndex);
 305         return hexToBytes(hexString, fromIndex, toIndex);
 306     }
 307 
 308     /**
 309      * Generates a dump of the contents of the provided input stream, as a
 310      * stream of hexadecimal strings in hexdump format.
 311      * This method outputs the same format as
 312      * {@link #dump(byte[],OutputStream)},
 313      * without the line-separator characters.
 314      * <p>
 315      * If the input is not a multiple of 16 bytes then the final chunk will
 316      * be shorter than the preceding chunks.
 317      * <p>
 318      * On return, the input stream will be at end-of-stream.
 319      * This method does not close the input stream and may block indefinitely
 320      * reading from it. The behavior for the case where it is
 321      * <i>asynchronously closed</i>, or the thread interrupted,
 322      * is highly input stream specific, and therefore not specified.
 323      * <p>
 324      * If an I/O error occurs reading from the input stream then it may not be
 325      * at end-of-stream and may be in an inconsistent state. It is strongly
 326      * recommended that the input stream be promptly closed if an I/O error
 327      * occurs.
 328      *
 329      * @param in the input stream, non-null
 330      * @return a stream of hexadecimal strings
 331      */
 332     public static Stream<String> dumpAsStream(InputStream in) {
 333         return dumpAsStream(in, DEFAULT_CHUNK_SIZE, null);
 334     }
 335 
 336     /**
 337      * Generates a dump of the contents of the provided input stream, as a
 338      * stream of formatted hexadecimal strings. Each string is formatted
 339      * according to the {@code formatter} function, if present. Otherwise,
 340      * this method outputs the same format as
 341      * {@link #dump(byte[],OutputStream)},
 342      * without the line separator characters.
 343      * <p>
 344      * On return, the input stream will be at end-of-stream.
 345      * This method does not close the input stream and may block indefinitely
 346      * reading from it. The behavior for the case where it is
 347      * <i>asynchronously closed</i>, or the thread interrupted,
 348      * is highly input stream specific, and therefore not specified.
 349      * <p>
 350      * If an I/O error occurs reading from the input stream then it may not be
 351      * at end-of-stream and may be in an inconsistent state. It is strongly
 352      * recommended that the input stream be promptly closed if an I/O error
 353      * occurs.
 354      * <p>
 355      * If an error occurs in the {@code formatter} then an unchecked exception
 356      * will be thrown from the underlying {@code Stream} method.
 357      *
 358      * @param in the input stream, non-null
 359      * @param chunkSize the number of bytes-per-chunk (typically 16)
 360      * @param formatter a hexdump formatting function, or {@code null}
 361      * @return a stream of hexadecimal strings
 362      * @throws NullPointerException if {@code in} is {@code null}
 363      */
 364     public static Stream<String> dumpAsStream(InputStream in, int chunkSize,
 365             Formatter formatter) {
 366         Objects.requireNonNull(in, "in");
 367         final Formatter f = formatter == null ? HEXDUMP_FORMATTER : formatter;
 368 
 369         Iterator<String> iterator = new Iterator<>() {
 370             byte[] nextChunk = null;
 371             int counter = 0;
 372 
 373             @Override
 374             public boolean hasNext() {
 375                 if (nextChunk != null) {
 376                     return true;
 377                 } else {
 378                     try {
 379                         nextChunk = readChunk(in, chunkSize);
 380                         return (nextChunk != null);
 381 
 382                     } catch (IOException e) {
 383                         throw new UncheckedIOException(e);
 384                     }
 385                 }
 386             }
 387 
 388             @Override
 389             public String next() {
 390                 if (nextChunk != null || hasNext()) {
 391                     String formattedChunk =
 392                         f.format(counter * chunkSize, nextChunk, 0,
 393                             nextChunk.length);
 394                     nextChunk = null;
 395                     counter++;
 396                     return formattedChunk;
 397 
 398                 } else {
 399                     throw new NoSuchElementException();
 400                 }
 401             }
 402         };
 403 
 404         return StreamSupport.stream(
 405             Spliterators.spliteratorUnknownSize(
 406                 iterator, Spliterator.ORDERED | Spliterator.NONNULL),
 407             false);
 408     }
 409 
 410     /**
 411      * Generates a dump of the contents of the provided byte array, as a stream
 412      * of hexadecimal strings in hexdump format.
 413      * This method outputs the same format as
 414      * {@link #dump(byte[],OutputStream)},
 415      * without the line separator characters.
 416      * <p>
 417      * If the input is not a multiple of 16 bytes then the final chunk will
 418      * be shorter than the preceding chunks.
 419      *
 420      * @param bytes a binary buffer, assumed to be unmodified during use
 421      * @return a stream of hexadecimal strings
 422      * @throws NullPointerException if {@code bytes} is {@code null}
 423      */
 424     public static Stream<String> dumpAsStream(byte[] bytes) {
 425         Objects.requireNonNull(bytes, "bytes");
 426         return dumpAsStream(bytes, 0, bytes.length, DEFAULT_CHUNK_SIZE, null);
 427     }
 428 
 429     /**
 430      * Generates a dump of the contents of a <i>range</i> within the provided
 431      * byte array, as a stream of formatted hexadecimal strings. Each string is
 432      * formatted according to the {@code formatter} function, if present.
 433      * Otherwise, this method outputs the same format as
 434      * {@link #dump(byte[],OutputStream)},
 435      * without the line separator characters.
 436      * <p>
 437      * The range to be converted extends from index {@code fromIndex},
 438      * inclusive, to index {@code toIndex}, exclusive.
 439      * (If {@code fromIndex==toIndex}, the range to be converted is empty.)
 440      * If the input is not a multiple of {@code chunkSize} then the final chunk
 441      * will be shorter than the preceding chunks.
 442      * <p>
 443      * If an error occurs in the {@code formatter} then an unchecked exception
 444      * will be thrown from the underlying {@code Stream} method.
 445      *
 446      * @param bytes a binary buffer, assumed to be unmodified during use
 447      * @param fromIndex the index of the first byte (inclusive) to be converted
 448      * @param toIndex the index of the last byte (exclusive) to be converted
 449      * @param chunkSize the number of bytes-per-chunk (typically 16)
 450      * @param formatter a hexdump formatting function, or {@code null}
 451      * @return a stream of hexadecimal strings
 452      * @throws NullPointerException if {@code bytes} is {@code null}
 453      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 454      * @throws ArrayIndexOutOfBoundsException
 455      *     if {@code fromIndex < 0} or {@code toIndex > bytes.length}
 456      */
 457     public static Stream<String> dumpAsStream(byte[] bytes, int fromIndex,
 458             int toIndex, int chunkSize, Formatter formatter) {
 459         Objects.requireNonNull(bytes, "bytes");
 460         Arrays.rangeCheck(bytes.length, fromIndex, toIndex);
 461         final Formatter f = formatter == null ? HEXDUMP_FORMATTER : formatter;
 462 
 463         int range = toIndex - fromIndex;
 464         if (range == 0) {
 465             return Stream.empty();
 466         }
 467         final int length = chunkSize > range ? range : chunkSize;
 468 
 469         return IntStream.range(0, roundUp(range, length))
 470             .mapToObj(i -> {
 471                 int from = fromIndex + (i * length);
 472                 int to = from + length;
 473                 if (to > toIndex) {
 474                     to = toIndex;
 475                 }
 476                 return f.format(i * chunkSize, bytes, from, to);
 477             });
 478     }
 479 
 480     /**
 481      * Generates a dump of the contents of a <i>range</i> within the provided
 482      * ByteBuffer, as a stream of formatted hexadecimal strings. Each string is
 483      * formatted according to the {@code formatter} function, if present.
 484      * Otherwise, this method outputs the same format as
 485      * {@link #dump(byte[],OutputStream)},
 486      * without the line separator characters.
 487      * <p>
 488      * The range to be converted extends from index {@code fromIndex},
 489      * inclusive, to index {@code toIndex}, exclusive.
 490      * (If {@code fromIndex==toIndex}, the range to be converted is empty.)
 491      * If the input is not a multiple of {@code chunkSize} then the final chunk
 492      * will be shorter than the preceding chunks.
 493      * <p>
 494      * If an error occurs in the {@code formatter} then an unchecked exception
 495      * will be thrown from the underlying {@code Stream} method.
 496      *
 497      * @param buffer a binary buffer, assumed to be unmodified during use
 498      * @param fromIndex the index of the first byte (inclusive) to be converted
 499      * @param toIndex the index of the last byte (exclusive) to be converted
 500      * @param chunkSize the number of bytes-per-chunk (typically 16)
 501      * @param formatter a hexdump formatting function, or {@code null}
 502      * @return a stream of hexadecimal strings
 503      * @throws NullPointerException if {@code buffer} is {@code null}
 504      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 505      * @throws ArrayIndexOutOfBoundsException
 506      *     if {@code fromIndex < 0} or {@code toIndex > buffer.remaining()}
 507      */
 508     public static Stream<String> dumpAsStream(ByteBuffer buffer, int fromIndex,
 509             int toIndex, int chunkSize, Formatter formatter) {
 510         Objects.requireNonNull(buffer, "buffer");
 511         byte[] bytes = new byte[Math.max(0, buffer.limit() - buffer.position())];
 512         try {
 513             buffer.get(bytes);
 514         } catch (BufferUnderflowException e) {
 515             // Safe to ignore
 516         }
 517 
 518         return dumpAsStream(bytes, fromIndex, toIndex, chunkSize, formatter);
 519     }
 520 
 521     /**
 522      * Generates a hexadecimal dump of the contents of the provided byte array
 523      * and writes it to the provided output stream.
 524      * This method behaves <i>as if</i>:
 525      * <pre>{@code
 526      *     Hex.dumpAsStream(bytes, 16,
 527      *         (offset, chunk, from, to) ->
 528      *             String.format("%08x  %s  |%s|",
 529      *                 offset,
 530      *                 Hex.toFormattedHexString(chunk, from, to),
 531      *                 Hex.toPrintableString(chunk, from, to)))
 532      *         .forEachOrdered(PrintStream::println);
 533      * }</pre>
 534      * <p>
 535      * This method does not close the output stream and may block indefinitely
 536      * writing to it. The behavior for the case where it is
 537      * <i>asynchronously closed</i>, or the thread interrupted,
 538      * is highly output stream specific, and therefore not specified.
 539      * <p>
 540      * If an I/O error occurs writing to the output stream, then it may be
 541      * in an inconsistent state. It is strongly recommended that the output
 542      * stream be promptly closed if an I/O error occurs.
 543      *
 544      * @param bytes the binary buffer, assumed to be unmodified during use
 545      * @param out the output stream, non-null
 546      * @throws IOException if an I/O error occurs when writing
 547      * @throws NullPointerException if {@code bytes} or {@code out} is
 548      *     {@code null}
 549      */
 550     public static void dump(byte[] bytes, OutputStream out) throws IOException {
 551         Objects.requireNonNull(bytes, "bytes");
 552         dump(bytes, 0, bytes.length, out);
 553     }
 554 
 555     /**
 556      * Generates a hexadecimal dump of the contents of a <i>range</i> within the
 557      * provided byte array and writes it to the provided output stream.
 558      * This method outputs the same format as
 559      * {@link #dump(byte[],OutputStream)}. 
 560      * <p>
 561      * The range to be converted extends from index {@code fromIndex},
 562      * inclusive, to index {@code toIndex}, exclusive.
 563      * (If {@code fromIndex==toIndex}, the range to be converted is empty.)
 564      * <p>
 565      * This method does not close the output stream and may block indefinitely
 566      * writing to it. The behavior for the case where it is
 567      * <i>asynchronously closed</i>, or the thread interrupted,
 568      * is highly output stream specific, and therefore not specified.
 569      * <p>
 570      * If an I/O error occurs writing to the output stream, then it may be
 571      * in an inconsistent state. It is strongly recommended that the output
 572      * stream be promptly closed if an I/O error occurs.
 573      *
 574      * @param bytes the binary buffer, assumed to be unmodified during use
 575      * @param fromIndex the index of the first byte (inclusive) to be converted
 576      * @param toIndex the index of the last byte (exclusive) to be converted
 577      * @param out the output stream, non-null
 578      * @throws IOException if an I/O error occurs when writing
 579      * @throws NullPointerException if {@code bytes} or {@code out} is
 580      *     {@code null}
 581      * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 582      * @throws ArrayIndexOutOfBoundsException
 583      *     if {@code fromIndex < 0} or {@code toIndex > bytes.length}
 584      */
 585     public static void dump(byte[] bytes, int fromIndex, int toIndex,
 586         OutputStream out) throws IOException {
 587 
 588         dumpAsStream(bytes, fromIndex, toIndex, DEFAULT_CHUNK_SIZE, null)
 589             .forEachOrdered(getPrintStream(out)::println);
 590     }
 591 
 592     /**
 593      * Generates a hexadecimal dump of the contents of the provided input stream
 594      * and writes it to the provided output stream.
 595      * This method outputs the same format as
 596      * {@link #dump(byte[],OutputStream)}.
 597      * <p>
 598      * Reads all bytes from the input stream.
 599      * On return, the input stream will be at end-of-stream. This method does
 600      * not close either stream and may block indefinitely reading from the
 601      * input stream, or writing to the output stream. The behavior for the case
 602      * where the input and/or output stream is <i>asynchronously closed</i>,
 603      * or the thread interrupted, is highly input stream and output stream
 604      * specific, and therefore not specified.
 605      * <p>
 606      * If an I/O error occurs reading from the input stream or writing to the
 607      * output stream, then it may do so after some bytes have been read or
 608      * written. Consequently the input stream may not be at end-of-stream and
 609      * one, or both, streams may be in an inconsistent state. It is strongly
 610      * recommended that both streams be promptly closed if an I/O error occurs.
 611      *
 612      * @param  in the input stream, non-null
 613      * @param  out the output stream, non-null
 614      * @throws IOException if an I/O error occurs when reading or writing
 615      * @throws NullPointerException if {@code in} or {@code out} is {@code null}
 616      */
 617     public static void dump(InputStream in, OutputStream out)
 618             throws IOException {
 619         dumpAsStream(in, DEFAULT_CHUNK_SIZE, null)
 620             .forEachOrdered(getPrintStream(out)::println);
 621     }
 622 
 623     // Returns a hexadecimal string formatted according to the specified number
 624     // of columns and with/without space separators between pairs of hexadecimal
 625     // digits. Newlines are added when the chunkSize is exceeded. If the final
 626     // line is less than chunkSize then it is padded with spaces.
 627     private static String toFormattedString(byte[] bytes, int fromIndex,
 628         int toIndex, int chunkSize, int columns, boolean useSeparators) {
 629 
 630         int range = toIndex - fromIndex;
 631         if (range == 0) {
 632             return "";
 633         }
 634         int columnWidth = chunkSize / columns;
 635         int lineLength = useSeparators
 636             ? chunkSize * 3 + (columns - 1) - 1
 637             : chunkSize * 2 + (columns - 1);
 638 
 639         StringBuilder hexString =
 640             new StringBuilder(lineLength + lineLength * (range / chunkSize));
 641         int position = 1;
 642         int newlineCount = 0;
 643         for (int i = fromIndex; i < toIndex; i++, position++) {
 644             // add the pair of hex. digits
 645             hexString.append(HEX_DIGITS[(bytes[i] >> 4) & 0xF]);
 646             hexString.append(HEX_DIGITS[(bytes[i] & 0xF)]);
 647             // add a space between pairs of hex. digits
 648             if (useSeparators && position != chunkSize) {
 649                 hexString.append(' ');
 650             }
 651             // add a space between columns
 652             if (position % columnWidth == 0 && position != chunkSize) {
 653                 hexString.append(' ');
 654             }
 655             // handle end-of-line
 656             if (position == chunkSize && (i + 1 < toIndex)) {
 657                 hexString.append('\n');
 658                 newlineCount++;
 659                 position = 0;
 660             }
 661         }
 662         // add final line padding, if needed
 663         if (position <= chunkSize) {
 664             int len = hexString.length() - (newlineCount * NEWLINE_LENGTH);
 665             for (int i = len % lineLength; i < lineLength; i++) {
 666                 hexString.append(' ');
 667             }
 668         }
 669 
 670         return hexString.toString();
 671     }
 672 
 673     private static byte[] hexToBytes(CharSequence hexString, int fromIndex,
 674             int toIndex) {
 675 
 676         int len = toIndex - fromIndex;
 677         if (len % 2 != 0) {
 678             throw new IllegalArgumentException(
 679                 "contains an odd number of digits: " + hexString);
 680         }
 681         // Skip the '0x' prefix, if present
 682         if (len > 2 &&
 683             hexString.charAt(fromIndex) == '0' &&
 684             hexString.charAt(fromIndex + 1) == 'x') {
 685             fromIndex += 2;
 686             len -= 2;
 687         }
 688         byte[] bytes = new byte[len / 2];
 689 
 690         for (int i = 0; i < len; i += 2) {
 691             int hexIndex = fromIndex + i;
 692             int high = hexToBinary(hexString.charAt(hexIndex));
 693             int low = hexToBinary(hexString.charAt(hexIndex + 1));
 694             if (high == -1 || low == -1) {
 695                 throw new IllegalArgumentException(
 696                    "contains an illegal hexadecimal character: " + hexString);
 697             }
 698 
 699             bytes[i / 2] = (byte) (high * 16 + low);
 700         }
 701         return bytes;
 702     }
 703 
 704 //VR: TBD: check for (total + chunkSize - 1) > Integer.MAX_VALUE ??
 705     private static int roundUp(int total, int chunkSize) {
 706         return (total + chunkSize - 1) / chunkSize;
 707     }
 708 
 709     private static byte[] readChunk(InputStream inStream, int chunkSize)
 710             throws IOException {
 711         byte[] buffer = new byte[chunkSize];
 712 
 713         int n = inStream.readNBytes(buffer, 0, buffer.length);
 714         if (n == 0) {
 715             return null;
 716         } else if (n < chunkSize) {
 717             return Arrays.copyOf(buffer, n);
 718         } else {
 719             return buffer;
 720         }
 721     }
 722 
 723     private static PrintStream getPrintStream(OutputStream out)
 724             throws IOException {
 725         Objects.requireNonNull(out, "out");
 726         PrintStream ps = null;
 727         if (out instanceof PrintStream) {
 728             ps = (PrintStream) out;
 729         } else {
 730             ps = new PrintStream(out, true); // auto flush
 731         }
 732         return ps;
 733     }
 734 
 735     private static int hexToBinary(char ch) {
 736         if ('0' <= ch && ch <= '9') {
 737             return ch - '0';
 738         }
 739         if ('A' <= ch && ch <= 'F') {
 740             return ch - 'A' + 10;
 741         }
 742         if ('a' <= ch && ch <= 'f') {
 743             return ch - 'a' + 10;
 744         }
 745         return -1;
 746     }
 747 
 748     /**
 749      * Represents a function that formats a binary buffer as a hexadecimal
 750      * string.
 751      * 
 752      * <p>This is a <a href="package-summary.html">functional interface</a>
 753      * whose functional method is
 754      * {@link #format}.
 755      *
 756      * @see Function
 757      * @since 12
 758      */
 759     @FunctionalInterface
 760     public interface Formatter {
 761         /**
 762          * Returns a formatted hexadecimal string representation of the contents
 763          * of a chunk within a binary buffer.
 764          *
 765          * @param offset is the offset into the byte buffer
 766          * @param chunk a binary buffer
 767          * @param fromIndex the index of the first byte (inclusive) of the
 768          *     chunk to be converted
 769          * @param toIndex the index of the last byte (exclusive) of the
 770          *     chunk to be converted
 771          * @return a hexadecimal string representation of a chunk of the binary
 772          *     buffer
 773          * @throws NullPointerException if {@code chunk} is {@code null}
 774          * @throws IllegalArgumentException if {@code fromIndex > toIndex}
 775          * @throws ArrayIndexOutOfBoundsException
 776          *     if {@code fromIndex < 0} or {@code toIndex > chunk.length}
 777          */
 778         String format(long offset, byte[] chunk, int fromIndex, int toIndex);
 779     }
 780 }