aboutsummaryrefslogtreecommitdiffstats
path: root/modules/fd.ccm
blob: ad96ea7b4902e5839bcf3bf2d9b013a8e4ce4ca0 (plain) (blame)
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
/*
 * This source code is released into the public domain.
 */

module;

#include <fcntl.h>
#include <unistd.h>

#include <expected>
#include <format>
#include <stdexcept>
#include <system_error>

export module nihil:fd;

import :generic_error;

namespace nihil {

/*
 * Exception thrown when an internal fd error occurs.  This is not supposed
 * to be caught, since it indicates an internal logic error in the caller.
 */
export struct fd_logic_error final : std::logic_error {
	fd_logic_error(std::string what)
		: std::logic_error(std::move(what))
	{}
};

/*
 * fd: a file descriptor.
 */

export struct fd final {
	// Construct an empty (invalid) fd.
	fd() noexcept = default;

	// Construct an fd from an exising file destrictor, taking ownership.
	fd(int fd_) noexcept : _fd(fd_) {}

	// Destructor.  Close the fd, discarding any errors.
	~fd()
	{
		if (*this)
			this->close();
	}

	// Move from another fd, leaving the moved-from fd in an invalid state.
	fd(fd &&other) noexcept
		: _fd(std::exchange(other._fd, _invalid_fd))
	{}

	// Move assign from another fd.
	auto operator=(fd &&other) noexcept -> fd &
	{
		if (this != &other)
			_fd = std::exchange(other._fd, _invalid_fd);
		return *this;
	}

	// Not copyable.
	fd(fd const &) = delete;
	fd& operator=(fd const &) = delete;

	// Return true if this fd is valid (open).
	explicit operator bool(this fd const &self) noexcept
	{
		return self._fd != _invalid_fd;
	}

	// Close the wrapped fd.
	auto close(this fd &self) -> std::expected<void, std::error_code>
	{
		auto const ret = ::close(self.get());
		self._fd = _invalid_fd;

		if (ret == 0)
			return {};

		return std::unexpected(std::make_error_code(std::errc(errno)));
	}

	// Return the stored fd.
	auto get(this fd const &self) -> int {
		if (self)
			return self._fd;
		throw fd_logic_error("Attempt to call get() on invalid fd");
	}


	// Release the stored fd and return it.  The caller must close it.
	auto release(this fd &&self) -> int {
		if (self)
			return std::exchange(self._fd, self._invalid_fd);
		throw fd_logic_error("Attempt to release an invalid fd");
	}

private:
	static constexpr int _invalid_fd = -1;

	int _fd = _invalid_fd;
};

// Create a copy of this fd by calling dup().
export auto dup(fd const &self) -> std::expected<fd, std::error_code>
{
	auto thisfd = self.get();

	auto const newfd = ::dup(thisfd);
	if (newfd != -1)
		return {newfd};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Create a copy of this fd by calling dup2().  Note that because this results
// in the existing fd and the new fd both being managed by an fd instance,
// there are two potential cases that can cause problems:
//
// - dup()ing an fd to itself (a no-op)
// - dup()ing an fd to an fd which is already managed by an fd instance
//
// In both of these cases, either use raw_dup() instead, or immediately call
// release() on the returned fd to prevent the fd instance from closing it.
export auto dup(fd const &self, int newfd)
	-> std::expected<fd, std::error_code>
{
	auto thisfd = self.get();

	auto const ret = ::dup2(thisfd, newfd);
	if (ret != -1)
		return {newfd};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Create a copy of this fd by calling dup().
export auto raw_dup(fd const &self) -> std::expected<int, std::error_code>
{
	auto thisfd = self.get();

	auto const newfd = ::dup(thisfd);
	if (newfd != -1)
		return {newfd};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Create a copy of this fd by calling dup2().
export auto raw_dup(fd const &self, int newfd)
	-> std::expected<int, std::error_code>
{
	auto thisfd = self.get();

	auto const ret = ::dup2(thisfd, newfd);
	if (ret != -1)
		return {newfd};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Return the fnctl flags for this fd.
export auto getflags(fd const &self) -> std::expected<int, std::error_code>
{
	auto const flags = ::fcntl(self.get(), F_GETFL);
	if (flags != -1)
		return {flags};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Replace the fnctl flags for this fd.
export auto replaceflags(fd &self, int newflags)
	-> std::expected<void, std::error_code>
{
	auto const ret = ::fcntl(self.get(), F_SETFL, newflags);
	if (ret == 0)
		return {};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Add bits to the fcntl flags for this fd.  Returns the new flags.
export auto setflags(fd &self, int newflags)
	-> std::expected<int, std::error_code>
{
	auto flags = getflags(self);
	if (!flags)
		return flags;

	*flags |= newflags;
	auto const ret = replaceflags(self, *flags);
	if (!ret)
		return std::unexpected(ret.error());

	return {*flags};
}

// Remove bits from the fcntl flags for this fd.  Returns the new flags.
export auto clearflags(fd &self, int clrflags)
	-> std::expected<int, std::error_code>
{
	auto flags = getflags(self);
	if (!flags)
		return flags;

	*flags &= ~clrflags;
	auto const ret = replaceflags(self, *flags);
	if (!ret)
		return std::unexpected(ret.error());

	return {*flags};
}

// Return the fd flags for this fd.
export auto getfdflags(fd const &self) -> std::expected<int, std::error_code>
{
	auto const flags = ::fcntl(self.get(), F_GETFD);
	if (flags != -1)
		return {flags};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Replace the fd flags for this fd.
export auto replacefdflags(fd &self, int newflags)
	-> std::expected<void, std::error_code>
{
	auto const ret = ::fcntl(self.get(), F_SETFD, newflags);
	if (ret != -1)
		return {};

	return std::unexpected(std::make_error_code(std::errc(errno)));
}

// Add bits to the fd flags for this fd.  Returns the new flags.
export auto setfdflags(fd &self, int newflags)
	-> std::expected<int, std::error_code>
{
	auto flags = getfdflags(self);
	if (!flags)
		return flags;

	*flags |= newflags;
	auto const ret = replacefdflags(self, *flags);
	if (!ret)
		return std::unexpected(ret.error());

	return {*flags};
}

// Remove bits from the fd flags for this fd.  Returns the new flags.
export auto clearfdflags(fd &self, int clrflags)
	-> std::expected<int, std::error_code>
{
	auto flags = getfdflags(self);
	if (!flags)
		return flags;

	*flags &= ~clrflags;
	auto ret = replacefdflags(self, *flags);
	if (!ret)
		return std::unexpected(ret.error());

	return {*flags};
}

// Create two fds by calling pipe() and return them.
export auto pipe() -> std::expected<std::pair<fd, fd>, std::error_code> {
	auto fds = std::array<int, 2>{};

	if (auto const ret = ::pipe(fds.data()); ret != 0)
		return std::unexpected(std::make_error_code(std::errc(errno)));

	return {{fd(fds[0]), fd(fds[1])}};
}

/*
 * Write data to a file descriptor from the provided buffer.  Returns the
 * number of bytes (not objects) written.  Incomplete writes may cause a
 * partial object to be written.
 */
export auto write(fd &file, std::ranges::contiguous_range auto &&range)
	-> std::expected<std::size_t, std::error_code>
{
	auto const ret = ::write(file.get(), std::ranges::data(range),
				 std::ranges::size(range));
	if (ret >= 0)
		return ret;
	return std::unexpected(std::make_error_code(std::errc(errno)));
}

/*
 * Read data from a file descriptor into the provided buffer.  Returns the
 * number of bytes (not objects) read.  Incomplete reads may cause a partial
 * object to be read.
 */
export auto read(fd &file, std::ranges::contiguous_range auto &&range)
	-> std::expected<std::size_t, std::error_code>
{
	auto const ret = ::read(file.get(), std::ranges::data(range),
				std::ranges::size(range));
	if (ret >= 0)
		return ret;
	return std::unexpected(std::make_error_code(std::errc(errno)));
}

} // namespace nihil