Skip to content

Commit

Permalink
Add bit field utility functions
Browse files Browse the repository at this point in the history
  • Loading branch information
tmadlener committed Jun 26, 2024
1 parent 4f72168 commit ccb5543
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
2 changes: 1 addition & 1 deletion test/utils/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ endif()
include(Catch)

add_executable(unittests_edm4hep
test_kinematics.cpp test_vector_utils.cpp test_covmatrix_utils.cpp test_PIDHandler.cpp)
test_kinematics.cpp test_vector_utils.cpp test_covmatrix_utils.cpp test_PIDHandler.cpp test_bit_utils.cpp)

target_link_libraries(unittests_edm4hep edm4hep EDM4HEP::utils Catch2::Catch2 Catch2::Catch2WithMain)

Expand Down
25 changes: 25 additions & 0 deletions test/utils/test_bit_utils.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include "edm4hep/utils/bit_utils.h"

#include <catch2/catch_template_test_macros.hpp>
#include <catch2/catch_test_macros.hpp>

#include <cstdint>
#include <tuple>

// The integet types that we us as type fields in EDM4hep
using BitFieldTypes = std::tuple<int32_t, uint32_t, int64_t, int16_t, uint64_t>;

TEMPLATE_LIST_TEST_CASE("Bitfield utils set and get", "[bit_utils]", BitFieldTypes) {
using namespace edm4hep;
auto bitField = TestType{};

for (auto i = 0u; i < sizeof(TestType) * 8; ++i) {
REQUIRE_FALSE(utils::checkBit(bitField, i));
}

bitField = utils::setBit(bitField, 3, true);
REQUIRE(utils::checkBit(bitField, 3));

bitField = utils::setBit(bitField, 3, false);
REQUIRE_FALSE(utils::checkBit(bitField, 3));
}
16 changes: 16 additions & 0 deletions utils/include/edm4hep/utils/bit_utils.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#ifndef EDM4HEP_UTILS_BIT_UTILS_HH
#define EDM4HEP_UTILS_BIT_UTILS_HH

namespace edm4hep::utils {
template <typename T>
constexpr T setBit(T bits, int bitNum, bool value) {
return (bits & ~(1 << bitNum)) | (value << bitNum);
}

template <typename T>
constexpr bool checkBit(T bits, int bitNum) {
return bits & (0x1 << bitNum);
}
} // namespace edm4hep::utils

#endif // EDM4HEP_UTILS_BIT_UTILS_HH

0 comments on commit ccb5543

Please sign in to comment.