From 982961a54280f9ff791bccc50f5b6a3e169de402 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Niels=20M=C3=B6ller?= <nisse@lysator.liu.se>
Date: Fri, 17 May 2013 13:47:43 +0200
Subject: [PATCH] Fix rotation macros to portably support zero rotation count.

---
 ChangeLog | 4 ++++
 macros.h  | 8 +++++---
 2 files changed, 9 insertions(+), 3 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 06ae8ff5..958a85e3 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,9 @@
 2013-05-17  Niels Möller  <nisse@lysator.liu.se>
 
+	* macros.h (ROTL32, ROTL64): Avoid undefined behaviour for zero
+	rotation count. Unfortunately makes CAST128 a bit slower with
+	gcc-4.6.3.
+
 	* ecc-j-to-a.c (ecc_j_to_a): Fixed ecc_modp_mul call, to avoid
 	invalid overlap of arguments to mpn_mul_n. Problem tracked down by
 	Magnus Holmgren.
diff --git a/macros.h b/macros.h
index 38b9e219..5dbe29d3 100644
--- a/macros.h
+++ b/macros.h
@@ -141,9 +141,11 @@ do {						\
 		  (dst) += (blocksize),		\
 		  (src) += (blocksize)) )
 
-#define ROTL32(n,x) (((x)<<(n)) | ((x)>>(32-(n))))
-
-#define ROTL64(n,x) (((x)<<(n)) | ((x)>>(64-(n))))
+/* The masking of the right shift is needed to allow n == 0 (using
+   just 32 - n and 64 - n results in undefined behaviour). */
+#define ROTL32(n,x) (((x)<<(n)) | ((x)>>((-(n)&31))))
+  
+#define ROTL64(n,x) (((x)<<(n)) | ((x)>>((-(n))&63)))
 
 /* Requires that size > 0 */
 #define INCREMENT(size, ctr)			\
-- 
GitLab