test_alex_lib/
lib.rs

1use std::env;
2use std::fs;
3use std::fs::File;
4use std::io::{ErrorKind, Read};
5
6
7/// # Exemple
8/// read text from file
9///
10/// # Examples
11///
12/// ```
13///use test_alex_lib::Terminal;
14///
15///fn main() {
16///    let file = Terminal::new();
17///    let p =file.find(file.get_index(2));
18///    //file.create(file.get_index(1), file.get_index(2));
19///    println!("{}", p);
20///    
21///}
22/// ```
23#[derive()]
24pub struct Terminal {
25    value: Vec<String>
26}
27
28impl Terminal {
29    pub fn new() -> Terminal {
30        Terminal {
31            value: env::args().collect()
32        }
33    }
34
35    pub fn get(&self) -> String {
36        let output = self.value.iter().next();
37        let p  = match output {
38            Some(x) => x,
39            None => "Error get()"
40        };
41        p.to_string()
42    }
43
44    pub fn get_index(&self, x: usize) -> String {
45        let &n = &self.value.get(x);
46        let c = match n {
47            Some(x) => x,
48            None => "Error get_index()"
49        };
50        c.to_string()
51    }
52
53    pub fn is_err(&self, x: usize) -> bool {
54        let &n = &self.value.get(x);
55        let c = match n {
56            Some(_) => false,
57            None => true
58        };
59        c
60    }
61
62    pub fn read_file(&self) -> String{
63        let mut output = String::new();
64        let file_name = self.get_index(1);
65        let mut file = File::open(file_name.clone()).unwrap_or_else(|error| {
66            if error.kind() == ErrorKind::NotFound {
67                panic!("Error in Searching File: {:#?}", error);
68            }
69            else {
70                panic!("Error: {:#?}", error);
71            }
72        });
73        file.read_to_string( &mut output).unwrap();
74        output
75    }
76
77    pub fn find(&self, word: String) -> String {
78        let p = self.read_file().to_ascii_lowercase();
79        let out: String = p.lines().filter(|line| line.contains(word.as_str())).collect();
80        out
81    }
82
83    pub fn create(&self, name: String, text: String) -> std::io::Result<()>{
84        File::create(name.clone())?;
85        fs::write(name, text)?;
86        Ok(())
87    }
88}