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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
use std::fs::File;
use std::io::{Write, BufReader, BufRead};

#[derive(Default)]
pub struct BufData{
    filepath:&'static str,
    data:Vec<DataType>,
}
enum DataType {
    Notes(String),
    Data((String,String)),
}

impl BufData {
    /// Create a empty data squence in memory
    /// 
    /// ```rust
    /// use iii::BufData;
    /// let mut cc = BufData::new();
    /// cc.chgvalue("c1", "value");
    /// cc.chgvalue("c2", "value2");
    /// cc.chgvalue("c3", "value3");
    /// if let Ok(_) = cc.write(None){
    ///     println!("file write success")
    /// };
    /// ```
    pub fn new()->Self{
        Self { filepath:"default.iii",..Default::default() }
    }
    /// ### load config file
    /// 
    /// ```rust
    /// let cc = BufData::loadfromiii("default.iii");
    /// if let Some(v) = cc.getvalue("c2"){
    ///     println!("K:{},V:{}","c2",v);
    /// }
    /// if let Some(v) = cc.getvalue("c5"){
    ///     println!("K:{},V:{}","c5",v);
    /// }
    /// ```
    pub fn loadfromiii(filepath:&'static str)->Self{
        let mut data = Vec::new();
        if let Ok(file)=File::open(filepath){
            for idx in BufReader::new(file).lines(){
                if let Ok(iidx) = idx{
                    if iidx.trim().starts_with("#"){
                        data.push(DataType::Notes(iidx));
                    }else{
                        let cc:Vec<&str> = iidx.trim().split("=").collect();
                        if cc.len() == 2{
                            data.push(DataType::Data((cc[0].trim().to_string(),cc[1].trim().to_string())));
                        }
                    }
                }
            }
        }
        Self{filepath:filepath,data:data}
    }
    
    fn onlywrite(&self,path:&'static str)->Result<(),&'static str>{
        if let Ok(mut f) = File::create(path){
            let mut bufstr = String::new();
            for idx in &self.data{
                match idx {
                    DataType::Data((s1,s2))=>{
                        bufstr.push_str(&format!("{} = {}\r\n",s1,s2));
                    },
                    DataType::Notes(commet)=>{
                        bufstr.push_str(&commet);
                        bufstr.push_str("\r\n");
                    },
                }
            }
            if let Ok(_) = f.write(bufstr.as_bytes()){
                return Ok(());
            }
        }
        Err("write err")
        // std::io::Error(9)

    }
    
    /// ### save config to file 
    /// if newfile is None,use loaded file's path to save 
    pub fn save(&self,newfilepath:Option<&'static str>)->Result<(),&'static str>{
        if let Some(pth) = newfilepath{
            self.onlywrite(pth)
        }else{
            self.onlywrite(self.filepath)
        }
    }
    /// ### read value from file by key
    pub fn getvalue(&self,key:&'static str)->Option<String>{
        for idx in &self.data{
            if let DataType::Data((s1,s2))=idx{
                if key == s1{
                    return Some(s2.clone());
                }
            }
        }
        None
    }
    /// ### write value or change value
    pub fn chgvalue(&mut self,key:&'static str,value:&str){
        for idx in &mut self.data{
            if let DataType::Data((s1,s2))=idx{
                if key == s1{
                    s2.clear();
                    s2.push_str(value);
                    return;
                }
            }
        }
        self.data.push(DataType::Data((key.to_string(),value.to_string())));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn crate1(){
        let mut cc = BufData::new();
        cc.chgvalue("c1", "value");
        cc.chgvalue("c2", "value2");
        cc.chgvalue("c3", "value3");
        if let Ok(_) = cc.save(None){
            println!("file write success")
        };
    }
    #[test]
    fn readwrite(){
        let mut cc = BufData::loadfromiii("default.iii");
        cc.chgvalue("c3", "ccc3");
        cc.chgvalue("c5", "5c");
        if let Ok(_) = cc.save(None){
            println!("file write success")
        };
    }

    #[test]
    fn readvalue(){
        let cc = BufData::loadfromiii("default.iii");
        if let Some(v) = cc.getvalue("c2"){
            println!("K:{},V:{}","c2",v);
        }
        if let Some(v) = cc.getvalue("c5"){
            println!("K:{},V:{}","c5",v);
        }
    }
}