gavl 0.1.5

A fast implementation for a map and a set using an AVL tree
Documentation
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! # AVL data structures
//! This crate implements a `Map` based on an AVL in the near future it may include a `Set` as well 
//! # Panics
//! The only panic that can be raised by this crate arrises from Box panic
//! # Safety
//! As of now I haven run the analisis or test to determine if it is Send and Sync in in the near
//! future, maybe I will implement something `rwlocks`
//! # Features
//! * `into_precomputed` - Enables the into precomputed iterator
//! * `unchecked_mut` - Enables a iterator that yields a mutable reference to the key (Not yet in
//! the documentation)

mod structs;
mod balance;
mod traits;
mod iters;
mod errors; mod into_precomputed;


#[cfg(any(feature = "unchecked_mut", doc))]
pub use iters::IterMutUnchecked;


#[cfg(any(feature = "into_precomputed", doc))]
pub use into_precomputed::PrecomputedIterNode;
#[cfg(any(feature = "into_precomputed", doc))]
pub use iters::IntoIterPrecomp;



#[cfg(test)]
mod test;


use std::{
    ptr::NonNull,
};

/// # Map optimized for search
/// Map of `<KeyType>` to `<ContentType>` optimized for search
/// worst case log(n)
/// the implementation of a AVl self balancing tree 
/// 
/// should add a little bit more info on the implementation
pub struct Map<KeyType:Ord, ContentType>{
    head: Option<MapLink<KeyType, ContentType>>,
    size: usize,
}


pub use errors::Error;
pub use iters::IntoIter;
pub use iters::Iter;
pub use iters::IterMut;



#[allow(dead_code)]
struct MapNode<KeyType:Ord, ContentType>{
    key: KeyType,
    content: ContentType,
    father: Option<MapLink<KeyType,ContentType>>,
    depth: structs::BinarySon<i32>,
    son: structs::BinarySon<Option<MapLink<KeyType,ContentType>>>,
    metadata: into_precomputed::FeatureField,
}

type MapLink<KeyType, ContentType> = NonNull<MapNode<KeyType, ContentType>>;

/*
/// # set
pub struct Set<KeyType:Ord>{
    //head: Option<SetLink<KeyType>>,
    size: u64,
}

pub struct SetNode<KeyType:Ord>{
    content: KeyType,
    father: Option<SetLink<KeyType>>,
    depth: structs::BinarySon<i32>,
    son: structs::BinarySon<Option<SetLink<KeyType>>>,
    #[cfg(feature = "into_precomputed")]
    index: u64,
}

type SetLink<KeyType> = NonNull<SetNode<KeyType>>;
*/

impl<KeyType:Ord, ContentType> Map<KeyType, ContentType>{
    
    

    /// This function returns a `Map<KeyType, ContentType>`
    ///
    /// The map will not allocate until elements are inserted/added.
    ///
    /// `KeyType` should implement Ord
    ///
    /// # Example
    /// 
    /// ```
    /// let map:gavl::Map<String, i32> = gavl::Map::new();
    /// ```
    pub fn new() -> Self {
        Self{head:None ,size:0}
    }
    
    

    /// Inserts a node into the `Map`
    /// 
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<String, i32>::new();
    /// for elem in 0..10 {
    ///     map.add(elem.to_string(), elem);
    /// }
    /// assert_eq!(map.len(), 10);
    /// ```
    /// # Returns
    /// ## Success
    /// * `Ok(())`
    /// ## Errors
    /// * `Err(Error::KeyOcupied)`:   Is returned if the key is already present 
    pub fn add(&mut self, key:KeyType, content:ContentType) -> Result<(), Error> {
        let new_node = MapNode::new_map_link(key, content);
        
        match self.head {
            None => {
                self.head = Some(new_node);
                self.size = 1;
                Ok(())
            }
            Some(data) => {
                if let Err(_place) = MapNode::insert_node(data, new_node) {
                    MapNode::free_node(new_node);
                    return Err(Error::KeyOcupied);
                }
                self.size += 1;
                self.compute_balance_additive(new_node);
                Ok(())
            }
        }
        
    }
    
    
    /// Replaces or adds node to `Map`
    /// * If the key is not present in the map it works just like `add`
    /// 
    /// * If it already present it will remplace the `content` with new one return
    /// the old value
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<&str, i32>::new();
    /// const key:&str = "key";
    /// let old_content = map.insert(key, 12);
    /// let holder = map.get(&key);
    /// 
    /// assert_eq!(old_content, None);
    /// assert_eq!(holder, Ok(&12));
    /// 
    /// let old_content = map.insert(key, 13);
    /// let holder = map.get(&key);
    /// 
    /// assert_eq!(old_content, Some(12));
    /// assert_eq!(holder, Ok(&13));
    /// ```
    /// # Returns
    /// ## Success
    /// * `None`:   key didn't existed in `Map`
    /// * `Some(oldContent)`:  old key's content
    pub fn insert(&mut self, key:KeyType, content:ContentType) -> Option<ContentType> {
        let new_node = MapNode::new_map_link(key, content);
        
        match self.head {
            None => {
                self.head = Some(new_node);
                self.size = 1;
                None
            }
            Some(data) => {
                if let Err(place) = MapNode::insert_node(data, new_node) {
                    self.replace_node(place, new_node);
                    return Some(MapNode::unpack_node(place));// change to return the value (Error::KeyOcupied);
                }
                self.size += 1;
                self.compute_balance_additive(new_node);
                None
            }
            
        }
        
    }
    
    
    
    /*
    pub fn replace(&mut self, key:KeyType, content:ContentType) -> bool {
        let new_node = MapNode::new_map_link(key, content);
        
        match self.head {
            None => {
                self.head = Some(new_node);
                self.size = 1;
                false
            }
            Some(data) => {
                if let Err(place) = MapNode::insert_node(data, new_node) {
                    self.replace_node(place, new_node);
                    MapNode::free_node(place);
                    return true;// change to return the value (Error::KeyOcupied);
                }
                self.size += 1;
                self.compute_balance_additive(new_node);
                false
            }
            
        }
        
    }
    */
    
    

    /// Deletes all the nodes in the `Map` and sets the len to 0
    ///
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<String, i32>::new();
    /// for elem in 0..10 {
    ///     map.add(elem.to_string(), elem);
    /// }
    /// 
    /// assert_eq!(map.len(), 10);
    /// map.empty();
    /// assert_eq!(map.len(), 0);
    /// ```
    pub fn empty(&mut self) {
        let empty_iter = self.empty_iter();
        for _elem in empty_iter {
            //just drop them
        }
    }
    
    

    /// Gets a reference to the `content` associated to the `key` in `Map` 
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<String, i32>::new();
    /// map.add(12.to_string(), 12);
    /// let holder = map.get(&12.to_string()); // holder = Ok(&12)
    /// 
    /// assert_eq!(holder, Ok(&12));
    /// ```
    /// # Returns
    /// ## Success
    /// * `Ok(&ContentType)`:   A reference to the content associated to that key
    /// ## Errors
    /// * `Err(Error::NotFound)`:   Is returned if the key is not present
    pub fn get(&self, key:&KeyType) -> Result<&ContentType, Error> {
        let pivot = match self.head {
            None => {return Err(Error::NotFound);}
            Some(data) => data,
        };
        let node = MapNode::find_node(key, pivot).ok_or(Error::NotFound)?;
        let node_ref = unsafe{node.as_ref()};
        Ok(&node_ref.content)
    }
    
    
    
    /// Gets a mutable reference to the `content` associated to the `key` in `Map` 
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<i32, i32>::new();
    /// map.add(10, 1);
    /// let holder = map.get_mut(&10); // holder = Ok(&1)
    /// 
    /// *holder.unwrap() += 9; // holder = Ok(&12+8)
    /// let holder = map.get(&10);
    /// assert_eq!(holder, Ok(&10));
    /// 
    /// ```
    /// # Returns
    /// ## Success
    /// * `Ok(&mut ContentType)`:   A mutable reference to the content associated to that key
    /// ## Errors
    /// * `Err(Error::NotFound)`:   Is returned if the key is not present
    pub fn get_mut(&mut self, key:&KeyType) -> Result<&mut ContentType, Error> {
        let pivot = match self.head {
            None => {return Err(Error::NotFound);}
            Some(data) => data,
        };
        let mut node = MapNode::find_node(key, pivot).ok_or(Error::NotFound)?;
        let node_mut = unsafe{node.as_mut()};
        Ok(&mut node_mut.content)
    }



    /// Deletes one node the `Map` drops the key and the content if the key is found
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<String, i32>::new();
    /// map.add(12.to_string(), 12);
    /// assert_eq!(map.len(), 1);
    /// 
    /// let holder = map.remove(&12.to_string());
    /// assert_eq!(map.len(), 0);
    /// assert_eq!(holder, Ok(12));
    /// ```
    /// # Returns
    /// ## Success
    /// * `Ok(())`
    /// ## Errors
    /// * `Err(Error::NotFound)`:   Is returned if the key is not present
    pub fn remove(&mut self, key:&KeyType) -> Result<ContentType, Error> {
        match self.size {
            0 => {
                Err(Error::NotFound)
            }
            1 => {
                let head = self.head.unwrap();
                let head_ref = unsafe{head.as_ref()};
                if !head_ref.key.cmp(key).is_eq() {
                    return Err(Error::NotFound);
                }
                self.size = 0;
                self.head = None;
                let target = unsafe{Box::from_raw(head.as_ptr())};
                Ok(target.content)
            }
            _ => {
                let target = MapNode::find_node(key, self.head.unwrap()).ok_or(Error::NotFound)?;
                let balance_pivot = self.compute_subtraccion_pivot(target);
                self.compute_balance_subtractive(balance_pivot);
                self.size -= 1;
                let target = unsafe{Box::from_raw(target.as_ptr())};
                Ok(target.content)
            }
        }
    }
    
    

    /// Deletes one node the `Map` drops the key and the content if the key is found
    ///
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<String, i32>::new();
    /// map.add(12.to_string(), 12);
    /// assert_eq!(map.len(), 1);
    /// 
    /// map.delete(&12.to_string());
    /// assert_eq!(map.len(), 0);
    /// ```
    /// # Returns
    /// ## Success
    /// * `Ok(())`
    /// ## Errors
    /// * `Err(Error::NotFound)`:   Is returned if the key is not present
    pub fn delete(&mut self, key:&KeyType) -> Result<(), Error> {
        match self.size {
            0 => {
                Err(Error::NotFound)
            }
            1 => {
                let head = self.head.unwrap();
                let head_ref = unsafe{head.as_ref()};
                if !head_ref.key.cmp(key).is_eq() {
                    return Err(Error::NotFound);
                }
                self.size = 0;
                self.head = None;
                MapNode::free_node(head);
                Ok(())
            }
            _ => {
                let target = MapNode::find_node(key, self.head.unwrap()).ok_or(Error::NotFound)?;
                let balance_pivot = self.compute_subtraccion_pivot(target);
                self.compute_balance_subtractive(balance_pivot);
                self.size -= 1;
                MapNode::free_node(target);
                Ok(())
            }
        }
    }
    
    

    /// Returns the number of elemnts in the `Map`
    ///
    /// # Examples
    /// ```
    /// let mut map = gavl::Map::<String, i32>::new();
    /// for elem in 0..10 {
    ///     map.add(elem.to_string(), elem);
    /// }
    /// assert_eq!(map.len(), 10);
    /// ```
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.size
    }

    
    pub fn into_iter(self) -> iters::IntoIter<KeyType, ContentType> {
        iters::IntoIter::new(self)
    }
    
    

    /// Returns a iterator for Map
    /// 
    /// The iterator yields a pair of inmutable references to key and content for each element
    /// 
    /// Returned values are In-Order
    /// 
    /// `item = (&KeyType, &ContentType)`
    /// 
    /// # Examples
    /// ``` 
    /// let mut map:gavl::Map<usize, usize> = gavl::Map::new();
    /// 
    /// for elem in (0..4).rev() {
    ///     map.add(elem, 0).unwrap();
    /// }
    /// 
    /// let mut iterator = map.iter();
    /// 
    /// assert_eq!(Some((&0, &0)), iterator.next());
    /// assert_eq!(Some((&1, &0)), iterator.next());
    /// assert_eq!(Some((&2, &0)), iterator.next());
    /// assert_eq!(Some((&3, &0)), iterator.next());
    /// assert_eq!(None, iterator.next());
    /// 
    /// ```
    pub fn iter(&self) -> iters::Iter<KeyType, ContentType> {
        iters::Iter::new(self)
    }
    

    
    /// Returns a iterator for Map with mutable content
    /// 
    /// The iterator yields a pair of references for each elemnt inmutable for key and mutable for content
    /// 
    /// Returned values are In-Order
    /// 
    /// `item = (&KeyType, &mut ContentType)`
    /// 
    /// # Examples
    /// ``` 
    /// let mut map:gavl::Map<usize, usize> = gavl::Map::new();
    /// 
    /// for elem in (0..4).rev() {
    ///     map.add(elem, 0).unwrap();
    /// }
    /// 
    /// for (key, content) in map.iter_mut() {
    ///     *content = 1;
    /// }
    /// 
    /// let mut iterator = map.iter_mut();
    /// assert_eq!(Some((&0, &mut 1)), iterator.next());
    /// assert_eq!(Some((&1, &mut 1)), iterator.next());
    /// assert_eq!(Some((&2, &mut 1)), iterator.next());
    /// assert_eq!(Some((&3, &mut 1)), iterator.next());
    /// assert_eq!(None, iterator.next());
    /// 
    /// ```
    pub fn iter_mut(&mut self) -> iters::IterMut<KeyType, ContentType> {
        iters::IterMut::new(self)
    }
    
    
    
    #[cfg(any(feature = "unchecked_mut", doc))]
    pub fn iter_ref_mut_unchecked(&mut self) -> IterMutUnchecked<KeyType, ContentType> {
        iters::IterMutUnchecked::new(self)
    }

    

    /// # Dependant on feature into_precomputed
    /// Return an iterator check [`IntoIterPrecomp`][`IntoIterPrecomp`] for extra info
    /// * This method consumes the Map
    /// 
    /// 
    /// [`IntoIterPrecomp`]: iters::IntoIterPrecomp
    #[cfg(any(feature = "into_precomputed", doc))]
    pub fn into_iter_precomputed(self) -> iters::IntoIterPrecomp<KeyType, ContentType> {
        iters::IntoIterPrecomp::new(self)
    }

    
}