/* SPDX-FileCopyrightText: 2025 - Sébastien Wilmet <swilmet@gnome.org>
 * SPDX-License-Identifier: LGPL-2.1-or-later
 */

#include "gtksourceencodingconversion.h"
#include "gtksourceiconv.h"

/* If @input_buffer ends with an incomplete multi-byte character, that part is
 * ignored.
 *
 * Returns: %TRUE if @input_buffer can be converted from @from_encoding to UTF-8
 * without errors and without fallback characters.
 */
gboolean
_gtk_source_encoding_conversion_try_convert (const GtkSourceEncoding *from_encoding,
					     const gchar             *input_buffer,
					     gsize                    input_buffer_size)
{
	GtkSourceIconv *conv;
	gchar *input_buffer_pos;
	gsize input_buffer_n_bytes_left;
	GtkSourceIconvResult conv_result;
	gboolean success = FALSE;

	g_return_val_if_fail (from_encoding != NULL, FALSE);
	g_return_val_if_fail (input_buffer != NULL, FALSE);
	g_return_val_if_fail (input_buffer_size > 0, FALSE);

	conv = gtk_source_iconv_new ();

	if (!gtk_source_iconv_open (conv,
				    "UTF-8",
				    gtk_source_encoding_get_charset (from_encoding),
				    NULL))
	{
		success = FALSE;
		goto out;
	}

	input_buffer_pos = (gchar *) input_buffer;
	input_buffer_n_bytes_left = input_buffer_size;
	conv_result = gtk_source_iconv_feed_discard_output (conv,
							    &input_buffer_pos, &input_buffer_n_bytes_left,
							    NULL);

	switch (conv_result)
	{
		case GTK_SOURCE_ICONV_RESULT_OK:
		case GTK_SOURCE_ICONV_RESULT_INCOMPLETE_INPUT:
			success = TRUE;
			break;

		case GTK_SOURCE_ICONV_RESULT_ERROR:
		case GTK_SOURCE_ICONV_RESULT_ILLEGAL_SEQUENCE:
		case GTK_SOURCE_ICONV_RESULT_OUTPUT_BUFFER_FULL:
		case GTK_SOURCE_ICONV_RESULT_LOSSY_CONVERSION:
		default:
			success = FALSE;
			break;
	}

out:
	gtk_source_iconv_free (conv);
	return success;
}
