#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
#![warn(missing_docs, missing_debug_implementations, rust_2018_idioms)]
#![doc(
html_favicon_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
)]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/smol-rs/smol/master/assets/images/logo_fullsize_transparent.png"
)]
extern crate alloc;
#[cfg_attr(feature = "std", path = "std.rs")]
#[cfg_attr(not(feature = "std"), path = "no_std.rs")]
mod sys;
mod notify;
use alloc::boxed::Box;
use core::borrow::Borrow;
use core::fmt;
use core::future::Future;
use core::mem::ManuallyDrop;
use core::pin::Pin;
use core::ptr;
use core::task::{Context, Poll, Waker};
#[cfg(all(feature = "std", not(target_family = "wasm")))]
use {
parking::{Parker, Unparker},
std::time::{Duration, Instant},
};
use sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
use sync::{Arc, WithMut};
use notify::{Internal, NotificationPrivate};
pub use notify::{IntoNotification, Notification};
pub mod prelude {
pub use crate::{IntoNotification, Notification};
}
struct Inner<T> {
notified: AtomicUsize,
list: sys::List<T>,
}
impl<T> Inner<T> {
fn new() -> Self {
Self {
notified: AtomicUsize::new(core::usize::MAX),
list: sys::List::new(),
}
}
}
pub struct Event<T = ()> {
inner: AtomicPtr<Inner<T>>,
}
unsafe impl<T: Send> Send for Event<T> {}
unsafe impl<T: Send> Sync for Event<T> {}
impl<T> core::panic::UnwindSafe for Event<T> {}
impl<T> core::panic::RefUnwindSafe for Event<T> {}
impl<T> fmt::Debug for Event<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.try_inner() {
Some(inner) => {
let notified_count = inner.notified.load(Ordering::Relaxed);
let total_count = match inner.list.total_listeners() {
Ok(total_count) => total_count,
Err(_) => {
return f
.debug_tuple("Event")
.field(&format_args!("<locked>"))
.finish()
}
};
f.debug_struct("Event")
.field("listeners_notified", ¬ified_count)
.field("listeners_total", &total_count)
.finish()
}
None => f
.debug_tuple("Event")
.field(&format_args!("<uninitialized>"))
.finish(),
}
}
}
impl Default for Event {
#[inline]
fn default() -> Self {
Self::new()
}
}
impl<T> Event<T> {
#[cfg(feature = "std")]
#[inline]
pub const fn with_tag() -> Self {
Self {
inner: AtomicPtr::new(ptr::null_mut()),
}
}
#[inline]
pub fn is_notified(&self) -> bool {
self.try_inner()
.map_or(false, |inner| inner.notified.load(Ordering::Acquire) > 0)
}
#[cold]
pub fn listen(&self) -> Pin<Box<EventListener<T>>> {
let mut listener = Box::pin(EventListener::new());
listener.as_mut().listen(self);
listener
}
#[inline]
pub fn notify(&self, notify: impl IntoNotification<Tag = T>) -> usize {
let notify = notify.into_notification();
notify.fence(notify::Internal::new());
if let Some(inner) = self.try_inner() {
let limit = if notify.is_additional(Internal::new()) {
core::usize::MAX
} else {
notify.count(Internal::new())
};
if inner.needs_notification(limit) {
return inner.notify(notify);
}
}
0
}
#[inline]
fn try_inner(&self) -> Option<&Inner<T>> {
let inner = self.inner.load(Ordering::Acquire);
unsafe { inner.as_ref() }
}
fn inner(&self) -> *const Inner<T> {
let mut inner = self.inner.load(Ordering::Acquire);
if inner.is_null() {
let new = Arc::new(Inner::<T>::new());
let new = Arc::into_raw(new) as *mut Inner<T>;
inner = self
.inner
.compare_exchange(inner, new, Ordering::AcqRel, Ordering::Acquire)
.unwrap_or_else(|x| x);
if inner.is_null() {
inner = new;
} else {
unsafe {
drop(Arc::from_raw(new));
}
}
}
inner
}
}
impl Event<()> {
#[inline]
pub const fn new() -> Self {
Self {
inner: AtomicPtr::new(ptr::null_mut()),
}
}
#[inline]
pub fn notify_relaxed(&self, n: usize) -> usize {
self.notify(n.relaxed())
}
#[inline]
pub fn notify_additional(&self, n: usize) -> usize {
self.notify(n.additional())
}
#[inline]
pub fn notify_additional_relaxed(&self, n: usize) -> usize {
self.notify(n.additional().relaxed())
}
}
impl<T> Drop for Event<T> {
#[inline]
fn drop(&mut self) {
self.inner.with_mut(|&mut inner| {
if !inner.is_null() {
unsafe {
drop(Arc::from_raw(inner));
}
}
})
}
}
pin_project_lite::pin_project! {
#[project(!Unpin)] pub struct EventListener<T = ()> {
#[pin]
listener: Listener<T, Arc<Inner<T>>>,
}
}
unsafe impl<T: Send> Send for EventListener<T> {}
unsafe impl<T: Send> Sync for EventListener<T> {}
impl<T> core::panic::UnwindSafe for EventListener<T> {}
impl<T> core::panic::RefUnwindSafe for EventListener<T> {}
impl<T> Default for EventListener<T> {
fn default() -> Self {
Self::new()
}
}
impl<T> fmt::Debug for EventListener<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EventListener")
.field("listening", &self.is_listening())
.finish()
}
}
impl<T> EventListener<T> {
pub fn new() -> Self {
Self {
listener: Listener {
event: None,
listener: None,
},
}
}
pub fn listen(mut self: Pin<&mut Self>, event: &Event<T>) {
let inner = {
let inner = event.inner();
unsafe { Arc::clone(&ManuallyDrop::new(Arc::from_raw(inner))) }
};
let ListenerProject {
event,
mut listener,
} = self.as_mut().project().listener.project();
if let Some(current_event) = event.as_ref() {
current_event.remove(listener.as_mut(), false);
}
let inner = event.insert(inner);
inner.insert(listener);
notify::full_fence();
}
pub fn is_listening(&self) -> bool {
self.listener.listener.is_some()
}
#[cfg(all(feature = "std", not(target_family = "wasm")))]
pub fn wait(self: Pin<&mut Self>) -> T {
self.listener().wait_internal(None).unwrap()
}
#[cfg(all(feature = "std", not(target_family = "wasm")))]
pub fn wait_timeout(self: Pin<&mut Self>, timeout: Duration) -> Option<T> {
self.listener()
.wait_internal(Instant::now().checked_add(timeout))
}
#[cfg(all(feature = "std", not(target_family = "wasm")))]
pub fn wait_deadline(self: Pin<&mut Self>, deadline: Instant) -> Option<T> {
self.listener().wait_internal(Some(deadline))
}
pub fn discard(self: Pin<&mut Self>) -> bool {
self.project().listener.discard()
}
#[inline]
pub fn listens_to(&self, event: &Event<T>) -> bool {
if let Some(inner) = &self.listener.event {
return ptr::eq::<Inner<T>>(&**inner, event.inner.load(Ordering::Acquire));
}
false
}
pub fn same_event(&self, other: &EventListener<T>) -> bool {
if let (Some(inner1), Some(inner2)) = (self.inner(), other.inner()) {
return ptr::eq::<Inner<T>>(&**inner1, &**inner2);
}
false
}
fn listener(self: Pin<&mut Self>) -> Pin<&mut Listener<T, Arc<Inner<T>>>> {
self.project().listener
}
fn inner(&self) -> Option<&Arc<Inner<T>>> {
self.listener.event.as_ref()
}
}
impl<T> Future for EventListener<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.listener().poll_internal(cx)
}
}
pin_project_lite::pin_project! {
#[project(!Unpin)]
#[project = ListenerProject]
struct Listener<T, B: Borrow<Inner<T>>>
where
B: Unpin,
{
event: Option<B>,
#[pin]
listener: Option<sys::Listener<T>>,
}
impl<T, B: Borrow<Inner<T>>> PinnedDrop for Listener<T, B>
where
B: Unpin,
{
fn drop(mut this: Pin<&mut Self>) {
let this = this.project();
if let Some(inner) = this.event {
(*inner).borrow().remove(this.listener, true);
}
}
}
}
unsafe impl<T: Send, B: Borrow<Inner<T>> + Unpin + Send> Send for Listener<T, B> {}
unsafe impl<T: Send, B: Borrow<Inner<T>> + Unpin + Sync> Sync for Listener<T, B> {}
impl<T, B: Borrow<Inner<T>> + Unpin> Listener<T, B> {
#[cfg(all(feature = "std", not(target_family = "wasm")))]
fn wait_internal(mut self: Pin<&mut Self>, deadline: Option<Instant>) -> Option<T> {
use std::cell::RefCell;
std::thread_local! {
static PARKER: RefCell<Option<(Parker, Task)>> = RefCell::new(None);
}
PARKER
.try_with({
let this = self.as_mut();
|parker| {
let mut pair = parker
.try_borrow_mut()
.expect("Shouldn't be able to borrow parker reentrantly");
let (parker, unparker) = pair.get_or_insert_with(|| {
let (parker, unparker) = parking::pair();
(parker, Task::Unparker(unparker))
});
this.wait_with_parker(deadline, parker, unparker.as_task_ref())
}
})
.unwrap_or_else(|_| {
let (parker, unparker) = parking::pair();
self.wait_with_parker(deadline, &parker, TaskRef::Unparker(&unparker))
})
}
#[cfg(all(feature = "std", not(target_family = "wasm")))]
fn wait_with_parker(
self: Pin<&mut Self>,
deadline: Option<Instant>,
parker: &Parker,
unparker: TaskRef<'_>,
) -> Option<T> {
let mut this = self.project();
let inner = (*this
.event
.as_ref()
.expect("must listen() on event listener before waiting"))
.borrow();
if let Some(tag) = inner.register(this.listener.as_mut(), unparker).notified() {
return Some(tag);
}
loop {
match deadline {
None => parker.park(),
Some(deadline) => {
let now = Instant::now();
if now >= deadline {
return inner
.remove(this.listener, false)
.expect("We never removed ourself from the list")
.notified();
}
parker.park_deadline(deadline);
}
}
if let Some(tag) = inner.register(this.listener.as_mut(), unparker).notified() {
return Some(tag);
}
}
}
fn discard(self: Pin<&mut Self>) -> bool {
let this = self.project();
if let Some(inner) = this.event.as_ref() {
(*inner)
.borrow()
.remove(this.listener, false)
.map_or(false, |state| state.is_notified())
} else {
false
}
}
fn poll_internal(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
let mut this = self.project();
let inner = match &this.event {
Some(inner) => (*inner).borrow(),
None => panic!(""),
};
match inner
.register(this.listener.as_mut(), TaskRef::Waker(cx.waker()))
.notified()
{
Some(tag) => {
Poll::Ready(tag)
}
None => {
Poll::Pending
}
}
}
}
#[derive(PartialEq)]
enum State<T> {
Created,
Notified {
additional: bool,
tag: T,
},
Task(Task),
NotifiedTaken,
}
impl<T> fmt::Debug for State<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Created => f.write_str("Created"),
Self::Notified { additional, .. } => f
.debug_struct("Notified")
.field("additional", additional)
.finish(),
Self::Task(_) => f.write_str("Task(_)"),
Self::NotifiedTaken => f.write_str("NotifiedTaken"),
}
}
}
impl<T> State<T> {
fn is_notified(&self) -> bool {
matches!(self, Self::Notified { .. } | Self::NotifiedTaken)
}
#[allow(unused)]
fn notified(self) -> Option<T> {
match self {
Self::Notified { tag, .. } => Some(tag),
Self::NotifiedTaken => panic!("listener was already notified but taken"),
_ => None,
}
}
}
#[derive(Debug, PartialEq)]
enum RegisterResult<T> {
Notified(T),
Registered,
NeverInserted,
}
impl<T> RegisterResult<T> {
fn notified(self) -> Option<T> {
match self {
Self::Notified(tag) => Some(tag),
Self::Registered => None,
Self::NeverInserted => panic!("listener was never inserted into the list"),
}
}
}
#[derive(Debug, Clone)]
enum Task {
Waker(Waker),
#[cfg(all(feature = "std", not(target_family = "wasm")))]
Unparker(Unparker),
}
impl Task {
fn as_task_ref(&self) -> TaskRef<'_> {
match self {
Self::Waker(waker) => TaskRef::Waker(waker),
#[cfg(all(feature = "std", not(target_family = "wasm")))]
Self::Unparker(unparker) => TaskRef::Unparker(unparker),
}
}
fn wake(self) {
match self {
Self::Waker(waker) => waker.wake(),
#[cfg(all(feature = "std", not(target_family = "wasm")))]
Self::Unparker(unparker) => {
unparker.unpark();
}
}
}
}
impl PartialEq for Task {
fn eq(&self, other: &Self) -> bool {
self.as_task_ref().will_wake(other.as_task_ref())
}
}
#[derive(Clone, Copy)]
enum TaskRef<'a> {
Waker(&'a Waker),
#[cfg(all(feature = "std", not(target_family = "wasm")))]
Unparker(&'a Unparker),
}
impl TaskRef<'_> {
#[allow(unreachable_patterns)]
fn will_wake(self, other: Self) -> bool {
match (self, other) {
(Self::Waker(a), Self::Waker(b)) => a.will_wake(b),
#[cfg(all(feature = "std", not(target_family = "wasm")))]
(Self::Unparker(_), Self::Unparker(_)) => {
false
}
_ => false,
}
}
fn into_task(self) -> Task {
match self {
Self::Waker(waker) => Task::Waker(waker.clone()),
#[cfg(all(feature = "std", not(target_family = "wasm")))]
Self::Unparker(unparker) => Task::Unparker(unparker.clone()),
}
}
}
mod sync {
pub(super) use core::cell;
#[cfg(not(feature = "portable-atomic"))]
pub(super) use alloc::sync::Arc;
#[cfg(not(feature = "portable-atomic"))]
pub(super) use core::sync::atomic;
#[cfg(feature = "portable-atomic")]
pub(super) use portable_atomic_crate as atomic;
#[cfg(feature = "portable-atomic")]
pub(super) use portable_atomic_util::Arc;
#[cfg(feature = "std")]
pub(super) use std::sync::{Mutex, MutexGuard};
pub(super) trait WithMut {
type Output;
fn with_mut<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Self::Output) -> R;
}
impl<T> WithMut for atomic::AtomicPtr<T> {
type Output = *mut T;
#[inline]
fn with_mut<F, R>(&mut self, f: F) -> R
where
F: FnOnce(&mut Self::Output) -> R,
{
f(self.get_mut())
}
}
}
fn __test_send_and_sync() {
fn _assert_send<T: Send>() {}
fn _assert_sync<T: Sync>() {}
_assert_send::<Event<()>>();
_assert_sync::<Event<()>>();
_assert_send::<EventListener<()>>();
_assert_sync::<EventListener<()>>();
}