No commit activity in last 3 years
No release in over 3 years
A circular data structure
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 3.4
= 0.81.0
 Project Readme

FixedSizeBuffer

Gem Version CI Code Quality Code Coverage Inline docs

A ring buffer with a fixed capacity

buffer = FixedSizeBuffer.new(3)
buffer.write(1)
buffer.write(2)
buffer.to_a # [1, 2]
buffer.read # => 1
buffer.read # => 2

What is a Ring Buffer?

A ring buffer is a continuously writable and continuously readable data structure that is contained in a fixed amount of memory. It can be conceptualized as writing values around a circular array. As we write, we move clockwise around the circle, and the reader trails around in the same direction.

The advantages of a ring buffer as opposed to pushing and shifting an array is that a ring buffer only can be heap allocated once, and since it's a fixed size, it never needs to be reallocated.

Installation

Add it to your Gemfile:

gem 'fixed_size_buffer'

Or install it manually:

gem install fixed_size_buffer

API Documentation

API docs can be read on rubydoc.info, inline in the source code, or you can generate them yourself with Ruby yard:

bin/yardoc

Then open doc/index.html in your browser.

Usage

Create a new ring buffer with a given capacity

buffer = FixedSizeBuffer.new(100)

Then write and read from the buffer

buffer = FixedSizeBuffer.new(2)
buffer.empty? # => true
buffer.size # => 0
buffer.write('hello')
buffer.write('world')
buffer.size # => 2
buffer.full? # => true
buffer.to_a # => ['hello', 'world']
buffer.peek # => 'hello'
buffer.read # => 'hello'
buffer.read # => 'world'
buffer.read # => nil

Once the buffer fills up, it will overwrite the oldest values.

buffer = FixedSizeBuffer.new(2)
buffer.write('hello')
buffer.write('world')
buffer.write('again')
buffer.read # => 'world'