mirror of
https://github.com/callumio/suck.git
synced 2026-03-21 22:18:10 +00:00
Compare commits
8 commits
46c72410af
...
e12ed6f4f5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e12ed6f4f5 | ||
| f62d8eebca | |||
| 8366421ede | |||
| 72b87fd6e0 | |||
| 79ad51772d | |||
| 863ca61215 | |||
| 56d0889b37 | |||
| 3e8a541daa |
13 changed files with 625 additions and 20 deletions
26
CHANGELOG.md
26
CHANGELOG.md
|
|
@ -6,6 +6,32 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
## [0.0.3] - 2026-03-04
|
||||
|
||||
### 🚀 Features
|
||||
|
||||
- Remove closed flag from ChannelState
|
||||
- Add internal constructor for `Sucker`/`Sourcer`
|
||||
- Implement asynchronous channel support with tokio integration
|
||||
|
||||
### 🐛 Bug Fixes
|
||||
|
||||
- Correct toolchain in flake
|
||||
|
||||
### 🚜 Refactor
|
||||
|
||||
- Move traits to sync module and update imports
|
||||
- Reorganize channel modules and implement async/sync structures
|
||||
|
||||
### 🧪 Testing
|
||||
|
||||
- Set_mut tests
|
||||
- Increase code coverage of failure paths
|
||||
|
||||
### ⚙️ Miscellaneous Tasks
|
||||
|
||||
- Remove unused traits module
|
||||
- Reorganize module exports for async and sync features
|
||||
## [0.0.2] - 2025-09-04
|
||||
|
||||
### 🚀 Features
|
||||
|
|
|
|||
10
Cargo.toml
10
Cargo.toml
|
|
@ -2,7 +2,7 @@
|
|||
name = "suck"
|
||||
description = "Suck data up through a channel"
|
||||
authors = ["Callum Leslie <git@cleslie.uk>"]
|
||||
version = "0.0.2"
|
||||
version = "0.0.3"
|
||||
edition = "2024"
|
||||
documentation = "https://docs.rs/suck"
|
||||
homepage = "https://github.com/callumio/suck"
|
||||
|
|
@ -18,20 +18,24 @@ thiserror = "2.0"
|
|||
flume = { version = "0.12", optional = true }
|
||||
crossbeam-channel = { version = "0.5", optional = true }
|
||||
arc-swap = "1.7.1"
|
||||
tokio = { version = "1.48", features = ["sync", "macros", "rt-multi-thread"], optional = true }
|
||||
async-trait = { version = "0.1", optional = true }
|
||||
|
||||
[features]
|
||||
default = ["all"]
|
||||
|
||||
sync = []
|
||||
async = []
|
||||
async = ["dep:async-trait"]
|
||||
|
||||
sync-std = ["sync"]
|
||||
sync-flume = ["sync", "dep:flume"]
|
||||
sync-crossbeam = ["sync", "dep:crossbeam-channel"]
|
||||
async-tokio = ["async", "dep:tokio"]
|
||||
|
||||
all-sync = ["sync-std", "sync-flume", "sync-crossbeam"]
|
||||
all-async = ["async-tokio"]
|
||||
|
||||
all = ["all-sync"]
|
||||
all = ["all-sync", "all-async"]
|
||||
|
||||
[lib]
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +0,0 @@
|
|||
[toolchain]
|
||||
channel = "stable"
|
||||
profile = "default"
|
||||
196
src/asynchronous/channel.rs
Normal file
196
src/asynchronous/channel.rs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crate::asynchronous::traits::{AsyncChannelReceiver, AsyncChannelSender};
|
||||
use crate::error::Error;
|
||||
use crate::types::{ChannelState, Request, Response, ValueSource};
|
||||
|
||||
/// The consumer side of the channel that requests values asynchronously.
|
||||
pub struct AsyncSucker<T, ST, SR>
|
||||
where
|
||||
ST: AsyncChannelSender<Request>,
|
||||
SR: AsyncChannelReceiver<Response<T>>,
|
||||
{
|
||||
request_tx: ST,
|
||||
response_rx: SR,
|
||||
closed: AtomicBool,
|
||||
_phantom: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T, ST, SR> AsyncSucker<T, ST, SR>
|
||||
where
|
||||
ST: AsyncChannelSender<Request>,
|
||||
SR: AsyncChannelReceiver<Response<T>>,
|
||||
{
|
||||
pub(crate) fn new(request_tx: ST, response_rx: SR) -> Self {
|
||||
Self {
|
||||
request_tx,
|
||||
response_rx,
|
||||
closed: AtomicBool::new(false),
|
||||
_phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The producer side of the channel that provides values asynchronously.
|
||||
pub struct AsyncSourcer<T, SR, ST>
|
||||
where
|
||||
SR: AsyncChannelReceiver<Request>,
|
||||
ST: AsyncChannelSender<Response<T>>,
|
||||
{
|
||||
request_rx: SR,
|
||||
response_tx: ST,
|
||||
state: ChannelState<T>,
|
||||
_phantom: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T, SR, ST> AsyncSourcer<T, SR, ST>
|
||||
where
|
||||
SR: AsyncChannelReceiver<Request>,
|
||||
ST: AsyncChannelSender<Response<T>>,
|
||||
{
|
||||
pub(crate) fn new(request_rx: SR, response_tx: ST, state: ChannelState<T>) -> Self {
|
||||
Self {
|
||||
request_rx,
|
||||
response_tx,
|
||||
state,
|
||||
_phantom: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, SR, ST> AsyncSourcer<T, SR, ST>
|
||||
where
|
||||
T: Send + 'static,
|
||||
SR: AsyncChannelReceiver<Request>,
|
||||
ST: AsyncChannelSender<Response<T>>,
|
||||
{
|
||||
pub fn set_static(&self, val: T) -> Result<(), Error>
|
||||
where
|
||||
T: Clone,
|
||||
{
|
||||
self.state.swap(Arc::new(ValueSource::Static {
|
||||
val,
|
||||
clone: T::clone,
|
||||
}));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set<F>(&self, closure: F) -> Result<(), Error>
|
||||
where
|
||||
F: Fn() -> T + Send + Sync + 'static,
|
||||
{
|
||||
self.state
|
||||
.swap(Arc::new(ValueSource::Dynamic(Box::new(closure))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_mut<F>(&self, closure: F) -> Result<(), Error>
|
||||
where
|
||||
F: FnMut() -> T + Send + Sync + 'static,
|
||||
{
|
||||
self.state
|
||||
.swap(Arc::new(ValueSource::DynamicMut(Mutex::new(Box::new(
|
||||
closure,
|
||||
)))));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn close(&self) -> Result<(), Error> {
|
||||
self.state.swap(Arc::new(ValueSource::Cleared));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn run(self) -> Result<(), Error> {
|
||||
loop {
|
||||
match self.request_rx.recv().await {
|
||||
Ok(Request::GetValue) => {
|
||||
let response = self.handle_get_value()?;
|
||||
if self.response_tx.send(response).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(Request::Close) => {
|
||||
self.close()?;
|
||||
break;
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_get_value(&self) -> Result<Response<T>, Error> {
|
||||
let state = self.state.load();
|
||||
|
||||
match &**state {
|
||||
ValueSource::Static { val, clone } => {
|
||||
let value = self.execute_closure_safely(&mut || clone(val));
|
||||
match value {
|
||||
Ok(v) => Ok(Response::Value(v)),
|
||||
Err(_) => Ok(Response::NoSource),
|
||||
}
|
||||
}
|
||||
ValueSource::Dynamic(closure) => {
|
||||
let value = self.execute_closure_safely(&mut || closure());
|
||||
match value {
|
||||
Ok(v) => Ok(Response::Value(v)),
|
||||
Err(_) => Ok(Response::NoSource),
|
||||
}
|
||||
}
|
||||
ValueSource::DynamicMut(closure) => {
|
||||
let mut closure = closure.lock().unwrap();
|
||||
let value = self.execute_closure_safely(&mut *closure);
|
||||
match value {
|
||||
Ok(v) => Ok(Response::Value(v)),
|
||||
Err(_) => Ok(Response::NoSource),
|
||||
}
|
||||
}
|
||||
ValueSource::None => Ok(Response::NoSource),
|
||||
ValueSource::Cleared => Ok(Response::Closed),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_closure_safely(
|
||||
&self,
|
||||
closure: &mut dyn FnMut() -> T,
|
||||
) -> Result<T, Box<dyn std::any::Any + Send>> {
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(closure))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, ST, SR> AsyncSucker<T, ST, SR>
|
||||
where
|
||||
ST: AsyncChannelSender<Request>,
|
||||
SR: AsyncChannelReceiver<Response<T>>,
|
||||
{
|
||||
pub async fn get(&self) -> Result<T, Error> {
|
||||
if self.closed.load(Ordering::Acquire) {
|
||||
return Err(Error::ChannelClosed);
|
||||
}
|
||||
|
||||
self.request_tx
|
||||
.send(Request::GetValue)
|
||||
.await
|
||||
.map_err(|_| Error::ProducerDisconnected)?;
|
||||
|
||||
match self.response_rx.recv().await {
|
||||
Ok(Response::Value(value)) => Ok(value),
|
||||
Ok(Response::NoSource) => Err(Error::NoSource),
|
||||
Ok(Response::Closed) => Err(Error::ChannelClosed),
|
||||
Err(_) => Err(Error::ProducerDisconnected),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn is_closed(&self) -> bool {
|
||||
self.request_tx.send(Request::GetValue).await.is_err()
|
||||
}
|
||||
|
||||
pub async fn close(&self) -> Result<(), Error> {
|
||||
self.closed.store(true, Ordering::Release);
|
||||
self.request_tx
|
||||
.send(Request::Close)
|
||||
.await
|
||||
.map_err(|_| Error::ProducerDisconnected)
|
||||
}
|
||||
}
|
||||
8
src/asynchronous/mod.rs
Normal file
8
src/asynchronous/mod.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
pub mod traits;
|
||||
pub mod channel;
|
||||
|
||||
#[cfg(feature = "async-tokio")]
|
||||
pub mod tokio;
|
||||
|
||||
#[cfg(feature = "async-tokio")]
|
||||
pub use tokio::TokioSuck;
|
||||
121
src/asynchronous/tokio.rs
Normal file
121
src/asynchronous/tokio.rs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
|
||||
use crate::asynchronous::traits::{
|
||||
AsyncChannelReceiver, AsyncChannelSender, AsyncChannelType, ChannelError,
|
||||
};
|
||||
use crate::types;
|
||||
|
||||
type TokioSucker<T> =
|
||||
crate::asynchronous::channel::AsyncSucker<
|
||||
T,
|
||||
TokioSender<types::Request>,
|
||||
TokioReceiver<types::Response<T>>,
|
||||
>;
|
||||
type TokioSourcer<T> =
|
||||
crate::asynchronous::channel::AsyncSourcer<
|
||||
T,
|
||||
TokioReceiver<types::Request>,
|
||||
TokioSender<types::Response<T>>,
|
||||
>;
|
||||
|
||||
pub struct TokioSender<T>(mpsc::UnboundedSender<T>);
|
||||
pub struct TokioReceiver<T>(Mutex<mpsc::UnboundedReceiver<T>>);
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Send + 'static> AsyncChannelSender<T> for TokioSender<T> {
|
||||
async fn send(&self, msg: T) -> Result<(), ChannelError> {
|
||||
self.0
|
||||
.send(msg)
|
||||
.map_err(|_| ChannelError::ProducerDisconnected)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T: Send + 'static> AsyncChannelReceiver<T> for TokioReceiver<T> {
|
||||
async fn recv(&self) -> Result<T, ChannelError> {
|
||||
let mut receiver = self.0.lock().await;
|
||||
receiver
|
||||
.recv()
|
||||
.await
|
||||
.ok_or(ChannelError::ProducerDisconnected)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TokioChannel;
|
||||
|
||||
impl AsyncChannelType for TokioChannel {
|
||||
type Sender<T: Send + 'static> = TokioSender<T>;
|
||||
type Receiver<T: Send + 'static> = TokioReceiver<T>;
|
||||
|
||||
fn create_request_channel() -> (Self::Sender<types::Request>, Self::Receiver<types::Request>) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
(TokioSender(tx), TokioReceiver(Mutex::new(rx)))
|
||||
}
|
||||
|
||||
fn create_response_channel<T: Send + 'static>() -> (
|
||||
Self::Sender<types::Response<T>>,
|
||||
Self::Receiver<types::Response<T>>,
|
||||
) {
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
(TokioSender(tx), TokioReceiver(Mutex::new(rx)))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TokioSuck<T> {
|
||||
_phantom: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> TokioSuck<T> {
|
||||
pub fn pair() -> (TokioSucker<T>, TokioSourcer<T>)
|
||||
where
|
||||
T: Clone + Send + 'static,
|
||||
{
|
||||
let (request_tx, request_rx) = TokioChannel::create_request_channel();
|
||||
let (response_tx, response_rx) = TokioChannel::create_response_channel::<T>();
|
||||
let state = ArcSwap::new(Arc::new(crate::types::ValueSource::None));
|
||||
|
||||
let sucker = crate::asynchronous::channel::AsyncSucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::asynchronous::channel::AsyncSourcer::new(request_rx, response_tx, state);
|
||||
|
||||
(sucker, sourcer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::Error;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_pre_computed_value() {
|
||||
let (sucker, sourcer) = TokioSuck::<i32>::pair();
|
||||
|
||||
let producer = tokio::spawn(async move {
|
||||
sourcer.set_static(42).unwrap();
|
||||
sourcer.run().await.unwrap();
|
||||
});
|
||||
|
||||
let value = sucker.get().await.unwrap();
|
||||
assert_eq!(value, 42);
|
||||
sucker.close().await.unwrap();
|
||||
producer.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_no_source_error() {
|
||||
let (sucker, sourcer) = TokioSuck::<i32>::pair();
|
||||
|
||||
let producer = tokio::spawn(async move {
|
||||
sourcer.run().await.unwrap();
|
||||
});
|
||||
|
||||
let result = sucker.get().await;
|
||||
assert!(matches!(result, Err(Error::NoSource)));
|
||||
sucker.close().await.unwrap();
|
||||
producer.await.unwrap();
|
||||
}
|
||||
}
|
||||
27
src/asynchronous/traits.rs
Normal file
27
src/asynchronous/traits.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
use async_trait::async_trait;
|
||||
|
||||
pub use crate::error::Error as ChannelError;
|
||||
|
||||
#[async_trait]
|
||||
pub trait AsyncChannelSender<T>: Send + Sync {
|
||||
async fn send(&self, msg: T) -> Result<(), ChannelError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait AsyncChannelReceiver<T>: Send + Sync {
|
||||
async fn recv(&self) -> Result<T, ChannelError>;
|
||||
}
|
||||
|
||||
pub trait AsyncChannelType {
|
||||
type Sender<T: Send + 'static>: AsyncChannelSender<T>;
|
||||
type Receiver<T: Send + 'static>: AsyncChannelReceiver<T>;
|
||||
|
||||
fn create_request_channel() -> (
|
||||
Self::Sender<crate::types::Request>,
|
||||
Self::Receiver<crate::types::Request>,
|
||||
);
|
||||
fn create_response_channel<T: Send + 'static>() -> (
|
||||
Self::Sender<crate::types::Response<T>>,
|
||||
Self::Receiver<crate::types::Response<T>>,
|
||||
);
|
||||
}
|
||||
|
|
@ -1,12 +1,17 @@
|
|||
#![doc = include_str!("../README.md")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
||||
pub mod channel;
|
||||
pub mod error;
|
||||
|
||||
#[cfg(feature = "async")]
|
||||
pub mod asynchronous;
|
||||
#[cfg(feature = "sync")]
|
||||
pub mod sync;
|
||||
#[cfg(any(feature = "sync", feature = "async"))]
|
||||
pub mod types;
|
||||
|
||||
pub use channel::{Sourcer, Sucker};
|
||||
#[cfg(feature = "async")]
|
||||
pub use asynchronous::channel::{AsyncSourcer, AsyncSucker};
|
||||
#[cfg(feature = "sync")]
|
||||
pub use sync::channel::{Sourcer, Sucker};
|
||||
pub use error::Error;
|
||||
|
|
|
|||
|
|
@ -7,9 +7,17 @@ use arc_swap::ArcSwap;
|
|||
use crossbeam_channel;
|
||||
|
||||
type CrossbeamSucker<T> =
|
||||
crate::Sucker<T, CrossbeamSender<types::Request>, CrossbeamReceiver<types::Response<T>>>;
|
||||
crate::sync::channel::Sucker<
|
||||
T,
|
||||
CrossbeamSender<types::Request>,
|
||||
CrossbeamReceiver<types::Response<T>>,
|
||||
>;
|
||||
type CrossbeamSourcer<T> =
|
||||
crate::Sourcer<T, CrossbeamReceiver<types::Request>, CrossbeamSender<types::Response<T>>>;
|
||||
crate::sync::channel::Sourcer<
|
||||
T,
|
||||
CrossbeamReceiver<types::Request>,
|
||||
CrossbeamSender<types::Response<T>>,
|
||||
>;
|
||||
|
||||
/// Internal sender type for crossbeam backend
|
||||
pub struct CrossbeamSender<T>(crossbeam_channel::Sender<T>);
|
||||
|
|
@ -67,8 +75,8 @@ impl<T> CrossbeamSuck<T> {
|
|||
|
||||
let state = ArcSwap::new(Arc::new(crate::types::ValueSource::None));
|
||||
|
||||
let sucker = crate::Sucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::Sourcer::new(request_rx, response_tx, state);
|
||||
let sucker = crate::sync::channel::Sucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::sync::channel::Sourcer::new(request_rx, response_tx, state);
|
||||
|
||||
(sucker, sourcer)
|
||||
}
|
||||
|
|
@ -132,6 +140,38 @@ mod tests {
|
|||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mut_closure_value() {
|
||||
let (sucker, sourcer) = CrossbeamSuck::<i32>::pair();
|
||||
|
||||
// Start producer
|
||||
let producer_handle = std::thread::spawn(move || {
|
||||
let mut count = 0;
|
||||
sourcer
|
||||
.set_mut(move || {
|
||||
count += 1;
|
||||
count
|
||||
})
|
||||
.unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
// Ensure consumer gets incrementing values from the mutable closure
|
||||
let value1 = sucker.get().unwrap();
|
||||
assert_eq!(value1, 1);
|
||||
|
||||
let value2 = sucker.get().unwrap();
|
||||
assert_eq!(value2, 2);
|
||||
|
||||
let value3 = sucker.get().unwrap();
|
||||
assert_eq!(value3, 3);
|
||||
|
||||
// Close consumer
|
||||
sucker.close().unwrap();
|
||||
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_source_error() {
|
||||
let (sucker, sourcer) = CrossbeamSuck::<i32>::pair();
|
||||
|
|
|
|||
|
|
@ -7,9 +7,9 @@ use arc_swap::ArcSwap;
|
|||
use flume;
|
||||
|
||||
type FlumeSucker<T> =
|
||||
crate::Sucker<T, FlumeSender<types::Request>, FlumeReceiver<types::Response<T>>>;
|
||||
crate::sync::channel::Sucker<T, FlumeSender<types::Request>, FlumeReceiver<types::Response<T>>>;
|
||||
type FlumeSourcer<T> =
|
||||
crate::Sourcer<T, FlumeReceiver<types::Request>, FlumeSender<types::Response<T>>>;
|
||||
crate::sync::channel::Sourcer<T, FlumeReceiver<types::Request>, FlumeSender<types::Response<T>>>;
|
||||
|
||||
/// Internal sender type for flume backend
|
||||
pub struct FlumeSender<T>(flume::Sender<T>);
|
||||
|
|
@ -68,8 +68,8 @@ impl<T> FlumeSuck<T> {
|
|||
let state = Arc::new(crate::types::ValueSource::None);
|
||||
let state = ArcSwap::new(state);
|
||||
|
||||
let sucker = crate::Sucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::Sourcer::new(request_rx, response_tx, state);
|
||||
let sucker = crate::sync::channel::Sucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::sync::channel::Sourcer::new(request_rx, response_tx, state);
|
||||
|
||||
(sucker, sourcer)
|
||||
}
|
||||
|
|
@ -133,6 +133,38 @@ mod tests {
|
|||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mut_closure_value() {
|
||||
let (sucker, sourcer) = FlumeSuck::<i32>::pair();
|
||||
|
||||
// Start producer
|
||||
let producer_handle = std::thread::spawn(move || {
|
||||
let mut count = 0;
|
||||
sourcer
|
||||
.set_mut(move || {
|
||||
count += 1;
|
||||
count
|
||||
})
|
||||
.unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
// Ensure consumer gets incrementing values from the mutable closure
|
||||
let value1 = sucker.get().unwrap();
|
||||
assert_eq!(value1, 1);
|
||||
|
||||
let value2 = sucker.get().unwrap();
|
||||
assert_eq!(value2, 2);
|
||||
|
||||
let value3 = sucker.get().unwrap();
|
||||
assert_eq!(value3, 3);
|
||||
|
||||
// Close consumer
|
||||
sucker.close().unwrap();
|
||||
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_source_error() {
|
||||
let (sucker, sourcer) = FlumeSuck::<i32>::pair();
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
pub mod traits;
|
||||
pub mod channel;
|
||||
|
||||
#[cfg(feature = "sync-crossbeam")]
|
||||
pub mod crossbeam;
|
||||
|
|
|
|||
156
src/sync/std.rs
156
src/sync/std.rs
|
|
@ -6,8 +6,10 @@ use std::sync::Arc;
|
|||
#[cfg(feature = "sync-std")]
|
||||
use std::sync::mpsc;
|
||||
|
||||
type StdSucker<T> = crate::Sucker<T, StdSender<types::Request>, StdReceiver<types::Response<T>>>;
|
||||
type StdSourcer<T> = crate::Sourcer<T, StdReceiver<types::Request>, StdSender<types::Response<T>>>;
|
||||
type StdSucker<T> =
|
||||
crate::sync::channel::Sucker<T, StdSender<types::Request>, StdReceiver<types::Response<T>>>;
|
||||
type StdSourcer<T> =
|
||||
crate::sync::channel::Sourcer<T, StdReceiver<types::Request>, StdSender<types::Response<T>>>;
|
||||
|
||||
/// Internal sender type for std backend
|
||||
pub struct StdSender<T>(mpsc::Sender<T>);
|
||||
|
|
@ -66,8 +68,8 @@ impl<T> StdSuck<T> {
|
|||
let state = Arc::new(crate::types::ValueSource::None);
|
||||
let state = ArcSwap::new(state);
|
||||
|
||||
let sucker = crate::Sucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::Sourcer::new(request_rx, response_tx, state);
|
||||
let sucker = crate::sync::channel::Sucker::new(request_tx, response_rx);
|
||||
let sourcer = crate::sync::channel::Sourcer::new(request_rx, response_tx, state);
|
||||
|
||||
(sucker, sourcer)
|
||||
}
|
||||
|
|
@ -77,8 +79,18 @@ impl<T> StdSuck<T> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
use crate::Error;
|
||||
use crate::sync::traits::ChannelType;
|
||||
use std::thread;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PanicOnClone;
|
||||
|
||||
impl Clone for PanicOnClone {
|
||||
fn clone(&self) -> Self {
|
||||
panic!("intentional panic from Clone");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_pre_computed_value() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
|
@ -131,6 +143,38 @@ mod tests {
|
|||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mut_closure_value() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
||||
// Start producer
|
||||
let producer_handle = std::thread::spawn(move || {
|
||||
let mut count = 0;
|
||||
sourcer
|
||||
.set_mut(move || {
|
||||
count += 1;
|
||||
count
|
||||
})
|
||||
.unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
// Ensure consumer gets incrementing values from the mutable closure
|
||||
let value1 = sucker.get().unwrap();
|
||||
assert_eq!(value1, 1);
|
||||
|
||||
let value2 = sucker.get().unwrap();
|
||||
assert_eq!(value2, 2);
|
||||
|
||||
let value3 = sucker.get().unwrap();
|
||||
assert_eq!(value3, 3);
|
||||
|
||||
// Close consumer
|
||||
sucker.close().unwrap();
|
||||
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_source_error() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
|
@ -186,6 +230,110 @@ mod tests {
|
|||
let _ = producer_handle.join();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_breaks_when_response_receiver_is_dropped() {
|
||||
let (request_tx, request_rx) = StdChannel::create_request_channel();
|
||||
let (response_tx, response_rx) = StdChannel::create_response_channel::<i32>();
|
||||
drop(response_rx);
|
||||
|
||||
let state = Arc::new(crate::types::ValueSource::None);
|
||||
let state = ArcSwap::new(state);
|
||||
let sourcer = crate::sync::channel::Sourcer::new(request_rx, response_tx, state);
|
||||
sourcer.set_static(42).unwrap();
|
||||
|
||||
let producer_handle = thread::spawn(move || sourcer.run().unwrap());
|
||||
|
||||
request_tx.send(crate::types::Request::GetValue).unwrap();
|
||||
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_run_breaks_when_request_sender_is_dropped() {
|
||||
let (request_tx, request_rx) = StdChannel::create_request_channel();
|
||||
let (response_tx, _response_rx) = StdChannel::create_response_channel::<i32>();
|
||||
drop(request_tx);
|
||||
|
||||
let state = Arc::new(crate::types::ValueSource::None);
|
||||
let state = ArcSwap::new(state);
|
||||
let sourcer = crate::sync::channel::Sourcer::new(request_rx, response_tx, state);
|
||||
|
||||
sourcer.run().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_static_source_panic_returns_no_source() {
|
||||
let (sucker, sourcer) = StdSuck::<PanicOnClone>::pair();
|
||||
|
||||
let producer_handle = thread::spawn(move || {
|
||||
sourcer.set_static(PanicOnClone).unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
let result = sucker.get();
|
||||
assert!(matches!(result, Err(Error::NoSource)));
|
||||
|
||||
sucker.close().unwrap();
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dynamic_source_panic_returns_no_source() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
||||
let producer_handle = thread::spawn(move || {
|
||||
sourcer
|
||||
.set(|| -> i32 {
|
||||
panic!("intentional panic from Fn source");
|
||||
})
|
||||
.unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
let result = sucker.get();
|
||||
assert!(matches!(result, Err(Error::NoSource)));
|
||||
|
||||
sucker.close().unwrap();
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dynamic_mut_source_panic_returns_no_source() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
||||
let producer_handle = thread::spawn(move || {
|
||||
sourcer
|
||||
.set_mut(|| -> i32 {
|
||||
panic!("intentional panic from FnMut source");
|
||||
})
|
||||
.unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
let result = sucker.get();
|
||||
assert!(matches!(result, Err(Error::NoSource)));
|
||||
|
||||
sucker.close().unwrap();
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_cleared_source_returns_channel_closed() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
||||
let producer_handle = thread::spawn(move || {
|
||||
sourcer.set_static(42).unwrap();
|
||||
sourcer.close().unwrap();
|
||||
sourcer.run().unwrap();
|
||||
});
|
||||
|
||||
let result = sucker.get();
|
||||
assert!(matches!(result, Err(Error::ChannelClosed)));
|
||||
|
||||
sucker.close().unwrap();
|
||||
producer_handle.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_closed() {
|
||||
let (sucker, sourcer) = StdSuck::<i32>::pair();
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue