add write command

This commit is contained in:
rick 2023-04-23 03:01:37 +02:00
parent a265b3a890
commit db2adaae4c
Signed by: Rick
GPG key ID: 5CBE8779CD27BCBA
3 changed files with 36 additions and 5 deletions

View file

@ -1,22 +1,30 @@
use crate::enums::Address;
use std::io;
use std::fs::OpenOptions;
use std::io::Write;
pub struct Buffer {
has_changed: bool,
buffer: Vec<Result<String, io::Error>>,
current_line: usize,
file_name: String,
}
impl Buffer {
pub fn new(buffer: Vec<Result<String, io::Error>>) -> Self {
pub fn new(file_name: &str, buffer: Vec<Result<String, io::Error>>) -> Self {
let tmp = buffer.len().saturating_sub(1);
Self {
has_changed: false,
buffer,
current_line: tmp
current_line: tmp,
file_name: String::from(file_name)
}
}
pub fn is_modified(&self) -> bool {
self.has_changed
}
// Return the actual line of the buffer
pub fn line(&self) -> usize {
self.current_line
@ -28,6 +36,24 @@ impl Buffer {
self.current_line = new;
}
pub fn save(&mut self) {
if let Ok(mut file) = OpenOptions::new().write(true).open(&self.file_name) {
let mut tmp = String::new();
for line in &self.buffer {
if let Ok(l) = line {
tmp.push_str(&l);
tmp.push('\n');
}
}
if let Err(e) = file.write(tmp.as_bytes()) {
panic!("{}", e);
}
self.has_changed = false;
}
}
pub fn append(&mut self, addr: Address, lines: Vec<String>) {
self.has_changed = true;
match addr {

View file

@ -122,7 +122,7 @@ pub enum Command {
CopyLines,
Undo,
// TODO
Write,
Write(Address),
// TODO
Line,
// TODO
@ -158,6 +158,7 @@ fn parse(c: char, addr: Address) -> Result<Command, String> {
'n' => Ok(Command::Number(addr)),
'q' => Ok(Command::Quit(false)),
'Q' => Ok(Command::Quit(true)),
'w' => Ok(Command::Write(addr)),
_ => Ok(Command::Help),
}
}

View file

@ -81,6 +81,10 @@ fn execute_command(buffer: &mut Buffer, c: Command) -> Exit {
} else {
ret = Exit::Quit;
},
Command::Write(_) => {
buffer.save();
ret = Exit::Continue;
},
_ => (),
}
@ -89,7 +93,7 @@ fn execute_command(buffer: &mut Buffer, c: Command) -> Exit {
fn parse_line(input: &str) -> Result<Command, String> {
let address = take_while(check_address_complete);
let command = one_of::<_, _, (&str, ErrorKind)>("apnqQ");
let command = one_of::<_, _, (&str, ErrorKind)>("apnqQw");
//if let Ok((input, (a, c))) = alt(address, command).parse(input) {
let tmp = (address, command).parse(input);
@ -111,7 +115,7 @@ fn main() {
panic!("Le fichier n'existe pas.");
};
let mut buffer_struct = Buffer::new(buffer);
let mut buffer_struct = Buffer::new(FILE, buffer);
println!("fichier lu !");
let mut pred = Exit::Continue;