void _Assert(char* strFile, unsigned line)
{
fflush(stdout);
fprintf(stderr, "\nAssert Failed %s, line:%u\n", strFile, line);
fflush(stderr);
abort();
}
#ifdef _DEBUG
#define MY_ASSERT(f) \
if (f) \
NULL; \
else \
_Assert(__FILE__, __LINE__);
#else
#define MY_ASSERT(f) NULL
#endif
void* my_memcpy(void* pvTo, void* pvFrom, size_t size)
{
byte* pbTo = (byte*)pvTo;
byte* pbFrom = (byte*)pvFrom;
MY_ASSERT(pbTo != NULL && pbFrom != NULL);
MY_ASSERT(pbTo >= pbFrom + size || pbFrom >= pbTo + size);
while(size-- > 0)
*pbTo++ = *pbFrom++;
return (void*)pbTo;
}
char* my_strdup(char* str)
{
MY_ASSERT(str != NULL);
char* strNew = (char*)malloc(strlen(str) + 1);
if (strNew == NULL)
return NULL;
//strcpy(str1,str2)时,str2会把末尾的'\0’也给复制到str1中且覆盖一个str1字符;
strcpy(strNew, str);
return strNew;
}
void* my_memset1(void* pv, byte b, size_t size)
{
MY_ASSERT(pv != NULL);
byte* pb = (byte*)pv;
while (size-- > 0)
*pb++ = b;
return pv;
}
// 假定long占4字节,一字节为8位
long* long_fill(void* pv, long l, size_t size)
{
MY_ASSERT(pv != NULL);
long* pl = (long*)pv;
while (size > 0)
{
*pl = l;
size -= 4;
pl += 4;
}
return (long*)pv;
}
size_t threshold = 4;
void* my_memset2(void* pv, byte b, size_t size)
{
byte* pb = (byte*)pv;
if (size > threshold)
{
unsigned long l;
l = (b << 8) | b;
l = (l << 16) | l;
pb = (byte*)long_fill((long*)pb, l, size / 4);
size = size % 4;
}
while (size -- >0)
*(pb++) = b;
return pv;
}
struct Prim
{
int pos;
int index;
};
Prim vecPrim[N];
bool binarySearch(int pos, int& index)
{
int first = 0;
int last = N - 1;
int mid = 0;
while (first <= last)
{
mid = (first + last) / 2;
if (vecPrim[mid].pos < pos)
first = mid + 1;
else if (vecPrim[mid].pos > pos)
last = mid - 1;
else
{
index = vecPrim[mid].pos;
return true;
}
}
return false;
}
template<class T>
int highestBitSet(T input)
{
register int result;
assert(input); // zero is invalid input!
assert(sizeof(T)==4); // 32bit data only!
_asm bsr eax, input
_asm mov result, eax
return result;
}
template<class T>
T nearestPowerOfTwo(T input)
{
// the least possible power-of-two value is 1
if (input <= 1) return 1;
int highestBit = highestBitSet(input);
int roundingTest = input & (1<< (highestBit-1));
if (roundingTest)
++highestBit;
return static_cast<T>(1<<highestBit);
}
inline int lowestBitSet (unsigned short input)
{
register int result;
assert(input); // zero is invalid input!
_asm mov dx, input // copy into a 32bit reg
_asm and edx, 0xffff // keep only the bits we want
_asm bsf eax, edx // perform the scan
_asm mov result, eax
return result;
}