Permalink
Browse files

vcap ring buffer

Change-Id: I7487a4028dd1278787651277996f36006860c794
  • Loading branch information...
1 parent 3789f89 commit 54ea0c7cfd945536f15c333a025012950ffc9a85 @pbozeman pbozeman committed Oct 11, 2012
Showing with 65 additions and 0 deletions.
  1. +16 −0 lib/vcap/ring_buffer.rb
  2. +49 −0 spec/vcap/ring_buffer_spec.rb
View
16 lib/vcap/ring_buffer.rb
@@ -0,0 +1,16 @@
+module VCAP
+ class RingBuffer < Array
+ attr_reader :max_size
+
+ def initialize(max_size)
+ @max_size = max_size
+ end
+
+ def push(item)
+ super
+ self.shift if size > @max_size
+ end
+
+ alias :<< :push
+ end
+end
View
49 spec/vcap/ring_buffer_spec.rb
@@ -0,0 +1,49 @@
+# Copyright (c) 2009-2012 VMware, Inc.
+
+require File.expand_path("../spec_helper", __FILE__)
+require "vcap/ring_buffer"
+
+module VCAP
+ describe RingBuffer do
+ MAX_ENTRIES = 5
+ let(:rb) { RingBuffer.new(MAX_ENTRIES) }
+
+ context "empty" do
+ it ".empty? should be true" do
+ rb.empty?.should be_true
+ end
+ end
+
+ context "with max push MAX_ENTRIES times" do
+ before do
+ MAX_ENTRIES.times do |i|
+ rb.push i
+ end
+ end
+
+ it ".empty? should be false" do
+ rb.empty?.should be_false
+ end
+
+ it ".size should return MAX_ENTRIES" do
+ rb.size.should == MAX_ENTRIES
+ end
+
+ it "should be in the correct order" do
+ a = []
+ MAX_ENTRIES.times { |i| a.push i }
+ rb.should == a
+ end
+
+ it ".push should add a new entry and drop the old one" do
+ rb.push "a"
+ rb.should == [1, 2, 3, 4, "a"]
+ end
+
+ it ".<< should add a new entry and drop the old one" do
+ rb << "a"
+ rb.should == [1, 2, 3, 4, "a"]
+ end
+ end
+ end
+end

0 comments on commit 54ea0c7

Please sign in to comment.