]> git.saurik.com Git - apple/system_cmds.git/blame - CPPUtil/UtilFileDescriptor.hpp
system_cmds-671.10.3.tar.gz
[apple/system_cmds.git] / CPPUtil / UtilFileDescriptor.hpp
CommitLineData
bd6521f0
A
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
12class 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