Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ pub enum Either<L, R> {
/// This macro is useful in cases where both sides of [`Either`] can be interacted with
/// in the same way even though the don't share the same type.
///
/// Syntax: `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)`
/// Syntax:
///
/// - `either::for_both!(` *expression* `,` *pattern* `=>` *expression* `)`
/// - `either::for_both!(` *ident* `=>` *expression* `)`
///
/// # Example
///
Expand All @@ -77,6 +80,22 @@ pub enum Either<L, R> {
/// assert_eq!(length(owned), 12);
/// }
/// ```
///
/// ```
/// use either::Either;
///
/// fn length(s: Either<String, Vec<u8>>) -> usize {
/// either::for_both!(s => s.len())
/// }
///
/// fn main() {
/// let string = Either::Left("Hello world!".to_owned());
/// let bytes = Either::Right(b"Hello world!".to_vec());
///
/// assert_eq!(length(string), 12);
/// assert_eq!(length(bytes), 12);
/// }
/// ```
#[macro_export]
macro_rules! for_both {
($value:expr, $pattern:pat => $result:expr) => {
Expand All @@ -85,6 +104,12 @@ macro_rules! for_both {
$crate::Either::Right($pattern) => $result,
}
};
($name:ident => $result:expr) => {
match $name {
$crate::Either::Left($name) => $result,
$crate::Either::Right($name) => $result,
}
};
}

/// Macro for unwrapping the left side of an [`Either`], which fails early
Expand Down