use anyhow::{Context as _, Result};
use ropey::Rope;
use std::fs::File;
use std::io::BufReader;
#[derive(Debug, Clone)]
pub struct TextBuffer {
pub(super) rope: Rope,
}
impl Default for TextBuffer {
fn default() -> Self {
Self::new()
}
}
impl TextBuffer {
#[inline]
pub fn new() -> Self {
Self { rope: Rope::new() }
}
#[inline]
pub fn from_str(s: &str) -> Self {
Self {
rope: Rope::from_str(s),
}
}
pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
let path = path.as_ref();
let file = File::open(path)
.with_context(|| format!("failed to read file: {}", path.to_string_lossy()))?;
let reader = BufReader::new(file);
let rope = Rope::from_reader(reader)
.with_context(|| format!("file is not valid UTF-8: {}", path.to_string_lossy()))?;
Ok(Self { rope })
}
#[inline]
pub fn rope(&self) -> &Rope {
&self.rope
}
#[inline]
pub fn rope_mut(&mut self) -> &mut Rope {
&mut self.rope
}
#[inline]
pub fn len_chars(&self) -> usize {
self.rope.len_chars()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.rope.len_chars() == 0
}
}