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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//! A simple crate to join the elements of iterators, interspersing a separator between all elements.
//! 
//! This is done somewhat efficiently, if possible, meaning if the iterator is cheaply clonable you can
//! directly print the result of [`Join::join()`] without creating a temporary [`String`] in memory.
//!
//! ```
//! use join_string::Join;
//! 
//! assert_eq!(
//!     "foo bar baz".split_whitespace().join(", ").into_string(),
//!     "foo, bar, baz");
//! 
//! println!("{}",
//!     "foo bar baz".split_whitespace()
//!         .map(|s| s.chars().rev().join(""))
//!         .join(' '));
//! // Output: oof rab zab
//! ```

// =============================================================================
//      struct Joiner
// =============================================================================

/// Helper struct that captures the iterator and separator for later joining.
#[derive(Debug)]
pub struct Joiner<I, S> where I: std::iter::Iterator, S: std::fmt::Display {
    iter: I,
    sep: S
}

impl<I, S> Joiner<I, S> where I: std::iter::Iterator, S: std::fmt::Display, I::Item: std::fmt::Display {
    /// Consumes the backing iterator of a [`Joiner`] and returns the joined elements as a new [`String`].
    #[inline]
    pub fn into_string(self) -> String {
        let mut buffer = String::new();
        let _ = self.write_fmt(&mut buffer);
        buffer
    }

    /// Consumes the backing iterator of a [`Joiner`] and writes the joined elements into a [`std::fmt::Write`].
    pub fn write_fmt<W: std::fmt::Write>(mut self, mut writer: W) -> std::fmt::Result {
        if let Some(first) = self.iter.next() {
            write!(writer, "{}", first)?;
            for item in self.iter {
                write!(writer, "{}{}", self.sep, item)?;
            }
        }
        Ok(())
    }

    /// Consumes the backing iterator of a [`Joiner`] and writes the joined elements into a [`std::io::Write`].
    pub fn write_io<W: std::io::Write>(mut self, mut writer: W) -> std::io::Result<()> {
        if let Some(first) = self.iter.next() {
            write!(writer, "{}", first)?;
            for item in self.iter {
                write!(writer, "{}{}", self.sep, item)?;
            }
        }
        Ok(())
    }
}

impl<I, S> From<Joiner<I, S>> for String
where I: std::iter::Iterator, S: std::fmt::Display, I::Item: std::fmt::Display {
    #[inline]
    fn from(value: Joiner<I, S>) -> Self {
        value.into_string()
    }
}

impl<I, S> Clone for Joiner<I, S>
where I: std::iter::Iterator, S: std::fmt::Display, I::Item: std::fmt::Display, I: Clone, S: Clone {
    #[inline]
    fn clone(&self) -> Self {
        Joiner {
            iter: self.iter.clone(),
            sep: self.sep.clone()
        }
    }
}

impl<I, S> std::fmt::Display for Joiner<I, S>
where I: std::iter::Iterator, S: std::fmt::Display, I::Item: std::fmt::Display, I: Clone {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut iter = self.iter.clone();
        if let Some(first) = iter.next() {
            first.fmt(f)?;
            for item in iter {
                self.sep.fmt(f)?;
                item.fmt(f)?;
            }
        }
        Ok(())
    }
}

// =============================================================================
//      trait Join
// =============================================================================

/// Trait that provides a method to join elements of an iterator, interspersing
/// a separator between all elements.
/// 
/// It is also implemented for a few common types that aren't iterators, but
/// have an `iter()` method. Among these types are arrays, slices, and [`Vec`]s.
pub trait Join<I: std::iter::Iterator> {
    fn iter(self) -> I;

    fn join<S>(self, sep: S) -> Joiner<I, S>
    where Self: Sized, S: std::fmt::Display, I::Item: std::fmt::Display {
        Joiner {
            iter: self.iter(),
            sep
        }
    }

    fn join_str<S>(self, sep: S) -> Joiner<DisplayIter<I>, DisplayWrapper<S>>
    where Self: Sized, S: AsRef<str>, I::Item: AsRef<str> {
        Joiner {
            iter: DisplayIter { iter: self.iter() },
            sep: DisplayWrapper (sep)
        }
    }
}

impl<I> Join<I> for I where I: std::iter::Iterator {
    #[inline]
    fn iter(self) -> I {
        self
    }
}

impl<'a, T> Join<core::slice::Iter<'a, T>> for &'a [T] {
    #[inline]
    fn iter(self) -> core::slice::Iter<'a, T> {
        self.iter()
    }
}

impl<'a, T, const N: usize> Join<core::slice::Iter<'a, T>> for &'a [T; N] {
    #[inline]
    fn iter(self) -> core::slice::Iter<'a, T> {
        self.as_slice().iter()
    }
}

impl<'a, T> Join<core::slice::Iter<'a, T>> for &'a Vec<T> {
    #[inline]
    fn iter(self) -> core::slice::Iter<'a, T> {
        self.as_slice().iter()
    }
}

// =============================================================================
//      struct DisplayWrapper
// =============================================================================

/// Helper for joining elements that only implement [`AsRef<str>`], but not [`std::fmt::Display`].
#[repr(transparent)]
#[derive(Debug)]
pub struct DisplayWrapper<T: AsRef<str>> ( T );

impl<T: AsRef<str>> DisplayWrapper<T> {
    #[inline]
    pub fn new(value: T) -> Self {
        Self (value)
    }
}

impl<T> std::fmt::Display for DisplayWrapper<T> where T: AsRef<str> {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.as_ref().fmt(f)
    }
}

impl<T> Clone for DisplayWrapper<T> where T: AsRef<str>, T: Clone {
    #[inline]
    fn clone(&self) -> Self {
        Self (self.0.clone())
    }
}

// =============================================================================
//      struct DisplayIter
// =============================================================================

/// Iterator-facade that maps an iterator over [`AsRef<str>`] to an iterator
/// over [`DisplayWrapper`].
/// 
/// This is used to implement [`Join::join_str()`].
#[derive(Debug)]
pub struct DisplayIter<I>
where I: std::iter::Iterator {
    iter: I
}

impl<I> DisplayIter<I> where I: std::iter::Iterator {
    #[inline]
    pub fn new(elements: impl Join<I>) -> Self {
        Self { iter: elements.iter() }
    }
}

impl<I> std::iter::Iterator for DisplayIter<I>
where I: std::iter::Iterator, I::Item: AsRef<str> {
    type Item = DisplayWrapper<I::Item>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(item) = self.iter.next() {
            return Some(DisplayWrapper (item));
        }
        None
    }

    #[inline]
    fn last(self) -> Option<Self::Item>
    where Self: Sized {
        if let Some(item) = self.iter.last() {
            return Some(DisplayWrapper (item));
        }
        None
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.iter.nth(n).map(|item| DisplayWrapper (item))
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    #[inline]
    #[cfg(target_feature = "iter_advance_by")]
    fn advance_by(&mut self, n: usize) -> Result<(), NonZeroUsize> {
        self.iter.advance_by(n)
    }

    #[cfg(target_feature = "trusted_random_access")]
    #[inline]
    unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item
    where Self: TrustedRandomAccessNoCoerce
    {
        DisplayWrapper (self.iter.__iterator_get_unchecked(idx))
    }
}

impl<I> std::iter::DoubleEndedIterator for DisplayIter<I>
where I: std::iter::DoubleEndedIterator, I::Item: AsRef<str> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if let Some(item) = self.iter.next_back() {
            return Some(DisplayWrapper (item));
        }
        None
    }

    #[inline]
    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
        if let Some(item) = self.iter.nth_back(n) {
            return Some(DisplayWrapper (item));
        }
        None
    }

    #[cfg(target_feature = "iter_advance_by")]
    #[inline]
    fn advance_back_by(&mut self, n: usize) -> Result<(), NonZeroUsize> {
        self.iter.advance_back_by(n)
    }
}

impl<I> Clone for DisplayIter<I> where I: std::iter::Iterator, I: Clone {
    #[inline]
    fn clone(&self) -> Self {
        DisplayIter {
            iter: self.iter.clone()
        }
    }
}

// =============================================================================
//      functions
// =============================================================================

/// Join anything that implements [`Join`], not just iterators.
/// The elements need to implement [`std::fmt::Display`].
/// 
/// You can pass iterators, slices, and borrows of arrays and [`Vec`]s:
/// 
/// ```
/// use join_string::join;
/// 
/// assert_eq!(
///     join(&["foo", "bar", "baz"], ", ").into_string(),
///     "foo, bar, baz"
/// );
/// 
/// assert_eq!(
///     join([1, 2, 3].as_slice(), ", ").into_string(),
///     "1, 2, 3"
/// );
/// 
/// assert_eq!(
///     join(&vec!['a', 'b', 'c'], ", ").into_string(),
///     "a, b, c"
/// );
/// 
/// assert_eq!(
///     join([
///         "foo".to_owned(),
///         "bar".to_owned(),
///         "baz".to_owned()
///     ].iter().rev(), ", ").into_string(),
///     "baz, bar, foo"
/// );
/// ```
#[inline]
pub fn join<I, S>(elements: impl Join<I>, sep: S) -> Joiner<I, S>
where I: std::iter::Iterator, I::Item: std::fmt::Display, S: std::fmt::Display {
    elements.join(sep)
}

/// Join anything that implements [`Join`], not just iterators when elements
/// don't implement [`std::fmt::Display`], but implement [`AsRef<str>`] instead.
/// 
/// You can pass iterators, slices, and borrows of arrays and [`Vec`]s:
/// 
/// ```
/// use join_string::join_str;
/// 
/// assert_eq!(
///     join_str(&["foo", "bar", "baz"], ", ").into_string(),
///     "foo, bar, baz"
/// );
/// 
/// assert_eq!(
///     join_str([
///         &"foo".to_owned(),
///         &"bar".to_owned(),
///         &"baz".to_owned()
///     ].as_slice(), ", ").into_string(),
///     "foo, bar, baz"
/// );
/// 
/// assert_eq!(
///     join_str(&vec!["foo", "bar", "baz"], ", ").into_string(),
///     "foo, bar, baz"
/// );
/// 
/// assert_eq!(
///     join_str([
///         "foo".to_owned(),
///         "bar".to_owned(),
///         "baz".to_owned()
///     ].iter().rev(), ", ").into_string(),
///     "baz, bar, foo"
/// );
/// ```
#[inline]
pub fn join_str<I, S>(elements: impl Join<I>, sep: S) -> Joiner<impl std::iter::Iterator<Item = impl std::fmt::Display>, impl std::fmt::Display>
where I: std::iter::Iterator, I::Item: AsRef<str>, S: AsRef<str> {
    DisplayIter::new(elements).join(DisplayWrapper (sep))
}