matklad / once_cell

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

Add `OnceCell::with_value` and improve `Clone` implementation #170

Closed a1phyr closed 2 years ago

a1phyr commented 2 years ago

This PR adds OnceCell::with_value to both sync::OnceCell and unsync::OnceCell. This enables creating an initialized OnceCell at compile time and/or without synchronization cost.

Additionally, this improve Clone implementations by removing a panicking branch, reducing synchronization cost and overriding clone_from implementation.

Closes #164

matklad commented 2 years ago

Hm, I am a bit torn here -- it feels like From is probably the best interface here. But that can't be const. On the other hand, const-creating a full OnceCell feels a bit odd. Do we have a real use-case for that? At the same time, the API does feel rather tidy.

:thinking: yeah, I guess, lets have this! The implementation looks good to me, but lets add a couple of tests to https://github.com/matklad/once_cell/blob/master/tests/it.rs to make sure the new API doesn't get broken by accident.

a1phyr commented 2 years ago

Actually, I didn't see the From implementation when I wrote this patch, so I wrote with_value for that, so I don't have a strong will to add this.

There might be a use-case for something like that, I guess (though very specific):

const fn get_some_value() -> Option<T> {
    /* ... */
}

static CELL: OnceCell<T> = match get_some_value() {
    Some(value) => OnceCell::with_value(value),
    None => OnceCell::new(),
};

I think the main benefit of this would be discoverability, which is not great today, as shown by the linked issue (and my own experience ^^').

bors[bot] commented 2 years ago

Build succeeded: