#include "ltrsrv_cyclebuf.h"



void ltrsrv_cyclebuf_realloc(t_cycle_buf *pbuf, uint32_t new_size) {
    uint32_t *new_data = (uint32_t*)malloc((new_size) * sizeof((pbuf)->data[0]));
    if (new_data != NULL) {
        uint32_t cpy_size = CYCLEBUF_FILL_SIZE(pbuf);
        uint32_t done_size = 0;
        if (cpy_size > new_size) {
             cpy_size = new_size;
        }
        if (cpy_size > 0) {
            uint32_t cont_rdy = CYCLEBUF_GET_CONT_RDY_SIZE(pbuf);
            if (cont_rdy > cpy_size)
                cont_rdy = cpy_size;

            if (cont_rdy > 0) {
                memcpy(new_data, CYCLEBUF_GETPTR(pbuf), cont_rdy*sizeof(pbuf->data[0]));
                CYCLEBUF_GET_CONT_DONE(pbuf, cont_rdy);
                cpy_size -= cont_rdy;
                done_size += cont_rdy;
                if (cpy_size > 0) {
                    cont_rdy = CYCLEBUF_GET_CONT_RDY_SIZE(pbuf);
                    if (cont_rdy > cpy_size)
                        cont_rdy = cpy_size;
                    if (cont_rdy > 0) {
                        memcpy(&new_data[done_size], CYCLEBUF_GETPTR(pbuf), cont_rdy*sizeof(pbuf->data[0]));
                        done_size += cont_rdy;
                    }
                }
            }
        }
        CYCLEBUF_CLOSE(pbuf);
        pbuf->data = new_data;
        pbuf->put_pos = done_size;
        pbuf->wrds_cnt = done_size;
        pbuf->size = new_size;
        pbuf->get_pos = 0;
    }
}
