summaryrefslogtreecommitdiff
path: root/words.h
blob: 5a5af2a2a27e72ec4edaa38e4d1d7d2c98cf58bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#ifndef CRYPTOPP_WORDS_H
#define CRYPTOPP_WORDS_H

#include "config.h"
#include "misc.h"

NAMESPACE_BEGIN(CryptoPP)

inline size_t CountWords(const word *X, size_t N)
{
	while (N && X[N-1]==0)
		N--;
	return N;
}

inline void SetWords(word *r, word a, size_t n)
{
	for (size_t i=0; i<n; i++)
		r[i] = a;
}

inline void CopyWords(word *r, const word *a, size_t n)
{
	if (r != a)
#if CRYPTOPP_MSC_VERSION
		memcpy_s(r, n*WORD_SIZE, a, n*WORD_SIZE);
#else
		memcpy(r, a, n*WORD_SIZE);
#endif
}

inline void XorWords(word *r, const word *a, const word *b, size_t n)
{
	for (size_t i=0; i<n; i++)
		r[i] = a[i] ^ b[i];
}

inline void XorWords(word *r, const word *a, size_t n)
{
	for (size_t i=0; i<n; i++)
		r[i] ^= a[i];
}

inline void AndWords(word *r, const word *a, const word *b, size_t n)
{
	for (size_t i=0; i<n; i++)
		r[i] = a[i] & b[i];
}

inline void AndWords(word *r, const word *a, size_t n)
{
	for (size_t i=0; i<n; i++)
		r[i] &= a[i];
}

inline word ShiftWordsLeftByBits(word *r, size_t n, unsigned int shiftBits)
{
	assert (shiftBits<WORD_BITS);
	word u, carry=0;
	if (shiftBits)
		for (size_t i=0; i<n; i++)
		{
			u = r[i];
			r[i] = (u << shiftBits) | carry;
			carry = u >> (WORD_BITS-shiftBits);
		}
	return carry;
}

inline word ShiftWordsRightByBits(word *r, size_t n, unsigned int shiftBits)
{
	assert (shiftBits<WORD_BITS);
	word u, carry=0;
	if (shiftBits)
		for (size_t i=n; i>0; i--)
		{
			u = r[i-1];
			r[i-1] = (u >> shiftBits) | carry;
			carry = u << (WORD_BITS-shiftBits);
		}
	return carry;
}

inline void ShiftWordsLeftByWords(word *r, size_t n, size_t shiftWords)
{
	shiftWords = STDMIN(shiftWords, n);
	if (shiftWords)
	{
		for (size_t i=n-1; i>=shiftWords; i--)
			r[i] = r[i-shiftWords];
		SetWords(r, 0, shiftWords);
	}
}

inline void ShiftWordsRightByWords(word *r, size_t n, size_t shiftWords)
{
	shiftWords = STDMIN(shiftWords, n);
	if (shiftWords)
	{
		for (size_t i=0; i+shiftWords<n; i++)
			r[i] = r[i+shiftWords];
		SetWords(r+n-shiftWords, 0, shiftWords);
	}
}

NAMESPACE_END

#endif