File tree Expand file tree Collapse file tree 1 file changed +16
-6
lines changed
src/main/java/com/github/fzakaria/ascii85 Expand file tree Collapse file tree 1 file changed +16
-6
lines changed Original file line number Diff line number Diff line change @@ -95,12 +95,22 @@ public static byte[] decode(String chars) {
95
95
// to scan through the input to compute the target length, instead of just subtracting 20% of
96
96
// the encoded text length.
97
97
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 ());
104
114
//1. Whitespace characters may occur anywhere to accommodate line length limitations. So lets strip it.
105
115
chars = REMOVE_WHITESPACE .matcher (chars ).replaceAll ("" );
106
116
//Since Base85 is an ascii encoder, we don't need to get the bytes as UTF-8.
You can’t perform that action at this time.
0 commit comments