1// misc.cpp - written and placed in the public domain by Wei Dai
2
3#include "pch.h"
4
5#ifndef CRYPTOPP_IMPORTS
6
7#include "misc.h"
8#include "words.h"
9#include <new>
10
11NAMESPACE_BEGIN(CryptoPP)
12
13void xorbuf(byte *buf, const byte *mask, size_t count)
14{
15	size_t i;
16
17	if (IsAligned<word32>(buf) && IsAligned<word32>(mask))
18	{
19		if (!CRYPTOPP_BOOL_SLOW_WORD64 && IsAligned<word64>(buf) && IsAligned<word64>(mask))
20		{
21			for (i=0; i<count/8; i++)
22				((word64*)buf)[i] ^= ((word64*)mask)[i];
23			count -= 8*i;
24			if (!count)
25				return;
26			buf += 8*i;
27			mask += 8*i;
28		}
29
30		for (i=0; i<count/4; i++)
31			((word32*)buf)[i] ^= ((word32*)mask)[i];
32		count -= 4*i;
33		if (!count)
34			return;
35		buf += 4*i;
36		mask += 4*i;
37	}
38
39	for (i=0; i<count; i++)
40		buf[i] ^= mask[i];
41}
42
43void xorbuf(byte *output, const byte *input, const byte *mask, size_t count)
44{
45	size_t i;
46
47	if (IsAligned<word32>(output) && IsAligned<word32>(input) && IsAligned<word32>(mask))
48	{
49		if (!CRYPTOPP_BOOL_SLOW_WORD64 && IsAligned<word64>(output) && IsAligned<word64>(input) && IsAligned<word64>(mask))
50		{
51			for (i=0; i<count/8; i++)
52				((word64*)output)[i] = ((word64*)input)[i] ^ ((word64*)mask)[i];
53			count -= 8*i;
54			if (!count)
55				return;
56			output += 8*i;
57			input += 8*i;
58			mask += 8*i;
59		}
60
61		for (i=0; i<count/4; i++)
62			((word32*)output)[i] = ((word32*)input)[i] ^ ((word32*)mask)[i];
63		count -= 4*i;
64		if (!count)
65			return;
66		output += 4*i;
67		input += 4*i;
68		mask += 4*i;
69	}
70
71	for (i=0; i<count; i++)
72		output[i] = input[i] ^ mask[i];
73}
74
75bool VerifyBufsEqual(const byte *buf, const byte *mask, size_t count)
76{
77	size_t i;
78	byte acc8 = 0;
79
80	if (IsAligned<word32>(buf) && IsAligned<word32>(mask))
81	{
82		word32 acc32 = 0;
83		if (!CRYPTOPP_BOOL_SLOW_WORD64 && IsAligned<word64>(buf) && IsAligned<word64>(mask))
84		{
85			word64 acc64 = 0;
86			for (i=0; i<count/8; i++)
87				acc64 |= ((word64*)buf)[i] ^ ((word64*)mask)[i];
88			count -= 8*i;
89			if (!count)
90				return acc64 == 0;
91			buf += 8*i;
92			mask += 8*i;
93			acc32 = word32(acc64) | word32(acc64>>32);
94		}
95
96		for (i=0; i<count/4; i++)
97			acc32 |= ((word32*)buf)[i] ^ ((word32*)mask)[i];
98		count -= 4*i;
99		if (!count)
100			return acc32 == 0;
101		buf += 4*i;
102		mask += 4*i;
103		acc8 = byte(acc32) | byte(acc32>>8) | byte(acc32>>16) | byte(acc32>>24);
104	}
105
106	for (i=0; i<count; i++)
107		acc8 |= buf[i] ^ mask[i];
108	return acc8 == 0;
109}
110
111#if !(defined(_MSC_VER) && (_MSC_VER < 1300))
112using std::new_handler;
113using std::set_new_handler;
114#endif
115
116void CallNewHandler()
117{
118	new_handler newHandler = set_new_handler(NULL);
119	if (newHandler)
120		set_new_handler(newHandler);
121
122	if (newHandler)
123		newHandler();
124	else
125		throw std::bad_alloc();
126}
127
128NAMESPACE_END
129
130#endif
131