Skip to content

Commit

Permalink
cosmos-sdk-proto: replace TypeUrl with Name trait
Browse files Browse the repository at this point in the history
The `Name` trait added upstream in `prost` can be used to compute the
type URL using `Name::type_url`:

tokio-rs/prost#896

The new `Any::{from_msg, to_msg}` methods can be used to serialize
`Message` types to/from messages.

This commit switches from the `TypeUrl` trait to `Name` and relies
more on upstream functionality in `prost`.

Unfortunately it shipped with a bug in the default `Name::full_name`
method, so a workaround is temporarily used until a fix ships:

tokio-rs/prost#923
  • Loading branch information
tony-iqlusion committed Oct 3, 2023
1 parent 860cb1d commit c7a3e03
Show file tree
Hide file tree
Showing 5 changed files with 515 additions and 254 deletions.
2 changes: 1 addition & 1 deletion cosmos-sdk-proto/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
#![warn(trivial_casts, trivial_numeric_casts, unused_import_braces)]

pub mod traits;
mod type_urls;
mod type_names;

pub use prost;
pub use prost_types::Any;
Expand Down
29 changes: 5 additions & 24 deletions cosmos-sdk-proto/src/traits.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,27 @@
//! Support traits for Cosmos SDK protobufs.

pub use prost::Message;
pub use prost::{Message, Name};

use crate::Any;
use prost::{DecodeError, EncodeError};
use std::str::FromStr;

/// Associate a type URL with a given proto.
pub trait TypeUrl: Message {
/// Type URL value
const TYPE_URL: &'static str;
}

/// Extension trait for [`Message`].
pub trait MessageExt: Message {
/// Parse this message proto from [`Any`].
fn from_any(any: &Any) -> Result<Self, DecodeError>
where
Self: Default + Sized + TypeUrl,
Self: Default + Name + Sized,
{
if any.type_url == Self::TYPE_URL {
Ok(Self::decode(&*any.value)?)
} else {
let mut err = DecodeError::new(format!(
"expected type URL: \"{}\" (got: \"{}\")",
Self::TYPE_URL,
&any.type_url
));
err.push("unexpected type URL", "type_url");
Err(err)
}
any.to_msg()
}

/// Serialize this message proto as [`Any`].
fn to_any(&self) -> Result<Any, EncodeError>
where
Self: TypeUrl,
Self: Name + Sized,
{
self.to_bytes().map(|bytes| Any {
type_url: Self::TYPE_URL.to_owned(),
value: bytes,
})
Any::from_msg(self)
}

/// Serialize this protobuf message as a byte vector.
Expand Down
Loading

0 comments on commit c7a3e03

Please sign in to comment.