/*	Copyright  (c)	Günter Woigk 2018 - 2020
					mailto:kio@little-bat.de

	This file is free software.

	Permission to use, copy, modify, distribute, and sell this software
	and its documentation for any purpose is hereby granted without fee,
	provided that the above copyright notice appears in all copies and
	that both that copyright notice, this permission notice and the
	following disclaimer appear in supporting documentation.

	THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY,
	NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR
	A PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE COPYRIGHT HOLDER
	BE LIABLE FOR ANY DAMAGES ARISING FROM THE USE OF THIS SOFTWARE,
	TO THE EXTENT PERMITTED BY APPLICABLE LAW.
*/

#include "kio/kio.h"
#include "utilities.h"


uint32 lineForPos (cstr source, uint32 spos) noexcept
{
	// find line for source position
	// source must be 0-delimited.
	// line numbers start with 1

	cptr p = source;		// scan pointer
	cptr e = source+spos;	// end pointer
	uint32 line = 1;		// current line number	((start at 1))

	for (;;)
	{
		p = strchr(p, '\n');
		if (p == nullptr) break;
		if (p >= e) break;
		p++;				// skip newline
		line++;				// count
	}

	return line;
}

uint32 tou32 (cptr s, uint32 min, uint32 max, cstr name) throws
{
	if (!is_dec_digit(*s)) throw AnyError("%s: argument missing", name);

	ulong n = strtoul(s,nullptr,10);

	if (n < min)
	{
		fprintf(stderr, "%s: limited to %u\n", name, min);
		return min;
	}

	if (n > max)
	{
		fprintf(stderr, "%s: limited to %u\n", name, max);
		return max;
	}

	return uint32(n);
}





































