diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 12:41:41 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-04 12:41:41 +0000 |
commit | 10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87 (patch) | |
tree | bdffd5d80c26cf4a7a518281a204be1ace85b4c1 /vendor/normalize-line-endings/src | |
parent | Releasing progress-linux version 1.70.0+dfsg1-9~progress7.99u1. (diff) | |
download | rustc-10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87.tar.xz rustc-10ee2acdd26a7f1298c6f6d6b7af9b469fe29b87.zip |
Merging upstream version 1.70.0+dfsg2.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'vendor/normalize-line-endings/src')
-rw-r--r-- | vendor/normalize-line-endings/src/lib.rs | 82 |
1 files changed, 82 insertions, 0 deletions
diff --git a/vendor/normalize-line-endings/src/lib.rs b/vendor/normalize-line-endings/src/lib.rs new file mode 100644 index 000000000..955234a7e --- /dev/null +++ b/vendor/normalize-line-endings/src/lib.rs @@ -0,0 +1,82 @@ +#![warn(missing_docs)] +//! +//! Normalize line endings +//! +//! This crate provides a `normalize` method that takes a char iterator and returns +//! a new one with `\n` for all line endings + +/// This struct wraps a `std::io::Chars` to normalize line endings. +/// +/// Implements `Iterator<Item=char>` so can be used in place +struct Normalized<I> { + iter: I, + prev_was_cr: bool, +} + +/// Take a Chars and return similar struct with normalized line endings +/// +/// # Example +/// ``` +/// use std::iter::FromIterator; +/// use normalize_line_endings::normalized; +/// +/// let input = "This is a string \n with \r some \n\r\n random newlines\r\r\n\n"; +/// assert_eq!( +/// &String::from_iter(normalized(input.chars())), +/// "This is a string \n with \n some \n\n random newlines\n\n\n" +/// ); +/// ``` +#[inline] +pub fn normalized(iter: impl Iterator<Item = char>) -> impl Iterator<Item = char> { + Normalized { + iter, + prev_was_cr: false, + } +} + +impl<I> Iterator for Normalized<I> +where + I: Iterator<Item = char>, +{ + type Item = char; + fn next(&mut self) -> Option<char> { + match self.iter.next() { + Some('\n') if self.prev_was_cr => { + self.prev_was_cr = false; + match self.iter.next() { + Some('\r') => { + self.prev_was_cr = true; + Some('\n') + } + any => { + self.prev_was_cr = false; + any + } + } + } + Some('\r') => { + self.prev_was_cr = true; + Some('\n') + } + any => { + self.prev_was_cr = false; + any + } + } + } +} + +// tests +#[cfg(test)] +mod tests { + use std::iter::FromIterator; + + #[test] + fn normalized() { + let input = "This is a string \n with \r some \n\r\n random newlines\r\r\n\n"; + assert_eq!( + &String::from_iter(super::normalized(input.chars())), + "This is a string \n with \n some \n\n random newlines\n\n\n" + ); + } +} |