1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.util.internal;
17
18 import org.jetbrains.annotations.NotNull;
19
20 import java.io.FilterInputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23
24 public final class BoundedInputStream extends FilterInputStream {
25
26 private final int maxBytesRead;
27 private int numRead;
28
29 public BoundedInputStream(@NotNull InputStream in, int maxBytesRead) {
30 super(in);
31 this.maxBytesRead = ObjectUtil.checkPositive(maxBytesRead, "maxRead");
32 }
33
34 public BoundedInputStream(@NotNull InputStream in) {
35 this(in, 8 * 1024);
36 }
37
38 @Override
39 public int read() throws IOException {
40 checkMaxBytesRead();
41
42 int b = super.read();
43 if (b != -1) {
44 numRead++;
45 }
46 return b;
47 }
48
49 @Override
50 public int read(byte[] buf, int off, int len) throws IOException {
51 checkMaxBytesRead();
52
53
54 int num = Math.min(len, maxBytesRead - numRead + 1);
55
56 int b = super.read(buf, off, num);
57
58 if (b != -1) {
59 numRead += b;
60 }
61 return b;
62 }
63
64 private void checkMaxBytesRead() throws IOException {
65 if (numRead > maxBytesRead) {
66 throw new IOException("Maximum number of bytes read: " + numRead);
67 }
68 }
69 }