# Subscription Filters

## Overview

In the `mechutil` library, subscription filters are used to determine if a message matches a subscription. This is achieved through the `SubscriptionFilter` trait, which allows for custom filtering logic to be implemented.

## SubscriptionFilter Trait

The `SubscriptionFilter` trait defines a single method, `matches`, which takes a reference to a message and returns a boolean indicating whether the message matches the filter.

```rust
pub trait SubscriptionFilter<R> {
    /// Returns true if the message matches the filter, false otherwise.
    ///
    /// # Parameters
    /// - `message`: The message to be checked against the filter.
    fn matches(&self, message: &R) -> bool;
}
```

## DefaultSubscriptionFilter

The DefaultSubscriptionFilter is a simple implementation of the SubscriptionFilter trait that always returns true. This means that any message will match the filter, effectively disabling filtering.


```rust
pub struct DefaultSubscriptionFilter;

impl<R> SubscriptionFilter<R> for DefaultSubscriptionFilter {
    fn matches(&self, _message: &R) -> bool {
        true
    }
}
```

## Implementing a Custom Filter

To implement a custom filter, you need to define a struct and implement the SubscriptionFilter trait for it. Below is an example of a custom filter that only matches messages that are greater than a specified threshold.

```rust
pub struct ThresholdFilter {
    threshold: i32,
}

impl ThresholdFilter {
    pub fn new(threshold: i32) -> Self {
        Self { threshold }
    }
}

impl SubscriptionFilter<i32> for ThresholdFilter {
    fn matches(&self, message: &i32) -> bool {
        message > &self.threshold
    }
}
```

In this example, the ThresholdFilter struct has a threshold field, and the matches method returns true if the message is greater than the threshold.

## Usage Example

Here is an example of how to use the ThresholdFilter in a subscription manager:

use tokio::sync::{mpsc, oneshot};
use mechutil::subscription::{SubscriptionManager, SubscriptionHandler, ThresholdFilter};

```rust
#[tokio::main]
async fn main() {
    let mut manager: SubscriptionManager<String, i32> = SubscriptionManager::new();

    let (tx, rx) = mpsc::channel(100);
    let (response_tx, response_rx) = oneshot::channel();

    let filter = Box::new(ThresholdFilter::new(10));

    manager.subscribe_with_filter("example_topic".to_string(), filter, tx, response_tx).await;

    // Now, only messages greater than 10 will be sent to the subscriber.
}
```

## Conclusion

The SubscriptionFilter trait provides a flexible way to implement custom filtering logic for subscriptions. The DefaultSubscriptionFilter can be used when no filtering is needed, and custom filters can be implemented by defining a struct and implementing the SubscriptionFilter trait for it.