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

feat(swarm): impl FromStr for StreamProtocol #3951

Closed
wants to merge 1 commit into from
Closed
Changes from all 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
11 changes: 10 additions & 1 deletion swarm/src/stream_protocol.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use either::Either;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::Arc;

/// Identifies a protocol for a stream.
Expand Down Expand Up @@ -39,7 +40,7 @@ impl StreamProtocol {
}

Ok(StreamProtocol {
inner: Either::Right(Arc::from(protocol)), // FIXME: Can we somehow reuse the allocation from the owned string?
inner: Either::Right(Arc::from(protocol)),
Comment on lines -42 to +43
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leftover from a refactor, right @thomaseizinger?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, this still applies. Arc will allocate again despite the String already having an allocation.

})
}
}
Expand Down Expand Up @@ -80,6 +81,14 @@ impl Hash for StreamProtocol {
}
}

impl FromStr for StreamProtocol {
type Err = InvalidProtocol;

fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from_owned(s.into())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This results in one more allocation than necessary because we could also construct an Arc<str> from a string slice and don't have to go via an owned string.

We would duplicate the check then but perhaps you can refactor that check out in a separate function?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or perhaps we can widen the accepted type on try_from_owned to something impl? But then we'd have to rename it as well ..

}
}

#[derive(Debug)]
pub struct InvalidProtocol {
// private field to prevent construction outside of this module
Expand Down