int BUFFER_shrink()

in src/buffer.c [382:448]


int BUFFER_shrink(BUFFER_HANDLE handle, size_t decreaseSize, bool fromEnd)
{
    int result;
    if (handle == NULL)
    {
        /* Codes_SRS_BUFFER_07_036: [ if handle is NULL, BUFFER_shrink shall return a non-null value ]*/
        LogError("Failure: handle is invalid.");
        result = MU_FAILURE;
    }
    else if (decreaseSize == 0)
    {
        /* Codes_SRS_BUFFER_07_037: [ If decreaseSize is equal zero, BUFFER_shrink shall return a non-null value ] */
        LogError("Failure: decrease size is 0.");
        result = MU_FAILURE;
    }
    else if (decreaseSize > handle->size)
    {
        /* Codes_SRS_BUFFER_07_038: [ If decreaseSize is less than the size of the buffer, BUFFER_shrink shall return a non-null value ] */
        LogError("Failure: decrease size is more than buffer size.");
        result = MU_FAILURE;
    }
    else
    {
        /* Codes_SRS_BUFFER_07_039: [ BUFFER_shrink shall allocate a temporary buffer of existing buffer size minus decreaseSize. ] */
        size_t alloc_size = handle->size - decreaseSize;
        if (alloc_size == 0)
        {
            /* Codes_SRS_BUFFER_07_043: [ If the decreaseSize is equal the buffer size , BUFFER_shrink shall deallocate the buffer and set the size to zero. ] */
            free(handle->buffer);
            handle->buffer = NULL;
            handle->size = 0;
            result = 0;
        }
        else
        {
            unsigned char* tmp = malloc(alloc_size);
            if (tmp == NULL)
            {
                /* Codes_SRS_BUFFER_07_042: [ If a failure is encountered, BUFFER_shrink shall return a non-null value ] */
                LogError("Failure: allocating temp buffer.");
                result = MU_FAILURE;
            }
            else
            {
                if (fromEnd)
                {
                    /* Codes_SRS_BUFFER_07_040: [ if the fromEnd variable is true, BUFFER_shrink shall remove the end of the buffer of size decreaseSize. ] */
                    (void)memcpy(tmp, handle->buffer, alloc_size);
                    free(handle->buffer);
                    handle->buffer = tmp;
                    handle->size = alloc_size;
                    result = 0;
                }
                else
                {
                    /* Codes_SRS_BUFFER_07_041: [ if the fromEnd variable is false, BUFFER_shrink shall remove the beginning of the buffer of size decreaseSize. ] */
                    (void)memcpy(tmp, handle->buffer + decreaseSize, alloc_size);
                    free(handle->buffer);
                    handle->buffer = tmp;
                    handle->size = alloc_size;
                    result = 0;
                }
            }
        }
    }
    return result;
}