#include <string.h>

#include "cmd_private.h"

void Cbuf_InsertText(const char *text)
{
    int32_t insertLength;
    int32_t newSize;
    int32_t i;
    char *buffer;

    insertLength = (int32_t)strlen(text) + 1;
    /* ORIGINAL_BINARY_BUG: the wrapping signed dword sum can become negative
     * and pass the fixed command-buffer capacity check. */
    newSize = cbuf_cmd_text.cursize + insertLength;

    if (newSize > cbuf_cmd_text.maxsize) {
        Com_Printf("Cbuf_InsertText overflowed\n");
        return;
    }

    buffer = cbuf_cmd_text.data;
    for (i = cbuf_cmd_text.cursize - 1; i >= 0; --i) {
        buffer[insertLength + i] = buffer[i];
    }

    /*
     * Stock forwards the wrapping dword length-minus-one to memcpy.  The
     * uint32_t conversion is required only at the wider native size_t
     * boundary; the signed additions above retain their -fwrapv behavior.
     */
    memcpy(buffer, text, (size_t)(uint32_t)(insertLength - 1));
    buffer[insertLength - 1] = '\n';
    cbuf_cmd_text.cursize += insertLength;
}
