aboutsummaryrefslogtreecommitdiffstats
path: root/nihil.posix/read_file.ccm
blob: 61c50855c7269a9323fdb2bc003e6839c29f64c4 (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
// This source code is released into the public domain.
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, open_read);

	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