1/*
2 * Copyright (C) 2007 The Guava Authors
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.google.common.io;
18
19import com.google.common.annotations.Beta;
20
21import java.io.FilterInputStream;
22import java.io.IOException;
23import java.io.InputStream;
24
25/**
26 * An {@link InputStream} that counts the number of bytes read.
27 *
28 * @author Chris Nokleberg
29 * @since 1.0
30 */
31@Beta
32public final class CountingInputStream extends FilterInputStream {
33
34  private long count;
35  private long mark = -1;
36
37  /**
38   * Wraps another input stream, counting the number of bytes read.
39   *
40   * @param in the input stream to be wrapped
41   */
42  public CountingInputStream(InputStream in) {
43    super(in);
44  }
45
46  /** Returns the number of bytes read. */
47  public long getCount() {
48    return count;
49  }
50
51  @Override public int read() throws IOException {
52    int result = in.read();
53    if (result != -1) {
54      count++;
55    }
56    return result;
57  }
58
59  @Override public int read(byte[] b, int off, int len) throws IOException {
60    int result = in.read(b, off, len);
61    if (result != -1) {
62      count += result;
63    }
64    return result;
65  }
66
67  @Override public long skip(long n) throws IOException {
68    long result = in.skip(n);
69    count += result;
70    return result;
71  }
72
73  @Override public synchronized void mark(int readlimit) {
74    in.mark(readlimit);
75    mark = count;
76    // it's okay to mark even if mark isn't supported, as reset won't work
77  }
78
79  @Override public synchronized void reset() throws IOException {
80    if (!in.markSupported()) {
81      throw new IOException("Mark not supported");
82    }
83    if (mark == -1) {
84      throw new IOException("Mark not set");
85    }
86
87    in.reset();
88    count = mark;
89  }
90}
91