Add method to transpose valid options

This commit is contained in:
Benjamin Herman 2022-07-09 15:13:26 -07:00
parent 713e8f4d96
commit ff56bbf7be
No known key found for this signature in database
GPG key ID: A2D1938EC56DBF49
2 changed files with 19 additions and 1 deletions

View file

@ -115,12 +115,21 @@ impl<T: Vet> Vet for Option<T> {
fn is_valid(&self) -> Result<(), Self::VetError> { fn is_valid(&self) -> Result<(), Self::VetError> {
match self { match self {
Some(t) => t.is_valid(), Some(o) => o.is_valid(),
None => Ok(()), None => Ok(()),
} }
} }
} }
impl<T: Vet> Valid<Option<T>> {
pub fn transpose(self) -> Option<Valid<T>> {
match self {
Valid(Some(o)) => Some(Valid(o)),
Valid(None) => None,
}
}
}
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
impl<T: Vet> Vet for alloc::vec::Vec<T> { impl<T: Vet> Vet for alloc::vec::Vec<T> {
type VetError = T::VetError; type VetError = T::VetError;

View file

@ -50,6 +50,15 @@ fn vet_option() {
assert!(foo.is_valid().is_err()); assert!(foo.is_valid().is_err());
} }
#[test]
fn transpose_valid_option() {
let foo = None::<EvenUsize>.vet().unwrap();
assert_eq!(foo.transpose(), None);
let foo = Some(EvenUsize(84)).vet().unwrap();
assert_eq!(foo.transpose(), Some(Valid(EvenUsize(84))));
}
#[test] #[test]
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
fn vet_vec() { fn vet_vec() {