1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.email;
18
19import java.io.IOException;
20import java.io.InputStream;
21
22/**
23 * A filtering InputStream that allows single byte "peeks" without consuming the byte. The
24 * client of this stream can call peek() to see the next available byte in the stream
25 * and a subsequent read will still return the peeked byte.
26 */
27public class PeekableInputStream extends InputStream {
28    private final InputStream mIn;
29    private boolean mPeeked;
30    private int mPeekedByte;
31
32    public PeekableInputStream(InputStream in) {
33        this.mIn = in;
34    }
35
36    @Override
37    public int read() throws IOException {
38        if (!mPeeked) {
39            return mIn.read();
40        } else {
41            mPeeked = false;
42            return mPeekedByte;
43        }
44    }
45
46    public int peek() throws IOException {
47        if (!mPeeked) {
48            mPeekedByte = read();
49            mPeeked = true;
50        }
51        return mPeekedByte;
52    }
53
54    @Override
55    public int read(byte[] b, int offset, int length) throws IOException {
56        if (!mPeeked) {
57            return mIn.read(b, offset, length);
58        } else {
59            b[0] = (byte)mPeekedByte;
60            mPeeked = false;
61            int r = mIn.read(b, offset + 1, length - 1);
62            if (r == -1) {
63                return 1;
64            } else {
65                return r + 1;
66            }
67        }
68    }
69
70    @Override
71    public int read(byte[] b) throws IOException {
72        return read(b, 0, b.length);
73    }
74
75    @Override
76    public String toString() {
77        return String.format("PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)",
78                mIn.toString(), mPeeked, mPeekedByte);
79    }
80}
81