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 com.google.common.annotations.J2ktIncompatible;
022import java.io.FilterInputStream;
023import java.io.IOException;
024import java.io.InputStream;
025
026/**
027 * An {@link InputStream} that counts the number of bytes read.
028 *
029 * @author Chris Nokleberg
030 * @since 1.0
031 */
032@Beta
033@J2ktIncompatible
034@GwtIncompatible
035@ElementTypesAreNonnullByDefault
036public final class CountingInputStream extends FilterInputStream {
037
038  private long count;
039  private long mark = -1;
040
041  /**
042   * Wraps another input stream, counting the number of bytes read.
043   *
044   * @param in the input stream to be wrapped
045   */
046  public CountingInputStream(InputStream in) {
047    super(checkNotNull(in));
048  }
049
050  /** Returns the number of bytes read. */
051  public long getCount() {
052    return count;
053  }
054
055  @Override
056  public int read() throws IOException {
057    int result = in.read();
058    if (result != -1) {
059      count++;
060    }
061    return result;
062  }
063
064  @Override
065  public int read(byte[] b, int off, int len) throws IOException {
066    int result = in.read(b, off, len);
067    if (result != -1) {
068      count += result;
069    }
070    return result;
071  }
072
073  @Override
074  public long skip(long n) throws IOException {
075    long result = in.skip(n);
076    count += result;
077    return result;
078  }
079
080  @Override
081  public synchronized void mark(int readlimit) {
082    in.mark(readlimit);
083    mark = count;
084    // it's okay to mark even if mark isn't supported, as reset won't work
085  }
086
087  @Override
088  public synchronized void reset() throws IOException {
089    if (!in.markSupported()) {
090      throw new IOException("Mark not supported");
091    }
092    if (mark == -1) {
093      throw new IOException("Mark not set");
094    }
095
096    in.reset();
097    count = mark;
098  }
099}