Class: Foruiman::Ring
- Inherits:
-
Object
- Object
- Foruiman::Ring
- Includes:
- Enumerable
- Defined in:
- lib/foruiman/ring.rb
Instance Attribute Summary collapse
-
#capacity ⇒ Object
readonly
Returns the value of attribute capacity.
-
#size ⇒ Object
readonly
Returns the value of attribute size.
Instance Method Summary collapse
- #[](index) ⇒ Object
- #append(record) ⇒ Object
- #each ⇒ Object
- #index_of(sequence) ⇒ Object
-
#initialize(capacity) ⇒ Ring
constructor
A new instance of Ring.
- #replace(record) ⇒ Object
Constructor Details
#initialize(capacity) ⇒ Ring
Returns a new instance of Ring.
8 9 10 11 12 13 14 15 16 |
# File 'lib/foruiman/ring.rb', line 8 def initialize(capacity) raise Foruiman::Error, "log-lines must be a positive integer" unless capacity.is_a?(Integer) && capacity.positive? @capacity = capacity @slots = [] @positions = {} @head = 0 @size = 0 end |
Instance Attribute Details
#capacity ⇒ Object (readonly)
Returns the value of attribute capacity.
6 7 8 |
# File 'lib/foruiman/ring.rb', line 6 def capacity @capacity end |
#size ⇒ Object (readonly)
Returns the value of attribute size.
6 7 8 |
# File 'lib/foruiman/ring.rb', line 6 def size @size end |
Instance Method Details
#[](index) ⇒ Object
37 38 39 40 41 |
# File 'lib/foruiman/ring.rb', line 37 def [](index) return unless index >= 0 && index < size @slots[(@head + index) % capacity] end |
#append(record) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/foruiman/ring.rb', line 18 def append(record) index = (@head + @size) % capacity if size == capacity @positions.delete(@slots[index].sequence) @head = (@head + 1) % capacity else @size += 1 end @slots[index] = record @positions[record.sequence] = index record end |
#each ⇒ Object
48 49 50 51 52 |
# File 'lib/foruiman/ring.rb', line 48 def each return enum_for(:each) unless block_given? size.times { |index| yield self[index] } end |
#index_of(sequence) ⇒ Object
43 44 45 46 |
# File 'lib/foruiman/ring.rb', line 43 def index_of(sequence) position = @positions[sequence] (position - @head) % capacity if position end |
#replace(record) ⇒ Object
31 32 33 34 35 |
# File 'lib/foruiman/ring.rb', line 31 def replace(record) index = @positions[record.sequence] @slots[index] = record if index record end |