Skip to content

Commit e8c3f71

Browse files
committed
Optimze Gzip compression logic and error handling
1 parent 427cb84 commit e8c3f71

File tree

1 file changed

+8
-41
lines changed

1 file changed

+8
-41
lines changed

src/main/java/at/favre/lib/bytes/BytesTransformers.java

Lines changed: 8 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -303,65 +303,32 @@ public byte[] transform(byte[] currentArray, boolean inPlace) {
303303
}
304304

305305
private byte[] decompress(byte[] compressedContent) {
306-
ByteArrayOutputStream bos = new ByteArrayOutputStream();
307-
GZIPInputStream gzipInputStream = null;
308-
byte[] returnBuffer;
309-
try {
306+
ByteArrayOutputStream bos = new ByteArrayOutputStream(Math.max(32, compressedContent.length / 2));
307+
308+
try (GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedContent))) {
310309
int len;
311310
byte[] buffer = new byte[4 * 1024];
312-
gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(compressedContent));
313311

314312
while ((len = gzipInputStream.read(buffer)) > 0) {
315313
bos.write(buffer, 0, len);
316314
}
317315

318-
gzipInputStream.close();
319-
returnBuffer = bos.toByteArray();
320-
bos.close();
321-
return returnBuffer;
316+
return bos.toByteArray();
322317
} catch (Exception e) {
323318
throw new IllegalStateException("could not decompress gzip", e);
324-
} finally {
325-
try {
326-
bos.close();
327-
} catch (IOException ignore) {
328-
}
329-
330-
if (gzipInputStream != null) {
331-
try {
332-
gzipInputStream.close();
333-
} catch (IOException ignore) {
334-
}
335-
}
336319
}
337320
}
338321

339322
private byte[] compress(byte[] content) {
340323
ByteArrayOutputStream bos = new ByteArrayOutputStream(content.length);
341-
GZIPOutputStream gzipOutputStream = null;
342-
byte[] returnBuffer;
343-
try {
344-
gzipOutputStream = new GZIPOutputStream(bos);
324+
325+
try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bos)) {
345326
gzipOutputStream.write(content);
346-
gzipOutputStream.close();
347-
returnBuffer = bos.toByteArray();
348-
bos.close();
349-
return returnBuffer;
350327
} catch (Exception e) {
351328
throw new IllegalStateException("could not compress gzip", e);
352-
} finally {
353-
try {
354-
bos.close();
355-
} catch (IOException ignore) {
356-
}
357-
358-
if (gzipOutputStream != null) {
359-
try {
360-
gzipOutputStream.close();
361-
} catch (IOException ignore) {
362-
}
363-
}
364329
}
330+
331+
return bos.toByteArray();
365332
}
366333

367334
@Override

0 commit comments

Comments
 (0)