Addressing #473 ... if I understood the ticket right, we want to pass… (#1395)

* Addressing #473 ... if I understood the ticket right, we want to pass through whatever the application provides as a topic identifier, leaving hashing (or not hashing) up to the application.

* Remove TopicDescriptor and use Topic newtype everywhere

* PR feedback

Use From<Topic> instead of Into<String>
Use impl Into<Topic> instead of Topic in public API

Co-authored-by: Peat Bakke <peat@peat.org>
This commit is contained in:
Rüdiger Klaehn
2020-01-27 15:23:01 +01:00
committed by Pierre Krieger
parent 2ef7c40cda
commit 3b50cbd1b8
6 changed files with 46 additions and 142 deletions

View File

@ -18,93 +18,27 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use bs58;
use crate::rpc_proto;
use prost::Message;
/// Represents the hash of a topic.
///
/// Instead of a using the topic as a whole, the API of floodsub uses a hash of the topic. You only
/// have to build the hash once, then use it everywhere.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TopicHash {
hash: String,
}
impl TopicHash {
/// Builds a new `TopicHash` from the given hash.
pub fn from_raw(hash: String) -> TopicHash {
TopicHash { hash }
}
pub fn into_string(self) -> String {
self.hash
}
}
/// Built topic.
#[derive(Debug, Clone)]
pub struct Topic {
descriptor: rpc_proto::TopicDescriptor,
hash: TopicHash,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Topic(String);
impl Topic {
/// Returns the hash of the topic.
pub fn hash(&self) -> &TopicHash {
&self.hash
/// Returns the id of the topic.
#[inline]
pub fn id(&self) -> &str {
&self.0
}
}
impl AsRef<TopicHash> for Topic {
fn as_ref(&self) -> &TopicHash {
&self.hash
}
}
impl From<Topic> for TopicHash {
fn from(topic: Topic) -> TopicHash {
topic.hash
}
}
impl<'a> From<&'a Topic> for TopicHash {
fn from(topic: &'a Topic) -> TopicHash {
topic.hash.clone()
}
}
/// Builder for a `TopicHash`.
#[derive(Debug, Clone)]
pub struct TopicBuilder {
builder: rpc_proto::TopicDescriptor,
}
impl TopicBuilder {
pub fn new<S>(name: S) -> TopicBuilder
pub fn new<S>(name: S) -> Topic
where
S: Into<String>,
{
TopicBuilder {
builder: rpc_proto::TopicDescriptor {
name: Some(name.into()),
auth: None,
enc: None
}
}
}
/// Turns the builder into an actual `Topic`.
pub fn build(self) -> Topic {
let mut buf = Vec::with_capacity(self.builder.encoded_len());
self.builder.encode(&mut buf).expect("Vec<u8> provides capacity as needed");
// TODO: https://github.com/libp2p/rust-libp2p/issues/473
let hash = TopicHash {
hash: bs58::encode(&buf).into_string(),
};
Topic {
descriptor: self.builder,
hash,
}
Topic(name.into())
}
}
impl From<Topic> for String {
fn from(topic: Topic) -> String {
topic.0
}
}