1 /*
2  * Copyright (C) 2020 The Android Open Source Project
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 
17 package com.android.server.integrity.model;
18 
19 import java.io.IOException;
20 import java.io.OutputStream;
21 
22 /**
23  * An output stream that tracks the total number written bytes since construction and allows
24  * querying this value any time during the execution.
25  *
26  * <p>This class is used for constructing the rule indexing.
27  */
28 public class ByteTrackedOutputStream extends OutputStream {
29 
30     private int mWrittenBytesCount;
31     private final OutputStream mOutputStream;
32 
ByteTrackedOutputStream(OutputStream outputStream)33     public ByteTrackedOutputStream(OutputStream outputStream) {
34         mWrittenBytesCount = 0;
35         mOutputStream = outputStream;
36     }
37 
38     @Override
write(int b)39     public void write(int b) throws IOException {
40         mWrittenBytesCount++;
41         mOutputStream.write(b);
42     }
43 
44     /**
45      * Writes the given bytes into the output stream provided in constructor and updates the total
46      * number of written bytes.
47      */
48     @Override
write(byte[] bytes)49     public void write(byte[] bytes) throws IOException {
50         write(bytes, 0, bytes.length);
51     }
52 
53     @Override
write(byte[] b, int off, int len)54     public void write(byte[] b, int off, int len) throws IOException {
55         mWrittenBytesCount += len;
56         mOutputStream.write(b, off, len);
57     }
58 
59     /** Returns the total number of bytes written into the output stream at the requested time. */
getWrittenBytesCount()60     public int getWrittenBytesCount() {
61         return mWrittenBytesCount;
62     }
63 }
64