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

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()?

Activity

added
breakingThis change will break code
designDesign of APIs or of the language itself
speculativeWhether the change will be implemented is speculative
on Jan 15, 2025
adienes

adienes commented on Jan 22, 2025

@adienes
Contributor

Currently a common practice that would break is seeding hash with UInt constants

what are the problems with this? that's not rhetorical I'm genuinely unaware of such constraints

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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

      safer, more foolproof `hash`: make `hash` return an opaque value, and take that type as the second argument · Issue #57055 · JuliaLang/julia