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_INPUT_STREAM_H_ 18 #define TINK_UTIL_FILE_INPUT_STREAM_H_ 19 20 #include <cstdint> 21 #include <memory> 22 #include <vector> 23 24 #include "tink/input_stream.h" 25 #include "tink/util/status.h" 26 #include "tink/util/statusor.h" 27 28 namespace crypto { 29 namespace tink { 30 namespace util { 31 32 // An InputStream that reads from a file descriptor. 33 // 34 // NOTE: This class in not available when building on Windows. 35 class FileInputStream : public crypto::tink::InputStream { 36 public: 37 // Constructs an InputStream that will read from the file specified 38 // via `file_descriptor`, using a buffer of the specified size, if any 39 // (if no legal `buffer_size` is given, a reasonable default will be used). 40 // Takes the ownership of the file, and will close it upon destruction. 41 explicit FileInputStream(int file_descriptor, int buffer_size = -1); 42 43 ~FileInputStream() override; 44 45 crypto::tink::util::StatusOr<int> Next(const void** data) override; 46 47 void BackUp(int count) override; 48 49 int64_t Position() const override; 50 51 private: 52 // Status of the stream. 53 util::Status status_ = util::OkStatus(); 54 int fd_; 55 std::vector<uint8_t> buffer_; 56 57 // Current position in the stream (from the beginning). 58 int64_t position_ = 0; 59 // Counters that describe the state of the data in buffer_. 60 // # of bytes available in buffer_. 61 int count_in_buffer_ = 0; 62 // # of bytes available in buffer_ that were backed up. 63 int count_backedup_ = 0; 64 // offset at which the returned bytes start in buffer_. 65 int buffer_offset_ = 0; 66 }; 67 68 } // namespace util 69 } // namespace tink 70 } // namespace crypto 71 72 #endif // TINK_UTIL_FILE_INPUT_STREAM_H_ 73