-
Notifications
You must be signed in to change notification settings - Fork 63
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
81 additions
and
62 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 |
---|---|---|
@@ -0,0 +1,79 @@ | ||
use serde::{Deserialize, Serialize}; | ||
|
||
#[derive(Debug, Serialize, Deserialize, Clone)] | ||
#[serde(untagged)] | ||
pub enum OneOrMany<T> { | ||
One(T), | ||
Many(Vec<T>), | ||
} | ||
|
||
impl<T> OneOrMany<T> { | ||
pub fn len(&self) -> usize { | ||
match self { | ||
Self::One(_) => 1, | ||
Self::Many(values) => values.len(), | ||
} | ||
} | ||
|
||
pub fn contains(&self, x: &T) -> bool | ||
where | ||
T: PartialEq<T>, | ||
{ | ||
match self { | ||
Self::One(value) => x == value, | ||
Self::Many(values) => values.contains(x), | ||
} | ||
} | ||
|
||
pub fn first(&self) -> Option<&T> { | ||
match self { | ||
Self::One(value) => Some(&value), | ||
Self::Many(values) => { | ||
if values.len() > 0 { | ||
Some(&values[0]) | ||
} else { | ||
None | ||
} | ||
} | ||
} | ||
} | ||
|
||
pub fn to_single(&self) -> Option<&T> { | ||
match self { | ||
Self::One(value) => Some(&value), | ||
Self::Many(values) => { | ||
if values.len() == 1 { | ||
Some(&values[0]) | ||
} else { | ||
None | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
// consuming iterator | ||
impl<T> IntoIterator for OneOrMany<T> { | ||
type Item = T; | ||
type IntoIter = std::vec::IntoIter<Self::Item>; | ||
|
||
fn into_iter(self) -> Self::IntoIter { | ||
match self { | ||
Self::One(value) => vec![value].into_iter(), | ||
Self::Many(values) => values.into_iter(), | ||
} | ||
} | ||
} | ||
|
||
// non-consuming iterator | ||
impl<'a, T> IntoIterator for &'a OneOrMany<T> { | ||
type Item = &'a T; | ||
type IntoIter = std::vec::IntoIter<Self::Item>; | ||
|
||
fn into_iter(self) -> Self::IntoIter { | ||
match self { | ||
OneOrMany::One(value) => vec![value].into_iter(), | ||
OneOrMany::Many(values) => values.into_iter().collect::<Vec<Self::Item>>().into_iter(), | ||
} | ||
} | ||
} |
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