Shareable

Trait Shareable 

Source
pub trait Shareable<T>:
    Clone
    + Send
    + Sync
    + 'static {
    // Required method
    fn new(inner: T) -> Self;
}
Expand description

Trait for types that can be wrapped in a thread-safe shared wrapper

This trait defines the interface for creating shared wrappers that encapsulate Arc/Mutex complexity and provide clean APIs for concurrent access.

§Design Principles

  • Hide complexity: Encapsulate Arc/Mutex details from users
  • Preserve semantics: Maintain original API behavior as much as possible
  • Enable sharing: Allow multiple tasks to access the same instance safely
  • Async-first: Design for async/await patterns

§Implementation Guidelines

When implementing this trait, consider:

  • Methods requiring &mut self need special handling in shared contexts
  • Reference-returning methods (&T) can’t work directly with async mutexes
  • Consuming methods (taking self) may need special consumption patterns
  • Performance implications of mutex contention

§Examples

use std::sync::Arc;
use tokio::sync::Mutex;
use turbomcp_core::shared::Shareable;

struct MyService {
    counter: u64,
}

impl MyService {
    fn new() -> Self {
        Self { counter: 0 }
    }

    fn increment(&mut self) {
        self.counter += 1;
    }

    fn count(&self) -> u64 {
        self.counter
    }
}

// Shared wrapper
struct SharedMyService {
    inner: Arc<Mutex<MyService>>,
}

impl Shareable<MyService> for SharedMyService {
    fn new(inner: MyService) -> Self {
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }
}

impl Clone for SharedMyService {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl SharedMyService {
    async fn increment(&self) {
        self.inner.lock().await.increment();
    }

    async fn count(&self) -> u64 {
        self.inner.lock().await.count()
    }
}

Required Methods§

Source

fn new(inner: T) -> Self

Create a new shared wrapper around the inner type

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T> Shareable<T> for ConsumableShared<T>
where T: Send + 'static,

Source§

impl<T> Shareable<T> for Shared<T>
where T: Send + 'static,