Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 57 lines (49 sloc) 1.223 kb
4c3738c6 »
2009-03-16 Completed initial impl
1 class ChunkedArray
2 def initialize(bucket_size = 500)
3 @array, @bucket_size, @offset = [[]], bucket_size, 0
4 @mutex = Mutex.new
5 end
6
7 def push(item)
8 @mutex.synchronize do
9 if @array.last.nil? || @array.last.size == @bucket_size
10 @array << []
11 end
12 @array.last << item
13 end
14 end
15
16 def [](index)
17 bucket = (index / @bucket_size) - @offset
18 idx = index % @bucket_size
19 if bucket >= 0 && @array[bucket]
20 @array[bucket][idx]
21 end
22 end
23
24 def gc(lowest_valid_item)
25 bucket = (lowest_valid_item / @bucket_size)
26 if bucket > @offset
27 @mutex.synchronize do
28 (bucket - @offset).times { @array.shift }
29 @offset = bucket
30 end
31 end
32 end
33 end
34
35 describe "a chunked Array" do
36 before(:each) do
37 @array = ChunkedArray.new
38 end
39
40 it "works like an array for the first element" do
41 @array.push 1
42 @array[0].should == 1
43 end
44
45 it "works like an Array for the 750th element" do
46 750.times {|i| @array.push i }
47 @array[749].should == 749
48 end
49
50 it "continues to work after collecting a bucket" do
51 750.times {|i| @array.push i }
52 @array.gc(501)
53 @array[0].should == nil
54 @array[749].should == 749
55 end
56 end
Something went wrong with that request. Please try again.