File: util.cpp

package info (click to toggle)
minetestmapper 20200328-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 252 kB
  • sloc: cpp: 2,454; sh: 65; ansic: 32; makefile: 9
file content (45 lines) | stat: -rw-r--r-- 994 bytes parent folder | download
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
#include <stdexcept>
#include <sstream>

#include "util.h"

static inline std::string trim(const std::string &s)
{
	auto isspace = [] (char c) -> bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };

	size_t front = 0;
	while(isspace(s[front]))
		++front;
	size_t back = s.size() - 1;
	while(back > front && isspace(s[back]))
		--back;

	return s.substr(front, back - front + 1);
}

std::string read_setting(const std::string &name, std::istream &is)
{
	char linebuf[512];
	while (is.good()) {
		is.getline(linebuf, sizeof(linebuf));

		for(char *p = linebuf; *p; p++) {
			if(*p != '#')
				continue;
			*p = '\0'; // Cut off at the first #
			break;
		}
		std::string line(linebuf);

		auto pos = line.find('=');
		if (pos == std::string::npos)
			continue;
		auto key = trim(line.substr(0, pos));
		if (key != name)
			continue;
		return trim(line.substr(pos+1));
	}
	std::ostringstream oss;
	oss << "Setting '" << name << "' not found";
	throw std::runtime_error(oss.str());
}