2008-11-01 21:32:06 +00:00
|
|
|
|
2009-12-15 02:50:53 +00:00
|
|
|
package com.fsck.k9;
|
2008-11-01 21:32:06 +00:00
|
|
|
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.InputStream;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A filtering InputStream that allows single byte "peeks" without consuming the byte. The
|
|
|
|
* client of this stream can call peek() to see the next available byte in the stream
|
2009-11-25 00:40:29 +00:00
|
|
|
* and a subsequent read will still return the peeked byte.
|
2008-11-01 21:32:06 +00:00
|
|
|
*/
|
2009-11-25 00:40:29 +00:00
|
|
|
public class PeekableInputStream extends InputStream
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
private InputStream mIn;
|
|
|
|
private boolean mPeeked;
|
|
|
|
private int mPeekedByte;
|
|
|
|
|
2009-11-25 00:40:29 +00:00
|
|
|
public PeekableInputStream(InputStream in)
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
this.mIn = in;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2009-11-25 00:40:29 +00:00
|
|
|
public int read() throws IOException
|
|
|
|
{
|
|
|
|
if (!mPeeked)
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
return mIn.read();
|
2009-11-25 00:40:29 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
mPeeked = false;
|
|
|
|
return mPeekedByte;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-11-25 00:40:29 +00:00
|
|
|
public int peek() throws IOException
|
|
|
|
{
|
|
|
|
if (!mPeeked)
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
mPeekedByte = read();
|
|
|
|
mPeeked = true;
|
|
|
|
}
|
|
|
|
return mPeekedByte;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2009-11-25 00:40:29 +00:00
|
|
|
public int read(byte[] b, int offset, int length) throws IOException
|
|
|
|
{
|
|
|
|
if (!mPeeked)
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
return mIn.read(b, offset, length);
|
2009-11-25 00:40:29 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
b[0] = (byte)mPeekedByte;
|
|
|
|
mPeeked = false;
|
|
|
|
int r = mIn.read(b, offset + 1, length - 1);
|
2009-11-25 00:40:29 +00:00
|
|
|
if (r == -1)
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
return 1;
|
2009-11-25 00:40:29 +00:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
return r + 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2009-11-25 00:40:29 +00:00
|
|
|
public int read(byte[] b) throws IOException
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
return read(b, 0, b.length);
|
|
|
|
}
|
|
|
|
|
2010-04-16 12:20:10 +00:00
|
|
|
@Override
|
2009-11-25 00:40:29 +00:00
|
|
|
public String toString()
|
|
|
|
{
|
2008-11-01 21:32:06 +00:00
|
|
|
return String.format("PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)",
|
2009-11-25 00:40:29 +00:00
|
|
|
mIn.toString(), mPeeked, mPeekedByte);
|
2008-11-01 21:32:06 +00:00
|
|
|
}
|
|
|
|
}
|