001/*
002 * Copyright (C) 2012 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.io;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkPositionIndexes;
020import static com.google.common.base.Preconditions.checkState;
021import static com.google.common.math.IntMath.divide;
022import static com.google.common.math.IntMath.log2;
023import static java.lang.Math.max;
024import static java.lang.Math.min;
025import static java.lang.System.arraycopy;
026import static java.math.RoundingMode.CEILING;
027import static java.math.RoundingMode.FLOOR;
028import static java.math.RoundingMode.UNNECESSARY;
029
030import com.google.common.annotations.GwtCompatible;
031import com.google.common.annotations.GwtIncompatible;
032import com.google.common.annotations.J2ktIncompatible;
033import com.google.common.base.Ascii;
034import com.google.errorprone.annotations.concurrent.LazyInit;
035import java.io.IOException;
036import java.io.InputStream;
037import java.io.OutputStream;
038import java.io.Reader;
039import java.io.Writer;
040import java.util.Arrays;
041import java.util.Objects;
042import org.jspecify.annotations.Nullable;
043
044/**
045 * A binary encoding scheme for reversibly translating between byte sequences and printable ASCII
046 * strings. This class includes several constants for encoding schemes specified by <a
047 * href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression:
048 *
049 * {@snippet :
050 * BaseEncoding.base32().encode("foo".getBytes(US_ASCII))
051 * }
052 *
053 * <p>returns the string {@code "MZXW6==="}, and
054 *
055 * {@snippet :
056 * byte[] decoded = BaseEncoding.base32().decode("MZXW6===");
057 * }
058 *
059 * <p>...returns the ASCII bytes of the string {@code "foo"}.
060 *
061 * <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with RFC
062 * 4648. Decoding rejects characters in the wrong case, though padding is optional. To modify
063 * encoding and decoding behavior, use configuration methods to obtain a new encoding with modified
064 * behavior:
065 *
066 * {@snippet :
067 * BaseEncoding.base16().lowerCase().decode("deadbeef");
068 * }
069 *
070 * <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect
071 * on the receiving instance; you must store and use the new encoding instance it returns, instead.
072 *
073 * {@snippet :
074 * // Do NOT do this
075 * BaseEncoding hex = BaseEncoding.base16();
076 * hex.lowerCase(); // does nothing!
077 * return hex.decode("deadbeef"); // throws an IllegalArgumentException
078 * }
079 *
080 * <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to {@code
081 * x}, but the reverse does not necessarily hold.
082 *
083 * <table>
084 * <caption>Encodings</caption>
085 * <tr>
086 * <th>Encoding
087 * <th>Alphabet
088 * <th>{@code char:byte} ratio
089 * <th>Default padding
090 * <th>Comments
091 * <tr>
092 * <td>{@link #base16()}
093 * <td>0-9 A-F
094 * <td>2.00
095 * <td>N/A
096 * <td>Traditional hexadecimal. Defaults to upper case.
097 * <tr>
098 * <td>{@link #base32()}
099 * <td>A-Z 2-7
100 * <td>1.60
101 * <td>=
102 * <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case.
103 * <tr>
104 * <td>{@link #base32Hex()}
105 * <td>0-9 A-V
106 * <td>1.60
107 * <td>=
108 * <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case.
109 * <tr>
110 * <td>{@link #base64()}
111 * <td>A-Z a-z 0-9 + /
112 * <td>1.33
113 * <td>=
114 * <td>
115 * <tr>
116 * <td>{@link #base64Url()}
117 * <td>A-Z a-z 0-9 - _
118 * <td>1.33
119 * <td>=
120 * <td>Safe to use as filenames, or to pass in URLs without escaping
121 * </table>
122 *
123 * <p>All instances of this class are immutable, so they may be stored safely as static constants.
124 *
125 * @author Louis Wasserman
126 * @since 14.0
127 */
128@GwtCompatible
129public abstract class BaseEncoding {
130  // TODO(lowasser): consider making encodeTo(Appendable, byte[], int, int) public.
131
132  BaseEncoding() {}
133
134  /**
135   * Exception indicating invalid base-encoded input encountered while decoding.
136   *
137   * @author Louis Wasserman
138   * @since 15.0
139   */
140  public static final class DecodingException extends IOException {
141    DecodingException(@Nullable String message) {
142      super(message);
143    }
144  }
145
146  /** Encodes the specified byte array, and returns the encoded {@code String}. */
147  public String encode(byte[] bytes) {
148    return encode(bytes, 0, bytes.length);
149  }
150
151  /**
152   * Encodes the specified range of the specified byte array, and returns the encoded {@code
153   * String}.
154   */
155  public final String encode(byte[] bytes, int off, int len) {
156    checkPositionIndexes(off, off + len, bytes.length);
157    StringBuilder result = new StringBuilder(maxEncodedSize(len));
158    try {
159      encodeTo(result, bytes, off, len);
160    } catch (IOException impossible) {
161      throw new AssertionError(impossible);
162    }
163    return result.toString();
164  }
165
166  /**
167   * Returns an {@code OutputStream} that encodes bytes using this encoding into the specified
168   * {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code
169   * Writer}.
170   */
171  @J2ktIncompatible
172  @GwtIncompatible // Writer,OutputStream
173  public abstract OutputStream encodingStream(Writer writer);
174
175  /**
176   * Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}.
177   */
178  @J2ktIncompatible
179  @GwtIncompatible // ByteSink,CharSink
180  public final ByteSink encodingSink(CharSink encodedSink) {
181    checkNotNull(encodedSink);
182    return new ByteSink() {
183      @Override
184      public OutputStream openStream() throws IOException {
185        return encodingStream(encodedSink.openStream());
186      }
187    };
188  }
189
190  // TODO(lowasser): document the extent of leniency, probably after adding ignore(CharMatcher)
191
192  private static byte[] extract(byte[] result, int length) {
193    if (length == result.length) {
194      return result;
195    }
196    byte[] trunc = new byte[length];
197    arraycopy(result, 0, trunc, 0, length);
198    return trunc;
199  }
200
201  /**
202   * Determines whether the specified character sequence is a valid encoded string according to this
203   * encoding.
204   *
205   * @since 20.0
206   */
207  public abstract boolean canDecode(CharSequence chars);
208
209  /**
210   * Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the
211   * inverse operation to {@link #encode(byte[])}.
212   *
213   * @throws IllegalArgumentException if the input is not a valid encoded string according to this
214   *     encoding.
215   */
216  public final byte[] decode(CharSequence chars) {
217    try {
218      return decodeChecked(chars);
219    } catch (DecodingException badInput) {
220      throw new IllegalArgumentException(badInput);
221    }
222  }
223
224  /**
225   * Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the
226   * inverse operation to {@link #encode(byte[])}.
227   *
228   * @throws DecodingException if the input is not a valid encoded string according to this
229   *     encoding.
230   */
231  final byte[] decodeChecked(CharSequence chars)
232      throws DecodingException {
233    chars = trimTrailingPadding(chars);
234    byte[] tmp = new byte[maxDecodedSize(chars.length())];
235    int len = decodeTo(tmp, chars);
236    return extract(tmp, len);
237  }
238
239  /**
240   * Returns an {@code InputStream} that decodes base-encoded input from the specified {@code
241   * Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors.
242   */
243  @J2ktIncompatible
244  @GwtIncompatible // Reader,InputStream
245  public abstract InputStream decodingStream(Reader reader);
246
247  /**
248   * Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code
249   * CharSource}.
250   */
251  @J2ktIncompatible
252  @GwtIncompatible // ByteSource,CharSource
253  public final ByteSource decodingSource(CharSource encodedSource) {
254    checkNotNull(encodedSource);
255    return new ByteSource() {
256      @Override
257      public InputStream openStream() throws IOException {
258        return decodingStream(encodedSource.openStream());
259      }
260    };
261  }
262
263  // Implementations for encoding/decoding
264
265  abstract int maxEncodedSize(int bytes);
266
267  abstract void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException;
268
269  abstract int maxDecodedSize(int chars);
270
271  abstract int decodeTo(byte[] target, CharSequence chars) throws DecodingException;
272
273  CharSequence trimTrailingPadding(CharSequence chars) {
274    return checkNotNull(chars);
275  }
276
277  // Modified encoding generators
278
279  /**
280   * Returns an encoding that behaves equivalently to this encoding, but omits any padding
281   * characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648
282   * section 3.2</a>, Padding of Encoded Data.
283   */
284  public abstract BaseEncoding omitPadding();
285
286  /**
287   * Returns an encoding that behaves equivalently to this encoding, but uses an alternate character
288   * for padding.
289   *
290   * @throws IllegalArgumentException if this padding character is already used in the alphabet or a
291   *     separator
292   */
293  public abstract BaseEncoding withPadChar(char padChar);
294
295  /**
296   * Returns an encoding that behaves equivalently to this encoding, but adds a separator string
297   * after every {@code n} characters. Any occurrences of any characters that occur in the separator
298   * are skipped over in decoding.
299   *
300   * @throws IllegalArgumentException if any alphabet or padding characters appear in the separator
301   *     string, or if {@code n <= 0}
302   * @throws UnsupportedOperationException if this encoding already uses a separator
303   */
304  public abstract BaseEncoding withSeparator(String separator, int n);
305
306  /**
307   * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
308   * uppercase letters. Padding and separator characters remain in their original case.
309   *
310   * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
311   *     lower-case characters
312   */
313  public abstract BaseEncoding upperCase();
314
315  /**
316   * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
317   * lowercase letters. Padding and separator characters remain in their original case.
318   *
319   * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
320   *     lower-case characters
321   */
322  public abstract BaseEncoding lowerCase();
323
324  /**
325   * Returns an encoding that behaves equivalently to this encoding, but decodes letters without
326   * regard to case.
327   *
328   * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
329   *     lower-case characters
330   * @since 32.0.0
331   */
332  public abstract BaseEncoding ignoreCase();
333
334  private static final BaseEncoding BASE64 =
335      new Base64Encoding(
336          "base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '=');
337
338  /**
339   * The "base64" base encoding specified by <a
340   * href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding.
341   * (This is the same as the base 64 encoding from <a
342   * href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.)
343   *
344   * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
345   * omitted} or {@linkplain #withPadChar(char) replaced}.
346   *
347   * <p>No line feeds are added by default, as per <a
348   * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
349   * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
350   */
351  public static BaseEncoding base64() {
352    return BASE64;
353  }
354
355  private static final BaseEncoding BASE64_URL =
356      new Base64Encoding(
357          "base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '=');
358
359  /**
360   * The "base64url" encoding specified by <a
361   * href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding
362   * with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64." (This
363   * is the same as the base 64 encoding with URL and filename safe alphabet from <a
364   * href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.)
365   *
366   * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
367   * omitted} or {@linkplain #withPadChar(char) replaced}.
368   *
369   * <p>No line feeds are added by default, as per <a
370   * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
371   * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
372   */
373  public static BaseEncoding base64Url() {
374    return BASE64_URL;
375  }
376
377  private static final BaseEncoding BASE32 =
378      new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '=');
379
380  /**
381   * The "base32" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-6">RFC
382   * 4648 section 6</a>, Base 32 Encoding. (This is the same as the base 32 encoding from <a
383   * href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.)
384   *
385   * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
386   * omitted} or {@linkplain #withPadChar(char) replaced}.
387   *
388   * <p>No line feeds are added by default, as per <a
389   * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
390   * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
391   */
392  public static BaseEncoding base32() {
393    return BASE32;
394  }
395
396  private static final BaseEncoding BASE32_HEX =
397      new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '=');
398
399  /**
400   * The "base32hex" encoding specified by <a
401   * href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding
402   * with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548.
403   *
404   * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
405   * omitted} or {@linkplain #withPadChar(char) replaced}.
406   *
407   * <p>No line feeds are added by default, as per <a
408   * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
409   * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
410   */
411  public static BaseEncoding base32Hex() {
412    return BASE32_HEX;
413  }
414
415  private static final BaseEncoding BASE16 = new Base16Encoding("base16()", "0123456789ABCDEF");
416
417  /**
418   * The "base16" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-8">RFC
419   * 4648 section 8</a>, Base 16 Encoding. (This is the same as the base 16 encoding from <a
420   * href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as
421   * "hexadecimal" format.
422   *
423   * <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and {@link #omitPadding()}
424   * have no effect.
425   *
426   * <p>No line feeds are added by default, as per <a
427   * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
428   * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
429   *
430   * <p><b>Java 17+ users:</b> Consider using the {@link java.util.HexFormat} API instead.
431   */
432  public static BaseEncoding base16() {
433    return BASE16;
434  }
435
436  static final class Alphabet {
437    private final String name;
438    // this is meant to be immutable -- don't modify it!
439    private final char[] chars;
440    final int mask;
441    final int bitsPerChar;
442    final int charsPerChunk;
443    final int bytesPerChunk;
444    private final byte[] decodabet;
445    private final boolean[] validPadding;
446    private final boolean ignoreCase;
447
448    Alphabet(String name, char[] chars) {
449      this(name, chars, decodabetFor(chars), /* ignoreCase= */ false);
450    }
451
452    private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) {
453      this.name = checkNotNull(name);
454      this.chars = checkNotNull(chars);
455      try {
456        this.bitsPerChar = log2(chars.length, UNNECESSARY);
457      } catch (ArithmeticException e) {
458        throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e);
459      }
460
461      // Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into
462      // 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3.
463      // We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a
464      // multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many
465      // extra zero bits we need to add to the end of bitsPerChar to get 3 in total.
466      // The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII
467      // characters that can't happen.
468      int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar);
469      this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar);
470      this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar;
471
472      this.mask = chars.length - 1;
473
474      this.decodabet = decodabet;
475
476      boolean[] validPadding = new boolean[charsPerChunk];
477      for (int i = 0; i < bytesPerChunk; i++) {
478        validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
479      }
480      this.validPadding = validPadding;
481      this.ignoreCase = ignoreCase;
482    }
483
484    private static byte[] decodabetFor(char[] chars) {
485      byte[] decodabet = new byte[Ascii.MAX + 1];
486      Arrays.fill(decodabet, (byte) -1);
487      for (int i = 0; i < chars.length; i++) {
488        char c = chars[i];
489        checkArgument(c < decodabet.length, "Non-ASCII character: %s", c);
490        checkArgument(decodabet[c] == -1, "Duplicate character: %s", c);
491        decodabet[c] = (byte) i;
492      }
493      return decodabet;
494    }
495
496    /** Returns an equivalent {@code Alphabet} except it ignores case. */
497    Alphabet ignoreCase() {
498      if (ignoreCase) {
499        return this;
500      }
501
502      // We can't use .clone() because of GWT.
503      byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length);
504      for (int upper = 'A'; upper <= 'Z'; upper++) {
505        int lower = upper | 0x20;
506        byte decodeUpper = decodabet[upper];
507        byte decodeLower = decodabet[lower];
508        if (decodeUpper == -1) {
509          newDecodabet[upper] = decodeLower;
510        } else {
511          checkState(
512              decodeLower == -1,
513              "Can't ignoreCase() since '%s' and '%s' encode different values",
514              (char) upper,
515              (char) lower);
516          newDecodabet[lower] = decodeUpper;
517        }
518      }
519      return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true);
520    }
521
522    char encode(int bits) {
523      return chars[bits];
524    }
525
526    boolean isValidPaddingStartPosition(int index) {
527      return validPadding[index % charsPerChunk];
528    }
529
530    boolean canDecode(char ch) {
531      return ch <= Ascii.MAX && decodabet[ch] != -1;
532    }
533
534    int decode(char ch) throws DecodingException {
535      if (ch > Ascii.MAX) {
536        throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch));
537      }
538      int result = decodabet[ch];
539      if (result == -1) {
540        if (ch <= 0x20 || ch == Ascii.MAX) {
541          throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch));
542        } else {
543          throw new DecodingException("Unrecognized character: " + ch);
544        }
545      }
546      return result;
547    }
548
549    private boolean hasLowerCase() {
550      for (char c : chars) {
551        if (Ascii.isLowerCase(c)) {
552          return true;
553        }
554      }
555      return false;
556    }
557
558    private boolean hasUpperCase() {
559      for (char c : chars) {
560        if (Ascii.isUpperCase(c)) {
561          return true;
562        }
563      }
564      return false;
565    }
566
567    Alphabet upperCase() {
568      if (!hasLowerCase()) {
569        return this;
570      }
571      checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet");
572      char[] upperCased = new char[chars.length];
573      for (int i = 0; i < chars.length; i++) {
574        upperCased[i] = Ascii.toUpperCase(chars[i]);
575      }
576      Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased);
577      return ignoreCase ? upperCase.ignoreCase() : upperCase;
578    }
579
580    Alphabet lowerCase() {
581      if (!hasUpperCase()) {
582        return this;
583      }
584      checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet");
585      char[] lowerCased = new char[chars.length];
586      for (int i = 0; i < chars.length; i++) {
587        lowerCased[i] = Ascii.toLowerCase(chars[i]);
588      }
589      Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased);
590      return ignoreCase ? lowerCase.ignoreCase() : lowerCase;
591    }
592
593    public boolean matches(char c) {
594      return c < decodabet.length && decodabet[c] != -1;
595    }
596
597    @Override
598    public String toString() {
599      return name;
600    }
601
602    @Override
603    public boolean equals(@Nullable Object other) {
604      if (other instanceof Alphabet) {
605        Alphabet that = (Alphabet) other;
606        return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars);
607      }
608      return false;
609    }
610
611    @Override
612    public int hashCode() {
613      return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237);
614    }
615  }
616
617  private static class StandardBaseEncoding extends BaseEncoding {
618    final Alphabet alphabet;
619
620    final @Nullable Character paddingChar;
621
622    StandardBaseEncoding(String name, String alphabetChars, @Nullable Character paddingChar) {
623      this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);
624    }
625
626    StandardBaseEncoding(Alphabet alphabet, @Nullable Character paddingChar) {
627      this.alphabet = checkNotNull(alphabet);
628      checkArgument(
629          paddingChar == null || !alphabet.matches(paddingChar),
630          "Padding character %s was already in alphabet",
631          paddingChar);
632      this.paddingChar = paddingChar;
633    }
634
635    @Override
636    int maxEncodedSize(int bytes) {
637      return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING);
638    }
639
640    @J2ktIncompatible
641    @GwtIncompatible // Writer,OutputStream
642    @Override
643    public OutputStream encodingStream(Writer out) {
644      checkNotNull(out);
645      return new OutputStream() {
646        int bitBuffer = 0;
647        int bitBufferLength = 0;
648        int writtenChars = 0;
649
650        @Override
651        public void write(int b) throws IOException {
652          bitBuffer <<= 8;
653          bitBuffer |= b & 0xFF;
654          bitBufferLength += 8;
655          while (bitBufferLength >= alphabet.bitsPerChar) {
656            int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask;
657            out.write(alphabet.encode(charIndex));
658            writtenChars++;
659            bitBufferLength -= alphabet.bitsPerChar;
660          }
661        }
662
663        @Override
664        public void flush() throws IOException {
665          out.flush();
666        }
667
668        @Override
669        public void close() throws IOException {
670          if (bitBufferLength > 0) {
671            int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask;
672            out.write(alphabet.encode(charIndex));
673            writtenChars++;
674            if (paddingChar != null) {
675              while (writtenChars % alphabet.charsPerChunk != 0) {
676                out.write(paddingChar);
677                writtenChars++;
678              }
679            }
680          }
681          out.close();
682        }
683      };
684    }
685
686    @Override
687    void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
688      checkNotNull(target);
689      checkPositionIndexes(off, off + len, bytes.length);
690      for (int i = 0; i < len; i += alphabet.bytesPerChunk) {
691        encodeChunkTo(target, bytes, off + i, min(alphabet.bytesPerChunk, len - i));
692      }
693    }
694
695    void encodeChunkTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
696      checkNotNull(target);
697      checkPositionIndexes(off, off + len, bytes.length);
698      checkArgument(len <= alphabet.bytesPerChunk);
699      long bitBuffer = 0;
700      for (int i = 0; i < len; ++i) {
701        bitBuffer |= bytes[off + i] & 0xFF;
702        bitBuffer <<= 8; // Add additional zero byte in the end.
703      }
704      // Position of first character is length of bitBuffer minus bitsPerChar.
705      int bitOffset = (len + 1) * 8 - alphabet.bitsPerChar;
706      int bitsProcessed = 0;
707      while (bitsProcessed < len * 8) {
708        int charIndex = (int) (bitBuffer >>> (bitOffset - bitsProcessed)) & alphabet.mask;
709        target.append(alphabet.encode(charIndex));
710        bitsProcessed += alphabet.bitsPerChar;
711      }
712      if (paddingChar != null) {
713        while (bitsProcessed < alphabet.bytesPerChunk * 8) {
714          target.append(paddingChar);
715          bitsProcessed += alphabet.bitsPerChar;
716        }
717      }
718    }
719
720    @Override
721    int maxDecodedSize(int chars) {
722      return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L);
723    }
724
725    @Override
726    CharSequence trimTrailingPadding(CharSequence chars) {
727      checkNotNull(chars);
728      if (paddingChar == null) {
729        return chars;
730      }
731      char padChar = paddingChar;
732      int l;
733      for (l = chars.length() - 1; l >= 0; l--) {
734        if (chars.charAt(l) != padChar) {
735          break;
736        }
737      }
738      return chars.subSequence(0, l + 1);
739    }
740
741    @Override
742    public boolean canDecode(CharSequence chars) {
743      checkNotNull(chars);
744      chars = trimTrailingPadding(chars);
745      if (!alphabet.isValidPaddingStartPosition(chars.length())) {
746        return false;
747      }
748      for (int i = 0; i < chars.length(); i++) {
749        if (!alphabet.canDecode(chars.charAt(i))) {
750          return false;
751        }
752      }
753      return true;
754    }
755
756    @Override
757    int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
758      checkNotNull(target);
759      chars = trimTrailingPadding(chars);
760      if (!alphabet.isValidPaddingStartPosition(chars.length())) {
761        throw new DecodingException("Invalid input length " + chars.length());
762      }
763      int bytesWritten = 0;
764      for (int charIdx = 0; charIdx < chars.length(); charIdx += alphabet.charsPerChunk) {
765        long chunk = 0;
766        int charsProcessed = 0;
767        for (int i = 0; i < alphabet.charsPerChunk; i++) {
768          chunk <<= alphabet.bitsPerChar;
769          if (charIdx + i < chars.length()) {
770            chunk |= alphabet.decode(chars.charAt(charIdx + charsProcessed++));
771          }
772        }
773        int minOffset = alphabet.bytesPerChunk * 8 - charsProcessed * alphabet.bitsPerChar;
774        for (int offset = (alphabet.bytesPerChunk - 1) * 8; offset >= minOffset; offset -= 8) {
775          target[bytesWritten++] = (byte) ((chunk >>> offset) & 0xFF);
776        }
777      }
778      return bytesWritten;
779    }
780
781    @Override
782    @J2ktIncompatible
783    @GwtIncompatible // Reader,InputStream
784    public InputStream decodingStream(Reader reader) {
785      checkNotNull(reader);
786      return new InputStream() {
787        int bitBuffer = 0;
788        int bitBufferLength = 0;
789        int readChars = 0;
790        boolean hitPadding = false;
791
792        @Override
793        public int read() throws IOException {
794          while (true) {
795            int readChar = reader.read();
796            if (readChar == -1) {
797              if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) {
798                throw new DecodingException("Invalid input length " + readChars);
799              }
800              return -1;
801            }
802            readChars++;
803            char ch = (char) readChar;
804            if (paddingChar != null && paddingChar == ch) {
805              if (!hitPadding
806                  && (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) {
807                throw new DecodingException("Padding cannot start at index " + readChars);
808              }
809              hitPadding = true;
810            } else if (hitPadding) {
811              throw new DecodingException(
812                  "Expected padding character but found '" + ch + "' at index " + readChars);
813            } else {
814              bitBuffer <<= alphabet.bitsPerChar;
815              bitBuffer |= alphabet.decode(ch);
816              bitBufferLength += alphabet.bitsPerChar;
817
818              if (bitBufferLength >= 8) {
819                bitBufferLength -= 8;
820                return (bitBuffer >> bitBufferLength) & 0xFF;
821              }
822            }
823          }
824        }
825
826        @Override
827        public int read(byte[] buf, int off, int len) throws IOException {
828          // Overriding this to work around the fact that InputStream's default implementation of
829          // this method will silently swallow exceptions thrown by the single-byte read() method
830          // (other than on the first call to it), which in this case can cause invalid encoded
831          // strings to not throw an exception.
832          // See https://github.com/google/guava/issues/3542
833          checkPositionIndexes(off, off + len, buf.length);
834
835          int i = off;
836          for (; i < off + len; i++) {
837            int b = read();
838            if (b == -1) {
839              int read = i - off;
840              return read == 0 ? -1 : read;
841            }
842            buf[i] = (byte) b;
843          }
844          return i - off;
845        }
846
847        @Override
848        public void close() throws IOException {
849          reader.close();
850        }
851      };
852    }
853
854    @Override
855    public BaseEncoding omitPadding() {
856      return (paddingChar == null) ? this : newInstance(alphabet, null);
857    }
858
859    @Override
860    public BaseEncoding withPadChar(char padChar) {
861      if (8 % alphabet.bitsPerChar == 0 || (paddingChar != null && paddingChar == padChar)) {
862        return this;
863      } else {
864        return newInstance(alphabet, padChar);
865      }
866    }
867
868    @Override
869    public BaseEncoding withSeparator(String separator, int afterEveryChars) {
870      for (int i = 0; i < separator.length(); i++) {
871        checkArgument(
872            !alphabet.matches(separator.charAt(i)),
873            "Separator (%s) cannot contain alphabet characters",
874            separator);
875      }
876      if (paddingChar != null) {
877        checkArgument(
878            separator.indexOf(paddingChar) < 0,
879            "Separator (%s) cannot contain padding character",
880            separator);
881      }
882      return new SeparatedBaseEncoding(this, separator, afterEveryChars);
883    }
884
885    @LazyInit private volatile @Nullable BaseEncoding upperCase;
886    @LazyInit private volatile @Nullable BaseEncoding lowerCase;
887    @LazyInit private volatile @Nullable BaseEncoding ignoreCase;
888
889    @Override
890    public BaseEncoding upperCase() {
891      BaseEncoding result = upperCase;
892      if (result == null) {
893        Alphabet upper = alphabet.upperCase();
894        result = upperCase = (upper == alphabet) ? this : newInstance(upper, paddingChar);
895      }
896      return result;
897    }
898
899    @Override
900    public BaseEncoding lowerCase() {
901      BaseEncoding result = lowerCase;
902      if (result == null) {
903        Alphabet lower = alphabet.lowerCase();
904        result = lowerCase = (lower == alphabet) ? this : newInstance(lower, paddingChar);
905      }
906      return result;
907    }
908
909    @Override
910    public BaseEncoding ignoreCase() {
911      BaseEncoding result = ignoreCase;
912      if (result == null) {
913        Alphabet ignore = alphabet.ignoreCase();
914        result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar);
915      }
916      return result;
917    }
918
919    BaseEncoding newInstance(Alphabet alphabet, @Nullable Character paddingChar) {
920      return new StandardBaseEncoding(alphabet, paddingChar);
921    }
922
923    @Override
924    public String toString() {
925      StringBuilder builder = new StringBuilder("BaseEncoding.");
926      builder.append(alphabet);
927      if (8 % alphabet.bitsPerChar != 0) {
928        if (paddingChar == null) {
929          builder.append(".omitPadding()");
930        } else {
931          builder.append(".withPadChar('").append(paddingChar).append("')");
932        }
933      }
934      return builder.toString();
935    }
936
937    @Override
938    public boolean equals(@Nullable Object other) {
939      if (other instanceof StandardBaseEncoding) {
940        StandardBaseEncoding that = (StandardBaseEncoding) other;
941        return this.alphabet.equals(that.alphabet)
942            && Objects.equals(this.paddingChar, that.paddingChar);
943      }
944      return false;
945    }
946
947    @Override
948    public int hashCode() {
949      return alphabet.hashCode() ^ Objects.hashCode(paddingChar);
950    }
951  }
952
953  private static final class Base16Encoding extends StandardBaseEncoding {
954    final char[] encoding = new char[512];
955
956    Base16Encoding(String name, String alphabetChars) {
957      this(new Alphabet(name, alphabetChars.toCharArray()));
958    }
959
960    private Base16Encoding(Alphabet alphabet) {
961      super(alphabet, null);
962      checkArgument(alphabet.chars.length == 16);
963      for (int i = 0; i < 256; ++i) {
964        encoding[i] = alphabet.encode(i >>> 4);
965        encoding[i | 0x100] = alphabet.encode(i & 0xF);
966      }
967    }
968
969    @Override
970    void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
971      checkNotNull(target);
972      checkPositionIndexes(off, off + len, bytes.length);
973      for (int i = 0; i < len; ++i) {
974        int b = bytes[off + i] & 0xFF;
975        target.append(encoding[b]);
976        target.append(encoding[b | 0x100]);
977      }
978    }
979
980    @Override
981    int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
982      checkNotNull(target);
983      if (chars.length() % 2 == 1) {
984        throw new DecodingException("Invalid input length " + chars.length());
985      }
986      int bytesWritten = 0;
987      for (int i = 0; i < chars.length(); i += 2) {
988        int decoded = alphabet.decode(chars.charAt(i)) << 4 | alphabet.decode(chars.charAt(i + 1));
989        target[bytesWritten++] = (byte) decoded;
990      }
991      return bytesWritten;
992    }
993
994    @Override
995    BaseEncoding newInstance(Alphabet alphabet, @Nullable Character paddingChar) {
996      return new Base16Encoding(alphabet);
997    }
998  }
999
1000  private static final class Base64Encoding extends StandardBaseEncoding {
1001    Base64Encoding(String name, String alphabetChars, @Nullable Character paddingChar) {
1002      this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);
1003    }
1004
1005    private Base64Encoding(Alphabet alphabet, @Nullable Character paddingChar) {
1006      super(alphabet, paddingChar);
1007      checkArgument(alphabet.chars.length == 64);
1008    }
1009
1010    @Override
1011    void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
1012      checkNotNull(target);
1013      checkPositionIndexes(off, off + len, bytes.length);
1014      int i = off;
1015      for (int remaining = len; remaining >= 3; remaining -= 3) {
1016        int chunk = (bytes[i++] & 0xFF) << 16 | (bytes[i++] & 0xFF) << 8 | (bytes[i++] & 0xFF);
1017        target.append(alphabet.encode(chunk >>> 18));
1018        target.append(alphabet.encode((chunk >>> 12) & 0x3F));
1019        target.append(alphabet.encode((chunk >>> 6) & 0x3F));
1020        target.append(alphabet.encode(chunk & 0x3F));
1021      }
1022      if (i < off + len) {
1023        encodeChunkTo(target, bytes, i, off + len - i);
1024      }
1025    }
1026
1027    @Override
1028    int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
1029      checkNotNull(target);
1030      chars = trimTrailingPadding(chars);
1031      if (!alphabet.isValidPaddingStartPosition(chars.length())) {
1032        throw new DecodingException("Invalid input length " + chars.length());
1033      }
1034      int bytesWritten = 0;
1035      for (int i = 0; i < chars.length(); ) {
1036        int chunk = alphabet.decode(chars.charAt(i++)) << 18;
1037        chunk |= alphabet.decode(chars.charAt(i++)) << 12;
1038        target[bytesWritten++] = (byte) (chunk >>> 16);
1039        if (i < chars.length()) {
1040          chunk |= alphabet.decode(chars.charAt(i++)) << 6;
1041          target[bytesWritten++] = (byte) ((chunk >>> 8) & 0xFF);
1042          if (i < chars.length()) {
1043            chunk |= alphabet.decode(chars.charAt(i++));
1044            target[bytesWritten++] = (byte) (chunk & 0xFF);
1045          }
1046        }
1047      }
1048      return bytesWritten;
1049    }
1050
1051    @Override
1052    BaseEncoding newInstance(Alphabet alphabet, @Nullable Character paddingChar) {
1053      return new Base64Encoding(alphabet, paddingChar);
1054    }
1055  }
1056
1057  @J2ktIncompatible
1058  @GwtIncompatible
1059  static Reader ignoringReader(Reader delegate, String toIgnore) {
1060    checkNotNull(delegate);
1061    checkNotNull(toIgnore);
1062    return new Reader() {
1063      @Override
1064      public int read() throws IOException {
1065        int readChar;
1066        do {
1067          readChar = delegate.read();
1068        } while (readChar != -1 && toIgnore.indexOf((char) readChar) >= 0);
1069        return readChar;
1070      }
1071
1072      @Override
1073      public int read(char[] cbuf, int off, int len) {
1074        throw new UnsupportedOperationException();
1075      }
1076
1077      @Override
1078      public void close() throws IOException {
1079        delegate.close();
1080      }
1081    };
1082  }
1083
1084  static Appendable separatingAppendable(
1085      Appendable delegate, String separator, int afterEveryChars) {
1086    checkNotNull(delegate);
1087    checkNotNull(separator);
1088    checkArgument(afterEveryChars > 0);
1089    return new Appendable() {
1090      int charsUntilSeparator = afterEveryChars;
1091
1092      @Override
1093      public Appendable append(char c) throws IOException {
1094        if (charsUntilSeparator == 0) {
1095          delegate.append(separator);
1096          charsUntilSeparator = afterEveryChars;
1097        }
1098        delegate.append(c);
1099        charsUntilSeparator--;
1100        return this;
1101      }
1102
1103      @Override
1104      public Appendable append(@Nullable CharSequence chars, int off, int len) {
1105        throw new UnsupportedOperationException();
1106      }
1107
1108      @Override
1109      public Appendable append(@Nullable CharSequence chars) {
1110        throw new UnsupportedOperationException();
1111      }
1112    };
1113  }
1114
1115  @J2ktIncompatible
1116  @GwtIncompatible // Writer
1117  static Writer separatingWriter(Writer delegate, String separator, int afterEveryChars) {
1118    Appendable separatingAppendable = separatingAppendable(delegate, separator, afterEveryChars);
1119    return new Writer() {
1120      @Override
1121      public void write(int c) throws IOException {
1122        separatingAppendable.append((char) c);
1123      }
1124
1125      @Override
1126      public void write(char[] chars, int off, int len) {
1127        throw new UnsupportedOperationException();
1128      }
1129
1130      @Override
1131      public void flush() throws IOException {
1132        delegate.flush();
1133      }
1134
1135      @Override
1136      public void close() throws IOException {
1137        delegate.close();
1138      }
1139    };
1140  }
1141
1142  static final class SeparatedBaseEncoding extends BaseEncoding {
1143    private final BaseEncoding delegate;
1144    private final String separator;
1145    private final int afterEveryChars;
1146
1147    SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) {
1148      this.delegate = checkNotNull(delegate);
1149      this.separator = checkNotNull(separator);
1150      this.afterEveryChars = afterEveryChars;
1151      checkArgument(
1152          afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars);
1153    }
1154
1155    @Override
1156    CharSequence trimTrailingPadding(CharSequence chars) {
1157      return delegate.trimTrailingPadding(chars);
1158    }
1159
1160    @Override
1161    int maxEncodedSize(int bytes) {
1162      int unseparatedSize = delegate.maxEncodedSize(bytes);
1163      return unseparatedSize
1164          + separator.length() * divide(max(0, unseparatedSize - 1), afterEveryChars, FLOOR);
1165    }
1166
1167    @J2ktIncompatible
1168    @GwtIncompatible // Writer,OutputStream
1169    @Override
1170    public OutputStream encodingStream(Writer output) {
1171      return delegate.encodingStream(separatingWriter(output, separator, afterEveryChars));
1172    }
1173
1174    @Override
1175    void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
1176      delegate.encodeTo(separatingAppendable(target, separator, afterEveryChars), bytes, off, len);
1177    }
1178
1179    @Override
1180    int maxDecodedSize(int chars) {
1181      return delegate.maxDecodedSize(chars);
1182    }
1183
1184    @Override
1185    public boolean canDecode(CharSequence chars) {
1186      StringBuilder builder = new StringBuilder();
1187      for (int i = 0; i < chars.length(); i++) {
1188        char c = chars.charAt(i);
1189        if (separator.indexOf(c) < 0) {
1190          builder.append(c);
1191        }
1192      }
1193      return delegate.canDecode(builder);
1194    }
1195
1196    @Override
1197    int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
1198      StringBuilder stripped = new StringBuilder(chars.length());
1199      for (int i = 0; i < chars.length(); i++) {
1200        char c = chars.charAt(i);
1201        if (separator.indexOf(c) < 0) {
1202          stripped.append(c);
1203        }
1204      }
1205      return delegate.decodeTo(target, stripped);
1206    }
1207
1208    @Override
1209    @J2ktIncompatible
1210    @GwtIncompatible // Reader,InputStream
1211    public InputStream decodingStream(Reader reader) {
1212      return delegate.decodingStream(ignoringReader(reader, separator));
1213    }
1214
1215    @Override
1216    public BaseEncoding omitPadding() {
1217      return delegate.omitPadding().withSeparator(separator, afterEveryChars);
1218    }
1219
1220    @Override
1221    public BaseEncoding withPadChar(char padChar) {
1222      return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars);
1223    }
1224
1225    @Override
1226    public BaseEncoding withSeparator(String separator, int afterEveryChars) {
1227      throw new UnsupportedOperationException("Already have a separator");
1228    }
1229
1230    @Override
1231    public BaseEncoding upperCase() {
1232      return delegate.upperCase().withSeparator(separator, afterEveryChars);
1233    }
1234
1235    @Override
1236    public BaseEncoding lowerCase() {
1237      return delegate.lowerCase().withSeparator(separator, afterEveryChars);
1238    }
1239
1240    @Override
1241    public BaseEncoding ignoreCase() {
1242      return delegate.ignoreCase().withSeparator(separator, afterEveryChars);
1243    }
1244
1245    @Override
1246    public String toString() {
1247      return delegate + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")";
1248    }
1249  }
1250}