Description
openedon Jan 3, 2024
Proposal
Problem statement
As discussed in the 2024-01-03 T-lang triage meeting, equality for function pointers is awkward (due to "equal" functions being merged together or duplicated across different CGUs).
Motivating examples or use cases
fn a() {}
fn b() {}
fn main() {
assert_ne!(a as fn(), b as fn());
// ^- Depending a optimizations this may (and does) not always hold.
}
Solution sketch
In core::ptr
and std::ptr
:
/// Compares the *addresses* of the two function pointers for equality.
///
/// Function pointers comparisons can have surprising results since
/// they are never guaranteed to be unique and could vary between different
/// code generation units. Furthermore, different functions could have the
/// same address after being merged together.
///
/// This is the same as `f == g` but using this function makes clear
/// that you are aware of these potentially surprising semantics.
///
/// # Examples
///
/// ```
/// fn a() { println!("a"); }
/// fn b() { println!("b"); }
/// assert!(!std::ptr::fn_addr_eq(a as fn(), b as fn()));
/// ```
#[allow(unpredictable_function_pointer_comparisons)]
pub fn fn_addr_eq<T: FnPtr, U: FnPtr>(f: T, g: U) -> bool {
f.addr() == g.addr()
}
Alternatives
- Different name? Method instead of function?
Links and related work
rust-lang/rust#118833 a lint I'm trying to add to warn against functions pointers and T-lang decided that they want to recommend something that won't warn, similar to ptr::addr_eq
for thin pointer comparisons.
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.