| 1 | use alloc::string::String; |
| 2 | |
| 3 | /// Join the list with an 'or' before the last element of the list. |
| 4 | /// |
| 5 | /// # Examples |
| 6 | /// ``` |
| 7 | /// assert_eq!(reword::or_join(&["a", "b"]), "a or b"); |
| 8 | /// assert_eq!(reword::or_join(&["a", "b", "c"]), "a, b or c"); |
| 9 | /// ``` |
| 10 | pub fn or_join<I>(iter: I) -> String |
| 11 | where |
| 12 | I: IntoIterator, |
| 13 | I::Item: AsRef<str>, |
| 14 | { |
| 15 | join(iter, ", ", " or ") |
| 16 | } |
| 17 | |
| 18 | /// Join the list with an 'and' before the last element of the list. |
| 19 | /// |
| 20 | /// # Examples |
| 21 | /// ``` |
| 22 | /// assert_eq!(reword::and_join(&["a", "b"]), "a and b"); |
| 23 | /// assert_eq!(reword::and_join(&["a", "b", "c"]), "a, b and c"); |
| 24 | /// ``` |
| 25 | pub fn and_join<I>(iter: I) -> String |
| 26 | where |
| 27 | I: IntoIterator, |
| 28 | I::Item: AsRef<str>, |
| 29 | { |
| 30 | join(iter, ", ", " and ") |
| 31 | } |
| 32 | |
| 33 | fn join<I>(iter: I, mid_sep: &str, end_sep: &str) -> String |
| 34 | where |
| 35 | I: IntoIterator, |
| 36 | I::Item: AsRef<str>, |
| 37 | { |
| 38 | let mut iter = iter.into_iter(); |
| 39 | let Some(first) = iter.next() else { |
| 40 | return String::new(); |
| 41 | }; |
| 42 | |
| 43 | let (lower, upper) = iter.size_hint(); |
| 44 | let mut string = String::with_capacity(upper.unwrap_or(lower) * 8); |
| 45 | string.push_str(first.as_ref()); |
| 46 | let Some(mut next) = iter.next() else { |
| 47 | return string; |
| 48 | }; |
| 49 | |
| 50 | for peek in iter { |
| 51 | string.push_str(mid_sep); |
| 52 | string.push_str(next.as_ref()); |
| 53 | next = peek; |
| 54 | } |
| 55 | |
| 56 | string.push_str(end_sep); |
| 57 | string.push_str(next.as_ref()); |
| 58 | string |
| 59 | } |