Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/ohkami-rs/serdev
SerdeV - Serde with Validation
https://github.com/ohkami-rs/serdev
derive no-std rust serde validation
Last synced: 5 days ago
JSON representation
SerdeV - Serde with Validation
- Host: GitHub
- URL: https://github.com/ohkami-rs/serdev
- Owner: ohkami-rs
- License: mit
- Created: 2024-08-20T13:51:37.000Z (4 months ago)
- Default Branch: main
- Last Pushed: 2024-09-14T09:08:31.000Z (3 months ago)
- Last Synced: 2024-12-07T03:09:01.472Z (15 days ago)
- Topics: derive, no-std, rust, serde, validation
- Language: Rust
- Homepage:
- Size: 67.4 KB
- Stars: 48
- Watchers: 0
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
SerdeV
SerdeV - Serde with Validation
- Just a wrapper of Serde and 100% compatible
- Declarative validation in deserialization by `#[serde(validate = "...")]`## Example
```toml
[dependencies]
serdev = "0.2"
serde_json = "1.0"
``````rust
use serdev::{Serialize, Deserialize};#[derive(Serialize, Deserialize, Debug)]
#[serde(validate = "Self::validate")]
struct Point {
x: i32,
y: i32,
}impl Point {
fn validate(&self) -> Result<(), impl std::fmt::Display> {
if self.x * self.y > 100 {
return Err("x * y must not exceed 100")
}
Ok(())
}
}fn main() {
let point = serde_json::from_str::(r#"
{ "x" : 1, "y" : 2 }
"#).unwrap();// Prints point = Point { x: 1, y: 2 }
println!("point = {point:?}");let error = serde_json::from_str::(r#"
{ "x" : 10, "y" : 20 }
"#).unwrap_err();// Prints error = x * y must not exceed 100
println!("error = {error}");
}
```Of course, you can use it in combination with some validation tools like validator! ( full example )
## Attribute
- `#[serde(validate = "function")]`
Automatically validate by the `function` in deserialization. The `function` must be callable as `fn(&self) -> Result<(), impl Display>`.\
Errors are converted to a `String` internally and passed to `serde::de::Error::custom`.- `#[serde(validate(by = "function", error = "Type"))]`
Using given `Type` for validation error without internal conversion. The `function` must explicitly return `Result<(), Type>`.\
This may be preferred when you need better performance _even in error cases_.\
For **no-std** use, this is the only way supported.Both `"function"` and `"Type"` accept path like `"crate::util::validate"`.
Additionally, `#[serdev(crate = "path::to::serdev")]` is supported for reexport from another crate.
## License
Licensed under MIT LICENSE ( [LICENSE](https://github.com/ohkami-rs/serdev/blob/main/LICENSE) or [https://opensource.org/licenses/MIT](https://opensource.org/licenses/MIT) ).