| Crates.io | announcement |
| lib.rs | announcement |
| version | 0.1.0 |
| created_at | 2025-10-14 02:30:55.339063+00 |
| updated_at | 2025-10-14 02:30:55.339063+00 |
| description | A runtime-agnostic oneshot broadcast channel |
| homepage | |
| repository | https://github.com/swaits/announcement |
| max_upload_size | |
| id | 1881509 |
| size | 766,541 |
A runtime-agnostic oneshot broadcast channel for Rust.
Broadcast a value once to multiple listeners with minimal overhead and zero data duplication when used with Arc<T>.
Arc<OnceLock> and event-listenerSub-microsecond operations with linear scaling
Critical recommendation: Use Arc<T> for types >64 bytes or with 3+ listeners for dramatic performance gains (up to 600x faster for large types).
📊 Full Performance Analysis → - Comprehensive benchmarks, scaling analysis, and optimization guide
Add this to your Cargo.toml:
[dependencies]
announcement = "0.1"
For tracing support:
[dependencies]
announcement = { version = "0.1", features = ["tracing"] }
For blocking-only (no std):
[dependencies]
announcement = { version = "0.1", default-features = false }
use announcement::Announcement;
#[tokio::main]
async fn main() {
// Create announcement channel
let (announcer, announcement) = Announcement::new();
// Create multiple listeners
let listener1 = announcement.listener();
let listener2 = announcement.listener();
// Spawn tasks that wait for the announcement
tokio::spawn(async move {
let value = listener1.listen().await;
println!("Listener 1 received: {}", value);
});
tokio::spawn(async move {
let value = listener2.listen().await;
println!("Listener 2 received: {}", value);
});
// Announce to all listeners at once
announcer.announce(42).unwrap();
}
The examples/ directory contains a progressive learning guide. Read these in order:
Each example is heavily documented with explanations, tips, and best practices. They're meant to be read and learned from, not just run.
After completing the guide, check out these real-world patterns:
Coordinate graceful shutdown of multiple worker tasks:
use announcement::Announcement;
#[tokio::main]
async fn main() {
let (shutdown_tx, shutdown_rx) = Announcement::new();
// Spawn workers with shutdown listeners
let worker = tokio::spawn({
let shutdown = shutdown_rx.listener();
async move {
loop {
tokio::select! {
_ = shutdown.listen() => {
println!("Shutting down gracefully...");
break;
}
_ = do_work() => {}
}
}
}
});
// Later: broadcast shutdown signal
shutdown_tx.announce(()).unwrap();
worker.await.unwrap();
}
async fn do_work() {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
Share initialized configuration to multiple workers using Arc for efficiency:
use announcement::Announcement;
use std::sync::Arc;
#[derive(Clone, Debug)]
struct Config {
database_url: String,
api_key: String,
}
#[tokio::main]
async fn main() {
let (config_tx, config_rx) = Announcement::new();
// Workers can start before config is ready
let worker = tokio::spawn({
let config_listener = config_rx.listener();
async move {
// Wait for config to be ready
let config = config_listener.listen().await;
println!("Worker received config: {:?}", config);
}
});
// Initialize config (takes time)
let config = Arc::new(Config {
database_url: "postgresql://localhost/db".to_string(),
api_key: "secret".to_string(),
});
// Broadcast to all workers (Arc is cloned, not the data)
config_tx.announce(config).unwrap();
worker.await.unwrap();
}
Signal when a resource is ready:
use announcement::Announcement;
use std::sync::Arc;
struct Database { /* ... */ }
impl Database {
async fn connect() -> Self {
// Expensive initialization
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Database { /* ... */ }
}
}
#[tokio::main]
async fn main() {
let (db_tx, db_rx) = Announcement::new();
// Services wait for database
let api_service = tokio::spawn({
let db = db_rx.listener();
async move {
let db = db.listen().await;
// Use database
}
});
// Initialize database
let db = Arc::new(Database::connect().await);
db_tx.announce(db).unwrap();
api_service.await.unwrap();
}
Use try_listen() to check without waiting:
use announcement::Announcement;
let (announcer, announcement) = Announcement::new();
let listener = announcement.listener();
// Check if value is ready
if let Some(value) = listener.try_listen() {
println!("Already announced: {}", value);
} else {
println!("Not announced yet");
}
announcer.announce(42).unwrap();
// Now it's available
assert_eq!(listener.try_listen(), Some(42));
Announcement<T> requires T: Clone. Each listener clones the value.
✓ For small types (< 16 bytes):
Announcement::<i32>::new()
Announcement::<(u64, u64)>::new()
✓ For Copy types:
Announcement::<f64>::new()
✓ For 1-2 listeners (clone cost amortized)
✓ For large types:
Announcement::<Arc<Vec<u8>>>::new() // Instead of Vec<u8>
✓ For expensive clones:
Announcement::<Arc<Config>>::new() // Config has String, Vec, HashMap
✓ For many listeners (3+):
let (tx, announcement) = Announcement::<Arc<Data>>::new();
// Create 1000 listeners - only 1 Data allocation!
Broadcasting 1MB data to 100 listeners:
See example 04 for detailed explanation.
Benchmarked on AMD Ryzen 7 7840U (8C/16T), 64GB RAM, Framework 13 laptop
| Operation | Time | Notes |
|---|---|---|
| Channel creation | ~150ns | 2 allocations |
| Listener creation | ~15ns | 2 Arc clones |
| Announce (no listeners) | ~30ns | Non-blocking |
| Announce (N listeners) | ~30ns + wakeup | O(N) wakeup |
| try_listen() hit | ~8ns | Lock-free read |
| try_listen() miss | ~5ns | Lock-free read |
| is_announced() | ~5ns | Lock-free read |
For large types (1MB) with 100 listeners:
| Method | Memory | Time | Speedup |
|---|---|---|---|
| Direct Clone | 100 MB | ~100ms | 1x |
| Arc Clone | 1 MB | ~500ns | 200,000x |
Rule of thumb: Use Arc<T> for:
Linear scaling O(N) for wakeup, constant O(1) for retrieval.
Run tests (recommended - faster):
cargo nextest run
Or with standard test runner:
cargo test
Test Coverage: 507+ tests covering:
tokio::sync::broadcast| Feature | announcement |
tokio::sync::broadcast |
|---|---|---|
| One-shot | Yes | No (multi-shot) |
| Runtime-agnostic | Yes | No (tokio only) |
| Bounded capacity | N/A (single value) | Yes |
| Lagging handling | N/A | Required |
| API complexity | Simple | More complex |
| Use case | One-time events | Continuous streams |
Use announcement when:
Use tokio::sync::broadcast when:
tokio::sync::oneshot| Feature | announcement |
tokio::sync::oneshot |
|---|---|---|
| Multiple receivers | Yes | No (1-to-1) |
| Runtime-agnostic | Yes | No (tokio only) |
| Cloneable receiver | Yes | No |
| Memory per listener | ~16 bytes | Full channel per pair |
Use announcement when:
Use tokio::sync::oneshot when:
Arc<OnceLock> + Eventannouncement provides a safe, ergonomic wrapper around this pattern with:
Contributions are welcome! Please see CODE_OF_CONDUCT.md for community guidelines.
This project is licensed under the MIT License.
Copyright (c) 2025 Stephen Waits steve@waits.net
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.