Skip to content

Commit cb383cd

Browse files
committed
Optimize readFromStream method
1 parent 23e4303 commit cb383cd

File tree

1 file changed

+13
-23
lines changed

1 file changed

+13
-23
lines changed

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

Lines changed: 13 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,30 +21,18 @@
2121

2222
package at.favre.lib.bytes;
2323

24-
import java.io.ByteArrayOutputStream;
25-
import java.io.DataInput;
26-
import java.io.File;
27-
import java.io.IOException;
28-
import java.io.InputStream;
24+
import java.io.*;
2925
import java.nio.ByteBuffer;
3026
import java.nio.ByteOrder;
3127
import java.nio.file.Files;
32-
import java.util.ArrayList;
33-
import java.util.Arrays;
34-
import java.util.Collection;
35-
import java.util.HashMap;
36-
import java.util.Iterator;
37-
import java.util.List;
38-
import java.util.Map;
39-
import java.util.NoSuchElementException;
40-
import java.util.Objects;
41-
import java.util.Random;
42-
import java.util.UUID;
28+
import java.util.*;
4329

4430
/**
4531
* Common Util methods to convert or modify byte arrays
4632
*/
4733
final class Util {
34+
private static final int BUF_SIZE = 0x1000; // 4K
35+
4836
private Util() {
4937
}
5038

@@ -297,8 +285,6 @@ static void reverse(byte[] array, int fromIndex, int toIndex) {
297285
}
298286
}
299287

300-
private static final int BUF_SIZE = 0x1000; // 4K
301-
302288
/**
303289
* Read bytes, buffered, from given input stream. Pass -1 to read the whole stream or limit with length
304290
* parameter.
@@ -312,8 +298,12 @@ static byte[] readFromStream(InputStream inputStream, final int maxLengthToRead)
312298
int remaining = maxLengthToRead;
313299
try {
314300
ByteArrayOutputStream out = new ByteArrayOutputStream(readWholeStream ? 32 : maxLengthToRead);
301+
byte[] buf = new byte[0];
315302
while (readWholeStream || remaining > 0) {
316-
byte[] buf = new byte[Math.min(BUF_SIZE, readWholeStream ? BUF_SIZE : remaining)];
303+
int bufSize = Math.min(BUF_SIZE, readWholeStream ? BUF_SIZE : remaining);
304+
if (buf.length != bufSize) {
305+
buf = new byte[bufSize];
306+
}
317307
int r = inputStream.read(buf);
318308
if (r == -1) {
319309
break;
@@ -544,10 +534,6 @@ static final class Entropy<T> {
544534
private final Map<T, Integer> map = new HashMap<>();
545535
private int total = 0;
546536

547-
private double Log2(double n) {
548-
return Math.log(n) / Math.log(2);
549-
}
550-
551537
public Entropy(Iterable<T> elements) {
552538
for (T element : elements) {
553539
if (!map.containsKey(element)) {
@@ -558,6 +544,10 @@ public Entropy(Iterable<T> elements) {
558544
}
559545
}
560546

547+
private double Log2(double n) {
548+
return Math.log(n) / Math.log(2);
549+
}
550+
561551
public double entropy() {
562552
double entropy = 0;
563553
for (int count : map.values()) {

0 commit comments

Comments
 (0)