]> git.saurik.com Git - apple/system_cmds.git/blob - CPPUtil/UtilFileDescriptor.hpp
be861b0a1c0c4affaef60469b597eedae1bfec60
[apple/system_cmds.git] / CPPUtil / UtilFileDescriptor.hpp
1 //
2 // UtilFileDescriptor.hpp
3 // CPPUtil
4 //
5 // Created by James McIlree on 4/16/13.
6 // Copyright (c) 2013 Apple. All rights reserved.
7 //
8
9 #ifndef CPPUtil_UtilFileDescriptor_hpp
10 #define CPPUtil_UtilFileDescriptor_hpp
11
12 class FileDescriptor {
13 protected:
14 int _fd;
15
16 // FD's aren't reference counted, we allow move semantics but
17 // not copy semantics. Disable the copy constructor and copy
18 // assignment.
19 FileDescriptor(const FileDescriptor& that) = delete;
20 FileDescriptor& operator=(const FileDescriptor& other) = delete;
21
22 public:
23
24 FileDescriptor() : _fd(-1) {}
25 FileDescriptor(int fd) : _fd(fd) {}
26
27 template <typename... Args>
28 FileDescriptor(Args&& ... args) :
29 _fd(open(static_cast<Args &&>(args)...))
30 {
31 }
32
33 FileDescriptor (FileDescriptor&& rhs) noexcept :
34 _fd(rhs._fd)
35 {
36 rhs._fd = -1;
37 }
38
39 ~FileDescriptor() { close(); }
40
41 FileDescriptor& operator=(int fd) { close(); _fd = fd; return *this; }
42 FileDescriptor& operator=(FileDescriptor&& rhs) { std::swap(_fd, rhs._fd); return *this; }
43
44 bool is_open() const { return _fd > -1 ? true : false; }
45 void close() { if (is_open()) { ::close(_fd); _fd = -1; } }
46
47 explicit operator bool() const { return is_open(); }
48 operator int() const { return _fd; }
49 };
50
51
52 #endif