Skip to content

Commit

Permalink
Add a range check to bitset_index.
Browse files Browse the repository at this point in the history
The function assumes the two bitsets are the same size, but was never
checking for it. If the user passed in a second bitset that is smaller
than the first, it could lead to an out-of-bounds access on the
underlying std::vector.
  • Loading branch information
plietar committed Aug 29, 2024
1 parent 3e76ce8 commit ffa1f4a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ std::vector<size_t> bitset_index_cpp(
Rcpp::XPtr<individual_index_t> a,
Rcpp::XPtr<individual_index_t> b
) {
if (a->max_size() != b->max_size()) {
Rcpp::stop("Incompatible bitmap sizes, %d vs %d",
a->max_size(), b->max_size());
}

auto values = std::vector<size_t>();
auto i = 1u;
for (const auto& v : *a) {
Expand Down
20 changes: 20 additions & 0 deletions tests/testthat/test-utils.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,23 @@ test_that('time_cached calls again for a different timestep', {
expect_equal(cached_fn(timestep = 2), 43)
mockery::expect_called(fn, 2)
})

test_that("bitset_index works", {
a <- individual::Bitset$new(10)$insert(c(3,5,7,9))
b <- individual::Bitset$new(10)$insert(c(2,4,5,8,9))
expect_equal(bitset_index(a, b), c(2,4))

a <- individual::Bitset$new(10)
b <- individual::Bitset$new(10)$insert(c(2,4,5,8,9))
expect_equal(bitset_index(a, b), NULL)

a <- individual::Bitset$new(10)$insert(c(3,5,7,9))
b <- individual::Bitset$new(10)
expect_equal(bitset_index(a, b), NULL)
})

test_that("bitset_index errors if size does not match", {
a <- individual::Bitset$new(10)$insert(c(3,5,7,9))
b <- individual::Bitset$new(20)$insert(c(2,4,5,8,9))
expect_error(bitset_index(a, b), "Incompatible bitmap sizes")
})

0 comments on commit ffa1f4a

Please sign in to comment.