int_list_parser.cpp 1.36 KB
Newer Older
Swann Perarnau's avatar
Swann Perarnau committed
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
#include "int_list_parser.hpp"
#include "utils.hpp"
#include <cstdlib>
#include <algorithm>


Int_list_parser::Int_list_parser():
	_has_stride(false)
{
}

void Int_list_parser::expand_range(const string& input, vector<int>& out)
{
	vector<string> tokens;
	int stride = 1;
	split(input, '-', tokens);

	THROW_ON_BAD_INPUT_IF(!is_int(tokens[0]),
				"Ill-formed input; non-integer encountered while expanding a range");

	int start = atoi(tokens[0].c_str());
	string str_end = tokens[1];
	tokens.clear();
	split(str_end, 's', tokens);

	THROW_ON_BAD_INPUT_IF(!is_int(tokens[0]),
				"Ill-formed input; non-integer encountered while expanding a range");
	int end = atoi(tokens[0].c_str());
	if(tokens.size() == 2)
	{
		_has_stride = true;
		stride = atoi(tokens[1].c_str());	
	}

	for(int i=start; i<=end; i+=stride)
		out.push_back(i);
}

void Int_list_parser::convert_to_comprehensive(const string& input, 
		vector<int>& out, bool append)
{
	if(!append)
		out.clear();
	_has_stride = false;
	vector<string> tokens;
	split(input, ',', tokens);
	out.clear();
	for(int i=0; i< (int)tokens.size(); i++)
	{
		if(str_contains(tokens[i], "-"))
			expand_range(tokens[i], out);
		else
		{
			THROW_ON_BAD_INPUT_IF(!is_int(tokens[i]),
					"Ill-formed input; non-integer encountered while expanding a range");
			out.push_back(atoi(tokens[i].c_str()));
		}
	}
	std::sort(out.begin(), out.end());
}