Mercurial Hosting > luan
view src/goodjava/io/LimitedInputStream.java @ 1485:6a24c8b33d6b
minor
author | Franklin Schmidt <fschmidt@gmail.com> |
---|---|
date | Fri, 01 May 2020 11:23:29 -0600 |
parents | 1f41e5921090 |
children |
line wrap: on
line source
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; } }