Update rule.adoc
This commit is contained in:
parent
d6c25d095c
commit
b75de05030
@ -1,44 +1,41 @@
|
|||||||
FIXME: add a description
|
|
||||||
|
|
||||||
// If you want to factorize the description uncomment the following line and create the file.
|
|
||||||
//include::../description.adoc[]
|
|
||||||
|
|
||||||
== Why is this an issue?
|
== Why is this an issue?
|
||||||
|
|
||||||
FIXME: remove the unused optional headers (that are commented out)
|
When a type implements `Borrow<T>`, it should provide consistent behavior between the borrowed and owned values, especially regarding `Eq`, `Ord`, and `Hash`. However, `str` and `[u8]` have different Hash implementations, leading to inconsistent hash values for the same underlying data when accessed through different Borrow implementations. This violates the principle that `hash(x) == hash((x as Borrow<[u8]>).borrow()) == hash((x as Borrow<str>).borrow())` must hold, and can cause issues with hash-based collections and comparisons.
|
||||||
|
|
||||||
//=== What is the potential impact?
|
|
||||||
|
|
||||||
== How to fix it
|
|
||||||
//== How to fix it in FRAMEWORK NAME
|
|
||||||
|
|
||||||
=== Code examples
|
=== Code examples
|
||||||
|
|
||||||
==== Noncompliant code example
|
==== Noncompliant code example
|
||||||
|
|
||||||
[source,rust,diff-id=1,diff-type=noncompliant]
|
[source,rust]
|
||||||
----
|
----
|
||||||
FIXME
|
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); // Noncompliant: Inconsistent Hash
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Borrow<str> for ExampleType {
|
||||||
|
fn borrow(&self) -> &str {
|
||||||
|
&self.data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Borrow<[u8]> for ExampleType {
|
||||||
|
fn borrow(&self) -> &[u8] {
|
||||||
|
self.data.as_bytes()
|
||||||
|
}
|
||||||
|
}
|
||||||
----
|
----
|
||||||
|
|
||||||
==== Compliant solution
|
== Resources
|
||||||
|
=== Documentation
|
||||||
|
|
||||||
[source,rust,diff-id=1,diff-type=compliant]
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#impl_hash_borrow_with_str_and_bytes
|
||||||
----
|
|
||||||
FIXME
|
|
||||||
----
|
|
||||||
|
|
||||||
//=== How does this work?
|
|
||||||
|
|
||||||
//=== Pitfalls
|
|
||||||
|
|
||||||
//=== Going the extra mile
|
|
||||||
|
|
||||||
|
|
||||||
//== Resources
|
|
||||||
//=== Documentation
|
|
||||||
//=== Articles & blog posts
|
|
||||||
//=== Conference presentations
|
|
||||||
//=== Standards
|
|
||||||
//=== External coding guidelines
|
|
||||||
//=== Benchmarks
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user