Merge pull request #9722 from lucthev/main

[Ruby] Fix RepeatedField#last, #first inconsistencies
This commit is contained in:
Jason Lunn 2022-04-06 17:37:22 -04:00 committed by GitHub
commit 05df37d35c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 2 deletions

View File

@ -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...self.size]
end
end

View File

@ -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