Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Fn impl to Arc #89771

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1663,6 +1663,29 @@ impl Arc<dyn Any + Send + Sync> {
}
}

#[stable(feature = "arc_fn_impls", since = "1.57.0")]
impl<Args, F: Fn<Args> + ?Sized> FnOnce<Args> for Arc<F> {
type Output = <F as FnOnce<Args>>::Output;

extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
<F as Fn<Args>>::call(&self, args)
}
}

#[stable(feature = "arc_fn_impls", since = "1.57.0")]
impl<Args, F: Fn<Args> + ?Sized> FnMut<Args> for Arc<F> {
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
<F as Fn<Args>>::call(self, args)
}
}

#[stable(feature = "arc_fn_impls", since = "1.57.0")]
impl<Args, F: Fn<Args> + ?Sized> Fn<Args> for Arc<F> {
extern "rust-call" fn call(&self, args: Args) -> Self::Output {
<F as Fn<Args>>::call(self, args)
}
}

impl<T> Weak<T> {
/// Constructs a new `Weak<T>`, without allocating any memory.
/// Calling [`upgrade`] on the return value always gives [`None`].
Expand Down
37 changes: 37 additions & 0 deletions library/alloc/src/sync/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -618,3 +618,40 @@ fn test_arc_cyclic_two_refs() {
assert_eq!(Arc::strong_count(&two_refs), 3);
assert_eq!(Arc::weak_count(&two_refs), 2);
}

#[test]
fn test_arc_fn() {
let f = || String::from("hello");
let f: Arc<dyn Fn() -> String> = Arc::new(f);

assert_eq!(quox(&f), "hello");
}

fn quox<F>(f: &F) -> String
where
F: Fn() -> String,
{
f()
}

#[test]
fn test_arc_fn2() {
fn apply_fn_once<T>(v: T, f: impl FnOnce(T)) {
f(v)
}
fn apply_fn_mut<T>(v: T, mut f: impl FnMut(T)) {
f(v)
}
fn apply_fn<T>(v: T, f: impl Fn(T)) {
f(v)
}

let x = Mutex::new(0);
let f = Arc::new(|v: i32| *x.lock().unwrap() += v);

apply_fn_once(1, f.clone());
apply_fn_mut(2, f.clone());
apply_fn(4, f.clone());

assert_eq!(*x.lock().unwrap(), 7);
}