mirror of
https://github.com/leptos-rs/leptos
synced 2025-02-02 23:13:25 +00:00
feat(callback): implement matches
method for Callback and UnsyncCallback (#3520)
* feat(callback): implement matches method for Callback and UnsyncCallback * [autofix.ci] apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
9cc8ee3c5a
commit
d4cbba7c63
1 changed files with 51 additions and 0 deletions
|
@ -80,6 +80,16 @@ impl<In, Out> UnsyncCallback<In, Out> {
|
|||
{
|
||||
Self(StoredValue::new_local(Rc::new(f)))
|
||||
}
|
||||
|
||||
/// Returns `true` if both callbacks wrap the same underlying function pointer.
|
||||
#[inline]
|
||||
pub fn matches(&self, other: &Self) -> bool {
|
||||
self.0.with_value(|self_value| {
|
||||
other
|
||||
.0
|
||||
.with_value(|other_value| Rc::ptr_eq(self_value, other_value))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<In: 'static, Out: 'static> Callable<In, Out> for UnsyncCallback<In, Out> {
|
||||
|
@ -212,6 +222,19 @@ impl<In: 'static, Out: 'static> Callback<In, Out> {
|
|||
{
|
||||
Self(StoredValue::new(Arc::new(fun)))
|
||||
}
|
||||
|
||||
/// Returns `true` if both callbacks wrap the same underlying function pointer.
|
||||
#[inline]
|
||||
pub fn matches(&self, other: &Self) -> bool {
|
||||
self.0
|
||||
.try_with_value(|self_value| {
|
||||
other.0.try_with_value(|other_value| {
|
||||
Arc::ptr_eq(self_value, other_value)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -246,4 +269,32 @@ mod tests {
|
|||
let _callback: UnsyncCallback<(i32, String), String> =
|
||||
(|num, s| format!("{num} {s}")).into();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_matches_same() {
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
let callback2 = callback1.clone();
|
||||
assert!(callback1.matches(&callback2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callback_matches_different() {
|
||||
let callback1 = Callback::new(|x: i32| x * 2);
|
||||
let callback2 = Callback::new(|x: i32| x + 1);
|
||||
assert!(!callback1.matches(&callback2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_matches_same() {
|
||||
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
|
||||
let callback2 = callback1.clone();
|
||||
assert!(callback1.matches(&callback2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsync_callback_matches_different() {
|
||||
let callback1 = UnsyncCallback::new(|x: i32| x * 2);
|
||||
let callback2 = UnsyncCallback::new(|x: i32| x + 1);
|
||||
assert!(!callback1.matches(&callback2));
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue