Skip to content

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

Closed as not planned
Closed as not planned
@daboross

Description

@daboross

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 rust-lang/rust#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: rust-lang/rust#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):

  • 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions