#[derive(Copy, Clone, Default)]
pub enum LineEndings {
#[default]
Lf, CrLf, }
impl LineEndings {
pub fn name(&self) -> Option<&'static str> {
match self {
Self::Lf => None,
Self::CrLf => Some("DOS"),
}
}
pub fn reader_to_rope<R>(r: R) -> std::io::Result<(Self, ropey::Rope)>
where
R: std::io::Read,
{
use std::io::{BufRead, BufReader};
let mut rope = ropey::RopeBuilder::default();
let mut reader = BufReader::new(r);
let mut line = String::default();
reader.read_line(&mut line)?;
let endings = match line.ends_with("\r\n") {
true => LineEndings::CrLf,
false => LineEndings::Lf,
};
while !line.is_empty() {
if line.ends_with("\r\n") {
assert_eq!(line.pop(), Some('\n'));
assert_eq!(line.pop(), Some('\r'));
line.push('\n');
}
rope.append(&line);
line.clear();
reader.read_line(&mut line)?;
}
Ok((endings, rope.finish()))
}
pub fn reader_to_string<R>(self, mut r: R) -> std::io::Result<String>
where
R: std::io::Read,
{
let mut s = String::new();
r.read_to_string(&mut s)?;
match self {
Self::Lf => Ok(s),
Self::CrLf => Ok(s.replace("\r\n", "\n")),
}
}
pub fn rope_to_writer<W>(self, rope: &ropey::Rope, mut w: W) -> std::io::Result<()>
where
W: std::io::Write,
{
match self {
Self::Lf => rope.write_to(w),
Self::CrLf => rope.lines().try_for_each(|line| {
let line = std::borrow::Cow::from(line);
match line.strip_suffix('\n') {
Some(line) => write!(w, "{line}\r\n")?,
None => write!(w, "{line}")?,
}
Ok(())
}),
}
}
}