// SPDX-License-Identifier: 0BSD


#pragma once

#include <cstdlib>
#include <errno.h>
#include <limits>


namespace vore {
	namespace {
		template <int base = 0, class T>
		bool parse_sint_minmax(const char * val, T & out, long long min, long long max = std::numeric_limits<T>::max()) {
			if(val[0] == '\0')
				return errno = EINVAL, false;

			char * end{};
			errno    = 0;
			auto res = std::strtoll(val, &end, base);
			out      = res;
			if(errno)
				return false;
			if(res < min || res > max)
				return errno = ERANGE, false;
			if(*end != '\0')
				return errno = EINVAL, false;

			return true;
		}

		template <int base = 0, class T>
		bool parse_sint(const char * val, T & out) {
			return parse_sint_minmax<base, T>(val, out, std::numeric_limits<T>::min());
		}
	}
}
