simple_dic/
lib.rs

1use std::fmt; 
2
3pub struct Dictionary<T> {
4        key: Vec<String>,
5        value: Vec<T>,
6        unique: bool,
7    }
8    impl<T: std::cmp::PartialEq> Dictionary<T> {
9    //Function to create an instance of a dictionary
10        pub fn new(x:bool) -> Self {
11            Dictionary {
12                key: Vec::new(),
13                value: Vec::new(),
14                unique: x,
15            }
16        }
17     //Pushes a key/value pair to the end
18        pub fn push(&mut self,key:String,value:T) -> Result<(),String> {
19            if self.unique {
20                if self.key.contains(&key){
21                return Err(format!("Key: '{}' does not exist.",key))
22            }else{
23                self.key.push(key);
24                self.value.push(value);
25                Ok(())
26            }
27            }else{
28                self.key.push(key);
29                self.value.push(value);
30                Ok(())
31            }
32        }
33        //removes newest element from Dic
34        pub fn pop(&mut self){
35            self.key.pop();
36            self.value.pop();
37        }
38        //search for a key
39        pub fn search(&mut self, key:String) -> bool {
40            if self.key.contains(&key) {
41                return true;
42            }else{
43                return false;
44            }
45        }
46        //returns a usize with the length of the dictionary
47        pub fn len(&self) -> usize {
48            return self.key.len();
49        }
50
51        //search for a key and return an index
52         fn raw_search(&self,key:String) -> Result<usize,String> {
53            for i in 0..self.key.len(){
54                 if self.key[i] == key {
55                    return Ok(i)
56               }
57            }
58            return Err(format!("Could not find key: {}",key));
59     }
60
61        pub fn index_of(&self,key:String) -> Result<Vec<usize>,String>{
62            let mut y = vec![];
63             for i in 0..self.key.len(){
64                if self.key[i] == key{
65                    y.push(i);
66                }
67             }
68             if y.len() > 0 {
69                return Ok(y);
70             }else{
71                return Err(format!("Could not find key: {}",key));
72             }
73        }
74
75        //deletes the key and value with a key passed into the function
76        pub fn drop(&mut self,key:String) -> bool{
77               if let Some(index) = self.key.iter().position(|x| x == &key){
78                    self.key.remove(index);
79                    self.value.remove(index);
80                    return true;
81                }else{
82                    return false;
83                }
84        }
85        //checks if a value exists in the dictionary
86        pub fn contains(&self,value:&T) ->bool{
87            return self.value.contains(value);
88        }
89        //overwrite the value of the value of a key
90        pub fn overwrite(&mut self,key:String,newvalue:T) -> Result<(),String>{
91            match self.raw_search(key) {
92               Ok(val) => {
93                self.value[val] = newvalue;
94                return Ok(());
95                },
96               Err(error) => {
97                return Err(error)
98                },       
99            }     
100        }
101    }
102 impl<T> fmt::Display for Dictionary<T> 
103    where
104    T: fmt::Display,{
105    fn fmt(&self,f: &mut fmt::Formatter) -> fmt::Result{
106          if self.key.len() != self.value.len() {
107            return Err(fmt::Error);
108        }
109
110        writeln!(f, "{{")?;
111
112        for (i, (key, value)) in self.key.iter().zip(self.value.iter()).enumerate() {
113            write!(f, "   {}: ", key)?;
114            value.fmt(f)?;
115
116            if i < self.key.len() - 1 {
117                writeln!(f, ",")?;
118            } else {
119                writeln!(f)?;
120            }
121        }
122
123        writeln!(f, "}}")
124    }
125 }
126#[cfg(test)]
127mod tests {
128    use crate::Dictionary;
129     #[test]
130     fn testcase0() {
131            //testing if length works
132    let mut obj = Dictionary::<&str>::new(true);
133    let mut  f = 0;
134
135    for i in 0..100{
136        let iclone = i.clone().to_string();
137        obj.push(format!("a{}",iclone),"Value");
138        f = f + 1
139    }
140    assert_eq!(f,obj.len());
141}
142    //testing searching and loops
143   #[test]
144    fn testcase1() {
145        let mut obj = Dictionary::<&str>::new(true);
146        let mut  f = false;
147
148         for i in 0..100{
149             let iclone = i.clone().to_string();
150            obj.push(format!("a{}",iclone),"Value");
151         }
152         f = obj.search("a51".to_string());
153         assert_eq!(f,true);
154    }
155     //testing drop function
156     #[test]
157    fn testcase2() {
158    let mut obj = Dictionary::<&str>::new(true);
159    let mut  f = 0;
160    for i in 0..100{
161        let iclone = i.clone().to_string();
162        obj.push(format!("a{}",iclone),"Value");
163        f = f + 1
164    }
165    obj.drop("a51".to_string());
166    assert_eq!(f-1,obj.len());
167    }
168    //testing containts function
169     #[test]
170     fn testcase3() {
171        let mut obj = Dictionary::<String>::new(true);
172        let mut  f = false;
173
174         for i in 0..100{
175             let iclone = i.clone().to_string();
176            obj.push(format!("a{}",iclone),format!("b{}",iclone));
177         }
178         f = obj.contains(&"b20".to_string());
179         assert_eq!(f,true);    
180     }
181    //testing the overwrite
182    #[test]
183    fn testcase4() {
184        let mut obj = Dictionary::<String>::new(true);
185        let mut f = false;
186        for i in 0..100{
187             let iclone = i.clone().to_string();
188            obj.push(format!("a{}",iclone),format!("b{}",iclone));
189         }
190        obj.overwrite("a20".to_string(),"x20".to_string());
191        f = obj.contains(&"x20".to_string());
192        assert_eq!(f,true);
193    }
194    #[test]
195     fn testcase5(){
196        //testing priting
197        let mut obj = Dictionary::<String>::new(true);
198        for i in 0..20{ let iclone = i.clone().to_string();
199            obj.push(format!("a{}",iclone),format!("b{}",iclone));
200         }
201         println!("{}",obj);
202    }
203    #[test]
204    fn testcase6() {
205    //testing experimental non unique
206    let mut obj = Dictionary::<String>::new(false);
207    for i in 0..20{
208        obj.push("a".to_string(),"b".to_string());
209    }
210        println!("{}",obj)
211    }
212
213    #[test]
214    fn testcase7() {
215    let mut obj = Dictionary::<String>::new(false);
216    for i in 0..4{
217        obj.push("a".to_string(),"b".to_string());
218    }
219    for i in 0..4{
220        obj.push("c".to_string(),"d".to_string());
221    }
222        let f = obj.index_of("a".to_string());
223        let y = vec![0,1,2,3];
224        assert_eq!(y,f.unwrap());
225    }
226}