[Ruby] Fix RepeatedField#last, #first inconsistencies

pull/9722/head
Luc Thevenard 3 years ago
parent 7508ae82d3
commit d85f03d66a
  1. 17
      ruby/lib/google/protobuf/repeated_field.rb
  2. 13
      ruby/tests/repeated_field_test.rb

@ -79,12 +79,25 @@ module Google
def first(n=nil)
n ? self[0...n] : self[0]
if n.nil?
return self[0]
elsif n < 0
raise ArgumentError, "negative array size"
else
return self[0...n]
end
end
def last(n=nil)
n ? self[(self.size-n-1)..-1] : self[-1]
if n.nil?
return self[-1]
elsif n < 0
raise ArgumentError, "negative array size"
else
start = [self.size-n, 0].max
return self[start..-1]
end
end

@ -48,6 +48,10 @@ class RepeatedFieldTest < Test::Unit::TestCase
assert_equal TestMessage2.new(:foo => 1), m.repeated_msg.first
assert_equal :A, m.repeated_enum.first
err = assert_raises(ArgumentError) do
m.repeated_int32.first(-1)
end
assert_equal "negative array size", err.message
assert_equal [], m.repeated_int32.first(0)
assert_equal [-10], m.repeated_int32.first(1)
assert_equal [-10, -11], m.repeated_int32.first(2)
@ -72,6 +76,15 @@ class RepeatedFieldTest < Test::Unit::TestCase
assert_equal "foo".encode!('ASCII-8BIT'), m.repeated_bytes.last
assert_equal TestMessage2.new(:foo => 2), m.repeated_msg.last
assert_equal :B, m.repeated_enum.last
err = assert_raises(ArgumentError) do
m.repeated_int32.last(-1)
end
assert_equal "negative array size", err.message
assert_equal [], m.repeated_int32.last(0)
assert_equal [-11], m.repeated_int32.last(1)
assert_equal [-10, -11], m.repeated_int32.last(2)
assert_equal [-10, -11], m.repeated_int32.last(3)
end

Loading…
Cancel
Save