hecto/src/document.rs

58 lines
1.2 KiB
Rust
Raw Normal View History

2021-03-10 13:48:21 -05:00
use crate::Position;
2021-03-08 10:21:06 -05:00
use crate::Row;
2021-03-08 13:34:25 -05:00
use std::fs;
2021-03-08 10:21:06 -05:00
#[derive(Default)]
pub struct Document {
rows: Vec<Row>,
2021-03-08 14:41:40 -05:00
pub file_name: Option<String>,
2021-03-08 10:43:40 -05:00
}
impl Document {
2021-03-08 13:34:25 -05:00
pub fn open(filename: &str) -> Result<Self, std::io::Error> {
let contents = fs::read_to_string(filename)?;
2021-03-08 10:43:40 -05:00
let mut rows = Vec::new();
2021-03-08 13:34:25 -05:00
for value in contents.lines() {
rows.push(Row::from(value));
}
Ok(Self {
2021-03-08 14:41:40 -05:00
rows,
file_name: Some(filename.to_string()),
2021-03-08 13:34:25 -05:00
})
2021-03-08 10:43:40 -05:00
}
pub fn row(&self, index: usize) -> Option<&Row> {
self.rows.get(index)
}
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
2021-03-08 14:21:24 -05:00
pub fn len(&self) -> usize {
self.rows.len()
}
2021-03-10 13:48:21 -05:00
pub fn insert(&mut self, at: &Position, c: char) {
if at.y == self.len() {
let mut row = Row::default();
row.insert(0, c);
self.rows.push(row);
} else if at.y < self.len() {
let row = self.rows.get_mut(at.y).unwrap();
row.insert(at.x, c);
}
}
pub fn delete(&mut self, at: &Position) {
if at.y >= self.len() {
return
}
let row = self.rows.get_mut(at.y).unwrap();
row.delete(at.x);
}
2021-03-08 10:21:06 -05:00
}