encode/combinators/
separated.rs

1/// Encodes a sequence of encodables separated by a given delimiter.
2///
3/// # Example
4///
5/// ```
6/// # #[cfg(feature = "alloc")] {
7/// use encode::Encodable;
8/// use encode::combinators::Separated;
9///
10/// let mut buf = Vec::new();
11/// let array = ["hello", "world", "another"];
12/// Separated::new(&array, ", ").encode(&mut buf).unwrap();
13/// assert_eq!(&buf, b"hello, world, another");
14/// # }
15/// ```
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
17pub struct Separated<I, S> {
18    encodable_iter: I,
19    separator: S,
20}
21
22impl<I, S> Separated<I, S> {
23    /// Creates a new [`Separated`] combinator.
24    #[inline]
25    pub const fn new(encodable_iter: I, separator: S) -> Self {
26        Self {
27            encodable_iter,
28            separator,
29        }
30    }
31    /// Consumes the [`Separated`] combinator and returns the inner value.
32    #[inline]
33    #[must_use]
34    pub fn into_inner(self) -> (I, S) {
35        (self.encodable_iter, self.separator)
36    }
37}
38
39impl<EncodableIter, Separator, Encoder> crate::Encodable<Encoder>
40    for Separated<EncodableIter, Separator>
41where
42    EncodableIter: IntoIterator + Clone,
43    EncodableIter::Item: crate::Encodable<Encoder, Error = Separator::Error>,
44    Separator: crate::Encodable<Encoder>,
45    Encoder: crate::BaseEncoder,
46{
47    type Error = Separator::Error;
48
49    #[inline]
50    fn encode(&self, encoder: &mut Encoder) -> Result<(), Self::Error> {
51        let mut is_first = true;
52
53        for encodable in self.encodable_iter.clone() {
54            if is_first {
55                is_first = false;
56            } else {
57                self.separator.encode(encoder)?;
58            }
59            encodable.encode(encoder)?;
60        }
61        Ok(())
62    }
63}