View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.codec.binary;
19  
20  import java.util.Arrays;
21  import java.util.Objects;
22  import java.util.function.Supplier;
23  
24  import org.apache.commons.codec.BinaryDecoder;
25  import org.apache.commons.codec.BinaryEncoder;
26  import org.apache.commons.codec.CodecPolicy;
27  import org.apache.commons.codec.DecoderException;
28  import org.apache.commons.codec.EncoderException;
29  
30  /**
31   * Abstract superclass for Base-N encoders and decoders.
32   *
33   * <p>
34   * This class is thread-safe.
35   * </p>
36   * <p>
37   * You can set the decoding behavior when the input bytes contain leftover trailing bits that cannot be created by a valid encoding. These can be bits that are
38   * unused from the final character or entire characters. The default mode is lenient decoding.
39   * </p>
40   * <ul>
41   * <li>Lenient: Any trailing bits are composed into 8-bit bytes where possible. The remainder are discarded.</li>
42   * <li>Strict: The decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid encoding. Any unused bits from the final
43   * character must be zero. Impossible counts of entire final characters are not allowed.</li>
44   * </ul>
45   * <p>
46   * When strict decoding is enabled it is expected that the decoded bytes will be re-encoded to a byte array that matches the original, i.e. no changes occur on
47   * the final character. This requires that the input bytes use the same padding and alphabet as the encoder.
48   * </p>
49   */
50  public abstract class BaseNCodec implements BinaryEncoder, BinaryDecoder {
51  
52      /**
53       * Builds {@link Base64} instances.
54       *
55       * @param <T> the codec type to build.
56       * @param <B> the codec builder subtype.
57       * @since 1.17.0
58       */
59      public abstract static class AbstractBuilder<T, B extends AbstractBuilder<T, B>> implements Supplier<T> {
60  
61          private int unencodedBlockSize;
62          private int encodedBlockSize;
63          private CodecPolicy decodingPolicy = DECODING_POLICY_DEFAULT;
64          private int lineLength;
65          private byte[] lineSeparator = CHUNK_SEPARATOR;
66          private final byte[] defaultEncodeTable;
67          private byte[] encodeTable;
68          private byte[] decodeTable;
69  
70          /** Padding byte. */
71          private byte padding = PAD_DEFAULT;
72  
73          AbstractBuilder(final byte[] defaultEncodeTable) {
74              this.defaultEncodeTable = defaultEncodeTable;
75              this.encodeTable = defaultEncodeTable;
76          }
77  
78          /**
79           * Returns this instance typed as the subclass type {@code B}.
80           * <p>
81           * This is the same as the expression:
82           * </p>
83           *
84           * <pre>
85           * (B) this
86           * </pre>
87           *
88           * @return {@code this} instance typed as the subclass type {@code B}.
89           */
90          @SuppressWarnings("unchecked")
91          B asThis() {
92              return (B) this;
93          }
94  
95          byte[] getDecodeTable() {
96              return decodeTable;
97          }
98  
99          CodecPolicy getDecodingPolicy() {
100             return decodingPolicy;
101         }
102 
103         int getEncodedBlockSize() {
104             return encodedBlockSize;
105         }
106 
107         byte[] getEncodeTable() {
108             return encodeTable;
109         }
110 
111         int getLineLength() {
112             return lineLength;
113         }
114 
115         byte[] getLineSeparator() {
116             return lineSeparator;
117         }
118 
119         byte getPadding() {
120             return padding;
121         }
122 
123         int getUnencodedBlockSize() {
124             return unencodedBlockSize;
125         }
126 
127         /**
128          * Sets the decode table.
129          *
130          * @param decodeTable the decode table.
131          * @return {@code this} instance.
132          * @since 1.20.0
133          */
134         public B setDecodeTable(final byte[] decodeTable) {
135             this.decodeTable = decodeTable != null ? decodeTable.clone() : null;
136             return asThis();
137         }
138 
139         /**
140          * Sets the decode table.
141          *
142          * @param decodeTable the decode table, null resets to the default.
143          * @return {@code this} instance.
144          */
145         B setDecodeTableRaw(final byte[] decodeTable) {
146             this.decodeTable = decodeTable;
147             return asThis();
148         }
149 
150         /**
151          * Sets the decoding policy.
152          *
153          * @param decodingPolicy the decoding policy, null resets to the default.
154          * @return {@code this} instance.
155          */
156         public B setDecodingPolicy(final CodecPolicy decodingPolicy) {
157             this.decodingPolicy = decodingPolicy != null ? decodingPolicy : DECODING_POLICY_DEFAULT;
158             return asThis();
159         }
160 
161         /**
162          * Sets the encoded block size, subclasses normally set this on construction.
163          *
164          * @param encodedBlockSize the encoded block size, subclasses normally set this on construction.
165          * @return {@code this} instance.
166          */
167         B setEncodedBlockSize(final int encodedBlockSize) {
168             this.encodedBlockSize = encodedBlockSize;
169             return asThis();
170         }
171 
172         /**
173          * Sets the encode table.
174          *
175          * @param encodeTable the encode table, null resets to the default.
176          * @return {@code this} instance.
177          */
178         public B setEncodeTable(final byte... encodeTable) {
179             this.encodeTable = encodeTable != null ? encodeTable.clone() : defaultEncodeTable;
180             return asThis();
181         }
182 
183         /**
184          * Sets the encode table.
185          *
186          * @param encodeTable the encode table, null resets to the default.
187          * @return {@code this} instance.
188          */
189         B setEncodeTableRaw(final byte... encodeTable) {
190             this.encodeTable = encodeTable != null ? encodeTable : defaultEncodeTable;
191             return asThis();
192         }
193 
194         /**
195          * Sets the line length.
196          *
197          * @param lineLength the line length, less than 0 resets to the default.
198          * @return {@code this} instance.
199          */
200         public B setLineLength(final int lineLength) {
201             this.lineLength = Math.max(0, lineLength);
202             return asThis();
203         }
204 
205         /**
206          * Sets the line separator.
207          *
208          * @param lineSeparator the line separator, null resets to the default.
209          * @return {@code this} instance.
210          */
211         public B setLineSeparator(final byte... lineSeparator) {
212             this.lineSeparator = lineSeparator != null ? lineSeparator.clone() : CHUNK_SEPARATOR;
213             return asThis();
214         }
215 
216         /**
217          * Sets the padding byte.
218          *
219          * @param padding the padding byte.
220          * @return {@code this} instance.
221          */
222         public B setPadding(final byte padding) {
223             this.padding = padding;
224             return asThis();
225         }
226 
227         /**
228          * Sets the unencoded block size, subclasses normally set this on construction.
229          *
230          * @param unencodedBlockSize the unencoded block size, subclasses normally set this on construction.
231          * @return {@code this} instance.
232          */
233         B setUnencodedBlockSize(final int unencodedBlockSize) {
234             this.unencodedBlockSize = unencodedBlockSize;
235             return asThis();
236         }
237     }
238 
239     /**
240      * Holds thread context so classes can be thread-safe.
241      *
242      * This class is not itself thread-safe; each thread must allocate its own copy.
243      */
244     static class Context {
245 
246         /**
247          * Placeholder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the encoding or decoding from this variable.
248          */
249         int ibitWorkArea;
250 
251         /**
252          * Placeholder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the encoding or decoding from this variable.
253          */
254         long lbitWorkArea;
255 
256         /**
257          * Buffer for streaming.
258          */
259         byte[] buffer;
260 
261         /**
262          * Position where next character should be written in the buffer.
263          */
264         int pos;
265 
266         /**
267          * Position where next character should be read from the buffer.
268          */
269         int readPos;
270 
271         /**
272          * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and must be thrown away.
273          */
274         boolean eof;
275 
276         /**
277          * Variable tracks how many characters have been written to the current line. Only used when encoding. We use it to make sure each encoded line never
278          * goes beyond lineLength (if lineLength &gt; 0).
279          */
280         int currentLinePos;
281 
282         /**
283          * Writes to the buffer only occur after every 3/5 reads when encoding, and every 4/8 reads when decoding. This variable helps track that.
284          */
285         int modulus;
286 
287         /**
288          * Returns a String useful for debugging (especially within a debugger.)
289          *
290          * @return a String useful for debugging.
291          */
292         @Override
293         public String toString() {
294             return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " + "modulus=%s, pos=%s, readPos=%s]",
295                     this.getClass().getSimpleName(), Arrays.toString(buffer), currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
296         }
297     }
298 
299     /**
300      * End-of-file marker.
301      *
302      * @since 1.7
303      */
304     static final int EOF = -1;
305 
306     /**
307      * MIME chunk size per RFC 2045 section 6.8.
308      *
309      * <p>
310      * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
311      * </p>
312      *
313      * @see <a href="https://www.ietf.org/rfc/rfc2045">RFC 2045 section 6.8</a>
314      */
315     public static final int MIME_CHUNK_SIZE = 76;
316 
317     /**
318      * PEM chunk size per RFC 1421 section 4.3.2.4.
319      *
320      * <p>
321      * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
322      * </p>
323      *
324      * @see <a href="https://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
325      */
326     public static final int PEM_CHUNK_SIZE = 64;
327     private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
328 
329     /**
330      * Defines the default buffer size - currently {@value} - must be large enough for at least one encoded block+separator
331      */
332     private static final int DEFAULT_BUFFER_SIZE = 8192;
333 
334     /**
335      * The maximum size buffer to allocate.
336      *
337      * <p>
338      * This is set to the same size used in the JDK {@link java.util.ArrayList}:
339      * </p>
340      * <blockquote> Some VMs reserve some header words in an array. Attempts to allocate larger arrays may result in OutOfMemoryError: Requested array size
341      * exceeds VM limit. </blockquote>
342      */
343     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
344 
345     /** Mask used to extract 8 bits, used in decoding bytes */
346     protected static final int MASK_8BITS = 0xff;
347 
348     /**
349      * Byte used to pad output.
350      */
351     protected static final byte PAD_DEFAULT = '='; // Allow static access to default
352 
353     /**
354      * The default decoding policy.
355      *
356      * @since 1.15
357      */
358     protected static final CodecPolicy DECODING_POLICY_DEFAULT = CodecPolicy.LENIENT;
359 
360     /**
361      * Chunk separator per RFC 2045 section 2.1.
362      *
363      * @see <a href="https://www.ietf.org/rfc/rfc2045">RFC 2045 section 2.1</a>
364      */
365     static final byte[] CHUNK_SEPARATOR = { '\r', '\n' };
366 
367     /**
368      * The empty byte array.
369      */
370     static final byte[] EMPTY_BYTE_ARRAY = {};
371 
372     /**
373      * Create a positive capacity at least as large the minimum required capacity. If the minimum capacity is negative then this throws an OutOfMemoryError as
374      * no array can be allocated.
375      *
376      * @param minCapacity the minimum capacity.
377      * @return the capacity.
378      * @throws OutOfMemoryError if the {@code minCapacity} is negative.
379      */
380     private static int createPositiveCapacity(final int minCapacity) {
381         if (minCapacity < 0) {
382             // overflow
383             throw new OutOfMemoryError("Unable to allocate array size: " + (minCapacity & 0xffffffffL));
384         }
385         // This is called when we require buffer expansion to a very big array.
386         // Use the conservative maximum buffer size if possible, otherwise the biggest required.
387         //
388         // Note: In this situation JDK 1.8 java.util.ArrayList returns Integer.MAX_VALUE.
389         // This excludes some VMs that can exceed MAX_BUFFER_SIZE but not allocate a full
390         // Integer.MAX_VALUE length array.
391         // The result is that we may have to allocate an array of this size more than once if
392         // the capacity must be expanded again.
393         return Math.max(minCapacity, MAX_BUFFER_SIZE);
394     }
395 
396     /**
397      * Gets a copy of the chunk separator per RFC 2045 section 2.1.
398      *
399      * @return the chunk separator.
400      * @see <a href="https://www.ietf.org/rfc/rfc2045">RFC 2045 section 2.1</a>
401      * @since 1.15
402      */
403     public static byte[] getChunkSeparator() {
404         return CHUNK_SEPARATOR.clone();
405     }
406 
407     /**
408      * Gets the array length or 0 if null.
409      *
410      * @param array the array or null.
411      * @return the array length or 0 if null.
412      */
413     static int getLength(final byte[] array) {
414         return array == null ? 0 : array.length;
415     }
416 
417     /**
418      * Checks if a byte value is whitespace or not.
419      *
420      * @param byteToCheck the byte to check.
421      * @return true if byte is whitespace, false otherwise.
422      * @see Character#isWhitespace(int)
423      * @deprecated Use {@link Character#isWhitespace(int)}.
424      */
425     @Deprecated
426     protected static boolean isWhiteSpace(final byte byteToCheck) {
427         return Character.isWhitespace(byteToCheck);
428     }
429 
430     /**
431      * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
432      *
433      * @param context     the context to be used.
434      * @param minCapacity the minimum required capacity.
435      * @return the resized byte[] buffer.
436      * @throws OutOfMemoryError if the {@code minCapacity} is negative.
437      */
438     private static byte[] resizeBuffer(final Context context, final int minCapacity) {
439         // Overflow-conscious code treats the min and new capacity as unsigned.
440         final int oldCapacity = context.buffer.length;
441         int newCapacity = oldCapacity * DEFAULT_BUFFER_RESIZE_FACTOR;
442         if (Integer.compareUnsigned(newCapacity, minCapacity) < 0) {
443             newCapacity = minCapacity;
444         }
445         if (Integer.compareUnsigned(newCapacity, MAX_BUFFER_SIZE) > 0) {
446             newCapacity = createPositiveCapacity(minCapacity);
447         }
448         final byte[] b = Arrays.copyOf(context.buffer, newCapacity);
449         context.buffer = b;
450         return b;
451     }
452 
453     /**
454      * Deprecated: Will be removed in 2.0.
455      * <p>
456      * Instance variable just in case it needs to vary later
457      * </p>
458      *
459      * @deprecated Use {@link #pad}. Will be removed in 2.0.
460      */
461     @Deprecated
462     protected final byte PAD = PAD_DEFAULT;
463 
464     /** Pad byte. Instance variable just in case it needs to vary later. */
465     protected final byte pad;
466 
467     /** Number of bytes in each full block of unencoded data, for example 4 for Base64 and 5 for Base32 */
468     private final int unencodedBlockSize;
469 
470     /** Number of bytes in each full block of encoded data, for example 3 for Base64 and 8 for Base32 */
471     private final int encodedBlockSize;
472 
473     /**
474      * Chunksize for encoding. Not used when decoding. A value of zero or less implies no chunking of the encoded data. Rounded down to the nearest multiple of
475      * encodedBlockSize.
476      */
477     protected final int lineLength;
478 
479     /**
480      * Size of chunk separator. Not used unless {@link #lineLength} &gt; 0.
481      */
482     private final int chunkSeparatorLength;
483 
484     /**
485      * Defines the decoding behavior when the input bytes contain leftover trailing bits that cannot be created by a valid encoding. These can be bits that are
486      * unused from the final character or entire characters. The default mode is lenient decoding. Set this to {@code true} to enable strict decoding.
487      * <ul>
488      * <li>Lenient: Any trailing bits are composed into 8-bit bytes where possible. The remainder are discarded.</li>
489      * <li>Strict: The decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid encoding. Any unused bits from the final
490      * character must be zero. Impossible counts of entire final characters are not allowed.</li>
491      * </ul>
492      * <p>
493      * When strict decoding is enabled it is expected that the decoded bytes will be re-encoded to a byte array that matches the original, i.e. no changes occur
494      * on the final character. This requires that the input bytes use the same padding and alphabet as the encoder.
495      * </p>
496      */
497     private final CodecPolicy decodingPolicy;
498 
499     /**
500      * Decode table to use.
501      */
502     final byte[] decodeTable;
503 
504     /**
505      * Encode table.
506      */
507     final byte[] encodeTable;
508 
509     /**
510      * Constructs a new instance for a subclass.
511      *
512      * @param builder How to build this portion of the instance.
513      * @since 1.20.0
514      */
515     protected BaseNCodec(final AbstractBuilder<?, ?> builder) {
516         this.unencodedBlockSize = builder.unencodedBlockSize;
517         this.encodedBlockSize = builder.encodedBlockSize;
518         final boolean useChunking = builder.lineLength > 0 && builder.lineSeparator.length > 0;
519         this.lineLength = useChunking ? builder.lineLength / builder.encodedBlockSize * builder.encodedBlockSize : 0;
520         this.chunkSeparatorLength = builder.lineSeparator.length;
521         this.pad = builder.padding;
522         this.decodingPolicy = Objects.requireNonNull(builder.decodingPolicy, "codecPolicy");
523         this.encodeTable = Objects.requireNonNull(builder.getEncodeTable(), "builder.getEncodeTable()");
524         this.decodeTable = builder.getDecodeTable();
525     }
526 
527     /**
528      * Constructs a new instance.
529      * <p>
530      * Note {@code lineLength} is rounded down to the nearest multiple of the encoded block size. If {@code chunkSeparatorLength} is zero, then chunking is
531      * disabled.
532      * </p>
533      *
534      * @param unencodedBlockSize   the size of an unencoded block (for example Base64 = 3).
535      * @param encodedBlockSize     the size of an encoded block (for example Base64 = 4).
536      * @param lineLength           if &gt; 0, use chunking with a length {@code lineLength}.
537      * @param chunkSeparatorLength the chunk separator length, if relevant.
538      * @deprecated Use {@link BaseNCodec#BaseNCodec(AbstractBuilder)}.
539      */
540     @Deprecated
541     protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength) {
542         this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT);
543     }
544 
545     /**
546      * Constructs a new instance.
547      * <p>
548      * Note {@code lineLength} is rounded down to the nearest multiple of the encoded block size. If {@code chunkSeparatorLength} is zero, then chunking is
549      * disabled.
550      * </p>
551      *
552      * @param unencodedBlockSize   the size of an unencoded block (for example Base64 = 3).
553      * @param encodedBlockSize     the size of an encoded block (for example Base64 = 4).
554      * @param lineLength           if &gt; 0, use chunking with a length {@code lineLength}.
555      * @param chunkSeparatorLength the chunk separator length, if relevant.
556      * @param pad                  byte used as padding byte.
557      * @deprecated Use {@link BaseNCodec#BaseNCodec(AbstractBuilder)}.
558      */
559     @Deprecated
560     protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad) {
561         this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, pad, DECODING_POLICY_DEFAULT);
562     }
563 
564     /**
565      * Constructs a new instance.
566      * <p>
567      * Note {@code lineLength} is rounded down to the nearest multiple of the encoded block size. If {@code chunkSeparatorLength} is zero, then chunking is
568      * disabled.
569      * </p>
570      *
571      * @param unencodedBlockSize   the size of an unencoded block (for example Base64 = 3).
572      * @param encodedBlockSize     the size of an encoded block (for example Base64 = 4).
573      * @param lineLength           if &gt; 0, use chunking with a length {@code lineLength}.
574      * @param chunkSeparatorLength the chunk separator length, if relevant.
575      * @param pad                  byte used as padding byte.
576      * @param decodingPolicy       Decoding policy.
577      * @since 1.15
578      * @deprecated Use {@link BaseNCodec#BaseNCodec(AbstractBuilder)}.
579      */
580     @Deprecated
581     protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad,
582             final CodecPolicy decodingPolicy) {
583         this.unencodedBlockSize = unencodedBlockSize;
584         this.encodedBlockSize = encodedBlockSize;
585         final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
586         this.lineLength = useChunking ? lineLength / encodedBlockSize * encodedBlockSize : 0;
587         this.chunkSeparatorLength = chunkSeparatorLength;
588         this.pad = pad;
589         this.decodingPolicy = Objects.requireNonNull(decodingPolicy, "codecPolicy");
590         this.encodeTable = null;
591         this.decodeTable = null;
592     }
593 
594     /**
595      * Returns the amount of buffered data available for reading.
596      *
597      * @param context the context to be used.
598      * @return The amount of buffered data available for reading.
599      */
600     int available(final Context context) { // package protected for access from I/O streams
601         return hasData(context) ? context.pos - context.readPos : 0;
602     }
603 
604     /**
605      * Tests a given byte array to see if it contains any characters within the alphabet or PAD.
606      *
607      * Intended for use in checking line-ending arrays.
608      *
609      * @param arrayOctet byte array to test.
610      * @return {@code true} if any byte is a valid character in the alphabet or PAD; {@code false} otherwise.
611      */
612     protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
613         if (arrayOctet != null) {
614             for (final byte element : arrayOctet) {
615                 if (pad == element || isInAlphabet(element)) {
616                     return true;
617                 }
618             }
619         }
620         return false;
621     }
622 
623     /**
624      * Decodes a byte[] containing characters in the Base-N alphabet.
625      *
626      * @param array A byte array containing Base-N character data.
627      * @return a byte array containing binary data.
628      */
629     @Override
630     public byte[] decode(final byte[] array) {
631         if (BinaryCodec.isEmpty(array)) {
632             return array;
633         }
634         final Context context = new Context();
635         decode(array, 0, array.length, context);
636         decode(array, 0, EOF, context); // Notify decoder of EOF.
637         final byte[] result = new byte[context.pos];
638         readResults(result, 0, result.length, context);
639         return result;
640     }
641 
642     // package protected for access from I/O streams
643     abstract void decode(byte[] array, int i, int length, Context context);
644 
645     /**
646      * Decodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Decoder interface, and will throw a
647      * DecoderException if the supplied object is not of type byte[] or String.
648      *
649      * @param obj Object to decode.
650      * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied.
651      * @throws DecoderException if the parameter supplied is not of type byte[].
652      */
653     @Override
654     public Object decode(final Object obj) throws DecoderException {
655         if (obj instanceof byte[]) {
656             return decode((byte[]) obj);
657         }
658         if (obj instanceof String) {
659             return decode((String) obj);
660         }
661         throw new DecoderException("Parameter supplied to Base-N decode is not a byte[] or a String");
662     }
663 
664     /**
665      * Decodes a String containing characters in the Base-N alphabet.
666      *
667      * @param array A String containing Base-N character data.
668      * @return a byte array containing binary data.
669      */
670     public byte[] decode(final String array) {
671         return decode(StringUtils.getBytesUtf8(array));
672     }
673 
674     /**
675      * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
676      *
677      * @param array a byte array containing binary data.
678      * @return A byte array containing only the base N alphabetic character data.
679      */
680     @Override
681     public byte[] encode(final byte[] array) {
682         if (BinaryCodec.isEmpty(array)) {
683             return array;
684         }
685         return encode(array, 0, array.length);
686     }
687 
688     /**
689      * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
690      *
691      * @param array  a byte array containing binary data.
692      * @param offset initial offset of the subarray.
693      * @param length length of the subarray.
694      * @return A byte array containing only the base N alphabetic character data.
695      * @since 1.11
696      */
697     public byte[] encode(final byte[] array, final int offset, final int length) {
698         if (BinaryCodec.isEmpty(array)) {
699             return array;
700         }
701         final Context context = new Context();
702         encode(array, offset, length, context);
703         encode(array, offset, EOF, context); // Notify encoder of EOF.
704         final byte[] buf = new byte[context.pos - context.readPos];
705         readResults(buf, 0, buf.length, context);
706         return buf;
707     }
708 
709     // package protected for access from I/O streams
710     abstract void encode(byte[] array, int i, int length, Context context);
711 
712     /**
713      * Encodes an Object using the Base-N algorithm. This method is provided in order to satisfy the requirements of the Encoder interface, and will throw an
714      * EncoderException if the supplied object is not of type byte[].
715      *
716      * @param obj Object to encode.
717      * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
718      * @throws EncoderException if the parameter supplied is not of type byte[].
719      */
720     @Override
721     public Object encode(final Object obj) throws EncoderException {
722         if (!(obj instanceof byte[])) {
723             throw new EncoderException("Parameter supplied to Base-N encode is not a byte[]");
724         }
725         return encode((byte[]) obj);
726     }
727 
728     /**
729      * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses UTF8 encoding.
730      * <p>
731      * This is a duplicate of {@link #encodeToString(byte[])}; it was merged during refactoring.
732      * </p>
733      *
734      * @param array a byte array containing binary data.
735      * @return String containing only character data in the appropriate alphabet.
736      * @since 1.5
737      */
738     public String encodeAsString(final byte[] array) {
739         return StringUtils.newStringUtf8(encode(array));
740     }
741 
742     /**
743      * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. Uses UTF8 encoding.
744      *
745      * @param array a byte array containing binary data.
746      * @return A String containing only Base-N character data.
747      */
748     public String encodeToString(final byte[] array) {
749         return StringUtils.newStringUtf8(encode(array));
750     }
751 
752     /**
753      * Ensures that the buffer has room for {@code size} bytes
754      *
755      * @param size    minimum spare space required.
756      * @param context the context to be used.
757      * @return the buffer.
758      */
759     protected byte[] ensureBufferSize(final int size, final Context context) {
760         if (context.buffer == null) {
761             context.buffer = new byte[Math.max(size, getDefaultBufferSize())];
762             context.pos = 0;
763             context.readPos = 0;
764             // Overflow-conscious:
765             // x + y > z == x + y - z > 0
766         } else if (context.pos + size - context.buffer.length > 0) {
767             return resizeBuffer(context, context.pos + size);
768         }
769         return context.buffer;
770     }
771 
772     /**
773      * Gets the decoding behavior policy.
774      *
775      * <p>
776      * The default is lenient. If the decoding policy is strict, then decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a
777      * valid encoding. Decoding will compose trailing bits into 8-bit bytes and discard the remainder.
778      * </p>
779      *
780      * @return true if using strict decoding.
781      * @since 1.15
782      */
783     public CodecPolicy getCodecPolicy() {
784         return decodingPolicy;
785     }
786 
787     /**
788      * Gets the default buffer size. Can be overridden.
789      *
790      * @return the default buffer size.
791      */
792     protected int getDefaultBufferSize() {
793         return DEFAULT_BUFFER_SIZE;
794     }
795 
796     /**
797      * Gets the amount of space needed to encode the supplied array.
798      *
799      * @param array byte[] array which will later be encoded.
800      * @return amount of space needed to encode the supplied array. Returns a long since a max-len array will require &gt; Integer.MAX_VALUE.
801      */
802     public long getEncodedLength(final byte[] array) {
803         // Calculate non-chunked size - rounded up to allow for padding
804         // cast to long is needed to avoid possibility of overflow
805         long len = (array.length + unencodedBlockSize - 1) / unencodedBlockSize * (long) encodedBlockSize;
806         if (lineLength > 0) { // We're using chunking
807             // Round up to nearest multiple
808             len += (len + lineLength - 1) / lineLength * chunkSeparatorLength;
809         }
810         return len;
811     }
812 
813     /**
814      * Tests whether this object has buffered data for reading.
815      *
816      * @param context the context to be used.
817      * @return true if there is data still available for reading.
818      */
819     boolean hasData(final Context context) { // package protected for access from I/O streams
820         return context.pos > context.readPos;
821     }
822 
823     /**
824      * Tests whether or not the {@code octet} is in the current alphabet. Does not allow whitespace or pad.
825      *
826      * @param value The value to test.
827      * @return {@code true} if the value is defined in the current alphabet, {@code false} otherwise.
828      */
829     protected abstract boolean isInAlphabet(byte value);
830 
831     /**
832      * Tests a given byte array to see if it contains only valid characters within the alphabet. The method optionally treats whitespace and pad as valid.
833      *
834      * @param arrayOctet byte array to test.
835      * @param allowWSPad if {@code true}, then whitespace and PAD are also allowed.
836      * @return {@code true} if all bytes are valid characters in the alphabet or if the byte array is empty; {@code false}, otherwise.
837      */
838     public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
839         for (final byte octet : arrayOctet) {
840             if (!isInAlphabet(octet) && (!allowWSPad || octet != pad && !Character.isWhitespace(octet))) {
841                 return false;
842             }
843         }
844         return true;
845     }
846 
847     /**
848      * Tests a given String to see if it contains only valid characters within the alphabet. The method treats whitespace and PAD as valid.
849      *
850      * @param basen String to test.
851      * @return {@code true} if all characters in the String are valid characters in the alphabet or if the String is empty; {@code false}, otherwise.
852      * @see #isInAlphabet(byte[], boolean)
853      */
854     public boolean isInAlphabet(final String basen) {
855         return isInAlphabet(StringUtils.getBytesUtf8(basen), true);
856     }
857 
858     /**
859      * Tests true if decoding behavior is strict. Decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid encoding.
860      *
861      * <p>
862      * The default is false for lenient decoding. Decoding will compose trailing bits into 8-bit bytes and discard the remainder.
863      * </p>
864      *
865      * @return true if using strict decoding.
866      * @since 1.15
867      */
868     public boolean isStrictDecoding() {
869         return decodingPolicy == CodecPolicy.STRICT;
870     }
871 
872     /**
873      * Reads buffered data into the provided byte[] array, starting at position bPos, up to a maximum of bAvail bytes. Returns how many bytes were actually
874      * extracted.
875      * <p>
876      * Package private for access from I/O streams.
877      * </p>
878      *
879      * @param b       byte[] array to extract the buffered data into.
880      * @param bPos    position in byte[] array to start extraction at.
881      * @param bAvail  amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
882      * @param context the context to be used.
883      * @return The number of bytes successfully extracted into the provided byte[] array.
884      */
885     int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
886         if (hasData(context)) {
887             final int len = Math.min(available(context), bAvail);
888             System.arraycopy(context.buffer, context.readPos, b, bPos, len);
889             context.readPos += len;
890             if (!hasData(context)) {
891                 // All data read.
892                 // Reset position markers but do not set buffer to null to allow its reuse.
893                 // hasData(context) will still return false, and this method will return 0 until
894                 // more data is available, or -1 if EOF.
895                 context.pos = context.readPos = 0;
896             }
897             return len;
898         }
899         return context.eof ? EOF : 0;
900     }
901 }