/*
 * This file was generated automatically by ExtUtils::ParseXS version 3.51 from the
 * contents of XS.xs. Do not edit this file, edit XS.xs instead.
 *
 *    ANY CHANGES MADE HERE WILL BE LOST!
 *
 */

#line 1 "XS.xs"
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"

#ifdef AMBIGUOUS_WIDTH_IS_WIDE
#include "charwidth_ambiguous_is_wide.h"
#else
#include "charwidth_default.h"
#endif


static int _char_width(UV codepoint) {
    int min = 0;
    int max = width_table_len - 1;
    int mid;

    if (codepoint < width_table[0].start || codepoint > width_table[max].end) {
        return 1;
    } else {
        while (max >= min) {
            mid = (min + max) / 2;
            if (codepoint > width_table[mid].end) {
                min = mid + 1;
            } else if (codepoint < width_table[mid].start) {
                max = mid - 1;
            } else {
                return width_table[mid].width;
            }
        }
        return 1;
    }
}


#line 46 "XS.c"
#ifndef PERL_UNUSED_VAR
#  define PERL_UNUSED_VAR(var) if (0) var = var
#endif

#ifndef dVAR
#  define dVAR		dNOOP
#endif


/* This stuff is not part of the API! You have been warned. */
#ifndef PERL_VERSION_DECIMAL
#  define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s)
#endif
#ifndef PERL_DECIMAL_VERSION
#  define PERL_DECIMAL_VERSION \
	  PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION)
#endif
#ifndef PERL_VERSION_GE
#  define PERL_VERSION_GE(r,v,s) \
	  (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s))
#endif
#ifndef PERL_VERSION_LE
#  define PERL_VERSION_LE(r,v,s) \
	  (PERL_DECIMAL_VERSION <= PERL_VERSION_DECIMAL(r,v,s))
#endif

/* XS_INTERNAL is the explicit static-linkage variant of the default
 * XS macro.
 *
 * XS_EXTERNAL is the same as XS_INTERNAL except it does not include
 * "STATIC", ie. it exports XSUB symbols. You probably don't want that
 * for anything but the BOOT XSUB.
 *
 * See XSUB.h in core!
 */


/* TODO: This might be compatible further back than 5.10.0. */
#if PERL_VERSION_GE(5, 10, 0) && PERL_VERSION_LE(5, 15, 1)
#  undef XS_EXTERNAL
#  undef XS_INTERNAL
#  if defined(__CYGWIN__) && defined(USE_DYNAMIC_LOADING)
#    define XS_EXTERNAL(name) __declspec(dllexport) XSPROTO(name)
#    define XS_INTERNAL(name) STATIC XSPROTO(name)
#  endif
#  if defined(__SYMBIAN32__)
#    define XS_EXTERNAL(name) EXPORT_C XSPROTO(name)
#    define XS_INTERNAL(name) EXPORT_C STATIC XSPROTO(name)
#  endif
#  ifndef XS_EXTERNAL
#    if defined(HASATTRIBUTE_UNUSED) && !defined(__cplusplus)
#      define XS_EXTERNAL(name) void name(pTHX_ CV* cv __attribute__unused__)
#      define XS_INTERNAL(name) STATIC void name(pTHX_ CV* cv __attribute__unused__)
#    else
#      ifdef __cplusplus
#        define XS_EXTERNAL(name) extern "C" XSPROTO(name)
#        define XS_INTERNAL(name) static XSPROTO(name)
#      else
#        define XS_EXTERNAL(name) XSPROTO(name)
#        define XS_INTERNAL(name) STATIC XSPROTO(name)
#      endif
#    endif
#  endif
#endif

/* perl >= 5.10.0 && perl <= 5.15.1 */


/* The XS_EXTERNAL macro is used for functions that must not be static
 * like the boot XSUB of a module. If perl didn't have an XS_EXTERNAL
 * macro defined, the best we can do is assume XS is the same.
 * Dito for XS_INTERNAL.
 */
#ifndef XS_EXTERNAL
#  define XS_EXTERNAL(name) XS(name)
#endif
#ifndef XS_INTERNAL
#  define XS_INTERNAL(name) XS(name)
#endif

/* Now, finally, after all this mess, we want an ExtUtils::ParseXS
 * internal macro that we're free to redefine for varying linkage due
 * to the EXPORT_XSUB_SYMBOLS XS keyword. This is internal, use
 * XS_EXTERNAL(name) or XS_INTERNAL(name) in your code if you need to!
 */

#undef XS_EUPXS
#if defined(PERL_EUPXS_ALWAYS_EXPORT)
#  define XS_EUPXS(name) XS_EXTERNAL(name)
#else
   /* default to internal */
#  define XS_EUPXS(name) XS_INTERNAL(name)
#endif

#ifndef PERL_ARGS_ASSERT_CROAK_XS_USAGE
#define PERL_ARGS_ASSERT_CROAK_XS_USAGE assert(cv); assert(params)

/* prototype to pass -Wmissing-prototypes */
STATIC void
S_croak_xs_usage(const CV *const cv, const char *const params);

STATIC void
S_croak_xs_usage(const CV *const cv, const char *const params)
{
    const GV *const gv = CvGV(cv);

    PERL_ARGS_ASSERT_CROAK_XS_USAGE;

    if (gv) {
        const char *const gvname = GvNAME(gv);
        const HV *const stash = GvSTASH(gv);
        const char *const hvname = stash ? HvNAME(stash) : NULL;

        if (hvname)
	    Perl_croak_nocontext("Usage: %s::%s(%s)", hvname, gvname, params);
        else
	    Perl_croak_nocontext("Usage: %s(%s)", gvname, params);
    } else {
        /* Pants. I don't think that it should be possible to get here. */
	Perl_croak_nocontext("Usage: CODE(0x%" UVxf ")(%s)", PTR2UV(cv), params);
    }
}
#undef  PERL_ARGS_ASSERT_CROAK_XS_USAGE

#define croak_xs_usage        S_croak_xs_usage

#endif

/* NOTE: the prototype of newXSproto() is different in versions of perls,
 * so we define a portable version of newXSproto()
 */
#ifdef newXS_flags
#define newXSproto_portable(name, c_impl, file, proto) newXS_flags(name, c_impl, file, proto, 0)
#else
#define newXSproto_portable(name, c_impl, file, proto) (PL_Sv=(SV*)newXS(name, c_impl, file), sv_setpv(PL_Sv, proto), (CV*)PL_Sv)
#endif /* !defined(newXS_flags) */

#if PERL_VERSION_LE(5, 21, 5)
#  define newXS_deffile(a,b) Perl_newXS(aTHX_ a,b,file)
#else
#  define newXS_deffile(a,b) Perl_newXS_deffile(aTHX_ a,b)
#endif

#line 190 "XS.c"

XS_EUPXS(XS_Term__Choose__LineFold__XS_char_width); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Term__Choose__LineFold__XS_char_width)
{
    dVAR; dXSARGS;
    if (items != 1)
       croak_xs_usage(cv,  "codepoint");
    {
	int	RETVAL;
	dXSTARG;
	UV	codepoint = (UV)SvUV(ST(0))
;
#line 44 "XS.xs"
        RETVAL = _char_width(codepoint);
#line 205 "XS.c"
	XSprePUSH;
	PUSHi((IV)RETVAL);
    }
    XSRETURN(1);
}


XS_EUPXS(XS_Term__Choose__LineFold__XS_print_columns); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Term__Choose__LineFold__XS_print_columns)
{
    dVAR; dXSARGS;
    if (items != 1)
       croak_xs_usage(cv,  "input");
    {
#line 53 "XS.xs"
        STRLEN len;
        const U8 *p, *end;
        UV codepoint;
        int width = 0;
        STRLEN clen;
#line 226 "XS.c"
	SV *	RETVAL;
	SV *	input = ST(0)
;
#line 59 "XS.xs"
        if (!SvOK(input)) {
            XSRETURN_UNDEF;
        }
        if (!SvPOK(input)) {
            input = sv_mortalcopy(input); // Ensure string
            SvPV_force(input, len);
        }
        p = (const U8 *) SvPVutf8(input, len);
        end = p + len;

        while (p < end) {
            codepoint = utf8_to_uvchr_buf(p, end, &clen);
            if (clen == -1 ) {
                codepoint = *p; // Interpret the invalid byte as a single character
                clen = 1;       // Advance by 1 byte

                // Option B: Stop processing on error
                // Perl_warn(aTHX_ "Malformed UTF-8 at byte offset %ld", (long)(p - (const U8 *)SvPVX(input)));
                // break;

                // Option C: Malformed UTF-8. Skip bad byte and keep going
                // p++;
                // continue;
            }
            p += clen;
            width += _char_width(codepoint);
        }

        RETVAL = newSViv(width);
#line 260 "XS.c"
	RETVAL = sv_2mortal(RETVAL);
	ST(0) = RETVAL;
    }
    XSRETURN(1);
}


XS_EUPXS(XS_Term__Choose__LineFold__XS_cut_to_printwidth); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Term__Choose__LineFold__XS_cut_to_printwidth)
{
    dVAR; dXSARGS;
    if (items != 2)
       croak_xs_usage(cv,  "input, max_width");
    PERL_UNUSED_VAR(ax); /* -Wall */
    SP -= items;
    {
#line 96 "XS.xs"
        STRLEN len;
        const U8 *p, *end;
        const U8 *split_point = NULL;
        const U8 *char_start;
        UV codepoint;
        int str_w = 0, this_w;
        STRLEN clen;
//        bool skip_padding;
#line 286 "XS.c"
	SV *	RETVAL;
	SV *	input = ST(0)
;
	int	max_width = (int)SvIV(ST(1))
;
#line 105 "XS.xs"
        if (!SvOK(input)) {
            XSRETURN_UNDEF;
        }

        if (!SvPOK(input)) {
            input = sv_mortalcopy(input);
            SvPV_force(input, len);
        }

        const U8 *start = (const U8 *) SvPVutf8(input, len);
        p = start;
        end = p + len;

        while (p < end) {
            char_start = p;
            codepoint = utf8_to_uvchr_buf(p, end, &clen);

            if (clen == -1) {
                codepoint = *p;
                clen = 1;
            }

            this_w = _char_width(codepoint);

            if (str_w + this_w > max_width) {
                split_point = char_start;
                break;
            }

            //if (str_w + this_w == max_width) {
            //    p += clen;
            //    str_w += this_w;
            //    split_point = p;
            //    break;
            //}

            str_w += this_w;
            p += clen;
        }

        if (!split_point) {
            // Whole string fits
            if (GIMME_V == G_ARRAY) {
                XPUSHs(sv_2mortal(newSVsv(input)));
                XPUSHs(sv_2mortal(newSVpvn("", 0)));
            } else {
                XPUSHs(sv_2mortal(newSVsv(input)));
            }
        } else {
            STRLEN first_len = split_point - start;
            SV *first_part = newSVpvn((const char *)start, first_len);
            SvUTF8_on(first_part);

            if (str_w == max_width - 1) {
                sv_catpv(first_part, " ");
                str_w += 1;
            }

            if (GIMME_V == G_ARRAY) {
                STRLEN rest_len = end - split_point;
                SV *rest_part = newSVpvn((const char *)split_point, rest_len);
                SvUTF8_on(rest_part);

                XPUSHs(sv_2mortal(first_part));
                XPUSHs(sv_2mortal(rest_part));
            } else {
                XPUSHs(sv_2mortal(first_part));
            }
        }
#line 362 "XS.c"
	PUTBACK;
	return;
    }
}


XS_EUPXS(XS_Term__Choose__LineFold__XS_adjust_to_printwidth); /* prototype to pass -Wmissing-prototypes */
XS_EUPXS(XS_Term__Choose__LineFold__XS_adjust_to_printwidth)
{
    dVAR; dXSARGS;
    if (items != 2)
       croak_xs_usage(cv,  "input, width");
    {
#line 180 "XS.xs"
        STRLEN len;
        const U8 *p, *end;
        UV codepoint;
        int str_w = 0, this_w;
        STRLEN clen;
        SV *result;
        const U8 *start;
#line 384 "XS.c"
	SV *	RETVAL;
	SV *	input = ST(0)
;
	int	width = (int)SvIV(ST(1))
;
#line 188 "XS.xs"
        if (!SvOK(input)) {
            XSRETURN_UNDEF;
        }

        if (!SvPOK(input)) {
            input = sv_mortalcopy(input);
            SvPV_force(input, len);
        }

        p = (const U8 *) SvPVutf8(input, len);  // len is char length
        end = p + len;
        start = p;

        while (p < end) {
            codepoint = utf8_to_uvchr_buf(p, end, &clen);
            if (clen == (STRLEN)-1) {
                codepoint = *p;
                clen = 1;
            }

            this_w = _char_width(codepoint);
            if (str_w + this_w > width) {
                break;
            }

            str_w += this_w;
            p += clen;
        }

        len = (STRLEN)(p - start);  // Final cutoff length: now len is bytes length

        if (str_w == width) {
            RETVAL = newSVpvn((const char *)start, len);
        } else {
            result = newSVpvn((const char *)start, len);
            sv_catpvf(result, "%*s", width - str_w, "");
            RETVAL = result;
        }

        SvUTF8_on(RETVAL);
#line 431 "XS.c"
	RETVAL = sv_2mortal(RETVAL);
	ST(0) = RETVAL;
    }
    XSRETURN(1);
}

#ifdef __cplusplus
extern "C" {
#endif
XS_EXTERNAL(boot_Term__Choose__LineFold__XS); /* prototype to pass -Wmissing-prototypes */
XS_EXTERNAL(boot_Term__Choose__LineFold__XS)
{
#if PERL_VERSION_LE(5, 21, 5)
    dVAR; dXSARGS;
#else
    dVAR; dXSBOOTARGSXSAPIVERCHK;
#endif
#if PERL_VERSION_LE(5, 8, 999) /* PERL_VERSION_LT is 5.33+ */
    char* file = __FILE__;
#else
    const char* file = __FILE__;
#endif

    PERL_UNUSED_VAR(file);

    PERL_UNUSED_VAR(cv); /* -W */
    PERL_UNUSED_VAR(items); /* -W */
#if PERL_VERSION_LE(5, 21, 5)
    XS_VERSION_BOOTCHECK;
#  ifdef XS_APIVERSION_BOOTCHECK
    XS_APIVERSION_BOOTCHECK;
#  endif
#endif

        newXS_deffile("Term::Choose::LineFold::XS::char_width", XS_Term__Choose__LineFold__XS_char_width);
        newXS_deffile("Term::Choose::LineFold::XS::print_columns", XS_Term__Choose__LineFold__XS_print_columns);
        newXS_deffile("Term::Choose::LineFold::XS::cut_to_printwidth", XS_Term__Choose__LineFold__XS_cut_to_printwidth);
        newXS_deffile("Term::Choose::LineFold::XS::adjust_to_printwidth", XS_Term__Choose__LineFold__XS_adjust_to_printwidth);
#if PERL_VERSION_LE(5, 21, 5)
#  if PERL_VERSION_GE(5, 9, 0)
    if (PL_unitcheckav)
        call_list(PL_scopestack_ix, PL_unitcheckav);
#  endif
    XSRETURN_YES;
#else
    Perl_xs_boot_epilog(aTHX_ ax);
#endif
}

#ifdef __cplusplus
}
#endif
