From cb8be232a1bc81300ba0882b473e447698df4e18 Mon Sep 17 00:00:00 2001 From: Xaver Hugl Date: Fri, 15 Jul 2022 00:32:11 +0200 Subject: [PATCH] utils: introduce helper class for file descriptors --- src/utils/CMakeLists.txt | 1 + src/utils/filedescriptor.cpp | 61 ++++++++++++++++++++++++++++++++++++ src/utils/filedescriptor.h | 33 +++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 src/utils/filedescriptor.cpp create mode 100644 src/utils/filedescriptor.h diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt index 5cf290d66b..e84ea1c3b9 100644 --- a/src/utils/CMakeLists.txt +++ b/src/utils/CMakeLists.txt @@ -3,6 +3,7 @@ target_sources(kwin PRIVATE common.cpp edid.cpp egl_context_attribute_builder.cpp + filedescriptor.cpp realtime.cpp subsurfacemonitor.cpp udev.cpp diff --git a/src/utils/filedescriptor.cpp b/src/utils/filedescriptor.cpp new file mode 100644 index 0000000000..fbffecd132 --- /dev/null +++ b/src/utils/filedescriptor.cpp @@ -0,0 +1,61 @@ +/* + KWin - the KDE window manager + This file is part of the KDE project. + + SPDX-FileCopyrightText:: 2022 Xaver Hugl + + SPDX-License-Identifier: GPL-2.0-or-later +*/ +#include "filedescriptor.h" + +#include +#include + +namespace KWin +{ + +FileDescriptor::FileDescriptor(int fd) + : m_fd(fd) +{ +} + +FileDescriptor::FileDescriptor(FileDescriptor &&other) + : m_fd(std::exchange(other.m_fd, -1)) +{ +} + +FileDescriptor &FileDescriptor::operator=(FileDescriptor &&other) +{ + if (m_fd != -1) { + ::close(m_fd); + } + m_fd = std::exchange(other.m_fd, -1); + return *this; +} + +FileDescriptor::~FileDescriptor() +{ + if (m_fd != -1) { + ::close(m_fd); + } +} + +FileDescriptor::operator bool() const +{ + return m_fd != -1; +} + +int FileDescriptor::get() const +{ + return m_fd; +} + +FileDescriptor FileDescriptor::duplicate() const +{ + if (m_fd != -1) { + return FileDescriptor{dup(m_fd)}; + } else { + return {}; + } +} +} diff --git a/src/utils/filedescriptor.h b/src/utils/filedescriptor.h new file mode 100644 index 0000000000..0522e70087 --- /dev/null +++ b/src/utils/filedescriptor.h @@ -0,0 +1,33 @@ +/* + KWin - the KDE window manager + This file is part of the KDE project. + + SPDX-FileCopyrightText:: 2022 Xaver Hugl + + SPDX-License-Identifier: GPL-2.0-or-later +*/ +#pragma once + +#include + +namespace KWin +{ + +class KWIN_EXPORT FileDescriptor +{ +public: + FileDescriptor() = default; + explicit FileDescriptor(int fd); + FileDescriptor(FileDescriptor &&); + FileDescriptor &operator=(FileDescriptor &&); + ~FileDescriptor(); + + explicit operator bool() const; + int get() const; + FileDescriptor duplicate() const; + +private: + int m_fd = -1; +}; + +}