Mercurial Hosting > luan
comparison src/goodjava/io/LimitedInputStream.java @ 1480:1f41e5921090
input buffering
| author | Franklin Schmidt <fschmidt@gmail.com> |
|---|---|
| date | Fri, 24 Apr 2020 14:32:20 -0600 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 1479:bd13aaeaf6d4 | 1480:1f41e5921090 |
|---|---|
| 1 package goodjava.io; | |
| 2 import java.io.InputStream; | |
| 3 import java.io.FilterInputStream; | |
| 4 import java.io.IOException; | |
| 5 | |
| 6 | |
| 7 public final class LimitedInputStream extends FilterInputStream { | |
| 8 private final long limit; | |
| 9 private long pos = 0; | |
| 10 | |
| 11 public LimitedInputStream(InputStream in, long limit) { | |
| 12 super(in); | |
| 13 this.limit = limit; | |
| 14 } | |
| 15 | |
| 16 public synchronized int read() throws IOException { | |
| 17 if( pos >= limit ) | |
| 18 return -1; | |
| 19 int n = super.read(); | |
| 20 if( n != -1 ) | |
| 21 pos++; | |
| 22 return n; | |
| 23 } | |
| 24 | |
| 25 public synchronized int read(byte[] b, int off, int len) throws IOException { | |
| 26 long avail = limit - pos; | |
| 27 if( avail <= 0 ) | |
| 28 return -1; | |
| 29 if( len > avail ) | |
| 30 len = (int)avail; | |
| 31 int n = super.read(b,off,len); | |
| 32 if( n > 0 ) | |
| 33 pos += n; | |
| 34 return n; | |
| 35 } | |
| 36 | |
| 37 public synchronized long skip(long n) throws IOException { | |
| 38 long avail = limit - pos; | |
| 39 if( avail <= 0 ) | |
| 40 return 0; | |
| 41 if( n > avail ) | |
| 42 n = (int)avail; | |
| 43 n = super.skip(n); | |
| 44 pos += n; | |
| 45 return n; | |
| 46 } | |
| 47 | |
| 48 public synchronized int available() throws IOException { | |
| 49 long avail = limit - pos; | |
| 50 if( avail <= 0 ) | |
| 51 return 0; | |
| 52 int n = super.available(); | |
| 53 if( n > avail ) | |
| 54 n = (int)avail; | |
| 55 return n; | |
| 56 } | |
| 57 | |
| 58 } |
