serde_validate/lib.rs
1/*
2 * serde-validate - A library for validating deserialized structs and enums
3 *
4 * Copyright (C) 2024 Lucas M. de Jong Larrarte
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20//! # serde-validate
21//!
22//! The `serde-validate` crate provides utilities for validating deserialized structs and enums in Rust.
23//!
24//! The core of the crate is the `Validate` trait, which defines a method for validating instances of types
25//! and returning a custom error type if validation fails. The crate also includes a procedural serde-validate-macro,
26//! `serde-validate`, that generates deserialization code that validates the deserialized data.
27//!
28//! ## Example
29//!
30//! ```rust
31//! use serde_validate::{Validate, validate_deser};
32//!
33//! #[validate_deser]
34//! struct MyStruct {
35//! value: i32,
36//! }
37//!
38//! impl Validate for MyStruct {
39//! type Error = String;
40//!
41//! fn validate(&self) -> Result<(), Self::Error> {
42//! if self.value < 0 {
43//! Err("Value must be non-negative".into())
44//! } else {
45//! Ok(())
46//! }
47//! }
48//! }
49//!
50//! // Assuming you have a JSON input as below:
51//! let good_json_input = r#"{ "value": 10 }"#;
52//!
53//! // Deserialize and validate the JSON input
54//! let my_struct: Result<MyStruct, _> = serde_json::from_str(good_json_input);
55//! assert!(my_struct.is_ok());
56//!
57//! // Assuming you have a JSON input as below:
58//! let bad_json_input = r#"{ "value": -10 }"#;
59//!
60//! // Deserialize and validate the JSON input
61//! let my_struct: Result<MyStruct, _> = serde_json::from_str(bad_json_input);
62//! assert!(my_struct.is_err());
63//! ```
64
65/// The `Validate` trait defines the contract for validating deserialized structs.
66///
67/// Implementors of this trait are required to provide their own validation logic
68/// and an associated error type.
69///
70/// # Example
71///
72/// ```
73/// use serde_validate::Validate;
74///
75/// struct MyStruct {
76/// value: i32,
77/// }
78///
79/// impl Validate for MyStruct {
80/// type Error = String;
81///
82/// fn validate(&self) -> Result<(), Self::Error> {
83/// if self.value < 0 {
84/// Err("Value must be non-negative".into())
85/// } else {
86/// Ok(())
87/// }
88/// }
89/// }
90///
91/// let my_struct = MyStruct { value: 10 };
92/// assert!(my_struct.validate().is_ok());
93/// ```
94pub trait Validate: Sized {
95 /// The error type returned by the `validate` method.
96 type Error;
97
98 /// Validates the instance, returning `Ok(())` if serde-validate, or an `Error` otherwise.
99 fn validate(&self) -> Result<(), Self::Error>;
100
101 /// Consumes the instance, validating it and returning the instance itself if serde-validate.
102 ///
103 /// This method provides a convenient way to validate and immediately use the instance.
104 fn validated(self) -> Result<Self, Self::Error> {
105 self.validate().map(|_| self)
106 }
107}
108
109#[cfg(feature = "macro")]
110pub use serde_validate_macro::validate_deser;