Skip to content

Commit

Permalink
Make sure things fail at compile time for wrong inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
tmadlener committed Apr 19, 2024
1 parent 6dcec4d commit 71d4e77
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
3 changes: 3 additions & 0 deletions test/utils/test_covmatrix_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ TEST_CASE("CovarianceMatrix indexing", "[cov_matrix_utils]") {

STATIC_REQUIRE(get_cov_dim(21) == 6);
STATIC_REQUIRE(get_cov_dim(1) == 1);
#if !__cpp_consteval
// This will fail to compile if we have consteval
REQUIRE_THROWS_AS(get_cov_dim(14), std::invalid_argument);
#endif

// clang-format off
// For better interpretability of the tests below, these are the indices of a
Expand Down
17 changes: 10 additions & 7 deletions utils/include/edm4hep/utils/cov_matrix_utils.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
#ifndef EDM4HEP_UTILS_COVMATRIXUTILS_H
#define EDM4HEP_UTILS_COVMATRIXUTILS_H

#include <algorithm>
#include <array>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#include <type_traits>

Expand Down Expand Up @@ -44,13 +41,19 @@ namespace utils {
*
* **NOTE: to avoid having to do a square root operation and in order to keep
* this constexpr this is currently only implemented for storage sizes up to
* 21 (corresponding to covariance matrix dimensions of 6 x 6)**
* 21 (corresponding to covariance matrix dimensions of 6 x 6)**. This
* function is intended to be called in constexpr or immediate contexts in
* order to fail at compilation already for invalid values of N.
*
* @param N the size of the 1D storage
*
* @returns the dimension of the covariance matrix
*/
inline constexpr std::size_t get_cov_dim(std::size_t N) {
#if cpp_consteval
consteval std::size_t get_cov_dim(std::size_t N) {
#else
constexpr std::size_t get_cov_dim(std::size_t N) {
#endif
switch (N) {
case 21:
return 6;
Expand Down Expand Up @@ -91,7 +94,7 @@ namespace utils {
const auto i = detail::to_index(dimI);
const auto j = detail::to_index(dimJ);

const auto dim = get_cov_dim(N);
constexpr auto dim = get_cov_dim(N);
if (i < 0 || j < 0 || i >= dim || j >= dim) {
// TODO: error handling
}
Expand All @@ -104,7 +107,7 @@ namespace utils {
auto i = detail::to_index(dimI);
auto j = detail::to_index(dimJ);

const auto dim = get_cov_dim(N);
constexpr auto dim = get_cov_dim(N);
if (i < 0 || j < 0 || i >= dim || j >= dim) {
// TODO: error handling
}
Expand Down

0 comments on commit 71d4e77

Please sign in to comment.