/* SPDX-FileCopyrightText: 2023-2024 - Sébastien Wilmet
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include <gfls/gfls.h>

static void
check_find_very_long_line (const gchar *str,
			   guint        max_n_bytes_per_line,
			   gint         expected_found_at_pos)
{
	const gchar *result;

	result = gfls_utf8_find_very_long_line (str, max_n_bytes_per_line);

	if (expected_found_at_pos < 0)
	{
		g_assert_null (result);
	}
	else
	{
		gint found_at_pos;

		g_assert_nonnull (result);

		found_at_pos = result - str;
		g_assert_cmpint (found_at_pos, ==, expected_found_at_pos);
	}
}

static void
test_find_very_long_line (void)
{
	/* Without newline chars */
	check_find_very_long_line ("", 0, -1);
	check_find_very_long_line ("a", 0, 0);

	check_find_very_long_line ("", 1, -1);
	check_find_very_long_line ("a", 1, -1);
	check_find_very_long_line ("ab", 1, 0);

	check_find_very_long_line ("é", 1, 0);
	check_find_very_long_line ("é", 2, -1);

	/* With \n */
	check_find_very_long_line ("\n\n\n", 0, -1);
	check_find_very_long_line ("\na\n", 0, 1);
	check_find_very_long_line ("\na", 0, 1);

	check_find_very_long_line ("a\nb\nc\n", 1, -1);
	check_find_very_long_line ("a\nb\nc", 1, -1);
	check_find_very_long_line ("a\nbc\n", 1, 2);
	check_find_very_long_line ("a\nbcd\n", 1, 2);
	check_find_very_long_line ("a\nbcd\n", 2, 2);
	check_find_very_long_line ("a\nbcd", 2, 2);

	check_find_very_long_line ("é\nSé", 2, 3);
	check_find_very_long_line ("é\nSé", 3, -1);
	check_find_very_long_line ("é\nSé\n", 3, -1);

	/* Quick test with \r */
	check_find_very_long_line ("\r\r\r", 0, -1);
	check_find_very_long_line ("\n\r\n\r\n\r", 0, -1);
	check_find_very_long_line ("\r\n\r\n\r\n", 0, -1);

	check_find_very_long_line ("a\rb\nc\rd", 1, -1);

	check_find_very_long_line ("a\ré", 1, 2);
	check_find_very_long_line ("a\ré", 2, -1);
}

int
main (int    argc,
      char **argv)
{
	int exit_status;

	gfls_init ();
	g_test_init (&argc, &argv, NULL);

	g_test_add_func ("/utf8/find_very_long_line", test_find_very_long_line);

	exit_status = g_test_run ();
	gfls_finalize ();

	return exit_status;
}
