dfx 0.1.0
Linux-based dynamic dataflow executor
Loading...
Searching...
No Matches
OwnedFd.hpp
1// SPDX-FileCopyrightText: 2025 Vincent Leroy
2// SPDX-License-Identifier: MIT
3//
4// This file is part of dfx.
5//
6// Licensed under the MIT License. See the LICENSE file in the project root
7// for full license information.
8
9#pragma once
10
11// Standard includes
12#include <format>
13
14// Project includes
15#include "BorrowedFd.hpp"
17
18namespace dfx::FdWatch
19{
36{
37public:
39 OwnedFd() noexcept;
40
44 explicit OwnedFd(int fd) noexcept;
45
48 OwnedFd(OwnedFd && other) noexcept;
49
50 DISABLE_COPY(OwnedFd);
51
54
58 OwnedFd & operator=(OwnedFd && other) noexcept;
59
60 // Comparing 2 OwnedFd doesn't make sense since a OwnedFd owns its fd int
61 // so if 2 are equals it means that there is a bug somewhere
62 bool operator==(OwnedFd const &) const noexcept = delete;
63 bool operator!=(OwnedFd const &) const noexcept = delete;
64
65 bool operator==(int fd) const noexcept { return _fd == fd; }
66 bool operator==(BorrowedFd const & fd) const noexcept { return _fd == fd.get(); }
67
68 void swap(OwnedFd & other) noexcept;
69
71 bool isValid() const noexcept { return _fd != -1; }
72
75 int get() const noexcept { return _fd; }
76
79 void close() noexcept;
80
84 int release() noexcept;
85
89 void reset(int newFd = -1) noexcept;
90
95 [[nodiscard]] BorrowedFd borrow() const noexcept { return BorrowedFd(*this); }
96
97private:
98 int _fd = -1;
99};
100
102[[nodiscard]] inline OwnedFd makeOwnedFd(int fd) noexcept { return OwnedFd(fd); }
103inline void swap(OwnedFd & fd1, OwnedFd & fd2) noexcept { fd1.swap(fd2); }
104} // !namespace dfx::FdWatch
105
106template<>
107struct std::formatter<dfx::FdWatch::OwnedFd> : public formatter<int>
108{
109 auto format(dfx::FdWatch::OwnedFd const & e, format_context & ctx) const
110 { return formatter<int>::format(e.get(), ctx); }
111};
Convenience macros to explicitly control copy and move semantics.
Non-owning wrapper around a file descriptor.
Definition BorrowedFd.hpp:37
Owning RAII wrapper around a file descriptor.
Definition OwnedFd.hpp:36
BorrowedFd borrow() const noexcept
Create a non-owning view of the owned file descriptor.
Definition OwnedFd.hpp:95
void close() noexcept
Close the owned file descriptor.
int get() const noexcept
Get the owned file descriptor.
Definition OwnedFd.hpp:75
OwnedFd() noexcept
Create an invalid OwnedFd.
int release() noexcept
Release ownership of the file descriptor.
void reset(int newFd=-1) noexcept
Replace the owned file descriptor.
bool isValid() const noexcept
Check if this object owns a valid file descriptor.
Definition OwnedFd.hpp:71
Definition SocketClient.hpp:23
OwnedFd makeOwnedFd(int fd) noexcept
Create a OwnedFd that will automatically close the given fd on destruction.
Definition OwnedFd.hpp:102
Definition Message.hpp:21