1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.marshalling;
17
18 import org.jboss.marshalling.ByteInput;
19
20 import java.io.IOException;
21
22
23
24
25
26 class LimitingByteInput implements ByteInput {
27
28
29 private static final TooBigObjectException EXCEPTION = new TooBigObjectException();
30
31 private final ByteInput input;
32 private final long limit;
33 private long read;
34
35 LimitingByteInput(ByteInput input, long limit) {
36 if (limit <= 0) {
37 throw new IllegalArgumentException("The limit MUST be > 0");
38 }
39 this.input = input;
40 this.limit = limit;
41 }
42
43 @Override
44 public void close() throws IOException {
45
46 }
47
48 @Override
49 public int available() throws IOException {
50 return readable(input.available());
51 }
52
53 @Override
54 public int read() throws IOException {
55 int readable = readable(1);
56 if (readable > 0) {
57 int b = input.read();
58 read++;
59 return b;
60 } else {
61 throw EXCEPTION;
62 }
63 }
64
65 @Override
66 public int read(byte[] array) throws IOException {
67 return read(array, 0, array.length);
68 }
69
70 @Override
71 public int read(byte[] array, int offset, int length) throws IOException {
72 int readable = readable(length);
73 if (readable > 0) {
74 int i = input.read(array, offset, readable);
75 read += i;
76 return i;
77 } else {
78 throw EXCEPTION;
79 }
80 }
81
82 @Override
83 public long skip(long bytes) throws IOException {
84 int readable = readable((int) bytes);
85 if (readable > 0) {
86 long i = input.skip(readable);
87 read += i;
88 return i;
89 } else {
90 throw EXCEPTION;
91 }
92 }
93
94 private int readable(int length) {
95 return (int) Math.min(length, limit - read);
96 }
97
98
99
100
101
102 static final class TooBigObjectException extends IOException {
103 private static final long serialVersionUID = 1L;
104 }
105 }