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 #include "io/FileInputStream.h" 18 19 #include <errno.h> // for errno 20 #include <fcntl.h> // for O_RDONLY 21 #include <unistd.h> // for read 22 23 #include "android-base/errors.h" 24 #include "android-base/file.h" // for O_BINARY 25 #include "android-base/macros.h" 26 #include "android-base/utf8.h" 27 28 using ::android::base::SystemErrorCodeToString; 29 30 namespace aapt { 31 namespace io { 32 33 FileInputStream::FileInputStream(const std::string& path, size_t buffer_capacity) 34 : FileInputStream(::android::base::utf8::open(path.c_str(), O_RDONLY | O_BINARY), 35 buffer_capacity) { 36 } 37 38 FileInputStream::FileInputStream(int fd, size_t buffer_capacity) 39 : fd_(fd), 40 buffer_capacity_(buffer_capacity), 41 buffer_offset_(0u), 42 buffer_size_(0u), 43 total_byte_count_(0u) { 44 if (fd_ == -1) { 45 error_ = SystemErrorCodeToString(errno); 46 } else { 47 buffer_.reset(new uint8_t[buffer_capacity_]); 48 } 49 } 50 51 bool FileInputStream::Next(const void** data, size_t* size) { 52 if (HadError()) { 53 return false; 54 } 55 56 // Deal with any remaining bytes after BackUp was called. 57 if (buffer_offset_ != buffer_size_) { 58 *data = buffer_.get() + buffer_offset_; 59 *size = buffer_size_ - buffer_offset_; 60 total_byte_count_ += buffer_size_ - buffer_offset_; 61 buffer_offset_ = buffer_size_; 62 return true; 63 } 64 65 ssize_t n = TEMP_FAILURE_RETRY(read(fd_, buffer_.get(), buffer_capacity_)); 66 if (n < 0) { 67 error_ = SystemErrorCodeToString(errno); 68 fd_.reset(); 69 return false; 70 } 71 72 buffer_size_ = static_cast<size_t>(n); 73 buffer_offset_ = buffer_size_; 74 total_byte_count_ += buffer_size_; 75 76 *data = buffer_.get(); 77 *size = buffer_size_; 78 return buffer_size_ != 0u; 79 } 80 81 void FileInputStream::BackUp(size_t count) { 82 if (count > buffer_offset_) { 83 count = buffer_offset_; 84 } 85 buffer_offset_ -= count; 86 total_byte_count_ -= count; 87 } 88 89 size_t FileInputStream::ByteCount() const { 90 return total_byte_count_; 91 } 92 93 bool FileInputStream::HadError() const { 94 return !error_.empty(); 95 } 96 97 std::string FileInputStream::GetError() const { 98 return error_; 99 } 100 101 } // namespace io 102 } // namespace aapt 103