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