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_FILE_OUTPUT_STREAM_H_ 18 #define TINK_UTIL_FILE_OUTPUT_STREAM_H_ 19 20 #include <memory> 21 22 #include "tink/output_stream.h" 23 #include "tink/util/status.h" 24 #include "tink/util/statusor.h" 25 26 namespace crypto { 27 namespace tink { 28 namespace util { 29 30 // An OutputStream that writes to a file descriptor. 31 // 32 // NOTE: This class in not available when building on Windows. 33 class FileOutputStream : public crypto::tink::OutputStream { 34 public: 35 // Constructs an OutputStream that will write to the file specified 36 // via 'file_descriptor', using a buffer of the specified size, if any 37 // (if no legal 'buffer_size' is given, a reasonable default will be used). 38 // Takes the ownership of the file, and will close it upon destruction. 39 explicit FileOutputStream(int file_descriptor, int buffer_size = -1); 40 41 ~FileOutputStream() override; 42 43 crypto::tink::util::StatusOr<int> Next(void** data) override; 44 45 void BackUp(int count) override; 46 47 crypto::tink::util::Status Close() override; 48 49 int64_t Position() const override; 50 51 private: 52 util::Status status_; 53 int fd_; 54 std::unique_ptr<uint8_t[]> buffer_; 55 const int buffer_size_; 56 int64_t position_; // current position in the file (from the beginning) 57 58 // Counters that describe the state of the data in buffer_. 59 // count_in_buffer_ is always equal to (buffer_size_ - count_backedup_), 60 // except initially (before the first call to Next()). 61 // In other words, we have an invariant: 62 // (count_in_buffer_ == buffer_size_ - count_backedup_) || buffer_ == nullptr 63 int count_in_buffer_; // # bytes in buffer_ that will be eventually written 64 int count_backedup_; // # bytes in buffer_ that were backed up 65 int buffer_offset_; // offset where the returned *data starts in buffer_ 66 }; 67 68 } // namespace util 69 } // namespace tink 70 } // namespace crypto 71 72 #endif // TINK_UTIL_FILE_OUTPUT_STREAM_H_ 73