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
/// Declares a `Vec<String>` and casts string literals from `&str` to `String`
///
/// # Examples
///
/// ```
/// assert_eq!(tmx_utils::vec_string!["I was once a string slice &str"],
///            vec!["I was once a string slice &str".to_string()]);
/// ```
#[macro_export]
macro_rules! vec_string {
    ($($x:expr),*) => (vec![$(String::from($x)),*]);
}

/// Formats a list of strings with commas and "and" if necessary. Uses the oxford comma.<br>
/// <i>Note: An attempt was made to genericize these functions to work with Vec<T : Display + Join>, but the Join trait is unstable.</i>
///
/// # Examples
///
/// ```
/// # use tmx_utils::string_ext::format_list;
/// assert_eq!(format_list(
///            &vec![]),
///            "nothing");
/// ```
///
/// ```
/// # use tmx_utils::{vec_string, string_ext::format_list};
/// assert_eq!(format_list(&vec_string![
///            "Nona"]),
///            "Nona");
/// ```
///
/// ```
/// # use tmx_utils::{vec_string, string_ext::format_list};
/// assert_eq!(format_list(&vec_string![
///            "Nona", "Samantha"]),
///            "Nona and Samantha");
/// ```
///
/// ```
/// # use tmx_utils::{vec_string, string_ext::format_list};
/// assert_eq!(format_list(&vec_string![
///            "Nona", "Samantha", "Lucy", "Charles"]),
///            "Nona, Samantha, Lucy, and Charles");
/// ```
pub fn format_list(list: &Vec<String>) -> String {
    let love_count: usize = list.len();
    let string_val: String = match love_count {
        0 => String::from("nothing"),
        1 => list[0].to_string(),
        2 => format!("{} and {}", list[0], list[1]),
        _ => format!(
            "{}, and {}",
            list[..love_count - 1].join(", "),
            list[love_count - 1],
        ),
    };
    string_val
}

/// Formats a list of string slices with commas and "and" if necessary. Uses the oxford comma.<br>
/// <i>Note: An attempt was made to genericize these functions to work with Vec<T : Display + Join>, but the Join trait is unstable.</i>
///
/// # Examples
///
/// ```
/// # use tmx_utils::string_ext::format_list_slices;
/// assert_eq!(format_list_slices(
///            &vec![]),
///            "nothing");
/// ```
///
/// ```
/// # use tmx_utils::string_ext::format_list_slices;
/// assert_eq!(format_list_slices(&vec![
///            "Nona"]),
///            "Nona");
/// ```
///
/// ```
/// # use tmx_utils::string_ext::format_list_slices;
/// assert_eq!(format_list_slices(&vec![
///            "Nona", "Samantha"]),
///            "Nona and Samantha");
/// ```
///
/// ```
/// # use tmx_utils::string_ext::format_list_slices;
/// assert_eq!(format_list_slices(&vec![
///            "Nona", "Samantha", "Lucy", "Charles"]),
///            "Nona, Samantha, Lucy, and Charles");
/// ```
pub fn format_list_slices(list: &Vec<&str>) -> String {
    let love_count: usize = list.len();
    let string_val: String = match love_count {
        0 => String::from("nothing"),
        1 => list[0].to_string(),
        2 => format!("{} and {}", list[0], list[1]),
        _ => format!(
            "{}, and {}",
            list[..love_count - 1].join(", "),
            list[love_count - 1],
        ),
    };
    string_val
}

/// Reads a line from `std::io::stdin().lock()` and trims it. Returns an error if the line is empty or if an error is returned from `read_line()`.
///
/// # Examples
///
/// ```
/// # use tmx_utils::string_ext::read_string_stdin;
/// let e = read_string_stdin().err().unwrap();
/// assert!(e.kind() == std::io::ErrorKind::InvalidInput);
/// ```
pub fn read_string_stdin() -> Result<String, std::io::Error> {
    read_string(&mut std::io::stdin().lock())
}

/// Reads a line from a reader and trims it. Returns io errors or an error if the line is empty.
///
/// # Examples
///
/// ```
/// # use tmx_utils::string_ext::read_string;
/// let e = read_string(&mut std::io::stdin().lock()).err().unwrap();
/// assert!(e.kind() == std::io::ErrorKind::InvalidInput);
/// ```
///
/// ```
/// # use tmx_utils::string_ext::read_string;
/// use tmx_utils::test_utils::run_file_test;
/// use std::io::BufReader;
///
/// let path = "./read_string.txt";
/// let content = "input_string";
/// run_file_test(
///     |f| {
///         assert_eq!(
///             read_string(BufReader::new(f)).unwrap(),
///             content
///         );
///     },
///     path, content,
/// );
/// ```
pub fn read_string<R>(mut reader: R) -> Result<String, std::io::Error>
where
    R: std::io::BufRead,
{
    let mut input = String::new();
    reader.read_line(&mut input)?;
    let trimmed = input.trim();
    match trimmed.len() {
        0 => Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Input was empty",
        )),
        _ => Ok(trimmed.to_string()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_format_list() {
        assert_eq!(format_list(&vec![]), "nothing");
        assert_eq!(format_list(&vec_string!["Nona"]), "Nona");
        assert_eq!(
            format_list(&vec_string!["Nona", "Samantha"]),
            "Nona and Samantha"
        );
        assert_eq!(
            format_list(&vec_string!["Nona", "Samantha", "Lucy", "Charles"]),
            "Nona, Samantha, Lucy, and Charles"
        );
    }

    #[test]
    fn test_format_list_slices() {
        assert_eq!(format_list_slices(&vec![]), "nothing");
        assert_eq!(format_list_slices(&vec!["Nona"]), "Nona");
        assert_eq!(
            format_list_slices(&vec!["Nona", "Samantha"]),
            "Nona and Samantha"
        );
        assert_eq!(
            format_list_slices(&vec!["Nona", "Samantha", "Lucy", "Charles"]),
            "Nona, Samantha, Lucy, and Charles"
        );
    }

    #[test]
    fn test_read_input() {
        use super::read_string;
        let path = "./test_read_input.txt";
        let content = "input_string";
        crate::test_utils::run_file_test(
            |f| {
                assert_eq!(read_string(std::io::BufReader::new(f)).unwrap(), content);
            },
            path,
            content,
        )
    }
}