create changelog entry
[debian/openrocket] / core / src / net / sf / openrocket / util / LimitedInputStream.java
1 package net.sf.openrocket.util;
2
3 import java.io.FilterInputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6
7 /**
8  * A filtering InputStream that limits the number of bytes that can be
9  * read from a stream.   This can be used to enforce security, so that overlong
10  * input is ignored.
11  * 
12  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
13  */
14 public class LimitedInputStream extends FilterInputStream {
15
16         private int remaining;
17         
18         public LimitedInputStream(InputStream is, int limit) {
19                 super(is);
20                 this.remaining = limit;
21         }
22
23         
24         @Override
25         public int available() throws IOException {
26                 int available = super.available();
27                 return Math.min(available, remaining);
28         }
29
30
31         @Override
32         public int read(byte[] b, int off, int len) throws IOException {
33                 if (remaining <= 0)
34                         return -1;
35                 
36                 int result = super.read(b, off, Math.min(len, remaining));
37                 if (result >= 0)
38                         remaining -= result;
39                 return result;
40         }
41
42
43         @Override
44         public long skip(long n) throws IOException {
45                 if (n > remaining)
46                         n = remaining;
47                 long result = super.skip(n);
48                 remaining -= result;
49                 return result;
50         }
51
52
53         @Override
54         public int read() throws IOException {
55                 if (remaining <= 0)
56                         return -1;
57                 
58                 int result = super.read();
59                 if (result >= 0)
60                         remaining--;
61                 return result;
62         }
63
64         
65         
66         //  Disable mark support
67
68         @Override
69         public void mark(int readlimit) {
70
71         }
72
73         @Override
74         public boolean markSupported() {
75                 return false;
76         }
77
78         @Override
79         public synchronized void reset() throws IOException {
80                 throw new IOException("mark/reset not supported");
81         }
82         
83 }