Skip to content

HashMap and HashSet hash and compare a key by its bytes: two equal keys holding a str are two entries #2180

Closed

Description

@ehartford

§11.7 / §11.8 (Eq, Hash), D95 (structural types derive). Found implementing #2161 on main cbcbd51.

The runtime map (rt/rt_core.w hm_hash_key, hm_keys_eq) hashes and compares a key by its bytes unless the key is exactly str. Every other key that owns or views memory is compared by address:

use std.collections.HashSet
@[derive(Eq, Hash)]
type K { a: i32, s: str }
var s: HashSet[K] = HashSet.new()
s.insert(K { a: 1, s: "a".to_lower() })
s.insert(K { a: 1, s: "A".to_lower() })
print(s.len())                                   // 2, expected 1
print(s.contains(K { a: 1, s: "a".to_lower() }))  // false, expected true

The same for a tuple key (i32, str) and an Option[str] key (both print 2). A user impl Eq/impl Hash is never called either. Floats are wrong the same way (-0.0 == 0.0, different bytes).

Expected: a key is hashed by its Hash and compared by its Eq (#2137 made == structural; the map was left behind). Plan: the compiler passes per-key-type hash and equality functions to a new with_hashmap_new_keyed; a key whose bytes are its value (integers, bools, plain enums, records of those) keeps the byte path.

Activity

  1. ehartford commented on Oct 5, 2026

    @ehartford
    ContributorAuthor

    Worse than byte comparison: with_hashmap_new marks every 16-byte key as a str (hm_set_is_str_key(mi, if key_size == 16: 1 else: 0)), so HashSet[(i64, i64)] reads the first integer as a pointer. s.insert((5, 3)) exits with SIGSEGV (rc 139) on main cbcbd51.

  2. ehartford commented on Oct 5, 2026

    @ehartford
    ContributorAuthor

    Fixed on main by stack #2196 (merged as efb765c), battery green on a21e326; the regression test for it landed with the fix.

  3. added a commit that references this issue on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions