Skip to content

Commit 8ce9ad5

Browse files
committed
Optimize LAST_BITS array size and update buffer length calculations
1 parent 841e708 commit 8ce9ad5

1 file changed

Lines changed: 8 additions & 5 deletions

File tree

src/main/java/net/eewbot/base32768j/Base32768Decoder.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@ public class Base32768Decoder {
1919

2020
private static final int TABLE_SIZE = 0xa840 + 32; // 43104 (max CODES_15 codepoint + 32)
2121
private static final char[] DECODE = new char[TABLE_SIZE];
22-
private static final byte[] LAST_BITS = new byte[TABLE_SIZE];
22+
private static final int LAST_BITS_SIZE = (0xa840 >> 5) + 1; // 1347
23+
private static final byte[] LAST_BITS = new byte[LAST_BITS_SIZE];
2324

2425
private static final VarHandle VH_LONG_BE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.BIG_ENDIAN);
2526

@@ -30,21 +31,21 @@ public class Base32768Decoder {
3031
for (int i = 0; i < Base32768Encoder.CODES_7.length; i++) {
3132
int base = i << 5; // 0..127
3233
int cp0 = Base32768Encoder.CODES_7[i];
34+
LAST_BITS[cp0 >> 5] = 7;
3335
for (int lo = 0; lo < 32; lo++) {
3436
int cp = cp0 + lo;
3537
DECODE[cp] = (char) (FLAG7 | (base + lo)); // bit15=1 を7bitフラグに
36-
LAST_BITS[cp] = 7;
3738
}
3839
}
3940

4041
// 15-bit blocks(非末尾/末尾とも有効)
4142
for (int i = 0; i < Base32768Encoder.CODES_15.length; i++) {
4243
int base = i << 5; // 0..32767
4344
int cp0 = Base32768Encoder.CODES_15[i];
45+
LAST_BITS[cp0 >> 5] = 15;
4446
for (int lo = 0; lo < 32; lo++) {
4547
int cp = cp0 + lo;
4648
DECODE[cp] = (char) (base + lo); // bit15=0
47-
LAST_BITS[cp] = 15;
4849
}
4950
}
5051
}
@@ -53,7 +54,8 @@ private static int calcBufferLength(String src) {
5354
if (src.isEmpty()) return 0;
5455
final int n = src.length();
5556
final char last = src.charAt(n - 1);
56-
final int lastBits = (last < TABLE_SIZE) ? (LAST_BITS[last] & 0xFF) : 0;
57+
final int block = last >> 5;
58+
final int lastBits = (block < LAST_BITS_SIZE) ? (LAST_BITS[block] & 0xFF) : 0;
5759
if (lastBits == 0) throw new IllegalBase32768TextException(n - 1, last);
5860
return ((n - 1) * 15 + lastBits) >>> 3;
5961
}
@@ -125,7 +127,8 @@ public byte[] decode(String src) {
125127
if (n == 0) return new byte[0];
126128

127129
final char last = src.charAt(n - 1);
128-
final int lastBits = (last < TABLE_SIZE) ? (LAST_BITS[last] & 0xFF) : 0;
130+
final int block = last >> 5;
131+
final int lastBits = (block < LAST_BITS_SIZE) ? (LAST_BITS[block] & 0xFF) : 0;
129132
if (lastBits == 0) throw new IllegalBase32768TextException(n - 1, last);
130133

131134
final int outLen = ((n - 1) * 15 + lastBits) >>> 3;

0 commit comments

Comments
 (0)