- Just a wrapper of Serde (100% compatible),
- implementing
serde::{Serialize, Deserialize}for your structs, - with providing
#[serde(validate = "...")]for declarative validation in#[derive(Deserialize)].
A manual implementation for "Parse, don't validate" without serdev will be like:
;
This is, actually, (almost) exactly what serdev does!
Such manual implementation may be a trigger of mistakes like using Point directly for parsing user's input.
serdev eliminates such kind of mistakes, automatically performing the specified validation.
Or, manual Deserialize impl?:
Indeed this doesn't cause such misuses, but produces boilerplate... (more and more boilerplate in complex situation)
#[serde(validate)] makes, for a struct having complicated conditions, its Deserialize itself the valid parser of the struct,
in a clean way with near-zero boilerplate.
If you have no pain on this, you may not need serdev.
Example
[]
= "0.3"
= "1.0"
use ;
#[serde(validate = "...")] works with:
-
other validation tools like
validatorcrate or something similar. (working example: validator.rs)use Deserialize; use ; -
inlined closure like
|p| if p.x * p.y <= 100 {Ok(())} else {Err("...")}, not only a method path. (working example: closure.rs)use ;
Attribute
-
#[serde(validate = "function")]Automatically validate the deserialized struct by the
function. Thefunctionmust be an expression that is callable as typefn(&self) -> Result<(), impl Display>(of course the error type must be known at compile time).(expression: an inlined closure as above, or name/path to a
fnor a method, or even a block expression or function calling or anything that are finally evaluated asfn(&self) -> Result<(), impl Display>)Errors are internally converted to a
Stringand passed toserde::de::Error::custom. -
#[serde(validate(by = "function", error = "Type"))]Using given
Typefor the validation error, without conversion. Thefunctionsignature must befn(&self) -> Result<(), Type>.This will be preferred in no-std use, or, maybe when you need better performance in error cases.
Both "function" and "Type" above accept path e.g. "Self::validate" or "crate::util::validate".
Additionally, #[serdev(crate = "path::to::serdev")] is supported for reexport from another crate.
License
Licensed under MIT LICENSE ( LICENSE or https://opensource.org/licenses/MIT ).