Victor Hsieh | cb35a06 | 2020-08-13 16:11:13 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2020 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 "unique_file.h" |
| 18 | |
| 19 | #include <string> |
| 20 | |
| 21 | #include <unistd.h> |
| 22 | |
| 23 | #include <android-base/logging.h> |
| 24 | |
| 25 | namespace android { |
| 26 | namespace installd { |
| 27 | |
| 28 | UniqueFile::UniqueFile() : UniqueFile(-1, "") {} |
| 29 | |
| 30 | UniqueFile::UniqueFile(int value, std::string path) : UniqueFile(value, path, nullptr) {} |
| 31 | |
| 32 | UniqueFile::UniqueFile(int value, std::string path, CleanUpFunction cleanup) |
| 33 | : value_(value), path_(path), cleanup_(cleanup), do_cleanup_(true), auto_close_(true) {} |
| 34 | |
| 35 | UniqueFile::UniqueFile(UniqueFile&& other) { |
| 36 | *this = std::move(other); |
| 37 | } |
| 38 | |
| 39 | UniqueFile::~UniqueFile() { |
| 40 | reset(); |
| 41 | } |
| 42 | |
| 43 | UniqueFile& UniqueFile::operator=(UniqueFile&& other) { |
| 44 | value_ = other.value_; |
| 45 | path_ = other.path_; |
| 46 | cleanup_ = other.cleanup_; |
| 47 | do_cleanup_ = other.do_cleanup_; |
| 48 | auto_close_ = other.auto_close_; |
| 49 | other.release(); |
| 50 | return *this; |
| 51 | } |
| 52 | |
| 53 | void UniqueFile::reset() { |
| 54 | reset(-1, ""); |
| 55 | } |
| 56 | |
| 57 | void UniqueFile::reset(int new_value, std::string path, CleanUpFunction new_cleanup) { |
| 58 | if (auto_close_ && value_ >= 0) { |
| 59 | if (close(value_) < 0) { |
| 60 | PLOG(ERROR) << "Failed to close fd " << value_ << ", with path " << path; |
| 61 | } |
| 62 | } |
| 63 | if (do_cleanup_ && cleanup_ != nullptr) { |
| 64 | cleanup_(path_); |
| 65 | } |
| 66 | |
| 67 | value_ = new_value; |
| 68 | path_ = path; |
| 69 | cleanup_ = new_cleanup; |
| 70 | } |
| 71 | |
| 72 | void UniqueFile::release() { |
| 73 | value_ = -1; |
| 74 | path_ = ""; |
| 75 | do_cleanup_ = false; |
| 76 | cleanup_ = nullptr; |
| 77 | } |
| 78 | |
| 79 | } // namespace installd |
| 80 | } // namespace android |