//! Open buffers: the engine's copy of every file the user is editing. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use lutra_text::{Buffer, LineEnding}; use serde::Serialize; /// Identifier of an open buffer, unique for the engine's lifetime. pub type BufferId = u64; /// One open file. #[derive(Debug, Clone)] pub struct OpenBuffer { /// The text. pub buffer: Buffer, /// Project-relative path of the file. pub path: PathBuf, /// Incremented by every change of the text. pub version: u64, /// The version that matches the file on disk. pub saved_version: u64, /// The file started with a UTF-8 byte order mark; kept on save. pub bom: bool, } impl OpenBuffer { /// Whether the buffer has unsaved changes. pub fn dirty(&self) -> bool { self.version != self.saved_version } } /// The open buffers by id. #[derive(Debug, Default)] pub struct Buffers { /// Buffers by id. by_id: BTreeMap, /// The id the next buffer gets. next_id: BufferId, } impl Buffers { /// Adds a buffer and returns its id. pub fn insert(&mut self, buffer: OpenBuffer) -> BufferId { self.next_id = self.next_id.saturating_add(1); let id = self.next_id; self.by_id.insert(id, buffer); id } /// The buffer with `id`. pub fn get(&self, id: BufferId) -> Option<&OpenBuffer> { self.by_id.get(&id) } /// The buffer with `id`, mutable. pub fn get_mut(&mut self, id: BufferId) -> Option<&mut OpenBuffer> { self.by_id.get_mut(&id) } /// Removes the buffer with `id`. pub fn remove(&mut self, id: BufferId) -> Option { self.by_id.remove(&id) } /// The id of the buffer for the project-relative `path`, if open. pub fn find(&self, path: &Path) -> Option { self.by_id .iter() .find(|(_, b)| b.path == path) .map(|(id, _)| *id) } /// Ids of all buffers, ascending. pub fn ids(&self) -> Vec { self.by_id.keys().copied().collect() } /// Ids of the buffers with unsaved changes, ascending. pub fn dirty_ids(&self) -> Vec { self.by_id .iter() .filter(|(_, b)| b.dirty()) .map(|(id, _)| *id) .collect() } /// Number of open buffers. pub fn len(&self) -> usize { self.by_id.len() } /// Whether no buffer is open. pub fn is_empty(&self) -> bool { self.by_id.is_empty() } /// Removes every buffer. pub fn clear(&mut self) { self.by_id.clear(); } } /// A line ending as sent to clients: `"lf"`, `"crlf"` or `"cr"`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] pub enum LineEndingName { /// `\n`. Lf, /// `\r\n`. Crlf, /// `\r`. Cr, } impl From for LineEndingName { fn from(ending: LineEnding) -> Self { match ending { LineEnding::Lf => Self::Lf, LineEnding::CrLf => Self::Crlf, LineEnding::Cr => Self::Cr, } } }