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
#[cfg(test)]
mod tests;

#[cfg(test)]
mod test_asymptotes;

// Realized that this was the only useful data type to use as keys
// for the tree.  usize is the default pointer size for the system.
type T = usize;

/// An implementation of Van Emde Boas Trees in Rust
///
/// # Fields
/// * children: Vec<VEBTree> - the child VEBTrees of this tree
/// * aux: Vec<VEBTree> - a single element Vec that holds to aux tree
///     uses a Vec wrapper to allocate it on the heap without hardcore
///     mutable reference nonsense.
/// * max: Option<T> - The maximum of the currently stored elements,
///     none if there are no stored elements, equal to min if there is
///     only one element
/// * min: Option<T> - The minimum of the currently stored elements,
///     none if there are no stored elements, equal to max if there is
///     only one element
#[derive(Clone,Debug, PartialEq, Eq)]
pub struct VEBTree {
    children: Vec<VEBTree>,
    aux: Vec<VEBTree>,
    max: Option<T>,
    min: Option<T>

}

impl VEBTree {
    /// Creates a new VEBTree with given max capacity.
    ///
    /// # Arguments
    /// * max_size: the maximum capacity with which to
    ///     initialize the tree
    ///
    /// # Returns
    /// * A tree initialized to the maximum capacity
    ///     specified
    pub fn new(max_size: usize) -> Self {
        // Takes the square root of the max_size, then casts
        // it back to an usize integer 
        let self_size: usize;
        let pass_size: usize;
        if max_size <= 2 {
            self_size = 0;
            pass_size = 0;
        } else {
            let tmp = (max_size as f64).sqrt().ceil() as usize;
            self_size = tmp;
            pass_size = tmp;
        }
        let mut children_seed: Vec<VEBTree> = Vec::with_capacity(self_size);
        let mut aux_seed: Vec<VEBTree> = Vec::with_capacity(1);
        if pass_size > 0 {
            for index in 0..self_size {
                children_seed.push(Self::new(pass_size));
            }
            let mut aux = Self::new(pass_size);
            aux_seed.push(aux);
        }
        let mut tree = VEBTree {
            children: children_seed,
            aux: aux_seed,
            max: None,
            min: None
        };
        return tree
    }
}

impl VEBTree {
    /// Returns the quotient of the given number with respect to the
    ///     instance's number of children.
    /// # Arguments
    /// * self: the instance of the VEBTree
    /// * value: the value to divide by the number of
    ///     children
    ///
    /// # Returns
    /// * The quotient of the number w.r.t. self.children.len()
    fn high(&self, value: T) -> T {
        return value / self.children.len();
    }

    /// Returns the modulus of the given number with respect to the
    ///     instance's number of children.
    /// # Arguments
    /// * self: &Self - the instance of the VEBTree
    /// * value: T==usize - the value to modulo by the number of
    ///     children
    ///
    /// # Returns
    /// * The modulus of the number w.r.t. self.children.len()
    fn low(&self, value: T) -> T {
        return value % self.children.len();
    }

    /// Returns whether or not the given element is in the tree
    ///
    /// # Arguments
    /// * self: the instance of the VEBTree
    /// * value: the value for which to check membership
    ///
    /// # Returns
    /// * Whether or not the value is contained in the tree
    pub fn contains(&self, value: T) -> bool {
        match self.min {
            Some(min_val) => {
                if value == min_val {
                    return true;
                } else {
                    match self.max {
                        Some(max_val) => {
                            if value == max_val {
                                return true;
                            } else {
                                if self.children.len() > 0 {
                                    return self
                                        .children[self.high(value)]
                                        .contains(self.low(value));
                                } else {
                                    return false;
                                }
                            }
                        },
                        None => {return false;}
                    }
                }
            },
            None => {return false;}
        }
    }

    /// Searches the tree for the given value and returns the value if
    ///     it is in the tree, None if not.
    ///
    /// # Arguments
    /// * self: the instance of the VEBTree to operate on
    /// * value: the value to search for in the tree
    ///
    /// # Returns
    /// * The value being searched for or None if the value
    ///     is not in the tree.
    pub fn search(&self, value: T) -> Option<T> {
        let min_val = self.min?;
        if value == min_val {
            return self.min;
        }
        let max_val = self.max?;
        if value == max_val {
            return self.max;
        }
        if self.children.len() == 0 {
            return None;
        } else {
            let local_idx = self.high(value);
            let pass_value = self.low(value);
            self.children[local_idx].minimum()?;
            let result = self.children[local_idx].search(pass_value)?;
            return Some(result+local_idx*self.children.len());
        }
    }

    /// Convenience function to handle making the recursive insert calls
    ///     into the child trees.
    ///
    /// # Arguments
    /// * self: the instance of the VEBTree to operate on
    /// * value: the value to insert into the tree
    fn insert_into_tree(&mut self, value: T) {
        if self.children.len() > 0 {
            let local_idx = self.high(value);
            let pass_value = self.low(value);
            match self.children[local_idx].minimum() {
                Some(min_value) => (),
                None => {
                    self.aux[0].insert(local_idx);
                }
            };
            self.children[local_idx].insert(pass_value);
        }
    }

    /// Insert a value into the array, does nothing if the value
    ///     is already present.
    ///
    /// # Arguments
    /// * self: the instance of the VEBTree to operate on
    /// * value: the value to insert into the tree
    pub fn insert(&mut self, value: T) {
        match self.min {
            Some(min_value) => {
                if value == min_value {
                    return;
                } else {
                    match self.max {
                        Some(max_value) => {
                            if max_value == value {
                                return;
                            } else {
                                if value < min_value {
                                    self.min = Some(value);
                                    self.insert_into_tree(value);
                                    return;
                                } else if value > max_value {
                                    self.max = Some(value);
                                    self.insert_into_tree(value);
                                    return;
                                } else {
                                    self.insert_into_tree(value);
                                    return;
                                }
                            }
                        },
                        None => {
                            self.max = Some(value);
                            self.insert_into_tree(value);
                            return;
                        }
                    };
                }
            },
            None => {
                self.min = Some(value);
                self.max = Some(value);
                self.insert_into_tree(value);
                return;
            }
        };

    }

    /// Convenience function to manage making recursive delete calls
    ///     into the VEBTree
    ///
    /// # Arguments
    /// * self: the instance of the VEBTree to operate on
    /// * value: the value to delete from the child trees
    fn delete_from_tree(&mut self, value: T) {
        if self.children.len() > 0 {
            let local_idx = self.high(value);
            let pass_value = self.low(value);
            self.children[local_idx].delete(pass_value);
            if self.children[local_idx].minimum() == None {
                self.aux[0].delete(local_idx);
            }
        }
    }

    /// Deletes an element from the VEBTree
    ///
    /// # Arguments
    /// * self: the instance of the VEBTree to operate on
    /// * value: the value to delete from the tree
    pub fn delete(&mut self, value: T){
        match self.min {
            Some(min_value) => {
                match self.max {
                    Some(max_value) => {
                        if max_value == min_value {
                            self.delete_from_tree(value);
                            self.min = None;
                            self.max = None;
                            return;
                        } else if self.children.len() == 0 {
                            if value == min_value {
                                self.min = Some(max_value);
                            } else {
                                self.max = Some(min_value);
                            }
                        } else if value == min_value {
                            self.delete_from_tree(value);
                            let first_populated = self.aux[0].minimum();
                            match first_populated {
                                Some(first_cluster) => {
                                    let new_min = self
                                        .children[first_cluster as usize]
                                        .minimum();
                                    match new_min {
                                        Some(min) => {
                                            self.min = Some((first_cluster
                                                            * self.children.len() as T
                                                             + min));
                                            return;
                                        },
                                        // Not sure how one gets here, probably
                                        // going to panic because structure corruption
                                        None => {
                                            panic!("Data structure appears corrupt");
                                        }
                                    };
                                },
                                None => {
                                    self.max = None;
                                    self.min = None;
                                }
                            };
                        } else if value == max_value {
                            self.delete_from_tree(value);
                            let last_populated = self.aux[0].maximum();
                            match last_populated {
                                Some(last_cluster) => {
                                    let new_max = self
                                        .children[last_cluster as usize]
                                        .maximum();
                                    match new_max {
                                        Some(max) => {
                                            self.max = Some((last_cluster
                                                             * self.children.len() as T
                                                             + max));
                                            return;
                                        },
                                        None => {
                                            panic!("Data structure appears corrupt");
                                        }
                                    };
                                },
                                None => {
                                    self.max = None;
                                    self.min = None;
                                }
                            };
                        } else if value < max_value && value > min_value {
                            self.delete_from_tree(value);
                            return;
                        } else {
                            return;
                        }

                    },
                    None => {
                        // This case shouldn't happen as there should always
                        // be a max when there is a min.
                        self.min = None;
                        self.max = None;
                        return;
                    }
                };
            },
            None => {
                self.min = None;
                self.max = None;
                return;
            }
        };
    }

    /// Gets the minimum of the currently stored elements
    ///
    /// # Arguments
    /// * self: the instance of VEBTree to operate on
    ///
    /// # Returns
    /// * The minimum element currently stored in the tree
    pub fn minimum(&self) -> Option<T> {
        return self.min;
    }

    /// Gets the maximum of the currently stored elements
    ///
    /// # Arguments
    /// * self: &Self - the instance of VEBTree to operate on.
    ///
    /// # Returns
    /// * The maximum element currently stored in the tree
    pub fn maximum(&self) -> Option<T> {
        return self.max;
    }

    /// Finds the next consecutive element currently in the tree
    ///
    /// # Arguments
    /// * self: the instance of VEBTree to operate on.
    /// * value: the value to find the successor of.
    ///
    /// # Returns
    /// * The successor of 'value' or None if not found
    pub fn findnext(&self, value: T) -> Option<T> {
        if self.children.len() == 0 {
            let min_val = self.min?;
            let max_val = self.max?;
            if value == 0 && max_val == 1 {
                return self.max;
            } else {
                return None;
            }
        } else {
            match self.min {
                Some(min_value) => {
                    if value < min_value {
                        return self.min
                    }
                },
                None => ()
            };
            let cur_cluster_max = self.children[self.high(value)].maximum();
            match cur_cluster_max {
                Some(max_value) => {
                    if self.low(value) < max_value {
                        let offset = self.children[self.high(value)]
                            .findnext(self.low(value))?;
                        return match self.children[self.high(value)].search(offset) {
                            Some(n) => {
                                return Some(n + self.high(value)*self.children.len());
                            },
                            None => {
                                return None;
                            }
                        };
                    }
                },
                None => ()
            };
            let next_cluster = self.aux[0].findnext(self.high(value))?;
            let offset = self.children[next_cluster].minimum()?;
            return match self.children[next_cluster].search(offset) {
                Some(n) => {
                    return Some(n + next_cluster*self.children.len());
                },
                None => {
                    return None;
                }
            };
        }
    }

    /// Finds the immediate previous element currently in the array
    ///
    /// # Arguments
    /// * self: the instance of VEBTree to operate on
    /// * value: the value to find the predecessor of
    ///
    /// # Returns
    /// * The predecessor of 'value' or None if not found
    pub fn findprev(&self, value: T) -> Option<T> {
        if self.children.len() == 0 {
            let max_value = self.maximum()?;
            let min_value = self.minimum()?;
            if max_value == value && max_value != min_value {
                return self.min;
            } else {
                return None;
            }
        } else {
            match self.maximum() {
                Some(max_value) => {
                    if value > max_value {
                        return self.max;
                    }
                },
                None => ()
            };
            let cur_cluster_min = self.children[self.high(value)].minimum();
            match cur_cluster_min {
                Some(min_value) => {
                    if self.low(value) > min_value {
                        let offset = self.children[self.high(value)]
                            .findprev(self.low(value))?;
                        return match self.children[self.high(value)].search(offset) {
                            Some(n) => {
                                return Some(n + self.high(value)*self.children.len());
                            },
                            None => {
                                return None;
                            }
                        };
                    }
                },
                None => ()
            };
            let next_cluster = self.aux[0].findprev(self.high(value))?;
            let offset = self.children[next_cluster].maximum()?;
            return match self.children[next_cluster].search(offset) {
                Some(n) => {
                    return Some(n + next_cluster*self.children.len());
                },
                None => {
                    return None;
                }
            };
        }
    }
}