Skip to content

Commit

Permalink
Merge pull request #2 from polyphony-chat/clone-and-partialeq
Browse files Browse the repository at this point in the history
Clone and partialeq
  • Loading branch information
bitfl0wer authored Jul 13, 2024
2 parents 8e23b54 + 1d562ca commit 7dd9840
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 2 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "pubserve"
license = "MPL-2.0"
version = "1.1.0-alpha.1"
version = "1.1.0"
edition = "2021"
authors = ["bitfl0wer <[email protected]>"]
description = "Simple, generic observer trait."
Expand Down
14 changes: 14 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ pub trait Subscriber<T> {
/// let mut publisher = Publisher::<String>::new();
/// publisher.publish("Hello, World!".to_string()); // .await, if async feature is enabled
/// ```
#[derive(Clone)]
pub struct Publisher<T> {
subscribers: Vec<ReferenceCounted<dyn Subscriber<T>>>,
}
Expand All @@ -68,6 +69,19 @@ impl<T> Debug for Publisher<T> {
}
}

impl<T> PartialEq for Publisher<T> {
fn eq(&self, other: &Self) -> bool {
for (own_subscriber, other_subscriber) in
self.subscribers.iter().zip(other.subscribers.iter())
{
if !ReferenceCounted::ptr_eq(own_subscriber, other_subscriber) {
return false;
}
}
true
}
}

impl<T> std::default::Default for Publisher<T> {
fn default() -> Self {
Self {
Expand Down
36 changes: 36 additions & 0 deletions tests/clone.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

#[cfg(not(feature = "async"))]
#[test]
fn test_clone() {
use std::cell::RefCell;

use pubserve::{Publisher, ReferenceCounted, Subscriber};

struct MySubscriber {
vec: RefCell<Vec<i32>>,
}

impl Subscriber<i32> for MySubscriber {
fn update(&self, message: &i32) {
self.vec.borrow_mut().push(*message);
dbg!(self.vec.borrow());
}
}

let mut publisher = Publisher::<i32>::new();
let shared = ReferenceCounted::new(MySubscriber {
vec: RefCell::new(Vec::new()),
});
publisher.subscribe(shared.clone());
publisher.publish(42);
assert!(shared.vec.borrow().contains(&42));
// Test, if cloning the publisher, then dropping the original publisher, still allows the
// subscriber to receive messages.
let publisher_clone = publisher.clone();
drop(publisher);
publisher_clone.publish(43);
assert!(shared.vec.borrow().contains(&43));
}

0 comments on commit 7dd9840

Please sign in to comment.