use std::io::Read;
use std::path::Path;
#[derive(Debug, Clone)]
pub struct LineMap {
text: String,
starts: Vec<usize>,
n: usize,
}
impl LineMap {
pub fn new(text: String) -> Self {
let mut starts = vec![0usize];
for (j, b) in text.bytes().enumerate() {
if b == b'\n' && j + 1 < text.len() {
starts.push(j + 1);
}
}
let n = if text.is_empty() { 0 } else { starts.len() };
LineMap { text, starts, n }
}
#[must_use]
pub fn n(&self) -> usize {
self.n
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
#[must_use]
pub fn line_of(&self, o: usize) -> usize {
self.starts.partition_point(|&s| s <= o)
}
#[must_use]
pub fn span(&self, a: usize, b: usize) -> &str {
if a < 1 || a > b || a > self.n {
return "";
}
let start = self.starts[a - 1];
let end = if b < self.n {
self.starts[b]
} else {
self.text.len()
};
&self.text[start..end]
}
#[must_use]
pub fn chars(&self, a: usize, b: usize) -> usize {
self.span(a, b).chars().count()
}
}
#[derive(Debug)]
pub enum LoadErr {
Io(std::io::Error),
NotUtf8,
}
pub fn load_text(path: &Path) -> Result<String, LoadErr> {
decode(&std::fs::read(path).map_err(LoadErr::Io)?)
}
pub fn load_stdin() -> Result<String, LoadErr> {
let mut bytes = Vec::new();
std::io::stdin()
.read_to_end(&mut bytes)
.map_err(LoadErr::Io)?;
decode(&bytes)
}
fn decode(bytes: &[u8]) -> Result<String, LoadErr> {
let bytes = bytes
.strip_prefix([0xEF, 0xBB, 0xBF].as_slice())
.unwrap_or(bytes);
String::from_utf8(bytes.to_vec()).map_err(|_| LoadErr::NotUtf8)
}
#[must_use]
pub fn io_reason(e: &std::io::Error) -> String {
match e.kind() {
std::io::ErrorKind::NotFound => "No such file or directory".into(),
std::io::ErrorKind::IsADirectory => "is a directory".into(),
_ => e.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lm(s: &str) -> LineMap {
LineMap::new(s.to_string())
}
#[test]
fn empty() {
let l = lm("");
assert_eq!(l.n(), 0);
assert_eq!(l.span(1, 1), "");
}
#[test]
fn lone_newline() {
let l = lm("\n");
assert_eq!(l.n(), 1);
assert_eq!(l.span(1, 1), "\n");
}
#[test]
fn single_no_newline() {
let l = lm("a");
assert_eq!(l.n(), 1);
assert_eq!(l.span(1, 1), "a");
assert_eq!(l.line_of(0), 1);
}
#[test]
fn single_with_newline() {
let l = lm("a\n");
assert_eq!(l.n(), 1);
assert_eq!(l.span(1, 1), "a\n");
}
#[test]
fn two_lines() {
let l = lm("a\nb");
assert_eq!(l.n(), 2);
assert_eq!(l.span(1, 1), "a\n");
assert_eq!(l.span(2, 2), "b");
assert_eq!(l.span(1, 2), "a\nb");
assert_eq!(l.line_of(0), 1);
assert_eq!(l.line_of(1), 1);
assert_eq!(l.line_of(2), 2);
assert_eq!(l.chars(1, 2), 3);
}
#[test]
fn trailing_blank_line() {
let l = lm("a\n\n");
assert_eq!(l.n(), 2);
assert_eq!(l.span(1, 1), "a\n");
assert_eq!(l.span(2, 2), "\n");
assert_eq!(l.span(1, 2), "a\n\n");
}
#[test]
fn crlf_keeps_cr_on_line() {
let l = lm("a\r\nb\r\n");
assert_eq!(l.n(), 2);
assert_eq!(l.span(1, 1), "a\r\n");
assert_eq!(l.span(2, 2), "b\r\n");
assert_eq!(l.chars(1, 1), 3); assert_eq!(l.line_of(2), 1);
assert_eq!(l.line_of(3), 2);
}
#[test]
fn lone_cr_is_not_a_line_terminator() {
let l = lm("a\rb");
assert_eq!(l.n(), 1);
assert_eq!(l.span(1, 1), "a\rb");
assert_eq!(l.chars(1, 1), 3);
}
#[test]
fn multibyte_chars_counted_not_bytes() {
let l = lm("héllo\n"); assert_eq!(l.n(), 1);
assert_eq!(l.chars(1, 1), 6); assert_eq!(l.span(1, 1).len(), 7); }
#[test]
fn span_invalid_ranges_are_empty() {
let l = lm("a\nb");
assert_eq!(l.span(3, 2), ""); assert_eq!(l.span(0, 2), ""); assert_eq!(l.chars(3, 3), 0);
}
#[test]
fn line_of_clamps_out_of_range() {
let l = lm("a\nb");
assert_eq!(l.line_of(100), 2); }
#[test]
fn load_strips_bom() {
let p = std::env::temp_dir().join("skimmd_test_bom.md");
std::fs::write(&p, [0xEF, 0xBB, 0xBF, b'#', b't'].as_slice()).unwrap();
let t = load_text(&p).unwrap();
assert_eq!(t, "#t"); std::fs::remove_file(&p).ok();
}
#[test]
fn load_invalid_utf8() {
let p = std::env::temp_dir().join("skimmd_test_bad.md");
std::fs::write(&p, [0xFF, 0xFE, 0x00]).unwrap();
assert!(matches!(load_text(&p), Err(LoadErr::NotUtf8)));
std::fs::remove_file(&p).ok();
}
#[test]
fn io_reason_not_found() {
let e = std::fs::read("/nonexistent/skimmd_nope.md").unwrap_err();
assert_eq!(io_reason(&e), "No such file or directory");
}
#[test]
fn io_reason_is_a_directory() {
let e = std::fs::read(std::path::Path::new("/")).unwrap_err();
assert_eq!(io_reason(&e), "is a directory");
}
}