side_proto/
traits.rs

1//! Support traits for Cosmos SDK protobufs.
2
3pub use prost::{Message, Name};
4
5use alloc::{string::String, vec::Vec};
6use core::str::FromStr;
7use prost::EncodeError;
8
9/// Extension trait for [`Message`].
10pub trait MessageExt: Message {
11    /// Serialize this protobuf message as a byte vector.
12    fn to_bytes(&self) -> Result<Vec<u8>, EncodeError>;
13}
14
15impl<M> MessageExt for M
16where
17    M: prost::Message,
18{
19    fn to_bytes(&self) -> Result<Vec<u8>, EncodeError> {
20        let mut bytes = Vec::new();
21        Message::encode(self, &mut bytes)?;
22        Ok(bytes)
23    }
24}
25
26/// Extension traits for optionally parsing non-empty strings.
27///
28/// This is a common pattern in Cosmos SDK protobufs.
29pub trait ParseOptional: AsRef<str> {
30    /// Parse optional field.
31    fn parse_optional<T: FromStr>(&self) -> Result<Option<T>, T::Err> {
32        if self.as_ref().is_empty() {
33            Ok(None)
34        } else {
35            Ok(Some(self.as_ref().parse()?))
36        }
37    }
38}
39
40impl ParseOptional for str {}
41impl ParseOptional for String {}