Indeterminate `HashSet::contains` behavior
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
use std::borrow::Borrow;
use std::collections::HashSet;
#[derive(PartialEq, Eq, Hash)]
struct Label(pub [u8; 7]);
impl Label {
pub fn new(x: &str) -> Self {
let mut bytes = x.bytes();
Label(std::array::from_fn(|_| bytes.next().unwrap()))
}
}
impl Borrow<str> for &Label {
fn borrow(&self) -> &str {
println!("───────────────────────────────────────────────────────────────────");
std::str::from_utf8(&self.0).unwrap()
}
}
impl Borrow<[u8]> for &Label {
fn borrow(&self) -> &[u8] {
&self.0
}
}
fn main() {
let labels = [
Label::new("label01"),
Label::new("label02"),
Label::new("label03"),
];
let mut hs = HashSet::new();
for i in 0..labels.len() {
hs.insert(&labels[i]);
}
println!("Contains -> {}", hs.contains(b"label01" as &[u8]));
println!("Contains -> {}", hs.contains("label01"));
}
I included an implementation of Borrow<[u8]> for &Label as a sanity check, but the main focus here is Borrow<str> for &Label.
I expected to see this happen:
For every run to print the long line "────", triggered by the .contains() call in the last line of main().
Instead, this happened:
The long line "────" is only printed on certain runs. It prints at about one in every 30 runs of cargo run.
Meta
rustc --version --verbose:
rustc 1.80.0 (051478957 2024-07-21)
binary: rustc
commit-hash: 051478957371ee0084a7c0913941d2a8c4757bb9
commit-date: 2024-07-21
host: aarch64-apple-darwin
release: 1.80.0
LLVM version: 18.1.7
Screenshot of trying `cargo run` multiple times
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the supplied Rust program and inspecting the HashSet::contains entry point, especially how Borrow and Borrow<[u8]> are selected for the stored references. Determine why the str lookup is intermittent, then add coverage for repeated lookups and verify that the expected Borrow behavior is consistent.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 35/100