rust-lang / libs-team

The home of the library team
Apache License 2.0
128 stars 19 forks source link

`RefCell::{try_replace, try_replace_with, try_swap}` #472

Closed daboross closed 3 weeks ago

daboross commented 1 month ago

Proposal

Problem statement

I'd like to have the full easy-to-access utility of RefCell without ever panicking. Specifically, the niche functions less used overall - replace, replace_with and swap, introduced in RFC 2057 and https://github.com/rust-lang/rust/pull/45819.

Motivating examples or use cases

Finding real use cases here has been hard - I suspect mostly because replace, replace_with and swap themselves aren't used that often.

With that said, I've found one piece of code that would/could have used replace, but didn't because of a no-panic requirement: https://github.com/diwic/thin_main_loop/blob/1bc33eeabf7893f7ac972ef7e27da60f8be8886f/src/mainloop.rs#L37-L47

Minimized,

use std::any::Any;
use std::cell::RefCell;
use std::panic::{catch_unwind, AssertUnwindSafe};

thread_local! {
    static CURRENT_PANIC: RefCell<Option<Box<dyn Any + Send + 'static>>>
            = Default::default();
}

pub fn ffi_wrapper<R, F: FnOnce() -> R>(f: F) -> Option<R> {
    match catch_unwind(AssertUnwindSafe(|| f())) {
        Ok(x) => Some(x),
        Err(e) => {
            CURRENT_PANIC.with(|p| {
                let _ = p.try_borrow_mut().map(|mut p| {
                    *p = Some(e);
                });
            });
            None
        }
    }
}

The try_borrow_mut() expression here is overly verbose, and seems like exactly what .replace() was built for. However, because of FFI, there's a no-panic requirement.

This is only a use case for try_replace, but it demonstrates the kind of problem I think this should address. It's quite niche, but RefCell::replace, replace_with and swap are relatively niche to begin with, so I believe that's appropriate.

Solution sketch

Introduce three new methods to RefCell, try_replace, try_replace_with and try_swap. These match the semantics of RefCell::replace, replace_with and swap respectively, except rather than panicking, all return a Result<T, BorrowMutError>.

I've written a PR that implements this, for demonstration: https://github.com/rust-lang/rust/pull/132011

Alternatives

I think the most obvious solution is deciding not to fix this problem. It's a niche use case, and we don't need to address it. The above code example works today, and is simply mildly overly verbose.

There are some other subtle design choices:

We could return different error types - providing a customized errors for each method, with more specific error text. This doesn't feel compelling to me, given the increased complexity it entails.

Along the same lines, we could have a special error for try_replace which includes the value given to the function, along the lines of std::string::FromUtf8Error. This would make the API strictly more useful, but again, add complication.

Links and related work

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):

Second, if there's a concrete solution:

Amanieu commented 3 weeks ago

We discussed this in the libs-api meeting. Fundamentally, these are helper functions: they don't enable anything that wasn't already possible before, they just make it less verbose. However in practice it's very rare not to know whether a RefCell is already borrowed. As such we don't think that there are sufficient use cases to justify the extended API.