Skip to content

Commit 299bf2e

Browse files
committed
Small cleanup over #10
1 parent fc49725 commit 299bf2e

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/main/java/com/github/fzakaria/ascii85/Ascii85.java

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,22 @@ public static byte[] decode(String chars) {
9595
// to scan through the input to compute the target length, instead of just subtracting 20% of
9696
// the encoded text length.
9797
final int inputLength = chars.length();
98-
int zCount = 0;
99-
for(int i = 0 ; i < inputLength; i++) {
100-
if(chars.charAt(i) == 'z') ++ zCount;
101-
}
102-
int computedLength = 4 * zCount + 4 * (inputLength - zCount) / 5;
103-
ByteBuffer bytebuff = ByteBuffer.allocate(computedLength);
98+
99+
// lets first count the occurrences of 'z'
100+
long zCount = chars.chars().filter(c -> c == 'z').count();
101+
102+
// Typically by using five ASCII characters to represent four bytes of binary data
103+
// the encoded size ¹⁄₄ is larger than the original.
104+
// We however have to account for the 'z' which were compressed
105+
BigDecimal uncompressedZLength = BigDecimal.valueOf(zCount).multiply(BigDecimal.valueOf(4));
106+
107+
BigDecimal uncompressedNonZLength = BigDecimal.valueOf(inputLength - zCount)
108+
.multiply(BigDecimal.valueOf(4))
109+
.divide(BigDecimal.valueOf(5));
110+
111+
BigDecimal uncompressedLength = uncompressedZLength.add(uncompressedNonZLength);
112+
113+
ByteBuffer bytebuff = ByteBuffer.allocate(uncompressedLength.intValue());
104114
//1. Whitespace characters may occur anywhere to accommodate line length limitations. So lets strip it.
105115
chars = REMOVE_WHITESPACE.matcher(chars).replaceAll("");
106116
//Since Base85 is an ascii encoder, we don't need to get the bytes as UTF-8.

0 commit comments

Comments
 (0)