matklad / once_cell

Rust library for single assignment cells and lazy statics without macros

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

What's the difference between unsync::OnceCell::from and sync::OnceCell::from

fogti opened this issue · comments

Why is the unsync version initialized directly, but the sync version isn't?

unsync:

impl<T> From<T> for OnceCell<T> {
    fn from(value: T) -> Self {
        OnceCell { inner: UnsafeCell::new(Some(value)) }
    }
}

sync:

impl<T> From<T> for OnceCell<T> {
    fn from(value: T) -> Self {
        let cell = Self::new();
        cell.get_or_init(|| value);
        cell
    }
}

this is to save code: there are two sync impls

Couldn't appropriate From impls be added to the two sync impls? They would probably invoke far lesser code than currently (esp. as the code uses atomics and mutexes, which both interactions aren't required in that code path as there is only one owner which can access it).

Yeah, makes sense to do this.