/
BaseEncoding.java
1248 lines (1115 loc) · 41.7 KB
/
BaseEncoding.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.math.IntMath.divide;
import static com.google.common.math.IntMath.log2;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.UNNECESSARY;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import com.google.common.base.Ascii;
import com.google.errorprone.annotations.concurrent.LazyInit;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
import java.util.Objects;
import javax.annotation.CheckForNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* A binary encoding scheme for reversibly translating between byte sequences and printable ASCII
* strings. This class includes several constants for encoding schemes specified by <a
* href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression:
*
* <pre>{@code
* BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII))
* }</pre>
*
* <p>returns the string {@code "MZXW6==="}, and
*
* <pre>{@code
* byte[] decoded = BaseEncoding.base32().decode("MZXW6===");
* }</pre>
*
* <p>...returns the ASCII bytes of the string {@code "foo"}.
*
* <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with RFC
* 4648. Decoding rejects characters in the wrong case, though padding is optional. To modify
* encoding and decoding behavior, use configuration methods to obtain a new encoding with modified
* behavior:
*
* <pre>{@code
* BaseEncoding.base16().lowerCase().decode("deadbeef");
* }</pre>
*
* <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect
* on the receiving instance; you must store and use the new encoding instance it returns, instead.
*
* <pre>{@code
* // Do NOT do this
* BaseEncoding hex = BaseEncoding.base16();
* hex.lowerCase(); // does nothing!
* return hex.decode("deadbeef"); // throws an IllegalArgumentException
* }</pre>
*
* <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to {@code
* x}, but the reverse does not necessarily hold.
*
* <table>
* <caption>Encodings</caption>
* <tr>
* <th>Encoding
* <th>Alphabet
* <th>{@code char:byte} ratio
* <th>Default padding
* <th>Comments
* <tr>
* <td>{@link #base16()}
* <td>0-9 A-F
* <td>2.00
* <td>N/A
* <td>Traditional hexadecimal. Defaults to upper case.
* <tr>
* <td>{@link #base32()}
* <td>A-Z 2-7
* <td>1.60
* <td>=
* <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case.
* <tr>
* <td>{@link #base32Hex()}
* <td>0-9 A-V
* <td>1.60
* <td>=
* <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case.
* <tr>
* <td>{@link #base64()}
* <td>A-Z a-z 0-9 + /
* <td>1.33
* <td>=
* <td>
* <tr>
* <td>{@link #base64Url()}
* <td>A-Z a-z 0-9 - _
* <td>1.33
* <td>=
* <td>Safe to use as filenames, or to pass in URLs without escaping
* </table>
*
* <p>All instances of this class are immutable, so they may be stored safely as static constants.
*
* @author Louis Wasserman
* @since 14.0
*/
@GwtCompatible(emulated = true)
@ElementTypesAreNonnullByDefault
public abstract class BaseEncoding {
// TODO(lowasser): consider making encodeTo(Appendable, byte[], int, int) public.
BaseEncoding() {}
/**
* Exception indicating invalid base-encoded input encountered while decoding.
*
* @author Louis Wasserman
* @since 15.0
*/
public static final class DecodingException extends IOException {
DecodingException(@Nullable String message) {
super(message);
}
}
/** Encodes the specified byte array, and returns the encoded {@code String}. */
public String encode(byte[] bytes) {
return encode(bytes, 0, bytes.length);
}
/**
* Encodes the specified range of the specified byte array, and returns the encoded {@code
* String}.
*/
public final String encode(byte[] bytes, int off, int len) {
checkPositionIndexes(off, off + len, bytes.length);
StringBuilder result = new StringBuilder(maxEncodedSize(len));
try {
encodeTo(result, bytes, off, len);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
return result.toString();
}
/**
* Returns an {@code OutputStream} that encodes bytes using this encoding into the specified
* {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code
* Writer}.
*/
@J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
public abstract OutputStream encodingStream(Writer writer);
/**
* Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}.
*/
@J2ktIncompatible
@GwtIncompatible // ByteSink,CharSink
public final ByteSink encodingSink(CharSink encodedSink) {
checkNotNull(encodedSink);
return new ByteSink() {
@Override
public OutputStream openStream() throws IOException {
return encodingStream(encodedSink.openStream());
}
};
}
// TODO(lowasser): document the extent of leniency, probably after adding ignore(CharMatcher)
private static byte[] extract(byte[] result, int length) {
if (length == result.length) {
return result;
}
byte[] trunc = new byte[length];
System.arraycopy(result, 0, trunc, 0, length);
return trunc;
}
/**
* Determines whether the specified character sequence is a valid encoded string according to this
* encoding.
*
* @since 20.0
*/
public abstract boolean canDecode(CharSequence chars);
/**
* Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the
* inverse operation to {@link #encode(byte[])}.
*
* @throws IllegalArgumentException if the input is not a valid encoded string according to this
* encoding.
*/
public final byte[] decode(CharSequence chars) {
try {
return decodeChecked(chars);
} catch (DecodingException badInput) {
throw new IllegalArgumentException(badInput);
}
}
/**
* Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the
* inverse operation to {@link #encode(byte[])}.
*
* @throws DecodingException if the input is not a valid encoded string according to this
* encoding.
*/
final byte[] decodeChecked(CharSequence chars)
throws DecodingException {
chars = trimTrailingPadding(chars);
byte[] tmp = new byte[maxDecodedSize(chars.length())];
int len = decodeTo(tmp, chars);
return extract(tmp, len);
}
/**
* Returns an {@code InputStream} that decodes base-encoded input from the specified {@code
* Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors.
*/
@J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public abstract InputStream decodingStream(Reader reader);
/**
* Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code
* CharSource}.
*/
@J2ktIncompatible
@GwtIncompatible // ByteSource,CharSource
public final ByteSource decodingSource(CharSource encodedSource) {
checkNotNull(encodedSource);
return new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return decodingStream(encodedSource.openStream());
}
};
}
// Implementations for encoding/decoding
abstract int maxEncodedSize(int bytes);
abstract void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException;
abstract int maxDecodedSize(int chars);
abstract int decodeTo(byte[] target, CharSequence chars) throws DecodingException;
CharSequence trimTrailingPadding(CharSequence chars) {
return checkNotNull(chars);
}
// Modified encoding generators
/**
* Returns an encoding that behaves equivalently to this encoding, but omits any padding
* characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648
* section 3.2</a>, Padding of Encoded Data.
*/
public abstract BaseEncoding omitPadding();
/**
* Returns an encoding that behaves equivalently to this encoding, but uses an alternate character
* for padding.
*
* @throws IllegalArgumentException if this padding character is already used in the alphabet or a
* separator
*/
public abstract BaseEncoding withPadChar(char padChar);
/**
* Returns an encoding that behaves equivalently to this encoding, but adds a separator string
* after every {@code n} characters. Any occurrences of any characters that occur in the separator
* are skipped over in decoding.
*
* @throws IllegalArgumentException if any alphabet or padding characters appear in the separator
* string, or if {@code n <= 0}
* @throws UnsupportedOperationException if this encoding already uses a separator
*/
public abstract BaseEncoding withSeparator(String separator, int n);
/**
* Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
* uppercase letters. Padding and separator characters remain in their original case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
*/
public abstract BaseEncoding upperCase();
/**
* Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with
* lowercase letters. Padding and separator characters remain in their original case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
*/
public abstract BaseEncoding lowerCase();
/**
* Returns an encoding that behaves equivalently to this encoding, but decodes letters without
* regard to case.
*
* @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and
* lower-case characters
* @since 32.0.0
*/
public abstract BaseEncoding ignoreCase();
private static final BaseEncoding BASE64 =
new Base64Encoding(
"base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '=');
/**
* The "base64" base encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding.
* (This is the same as the base 64 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base64() {
return BASE64;
}
private static final BaseEncoding BASE64_URL =
new Base64Encoding(
"base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '=');
/**
* The "base64url" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding
* with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64." (This
* is the same as the base 64 encoding with URL and filename safe alphabet from <a
* href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base64Url() {
return BASE64_URL;
}
private static final BaseEncoding BASE32 =
new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '=');
/**
* The "base32" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-6">RFC
* 4648 section 6</a>, Base 32 Encoding. (This is the same as the base 32 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.)
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base32() {
return BASE32;
}
private static final BaseEncoding BASE32_HEX =
new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '=');
/**
* The "base32hex" encoding specified by <a
* href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding
* with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548.
*
* <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding()
* omitted} or {@linkplain #withPadChar(char) replaced}.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base32Hex() {
return BASE32_HEX;
}
private static final BaseEncoding BASE16 = new Base16Encoding("base16()", "0123456789ABCDEF");
/**
* The "base16" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-8">RFC
* 4648 section 8</a>, Base 16 Encoding. (This is the same as the base 16 encoding from <a
* href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as
* "hexadecimal" format.
*
* <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and {@link #omitPadding()}
* have no effect.
*
* <p>No line feeds are added by default, as per <a
* href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in
* Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}.
*/
public static BaseEncoding base16() {
return BASE16;
}
static final class Alphabet {
private final String name;
// this is meant to be immutable -- don't modify it!
private final char[] chars;
final int mask;
final int bitsPerChar;
final int charsPerChunk;
final int bytesPerChunk;
private final byte[] decodabet;
private final boolean[] validPadding;
private final boolean ignoreCase;
Alphabet(String name, char[] chars) {
this(name, chars, decodabetFor(chars), /* ignoreCase= */ false);
}
private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) {
this.name = checkNotNull(name);
this.chars = checkNotNull(chars);
try {
this.bitsPerChar = log2(chars.length, UNNECESSARY);
} catch (ArithmeticException e) {
throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e);
}
// Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into
// 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3.
// We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a
// multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many
// extra zero bits we need to add to the end of bitsPerChar to get 3 in total.
// The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII
// characters that can't happen.
int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar);
this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar);
this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar;
this.mask = chars.length - 1;
this.decodabet = decodabet;
boolean[] validPadding = new boolean[charsPerChunk];
for (int i = 0; i < bytesPerChunk; i++) {
validPadding[divide(i * 8, bitsPerChar, CEILING)] = true;
}
this.validPadding = validPadding;
this.ignoreCase = ignoreCase;
}
private static byte[] decodabetFor(char[] chars) {
byte[] decodabet = new byte[Ascii.MAX + 1];
Arrays.fill(decodabet, (byte) -1);
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
checkArgument(c < decodabet.length, "Non-ASCII character: %s", c);
checkArgument(decodabet[c] == -1, "Duplicate character: %s", c);
decodabet[c] = (byte) i;
}
return decodabet;
}
/** Returns an equivalent {@code Alphabet} except it ignores case. */
Alphabet ignoreCase() {
if (ignoreCase) {
return this;
}
// We can't use .clone() because of GWT.
byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length);
for (int upper = 'A'; upper <= 'Z'; upper++) {
int lower = upper | 0x20;
byte decodeUpper = decodabet[upper];
byte decodeLower = decodabet[lower];
if (decodeUpper == -1) {
newDecodabet[upper] = decodeLower;
} else {
checkState(
decodeLower == -1,
"Can't ignoreCase() since '%s' and '%s' encode different values",
(char) upper,
(char) lower);
newDecodabet[lower] = decodeUpper;
}
}
return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true);
}
char encode(int bits) {
return chars[bits];
}
boolean isValidPaddingStartPosition(int index) {
return validPadding[index % charsPerChunk];
}
boolean canDecode(char ch) {
return ch <= Ascii.MAX && decodabet[ch] != -1;
}
int decode(char ch) throws DecodingException {
if (ch > Ascii.MAX) {
throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch));
}
int result = decodabet[ch];
if (result == -1) {
if (ch <= 0x20 || ch == Ascii.MAX) {
throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch));
} else {
throw new DecodingException("Unrecognized character: " + ch);
}
}
return result;
}
private boolean hasLowerCase() {
for (char c : chars) {
if (Ascii.isLowerCase(c)) {
return true;
}
}
return false;
}
private boolean hasUpperCase() {
for (char c : chars) {
if (Ascii.isUpperCase(c)) {
return true;
}
}
return false;
}
Alphabet upperCase() {
if (!hasLowerCase()) {
return this;
}
checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet");
char[] upperCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
upperCased[i] = Ascii.toUpperCase(chars[i]);
}
Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased);
return ignoreCase ? upperCase.ignoreCase() : upperCase;
}
Alphabet lowerCase() {
if (!hasUpperCase()) {
return this;
}
checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet");
char[] lowerCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
lowerCased[i] = Ascii.toLowerCase(chars[i]);
}
Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased);
return ignoreCase ? lowerCase.ignoreCase() : lowerCase;
}
public boolean matches(char c) {
return c < decodabet.length && decodabet[c] != -1;
}
@Override
public String toString() {
return name;
}
@Override
public boolean equals(@CheckForNull Object other) {
if (other instanceof Alphabet) {
Alphabet that = (Alphabet) other;
return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237);
}
}
private static class StandardBaseEncoding extends BaseEncoding {
final Alphabet alphabet;
@CheckForNull final Character paddingChar;
StandardBaseEncoding(String name, String alphabetChars, @CheckForNull Character paddingChar) {
this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);
}
StandardBaseEncoding(Alphabet alphabet, @CheckForNull Character paddingChar) {
this.alphabet = checkNotNull(alphabet);
checkArgument(
paddingChar == null || !alphabet.matches(paddingChar),
"Padding character %s was already in alphabet",
paddingChar);
this.paddingChar = paddingChar;
}
@Override
int maxEncodedSize(int bytes) {
return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING);
}
@J2ktIncompatible
@GwtIncompatible // Writer,OutputStream
@Override
public OutputStream encodingStream(Writer out) {
checkNotNull(out);
return new OutputStream() {
int bitBuffer = 0;
int bitBufferLength = 0;
int writtenChars = 0;
@Override
public void write(int b) throws IOException {
bitBuffer <<= 8;
bitBuffer |= b & 0xFF;
bitBufferLength += 8;
while (bitBufferLength >= alphabet.bitsPerChar) {
int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask;
out.write(alphabet.encode(charIndex));
writtenChars++;
bitBufferLength -= alphabet.bitsPerChar;
}
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
if (bitBufferLength > 0) {
int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask;
out.write(alphabet.encode(charIndex));
writtenChars++;
if (paddingChar != null) {
while (writtenChars % alphabet.charsPerChunk != 0) {
out.write(paddingChar.charValue());
writtenChars++;
}
}
}
out.close();
}
};
}
@Override
void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
for (int i = 0; i < len; i += alphabet.bytesPerChunk) {
encodeChunkTo(target, bytes, off + i, Math.min(alphabet.bytesPerChunk, len - i));
}
}
void encodeChunkTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
checkArgument(len <= alphabet.bytesPerChunk);
long bitBuffer = 0;
for (int i = 0; i < len; ++i) {
bitBuffer |= bytes[off + i] & 0xFF;
bitBuffer <<= 8; // Add additional zero byte in the end.
}
// Position of first character is length of bitBuffer minus bitsPerChar.
int bitOffset = (len + 1) * 8 - alphabet.bitsPerChar;
int bitsProcessed = 0;
while (bitsProcessed < len * 8) {
int charIndex = (int) (bitBuffer >>> (bitOffset - bitsProcessed)) & alphabet.mask;
target.append(alphabet.encode(charIndex));
bitsProcessed += alphabet.bitsPerChar;
}
if (paddingChar != null) {
while (bitsProcessed < alphabet.bytesPerChunk * 8) {
target.append(paddingChar.charValue());
bitsProcessed += alphabet.bitsPerChar;
}
}
}
@Override
int maxDecodedSize(int chars) {
return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L);
}
@Override
CharSequence trimTrailingPadding(CharSequence chars) {
checkNotNull(chars);
if (paddingChar == null) {
return chars;
}
char padChar = paddingChar.charValue();
int l;
for (l = chars.length() - 1; l >= 0; l--) {
if (chars.charAt(l) != padChar) {
break;
}
}
return chars.subSequence(0, l + 1);
}
@Override
public boolean canDecode(CharSequence chars) {
checkNotNull(chars);
chars = trimTrailingPadding(chars);
if (!alphabet.isValidPaddingStartPosition(chars.length())) {
return false;
}
for (int i = 0; i < chars.length(); i++) {
if (!alphabet.canDecode(chars.charAt(i))) {
return false;
}
}
return true;
}
@Override
int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
checkNotNull(target);
chars = trimTrailingPadding(chars);
if (!alphabet.isValidPaddingStartPosition(chars.length())) {
throw new DecodingException("Invalid input length " + chars.length());
}
int bytesWritten = 0;
for (int charIdx = 0; charIdx < chars.length(); charIdx += alphabet.charsPerChunk) {
long chunk = 0;
int charsProcessed = 0;
for (int i = 0; i < alphabet.charsPerChunk; i++) {
chunk <<= alphabet.bitsPerChar;
if (charIdx + i < chars.length()) {
chunk |= alphabet.decode(chars.charAt(charIdx + charsProcessed++));
}
}
int minOffset = alphabet.bytesPerChunk * 8 - charsProcessed * alphabet.bitsPerChar;
for (int offset = (alphabet.bytesPerChunk - 1) * 8; offset >= minOffset; offset -= 8) {
target[bytesWritten++] = (byte) ((chunk >>> offset) & 0xFF);
}
}
return bytesWritten;
}
@Override
@J2ktIncompatible
@GwtIncompatible // Reader,InputStream
public InputStream decodingStream(Reader reader) {
checkNotNull(reader);
return new InputStream() {
int bitBuffer = 0;
int bitBufferLength = 0;
int readChars = 0;
boolean hitPadding = false;
@Override
public int read() throws IOException {
while (true) {
int readChar = reader.read();
if (readChar == -1) {
if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) {
throw new DecodingException("Invalid input length " + readChars);
}
return -1;
}
readChars++;
char ch = (char) readChar;
if (paddingChar != null && paddingChar.charValue() == ch) {
if (!hitPadding
&& (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) {
throw new DecodingException("Padding cannot start at index " + readChars);
}
hitPadding = true;
} else if (hitPadding) {
throw new DecodingException(
"Expected padding character but found '" + ch + "' at index " + readChars);
} else {
bitBuffer <<= alphabet.bitsPerChar;
bitBuffer |= alphabet.decode(ch);
bitBufferLength += alphabet.bitsPerChar;
if (bitBufferLength >= 8) {
bitBufferLength -= 8;
return (bitBuffer >> bitBufferLength) & 0xFF;
}
}
}
}
@Override
public int read(byte[] buf, int off, int len) throws IOException {
// Overriding this to work around the fact that InputStream's default implementation of
// this method will silently swallow exceptions thrown by the single-byte read() method
// (other than on the first call to it), which in this case can cause invalid encoded
// strings to not throw an exception.
// See https://github.com/google/guava/issues/3542
checkPositionIndexes(off, off + len, buf.length);
int i = off;
for (; i < off + len; i++) {
int b = read();
if (b == -1) {
int read = i - off;
return read == 0 ? -1 : read;
}
buf[i] = (byte) b;
}
return i - off;
}
@Override
public void close() throws IOException {
reader.close();
}
};
}
@Override
public BaseEncoding omitPadding() {
return (paddingChar == null) ? this : newInstance(alphabet, null);
}
@Override
public BaseEncoding withPadChar(char padChar) {
if (8 % alphabet.bitsPerChar == 0
|| (paddingChar != null && paddingChar.charValue() == padChar)) {
return this;
} else {
return newInstance(alphabet, padChar);
}
}
@Override
public BaseEncoding withSeparator(String separator, int afterEveryChars) {
for (int i = 0; i < separator.length(); i++) {
checkArgument(
!alphabet.matches(separator.charAt(i)),
"Separator (%s) cannot contain alphabet characters",
separator);
}
if (paddingChar != null) {
checkArgument(
separator.indexOf(paddingChar.charValue()) < 0,
"Separator (%s) cannot contain padding character",
separator);
}
return new SeparatedBaseEncoding(this, separator, afterEveryChars);
}
@LazyInit @CheckForNull private volatile BaseEncoding upperCase;
@LazyInit @CheckForNull private volatile BaseEncoding lowerCase;
@LazyInit @CheckForNull private volatile BaseEncoding ignoreCase;
@Override
public BaseEncoding upperCase() {
BaseEncoding result = upperCase;
if (result == null) {
Alphabet upper = alphabet.upperCase();
result = upperCase = (upper == alphabet) ? this : newInstance(upper, paddingChar);
}
return result;
}
@Override
public BaseEncoding lowerCase() {
BaseEncoding result = lowerCase;
if (result == null) {
Alphabet lower = alphabet.lowerCase();
result = lowerCase = (lower == alphabet) ? this : newInstance(lower, paddingChar);
}
return result;
}
@Override
public BaseEncoding ignoreCase() {
BaseEncoding result = ignoreCase;
if (result == null) {
Alphabet ignore = alphabet.ignoreCase();
result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar);
}
return result;
}
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new StandardBaseEncoding(alphabet, paddingChar);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("BaseEncoding.");
builder.append(alphabet);
if (8 % alphabet.bitsPerChar != 0) {
if (paddingChar == null) {
builder.append(".omitPadding()");
} else {
builder.append(".withPadChar('").append(paddingChar).append("')");
}
}
return builder.toString();
}
@Override
public boolean equals(@CheckForNull Object other) {
if (other instanceof StandardBaseEncoding) {
StandardBaseEncoding that = (StandardBaseEncoding) other;
return this.alphabet.equals(that.alphabet)
&& Objects.equals(this.paddingChar, that.paddingChar);
}
return false;
}
@Override
public int hashCode() {
return alphabet.hashCode() ^ Objects.hashCode(paddingChar);
}
}
private static final class Base16Encoding extends StandardBaseEncoding {
final char[] encoding = new char[512];
Base16Encoding(String name, String alphabetChars) {
this(new Alphabet(name, alphabetChars.toCharArray()));
}
private Base16Encoding(Alphabet alphabet) {
super(alphabet, null);
checkArgument(alphabet.chars.length == 16);
for (int i = 0; i < 256; ++i) {
encoding[i] = alphabet.encode(i >>> 4);
encoding[i | 0x100] = alphabet.encode(i & 0xF);
}
}
@Override
void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException {
checkNotNull(target);
checkPositionIndexes(off, off + len, bytes.length);
for (int i = 0; i < len; ++i) {
int b = bytes[off + i] & 0xFF;
target.append(encoding[b]);
target.append(encoding[b | 0x100]);
}
}
@Override
int decodeTo(byte[] target, CharSequence chars) throws DecodingException {
checkNotNull(target);
if (chars.length() % 2 == 1) {
throw new DecodingException("Invalid input length " + chars.length());
}
int bytesWritten = 0;
for (int i = 0; i < chars.length(); i += 2) {
int decoded = alphabet.decode(chars.charAt(i)) << 4 | alphabet.decode(chars.charAt(i + 1));
target[bytesWritten++] = (byte) decoded;
}
return bytesWritten;
}
@Override
BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) {
return new Base16Encoding(alphabet);
}
}
private static final class Base64Encoding extends StandardBaseEncoding {
Base64Encoding(String name, String alphabetChars, @CheckForNull Character paddingChar) {
this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar);