Skip to content

Commit

Permalink
Merge pull request #390 from ruby-protobuf/ah/fix_enum_hash_equality
Browse files Browse the repository at this point in the history
Fix enum hash equality
  • Loading branch information
liveh2o authored Nov 13, 2018
2 parents 7962468 + da5b844 commit f736e2b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/protobuf/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,25 @@ def class
tag.class
end

# Protobuf::Enum delegates methods to Fixnum, which has a custom hash equality method (`eql?`)
# This causes enum values to be equivalent when using `==`, `===`, `equals?`, but not `eql?`**:
#
# 2.3.7 :002 > ::Test::EnumTestType::ZERO.eql?(::Test::EnumTestType::ZERO)
# => false
#
# However, they are equilvalent to their tag value:
#
# 2.3.7 :002 > ::Test::EnumTestType::ZERO.eql?(::Test::EnumTestType::ZERO.tag)
# => true
#
# **The implementation changed in Ruby 2.5, so this only affects Ruby versions less than v2.4.
#
# Use the hash equality implementation from Object#eql?, which is equivalent to == instead.
#
def eql?(other)
self == other
end

def inspect
"\#<Protobuf::Enum(#{parent_class})::#{name}=#{tag}>"
end
Expand Down
14 changes: 14 additions & 0 deletions spec/lib/protobuf/enum_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,20 @@
specify { subject.try { |yielded| expect(yielded).to eq(subject) } }
end

describe '#eql?' do
it "is equal to itself" do
expect(::Test::EnumTestType::ZERO.eql?(::Test::EnumTestType::ZERO)).to be(true)
end

it "is equal to it's tag" do
expect(::Test::EnumTestType::ZERO.eql?(::Test::EnumTestType::ZERO.tag)).to be(true)
end

it "is not equal to it's name" do
expect(::Test::EnumTestType::ZERO.eql?(::Test::EnumTestType::ZERO.name)).to be(false)
end
end

context 'when coercing from enum' do
subject { Test::StatusType::PENDING }
it { is_expected.to eq(0) }
Expand Down

0 comments on commit f736e2b

Please sign in to comment.