justinhoward / fixed_size_buffer

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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'

About

License:MIT License


Languages

Language:Ruby 98.2%Language:Shell 1.8%