Skip to content

Commit b83fa9c

Browse files
committed
sync: Add const fn OnceCell::from_value
Signed-off-by: Jiahao XU <[email protected]>
1 parent 5d29bdf commit b83fa9c

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-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

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

152+
/// Creates a new `OnceCell` that contains the provided value.
153+
///
154+
/// This is equivalent to `<OnceCell<T> as From<T>>::from(value)`.
155+
///
156+
/// # Example
157+
///
158+
/// ```
159+
/// use tokio::sync::OnceCell;
160+
///
161+
/// static ONCE: OnceCell<u32> = OnceCell::const_new_with(1);
162+
///
163+
/// async fn get_global_integer() -> &'static u32 {
164+
/// ONCE.get_or_init(|| async {
165+
/// 1 + 1
166+
/// }).await
167+
/// }
168+
///
169+
/// #[tokio::main]
170+
/// async fn main() {
171+
/// let result = get_global_integer().await;
172+
/// assert_eq!(*result, 1);
173+
/// }
174+
/// ```
175+
#[cfg(not(all(loom, test)))]
176+
pub const fn const_new_with(value: T) -> Self {
177+
OnceCell {
178+
value_set: AtomicBool::new(true),
179+
value: UnsafeCell::new(MaybeUninit::new(value)),
180+
semaphore: Semaphore::const_new_closed(),
181+
}
182+
}
183+
152184
/// Creates a new empty `OnceCell` instance.
153185
///
154186
/// 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
@@ -190,6 +190,16 @@ impl Semaphore {
190190
}
191191
}
192192

193+
/// Creates a new closed semaphore with 0 permits.
194+
#[cfg(not(all(loom, test)))]
195+
pub(crate) const fn const_new_closed() -> Self {
196+
Self {
197+
ll_sem: ll::Semaphore::const_new_closed(),
198+
#[cfg(all(tokio_unstable, feature = "tracing"))]
199+
resource_span: tracing::Span::none(),
200+
}
201+
}
202+
193203
/// Returns the current number of available permits.
194204
pub fn available_permits(&self) -> usize {
195205
self.ll_sem.available_permits()

0 commit comments

Comments
 (0)