surjection_core/formats/
text.rs1use 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 pub bom: bool,
20 pub line_ending: LineEnding,
23 pub final_newline: bool,
26}
27
28pub 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
53pub 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
75pub 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}