Nutype supports generic newtypes, including the use of where clauses and Higher-Ranked Trait Bounds (HRTB).
Generic Newtype with Sanitization and Validation:
#[nutype(
sanitize(with = |mut v| { v.sort(); v }),
validate(predicate = |vec| !vec.is_empty()),
derive(Debug, PartialEq, AsRef, Deref),
)]
struct SortedNotEmptyVec<T: Ord>(Vec<T>);
Generic Newtype with HRTB:
#[nutype(
validate(predicate = |c| c.into_iter().next().is_some()),
derive(Debug)
)]
struct NonEmpty<C>(C)
where
for<'a> &'a C: IntoIterator;
use nutype::nutype;
#[nutype(
sanitize(with = |mut v| { v.sort(); v }),
validate(predicate = |vec| !vec.is_empty()),
derive(Debug, PartialEq, AsRef, Deref),
)]
struct SortedNotEmptyVec<T: Ord>(Vec<T>);
let wise_friends = SortedNotEmptyVec::try_new(vec!["Seneca", "Zeno", "Plato"]).unwrap();
assert_eq!(wise_friends.as_ref(), &["Plato", "Seneca", "Zeno"]);
#[nutype(
validate(predicate = |c| c.into_iter().next().is_some()),
derive(Debug)
)]
struct NonEmpty<C>(C)
where
for<'a> &'a C: IntoIterator;
let non_empty = NonEmpty::try_new(vec![1, 2, 3]).unwrap();
assert!(NonEmpty::try_new(Vec::<i32>::new()).is_err());