From 736d19fdf73779242aca66b58d91269c1ae00970 Mon Sep 17 00:00:00 2001 From: Jeron Aldaron Lau Date: Fri, 5 Aug 2022 13:23:50 -0500 Subject: [PATCH] Add `Weak`, a weak reference to a `Channel` --- CHANGELOG.md | 3 +++ src/lib.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 988212e..bbfc6c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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` diff --git a/src/lib.rs b/src/lib.rs index a3b6b32..c008774 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -91,7 +91,7 @@ extern crate alloc; -use alloc::sync::Arc; +use alloc::sync::{self, Arc}; use core::{ cell::UnsafeCell, future::Future, @@ -271,6 +271,12 @@ impl Channel { pub async fn recv(&mut self) -> T { self.await } + + /// Create a new corresponding [`Weak`] channel. + #[inline] + pub fn downgrade(&self) -> Weak { + Weak(Arc::downgrade(&self.0)) + } } impl Future for Channel @@ -327,6 +333,26 @@ where } } +/// A weak version of a `Channel`. +#[derive(Debug, Default)] +pub struct Weak( + sync::Weak>, +); + +impl Weak { + /// 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> { + Some(Channel(self.0.upgrade()?, usize::MAX)) + } +} + /// A message in the process of being sent over a [`Channel`]. #[derive(Debug)] struct Message(