summaryrefslogtreecommitdiffstats
path: root/third_party/rust/smart-default/src/util.rs
blob: 452ac91f9515d9b626cfebd075d1e8fb8525fda3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use syn::spanned::Spanned;
use syn::parse::Error;

/// Return the value that fulfills the predicate if there is one in the slice. Panic if there is
/// more than one.
pub fn find_only<T, F>(iter: impl Iterator<Item = T>, pred: F) -> Result<Option<T>, Error>
where T: Spanned,
      F: Fn(&T) -> Result<bool, Error>,
{
    let mut result = None;
    for item in iter {
        if pred(&item)? {
            if result.is_some() {
                return Err(Error::new(item.span(), "Multiple defaults"));
            }
            result = Some(item);
        }
    }
    Ok(result)
}

pub fn single_value<T>(mut it: impl Iterator<Item = T>) -> Option<T> {
    if let Some(result) = it.next() {
        if it.next().is_none() {
            return Some(result)
        }
    }
    None
}