-
Notifications
You must be signed in to change notification settings - Fork 26
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #90 from greyblake/any-type-doc
Any type doc
- Loading branch information
Showing
3 changed files
with
92 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,44 @@ | ||
use nutype::nutype; | ||
|
||
#[derive(Debug)] | ||
pub struct Point { | ||
x: i32, | ||
y: i32, | ||
} | ||
|
||
#[nutype( | ||
derive(Debug), | ||
sanitize(with = |p| { | ||
Point { | ||
x: p.x.clamp(0, 100), | ||
y: p.y.clamp(0, 100), | ||
} | ||
}), | ||
validate(predicate = |p| p.x > p.y), | ||
derive(Debug, PartialEq, Deref, AsRef), | ||
sanitize(with = |mut guests: Vec<String>| { guests.sort(); guests }), | ||
validate(predicate = |guests| !guests.is_empty() ), | ||
)] | ||
pub struct Pos(Point); | ||
pub struct GuestList(Vec<String>); | ||
|
||
fn main() { | ||
// Empty list is not allowed | ||
assert_eq!( | ||
GuestList::new(vec![]), | ||
Err(GuestListError::PredicateViolated) | ||
); | ||
|
||
// Create the list of our guests | ||
let guest_list = GuestList::new(vec![ | ||
"Seneca".to_string(), | ||
"Marcus Aurelius".to_string(), | ||
"Socrates".to_string(), | ||
"Epictetus".to_string(), | ||
]) | ||
.unwrap(); | ||
|
||
fn main() {} | ||
// The list is sorted (thanks to sanitize) | ||
assert_eq!( | ||
guest_list.as_ref(), | ||
&[ | ||
"Epictetus".to_string(), | ||
"Marcus Aurelius".to_string(), | ||
"Seneca".to_string(), | ||
"Socrates".to_string(), | ||
] | ||
); | ||
|
||
// Since GuestList derives Deref, we can use methods from `Vec<T>` | ||
// due to deref coercion (if it's a good idea or not, it's left up to you to decide!). | ||
assert_eq!(guest_list.len(), 4); | ||
|
||
for guest in guest_list.iter() { | ||
println!("{guest}"); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters