Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a debug implementation for Address #67

Merged
merged 16 commits into from
Jun 9, 2022
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions examples/basic_wasm_bindgen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,19 @@ use xtra::spawn::WasmBindgen;

struct Echoer;

impl Actor for Echoer {}
#[async_trait]
impl Actor for Echoer {
type Stop = ();

struct Echo(String);
impl Message for Echo {
type Result = String;
async fn stopped(self) {}
}

struct Echo(String);

#[async_trait]
impl Handler<Echo> for Echoer {
type Return = String;

Restioson marked this conversation as resolved.
Show resolved Hide resolved
async fn handle(&mut self, echo: Echo, _ctx: &mut Context<Self>) -> String {
echo.0
}
Expand Down
10 changes: 9 additions & 1 deletion src/address.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! An address to an actor is a way to send it a message. An address allows an actor to be sent any
//! kind of message that it can receive.

use std::fmt::{self, Display, Formatter};
use std::fmt::{self, Debug, Display, Formatter};
use std::future::Future;
use std::{cmp::Ordering, error::Error, hash::Hash};

Expand Down Expand Up @@ -44,6 +44,14 @@ pub struct Address<A, Rc: RefCounter = Strong> {
pub(crate) ref_counter: Rc,
}

impl<A, Rc: RefCounter> Debug for Address<A, Rc> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct(&format!("Address<{}>", std::any::type_name::<A>()))
.field("ref_counter", &self.ref_counter)
.finish()
}
}

/// A `WeakAddress` is a reference to an actor through which [`Message`s](../trait.Message.html) can be
/// sent. It can be cloned. Unlike [`Address`](struct.Address.html), a `WeakAddress` will not inhibit
/// the dropping of an actor. It is created by the [`Address::downgrade`](struct.Address.html#method.downgrade)
Expand Down
5 changes: 3 additions & 2 deletions src/message_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
//! any actor that can handle it. It is like [`Address`](../address/struct.Address.html), but associated with
//! the message type rather than the actor type.

use std::fmt::Debug;

use futures_core::future::BoxFuture;
use futures_core::stream::BoxStream;

Expand Down Expand Up @@ -77,10 +79,9 @@ use crate::{Handler, KeepRunning};
/// })
/// }
/// ```
pub trait MessageChannel<M>: Sealed + Unpin + Send + Sync {
pub trait MessageChannel<M>: Sealed + Unpin + Debug + Send + Sync {
/// The return value of the handler for `M`.
type Return: Send + 'static;

/// Returns whether the actor referred to by this address is running and accepting messages.
fn is_connected(&self) -> bool;

Expand Down
39 changes: 34 additions & 5 deletions src/refcount.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::drop_notice;
use crate::drop_notice::DropNotice;
use std::fmt::{Debug, Formatter};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock, Weak as ArcWeak};

use crate::drop_notice::{self, DropNotice};
use crate::private::Sealed;

/// The reference count of a strong address. Strong addresses will prevent the actor from being
Expand All @@ -18,6 +17,16 @@ pub struct Strong {
lock: Arc<RwLock<()>>,
}

impl Debug for Strong {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Strong")
.field("connected", &self.is_connected())
.field("strong_count", &self.strong_count())
.field("weak_count", &self.weak_count())
.finish()
}
}

#[doc(hidden)]
pub struct Shared {
connected: AtomicBool,
Expand All @@ -35,6 +44,11 @@ impl Strong {
}
}

fn weak_count(&self) -> usize {
let _lock = self.lock.read().unwrap();
Restioson marked this conversation as resolved.
Show resolved Hide resolved
Arc::weak_count(&self.shared)
}

pub(crate) fn downgrade(&self) -> Weak {
Weak {
shared: Arc::downgrade(&self.shared),
Expand All @@ -55,17 +69,32 @@ pub struct Weak {
lock: Arc<RwLock<()>>,
}

impl Debug for Weak {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Weak")
.field("connected", &self.is_connected())
.field("strong_count", &self.strong_count())
.field("weak_count", &self.weak_count())
.finish()
}
}

impl Weak {
pub(crate) fn upgrade(&self) -> Option<Strong> {
ArcWeak::upgrade(&self.shared).map(|shared| Strong {
shared,
lock: self.lock.clone(),
})
}

fn weak_count(&self) -> usize {
let _lock = self.lock.read().unwrap();
ArcWeak::weak_count(&self.shared)
}
}

/// A reference counter that can be dynamically either strong or weak.
#[derive(Clone)]
#[derive(Clone, Debug)]
pub enum Either {
/// A strong reference counter.
Strong(Strong),
Expand All @@ -87,7 +116,7 @@ impl Either {
/// [`Strong`](struct.Weak.html). These can be provided as the second type argument to
/// [`Address`](../address/struct.Address.html) in order to change how the address affects the actor's
/// dropping. Read the docs of [`Address`](../address/struct.Address.html) to find out more.
pub trait RefCounter: Sealed + Clone + Unpin + Send + Sync + 'static {
pub trait RefCounter: Sealed + Clone + Unpin + Debug + Send + Sync + 'static {
#[doc(hidden)]
fn is_connected(&self) -> bool;
#[doc(hidden)]
Expand Down
22 changes: 22 additions & 0 deletions tests/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,3 +273,25 @@ async fn address_send_exercises_backpressure() {
.now_or_never()
.expect("be able to queue another message because the mailbox is empty again");
}

#[test]
fn address_debug() {
let (addr1, _ctx): (Address<_>, Context<Greeter>) = Context::new(None);
Restioson marked this conversation as resolved.
Show resolved Hide resolved

let addr2 = addr1.clone();
let weak_addr = addr2.downgrade();

assert_eq!(
format!("{:?}", addr1),
"Address<basic::Greeter> { \
ref_counter: Strong { connected: true, strong_count: 2, weak_count: 2 } }"
);

assert_eq!(format!("{:?}", addr1), format!("{:?}", addr2));

assert_eq!(
format!("{:?}", weak_addr),
"Address<basic::Greeter> { \
ref_counter: Weak { connected: true, strong_count: 2, weak_count: 2 } }"
);
}