Simple checked newtype generator, primarily for use with serde.
Serde support (and dependency) may be disabled with default_features = false
.
This is #![no_std]
library.
Usage: ```rust validated_newtype! { /// Documentation comments and attributes are applied #[derive(Debug, PartialOrd, Ord, PartialEq, Eq)] // basic type name => optional visibility + newtype name u32 => pub Percent // condition to check when creating/deserializing if |n: &u32| *n <= 100; // error message if condition is not met error "percent must be in range 0-100" }
let x: Percent = serdejson::fromstr("42").unwrap();
asserteq!(*x, 42);
let y: Result
```rust validated_newtype! { #[derive(Debug)] u32 => pub Percent if |n: &u32| *n <= 100; else |n: &u32| format!("number {} is not in range 0-100", n) => String }
// Deserialize for newtypes uses tryinto internally
let x: Result
```rust validated_newtype! { #[derive(Debug)] u32 => pub Percent }
impl TryFrom
fn try_from(val: u32) -> Result<Self, Self::Error> {
if val > 100 {
Err("percent must be in range 0-100")
} else {
Ok(Self(val))
}
}
}
let x: Percent = serdejson::fromstr("42").unwrap();
asserteq!(*x, 42);
let y: Result