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.
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.
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          * Placeholder for the bytes we're dealing with for our based logic. Bitwise operations store and extract the encoding or decoding from this variable.
252          */
253         long lbitWorkArea;
254         /**
255          * Buffer for streaming.
256          */
257         byte[] buffer;
258         /**
259          * Position where next character should be written in the buffer.
260          */
261         int pos;
262         /**
263          * Position where next character should be read from the buffer.
264          */
265         int readPos;
266         /**
267          * Boolean flag to indicate the EOF has been reached. Once EOF has been reached, this object becomes useless, and must be thrown away.
268          */
269         boolean eof;
270         /**
271          * 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
272          * goes beyond lineLength (if lineLength &gt; 0).
273          */
274         int currentLinePos;
275         /**
276          * 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.
277          */
278         int modulus;
279 
280         /**
281          * Returns a String useful for debugging (especially within a debugger.)
282          *
283          * @return a String useful for debugging.
284          */
285         @Override
286         public String toString() {
287             return String.format("%s[buffer=%s, currentLinePos=%s, eof=%s, ibitWorkArea=%s, lbitWorkArea=%s, " + "modulus=%s, pos=%s, readPos=%s]",
288                     this.getClass().getSimpleName(), Arrays.toString(buffer), currentLinePos, eof, ibitWorkArea, lbitWorkArea, modulus, pos, readPos);
289         }
290     }
291 
292     /**
293      * End-of-file marker.
294      *
295      * @since 1.7
296      */
297     static final int EOF = -1;
298     /**
299      * MIME chunk size per RFC 2045 section 6.8.
300      *
301      * <p>
302      * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
303      * </p>
304      *
305      * @see <a href="https://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 6.8</a>
306      */
307     public static final int MIME_CHUNK_SIZE = 76;
308     /**
309      * PEM chunk size per RFC 1421 section 4.3.2.4.
310      *
311      * <p>
312      * The {@value} character limit does not count the trailing CRLF, but counts all other characters, including any equal signs.
313      * </p>
314      *
315      * @see <a href="https://tools.ietf.org/html/rfc1421">RFC 1421 section 4.3.2.4</a>
316      */
317     public static final int PEM_CHUNK_SIZE = 64;
318     private static final int DEFAULT_BUFFER_RESIZE_FACTOR = 2;
319     /**
320      * Defines the default buffer size - currently {@value} - must be large enough for at least one encoded block+separator
321      */
322     private static final int DEFAULT_BUFFER_SIZE = 8192;
323     /**
324      * The maximum size buffer to allocate.
325      *
326      * <p>
327      * This is set to the same size used in the JDK {@link java.util.ArrayList}:
328      * </p>
329      * <blockquote> Some VMs reserve some header words in an array. Attempts to allocate larger arrays may result in OutOfMemoryError: Requested array size
330      * exceeds VM limit. </blockquote>
331      */
332     private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8;
333     /** Mask used to extract 8 bits, used in decoding bytes */
334     protected static final int MASK_8BITS = 0xff;
335     /**
336      * Byte used to pad output.
337      */
338     protected static final byte PAD_DEFAULT = '='; // Allow static access to default
339     /**
340      * The default decoding policy.
341      *
342      * @since 1.15
343      */
344     protected static final CodecPolicy DECODING_POLICY_DEFAULT = CodecPolicy.LENIENT;
345     /**
346      * Chunk separator per RFC 2045 section 2.1.
347      *
348      * @see <a href="https://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
349      */
350     static final byte[] CHUNK_SEPARATOR = { '\r', '\n' };
351     /**
352      * The empty byte array.
353      */
354     static final byte[] EMPTY_BYTE_ARRAY = {};
355 
356     /**
357      * Create a positive capacity at least as large the minimum required capacity. If the minimum capacity is negative then this throws an OutOfMemoryError as
358      * no array can be allocated.
359      *
360      * @param minCapacity the minimum capacity
361      * @return the capacity
362      * @throws OutOfMemoryError if the {@code minCapacity} is negative
363      */
364     private static int createPositiveCapacity(final int minCapacity) {
365         if (minCapacity < 0) {
366             // overflow
367             throw new OutOfMemoryError("Unable to allocate array size: " + (minCapacity & 0xffffffffL));
368         }
369         // This is called when we require buffer expansion to a very big array.
370         // Use the conservative maximum buffer size if possible, otherwise the biggest required.
371         //
372         // Note: In this situation JDK 1.8 java.util.ArrayList returns Integer.MAX_VALUE.
373         // This excludes some VMs that can exceed MAX_BUFFER_SIZE but not allocate a full
374         // Integer.MAX_VALUE length array.
375         // The result is that we may have to allocate an array of this size more than once if
376         // the capacity must be expanded again.
377         return Math.max(minCapacity, MAX_BUFFER_SIZE);
378     }
379 
380     /**
381      * Gets a copy of the chunk separator per RFC 2045 section 2.1.
382      *
383      * @return the chunk separator
384      * @see <a href="https://www.ietf.org/rfc/rfc2045.txt">RFC 2045 section 2.1</a>
385      * @since 1.15
386      */
387     public static byte[] getChunkSeparator() {
388         return CHUNK_SEPARATOR.clone();
389     }
390 
391     /**
392      * Gets the array length or 0 if null.
393      *
394      * @param array the array or null.
395      * @return the array length or 0 if null.
396      */
397     static int getLength(final byte[] array) {
398         return array == null ? 0 : array.length;
399     }
400 
401     /**
402      * Checks if a byte value is whitespace or not.
403      *
404      * @param byteToCheck the byte to check
405      * @return true if byte is whitespace, false otherwise
406      * @see Character#isWhitespace(int)
407      * @deprecated Use {@link Character#isWhitespace(int)}.
408      */
409     @Deprecated
410     protected static boolean isWhiteSpace(final byte byteToCheck) {
411         return Character.isWhitespace(byteToCheck);
412     }
413 
414     /**
415      * Increases our buffer by the {@link #DEFAULT_BUFFER_RESIZE_FACTOR}.
416      *
417      * @param context     the context to be used
418      * @param minCapacity the minimum required capacity
419      * @return the resized byte[] buffer
420      * @throws OutOfMemoryError if the {@code minCapacity} is negative
421      */
422     private static byte[] resizeBuffer(final Context context, final int minCapacity) {
423         // Overflow-conscious code treats the min and new capacity as unsigned.
424         final int oldCapacity = context.buffer.length;
425         int newCapacity = oldCapacity * DEFAULT_BUFFER_RESIZE_FACTOR;
426         if (Integer.compareUnsigned(newCapacity, minCapacity) < 0) {
427             newCapacity = minCapacity;
428         }
429         if (Integer.compareUnsigned(newCapacity, MAX_BUFFER_SIZE) > 0) {
430             newCapacity = createPositiveCapacity(minCapacity);
431         }
432         final byte[] b = Arrays.copyOf(context.buffer, newCapacity);
433         context.buffer = b;
434         return b;
435     }
436 
437     /**
438      * Deprecated: Will be removed in 2.0.
439      * <p>
440      * Instance variable just in case it needs to vary later
441      * </p>
442      *
443      * @deprecated Use {@link #pad}. Will be removed in 2.0.
444      */
445     @Deprecated
446     protected final byte PAD = PAD_DEFAULT;
447     /** Pad byte. Instance variable just in case it needs to vary later. */
448     protected final byte pad;
449     /** Number of bytes in each full block of unencoded data, for example 4 for Base64 and 5 for Base32 */
450     private final int unencodedBlockSize;
451     /** Number of bytes in each full block of encoded data, for example 3 for Base64 and 8 for Base32 */
452     private final int encodedBlockSize;
453     /**
454      * 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
455      * encodedBlockSize.
456      */
457     protected final int lineLength;
458     /**
459      * Size of chunk separator. Not used unless {@link #lineLength} &gt; 0.
460      */
461     private final int chunkSeparatorLength;
462     /**
463      * 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
464      * unused from the final character or entire characters. The default mode is lenient decoding. Set this to {@code true} to enable strict decoding.
465      * <ul>
466      * <li>Lenient: Any trailing bits are composed into 8-bit bytes where possible. The remainder are discarded.
467      * <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
468      * character must be zero. Impossible counts of entire final characters are not allowed.
469      * </ul>
470      * <p>
471      * 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
472      * on the final character. This requires that the input bytes use the same padding and alphabet as the encoder.
473      * </p>
474      */
475     private final CodecPolicy decodingPolicy;
476 
477     /**
478      * Decode table to use.
479      */
480     final byte[] decodeTable;
481 
482     /**
483      * Encode table.
484      */
485     final byte[] encodeTable;
486 
487     /**
488      * Constructs a new instance for a subclass.
489      *
490      * @param builder How to build this portion of the instance.
491      * @since 1.20.0
492      */
493     protected BaseNCodec(final AbstractBuilder<?, ?> builder) {
494         this.unencodedBlockSize = builder.unencodedBlockSize;
495         this.encodedBlockSize = builder.encodedBlockSize;
496         final boolean useChunking = builder.lineLength > 0 && builder.lineSeparator.length > 0;
497         this.lineLength = useChunking ? builder.lineLength / builder.encodedBlockSize * builder.encodedBlockSize : 0;
498         this.chunkSeparatorLength = builder.lineSeparator.length;
499         this.pad = builder.padding;
500         this.decodingPolicy = Objects.requireNonNull(builder.decodingPolicy, "codecPolicy");
501         this.encodeTable = Objects.requireNonNull(builder.getEncodeTable(), "builder.getEncodeTable()");
502         this.decodeTable = builder.getDecodeTable();
503     }
504 
505     /**
506      * Constructs a new instance.
507      * <p>
508      * Note {@code lineLength} is rounded down to the nearest multiple of the encoded block size. If {@code chunkSeparatorLength} is zero, then chunking is
509      * disabled.
510      * </p>
511      *
512      * @param unencodedBlockSize   the size of an unencoded block (for example Base64 = 3).
513      * @param encodedBlockSize     the size of an encoded block (for example Base64 = 4).
514      * @param lineLength           if &gt; 0, use chunking with a length {@code lineLength}.
515      * @param chunkSeparatorLength the chunk separator length, if relevant.
516      * @deprecated Use {@link BaseNCodec#BaseNCodec(AbstractBuilder)}.
517      */
518     @Deprecated
519     protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength) {
520         this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, PAD_DEFAULT);
521     }
522 
523     /**
524      * Constructs a new instance.
525      * <p>
526      * Note {@code lineLength} is rounded down to the nearest multiple of the encoded block size. If {@code chunkSeparatorLength} is zero, then chunking is
527      * disabled.
528      * </p>
529      *
530      * @param unencodedBlockSize   the size of an unencoded block (for example Base64 = 3).
531      * @param encodedBlockSize     the size of an encoded block (for example Base64 = 4).
532      * @param lineLength           if &gt; 0, use chunking with a length {@code lineLength}.
533      * @param chunkSeparatorLength the chunk separator length, if relevant.
534      * @param pad                  byte used as padding byte.
535      * @deprecated Use {@link BaseNCodec#BaseNCodec(AbstractBuilder)}.
536      */
537     @Deprecated
538     protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad) {
539         this(unencodedBlockSize, encodedBlockSize, lineLength, chunkSeparatorLength, pad, DECODING_POLICY_DEFAULT);
540     }
541 
542     /**
543      * Constructs a new instance.
544      * <p>
545      * Note {@code lineLength} is rounded down to the nearest multiple of the encoded block size. If {@code chunkSeparatorLength} is zero, then chunking is
546      * disabled.
547      * </p>
548      *
549      * @param unencodedBlockSize   the size of an unencoded block (for example Base64 = 3).
550      * @param encodedBlockSize     the size of an encoded block (for example Base64 = 4).
551      * @param lineLength           if &gt; 0, use chunking with a length {@code lineLength}.
552      * @param chunkSeparatorLength the chunk separator length, if relevant.
553      * @param pad                  byte used as padding byte.
554      * @param decodingPolicy       Decoding policy.
555      * @since 1.15
556      * @deprecated Use {@link BaseNCodec#BaseNCodec(AbstractBuilder)}.
557      */
558     @Deprecated
559     protected BaseNCodec(final int unencodedBlockSize, final int encodedBlockSize, final int lineLength, final int chunkSeparatorLength, final byte pad,
560             final CodecPolicy decodingPolicy) {
561         this.unencodedBlockSize = unencodedBlockSize;
562         this.encodedBlockSize = encodedBlockSize;
563         final boolean useChunking = lineLength > 0 && chunkSeparatorLength > 0;
564         this.lineLength = useChunking ? lineLength / encodedBlockSize * encodedBlockSize : 0;
565         this.chunkSeparatorLength = chunkSeparatorLength;
566         this.pad = pad;
567         this.decodingPolicy = Objects.requireNonNull(decodingPolicy, "codecPolicy");
568         this.encodeTable = null;
569         this.decodeTable = null;
570     }
571 
572     /**
573      * Returns the amount of buffered data available for reading.
574      *
575      * @param context the context to be used.
576      * @return The amount of buffered data available for reading.
577      */
578     int available(final Context context) { // package protected for access from I/O streams
579         return hasData(context) ? context.pos - context.readPos : 0;
580     }
581 
582     /**
583      * Tests a given byte array to see if it contains any characters within the alphabet or PAD.
584      *
585      * Intended for use in checking line-ending arrays.
586      *
587      * @param arrayOctet byte array to test.
588      * @return {@code true} if any byte is a valid character in the alphabet or PAD; {@code false} otherwise.
589      */
590     protected boolean containsAlphabetOrPad(final byte[] arrayOctet) {
591         if (arrayOctet != null) {
592             for (final byte element : arrayOctet) {
593                 if (pad == element || isInAlphabet(element)) {
594                     return true;
595                 }
596             }
597         }
598         return false;
599     }
600 
601     /**
602      * Decodes a byte[] containing characters in the Base-N alphabet.
603      *
604      * @param array A byte array containing Base-N character data.
605      * @return a byte array containing binary data.
606      */
607     @Override
608     public byte[] decode(final byte[] array) {
609         if (BinaryCodec.isEmpty(array)) {
610             return array;
611         }
612         final Context context = new Context();
613         decode(array, 0, array.length, context);
614         decode(array, 0, EOF, context); // Notify decoder of EOF.
615         final byte[] result = new byte[context.pos];
616         readResults(result, 0, result.length, context);
617         return result;
618     }
619 
620     // package protected for access from I/O streams
621     abstract void decode(byte[] array, int i, int length, Context context);
622 
623     /**
624      * 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
625      * DecoderException if the supplied object is not of type byte[] or String.
626      *
627      * @param obj Object to decode.
628      * @return An object (of type byte[]) containing the binary data which corresponds to the byte[] or String supplied.
629      * @throws DecoderException if the parameter supplied is not of type byte[].
630      */
631     @Override
632     public Object decode(final Object obj) throws DecoderException {
633         if (obj instanceof byte[]) {
634             return decode((byte[]) obj);
635         }
636         if (obj instanceof String) {
637             return decode((String) obj);
638         }
639         throw new DecoderException("Parameter supplied to Base-N decode is not a byte[] or a String");
640     }
641 
642     /**
643      * Decodes a String containing characters in the Base-N alphabet.
644      *
645      * @param array A String containing Base-N character data.
646      * @return a byte array containing binary data.
647      */
648     public byte[] decode(final String array) {
649         return decode(StringUtils.getBytesUtf8(array));
650     }
651 
652     /**
653      * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
654      *
655      * @param array a byte array containing binary data.
656      * @return A byte array containing only the base N alphabetic character data.
657      */
658     @Override
659     public byte[] encode(final byte[] array) {
660         if (BinaryCodec.isEmpty(array)) {
661             return array;
662         }
663         return encode(array, 0, array.length);
664     }
665 
666     /**
667      * Encodes a byte[] containing binary data, into a byte[] containing characters in the alphabet.
668      *
669      * @param array  a byte array containing binary data.
670      * @param offset initial offset of the subarray.
671      * @param length length of the subarray.
672      * @return A byte array containing only the base N alphabetic character data.
673      * @since 1.11
674      */
675     public byte[] encode(final byte[] array, final int offset, final int length) {
676         if (BinaryCodec.isEmpty(array)) {
677             return array;
678         }
679         final Context context = new Context();
680         encode(array, offset, length, context);
681         encode(array, offset, EOF, context); // Notify encoder of EOF.
682         final byte[] buf = new byte[context.pos - context.readPos];
683         readResults(buf, 0, buf.length, context);
684         return buf;
685     }
686 
687     // package protected for access from I/O streams
688     abstract void encode(byte[] array, int i, int length, Context context);
689 
690     /**
691      * 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
692      * EncoderException if the supplied object is not of type byte[].
693      *
694      * @param obj Object to encode.
695      * @return An object (of type byte[]) containing the Base-N encoded data which corresponds to the byte[] supplied.
696      * @throws EncoderException if the parameter supplied is not of type byte[].
697      */
698     @Override
699     public Object encode(final Object obj) throws EncoderException {
700         if (!(obj instanceof byte[])) {
701             throw new EncoderException("Parameter supplied to Base-N encode is not a byte[]");
702         }
703         return encode((byte[]) obj);
704     }
705 
706     /**
707      * Encodes a byte[] containing binary data, into a String containing characters in the appropriate alphabet. Uses UTF8 encoding.
708      * <p>
709      * This is a duplicate of {@link #encodeToString(byte[])}; it was merged during refactoring.
710      * </p>
711      *
712      * @param array a byte array containing binary data.
713      * @return String containing only character data in the appropriate alphabet.
714      * @since 1.5
715      */
716     public String encodeAsString(final byte[] array) {
717         return StringUtils.newStringUtf8(encode(array));
718     }
719 
720     /**
721      * Encodes a byte[] containing binary data, into a String containing characters in the Base-N alphabet. Uses UTF8 encoding.
722      *
723      * @param array a byte array containing binary data.
724      * @return A String containing only Base-N character data.
725      */
726     public String encodeToString(final byte[] array) {
727         return StringUtils.newStringUtf8(encode(array));
728     }
729 
730     /**
731      * Ensures that the buffer has room for {@code size} bytes
732      *
733      * @param size    minimum spare space required.
734      * @param context the context to be used.
735      * @return the buffer
736      */
737     protected byte[] ensureBufferSize(final int size, final Context context) {
738         if (context.buffer == null) {
739             context.buffer = new byte[Math.max(size, getDefaultBufferSize())];
740             context.pos = 0;
741             context.readPos = 0;
742             // Overflow-conscious:
743             // x + y > z == x + y - z > 0
744         } else if (context.pos + size - context.buffer.length > 0) {
745             return resizeBuffer(context, context.pos + size);
746         }
747         return context.buffer;
748     }
749 
750     /**
751      * Gets the decoding behavior policy.
752      *
753      * <p>
754      * 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
755      * valid encoding. Decoding will compose trailing bits into 8-bit bytes and discard the remainder.
756      * </p>
757      *
758      * @return true if using strict decoding.
759      * @since 1.15
760      */
761     public CodecPolicy getCodecPolicy() {
762         return decodingPolicy;
763     }
764 
765     /**
766      * Gets the default buffer size. Can be overridden.
767      *
768      * @return the default buffer size.
769      */
770     protected int getDefaultBufferSize() {
771         return DEFAULT_BUFFER_SIZE;
772     }
773 
774     /**
775      * Gets the amount of space needed to encode the supplied array.
776      *
777      * @param array byte[] array which will later be encoded.
778      * @return amount of space needed to encode the supplied array. Returns a long since a max-len array will require &gt; Integer.MAX_VALUE.
779      */
780     public long getEncodedLength(final byte[] array) {
781         // Calculate non-chunked size - rounded up to allow for padding
782         // cast to long is needed to avoid possibility of overflow
783         long len = (array.length + unencodedBlockSize - 1) / unencodedBlockSize * (long) encodedBlockSize;
784         if (lineLength > 0) { // We're using chunking
785             // Round up to nearest multiple
786             len += (len + lineLength - 1) / lineLength * chunkSeparatorLength;
787         }
788         return len;
789     }
790 
791     /**
792      * Tests whether this object has buffered data for reading.
793      *
794      * @param context the context to be used.
795      * @return true if there is data still available for reading.
796      */
797     boolean hasData(final Context context) { // package protected for access from I/O streams
798         return context.pos > context.readPos;
799     }
800 
801     /**
802      * Tests whether or not the {@code octet} is in the current alphabet. Does not allow whitespace or pad.
803      *
804      * @param value The value to test.
805      * @return {@code true} if the value is defined in the current alphabet, {@code false} otherwise.
806      */
807     protected abstract boolean isInAlphabet(byte value);
808 
809     /**
810      * 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.
811      *
812      * @param arrayOctet byte array to test.
813      * @param allowWSPad if {@code true}, then whitespace and PAD are also allowed.
814      * @return {@code true} if all bytes are valid characters in the alphabet or if the byte array is empty; {@code false}, otherwise.
815      */
816     public boolean isInAlphabet(final byte[] arrayOctet, final boolean allowWSPad) {
817         for (final byte octet : arrayOctet) {
818             if (!isInAlphabet(octet) && (!allowWSPad || octet != pad && !Character.isWhitespace(octet))) {
819                 return false;
820             }
821         }
822         return true;
823     }
824 
825     /**
826      * Tests a given String to see if it contains only valid characters within the alphabet. The method treats whitespace and PAD as valid.
827      *
828      * @param basen String to test.
829      * @return {@code true} if all characters in the String are valid characters in the alphabet or if the String is empty; {@code false}, otherwise.
830      * @see #isInAlphabet(byte[], boolean)
831      */
832     public boolean isInAlphabet(final String basen) {
833         return isInAlphabet(StringUtils.getBytesUtf8(basen), true);
834     }
835 
836     /**
837      * Tests true if decoding behavior is strict. Decoding will raise an {@link IllegalArgumentException} if trailing bits are not part of a valid encoding.
838      *
839      * <p>
840      * The default is false for lenient decoding. Decoding will compose trailing bits into 8-bit bytes and discard the remainder.
841      * </p>
842      *
843      * @return true if using strict decoding.
844      * @since 1.15
845      */
846     public boolean isStrictDecoding() {
847         return decodingPolicy == CodecPolicy.STRICT;
848     }
849 
850     /**
851      * 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
852      * extracted.
853      * <p>
854      * Package private for access from I/O streams.
855      * </p>
856      *
857      * @param b       byte[] array to extract the buffered data into.
858      * @param bPos    position in byte[] array to start extraction at.
859      * @param bAvail  amount of bytes we're allowed to extract. We may extract fewer (if fewer are available).
860      * @param context the context to be used.
861      * @return The number of bytes successfully extracted into the provided byte[] array.
862      */
863     int readResults(final byte[] b, final int bPos, final int bAvail, final Context context) {
864         if (hasData(context)) {
865             final int len = Math.min(available(context), bAvail);
866             System.arraycopy(context.buffer, context.readPos, b, bPos, len);
867             context.readPos += len;
868             if (!hasData(context)) {
869                 // All data read.
870                 // Reset position markers but do not set buffer to null to allow its reuse.
871                 // hasData(context) will still return false, and this method will return 0 until
872                 // more data is available, or -1 if EOF.
873                 context.pos = context.readPos = 0;
874             }
875             return len;
876         }
877         return context.eof ? EOF : 0;
878     }
879 }