How to make the Ring Buffer circular?

The chapter 8: Queues talks about Ring buffer implementation. Yet this buffer is not circular. It does not wrap around and it does not start from the beginning when full. How to make it circular?

1 Like

@jomoka Can you please help with this when you get a chance? Thank you - much appreciated! :]

Hi @tomn , could you please give some more context on your use case? Maybe an example test case? Ring Buffer implementation is circular in the sense that it has a fixed size, and reuses other slots in an array.

So for example if you had the following data set of size 4:

[1, 2, 8, 3]
 w            

If you appended another element (10) it would override the next write pointer in the ring buffer:

[10, 2, 8, 3]
      w       

Hope this makes sense. thanks!

2 Likes

I also encountered this problem. This is the code in Supporting Materials. When the array is full, it does not continue to write, but returns flase. In addition, the β€œfirst” property may be out of index.

public mutating func write(_ element: T) -> Bool {
    if !isFull {
      array[writeIndex % array.count] = element
      writeIndex += 1
      return true
    } else {
      return false
    }
  }

https://github.com/raywenderlich/alg-materials/blob/editions/4.0/08-queues/projects/starter/Queue.playground/Pages/QueueRingBuffer.xcplaygroundpage/Sources/RingBuffer.swift

1 Like