summaryrefslogtreecommitdiff
path: root/src/FileDescriptor.cpp
blob: 8592f4205a1fd6cf4a7673bb9760ae9228d06f24 (plain)
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
#include <cstdlib>
#include <hyprutils/os/FileDescriptor.hpp>
#include <fcntl.h>
#include <sys/poll.h>
#include <unistd.h>
#include <utility>

using namespace Hyprutils::OS;

CFileDescriptor::CFileDescriptor(int const fd) : m_fd(fd) {}

CFileDescriptor::CFileDescriptor(CFileDescriptor&& other) : m_fd(std::exchange(other.m_fd, -1)) {}

CFileDescriptor& CFileDescriptor::operator=(CFileDescriptor&& other) {
    if (this == &other) // Shit will go haywire if there is duplicate ownership
        abort();

    reset();
    m_fd = std::exchange(other.m_fd, -1);
    return *this;
}

CFileDescriptor::~CFileDescriptor() {
    reset();
}

bool CFileDescriptor::isValid() const {
    return m_fd != -1;
}

int CFileDescriptor::get() const {
    return m_fd;
}

int CFileDescriptor::getFlags() const {
    return fcntl(m_fd, F_GETFD);
}

bool CFileDescriptor::setFlags(int flags) {
    if (fcntl(m_fd, F_SETFD, flags) == -1)
        return false;

    return true;
}

int CFileDescriptor::take() {
    return std::exchange(m_fd, -1);
}

void CFileDescriptor::reset() {
    if (m_fd != -1) {
        close(m_fd);
        m_fd = -1;
    }
}

CFileDescriptor CFileDescriptor::duplicate(int flags) const {
    if (m_fd == -1)
        return {};

    return CFileDescriptor{fcntl(m_fd, flags, 0)};
}

bool CFileDescriptor::isClosed() const {
    return isClosed(m_fd);
}

bool CFileDescriptor::isReadable() const {
    return isReadable(m_fd);
}

bool CFileDescriptor::isClosed(int fd) {
    pollfd pfd = {
        .fd      = fd,
        .events  = POLLIN,
        .revents = 0,
    };

    if (poll(&pfd, 1, 0) < 0)
        return true;

    return pfd.revents & (POLLHUP | POLLERR);
}

bool CFileDescriptor::isReadable(int fd) {
    pollfd pfd = {.fd = fd, .events = POLLIN, .revents = 0};

    return poll(&pfd, 1, 0) > 0 && (pfd.revents & POLLIN);
}