ACP: std::cell::{Ref,RefMut}::try_map (original) (raw)

Proposal

Problem statement

If the mapper function passed to RefMut::map is fallible, there is no way to pass the error out.

Motivating examples or use case

use std::cell::{self, RefCell}; use std::ops;

pub struct Connection(());

fn new_db() -> anyhow::Result { todo!() }

pub fn get_db( cell: &RefCell<Option>, ) -> anyhow::Result<impl ops::Deref<Target = Connection> + '_> { let borrow = cell.borrow_mut();

let mut err = None;
let ref_ = cell::RefMut::filter_map(borrow, |option| match option {
    Some(db) => Some(db),
    None => match new_db() {
        Ok(db) => Some(option.insert(db)),
        Err(e) => {
            err = Some(e);
            None
        }
    },
});

match (ref_, err) {
    (Ok(_), Some(_)) | (Err(_), None) => unreachable!(),
    (Ok(ref_), None) => Ok(ref_),
    (Err(_), Some(err)) => Err(err),
}

}

It is not possible to avoid the unreachable!() unwrap in the above scenario.

Solution sketch

Add a new associated function try_map to both cell::Ref and cell::RefMut:

impl<'b, T> Ref<'b, T> { pub fn try_map<U: ?Sized>( orig: Ref<'b, T>, f: impl for<'a> FnOnce(&'a T) -> impl Try< Output = &'a U, Residual: Residual<Ref<'b, U>>, >, ) -> Result<Ref<'b, U>>; }

impl<'b, T> RefMut<'b, T> { pub fn try_map<U: ?Sized>( orig: RefMut<'b, T>, f: impl for<'a> FnOnce(&'a mut T) -> impl Try< Output = &'a mut U, Residual: Residual<RefMut<'b, U>>, >, ) -> impl Try<Output = RefMut<'b, U>>; }

I am not sure if there is a simple way to express the lifetimes correctly in stable Rust.

Example use case:

use std::cell::{RefCell, Ref}; use std::str::Utf8Error;

let c = RefCell::new(vec![240, 159, 166, 128]); let b1: Ref<Vec> = c.borrow(); let b2: Result<Ref, Utf8Error> = Ref::try_map(b1, str::from_utf8); assert!(b2.is_ok_and(|s| s == "🦀"));

Alternatives

Instead of using Try trait, just expose an API based on Result<&U, E> -> Result<Ref<U>, E>.

This was previously brought up on IRLO.

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: