-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsafefd.h
94 lines (73 loc) · 1.69 KB
/
safefd.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#pragma once
#include <algorithm>
#include <cstring>
#include <cstddef>
#include <unistd.h>
#include <utility>
namespace shitty {
// Basically unique_ptr but for file descriptors
class SafeFD {
public:
explicit SafeFD(int fd = -1):
fd_(fd)
{}
SafeFD(const SafeFD&) = delete;
SafeFD(SafeFD&& other) /*noexcept(std::is_nothrow_swappable<int>::value)*/ {
::std::swap(fd_, other.fd_);
}
SafeFD& operator=(const SafeFD&) = delete;
SafeFD& operator=(SafeFD&& other) /*noexcept(std::is_nothrow_swappable<int>::value)*/ {
::std::swap(fd_, other.fd_);
return *this;
}
// Implicit conversion to int for convenience
operator int() const {
return fd_;
}
~SafeFD() {
try {
close();
} catch (...)
{}
}
int release() {
int fd = fd_;
fd_ = -1;
return fd;
}
void reset() {
close();
}
void swap(SafeFD& other) {
std::swap(fd_, other.fd_);
}
explicit operator bool() const {
return fd_ != -1;
}
int get() const {
return fd_;
}
int operator*() const {
return fd_;
}
void close() {
if (fd_ == -1)
return;
if (::close(fd_) == -1)
throw std::runtime_error(std::string("close: ") + strerror(errno));
fd_ = -1;
}
bool operator==(const SafeFD& rhs) const {
return fd_ == rhs.fd_;
}
friend struct std::hash<SafeFD>;
private:
int fd_ = -1;
};
} // namespace shitty
template <>
struct std::hash<shitty::SafeFD> {
size_t operator()(const shitty::SafeFD& fd) const {
return static_cast<size_t>(fd.fd_);
}
};