summaryrefslogtreecommitdiff
path: root/crates/arti-relay/src/util.rs
blob: cfda856cb06c5e654beb6efad1cfbf50fa9cfa1c (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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//! Miscellaneous utility functions/macros/types.

use std::fmt::Display;

/// Formats an iterator as an object whose display implementation is a `separator`-separated string
/// of items from `iter`.
// TODO: This can be replaced with `std::fmt::from_fn()` once stabilised and within our MSRV.
pub(crate) fn iter_join(
    separator: &str,
    iter: impl Iterator<Item: Display> + Clone,
) -> impl Display {
    struct Fmt<'a, I: Iterator<Item: Display> + Clone> {
        /// Separates items in `iter`.
        separator: &'a str,
        /// Iterator to join.
        iter: I,
    }
    impl<'a, I: Iterator<Item: Display> + Clone> Display for Fmt<'a, I> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let Self { separator, iter } = self;
            let mut iter = iter.clone();
            if let Some(first) = iter.next() {
                write!(f, "{first}")?;
            }
            for x in iter {
                write!(f, "{separator}{x}")?;
            }
            Ok(())
        }
    }
    Fmt { separator, iter }
}

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(into = "Vec<T>")]
#[serde(try_from = "Vec<T>")]
/// A list that contains at least one item.
///
/// We mainly use this for ensuring the user configures at least one item during config
/// deserialization, but may be useful for enforcing at least one item in the type system.
pub(crate) struct NonEmptyList<T: Clone>(T, Vec<T>);

impl<T: Clone> NonEmptyList<T> {
    /// Get the items in the list.
    ///
    /// Is guaranteed to have at least one item.
    pub(crate) fn iter(&self) -> impl Iterator<Item = &T> {
        Some(&self.0).into_iter().chain(&self.1)
    }
}

impl<T: Clone> From<NonEmptyList<T>> for Vec<T> {
    fn from(from: NonEmptyList<T>) -> Vec<T> {
        Some(from.0).into_iter().chain(from.1).collect()
    }
}

impl<T: Clone> TryFrom<Vec<T>> for NonEmptyList<T> {
    type Error = EmptyListError;

    fn try_from(mut from: Vec<T>) -> Result<Self, Self::Error> {
        if from.is_empty() {
            return Err(EmptyListError);
        }
        Ok(Self(from.remove(0), from))
    }
}

#[derive(Debug, thiserror::Error)]
/// An error indicating that the list was empty, so cannot be converted to a [`NonEmptyList`].
#[error("The list is empty")]
pub(crate) struct EmptyListError;

#[cfg(test)]
mod test {
    #![allow(clippy::unwrap_used)]

    use super::*;

    #[test]
    fn non_empty_list() {
        let v = vec![1, 2, 3];
        let l: NonEmptyList<_> = v.clone().try_into().unwrap();
        assert_eq!(v, Vec::from(l));

        assert!(NonEmptyList::<u32>::try_from(Vec::new()).is_err());
    }
}