Polishing Rust: Boxing and Unboxing Results

FWIW, I personally find the outer map_or harder to read than the outer if let because the body of the closure is long (it's basically the rest of the original function's body). So I don't actually like the end result better.

I think it would have been more beneficial to extract the call to graph_ahead_behind() into a variable instead, and reduce nesting by means of an early return. There's also map_err with which you could spare the branch.name()?.unwrap() and stick to the original error reporting approach:

fn get_branch_ahead_behind(&self, branch: Branch) -> anyhow::Result<AheadBehind> {
    let upstream = match branch.upstream() {
        Ok(upstream) => upstream,
        Err(_) => return Ok(NotTracking),
    };

    let ab = self.graph_ahead_behind(
        branch.get().target().unwrap(),
        upstream.get().target().unwrap(),
    );

    ab.map(|ab| match ab {
        (0, 0) => Ok(UpToDate),
        (ahead, 0) => Ahead(ahead),
        (0, behind) => Behind(behind),
        (ahead, behind) => AB(ahead, behind),
    }).map_err(|e| {
        anyhow!("Could not get upstream info: {}", e)
    })
}
1 Like