aboutsummaryrefslogtreecommitdiff
path: root/src/game_of_life.cpp
blob: 3cd662bd2db9903ff63f9aca943184705eda4709 (plain)
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
#include "conversion.hpp"
#include "randomization.hpp"

#include <getopt.h>
#include <iostream>
#include <memory>
#include <string_view>
#include <vector>

namespace
{
void optarg_error(char arg, const std::string_view &error)
{
	std::cout << "Error: Invalid option argument for -" << arg << ". " << error
			  << std::endl;
	exit(EXIT_FAILURE);
}

/**
 * Returns the current optarg as a string view.
 */
std::string_view get_str_optarg()
{
	return std::string_view(optarg);
}

/**
 * Returns the current optarg as a unsigned integer.
 *
 * @param arg The current command-line argument character
 * @param check_zero Whether or not to make sure that the result is not zero
 */
unsigned int get_uint_optarg(char arg, bool check_zero = false)
{
	auto conversion_result = str_to_uint(get_str_optarg());

	if (!conversion_result.success || (check_zero && conversion_result.result == 0))
	{
		optarg_error(arg, conversion_result.fail_reason);
	}

	return conversion_result.result;
}
} // namespace

constexpr std::array<option, 8> options = {
	option({"seed", required_argument, nullptr, 's'}),
	option({"help", no_argument, nullptr, 0}), option({nullptr, 0, nullptr, 0})};

int main(int argc, char *argv[])
{
	auto args = std::vector<std::string_view>(argv, argv + argc);

	std::shared_ptr<RandomNumberGenerator> random_gen = nullptr;

	char arg = 0;
	while ((arg = static_cast<char>(
				getopt_long(argc, argv, "s:", options.data(), nullptr))) != -1)
	{
		switch (arg)
		{
		case 's':
		{
			auto seed = get_uint_optarg(arg, true);

			random_gen = std::make_shared<RandomNumberGenerator>(seed);
			break;
		}
		case 0:
		{
			std::cout << "Usage: " << args[0]
					  << " [OPTION]...\n\n"
						 "Options:\n"
					  << "  -s, --seed SEED         The randomization seed used\n"
						 "      --help              Displays usage information"
					  << std::endl;
			return EXIT_SUCCESS;
		}
		case '?':
		{
			std::cout << "\nTry '" << args[0] << " --help' for more information"
					  << std::endl;
			return EXIT_FAILURE;
		}
		default:
			abort();
		}
	}

	if (random_gen == nullptr)
	{
		random_gen = std::make_shared<RandomNumberGenerator>();
	}
}