001/*
002 * Copyright (C) 2007 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.google.common.io;
018
019import com.google.common.annotations.Beta;
020
021import java.io.FilterInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024
025import javax.annotation.Nullable;
026
027/**
028 * An {@link InputStream} that counts the number of bytes read.
029 *
030 * @author Chris Nokleberg
031 * @since 1.0
032 */
033@Beta
034public final class CountingInputStream extends FilterInputStream {
035
036  private long count;
037  private long mark = -1;
038
039  /**
040   * Wraps another input stream, counting the number of bytes read.
041   *
042   * @param in the input stream to be wrapped
043   */
044  public CountingInputStream(@Nullable InputStream in) {
045    super(in);
046  }
047
048  /** Returns the number of bytes read. */
049  public long getCount() {
050    return count;
051  }
052
053  @Override public int read() throws IOException {
054    int result = in.read();
055    if (result != -1) {
056      count++;
057    }
058    return result;
059  }
060
061  @Override public int read(byte[] b, int off, int len) throws IOException {
062    int result = in.read(b, off, len);
063    if (result != -1) {
064      count += result;
065    }
066    return result;
067  }
068
069  @Override public long skip(long n) throws IOException {
070    long result = in.skip(n);
071    count += result;
072    return result;
073  }
074
075  @Override public synchronized void mark(int readlimit) {
076    in.mark(readlimit);
077    mark = count;
078    // it's okay to mark even if mark isn't supported, as reset won't work
079  }
080
081  @Override public synchronized void reset() throws IOException {
082    if (!in.markSupported()) {
083      throw new IOException("Mark not supported");
084    }
085    if (mark == -1) {
086      throw new IOException("Mark not set");
087    }
088
089    in.reset();
090    count = mark;
091  }
092}