Skip to content

Commit

Permalink
maths_utils: Factor out calculate_odd_parity() with builtins
Browse files Browse the repository at this point in the history
* swdptap of firmware and "adapter"_swd of `hosted` all used parity/popcount
* Extracting this also allows using MSVC with adapter backends
* Use `uint8_t` to correspond to `hosted` libusb packet buffers
  • Loading branch information
ALTracer committed Dec 31, 2023
1 parent c5c91e2 commit 4e42c24
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/include/maths_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,6 @@
#include <stdint.h>

uint8_t ulog2(uint32_t value);
uint8_t calculate_odd_parity(uint32_t value);

#endif /* INCLUDE_MATHS_UTILS_H */
18 changes: 18 additions & 0 deletions src/maths_utils.c
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,21 @@ uint8_t ulog2(uint32_t value)
return (sizeof(uint8_t) * 8U) - result;
#endif
}

uint8_t calculate_odd_parity(const uint32_t value)
{
#if defined(__GNUC__)
/* Ask for the libgcc impl */
return __builtin_parity(value);
#elif defined(_MSC_VER)
/* Ask for a CPU insn */
return __popcount(value) & 1U;
#else
/* Generic impl */
uint8_t result = 0;
for (uint32_t bit = 0; bit < 32; ++bit)
result ^= (value >> bit) & 1U;

return result;
#endif
}

0 comments on commit 4e42c24

Please sign in to comment.