prost_helper/
lib.rs

1//! A set of prost helper functions to make prost generated code easy to work with.
2//!
3//! If you use `prost-serde` to build your protobuf files, mostly you need this crate to provide
4//! functions for `is_zero` and `deserialize_null_default`.
5//!
6//! You can also use the macros to convert protobuf messages to / try_from `Vec<u8>`.
7//!
8//! For example, if prost generated a data struct `Hello`, You can use the macros to generate
9//! `From` and /`TryFrom` respectively, and then use them:
10//!
11//! ```ignore
12//! use prost_helper::{prost_into_vec, vec_try_into_prost};
13//! use prost::Message;
14//!
15//! #[derive(Clone, PartialEq, Eq, prost::Message)]
16//! pub struct Hello {
17//!     #[prost(string, tag = "1")]
18//!     pub msg: String,
19//! }
20//!
21//! prost_into_vec!(Hello, 32);
22//! vec_try_into_prost!(Hello);
23//!
24//! fn send_hello(data: Vec<u8>) {
25//!     unimplemented!();
26//! }
27//!
28//! let hello = Hello::default();
29//! send_hello(hello.into());
30//!```
31//!
32use num_traits::Num;
33use serde::{Deserialize, Deserializer};
34
35pub mod macros;
36
37#[cfg(feature = "b64")]
38mod buf;
39
40#[cfg(feature = "b64")]
41pub use buf::*;
42
43#[cfg(feature = "id")]
44mod id;
45
46#[cfg(feature = "id")]
47pub use id::*;
48
49#[cfg(feature = "json")]
50/// Convert the prost message to JSON string for debugging purpose. Need serde_json support.
51pub trait ToJson {
52    fn to_json(&self) -> String;
53}
54
55/// customized skip_serializing_if function to skip 0 for numbers.
56pub fn is_zero(v: impl Num) -> bool {
57    v.is_zero()
58}
59
60/// customized deserialize function to use default for JSON null value.
61pub fn deserialize_null_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
62where
63    T: Default + Deserialize<'de>,
64    D: Deserializer<'de>,
65{
66    let opt = Option::deserialize(deserializer)?;
67    Ok(opt.unwrap_or_default())
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn is_zero_work_for_i32() {
76        assert!(is_zero(0i32));
77    }
78
79    #[test]
80    fn is_zero_work_for_u64() {
81        assert!(is_zero(0u64));
82    }
83}