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