}
-static INLINE void add512(const union uint512_u *x,
- const union uint512_u *y, union uint512_u *r)
+static INLINE void add512(union uint512_u * RESTRICT x,
+ const union uint512_u * RESTRICT y)
{
#ifndef __GOST3411_BIG_ENDIAN__
- unsigned int CF, OF;
- unsigned long long tmp;
+ unsigned int CF;
unsigned int i;
CF = 0;
- for (i = 0; i < 8; i++)
- {
- /* Detecting integer overflow condition for three numbers
- * in a portable way is tricky a little. */
-
- /* Step 1: numbers cause overflow */
- tmp = x->QWORD[i] + y->QWORD[i];
-
- /* Compare with any of two summands, no need to check both */
- if (tmp < x->QWORD[i])
- OF = 1;
- else
- OF = 0;
-
- /* Step 2: carry bit causes overflow */
- tmp += CF;
-
- if (CF > 0 && tmp == 0)
- OF = 1;
-
- CF = OF;
-
- r->QWORD[i] = tmp;
+ for (i = 0; i < 8; i++) {
+ const unsigned long long left = x->QWORD[i];
+ unsigned long long sum;
+
+ sum = left + y->QWORD[i] + CF;
+ /*
+ * (sum == left): is noop, because it's possible only
+ * when `left' is added with `0 + 0' or with `ULLONG_MAX + 1',
+ * in that case `CF' (carry) retain previous value, which is correct,
+ * because when `left + 0 + 0' there was no overflow (thus no carry),
+ * and when `left + ULLONG_MAX + 1' value is wrapped back to
+ * itself with overflow, thus creating carry.
+ *
+ * (sum != left):
+ * if `sum' is not wrapped (sum > left) there should not be carry,
+ * if `sum' is wrapped (sum < left) there should be carry.
+ */
+ if (sum != left)
+ CF = (sum < left);
+ x->QWORD[i] = sum;
}
#else
- const unsigned char *xp, *yp;
- unsigned char *rp;
+ const unsigned char *yp;
+ unsigned char *xp;
unsigned int i;
int buf;
- xp = (const unsigned char *)&x[0];
+ xp = (unsigned char *)&x[0];
yp = (const unsigned char *)&y[0];
- rp = (unsigned char *)&r[0];
buf = 0;
for (i = 0; i < 64; i++) {
buf = xp[i] + yp[i] + (buf >> 8);
- rp[i] = (unsigned char)buf & 0xFF;
+ xp[i] = (unsigned char)buf & 0xFF;
}
#endif
}
static INLINE void stage2(gost2012_hash_ctx * CTX, const unsigned char *data)
{
- union uint512_u m;
-
- memcpy(&m, data, sizeof(m));
- g(&(CTX->h), &(CTX->N), (const unsigned char *)&m);
+ g(&(CTX->h), &(CTX->N), data);
- add512(&(CTX->N), &buffer512, &(CTX->N));
- add512(&(CTX->Sigma), &m, &(CTX->Sigma));
+ add512(&(CTX->N), &buffer512);
+ add512(&(CTX->Sigma), (const union uint512_u *)data);
}
static INLINE void stage3(gost2012_hash_ctx * CTX)
g(&(CTX->h), &(CTX->N), (const unsigned char *)&(CTX->buffer));
- add512(&(CTX->N), &buf, &(CTX->N));
- add512(&(CTX->Sigma), (const union uint512_u *)&CTX->buffer[0],
- &(CTX->Sigma));
+ add512(&(CTX->N), &buf);
+ add512(&(CTX->Sigma), (const union uint512_u *)&CTX->buffer[0]);
g(&(CTX->h), &buffer0, (const unsigned char *)&(CTX->N));
size_t chunksize;
while (len > 63 && CTX->bufsize == 0) {
- stage2(CTX, data);
+ memcpy(&CTX->buffer[0], data, 64);
+ stage2(CTX, &CTX->buffer[0]);
data += 64;
len -= 64;