/*tex
    This file was generated by "mtxrun --script "mtx-wtoc.lua" from the metapost cweb files but
    now maintained as C file.
*/

# include "mpstrings.h"

/*tex
    Housekeeping:
*/

inline static void *delete_strings_entry(void *p)
{
    mp_string ff = (mp_string) p;
    if (ff) {
        mp_memory_free(ff->str);
        mp_memory_free(ff);
    }
    return NULL;
}

inline static mp_string new_strings_entry(void)
{
    return mp_memory_clear_allocate(sizeof(mp_lstring));
}

inline void mp_add_string_reference(MP mp, mp_string s)
{
    (void) mp;
    if (s && s->refs < MAX_STR_REF) {
        (s->refs)++;
    }
}

inline void mp_delete_string_reference(MP mp, mp_string s)
{
    if (s && s->refs < MAX_STR_REF) {
        if (s->refs > 1) {
            (s->refs)--;
        } else {
            mp_flush_string(mp, s);
        }
    }
}

/*tex
    Here is a routine that compares two strings in the string pool, and it does not assume that
    they have the same length. If the first string is lexicographically greater than, less than,
    or equal to the second, the result is respectively positive, negative, or zero.
*/

static int mp_aux_comp_strings_entry(void *p, const void *pa, const void *pb)
{
    const mp_lstring *a = (const mp_lstring *) pa;
    const mp_lstring *b = (const mp_lstring *) pb;
    (void) p;
    size_t min_len = a->len < b->len ? a->len : b->len;
    int res = memcmp(a->str, b->str, min_len);
    if (res != 0) {
        return (res > 0) - (res < 0); /* normalize to -1, 0, 1 */
    }
    return (a->len > b->len) - (a->len < b->len); /* normalize to -1, 0, 1 */
}

inline void *mp_aux_copy_strings_entry(const void *p)
{
    /*tex We know that |p| is not |NULL|. */
    const mp_lstring *fp = (const mp_lstring *) p;
    mp_string ff = new_strings_entry();
    if (! ff) {
        return NULL;
    }
    /*tex We append zero even when we have one already. */
    ff->str = mp_memory_allocate(fp->len + 1);
    if (! ff->str) {
        mp_memory_free(ff);
        return NULL;
    }
    if (fp->len > 0) {
        memcpy(ff->str, fp->str, fp->len);
    }
    ff->str[fp->len] = '\0';
    ff->len          = fp->len;
    return ff;
}

inline char *mp_strdup(const char *s)
{
    if (s) {
        char *w = lmt_memory_strdup(s);
        if lmt_likely(w) {
            return w;
        } else {
            printf("mplib ran out of memory, case 3");
            exit(EXIT_FAILURE);
        }
    }
    return NULL;
}

inline char *mp_strndup(const char *p, size_t l)
{
    if (p) {
        char *r = mp_memory_allocate(l + 1);
        if lmt_likely(r) {
            memcpy(r, p, l);
            r[l] = '\0';
            return r;
        } else {
            printf("mplib ran out of memory, case 4\n");
            exit(EXIT_FAILURE);
        }
    }
    return NULL;
}

void mp_initialize_strings(MP mp)
{
    mp->strings = avl_create(
        mp_aux_comp_strings_entry,
        mp_aux_copy_strings_entry,
        delete_strings_entry,
        mp_memory_allocate,
        mp_memory_free,
        NULL
    );
    mp->cur_string      = NULL;
    mp->cur_length      = 0;
    mp->cur_string_size = 0;
}

void mp_free_strings(MP mp)
{
    if (mp->strings != NULL) {
        avl_destroy(mp->strings);
        mp->strings = NULL;
    }
    mp_memory_free(mp->cur_string);
    mp->cur_string      = NULL;
    mp->cur_length      = 0;
    mp->cur_string_size = 0;
}

/*tex

    The |avl_find| after an |avl_ins| is somewhat inefficient but the library doesn't provide a
    variant that returns the pointer. In practice we only add strings so we can bear it.

*/

static inline void mp_aux_add_to_pool(MP mp, int len)
{
    mp->pool_in_use += len;
    if (mp->pool_in_use > mp->max_pool_used) {
        mp->max_pool_used = mp->pool_in_use;
    }
    mp->strings_in_use++;
    if (mp->strings_in_use > mp->max_strings_used) {
        mp->max_strings_used = mp->strings_in_use;
    }
}

# if 0

    mp_string mp_rtsl(MP mp, const char *s, size_t l)
    {
        mp_string nstr;
        mp_string str = new_strings_entry();
        str->str  = (unsigned char *) mp_strndup(s, l);
        str->len  = l;
        nstr = (mp_string) avl_find(str, mp->strings);
        if (nstr == NULL) {
            avl_ins(str, mp->strings, avl_false);
            nstr = (mp_string) avl_find(str, mp->strings);
        }
        delete_strings_entry(str);
        mp_add_string_reference(mp, nstr);
        return nstr;
    }

# else

    mp_string mp_rtsl(MP mp, const char *s, size_t l)
    {
        mp_string nstr;
        mp_lstring tmp = {
            .str  = (unsigned char *) mp_strndup(s, l),
            .len  = l,
            .refs = 0,
        };
        nstr = (mp_string) avl_find(&tmp, mp->strings);
        if (nstr == NULL) {
            avl_ins(&tmp, mp->strings, avl_false);
            nstr = (mp_string) avl_find(&tmp, mp->strings);
        }
        mp_memory_free(tmp.str);
        mp_add_string_reference(mp, nstr);
        return nstr;
    }

# endif

mp_string mp_rts(MP mp, const char *s)
{
    return s ? mp_rtsl(mp, s, strlen(s)) : NULL;
}

/*tex
    Strings are created by appending character codes to |cur_string|. The |mp_append_char|
    function, defined here, does not check to see if the buffer overflows; this test is supposed
    to be made before |mp_append_char| is used.

    To test if there is room to append |l| more characters to |cur_string|, we shall write
    |str_room(l)|, which tries to make sure there is enough room in the |cur_string|. At the very
    start of the metapost run and each time after |make_string| has stored a new string in the
    avl tree, the |cur_string| variable has to be prepared so that it will be ready to start
    creating a new string. The initial size is fairly arbitrary, but setting it a little higher
    than expected helps prevent |reallocs|.
*/

# define EXTRA_STRING 500

void mp_str_room(MP mp, int wsize)
{
    /* we always add one more */
    if ((mp->cur_length + (size_t) wsize + 1) > mp->cur_string_size) {
        size_t nsize = mp->cur_string_size + mp->cur_string_size / 5 + EXTRA_STRING;
        if (nsize < (mp->cur_length + (size_t) wsize + 1)) {
            nsize = mp->cur_length + (size_t) wsize + EXTRA_STRING;
        }
        mp->cur_string = (unsigned char *) mp_memory_clear_reallocate(mp->cur_string, mp->cur_string_size, nsize);
     // memset(mp->cur_string + mp->cur_length, 0, nsize - mp->cur_length);
        mp->cur_string_size = nsize;
    }
}

void mp_append_char(MP mp, unsigned char c)
{
    mp->cur_string[mp->cur_length++] = c;
}

/*tex
    We only append in pre- and postscripts and before we do that we create room so that
    we don't reallocate too often.
*/

void mp_append_str(MP mp, const char *s, int len)
{
    if (s) {
        mp_str_room(mp, len); /* adds some 500 bytes future wiggle room */
        memcpy(mp->cur_string + mp->cur_length, s, (size_t) len);
        mp->cur_length += len;
    }
}

void mp_reset_cur_string(MP mp)
{
    mp_memory_free(mp->cur_string);
    mp->cur_length      = 0;
    mp->cur_string_size = 64; /* was 63 */
    mp->cur_string      = (unsigned char *) mp_memory_clear_allocate(64);
}

/*tex

    \MP's string expressions are implemented in a brute-force way: Every new string or substring
    that is needed is simply stored into the string pool. Space is eventually reclaimed using the
    aid of a simple system system of reference counts.

    The number of references to string number |s| will be |s->refs|. The special value |s->refs =
    MAX_STR_REF=127| is used to denote an unknown positive number of references; such strings will
    never be recycled. If a string is ever referred to more than 126 times, simultaneously, we put
    it in this category. Here's what we do when a string reference disappears:

*/

void mp_flush_string(MP mp, mp_string s)
{
    /*tex We know that |s| is not |NULL|. */
    if (s->refs == 0) {
        mp->strings_in_use--;
        mp->pool_in_use -= (int) s->len;
        avl_del(s, mp->strings, NULL);
    }
}

/*tex
    Some C literals that are used as values cannot be simply added, their reference count has to be
    set such that they can not be flushed.
*/

mp_string mp_intern(MP mp, const char *s)
{
    mp_string r = mp_rts(mp, s);
    if (r) {
        r->refs = MAX_STR_REF;
    }
    return r;
}

/*tex

    Once a sequence of characters has been appended to |cur_string|, it officially becomes a string
    when the function |make_string| is called. This function returns a pointer to the new string as
    its value.

 */

# if 0

    mp_string mp_make_string(MP mp)
    {
        mp_lstring tmp = {
            .str  = mp->cur_string,
            .len  = mp->cur_length,
            .refs = 0,
        };
        mp_string str = (mp_string) avl_find(&tmp, mp->strings);
        if (str == NULL) {
            str = new_string_entry()
            str->str = mp->cur_string;
            str->len = tmp.len;
            avl_ins(str, mp->strings, avl_false);
            str = (mp_string) avl_find(&tmp, mp->strings);
            mp->pool_in_use = mp->pool_in_use + (int) str->len;
            if (mp->pool_in_use > mp->max_pool_used) {
                mp->max_pool_used = mp->pool_in_use;
            }
            mp->strings_in_use++;
            if (mp->strings_in_use > mp->max_strings_used) {
                mp->max_strings_used = mp->strings_in_use;
            }
        }
        mp_add_string_reference(mp, str);
        mp_reset_cur_string(mp);
        return str;
    }

# else

    mp_string mp_make_string(MP mp)
    {
        mp_lstring tmp = {
            .str  = mp->cur_string,
            .len  = mp->cur_length,
            .refs = 0,
        };
        mp_string nstr = (mp_string) avl_find(&tmp, mp->strings);
        if (! nstr) {
         // mp_string str = new_strings_entry();
         // str->str = mp->cur_string;
         // str->len = mp->cur_length;
            if (avl_ins(&tmp, mp->strings, avl_false) >= 0) {
                mp_aux_add_to_pool(mp, (int) mp->cur_length);
                /*tex As |avl_ins| called for a copy we need to resolve: */
                nstr = (mp_string) avl_find(&tmp, mp->strings);
            } else {
                printf("mplib ran out of memory, case 6\n");
                exit(EXIT_FAILURE);
            }
        }
        mp_add_string_reference(mp, nstr);
        mp_reset_cur_string(mp);
        return nstr;
    }

# endif

int mp_str_vs_str(MP mp, mp_string s, mp_string t)
{
    (void) mp;
    return mp_aux_comp_strings_entry(NULL, (const void *) s, (const void *) t);
}

mp_string mp_cat(MP mp, mp_string a, mp_string b)
{
    mp_string str;
    size_t saved_cur_length = mp->cur_length;
    unsigned char *saved_cur_string = mp->cur_string;
    size_t saved_cur_string_size = mp->cur_string_size;
    size_t needed = a->len + b->len;
    mp->cur_length = 0;
# if 0
    /* |mp->cur_string = NULL;|  needs malloc, spotted by clang */
    mp->cur_string = (unsigned char *) mp_memory_allocate((size_t) (needed + 1) * sizeof(unsigned char));
    mp->cur_string_size = 0;
    mp_str_room(mp, (int) needed + 1);
# else
    mp->cur_string_size = needed + 1;
    mp->cur_string = (unsigned char *) mp_memory_allocate(mp->cur_string_size);
# endif
    memcpy(mp->cur_string, a->str, a->len);
    memcpy(mp->cur_string + a->len, b->str, b->len);
    mp->cur_length = needed;
    mp->cur_string[needed] = '\0';
    str = mp_make_string(mp);
    mp_memory_free(mp->cur_string); /* created by |mp_make_string| */
    mp->cur_length = saved_cur_length;
    mp->cur_string = saved_cur_string;
    mp->cur_string_size = saved_cur_string_size;
    return str;
}

/*tex This one is used in |substring|. */

mp_string mp_chop_string(MP mp, mp_string s, int a, int b)
{
    int l = (int) s->len;
    int reversed = 0;
    if (a > b) {
        int k = a;
        a = b;
        b = k;
        reversed = 1;
    }
    if (a < 0) a = 0;
    if (b < 0) b = 0;
    if (a > l) a = l;
    if (b > l) b = l;
    int slice_len = b - a;
    mp_str_room(mp, slice_len);
    if (reversed) {
        for (int k = b - 1; k >= a; k--) {
            mp_append_char(mp, s->str[k]);
        }
    } else if (slice_len > 0) {
        memcpy(mp->cur_string + mp->cur_length, s->str + a, slice_len);
        mp->cur_length += slice_len;
    }
    return mp_make_string(mp);
}
