matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.84k stars 110 forks source link

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

Closed fogti closed 3 years ago

fogti commented 3 years ago

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
    }
}
matklad commented 3 years ago

this is to save code: there are two sync impls

fogti commented 3 years ago

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

matklad commented 3 years ago

Yeah, makes sense to do this.