ring: fix swap parts of array in to_a and index access

This commit is contained in:
zaru@sakuraba 2018-11-25 16:40:25 +09:00
parent 85850f47e0
commit bb73fd1f19
2 changed files with 18 additions and 6 deletions

View File

@ -57,10 +57,7 @@ class Pry
return @buffer[(count + index) % max_size] if index.is_a?(Integer)
return @buffer[index] if count <= max_size
# Swap parts of array when the array turns page and starts overwriting
# from the beginning, then apply the range.
last_part = @buffer.slice([index.end, max_size - 1].min, count % max_size)
(last_part + (@buffer - last_part))[index]
transpose_buffer_tail[index]
end
end
@ -68,8 +65,7 @@ class Pry
def to_a
return @buffer.dup if count <= max_size
last_part = @buffer.slice(count % max_size, @buffer.size)
last_part + (@buffer - last_part)
transpose_buffer_tail
end
# Clear the buffer and reset count.
@ -80,5 +76,12 @@ class Pry
@count = 0
end
end
private
def transpose_buffer_tail
tail = @buffer.slice(count % max_size, @buffer.size)
tail.concat @buffer.slice(0, count % max_size)
end
end
end

View File

@ -13,6 +13,11 @@ describe Pry::Ring do
ring << 1 << 2 << 3 << 4 << 5
expect(ring.to_a).to eq([3, 4, 5])
end
it "keeps duplicate elements" do
ring << 1 << 1 << 1 << 1
expect(ring.to_a).to eq([1, 1, 1])
end
end
describe "#[]" do
@ -54,6 +59,10 @@ describe Pry::Ring do
expect(ring[-3]).to eq(3)
end
it "returns the first element when accessed through 0..0" do
expect(ring[0..0]).to eq([3])
end
it "reads elements via inclusive range" do
expect(ring[1..2]).to eq([4, 5])
expect(ring[-2..-1]).to eq([4, 5])