Email me

Clippy lints / Correctness

Clippy lint · Correctness · checked with Clippy 0.1.99

clippy::impl_hash_borrow_with_str_and_bytes: the semantics of `Borrow<T>` around `Hash` can't be satisfied when both `Borrow<str>` and `Borrow<[u8]>` are implemented

What it meansThis lint is concerned with the semantics of Borrow and Hash for a type that implements all three of Hash, Borrow<str> and Borrow<[u8]> as it is impossible to satisfy the semantics of Borrow and Hash for both Borrow<str> and Borrow<[u8]>. It is in the correctness group and denied by default (the build fails).

What you see

error: the semantics of `Borrow<T>` around `Hash` can't be satisfied when both `Borrow<str>` and `Borrow<[u8]>` are implemented
  --> main.rs:10:6
   |
10 | impl Hash for ExampleType {
   |      ^^^^
   |
   = note: the `Borrow` semantics require that `Hash` must behave the same for all implementations of Borrow<T>
   = note: however, the hash implementations of a string (`str`) and the bytes of a string `[u8]` do not behave the same ...
   = note: ... as (`hash("abc") != hash("abc".as_bytes())`
   = help: consider either removing one of the  `Borrow` implementations (`Borrow<str>` or `Borrow<[u8]>`) ...
   = help: ... or not implementing `Hash` for this type
   = help: for further information visit https://rust-lang.github.io/rust-clippy/stable/index.html#impl_hash_borrow_with_str_and_bytes
   = note: `#[deny(clippy::impl_hash_borrow_with_str_and_bytes)]` on by default

Real output of Clippy 0.1.99 (Rust 1.99) on the example below. Names and line numbers in yours will differ.

Does it matter?

When providing implementations for Borrow<T>, one should consider whether the different implementations should act as facets or representations of the underlying type. Generic code typically uses Borrow<T> when it relies on the identical behavior of these additional trait implementations. These traits will likely appear as additional trait bounds. In particular Eq, Ord and Hash must be equivalent for borrowed and owned values: x.borrow() == y.borrow() should give the same result as x == y. It follows then that the following equivalence must hold: hash(x) == hash((x as Borrow<[u8]>).borrow()) == hash((x as Borrow<str>).borrow()) Unfortunately it doesn’t hold as hash("abc") != hash("abc".as_bytes()). This happens because the Hash impl for str passes an additional 0xFF byte to the hasher to avoid collisions. For example, given the tuples ("a", "bc"), and ("ab", "c"), the two tuples would have the same hash value if the 0xFF byte was not added.

Code that is almost certainly wrong. Denied by default: the build fails until you fix it or allow it.

How to fix it

Clippy does not fix this one automatically. Change the code by hand:

Flagged

use std::borrow::Borrow;
use std::hash::{Hash, Hasher};

struct ExampleType {
    data: String
}

impl Hash for ExampleType {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data.hash(state);
    }
}

impl Borrow<str> for ExampleType {
    fn borrow(&self) -> &str {
        &self.data
    }
}

impl Borrow<[u8]> for ExampleType {
    fn borrow(&self) -> &[u8] {
        self.data.as_bytes()
    }
}

Turn it off, or on

Allow it where it does not fit your code, as narrowly as you can:

On one item

#[allow(clippy::impl_hash_borrow_with_str_and_bytes)]
fn my_function() { /* ... */ }

Whole crate (Cargo.toml)

[lints.clippy]
impl_hash_borrow_with_str_and_bytes = "allow"

One run

cargo clippy -- -A clippy::impl-hash-borrow-with-str-and-bytes

The [lints] table needs Rust 1.74 or newer. In a workspace, put it under [workspace.lints.clippy] and add [lints] workspace = true to each member.

Correctnessgroup
denydefault level
nofixed by cargo clippy --fix
1.76.0added in Rust

Clippy's own documentation

What it does

This lint is concerned with the semantics of Borrow and Hash for a type that implements all three of Hash, Borrow<str> and Borrow<[u8]> as it is impossible to satisfy the semantics of Borrow and Hash for both Borrow<str> and Borrow<[u8]>.

Why is this bad?

When providing implementations for Borrow<T>, one should consider whether the different implementations should act as facets or representations of the underlying type. Generic code typically uses Borrow<T> when it relies on the identical behavior of these additional trait implementations. These traits will likely appear as additional trait bounds.

In particular Eq, Ord and Hash must be equivalent for borrowed and owned values: x.borrow() == y.borrow() should give the same result as x == y. It follows then that the following equivalence must hold: hash(x) == hash((x as Borrow<[u8]>).borrow()) == hash((x as Borrow<str>).borrow())

Unfortunately it doesn’t hold as hash("abc") != hash("abc".as_bytes()). This happens because the Hash impl for str passes an additional 0xFF byte to the hasher to avoid collisions. For example, given the tuples ("a", "bc"), and ("ab", "c"), the two tuples would have the same hash value if the 0xFF byte was not added.

Example

use std::borrow::Borrow;
use std::hash::{Hash, Hasher};

struct ExampleType {
    data: String
}

impl Hash for ExampleType {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.data.hash(state);
    }
}

impl Borrow<str> for ExampleType {
    fn borrow(&self) -> &str {
        &self.data
    }
}

impl Borrow<[u8]> for ExampleType {
    fn borrow(&self) -> &[u8] {
        self.data.as_bytes()
    }
}

As a consequence, hashing a &ExampleType and hashing the result of the two borrows will result in different values.

From the Clippy lint list (0.1.99), part of the Rust project, MIT or Apache-2.0. Official entry.

Related lints

All 847 Clippy lints · Rust compiler errors · Cargo.toml checker

Up next

Related lintclippy::erasing_opthis operation will always return zero. This is likely not the intended outcomeRead it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ