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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
#![cfg_attr(feature = "nightly", feature(trusted_len))]

//! Joinery provides generic joining of iterables with separators. While it is
//! primarily designed the typical use case of writing to a [writer][fmt::Write]
//! or creating a [`String`] by joining a list of data with some kind of string
//! separator (such as `", "`),  it is fully generic and can be used to combine
//! any iterator or collection with any separator. In this way it is intended
//! to supercede the existing [`SliceConcatExt::join`] method, which only works
//! on slices and can only join with a matching type.
//!
//! # Examples
//!
//! Create a comma separated list:
//!
//! ```
//! use joinery::Joinable;
//!
//! let result = [1, 2, 3, 4].iter().join_with(", ").to_string();
//! assert_eq!(result, "1, 2, 3, 4")
//! ```
//!
//! Create a newline separated list, using a python-style syntax (with the
//! separator at the beginning of the expression):
//!
//! ```
//! use joinery::Separator;
//!
//! let result = '\n'.separate(&[1, 2, 3]).to_string();
//! assert_eq!(result, "1\n2\n3");
//! ```
//!
//! `write!` a comma-separated list:
//!
//! ```
//! use joinery::Joinable;
//! # use std::fmt::Write;
//!
//! let join = vec![1, 2, 3, 4, 5].join_with(", ");
//!
//! let mut result = String::new();
//!
//! write!(&mut result, "Numbers: {}", join);
//! assert_eq!(result, "Numbers: 1, 2, 3, 4, 5");
//!
//! // Note that joins are stateless; they can be reused after writing
//! let result2 = join.to_string();
//! assert_eq!(result2, "1, 2, 3, 4, 5");
//! ```
//!
//! Iterate over joins:
//!
//! ```
//! use joinery::{Joinable, JoinItem};
//!
//! // Note that the collection values and the separator can be different types
//! let join = ["some", "sample", "text"].iter().join_with(' ');
//! let mut join_iter = join.iter();
//!
//! assert_eq!(join_iter.next(), Some(JoinItem::Element(&"some")));
//! assert_eq!(join_iter.next(), Some(JoinItem::Separator(&' ')));
//! assert_eq!(join_iter.next(), Some(JoinItem::Element(&"sample")));
//! assert_eq!(join_iter.next(), Some(JoinItem::Separator(&' ')));
//! assert_eq!(join_iter.next(), Some(JoinItem::Element(&"text")));
//! assert_eq!(join_iter.next(), None);
//! ```
//!
//! Display the first 5 consecutive multiples of 1-5 on separate lines:
//!
//! ```
//! use joinery::Joinable;
//! let multiples = 1..=5;
//! let ranges = multiples.map(|m| (1..=5).map(move |n| n * m));
//!
//! let lines = ranges.map(|range| range.join_with(", "));
//! let result = lines.join_with('\n').to_string();
//! assert_eq!(result, "1, 2, 3, 4, 5\n\
//!                     2, 4, 6, 8, 10\n\
//!                     3, 6, 9, 12, 15\n\
//!                     4, 8, 12, 16, 20\n\
//!                     5, 10, 15, 20, 25");
//! ```

use std::fmt::{self, Debug, Display, Formatter};
use std::iter::{FusedIterator, Peekable};

#[cfg(feature = "nightly")]
use std::iter::TrustedLen;

/// A trait for converting iterables and collections into [`Join`] instances.
///
/// This trait is the primary way to create [`Join`] instances. It is
/// implemented for all [`IntoIterator`] types. See
/// [`join_with`][Joinable::join_with] for an example of its usage.
pub trait Joinable {
    /// The iterator type which will be used in the join.
    type IntoIter;

    /// Combine this object with a separator to create a new [`Join`] instance.
    /// Note that the separator does not have to share the same type as the
    /// iterator's values.
    ///
    /// # Examples
    ///
    /// ```
    /// use joinery::Joinable;
    ///
    /// let parts = vec!["this", "is", "a", "sentence"];
    /// let join = parts.iter().join_with(' ');
    /// assert_eq!(join.to_string(), "this is a sentence");
    /// ```
    fn join_with<S>(self, sep: S) -> Join<Self::IntoIter, S>;

    /// Join this object without a separator. When rendered with [`Display`],
    /// the underlying elements will be directly concatenated.
    ///
    /// # Examples
    ///
    /// ```
    /// use joinery::Joinable;
    ///
    /// let parts = vec!['a', 'b', 'c', 'd', 'e'];
    /// let join = parts.iter().join_concat();
    /// assert_eq!(join.to_string(), "abcde");
    /// ```
    ///
    /// *New in v1.1.0*
    fn join_concat(self) -> Join<Self::IntoIter, NoSeparator>
    where
        Self: Sized,
    {
        self.join_with(NoSeparator)
    }
}

impl<T: IntoIterator> Joinable for T {
    type IntoIter = T::IntoIter;

    fn join_with<S>(self, sep: S) -> Join<Self::IntoIter, S> {
        Join {
            iter: self.into_iter(),
            sep,
        }
    }
}

// NOTE: we hope that the compiler will detect that most operations on NoSeparator
// are no-ops, and optimize heavily, because I'd rather not implement a separate
// type for empty-separator-joins.

/// Zero-size type representing the empty separator.
///
/// This struct can be used as a separator in cases where you simply want to
/// join the elements of a separator without any elements between them.
///
/// See also the [`join_concat`](Joinable::join_concat) method.
///
/// # Examples
///
/// ```
/// use joinery::{Joinable, NoSeparator};
///
/// let parts = (0..10);
/// let join = parts.join_with(NoSeparator);
/// assert_eq!(join.to_string(), "0123456789");
/// ```
///
/// *New in v1.1.0*
#[derive(Debug, Clone)]
pub struct NoSeparator;

impl Display for NoSeparator {
    fn fmt(&self, _f: &mut Formatter) -> fmt::Result {
        Ok(())
    }
}

/// A trait for using a separator to produce a [`Join`].
///
/// This trait provides a more python-style interface for performing joins.
/// Rather than do [`collection.join_with`][Joinable::join_with], you do:
///
/// ```
/// use joinery::Separator;
///
/// let join = ", ".separate(&[1, 2, 3, 4]);
/// assert_eq!(join.to_string(), "1, 2, 3, 4");
/// ```
///
/// By default, [`Separator`] is implemented for [`char`], [`&str`][str], and
/// [`NoSeparator`].
///
/// Note that any type can be used as a separator in a [`Join`] when
/// creating one via [`Joinable::join_with`]. The [`Separator`] trait and its
/// implementations on [`char`] and [`&str`][str] are provided simply as
/// a convenience.
pub trait Separator {
    /// Combine a [`Separator`] with a [`Joinable`] to create a [`Join`].
    fn separate<T: Joinable>(self, iter: T) -> Join<T::IntoIter, Self>
    where
        Self: Sized,
    {
        iter.join_with(self)
    }
}

impl<'a> Separator for &'a str {}
impl Separator for char {}
impl Separator for NoSeparator {}

/// The primary data structure for representing a joined sequence.
///
/// It contains an interator and a separator, and represents the elements of the
/// iterator with the separator dividing each element.
///
/// A [`Join`] is created with [`Joinable::join_with`] or [`Separator::separate`].
/// It can be [iterated][Join::iter], and implements [`Display`] so that it can
/// be written to a [writer][fmt::Write] or converted into a [`String`].
///
///
/// # Examples
///
/// Writing via [`Display`]:
///
/// ```
/// use joinery::Joinable;
/// use std::fmt::Write;
///
/// let content = 0..10;
/// let join = content.join_with(", ");
///
/// let mut buffer = String::new();
/// write!(buffer, "Numbers: {}", join);
///
/// assert_eq!(buffer, "Numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9");
///
/// // Don't forget that `Display` gives to `ToString` for free!
/// assert_eq!(join.to_string(), "0, 1, 2, 3, 4, 5, 6, 7, 8, 9")
/// ```
///
/// Iterating via [`IntoIterator`]:
///
/// ```
/// use joinery::{Separator, JoinItem};
///
/// let content = 0..3;
/// let join = ", ".separate(content);
/// let mut join_iter = join.into_iter();
///
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(0)));
/// assert_eq!(join_iter.next(), Some(JoinItem::Separator(", ")));
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(1)));
/// assert_eq!(join_iter.next(), Some(JoinItem::Separator(", ")));
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(2)));
/// assert_eq!(join_iter.next(), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Join<Iter, Sep> {
    iter: Iter,
    sep: Sep,
}

impl<I, S> Join<I, S> {
    /// Get a reference to the separator.
    pub fn sep(&self) -> &S {
        &self.sep
    }
    /// Get a reference to the underlying iterator.
    pub fn underlying_iter(&self) -> &I {
        &self.iter
    }
    /// Consume `self` and return the separator and underlying iterator.
    pub fn extract_parts(self) -> (I, S) {
        (self.iter, self.sep)
    }
}

impl<I: Clone, S> Join<I, S> {
    /// Create a partial clone of `self`. A partial clone is a [`Join`] instance
    /// which contains a cloned iterator, but a reference to the original
    /// separator. This is useful in cases where the iterator needs to be
    /// consumed, but there's no need to perform a full clone of the separator
    /// (e.g. if it's a [`String`]).
    ///
    /// Most functions which observe `&self` make use of this conversion
    /// internally, because it's necessary to consume the iterator in order to
    /// render or iterate a [`Join`].
    pub fn partial_clone(&self) -> Join<I, &S> {
        Join {
            iter: self.iter.clone(),
            sep: &self.sep,
        }
    }
}

impl<I, S> Join<I, S>
where
    I: Iterator,
    S: Display,
    I::Item: Display,
{
    /// Consume `self`, writing it to a [`Formatter`]. The [`Display`] trait
    /// requires `&self`, so this method is provided in the event that you can't
    /// or don't want to clone the underlying iterator.
    pub fn consume_fmt(self, f: &mut Formatter) -> fmt::Result {
        let mut iter = self.iter;
        let sep = self.sep;

        match iter.next() {
            None => Ok(()),
            Some(first) => {
                first.fmt(f)?;

                iter.try_for_each(move |element| {
                    sep.fmt(f)?;
                    element.fmt(f)
                })
            }
        }
    }
}

impl<I, S> Display for Join<I, S>
where
    I: Iterator + Clone,
    S: Display,
    I::Item: Display,
{
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.partial_clone().consume_fmt(f)
    }
}

impl<I: Iterator, S: Clone> IntoIterator for Join<I, S> {
    type IntoIter = JoinIter<I, S>;
    type Item = JoinItem<I::Item, S>;

    fn into_iter(self) -> Self::IntoIter {
        self.into()
    }
}

impl<I: Iterator + Clone, S> Join<I, S> {
    /// Create an [iterator][JoinIter] for this [`Join`]. This iterator uses
    /// a clone of the underlying iterator, but a reference to the separator.
    pub fn iter(&self) -> JoinIter<I, &S> {
        self.partial_clone().into_iter()
    }
}

/// Enum representing the elements of a [`JoinIter`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JoinItem<T, S> {
    /// An element from the underlying iterator
    Element(T),
    /// A separator between two elements
    Separator(S),
}

impl<T, S> JoinItem<T, S> {
    /// Convert a [`JoinItem`] into a common type `R`, in the case where both
    /// `T` and `S` can be converted to `R`. Unfortunately, due to potentially
    /// conflicting implementations, we can't implement `Into<R>` for `JoinItem`.
    pub fn into<R>(self) -> R
    where
        T: Into<R>,
        S: Into<R>,
    {
        match self {
            JoinItem::Element(el) => el.into(),
            JoinItem::Separator(sep) => sep.into(),
        }
    }
}

/// Get a reference to a common type `R` from a [`JoinItem`], in the case where
/// both `T` and `S` implement [`AsRef<R>`][AsRef]
impl<R, T: AsRef<R>, S: AsRef<R>> AsRef<R> for JoinItem<T, S> {
    fn as_ref(&self) -> &R {
        match self {
            JoinItem::Element(el) => el.as_ref(),
            JoinItem::Separator(sep) => sep.as_ref(),
        }
    }
}

impl<T: Display, S: Display> Display for JoinItem<T, S> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        use JoinItem::*;

        match self {
            Element(el) => el.fmt(f),
            Separator(sep) => sep.fmt(f),
        }
    }
}

/// An iterator for a [`Join`].
///
/// Emits the elements of the [`Join`]'s underlying iterator, interspersed with
/// its separator. Note that it uses [`clone`][Clone::clone] to generate copies
/// of the separator while iterating, but also keep in mind that in most cases
/// the [`JoinItem`] instance will have a trivially cloneable reference to the
/// separator, rather than the separator itself.
///
/// # Examples
///
/// Via [`IntoIterator`]:
///
/// ```
/// use joinery::{Joinable, JoinItem};
///
/// let join = vec![1, 2, 3].join_with(" ");
/// let mut join_iter = join.into_iter();
///
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(1)));
/// assert_eq!(join_iter.next(), Some(JoinItem::Separator(" ")));
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(2)));
/// assert_eq!(join_iter.next(), Some(JoinItem::Separator(" ")));
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(3)));
/// assert_eq!(join_iter.next(), None);
/// ```
///
/// Via [`.iter()`][Join::iter]
///
/// ```
/// use joinery::{Joinable, JoinItem};
///
/// let join = vec![1, 2, 3].join_with(" ");
/// let mut join_iter = join.iter();
///
/// // Note that using .iter() produces references to the separator, rather than clones.
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(1)));
/// assert_eq!(join_iter.next(), Some(JoinItem::Separator(&" ")));
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(2)));
/// assert_eq!(join_iter.next(), Some(JoinItem::Separator(&" ")));
/// assert_eq!(join_iter.next(), Some(JoinItem::Element(3)));
/// assert_eq!(join_iter.next(), None);
/// ```
pub struct JoinIter<Iter: Iterator, Sep> {
    iter: Peekable<Iter>,
    sep: Sep,
    next_sep: bool,
}

impl<I: Iterator, S> JoinIter<I, S> {
    /// Check if the next iteration of this iterator will (try to) return a
    /// separator. Note that this does not check if the underlying iterator is
    /// empty, so the next `next` call could still return `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use joinery::{Joinable, JoinItem};
    ///
    /// let mut join_iter = (0..3).join_with(", ").into_iter();
    ///
    /// assert_eq!(join_iter.is_sep_next(), false);
    /// join_iter.next();
    /// assert_eq!(join_iter.is_sep_next(), true);
    /// join_iter.next();
    /// assert_eq!(join_iter.is_sep_next(), false);
    /// ```
    #[inline]
    pub fn is_sep_next(&self) -> bool {
        self.next_sep
    }

    /// Get a reference to the separator.
    #[inline]
    pub fn sep(&self) -> &S {
        &self.sep
    }

    /// Peek at what the next item in the iterator will be without consuming
    /// it. Note that this interface is similar, but not identical, to
    /// [`Peekable::peek`].
    ///
    /// # Examples
    ///
    /// ```
    /// use joinery::{Joinable, JoinItem};
    ///
    /// let mut join_iter = (0..3).join_with(", ").into_iter();
    ///
    /// assert_eq!(join_iter.peek(), Some(JoinItem::Element(&0)));
    /// assert_eq!(join_iter.next(), Some(JoinItem::Element(0)));
    /// assert_eq!(join_iter.peek(), Some(JoinItem::Separator(&", ")));
    /// assert_eq!(join_iter.next(), Some(JoinItem::Separator(", ")));
    /// assert_eq!(join_iter.peek(), Some(JoinItem::Element(&1)));
    /// assert_eq!(join_iter.next(), Some(JoinItem::Element(1)));
    /// ```
    pub fn peek(&mut self) -> Option<JoinItem<&I::Item, &S>> {
        let next_sep = self.next_sep;
        let sep = &self.sep;

        self.iter.peek().map(move |element| {
            if next_sep {
                JoinItem::Separator(sep)
            } else {
                JoinItem::Element(element)
            }
        })
    }

    /// Peek at what the next non-separator item in the iterator will be
    /// without consuming it.
    ///
    /// # Examples
    ///
    /// ```
    /// use joinery::{Joinable, JoinItem};
    ///
    /// let mut join_iter = vec!["This", "is", "a", "sentence"].join_with(' ').into_iter();
    ///
    /// assert_eq!(join_iter.peek_element(), Some(&"This"));
    /// assert_eq!(join_iter.peek(), Some(JoinItem::Element(&"This")));
    /// assert_eq!(join_iter.next(), Some(JoinItem::Element("This")));
    ///
    /// assert_eq!(join_iter.peek_element(), Some(&"is"));
    /// assert_eq!(join_iter.peek(), Some(JoinItem::Separator(&' ')));
    /// assert_eq!(join_iter.next(), Some(JoinItem::Separator(' ')));
    ///
    /// assert_eq!(join_iter.peek_element(), Some(&"is"));
    /// assert_eq!(join_iter.peek(), Some(JoinItem::Element(&"is")));
    /// assert_eq!(join_iter.next(), Some(JoinItem::Element("is")));
    /// ```
    pub fn peek_element(&mut self) -> Option<&I::Item> {
        self.iter.peek()
    }
}

impl<I, S> Debug for JoinIter<I, S>
where
    I: Iterator + Debug,
    S: Debug,
    I::Item: Debug,
{
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("JoinIter")
            .field("iter", &self.iter)
            .field("sep", &self.sep)
            .field("next_sep", &self.next_sep)
            .finish()
    }
}

impl<I: Iterator, S> From<Join<I, S>> for JoinIter<I, S> {
    fn from(join: Join<I, S>) -> Self {
        JoinIter {
            iter: join.iter.peekable(),
            sep: join.sep,
            next_sep: false,
        }
    }
}

impl<I, S> Clone for JoinIter<I, S>
where
    I: Iterator + Clone,
    S: Clone,
    I::Item: Clone, // Needed because we use a peekable iterator
{
    fn clone(&self) -> Self {
        JoinIter {
            iter: self.iter.clone(),
            sep: self.sep.clone(),
            next_sep: self.next_sep,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.iter.clone_from(&source.iter);
        self.sep.clone_from(&source.sep);
        self.next_sep = source.next_sep;
    }
}

impl<I: Iterator, S: Clone> JoinIter<I, S> {
    /// Convert the [`JoinItem`] elements of a [`JoinIter`] into some common
    /// type, using [`Into`] The type should be one that both the iterator items
    /// and the separator can be converted into via [`Into`]. Note that, because
    /// [`Into`] is reflexive, this can be used in cases where the separator and
    /// the item are the same type.
    ///
    /// # Examples
    ///
    /// ```
    /// use joinery::Joinable;
    ///
    /// // Use this function to aid with type inference
    /// fn assert_str(lhs: Option<&str>, rhs: Option<&str>) {
    ///     assert_eq!(lhs, rhs);
    /// }
    ///
    /// let content = vec!["Hello", "World!"];
    ///
    /// let join = content.join_with(", ");
    /// let mut iter = join.into_iter().normalize();
    ///
    /// assert_str(iter.next(), Some("Hello"));
    /// assert_str(iter.next(), Some(", "));
    /// assert_str(iter.next(), Some("World!"));
    /// assert_str(iter.next(), None);
    ///
    ///
    /// ```
    pub fn normalize<R>(self) -> impl Iterator<Item = R>
    where
        I::Item: Into<R>,
        S: Into<R>,
    {
        self.map(|item| item.into())
    }
}

/// Get the size of a [`JoinIter`], given the size of the underlying iterator. If
/// next_sep is true, the next element in the [`JoinIter`] will be the separator.
/// Return None in the event of an overflow. This logic is provided as a separate
/// function in the hopes that it will aid compiler optimization, and also with
/// the intention that in the future it will be a `const fn`.
#[inline]
fn join_size(iter_size: usize, next_sep: bool) -> Option<usize> {
    // 32 => 16
    const SIZE_THRESHOLD: usize = (usize::max_value() / 2) + 1;

    if iter_size == 0 {
        Some(0)
    } else if next_sep {
        iter_size.checked_mul(2)
    } else if iter_size > SIZE_THRESHOLD {
        None
    } else {
        // This works because (with wrapping logic) 16 * 2 => 0, 0 - 1 => 31
        Some(iter_size.wrapping_mul(2).wrapping_sub(1))
    }
}

impl<I: Iterator, S: Clone> Iterator for JoinIter<I, S> {
    type Item = JoinItem<I::Item, S>;

    /// Advance to the next item in the Join. This will either be the next
    /// element in the underlying iterator, or a clone of the separator.
    fn next(&mut self) -> Option<Self::Item> {
        let sep = &self.sep;
        let next_sep = &mut self.next_sep;

        if *next_sep {
            self.iter.peek().map(|_| {
                *next_sep = false;
                JoinItem::Separator(sep.clone())
            })
        } else {
            self.iter.next().map(|element| {
                *next_sep = true;
                JoinItem::Element(element)
            })
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let (min, max) = self.iter.size_hint();

        let min = join_size(min, self.next_sep).unwrap_or(usize::max_value());
        let max = max.and_then(|max| join_size(max, self.next_sep));

        (min, max)
    }

    fn fold<B, F>(self, init: B, mut func: F) -> B
    where
        F: FnMut(B, Self::Item) -> B,
    {
        let mut iter = self.iter.map(JoinItem::Element);
        let sep = self.sep;

        let accum = if !self.next_sep {
            match iter.next() {
                None => return init,
                Some(element) => func(init, element),
            }
        } else {
            init
        };

        iter.fold(accum, move |accum, element| {
            let accum = func(accum, JoinItem::Separator(sep.clone()));
            func(accum, element)
        })
    }

    // TODO: Add try_fold implementation based on self.iter.try_fold.
    // Unfortunately, this will be difficult, because when the reducer is called,
    // it has to make a decision about if and when to evaluate the separator.
}

impl<I: FusedIterator, S: Clone> FusedIterator for JoinIter<I, S> {}

#[cfg(feature = "nightly")]
unsafe impl<I: TrustedLen, S: Clone> TrustedLen for JoinIter<I, S> {}

/// The joinery prelude
pub mod prelude {
    pub use {Joinable, Separator};
}

#[cfg(test)]
mod tests {
    macro_rules! join_test {
        ($($test:ident : ($content:expr) @ $join:tt => $expected:expr);*) => {$(
            #[test]
            fn $test() {
                use std::string::ToString;
                use {Joinable, Separator};

                let content = $content;
                let result = content.join_with($join).to_string();
                assert_eq!(result, $expected);

                let content = $content;
                let result = $join.separate(content.into_iter()).to_string();
                assert_eq!(result, $expected);
            }
        )*};
    }

    join_test!{
        join_empty: (0..0) @ ", " => "";
        join_one: (["Hello, World"]) @ ":::" => "Hello, World";
        string_join_char: (["This", "is", "a", "sentence"]) @ ' ' => "This is a sentence";
        char_join_string: (['a', 'b', 'c', 'd', 'e']) @ ", " => "a, b, c, d, e";
        range_join: (0..5) @ ", " => "0, 1, 2, 3, 4"
    }

    #[test]
    fn lines() {
        use {Joinable, Separator};

        let lines = [
            ["This", "is", "line", "1"],
            ["This", "is", "line", "2"],
            ["This", "is", "line", "3"],
        ];

        let result = lines
            .iter()
            .map(|line| ", ".separate(line))
            .join_with('\n')
            .to_string();
        assert_eq!(
            result,
            "This, is, line, 1\n\
             This, is, line, 2\n\
             This, is, line, 3"
        );
    }

    #[test]
    fn counting() {
        use Joinable;

        let result = (1..=5)
            .map(|m| (0..5).map(move |n| n * m).join_with(", "))
            .join_with("\n")
            .to_string();

        assert_eq!(
            result,
            "0, 1, 2, 3, 4\n\
             0, 2, 4, 6, 8\n\
             0, 3, 6, 9, 12\n\
             0, 4, 8, 12, 16\n\
             0, 5, 10, 15, 20"
        );
    }

    mod iter {
        use JoinItem::*;
        use Joinable;

        #[test]
        fn empty_iter() {
            let mut join_iter = (0..0).join_with(", ").into_iter();

            assert_eq!(join_iter.next(), None);
        }

        #[test]
        fn single() {
            let mut join_iter = (0..1).join_with(", ").into_iter();

            assert_eq!(join_iter.next(), Some(Element(0)));
            assert_eq!(join_iter.next(), None);
        }

        #[test]
        fn few() {
            let mut join_iter = (0..3).join_with(", ").into_iter();

            assert_eq!(join_iter.next(), Some(Element(0)));
            assert_eq!(join_iter.next(), Some(Separator(", ")));
            assert_eq!(join_iter.next(), Some(Element(1)));
            assert_eq!(join_iter.next(), Some(Separator(", ")));
            assert_eq!(join_iter.next(), Some(Element(2)));
            assert_eq!(join_iter.next(), None);
        }

        #[test]
        fn regular_size_hint() {
            let mut join_iter = (0..10).join_with(", ").into_iter();
            assert_eq!(join_iter.size_hint(), (19, Some(19)));

            join_iter.next();
            assert_eq!(join_iter.size_hint(), (18, Some(18)));
        }

        #[test]
        fn large_size_hint() {
            let join_iter = (0..usize::max_value() - 10).join_with(", ").into_iter();
            assert_eq!(join_iter.size_hint(), (usize::max_value(), None));
        }

        #[test]
        fn threshold_size_hint() {
            let umax = usize::max_value();
            let usize_threshold = (usize::max_value() / 2) + 1;

            let mut join_iter = (0..usize_threshold + 1).join_with(", ").into_iter();
            assert_eq!(join_iter.size_hint(), (umax, None));

            join_iter.next();
            assert_eq!(join_iter.size_hint(), (umax, None));

            join_iter.next();
            assert_eq!(join_iter.size_hint(), (umax, Some(umax)));
        }

        #[test]
        fn test_partial_iteration() {
            let content = 0..3;
            let mut join_iter = content.join_with(' ').into_iter();

            join_iter.next();

            let rest: Vec<_> = join_iter.collect();
            assert_eq!(
                rest,
                [Separator(' '), Element(1), Separator(' '), Element(2),]
            );
        }

        #[test]
        fn fold() {
            let content = [1, 2, 3];
            let join_iter = content.iter().join_with(4).into_iter();

            let sum = join_iter.fold(0, |accum, next| match next {
                Element(el) => accum + el,
                Separator(sep) => accum + sep,
            });

            assert_eq!(sum, 14);
        }

        #[test]
        fn partial_fold() {
            let content = [1, 2, 3, 4];
            let mut join_iter = content.iter().join_with(1).into_iter();

            join_iter.next();
            join_iter.next();
            join_iter.next();

            let sum = join_iter.fold(0, |accum, next| match next {
                Element(el) => accum + el,
                Separator(sep) => accum + sep,
            });

            assert_eq!(sum, 9);
        }

        #[test]
        fn try_fold() {
            let content = [1, 2, 0, 3];
            let mut join_iter = content.iter().join_with(1).into_iter();

            let result = join_iter.try_fold(0, |accum, next| match next {
                Separator(sep) => Ok(accum + sep),
                Element(el) if *el == 0 => Err(accum),
                Element(el) => Ok(accum + el),
            });

            assert_eq!(result, Err(5));
        }

        #[test]
        fn partial_try_fold() {
            let content = [1, 2, 3];
            let mut join_iter = content.iter().join_with(1).into_iter();

            let _ = join_iter.try_fold(1, |_, next| match next {
                Element(_) => Some(1),
                Separator(_) => None,
            });

            // At this point, the remaining elements in the iterator SHOULD be E(2), S(1), E(3)
            assert_eq!(join_iter.count(), 3);
        }
    }
}