Mercurial Hosting > luan
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/goodjava/io/LimitedInputStream.java Fri Apr 24 14:32:20 2020 -0600 @@ -0,0 +1,58 @@ +package goodjava.io; +import java.io.InputStream; +import java.io.FilterInputStream; +import java.io.IOException; + + +public final class LimitedInputStream extends FilterInputStream { + private final long limit; + private long pos = 0; + + public LimitedInputStream(InputStream in, long limit) { + super(in); + this.limit = limit; + } + + public synchronized int read() throws IOException { + if( pos >= limit ) + return -1; + int n = super.read(); + if( n != -1 ) + pos++; + return n; + } + + public synchronized int read(byte[] b, int off, int len) throws IOException { + long avail = limit - pos; + if( avail <= 0 ) + return -1; + if( len > avail ) + len = (int)avail; + int n = super.read(b,off,len); + if( n > 0 ) + pos += n; + return n; + } + + public synchronized long skip(long n) throws IOException { + long avail = limit - pos; + if( avail <= 0 ) + return 0; + if( n > avail ) + n = (int)avail; + n = super.skip(n); + pos += n; + return n; + } + + public synchronized int available() throws IOException { + long avail = limit - pos; + if( avail <= 0 ) + return 0; + int n = super.available(); + if( n > avail ) + n = (int)avail; + return n; + } + +}