Skip to content
This repository was archived by the owner on May 4, 2023. It is now read-only.

Commit 6ecf659

Browse files
committed
Avoid out of memory errors when using buffers.
1 parent bc5bb2a commit 6ecf659

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

app/src/main/java/com/fox2code/mmm/utils/Files.java

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package com.fox2code.mmm.utils;
22

3+
import android.os.Build;
4+
5+
import androidx.annotation.NonNull;
6+
37
import com.topjohnwu.superuser.io.SuFile;
48
import com.topjohnwu.superuser.io.SuFileInputStream;
59
import com.topjohnwu.superuser.io.SuFileOutputStream;
@@ -18,6 +22,8 @@
1822
import java.util.zip.ZipOutputStream;
1923

2024
public class Files {
25+
private static final boolean is64bit = Build.SUPPORTED_64_BIT_ABIS.length > 0;
26+
2127
public static void write(File file, byte[] bytes) throws IOException {
2228
try (OutputStream outputStream = new FileOutputStream(file)) {
2329
outputStream.write(bytes);
@@ -63,8 +69,24 @@ public static void closeSilently(Closeable closeable) {
6369
} catch (IOException ignored) {}
6470
}
6571

72+
public static ByteArrayOutputStream makeBuffer(long capacity) {
73+
// Cap buffer to 1 Gib (or 512 Mib for 32bit) to avoid memory errors
74+
return Files.makeBuffer((int) Math.min(capacity, is64bit ? 0x40000000 : 0x20000000));
75+
}
76+
77+
public static ByteArrayOutputStream makeBuffer(int capacity) {
78+
return new ByteArrayOutputStream(Math.max(0x20, capacity)) {
79+
@NonNull
80+
@Override
81+
public byte[] toByteArray() {
82+
return this.buf.length == this.count ?
83+
this.buf : super.toByteArray();
84+
}
85+
};
86+
}
87+
6688
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
67-
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
89+
ByteArrayOutputStream buffer = Files.makeBuffer(inputStream.available());
6890
copy(inputStream, buffer);
6991
return buffer.toByteArray();
7092
}

app/src/main/java/com/fox2code/mmm/utils/Http.java

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,7 @@ public static byte[] doHttpGet(String url,ProgressListener progressListener) thr
225225
byte[] buff = new byte[1024 * 4];
226226
long downloaded = 0;
227227
long target = responseBody.contentLength();
228-
ByteArrayOutputStream byteArrayOutputStream =
229-
new ByteArrayOutputStream();
228+
ByteArrayOutputStream byteArrayOutputStream = Files.makeBuffer(target);
230229
int divider = 1; // Make everything go in an int
231230
while ((target / divider) > (Integer.MAX_VALUE / 2)) {
232231
divider *= 2;

0 commit comments

Comments
 (0)