Zach Reizner | ff30b52 | 2015-10-28 19:08:45 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2015 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 <unistd.h> |
| 18 | |
| 19 | namespace android { |
| 20 | |
| 21 | class UniqueFd { |
| 22 | public: |
| 23 | UniqueFd() = default; |
| 24 | UniqueFd(int fd) : fd_(fd) { |
| 25 | } |
| 26 | UniqueFd(UniqueFd &&rhs) { |
| 27 | fd_ = rhs.fd_; |
| 28 | rhs.fd_ = -1; |
| 29 | } |
| 30 | |
| 31 | UniqueFd &operator=(UniqueFd &&rhs) { |
| 32 | Set(rhs.Release()); |
| 33 | return *this; |
| 34 | } |
| 35 | |
| 36 | ~UniqueFd() { |
| 37 | if (fd_ >= 0) |
| 38 | close(fd_); |
| 39 | } |
| 40 | |
| 41 | int Release() { |
| 42 | int old_fd = fd_; |
| 43 | fd_ = -1; |
| 44 | return old_fd; |
| 45 | } |
| 46 | |
| 47 | int Set(int fd) { |
| 48 | if (fd_ >= 0) |
| 49 | close(fd_); |
| 50 | fd_ = fd; |
| 51 | return fd_; |
| 52 | } |
| 53 | |
| 54 | void Close() { |
| 55 | if (fd_ >= 0) |
| 56 | close(fd_); |
| 57 | fd_ = -1; |
| 58 | } |
| 59 | |
| 60 | int get() const { |
| 61 | return fd_; |
| 62 | } |
| 63 | |
| 64 | private: |
| 65 | int fd_ = -1; |
| 66 | }; |
| 67 | |
| 68 | struct OutputFd { |
| 69 | OutputFd() = default; |
| 70 | OutputFd(int *fd) : fd_(fd) { |
| 71 | } |
| 72 | OutputFd(OutputFd &&rhs) { |
| 73 | fd_ = rhs.fd_; |
| 74 | rhs.fd_ = NULL; |
| 75 | } |
| 76 | |
| 77 | OutputFd &operator=(OutputFd &&rhs) { |
| 78 | fd_ = rhs.fd_; |
| 79 | rhs.fd_ = NULL; |
| 80 | return *this; |
| 81 | } |
| 82 | |
| 83 | int Set(int fd) { |
| 84 | if (*fd_ >= 0) |
| 85 | close(*fd_); |
| 86 | *fd_ = fd; |
| 87 | return fd; |
| 88 | } |
| 89 | |
| 90 | int get() { |
| 91 | return *fd_; |
| 92 | } |
| 93 | |
| 94 | private: |
| 95 | int *fd_ = NULL; |
| 96 | }; |
| 97 | } |