/*
 * Nonidentical conversion
 *
 * SPDX-FileType: SOURCE
 * SPDX-FileCopyrightText: Michael Bäuerle
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "assert.h"
#include "string.h"

#include "libuciconv-0/iconv.h"  /* Always include main header file first */
#include "nonident.h"
#include "iconv_private.h"


/* ========================================================================== */
ucic0_i_bool ucic0_i_nonident(ucic0_i_state *state)
{
    static const size_t len_ni = sizeof UCIC0_I_NONIDENT - 1U;  /* -1 for NUL */

    if (!(UCIC0_ICONV_REPLACE_INVALID & state->flag))
    {
        errno = UCIC0_I_EILSEQ;
        return 1;
    }
    else
    {
        const size_t index_out = state->outlen_start - *(state->outlen);

        if (*(state->outlen) < len_ni)
        {
            /* Not enough space for replacement in outarray */
            errno = UCIC0_I_E2BIG;
            return 1;
        }

        assert(0U < *(state->inlen));
        --(*(state->inlen));

        (void)memcpy(&(state->outarray)[index_out], UCIC0_I_NONIDENT, len_ni);
        *(state->outlen) -= len_ni;
        ++(state->nonident);
    }

    return 0;
}
