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
//! 实现修改数据功能 trait

use std::fmt::Display;

use crate::{App, AppData, FQLType};

pub trait Editor {
    fn add(&mut self, new_data: AppData);
    fn remove(&mut self, index: usize);
    fn insert(&mut self, index: usize, new_data: AppData);
    fn replace(&mut self, index: usize, new_data: AppData);
    fn update<T: Display>(&mut self, index: usize, key: T, new_value: FQLType);
}

impl Editor for App {
    /// 修改一行数据
    /// #Example
    ///```
    /// use file_sql::*;
    /// let app = App::from_file("example.fql");
    /// let new_data = app.find_index(1);
    /// app.replace(0, "age", new_data.to_owned());
    ///```
    fn replace(&mut self, index: usize, new_data: AppData) {
        self.data.remove(index);
        self.data.insert(index, new_data);
    }

    /// 在指定一行加入数据  
    fn insert(&mut self, index: usize, new_data: AppData) {
        self.data.insert(index, new_data);
    }

    /// 删除某一列数据
    /// #Example
    ///```
    /// use file_sql::*;
    /// let app = App::from_file("example.fql");
    /// app.remove(1); // 删除第二行数据
    ///```
    fn remove(&mut self, index: usize) {
        self.data.remove(index);
    }

    fn update<T: Display>(&mut self, index: usize, key: T, new_value: FQLType) {
        let mut new_data = self.data.remove(index);
        new_data.insert(key.to_string(), new_value);
        self.data.insert(index, new_data);
    }

    /// 添加数据到末尾
    fn add(&mut self, new_data: AppData) {
        self.data.push(new_data);
    }
}