utils: introduce helper class for file descriptors

This commit is contained in:
Xaver Hugl 2022-07-15 00:32:11 +02:00
parent ca6f84dad6
commit cb8be232a1
3 changed files with 95 additions and 0 deletions

View file

@ -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

View file

@ -0,0 +1,61 @@
/*
KWin - the KDE window manager
This file is part of the KDE project.
SPDX-FileCopyrightText:: 2022 Xaver Hugl <xaver.hugl@gmail.com>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "filedescriptor.h"
#include <unistd.h>
#include <utility>
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 {};
}
}
}

View file

@ -0,0 +1,33 @@
/*
KWin - the KDE window manager
This file is part of the KDE project.
SPDX-FileCopyrightText:: 2022 Xaver Hugl <xaver.hugl@gmail.com>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#pragma once
#include <kwin_export.h>
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;
};
}