Echo Writes Code

boot.cpp

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
#include "crucible/core/boot.hpp"

#include "crucible/core/console.hpp"
#include "crucible/core/environment.hpp"
#include "crucible/core/handlers.hpp"
#include "crucible/core/hash.hpp"
#include "crucible/core/iterators.hpp"

#include <exception>
#include <type_traits>
#include <utility>

namespace crucible
{
	namespace
	{
		[[nodiscard]] auto exit_status_to_exit_code(exit_status const status) -> int
		{
			static_assert(std::is_same_v<std::underlying_type_t<exit_status>, int>);
			return static_cast<int>(status);
		}
	}

	auto boot_from_main(int argc, char **argv, boot_function const boot) -> int
	{
		// Set the terminate handler; crashes will not print a backtrace until this is called.
		std::set_terminate(handle_terminate);

		// Parse environment variables; environment queries will return default values until this is
		// called.
		environment().initialize();

		// Select and initialize the best hash function for the current platform; prior to this process,
		// or if it fails, a simple fallback hash function is used.
		// May be a no-op on some platforms.
		hash_manager().initialize();

		// Convert argv into Crucible data structures
		auto const arguments {
			iterate(argv, argc)
				.map([](char const *argument) {
					return string_view { argument, std::strlen(argument) };
				})
				.materialize<heap_buffer<string_view>>()
		};

		// Call into client code. If you're looking for where your program starts, it's here! :)
		exit_status const status { boot(arguments.view()) };

		// Convert the exit status back into an `int` and finish up.
		return exit_status_to_exit_code(status);
	}
}