Skip to content

Commit

Permalink
Allow iterating over audiences. (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
bittrance authored May 27, 2024
1 parent f6edd85 commit caa712f
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ impl<T> OneOrMany<T> {
fn is_empty(&self) -> bool {
matches!(self, OneOrMany::Vec(v) if v.is_empty())
}

/// Iterate over the values regardless of whether it contains one or many.
#[inline]
pub fn iter(&self) -> OneOrManyIter<T> {
OneOrManyIter::new(self)
}
}

impl<T> Default for OneOrMany<T> {
Expand All @@ -72,6 +78,37 @@ impl<T> Default for OneOrMany<T> {
}
}

pub struct OneOrManyIter<'a, T> {
one: Option<&'a T>,
many: Option<std::slice::Iter<'a, T>>,
}

impl<'a, T> OneOrManyIter<'a, T> {
fn new(inner: &'a OneOrMany<T>) -> Self {
match inner {
OneOrMany::One(v) => Self {
one: Some(v),
many: None,
},
OneOrMany::Vec(v) => Self {
one: None,
many: Some(v.iter()),
},
}
}
}

impl<'a, T> Iterator for OneOrManyIter<'a, T> {
type Item = &'a T;

fn next(&mut self) -> Option<Self::Item> {
if let Some(one) = self.one.take() {
return Some(one);
}
self.many.as_mut().and_then(|iter| iter.next())
}
}

/// JWT Claims.
#[serde_as]
#[skip_serializing_none]
Expand Down Expand Up @@ -502,6 +539,21 @@ mod tests {

use super::*;

#[test]
fn one_or_many_iterator() {
let v = OneOrMany::Vec(vec![1, 2, 3]);
let mut iter = v.iter();
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), None);

let v = OneOrMany::One(1);
let mut iter = v.iter();
assert_eq!(iter.next(), Some(&1));
assert_eq!(iter.next(), None);
}

#[test]
fn signing_and_verification() -> Result<()> {
let mut claims = HeaderAndClaims::new_dynamic();
Expand Down

0 comments on commit caa712f

Please sign in to comment.