File: simple_buffer.rs

package info (click to toggle)
rust-ropey 1.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,160 kB
  • sloc: makefile: 2
file content (75 lines) | stat: -rw-r--r-- 1,609 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#![allow(clippy::redundant_field_names)]
#![allow(dead_code)]

extern crate ropey;

use std::fs::File;
use std::io;

use ropey::iter::{Bytes, Chars, Chunks, Lines};
use ropey::{Rope, RopeSlice};

struct TextBuffer {
    text: Rope,
    path: String,
    dirty: bool,
}

impl TextBuffer {
    fn from_path(path: &str) -> io::Result<TextBuffer> {
        let text = Rope::from_reader(&mut io::BufReader::new(File::open(&path)?))?;
        Ok(TextBuffer {
            text: text,
            path: path.to_string(),
            dirty: false,
        })
    }

    fn get_line(&self, idx: usize) -> RopeSlice {
        self.text.line(idx)
    }

    fn bytes(&self) -> Bytes {
        self.text.bytes()
    }

    fn chars(&self) -> Chars {
        self.text.chars()
    }

    fn lines(&self) -> Lines {
        self.text.lines()
    }

    fn chunks(&self) -> Chunks {
        self.text.chunks()
    }

    fn edit(&mut self, start: usize, end: usize, text: &str) {
        if start != end {
            self.text.remove(start..end);
        }
        if !text.is_empty() {
            self.text.insert(start, text);
        }
        self.dirty = true;
    }
}

fn main() {
    // Get filepath from commandline
    let filepath = if std::env::args().count() > 1 {
        std::env::args().nth(1).unwrap()
    } else {
        println!(
            "You must pass a filepath!  Only recieved {} arguments.",
            std::env::args().count()
        );
        panic!()
    };

    let mut buf = TextBuffer::from_path(&filepath).unwrap();

    buf.edit(3, 5, "Hello!");
    println!("{}", buf.get_line(2));
}