Closed daxpedda closed 11 months ago
Seconded. (I will say though that I am somewhat skeptical of this routine and it isn't clear that it pulls its weight. On the path to stabilization, I'd be interested in both how much this optimization buys us and how often it would be used.)
Proposal
Problem statement
I would like to insert a value into a
OnceCell/Lock
and get back a reference to it while also checking if the value was already set or not.Motivating examples or use cases
This can be useful in racy conditions, where different threads or
Future
s are trying to assign to the sameOnceCell/Lock
. The "loser" should be able to get the old and new value and determine if there is any difference or what that difference is.Solution sketch
Alternatives
This proposal offers an optimization, but it's perfectly possible to do this with the existing methods:
try_insert()
would offer an optimized path that doesn't require an additionalunwrap()
.This method is currently available in
once_cell
, which as far as I'm aware was the original inspiration forstd::cell::OnceCell
andstd::sync::OnceLock
.Links and related work
once_cell::unsync::OnceCell::try_insert()
once_cell::sync::OnceCell::try_insert()