Module RingBuffer

Types

RingBuffer*[T] = object 
  data: seq[T]
  head, tail: int
  size, length*: int
A ring buffer is a sequence-like type which can store up to length elements. After length elements are added to the buffer, new items will begin to replace the oldest ones (i.e. the elements at the start of the buffer).

Procs

proc newRingBuffer*[T](length: int): RingBuffer[T]
Construct a new RingBuffer which can hold up to length elements
var b = newRingBuffer[int](5)
b.add([1, 2, 3, 4, 5])
b.add(6)
b.add([7, 8])
@b == [4, 5, 6, 7, 8]  
proc `[]`*[T](b: RingBuffer[T]; idx: int): T {.inline.}
Get an item at index (adjusted)
proc `[]=`*[T](b: var RingBuffer[T]; idx: int; item: T) {.raises: [IndexError].}
Set an item at index (adjusted)
proc len*(b: RingBuffer): int
proc slice*[T](b: RingBuffer[T]; s = 0; e1 = MAX_INT): seq[T]
Create a subsequence of the buffer from elements s to e Creates a sequence of the entire collection by default.
proc `@`*[T](b: RingBuffer[T]): seq[T]
Convert the buffer to a sequence
proc add*[T](b: var RingBuffer[T]; item: T)
Add an element to the buffer
proc add*[T](b: var RingBuffer[T]; data: openArray[T])
Add elements to the buffer
proc pop*[T](b: var RingBuffer[T]): T
Remove an element from the buffer and return it
proc isFull*(b: RingBuffer): bool
Is the buffer at capacity (add will overwrite another element)
proc find*[T](b: RingBuffer[T]; val: T): int
Find the first index of a value or -1
proc `contains`*[T](b: RingBuffer[T]; val: T): bool
Check if the buffer contains a given value
proc sort*[T](b: var RingBuffer[T]; cmp: proc (x, y: T): int {.closure.}; 
              order = SortOrder.Ascending)
Sort the buffer using a compare function
proc empty*[T](b: var RingBuffer[T])
Mark the buffer as empty (len=0)

Iterators

iterator `items`*[T](b: RingBuffer[T]): T
iterator `pairs`*[T](b: RingBuffer[T]): tuple[a: int, b: T]

Converters

converter toSeq*[T](b: RingBuffer[T]): seq[T]