Skip to content

Commit

Permalink
Optimize Bytes#hash and keep slow Slice(T)#hash
Browse files Browse the repository at this point in the history
  • Loading branch information
ysbaddaden committed Oct 19, 2017
1 parent a2af730 commit 7733d3e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
8 changes: 8 additions & 0 deletions spec/std/slice_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,14 @@ describe "Slice" do
slice = Bytes[1, 2, 3, read_only: true]
expect_raises { slice[0] = 0_u8 }
end

it "hashes each item in collection" do
Slice[1, 2, 3].hash.should eq(Slice[1_u64, 2_u64, 3_u64].hash)
end

it "optimizes hash for Bytes" do
Bytes[1, 2, 3].hash.should_not eq(Slice[1, 2, 3].hash)
end
end

private def itself(*args)
Expand Down
9 changes: 7 additions & 2 deletions src/crystal/hasher.cr
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ struct Crystal::Hasher
# disclose the result of the hashes, we don't need the cryptographically
# verified siphash-2-4, but can use the faster siphash-1-3 alternative.
#
# On 32-bit systems, we prefer the halfsiphash-1-3 alternative (32-bit hashes)
# that should perform better than siphash-1-3 (64-bit hashes).
# On 32-bit systems, we prefer the halfsiphash-1-3 alternative (32-bit
# computations) that performs better than siphash-1-3 (64-bit computations).

# TODO: use flag?(:bits64) for Crystal > 0.23.1
{% if flag?(:x86_64) || flag?(:aarch64) %}
Expand Down Expand Up @@ -80,6 +80,11 @@ struct Crystal::Hasher
self
end

def slice(value : Bytes)
@siphash.update(value)
self
end

def class(value)
value.crystal_type_id.hash(self)
end
Expand Down
9 changes: 9 additions & 0 deletions src/slice.cr
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,15 @@ struct Slice(T)
nil
end

# See `Object#hash(hasher)`
def hash(hasher)
{% if T == UInt8 %}
hasher.slice(self)
{% else %}
super hasher
{% end %}
end

protected def check_writable
raise "Can't write to read-only Slice" if @read_only
end
Expand Down

0 comments on commit 7733d3e

Please sign in to comment.