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