Skip to content

Commit

Permalink
Implement Table#hash
Browse files Browse the repository at this point in the history
Copy the implemenation from Hash#hash, which produces the same hash
regardless of order of keys
  • Loading branch information
carlhoerberg committed Jul 28, 2024
1 parent bebed22 commit 2cd47e3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
6 changes: 6 additions & 0 deletions spec/table_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@ describe AMQ::Protocol::Table do
t1["x-delay"]?.should be_nil
t1.to_h.should eq({"x-stream-offset" => 1i64})
end

it "hash values for two semantically tables are the same" do
t1 = AMQ::Protocol::Table.new({a: 1, b: "foo"})
t2 = AMQ::Protocol::Table.new({b: "foo", a: 1})
t1.hash.should eq t2.hash
end
end

# Verifies bugfix for Sub-table memory corruption
Expand Down
17 changes: 17 additions & 0 deletions src/amq/protocol/table.cr
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,23 @@ module AMQ
true
end

# See `Object#hash(hasher)`
def hash(hasher)
# Copied from Hash#hash
# The hash value must be the same regardless of the
# order of the keys.
result = hasher.result

each do |key, value|
copy = hasher
copy = key.hash(copy)
copy = value.hash(copy)
result &+= copy.result
end

result.hash(hasher)
end

def delete(key : String)
ensure_writeable
@io.rewind
Expand Down

0 comments on commit 2cd47e3

Please sign in to comment.