Coverage Summary for Class: CountingInputStream (com.google.common.io)

Class Class, % Method, % Line, %
CountingInputStream 0% (0/1) 0% (0/7) 0% (0/22)


1 /* 2  * Copyright (C) 2007 The Guava Authors 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5  * in compliance with the License. You may obtain a copy of the License at 6  * 7  * http://www.apache.org/licenses/LICENSE-2.0 8  * 9  * Unless required by applicable law or agreed to in writing, software distributed under the License 10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11  * or implied. See the License for the specific language governing permissions and limitations under 12  * the License. 13  */ 14  15 package com.google.common.io; 16  17 import static com.google.common.base.Preconditions.checkNotNull; 18  19 import com.google.common.annotations.Beta; 20 import com.google.common.annotations.GwtIncompatible; 21 import java.io.FilterInputStream; 22 import java.io.IOException; 23 import 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 32 @GwtIncompatible 33 @ElementTypesAreNonnullByDefault 34 public final class CountingInputStream extends FilterInputStream { 35  36  private long count; 37  private long mark = -1; 38  39  /** 40  * Wraps another input stream, counting the number of bytes read. 41  * 42  * @param in the input stream to be wrapped 43  */ 44  public CountingInputStream(InputStream in) { 45  super(checkNotNull(in)); 46  } 47  48  /** Returns the number of bytes read. */ 49  public long getCount() { 50  return count; 51  } 52  53  @Override 54  public int read() throws IOException { 55  int result = in.read(); 56  if (result != -1) { 57  count++; 58  } 59  return result; 60  } 61  62  @Override 63  public int read(byte[] b, int off, int len) throws IOException { 64  int result = in.read(b, off, len); 65  if (result != -1) { 66  count += result; 67  } 68  return result; 69  } 70  71  @Override 72  public long skip(long n) throws IOException { 73  long result = in.skip(n); 74  count += result; 75  return result; 76  } 77  78  @Override 79  public synchronized void mark(int readlimit) { 80  in.mark(readlimit); 81  mark = count; 82  // it's okay to mark even if mark isn't supported, as reset won't work 83  } 84  85  @Override 86  public synchronized void reset() throws IOException { 87  if (!in.markSupported()) { 88  throw new IOException("Mark not supported"); 89  } 90  if (mark == -1) { 91  throw new IOException("Mark not set"); 92  } 93  94  in.reset(); 95  count = mark; 96  } 97 }