Skip to content

safer, more foolproof hash: make hash return an opaque value, and take that type as the second argument #57055

Open
@nsajko

Description

@nsajko

The hash doc string says:

only use the output of another hash function as the second argument

It'd be easy to enforce this with dispatch in v2, if hash returned an opaque type and took the same type as the second argument. If UInt isn't accepted as the second argument there's less potential for error and confusion.

Something like this:

"""
    HashValue

Constructed by [`hash`](@ref), opaque.
"""
struct HashValue
    v::UInt
    # there's no constructors and this function is not `public`
    global function new_hash_value(v::UInt)
        new(v)
    end
end

"""
    xor(::HashValue, ::HashValue)::HashValue

Combine two hash values in a symmetric manner.
"""
function xor(l::HashValue, r::HashValue)
    xor(l.v, r.v)
end

"""
    hash(::Any, ::HashValue)::HashValue

...
"""
function hash end

Currently a common practice that would break is seeding hash with UInt constants. This would have to be fixed by changing const seed = 0xdeadbeef to const seed = hash(0xdeadbeef). Perhaps a nullary method should be provided, turning this into const seed = hash()?

Metadata

Metadata

Assignees

No one assigned

    Labels

    breakingThis change will break codedesignDesign of APIs or of the language itselfhashingspeculativeWhether the change will be implemented is speculative

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions