mirror of
https://github.com/fluencelabs/rust-libp2p
synced 2025-06-25 15:51:34 +00:00
refactor: make debug-print of StreamProtocol
more concise
The` fmt::Debug` implementation of a type should in most cases reveal its internal structure. `StreamProtocol` is likely to be debug-printed a lot and in many cases, the only contract is the `fmt::Debug` impl. The internals of `StreamProtocol` only exist for performance reasons to avoid allocations for statically-known protocol strings. Revealing this implementation detail isn't particularly beneficial to end users. At the same time, the current implementation is very noise. Previously, the `protocols` field of an `identify::Info` would e.g. read as: ``` protocols: [StreamProtocol { inner: Right("/ipfs/id/1.0.0") }, StreamProtocol { inner: Right("/ipfs/id/push/1.0.0") }, StreamProtocol { inner: Right("/ipfs/kad/1.0.0") }] ``` With this patch, it reads as: ``` protocols: ["/ipfs/id/1.0.0", "/ipfs/kad/1.0.0", "/ipfs/id/push/1.0.0"] ``` Pull-Request: #4631.
This commit is contained in:
@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
///
|
||||
/// libp2p nodes use stream protocols to negotiate what to do with a newly opened stream.
|
||||
/// Stream protocols are string-based and must start with a forward slash: `/`.
|
||||
#[derive(Debug, Clone, Eq)]
|
||||
#[derive(Clone, Eq)]
|
||||
pub struct StreamProtocol {
|
||||
inner: Either<&'static str, Arc<str>>,
|
||||
}
|
||||
@ -50,6 +50,12 @@ impl AsRef<str> for StreamProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for StreamProtocol {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
either::for_both!(&self.inner, s => s.fmt(f))
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for StreamProtocol {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.inner.fmt(f)
|
||||
@ -102,3 +108,25 @@ impl fmt::Display for InvalidProtocol {
|
||||
}
|
||||
|
||||
impl std::error::Error for InvalidProtocol {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn stream_protocol_print() {
|
||||
let protocol = StreamProtocol::new("/foo/bar/1.0.0");
|
||||
|
||||
let debug = format!("{protocol:?}");
|
||||
let display = format!("{protocol}");
|
||||
|
||||
assert_eq!(
|
||||
debug, r#""/foo/bar/1.0.0""#,
|
||||
"protocol to debug print as string with quotes"
|
||||
);
|
||||
assert_eq!(
|
||||
display, "/foo/bar/1.0.0",
|
||||
"protocol to display print as string without quotes"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user