From def14493cb660b9503f6493f88f9935d4119f9ba Mon Sep 17 00:00:00 2001 From: Adrian Conlon Date: Sat, 2 Dec 2017 19:01:07 +0000 Subject: [PATCH] Allow fallback for where intrinsics aren't available. Signed-off-by: Adrian Conlon --- inc/EightBitCompilerDefinitions.h | 36 +++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/inc/EightBitCompilerDefinitions.h b/inc/EightBitCompilerDefinitions.h index 2cbe43d..965743f 100644 --- a/inc/EightBitCompilerDefinitions.h +++ b/inc/EightBitCompilerDefinitions.h @@ -1,5 +1,30 @@ #pragma once +namespace EightBit { + int countBits(uint8_t value); + bool oddParity(uint8_t value); +} + +/* +Published in 1988, the C Programming Language 2nd Ed. +(by Brian W.Kernighan and Dennis M.Ritchie) mentions +this in exercise 2 - 9. On April 19, 2006 Don Knuth pointed +out to me that this method "was first published by Peter +Wegner in CACM 3 (1960), 322. +(Also discovered independently by Derrick Lehmer and published +in 1964 in a book edited by Beckenbach.)" +*/ +inline int EightBit::countBits(uint8_t value) { + int count; // c accumulates the total bits set in value + for (count = 0; value; ++count) + value &= value - 1; // clear the least significant bit set + return count; +} + +inline bool EightBit::oddParity(uint8_t value) { + return countBits(value) % 2; +} + #ifdef _MSC_VER # include @@ -7,7 +32,7 @@ # define LIKELY(x) (x) # define UNLIKELY(x) (x) -# define EIGHTBIT_PARITY(x) (__popcnt(value) % 2) +# define EIGHTBIT_PARITY(x) (__popcnt(x) % 2) # define UNREACHABLE __assume(0) @@ -23,5 +48,12 @@ # define UNREACHABLE __builtin_unreachable(); #else -# error Unknown compiler + +# define LIKELY(x) (x) +# define UNLIKELY(x) (x) + +# define EIGHTBIT_PARITY(x) EightBit::oddParity(x) + +# define UNREACHABLE + #endif