prost_reflect_validate/lib.rs
1#![doc = include_str!("../README.md")]
2
3use crate::registry::REGISTRY;
4use prost_reflect::ReflectMessage;
5
6mod any;
7mod bool;
8mod bytes;
9mod duration;
10mod r#enum;
11mod field;
12mod list;
13mod map;
14mod message;
15mod number;
16mod registry;
17mod string;
18mod timestamp;
19mod utils;
20
21/// Extension trait for validating messages using [`prost-reflect`](https://docs.rs/prost-reflect/latest/prost_reflect/).
22///
23/// The implementation is provided for the [`prost_reflect::ReflectMessage`](https://docs.rs/prost-reflect/latest/prost_reflect/trait.ReflectMessage.html) trait:
24/// ```rust
25/// use prost_reflect_validate::ValidatorExt;
26/// use example_proto::ExampleMessage;
27///
28/// match ExampleMessage::default().validate() {
29/// Ok(_) => println!("Validation passed"),
30/// Err(e) => eprintln!("Validation failed: {}", e),
31/// }
32/// let msg = ExampleMessage{content: "Hello, world!".to_string()};
33/// match msg.validate() {
34/// Ok(_) => println!("Validation passed"),
35/// Err(e) => eprintln!("Validation failed: {}", e),
36/// }
37/// ```
38pub trait ValidatorExt: Send + Sync {
39 fn validate(&self) -> prost_validate::Result<()>;
40}
41
42impl<T: ReflectMessage> ValidatorExt for T {
43 fn validate(&self) -> prost_validate::Result<()> {
44 validate(self)
45 }
46}
47
48pub fn validate<T: ReflectMessage>(msg: &T) -> prost_validate::Result<()> {
49 let msg = msg.transcode_to_dynamic();
50 REGISTRY.validate(&msg)
51}