Changyeon Jo | b927b88 | 2019-11-21 10:16:33 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2016 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 | #pragma once |
| 18 | |
| 19 | namespace android { |
| 20 | namespace automotive { |
| 21 | namespace evs { |
| 22 | namespace V1_1 { |
| 23 | namespace implementation { |
| 24 | |
| 25 | // This is a simple C++ wrapper around a POSIX file descriptor. It is meant to |
| 26 | // enforce ownership just like unique_ptr<T> |
| 27 | // |
| 28 | // Instances of this type cannot be copied, but they can be moved. |
| 29 | class UniqueFd { |
| 30 | public: |
| 31 | UniqueFd(); |
| 32 | explicit UniqueFd(int fd); |
| 33 | ~UniqueFd(); |
| 34 | UniqueFd(UniqueFd&&); |
| 35 | UniqueFd& operator=(UniqueFd&&); |
| 36 | |
| 37 | // Destroy the current descriptor, and take ownership of a new one. |
| 38 | void Reset(int new_fd = -1); |
| 39 | |
| 40 | // Duplicate the current descriptor. |
| 41 | UniqueFd Dup() const; |
| 42 | |
| 43 | // Returns true if the descriptor is valid. False otherwise. |
| 44 | explicit operator bool() const; |
| 45 | |
| 46 | // Gets the descriptor |
| 47 | int Get() const; |
| 48 | |
| 49 | // Gets a unowned duplicate of the descriptor. The caller is responsible for |
| 50 | // closing it. |
| 51 | int GetUnowned() const; |
| 52 | |
| 53 | // Gets the descriptor and releases ownership. The caller is responsible for |
| 54 | // closing it. |
| 55 | int Release(); |
| 56 | |
| 57 | private: |
| 58 | UniqueFd(const UniqueFd&) = delete; |
| 59 | UniqueFd& operator=(const UniqueFd&) = delete; |
| 60 | |
| 61 | void InternalClose(); |
| 62 | int InternalDup() const; |
| 63 | |
| 64 | int fd_; |
| 65 | }; |
| 66 | |
| 67 | } // namespace implementation |
| 68 | } // namespace V1_1 |
| 69 | } // namespace evs |
| 70 | } // namespace automotive |
| 71 | } // namespace android |
| 72 | |