1 /* 2 * Copyright (C) 2017 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 #ifndef AAPT_IO_FILESTREAM_H 18 #define AAPT_IO_FILESTREAM_H 19 20 #include "io/Io.h" 21 22 #include <memory> 23 #include <string> 24 25 #include "android-base/macros.h" 26 #include "android-base/unique_fd.h" 27 28 namespace aapt { 29 namespace io { 30 31 constexpr size_t kDefaultBufferCapacity = 4096u; 32 33 class FileInputStream : public InputStream { 34 public: 35 explicit FileInputStream(const std::string& path, 36 size_t buffer_capacity = kDefaultBufferCapacity); 37 38 // Take ownership of `fd`. 39 explicit FileInputStream(int fd, size_t buffer_capacity = kDefaultBufferCapacity); 40 41 bool Next(const void** data, size_t* size) override; 42 43 void BackUp(size_t count) override; 44 45 size_t ByteCount() const override; 46 47 bool HadError() const override; 48 49 std::string GetError() const override; 50 51 private: 52 DISALLOW_COPY_AND_ASSIGN(FileInputStream); 53 54 android::base::unique_fd fd_; 55 std::string error_; 56 std::unique_ptr<uint8_t[]> buffer_; 57 size_t buffer_capacity_ = 0u; 58 size_t buffer_offset_ = 0u; 59 size_t buffer_size_ = 0u; 60 size_t total_byte_count_ = 0u; 61 }; 62 63 class FileOutputStream : public OutputStream { 64 public: 65 explicit FileOutputStream(const std::string& path, 66 size_t buffer_capacity = kDefaultBufferCapacity); 67 68 // Does not take ownership of `fd`. 69 explicit FileOutputStream(int fd, size_t buffer_capacity = kDefaultBufferCapacity); 70 71 // Takes ownership of `fd`. 72 explicit FileOutputStream(android::base::unique_fd fd, 73 size_t buffer_capacity = kDefaultBufferCapacity); 74 75 ~FileOutputStream(); 76 77 bool Next(void** data, size_t* size) override; 78 79 // Immediately flushes out the contents of the buffer to disk. 80 bool Flush(); 81 82 void BackUp(size_t count) override; 83 84 size_t ByteCount() const override; 85 86 bool HadError() const override; 87 88 std::string GetError() const override; 89 90 private: 91 DISALLOW_COPY_AND_ASSIGN(FileOutputStream); 92 93 bool FlushImpl(); 94 95 android::base::unique_fd owned_fd_; 96 int fd_; 97 std::string error_; 98 std::unique_ptr<uint8_t[]> buffer_; 99 size_t buffer_capacity_ = 0u; 100 size_t buffer_offset_ = 0u; 101 size_t total_byte_count_ = 0u; 102 }; 103 104 } // namespace io 105 } // namespace aapt 106 107 #endif // AAPT_IO_FILESTREAM_H 108