c - Moving the content of a RingBuffer to a LinearBuffer -
i copy ringbuffer linearbuffer. let's assume ringbuffer dealing of type ringbuff_t buf, :
typedef struct { ringbuff_data_t buffer[buffer_size]; /**< internal ring buffer data, referenced buffer pointers. */ ringbuff_data_t* in; /**< current storage location in circular buffer */ ringbuff_data_t* out; /**< current retrieval location in circular buffer */ ringbuff_count_t count; } ringbuff_t;
it looks need devide 2 cases : when "in" after "out" pointer or when it's before. i'v wrote code i'm not sure it's quite :
memset(linearbuffer,0,linear_buffer_size); ringbuff_data_t* tempin = buf.in; if (buf.out < tempin){ memcpy(linearbuffer,buf.out,tempin-buf.out); } else if (buf.out > tempin){ strcpy(linearbuffer,buf.out); strncpy(linearbuffer+strlen(buf.out),buf.buffer,buf.in-buf.buffer); }
your basic idea right, should use memcpy
throughout.
apparently, yout ring buffer designed use data type, not idea restrict implementation chars. when dealing arbitrary types, must aware memcpy
deals raw data , must pass size in bytes. involves taking size of data type copied.
the pointer arithmetic on source , destination buffers not involve sizeof
, because arithmetic done on pointers used data type.
your code then:
if (buf.out < buf.in) { memcpy(linearbuffer, buf.out, (buf.in - buf.out) * sizeof(*buf.buffer)); } else if (buf.out > buf.in) { size_t s1 = buf.buffer + buffer_size - buf.out; size_t s2 = buf.in - buf.buffer; memcpy(linearbuffer, buf.out, s1 * sizeof(*buf.buffer)); memcpy(linearbuffer + s1, buf.buffer, s2 * sizeof(*buf.buffer)); }
this solution not check bounds of linear buffer; assumed big enough hold contents of full ring buffer. assumed buffers arrays of same type.
Comments
Post a Comment