Skip to content

Commit

Permalink
Merge pull request #92 from dusk-network/insert-bounds-check
Browse files Browse the repository at this point in the history
dusk-merkle: add bounds check at `Tree::insert`
  • Loading branch information
Eduardo Leegwater Simões authored Sep 9, 2024
2 parents 7d24269 + e422e58 commit 00f0ce9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
5 changes: 5 additions & 0 deletions dusk-merkle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## Added

- Add bounds check on `Tree::insert`, improving panic message [#91]

## [0.5.2] - 2023-10-27

### Fixed
Expand Down Expand Up @@ -102,6 +106,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fix `CheckBytes` derivation in `Node` [#15]

<!-- ISSUES -->
[#91]: https://github.com/dusk-network/merkle/issues/91
[#73]: https://github.com/dusk-network/merkle/issues/73
[#62]: https://github.com/dusk-network/merkle/issues/62
[#58]: https://github.com/dusk-network/merkle/issues/58
Expand Down
20 changes: 15 additions & 5 deletions dusk-merkle/src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,18 @@ where
/// Insert an `item` at the given `position` in the tree.
///
/// # Panics
/// If `position >= capacity`.
pub fn insert(&mut self, position: u64, item: impl Into<T>) {
self.root.insert(0, position, item);
self.positions.insert(position);
/// If `index >= capacity`.
pub fn insert(&mut self, index: u64, item: impl Into<T>) {
let capacity = self.capacity();

assert!(
index < capacity,
"index out of bounds: \
the capacity is {capacity} but the index is {index}"
);

self.root.insert(0, index, item);
self.positions.insert(index);
}

/// Remove and return the item at the given `position` in the tree if it
Expand Down Expand Up @@ -200,7 +208,9 @@ mod tests {
}

#[test]
#[should_panic]
#[should_panic(
expected = "index out of bounds: the capacity is 8 but the index is 8"
)]
fn tree_insertion_out_of_bounds() {
let mut tree = SumTree::new();
tree.insert(tree.capacity(), 42);
Expand Down

0 comments on commit 00f0ce9

Please sign in to comment.