blob: 9af6c220ab097f1ceb393a416ee67a2c3ce7a141 [file] [log] [blame]
Zach Reiznerff30b522015-10-28 19:08:45 -07001/*
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
Sean Paul538a3752016-03-24 14:50:53 -040017#ifndef ANDROID_AUTO_FD_H_
18#define ANDROID_AUTO_FD_H_
19
Zach Reiznerff30b522015-10-28 19:08:45 -070020#include <unistd.h>
21
22namespace android {
23
24class UniqueFd {
25 public:
26 UniqueFd() = default;
27 UniqueFd(int fd) : fd_(fd) {
28 }
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
39 ~UniqueFd() {
40 if (fd_ >= 0)
41 close(fd_);
42 }
43
44 int Release() {
45 int old_fd = fd_;
46 fd_ = -1;
47 return old_fd;
48 }
49
50 int Set(int fd) {
51 if (fd_ >= 0)
52 close(fd_);
53 fd_ = fd;
54 return fd_;
55 }
56
57 void Close() {
58 if (fd_ >= 0)
59 close(fd_);
60 fd_ = -1;
61 }
62
63 int get() const {
64 return fd_;
65 }
66
67 private:
68 int fd_ = -1;
69};
70
71struct OutputFd {
72 OutputFd() = default;
73 OutputFd(int *fd) : fd_(fd) {
74 }
75 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
86 int Set(int fd) {
87 if (*fd_ >= 0)
88 close(*fd_);
89 *fd_ = fd;
90 return fd;
91 }
92
93 int get() {
94 return *fd_;
95 }
96
Zach Reiznercb1cfc82015-11-13 16:11:37 -080097 operator bool() const {
98 return fd_ != NULL;
99 }
100
Zach Reiznerff30b522015-10-28 19:08:45 -0700101 private:
102 int *fd_ = NULL;
103};
Sean Paulf72cccd2018-08-27 13:59:08 -0400104} // namespace android
Sean Paul538a3752016-03-24 14:50:53 -0400105
106#endif