Skip to content

Commit

Permalink
Add Weak, a weak reference to a Channel
Browse files Browse the repository at this point in the history
  • Loading branch information
AldaronLau committed Aug 5, 2022
1 parent 9bedad2 commit 736d19f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://github.com/AldaronLau/semver).

## [0.5.0] - Unreleased
### Added
- `Weak` reference to a `Channel`

### Removed
- `Message`

Expand Down
28 changes: 27 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@

extern crate alloc;

use alloc::sync::Arc;
use alloc::sync::{self, Arc};
use core::{
cell::UnsafeCell,
future::Future,
Expand Down Expand Up @@ -271,6 +271,12 @@ impl<T: Send + Unpin, const S: usize, const R: usize> Channel<T, S, R> {
pub async fn recv(&mut self) -> T {
self.await
}

/// Create a new corresponding [`Weak`] channel.
#[inline]
pub fn downgrade(&self) -> Weak<T, S, R> {
Weak(Arc::downgrade(&self.0))
}
}

impl<T, const S: usize, const R: usize> Future for Channel<T, S, R>
Expand Down Expand Up @@ -327,6 +333,26 @@ where
}
}

/// A weak version of a `Channel`.
#[derive(Debug, Default)]
pub struct Weak<T: Send + Unpin, const S: usize = 1, const R: usize = 1>(
sync::Weak<Shared<T, S, R>>,
);

impl<T: Send + Unpin, const S: usize, const R: usize> Weak<T, S, R> {
/// Calling `upgrade()` will always return `None`.
#[inline]
pub fn new() -> Self {
Self(sync::Weak::new())
}

/// Attempt to upgrade the Weak channel to a [`Channel`].
#[inline]
pub fn upgrade(&self) -> Option<Channel<T, S, R>> {
Some(Channel(self.0.upgrade()?, usize::MAX))
}
}

/// A message in the process of being sent over a [`Channel`].
#[derive(Debug)]
struct Message<T: Send + Unpin, const S: usize, const R: usize>(
Expand Down

0 comments on commit 736d19f

Please sign in to comment.