#include "utils.h"

ULONG GetRandomInt(PRUNTIME pRuntime, __in ULONG uMin, __in ULONG uMax)
{
	if (uMax < (ULONG)0xFFFFFFFF)
		uMax++;

	return (API_RAND() % (uMax - uMin)) + uMin;
}

LPWSTR GetRandomStringW(PRUNTIME pRuntime,  __in ULONG uMin)
{
	LPWSTR pString = (LPWSTR)API_ALLOC(pRuntime, (uMin + 64) * sizeof(WCHAR));

	while (API_WCSLEN(pString) < uMin)
	{
		WCHAR pSubString[32] = { 0x0, 0x0 };

		API__ITOW_S(GetRandomInt(pRuntime, 1, 0xffffff), pSubString, 6, 0x10);
		API_WCSCAT_S(pString, uMin + 64, pSubString);
	}

	return pString;
}

LPSTR GetRandomStringA(PRUNTIME pRuntime,  __in ULONG uMin)
{
	LPSTR pString = (LPSTR)API_ALLOC(pRuntime, uMin + 64);

	while (API_STRLEN(pString) < uMin)
	{
		CHAR pSubString[32] = { 0x0, 0x0 };

		API__ITOA_S(GetRandomInt(pRuntime, 1, 0xffffff), pSubString, 6, 0x10);
		API_STRCAT_S(pString, uMin + 64, pSubString);
	}

	return pString;
}

VOID AppendRandomData(PRUNTIME pRuntime,  PBYTE pBuffer, DWORD uBuffLen)
{
	DWORD i;
	static BOOL uFirstTime = TRUE;

	if (uFirstTime) {
		API_SRAND(API_GETTICKCOUNT());
		uFirstTime = FALSE;
	}

	for (i = 0; i<uBuffLen; i++)
		pBuffer[i] = API_RAND();
}


LPBYTE GetRandomData(PRUNTIME pRuntime, __in DWORD dwBuffLen)
{
	LPBYTE lpBuffer = (LPBYTE)API_ALLOC(pRuntime, dwBuffLen);
	AppendRandomData(pRuntime, lpBuffer, dwBuffLen);
	return lpBuffer;
}


ULONG Align(__in ULONG uSize, __in ULONG uAlignment)
{
	return (((uSize + uAlignment - 1) / uAlignment) * uAlignment);
}