use crate::types::Entry;
use tokio::sync::mpsc::UnboundedReceiver;
pub trait ClipboardWatcher: Send + Sync {
fn subscribe(&self) -> UnboundedReceiver<Entry>;
}
#[cfg(any(test, feature = "mock"))]
pub mod mock {
use super::*;
use std::sync::Mutex;
use tokio::sync::mpsc::{self, UnboundedSender};
#[derive(Default)]
pub struct MockWatcher {
subscribers: Mutex<Vec<UnboundedSender<Entry>>>,
}
impl MockWatcher {
pub fn new() -> Self {
Self::default()
}
pub fn push(&self, entry: Entry) {
let mut subscribers = self.subscribers.lock().unwrap_or_else(|e| e.into_inner());
subscribers.retain(|tx| tx.send(entry.clone()).is_ok());
}
pub fn subscriber_count(&self) -> usize {
self.subscribers
.lock()
.unwrap_or_else(|e| e.into_inner())
.len()
}
}
impl ClipboardWatcher for MockWatcher {
fn subscribe(&self) -> UnboundedReceiver<Entry> {
let (tx, rx) = mpsc::unbounded_channel();
self.subscribers
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(tx);
rx
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{Content, EntryId};
fn entry(text: &str) -> Entry {
let content = Content::Text(text.to_string());
Entry {
id: EntryId::of(&content),
content,
copied_at: 0,
pinned: false,
}
}
#[tokio::test]
async fn a_pushed_entry_reaches_every_current_subscriber() {
let watcher = MockWatcher::new();
let mut a = watcher.subscribe();
let mut b = watcher.subscribe();
watcher.push(entry("hello"));
assert_eq!(
a.recv().await.unwrap().content,
Content::Text("hello".to_string())
);
assert_eq!(
b.recv().await.unwrap().content,
Content::Text("hello".to_string())
);
}
#[tokio::test]
async fn dropping_a_receiver_removes_it_as_a_subscriber() {
let watcher = MockWatcher::new();
let rx = watcher.subscribe();
assert_eq!(watcher.subscriber_count(), 1);
drop(rx);
watcher.push(entry("hello"));
assert_eq!(watcher.subscriber_count(), 0);
}
}
}