add range write and fix no truncate

This commit is contained in:
rick 2023-04-23 11:48:54 +02:00
parent 112cc09732
commit eada03a570
Signed by: Rick
GPG key ID: 5CBE8779CD27BCBA
3 changed files with 30 additions and 9 deletions

View file

@ -1,5 +1,5 @@
use crate::enums::Address;
use std::fs::OpenOptions;
use std::fs::File;
use std::io;
use std::io::Write;
@ -36,10 +36,27 @@ impl Buffer {
self.current_line = new;
}
pub fn save(&mut self) {
if let Ok(mut file) = OpenOptions::new().write(true).open(&self.file_name) {
pub fn save(&mut self, range: Address) {
let len = self.buffer.len();
let curr = self.current_line.saturating_sub(1);
match range {
Address::Actual => self.save_range(curr, curr),
Address::Empty | Address::All => self.save_range(0, len),
Address::Last => self.save_range(len.saturating_sub(1), len),
Address::Line(l) => self.save_range(l.saturating_sub(1), l),
Address::FromStartTo(l) => self.save_range(0, l),
Address::FromToEnd(l) => self.save_range(l.saturating_sub(1), len),
Address::FromTo(a, b) => self.save_range(a.saturating_sub(1), b),
Address::FromActTo(l) => self.save_range(curr, l),
Address::FromActToEnd => self.save_range(curr, len),
_ => (),
}
}
fn save_range(&mut self, start: usize, end: usize) {
if let Ok(mut file) = File::create(&self.file_name) {
let mut tmp = String::new();
for line in self.buffer.iter().flatten() {
for line in self.buffer[start..end].iter().flatten() {
tmp.push_str(line);
tmp.push('\n');
}

View file

@ -4,6 +4,9 @@ use std::str::FromStr;
#[derive(Debug)]
pub enum Address {
Actual,
// utile pour write qui considère une adresse nulle comme l'ensemble du
// fichier par défaut
Empty,
Last,
Line(usize),
FromStartTo(usize),
@ -19,7 +22,7 @@ impl Address {
pub fn is_multi_line(&self) -> bool {
!matches!(
self,
Address::Null | Address::Actual | Address::Last | Address::Line(_)
Address::Null | Address::Actual | Address::Last | Address::Line(_) | Address::Empty
)
}
}
@ -30,7 +33,7 @@ pub fn parse_address(addr: &str) -> Address {
let addr = tmp.as_str();
if addr.is_empty() {
Address::Actual
Address::Empty
} else if addr.contains(',') || addr.contains(';') {
parse_multi_addr(addr)
} else if let Ok(l) = usize::from_str(addr) {
@ -120,8 +123,9 @@ pub enum Command {
Substitute,
// TODO
CopyLines,
Undo,
// TODO
Undo,
// TODO nom de fichier
Write(Address),
// TODO
Line,

View file

@ -81,8 +81,8 @@ fn execute_command(buffer: &mut Buffer, c: Command) -> Exit {
ret = Exit::Quit;
}
}
Command::Write(_) => {
buffer.save();
Command::Write(a) => {
buffer.save(a);
ret = Exit::Continue;
}
_ => (),