aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.posix/read_file.ccm
blob: be9e102162693ca0d7f2556a16c6c0b5c5b2b4a0 (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
/*
 * This source code is released into the public domain.
 */

module;

#include <algorithm>
#include <expected>
#include <filesystem>
#include <iterator>
#include <ranges>
#include <span>
#include <system_error>

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

export module nihil.posix:read_file;

import nihil.error;
import nihil.monad;
import :fd;
import :open;

namespace nihil {

/*
 * Read the contents of a file into an output iterator. 
 */
export [[nodiscard]] auto
read_file(std::filesystem::path const &filename,
	  std::output_iterator<char> auto &&iter)
	-> std::expected<void, error>
{
	auto file = co_await open(filename, O_RDONLY);

	auto constexpr bufsize = std::size_t{1024};
	auto buffer = std::array<char, bufsize>{};

	for (;;) {
		auto read_buf = co_await(read(file, buffer));
		if (read_buf.empty())
			co_return {};

		std::ranges::copy(read_buf, iter);
	}
}

} // namespace nihil