xref: /aosp_15_r20/external/tink/cc/util/ostream_output_stream.h (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2018 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // 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
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ///////////////////////////////////////////////////////////////////////////////
16 
17 #ifndef TINK_UTIL_OSTREAM_OUTPUT_STREAM_H_
18 #define TINK_UTIL_OSTREAM_OUTPUT_STREAM_H_
19 
20 #include <memory>
21 #include <ostream>
22 
23 #include "tink/output_stream.h"
24 #include "tink/util/status.h"
25 #include "tink/util/statusor.h"
26 
27 namespace crypto {
28 namespace tink {
29 namespace util {
30 
31 // An OutputStream that writes to an ostream.
32 class OstreamOutputStream : public crypto::tink::OutputStream {
33  public:
34   // Constructs an OutputStream that will write to the ostream specified
35   // via 'output', using a buffer of the specified size, if any
36   // (if no legal 'buffer_size' is given, a reasonable default will be used).
37   explicit OstreamOutputStream(std::unique_ptr<std::ostream> output,
38                                int buffer_size = -1);
39 
40   ~OstreamOutputStream() override;
41 
42   crypto::tink::util::StatusOr<int> Next(void** data) override;
43 
44   void BackUp(int count) override;
45 
46   crypto::tink::util::Status Close() override;
47 
48   int64_t Position() const override;
49 
50  private:
51   util::Status status_;
52   std::unique_ptr<std::ostream> output_;
53   std::unique_ptr<uint8_t[]> buffer_;
54   const int buffer_size_;
55   int64_t position_;     // current position in the ostream (from the beginning)
56 
57   // Counters that describe the state of the data in buffer_.
58   // count_in_buffer_ is always equal to (buffer_size_ - count_backedup_),
59   // except initially (before the first call to Next()).
60   // In other words, we have an invariant:
61   // (count_in_buffer_ == buffer_size_ - count_backedup_) || buffer_ == nullptr
62   int count_in_buffer_;  // # bytes in buffer_ that will be eventually written
63   int count_backedup_;   // # bytes in buffer_ that were backed up
64   int buffer_offset_;    // offset where the returned *data starts in buffer_
65 };
66 
67 }  // namespace util
68 }  // namespace tink
69 }  // namespace crypto
70 
71 #endif  // TINK_UTIL_OSTREAM_OUTPUT_STREAM_H_
72