2008-11-01 17:32:06 -04:00
|
|
|
|
2008-12-16 18:34:01 -05:00
|
|
|
package com.android.email;
|
2008-11-01 17:32:06 -04: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-24 19:40:29 -05:00
|
|
|
* and a subsequent read will still return the peeked byte.
|
2008-11-01 17:32:06 -04:00
|
|
|
*/
|
2009-11-24 19:40:29 -05:00
|
|
|
public class PeekableInputStream extends InputStream
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
private InputStream mIn;
|
|
|
|
private boolean mPeeked;
|
|
|
|
private int mPeekedByte;
|
|
|
|
|
2009-11-24 19:40:29 -05:00
|
|
|
public PeekableInputStream(InputStream in)
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
this.mIn = in;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2009-11-24 19:40:29 -05:00
|
|
|
public int read() throws IOException
|
|
|
|
{
|
|
|
|
if (!mPeeked)
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
return mIn.read();
|
2009-11-24 19:40:29 -05:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
mPeeked = false;
|
|
|
|
return mPeekedByte;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2009-11-24 19:40:29 -05:00
|
|
|
public int peek() throws IOException
|
|
|
|
{
|
|
|
|
if (!mPeeked)
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
mPeekedByte = read();
|
|
|
|
mPeeked = true;
|
|
|
|
}
|
|
|
|
return mPeekedByte;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2009-11-24 19:40:29 -05:00
|
|
|
public int read(byte[] b, int offset, int length) throws IOException
|
|
|
|
{
|
|
|
|
if (!mPeeked)
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
return mIn.read(b, offset, length);
|
2009-11-24 19:40:29 -05:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
b[0] = (byte)mPeekedByte;
|
|
|
|
mPeeked = false;
|
|
|
|
int r = mIn.read(b, offset + 1, length - 1);
|
2009-11-24 19:40:29 -05:00
|
|
|
if (r == -1)
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
return 1;
|
2009-11-24 19:40:29 -05:00
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
return r + 1;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2009-11-24 19:40:29 -05:00
|
|
|
public int read(byte[] b) throws IOException
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
return read(b, 0, b.length);
|
|
|
|
}
|
|
|
|
|
2009-11-24 19:40:29 -05:00
|
|
|
public String toString()
|
|
|
|
{
|
2008-11-01 17:32:06 -04:00
|
|
|
return String.format("PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)",
|
2009-11-24 19:40:29 -05:00
|
|
|
mIn.toString(), mPeeked, mPeekedByte);
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
|
|
|
}
|