| 1 | // -*- C++ -*- |
| 2 | |
| 3 | #ifndef HL_MODULO_H |
| 4 | #define HL_MODULO_H |
| 5 | |
| 6 | /// A templated class that provides faster modulo functions when the |
| 7 | /// argument is a power of two. |
| 8 | |
| 9 | #include <stdlib.h> |
| 10 | #include "checkpoweroftwo.h" |
| 11 | |
| 12 | namespace HL { |
| 13 | |
| 14 | template <size_t Modulus> |
| 15 | class Modulo; |
| 16 | |
| 17 | template <size_t Modulus> |
| 18 | class Modulo { |
| 19 | public: |
| 20 | template <class TYPE> |
| 21 | static TYPE mod (TYPE m) { |
| 22 | if (IsPowerOfTwo<Modulus>::VALUE) { |
| 23 | return m & (Modulus - 1); |
| 24 | } else { |
| 25 | return m % Modulus; |
| 26 | } |
| 27 | } |
| 28 | }; |
| 29 | |
| 30 | } |
| 31 | |
| 32 | #endif |