async-broadcast-0.7.0/.cargo_vcs_info.json0000644000000001360000000000100141150ustar { "git": { "sha1": "1803434a2c89e067f99f743d872035c8324ba101" }, "path_in_vcs": "" }async-broadcast-0.7.0/.gitattributes000064400000000000000000000001021046102023000155710ustar 00000000000000# Auto detect text files and perform LF normalization * text=auto async-broadcast-0.7.0/.github/CODE_OF_CONDUCT.md000064400000000000000000000061521046102023000170500ustar 00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: - Using welcoming and inclusive language - Being respectful of differing viewpoints and experiences - Gracefully accepting constructive criticism - Focusing on what is best for the community - Showing empathy towards other community members Examples of unacceptable behavior by participants include: - The use of sexualized language or imagery and unwelcome sexual attention or advances - Trolling, insulting/derogatory comments, and personal or political attacks - Public or private harassment - Publishing others' private information, such as a physical or electronic address, without explicit permission - Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at yoshuawuyts@gmail.com, or through IRC. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html async-broadcast-0.7.0/.github/CONTRIBUTING.md000064400000000000000000000051771046102023000165100ustar 00000000000000# Contributing Contributions include code, documentation, answering user questions, running the project's infrastructure, and advocating for all types of users. The project welcomes all contributions from anyone willing to work in good faith with other contributors and the community. No contribution is too small and all contributions are valued. This guide explains the process for contributing to the project's GitHub Repository. - [Code of Conduct](#code-of-conduct) - [Bad Actors](#bad-actors) ## Code of Conduct The project has a [Code of Conduct](./CODE_OF_CONDUCT.md) that *all* contributors are expected to follow. This code describes the *minimum* behavior expectations for all contributors. As a contributor, how you choose to act and interact towards your fellow contributors, as well as to the community, will reflect back not only on yourself but on the project as a whole. The Code of Conduct is designed and intended, above all else, to help establish a culture within the project that allows anyone and everyone who wants to contribute to feel safe doing so. Should any individual act in any way that is considered in violation of the [Code of Conduct](./CODE_OF_CONDUCT.md), corrective actions will be taken. It is possible, however, for any individual to *act* in such a manner that is not in violation of the strict letter of the Code of Conduct guidelines while still going completely against the spirit of what that Code is intended to accomplish. Open, diverse, and inclusive communities live and die on the basis of trust. Contributors can disagree with one another so long as they trust that those disagreements are in good faith and everyone is working towards a common goal. ## Bad Actors All contributors to tacitly agree to abide by both the letter and spirit of the [Code of Conduct](./CODE_OF_CONDUCT.md). Failure, or unwillingness, to do so will result in contributions being respectfully declined. A *bad actor* is someone who repeatedly violates the *spirit* of the Code of Conduct through consistent failure to self-regulate the way in which they interact with other contributors in the project. In doing so, bad actors alienate other contributors, discourage collaboration, and generally reflect poorly on the project as a whole. Being a bad actor may be intentional or unintentional. Typically, unintentional bad behavior can be easily corrected by being quick to apologize and correct course *even if you are not entirely convinced you need to*. Giving other contributors the benefit of the doubt and having a sincere willingness to admit that you *might* be wrong is critical for any successful open collaboration. Don't be a bad actor. async-broadcast-0.7.0/.github/workflows/build-and-test.yaml000064400000000000000000000017611046102023000220070ustar 00000000000000name: Build and test on: push: branches: - master pull_request: jobs: build_and_test: runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest] rust: [nightly, beta, stable] steps: - uses: actions/checkout@v4 - name: Install latest ${{ matrix.rust }} uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.rust }} profile: minimal override: true - name: Run cargo check uses: actions-rs/cargo@v1 with: command: check args: --all --bins --examples --tests --all-features - name: Run cargo check (without dev-dependencies to catch missing feature flags) if: startsWith(matrix.rust, 'nightly') uses: actions-rs/cargo@v1 with: command: check args: -Z features=dev_dep - name: Run cargo test uses: actions-rs/cargo@v1 with: command: test async-broadcast-0.7.0/.github/workflows/lint.yaml000064400000000000000000000006741046102023000201430ustar 00000000000000name: Lint on: push: branches: - master pull_request: jobs: clippy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal components: clippy - uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} args: --all-features -- -W clippy::all async-broadcast-0.7.0/.github/workflows/security.yaml000064400000000000000000000004241046102023000210350ustar 00000000000000name: Security audit on: push: branches: - master pull_request: jobs: security_audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} async-broadcast-0.7.0/.gitignore000064400000000000000000000000421046102023000146710ustar 00000000000000target/ tmp/ Cargo.lock .DS_Store async-broadcast-0.7.0/CHANGELOG.md000064400000000000000000000031771046102023000145260ustar 00000000000000# Version 0.7.0 - **Breaking:** `Recv` and `Send` are now `!Unpin` to allow for future optimizations. - Port to event-listener v5.0. # Version 0.6.0 - Bump to event-listener v3.0.0. - Add smol-rs logo to docs. # Version 0.5.1 - Drop `parking_lot` dependency, in favor of sync primitives in std. # Version 0.5.0 - API to disable waiting for active receivers (#35). # Version 0.4.1 - Drop unneeded easy-parallel dep. - Bumb dependencies to the current versions. - Update `parking_lot` to 0.12.1. - fix incorrect documentation for `TrySendError::is_disconnected`. # Version 0.4.0 - Add `RecvError::Overflowed` for detecting missing messages. - Avoid overflows on 32- and 16-bit systems (#22). - Add overflow message count. - `Clone` impl of `Receiver` now properly duplicates it. - Add `Receiver::new_receiver`. - Add `Receiver::new_sender` and `Sender::new_receiver`, allowing generating senders from receivers and vice versa, respectively. - Switch to `parking_lot::RwLock` instead of `std::sync::Mutex`. # Version 0.3.4 - Avoid the last clone in `try_recv` (#18). - Add some basic benchmarks. # Version 0.3.3 - Close channel if the last receiver to drop is inactive. # Version 0.3.2 - Fix a underflow panic (#14). - Document difference with other broadcast APIs. # Version 0.3.1 - Channel API in InactiveReceiver (#11). - {Sender,Receiver}::inactive_receiver_count method. # Version 0.3.0 - overflow mode. - ability to modify channel capacity. - Inactive receivers (#2). - Document difference to `async-channel` crate (#6). # Version 0.2.0 - First real release. # Version 0.1.0 - Dummy release to get the name registered on crates.io. async-broadcast-0.7.0/Cargo.toml0000644000000026400000000000100121150ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "async-broadcast" version = "0.7.0" authors = [ "Stjepan Glavina ", "Yoshua Wuyts ", "Zeeshan Ali Khan ", ] description = "Async broadcast channels" documentation = "https://docs.rs/async-broadcast" readme = "README.md" keywords = [] categories = [] license = "MIT OR Apache-2.0" repository = "https://github.com/smol-rs/async-broadcast" [[bench]] name = "broadcast_bench" harness = false [dependencies.event-listener] version = "5.0.0" [dependencies.event-listener-strategy] version = "0.5.0" [dependencies.futures-core] version = "0.3.21" [dependencies.pin-project-lite] version = "0.2.13" [dev-dependencies.criterion] version = "0.3.5" [dev-dependencies.doc-comment] version = "0.3.3" [dev-dependencies.easy-parallel] version = "3.2.0" [dev-dependencies.futures-lite] version = "1.11.3" [dev-dependencies.futures-util] version = "0.3.21" [features] async-broadcast-0.7.0/Cargo.toml.orig000064400000000000000000000014051046102023000155740ustar 00000000000000[package] name = "async-broadcast" version = "0.7.0" license = "MIT OR Apache-2.0" repository = "https://github.com/smol-rs/async-broadcast" documentation = "https://docs.rs/async-broadcast" description = "Async broadcast channels" readme = "README.md" edition = "2018" keywords = [] categories = [] authors = [ "Stjepan Glavina ", "Yoshua Wuyts ", "Zeeshan Ali Khan ", ] [[bench]] harness = false name = "broadcast_bench" [features] [dependencies] event-listener = "5.0.0" event-listener-strategy = "0.5.0" futures-core = "0.3.21" pin-project-lite = "0.2.13" [dev-dependencies] criterion = "0.3.5" doc-comment = "0.3.3" easy-parallel = "3.2.0" futures-lite = "1.11.3" futures-util = "0.3.21" async-broadcast-0.7.0/LICENSE-APACHE000064400000000000000000000250051046102023000146330ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2020 Yoshua Wuyts Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. async-broadcast-0.7.0/LICENSE-MIT000064400000000000000000000020671046102023000143460ustar 00000000000000The MIT License (MIT) Copyright (c) 2020 Yoshua Wuyts Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. async-broadcast-0.7.0/README.md000064400000000000000000000126471046102023000141760ustar 00000000000000# async-broadcast [![Build](https://github.com/smol-rs/async-broadcast/workflows/Build%20and%20test/badge.svg)]( https://github.com/smol-rs/async-broadcast/actions) [![License](https://img.shields.io/badge/license-Apache--2.0_OR_MIT-blue.svg)]( https://github.com/smol-rs/async-broadcast) [![Cargo](https://img.shields.io/crates/v/async-broadcast.svg)]( https://crates.io/crates/async-broadcast) [![Documentation](https://docs.rs/async-broadcast/badge.svg)]( https://docs.rs/async-broadcast) An async multi-producer multi-consumer broadcast channel, where each consumer gets a clone of every message sent on the channel. For obvious reasons, the channel can only be used to broadcast types that implement `Clone`. A channel has the `Sender` and `Receiver` side. Both sides are cloneable and can be shared among multiple threads. When all `Sender`s or all `Receiver`s are dropped, the channel becomes closed. When a channel is closed, no more messages can be sent, but remaining messages can still be received. The channel can also be closed manually by calling `Sender::close()` or `Receiver::close()`. ## Examples ```rust use async_broadcast::{broadcast, TryRecvError}; use futures_lite::{future::block_on, stream::StreamExt}; block_on(async move { let (s1, mut r1) = broadcast(2); let s2 = s1.clone(); let mut r2 = r1.clone(); // Send 2 messages from two different senders. s1.broadcast(7).await.unwrap(); s2.broadcast(8).await.unwrap(); // Channel is now at capacity so sending more messages will result in an error. assert!(s2.try_broadcast(9).unwrap_err().is_full()); assert!(s1.try_broadcast(10).unwrap_err().is_full()); // We can use `recv` method of the `Stream` implementation to receive messages. assert_eq!(r1.next().await.unwrap(), 7); assert_eq!(r1.recv().await.unwrap(), 8); assert_eq!(r2.next().await.unwrap(), 7); assert_eq!(r2.recv().await.unwrap(), 8); // All receiver got all messages so channel is now empty. assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); // Drop both senders, which closes the channel. drop(s1); drop(s2); assert_eq!(r1.try_recv(), Err(TryRecvError::Closed)); assert_eq!(r2.try_recv(), Err(TryRecvError::Closed)); }) ``` ## Difference with `async-channel` This crate is similar to [`async-channel`] in that they both provide an MPMC channel but the main difference being that in `async-channel`, each message sent on the channel is only received by one of the receivers. `async-broadcast` on the other hand, delivers each message to every receiver (IOW broadcast) by cloning it for each receiver. [`async-channel`]: https://crates.io/crates/async-channel ## Difference with other broadcast crates * [`broadcaster`]: The main difference would be that `broadcaster` doesn't have a sender and receiver split and both sides use clones of the same BroadcastChannel instance. The messages are sent are sent to all channel clones. While this can work for many cases, the lack of sender and receiver split, means that often times, you'll find yourself having to drain the channel on the sending side yourself. * [`postage`]: this crate provides a [broadcast API][pba] similar to `async_broadcast`. However, it: - (at the time of this writing) duplicates [futures] API, which isn't ideal. - Does not support overflow mode nor has the concept of inactive receivers, so a slow or inactive receiver blocking the whole channel is not a solvable problem. - Provides all kinds of channels, which is generally good but if you just need a broadcast channel, `async_broadcast` is probably a better choice. * [`tokio::sync`]: Tokio's `sync` module provides a [broadcast channel][tbc] API. The differences here are: - While this implementation does provide [overflow mode][tom], it is the default behavior and not opt-in. - There is no equivalent of inactive receivers. - While it's possible to build tokio with only the `sync` module, it comes with other APIs that you may not need. [`broadcaster`]: https://crates.io/crates/broadcaster [`postage`]: https://crates.io/crates/postage [pba]: https://docs.rs/postage/0.4.1/postage/broadcast/fn.channel.html [futures]: https://crates.io/crates/futures [`tokio::sync`]: https://docs.rs/tokio/1.6.0/tokio/sync [tbc]: https://docs.rs/tokio/1.6.0/tokio/sync/broadcast/index.html [tom]: https://docs.rs/tokio/1.6.0/tokio/sync/broadcast/index.html#lagging ## Safety This crate uses ``#![deny(unsafe_code)]`` to ensure everything is implemented in 100% Safe Rust. ## Contributing Want to join us? Check out our ["Contributing" guide][contributing] and take a look at some of these issues: - [Issues labeled "good first issue"][good-first-issue] - [Issues labeled "help wanted"][help-wanted] [contributing]: https://github.com/smol-rs/async-broadcast/blob/master/.github/CONTRIBUTING.md [good-first-issue]: https://github.com/smol-rs/async-broadcast/labels/good%20first%20issue [help-wanted]: https://github.com/smol-rs/async-broadcast/labels/help%20wanted ## License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. async-broadcast-0.7.0/benches/broadcast_bench.rs000064400000000000000000000041301046102023000177610ustar 00000000000000use async_broadcast::broadcast; use criterion::{criterion_group, criterion_main, Criterion}; use futures_lite::future::block_on; pub fn broadcast_and_recv(c: &mut Criterion) { let (s, mut r1) = broadcast(1); let mut n = 0; c.bench_function("1 -> 1", |b| { b.iter(|| { block_on(async { s.broadcast(n).await.unwrap(); assert_eq!(r1.recv().await.unwrap(), n); n += 1; }) }) }); let mut r2 = r1.clone(); c.bench_function("1 -> 2", |b| { b.iter(|| { block_on(async { s.broadcast(n).await.unwrap(); assert_eq!(r1.recv().await.unwrap(), n); assert_eq!(r2.recv().await.unwrap(), n); n += 1; }) }) }); let mut r3 = r1.clone(); let mut r4 = r1.clone(); c.bench_function("1 -> 4", |b| { b.iter(|| { block_on(async { s.broadcast(n).await.unwrap(); assert_eq!(r1.recv().await.unwrap(), n); assert_eq!(r2.recv().await.unwrap(), n); assert_eq!(r3.recv().await.unwrap(), n); assert_eq!(r4.recv().await.unwrap(), n); n += 1; }) }) }); let mut r5 = r1.clone(); let mut r6 = r1.clone(); let mut r7 = r1.clone(); let mut r8 = r1.clone(); c.bench_function("1 -> 8", |b| { b.iter(|| { block_on(async { s.broadcast(n).await.unwrap(); assert_eq!(r1.recv().await.unwrap(), n); assert_eq!(r2.recv().await.unwrap(), n); assert_eq!(r3.recv().await.unwrap(), n); assert_eq!(r4.recv().await.unwrap(), n); assert_eq!(r5.recv().await.unwrap(), n); assert_eq!(r6.recv().await.unwrap(), n); assert_eq!(r7.recv().await.unwrap(), n); assert_eq!(r8.recv().await.unwrap(), n); n += 1; }) }) }); } criterion_group!(benches, broadcast_and_recv); criterion_main!(benches); async-broadcast-0.7.0/src/lib.rs000064400000000000000000001724021046102023000146160ustar 00000000000000//! Async broadcast channel //! //! An async multi-producer multi-consumer broadcast channel, where each consumer gets a clone of every //! message sent on the channel. For obvious reasons, the channel can only be used to broadcast types //! that implement [`Clone`]. //! //! A channel has the [`Sender`] and [`Receiver`] side. Both sides are cloneable and can be shared //! among multiple threads. //! //! When all `Sender`s or all `Receiver`s are dropped, the channel becomes closed. When a channel is //! closed, no more messages can be sent, but remaining messages can still be received. //! //! The channel can also be closed manually by calling [`Sender::close()`] or [`Receiver::close()`]. //! //! ## Examples //! //! ```rust //! use async_broadcast::{broadcast, TryRecvError}; //! use futures_lite::{future::block_on, stream::StreamExt}; //! //! block_on(async move { //! let (s1, mut r1) = broadcast(2); //! let s2 = s1.clone(); //! let mut r2 = r1.clone(); //! //! // Send 2 messages from two different senders. //! s1.broadcast(7).await.unwrap(); //! s2.broadcast(8).await.unwrap(); //! //! // Channel is now at capacity so sending more messages will result in an error. //! assert!(s2.try_broadcast(9).unwrap_err().is_full()); //! assert!(s1.try_broadcast(10).unwrap_err().is_full()); //! //! // We can use `recv` method of the `Stream` implementation to receive messages. //! assert_eq!(r1.next().await.unwrap(), 7); //! assert_eq!(r1.recv().await.unwrap(), 8); //! assert_eq!(r2.next().await.unwrap(), 7); //! assert_eq!(r2.recv().await.unwrap(), 8); //! //! // All receiver got all messages so channel is now empty. //! assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); //! assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); //! //! // Drop both senders, which closes the channel. //! drop(s1); //! drop(s2); //! //! assert_eq!(r1.try_recv(), Err(TryRecvError::Closed)); //! assert_eq!(r2.try_recv(), Err(TryRecvError::Closed)); //! }) //! ``` //! //! ## Difference with `async-channel` //! //! This crate is similar to [`async-channel`] in that they both provide an MPMC channel but the //! main difference being that in `async-channel`, each message sent on the channel is only received //! by one of the receivers. `async-broadcast` on the other hand, delivers each message to every //! receiver (IOW broadcast) by cloning it for each receiver. //! //! [`async-channel`]: https://crates.io/crates/async-channel //! //! ## Difference with other broadcast crates //! //! * [`broadcaster`]: The main difference would be that `broadcaster` doesn't have a sender and //! receiver split and both sides use clones of the same BroadcastChannel instance. The messages //! are sent are sent to all channel clones. While this can work for many cases, the lack of //! sender and receiver split, means that often times, you'll find yourself having to drain the //! channel on the sending side yourself. //! //! * [`postage`]: this crate provides a [broadcast API][pba] similar to `async_broadcast`. However, //! it: //! - (at the time of this writing) duplicates [futures] API, which isn't ideal. //! - Does not support overflow mode nor has the concept of inactive receivers, so a slow or //! inactive receiver blocking the whole channel is not a solvable problem. //! - Provides all kinds of channels, which is generally good but if you just need a broadcast //! channel, `async_broadcast` is probably a better choice. //! //! * [`tokio::sync`]: Tokio's `sync` module provides a [broadcast channel][tbc] API. The differences //! here are: //! - While this implementation does provide [overflow mode][tom], it is the default behavior and not //! opt-in. //! - There is no equivalent of inactive receivers. //! - While it's possible to build tokio with only the `sync` module, it comes with other APIs that //! you may not need. //! //! [`broadcaster`]: https://crates.io/crates/broadcaster //! [`postage`]: https://crates.io/crates/postage //! [pba]: https://docs.rs/postage/0.4.1/postage/broadcast/fn.channel.html //! [futures]: https://crates.io/crates/futures //! [`tokio::sync`]: https://docs.rs/tokio/1.6.0/tokio/sync //! [tbc]: https://docs.rs/tokio/1.6.0/tokio/sync/broadcast/index.html //! [tom]: https://docs.rs/tokio/1.6.0/tokio/sync/broadcast/index.html#lagging //! #![forbid(unsafe_code)] #![deny(missing_debug_implementations, nonstandard_style, rust_2018_idioms)] #![warn(rustdoc::missing_doc_code_examples, unreachable_pub)] #![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" )] #[cfg(doctest)] mod doctests { doc_comment::doctest!("../README.md"); } use std::collections::VecDeque; use std::convert::TryInto; use std::error; use std::fmt; use std::future::Future; use std::marker::PhantomPinned; use std::pin::Pin; use std::sync::{Arc, RwLock}; use std::task::{Context, Poll}; use event_listener::{Event, EventListener}; use event_listener_strategy::{easy_wrapper, EventListenerFuture}; use futures_core::{ready, stream::Stream}; use pin_project_lite::pin_project; /// Create a new broadcast channel. /// /// The created channel has space to hold at most `cap` messages at a time. /// /// # Panics /// /// Capacity must be a positive number. If `cap` is zero, this function will panic. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, TryRecvError, TrySendError}; /// /// let (s, mut r1) = broadcast(1); /// let mut r2 = r1.clone(); /// /// assert_eq!(s.broadcast(10).await, Ok(None)); /// assert_eq!(s.try_broadcast(20), Err(TrySendError::Full(20))); /// /// assert_eq!(r1.recv().await, Ok(10)); /// assert_eq!(r2.recv().await, Ok(10)); /// assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); /// assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); /// # }); /// ``` pub fn broadcast(cap: usize) -> (Sender, Receiver) { assert!(cap > 0, "capacity cannot be zero"); let inner = Arc::new(RwLock::new(Inner { queue: VecDeque::with_capacity(cap), capacity: cap, overflow: false, await_active: true, receiver_count: 1, inactive_receiver_count: 0, sender_count: 1, head_pos: 0, is_closed: false, send_ops: Event::new(), recv_ops: Event::new(), })); let s = Sender { inner: inner.clone(), }; let r = Receiver { inner, pos: 0, listener: None, }; (s, r) } #[derive(Debug)] struct Inner { queue: VecDeque<(T, usize)>, // We assign the same capacity to the queue but that's just specifying the minimum capacity and // the actual capacity could be anything. Hence the need to keep track of our own set capacity. capacity: usize, receiver_count: usize, inactive_receiver_count: usize, sender_count: usize, /// Send sequence number of the front of the queue head_pos: u64, overflow: bool, await_active: bool, is_closed: bool, /// Send operations waiting while the channel is full. send_ops: Event, /// Receive operations waiting while the channel is empty and not closed. recv_ops: Event, } impl Inner { /// Try receiving at the given position, returning either the element or a reference to it. /// /// Result is used here instead of Cow because we don't have a Clone bound on T. fn try_recv_at(&mut self, pos: &mut u64) -> Result, TryRecvError> { let i = match pos.checked_sub(self.head_pos) { Some(i) => i .try_into() .expect("Head position more than usize::MAX behind a receiver"), None => { let count = self.head_pos - *pos; *pos = self.head_pos; return Err(TryRecvError::Overflowed(count)); } }; let last_waiter; if let Some((_elt, waiters)) = self.queue.get_mut(i) { *pos += 1; *waiters -= 1; last_waiter = *waiters == 0; } else { debug_assert_eq!(i, self.queue.len()); if self.is_closed { return Err(TryRecvError::Closed); } else { return Err(TryRecvError::Empty); } } // If we read from the front of the queue and this is the last receiver reading it // we can pop the queue instead of cloning the message if last_waiter { // Only the first element of the queue should have 0 waiters assert_eq!(i, 0); // Remove the element from the queue, adjust space, and notify senders let elt = self.queue.pop_front().unwrap().0; self.head_pos += 1; if !self.overflow { // Notify 1 awaiting senders that there is now room. If there is still room in the // queue, the notified operation will notify another awaiting sender. self.send_ops.notify(1); } Ok(Ok(elt)) } else { Ok(Err(&self.queue[i].0)) } } /// Closes the channel and notifies all waiting operations. /// /// Returns `true` if this call has closed the channel and it was not closed already. fn close(&mut self) -> bool { if self.is_closed { return false; } self.is_closed = true; // Notify all waiting senders and receivers. self.send_ops.notify(usize::MAX); self.recv_ops.notify(usize::MAX); true } /// Set the channel capacity. /// /// There are times when you need to change the channel's capacity after creating it. If the /// `new_cap` is less than the number of messages in the channel, the oldest messages will be /// dropped to shrink the channel. fn set_capacity(&mut self, new_cap: usize) { self.capacity = new_cap; if new_cap > self.queue.capacity() { let diff = new_cap - self.queue.capacity(); self.queue.reserve(diff); } // Ensure queue doesn't have more than `new_cap` messages. if new_cap < self.queue.len() { let diff = self.queue.len() - new_cap; self.queue.drain(0..diff); self.head_pos += diff as u64; } } /// Close the channel if there aren't any receivers present anymore fn close_channel(&mut self) { if self.receiver_count == 0 && self.inactive_receiver_count == 0 { self.close(); } } } /// The sending side of the broadcast channel. /// /// Senders can be cloned and shared among threads. When all senders associated with a channel are /// dropped, the channel becomes closed. /// /// The channel can also be closed manually by calling [`Sender::close()`]. #[derive(Debug)] pub struct Sender { inner: Arc>>, } impl Sender { /// Returns the channel capacity. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::(5); /// assert_eq!(s.capacity(), 5); /// ``` pub fn capacity(&self) -> usize { self.inner.read().unwrap().capacity } /// Set the channel capacity. /// /// There are times when you need to change the channel's capacity after creating it. If the /// `new_cap` is less than the number of messages in the channel, the oldest messages will be /// dropped to shrink the channel. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError, TryRecvError}; /// /// let (mut s, mut r) = broadcast::(3); /// assert_eq!(s.capacity(), 3); /// s.try_broadcast(1).unwrap(); /// s.try_broadcast(2).unwrap(); /// s.try_broadcast(3).unwrap(); /// /// s.set_capacity(1); /// assert_eq!(s.capacity(), 1); /// assert_eq!(r.try_recv(), Err(TryRecvError::Overflowed(2))); /// assert_eq!(r.try_recv().unwrap(), 3); /// assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); /// s.try_broadcast(1).unwrap(); /// assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2))); /// /// s.set_capacity(2); /// assert_eq!(s.capacity(), 2); /// s.try_broadcast(2).unwrap(); /// assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2))); /// ``` pub fn set_capacity(&mut self, new_cap: usize) { self.inner.write().unwrap().set_capacity(new_cap); } /// If overflow mode is enabled on this channel. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::(5); /// assert!(!s.overflow()); /// ``` pub fn overflow(&self) -> bool { self.inner.read().unwrap().overflow } /// Set overflow mode on the channel. /// /// When overflow mode is set, broadcasting to the channel will succeed even if the channel is /// full. It achieves that by removing the oldest message from the channel. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError, TryRecvError}; /// /// let (mut s, mut r) = broadcast::(2); /// s.try_broadcast(1).unwrap(); /// s.try_broadcast(2).unwrap(); /// assert_eq!(s.try_broadcast(3), Err(TrySendError::Full(3))); /// s.set_overflow(true); /// assert_eq!(s.try_broadcast(3).unwrap(), Some(1)); /// assert_eq!(s.try_broadcast(4).unwrap(), Some(2)); /// /// assert_eq!(r.try_recv(), Err(TryRecvError::Overflowed(2))); /// assert_eq!(r.try_recv().unwrap(), 3); /// assert_eq!(r.try_recv().unwrap(), 4); /// assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); /// ``` pub fn set_overflow(&mut self, overflow: bool) { self.inner.write().unwrap().overflow = overflow; } /// If sender will wait for active receivers. /// /// If set to `false`, [`Send`] will resolve immediately with a [`SendError`]. Defaults to /// `true`. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, _) = broadcast::(5); /// assert!(s.await_active()); /// ``` pub fn await_active(&self) -> bool { self.inner.read().unwrap().await_active } /// Specify if sender will wait for active receivers. /// /// If set to `false`, [`Send`] will resolve immediately with a [`SendError`]. Defaults to /// `true`. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (mut s, mut r) = broadcast::(2); /// s.broadcast(1).await.unwrap(); /// /// let _ = r.deactivate(); /// s.set_await_active(false); /// assert!(s.broadcast(2).await.is_err()); /// # }); /// ``` pub fn set_await_active(&mut self, await_active: bool) { self.inner.write().unwrap().await_active = await_active; } /// Closes the channel. /// /// Returns `true` if this call has closed the channel and it was not closed already. /// /// The remaining messages can still be received. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r) = broadcast(1); /// s.broadcast(1).await.unwrap(); /// assert!(s.close()); /// /// assert_eq!(r.recv().await.unwrap(), 1); /// assert_eq!(r.recv().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn close(&self) -> bool { self.inner.write().unwrap().close() } /// Returns `true` if the channel is closed. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, r) = broadcast::<()>(1); /// assert!(!s.is_closed()); /// /// drop(r); /// assert!(s.is_closed()); /// # }); /// ``` pub fn is_closed(&self) -> bool { self.inner.read().unwrap().is_closed } /// Returns `true` if the channel is empty. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast(1); /// /// assert!(s.is_empty()); /// s.broadcast(1).await; /// assert!(!s.is_empty()); /// # }); /// ``` pub fn is_empty(&self) -> bool { self.inner.read().unwrap().queue.is_empty() } /// Returns `true` if the channel is full. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast(1); /// /// assert!(!s.is_full()); /// s.broadcast(1).await; /// assert!(s.is_full()); /// # }); /// ``` pub fn is_full(&self) -> bool { let inner = self.inner.read().unwrap(); inner.queue.len() == inner.capacity } /// Returns the number of messages in the channel. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast(2); /// assert_eq!(s.len(), 0); /// /// s.broadcast(1).await; /// s.broadcast(2).await; /// assert_eq!(s.len(), 2); /// # }); /// ``` pub fn len(&self) -> usize { self.inner.read().unwrap().queue.len() } /// Returns the number of receivers for the channel. /// /// This does not include inactive receivers. Use [`Sender::inactive_receiver_count`] if you /// are interested in that. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.receiver_count(), 1); /// let r = r.deactivate(); /// assert_eq!(s.receiver_count(), 0); /// /// let r2 = r.activate_cloned(); /// assert_eq!(r.receiver_count(), 1); /// assert_eq!(r.inactive_receiver_count(), 1); /// ``` pub fn receiver_count(&self) -> usize { self.inner.read().unwrap().receiver_count } /// Returns the number of inactive receivers for the channel. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.receiver_count(), 1); /// let r = r.deactivate(); /// assert_eq!(s.receiver_count(), 0); /// /// let r2 = r.activate_cloned(); /// assert_eq!(r.receiver_count(), 1); /// assert_eq!(r.inactive_receiver_count(), 1); /// ``` pub fn inactive_receiver_count(&self) -> usize { self.inner.read().unwrap().inactive_receiver_count } /// Returns the number of senders for the channel. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.sender_count(), 1); /// /// let s2 = s.clone(); /// assert_eq!(s.sender_count(), 2); /// # }); /// ``` pub fn sender_count(&self) -> usize { self.inner.read().unwrap().sender_count } /// Produce a new Receiver for this channel. /// /// The new receiver starts with zero messages available. This will not re-open the channel if /// it was closed due to all receivers being dropped. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r1) = broadcast(2); /// /// assert_eq!(s.broadcast(1).await, Ok(None)); /// /// let mut r2 = s.new_receiver(); /// /// assert_eq!(s.broadcast(2).await, Ok(None)); /// drop(s); /// /// assert_eq!(r1.recv().await, Ok(1)); /// assert_eq!(r1.recv().await, Ok(2)); /// assert_eq!(r1.recv().await, Err(RecvError::Closed)); /// /// assert_eq!(r2.recv().await, Ok(2)); /// assert_eq!(r2.recv().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn new_receiver(&self) -> Receiver { let mut inner = self.inner.write().unwrap(); inner.receiver_count += 1; Receiver { inner: self.inner.clone(), pos: inner.head_pos + inner.queue.len() as u64, listener: None, } } } impl Sender { /// Broadcasts a message on the channel. /// /// If the channel is full, this method waits until there is space for a message unless: /// /// 1. overflow mode (set through [`Sender::set_overflow`]) is enabled, in which case it removes /// the oldest message from the channel to make room for the new message. The removed message /// is returned to the caller. /// 2. this behavior is disabled using [`Sender::set_await_active`], in which case, it returns /// [`SendError`] immediately. /// /// If the channel is closed, this method returns an error. /// /// The future returned by this function is pinned to the heap. If the future being `Unpin` is /// not important to you, or if you just `.await` this future, use the [`broadcast_direct`] method /// instead. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, SendError}; /// /// let (s, r) = broadcast(1); /// /// assert_eq!(s.broadcast(1).await, Ok(None)); /// drop(r); /// assert_eq!(s.broadcast(2).await, Err(SendError(2))); /// # }); /// ``` pub fn broadcast(&self, msg: T) -> Pin>> { Box::pin(self.broadcast_direct(msg)) } /// Broadcasts a message on the channel without pinning the future to the heap. /// /// The future returned by this method is not `Unpin` and must be pinned before use. This is /// the desired behavior if you just `.await` on the future. For other uses cases, use the /// [`broadcast`] method instead. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, SendError}; /// /// let (s, r) = broadcast(1); /// /// assert_eq!(s.broadcast_direct(1).await, Ok(None)); /// drop(r); /// assert_eq!(s.broadcast_direct(2).await, Err(SendError(2))); /// # }); /// ``` pub fn broadcast_direct(&self, msg: T) -> Send<'_, T> { Send::_new(SendInner { sender: self, listener: None, msg: Some(msg), _pin: PhantomPinned, }) } /// Attempts to broadcast a message on the channel. /// /// If the channel is full, this method returns an error unless overflow mode (set through /// [`Sender::set_overflow`]) is enabled. If the overflow mode is enabled, it removes the /// oldest message from the channel to make room for the new message. The removed message /// is returned to the caller. /// /// If the channel is closed, this method returns an error. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError}; /// /// let (s, r) = broadcast(1); /// /// assert_eq!(s.try_broadcast(1), Ok(None)); /// assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2))); /// /// drop(r); /// assert_eq!(s.try_broadcast(3), Err(TrySendError::Closed(3))); /// ``` pub fn try_broadcast(&self, msg: T) -> Result, TrySendError> { let mut ret = None; let mut inner = self.inner.write().unwrap(); if inner.is_closed { return Err(TrySendError::Closed(msg)); } else if inner.receiver_count == 0 { assert!(inner.inactive_receiver_count != 0); return Err(TrySendError::Inactive(msg)); } else if inner.queue.len() == inner.capacity { if inner.overflow { // Make room by popping a message. ret = inner.queue.pop_front().map(|(m, _)| m); } else { return Err(TrySendError::Full(msg)); } } let receiver_count = inner.receiver_count; inner.queue.push_back((msg, receiver_count)); if ret.is_some() { inner.head_pos += 1; } // Notify all awaiting receive operations. inner.recv_ops.notify(usize::MAX); Ok(ret) } } impl Drop for Sender { fn drop(&mut self) { let mut inner = self.inner.write().unwrap(); inner.sender_count -= 1; if inner.sender_count == 0 { inner.close(); } } } impl Clone for Sender { fn clone(&self) -> Self { self.inner.write().unwrap().sender_count += 1; Sender { inner: self.inner.clone(), } } } /// The receiving side of a channel. /// /// Receivers can be cloned and shared among threads. When all (active) receivers associated with a /// channel are dropped, the channel becomes closed. You can deactivate a receiver using /// [`Receiver::deactivate`] if you would like the channel to remain open without keeping active /// receivers around. #[derive(Debug)] pub struct Receiver { inner: Arc>>, pos: u64, /// Listens for a send or close event to unblock this stream. listener: Option, } impl Receiver { /// Returns the channel capacity. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (_s, r) = broadcast::(5); /// assert_eq!(r.capacity(), 5); /// ``` pub fn capacity(&self) -> usize { self.inner.read().unwrap().capacity } /// Set the channel capacity. /// /// There are times when you need to change the channel's capacity after creating it. If the /// `new_cap` is less than the number of messages in the channel, the oldest messages will be /// dropped to shrink the channel. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError, TryRecvError}; /// /// let (s, mut r) = broadcast::(3); /// assert_eq!(r.capacity(), 3); /// s.try_broadcast(1).unwrap(); /// s.try_broadcast(2).unwrap(); /// s.try_broadcast(3).unwrap(); /// /// r.set_capacity(1); /// assert_eq!(r.capacity(), 1); /// assert_eq!(r.try_recv(), Err(TryRecvError::Overflowed(2))); /// assert_eq!(r.try_recv().unwrap(), 3); /// assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); /// s.try_broadcast(1).unwrap(); /// assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2))); /// /// r.set_capacity(2); /// assert_eq!(r.capacity(), 2); /// s.try_broadcast(2).unwrap(); /// assert_eq!(s.try_broadcast(2), Err(TrySendError::Full(2))); /// ``` pub fn set_capacity(&mut self, new_cap: usize) { self.inner.write().unwrap().set_capacity(new_cap); } /// If overflow mode is enabled on this channel. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (_s, r) = broadcast::(5); /// assert!(!r.overflow()); /// ``` pub fn overflow(&self) -> bool { self.inner.read().unwrap().overflow } /// Set overflow mode on the channel. /// /// When overflow mode is set, broadcasting to the channel will succeed even if the channel is /// full. It achieves that by removing the oldest message from the channel. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError, TryRecvError}; /// /// let (s, mut r) = broadcast::(2); /// s.try_broadcast(1).unwrap(); /// s.try_broadcast(2).unwrap(); /// assert_eq!(s.try_broadcast(3), Err(TrySendError::Full(3))); /// r.set_overflow(true); /// assert_eq!(s.try_broadcast(3).unwrap(), Some(1)); /// assert_eq!(s.try_broadcast(4).unwrap(), Some(2)); /// /// assert_eq!(r.try_recv(), Err(TryRecvError::Overflowed(2))); /// assert_eq!(r.try_recv().unwrap(), 3); /// assert_eq!(r.try_recv().unwrap(), 4); /// assert_eq!(r.try_recv(), Err(TryRecvError::Empty)); /// ``` pub fn set_overflow(&mut self, overflow: bool) { self.inner.write().unwrap().overflow = overflow; } /// If sender will wait for active receivers. /// /// If set to `false`, [`Send`] will resolve immediately with a [`SendError`]. Defaults to /// `true`. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (_, r) = broadcast::(5); /// assert!(r.await_active()); /// ``` pub fn await_active(&self) -> bool { self.inner.read().unwrap().await_active } /// Specify if sender will wait for active receivers. /// /// If set to `false`, [`Send`] will resolve immediately with a [`SendError`]. Defaults to /// `true`. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, mut r) = broadcast::(2); /// s.broadcast(1).await.unwrap(); /// /// r.set_await_active(false); /// let _ = r.deactivate(); /// assert!(s.broadcast(2).await.is_err()); /// # }); /// ``` pub fn set_await_active(&mut self, await_active: bool) { self.inner.write().unwrap().await_active = await_active; } /// Closes the channel. /// /// Returns `true` if this call has closed the channel and it was not closed already. /// /// The remaining messages can still be received. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r) = broadcast(1); /// s.broadcast(1).await.unwrap(); /// assert!(s.close()); /// /// assert_eq!(r.recv().await.unwrap(), 1); /// assert_eq!(r.recv().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn close(&self) -> bool { self.inner.write().unwrap().close() } /// Returns `true` if the channel is closed. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, r) = broadcast::<()>(1); /// assert!(!s.is_closed()); /// /// drop(r); /// assert!(s.is_closed()); /// # }); /// ``` pub fn is_closed(&self) -> bool { self.inner.read().unwrap().is_closed } /// Returns `true` if the channel is empty. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast(1); /// /// assert!(s.is_empty()); /// s.broadcast(1).await; /// assert!(!s.is_empty()); /// # }); /// ``` pub fn is_empty(&self) -> bool { self.inner.read().unwrap().queue.is_empty() } /// Returns `true` if the channel is full. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast(1); /// /// assert!(!s.is_full()); /// s.broadcast(1).await; /// assert!(s.is_full()); /// # }); /// ``` pub fn is_full(&self) -> bool { let inner = self.inner.read().unwrap(); inner.queue.len() == inner.capacity } /// Returns the number of messages in the channel. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast(2); /// assert_eq!(s.len(), 0); /// /// s.broadcast(1).await; /// s.broadcast(2).await; /// assert_eq!(s.len(), 2); /// # }); /// ``` pub fn len(&self) -> usize { self.inner.read().unwrap().queue.len() } /// Returns the number of receivers for the channel. /// /// This does not include inactive receivers. Use [`Receiver::inactive_receiver_count`] if you /// are interested in that. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.receiver_count(), 1); /// let r = r.deactivate(); /// assert_eq!(s.receiver_count(), 0); /// /// let r2 = r.activate_cloned(); /// assert_eq!(r.receiver_count(), 1); /// assert_eq!(r.inactive_receiver_count(), 1); /// ``` pub fn receiver_count(&self) -> usize { self.inner.read().unwrap().receiver_count } /// Returns the number of inactive receivers for the channel. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.receiver_count(), 1); /// let r = r.deactivate(); /// assert_eq!(s.receiver_count(), 0); /// /// let r2 = r.activate_cloned(); /// assert_eq!(r.receiver_count(), 1); /// assert_eq!(r.inactive_receiver_count(), 1); /// ``` pub fn inactive_receiver_count(&self) -> usize { self.inner.read().unwrap().inactive_receiver_count } /// Returns the number of senders for the channel. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.sender_count(), 1); /// /// let s2 = s.clone(); /// assert_eq!(s.sender_count(), 2); /// # }); /// ``` pub fn sender_count(&self) -> usize { self.inner.read().unwrap().sender_count } /// Downgrade to a [`InactiveReceiver`]. /// /// An inactive receiver is one that can not and does not receive any messages. Its only purpose /// is keep the associated channel open even when there are no (active) receivers. An inactive /// receiver can be upgraded into a [`Receiver`] using [`InactiveReceiver::activate`] or /// [`InactiveReceiver::activate_cloned`]. /// /// [`Sender::try_broadcast`] will return [`TrySendError::Inactive`] if only inactive /// receivers exists for the associated channel and [`Sender::broadcast`] will wait until an /// active receiver is available. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, TrySendError}; /// /// let (s, r) = broadcast(1); /// let inactive = r.deactivate(); /// assert_eq!(s.try_broadcast(10), Err(TrySendError::Inactive(10))); /// /// let mut r = inactive.activate(); /// assert_eq!(s.broadcast(10).await, Ok(None)); /// assert_eq!(r.recv().await, Ok(10)); /// # }); /// ``` pub fn deactivate(self) -> InactiveReceiver { // Drop::drop impl of Receiver will take care of `receiver_count`. self.inner.write().unwrap().inactive_receiver_count += 1; InactiveReceiver { inner: self.inner.clone(), } } } impl Receiver { /// Receives a message from the channel. /// /// If the channel is empty, this method waits until there is a message. /// /// If the channel is closed, this method receives a message or returns an error if there are /// no more messages. /// /// If this receiver has missed a message (only possible if overflow mode is enabled), then /// this method returns an error and readjusts its cursor to point to the first available /// message. /// /// The future returned by this function is pinned to the heap. If the future being `Unpin` is /// not important to you, or if you just `.await` this future, use the [`recv_direct`] method /// instead. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r1) = broadcast(1); /// let mut r2 = r1.clone(); /// /// assert_eq!(s.broadcast(1).await, Ok(None)); /// drop(s); /// /// assert_eq!(r1.recv().await, Ok(1)); /// assert_eq!(r1.recv().await, Err(RecvError::Closed)); /// assert_eq!(r2.recv().await, Ok(1)); /// assert_eq!(r2.recv().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn recv(&mut self) -> Pin>> { Box::pin(self.recv_direct()) } /// Receives a message from the channel without pinning the future to the heap. /// /// The future returned by this method is not `Unpin` and must be pinned before use. This is /// the desired behavior if you just `.await` on the future. For other uses cases, use the /// [`recv`] method instead. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r1) = broadcast(1); /// let mut r2 = r1.clone(); /// /// assert_eq!(s.broadcast(1).await, Ok(None)); /// drop(s); /// /// assert_eq!(r1.recv_direct().await, Ok(1)); /// assert_eq!(r1.recv_direct().await, Err(RecvError::Closed)); /// assert_eq!(r2.recv_direct().await, Ok(1)); /// assert_eq!(r2.recv_direct().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn recv_direct(&mut self) -> Recv<'_, T> { Recv::_new(RecvInner { receiver: self, listener: None, _pin: PhantomPinned, }) } /// Attempts to receive a message from the channel. /// /// If the channel is empty or closed, this method returns an error. /// /// If this receiver has missed a message (only possible if overflow mode is enabled), then /// this method returns an error and readjusts its cursor to point to the first available /// message. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, TryRecvError}; /// /// let (s, mut r1) = broadcast(1); /// let mut r2 = r1.clone(); /// assert_eq!(s.broadcast(1).await, Ok(None)); /// /// assert_eq!(r1.try_recv(), Ok(1)); /// assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); /// assert_eq!(r2.try_recv(), Ok(1)); /// assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); /// /// drop(s); /// assert_eq!(r1.try_recv(), Err(TryRecvError::Closed)); /// assert_eq!(r2.try_recv(), Err(TryRecvError::Closed)); /// # }); /// ``` pub fn try_recv(&mut self) -> Result { self.inner .write() .unwrap() .try_recv_at(&mut self.pos) .map(|cow| cow.unwrap_or_else(T::clone)) } /// Produce a new Sender for this channel. /// /// This will not re-open the channel if it was closed due to all senders being dropped. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s1, mut r) = broadcast(2); /// /// assert_eq!(s1.broadcast(1).await, Ok(None)); /// /// let mut s2 = r.new_sender(); /// /// assert_eq!(s2.broadcast(2).await, Ok(None)); /// drop(s1); /// drop(s2); /// /// assert_eq!(r.recv().await, Ok(1)); /// assert_eq!(r.recv().await, Ok(2)); /// assert_eq!(r.recv().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn new_sender(&self) -> Sender { self.inner.write().unwrap().sender_count += 1; Sender { inner: self.inner.clone(), } } /// Produce a new Receiver for this channel. /// /// Unlike [`Receiver::clone`], this method creates a new receiver that starts with zero /// messages available. This is slightly faster than a real clone. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r1) = broadcast(2); /// /// assert_eq!(s.broadcast(1).await, Ok(None)); /// /// let mut r2 = r1.new_receiver(); /// /// assert_eq!(s.broadcast(2).await, Ok(None)); /// drop(s); /// /// assert_eq!(r1.recv().await, Ok(1)); /// assert_eq!(r1.recv().await, Ok(2)); /// assert_eq!(r1.recv().await, Err(RecvError::Closed)); /// /// assert_eq!(r2.recv().await, Ok(2)); /// assert_eq!(r2.recv().await, Err(RecvError::Closed)); /// # }); /// ``` pub fn new_receiver(&self) -> Self { let mut inner = self.inner.write().unwrap(); inner.receiver_count += 1; Receiver { inner: self.inner.clone(), pos: inner.head_pos + inner.queue.len() as u64, listener: None, } } } impl Drop for Receiver { fn drop(&mut self) { let mut inner = self.inner.write().unwrap(); // Remove ourself from each item's counter loop { match inner.try_recv_at(&mut self.pos) { Ok(_) => continue, Err(TryRecvError::Overflowed(_)) => continue, Err(TryRecvError::Closed) => break, Err(TryRecvError::Empty) => break, } } inner.receiver_count -= 1; inner.close_channel(); } } impl Clone for Receiver { /// Produce a clone of this Receiver that has the same messages queued. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::{broadcast, RecvError}; /// /// let (s, mut r1) = broadcast(1); /// /// assert_eq!(s.broadcast(1).await, Ok(None)); /// drop(s); /// /// let mut r2 = r1.clone(); /// /// assert_eq!(r1.recv().await, Ok(1)); /// assert_eq!(r1.recv().await, Err(RecvError::Closed)); /// assert_eq!(r2.recv().await, Ok(1)); /// assert_eq!(r2.recv().await, Err(RecvError::Closed)); /// # }); /// ``` fn clone(&self) -> Self { let mut inner = self.inner.write().unwrap(); inner.receiver_count += 1; // increment the waiter count on all items not yet received by this object let n = self.pos.saturating_sub(inner.head_pos) as usize; for (_elt, waiters) in inner.queue.iter_mut().skip(n) { *waiters += 1; } Receiver { inner: self.inner.clone(), pos: self.pos, listener: None, } } } impl Stream for Receiver { type Item = T; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { loop { // If this stream is listening for events, first wait for a notification. if let Some(listener) = self.listener.as_mut() { ready!(Pin::new(listener).poll(cx)); self.listener = None; } loop { // Attempt to receive a message. match self.try_recv() { Ok(msg) => { // The stream is not blocked on an event - drop the listener. self.listener = None; return Poll::Ready(Some(msg)); } Err(TryRecvError::Closed) => { // The stream is not blocked on an event - drop the listener. self.listener = None; return Poll::Ready(None); } Err(TryRecvError::Overflowed(_)) => continue, Err(TryRecvError::Empty) => {} } // Receiving failed - now start listening for notifications or wait for one. match self.listener.as_mut() { None => { // Start listening and then try receiving again. self.listener = { let inner = self.inner.write().unwrap(); Some(inner.recv_ops.listen()) }; } Some(_) => { // Go back to the outer loop to poll the listener. break; } } } } } } impl futures_core::stream::FusedStream for Receiver { fn is_terminated(&self) -> bool { let inner = self.inner.read().unwrap(); inner.is_closed && inner.queue.is_empty() } } /// An error returned from [`Sender::broadcast()`]. /// /// Received because the channel is closed or no active receivers were present while `await-active` /// was set to `false` (See [`Sender::set_await_active`] for details). #[derive(PartialEq, Eq, Clone, Copy)] pub struct SendError(pub T); impl SendError { /// Unwraps the message that couldn't be sent. pub fn into_inner(self) -> T { self.0 } } impl error::Error for SendError {} impl fmt::Debug for SendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "SendError(..)") } } impl fmt::Display for SendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "sending into a closed channel") } } /// An error returned from [`Sender::try_broadcast()`]. #[derive(PartialEq, Eq, Clone, Copy)] pub enum TrySendError { /// The channel is full but not closed. Full(T), /// The channel is closed. Closed(T), /// There are currently no active receivers, only inactive ones. Inactive(T), } impl TrySendError { /// Unwraps the message that couldn't be sent. pub fn into_inner(self) -> T { match self { TrySendError::Full(t) => t, TrySendError::Closed(t) => t, TrySendError::Inactive(t) => t, } } /// Returns `true` if the channel is full but not closed. pub fn is_full(&self) -> bool { match self { TrySendError::Full(_) => true, TrySendError::Closed(_) | TrySendError::Inactive(_) => false, } } /// Returns `true` if the channel is closed. pub fn is_closed(&self) -> bool { match self { TrySendError::Full(_) | TrySendError::Inactive(_) => false, TrySendError::Closed(_) => true, } } /// Returns `true` if there are currently no active receivers, only inactive ones. pub fn is_disconnected(&self) -> bool { match self { TrySendError::Full(_) | TrySendError::Closed(_) => false, TrySendError::Inactive(_) => true, } } } impl error::Error for TrySendError {} impl fmt::Debug for TrySendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TrySendError::Full(..) => write!(f, "Full(..)"), TrySendError::Closed(..) => write!(f, "Closed(..)"), TrySendError::Inactive(..) => write!(f, "Inactive(..)"), } } } impl fmt::Display for TrySendError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TrySendError::Full(..) => write!(f, "sending into a full channel"), TrySendError::Closed(..) => write!(f, "sending into a closed channel"), TrySendError::Inactive(..) => write!(f, "sending into the void (no active receivers)"), } } } /// An error returned from [`Receiver::recv()`]. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum RecvError { /// The channel has overflowed since the last element was seen. Future recv operations will /// succeed, but some messages have been skipped. /// /// Contains the number of messages missed. Overflowed(u64), /// The channel is empty and closed. Closed, } impl error::Error for RecvError {} impl fmt::Display for RecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Overflowed(n) => write!(f, "receiving skipped {} messages", n), Self::Closed => write!(f, "receiving from an empty and closed channel"), } } } /// An error returned from [`Receiver::try_recv()`]. #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub enum TryRecvError { /// The channel has overflowed since the last element was seen. Future recv operations will /// succeed, but some messages have been skipped. Overflowed(u64), /// The channel is empty but not closed. Empty, /// The channel is empty and closed. Closed, } impl TryRecvError { /// Returns `true` if the channel is empty but not closed. pub fn is_empty(&self) -> bool { match self { TryRecvError::Empty => true, TryRecvError::Closed => false, TryRecvError::Overflowed(_) => false, } } /// Returns `true` if the channel is empty and closed. pub fn is_closed(&self) -> bool { match self { TryRecvError::Empty => false, TryRecvError::Closed => true, TryRecvError::Overflowed(_) => false, } } /// Returns `true` if this error indicates the receiver missed messages. pub fn is_overflowed(&self) -> bool { match self { TryRecvError::Empty => false, TryRecvError::Closed => false, TryRecvError::Overflowed(_) => true, } } } impl error::Error for TryRecvError {} impl fmt::Display for TryRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { TryRecvError::Empty => write!(f, "receiving from an empty channel"), TryRecvError::Closed => write!(f, "receiving from an empty and closed channel"), TryRecvError::Overflowed(n) => { write!(f, "receiving operation observed {} lost messages", n) } } } } easy_wrapper! { /// A future returned by [`Sender::broadcast()`]. #[derive(Debug)] #[must_use = "futures do nothing unless .awaited"] pub struct Send<'a, T: Clone>(SendInner<'a, T> => Result, SendError>); pub(crate) wait(); } pin_project! { #[derive(Debug)] struct SendInner<'a, T> { sender: &'a Sender, listener: Option, msg: Option, // Keeping this type `!Unpin` enables future optimizations. #[pin] _pin: PhantomPinned } } impl<'a, T: Clone> EventListenerFuture for SendInner<'a, T> { type Output = Result, SendError>; fn poll_with_strategy<'x, S: event_listener_strategy::Strategy<'x>>( self: Pin<&mut Self>, strategy: &mut S, context: &mut S::Context, ) -> Poll { let this = self.project(); loop { let msg = this.msg.take().unwrap(); let inner = &this.sender.inner; // Attempt to send a message. match this.sender.try_broadcast(msg) { Ok(msg) => { let inner = inner.write().unwrap(); if inner.queue.len() < inner.capacity { // Not full still, so notify the next awaiting sender. inner.send_ops.notify(1); } return Poll::Ready(Ok(msg)); } Err(TrySendError::Closed(msg)) => return Poll::Ready(Err(SendError(msg))), Err(TrySendError::Full(m)) => *this.msg = Some(m), Err(TrySendError::Inactive(m)) if inner.read().unwrap().await_active => { *this.msg = Some(m) } Err(TrySendError::Inactive(m)) => return Poll::Ready(Err(SendError(m))), } // Sending failed - now start listening for notifications or wait for one. match &this.listener { None => { // Start listening and then try sending again. let inner = inner.write().unwrap(); *this.listener = Some(inner.send_ops.listen()); } Some(_) => { // Wait for a notification. ready!(strategy.poll(this.listener, context)); *this.listener = None; } } } } } easy_wrapper! { /// A future returned by [`Receiver::recv()`]. #[derive(Debug)] #[must_use = "futures do nothing unless .awaited"] pub struct Recv<'a, T: Clone>(RecvInner<'a, T> => Result); pub(crate) wait(); } pin_project! { #[derive(Debug)] struct RecvInner<'a, T> { receiver: &'a mut Receiver, listener: Option, // Keeping this type `!Unpin` enables future optimizations. #[pin] _pin: PhantomPinned } } impl<'a, T: Clone> EventListenerFuture for RecvInner<'a, T> { type Output = Result; fn poll_with_strategy<'x, S: event_listener_strategy::Strategy<'x>>( self: Pin<&mut Self>, strategy: &mut S, context: &mut S::Context, ) -> Poll { let this = self.project(); loop { // Attempt to receive a message. match this.receiver.try_recv() { Ok(msg) => return Poll::Ready(Ok(msg)), Err(TryRecvError::Closed) => return Poll::Ready(Err(RecvError::Closed)), Err(TryRecvError::Overflowed(n)) => { return Poll::Ready(Err(RecvError::Overflowed(n))); } Err(TryRecvError::Empty) => {} } // Receiving failed - now start listening for notifications or wait for one. match &this.listener { None => { // Start listening and then try receiving again. *this.listener = { let inner = this.receiver.inner.write().unwrap(); Some(inner.recv_ops.listen()) }; } Some(_) => { // Wait for a notification. ready!(strategy.poll(this.listener, context)); *this.listener = None; } } } } } /// An inactive receiver. /// /// An inactive receiver is a receiver that is unable to receive messages. It's only useful for /// keeping a channel open even when no associated active receivers exist. #[derive(Debug)] pub struct InactiveReceiver { inner: Arc>>, } impl InactiveReceiver { /// Convert to an activate [`Receiver`]. /// /// Consumes `self`. Use [`InactiveReceiver::activate_cloned`] if you want to keep `self`. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError}; /// /// let (s, r) = broadcast(1); /// let inactive = r.deactivate(); /// assert_eq!(s.try_broadcast(10), Err(TrySendError::Inactive(10))); /// /// let mut r = inactive.activate(); /// assert_eq!(s.try_broadcast(10), Ok(None)); /// assert_eq!(r.try_recv(), Ok(10)); /// ``` pub fn activate(self) -> Receiver { self.activate_cloned() } /// Create an activate [`Receiver`] for the associated channel. /// /// # Examples /// /// ``` /// use async_broadcast::{broadcast, TrySendError}; /// /// let (s, r) = broadcast(1); /// let inactive = r.deactivate(); /// assert_eq!(s.try_broadcast(10), Err(TrySendError::Inactive(10))); /// /// let mut r = inactive.activate_cloned(); /// assert_eq!(s.try_broadcast(10), Ok(None)); /// assert_eq!(r.try_recv(), Ok(10)); /// ``` pub fn activate_cloned(&self) -> Receiver { let mut inner = self.inner.write().unwrap(); inner.receiver_count += 1; if inner.receiver_count == 1 { // Notify 1 awaiting senders that there is now a receiver. If there is still room in the // queue, the notified operation will notify another awaiting sender. inner.send_ops.notify(1); } Receiver { inner: self.inner.clone(), pos: inner.head_pos + inner.queue.len() as u64, listener: None, } } /// Returns the channel capacity. /// /// See [`Receiver::capacity`] documentation for examples. pub fn capacity(&self) -> usize { self.inner.read().unwrap().capacity } /// Set the channel capacity. /// /// There are times when you need to change the channel's capacity after creating it. If the /// `new_cap` is less than the number of messages in the channel, the oldest messages will be /// dropped to shrink the channel. /// /// See [`Receiver::set_capacity`] documentation for examples. pub fn set_capacity(&mut self, new_cap: usize) { self.inner.write().unwrap().set_capacity(new_cap); } /// If overflow mode is enabled on this channel. /// /// See [`Receiver::overflow`] documentation for examples. pub fn overflow(&self) -> bool { self.inner.read().unwrap().overflow } /// Set overflow mode on the channel. /// /// When overflow mode is set, broadcasting to the channel will succeed even if the channel is /// full. It achieves that by removing the oldest message from the channel. /// /// See [`Receiver::set_overflow`] documentation for examples. pub fn set_overflow(&mut self, overflow: bool) { self.inner.write().unwrap().overflow = overflow; } /// If sender will wait for active receivers. /// /// If set to `false`, [`Send`] will resolve immediately with a [`SendError`]. Defaults to /// `true`. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (_, r) = broadcast::(5); /// let r = r.deactivate(); /// assert!(r.await_active()); /// ``` pub fn await_active(&self) -> bool { self.inner.read().unwrap().await_active } /// Specify if sender will wait for active receivers. /// /// If set to `false`, [`Send`] will resolve immediately with a [`SendError`]. Defaults to /// `true`. /// /// # Examples /// /// ``` /// # futures_lite::future::block_on(async { /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::(2); /// s.broadcast(1).await.unwrap(); /// /// let mut r = r.deactivate(); /// r.set_await_active(false); /// assert!(s.broadcast(2).await.is_err()); /// # }); /// ``` pub fn set_await_active(&mut self, await_active: bool) { self.inner.write().unwrap().await_active = await_active; } /// Closes the channel. /// /// Returns `true` if this call has closed the channel and it was not closed already. /// /// The remaining messages can still be received. /// /// See [`Receiver::close`] documentation for examples. pub fn close(&self) -> bool { self.inner.write().unwrap().close() } /// Returns `true` if the channel is closed. /// /// See [`Receiver::is_closed`] documentation for examples. pub fn is_closed(&self) -> bool { self.inner.read().unwrap().is_closed } /// Returns `true` if the channel is empty. /// /// See [`Receiver::is_empty`] documentation for examples. pub fn is_empty(&self) -> bool { self.inner.read().unwrap().queue.is_empty() } /// Returns `true` if the channel is full. /// /// See [`Receiver::is_full`] documentation for examples. pub fn is_full(&self) -> bool { let inner = self.inner.read().unwrap(); inner.queue.len() == inner.capacity } /// Returns the number of messages in the channel. /// /// See [`Receiver::len`] documentation for examples. pub fn len(&self) -> usize { self.inner.read().unwrap().queue.len() } /// Returns the number of receivers for the channel. /// /// This does not include inactive receivers. Use [`InactiveReceiver::inactive_receiver_count`] /// if you're interested in that. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.receiver_count(), 1); /// let r = r.deactivate(); /// assert_eq!(s.receiver_count(), 0); /// /// let r2 = r.activate_cloned(); /// assert_eq!(r.receiver_count(), 1); /// assert_eq!(r.inactive_receiver_count(), 1); /// ``` pub fn receiver_count(&self) -> usize { self.inner.read().unwrap().receiver_count } /// Returns the number of inactive receivers for the channel. /// /// # Examples /// /// ``` /// use async_broadcast::broadcast; /// /// let (s, r) = broadcast::<()>(1); /// assert_eq!(s.receiver_count(), 1); /// let r = r.deactivate(); /// assert_eq!(s.receiver_count(), 0); /// /// let r2 = r.activate_cloned(); /// assert_eq!(r.receiver_count(), 1); /// assert_eq!(r.inactive_receiver_count(), 1); /// ``` pub fn inactive_receiver_count(&self) -> usize { self.inner.read().unwrap().inactive_receiver_count } /// Returns the number of senders for the channel. /// /// See [`Receiver::sender_count`] documentation for examples. pub fn sender_count(&self) -> usize { self.inner.read().unwrap().sender_count } } impl Clone for InactiveReceiver { fn clone(&self) -> Self { self.inner.write().unwrap().inactive_receiver_count += 1; InactiveReceiver { inner: self.inner.clone(), } } } impl Drop for InactiveReceiver { fn drop(&mut self) { let mut inner = self.inner.write().unwrap(); inner.inactive_receiver_count -= 1; inner.close_channel(); } } async-broadcast-0.7.0/tests/test.rs000064400000000000000000000215001046102023000153720ustar 00000000000000use std::{sync::mpsc, thread::sleep, time::Duration}; use async_broadcast::*; use futures_util::{future::join, stream::StreamExt}; use easy_parallel::Parallel; use futures_lite::future::block_on; fn ms(ms: u64) -> Duration { Duration::from_millis(ms) } #[test] fn basic_sync() { let (s, mut r1) = broadcast(10); let mut r2 = r1.clone(); s.try_broadcast(7).unwrap(); assert_eq!(r1.try_recv().unwrap(), 7); assert_eq!(r2.try_recv().unwrap(), 7); let mut r3 = r1.clone(); s.try_broadcast(8).unwrap(); assert_eq!(r1.try_recv().unwrap(), 8); assert_eq!(r2.try_recv().unwrap(), 8); assert_eq!(r3.try_recv().unwrap(), 8); } #[test] fn basic_async() { block_on(async { let (s, mut r1) = broadcast(10); let mut r2 = r1.clone(); s.broadcast(7).await.unwrap(); assert_eq!(r1.recv().await.unwrap(), 7); assert_eq!(r2.recv().await.unwrap(), 7); // Now let's try the Stream impl. let mut r3 = r1.clone(); s.broadcast(8).await.unwrap(); assert_eq!(r1.next().await.unwrap(), 8); assert_eq!(r2.next().await.unwrap(), 8); assert_eq!(r3.next().await.unwrap(), 8); }); } #[test] fn parallel() { let (s1, mut r1) = broadcast(2); let s2 = s1.clone(); let mut r2 = r1.clone(); let (sender_sync_send, sender_sync_recv) = mpsc::channel(); let (receiver_sync_send, receiver_sync_recv) = mpsc::channel(); Parallel::new() .add(move || { sender_sync_recv.recv().unwrap(); s1.try_broadcast(7).unwrap(); s2.try_broadcast(8).unwrap(); assert!(s2.try_broadcast(9).unwrap_err().is_full()); assert!(s1.try_broadcast(10).unwrap_err().is_full()); receiver_sync_send.send(()).unwrap(); drop(s1); drop(s2); receiver_sync_send.send(()).unwrap(); }) .add(move || { assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); sender_sync_send.send(()).unwrap(); receiver_sync_recv.recv().unwrap(); assert_eq!(r1.try_recv().unwrap(), 7); assert_eq!(r1.try_recv().unwrap(), 8); assert_eq!(r2.try_recv().unwrap(), 7); assert_eq!(r2.try_recv().unwrap(), 8); receiver_sync_recv.recv().unwrap(); assert_eq!(r1.try_recv(), Err(TryRecvError::Closed)); assert_eq!(r2.try_recv(), Err(TryRecvError::Closed)); }) .run(); } #[test] fn parallel_async() { let (s1, mut r1) = broadcast(2); let s2 = s1.clone(); let mut r2 = r1.clone(); let (sender_sync_send, sender_sync_recv) = mpsc::channel(); let (receiver_sync_send, receiver_sync_recv) = mpsc::channel(); Parallel::new() .add(move || { block_on(async move { sender_sync_recv.recv().unwrap(); sleep(ms(5)); s1.broadcast(7).await.unwrap(); s2.broadcast(8).await.unwrap(); assert!(s2.try_broadcast(9).unwrap_err().is_full()); assert!(s1.try_broadcast(10).unwrap_err().is_full()); receiver_sync_send.send(()).unwrap(); s1.broadcast(9).await.unwrap(); s2.broadcast(10).await.unwrap(); drop(s1); drop(s2); receiver_sync_send.send(()).unwrap(); }) }) .add(move || { block_on(async move { assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); sender_sync_send.send(()).unwrap(); receiver_sync_recv.recv().unwrap(); assert_eq!(r1.next().await.unwrap(), 7); assert_eq!(r2.next().await.unwrap(), 7); assert_eq!(r1.recv().await.unwrap(), 8); assert_eq!(r2.recv().await.unwrap(), 8); receiver_sync_recv.recv().unwrap(); sleep(ms(5)); assert_eq!(r1.next().await.unwrap(), 9); assert_eq!(r2.next().await.unwrap(), 9); assert_eq!(r1.recv().await.unwrap(), 10); assert_eq!(r2.recv().await.unwrap(), 10); assert_eq!(r1.recv().await, Err(RecvError::Closed)); assert_eq!(r2.recv().await, Err(RecvError::Closed)); }) }) .run(); } #[test] fn channel_shrink() { let (s1, mut r1) = broadcast(4); let mut r2 = r1.clone(); let mut r3 = r1.clone(); let mut r4 = r1.clone(); s1.try_broadcast(1).unwrap(); s1.try_broadcast(2).unwrap(); s1.try_broadcast(3).unwrap(); s1.try_broadcast(4).unwrap(); assert_eq!(r2.try_recv().unwrap(), 1); assert_eq!(r2.try_recv().unwrap(), 2); assert_eq!(r3.try_recv().unwrap(), 1); assert_eq!(r3.try_recv().unwrap(), 2); assert_eq!(r3.try_recv().unwrap(), 3); assert_eq!(r4.try_recv().unwrap(), 1); assert_eq!(r4.try_recv().unwrap(), 2); assert_eq!(r4.try_recv().unwrap(), 3); assert_eq!(r4.try_recv().unwrap(), 4); r1.set_capacity(2); assert_eq!(r1.try_recv(), Err(TryRecvError::Overflowed(2))); assert_eq!(r1.try_recv().unwrap(), 3); assert_eq!(r1.try_recv().unwrap(), 4); assert_eq!(r1.try_recv(), Err(TryRecvError::Empty)); assert_eq!(r2.try_recv().unwrap(), 3); assert_eq!(r2.try_recv().unwrap(), 4); assert_eq!(r2.try_recv(), Err(TryRecvError::Empty)); assert_eq!(r3.try_recv().unwrap(), 4); assert_eq!(r3.try_recv(), Err(TryRecvError::Empty)); assert_eq!(r4.try_recv(), Err(TryRecvError::Empty)); } #[test] fn overflow() { let (s1, mut r1) = broadcast(2); r1.set_overflow(true); // We'll keep r1 as the lagging receiver. let mut r2 = r1.clone(); let mut r3 = r1.clone(); let (sender_sync_send, sender_sync_recv) = mpsc::channel(); Parallel::new() .add(move || { block_on(async move { s1.broadcast(7).await.unwrap(); s1.broadcast(8).await.unwrap(); sender_sync_recv.recv().unwrap(); sleep(ms(5)); s1.broadcast(9).await.unwrap(); sender_sync_recv.recv().unwrap(); }) }) .add(move || { block_on(async move { assert_eq!(r2.next().await.unwrap(), 7); assert_eq!(r2.recv().await.unwrap(), 8); sender_sync_send.send(()).unwrap(); assert_eq!(r2.next().await.unwrap(), 9); sender_sync_send.send(()).unwrap(); }) }) .add(move || { block_on(async move { assert_eq!(r3.next().await.unwrap(), 7); assert_eq!(r3.recv().await.unwrap(), 8); assert_eq!(r3.next().await.unwrap(), 9); }) }) .run(); assert_eq!(r1.try_recv(), Err(TryRecvError::Overflowed(1))); assert_eq!(r1.try_recv().unwrap(), 8); assert_eq!(r1.try_recv().unwrap(), 9); } #[test] fn open_channel() { let (s1, r) = broadcast(2); let inactive = r.deactivate(); let s2 = s1.clone(); let (receiver_sync_send, receiver_sync_recv) = mpsc::channel(); let (sender_sync_send, sender_sync_recv) = mpsc::channel(); Parallel::new() .add(move || { block_on(async move { receiver_sync_send.send(()).unwrap(); let (result1, result2) = join(s1.broadcast(7), s2.broadcast(8)).await; result1.unwrap(); result2.unwrap(); sender_sync_recv.recv().unwrap(); assert_eq!(s1.try_broadcast(9), Err(TrySendError::Inactive(9))); assert_eq!(s2.try_broadcast(10), Err(TrySendError::Inactive(10))); receiver_sync_send.send(()).unwrap(); sleep(ms(5)); s1.broadcast(9).await.unwrap(); s2.broadcast(10).await.unwrap(); }) }) .add(move || { block_on(async move { receiver_sync_recv.recv().unwrap(); sleep(ms(5)); let mut r = inactive.activate_cloned(); assert_eq!(r.next().await.unwrap(), 7); assert_eq!(r.recv().await.unwrap(), 8); drop(r); sender_sync_send.send(()).unwrap(); receiver_sync_recv.recv().unwrap(); let mut r = inactive.activate(); assert_eq!(r.recv().await.unwrap(), 9); assert_eq!(r.recv().await.unwrap(), 10); }) }) .run(); } #[test] fn inactive_drop() { let (s, active_receiver) = broadcast::<()>(1); let inactive = active_receiver.deactivate(); let inactive2 = inactive.clone(); drop(inactive); drop(inactive2); assert!(s.is_closed()) }