Skip to main content

surjection_core/formats/
text.rs

1//! Byte-level style of a text file: UTF-8 BOM, line endings, final newline.
2//!
3//! Editors work on BOM-free text with `\n` line endings; [`decode`] and
4//! [`encode`] translate exactly, so untouched lines come back byte for byte.
5
6use crate::error::{CoreError, ErrorCode};
7
8const BOM: char = '\u{feff}';
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum LineEnding {
12    Lf,
13    Crlf,
14}
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17pub struct TextStyle {
18    /// The file starts with a UTF-8 byte order mark.
19    pub bom: bool,
20    /// `Crlf` when every line break is `\r\n`. A file that mixes both is
21    /// `Lf`: its breaks are kept as they are and new lines get `\n`.
22    pub line_ending: LineEnding,
23    /// The file ends with a line break (an empty file counts as one, so a new
24    /// file gets one).
25    pub final_newline: bool,
26}
27
28/// UTF-8 text without BOM and, for CRLF files, with `\n` line endings.
29pub fn decode(bytes: &[u8]) -> Result<(String, TextStyle), CoreError> {
30    let text = std::str::from_utf8(bytes).map_err(|err| {
31        CoreError::new(ErrorCode::ParseError, format!("file is not UTF-8: {err}"))
32    })?;
33    let bom = text.starts_with(BOM);
34    let text = text.strip_prefix(BOM).unwrap_or(text);
35    let crlf = text.contains('\n') && text.matches('\n').count() == text.matches("\r\n").count();
36    let style = TextStyle {
37        bom,
38        line_ending: if crlf {
39            LineEnding::Crlf
40        } else {
41            LineEnding::Lf
42        },
43        final_newline: text.is_empty() || text.ends_with('\n'),
44    };
45    let text = if crlf {
46        text.replace("\r\n", "\n")
47    } else {
48        text.to_owned()
49    };
50    Ok((text, style))
51}
52
53/// The inverse of [`decode`]. Also restores the presence or absence of a
54/// final line break, which an edit at the end of the file may have changed.
55pub fn encode(text: &str, style: TextStyle) -> Vec<u8> {
56    let mut text = text.to_owned();
57    if style.final_newline {
58        if !text.is_empty() && !text.ends_with('\n') {
59            text.push('\n');
60        }
61    } else if text.ends_with('\n') {
62        text.pop();
63    }
64    if style.line_ending == LineEnding::Crlf {
65        text = text.replace('\n', "\r\n");
66    }
67    let mut bytes = Vec::with_capacity(text.len() + 3);
68    if style.bom {
69        bytes.extend_from_slice(BOM.encode_utf8(&mut [0; 4]).as_bytes());
70    }
71    bytes.extend_from_slice(text.as_bytes());
72    bytes
73}
74
75/// 1-based line and column of byte `offset` in `text`, for messages.
76pub fn line_col(text: &str, offset: usize) -> (usize, usize) {
77    let before = &text[..offset.min(text.len())];
78    let line = before.matches('\n').count() + 1;
79    let column = before
80        .rfind('\n')
81        .map_or(before, |newline| &before[newline + 1..])
82        .chars()
83        .count()
84        + 1;
85    (line, column)
86}