// Copyright (C) FIT VUT
// Petr Lampa <lampa@fit.vutbr.cz>
// $Id$
// vi:set ts=8 sts=8 sw=8:
//
// simple config line parser
// 
class cfgparser
{
	string line;
	size_t pos;
public:
	cfgparser(): line(),pos(0) { }
	inline void set_line(const string &s) { line = s; pos = 0; }

	inline int length() const { return line.length(); }
	inline bool end() const { return pos >= line.length(); }
	inline bool skip_char() { 
		if (pos >= line.length()) return false;
		++pos;
		return true;
	}
	inline bool skip_ws(bool hash = false) { 
		if ((pos = line.find_first_not_of((hash?" \n\t\r#":" \n\t\r"), pos)) == line.npos) return false;
		return true;
	}
	inline char curchar() const { 
		if (pos < line.length()) return line[pos];
		return 0;
	}
	inline string get_word() {
		if (pos >= line.length()) return "";
		size_t o = pos;
		pos = line.find_first_of(" \n\t\r", pos);
		if (pos == line.npos) pos = line.length();
		return line.substr(o, pos - o);
	}
	inline bool get_ipv6addr(string delim, IPv6Address &addr) {
		if (pos >= line.length()) return false;
		size_t o = pos;
		delim.append(" \n\t\r");
		pos = line.find_first_of(delim, pos);
		if (pos == line.npos) pos = line.length();
		if (!addr.addr(line.substr(o, pos-o))) return false;
		return true;
	}
	inline bool get_macaddr(string delim, MacAddress &addr) {
		if (pos >= line.length()) return false;
		size_t o = pos;
		delim.append(" \n\t\r");
		pos = line.find_first_of(delim, pos);
		if (pos == line.npos) pos = line.length();
		if (!addr.addr(line.substr(o, pos-o))) return false;
		return true;
	}
	inline bool get_number(int &val, int min, int max, int base=10)
	{
		val = 0;
		if (pos >= line.length()) return false;
		if (!isdigit(line[pos])) {
			if (base != 16 || !isxdigit(line[pos])) return false;
		}
		do {
			val = val*base + line[pos]-'0';
			if (base == 16 && line[pos] > '9') {
				if (line[pos] >= 'a' && line[pos] <= 'f') val -= 'a' - '9' - 1;
				else
				if (line[pos] >= 'A' && line[pos] <= 'F') val -= 'A' - '9' - 1;
			}
			++pos;
			if (pos >= line.length()) break;
		} while (isdigit(line[pos]) || (base == 16 && isxdigit(line[pos])));
		if (val < min || val > max) return false;
		return true;
	}
};
