Debian Codegraph @

src/main/java/io/airlift/slice/CountingInputStream.java

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