blob: b48ce5e0426d8b46ab28b7fd1cdc9f255c482fca [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.io;
2
3import java.io.*;
4
5public class LimitedInputStream extends InputStream {
6
7 final InputStream in;
8 final int size;
9 int left;
10
11 public LimitedInputStream(InputStream in, int size) {
12 this.in = in;
13 this.left = size;
14 this.size = size;
15 }
16
Stuart McCulloch2286f232012-06-15 13:27:53 +000017 @Override
18 public int read() throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000019 if (left <= 0) {
20 eof();
21 return -1;
22 }
23
24 left--;
25 return in.read();
26 }
27
Stuart McCulloch2286f232012-06-15 13:27:53 +000028 @Override
29 public int available() throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000030 return Math.min(left, in.available());
31 }
32
Stuart McCulloch2286f232012-06-15 13:27:53 +000033 @Override
34 public void close() throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000035 eof();
36 in.close();
37 }
38
Stuart McCulloch2286f232012-06-15 13:27:53 +000039 protected void eof() {}
Stuart McCullochbb014372012-06-07 21:57:32 +000040
Stuart McCulloch2286f232012-06-15 13:27:53 +000041 @Override
42 public synchronized void mark(int readlimit) {
Stuart McCullochbb014372012-06-07 21:57:32 +000043 throw new UnsupportedOperationException();
44 }
45
Stuart McCulloch2286f232012-06-15 13:27:53 +000046 @Override
47 public boolean markSupported() {
Stuart McCullochbb014372012-06-07 21:57:32 +000048 return false;
49 }
50
Stuart McCulloch2286f232012-06-15 13:27:53 +000051 @Override
52 public int read(byte[] b, int off, int len) throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000053 int min = Math.min(len, left);
54 if (min == 0)
55 return 0;
56
57 int read = in.read(b, off, min);
58 if (read > 0)
59 left -= read;
60 return read;
61 }
62
Stuart McCulloch2286f232012-06-15 13:27:53 +000063 @Override
64 public int read(byte[] b) throws IOException {
65 return read(b, 0, b.length);
Stuart McCullochbb014372012-06-07 21:57:32 +000066 }
67
Stuart McCulloch2286f232012-06-15 13:27:53 +000068 @Override
69 public synchronized void reset() throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000070 throw new UnsupportedOperationException();
71 }
72
Stuart McCulloch2286f232012-06-15 13:27:53 +000073 @Override
74 public long skip(long n) throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000075 long count = 0;
76 byte buffer[] = new byte[1024];
Stuart McCulloch2286f232012-06-15 13:27:53 +000077 while (n > 0 && read() >= 0) {
Stuart McCullochbb014372012-06-07 21:57:32 +000078 int size = read(buffer);
Stuart McCulloch2286f232012-06-15 13:27:53 +000079 if (size <= 0)
Stuart McCullochbb014372012-06-07 21:57:32 +000080 return count;
Stuart McCulloch2286f232012-06-15 13:27:53 +000081 count += size;
82 n -= size;
Stuart McCullochbb014372012-06-07 21:57:32 +000083 }
84 return count;
85 }
86}