From d315cbd8dc938cc3f2972a37921cd648ba4a5d6a Mon Sep 17 00:00:00 2001 From: Marc-Andre Lafortune Date: Tue, 14 Apr 2020 13:40:15 -0400 Subject: [PATCH] + Add Source::Range#eql? and hash [#670] --- lib/parser/source/range.rb | 9 +++++++++ test/test_source_range.rb | 15 +++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/lib/parser/source/range.rb b/lib/parser/source/range.rb index ad421c918..686d0baeb 100644 --- a/lib/parser/source/range.rb +++ b/lib/parser/source/range.rb @@ -298,6 +298,15 @@ def <=>(other) (@end_pos <=> other.end_pos) end + alias_method :eql?, :== + + ## + # Support for Ranges be used in as Hash indices and in Sets. + # + def hash + [@source_buffer, @begin_pos, @end_pos].hash + end + ## # @return [String] a human-readable representation of this range. # diff --git a/test/test_source_range.rb b/test/test_source_range.rb index 2c7cfe72f..605b0132e 100644 --- a/test/test_source_range.rb +++ b/test/test_source_range.rb @@ -169,4 +169,19 @@ def test_with assert_equal 1, sr3.begin_pos assert_equal 4, sr3.end_pos end + + def test_eql_and_hash + assert_equal false, @sr1_3.eql?(@sr3_3) + assert @sr1_3.hash != @sr3_3.hash + + also_1_3 = @sr3_3.with(begin_pos: 1) + assert_equal true, @sr1_3.eql?(also_1_3) + assert_equal @sr1_3.hash, also_1_3.hash + + buf2 = Parser::Source::Buffer.new('(string)') + buf2.source = "foobar\nbaz" + from_other_buf = Parser::Source::Range.new(buf2, 1, 3) + assert_equal false, @sr1_3.eql?(from_other_buf) + assert @sr1_3.hash != from_other_buf.hash + end end