2008-11-01 17:32:06 -04:00
|
|
|
|
2010-05-19 14:17:06 -04:00
|
|
|
package com.fsck.k9.mail.filter;
|
2008-11-01 17:32:06 -04:00
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.InputStream;
|
2014-03-03 10:40:23 -05:00
|
|
|
import java.util.Locale;
|
2008-11-01 17:32:06 -04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A filtering InputStream that stops allowing reads after the given length has been read. This
|
|
|
|
* is used to allow a client to read directly from an underlying protocol stream without reading
|
2009-11-24 19:40:29 -05:00
|
|
|
* past where the protocol handler intended the client to read.
|
2008-11-01 17:32:06 -04:00
|
|
|
*/
|
2011-02-06 17:09:48 -05:00
|
|
|
public class FixedLengthInputStream extends InputStream {
|
2011-11-27 19:21:50 -05:00
|
|
|
private final InputStream mIn;
|
|
|
|
private final int mLength;
|
|
|
|
private int mCount = 0;
|
2008-11-01 17:32:06 -04:00
|
|
|
|
2011-02-06 17:09:48 -05:00
|
|
|
public FixedLengthInputStream(InputStream in, int length) {
|
2008-11-01 17:32:06 -04:00
|
|
|
this.mIn = in;
|
|
|
|
this.mLength = length;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public int available() throws IOException {
|
2008-11-01 17:32:06 -04:00
|
|
|
return mLength - mCount;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public int read() throws IOException {
|
2011-11-27 19:21:50 -05:00
|
|
|
if (mCount >= mLength) {
|
2008-11-01 17:32:06 -04:00
|
|
|
return -1;
|
|
|
|
}
|
2011-11-27 19:21:50 -05:00
|
|
|
|
|
|
|
int d = mIn.read();
|
|
|
|
if (d != -1) {
|
|
|
|
mCount++;
|
|
|
|
}
|
|
|
|
return d;
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public int read(byte[] b, int offset, int length) throws IOException {
|
2011-11-27 19:21:50 -05:00
|
|
|
if (mCount >= mLength) {
|
2008-11-01 17:32:06 -04:00
|
|
|
return -1;
|
|
|
|
}
|
2011-11-27 19:21:50 -05:00
|
|
|
|
|
|
|
int d = mIn.read(b, offset, Math.min(mLength - mCount, length));
|
|
|
|
if (d != -1) {
|
|
|
|
mCount += d;
|
|
|
|
}
|
|
|
|
return d;
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public int read(byte[] b) throws IOException {
|
2008-11-01 17:32:06 -04:00
|
|
|
return read(b, 0, b.length);
|
|
|
|
}
|
|
|
|
|
2011-11-27 19:14:49 -05:00
|
|
|
@Override
|
|
|
|
public long skip(long n) throws IOException {
|
|
|
|
long d = mIn.skip(Math.min(n, available()));
|
|
|
|
if (d > 0) {
|
|
|
|
mCount += d;
|
|
|
|
}
|
|
|
|
return d;
|
|
|
|
}
|
|
|
|
|
2010-04-16 08:20:10 -04:00
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public String toString() {
|
2014-03-03 10:40:23 -05:00
|
|
|
return String.format(Locale.US, "FixedLengthInputStream(in=%s, length=%d)", mIn.toString(), mLength);
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
|
|
|
}
|