1
2
3
4
5
6
7
8
9
10
11
12 package org.eclipse.jgit.util.io;
13
14 import java.io.FilterInputStream;
15 import java.io.IOException;
16 import java.io.InputStream;
17
18 import org.eclipse.jgit.internal.JGitText;
19
20
21
22
23
24
25
26
27
28
29
30
31 public abstract class LimitedInputStream extends FilterInputStream {
32
33 private long left;
34
35 protected final long limit;
36 private long mark = -1;
37
38
39
40
41
42
43
44 protected LimitedInputStream(InputStream in, long limit) {
45 super(in);
46 left = limit;
47 this.limit = limit;
48 }
49
50
51 @Override
52 public int available() throws IOException {
53 return (int) Math.min(in.available(), left);
54 }
55
56
57
58 @Override
59 public synchronized void mark(int readLimit) {
60 in.mark(readLimit);
61 mark = left;
62 }
63
64
65 @Override
66 public int read() throws IOException {
67 if (left == 0) {
68 if (in.available() == 0) {
69 return -1;
70 }
71 limitExceeded();
72 }
73
74 int result = in.read();
75 if (result != -1) {
76 --left;
77 }
78 return result;
79 }
80
81
82 @Override
83 public int read(byte[] b, int off, int len) throws IOException {
84 if (left == 0) {
85 if (in.available() == 0) {
86 return -1;
87 }
88 limitExceeded();
89 }
90
91 len = (int) Math.min(len, left);
92 int result = in.read(b, off, len);
93 if (result != -1) {
94 left -= result;
95 }
96 return result;
97 }
98
99
100 @Override
101 public synchronized void reset() throws IOException {
102 if (!in.markSupported())
103 throw new IOException(JGitText.get().unsupportedMark);
104
105 if (mark == -1)
106 throw new IOException(JGitText.get().unsetMark);
107
108 in.reset();
109 left = mark;
110 }
111
112
113 @Override
114 public long skip(long n) throws IOException {
115 n = Math.min(n, left);
116 long skipped = in.skip(n);
117 left -= skipped;
118 return skipped;
119 }
120
121
122
123
124
125
126
127
128
129
130
131 protected abstract void limitExceeded() throws IOException;
132 }