blob: 98a7c7b67125c42efbbd1ab4fd2c3e3f5fc8f2f5 [file] [log] [blame]
Tao Baoc7547922015-08-06 18:35:05 -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
17#ifndef UNIQUE_FD_H
18#define UNIQUE_FD_H
19
20#include <stdio.h>
21
22#include <memory>
23
24class unique_fd {
25 public:
26 unique_fd(int fd) : fd_(fd) { }
27
28 unique_fd(unique_fd&& uf) {
29 fd_ = uf.fd_;
30 uf.fd_ = -1;
31 }
32
33 ~unique_fd() {
34 if (fd_ != -1) {
35 close(fd_);
36 }
37 }
38
39 int get() {
40 return fd_;
41 }
42
43 // Movable.
44 unique_fd& operator=(unique_fd&& uf) {
45 fd_ = uf.fd_;
46 uf.fd_ = -1;
47 return *this;
48 }
49
50 explicit operator bool() const {
51 return fd_ != -1;
52 }
53
54 private:
55 int fd_;
56
57 // Non-copyable.
58 unique_fd(const unique_fd&) = delete;
59 unique_fd& operator=(const unique_fd&) = delete;
60};
61
62// Custom deleter for unique_file to avoid fclose(NULL).
63struct safe_fclose {
64 void operator()(FILE *fp) const {
65 if (fp) {
66 fclose(fp);
67 };
68 }
69};
70
71using unique_file = std::unique_ptr<FILE, safe_fclose>;
72
73#endif // UNIQUE_FD_H