|
| 1 | +/* |
| 2 | + * Copyright 2018 Patrick Favre-Bulle |
| 3 | + * |
| 4 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 5 | + * or more contributor license agreements. See the NOTICE file |
| 6 | + * distributed with this work for additional information |
| 7 | + * regarding copyright ownership. The ASF licenses this file |
| 8 | + * to you under the Apache License, Version 2.0 (the |
| 9 | + * "License"); you may not use this file except in compliance |
| 10 | + * with the License. You may obtain a copy of the License at |
| 11 | + * |
| 12 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 13 | + * |
| 14 | + * Unless required by applicable law or agreed to in writing, |
| 15 | + * software distributed under the License is distributed on an |
| 16 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 17 | + * KIND, either express or implied. See the License for the |
| 18 | + * specific language governing permissions and limitations |
| 19 | + * under the License. |
| 20 | + */ |
| 21 | + |
| 22 | +package at.favre.lib.bytes; |
| 23 | + |
| 24 | +import java.io.IOException; |
| 25 | +import java.nio.ByteOrder; |
| 26 | +import java.util.Arrays; |
| 27 | +import java.util.Objects; |
| 28 | + |
| 29 | +/** |
| 30 | + * Encoder which supports arbitrary alphabet and padding. |
| 31 | + * |
| 32 | + * Derived from Google Guava's common/io/ BaseEncoding |
| 33 | + * <p> |
| 34 | + * See: https://github.com/google/guava/blob/v26.0/guava/src/com/google/common/io/BaseEncoding.java |
| 35 | + */ |
| 36 | +final class BaseEncoding implements BinaryToTextEncoding.EncoderDecoder { |
| 37 | + private static final char ASCII_MAX = 127; |
| 38 | + |
| 39 | + static final Alphabet BASE32_RFC4848 = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".toCharArray()); |
| 40 | + static final char BASE32_RFC4848_PADDING = '='; |
| 41 | + |
| 42 | + private final Alphabet alphabet; |
| 43 | + private final Character paddingChar; |
| 44 | + |
| 45 | + BaseEncoding(Alphabet alphabet, Character paddingChar) { |
| 46 | + this.alphabet = Objects.requireNonNull(alphabet); |
| 47 | + this.paddingChar = paddingChar; |
| 48 | + } |
| 49 | + |
| 50 | + private int maxEncodedSize(int bytes) { |
| 51 | + return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk); |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public String encode(byte[] array, ByteOrder byteOrder) { |
| 56 | + return encode(array, 0, array.length); |
| 57 | + } |
| 58 | + |
| 59 | + private String encode(byte[] bytes, int off, int len) { |
| 60 | + StringBuilder result = new StringBuilder(maxEncodedSize(len)); |
| 61 | + try { |
| 62 | + encodeTo(result, bytes, off, len); |
| 63 | + } catch (IOException impossible) { |
| 64 | + throw new AssertionError(impossible); |
| 65 | + } |
| 66 | + return result.toString(); |
| 67 | + } |
| 68 | + |
| 69 | + private void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { |
| 70 | + Objects.requireNonNull(target); |
| 71 | + for (int i = 0; i < len; i += alphabet.bytesPerChunk) { |
| 72 | + encodeChunkTo(target, bytes, off + i, Math.min(alphabet.bytesPerChunk, len - i)); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + private void encodeChunkTo(Appendable target, byte[] bytes, int off, int len) throws IOException { |
| 77 | + Objects.requireNonNull(target); |
| 78 | + long bitBuffer = 0; |
| 79 | + for (int i = 0; i < len; ++i) { |
| 80 | + bitBuffer |= bytes[off + i] & 0xFF; |
| 81 | + bitBuffer <<= 8; // Add additional zero byte in the end. |
| 82 | + } |
| 83 | + // Position of first character is length of bitBuffer minus bitsPerChar. |
| 84 | + final int bitOffset = (len + 1) * 8 - alphabet.bitsPerChar; |
| 85 | + int bitsProcessed = 0; |
| 86 | + while (bitsProcessed < len * 8) { |
| 87 | + int charIndex = (int) (bitBuffer >>> (bitOffset - bitsProcessed)) & alphabet.mask; |
| 88 | + target.append(alphabet.encode(charIndex)); |
| 89 | + bitsProcessed += alphabet.bitsPerChar; |
| 90 | + } |
| 91 | + if (paddingChar != null) { |
| 92 | + while (bitsProcessed < alphabet.bytesPerChunk * 8) { |
| 93 | + target.append(paddingChar); |
| 94 | + bitsProcessed += alphabet.bitsPerChar; |
| 95 | + } |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + private int maxDecodedSize(int chars) { |
| 100 | + return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L); |
| 101 | + } |
| 102 | + |
| 103 | + private String trimTrailingPadding(CharSequence chars) { |
| 104 | + Objects.requireNonNull(chars); |
| 105 | + if (paddingChar == null) { |
| 106 | + return chars.toString(); |
| 107 | + } |
| 108 | + int l; |
| 109 | + for (l = chars.length() - 1; l >= 0; l--) { |
| 110 | + if (chars.charAt(l) != paddingChar) { |
| 111 | + break; |
| 112 | + } |
| 113 | + } |
| 114 | + return chars.subSequence(0, l + 1).toString(); |
| 115 | + } |
| 116 | + |
| 117 | + @Override |
| 118 | + public byte[] decode(String encoded) { |
| 119 | + encoded = trimTrailingPadding(encoded); |
| 120 | + byte[] tmp = new byte[maxDecodedSize(encoded.length())]; |
| 121 | + int len = decodeTo(tmp, encoded); |
| 122 | + return extract(tmp, len); |
| 123 | + } |
| 124 | + |
| 125 | + private static byte[] extract(byte[] result, int length) { |
| 126 | + if (length == result.length) { |
| 127 | + return result; |
| 128 | + } else { |
| 129 | + byte[] trunc = new byte[length]; |
| 130 | + System.arraycopy(result, 0, trunc, 0, length); |
| 131 | + return trunc; |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + private int decodeTo(byte[] target, CharSequence chars) { |
| 136 | + Objects.requireNonNull(target); |
| 137 | + chars = trimTrailingPadding(chars); |
| 138 | + int bytesWritten = 0; |
| 139 | + for (int charIdx = 0; charIdx < chars.length(); charIdx += alphabet.charsPerChunk) { |
| 140 | + long chunk = 0; |
| 141 | + int charsProcessed = 0; |
| 142 | + for (int i = 0; i < alphabet.charsPerChunk; i++) { |
| 143 | + chunk <<= alphabet.bitsPerChar; |
| 144 | + if (charIdx + i < chars.length()) { |
| 145 | + chunk |= alphabet.decode(chars.charAt(charIdx + charsProcessed++)); |
| 146 | + } |
| 147 | + } |
| 148 | + final int minOffset = alphabet.bytesPerChunk * 8 - charsProcessed * alphabet.bitsPerChar; |
| 149 | + for (int offset = (alphabet.bytesPerChunk - 1) * 8; offset >= minOffset; offset -= 8) { |
| 150 | + target[bytesWritten++] = (byte) ((chunk >>> offset) & 0xFF); |
| 151 | + } |
| 152 | + } |
| 153 | + return bytesWritten; |
| 154 | + } |
| 155 | + |
| 156 | + static final class Alphabet { |
| 157 | + // this is meant to be immutable -- don't modify it! |
| 158 | + private final char[] chars; |
| 159 | + final int mask; |
| 160 | + final int bitsPerChar; |
| 161 | + final int charsPerChunk; |
| 162 | + final int bytesPerChunk; |
| 163 | + private final byte[] decodabet; |
| 164 | + |
| 165 | + Alphabet(char[] chars) { |
| 166 | + this.chars = Objects.requireNonNull(chars); |
| 167 | + this.bitsPerChar = log2(chars.length); |
| 168 | + |
| 169 | + /* |
| 170 | + * e.g. for base64, bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. This makes |
| 171 | + * for the smallest chunk size that still has charsPerChunk * bitsPerChar be a multiple of 8. |
| 172 | + */ |
| 173 | + int gcd = Math.min(8, Integer.lowestOneBit(bitsPerChar)); |
| 174 | + this.charsPerChunk = 8 / gcd; |
| 175 | + this.bytesPerChunk = bitsPerChar / gcd; |
| 176 | + this.mask = chars.length - 1; |
| 177 | + |
| 178 | + byte[] decodabet = new byte[ASCII_MAX + 1]; |
| 179 | + Arrays.fill(decodabet, (byte) -1); |
| 180 | + for (int i = 0; i < chars.length; i++) { |
| 181 | + char c = chars[i]; |
| 182 | + decodabet[c] = (byte) i; |
| 183 | + } |
| 184 | + this.decodabet = decodabet; |
| 185 | + } |
| 186 | + |
| 187 | + char encode(int bits) { |
| 188 | + return chars[bits]; |
| 189 | + } |
| 190 | + |
| 191 | + int decode(char ch) { |
| 192 | + return (int) decodabet[ch]; |
| 193 | + } |
| 194 | + } |
| 195 | + |
| 196 | + private static int divide(int p, int q) { |
| 197 | + int div = p / q; |
| 198 | + int rem = p - q * div; // equal to p % q |
| 199 | + |
| 200 | + if (rem == 0) { |
| 201 | + return div; |
| 202 | + } |
| 203 | + int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1)); |
| 204 | + return signum > 0 ? div + signum : div; |
| 205 | + } |
| 206 | + |
| 207 | + private static int log2(int x) { |
| 208 | + return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x); |
| 209 | + } |
| 210 | +} |
0 commit comments