Skip to content

ACP: std::cell::{Ref,RefMut}::try_map #586

Open
@SOF3

Description

@SOF3

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<Connection> { todo!() }

pub fn get_db(
    cell: &RefCell<Option<Connection>>,
) -> 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<u8>> = c.borrow();
let b2: Result<Ref<str>, 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>.

Links and related work

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

  • 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

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)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