Chris
Chris

Reputation: 3405

c++: circular buffer with integer indices as iterators?

I'm writing a C++ application where I need a cache of the last n messages that have arrived. And I need a way to get the index of the last message stored so that I can later on figure out all messages that have arrived afterwards. As this index has to be transported forward and back over HTTP, it should be easy representable and checkable as it becomes potentially unsafe user content.

So far I was thinking of using the boost::circular_buffer. But I couldn't find a way to figure out the index of the latest entry except the iterator.

So is there a way to some how (efficiently) get an integer index?
Or is there a way to encode and decode the iterator into a string that's savely validateable?
Or perhaps even a totally different way that I didn't think of yet?

(Anything up to C++11 is allowed; STL/stdlib and Boost highly preferred)

Upvotes: 2

Views: 3354

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308530

If you don't care about erasing items from the buffer until they get overwritten by new data, this becomes almost trivial to implement with a std::vector.

std::vector<item> buffer;
buffer.reserve(BUFFER_SIZE);
int next_slot = 0;

// to insert:
if (next_slot >= buffer.size())
    buffer.push_back(new_item);
else
    buffer[next_slot] = new_item;
++next_slot;
if (next_slot >= BUFFER_SIZE)
    next_slot = 0;

Upvotes: 3

Related Questions