Skip to content

Commit

Permalink
Add from_vec to allow for stricter ownership
Browse files Browse the repository at this point in the history
  • Loading branch information
FintanH committed Apr 2, 2020
1 parent fe71f13 commit 65411ae
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,34 @@ impl<T> NonEmpty<T> {
.map(|(h, t)| NonEmpty(h.clone(), t.into()))
}

/// Often we have a `Vec` (or slice `&[T]`) but want to ensure that it is `NonEmpty` before
/// proceeding with a computation. Using `from_vec` will give us a proof
/// that we have a `NonEmpty` in the `Some` branch, otherwise it allows
/// the caller to handle the `None` case.
///
/// This version will consume the `Vec` you pass in. If you would rather pass the data as a
/// slice then use `NonEmpty::from_slice`.
///
/// # Example Use
///
/// ```
/// use nonempty::NonEmpty;
///
/// let non_empty_vec = NonEmpty::from_vec(vec![1, 2, 3, 4, 5]);
/// assert_eq!(non_empty_vec, Some(NonEmpty::from((1, vec![2, 3, 4, 5]))));
///
/// let empty_vec: Option<NonEmpty<&u32>> = NonEmpty::from_vec(vec![]);
/// assert!(empty_vec.is_none());
/// ```
pub fn from_vec(mut vec: Vec<T>) -> Option<NonEmpty<T>> {
if vec.is_empty() {
None
} else {
let head = vec.remove(0);
Some(NonEmpty(head, vec))
}
}

/// Deconstruct a `NonEmpty` into its head and tail.
/// This operation never fails since we are guranteed
/// to have a head element.
Expand Down

0 comments on commit 65411ae

Please sign in to comment.