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 #ifndef ANDROID_AUTO_FD_H_
18 #define ANDROID_AUTO_FD_H_
19 
20 #include <unistd.h>
21 
22 namespace android {
23 
24 class UniqueFd {
25  public:
26   UniqueFd() = default;
UniqueFd(int fd)27   UniqueFd(int fd) : fd_(fd) {
28   }
UniqueFd(UniqueFd && rhs)29   UniqueFd(UniqueFd &&rhs) {
30     fd_ = rhs.fd_;
31     rhs.fd_ = -1;
32   }
33 
34   UniqueFd &operator=(UniqueFd &&rhs) {
35     Set(rhs.Release());
36     return *this;
37   }
38 
~UniqueFd()39   ~UniqueFd() {
40     if (fd_ >= 0)
41       close(fd_);
42   }
43 
Release()44   int Release() {
45     int old_fd = fd_;
46     fd_ = -1;
47     return old_fd;
48   }
49 
Set(int fd)50   int Set(int fd) {
51     if (fd_ >= 0)
52       close(fd_);
53     fd_ = fd;
54     return fd_;
55   }
56 
Close()57   void Close() {
58     if (fd_ >= 0)
59       close(fd_);
60     fd_ = -1;
61   }
62 
get()63   int get() const {
64     return fd_;
65   }
66 
67  private:
68   int fd_ = -1;
69 };
70 
71 struct OutputFd {
72   OutputFd() = default;
OutputFdOutputFd73   OutputFd(int *fd) : fd_(fd) {
74   }
OutputFdOutputFd75   OutputFd(OutputFd &&rhs) {
76     fd_ = rhs.fd_;
77     rhs.fd_ = NULL;
78   }
79 
80   OutputFd &operator=(OutputFd &&rhs) {
81     fd_ = rhs.fd_;
82     rhs.fd_ = NULL;
83     return *this;
84   }
85 
SetOutputFd86   int Set(int fd) {
87     if (*fd_ >= 0)
88       close(*fd_);
89     *fd_ = fd;
90     return fd;
91   }
92 
getOutputFd93   int get() {
94     return *fd_;
95   }
96 
97   operator bool() const {
98     return fd_ != NULL;
99   }
100 
101  private:
102   int *fd_ = NULL;
103 };
104 }
105 
106 #endif
107