lite_sync/
lib.rs

1//! # lite-sync
2//! 
3//! Lightweight, high-performance async synchronization primitives for Rust.
4//! 
5//! 轻量级、高性能的 Rust 异步同步原语库。
6//! 
7//! ## Overview / 概述
8//! 
9//! `lite-sync` provides a collection of optimized synchronization primitives designed for
10//! low latency and minimal allocations. These primitives are built from the ground up with
11//! performance in mind, offering alternatives to heavier standard library implementations.
12//! 
13//! `lite-sync` 提供了一系列优化的同步原语,专为低延迟和最小分配而设计。
14//! 这些原语从头开始构建,以性能为核心,为更重的标准库实现提供替代方案。
15//! 
16//! ## Key Features / 主要特性
17//! 
18//! - **Zero or minimal allocations**: Most primitives avoid heap allocations entirely
19//! - **Lock-free algorithms**: Using atomic operations for maximum concurrency
20//! - **Single-waiter optimization**: Specialized for common SPSC (Single Producer Single Consumer) patterns
21//! - **Inline storage**: Support for stack-allocated buffers to avoid heap allocations
22//! 
23//! - **零或最小分配**:大多数原语完全避免堆分配
24//! - **无锁算法**:使用原子操作实现最大并发性
25//! - **单等待者优化**:专为常见的 SPSC(单生产者单消费者)模式优化
26//! - **内联存储**:支持栈分配缓冲区以避免堆分配
27//! 
28//! ## Modules / 模块
29//! 
30//! ### [`oneshot`]
31//! 
32//! One-shot completion notification with customizable state.
33//! 
34//! 带有可自定义状态的一次性完成通知。
35//! 
36//! Perfect for signaling task completion with minimal overhead. Supports custom state types
37//! through the [`oneshot::State`] trait, allowing you to communicate not just "done" but
38//! also "how it finished" (success, failure, timeout, etc.).
39//! 
40//! 非常适合以最小开销发出任务完成信号。通过 [`oneshot::State`] trait 支持自定义状态类型,
41//! 允许您不仅传达"完成",还能传达"如何完成"(成功、失败、超时等)。
42//! 
43//! **Key optimizations / 关键优化**:
44//! - Zero Box allocation for waker storage / Waker 存储零 Box 分配
45//! - Direct `Future` implementation for ergonomic `.await` / 直接实现 `Future` 以支持便捷的 `.await`
46//! - Fast path for immediate completion / 立即完成的快速路径
47//! 
48//! ### [`spsc`]
49//! 
50//! High-performance async SPSC (Single Producer Single Consumer) channel.
51//! 
52//! 高性能异步 SPSC(单生产者单消费者)通道。
53//! 
54//! Built on `smallring` for efficient ring buffer operations with inline storage support.
55//! Type-safe enforcement of single producer/consumer semantics eliminates synchronization overhead.
56//! 
57//! 基于 `smallring` 构建,支持内联存储的高效环形缓冲区操作。
58//! 类型安全地强制单生产者/消费者语义,消除同步开销。
59//! 
60//! **Key optimizations / 关键优化**:
61//! - Zero-cost interior mutability using `UnsafeCell` / 使用 `UnsafeCell` 实现零成本内部可变性
62//! - Inline buffer support for small channels / 小容量通道的内联缓冲区支持
63//! - Batch send/receive operations / 批量发送/接收操作
64//! - Single-waiter notification / 单等待者通知
65//! 
66//! ### [`notify`]
67//! 
68//! Lightweight single-waiter notification primitive.
69//! 
70//! 轻量级单等待者通知原语。
71//! 
72//! Much lighter than `tokio::sync::Notify` when you only need to wake one task at a time.
73//! Ideal for internal synchronization in other primitives.
74//! 
75//! 当您每次只需唤醒一个任务时,比 `tokio::sync::Notify` 更轻量。
76//! 非常适合在其他原语中进行内部同步。
77//! 
78//! ### [`atomic_waker`]
79//! 
80//! Atomic waker storage with state machine synchronization.
81//! 
82//! 带有状态机同步的原子 waker 存储。
83//! 
84//! Based on Tokio's `AtomicWaker` but simplified for specific use cases.
85//! Provides safe concurrent access to a waker without Box allocation.
86//! 
87//! 基于 Tokio 的 `AtomicWaker` 但为特定用例简化。
88//! 提供对 waker 的安全并发访问,无需 Box 分配。
89//! 
90//! ### [`request_response`]
91//! 
92//! Bidirectional request-response channels.
93//! 
94//! 双向请求-响应通道。
95//! 
96//! Provides request-response communication patterns optimized for different use cases.
97//! Currently supports one-to-one communication where side A sends requests and side B
98//! must respond before A can send the next request. No buffer needed due to strict
99//! turn-taking.
100//! 
101//! 提供针对不同用例优化的请求-响应通信模式。
102//! 目前支持一对一通信,A方发送请求,B方必须响应后A方才能发送下一个请求。
103//! 由于严格的轮流机制,无需缓冲区。
104//! 
105//! **Key optimizations / 关键优化**:
106//! - Lock-free atomic state machine / 无锁原子状态机
107//! - Zero buffer allocation (strict request-response) / 零缓冲区分配(严格请求-响应)
108//! - Dual waker storage for both ends / 双端waker存储
109//! - Type-safe one-to-one communication / 类型安全的一对一通信
110//! 
111//! ## Examples / 示例
112//! 
113//! ### One-shot completion with custom state
114//! 
115//! ```
116//! use lite_sync::oneshot::lite::{State, Sender};
117//! 
118//! #[derive(Debug, Clone, Copy, PartialEq, Eq)]
119//! enum TaskResult {
120//!     Success,
121//!     Error,
122//! }
123//! 
124//! impl State for TaskResult {
125//!     fn to_u8(&self) -> u8 {
126//!         match self {
127//!             TaskResult::Success => 1,
128//!             TaskResult::Error => 2,
129//!         }
130//!     }
131//!     
132//!     fn from_u8(value: u8) -> Option<Self> {
133//!         match value {
134//!             1 => Some(TaskResult::Success),
135//!             2 => Some(TaskResult::Error),
136//!             _ => None,
137//!         }
138//!     }
139//!     
140//!     fn pending_value() -> u8 { 0 }
141//! }
142//! 
143//! # tokio_test::block_on(async {
144//! let (sender, receiver) = Sender::<TaskResult>::new();
145//! 
146//! tokio::spawn(async move {
147//!     // Do some work...
148//!     sender.notify(TaskResult::Success);
149//! });
150//! 
151//! let result = receiver.await;
152//! assert_eq!(result, TaskResult::Success);
153//! # });
154//! ```
155//! 
156//! ### SPSC channel with inline storage
157//! 
158//! ```
159//! use lite_sync::spsc::channel;
160//! use std::num::NonZeroUsize;
161//! 
162//! # tokio_test::block_on(async {
163//! // Channel with capacity 32, inline buffer size 8
164//! let (tx, rx) = channel::<i32, 8>(NonZeroUsize::new(32).unwrap());
165//! 
166//! tokio::spawn(async move {
167//!     for i in 0..10 {
168//!         tx.send(i).await.unwrap();
169//!     }
170//! });
171//! 
172//! let mut sum = 0;
173//! while let Some(value) = rx.recv().await {
174//!     sum += value;
175//! }
176//! assert_eq!(sum, 45); // 0+1+2+...+9
177//! # });
178//! ```
179//! 
180//! ### Single-waiter notification
181//! 
182//! ```
183//! use lite_sync::notify::SingleWaiterNotify;
184//! use std::sync::Arc;
185//! 
186//! # tokio_test::block_on(async {
187//! let notify = Arc::new(SingleWaiterNotify::new());
188//! let notify_clone = notify.clone();
189//! 
190//! tokio::spawn(async move {
191//!     // Do some work...
192//!     notify_clone.notify_one();
193//! });
194//! 
195//! notify.notified().await;
196//! # });
197//! ```
198//! 
199//! ### Request-response channel
200//! 
201//! ```
202//! use lite_sync::request_response::one_to_one::channel;
203//! 
204//! # tokio_test::block_on(async {
205//! let (side_a, side_b) = channel::<String, i32>();
206//! 
207//! // Side B: Echo server
208//! tokio::spawn(async move {
209//!     while let Ok(guard) = side_b.recv_request().await {
210//!         let response = guard.request().len() as i32;
211//!         guard.reply(response);
212//!     }
213//! });
214//! 
215//! // Side A: Send requests
216//! let len = side_a.request("Hello".to_string()).await.unwrap();
217//! assert_eq!(len, 5);
218//! # });
219//! ```
220//! 
221//! ## Safety / 安全性
222//! 
223//! All primitives use `unsafe` internally for performance but expose safe APIs.
224//! Safety is guaranteed through:
225//! 
226//! 所有原语在内部使用 `unsafe` 以提高性能,但暴露安全的 API。
227//! 安全性通过以下方式保证:
228//! 
229//! - Type system enforcement of single ownership (no `Clone` on SPSC endpoints)
230//! - Atomic state machines for synchronization
231//! - Careful ordering of atomic operations
232//! - Comprehensive test coverage including concurrent scenarios
233//! 
234//! - 类型系统强制单一所有权(SPSC 端点不实现 `Clone`)
235//! - 用于同步的原子状态机
236//! - 原子操作的仔细排序
237//! - 全面的测试覆盖,包括并发场景
238
239pub mod notify;
240pub mod atomic_waker;
241pub mod oneshot;
242pub mod spsc;
243pub mod request_response;