Skip to content

Commit

Permalink
sync: add const fn OnceCell::from_value (#5903)
Browse files Browse the repository at this point in the history
Signed-off-by: Jiahao XU <Jiahao_XU@outlook.com>
  • Loading branch information
NobodyXu authored Aug 22, 2023
1 parent bc26934 commit 8955ed5
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 0 deletions.
14 changes: 14 additions & 0 deletions tokio/src/sync/batch_semaphore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,20 @@ impl Semaphore {
}
}

/// Creates a new closed semaphore with 0 permits.
#[cfg(not(all(loom, test)))]
pub(crate) const fn const_new_closed() -> Self {
Self {
permits: AtomicUsize::new(Self::CLOSED),
waiters: Mutex::const_new(Waitlist {
queue: LinkedList::new(),
closed: true,
}),
#[cfg(all(tokio_unstable, feature = "tracing"))]
resource_span: tracing::Span::none(),
}
}

/// Returns the current number of available permits.
pub(crate) fn available_permits(&self) -> usize {
self.permits.load(Acquire) >> Self::PERMIT_SHIFT
Expand Down
30 changes: 30 additions & 0 deletions tokio/src/sync/once_cell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,36 @@ impl<T> OnceCell<T> {
}
}

/// Creates a new `OnceCell` that contains the provided value.
///
/// # Example
///
/// ```
/// use tokio::sync::OnceCell;
///
/// static ONCE: OnceCell<u32> = OnceCell::const_new_with(1);
///
/// async fn get_global_integer() -> &'static u32 {
/// ONCE.get_or_init(|| async {
/// 1 + 1
/// }).await
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let result = get_global_integer().await;
/// assert_eq!(*result, 1);
/// }
/// ```
#[cfg(not(all(loom, test)))]
pub const fn const_new_with(value: T) -> Self {
OnceCell {
value_set: AtomicBool::new(true),
value: UnsafeCell::new(MaybeUninit::new(value)),
semaphore: Semaphore::const_new_closed(),
}
}

/// Creates a new empty `OnceCell` instance.
///
/// Equivalent to `OnceCell::new`, except that it can be used in static
Expand Down
10 changes: 10 additions & 0 deletions tokio/src/sync/semaphore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,16 @@ impl Semaphore {
}
}

/// Creates a new closed semaphore with 0 permits.
#[cfg(not(all(loom, test)))]
pub(crate) const fn const_new_closed() -> Self {
Self {
ll_sem: ll::Semaphore::const_new_closed(),
#[cfg(all(tokio_unstable, feature = "tracing"))]
resource_span: tracing::Span::none(),
}
}

/// Returns the current number of available permits.
pub fn available_permits(&self) -> usize {
self.ll_sem.available_permits()
Expand Down

0 comments on commit 8955ed5

Please sign in to comment.