I'm trying to modify a fixed size ring buffer structure (written in C++) so that it would be able to handle the resize as per the requirement. First of all, I would like to know if this scenario is really possible to achieve? Because I have read everywhere on the internet that a ring buffer has to be fixed size and resizing it could result in invalidation of pointers.

Current Implementation:

  1. A vector, with predefined size, of pointers of type of class called Records
  2. An index to keep the total count of Records. Index starts from 1 and can go upto 4 billion
  3. A function getSlot() - this function creates a buffer (Record pointer) at an index (rindex) that is calculated by (index - 1)% size and increments the original index. It returns the value of index that was just before incrementing it.
  4. getbuffer(int slot) : this will take the returned value from get slot, calculates the buffer index by (slot - 1) % size and get the buffer and return the Record pointer buffer at the calculated index.

I'm trying to write a new function as set_buffer_size(int new_size) if new_size > current size I can resize it and would not lose any Records pointers if(new_size < currentsize), I want to preserve the last new_size number of record pointers so that the resized vector contains those pointers

Issue: not able to come up with a generic solution to deal with copying of records and placing in the resized array. the other scenario would be when the buffer has been recycled already and the current element is in the middle of the vector. For eg,

  1. One of the scenarios would be when the buffer is full for the first time and it is resized. If the initial size of vector was 10 and this is the 10th Record and I want to resize the vector to 5

1 2 3 4 5 6 7 8 9 10 expected - 6 7 8 9 10

2.If the initial size of vector was 10 and this is the 23th Record and I want to resize the vector to 5

21 22 23 14 15 16 17 18 19 20

expected - 19 20 21 22 23

Another issue - if in case, I'm successfully able to store all of my records as expected. when next the getSlot is called, say for scenario 2, ideally it should create a buffer at index 0 (where 19 is sitting currently) and return 23 but as per the calculation [(23 - 1) % 5 = 2], it creates a buffer at index 2 where pointer for record 21 is sitting at. And next when get_buffer(23) would be called it would return the buffer that was at index 2.

The change in size is messing up this calculation (index - 1)% size.

Please provide suggestions.

0

There are 0 best solutions below