Caching/
lib.rs

1#![allow(non_snake_case)]
2
3use std::fs::OpenOptions;
4use std::io::Write;
5
6///The cache is in form of a Struct with two elements
7///The second part of the cache is the heart of the cache a Costume list type
8///to get the needed performance for my project
9pub struct Cache<E, T>
10where
11    T: std::cmp::PartialEq + Clone,
12    E: Clone,
13{
14    function: fn(Lists<T, E>) -> bool,
15    cache: Lists<T, E>,
16}
17
18impl<E, T> Cache<E, T>
19where
20    T: std::cmp::PartialEq + Clone + std::fmt::Display,
21    E: Clone + std::fmt::Display,
22{
23    ///fn new() creates a new cache
24    ///as an argument it takes an fn(Lists<E, T>) what returns a bool, to check if it had success or failure
25    /// # Examples
26    ///```rust
27    /// use Caching;
28    /// fn main() -> (){
29    ///     let cache = caching::Cache::<i32,String>::new(|a/* This is a lists<i32, String>*/|-> bool {return true});
30    ///     // Some Code
31    /// }
32    /// ```
33
34    pub fn new(function: fn(Lists<T, E>) -> bool) -> Self {
35        Self {
36            function,
37            cache: Lists::new(),
38        }
39    }
40    /// calls the expression and parse the Cache cache into it
41    /// this makes it possible to execute code directly in the cache
42    /// # Examples
43    ///```rust
44    /// use Caching;
45    /// fn main() -> (){
46    ///     let cache = caching::Cache::<i32,String>::new(|a/* This is a lists<i32, String>*/|-> bool {return true});
47    ///     cache.call(); //This executes the cade in the cache
48    ///     // Some Code
49    /// }
50    /// ```
51    pub fn call(&mut self) -> bool {
52        (self.function)(self.cache.clone())
53    }
54
55    ///insert a linked value into the cache
56    /// # Examples
57    ///```rust
58    /// use Caching;
59    /// fn main() -> (){
60    ///     let cache = caching::Cache::<i32,String>::new(|a/* This is a lists<i32, String>*/|-> bool {return true});
61    ///     cache.insert(4,"4".to_string()); //This puts the values 4 and "4" in the cache
62    ///     // Some Code
63    /// }
64    /// ```
65    pub fn insert(&mut self, link: T, value: E) {
66        self.cache.push(link, value);
67    }
68
69    ///insert a linked value into the cache
70    /// # Examples
71    ///```rust
72    /// use Caching;
73    /// fn main() -> (){
74    ///     let cache = caching::Cache::<i32,String>::new(|a/* This is a lists<i32, String>*/|-> bool {return true});
75    ///     cache.insert(4,"4".to_string()); //This puts the values 4 and "4" in the cache
76    ///     cache.get(4); //returns Option enum with None if the value is not the cache and Some(), in this case Some("4")
77    ///     // Some Code
78    /// }
79    /// ```
80    pub fn get(&self, link: T) -> Option<E> {
81        self.cache.get(link)
82    }
83    ///safes the cache into to files
84    /// # Examples
85    ///```rust
86    /// use Caching;
87    /// fn main() -> (){
88    ///     let cache = caching::Cache::<i32,String>::new(|a/* This is a lists<i32, String>*/|-> bool {return true});
89    ///     cache.insert(4,"4".to_string()); //This puts the values 4 and "4" in the cache
90    ///     cahce.save();//This safes the cache in two file, BUT NOT THE FUNCTION  
91    ///     // Some Code
92    /// }
93
94    pub fn save(&self) {
95        self.cache.save();
96    }
97}
98
99///This is the list used to increse performance
100///by about 12.3 times against an HashMap
101#[derive(Clone)]
102pub struct Lists<T, E> {
103    linked: Vec<T>,
104    list: Vec<E>,
105}
106
107impl<T, E> Lists<T, E>
108where
109    T: std::cmp::PartialEq + std::fmt::Display,
110    E: Clone + std::fmt::Display,
111{
112    //Creats a new list
113    pub fn new() -> Self {
114        Self {
115            linked: Vec::new(),
116            list: Vec::new(),
117        }
118    }
119    ///pushes values into the list
120    pub fn push(&mut self, link: T, list: E) {
121        self.linked.push(link);
122        self.list.push(list);
123    }
124    ///This returns the Element where link is Linked to
125    pub fn get(&self, link: T) -> Option<E> {
126        //this part returns the Element where linked is linked to
127        for i in 0..=(self.linked.len() - 1) {
128            if self.linked[i] == link {
129                return Some(self.list[i].clone());
130            }
131        }
132        None
133    }
134
135    pub fn save(&self) -> () {
136        let mut linked = "".to_string();
137        let mut list = "".to_string();
138        for i in 0..=(self.linked.len() - 1) {
139            linked = format!("{} {} ", linked, self.linked[i]);
140            list = format!("{} {} ", list, self.list[i]);
141        }
142        wright(linked, "linked.vec".to_string());
143        wright(list, "value.vec".to_string());
144    }
145
146    pub fn load(&self) -> () {
147        todo!();
148    }
149}
150
151pub(crate) fn wright(content: String, file: String) {
152    match OpenOptions::new()
153        .write(true)
154        .append(true)
155        .create(true)
156        .read(true)
157        .open(file)
158    {
159        Ok(mut e) => match e.write_all(content.as_bytes()) {
160            Ok(_) => {
161                e.flush().unwrap();
162            }
163            Err(e) => {
164                println!("\x1b[31m Error with Wright to File: {}\x1b[0m", e);
165            }
166        },
167        Err(e) => {
168            println!("\x1b[31m{}\x1b[0m", e);
169        }
170    }
171}
172#[cfg(test)]
173mod tests {
174    use super::*;
175    #[test]
176    fn it_works() {
177        let mut cache = Cache::<i32, i32>::new(|a| -> bool { true });
178        cache.insert(1, 3);
179        cache.insert(2, 3);
180        cache.insert(3, 3);
181        cache.insert(4, 3);
182        cache.insert(5, 3);
183        cache.insert(6, 3);
184        cache.insert(7, 3);
185        cache.insert(8, 9);
186        assert_eq!(9, cache.get(8).unwrap());
187        assert!(cache.call());
188        cache.save();
189    }
190}