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

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

	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 appear in all copies and that both that
	copyright notice and this permission notice appear in supporting
	documentation, and that the name of the copyright holder not be used
	in advertising or publicity pertaining to distribution of the software
	without specific, written prior permission.  The copyright holder makes no
	representations about the suitability of this software for any purpose.
	It is provided "as is" without express or implied warranty.

	THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
	INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
	EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, INDIRECT OR
	CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
	DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
	TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
	PERFORMANCE OF THIS SOFTWARE.
*/

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



uint normalizeLinebreaks(ptr q) noexcept
{
	// replace non-unix linebreaks with simple '\n'
	// returns number of bytes removed for DOS linebreaks

	static const char nl = '\n';
	static const char cr = '\r';

	ptr z = strchr(q,cr);
	if(z == nullptr) return 0;

	if (z>q) z--;	// prev char might be nl
	for (q=z;;)
	{
		char c;
		while (uchar(c = *z++ = *q++) > 13) {}

		if (c==0) return uint(q-z);
		if (c==nl || c==cr)
		{
			if (c + *q == cr+nl) q++;
			*(z-1) = nl;
		}
	}
}

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
	uint 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;
}






































