-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #40 from azizkayumov/index
Node deletion - reuses the space allocated for deleted nodes to create new nodes.
- Loading branch information
Showing
5 changed files
with
218 additions
and
171 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
pub struct Index { | ||
pub time_id: usize, | ||
deleted_ids: Vec<usize>, // maybe use a set instead? | ||
} | ||
|
||
impl Index { | ||
pub fn new() -> Self { | ||
Self { | ||
time_id: 0, | ||
deleted_ids: Vec::new(), | ||
} | ||
} | ||
|
||
pub fn insert(&mut self) -> usize { | ||
if !self.deleted_ids.is_empty() { | ||
return self.deleted_ids.pop().unwrap(); | ||
} | ||
self.time_id += 1; | ||
self.time_id - 1 | ||
} | ||
|
||
pub fn delete(&mut self, id: usize) { | ||
assert!(id < self.time_id, "Invalid deletion"); | ||
self.deleted_ids.push(id); | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
|
||
#[test] | ||
pub fn test_indexing() { | ||
let mut index = super::Index::new(); | ||
// make 3 insertions | ||
assert_eq!(index.insert(), 0); | ||
assert_eq!(index.insert(), 1); | ||
assert_eq!(index.insert(), 2); | ||
|
||
// delete 1 | ||
index.delete(1); | ||
|
||
// next insertion should be 1 | ||
assert_eq!(index.insert(), 1); | ||
} | ||
|
||
#[test] | ||
#[should_panic] | ||
pub fn test_invalid_deletion() { | ||
let mut index = super::Index::new(); | ||
// make 3 insertions | ||
assert_eq!(index.insert(), 0); | ||
assert_eq!(index.insert(), 1); | ||
assert_eq!(index.insert(), 2); | ||
|
||
index.delete(4); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.