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
//! A library for newline character converting.
//!
//! # Examples
//!
//! Using the extension trait:
//!
//! ```
//! use newline_converter::AsRefStrExt;
//! assert_eq!("foo\r\nbar", "foo\nbar".to_dos());
//! ```
//!
//! ```
//! use newline_converter::AsRefStrExt;
//! assert_eq!("foo\nbar", "foo\r\nbar".to_unix());
//! ```
//!
//! Using conversion functions directly:
//!
//! ```
//! assert_eq!("foo\r\nbar", newline_converter::unix2dos("foo\nbar"));
//! ```
//!
//! ```
//! assert_eq!("foo\nbar", newline_converter::dos2unix("foo\r\nbar"));
//! ```
//!
//! The conversion functions are **lazy** - they don't perform any allocations if the input is already in correct format.

#![deny(missing_docs)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]

use std::borrow::Cow;
use unicode_segmentation::UnicodeSegmentation;

const UNPACK_MSG: &str = "Grapheme should always be found -- Please file a bug report";

/// Converts DOS-style line endings (`\r\n`) to UNIX-style (`\n`).
///
/// The input string may already be in correct format, so this function
/// returns `Cow<str>`, to avoid unnecessary allocation and copying.
///
/// # Examples
/// ```
/// assert_eq!(newline_converter::dos2unix("\r\nfoo\r\nbar\r\n"), "\nfoo\nbar\n");
/// ```
///
/// Lone `\r` bytes will be preserved:
/// ```
///  assert_eq!(
///    newline_converter::dos2unix("\nfoo\rbar\r\n"),
///    "\nfoo\rbar\n"
///  );
/// ```
pub fn dos2unix<T: AsRef<str> + ?Sized>(input: &T) -> Cow<str> {
    let mut iter = input.as_ref().chars().peekable();

    let input = input.as_ref();
    let mut output: Option<String> = None;

    while let Some(current) = iter.next() {
        if '\r' == current {
            if let Some('\n') = iter.peek() {
                // drop it
                if output.is_none() {
                    let n = input.chars().filter(|x| *x == '\r').count();
                    let mut buffer = String::with_capacity(input.len() - n);
                    let i = input
                        .grapheme_indices(true)
                        .find(|(_, x)| *x == "\r\n")
                        .map_or_else(|| unreachable!("{}", UNPACK_MSG), |(i, _)| i);
                    let (past, _) = input.split_at(i);
                    buffer.push_str(past);
                    output = Some(buffer);
                }
                continue;
            }
        }
        if let Some(o) = output.as_mut() {
            o.push(current);
        }
    }

    match output {
        None => Cow::Borrowed(input),
        Some(o) => Cow::Owned(o),
    }
}

#[allow(clippy::match_like_matches_macro)] // MSRV 1.38, matches! macro available in 1.42
/// Converts UNIX-style line endings (`\n`) to DOS-style (`\r\n`).
///
/// The input string may already be in correct format, so this function
/// returns `Cow<str>`, to avoid unnecessary allocation and copying.
///
/// # Examples
/// ```
/// assert_eq!(newline_converter::unix2dos("\nfoo\nbar\n"), "\r\nfoo\r\nbar\r\n");
/// ```
///
/// Already present DOS line breaks are respected:
/// ```
/// assert_eq!(newline_converter::unix2dos("\nfoo\r\nbar\n"), "\r\nfoo\r\nbar\r\n");
/// ```
pub fn unix2dos<T: AsRef<str> + ?Sized>(input: &T) -> Cow<str> {
    let mut output: Option<String> = None;
    let mut last_char: Option<char> = None;

    let input = input.as_ref();
    for (i, current) in input.chars().enumerate() {
        if '\n' == current
            && (i == 0
                || match last_char {
                    Some('\r') => false,
                    _ => true,
                })
        {
            if output.is_none() {
                let n = input.chars().filter(|x| *x == '\n').count();
                let mut buffer = String::with_capacity(input.len() + n);
                let i = input
                    .grapheme_indices(true)
                    .find(|(_, x)| *x == "\n")
                    .map_or_else(|| unreachable!("{}", UNPACK_MSG), |(i, _)| i);
                let (past, _) = input.split_at(i);
                buffer.push_str(past);
                output = Some(buffer);
            }
            match output.as_mut() {
                Some(o) => o.push('\r'),
                None => unreachable!(),
            }
        }
        last_char = Some(current);

        if let Some(o) = output.as_mut() {
            o.push(current);
        }
    }

    match output {
        Some(o) => Cow::Owned(o),
        None => Cow::Borrowed(input),
    }
}

/// Extension trait for converting between DOS and UNIX linebreaks.
pub trait AsRefStrExt {
    /// Converts linebreaks to DOS (`\r\n`). See [`unix2dos`] for more info.
    ///
    /// # Examples
    ///
    /// ```
    /// use newline_converter::AsRefStrExt;
    /// assert_eq!("foo\r\nbar", "foo\nbar".to_dos());
    /// ```
    fn to_dos(&self) -> Cow<str>;

    /// Converts linebreaks to UNIX (`\n`). See [`dos2unix`] for more info.
    ///
    /// # Examples
    ///
    /// ```
    /// use newline_converter::AsRefStrExt;
    /// assert_eq!("foo\nbar", "foo\r\nbar".to_unix());
    /// ```
    fn to_unix(&self) -> Cow<str>;
}

impl<T> AsRefStrExt for T
where
    T: AsRef<str>,
{
    fn to_dos(&self) -> Cow<str> {
        unix2dos(self)
    }

    fn to_unix(&self) -> Cow<str> {
        dos2unix(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quickcheck::{quickcheck, TestResult};

    #[test]
    fn middle() {
        assert_eq!(dos2unix("foo\r\nbar"), "foo\nbar".to_dos().to_unix());
        assert_eq!(unix2dos("foo\nbar"), "foo\r\nbar");
    }

    #[test]
    fn beginning() {
        assert_eq!(dos2unix("\r\nfoobar"), "\nfoobar");
        assert_eq!(unix2dos("\nfoobar"), "\r\nfoobar");
    }

    #[test]
    fn end() {
        assert_eq!(dos2unix("foobar\r\n"), "foobar\n");
        assert_eq!(unix2dos("foobar\n"), "foobar\r\n");
    }

    #[test]
    fn all() {
        assert_eq!(dos2unix("\r\nfoo\r\nbar\r\n"), "\nfoo\nbar\n");
        assert_eq!(unix2dos("\nfoo\nbar\n"), "\r\nfoo\r\nbar\r\n");
    }

    #[test]
    fn advanced() {
        assert_eq!(unix2dos("\rfoo\r\nbar\n"), "\rfoo\r\nbar\r\n");
        assert_eq!(dos2unix("\nfoo\rbar\r\n"), "\nfoo\rbar\n");
    }

    #[test]
    fn not_mutated_dos2unix() {
        let converted = dos2unix("\nfoo\nbar\n");
        assert_eq!(converted, Cow::Borrowed("\nfoo\nbar\n") as Cow<str>);
    }

    #[test]
    fn mutated_dos2unix() {
        let converted = dos2unix("\r\nfoo\r\nbar\r\n");
        assert_eq!(
            converted,
            Cow::Owned(String::from("\nfoo\nbar\n")) as Cow<str>
        );
    }

    #[test]
    fn not_mutated_unix2dos() {
        let converted = unix2dos("\r\nfoo\r\nbar\r\n");
        assert_eq!(converted, Cow::Borrowed("\r\nfoo\r\nbar\r\n") as Cow<str>);
    }

    #[test]
    fn mutated_unix2dos() {
        let converted = unix2dos("\nfoo\nbar\n");
        assert_eq!(
            converted,
            Cow::Owned(String::from("\r\nfoo\r\nbar\r\n")) as Cow<str>
        );
    }

    #[test]
    fn non_ascii_characters_unix2dos() {
        assert_eq!(
            unix2dos("Zażółć\ngęślą\njaźń\n"),
            "Zażółć\r\ngęślą\r\njaźń\r\n"
        );
    }

    #[test]
    fn non_ascii_characters_dos2unix() {
        assert_eq!(
            dos2unix("Zażółć\r\ngęślą\r\njaźń\r\n"),
            "Zażółć\ngęślą\njaźń\n"
        );
    }

    #[test]
    // https://github.com/spitfire05/rnc/issues/14
    fn panics_in_0_2_1_unix2dos() {
        assert_eq!(unix2dos("ä\n"), "ä\r\n");
    }

    #[test]
    // https://github.com/spitfire05/rnc/issues/14
    fn panics_in_0_2_1_dos2unix() {
        assert_eq!(dos2unix("ä\r\n"), "ä\n");
    }

    #[test]
    fn just_linebreak_dos2unix() {
        assert_eq!(dos2unix("\r\n"), "\n");
    }

    #[test]
    fn just_linebreak_unix2dos() {
        assert_eq!(unix2dos("\n"), "\r\n");
    }

    quickcheck! {
        fn dos_unix_dos(data: String) -> TestResult {
            if data.contains("\r\n") {
                return TestResult::discard();
            }

            TestResult::from_bool(data.replace('\n', "\r\n") == unix2dos(&dos2unix(&data)))
        }

        fn unix_dos_unix(data: String) -> bool {
            data.replace("\r\n", "\n") == dos2unix(&unix2dos(&data))
        }

        fn unix_contains_no_crlf(data: String) -> bool {
            !dos2unix(&data).contains("\r\n")
        }

        fn dos_has_no_lf_without_cr(data: String) -> bool {
            let dos = unix2dos(&data);
            let crlf = dos.graphemes(true).filter(|x| *x == "\r\n").count();
            let lf = dos.chars().filter(|x| *x == '\n').count();

            lf == crlf
        }

        fn to_unix_equals_dos2unix(data: String) -> bool {
            dos2unix(&data) == data.to_unix()
        }

        fn to_dos_equals_unix2dos(data: String) -> bool {
            unix2dos(&data) == data.to_dos()
        }
    }
}