diwic / reffers-rs

Rust wrappers around references, boxes and Arcs.
68 stars 3 forks source link

ARef::map that can return error #3

Closed scottlamb closed 7 years ago

scottlamb commented 7 years ago

I've working on this code that does some lazy initialization of data reachable from my object. (I'm using a parking_lot::Once for this, fwiw.) It returns a reference that won't move...or it returns error. So I have this now:

let mp4 = ARefs::new(...);
...
// TODO: don't unwrap
Ok(mp4.map(|mp4| &mp4.get_lazily_initialized_thing().unwrap()[r]))

I'd love for ARefs::map (or something like it with a different name to maintain backward compatibility) to accept a function that can return error.

I could call my lazy initialization once before putting it into ARefs using ?, and then call it a second time through map with the unwrap. It'd be functionally similar but seems verbose and lame.

The function is currently:

pub fn map<V: ?Sized, F: FnOnce(&U) -> &V>(self, f: F) -> ARef<'a, V>

I'd like something like this:

pub fn map<V, F>(self, f: F) -> Result<ARef<'a, V>, E>
where V: ?Sized, F: FnOnce(&U) -> Result<&V, E>
diwic commented 7 years ago

I spent some time thinking about whether this could be generalized (to return other things than Results) but I think that kind of generalization requires HKT, so I implemented is as you wished. Enjoy!