Improve macro hygiene
This commit improves hygiene and formatting of macro definitions
throughout the library. Specifically:
- It adds brackets around parameters to avoid unintended
interpretation of arguments, e.g. due to operator precedence.
- It adds uses of the `do { ... } while( 0 )` idiom for macros that
can be used as commands.
diff --git a/library/sha512.c b/library/sha512.c
index 941ecda..cec955b 100644
--- a/library/sha512.c
+++ b/library/sha512.c
@@ -224,8 +224,8 @@
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( (const unsigned char *)data != NULL );
-#define SHR(x,n) (x >> n)
-#define ROTR(x,n) (SHR(x,n) | (x << (64 - n)))
+#define SHR(x,n) ((x) >> (n))
+#define ROTR(x,n) (SHR(x,n) | ((x) << (64 - (n))))
#define S0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7))
#define S1(x) (ROTR(x,19) ^ ROTR(x,61) ^ SHR(x, 6))
@@ -233,15 +233,16 @@
#define S2(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39))
#define S3(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41))
-#define F0(x,y,z) ((x & y) | (z & (x | y)))
-#define F1(x,y,z) (z ^ (x & (y ^ z)))
+#define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
+#define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
-#define P(a,b,c,d,e,f,g,h,x,K) \
-{ \
- temp1 = h + S3(e) + F1(e,f,g) + K + x; \
- temp2 = S2(a) + F0(a,b,c); \
- d += temp1; h = temp1 + temp2; \
-}
+#define P(a,b,c,d,e,f,g,h,x,K) \
+ do \
+ { \
+ temp1 = (h) + S3(e) + F1(e,f,g) + (K) + (x); \
+ temp2 = S2(a) + F0(a,b,c); \
+ (d) += temp1; (h) = temp1 + temp2; \
+ } while( 0 )
for( i = 0; i < 16; i++ )
{