Skip to content

Commit 8955ed5

Browse files
authored
sync: add const fn OnceCell::from_value (#5903)
Signed-off-by: Jiahao XU <[email protected]>
1 parent bc26934 commit 8955ed5

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

tokio/src/sync/batch_semaphore.rs

+14
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,20 @@ impl Semaphore {
206206
}
207207
}
208208

209+
/// Creates a new closed semaphore with 0 permits.
210+
#[cfg(not(all(loom, test)))]
211+
pub(crate) const fn const_new_closed() -> Self {
212+
Self {
213+
permits: AtomicUsize::new(Self::CLOSED),
214+
waiters: Mutex::const_new(Waitlist {
215+
queue: LinkedList::new(),
216+
closed: true,
217+
}),
218+
#[cfg(all(tokio_unstable, feature = "tracing"))]
219+
resource_span: tracing::Span::none(),
220+
}
221+
}
222+
209223
/// Returns the current number of available permits.
210224
pub(crate) fn available_permits(&self) -> usize {
211225
self.permits.load(Acquire) >> Self::PERMIT_SHIFT

tokio/src/sync/once_cell.rs

+30
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,36 @@ impl<T> OnceCell<T> {
149149
}
150150
}
151151

152+
/// Creates a new `OnceCell` that contains the provided value.
153+
///
154+
/// # Example
155+
///
156+
/// ```
157+
/// use tokio::sync::OnceCell;
158+
///
159+
/// static ONCE: OnceCell<u32> = OnceCell::const_new_with(1);
160+
///
161+
/// async fn get_global_integer() -> &'static u32 {
162+
/// ONCE.get_or_init(|| async {
163+
/// 1 + 1
164+
/// }).await
165+
/// }
166+
///
167+
/// #[tokio::main]
168+
/// async fn main() {
169+
/// let result = get_global_integer().await;
170+
/// assert_eq!(*result, 1);
171+
/// }
172+
/// ```
173+
#[cfg(not(all(loom, test)))]
174+
pub const fn const_new_with(value: T) -> Self {
175+
OnceCell {
176+
value_set: AtomicBool::new(true),
177+
value: UnsafeCell::new(MaybeUninit::new(value)),
178+
semaphore: Semaphore::const_new_closed(),
179+
}
180+
}
181+
152182
/// Creates a new empty `OnceCell` instance.
153183
///
154184
/// Equivalent to `OnceCell::new`, except that it can be used in static

tokio/src/sync/semaphore.rs

+10
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,16 @@ impl Semaphore {
219219
}
220220
}
221221

222+
/// Creates a new closed semaphore with 0 permits.
223+
#[cfg(not(all(loom, test)))]
224+
pub(crate) const fn const_new_closed() -> Self {
225+
Self {
226+
ll_sem: ll::Semaphore::const_new_closed(),
227+
#[cfg(all(tokio_unstable, feature = "tracing"))]
228+
resource_span: tracing::Span::none(),
229+
}
230+
}
231+
222232
/// Returns the current number of available permits.
223233
pub fn available_permits(&self) -> usize {
224234
self.ll_sem.available_permits()

0 commit comments

Comments
 (0)