2
3
mirror of https://foundry.openuru.org/gitblit/r/CWE-ou-minkata.git synced 2025-07-13 18:17:49 -04:00

Fix line endings and tabs

This commit is contained in:
Branan Purvine-Riley
2011-04-11 16:27:55 -07:00
parent d4250e19b5
commit 908aaeb6f6
2738 changed files with 702562 additions and 702562 deletions

View File

@ -1,46 +1,46 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Unix/pnUtUxStr.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#ifdef HS_BUILD_FOR_UNIX
#else
// Dummy function to prevent a linker warning complaining about no public symbols if the
// contents of the file get compiled out via pre-processor
void UxStrPreventLNK4221Warning () {
}
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Unix/pnUtUxStr.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#ifdef HS_BUILD_FOR_UNIX
#else
// Dummy function to prevent a linker warning complaining about no public symbols if the
// contents of the file get compiled out via pre-processor
void UxStrPreventLNK4221Warning () {
}
#endif

View File

@ -1,45 +1,45 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Unix/pnUtUxSync.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#ifdef HS_BUILD_FOR_UNIX
#else
// Dummy function to prevent a linker warning complaining about no public symbols if the
// contents of the file get compiled out via pre-processor
void UxSyncPreventLNK4221Warning () {
}
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Unix/pnUtUxSync.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#ifdef HS_BUILD_FOR_UNIX
#else
// Dummy function to prevent a linker warning complaining about no public symbols if the
// contents of the file get compiled out via pre-processor
void UxSyncPreventLNK4221Warning () {
}
#endif

View File

@ -1,55 +1,55 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Unix/pnUtUxUuid.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Uuid Unix implementation
*
***/
#ifdef HS_BUILD_FOR_UNIX
#include <uuid/uuid.h>
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(uuid_t));
#else
// Dummy function to prevent a linker warning complaining about no public symbols if the
// contents of the file get compiled out via pre-processor
void UxUuidPreventLNK4221Warning () {
}
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Unix/pnUtUxUuid.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Uuid Unix implementation
*
***/
#ifdef HS_BUILD_FOR_UNIX
#include <uuid/uuid.h>
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(uuid_t));
#else
// Dummy function to prevent a linker warning complaining about no public symbols if the
// contents of the file get compiled out via pre-processor
void UxUuidPreventLNK4221Warning () {
}
#endif

View File

@ -1,25 +1,25 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/

View File

@ -1,372 +1,372 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Addr.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
// hardcoded byte ordering -- Intel only
#ifdef _M_IX86
const unsigned kHostClassALoopbackAddr = 0x7f000001; // 127.0.0.1
const unsigned kHostClassALoopbackMask = 0x00ffffff;
const unsigned kNetClassALoopbackAddr = 0x0100007f; // 127.0.0.1
const unsigned kNetClassALoopbackMask = 0xffffff00;
const unsigned kHostClassANatAddr = 0x000000a0; // 10.0.0.0 - 10.255.255.255
const unsigned kHostClassANatMask = 0x000000ff;
const unsigned kNetClassANatAddr = 0x0a000000; // 10.0.0.0 - 10.255.255.255
const unsigned kNetClassANatMask = 0xff000000;
const unsigned kHostClassBNetAddr = 0x000010ac; // 172.16.0.0 - 172.31.255.255
const unsigned kHostClassBNetMask = 0x0000f0ff;
const unsigned kNetClassBNetAddr = 0xac100000; // 172.16.0.0 - 172.31.255.255
const unsigned kNetClassBNetMask = 0xfff00000;
const unsigned kHostClassCNatAddr = 0x0000a8c0; // 192.168.0.0 - 192.168.255.255
const unsigned kHostClassCNatMask = 0x0000ffff;
const unsigned kNetClassCNatAddr = 0xc0a80000; // 192.168.0.0 - 192.168.255.255
const unsigned kNetClassCNatMask = 0xffff0000;
#else
#error "Must implement for this architecture"
#endif // ifdef _M_IX86
/*****************************************************************************
*
* Internal functions
*
***/
//===========================================================================
// Address sort order:
// (highest)
// externally visible address
// 10.0.0.0 - 10.255.255.255
// 172.16.0.0 - 172.31.255.255
// 192.168.0.0 - 192.168.255.255
// 127.0.0.0 - 127.0.0.255
// (lowest)
static int NetAddressNodeSortValueNetOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kNetClassALoopbackMask) == (kNetClassALoopbackAddr & kNetClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kNetClassCNatMask) == (kNetClassCNatAddr & kNetClassCNatMask))
return 3;
if ((addr & kNetClassBNetMask) == (kNetClassBNetAddr & kNetClassBNetMask))
return 2;
if ((addr & kNetClassANatMask) == (kNetClassANatAddr & kNetClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static int NetAddressNodeSortValueHostOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kHostClassALoopbackMask) == (kHostClassALoopbackAddr & kHostClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kHostClassCNatMask) == (kHostClassCNatAddr & kHostClassCNatMask))
return 3;
if ((addr & kHostClassBNetMask) == (kHostClassBNetAddr & kHostClassBNetMask))
return 2;
if ((addr & kHostClassANatMask) == (kHostClassANatAddr & kHostClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static NetAddressNode NodeFromString (const wchar * string[]) {
// skip leading whitespace
const wchar * str = *string;
while (iswspace(*str))
++str;
// This function handles partial ip addresses (61.33)
// as well as full dotted quads. The address can be
// terminated by whitespace or ':' as well as '\0'
byte data[4];
* (dword *) data = 0;
for (unsigned i = sizeof(data); i--; ) {
if (!iswdigit(*str))
return (unsigned)-1;
unsigned value = StrToUnsigned(str, &str, 10);
if (value >= 256)
return (unsigned)-1;
data[i] = (byte) value;
if (!*str || (*str == ':') || iswspace(*str))
break;
static const wchar s_separator[] = L"\0...";
if (*str++ != s_separator[i])
return (unsigned)-1;
}
*string = str;
return * (NetAddressNode *) &data[0];
}
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
int d = i1.sin_addr.S_un.S_addr - i2.sin_addr.S_un.S_addr;
return d ? d : i1.sin_port - i2.sin_port;
}
//===========================================================================
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
return i1.sin_addr.S_un.S_addr == i2.sin_addr.S_un.S_addr;
}
//===========================================================================
unsigned NetAddressHash (const NetAddress & addr) {
// by using only the node number as the hash value, users can safely use
// hash value to find addresses by either using either "SameSystem" or "Equal"
const sockaddr_in & iAddr = * (const sockaddr_in *) &addr;
return iAddr.sin_addr.S_un.S_addr;
}
//===========================================================================
void NetAddressToString (
const NetAddress & addr,
wchar * str,
unsigned chars,
ENetAddressFormat format
) {
ASSERT(str);
static const wchar * s_fmts[] = {
L"%S", // kNetAddressFormatNodeNumber
L"%S:%u", // kNetAddressFormatAll
};
ASSERT(format < arrsize(s_fmts));
const sockaddr_in & inetaddr = * (const sockaddr_in *) &addr;
StrPrintf(
str,
chars,
s_fmts[format],
inet_ntoa(inetaddr.sin_addr),
ntohs(inetaddr.sin_port)
);
}
//===========================================================================
bool NetAddressFromString (NetAddress * addr, const wchar str[], unsigned defaultPort) {
ASSERT(addr);
ASSERT(str);
// NetAddress is bigger than sockaddr_in so start by zeroing the whole thing
ZEROPTR(addr);
for (;;) {
NetAddressNode node = NodeFromString(&str);
if (node == (unsigned)-1)
break;
if (*str == L':')
defaultPort = StrToUnsigned(str + 1, nil, 10);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_port = htons((word) defaultPort);
inetaddr->sin_addr.S_un.S_addr = htonl(node);
// inetaddr->sin_zero already zeroed
return true;
}
// address already zeroed
return false;
}
//===========================================================================
unsigned NetAddressGetPort (
const NetAddress & addr
) {
return ntohs(((sockaddr_in *) &addr)->sin_port);
}
//===========================================================================
void NetAddressSetPort (
unsigned port,
NetAddress * addr
) {
((sockaddr_in *) addr)->sin_port = htons((word) port);
}
//============================================================================
NetAddressNode NetAddressGetNode (const NetAddress & addr) {
return ntohl(((const sockaddr_in *) &addr)->sin_addr.S_un.S_addr);
}
//===========================================================================
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
) {
ZEROPTR(addr);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_addr.S_un.S_addr = htonl(node);
inetaddr->sin_port = htons((word) port);
}
//===========================================================================
void NetAddressNodeToString (
NetAddressNode node,
wchar * str,
unsigned chars
) {
in_addr addr;
addr.S_un.S_addr = htonl(node);
StrPrintf(str, chars, L"%S", inet_ntoa(addr));
}
//===========================================================================
NetAddressNode NetAddressNodeFromString (
const wchar string[],
const wchar * endPtr[]
) {
if (!endPtr)
endPtr = &string;
*endPtr = string;
return NodeFromString(endPtr);
}
//===========================================================================
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
) {
NetAddressFromNode(
kHostClassALoopbackAddr,
port,
addr
);
}
//===========================================================================
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
) {
ASSERT(count);
ASSERT(addresses);
for (;;) {
// Get local computer name
char name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = arrsize(name);
if (!GetComputerName(name, &size))
StrCopy(name, "localhost", arrsize(name));
// Get IPv4 addresses for local system
const struct hostent * host = gethostbyname(name);
if (!host || !host->h_name)
break;
host = gethostbyname(host->h_name);
if (!host)
break;
if (host->h_length != sizeof(dword))
break;
// Count total number of addresses
unsigned found = 0;
const dword ** addr = (const dword **) host->h_addr_list;
for (; *addr; ++addr)
++found;
if (!found)
break;
// Create a buffer to sort the addresses
NetAddressNode * dst;
if (found > count)
dst = ALLOCA(NetAddressNode, found);
else
dst = addresses;
// Fill address buffer
const dword * src = * (const dword **) host->h_addr_list;
for (unsigned index = 0; index < found; ++index)
dst[index] = ntohl(src[index]);
// Sort addresses by priority
QSORT(
NetAddressNode,
dst,
found,
NetAddressNodeSortValueHostOrder(elem1) - NetAddressNodeSortValueHostOrder(elem2)
);
// Return the number of addresses the user actually requested
if (found > count) {
for (unsigned index = 0; index < count; ++index)
addresses[index] = dst[index];
return count;
}
return found;
}
// Initialize with a valid value
addresses[0] = kHostClassALoopbackAddr;
return 1;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Addr.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
// hardcoded byte ordering -- Intel only
#ifdef _M_IX86
const unsigned kHostClassALoopbackAddr = 0x7f000001; // 127.0.0.1
const unsigned kHostClassALoopbackMask = 0x00ffffff;
const unsigned kNetClassALoopbackAddr = 0x0100007f; // 127.0.0.1
const unsigned kNetClassALoopbackMask = 0xffffff00;
const unsigned kHostClassANatAddr = 0x000000a0; // 10.0.0.0 - 10.255.255.255
const unsigned kHostClassANatMask = 0x000000ff;
const unsigned kNetClassANatAddr = 0x0a000000; // 10.0.0.0 - 10.255.255.255
const unsigned kNetClassANatMask = 0xff000000;
const unsigned kHostClassBNetAddr = 0x000010ac; // 172.16.0.0 - 172.31.255.255
const unsigned kHostClassBNetMask = 0x0000f0ff;
const unsigned kNetClassBNetAddr = 0xac100000; // 172.16.0.0 - 172.31.255.255
const unsigned kNetClassBNetMask = 0xfff00000;
const unsigned kHostClassCNatAddr = 0x0000a8c0; // 192.168.0.0 - 192.168.255.255
const unsigned kHostClassCNatMask = 0x0000ffff;
const unsigned kNetClassCNatAddr = 0xc0a80000; // 192.168.0.0 - 192.168.255.255
const unsigned kNetClassCNatMask = 0xffff0000;
#else
#error "Must implement for this architecture"
#endif // ifdef _M_IX86
/*****************************************************************************
*
* Internal functions
*
***/
//===========================================================================
// Address sort order:
// (highest)
// externally visible address
// 10.0.0.0 - 10.255.255.255
// 172.16.0.0 - 172.31.255.255
// 192.168.0.0 - 192.168.255.255
// 127.0.0.0 - 127.0.0.255
// (lowest)
static int NetAddressNodeSortValueNetOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kNetClassALoopbackMask) == (kNetClassALoopbackAddr & kNetClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kNetClassCNatMask) == (kNetClassCNatAddr & kNetClassCNatMask))
return 3;
if ((addr & kNetClassBNetMask) == (kNetClassBNetAddr & kNetClassBNetMask))
return 2;
if ((addr & kNetClassANatMask) == (kNetClassANatAddr & kNetClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static int NetAddressNodeSortValueHostOrder (NetAddressNode addr) {
// Loopback addresses
if ((addr & kHostClassALoopbackMask) == (kHostClassALoopbackAddr & kHostClassALoopbackMask))
return 4;
// Private addresses
if ((addr & kHostClassCNatMask) == (kHostClassCNatAddr & kHostClassCNatMask))
return 3;
if ((addr & kHostClassBNetMask) == (kHostClassBNetAddr & kHostClassBNetMask))
return 2;
if ((addr & kHostClassANatMask) == (kHostClassANatAddr & kHostClassANatMask))
return 1;
// Public addresses
return 0;
}
//===========================================================================
static NetAddressNode NodeFromString (const wchar * string[]) {
// skip leading whitespace
const wchar * str = *string;
while (iswspace(*str))
++str;
// This function handles partial ip addresses (61.33)
// as well as full dotted quads. The address can be
// terminated by whitespace or ':' as well as '\0'
byte data[4];
* (dword *) data = 0;
for (unsigned i = sizeof(data); i--; ) {
if (!iswdigit(*str))
return (unsigned)-1;
unsigned value = StrToUnsigned(str, &str, 10);
if (value >= 256)
return (unsigned)-1;
data[i] = (byte) value;
if (!*str || (*str == ':') || iswspace(*str))
break;
static const wchar s_separator[] = L"\0...";
if (*str++ != s_separator[i])
return (unsigned)-1;
}
*string = str;
return * (NetAddressNode *) &data[0];
}
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
int d = i1.sin_addr.S_un.S_addr - i2.sin_addr.S_un.S_addr;
return d ? d : i1.sin_port - i2.sin_port;
}
//===========================================================================
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2) {
const sockaddr_in & i1 = * (const sockaddr_in *) &a1;
const sockaddr_in & i2 = * (const sockaddr_in *) &a2;
return i1.sin_addr.S_un.S_addr == i2.sin_addr.S_un.S_addr;
}
//===========================================================================
unsigned NetAddressHash (const NetAddress & addr) {
// by using only the node number as the hash value, users can safely use
// hash value to find addresses by either using either "SameSystem" or "Equal"
const sockaddr_in & iAddr = * (const sockaddr_in *) &addr;
return iAddr.sin_addr.S_un.S_addr;
}
//===========================================================================
void NetAddressToString (
const NetAddress & addr,
wchar * str,
unsigned chars,
ENetAddressFormat format
) {
ASSERT(str);
static const wchar * s_fmts[] = {
L"%S", // kNetAddressFormatNodeNumber
L"%S:%u", // kNetAddressFormatAll
};
ASSERT(format < arrsize(s_fmts));
const sockaddr_in & inetaddr = * (const sockaddr_in *) &addr;
StrPrintf(
str,
chars,
s_fmts[format],
inet_ntoa(inetaddr.sin_addr),
ntohs(inetaddr.sin_port)
);
}
//===========================================================================
bool NetAddressFromString (NetAddress * addr, const wchar str[], unsigned defaultPort) {
ASSERT(addr);
ASSERT(str);
// NetAddress is bigger than sockaddr_in so start by zeroing the whole thing
ZEROPTR(addr);
for (;;) {
NetAddressNode node = NodeFromString(&str);
if (node == (unsigned)-1)
break;
if (*str == L':')
defaultPort = StrToUnsigned(str + 1, nil, 10);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_port = htons((word) defaultPort);
inetaddr->sin_addr.S_un.S_addr = htonl(node);
// inetaddr->sin_zero already zeroed
return true;
}
// address already zeroed
return false;
}
//===========================================================================
unsigned NetAddressGetPort (
const NetAddress & addr
) {
return ntohs(((sockaddr_in *) &addr)->sin_port);
}
//===========================================================================
void NetAddressSetPort (
unsigned port,
NetAddress * addr
) {
((sockaddr_in *) addr)->sin_port = htons((word) port);
}
//============================================================================
NetAddressNode NetAddressGetNode (const NetAddress & addr) {
return ntohl(((const sockaddr_in *) &addr)->sin_addr.S_un.S_addr);
}
//===========================================================================
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
) {
ZEROPTR(addr);
sockaddr_in * inetaddr = (sockaddr_in *) addr;
inetaddr->sin_family = AF_INET;
inetaddr->sin_addr.S_un.S_addr = htonl(node);
inetaddr->sin_port = htons((word) port);
}
//===========================================================================
void NetAddressNodeToString (
NetAddressNode node,
wchar * str,
unsigned chars
) {
in_addr addr;
addr.S_un.S_addr = htonl(node);
StrPrintf(str, chars, L"%S", inet_ntoa(addr));
}
//===========================================================================
NetAddressNode NetAddressNodeFromString (
const wchar string[],
const wchar * endPtr[]
) {
if (!endPtr)
endPtr = &string;
*endPtr = string;
return NodeFromString(endPtr);
}
//===========================================================================
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
) {
NetAddressFromNode(
kHostClassALoopbackAddr,
port,
addr
);
}
//===========================================================================
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
) {
ASSERT(count);
ASSERT(addresses);
for (;;) {
// Get local computer name
char name[MAX_COMPUTERNAME_LENGTH + 1];
DWORD size = arrsize(name);
if (!GetComputerName(name, &size))
StrCopy(name, "localhost", arrsize(name));
// Get IPv4 addresses for local system
const struct hostent * host = gethostbyname(name);
if (!host || !host->h_name)
break;
host = gethostbyname(host->h_name);
if (!host)
break;
if (host->h_length != sizeof(dword))
break;
// Count total number of addresses
unsigned found = 0;
const dword ** addr = (const dword **) host->h_addr_list;
for (; *addr; ++addr)
++found;
if (!found)
break;
// Create a buffer to sort the addresses
NetAddressNode * dst;
if (found > count)
dst = ALLOCA(NetAddressNode, found);
else
dst = addresses;
// Fill address buffer
const dword * src = * (const dword **) host->h_addr_list;
for (unsigned index = 0; index < found; ++index)
dst[index] = ntohl(src[index]);
// Sort addresses by priority
QSORT(
NetAddressNode,
dst,
found,
NetAddressNodeSortValueHostOrder(elem1) - NetAddressNodeSortValueHostOrder(elem2)
);
// Return the number of addresses the user actually requested
if (found > count) {
for (unsigned index = 0; index < count; ++index)
addresses[index] = dst[index];
return count;
}
return found;
}
// Initialize with a valid value
addresses[0] = kHostClassALoopbackAddr;
return 1;
}

View File

@ -1,41 +1,41 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Dll.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Dll.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/

View File

@ -1,207 +1,207 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Misc.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
static MEMORYSTATUSEX s_memstatus;
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
const wchar * AppGetCommandLine () {
return GetCommandLineW();
}
//============================================================================
void MachineGetName (wchar *computerName, unsigned int length) {
DWORD len = length;
GetComputerNameW(computerName, &len);
}
/*****************************************************************************
*
* System status
*
***/
//============================================================================
void MemoryGetStatus (MemoryStatus * status) {
MEMORYSTATUSEX mem;
mem.dwLength = sizeof(mem);
GlobalMemoryStatusEx(&mem);
const qword BYTES_PER_MB = 1024 * 1024;
status->totalPhysMB = unsigned(mem.ullTotalPhys / BYTES_PER_MB);
status->availPhysMB = unsigned(mem.ullAvailPhys / BYTES_PER_MB);
status->totalPageFileMB = unsigned(mem.ullTotalPageFile / BYTES_PER_MB);
status->availPageFileMB = unsigned(mem.ullAvailPageFile / BYTES_PER_MB);
status->totalVirtualMB = unsigned(mem.ullTotalVirtual / BYTES_PER_MB);
status->availVirtualMB = unsigned(mem.ullAvailVirtual / BYTES_PER_MB);
status->memoryLoad = mem.dwMemoryLoad;
}
//============================================================================
void DiskGetStatus (ARRAY(DiskStatus) * disks) {
for (;;) {
DWORD length = GetLogicalDriveStrings(0, NULL);
if (!length || length > 2048)
break;
wchar * buffer = ALLOCA(wchar, length + 1);
if (!GetLogicalDriveStringsW(length, buffer))
break;
for (; *buffer; buffer += StrLen(buffer) + 1) {
UINT driveType = GetDriveTypeW(buffer);
if (driveType != DRIVE_FIXED)
continue;
ULARGE_INTEGER freeBytes;
ULARGE_INTEGER totalBytes;
if (!GetDiskFreeSpaceExW(buffer, &freeBytes, &totalBytes, NULL))
continue;
DiskStatus status;
StrCopy(status.name, buffer, arrsize(status.name));
const qword BYTES_PER_MB = 1024 * 1024;
status.totalSpaceMB = unsigned(totalBytes.QuadPart / BYTES_PER_MB);
status.freeSpaceMB = unsigned(freeBytes.QuadPart / BYTES_PER_MB);
disks->Add(status);
}
break;
}
}
//============================================================================
// Loosely taken from MS's cpuid code sample
void CpuGetInfo (
word * cpuCaps,
dword * cpuVendor,
word * cpuSignature
) {
dword signature = 0;
dword extended = 0;
dword flags[2] = { 0, 0 };
cpuVendor[0] = 0;
_asm {
// Detect if cpuid instruction is supported by attempting
// to change the ID bit of EFLAGS
pushfd
pop eax // get EFLAGS
mov ecx, eax // store copy of original EFLAGS
xor eax, 0x200000 // flip ID bit
push eax
popfd // replace EFLAGS
pushfd // get EFLAGS
pop eax
xor eax, ecx
je DONE
// Get processor id (GenuineIntel, AuthenticAMD, etc)
xor eax, eax
cpuid
mov edi, cpuVendor
mov [edi + 0], ebx
mov [edi + 4], edx
mov [edi + 8], ecx
// Check if capability flags are supported
cmp eax, 1
jl DONE
// Get processor capability flags and signature
mov eax, 1
cpuid
mov signature, eax
mov [flags + 0], edx
mov [flags + 4], ecx
// Check for extended capabilities
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jl DONE
// Get extended capabilities
mov eax, 0x80000001
cpuid
mov extended, edx
DONE:
}
// Decode capability flags
const static struct CpuCap {
word cpuFlag;
byte field;
byte bit;
} s_caps[] = {
// feature field bit
// ------- ----- ---
{ kCpuCapCmov, 0, 15 },
{ kCpuCapEst, 1, 7 },
{ kCpuCapHtt, 0, 28 },
{ kCpuCapMmx, 0, 23 },
{ kCpuCapPsn, 0, 18 },
{ kCpuCapSse, 0, 25 },
{ kCpuCapSse2, 0, 26 },
{ kCpuCapSse3, 1, 0 },
{ kCpuCapTsc, 0, 4 },
};
for (unsigned i = 0; i < arrsize(s_caps); ++i) {
const CpuCap & cap = s_caps[i];
if (flags[cap.field] & (1 << cap.bit))
*cpuCaps |= cap.cpuFlag;
}
// Copy signature
*cpuSignature = word(signature & 0xfff);
// If this is an AMD CPU, check for 3DNow support
const char * vendorAmd = "AuthenticAMD";
if (!MemCmp(vendorAmd, cpuVendor, 12)) {
if (extended & (1 << 31))
*cpuCaps |= kCpuCap3dNow;
}
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Misc.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
static MEMORYSTATUSEX s_memstatus;
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
const wchar * AppGetCommandLine () {
return GetCommandLineW();
}
//============================================================================
void MachineGetName (wchar *computerName, unsigned int length) {
DWORD len = length;
GetComputerNameW(computerName, &len);
}
/*****************************************************************************
*
* System status
*
***/
//============================================================================
void MemoryGetStatus (MemoryStatus * status) {
MEMORYSTATUSEX mem;
mem.dwLength = sizeof(mem);
GlobalMemoryStatusEx(&mem);
const qword BYTES_PER_MB = 1024 * 1024;
status->totalPhysMB = unsigned(mem.ullTotalPhys / BYTES_PER_MB);
status->availPhysMB = unsigned(mem.ullAvailPhys / BYTES_PER_MB);
status->totalPageFileMB = unsigned(mem.ullTotalPageFile / BYTES_PER_MB);
status->availPageFileMB = unsigned(mem.ullAvailPageFile / BYTES_PER_MB);
status->totalVirtualMB = unsigned(mem.ullTotalVirtual / BYTES_PER_MB);
status->availVirtualMB = unsigned(mem.ullAvailVirtual / BYTES_PER_MB);
status->memoryLoad = mem.dwMemoryLoad;
}
//============================================================================
void DiskGetStatus (ARRAY(DiskStatus) * disks) {
for (;;) {
DWORD length = GetLogicalDriveStrings(0, NULL);
if (!length || length > 2048)
break;
wchar * buffer = ALLOCA(wchar, length + 1);
if (!GetLogicalDriveStringsW(length, buffer))
break;
for (; *buffer; buffer += StrLen(buffer) + 1) {
UINT driveType = GetDriveTypeW(buffer);
if (driveType != DRIVE_FIXED)
continue;
ULARGE_INTEGER freeBytes;
ULARGE_INTEGER totalBytes;
if (!GetDiskFreeSpaceExW(buffer, &freeBytes, &totalBytes, NULL))
continue;
DiskStatus status;
StrCopy(status.name, buffer, arrsize(status.name));
const qword BYTES_PER_MB = 1024 * 1024;
status.totalSpaceMB = unsigned(totalBytes.QuadPart / BYTES_PER_MB);
status.freeSpaceMB = unsigned(freeBytes.QuadPart / BYTES_PER_MB);
disks->Add(status);
}
break;
}
}
//============================================================================
// Loosely taken from MS's cpuid code sample
void CpuGetInfo (
word * cpuCaps,
dword * cpuVendor,
word * cpuSignature
) {
dword signature = 0;
dword extended = 0;
dword flags[2] = { 0, 0 };
cpuVendor[0] = 0;
_asm {
// Detect if cpuid instruction is supported by attempting
// to change the ID bit of EFLAGS
pushfd
pop eax // get EFLAGS
mov ecx, eax // store copy of original EFLAGS
xor eax, 0x200000 // flip ID bit
push eax
popfd // replace EFLAGS
pushfd // get EFLAGS
pop eax
xor eax, ecx
je DONE
// Get processor id (GenuineIntel, AuthenticAMD, etc)
xor eax, eax
cpuid
mov edi, cpuVendor
mov [edi + 0], ebx
mov [edi + 4], edx
mov [edi + 8], ecx
// Check if capability flags are supported
cmp eax, 1
jl DONE
// Get processor capability flags and signature
mov eax, 1
cpuid
mov signature, eax
mov [flags + 0], edx
mov [flags + 4], ecx
// Check for extended capabilities
mov eax, 0x80000000
cpuid
cmp eax, 0x80000001
jl DONE
// Get extended capabilities
mov eax, 0x80000001
cpuid
mov extended, edx
DONE:
}
// Decode capability flags
const static struct CpuCap {
word cpuFlag;
byte field;
byte bit;
} s_caps[] = {
// feature field bit
// ------- ----- ---
{ kCpuCapCmov, 0, 15 },
{ kCpuCapEst, 1, 7 },
{ kCpuCapHtt, 0, 28 },
{ kCpuCapMmx, 0, 23 },
{ kCpuCapPsn, 0, 18 },
{ kCpuCapSse, 0, 25 },
{ kCpuCapSse2, 0, 26 },
{ kCpuCapSse3, 1, 0 },
{ kCpuCapTsc, 0, 4 },
};
for (unsigned i = 0; i < arrsize(s_caps); ++i) {
const CpuCap & cap = s_caps[i];
if (flags[cap.field] & (1 << cap.bit))
*cpuCaps |= cap.cpuFlag;
}
// Copy signature
*cpuSignature = word(signature & 0xfff);
// If this is an AMD CPU, check for 3DNow support
const char * vendorAmd = "AuthenticAMD";
if (!MemCmp(vendorAmd, cpuVendor, 12)) {
if (extended & (1 << 31))
*cpuCaps |= kCpuCap3dNow;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,82 +1,82 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Str.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars) {
return StrToAnsi(dest, source, destChars, CP_ACP);
}
//===========================================================================
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars, unsigned codePage) {
ASSERT(destChars != (unsigned)-1);
ASSERT(dest != nil);
int result = WideCharToMultiByte(codePage, 0, source, -1, dest, destChars, nil, nil);
if (result)
return result - 1; // return number of characters not including null terminator
else if (destChars) {
dest[destChars - 1] = 0; // null terminate the destination buffer
return destChars - 1;
}
else
return 0;
}
//===========================================================================
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars) {
return StrToUnicode(dest, source, destChars, CP_ACP);
}
//===========================================================================
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars, unsigned codePage) {
ASSERT(destChars != (unsigned)-1);
ASSERT(dest != nil);
int result = MultiByteToWideChar(codePage, 0, source, -1, dest, destChars);
if (result)
return result - 1; // return number of characters not including null terminator
else if (destChars) {
dest[destChars - 1] = 0; // null terminate the destination buffer
return destChars - 1;
}
else
return 0;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Str.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars) {
return StrToAnsi(dest, source, destChars, CP_ACP);
}
//===========================================================================
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars, unsigned codePage) {
ASSERT(destChars != (unsigned)-1);
ASSERT(dest != nil);
int result = WideCharToMultiByte(codePage, 0, source, -1, dest, destChars, nil, nil);
if (result)
return result - 1; // return number of characters not including null terminator
else if (destChars) {
dest[destChars - 1] = 0; // null terminate the destination buffer
return destChars - 1;
}
else
return 0;
}
//===========================================================================
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars) {
return StrToUnicode(dest, source, destChars, CP_ACP);
}
//===========================================================================
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars, unsigned codePage) {
ASSERT(destChars != (unsigned)-1);
ASSERT(dest != nil);
int result = MultiByteToWideChar(codePage, 0, source, -1, dest, destChars);
if (result)
return result - 1; // return number of characters not including null terminator
else if (destChars) {
dest[destChars - 1] = 0; // null terminate the destination buffer
return destChars - 1;
}
else
return 0;
}

View File

@ -1,359 +1,359 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Sync.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Spin lock functions
*
***/
//===========================================================================
static inline void EnterSpinLock (long * spinLock) {
for (;;)
if (*spinLock < 0)
if (!InterlockedIncrement(spinLock))
return;
else
InterlockedDecrement(spinLock);
}
//===========================================================================
static inline void LeaveSpinLock (long * spinLock) {
InterlockedDecrement(spinLock);
}
/****************************************************************************
*
* CLockWaitSet / CLockWaitSetAllocator
*
***/
class CLockWaitSet {
private:
unsigned m_refCount;
HANDLE m_waitEvent;
public:
LINK(CLockWaitSet) link;
inline CLockWaitSet ();
inline ~CLockWaitSet ();
inline void DecRef ();
inline void IncRef ();
inline void Signal ();
inline void Wait ();
};
class CLockWaitSetAllocator {
private:
CLockWaitSet m_array[256];
CLockWaitSetAllocator * m_prev;
LISTDECL(CLockWaitSet, link) m_spareList;
LISTDECL(CLockWaitSet, link) m_usedList;
static CLockWaitSetAllocator * s_allocator;
static long s_spinLock;
public:
CLockWaitSetAllocator (CLockWaitSetAllocator * prev);
~CLockWaitSetAllocator ();
static CLockWaitSet * Alloc ();
static void Free (CLockWaitSet * waitSet);
static void __cdecl Shutdown ();
};
CLockWaitSetAllocator * CLockWaitSetAllocator::s_allocator;
long CLockWaitSetAllocator::s_spinLock = -1;
//===========================================================================
CLockWaitSet::CLockWaitSet () {
m_refCount = 0;
m_waitEvent = CreateEvent(nil, true, false, nil);
}
//===========================================================================
CLockWaitSet::~CLockWaitSet () {
ASSERT(!m_refCount);
CloseHandle(m_waitEvent);
m_waitEvent = 0;
}
//===========================================================================
void CLockWaitSet::DecRef () {
ASSERT(m_refCount);
if (!--m_refCount) {
ResetEvent(m_waitEvent);
CLockWaitSetAllocator::Free(this);
}
}
//===========================================================================
void CLockWaitSet::IncRef () {
++m_refCount;
}
//===========================================================================
void CLockWaitSet::Signal () {
ASSERT(m_refCount);
SetEvent(m_waitEvent);
}
//===========================================================================
void CLockWaitSet::Wait () {
ASSERT(m_refCount);
WaitForSingleObject(m_waitEvent, INFINITE);
}
//===========================================================================
CLockWaitSetAllocator::CLockWaitSetAllocator (CLockWaitSetAllocator * prev) {
m_prev = prev;
if (prev) {
m_spareList.Link(&prev->m_spareList);
m_usedList.Link(&prev->m_usedList);
}
for (unsigned index = arrsize(m_array); index--; )
m_spareList.Link(&m_array[index]);
}
//===========================================================================
CLockWaitSetAllocator::~CLockWaitSetAllocator () {
DEL(m_prev);
}
//===========================================================================
CLockWaitSet * CLockWaitSetAllocator::Alloc () {
EnterSpinLock(&s_spinLock);
// If there is no active allocator or if the active allocator is full,
// create a new one
if (!s_allocator || !s_allocator->m_spareList.Head()) {
if (!s_allocator)
atexit(Shutdown);
s_allocator = NEW(CLockWaitSetAllocator)(s_allocator);
}
// Get an available wait set from the active allocator
CLockWaitSet * waitSet = s_allocator->m_spareList.Head();
s_allocator->m_usedList.Link(waitSet);
LeaveSpinLock(&s_spinLock);
return waitSet;
}
//===========================================================================
void CLockWaitSetAllocator::Free (CLockWaitSet * waitSet) {
EnterSpinLock(&s_spinLock);
// Return this wait set to the active allocator's spare list
ASSERT(s_allocator);
s_allocator->m_spareList.Link(waitSet);
LeaveSpinLock(&s_spinLock);
}
//===========================================================================
void CLockWaitSetAllocator::Shutdown () {
EnterSpinLock(&s_spinLock);
// Free all allocators
while (s_allocator) {
CLockWaitSetAllocator * prev = s_allocator->m_prev;
DEL(s_allocator);
s_allocator = prev;
}
LeaveSpinLock(&s_spinLock);
}
/****************************************************************************
*
* CLock
*
***/
//===========================================================================
CLock::CLock () {
m_waitSet = nil;
m_spinLock = -1;
m_readerCount = 0;
m_writerCount = 0;
}
//===========================================================================
CLock::~CLock () {
ASSERT(!m_waitSet);
ASSERT(m_spinLock == -1);
ASSERT(!m_readerCount);
ASSERT(!m_writerCount);
}
//===========================================================================
void CLock::EnterRead () {
EnterSpinLock(&m_spinLock);
for (;;) {
// If there are no writers, claim this lock for reading
if (!m_writerCount) {
++m_readerCount;
break;
}
// Otherwise, wait until the existing writer releases the lock
CLockWaitSet * waitSet = m_waitSet = (m_waitSet ? m_waitSet : CLockWaitSetAllocator::Alloc());
waitSet->IncRef();
LeaveSpinLock(&m_spinLock);
waitSet->Wait();
EnterSpinLock(&m_spinLock);
waitSet->DecRef();
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::EnterWrite () {
EnterSpinLock(&m_spinLock);
for (;;) {
// If there are no readers or writers, claim this lock for writing
if (!m_readerCount && !m_writerCount) {
++m_writerCount;
break;
}
// Otherwise, wait until the existing writer or all existing readers
// release the lock
CLockWaitSet * waitSet = m_waitSet = (m_waitSet ? m_waitSet : CLockWaitSetAllocator::Alloc());
waitSet->IncRef();
LeaveSpinLock(&m_spinLock);
waitSet->Wait();
EnterSpinLock(&m_spinLock);
waitSet->DecRef();
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::LeaveRead () {
EnterSpinLock(&m_spinLock);
// If this is the last reader, signal waiting threads to try claiming
// the lock again
ASSERT(m_readerCount);
if (!--m_readerCount)
if (m_waitSet) {
m_waitSet->Signal();
m_waitSet = nil;
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::LeaveWrite () {
EnterSpinLock(&m_spinLock);
// This is the last writer. Signal waiting threads to try claiming the
// lock again.
ASSERT(m_writerCount == 1);
--m_writerCount;
if (m_waitSet) {
m_waitSet->Signal();
m_waitSet = nil;
}
LeaveSpinLock(&m_spinLock);
}
/*****************************************************************************
*
* CEvent
*
***/
//============================================================================
CEvent::CEvent (
ECEventResetBehavior resetType,
bool initialSet
) {
m_handle = CreateEvent(
nil, // security attributes
(resetType == kEventManualReset) ? true : false,
initialSet,
nil // name
);
}
//============================================================================
CEvent::~CEvent () {
(void) CloseHandle(m_handle);
}
//============================================================================
void CEvent::Signal () {
SetEvent(m_handle);
}
//============================================================================
void CEvent::Reset () {
ResetEvent(m_handle);
}
//============================================================================
bool CEvent::Wait (unsigned waitMs) {
ThreadAssertCanBlock(__FILE__, __LINE__);
return WaitForSingleObject(m_handle, waitMs) == WAIT_OBJECT_0;
}
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
long AtomicAdd (long * value, long increment) {
return InterlockedExchangeAdd(value, increment);
}
//===========================================================================
long AtomicSet (long * value, long set) {
return InterlockedExchange(value, set);
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Sync.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Spin lock functions
*
***/
//===========================================================================
static inline void EnterSpinLock (long * spinLock) {
for (;;)
if (*spinLock < 0)
if (!InterlockedIncrement(spinLock))
return;
else
InterlockedDecrement(spinLock);
}
//===========================================================================
static inline void LeaveSpinLock (long * spinLock) {
InterlockedDecrement(spinLock);
}
/****************************************************************************
*
* CLockWaitSet / CLockWaitSetAllocator
*
***/
class CLockWaitSet {
private:
unsigned m_refCount;
HANDLE m_waitEvent;
public:
LINK(CLockWaitSet) link;
inline CLockWaitSet ();
inline ~CLockWaitSet ();
inline void DecRef ();
inline void IncRef ();
inline void Signal ();
inline void Wait ();
};
class CLockWaitSetAllocator {
private:
CLockWaitSet m_array[256];
CLockWaitSetAllocator * m_prev;
LISTDECL(CLockWaitSet, link) m_spareList;
LISTDECL(CLockWaitSet, link) m_usedList;
static CLockWaitSetAllocator * s_allocator;
static long s_spinLock;
public:
CLockWaitSetAllocator (CLockWaitSetAllocator * prev);
~CLockWaitSetAllocator ();
static CLockWaitSet * Alloc ();
static void Free (CLockWaitSet * waitSet);
static void __cdecl Shutdown ();
};
CLockWaitSetAllocator * CLockWaitSetAllocator::s_allocator;
long CLockWaitSetAllocator::s_spinLock = -1;
//===========================================================================
CLockWaitSet::CLockWaitSet () {
m_refCount = 0;
m_waitEvent = CreateEvent(nil, true, false, nil);
}
//===========================================================================
CLockWaitSet::~CLockWaitSet () {
ASSERT(!m_refCount);
CloseHandle(m_waitEvent);
m_waitEvent = 0;
}
//===========================================================================
void CLockWaitSet::DecRef () {
ASSERT(m_refCount);
if (!--m_refCount) {
ResetEvent(m_waitEvent);
CLockWaitSetAllocator::Free(this);
}
}
//===========================================================================
void CLockWaitSet::IncRef () {
++m_refCount;
}
//===========================================================================
void CLockWaitSet::Signal () {
ASSERT(m_refCount);
SetEvent(m_waitEvent);
}
//===========================================================================
void CLockWaitSet::Wait () {
ASSERT(m_refCount);
WaitForSingleObject(m_waitEvent, INFINITE);
}
//===========================================================================
CLockWaitSetAllocator::CLockWaitSetAllocator (CLockWaitSetAllocator * prev) {
m_prev = prev;
if (prev) {
m_spareList.Link(&prev->m_spareList);
m_usedList.Link(&prev->m_usedList);
}
for (unsigned index = arrsize(m_array); index--; )
m_spareList.Link(&m_array[index]);
}
//===========================================================================
CLockWaitSetAllocator::~CLockWaitSetAllocator () {
DEL(m_prev);
}
//===========================================================================
CLockWaitSet * CLockWaitSetAllocator::Alloc () {
EnterSpinLock(&s_spinLock);
// If there is no active allocator or if the active allocator is full,
// create a new one
if (!s_allocator || !s_allocator->m_spareList.Head()) {
if (!s_allocator)
atexit(Shutdown);
s_allocator = NEW(CLockWaitSetAllocator)(s_allocator);
}
// Get an available wait set from the active allocator
CLockWaitSet * waitSet = s_allocator->m_spareList.Head();
s_allocator->m_usedList.Link(waitSet);
LeaveSpinLock(&s_spinLock);
return waitSet;
}
//===========================================================================
void CLockWaitSetAllocator::Free (CLockWaitSet * waitSet) {
EnterSpinLock(&s_spinLock);
// Return this wait set to the active allocator's spare list
ASSERT(s_allocator);
s_allocator->m_spareList.Link(waitSet);
LeaveSpinLock(&s_spinLock);
}
//===========================================================================
void CLockWaitSetAllocator::Shutdown () {
EnterSpinLock(&s_spinLock);
// Free all allocators
while (s_allocator) {
CLockWaitSetAllocator * prev = s_allocator->m_prev;
DEL(s_allocator);
s_allocator = prev;
}
LeaveSpinLock(&s_spinLock);
}
/****************************************************************************
*
* CLock
*
***/
//===========================================================================
CLock::CLock () {
m_waitSet = nil;
m_spinLock = -1;
m_readerCount = 0;
m_writerCount = 0;
}
//===========================================================================
CLock::~CLock () {
ASSERT(!m_waitSet);
ASSERT(m_spinLock == -1);
ASSERT(!m_readerCount);
ASSERT(!m_writerCount);
}
//===========================================================================
void CLock::EnterRead () {
EnterSpinLock(&m_spinLock);
for (;;) {
// If there are no writers, claim this lock for reading
if (!m_writerCount) {
++m_readerCount;
break;
}
// Otherwise, wait until the existing writer releases the lock
CLockWaitSet * waitSet = m_waitSet = (m_waitSet ? m_waitSet : CLockWaitSetAllocator::Alloc());
waitSet->IncRef();
LeaveSpinLock(&m_spinLock);
waitSet->Wait();
EnterSpinLock(&m_spinLock);
waitSet->DecRef();
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::EnterWrite () {
EnterSpinLock(&m_spinLock);
for (;;) {
// If there are no readers or writers, claim this lock for writing
if (!m_readerCount && !m_writerCount) {
++m_writerCount;
break;
}
// Otherwise, wait until the existing writer or all existing readers
// release the lock
CLockWaitSet * waitSet = m_waitSet = (m_waitSet ? m_waitSet : CLockWaitSetAllocator::Alloc());
waitSet->IncRef();
LeaveSpinLock(&m_spinLock);
waitSet->Wait();
EnterSpinLock(&m_spinLock);
waitSet->DecRef();
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::LeaveRead () {
EnterSpinLock(&m_spinLock);
// If this is the last reader, signal waiting threads to try claiming
// the lock again
ASSERT(m_readerCount);
if (!--m_readerCount)
if (m_waitSet) {
m_waitSet->Signal();
m_waitSet = nil;
}
LeaveSpinLock(&m_spinLock);
}
//===========================================================================
void CLock::LeaveWrite () {
EnterSpinLock(&m_spinLock);
// This is the last writer. Signal waiting threads to try claiming the
// lock again.
ASSERT(m_writerCount == 1);
--m_writerCount;
if (m_waitSet) {
m_waitSet->Signal();
m_waitSet = nil;
}
LeaveSpinLock(&m_spinLock);
}
/*****************************************************************************
*
* CEvent
*
***/
//============================================================================
CEvent::CEvent (
ECEventResetBehavior resetType,
bool initialSet
) {
m_handle = CreateEvent(
nil, // security attributes
(resetType == kEventManualReset) ? true : false,
initialSet,
nil // name
);
}
//============================================================================
CEvent::~CEvent () {
(void) CloseHandle(m_handle);
}
//============================================================================
void CEvent::Signal () {
SetEvent(m_handle);
}
//============================================================================
void CEvent::Reset () {
ResetEvent(m_handle);
}
//============================================================================
bool CEvent::Wait (unsigned waitMs) {
ThreadAssertCanBlock(__FILE__, __LINE__);
return WaitForSingleObject(m_handle, waitMs) == WAIT_OBJECT_0;
}
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
long AtomicAdd (long * value, long increment) {
return InterlockedExchangeAdd(value, increment);
}
//===========================================================================
long AtomicSet (long * value, long set) {
return InterlockedExchange(value, set);
}

View File

@ -1,146 +1,146 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Time.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local functions
*
***/
//============================================================================
static void FormatTime (
qword time,
wchar const dateFmt[],
wchar const timeFmt[],
unsigned chars,
wchar * buffer
) {
COMPILER_ASSERT(sizeof(FILETIME) == sizeof(qword));
SYSTEMTIME sysTime;
FileTimeToSystemTime((FILETIME *)&time, &sysTime);
unsigned offset = GetDateFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&sysTime,
dateFmt,
buffer,
chars
);
if (timeFmt) {
// if we printed any characters, move offset back to overwrite the string terminator
if (offset)
--offset;
offset += GetTimeFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&sysTime,
timeFmt,
buffer + offset,
chars - offset
);
}
// if we didn't print any characters, NULL terminate the buffer
if (!offset && chars)
buffer[0] = 0;
}
/*****************************************************************************
*
* Exported functions
*
***/
#ifdef HS_BUILD_FOR_WIN32
//===========================================================================
void TimeGetDesc (
qword time,
TimeDesc * desc
) {
ASSERT(desc);
SYSTEMTIME sysTime;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
FileTimeToSystemTime((FILETIME *) &time, &sysTime);
desc->year = sysTime.wYear;
desc->month = sysTime.wMonth;
desc->day = sysTime.wDay;
desc->dayOfWeek = sysTime.wDayOfWeek;
desc->hour = sysTime.wHour;
desc->minute = sysTime.wMinute;
desc->second = sysTime.wSecond;
}
//============================================================================
qword TimeGetTime () {
qword time;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
GetSystemTimeAsFileTime((FILETIME *) &time);
return time;
}
//============================================================================
qword TimeGetLocalTime () {
qword time;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
GetSystemTimeAsFileTime((FILETIME *) &time);
FileTimeToLocalFileTime((FILETIME *) &time, (FILETIME *) &time);
return time;
}
//============================================================================
void TimePrettyPrint (
qword time,
unsigned chars,
wchar * buffer
) {
FormatTime(
time,
L"ddd MMM dd',' yyyy ",
L"hh':'mm':'ss tt",
chars,
buffer
);
}
#endif // HS_BUILD_FOR_WIN32
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Time.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Local functions
*
***/
//============================================================================
static void FormatTime (
qword time,
wchar const dateFmt[],
wchar const timeFmt[],
unsigned chars,
wchar * buffer
) {
COMPILER_ASSERT(sizeof(FILETIME) == sizeof(qword));
SYSTEMTIME sysTime;
FileTimeToSystemTime((FILETIME *)&time, &sysTime);
unsigned offset = GetDateFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&sysTime,
dateFmt,
buffer,
chars
);
if (timeFmt) {
// if we printed any characters, move offset back to overwrite the string terminator
if (offset)
--offset;
offset += GetTimeFormatW(
LOCALE_SYSTEM_DEFAULT,
0,
&sysTime,
timeFmt,
buffer + offset,
chars - offset
);
}
// if we didn't print any characters, NULL terminate the buffer
if (!offset && chars)
buffer[0] = 0;
}
/*****************************************************************************
*
* Exported functions
*
***/
#ifdef HS_BUILD_FOR_WIN32
//===========================================================================
void TimeGetDesc (
qword time,
TimeDesc * desc
) {
ASSERT(desc);
SYSTEMTIME sysTime;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
FileTimeToSystemTime((FILETIME *) &time, &sysTime);
desc->year = sysTime.wYear;
desc->month = sysTime.wMonth;
desc->day = sysTime.wDay;
desc->dayOfWeek = sysTime.wDayOfWeek;
desc->hour = sysTime.wHour;
desc->minute = sysTime.wMinute;
desc->second = sysTime.wSecond;
}
//============================================================================
qword TimeGetTime () {
qword time;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
GetSystemTimeAsFileTime((FILETIME *) &time);
return time;
}
//============================================================================
qword TimeGetLocalTime () {
qword time;
COMPILER_ASSERT(sizeof(qword) == sizeof(FILETIME));
GetSystemTimeAsFileTime((FILETIME *) &time);
FileTimeToLocalFileTime((FILETIME *) &time, (FILETIME *) &time);
return time;
}
//============================================================================
void TimePrettyPrint (
qword time,
unsigned chars,
wchar * buffer
) {
FormatTime(
time,
L"ddd MMM dd',' yyyy ",
L"hh':'mm':'ss tt",
chars,
buffer
);
}
#endif // HS_BUILD_FOR_WIN32

View File

@ -1,171 +1,171 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Uuid.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#if 0
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(GUID));
void Uuid::Clear()
{
UuidCreateNil( (GUID *)this );
}
int Uuid::CompareTo( const Uuid * v ) const
{
RPC_STATUS s;
return UuidCompare( (GUID *)this, (GUID *)v, &s );
}
bool Uuid::IsEqualTo( const Uuid * v ) const
{
return ( CompareTo( v )==0 );
}
void Uuid::CopyFrom( const Uuid * v )
{
memcpy( (void*)fData, (const void*)v->fData, sizeof(fData) );
}
bool Uuid::IsNull() const
{
RPC_STATUS s;
return 1 == UuidIsNil( (GUID *)this, &s );
}
bool Uuid::FromString( const char * str )
{
Clear();
if ( !str )
return false;
return RPC_S_OK == UuidFromString( (unsigned char *)str, (GUID *)this );
}
bool Uuid::ToString( std::string & out ) const
{
out = "";
unsigned char * ubuf;
RPC_STATUS s;
s = UuidToString( (GUID *) this, &ubuf );
bool success = ( s==RPC_S_OK );
if ( success )
out = (char*)ubuf;
RpcStringFree( &ubuf );
return success;
}
// static
Uuid Uuid::Generate()
{
Uuid result;
UuidCreate( (GUID *)&result );
return result;
}
#endif
#ifdef HS_BUILD_FOR_WIN32
/*****************************************************************************
*
* Exports
*
***/
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(GUID));
//============================================================================
Uuid GuidGenerate () {
Uuid result;
UuidCreate( (GUID *)&result );
return result;
}
//============================================================================
void GuidClear (Uuid * uuid) {
UuidCreateNil((GUID *)uuid);
}
//============================================================================
bool GuidFromString (const wchar str[], Uuid * uuid) {
ASSERT(uuid);
COMPILER_ASSERT(sizeof(wchar) == sizeof(unsigned short));
return RPC_S_OK == UuidFromStringW((unsigned short *) str, (GUID *) uuid);
}
//============================================================================
bool GuidFromString (const char str[], Uuid * uuid) {
ASSERT(uuid);
return RPC_S_OK == UuidFromStringA((unsigned char *) str, (GUID *) uuid);
}
//============================================================================
int GuidCompare (const Uuid & a, const Uuid & b) {
RPC_STATUS s;
return UuidCompare((GUID *)&a, (GUID *)&b, &s);
}
//============================================================================
bool GuidIsNil (const Uuid & uuid) {
RPC_STATUS s;
return 1 == UuidIsNil((GUID *)&uuid, &s );
}
//============================================================================
const wchar * GuidToString (const Uuid & uuid, wchar * dst, unsigned chars) {
wchar * src;
RPC_STATUS s;
s = UuidToStringW( (GUID *) &uuid, (RPC_WSTR*)&src );
if (RPC_S_OK == s)
StrCopy(dst, src, chars);
else
StrCopy(dst, L"", chars);
RpcStringFreeW( (RPC_WSTR *)&src );
return dst;
}
//============================================================================
const char * GuidToString (const Uuid & uuid, char * dst, unsigned chars) {
byte * src;
RPC_STATUS s;
s = UuidToStringA( (GUID *) &uuid, &src );
if (RPC_S_OK == s)
StrCopy(dst, (char *)src, chars);
else
StrCopy(dst, "", chars);
RpcStringFreeA(&src);
return dst;
}
#endif // HS_BUILD_FOR_WIN32
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/Win32/pnUtW32Uuid.cpp
*
***/
#include "../../Pch.h"
#pragma hdrstop
#if 0
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(GUID));
void Uuid::Clear()
{
UuidCreateNil( (GUID *)this );
}
int Uuid::CompareTo( const Uuid * v ) const
{
RPC_STATUS s;
return UuidCompare( (GUID *)this, (GUID *)v, &s );
}
bool Uuid::IsEqualTo( const Uuid * v ) const
{
return ( CompareTo( v )==0 );
}
void Uuid::CopyFrom( const Uuid * v )
{
memcpy( (void*)fData, (const void*)v->fData, sizeof(fData) );
}
bool Uuid::IsNull() const
{
RPC_STATUS s;
return 1 == UuidIsNil( (GUID *)this, &s );
}
bool Uuid::FromString( const char * str )
{
Clear();
if ( !str )
return false;
return RPC_S_OK == UuidFromString( (unsigned char *)str, (GUID *)this );
}
bool Uuid::ToString( std::string & out ) const
{
out = "";
unsigned char * ubuf;
RPC_STATUS s;
s = UuidToString( (GUID *) this, &ubuf );
bool success = ( s==RPC_S_OK );
if ( success )
out = (char*)ubuf;
RpcStringFree( &ubuf );
return success;
}
// static
Uuid Uuid::Generate()
{
Uuid result;
UuidCreate( (GUID *)&result );
return result;
}
#endif
#ifdef HS_BUILD_FOR_WIN32
/*****************************************************************************
*
* Exports
*
***/
COMPILER_ASSERT(sizeof(Uuid) >= sizeof(GUID));
//============================================================================
Uuid GuidGenerate () {
Uuid result;
UuidCreate( (GUID *)&result );
return result;
}
//============================================================================
void GuidClear (Uuid * uuid) {
UuidCreateNil((GUID *)uuid);
}
//============================================================================
bool GuidFromString (const wchar str[], Uuid * uuid) {
ASSERT(uuid);
COMPILER_ASSERT(sizeof(wchar) == sizeof(unsigned short));
return RPC_S_OK == UuidFromStringW((unsigned short *) str, (GUID *) uuid);
}
//============================================================================
bool GuidFromString (const char str[], Uuid * uuid) {
ASSERT(uuid);
return RPC_S_OK == UuidFromStringA((unsigned char *) str, (GUID *) uuid);
}
//============================================================================
int GuidCompare (const Uuid & a, const Uuid & b) {
RPC_STATUS s;
return UuidCompare((GUID *)&a, (GUID *)&b, &s);
}
//============================================================================
bool GuidIsNil (const Uuid & uuid) {
RPC_STATUS s;
return 1 == UuidIsNil((GUID *)&uuid, &s );
}
//============================================================================
const wchar * GuidToString (const Uuid & uuid, wchar * dst, unsigned chars) {
wchar * src;
RPC_STATUS s;
s = UuidToStringW( (GUID *) &uuid, (RPC_WSTR*)&src );
if (RPC_S_OK == s)
StrCopy(dst, src, chars);
else
StrCopy(dst, L"", chars);
RpcStringFreeW( (RPC_WSTR *)&src );
return dst;
}
//============================================================================
const char * GuidToString (const Uuid & uuid, char * dst, unsigned chars) {
byte * src;
RPC_STATUS s;
s = UuidToStringA( (GUID *) &uuid, &src );
if (RPC_S_OK == s)
StrCopy(dst, (char *)src, chars);
else
StrCopy(dst, "", chars);
RpcStringFreeA(&src);
return dst;
}
#endif // HS_BUILD_FOR_WIN32

View File

@ -1,80 +1,80 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* CNetAddressHash
*
***/
//============================================================================
CNetAddressHash::CNetAddressHash (
const NetAddress & addr
) : m_addr(addr)
, m_equals(nil)
{ }
//============================================================================
CNetAddressHash::CNetAddressHash (
const NetAddress & addr,
FNetAddressEqualityProc equals
) : m_addr(addr)
, m_equals(equals)
{ }
//============================================================================
bool CNetAddressHash::operator== (const CNetAddressHash & rhs) const {
ASSERT(m_equals);
return m_equals(m_addr, rhs.m_addr);
}
//============================================================================
unsigned CNetAddressHash::GetHash () const {
return NetAddressHash(m_addr);
}
//============================================================================
const NetAddress & CNetAddressHash::GetAddr () const {
return m_addr;
}
/*****************************************************************************
*
* Exported data
*
***/
NetAddress kNilNetAddress;
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* CNetAddressHash
*
***/
//============================================================================
CNetAddressHash::CNetAddressHash (
const NetAddress & addr
) : m_addr(addr)
, m_equals(nil)
{ }
//============================================================================
CNetAddressHash::CNetAddressHash (
const NetAddress & addr,
FNetAddressEqualityProc equals
) : m_addr(addr)
, m_equals(equals)
{ }
//============================================================================
bool CNetAddressHash::operator== (const CNetAddressHash & rhs) const {
ASSERT(m_equals);
return m_equals(m_addr, rhs.m_addr);
}
//============================================================================
unsigned CNetAddressHash::GetHash () const {
return NetAddressHash(m_addr);
}
//============================================================================
const NetAddress & CNetAddressHash::GetAddr () const {
return m_addr;
}
/*****************************************************************************
*
* Exported data
*
***/
NetAddress kNilNetAddress;

View File

@ -1,154 +1,154 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTADDR_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTADDR_H
/*****************************************************************************
*
* Types and constants
*
***/
struct NetAddress {
byte data[24];
};
typedef unsigned NetAddressNode;
extern NetAddress kNilNetAddress;
typedef bool (*FNetAddressEqualityProc)(
const NetAddress & a1,
const NetAddress & a2
);
class CNetAddressHash {
NetAddress m_addr;
FNetAddressEqualityProc m_equals;
public:
CNetAddressHash (
const NetAddress & addr
);
CNetAddressHash (
const NetAddress & addr,
FNetAddressEqualityProc equals
// Useful values for 'equals':
// NetAddressEqual --> address node and port numbers match
// NetAddressSameSystem --> address node numbers match
);
void operator= (const CNetAddressHash & rhs) const; // not impl.
bool operator== (const CNetAddressHash & rhs) const;
unsigned GetHash () const;
const NetAddress & GetAddr () const;
};
/*****************************************************************************
*
* Functions
*
***/
enum ENetAddressFormat {
kNetAddressFormatNodeNumber,
kNetAddressFormatAll,
kNumNetAddressFormats
};
unsigned NetAddressHash (const NetAddress & addr);
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2);
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2);
inline bool NetAddressEqual (const NetAddress & a1, const NetAddress & a2) {
return NetAddressCompare(a1, a2) == 0;
}
void NetAddressToString (
const NetAddress & addr,
wchar * str,
unsigned chars,
ENetAddressFormat format
);
// 'str' must be in the form of a dotted IP address (IPv4 or IPv6)
// - names which require DNS lookup will cause the function to return false
bool NetAddressFromString (
NetAddress * addr,
const wchar str[],
unsigned defaultPort
);
unsigned NetAddressGetPort (
const NetAddress & addr
);
void NetAddressSetPort (
unsigned port,
NetAddress * addr
);
void NetAddressNodeToString (
NetAddressNode node,
wchar * str,
unsigned chars
);
NetAddressNode NetAddressNodeFromString (
const wchar string[],
const wchar * endPtr[]
);
NetAddressNode NetAddressGetNode (
const NetAddress & addr
);
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
);
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
);
// Returns number of addresses set, which is guaranteed to be non-zero.
// Furthermore, it sorts the addresses so that loopback and NAT addresses
// are at the end of the array, and "real" addresses are at the beginning.
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTADDR_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAddr.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTADDR_H
/*****************************************************************************
*
* Types and constants
*
***/
struct NetAddress {
byte data[24];
};
typedef unsigned NetAddressNode;
extern NetAddress kNilNetAddress;
typedef bool (*FNetAddressEqualityProc)(
const NetAddress & a1,
const NetAddress & a2
);
class CNetAddressHash {
NetAddress m_addr;
FNetAddressEqualityProc m_equals;
public:
CNetAddressHash (
const NetAddress & addr
);
CNetAddressHash (
const NetAddress & addr,
FNetAddressEqualityProc equals
// Useful values for 'equals':
// NetAddressEqual --> address node and port numbers match
// NetAddressSameSystem --> address node numbers match
);
void operator= (const CNetAddressHash & rhs) const; // not impl.
bool operator== (const CNetAddressHash & rhs) const;
unsigned GetHash () const;
const NetAddress & GetAddr () const;
};
/*****************************************************************************
*
* Functions
*
***/
enum ENetAddressFormat {
kNetAddressFormatNodeNumber,
kNetAddressFormatAll,
kNumNetAddressFormats
};
unsigned NetAddressHash (const NetAddress & addr);
int NetAddressCompare (const NetAddress & a1, const NetAddress & a2);
bool NetAddressSameSystem (const NetAddress & a1, const NetAddress & a2);
inline bool NetAddressEqual (const NetAddress & a1, const NetAddress & a2) {
return NetAddressCompare(a1, a2) == 0;
}
void NetAddressToString (
const NetAddress & addr,
wchar * str,
unsigned chars,
ENetAddressFormat format
);
// 'str' must be in the form of a dotted IP address (IPv4 or IPv6)
// - names which require DNS lookup will cause the function to return false
bool NetAddressFromString (
NetAddress * addr,
const wchar str[],
unsigned defaultPort
);
unsigned NetAddressGetPort (
const NetAddress & addr
);
void NetAddressSetPort (
unsigned port,
NetAddress * addr
);
void NetAddressNodeToString (
NetAddressNode node,
wchar * str,
unsigned chars
);
NetAddressNode NetAddressNodeFromString (
const wchar string[],
const wchar * endPtr[]
);
NetAddressNode NetAddressGetNode (
const NetAddress & addr
);
void NetAddressFromNode (
NetAddressNode node,
unsigned port,
NetAddress * addr
);
void NetAddressGetLoopback (
unsigned port,
NetAddress * addr
);
// Returns number of addresses set, which is guaranteed to be non-zero.
// Furthermore, it sorts the addresses so that loopback and NAT addresses
// are at the end of the array, and "real" addresses are at the beginning.
unsigned NetAddressGetLocal (
unsigned count,
NetAddressNode addresses[]
);

View File

@ -1,63 +1,63 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAllIncludes.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H
#include "pnUtCoreLib.h" // must be first in list
#include "pnUtPragma.h"
#include "pnUtAddr.h"
#include "pnUtUuid.h"
#include "pnUtMath.h"
#include "pnUtSort.h"
#include "pnUtArray.h"
#include "pnUtList.h"
#include "pnUtHash.h"
#include "pnUtPriQ.h"
#include "pnUtSync.h"
#include "pnUtTime.h"
#include "pnUtTls.h"
#include "pnUtStr.h"
#include "pnUtRef.h"
#include "pnUtPath.h"
#include "pnUtBigNum.h"
#include "pnUtCmd.h"
#include "pnUtMisc.h"
#include "pnUtCrypt.h"
#include "pnUtEndian.h"
#include "pnUtSpareList.h"
#include "pnUtSubst.h"
#include "pnUtRand.h"
#include "pnUtBase64.h"
#include "pnUtSkipList.h"
#endif // PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtAllIncludes.h
*
***/
#ifndef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H
#include "pnUtCoreLib.h" // must be first in list
#include "pnUtPragma.h"
#include "pnUtAddr.h"
#include "pnUtUuid.h"
#include "pnUtMath.h"
#include "pnUtSort.h"
#include "pnUtArray.h"
#include "pnUtList.h"
#include "pnUtHash.h"
#include "pnUtPriQ.h"
#include "pnUtSync.h"
#include "pnUtTime.h"
#include "pnUtTls.h"
#include "pnUtStr.h"
#include "pnUtRef.h"
#include "pnUtPath.h"
#include "pnUtBigNum.h"
#include "pnUtCmd.h"
#include "pnUtMisc.h"
#include "pnUtCrypt.h"
#include "pnUtEndian.h"
#include "pnUtSpareList.h"
#include "pnUtSubst.h"
#include "pnUtRand.h"
#include "pnUtBase64.h"
#include "pnUtSkipList.h"
#endif // PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTALLINCLUDES_H

View File

@ -1,85 +1,85 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtArray.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* CBaseArray
*
***/
//===========================================================================
unsigned CBaseArray::CalcAllocGrowth (unsigned newAlloc, unsigned oldAlloc, unsigned * chunkSize) {
// If this is the initial allocation, or if the new allocation is more
// than twice as big as the old allocation and larger than the chunk
// size, then allocate exactly the amount of memory requested
if (!oldAlloc || (newAlloc >= max(2 * oldAlloc, *chunkSize)))
return newAlloc;
// Otherwise, allocate memory beyond what was requested in preparation
// for future requests, so that we can reduce the time spent performing
// memory management
// For small allocations, double the size of the buffer each time
if (newAlloc < *chunkSize)
return max(newAlloc, 2 * oldAlloc);
// For larger allocations, grow by the chunk size each time
if (oldAlloc + *chunkSize > newAlloc) {
// If the application appears to be growing the array a chunk size
// at a time and has allocated at least 16 chunks, double the chunk
// size
if (newAlloc >= 16 * *chunkSize)
*chunkSize *= 2;
return oldAlloc + *chunkSize;
}
unsigned remainder = newAlloc % *chunkSize;
if (remainder)
return newAlloc + *chunkSize - remainder;
else
return newAlloc;
}
//===========================================================================
void * CBaseArray::ReallocPtr (void * ptr, unsigned bytes) {
void * newPtr = nil;
if (bytes) {
newPtr = ALLOCFLAGS(bytes, ARR_MEMORY_FLAGS);
}
return newPtr;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtArray.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* CBaseArray
*
***/
//===========================================================================
unsigned CBaseArray::CalcAllocGrowth (unsigned newAlloc, unsigned oldAlloc, unsigned * chunkSize) {
// If this is the initial allocation, or if the new allocation is more
// than twice as big as the old allocation and larger than the chunk
// size, then allocate exactly the amount of memory requested
if (!oldAlloc || (newAlloc >= max(2 * oldAlloc, *chunkSize)))
return newAlloc;
// Otherwise, allocate memory beyond what was requested in preparation
// for future requests, so that we can reduce the time spent performing
// memory management
// For small allocations, double the size of the buffer each time
if (newAlloc < *chunkSize)
return max(newAlloc, 2 * oldAlloc);
// For larger allocations, grow by the chunk size each time
if (oldAlloc + *chunkSize > newAlloc) {
// If the application appears to be growing the array a chunk size
// at a time and has allocated at least 16 chunks, double the chunk
// size
if (newAlloc >= 16 * *chunkSize)
*chunkSize *= 2;
return oldAlloc + *chunkSize;
}
unsigned remainder = newAlloc % *chunkSize;
if (remainder)
return newAlloc + *chunkSize - remainder;
else
return newAlloc;
}
//===========================================================================
void * CBaseArray::ReallocPtr (void * ptr, unsigned bytes) {
void * newPtr = nil;
if (bytes) {
newPtr = ALLOCFLAGS(bytes, ARR_MEMORY_FLAGS);
}
return newPtr;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,167 +1,167 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
static const char kEncode64[] = {
// 0000000000111111111122222222223333333333444444444455555555556666
// 0123456789012345678901234567890123456789012345678901234567890123
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
};
// Note that the decode table contains one special entry:
// The '-' character (0x2d) maps to 63 just like '/' (0x2f)
// so that URLs will work with Base64Decode when we implement them.
#define kTerminator 127
#define xx kTerminator
static const char kDecode64[] = {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,62,xx,63,xx,63,
52,53,54,55,56,57,58,59,60,61,xx,xx,xx,xx,xx,xx,
xx, 0, 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,xx,xx,xx,xx,xx,
xx,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,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
};
#undef xx
static const char kFillchar = '=';
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
unsigned Base64Encode (
unsigned srcChars,
const byte srcData[],
unsigned dstChars,
char * dstData
) {
ASSERT(srcData);
ASSERT(dstChars >= Base64EncodeSize(srcChars));
ASSERT(dstData);
const char * dstBase = dstData;
const byte * srcTerm = srcData + srcChars;
for (;;) switch (srcTerm - srcData) {
case 0:
*dstData++ = 0;
return dstData - dstBase;
case 1:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) ];
*dstData++ = kFillchar;
*dstData++ = kFillchar;
*dstData++ = 0;
return dstData - dstBase;
case 2:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) + ((srcData[1] >> 4) & 0x0f) ];
*dstData++ = kEncode64[ ((srcData[1] << 2) & 0x3c) ];
*dstData++ = kFillchar;
*dstData++ = 0;
return dstData - dstBase;
default:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) + ((srcData[1] >> 4) & 0x0f) ];
*dstData++ = kEncode64[ ((srcData[1] << 2) & 0x3c) + ((srcData[2] >> 6) & 0x03) ];
*dstData++ = kEncode64[ (srcData[2] & 0x3f) ];
srcData += 3;
break;
}
}
//============================================================================
unsigned Base64Decode (
unsigned srcChars,
const char srcData[],
unsigned dstChars,
byte * dstData
) {
ASSERT(srcData);
ASSERT(dstChars >= Base64DecodeSize(srcChars));
ASSERT(dstData);
const byte * dstBase = dstData;
const char * srcTerm = srcData + srcChars;
while (srcTerm - srcData >= 4) {
*dstData++ = (byte) (
(kDecode64[srcData[0]] << 2 & 0xfc)
+(kDecode64[srcData[1]] >> 4 & 0x03)
);
if (kDecode64[srcData[2]] == kTerminator)
break;
*dstData++ = (byte) (
(kDecode64[srcData[1]] << 4 & 0xf0)
+(kDecode64[srcData[2]] >> 2 & 0x0f)
);
if (kDecode64[srcData[3]] == kTerminator)
break;
*dstData++ = (byte) (
(kDecode64[srcData[2]] << 6 & 0xc0)
+(kDecode64[srcData[3]])
);
srcData += 4;
}
return dstData - dstBase;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
static const char kEncode64[] = {
// 0000000000111111111122222222223333333333444444444455555555556666
// 0123456789012345678901234567890123456789012345678901234567890123
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
};
// Note that the decode table contains one special entry:
// The '-' character (0x2d) maps to 63 just like '/' (0x2f)
// so that URLs will work with Base64Decode when we implement them.
#define kTerminator 127
#define xx kTerminator
static const char kDecode64[] = {
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,62,xx,63,xx,63,
52,53,54,55,56,57,58,59,60,61,xx,xx,xx,xx,xx,xx,
xx, 0, 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,xx,xx,xx,xx,xx,
xx,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,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,xx,
};
#undef xx
static const char kFillchar = '=';
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
unsigned Base64Encode (
unsigned srcChars,
const byte srcData[],
unsigned dstChars,
char * dstData
) {
ASSERT(srcData);
ASSERT(dstChars >= Base64EncodeSize(srcChars));
ASSERT(dstData);
const char * dstBase = dstData;
const byte * srcTerm = srcData + srcChars;
for (;;) switch (srcTerm - srcData) {
case 0:
*dstData++ = 0;
return dstData - dstBase;
case 1:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) ];
*dstData++ = kFillchar;
*dstData++ = kFillchar;
*dstData++ = 0;
return dstData - dstBase;
case 2:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) + ((srcData[1] >> 4) & 0x0f) ];
*dstData++ = kEncode64[ ((srcData[1] << 2) & 0x3c) ];
*dstData++ = kFillchar;
*dstData++ = 0;
return dstData - dstBase;
default:
*dstData++ = kEncode64[ ((srcData[0] >> 2) & 0x3f) ];
*dstData++ = kEncode64[ ((srcData[0] << 4) & 0x30) + ((srcData[1] >> 4) & 0x0f) ];
*dstData++ = kEncode64[ ((srcData[1] << 2) & 0x3c) + ((srcData[2] >> 6) & 0x03) ];
*dstData++ = kEncode64[ (srcData[2] & 0x3f) ];
srcData += 3;
break;
}
}
//============================================================================
unsigned Base64Decode (
unsigned srcChars,
const char srcData[],
unsigned dstChars,
byte * dstData
) {
ASSERT(srcData);
ASSERT(dstChars >= Base64DecodeSize(srcChars));
ASSERT(dstData);
const byte * dstBase = dstData;
const char * srcTerm = srcData + srcChars;
while (srcTerm - srcData >= 4) {
*dstData++ = (byte) (
(kDecode64[srcData[0]] << 2 & 0xfc)
+(kDecode64[srcData[1]] >> 4 & 0x03)
);
if (kDecode64[srcData[2]] == kTerminator)
break;
*dstData++ = (byte) (
(kDecode64[srcData[1]] << 4 & 0xf0)
+(kDecode64[srcData[2]] >> 2 & 0x0f)
);
if (kDecode64[srcData[3]] == kTerminator)
break;
*dstData++ = (byte) (
(kDecode64[srcData[2]] << 6 & 0xc0)
+(kDecode64[srcData[3]])
);
srcData += 4;
}
return dstData - dstBase;
}

View File

@ -1,66 +1,66 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBASE64_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBASE64_H
/*****************************************************************************
*
* Base64 Codec API
*
***/
const unsigned kBase64EncodeBlock = 4;
const unsigned kBase64EncodeMultiple = 3;
inline unsigned Base64EncodeSize (unsigned srcChars) {
return srcChars * kBase64EncodeBlock / kBase64EncodeMultiple + kBase64EncodeBlock;
}
unsigned Base64Encode (
unsigned srcChars,
const byte srcData[],
unsigned dstChars,
char * dstData
);
inline unsigned Base64DecodeSize (unsigned srcChars) {
return srcChars * kBase64EncodeMultiple / kBase64EncodeBlock + kBase64EncodeMultiple;
}
unsigned Base64Decode (
unsigned srcChars,
const char srcData[],
unsigned dstChars,
byte * dstData
);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBASE64_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBase64.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBASE64_H
/*****************************************************************************
*
* Base64 Codec API
*
***/
const unsigned kBase64EncodeBlock = 4;
const unsigned kBase64EncodeMultiple = 3;
inline unsigned Base64EncodeSize (unsigned srcChars) {
return srcChars * kBase64EncodeBlock / kBase64EncodeMultiple + kBase64EncodeBlock;
}
unsigned Base64Encode (
unsigned srcChars,
const byte srcData[],
unsigned dstChars,
char * dstData
);
inline unsigned Base64DecodeSize (unsigned srcChars) {
return srcChars * kBase64EncodeMultiple / kBase64EncodeBlock + kBase64EncodeMultiple;
}
unsigned Base64Decode (
unsigned srcChars,
const char srcData[],
unsigned dstChars,
byte * dstData
);

File diff suppressed because it is too large Load Diff

View File

@ -1,110 +1,110 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBigNum.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBIGNUM_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBigNum.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBIGNUM_H
/*****************************************************************************
*
* BigNum class
*
***/
class BigNum : private ARRAY(dword) {
public:
typedef dword Val; // must match base array
typedef qword DVal; // must be twice as large as Val
private:
bool m_isTemp;
void DivNormalized (const BigNum & a, const BigNum & b, BigNum * remainder);
void ModNormalized (const BigNum & a, const BigNum & b);
inline static DVal Mul (Val a, Val b);
inline void SetVal (unsigned index, Val value);
inline void SetVal (unsigned index, DVal value, Val * carry);
inline void Trim (unsigned count);
inline BigNum * UseTempAlloc (Val * ptr, unsigned count);
public:
BigNum ();
BigNum (const BigNum & a);
BigNum (unsigned a);
BigNum (unsigned bytes, const void * data);
BigNum (const wchar str[], Val radix);
~BigNum ();
// Constant parameters need not be distinct from the destination or from
// each other
void Add (const BigNum & a, Val b);
void Add (const BigNum & a, const BigNum & b);
int Compare (Val a) const;
int Compare (const BigNum & a) const;
void Div (const BigNum & a, Val b, Val * remainder);
void Div (const BigNum & a, const BigNum & b, BigNum * remainder);
void FromData (unsigned bytes, const void * data);
void FromStr (const wchar str[], Val radix);
void Gcd (const BigNum & a, const BigNum & b);
const void * GetData (unsigned * bytes) const;
unsigned HighBitPos () const;
bool InverseMod (const BigNum & a, const BigNum & b);
bool IsMultiple (Val a) const;
bool IsOdd () const;
bool IsPrime () const;
unsigned LowBitPos () const;
void Mod (const BigNum & a, const BigNum & b);
void Mul (const BigNum & a, Val b);
void Mul (const BigNum & a, const BigNum & b);
void MulMod (const BigNum & a, const BigNum & b, const BigNum & c);
void PowMod (Val a, const BigNum & b, const BigNum & c);
void PowMod (const BigNum & a, const BigNum & b, const BigNum & c);
void Rand (const BigNum & a, BigNum * seed);
void Rand (unsigned bits, BigNum * seed);
void RandPrime (unsigned bits, BigNum * seed);
void Set (const BigNum & a);
void Set (unsigned a);
void SetBits (unsigned setBitsOffset, unsigned setBitsCount);
void SetOne ();
void SetZero ();
void Shl (const BigNum & a, unsigned b);
void Shr (const BigNum & a, unsigned b);
void Square (const BigNum & a);
void Sub (const BigNum & a, Val b);
void Sub (const BigNum & a, const BigNum & b);
void ToStr (BigNum * buffer, Val radix) const;
};
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBigNum.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBIGNUM_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtBigNum.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTBIGNUM_H
/*****************************************************************************
*
* BigNum class
*
***/
class BigNum : private ARRAY(dword) {
public:
typedef dword Val; // must match base array
typedef qword DVal; // must be twice as large as Val
private:
bool m_isTemp;
void DivNormalized (const BigNum & a, const BigNum & b, BigNum * remainder);
void ModNormalized (const BigNum & a, const BigNum & b);
inline static DVal Mul (Val a, Val b);
inline void SetVal (unsigned index, Val value);
inline void SetVal (unsigned index, DVal value, Val * carry);
inline void Trim (unsigned count);
inline BigNum * UseTempAlloc (Val * ptr, unsigned count);
public:
BigNum ();
BigNum (const BigNum & a);
BigNum (unsigned a);
BigNum (unsigned bytes, const void * data);
BigNum (const wchar str[], Val radix);
~BigNum ();
// Constant parameters need not be distinct from the destination or from
// each other
void Add (const BigNum & a, Val b);
void Add (const BigNum & a, const BigNum & b);
int Compare (Val a) const;
int Compare (const BigNum & a) const;
void Div (const BigNum & a, Val b, Val * remainder);
void Div (const BigNum & a, const BigNum & b, BigNum * remainder);
void FromData (unsigned bytes, const void * data);
void FromStr (const wchar str[], Val radix);
void Gcd (const BigNum & a, const BigNum & b);
const void * GetData (unsigned * bytes) const;
unsigned HighBitPos () const;
bool InverseMod (const BigNum & a, const BigNum & b);
bool IsMultiple (Val a) const;
bool IsOdd () const;
bool IsPrime () const;
unsigned LowBitPos () const;
void Mod (const BigNum & a, const BigNum & b);
void Mul (const BigNum & a, Val b);
void Mul (const BigNum & a, const BigNum & b);
void MulMod (const BigNum & a, const BigNum & b, const BigNum & c);
void PowMod (Val a, const BigNum & b, const BigNum & c);
void PowMod (const BigNum & a, const BigNum & b, const BigNum & c);
void Rand (const BigNum & a, BigNum * seed);
void Rand (unsigned bits, BigNum * seed);
void RandPrime (unsigned bits, BigNum * seed);
void Set (const BigNum & a);
void Set (unsigned a);
void SetBits (unsigned setBitsOffset, unsigned setBitsCount);
void SetOne ();
void SetZero ();
void Shl (const BigNum & a, unsigned b);
void Shr (const BigNum & a, unsigned b);
void Square (const BigNum & a);
void Sub (const BigNum & a, Val b);
void Sub (const BigNum & a, const BigNum & b);
void ToStr (BigNum * buffer, Val radix) const;
};

File diff suppressed because it is too large Load Diff

View File

@ -1,128 +1,128 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCmd.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCMD_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCmd.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCMD_H
/*****************************************************************************
*
* Constants
*
***/
// Sets of mutually exclusive flags
const unsigned kCmdArgFlagged = 0x0 << 0; // default
const unsigned kCmdArgOptional = 0x1 << 0;
const unsigned kCmdArgRequired = 0x2 << 0;
const unsigned kCmdMaskArg = 0xf << 0;
const unsigned kCmdTypeBool = 0x0 << 4; // default
const unsigned kCmdTypeInt = 0x1 << 4;
const unsigned kCmdTypeUnsigned = 0x2 << 4;
const unsigned kCmdTypeFloat = 0x3 << 4;
const unsigned kCmdTypeString = 0x4 << 4;
const unsigned kCmdMaskType = 0xf << 4;
const unsigned kCmdBoolSet = 0x0 << 8; // default
const unsigned kCmdBoolUnset = 0x1 << 8;
const unsigned kCmdMaskBool = 0xf << 8;
// Other flags
const unsigned kCmdCaseSensitive = 0x1 << 28;
// Error codes
enum ECmdError {
kCmdErrorInvalidArg,
kCmdErrorInvalidValue,
kCmdErrorTooFewArgs,
kCmdErrorTooManyArgs,
kNumCmdErrors
};
/*****************************************************************************
*
* Types
*
***/
struct CmdArgDef {
unsigned flags;
const wchar * name; // must be compile-time constant
unsigned id;
};
class CCmdParser {
class CICmdParser * fParser;
static void DispatchError (const wchar str[], ECmdError errorCode, const wchar arg[], const wchar value[], void * param);
static bool DispatchExtra (const wchar str[], void * param);
protected:
CCmdParser ();
void Initialize (const CmdArgDef def[], unsigned defCount);
public:
CCmdParser (const CmdArgDef def[], unsigned defCount);
virtual ~CCmdParser ();
bool GetBool (unsigned id) const;
bool GetBool (const wchar name[]) const;
float GetFloat (unsigned id) const;
float GetFloat (const wchar name[]) const;
int GetInt (unsigned id) const;
int GetInt (const wchar name[]) const;
const wchar * GetString (unsigned id) const;
const wchar * GetString (const wchar name[]) const;
unsigned GetUnsigned (unsigned id) const;
unsigned GetUnsigned (const wchar name[]) const;
bool IsSpecified (unsigned id) const;
bool IsSpecified (const wchar name[]) const;
virtual void OnError (const wchar str[], ECmdError errorCode, const wchar arg[], const wchar value[]);
virtual bool OnExtra (const wchar str[]);
bool Parse (const wchar cmdLine[] = nil);
};
class CCmdParserSimple : public CCmdParser {
public:
CCmdParserSimple (
unsigned requiredStringCount,
unsigned optionalStringCount,
const wchar flaggedBoolNames[] // double null terminated if used
);
};
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCmd.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCMD_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCmd.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCMD_H
/*****************************************************************************
*
* Constants
*
***/
// Sets of mutually exclusive flags
const unsigned kCmdArgFlagged = 0x0 << 0; // default
const unsigned kCmdArgOptional = 0x1 << 0;
const unsigned kCmdArgRequired = 0x2 << 0;
const unsigned kCmdMaskArg = 0xf << 0;
const unsigned kCmdTypeBool = 0x0 << 4; // default
const unsigned kCmdTypeInt = 0x1 << 4;
const unsigned kCmdTypeUnsigned = 0x2 << 4;
const unsigned kCmdTypeFloat = 0x3 << 4;
const unsigned kCmdTypeString = 0x4 << 4;
const unsigned kCmdMaskType = 0xf << 4;
const unsigned kCmdBoolSet = 0x0 << 8; // default
const unsigned kCmdBoolUnset = 0x1 << 8;
const unsigned kCmdMaskBool = 0xf << 8;
// Other flags
const unsigned kCmdCaseSensitive = 0x1 << 28;
// Error codes
enum ECmdError {
kCmdErrorInvalidArg,
kCmdErrorInvalidValue,
kCmdErrorTooFewArgs,
kCmdErrorTooManyArgs,
kNumCmdErrors
};
/*****************************************************************************
*
* Types
*
***/
struct CmdArgDef {
unsigned flags;
const wchar * name; // must be compile-time constant
unsigned id;
};
class CCmdParser {
class CICmdParser * fParser;
static void DispatchError (const wchar str[], ECmdError errorCode, const wchar arg[], const wchar value[], void * param);
static bool DispatchExtra (const wchar str[], void * param);
protected:
CCmdParser ();
void Initialize (const CmdArgDef def[], unsigned defCount);
public:
CCmdParser (const CmdArgDef def[], unsigned defCount);
virtual ~CCmdParser ();
bool GetBool (unsigned id) const;
bool GetBool (const wchar name[]) const;
float GetFloat (unsigned id) const;
float GetFloat (const wchar name[]) const;
int GetInt (unsigned id) const;
int GetInt (const wchar name[]) const;
const wchar * GetString (unsigned id) const;
const wchar * GetString (const wchar name[]) const;
unsigned GetUnsigned (unsigned id) const;
unsigned GetUnsigned (const wchar name[]) const;
bool IsSpecified (unsigned id) const;
bool IsSpecified (const wchar name[]) const;
virtual void OnError (const wchar str[], ECmdError errorCode, const wchar arg[], const wchar value[]);
virtual bool OnExtra (const wchar str[]);
bool Parse (const wchar cmdLine[] = nil);
};
class CCmdParserSimple : public CCmdParser {
public:
CCmdParserSimple (
unsigned requiredStringCount,
unsigned optionalStringCount,
const wchar flaggedBoolNames[] // double null terminated if used
);
};

View File

@ -1,44 +1,44 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCoreLib.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCORELIB_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCoreLib.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCORELIB_H
#pragma warning(push, 0)
#include "HeadSpin.h"
#include "hsWindows.h"
#include "hsCritSect.h"
#include "hsStream.h"
#pragma warning(pop)
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCoreLib.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCORELIB_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCoreLib.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCORELIB_H
#pragma warning(push, 0)
#include "HeadSpin.h"
#include "hsWindows.h"
#include "hsCritSect.h"
#include "hsStream.h"
#pragma warning(pop)

File diff suppressed because it is too large Load Diff

View File

@ -1,166 +1,166 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCrypt.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCRYPT_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCrypt.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCRYPT_H
/*****************************************************************************
*
* Types and constants
*
***/
struct CryptKey;
enum ECryptAlgorithm {
kCryptSha,
kCryptSha1,
kCryptMd5,
kCryptRc4,
kCryptRsa,
kNumCryptAlgorithms
};
struct ShaDigest {
dword data[5];
};
/*****************************************************************************
*
* Digest functions
*
***/
void CryptDigest (
ECryptAlgorithm algorithm,
void * dest, // must be sized to the algorithm's digest size
const unsigned sourceBytes,
const void * sourceData
);
void CryptDigest (
ECryptAlgorithm algorithm,
void * dest, // must be sized to the algorithm's digest size
unsigned sourceCount,
const unsigned sourceBytes[], // [sourceCount]
const void * sourcePtrs[] // [sourceCount]
);
/*****************************************************************************
*
* Key generation
*
***/
CryptKey * CryptKeyCreate (
ECryptAlgorithm algorithm,
unsigned bytes,
const void * data
);
void CryptKeyClose (
CryptKey * key
);
void CryptKeyGenerate (
ECryptAlgorithm algorithm,
unsigned keyBits, // used for algorithms with variable key strength
unsigned randomBytes,
const void * randomData,
ARRAY(byte) * privateData,
ARRAY(byte) * publicData // only for public key cryptography
);
unsigned CryptKeyGetBlockSize (
CryptKey * key
);
void CryptCreateRandomSeed (
unsigned bytes,
byte * data
);
void CryptHashPassword (
const wchar username[],
const wchar password[],
ShaDigest * namePassHash
);
void CryptHashPasswordChallenge (
unsigned clientChallenge,
unsigned serverChallenge,
const ShaDigest & namePassHash,
ShaDigest * challengeHash
);
void CryptCreateFastWeakChallenge (
unsigned * challenge,
unsigned val1,
unsigned val2
);
/*****************************************************************************
*
* Encryption and Decryption
*
***/
void CryptEncrypt (
CryptKey * key,
ARRAY(byte) * dest,
unsigned sourceBytes,
const void * sourceData
);
void CryptEncrypt (
CryptKey * key,
unsigned bytes,
void * data
);
void CryptDecrypt (
CryptKey * key,
ARRAY(byte) * dest, // padded out to the algorithm's block size
unsigned sourceBytes,
const void * sourceData
);
void CryptDecrypt (
CryptKey * key,
unsigned bytes,
void * data
);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCrypt.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCRYPT_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtCrypt.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTCRYPT_H
/*****************************************************************************
*
* Types and constants
*
***/
struct CryptKey;
enum ECryptAlgorithm {
kCryptSha,
kCryptSha1,
kCryptMd5,
kCryptRc4,
kCryptRsa,
kNumCryptAlgorithms
};
struct ShaDigest {
dword data[5];
};
/*****************************************************************************
*
* Digest functions
*
***/
void CryptDigest (
ECryptAlgorithm algorithm,
void * dest, // must be sized to the algorithm's digest size
const unsigned sourceBytes,
const void * sourceData
);
void CryptDigest (
ECryptAlgorithm algorithm,
void * dest, // must be sized to the algorithm's digest size
unsigned sourceCount,
const unsigned sourceBytes[], // [sourceCount]
const void * sourcePtrs[] // [sourceCount]
);
/*****************************************************************************
*
* Key generation
*
***/
CryptKey * CryptKeyCreate (
ECryptAlgorithm algorithm,
unsigned bytes,
const void * data
);
void CryptKeyClose (
CryptKey * key
);
void CryptKeyGenerate (
ECryptAlgorithm algorithm,
unsigned keyBits, // used for algorithms with variable key strength
unsigned randomBytes,
const void * randomData,
ARRAY(byte) * privateData,
ARRAY(byte) * publicData // only for public key cryptography
);
unsigned CryptKeyGetBlockSize (
CryptKey * key
);
void CryptCreateRandomSeed (
unsigned bytes,
byte * data
);
void CryptHashPassword (
const wchar username[],
const wchar password[],
ShaDigest * namePassHash
);
void CryptHashPasswordChallenge (
unsigned clientChallenge,
unsigned serverChallenge,
const ShaDigest & namePassHash,
ShaDigest * challengeHash
);
void CryptCreateFastWeakChallenge (
unsigned * challenge,
unsigned val1,
unsigned val2
);
/*****************************************************************************
*
* Encryption and Decryption
*
***/
void CryptEncrypt (
CryptKey * key,
ARRAY(byte) * dest,
unsigned sourceBytes,
const void * sourceData
);
void CryptEncrypt (
CryptKey * key,
unsigned bytes,
void * data
);
void CryptDecrypt (
CryptKey * key,
ARRAY(byte) * dest, // padded out to the algorithm's block size
unsigned sourceBytes,
const void * sourceData
);
void CryptDecrypt (
CryptKey * key,
unsigned bytes,
void * data
);

View File

@ -1,130 +1,130 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtEndian.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Big endian functions
*
***/
#ifdef BIG_ENDIAN
//===========================================================================
void EndianConvert (word * array, unsigned count) {
for (; count--; ++array)
*array = Endian(*array);
}
//===========================================================================
void EndianConvert (dword * array, unsigned count) {
for (; count--; ++array)
*array = Endian(*array);
}
//===========================================================================
void EndianConvert (qword * array, unsigned count) {
for (; count--; ++array)
*array = Endian(*array);
}
//============================================================================
void EndianConvert (byte * data, unsigned elemCount, unsigned elemBytes) {
switch (elemBytes) {
case sizeof(byte):
break;
case sizeof(word):
EndianConvert((word *)data, elemCount);
break;
case sizeof(dword):
EndianConvert((dword *)data, elemCount);
break;
case sizeof(qword):
EndianConvert((qword *)data, elemCount);
break;
DEFAULT_FATAL(elemBytes);
}
}
//===========================================================================
void EndianCopy (unsigned * dst, const word src[], unsigned count) {
for (; count--; ++src, ++dst)
*dst = (unsigned)Endian(*src);
}
//===========================================================================
void EndianCopy (unsigned * dst, const dword src[], unsigned count) {
for (; count--; ++src, ++dst)
*dst = (unsigned)Endian(*src);
}
//===========================================================================
void EndianCopy (unsigned * dst, const qword src[], unsigned count) {
for (; count--; ++src, ++dst)
*dst = (unsigned)Endian(*src);
}
//============================================================================
void EndianCopy (
void * dst,
const byte src[],
unsigned elemCount,
unsigned elemBytes
) {
switch (elemBytes) {
case sizeof(byte):
MemCopy(dst, src, elemCount);
break;
case sizeof(word):
EndianCopy((word *)dst, (const word *)src, elemCount);
break;
case sizeof(dword):
EndianCopy((dword *)dst, (const dword *)src, elemCount);
break;
case sizeof(qword):
EndianCopy((qword *)dst, (const qword *)src, elemCount);
break;
DEFAULT_FATAL(elemBytes);
}
}
#endif // BIG_ENDIAN
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtEndian.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Big endian functions
*
***/
#ifdef BIG_ENDIAN
//===========================================================================
void EndianConvert (word * array, unsigned count) {
for (; count--; ++array)
*array = Endian(*array);
}
//===========================================================================
void EndianConvert (dword * array, unsigned count) {
for (; count--; ++array)
*array = Endian(*array);
}
//===========================================================================
void EndianConvert (qword * array, unsigned count) {
for (; count--; ++array)
*array = Endian(*array);
}
//============================================================================
void EndianConvert (byte * data, unsigned elemCount, unsigned elemBytes) {
switch (elemBytes) {
case sizeof(byte):
break;
case sizeof(word):
EndianConvert((word *)data, elemCount);
break;
case sizeof(dword):
EndianConvert((dword *)data, elemCount);
break;
case sizeof(qword):
EndianConvert((qword *)data, elemCount);
break;
DEFAULT_FATAL(elemBytes);
}
}
//===========================================================================
void EndianCopy (unsigned * dst, const word src[], unsigned count) {
for (; count--; ++src, ++dst)
*dst = (unsigned)Endian(*src);
}
//===========================================================================
void EndianCopy (unsigned * dst, const dword src[], unsigned count) {
for (; count--; ++src, ++dst)
*dst = (unsigned)Endian(*src);
}
//===========================================================================
void EndianCopy (unsigned * dst, const qword src[], unsigned count) {
for (; count--; ++src, ++dst)
*dst = (unsigned)Endian(*src);
}
//============================================================================
void EndianCopy (
void * dst,
const byte src[],
unsigned elemCount,
unsigned elemBytes
) {
switch (elemBytes) {
case sizeof(byte):
MemCopy(dst, src, elemCount);
break;
case sizeof(word):
EndianCopy((word *)dst, (const word *)src, elemCount);
break;
case sizeof(dword):
EndianCopy((dword *)dst, (const dword *)src, elemCount);
break;
case sizeof(qword):
EndianCopy((qword *)dst, (const qword *)src, elemCount);
break;
DEFAULT_FATAL(elemBytes);
}
}
#endif // BIG_ENDIAN

View File

@ -1,189 +1,189 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtEndian.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTENDIAN_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtEndian.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTENDIAN_H
// NOTE: Because we predominantly run on little-endian CPUs, we don't
// convert to "network order" when sending integers across the network
// (tcp uses big-endian regardless of underlying hardware) and instead
// use little-endian as the "native" language of our network messages.
/*****************************************************************************
*
* Types and constants
*
***/
#ifdef _M_IX86
# define LITTLE_ENDIAN 1
#else
# define BIG_ENDIAN 1
// That was a pretty weak check for endian-ness, if it
// failed then we probably need to strengthen it a bit.
# error "Are you sure this is a big-endian CPU?"
#endif
/*****************************************************************************
*
* Little endian functions
*
***/
#ifdef LITTLE_ENDIAN
//============================================================================
inline word Endian (word value) { return value; }
inline dword Endian (dword value) { return value; }
inline qword Endian (qword value) { return value; }
//===========================================================================
inline void EndianConvert (
word * array,
unsigned count
) {
return;
}
//===========================================================================
inline void EndianConvert (
dword * array,
unsigned count
) {
return;
}
//===========================================================================
inline void EndianConvert (
qword * array,
unsigned count
) {
return;
}
//===========================================================================
inline void EndianConvert (
byte * data,
unsigned elemCount,
unsigned elemBytes
) {
return;
}
//===========================================================================
inline void EndianCopy (
word * dst,
const word src[],
unsigned count
) {
MemCopy(dst, src, count * sizeof(word));
}
//===========================================================================
inline void EndianCopy (
dword * dst,
const dword src[],
unsigned count
) {
MemCopy(dst, src, count * sizeof(dword));
}
//===========================================================================
inline void EndianCopy (
qword * dst,
const qword src[],
unsigned count
) {
MemCopy(dst, src, count * sizeof(qword));
}
//===========================================================================
inline void EndianCopy (
void * dst,
const byte src[],
unsigned elemCount,
unsigned elemBytes
) {
MemCopy(dst, src, elemCount * elemBytes);
}
#endif // LITTLE_ENDIAN
/*****************************************************************************
*
* Big endian functions
*
***/
#ifdef BIG_ENDIAN
//===========================================================================
inline word Endian (word value) {
return (value >> 8) | (value << 8);
}
//===========================================================================
inline dword Endian (dword value) {
return ((value) << 24) |
((value & 0x0000ff00) << 8) |
((value & 0x00ff0000) >> 8) |
((value) >> 24);
}
//===========================================================================
inline qword Endian (qword value) {
return ((value) << 56) |
((value & 0x000000000000ff00) << 40) |
((value & 0x0000000000ff0000) << 24) |
((value & 0x00000000ff000000) << 8) |
((value & 0x000000ff00000000) >> 8) |
((value & 0x0000ff0000000000) >> 24) |
((value & 0x00ff000000000000) >> 40) |
((value) >> 56);
}
void EndianConvert (word * array, unsigned count);
void EndianConvert (dword * array, unsigned count);
void EndianConvert (qword * array, unsigned count);
void EndianConvert (byte * data, unsigned elemCount, unsigned elemBytes);
void EndianCopy (word * dst, const word src[], unsigned count);
void EndianCopy (dword * dst, const dword src[], unsigned count);
void EndianCopy (qword * dst, const dword src[], unsigned count);
void EndianCopy (void * dst, const byte src[], unsigned elemCount, unsigned elemBytes);
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtEndian.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTENDIAN_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtEndian.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTENDIAN_H
// NOTE: Because we predominantly run on little-endian CPUs, we don't
// convert to "network order" when sending integers across the network
// (tcp uses big-endian regardless of underlying hardware) and instead
// use little-endian as the "native" language of our network messages.
/*****************************************************************************
*
* Types and constants
*
***/
#ifdef _M_IX86
# define LITTLE_ENDIAN 1
#else
# define BIG_ENDIAN 1
// That was a pretty weak check for endian-ness, if it
// failed then we probably need to strengthen it a bit.
# error "Are you sure this is a big-endian CPU?"
#endif
/*****************************************************************************
*
* Little endian functions
*
***/
#ifdef LITTLE_ENDIAN
//============================================================================
inline word Endian (word value) { return value; }
inline dword Endian (dword value) { return value; }
inline qword Endian (qword value) { return value; }
//===========================================================================
inline void EndianConvert (
word * array,
unsigned count
) {
return;
}
//===========================================================================
inline void EndianConvert (
dword * array,
unsigned count
) {
return;
}
//===========================================================================
inline void EndianConvert (
qword * array,
unsigned count
) {
return;
}
//===========================================================================
inline void EndianConvert (
byte * data,
unsigned elemCount,
unsigned elemBytes
) {
return;
}
//===========================================================================
inline void EndianCopy (
word * dst,
const word src[],
unsigned count
) {
MemCopy(dst, src, count * sizeof(word));
}
//===========================================================================
inline void EndianCopy (
dword * dst,
const dword src[],
unsigned count
) {
MemCopy(dst, src, count * sizeof(dword));
}
//===========================================================================
inline void EndianCopy (
qword * dst,
const qword src[],
unsigned count
) {
MemCopy(dst, src, count * sizeof(qword));
}
//===========================================================================
inline void EndianCopy (
void * dst,
const byte src[],
unsigned elemCount,
unsigned elemBytes
) {
MemCopy(dst, src, elemCount * elemBytes);
}
#endif // LITTLE_ENDIAN
/*****************************************************************************
*
* Big endian functions
*
***/
#ifdef BIG_ENDIAN
//===========================================================================
inline word Endian (word value) {
return (value >> 8) | (value << 8);
}
//===========================================================================
inline dword Endian (dword value) {
return ((value) << 24) |
((value & 0x0000ff00) << 8) |
((value & 0x00ff0000) >> 8) |
((value) >> 24);
}
//===========================================================================
inline qword Endian (qword value) {
return ((value) << 56) |
((value & 0x000000000000ff00) << 40) |
((value & 0x0000000000ff0000) << 24) |
((value & 0x00000000ff000000) << 8) |
((value & 0x000000ff00000000) >> 8) |
((value & 0x0000ff0000000000) >> 24) |
((value & 0x00ff000000000000) >> 40) |
((value) >> 56);
}
void EndianConvert (word * array, unsigned count);
void EndianConvert (dword * array, unsigned count);
void EndianConvert (qword * array, unsigned count);
void EndianConvert (byte * data, unsigned elemCount, unsigned elemBytes);
void EndianCopy (word * dst, const word src[], unsigned count);
void EndianCopy (dword * dst, const dword src[], unsigned count);
void EndianCopy (qword * dst, const dword src[], unsigned count);
void EndianCopy (void * dst, const byte src[], unsigned elemCount, unsigned elemBytes);
#endif

View File

@ -1,78 +1,78 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtHash.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* CHashValue
*
***/
// These random values were generated by the radioactive decay based
// random number generator at www.fourmilab.ch
const dword CHashValue::s_hashTable[] = {
0xe8fd2035, 0xaf1add63, 0x049fb872, 0xcf9bb8eb, 0xc30d2a72, 0x15efaec1, 0xd250c7d9, 0xaf3c60a8,
0x17ae32ff, 0x4089cd9e, 0x91dd6936, 0x093f880d, 0x9608ae8f, 0x452c0e11, 0xb6840ffd, 0x3e36c913,
0x393114fd, 0xa72556b2, 0x7c338fb7, 0x4e445027, 0x2864eace, 0x9b0a17d6, 0x108da74b, 0xf2c479c1,
0x288a43ac, 0x241e8411, 0x12ace782, 0xfb015799, 0x8b4dd597, 0x97199bc0, 0x621f0cce, 0x1658553e,
0x99697839, 0xe3efb551, 0xbc1a2625, 0x54583c22, 0x9693d685, 0x612f910a, 0x080ccee8, 0xd00a43c9,
0x86e6984d, 0x793245cf, 0x5335afa0, 0xdb8734d8, 0xfe5ab506, 0x3aae2ec1, 0x0aac22a3, 0xf3cd2c16,
0x3d3039d1, 0x070b576d, 0x3a624bff, 0x0e185383, 0x78316efa, 0xafbef9ad, 0x556130cc, 0x54813111,
0xc0e59be8, 0x30010241, 0x2cfa9040, 0x5a039832, 0x68a8a31d, 0xac786303, 0xe81b7dea, 0x2e3d7f5a,
0xabb30a5c, 0xab08fef0, 0xf88cdc9d, 0x962d8361, 0x82ae270c, 0xc45a6e9c, 0x506a3f62, 0xed7c8f10,
0x64631545, 0xea26488a, 0xd39f06f7, 0xafa35b6b, 0xdd1f83fb, 0x60b57a99, 0x636373ee, 0x05e82732,
0xb2eaf275, 0x4763208c, 0x49499166, 0x8e436c6a, 0x3a4f831a, 0x57b7c11e, 0xbd751298, 0x6217ffbc,
0x789efe70, 0x91d695cc, 0xa7e9049e, 0x12b74cdb, 0x40a2d8e6, 0x4dd33013, 0x506ec265, 0x81b2a421,
0xdf98bac4, 0x554e33d0, 0x514decf9, 0x4374274c, 0x70b09e64, 0xac951473, 0xd6bb35eb, 0xa65ed4cf,
0x71f724ac, 0x91e8da43, 0xe386dcee, 0x45bc6b20, 0x08ddf47a, 0xadac9571, 0x44d3cddf, 0x535ace85,
0x5ac801cc, 0x89e90941, 0xa0507200, 0xe4b2a9b2, 0x00922b39, 0x2848f374, 0xfbe97b80, 0x77ea2e00,
0x05eea617, 0x2bf0baf7, 0x0c97f929, 0x4d3190c0, 0x31f58de0, 0x7cae5dc4, 0x39f33590, 0x9cd39b3f,
0x98b0bf46, 0x393169f1, 0x9f8271da, 0x0b85462f, 0xb8b81857, 0xed66ce2c, 0x6f97f3bb, 0x87e8c7dd,
0x55741d88, 0x9ccd43b8, 0xe537d98a, 0x64a28550, 0x165ba5bf, 0xe4229568, 0x1af7c624, 0x059b9f7a,
0x38129d4a, 0x73dca9ba, 0xe0185118, 0x48560fdb, 0xb7d0ec6b, 0x1acd6d4b, 0x84ab7a10, 0xcd9bf830,
0x539d6be2, 0xfdcb65f4, 0x183a4dd7, 0xc4425aa4, 0xa3934d5f, 0xf71b8023, 0x30c109f7, 0x512e5128,
0x7decdea5, 0xd3aded88, 0x34288710, 0x0c07a16e, 0xec0299da, 0x1e738f1b, 0xd7b898e1, 0x1b7318fd,
0x3b67392d, 0x60da77b3, 0x614d4804, 0xb854468a, 0x4dbfc9fd, 0x85185833, 0x56095260, 0xb85d0771,
0xbfe579e7, 0x51ca011b, 0xcebd2983, 0x4d56cda1, 0x5ec08b9a, 0x6bf9aa6f, 0x7da1e2c0, 0x4499dd84,
0x95ca5ba3, 0xd0f9e77b, 0x5d099253, 0xbe943272, 0x1a87fe96, 0x29584d77, 0x0344f269, 0x2bdafede,
0x4ababc94, 0x7a06acb7, 0x0a4c1efe, 0x8699f00f, 0x0f74e313, 0x0469ac17, 0x80f17875, 0xa6aecf16,
0x0d772a15, 0x60eb0850, 0xa852be33, 0xe1574793, 0x7847204c, 0x1cea62ac, 0xb5948e41, 0x0e574ae9,
0xdeb24de3, 0xe6472a0b, 0xaaaaf355, 0xa271aeae, 0xf3d5d209, 0x4f8fa676, 0x25ff71c9, 0x3f38d7df,
0x0a8cd458, 0x5c6ad602, 0x06d0c0ec, 0x0d84ac0f, 0xf3cc4a59, 0xd6f04d8c, 0x1b3c3229, 0xc8281f6d,
0x9410dd7c, 0x502519d1, 0x4449a76a, 0x88ba67b6, 0x8f710894, 0x7b63230e, 0xc095db28, 0x155a4ac7,
0x0d418a5d, 0xe2b69e59, 0xeab4ac50, 0x0de06aae, 0x60f272fa, 0x408aefd8, 0x01c3435a, 0x0880c1e3,
0x4f23137b, 0x9dfd6434, 0xd1e25d94, 0xbad4c88a, 0x0746edf9, 0x8103a9aa, 0xc8c73617, 0xe0f2759a,
0x00161c79, 0xd4545360, 0x1763cc5b, 0x296361fa, 0xbc35858d, 0xdaed5e93, 0x0b9d0aed, 0x01c45a64,
};
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtHash.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* CHashValue
*
***/
// These random values were generated by the radioactive decay based
// random number generator at www.fourmilab.ch
const dword CHashValue::s_hashTable[] = {
0xe8fd2035, 0xaf1add63, 0x049fb872, 0xcf9bb8eb, 0xc30d2a72, 0x15efaec1, 0xd250c7d9, 0xaf3c60a8,
0x17ae32ff, 0x4089cd9e, 0x91dd6936, 0x093f880d, 0x9608ae8f, 0x452c0e11, 0xb6840ffd, 0x3e36c913,
0x393114fd, 0xa72556b2, 0x7c338fb7, 0x4e445027, 0x2864eace, 0x9b0a17d6, 0x108da74b, 0xf2c479c1,
0x288a43ac, 0x241e8411, 0x12ace782, 0xfb015799, 0x8b4dd597, 0x97199bc0, 0x621f0cce, 0x1658553e,
0x99697839, 0xe3efb551, 0xbc1a2625, 0x54583c22, 0x9693d685, 0x612f910a, 0x080ccee8, 0xd00a43c9,
0x86e6984d, 0x793245cf, 0x5335afa0, 0xdb8734d8, 0xfe5ab506, 0x3aae2ec1, 0x0aac22a3, 0xf3cd2c16,
0x3d3039d1, 0x070b576d, 0x3a624bff, 0x0e185383, 0x78316efa, 0xafbef9ad, 0x556130cc, 0x54813111,
0xc0e59be8, 0x30010241, 0x2cfa9040, 0x5a039832, 0x68a8a31d, 0xac786303, 0xe81b7dea, 0x2e3d7f5a,
0xabb30a5c, 0xab08fef0, 0xf88cdc9d, 0x962d8361, 0x82ae270c, 0xc45a6e9c, 0x506a3f62, 0xed7c8f10,
0x64631545, 0xea26488a, 0xd39f06f7, 0xafa35b6b, 0xdd1f83fb, 0x60b57a99, 0x636373ee, 0x05e82732,
0xb2eaf275, 0x4763208c, 0x49499166, 0x8e436c6a, 0x3a4f831a, 0x57b7c11e, 0xbd751298, 0x6217ffbc,
0x789efe70, 0x91d695cc, 0xa7e9049e, 0x12b74cdb, 0x40a2d8e6, 0x4dd33013, 0x506ec265, 0x81b2a421,
0xdf98bac4, 0x554e33d0, 0x514decf9, 0x4374274c, 0x70b09e64, 0xac951473, 0xd6bb35eb, 0xa65ed4cf,
0x71f724ac, 0x91e8da43, 0xe386dcee, 0x45bc6b20, 0x08ddf47a, 0xadac9571, 0x44d3cddf, 0x535ace85,
0x5ac801cc, 0x89e90941, 0xa0507200, 0xe4b2a9b2, 0x00922b39, 0x2848f374, 0xfbe97b80, 0x77ea2e00,
0x05eea617, 0x2bf0baf7, 0x0c97f929, 0x4d3190c0, 0x31f58de0, 0x7cae5dc4, 0x39f33590, 0x9cd39b3f,
0x98b0bf46, 0x393169f1, 0x9f8271da, 0x0b85462f, 0xb8b81857, 0xed66ce2c, 0x6f97f3bb, 0x87e8c7dd,
0x55741d88, 0x9ccd43b8, 0xe537d98a, 0x64a28550, 0x165ba5bf, 0xe4229568, 0x1af7c624, 0x059b9f7a,
0x38129d4a, 0x73dca9ba, 0xe0185118, 0x48560fdb, 0xb7d0ec6b, 0x1acd6d4b, 0x84ab7a10, 0xcd9bf830,
0x539d6be2, 0xfdcb65f4, 0x183a4dd7, 0xc4425aa4, 0xa3934d5f, 0xf71b8023, 0x30c109f7, 0x512e5128,
0x7decdea5, 0xd3aded88, 0x34288710, 0x0c07a16e, 0xec0299da, 0x1e738f1b, 0xd7b898e1, 0x1b7318fd,
0x3b67392d, 0x60da77b3, 0x614d4804, 0xb854468a, 0x4dbfc9fd, 0x85185833, 0x56095260, 0xb85d0771,
0xbfe579e7, 0x51ca011b, 0xcebd2983, 0x4d56cda1, 0x5ec08b9a, 0x6bf9aa6f, 0x7da1e2c0, 0x4499dd84,
0x95ca5ba3, 0xd0f9e77b, 0x5d099253, 0xbe943272, 0x1a87fe96, 0x29584d77, 0x0344f269, 0x2bdafede,
0x4ababc94, 0x7a06acb7, 0x0a4c1efe, 0x8699f00f, 0x0f74e313, 0x0469ac17, 0x80f17875, 0xa6aecf16,
0x0d772a15, 0x60eb0850, 0xa852be33, 0xe1574793, 0x7847204c, 0x1cea62ac, 0xb5948e41, 0x0e574ae9,
0xdeb24de3, 0xe6472a0b, 0xaaaaf355, 0xa271aeae, 0xf3d5d209, 0x4f8fa676, 0x25ff71c9, 0x3f38d7df,
0x0a8cd458, 0x5c6ad602, 0x06d0c0ec, 0x0d84ac0f, 0xf3cc4a59, 0xd6f04d8c, 0x1b3c3229, 0xc8281f6d,
0x9410dd7c, 0x502519d1, 0x4449a76a, 0x88ba67b6, 0x8f710894, 0x7b63230e, 0xc095db28, 0x155a4ac7,
0x0d418a5d, 0xe2b69e59, 0xeab4ac50, 0x0de06aae, 0x60f272fa, 0x408aefd8, 0x01c3435a, 0x0880c1e3,
0x4f23137b, 0x9dfd6434, 0xd1e25d94, 0xbad4c88a, 0x0746edf9, 0x8103a9aa, 0xc8c73617, 0xe0f2759a,
0x00161c79, 0xd4545360, 0x1763cc5b, 0x296361fa, 0xbc35858d, 0xdaed5e93, 0x0b9d0aed, 0x01c45a64,
};

File diff suppressed because it is too large Load Diff

View File

@ -1,113 +1,113 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtList.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* CBaseList
*
***/
//===========================================================================
void CBaseList::Link (CBaseList * list, byte * afterNode, byte * beforeNode, ELinkType linkType, byte * existingNode) {
// Verify that the two lists share a common link offset
ASSERT(m_linkOffset != LINK_OFFSET_UNINIT);
ASSERT(m_linkOffset == list->m_linkOffset);
// Verify that the two lists are distinct
CBaseLink * sourceTerminator = &list->m_terminator;
ASSERT(sourceTerminator != &m_terminator);
// Find the first and last nodes to move from the source list
CBaseLink * afterLink = afterNode ? GetLink(afterNode) : sourceTerminator;
CBaseLink * beforeLink = beforeNode ? GetLink(beforeNode) : sourceTerminator;
CBaseLink * firstLink = afterLink->NextLink();
CBaseLink * lastLink = beforeLink->m_prevLink;
if (lastLink == afterLink)
return;
ASSERT(firstLink != beforeLink);
// Store nodes for later use in linking
byte * firstNode = afterLink->m_next;
byte * lastNextNode = lastLink->m_next;
ASSERT(firstNode);
ASSERT(lastNextNode);
// Find the previous and next nodes in the destination list which will
// bound all of the nodes of the source list
CBaseLink * existingLink = existingNode ? GetLink(existingNode) : &m_terminator;
CBaseLink * prevLink, * nextLink;
switch (linkType) {
case kListLinkAfter:
prevLink = existingLink;
nextLink = existingLink->NextLink();
break;
case kListLinkBefore:
prevLink = existingLink->m_prevLink;
nextLink = existingLink;
break;
DEFAULT_FATAL(linkType);
}
// Update the first and last nodes of the moved range to point to the
// previous and next nodes in the destination list
firstLink->m_prevLink = prevLink;
lastLink->m_next = prevLink->m_next;
// Update the previous and next nodes in the destination list to point to
// the first and last nodes of the source range
nextLink->m_prevLink = lastLink;
prevLink->m_next = firstNode;
// Update the before and after links from the source list to point to
// each other
afterLink->m_next = lastNextNode;
beforeLink->m_prevLink = afterLink;
}
//===========================================================================
void CBaseList::UnlinkAll () {
for (CBaseLink * link = m_terminator.m_prevLink, * prev; link != &m_terminator; link = prev) {
prev = link->m_prevLink;
link->InitializeLinksWithOffset(m_linkOffset);
}
m_terminator.InitializeLinksWithOffset(m_linkOffset);
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtList.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* CBaseList
*
***/
//===========================================================================
void CBaseList::Link (CBaseList * list, byte * afterNode, byte * beforeNode, ELinkType linkType, byte * existingNode) {
// Verify that the two lists share a common link offset
ASSERT(m_linkOffset != LINK_OFFSET_UNINIT);
ASSERT(m_linkOffset == list->m_linkOffset);
// Verify that the two lists are distinct
CBaseLink * sourceTerminator = &list->m_terminator;
ASSERT(sourceTerminator != &m_terminator);
// Find the first and last nodes to move from the source list
CBaseLink * afterLink = afterNode ? GetLink(afterNode) : sourceTerminator;
CBaseLink * beforeLink = beforeNode ? GetLink(beforeNode) : sourceTerminator;
CBaseLink * firstLink = afterLink->NextLink();
CBaseLink * lastLink = beforeLink->m_prevLink;
if (lastLink == afterLink)
return;
ASSERT(firstLink != beforeLink);
// Store nodes for later use in linking
byte * firstNode = afterLink->m_next;
byte * lastNextNode = lastLink->m_next;
ASSERT(firstNode);
ASSERT(lastNextNode);
// Find the previous and next nodes in the destination list which will
// bound all of the nodes of the source list
CBaseLink * existingLink = existingNode ? GetLink(existingNode) : &m_terminator;
CBaseLink * prevLink, * nextLink;
switch (linkType) {
case kListLinkAfter:
prevLink = existingLink;
nextLink = existingLink->NextLink();
break;
case kListLinkBefore:
prevLink = existingLink->m_prevLink;
nextLink = existingLink;
break;
DEFAULT_FATAL(linkType);
}
// Update the first and last nodes of the moved range to point to the
// previous and next nodes in the destination list
firstLink->m_prevLink = prevLink;
lastLink->m_next = prevLink->m_next;
// Update the previous and next nodes in the destination list to point to
// the first and last nodes of the source range
nextLink->m_prevLink = lastLink;
prevLink->m_next = firstNode;
// Update the before and after links from the source list to point to
// each other
afterLink->m_next = lastNextNode;
beforeLink->m_prevLink = afterLink;
}
//===========================================================================
void CBaseList::UnlinkAll () {
for (CBaseLink * link = m_terminator.m_prevLink, * prev; link != &m_terminator; link = prev) {
prev = link->m_prevLink;
link->InitializeLinksWithOffset(m_linkOffset);
}
m_terminator.InitializeLinksWithOffset(m_linkOffset);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,81 +1,81 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exported bit manipulation functions
*
***/
//===========================================================================
#ifndef _M_IX86
unsigned MathHighBitPos (dword val) {
ASSERT(val);
double f = (double)val;
return (*((dword *)&f + 1) >> 20) - 1023;
}
#else
__declspec(naked) unsigned __fastcall MathHighBitPos (dword) {
__asm {
bsr eax, ecx
ret 0
};
}
#endif
//===========================================================================
#ifndef _M_IX86
unsigned MathLowBitPos (dword val) {
val &= ~(val - 1); // clear all but the low bit
ASSERT(val);
double f = (double)val;
return (*((dword *)&f + 1) >> 20) - 1023;
}
#else
__declspec(naked) unsigned __fastcall MathLowBitPos (dword) {
__asm {
bsf eax, ecx
ret 0
};
}
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exported bit manipulation functions
*
***/
//===========================================================================
#ifndef _M_IX86
unsigned MathHighBitPos (dword val) {
ASSERT(val);
double f = (double)val;
return (*((dword *)&f + 1) >> 20) - 1023;
}
#else
__declspec(naked) unsigned __fastcall MathHighBitPos (dword) {
__asm {
bsr eax, ecx
ret 0
};
}
#endif
//===========================================================================
#ifndef _M_IX86
unsigned MathLowBitPos (dword val) {
val &= ~(val - 1); // clear all but the low bit
ASSERT(val);
double f = (double)val;
return (*((dword *)&f + 1) >> 20) - 1023;
}
#else
__declspec(naked) unsigned __fastcall MathLowBitPos (dword) {
__asm {
bsf eax, ecx
ret 0
};
}
#endif

View File

@ -1,100 +1,100 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMATH_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMATH_H
/*****************************************************************************
*
* Calling conventions
*
***/
#ifdef _M_IX86
#define MATHCALL __fastcall
#else
#define MATHCALL
#endif
/*****************************************************************************
*
* Bit manipulation functions
*
***/
unsigned MATHCALL MathLowBitPos (dword val);
unsigned MATHCALL MathHighBitPos (dword val);
//===========================================================================
inline unsigned MathBitCount (dword val) {
val = val - ((val >> 1) & 033333333333) - ((val >> 2) & 011111111111);
val = ((val + (val >> 3)) & 030707070707);
val = val + (val >> 6);
val = (val + (val >> 12) + (val >> 24)) & 077;
return val;
}
//===========================================================================
inline unsigned MathBitMaskCreate (unsigned count) {
ASSERT(count <= 8 * sizeof(unsigned));
return count ? ((2 << (count - 1)) - 1) : 0;
}
//===========================================================================
inline dword MathHighBitValue (dword val) {
return val ? 1 << MathHighBitPos(val) : 0;
}
//===========================================================================
inline bool MathIsPow2 (unsigned val) {
return !(val & (val - 1));
}
//===========================================================================
inline unsigned MathLowBitValue (unsigned val) {
return val & ~(val - 1);
}
//===========================================================================
inline unsigned MathNextMultiplePow2 (unsigned val, unsigned multiple) {
ASSERT(multiple);
ASSERT(MathIsPow2(multiple));
return (val + (multiple - 1)) & ~(multiple - 1);
}
//===========================================================================
inline dword MathNextPow2 (dword val) {
return MathIsPow2(val) ? val : 1 << (MathHighBitPos(val) + 1);
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMATH_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMath.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMATH_H
/*****************************************************************************
*
* Calling conventions
*
***/
#ifdef _M_IX86
#define MATHCALL __fastcall
#else
#define MATHCALL
#endif
/*****************************************************************************
*
* Bit manipulation functions
*
***/
unsigned MATHCALL MathLowBitPos (dword val);
unsigned MATHCALL MathHighBitPos (dword val);
//===========================================================================
inline unsigned MathBitCount (dword val) {
val = val - ((val >> 1) & 033333333333) - ((val >> 2) & 011111111111);
val = ((val + (val >> 3)) & 030707070707);
val = val + (val >> 6);
val = (val + (val >> 12) + (val >> 24)) & 077;
return val;
}
//===========================================================================
inline unsigned MathBitMaskCreate (unsigned count) {
ASSERT(count <= 8 * sizeof(unsigned));
return count ? ((2 << (count - 1)) - 1) : 0;
}
//===========================================================================
inline dword MathHighBitValue (dword val) {
return val ? 1 << MathHighBitPos(val) : 0;
}
//===========================================================================
inline bool MathIsPow2 (unsigned val) {
return !(val & (val - 1));
}
//===========================================================================
inline unsigned MathLowBitValue (unsigned val) {
return val & ~(val - 1);
}
//===========================================================================
inline unsigned MathNextMultiplePow2 (unsigned val, unsigned multiple) {
ASSERT(multiple);
ASSERT(MathIsPow2(multiple));
return (val + (multiple - 1)) & ~(multiple - 1);
}
//===========================================================================
inline dword MathNextPow2 (dword val) {
return MathIsPow2(val) ? val : 1 << (MathHighBitPos(val) + 1);
}

View File

@ -1,76 +1,76 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMisc.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private data
*
***/
static void * s_moduleInstance;
/*****************************************************************************
*
* Public functions
*
***/
//============================================================================
void ModuleSetInstance (void * instance) {
s_moduleInstance = instance;
}
//============================================================================
void * ModuleGetInstance () {
return s_moduleInstance;
}
/*****************************************************************************
*
* Dll initialization
*
***/
//============================================================================
#if HS_BUILD_FOR_WIN32
BOOL WINAPI PreDllMain (HANDLE handle, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
ModuleSetInstance(handle);
}
return true;
}
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMisc.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private data
*
***/
static void * s_moduleInstance;
/*****************************************************************************
*
* Public functions
*
***/
//============================================================================
void ModuleSetInstance (void * instance) {
s_moduleInstance = instance;
}
//============================================================================
void * ModuleGetInstance () {
return s_moduleInstance;
}
/*****************************************************************************
*
* Dll initialization
*
***/
//============================================================================
#if HS_BUILD_FOR_WIN32
BOOL WINAPI PreDllMain (HANDLE handle, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
ModuleSetInstance(handle);
}
return true;
}
#endif

View File

@ -1,150 +1,150 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMisc.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMISC_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMisc.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMISC_H
/*****************************************************************************
*
* Constants
*
***/
const wchar UNICODE_BOM = 0xfeff; // Unicode byte-order mark
const char UTF8_BOM[] = "\xef\xbb\xbf";
/*****************************************************************************
*
* Module instance functions
*
***/
void ModuleSetInstance (void * instance);
void * ModuleGetInstance ();
/*****************************************************************************
*
* Command line functions
*
***/
const wchar * AppGetCommandLine ();
/*****************************************************************************
*
* System info functions
*
***/
void MachineGetName (wchar * computerName, unsigned length = 32);
/*****************************************************************************
*
* Misc types
*
***/
// used to dump the internal state of a module
typedef void (__cdecl * FStateDump)(
void * param,
const wchar fmt[],
...
);
/*****************************************************************************
*
* Dll initialization
*
***/
#if HS_BUILD_FOR_WIN32
#define SRV_MODULE_PRE_INIT() \
extern BOOL WINAPI PreDllMain (HANDLE handle, DWORD reason, LPVOID); \
extern "C" BOOL (WINAPI *_pRawDllMain)(HANDLE, DWORD, LPVOID) = PreDllMain
#endif
/*****************************************************************************
*
* System status
*
***/
struct MemoryStatus {
unsigned totalPhysMB; // total physical memory
unsigned availPhysMB; // free physical memory
unsigned totalPageFileMB; // total page file size
unsigned availPageFileMB; // free page file size
unsigned totalVirtualMB; // total virtual address space for calling process
unsigned availVirtualMB; // available virtual address space for calling process
unsigned memoryLoad; // 0..100
};
void MemoryGetStatus (MemoryStatus * status);
struct DiskStatus {
wchar name[16];
unsigned totalSpaceMB;
unsigned freeSpaceMB;
};
void DiskGetStatus (ARRAY(DiskStatus) * disks);
void CpuGetInfo (
word * cpuCaps,
dword * cpuVendor,
word * cpuSignature
);
// CPU capability flags
const unsigned kCpuCap3dNow = 1<<0;
const unsigned kCpuCapCmov = 1<<1; // conditional move
const unsigned kCpuCapEst = 1<<2; // enhanced speed step
const unsigned kCpuCapHtt = 1<<3; // hyperthreading
const unsigned kCpuCapMmx = 1<<4; // multimedia extensions
const unsigned kCpuCapPsn = 1<<5; // processor serial number
const unsigned kCpuCapSse = 1<<6; // streaming SIMD extensions
const unsigned kCpuCapSse2 = 1<<7;
const unsigned kCpuCapSse3 = 1<<8;
const unsigned kCpuCapTsc = 1<<9; // time stamp counter
// Macros for packing and unpacking CPU signature
#define CPU_SIGNATURE(family, model, stepping) ((stepping) | (model << 4) | (family << 8))
#define CPU_SIGNATURE_FAMILY(sig) ((sig >> 8) & 0xf)
#define CPU_SIGNATURE_MODEL(sig) ((sig >> 4) & 0xf)
#define CPU_SIGNATURE_STEPPING(sig) (sig & 0xf)
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMisc.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMISC_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtMisc.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTMISC_H
/*****************************************************************************
*
* Constants
*
***/
const wchar UNICODE_BOM = 0xfeff; // Unicode byte-order mark
const char UTF8_BOM[] = "\xef\xbb\xbf";
/*****************************************************************************
*
* Module instance functions
*
***/
void ModuleSetInstance (void * instance);
void * ModuleGetInstance ();
/*****************************************************************************
*
* Command line functions
*
***/
const wchar * AppGetCommandLine ();
/*****************************************************************************
*
* System info functions
*
***/
void MachineGetName (wchar * computerName, unsigned length = 32);
/*****************************************************************************
*
* Misc types
*
***/
// used to dump the internal state of a module
typedef void (__cdecl * FStateDump)(
void * param,
const wchar fmt[],
...
);
/*****************************************************************************
*
* Dll initialization
*
***/
#if HS_BUILD_FOR_WIN32
#define SRV_MODULE_PRE_INIT() \
extern BOOL WINAPI PreDllMain (HANDLE handle, DWORD reason, LPVOID); \
extern "C" BOOL (WINAPI *_pRawDllMain)(HANDLE, DWORD, LPVOID) = PreDllMain
#endif
/*****************************************************************************
*
* System status
*
***/
struct MemoryStatus {
unsigned totalPhysMB; // total physical memory
unsigned availPhysMB; // free physical memory
unsigned totalPageFileMB; // total page file size
unsigned availPageFileMB; // free page file size
unsigned totalVirtualMB; // total virtual address space for calling process
unsigned availVirtualMB; // available virtual address space for calling process
unsigned memoryLoad; // 0..100
};
void MemoryGetStatus (MemoryStatus * status);
struct DiskStatus {
wchar name[16];
unsigned totalSpaceMB;
unsigned freeSpaceMB;
};
void DiskGetStatus (ARRAY(DiskStatus) * disks);
void CpuGetInfo (
word * cpuCaps,
dword * cpuVendor,
word * cpuSignature
);
// CPU capability flags
const unsigned kCpuCap3dNow = 1<<0;
const unsigned kCpuCapCmov = 1<<1; // conditional move
const unsigned kCpuCapEst = 1<<2; // enhanced speed step
const unsigned kCpuCapHtt = 1<<3; // hyperthreading
const unsigned kCpuCapMmx = 1<<4; // multimedia extensions
const unsigned kCpuCapPsn = 1<<5; // processor serial number
const unsigned kCpuCapSse = 1<<6; // streaming SIMD extensions
const unsigned kCpuCapSse2 = 1<<7;
const unsigned kCpuCapSse3 = 1<<8;
const unsigned kCpuCapTsc = 1<<9; // time stamp counter
// Macros for packing and unpacking CPU signature
#define CPU_SIGNATURE(family, model, stepping) ((stepping) | (model << 4) | (family << 8))
#define CPU_SIGNATURE_FAMILY(sig) ((sig >> 8) & 0xf)
#define CPU_SIGNATURE_MODEL(sig) ((sig >> 4) & 0xf)
#define CPU_SIGNATURE_STEPPING(sig) (sig & 0xf)

View File

@ -1,274 +1,274 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPath.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
void PathGetProgramDirectory (
wchar *dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
PathGetProgramName(dst, dstChars);
PathRemoveFilename(dst, dst, dstChars);
}
//===========================================================================
void PathAddFilename (
wchar *dst,
const wchar src[],
const wchar fname[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
wchar temp[MAX_PATH];
if (dst == src) {
StrCopy(temp, src, arrsize(temp));
src = temp;
}
else if (dst == fname) {
StrCopy(temp, fname, arrsize(temp));
fname = temp;
}
PathMakePath(dst, dstChars, 0, src, fname, 0);
}
//===========================================================================
void PathRemoveFilename (
wchar *dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
PathSplitPath(src, drive, dir, 0, 0);
PathMakePath(dst, dstChars, drive, dir, 0, 0);
}
//===========================================================================
void PathRemoveExtension (
wchar *dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
wchar fname[MAX_FNAME];
PathSplitPath(src, drive, dir, fname, 0);
PathMakePath(dst, dstChars, drive, dir, fname, 0);
}
//===========================================================================
void PathSetExtension (
wchar *dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dst != ext);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
wchar fname[MAX_FNAME];
PathSplitPath(src, drive, dir, fname, 0);
PathMakePath(dst, dstChars, drive, dir, fname, ext);
}
//===========================================================================
void PathAddExtension (
wchar *dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dst != ext);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
wchar fname[MAX_FNAME];
wchar oldext[MAX_EXT];
PathSplitPath(src, drive, dir, fname, oldext);
PathMakePath(
dst,
dstChars,
drive,
dir,
fname,
oldext[0] ? oldext : ext
);
}
//===========================================================================
void PathRemoveDirectory (
wchar *dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
wchar fname[MAX_FNAME];
wchar ext[MAX_EXT];
PathSplitPath(src, 0, 0, fname, ext);
PathMakePath(dst, dstChars, 0, 0, fname, ext);
}
/*****************************************************************************
*
* Email formatting functions
*
***/
//============================================================================
void PathSplitEmail (
const wchar emailAddr[],
wchar * user,
unsigned userChars,
wchar * domain,
unsigned domainChars,
wchar * tld,
unsigned tldChars,
wchar * subDomains,
unsigned subDomainChars,
unsigned subDomainCount
) {
ASSERT(emailAddr);
#define SUB_DOMAIN(i) subDomains[(i) * subDomainChars]
// null-terminate all output parameters
if (userChars) {
ASSERT(user);
user[0] = 0;
}
if (domainChars) {
ASSERT(domain);
domain[0] = 0;
}
if (tldChars) {
ASSERT(tld);
tld[0] = 0;
}
if (subDomainChars || subDomainCount) {
ASSERT(subDomains);
for (unsigned i = 0; i < subDomainCount; ++i)
SUB_DOMAIN(i) = 0;
}
// bail now if email address is zero-length
unsigned len = StrLen(emailAddr);
if (!len)
return;
// copy email address so we can tokenize it
wchar * tmp = ALLOCA(wchar, len + 1);
StrCopy(tmp, emailAddr, len + 1);
const wchar * work = tmp;
// parse user
wchar token[MAX_PATH];
if (!StrTokenize(&work, token, arrsize(token), L"@"))
return;
// copy user to output parameter
if (userChars)
StrCopy(user, token, userChars);
// skip past the '@' symbol
if (!*work++)
return;
// parse all domains
ARRAY(wchar *) arr;
while (StrTokenize(&work, token, arrsize(token), L".")) {
unsigned toklen = StrLen(token);
wchar * str = ALLOCA(wchar, toklen + 1);
StrCopy(str, token, toklen + 1);
arr.Add(str);
}
// copy domains to output parameters
unsigned index = 0;
if (arr.Count() > 2) {
// all domains except for the last two are sub-domains
for (index = 0; index < arr.Count() - 2; ++index) {
if (index < subDomainCount)
if (subDomains)
StrCopy(&SUB_DOMAIN(index), arr[index], subDomainChars);
}
}
if (arr.Count() > 1) {
// second to last domain is the primary domain
if (domain)
StrCopy(domain, arr[index], domainChars);
// last comes the top level domain
++index;
if (tld)
StrCopy(tld, arr[index], tldChars);
}
else if (arr.Count() == 1) {
// if only one domain, return it as a sub-domain
if (index < subDomainCount)
if (subDomains)
StrCopy(&SUB_DOMAIN(index), arr[index], subDomainChars);
}
#undef SUB_DOMAIN
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPath.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
void PathGetProgramDirectory (
wchar *dst,
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
PathGetProgramName(dst, dstChars);
PathRemoveFilename(dst, dst, dstChars);
}
//===========================================================================
void PathAddFilename (
wchar *dst,
const wchar src[],
const wchar fname[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(dstChars);
wchar temp[MAX_PATH];
if (dst == src) {
StrCopy(temp, src, arrsize(temp));
src = temp;
}
else if (dst == fname) {
StrCopy(temp, fname, arrsize(temp));
fname = temp;
}
PathMakePath(dst, dstChars, 0, src, fname, 0);
}
//===========================================================================
void PathRemoveFilename (
wchar *dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
PathSplitPath(src, drive, dir, 0, 0);
PathMakePath(dst, dstChars, drive, dir, 0, 0);
}
//===========================================================================
void PathRemoveExtension (
wchar *dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
wchar fname[MAX_FNAME];
PathSplitPath(src, drive, dir, fname, 0);
PathMakePath(dst, dstChars, drive, dir, fname, 0);
}
//===========================================================================
void PathSetExtension (
wchar *dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dst != ext);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
wchar fname[MAX_FNAME];
PathSplitPath(src, drive, dir, fname, 0);
PathMakePath(dst, dstChars, drive, dir, fname, ext);
}
//===========================================================================
void PathAddExtension (
wchar *dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dst != ext);
ASSERT(dstChars);
wchar drive[MAX_DRIVE];
wchar dir[MAX_DIR];
wchar fname[MAX_FNAME];
wchar oldext[MAX_EXT];
PathSplitPath(src, drive, dir, fname, oldext);
PathMakePath(
dst,
dstChars,
drive,
dir,
fname,
oldext[0] ? oldext : ext
);
}
//===========================================================================
void PathRemoveDirectory (
wchar *dst,
const wchar src[],
unsigned dstChars
) {
ASSERT(dst);
ASSERT(src);
ASSERT(dstChars);
wchar fname[MAX_FNAME];
wchar ext[MAX_EXT];
PathSplitPath(src, 0, 0, fname, ext);
PathMakePath(dst, dstChars, 0, 0, fname, ext);
}
/*****************************************************************************
*
* Email formatting functions
*
***/
//============================================================================
void PathSplitEmail (
const wchar emailAddr[],
wchar * user,
unsigned userChars,
wchar * domain,
unsigned domainChars,
wchar * tld,
unsigned tldChars,
wchar * subDomains,
unsigned subDomainChars,
unsigned subDomainCount
) {
ASSERT(emailAddr);
#define SUB_DOMAIN(i) subDomains[(i) * subDomainChars]
// null-terminate all output parameters
if (userChars) {
ASSERT(user);
user[0] = 0;
}
if (domainChars) {
ASSERT(domain);
domain[0] = 0;
}
if (tldChars) {
ASSERT(tld);
tld[0] = 0;
}
if (subDomainChars || subDomainCount) {
ASSERT(subDomains);
for (unsigned i = 0; i < subDomainCount; ++i)
SUB_DOMAIN(i) = 0;
}
// bail now if email address is zero-length
unsigned len = StrLen(emailAddr);
if (!len)
return;
// copy email address so we can tokenize it
wchar * tmp = ALLOCA(wchar, len + 1);
StrCopy(tmp, emailAddr, len + 1);
const wchar * work = tmp;
// parse user
wchar token[MAX_PATH];
if (!StrTokenize(&work, token, arrsize(token), L"@"))
return;
// copy user to output parameter
if (userChars)
StrCopy(user, token, userChars);
// skip past the '@' symbol
if (!*work++)
return;
// parse all domains
ARRAY(wchar *) arr;
while (StrTokenize(&work, token, arrsize(token), L".")) {
unsigned toklen = StrLen(token);
wchar * str = ALLOCA(wchar, toklen + 1);
StrCopy(str, token, toklen + 1);
arr.Add(str);
}
// copy domains to output parameters
unsigned index = 0;
if (arr.Count() > 2) {
// all domains except for the last two are sub-domains
for (index = 0; index < arr.Count() - 2; ++index) {
if (index < subDomainCount)
if (subDomains)
StrCopy(&SUB_DOMAIN(index), arr[index], subDomainChars);
}
}
if (arr.Count() > 1) {
// second to last domain is the primary domain
if (domain)
StrCopy(domain, arr[index], domainChars);
// last comes the top level domain
++index;
if (tld)
StrCopy(tld, arr[index], tldChars);
}
else if (arr.Count() == 1) {
// if only one domain, return it as a sub-domain
if (index < subDomainCount)
if (subDomains)
StrCopy(&SUB_DOMAIN(index), arr[index], subDomainChars);
}
#undef SUB_DOMAIN
}

View File

@ -1,309 +1,309 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPath.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPATH_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPath.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPATH_H
/*****************************************************************************
*
* Path definitions
*
***/
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
#define MAX_DRIVE 256
#define MAX_DIR 256
#define MAX_FNAME 256
#define MAX_EXT 256
const unsigned kPathFlagFile = 1<<0;
const unsigned kPathFlagDirectory = 1<<1;
const unsigned kPathFlagHidden = 1<<2;
const unsigned kPathFlagSystem = 1<<3;
const unsigned kPathFlagRecurse = 1<<4; // also set if "**" used in filespec
struct PathFind {
unsigned flags;
qword fileLength;
qword lastWriteTime;
wchar name[MAX_PATH];
};
/*****************************************************************************
*
* Path "get" functions
*
***/
void PathFindFiles (
ARRAY(PathFind) * paths,
const wchar fileSpec[],
unsigned pathFlags
);
void PathGetProgramName (
wchar * dst,
unsigned dstChars
);
void PathGetModuleName (
wchar * dst,
unsigned dstChars
);
// this function will use the current directory if <src> is a relative path
// (see PathSetCurrentDirectory/PathGetCurrentDirectory)
bool PathFromString (
wchar * dst,
const wchar src[],
unsigned dstChars
);
bool PathFromString (
wchar * dst,
const wchar src[],
unsigned dstChars,
const wchar baseDir[]
);
bool PathDoesFileExist (
const wchar fileName[]
);
bool PathDoesDirectoryExist (
const wchar directory[]
);
bool PathDeleteFile (
const wchar file[]
);
bool PathMoveFile (
const wchar src[],
const wchar dst[]
);
bool PathCopyFile (
const wchar src[],
const wchar dst[]
);
/*****************************************************************************
*
* Path building functions
*
***/
void PathSplitPath (
const wchar path[],
wchar * drive,
wchar * dir,
wchar * fname,
wchar * ext
);
void PathMakePath (
wchar * path,
unsigned chars,
const wchar drive[],
const wchar dir[],
const wchar fname[],
const wchar ext[]
);
// c:\dir1 + dir2\file.txt => c:\dir1\dir2\file.txt
void PathAddFilename (
wchar * dst,
const wchar src[],
const wchar fname[],
unsigned dstChars
);
// c:\dir1\dir2\file.txt => c:\dir1\dir2\ * note trailing backslash
void PathRemoveFilename (
wchar * dst,
const wchar src[],
unsigned dstChars
);
// c:\file.txt => c:\dir1\dir2\file
void PathRemoveExtension (
wchar * dst,
const wchar src[],
unsigned dstChars
);
// c:\file + .out => c:\file.out
// c:\file. + .out => c:\file.out
// c:\file.txt + .out => c:\file.out
void PathSetExtension (
wchar * dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
);
// c:\file + .out => c:\file.out
// c:\file. + .out => c:\file.
// c:\file.txt + .out => c:\file.txt
void PathAddExtension (
wchar * dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
);
// c:\dir1\dir2\file.txt => file.txt
void PathRemoveDirectory (
wchar * dst,
const wchar src[],
unsigned dstChars
);
// c:\dir1\dir2\file.txt - c:\dir1 => .\dir2\file.txt
// c:\dir1\dir2\file1.txt - c:\dir1\dir4\file2.txt => ..\dir4\file2.txt
bool PathMakeRelative (
wchar * dst,
unsigned fromFlags,
const wchar from[],
unsigned toFlags,
const wchar to[],
unsigned dstChars
);
bool PathIsRelative (
const wchar src[]
);
const wchar * PathFindFilename (const wchar path[]);
inline wchar * PathFindFilename (wchar * path) {
return const_cast<wchar *>(PathFindFilename(const_cast<const wchar *>(path)));
}
const wchar * PathFindExtension (const wchar path[]);
inline wchar * PathFindExtension (wchar * path) {
return const_cast<wchar *>(PathFindExtension(const_cast<const wchar *>(path)));
}
/*****************************************************************************
*
* Directory functions
*
***/
// Create directory
enum EPathCreateDirError {
kPathCreateDirSuccess,
kPathCreateDirErrInvalidPath,
kPathCreateDirErrAccessDenied,
kPathCreateDirErrFileWithSameName,
kPathCreateDirErrDirExists, // Directory exists and kPathCreateDirFlagCreateNew was specified
};
// Setting this flag causes the function to create the entire directory
// tree from top to bottom. Clearing this flag causes the function to
// create only the last entry in the path.
const unsigned kPathCreateDirFlagEntireTree = 1<<0;
// Setting this flag causes the function to create the last entry in the path
// ONLY if it doesn't already exist. If it does exist the function will return
// kPathCreateDirErrDirExistes.
const unsigned kPathCreateDirFlagCreateNew = 1<<1;
EPathCreateDirError PathCreateDirectory (
const wchar path[],
unsigned flags
);
void PathDeleteDirectory (
const wchar path[],
unsigned flags
);
// Set directory
bool PathSetCurrentDirectory (const wchar path[]);
void PathSetProgramDirectory ();
// Get directory
void PathGetProgramDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetCurrentDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetTempDirectory (
wchar * dst,
unsigned dstChars
);
// Product and user-specific common directory locations
void PathGetUserDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetLogDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetInitDirectory (
wchar * dst,
unsigned dstChars
);
/*****************************************************************************
*
* Email formatting functions
*
***/
// you may send nil for any fields you don't care about
void PathSplitEmail (
const wchar emailAddr[],
wchar * user,
unsigned userChars,
wchar * domain,
unsigned domainChars,
wchar * tld,
unsigned tldChars,
wchar * subDomains, // (wchar *)&subs --> wchar subs[16][256];
unsigned subDomainChars, // arrsize(subs[0]) --> 256
unsigned subDomainCount // arrsize(subs) --> 16
);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPath.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPATH_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPath.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPATH_H
/*****************************************************************************
*
* Path definitions
*
***/
#ifndef MAX_PATH
#define MAX_PATH 260
#endif
#define MAX_DRIVE 256
#define MAX_DIR 256
#define MAX_FNAME 256
#define MAX_EXT 256
const unsigned kPathFlagFile = 1<<0;
const unsigned kPathFlagDirectory = 1<<1;
const unsigned kPathFlagHidden = 1<<2;
const unsigned kPathFlagSystem = 1<<3;
const unsigned kPathFlagRecurse = 1<<4; // also set if "**" used in filespec
struct PathFind {
unsigned flags;
qword fileLength;
qword lastWriteTime;
wchar name[MAX_PATH];
};
/*****************************************************************************
*
* Path "get" functions
*
***/
void PathFindFiles (
ARRAY(PathFind) * paths,
const wchar fileSpec[],
unsigned pathFlags
);
void PathGetProgramName (
wchar * dst,
unsigned dstChars
);
void PathGetModuleName (
wchar * dst,
unsigned dstChars
);
// this function will use the current directory if <src> is a relative path
// (see PathSetCurrentDirectory/PathGetCurrentDirectory)
bool PathFromString (
wchar * dst,
const wchar src[],
unsigned dstChars
);
bool PathFromString (
wchar * dst,
const wchar src[],
unsigned dstChars,
const wchar baseDir[]
);
bool PathDoesFileExist (
const wchar fileName[]
);
bool PathDoesDirectoryExist (
const wchar directory[]
);
bool PathDeleteFile (
const wchar file[]
);
bool PathMoveFile (
const wchar src[],
const wchar dst[]
);
bool PathCopyFile (
const wchar src[],
const wchar dst[]
);
/*****************************************************************************
*
* Path building functions
*
***/
void PathSplitPath (
const wchar path[],
wchar * drive,
wchar * dir,
wchar * fname,
wchar * ext
);
void PathMakePath (
wchar * path,
unsigned chars,
const wchar drive[],
const wchar dir[],
const wchar fname[],
const wchar ext[]
);
// c:\dir1 + dir2\file.txt => c:\dir1\dir2\file.txt
void PathAddFilename (
wchar * dst,
const wchar src[],
const wchar fname[],
unsigned dstChars
);
// c:\dir1\dir2\file.txt => c:\dir1\dir2\ * note trailing backslash
void PathRemoveFilename (
wchar * dst,
const wchar src[],
unsigned dstChars
);
// c:\file.txt => c:\dir1\dir2\file
void PathRemoveExtension (
wchar * dst,
const wchar src[],
unsigned dstChars
);
// c:\file + .out => c:\file.out
// c:\file. + .out => c:\file.out
// c:\file.txt + .out => c:\file.out
void PathSetExtension (
wchar * dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
);
// c:\file + .out => c:\file.out
// c:\file. + .out => c:\file.
// c:\file.txt + .out => c:\file.txt
void PathAddExtension (
wchar * dst,
const wchar src[],
const wchar ext[],
unsigned dstChars
);
// c:\dir1\dir2\file.txt => file.txt
void PathRemoveDirectory (
wchar * dst,
const wchar src[],
unsigned dstChars
);
// c:\dir1\dir2\file.txt - c:\dir1 => .\dir2\file.txt
// c:\dir1\dir2\file1.txt - c:\dir1\dir4\file2.txt => ..\dir4\file2.txt
bool PathMakeRelative (
wchar * dst,
unsigned fromFlags,
const wchar from[],
unsigned toFlags,
const wchar to[],
unsigned dstChars
);
bool PathIsRelative (
const wchar src[]
);
const wchar * PathFindFilename (const wchar path[]);
inline wchar * PathFindFilename (wchar * path) {
return const_cast<wchar *>(PathFindFilename(const_cast<const wchar *>(path)));
}
const wchar * PathFindExtension (const wchar path[]);
inline wchar * PathFindExtension (wchar * path) {
return const_cast<wchar *>(PathFindExtension(const_cast<const wchar *>(path)));
}
/*****************************************************************************
*
* Directory functions
*
***/
// Create directory
enum EPathCreateDirError {
kPathCreateDirSuccess,
kPathCreateDirErrInvalidPath,
kPathCreateDirErrAccessDenied,
kPathCreateDirErrFileWithSameName,
kPathCreateDirErrDirExists, // Directory exists and kPathCreateDirFlagCreateNew was specified
};
// Setting this flag causes the function to create the entire directory
// tree from top to bottom. Clearing this flag causes the function to
// create only the last entry in the path.
const unsigned kPathCreateDirFlagEntireTree = 1<<0;
// Setting this flag causes the function to create the last entry in the path
// ONLY if it doesn't already exist. If it does exist the function will return
// kPathCreateDirErrDirExistes.
const unsigned kPathCreateDirFlagCreateNew = 1<<1;
EPathCreateDirError PathCreateDirectory (
const wchar path[],
unsigned flags
);
void PathDeleteDirectory (
const wchar path[],
unsigned flags
);
// Set directory
bool PathSetCurrentDirectory (const wchar path[]);
void PathSetProgramDirectory ();
// Get directory
void PathGetProgramDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetCurrentDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetTempDirectory (
wchar * dst,
unsigned dstChars
);
// Product and user-specific common directory locations
void PathGetUserDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetLogDirectory (
wchar * dst,
unsigned dstChars
);
void PathGetInitDirectory (
wchar * dst,
unsigned dstChars
);
/*****************************************************************************
*
* Email formatting functions
*
***/
// you may send nil for any fields you don't care about
void PathSplitEmail (
const wchar emailAddr[],
wchar * user,
unsigned userChars,
wchar * domain,
unsigned domainChars,
wchar * tld,
unsigned tldChars,
wchar * subDomains, // (wchar *)&subs --> wchar subs[16][256];
unsigned subDomainChars, // arrsize(subs[0]) --> 256
unsigned subDomainCount // arrsize(subs) --> 16
);

View File

@ -1,39 +1,39 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPragma.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRAGMA_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPragma.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRAGMA_H
#pragma warning(disable: 4800) // 'type' : forcing value to bool 'true' or 'false' (performance warning)
#pragma warning(disable: 4201) // nonstandard extension used : nameless struct/union
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPragma.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRAGMA_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPragma.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRAGMA_H
#pragma warning(disable: 4800) // 'type' : forcing value to bool 'true' or 'false' (performance warning)
#pragma warning(disable: 4201) // nonstandard extension used : nameless struct/union

View File

@ -1,471 +1,471 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPriQ.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRIQ_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPriQ.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRIQ_H
/****************************************************************************
*
* Macros
*
***/
#define PRIORITY_TIME(class) TPriorityTime< class >
#define PRIORITY_NUMERIC(class,type) TPriorityNumeric< class,type >
#define PRIQ(class,priority) TPriorityQueue< class,priority >
#define PRIQDECL(class,priority,field) TPriorityQueueDecl< class,priority,offsetof(class,field) >
#define PRIQDYN(class,priority) TPriorityQueueDyn< class,priority >
/****************************************************************************
*
* class TPriorityQueue
*
***/
template<class C, class P>
class TBasePriority;
template<class C, class P>
class TPriorityQueue {
public:
TPriorityQueue ();
~TPriorityQueue ();
C * const & operator[] (unsigned index) const;
void Clear ();
unsigned Count () const;
C * Delete (C * object);
C * Dequeue ();
void Enqueue (C * object);
C * const * Ptr () const;
C * Root () const;
C * const * Term () const;
void UnlinkAll ();
public:
// Intentionally unimplemented
TPriorityQueue (TPriorityQueue const &);
TPriorityQueue const & operator= (TPriorityQueue const &);
protected:
void SetLinkOffset (int offset);
private:
unsigned IndexChild (unsigned index) const;
unsigned IndexParent (unsigned index) const;
void Link (unsigned index);
P * Priority (C * object);
P const * Priority (C const * object) const;
void Remove (unsigned index);
void Unlink (unsigned index);
enum { LINK_OFFSET_UNINIT = 0xdddddddd };
int m_linkOffset;
ARRAY(C *) m_array;
friend TBasePriority<C,P>;
};
//===========================================================================
template<class C, class P>
inline C * const & TPriorityQueue<C,P>::operator[] (unsigned index) const {
return m_array[index];
}
//===========================================================================
template<class C, class P>
inline TPriorityQueue<C,P>::TPriorityQueue () :
m_linkOffset(LINK_OFFSET_UNINIT) {
}
//===========================================================================
template<class C, class P>
inline TPriorityQueue<C,P>::~TPriorityQueue () {
UnlinkAll();
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::Clear () {
// Deleting an object could cause other objects in the queue to be deleted
// so we can't make any assumptions about indices or counts of items in the array
while (C * head = Dequeue())
DEL(head);
m_array.Clear();
}
//===========================================================================
template<class C, class P>
inline unsigned TPriorityQueue<C,P>::Count () const {
return m_array.Count();
}
//===========================================================================
template<class C, class P>
C * TPriorityQueue<C,P>::Delete (C * object) {
// get the object's priority queue and position
P * priority = Priority(object);
const TPriorityQueue<C,P> * queue = priority->GetLink();
unsigned index = priority->GetIndex();
// delete the object
DEL(object);
// return the next object in that queue
if (queue && (index < queue->Count()))
return (*queue)[index];
else
return nil;
}
//===========================================================================
template<class C, class P>
C * TPriorityQueue<C,P>::Dequeue () {
if (!m_array.Count())
return nil;
C * value = m_array[0];
Remove(0);
return value;
}
//===========================================================================
template<class C, class P>
void TPriorityQueue<C,P>::Enqueue (C * object) {
P * priority = Priority(object);
// Verify that the object is not already linked into a priority queue.
// The original implementation of this function silently refused to
// enqueue at a new priority if the object was already in this queue.
// Since this behavior requires callers to check whether the object is
// already enqueued, we now simply assert that.
ASSERT(!priority->IsLinked());
unsigned index = m_array.Add(object);
unsigned parent = IndexParent(index);
// shift value toward root
while (index && priority->IsPriorityHigher(*Priority(m_array[parent]))) {
m_array[index] = m_array[parent];
Link(index);
index = parent;
parent = IndexParent(index);
}
// assign and link the new value
m_array[index] = object;
Link(index);
}
//===========================================================================
template<class C, class P>
inline unsigned TPriorityQueue<C,P>::IndexChild (unsigned index) const {
return (index << 1) + 1;
}
//===========================================================================
template<class C, class P>
inline unsigned TPriorityQueue<C,P>::IndexParent (unsigned index) const {
return (index - 1) >> 1;
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::Link (unsigned index) {
Priority(m_array[index])->Link(this, index);
}
//===========================================================================
template<class C, class P>
inline P * TPriorityQueue<C,P>::Priority (C * object) {
ASSERT(m_linkOffset != LINK_OFFSET_UNINIT);
return (P *)((byte *)object + m_linkOffset);
}
//===========================================================================
template<class C, class P>
inline P const * TPriorityQueue<C,P>::Priority (C const * object) const {
ASSERT(m_linkOffset != LINK_OFFSET_UNINIT);
return (P const *)((byte const *)object + m_linkOffset);
}
//===========================================================================
template<class C, class P>
inline C * const * TPriorityQueue<C,P>::Ptr () const {
return m_array.Ptr();
}
//===========================================================================
template<class C, class P>
void TPriorityQueue<C,P>::Remove (unsigned index) {
// reset the priority link fields
Unlink(index);
// save the terminal leaf node
C * value = m_array.Pop();
P * priority = Priority(value);
const unsigned count = m_array.Count();
if (count == index)
return;
// rebalance upwards from the position of the deleted entry
unsigned parent;
unsigned entry = index;
if (entry && priority->IsPriorityHigher(*Priority(m_array[parent = IndexParent(entry)]))) {
do {
m_array[entry] = m_array[parent];
Link(entry);
entry = parent;
} while (entry && priority->IsPriorityHigher(*Priority(m_array[parent = IndexParent(entry)])));
m_array[entry] = value;
Link(entry);
entry = index;
value = m_array[index];
priority = Priority(value);
}
// rebalance downwards from the position of the deleted entry
for (;;) {
unsigned child = IndexChild(entry);
if (child >= count)
break;
unsigned sibling = child + 1;
if ( (sibling < count) &&
(Priority(m_array[sibling])->IsPriorityHigher(*Priority(m_array[child]))) )
child = sibling;
if (priority->IsPriorityHigher(*Priority(m_array[child])))
break;
m_array[entry] = m_array[child];
Link(entry);
entry = child;
}
m_array[entry] = value;
Link(entry);
}
//===========================================================================
template<class C, class P>
inline C * TPriorityQueue<C,P>::Root () const {
return m_array.Count() ? m_array[0] : nil;
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::SetLinkOffset (int offset) {
ASSERT(m_linkOffset == LINK_OFFSET_UNINIT);
m_linkOffset = offset;
}
//===========================================================================
template<class C, class P>
inline C * const * TPriorityQueue<C,P>::Term () const {
return m_array.Term();
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::Unlink (unsigned index) {
Priority(m_array[index])->Link(nil, 0);
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::UnlinkAll () {
for (unsigned loop = m_array.Count(); loop--; )
Unlink(loop);
m_array.ZeroCount();
}
/****************************************************************************
*
* TPriorityQueueDecl
*
***/
template<class C, class P, int linkOffset>
class TPriorityQueueDecl : public TPriorityQueue<C,P> {
public:
TPriorityQueueDecl () { SetLinkOffset(linkOffset); }
};
/****************************************************************************
*
* TPriorityQueueDyn
*
***/
template<class C, class P>
class TPriorityQueueDyn : public TPriorityQueue<C,P> {
public:
void Initialize (int linkOffset) { SetLinkOffset(linkOffset); }
};
/****************************************************************************
*
* class TBasePriority
*
***/
template<class C, class P>
class TBasePriority {
public:
TBasePriority () : m_queue(nil), m_index(0) { }
virtual ~TBasePriority () { Unlink(); }
void Unlink () { if (m_queue) m_queue->Remove(m_index); }
bool IsLinked () const { return m_queue != nil; }
public:
TBasePriority (const TBasePriority &);
const TBasePriority & operator= (const TBasePriority &);
protected:
void Relink ();
private:
void Link (TPriorityQueue<C,P> * queue, unsigned index);
const TPriorityQueue<C,P> * GetLink () const { return m_queue; }
unsigned GetIndex () const { return m_index; }
private:
TPriorityQueue<C,P> * m_queue;
unsigned m_index;
friend TPriorityQueue<C,P>;
};
//===========================================================================
template<class C, class P>
inline void TBasePriority<C,P>::Link (TPriorityQueue<C,P> * queue, unsigned index) {
m_queue = queue;
m_index = index;
}
//===========================================================================
template<class C, class P>
void TBasePriority<C,P>::Relink () {
// cache m_queue, since m_queue->Remove() will set it to nil
TPriorityQueue<C,P> * queue = m_queue;
if (!queue)
return;
C * object = (*queue)[m_index];
queue->Remove(m_index);
queue->Enqueue(object);
}
/****************************************************************************
*
* class TPriorityNumeric
*
***/
template<class C,class T>
class TPriorityNumeric : public TBasePriority< C, TPriorityNumeric<C,T> > {
public:
TPriorityNumeric () : m_value(0) { }
TPriorityNumeric (T value) : m_value(value) { }
void Set (T value) {
if (value == m_value)
return;
m_value = value;
Relink();
}
T Get () const {
return m_value;
}
bool IsPriorityHigher (const TPriorityNumeric<C,T> & source) {
return m_value > source.m_value;
}
bool IsPriorityHigher (T value) const {
return m_value > value;
}
private:
T m_value;
};
/****************************************************************************
*
* class TPriorityTime
*
***/
template<class C>
class TPriorityTime : public TBasePriority< C, TPriorityTime<C> > {
public:
TPriorityTime () : m_time(0) { }
TPriorityTime (unsigned time) : m_time(time) { }
void Set (unsigned time) {
if (m_time == time)
return;
m_time = time;
Relink();
}
unsigned Get () const {
return m_time;
}
bool IsPriorityHigher (const TPriorityTime<C> & source) const {
return (int)(m_time - source.m_time) < 0;
}
bool IsPriorityHigher (unsigned time) const {
return (int)(m_time - time) < 0;
}
private:
unsigned m_time;
};
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPriQ.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRIQ_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtPriQ.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTPRIQ_H
/****************************************************************************
*
* Macros
*
***/
#define PRIORITY_TIME(class) TPriorityTime< class >
#define PRIORITY_NUMERIC(class,type) TPriorityNumeric< class,type >
#define PRIQ(class,priority) TPriorityQueue< class,priority >
#define PRIQDECL(class,priority,field) TPriorityQueueDecl< class,priority,offsetof(class,field) >
#define PRIQDYN(class,priority) TPriorityQueueDyn< class,priority >
/****************************************************************************
*
* class TPriorityQueue
*
***/
template<class C, class P>
class TBasePriority;
template<class C, class P>
class TPriorityQueue {
public:
TPriorityQueue ();
~TPriorityQueue ();
C * const & operator[] (unsigned index) const;
void Clear ();
unsigned Count () const;
C * Delete (C * object);
C * Dequeue ();
void Enqueue (C * object);
C * const * Ptr () const;
C * Root () const;
C * const * Term () const;
void UnlinkAll ();
public:
// Intentionally unimplemented
TPriorityQueue (TPriorityQueue const &);
TPriorityQueue const & operator= (TPriorityQueue const &);
protected:
void SetLinkOffset (int offset);
private:
unsigned IndexChild (unsigned index) const;
unsigned IndexParent (unsigned index) const;
void Link (unsigned index);
P * Priority (C * object);
P const * Priority (C const * object) const;
void Remove (unsigned index);
void Unlink (unsigned index);
enum { LINK_OFFSET_UNINIT = 0xdddddddd };
int m_linkOffset;
ARRAY(C *) m_array;
friend TBasePriority<C,P>;
};
//===========================================================================
template<class C, class P>
inline C * const & TPriorityQueue<C,P>::operator[] (unsigned index) const {
return m_array[index];
}
//===========================================================================
template<class C, class P>
inline TPriorityQueue<C,P>::TPriorityQueue () :
m_linkOffset(LINK_OFFSET_UNINIT) {
}
//===========================================================================
template<class C, class P>
inline TPriorityQueue<C,P>::~TPriorityQueue () {
UnlinkAll();
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::Clear () {
// Deleting an object could cause other objects in the queue to be deleted
// so we can't make any assumptions about indices or counts of items in the array
while (C * head = Dequeue())
DEL(head);
m_array.Clear();
}
//===========================================================================
template<class C, class P>
inline unsigned TPriorityQueue<C,P>::Count () const {
return m_array.Count();
}
//===========================================================================
template<class C, class P>
C * TPriorityQueue<C,P>::Delete (C * object) {
// get the object's priority queue and position
P * priority = Priority(object);
const TPriorityQueue<C,P> * queue = priority->GetLink();
unsigned index = priority->GetIndex();
// delete the object
DEL(object);
// return the next object in that queue
if (queue && (index < queue->Count()))
return (*queue)[index];
else
return nil;
}
//===========================================================================
template<class C, class P>
C * TPriorityQueue<C,P>::Dequeue () {
if (!m_array.Count())
return nil;
C * value = m_array[0];
Remove(0);
return value;
}
//===========================================================================
template<class C, class P>
void TPriorityQueue<C,P>::Enqueue (C * object) {
P * priority = Priority(object);
// Verify that the object is not already linked into a priority queue.
// The original implementation of this function silently refused to
// enqueue at a new priority if the object was already in this queue.
// Since this behavior requires callers to check whether the object is
// already enqueued, we now simply assert that.
ASSERT(!priority->IsLinked());
unsigned index = m_array.Add(object);
unsigned parent = IndexParent(index);
// shift value toward root
while (index && priority->IsPriorityHigher(*Priority(m_array[parent]))) {
m_array[index] = m_array[parent];
Link(index);
index = parent;
parent = IndexParent(index);
}
// assign and link the new value
m_array[index] = object;
Link(index);
}
//===========================================================================
template<class C, class P>
inline unsigned TPriorityQueue<C,P>::IndexChild (unsigned index) const {
return (index << 1) + 1;
}
//===========================================================================
template<class C, class P>
inline unsigned TPriorityQueue<C,P>::IndexParent (unsigned index) const {
return (index - 1) >> 1;
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::Link (unsigned index) {
Priority(m_array[index])->Link(this, index);
}
//===========================================================================
template<class C, class P>
inline P * TPriorityQueue<C,P>::Priority (C * object) {
ASSERT(m_linkOffset != LINK_OFFSET_UNINIT);
return (P *)((byte *)object + m_linkOffset);
}
//===========================================================================
template<class C, class P>
inline P const * TPriorityQueue<C,P>::Priority (C const * object) const {
ASSERT(m_linkOffset != LINK_OFFSET_UNINIT);
return (P const *)((byte const *)object + m_linkOffset);
}
//===========================================================================
template<class C, class P>
inline C * const * TPriorityQueue<C,P>::Ptr () const {
return m_array.Ptr();
}
//===========================================================================
template<class C, class P>
void TPriorityQueue<C,P>::Remove (unsigned index) {
// reset the priority link fields
Unlink(index);
// save the terminal leaf node
C * value = m_array.Pop();
P * priority = Priority(value);
const unsigned count = m_array.Count();
if (count == index)
return;
// rebalance upwards from the position of the deleted entry
unsigned parent;
unsigned entry = index;
if (entry && priority->IsPriorityHigher(*Priority(m_array[parent = IndexParent(entry)]))) {
do {
m_array[entry] = m_array[parent];
Link(entry);
entry = parent;
} while (entry && priority->IsPriorityHigher(*Priority(m_array[parent = IndexParent(entry)])));
m_array[entry] = value;
Link(entry);
entry = index;
value = m_array[index];
priority = Priority(value);
}
// rebalance downwards from the position of the deleted entry
for (;;) {
unsigned child = IndexChild(entry);
if (child >= count)
break;
unsigned sibling = child + 1;
if ( (sibling < count) &&
(Priority(m_array[sibling])->IsPriorityHigher(*Priority(m_array[child]))) )
child = sibling;
if (priority->IsPriorityHigher(*Priority(m_array[child])))
break;
m_array[entry] = m_array[child];
Link(entry);
entry = child;
}
m_array[entry] = value;
Link(entry);
}
//===========================================================================
template<class C, class P>
inline C * TPriorityQueue<C,P>::Root () const {
return m_array.Count() ? m_array[0] : nil;
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::SetLinkOffset (int offset) {
ASSERT(m_linkOffset == LINK_OFFSET_UNINIT);
m_linkOffset = offset;
}
//===========================================================================
template<class C, class P>
inline C * const * TPriorityQueue<C,P>::Term () const {
return m_array.Term();
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::Unlink (unsigned index) {
Priority(m_array[index])->Link(nil, 0);
}
//===========================================================================
template<class C, class P>
inline void TPriorityQueue<C,P>::UnlinkAll () {
for (unsigned loop = m_array.Count(); loop--; )
Unlink(loop);
m_array.ZeroCount();
}
/****************************************************************************
*
* TPriorityQueueDecl
*
***/
template<class C, class P, int linkOffset>
class TPriorityQueueDecl : public TPriorityQueue<C,P> {
public:
TPriorityQueueDecl () { SetLinkOffset(linkOffset); }
};
/****************************************************************************
*
* TPriorityQueueDyn
*
***/
template<class C, class P>
class TPriorityQueueDyn : public TPriorityQueue<C,P> {
public:
void Initialize (int linkOffset) { SetLinkOffset(linkOffset); }
};
/****************************************************************************
*
* class TBasePriority
*
***/
template<class C, class P>
class TBasePriority {
public:
TBasePriority () : m_queue(nil), m_index(0) { }
virtual ~TBasePriority () { Unlink(); }
void Unlink () { if (m_queue) m_queue->Remove(m_index); }
bool IsLinked () const { return m_queue != nil; }
public:
TBasePriority (const TBasePriority &);
const TBasePriority & operator= (const TBasePriority &);
protected:
void Relink ();
private:
void Link (TPriorityQueue<C,P> * queue, unsigned index);
const TPriorityQueue<C,P> * GetLink () const { return m_queue; }
unsigned GetIndex () const { return m_index; }
private:
TPriorityQueue<C,P> * m_queue;
unsigned m_index;
friend TPriorityQueue<C,P>;
};
//===========================================================================
template<class C, class P>
inline void TBasePriority<C,P>::Link (TPriorityQueue<C,P> * queue, unsigned index) {
m_queue = queue;
m_index = index;
}
//===========================================================================
template<class C, class P>
void TBasePriority<C,P>::Relink () {
// cache m_queue, since m_queue->Remove() will set it to nil
TPriorityQueue<C,P> * queue = m_queue;
if (!queue)
return;
C * object = (*queue)[m_index];
queue->Remove(m_index);
queue->Enqueue(object);
}
/****************************************************************************
*
* class TPriorityNumeric
*
***/
template<class C,class T>
class TPriorityNumeric : public TBasePriority< C, TPriorityNumeric<C,T> > {
public:
TPriorityNumeric () : m_value(0) { }
TPriorityNumeric (T value) : m_value(value) { }
void Set (T value) {
if (value == m_value)
return;
m_value = value;
Relink();
}
T Get () const {
return m_value;
}
bool IsPriorityHigher (const TPriorityNumeric<C,T> & source) {
return m_value > source.m_value;
}
bool IsPriorityHigher (T value) const {
return m_value > value;
}
private:
T m_value;
};
/****************************************************************************
*
* class TPriorityTime
*
***/
template<class C>
class TPriorityTime : public TBasePriority< C, TPriorityTime<C> > {
public:
TPriorityTime () : m_time(0) { }
TPriorityTime (unsigned time) : m_time(time) { }
void Set (unsigned time) {
if (m_time == time)
return;
m_time = time;
Relink();
}
unsigned Get () const {
return m_time;
}
bool IsPriorityHigher (const TPriorityTime<C> & source) const {
return (int)(m_time - source.m_time) < 0;
}
bool IsPriorityHigher (unsigned time) const {
return (int)(m_time - time) < 0;
}
private:
unsigned m_time;
};

View File

@ -1,169 +1,169 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
class RandomContext {
dword m_seed;
dword m_value;
void UpdateValue ();
public:
RandomContext ();
void Reset ();
void SetSeed (unsigned seed);
float GetFloat ();
float GetFloat (float minVal, float maxVal);
unsigned GetUnsigned ();
unsigned GetUnsigned (unsigned minVal, unsigned maxVal);
};
/*****************************************************************************
*
* Private data
*
***/
static const dword kDefaultRandomSeed = 0x075bd924;
static RandomContext s_random;
/*****************************************************************************
*
* RandomContext
*
***/
//============================================================================
RandomContext::RandomContext ()
: m_seed(kDefaultRandomSeed)
{
Reset();
}
//============================================================================
void RandomContext::UpdateValue () {
const dword A = 0xbc8f;
const dword Q = 0xadc8;
const dword R = 0x0d47;
dword div = m_value / Q;
m_value = A * (m_value - Q * div) - R * div;
if (m_value > kRandomMax)
m_value -= kRandomMax + 1;
if (!m_value)
m_value = kDefaultRandomSeed;
}
//============================================================================
void RandomContext::Reset () {
m_value = m_seed;
}
//============================================================================
void RandomContext::SetSeed (unsigned seed) {
// Never allow a seed of zero
m_seed = seed ? seed : kDefaultRandomSeed;
Reset();
}
//============================================================================
float RandomContext::GetFloat () {
UpdateValue();
return m_value * (1.0f / kRandomMax);
}
//============================================================================
float RandomContext::GetFloat (float minVal, float maxVal) {
float value = GetFloat();
return minVal + value * (maxVal - minVal);
}
//============================================================================
unsigned RandomContext::GetUnsigned () {
UpdateValue();
return (unsigned)m_value;
}
//============================================================================
unsigned RandomContext::GetUnsigned (unsigned minVal, unsigned maxVal) {
unsigned value = GetUnsigned();
return minVal + value % (maxVal - minVal + 1);
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void RandReset () {
s_random.Reset();
}
//============================================================================
void RandSetSeed (unsigned seed) {
s_random.SetSeed(seed);
}
//============================================================================
float RandFloat () {
return s_random.GetFloat();
}
//============================================================================
float RandFloat (float minVal, float maxVal) {
return s_random.GetFloat(minVal, maxVal);
}
//============================================================================
unsigned RandUnsigned () {
return s_random.GetUnsigned();
}
//============================================================================
unsigned RandUnsigned (unsigned minVal, unsigned maxVal) {
return s_random.GetUnsigned(minVal, maxVal);
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Private
*
***/
class RandomContext {
dword m_seed;
dword m_value;
void UpdateValue ();
public:
RandomContext ();
void Reset ();
void SetSeed (unsigned seed);
float GetFloat ();
float GetFloat (float minVal, float maxVal);
unsigned GetUnsigned ();
unsigned GetUnsigned (unsigned minVal, unsigned maxVal);
};
/*****************************************************************************
*
* Private data
*
***/
static const dword kDefaultRandomSeed = 0x075bd924;
static RandomContext s_random;
/*****************************************************************************
*
* RandomContext
*
***/
//============================================================================
RandomContext::RandomContext ()
: m_seed(kDefaultRandomSeed)
{
Reset();
}
//============================================================================
void RandomContext::UpdateValue () {
const dword A = 0xbc8f;
const dword Q = 0xadc8;
const dword R = 0x0d47;
dword div = m_value / Q;
m_value = A * (m_value - Q * div) - R * div;
if (m_value > kRandomMax)
m_value -= kRandomMax + 1;
if (!m_value)
m_value = kDefaultRandomSeed;
}
//============================================================================
void RandomContext::Reset () {
m_value = m_seed;
}
//============================================================================
void RandomContext::SetSeed (unsigned seed) {
// Never allow a seed of zero
m_seed = seed ? seed : kDefaultRandomSeed;
Reset();
}
//============================================================================
float RandomContext::GetFloat () {
UpdateValue();
return m_value * (1.0f / kRandomMax);
}
//============================================================================
float RandomContext::GetFloat (float minVal, float maxVal) {
float value = GetFloat();
return minVal + value * (maxVal - minVal);
}
//============================================================================
unsigned RandomContext::GetUnsigned () {
UpdateValue();
return (unsigned)m_value;
}
//============================================================================
unsigned RandomContext::GetUnsigned (unsigned minVal, unsigned maxVal) {
unsigned value = GetUnsigned();
return minVal + value % (maxVal - minVal + 1);
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
void RandReset () {
s_random.Reset();
}
//============================================================================
void RandSetSeed (unsigned seed) {
s_random.SetSeed(seed);
}
//============================================================================
float RandFloat () {
return s_random.GetFloat();
}
//============================================================================
float RandFloat (float minVal, float maxVal) {
return s_random.GetFloat(minVal, maxVal);
}
//============================================================================
unsigned RandUnsigned () {
return s_random.GetUnsigned();
}
//============================================================================
unsigned RandUnsigned (unsigned minVal, unsigned maxVal) {
return s_random.GetUnsigned(minVal, maxVal);
}

View File

@ -1,51 +1,51 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTRAND_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTRAND_H
/*****************************************************************************
*
* Psuedo-random number generator
*
***/
const dword kRandomMax = 0x7fffffff;
void RandReset ();
void RandSetSeed (unsigned seed);
float RandFloat ();
float RandFloat (float minVal, float maxVal);
unsigned RandUnsigned ();
unsigned RandUnsigned (unsigned minVal, unsigned maxVal);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTRAND_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRand.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTRAND_H
/*****************************************************************************
*
* Psuedo-random number generator
*
***/
const dword kRandomMax = 0x7fffffff;
void RandReset ();
void RandSetSeed (unsigned seed);
float RandFloat ();
float RandFloat (float minVal, float maxVal);
unsigned RandUnsigned ();
unsigned RandUnsigned (unsigned minVal, unsigned maxVal);

View File

@ -1,164 +1,164 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRef.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTREF_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRef.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTREF_H
/*****************************************************************************
*
* Debug macros
*
***/
#ifdef REFCOUNT_DEBUGGING
#define REFTRACE DEBUG_MSG
#else
#define REFTRACE NULL_STMT
#endif
/****************************************************************************
*
* AtomicRef
* Thread safe reference count
*
***/
class AtomicRef {
#ifdef HS_DEBUGGING
bool zeroed;
#endif
public:
inline AtomicRef ()
: m_ref(0)
#ifdef HS_DEBUGGING
, zeroed(false)
#endif
{}
inline void AcknowledgeZeroRef () {
#ifdef HS_DEBUGGING
zeroed = false;
#endif
}
inline long IncRef () {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, 1);
REFTRACE("Inc %p: %u", this, prev+1);
return prev+1;
}
inline long IncRef (const char tag[]) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, 1);
REFTRACE("Inc %p %s: %u", this, tag, prev+1);
return prev+1;
}
inline long IncRef (unsigned n) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, n);
REFTRACE("Inc %p: %u", this, prev+n);
return prev+n;
}
inline long IncRef (unsigned n, const char tag[]) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, n);
REFTRACE("Inc %p %s: %u", this, tag, prev+n);
return prev+n;
}
inline long DecRef () {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev;
if ((prev = AtomicAdd(&m_ref, -1)) == 1) {
#ifdef HS_DEBUGGING
zeroed = true;
#endif
OnZeroRef();
}
REFTRACE("Dec %p: %u", this, prev-1);
return prev-1;
}
inline long DecRef (const char tag[]) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev;
if ((prev = AtomicAdd(&m_ref, -1)) == 1) {
#ifdef HS_DEBUGGING
zeroed = true;
#endif
OnZeroRef();
}
REFTRACE("Dec %p %s: %u", this, tag, prev-1);
return prev-1;
}
inline void TransferRef (
const char oldTag[],
const char newTag[]
) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
REFTRACE("Inc %p %s: (xfer)", this, newTag);
REFTRACE("Dec %p %s: (xfer)", this, oldTag);
}
inline unsigned GetRefCount () {
return m_ref;
}
inline virtual void OnZeroRef () {
DEL(this);
}
protected:
inline virtual ~AtomicRef () {
ASSERT(!m_ref);
}
private:
long m_ref;
};
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRef.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTREF_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtRef.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTREF_H
/*****************************************************************************
*
* Debug macros
*
***/
#ifdef REFCOUNT_DEBUGGING
#define REFTRACE DEBUG_MSG
#else
#define REFTRACE NULL_STMT
#endif
/****************************************************************************
*
* AtomicRef
* Thread safe reference count
*
***/
class AtomicRef {
#ifdef HS_DEBUGGING
bool zeroed;
#endif
public:
inline AtomicRef ()
: m_ref(0)
#ifdef HS_DEBUGGING
, zeroed(false)
#endif
{}
inline void AcknowledgeZeroRef () {
#ifdef HS_DEBUGGING
zeroed = false;
#endif
}
inline long IncRef () {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, 1);
REFTRACE("Inc %p: %u", this, prev+1);
return prev+1;
}
inline long IncRef (const char tag[]) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, 1);
REFTRACE("Inc %p %s: %u", this, tag, prev+1);
return prev+1;
}
inline long IncRef (unsigned n) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, n);
REFTRACE("Inc %p: %u", this, prev+n);
return prev+n;
}
inline long IncRef (unsigned n, const char tag[]) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev = AtomicAdd(&m_ref, n);
REFTRACE("Inc %p %s: %u", this, tag, prev+n);
return prev+n;
}
inline long DecRef () {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev;
if ((prev = AtomicAdd(&m_ref, -1)) == 1) {
#ifdef HS_DEBUGGING
zeroed = true;
#endif
OnZeroRef();
}
REFTRACE("Dec %p: %u", this, prev-1);
return prev-1;
}
inline long DecRef (const char tag[]) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
long prev;
if ((prev = AtomicAdd(&m_ref, -1)) == 1) {
#ifdef HS_DEBUGGING
zeroed = true;
#endif
OnZeroRef();
}
REFTRACE("Dec %p %s: %u", this, tag, prev-1);
return prev-1;
}
inline void TransferRef (
const char oldTag[],
const char newTag[]
) {
#ifdef HS_DEBUGGING
ASSERT(!zeroed);
#endif
REFTRACE("Inc %p %s: (xfer)", this, newTag);
REFTRACE("Dec %p %s: (xfer)", this, oldTag);
}
inline unsigned GetRefCount () {
return m_ref;
}
inline virtual void OnZeroRef () {
DEL(this);
}
protected:
inline virtual ~AtomicRef () {
ASSERT(!m_ref);
}
private:
long m_ref;
};

View File

@ -1,461 +1,461 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSkipList.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSKIPLIST_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSkipList.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSKIPLIST_H
/*****************************************************************************
*
* Macros
*
***/
#define SKIPLIST(type, keyType, keyField, cmp) TSkipList< type, keyType, offsetof(type, keyField), cmp >
#define SKIPLIST_NUMERIC(type, keyType, keyField) SKIPLIST(type, keyType, keyField, TSkipListNumericCmp<keyType>)
#define SKIPLIST_STRING(type, keyType, keyField) SKIPLIST(type, keyType, keyField, TSkipListStringCmp<keyType>)
#define SKIPLIST_STRINGI(type, keyType, keyField) SKIPLIST(type, keyType, keyField, TSkipListStringCmpI<keyType>)
/*****************************************************************************
*
* Typedefs
*
***/
typedef void * SkipListTag;
/*****************************************************************************
*
* Comparers
*
***/
template<class K>
class TSkipListNumericCmp {
public:
static bool Eq (const K & a, const K & b) { return a == b; }
static bool Lt (const K & a, const K & b) { return a < b; }
};
template<class K>
class TSkipListStringCmp {
public:
static bool Eq (const K & a, const K & b) { return StrCmp(a, b, (unsigned)-1) == 0; }
static bool Lt (const K & a, const K & b) { return StrCmp(a, b, (unsigned)-1) < 0; }
};
template<class K>
class TSkipListStringCmpI {
public:
static bool Eq (const K & a, const K & b) { return StrCmpI(a, b, (unsigned)-1) == 0; }
static bool Lt (const K & a, const K & b) { return StrCmpI(a, b, (unsigned)-1) < 0; }
};
/*****************************************************************************
*
* TSkipList
*
***/
template<class T, class K, unsigned keyOffset, class Cmp>
class TSkipList {
private:
enum { kMaxLevels = 32 };
template<class T, class K>
struct TNode {
const K * key;
T * object;
unsigned level;
TNode<T, K> * prev;
TNode<T, K> * next[1]; // variable size array
};
typedef TNode<T,K> Node;
unsigned m_level;
Node * m_head;
Node * m_stop;
unsigned m_randomBits;
unsigned m_randomsLeft;
Node * AllocNode (unsigned levels);
void FreeNode (Node * node);
unsigned RandomLevel ();
public:
inline TSkipList ();
inline ~TSkipList ();
inline void Clear ();
inline void Delete (T * object);
inline T * Find (const K & key, SkipListTag * tag = nil) const;
inline T * FindNext (SkipListTag * tag) const;
inline T * Head (SkipListTag * tag) const;
inline T * Next (SkipListTag * tag) const;
inline T * Prev (SkipListTag * tag) const;
inline T * Tail (SkipListTag * tag) const;
inline void Link (T * object);
inline void Unlink (T * object);
inline void Unlink (SkipListTag * tag);
inline void UnlinkAll ();
#ifdef HS_DEBUGGING
inline void Print () const;
#endif
};
/*****************************************************************************
*
* TSkipList private member functions
*
***/
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
typename TSkipList<T,K,keyOffset,Cmp>::TNode<T,K> * TSkipList<T,K,keyOffset,Cmp>::AllocNode (unsigned level) {
unsigned size = offsetof(Node, next) + (level + 1) * sizeof(Node);
Node * node = (Node *)ALLOC(size);
node->level = level;
return node;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::FreeNode (TNode<T,K> * node) {
FREE(node);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
unsigned TSkipList<T,K,keyOffset,Cmp>::RandomLevel () {
unsigned level = 0;
unsigned bits = 0;
while (!bits) {
bits = m_randomBits % 4;
if (!bits)
++level;
m_randomBits >>= 2;
m_randomsLeft -= 2;
if (!m_randomsLeft) {
m_randomBits = RandUnsigned();
m_randomsLeft = 30;
}
}
return level;
}
/*****************************************************************************
*
* TSkipList public member functions
*
***/
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
TSkipList<T,K,keyOffset,Cmp>::TSkipList () {
m_level = 0;
m_head = AllocNode(kMaxLevels);
m_stop = AllocNode(0);
m_randomBits = RandUnsigned();
m_randomsLeft = 30;
// Initialize header and stop skip node pointers
m_stop->prev = m_head;
m_stop->object = nil;
m_stop->next[0] = nil;
m_head->object = nil;
for (unsigned index = 0; index < kMaxLevels; ++index)
m_head->next[index] = m_stop;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
TSkipList<T,K,keyOffset,Cmp>::~TSkipList () {
UnlinkAll();
ASSERT(m_stop->prev == m_head);
FreeNode(m_head);
FreeNode(m_stop);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Clear () {
Node * ptr = m_head->next[0];
while (ptr != m_stop) {
Node * next = ptr->next[0];
DEL(ptr->object);
FreeNode(ptr);
ptr = next;
}
m_stop->prev = m_head;
for (unsigned index = 0; index < kMaxLevels; ++index)
m_head->next[index] = m_stop;
m_level = 0;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Delete (T * object) {
Unlink(object);
DEL(object);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Find (const K & key, SkipListTag * tag) const {
Node * node = m_head;
m_stop->key = &key;
for (int level = (int)m_level; level >= 0; --level)
while (Cmp::Lt(*node->next[level]->key, key))
node = node->next[level];
node = node->next[0];
if (node != m_stop && Cmp::Eq(*node->key, *m_stop->key)) {
if (tag)
*tag = node;
return node->object;
}
else {
if (tag)
*tag = nil;
return nil;
}
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::FindNext (SkipListTag * tag) const {
Node * node = (Node *)*tag;
m_stop->key = node->key;
for (int level = (int)node->level; level >= 0; --level)
while (Cmp::Lt(*node->next[level]->key, *m_stop->key))
node = node->next[level];
node = node->next[0];
if (node != m_stop && Cmp::Eq(*node->key, *m_stop->key)) {
*tag = node;
return node->object;
}
else {
*tag = nil;
return nil;
}
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Head (SkipListTag * tag) const {
ASSERT(tag);
Node * first = m_head->next[0];
if (first == m_stop) {
*tag = nil;
return nil;
}
*tag = first;
return first->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Next (SkipListTag * tag) const {
ASSERT(tag);
Node * node = (Node *)*tag;
ASSERT(node);
if (node->next[0] == m_stop) {
*tag = nil;
return nil;
}
*tag = node->next[0];
return node->next[0]->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Prev (SkipListTag * tag) const {
ASSERT(tag);
Node * node = (Node *)*tag;
ASSERT(node);
if (node->prev == m_head) {
*tag = nil;
return nil;
}
*tag = node->prev;
return node->prev->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Tail (SkipListTag * tag) const {
ASSERT(tag);
Node * last = m_stop->prev;
if (last == m_head) {
*tag = nil;
return nil;
}
*tag = last;
return last->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Link (T * object) {
const K * key = (const K *)((const byte *)object + keyOffset);
// Find the node's insertion point
m_stop->key = key;
Node * update[kMaxLevels];
Node * node = m_head;
for (int level = (int)m_level; level >= 0; --level) {
while (Cmp::Lt(*node->next[level]->key, *key))
node = node->next[level];
update[level] = node;
}
node = node->next[0];
{
// Select a level for the skip node
unsigned newLevel = RandomLevel();
if (newLevel > m_level) {
if (m_level < kMaxLevels - 1) {
newLevel = ++m_level;
update[newLevel] = m_head;
}
else
newLevel = m_level;
}
// Create the node and insert it into the skip list
Node * node = AllocNode(newLevel);
node->key = key;
node->object = object;
for (unsigned level = newLevel; level >= 1; --level) {
node->next[level] = update[level]->next[level];
update[level]->next[level] = node;
}
node->prev = update[0];
node->next[0] = update[0]->next[0];
update[0]->next[0]->prev = node;
update[0]->next[0] = node;
}
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Unlink (T * object) {
const K * key = (const K *)((const byte *)object + keyOffset);
Node * node = m_head;
Node * update[kMaxLevels];
int level = m_level;
for (;;) {
// Find the node being unlinked
m_stop->key = key;
for (; level >= 0; --level) {
while (Cmp::Lt(*node->next[level]->key, *key))
node = node->next[level];
update[level] = node;
}
node = node->next[0];
// Node wasn't found so do nothing
if (*node->key != *key || node == m_stop)
return;
if (node->object == object)
break;
}
// Update all links
for (level = m_level; level >= 1; --level) {
if (update[level]->next[level] != node)
continue;
update[level]->next[level] = node->next[level];
}
ASSERT(update[0]->next[0] == node);
node->next[0]->prev = update[0];
update[0]->next[0] = node->next[0];
// Update header
while (m_level && m_head->next[m_level] == m_stop)
--m_level;
FreeNode(node);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::UnlinkAll () {
Node * ptr = m_head->next[0];
while (ptr != m_stop) {
Node * next = ptr->next[0];
FreeNode(ptr);
ptr = next;
}
m_stop->prev = m_head;
for (unsigned index = 0; index < kMaxLevels; ++index)
m_head->next[index] = m_stop;
m_level = 0;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSkipList.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSKIPLIST_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSkipList.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSKIPLIST_H
/*****************************************************************************
*
* Macros
*
***/
#define SKIPLIST(type, keyType, keyField, cmp) TSkipList< type, keyType, offsetof(type, keyField), cmp >
#define SKIPLIST_NUMERIC(type, keyType, keyField) SKIPLIST(type, keyType, keyField, TSkipListNumericCmp<keyType>)
#define SKIPLIST_STRING(type, keyType, keyField) SKIPLIST(type, keyType, keyField, TSkipListStringCmp<keyType>)
#define SKIPLIST_STRINGI(type, keyType, keyField) SKIPLIST(type, keyType, keyField, TSkipListStringCmpI<keyType>)
/*****************************************************************************
*
* Typedefs
*
***/
typedef void * SkipListTag;
/*****************************************************************************
*
* Comparers
*
***/
template<class K>
class TSkipListNumericCmp {
public:
static bool Eq (const K & a, const K & b) { return a == b; }
static bool Lt (const K & a, const K & b) { return a < b; }
};
template<class K>
class TSkipListStringCmp {
public:
static bool Eq (const K & a, const K & b) { return StrCmp(a, b, (unsigned)-1) == 0; }
static bool Lt (const K & a, const K & b) { return StrCmp(a, b, (unsigned)-1) < 0; }
};
template<class K>
class TSkipListStringCmpI {
public:
static bool Eq (const K & a, const K & b) { return StrCmpI(a, b, (unsigned)-1) == 0; }
static bool Lt (const K & a, const K & b) { return StrCmpI(a, b, (unsigned)-1) < 0; }
};
/*****************************************************************************
*
* TSkipList
*
***/
template<class T, class K, unsigned keyOffset, class Cmp>
class TSkipList {
private:
enum { kMaxLevels = 32 };
template<class T, class K>
struct TNode {
const K * key;
T * object;
unsigned level;
TNode<T, K> * prev;
TNode<T, K> * next[1]; // variable size array
};
typedef TNode<T,K> Node;
unsigned m_level;
Node * m_head;
Node * m_stop;
unsigned m_randomBits;
unsigned m_randomsLeft;
Node * AllocNode (unsigned levels);
void FreeNode (Node * node);
unsigned RandomLevel ();
public:
inline TSkipList ();
inline ~TSkipList ();
inline void Clear ();
inline void Delete (T * object);
inline T * Find (const K & key, SkipListTag * tag = nil) const;
inline T * FindNext (SkipListTag * tag) const;
inline T * Head (SkipListTag * tag) const;
inline T * Next (SkipListTag * tag) const;
inline T * Prev (SkipListTag * tag) const;
inline T * Tail (SkipListTag * tag) const;
inline void Link (T * object);
inline void Unlink (T * object);
inline void Unlink (SkipListTag * tag);
inline void UnlinkAll ();
#ifdef HS_DEBUGGING
inline void Print () const;
#endif
};
/*****************************************************************************
*
* TSkipList private member functions
*
***/
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
typename TSkipList<T,K,keyOffset,Cmp>::TNode<T,K> * TSkipList<T,K,keyOffset,Cmp>::AllocNode (unsigned level) {
unsigned size = offsetof(Node, next) + (level + 1) * sizeof(Node);
Node * node = (Node *)ALLOC(size);
node->level = level;
return node;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::FreeNode (TNode<T,K> * node) {
FREE(node);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
unsigned TSkipList<T,K,keyOffset,Cmp>::RandomLevel () {
unsigned level = 0;
unsigned bits = 0;
while (!bits) {
bits = m_randomBits % 4;
if (!bits)
++level;
m_randomBits >>= 2;
m_randomsLeft -= 2;
if (!m_randomsLeft) {
m_randomBits = RandUnsigned();
m_randomsLeft = 30;
}
}
return level;
}
/*****************************************************************************
*
* TSkipList public member functions
*
***/
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
TSkipList<T,K,keyOffset,Cmp>::TSkipList () {
m_level = 0;
m_head = AllocNode(kMaxLevels);
m_stop = AllocNode(0);
m_randomBits = RandUnsigned();
m_randomsLeft = 30;
// Initialize header and stop skip node pointers
m_stop->prev = m_head;
m_stop->object = nil;
m_stop->next[0] = nil;
m_head->object = nil;
for (unsigned index = 0; index < kMaxLevels; ++index)
m_head->next[index] = m_stop;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
TSkipList<T,K,keyOffset,Cmp>::~TSkipList () {
UnlinkAll();
ASSERT(m_stop->prev == m_head);
FreeNode(m_head);
FreeNode(m_stop);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Clear () {
Node * ptr = m_head->next[0];
while (ptr != m_stop) {
Node * next = ptr->next[0];
DEL(ptr->object);
FreeNode(ptr);
ptr = next;
}
m_stop->prev = m_head;
for (unsigned index = 0; index < kMaxLevels; ++index)
m_head->next[index] = m_stop;
m_level = 0;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Delete (T * object) {
Unlink(object);
DEL(object);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Find (const K & key, SkipListTag * tag) const {
Node * node = m_head;
m_stop->key = &key;
for (int level = (int)m_level; level >= 0; --level)
while (Cmp::Lt(*node->next[level]->key, key))
node = node->next[level];
node = node->next[0];
if (node != m_stop && Cmp::Eq(*node->key, *m_stop->key)) {
if (tag)
*tag = node;
return node->object;
}
else {
if (tag)
*tag = nil;
return nil;
}
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::FindNext (SkipListTag * tag) const {
Node * node = (Node *)*tag;
m_stop->key = node->key;
for (int level = (int)node->level; level >= 0; --level)
while (Cmp::Lt(*node->next[level]->key, *m_stop->key))
node = node->next[level];
node = node->next[0];
if (node != m_stop && Cmp::Eq(*node->key, *m_stop->key)) {
*tag = node;
return node->object;
}
else {
*tag = nil;
return nil;
}
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Head (SkipListTag * tag) const {
ASSERT(tag);
Node * first = m_head->next[0];
if (first == m_stop) {
*tag = nil;
return nil;
}
*tag = first;
return first->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Next (SkipListTag * tag) const {
ASSERT(tag);
Node * node = (Node *)*tag;
ASSERT(node);
if (node->next[0] == m_stop) {
*tag = nil;
return nil;
}
*tag = node->next[0];
return node->next[0]->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Prev (SkipListTag * tag) const {
ASSERT(tag);
Node * node = (Node *)*tag;
ASSERT(node);
if (node->prev == m_head) {
*tag = nil;
return nil;
}
*tag = node->prev;
return node->prev->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
T * TSkipList<T,K,keyOffset,Cmp>::Tail (SkipListTag * tag) const {
ASSERT(tag);
Node * last = m_stop->prev;
if (last == m_head) {
*tag = nil;
return nil;
}
*tag = last;
return last->object;
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Link (T * object) {
const K * key = (const K *)((const byte *)object + keyOffset);
// Find the node's insertion point
m_stop->key = key;
Node * update[kMaxLevels];
Node * node = m_head;
for (int level = (int)m_level; level >= 0; --level) {
while (Cmp::Lt(*node->next[level]->key, *key))
node = node->next[level];
update[level] = node;
}
node = node->next[0];
{
// Select a level for the skip node
unsigned newLevel = RandomLevel();
if (newLevel > m_level) {
if (m_level < kMaxLevels - 1) {
newLevel = ++m_level;
update[newLevel] = m_head;
}
else
newLevel = m_level;
}
// Create the node and insert it into the skip list
Node * node = AllocNode(newLevel);
node->key = key;
node->object = object;
for (unsigned level = newLevel; level >= 1; --level) {
node->next[level] = update[level]->next[level];
update[level]->next[level] = node;
}
node->prev = update[0];
node->next[0] = update[0]->next[0];
update[0]->next[0]->prev = node;
update[0]->next[0] = node;
}
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::Unlink (T * object) {
const K * key = (const K *)((const byte *)object + keyOffset);
Node * node = m_head;
Node * update[kMaxLevels];
int level = m_level;
for (;;) {
// Find the node being unlinked
m_stop->key = key;
for (; level >= 0; --level) {
while (Cmp::Lt(*node->next[level]->key, *key))
node = node->next[level];
update[level] = node;
}
node = node->next[0];
// Node wasn't found so do nothing
if (*node->key != *key || node == m_stop)
return;
if (node->object == object)
break;
}
// Update all links
for (level = m_level; level >= 1; --level) {
if (update[level]->next[level] != node)
continue;
update[level]->next[level] = node->next[level];
}
ASSERT(update[0]->next[0] == node);
node->next[0]->prev = update[0];
update[0]->next[0] = node->next[0];
// Update header
while (m_level && m_head->next[m_level] == m_stop)
--m_level;
FreeNode(node);
}
//============================================================================
template<class T, class K, unsigned keyOffset, class Cmp>
void TSkipList<T,K,keyOffset,Cmp>::UnlinkAll () {
Node * ptr = m_head->next[0];
while (ptr != m_stop) {
Node * next = ptr->next[0];
FreeNode(ptr);
ptr = next;
}
m_stop->prev = m_head;
for (unsigned index = 0; index < kMaxLevels; ++index)
m_head->next[index] = m_stop;
m_level = 0;
}

View File

@ -1,225 +1,225 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSort.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSORT_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSort.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSORT_H
/****************************************************************************
*
* QSORT
*
* This version of QuickSort is similar to the one in the C runtime library,
* but is implemented as a macro to allow more flexible usage.
*
* With the C runtime library version, when data external to the sort array
* is needed to make sorting decisions, that data must be stored in file- or
* global-scope variables. This creates thread safety problems which can
* only be resolved through the use of synchronization objects. The version
* of QuickSort provided here does not require function calls to make
* sorting decisions, so all data can be kept in stack variables.
*
* The expression used for making comparisons allows the same return values
* as the comparison function used by the C runtime library, and can in fact
* be a function call to a comparison function that was originally designed
* for use by the C runtime library.
* > 0 if elem1 greater than elem2
* = 0 if elem1 equivalent to elem2
* < 0 if elem1 less than elem2
*
* However, this implementation of QuickSort never requires a distinction
* between the case where elem1 is less than elem2 and the case where elem1
* is equivalent to elem2, so it is possible to use the following more
* efficient return values:
* > 0 if elem1 is greater than elem2
* <= 0 if elem1 is less than or equivalent to elem2
*
***/
//===========================================================================
#define QSORT(T, ptr, count, expr) { \
\
/* Largest possible stack count required is 1 + log2(size) */ \
T * loStack[32]; \
T * hiStack[32]; \
unsigned stackPos = 0; \
\
if ((count) >= 2) { \
T * lo = (ptr); \
T * hi = lo + (count); \
for (;;) { \
\
/* Pick a partitioning element */ \
T * mid = lo + (hi - lo) / 2; \
\
/* Swap it to the beginning of the array */ \
SWAP(*mid, *lo); \
\
/* Partition the array into three pieces, one consisting of */ \
/* elements <= the partitioning element, one of elements */ \
/* equal to it, and one of elements >= to it. */ \
T * loPart = lo; \
T * hiPart = hi; \
for (;;) { \
/* val(i) <= val(lo) for lo <= i <= loPart */ \
/* val(i) >= val(lo) for hiPart <= i <= hi */ \
\
for (;;) { \
if (++loPart == hi) \
break; \
T const & elem1 = *loPart; \
T const & elem2 = *lo; \
int result = (expr); \
if (result > 0) \
break; \
} \
\
for (;;) { \
if (--hiPart == lo) \
break; \
T const & elem1 = *lo; \
T const & elem2 = *hiPart; \
int result = (expr); \
if (result > 0) \
break; \
} \
\
if (hiPart < loPart) \
break; \
\
/* val(loPart) > val(lo) */ \
/* val(hiPart) < val(lo) */ \
\
SWAP(*loPart, *hiPart); \
\
/* val(loPart) < val(lo) */ \
/* val(hiPart) > val(lo) */ \
} \
\
/* val(i) <= val(lo) for lo <= i <= hiPart */ \
/* val(i) == val(lo) for hiPart < i < loPart */ \
/* val(i) >= val(lo) for loPart <= i <= hi */ \
\
/* Put the partitioning element in place */ \
SWAP(*lo, *hiPart); \
\
/* val(i) <= val(hiPart) for lo <= i < hiPart */ \
/* val(i) == val(lo) for hiPart <= i < loPart */ \
/* val(i) >= val(hiPart) for loPart <= i < hi */ \
\
/* Sort the subarrays [lo, hiPart-1] and [loPart, hi]. */ \
/* We sort the smaller one first to minimize stack usage. */ \
if (hiPart - lo >= hi - loPart) { \
if (lo + 1 < hiPart) { \
/* Store the bigger subarray */ \
loStack[stackPos] = lo; \
hiStack[stackPos] = hiPart; \
++stackPos; \
} \
if (loPart + 1 < hi) { \
/* Sort the smaller subarray */ \
lo = loPart; \
continue; \
} \
} \
else { \
if (loPart + 1 < hi) { \
/* Store the bigger subarray */ \
loStack[stackPos] = loPart; \
hiStack[stackPos] = hi; \
++stackPos; \
} \
if (lo + 1 < hiPart) { \
/* Sort the smaller subarray */ \
hi = hiPart; \
continue; \
} \
} \
\
/* Pop the next subarray off the stack */ \
if (stackPos--) { \
lo = loStack[stackPos]; \
hi = hiStack[stackPos]; \
continue; \
} \
\
break; \
} \
} \
}
/****************************************************************************
*
* BSEARCH
*
* This macro binary searches a sorted array to find an existing entry or
* the position where a TRACKED_NEW entry should be placed. It returns the index of
* the first entry for which the expression is false (zero or negative), or
* count if the expression is true (positive) for all entries.
*
* Typically the expression will return:
* > 0 if (sortKey > elem)
* <= 0 if (sortKey <= elem)
*
* The final parameter to the macro is the address of a variable which is
* filled with the resulting index.
*
***/
//===========================================================================
#define BSEARCH(T, ptr, count, expr, addrOfIndex) { \
\
const T * low = (ptr); \
const T * high = (ptr) + (count); /* first entry for which */ \
/* expr is false */ \
\
if (low != high) \
for (;;) { \
const T & elem = *(low + (high - low) / 2); \
int result = (expr); \
if (result > 0) { \
if (&elem == low) \
break; \
low = &elem; \
} \
else { \
high = &elem; \
if (&elem == low) \
break; \
} \
} \
\
*(addrOfIndex) = high - (ptr); \
\
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSort.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSORT_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSort.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSORT_H
/****************************************************************************
*
* QSORT
*
* This version of QuickSort is similar to the one in the C runtime library,
* but is implemented as a macro to allow more flexible usage.
*
* With the C runtime library version, when data external to the sort array
* is needed to make sorting decisions, that data must be stored in file- or
* global-scope variables. This creates thread safety problems which can
* only be resolved through the use of synchronization objects. The version
* of QuickSort provided here does not require function calls to make
* sorting decisions, so all data can be kept in stack variables.
*
* The expression used for making comparisons allows the same return values
* as the comparison function used by the C runtime library, and can in fact
* be a function call to a comparison function that was originally designed
* for use by the C runtime library.
* > 0 if elem1 greater than elem2
* = 0 if elem1 equivalent to elem2
* < 0 if elem1 less than elem2
*
* However, this implementation of QuickSort never requires a distinction
* between the case where elem1 is less than elem2 and the case where elem1
* is equivalent to elem2, so it is possible to use the following more
* efficient return values:
* > 0 if elem1 is greater than elem2
* <= 0 if elem1 is less than or equivalent to elem2
*
***/
//===========================================================================
#define QSORT(T, ptr, count, expr) { \
\
/* Largest possible stack count required is 1 + log2(size) */ \
T * loStack[32]; \
T * hiStack[32]; \
unsigned stackPos = 0; \
\
if ((count) >= 2) { \
T * lo = (ptr); \
T * hi = lo + (count); \
for (;;) { \
\
/* Pick a partitioning element */ \
T * mid = lo + (hi - lo) / 2; \
\
/* Swap it to the beginning of the array */ \
SWAP(*mid, *lo); \
\
/* Partition the array into three pieces, one consisting of */ \
/* elements <= the partitioning element, one of elements */ \
/* equal to it, and one of elements >= to it. */ \
T * loPart = lo; \
T * hiPart = hi; \
for (;;) { \
/* val(i) <= val(lo) for lo <= i <= loPart */ \
/* val(i) >= val(lo) for hiPart <= i <= hi */ \
\
for (;;) { \
if (++loPart == hi) \
break; \
T const & elem1 = *loPart; \
T const & elem2 = *lo; \
int result = (expr); \
if (result > 0) \
break; \
} \
\
for (;;) { \
if (--hiPart == lo) \
break; \
T const & elem1 = *lo; \
T const & elem2 = *hiPart; \
int result = (expr); \
if (result > 0) \
break; \
} \
\
if (hiPart < loPart) \
break; \
\
/* val(loPart) > val(lo) */ \
/* val(hiPart) < val(lo) */ \
\
SWAP(*loPart, *hiPart); \
\
/* val(loPart) < val(lo) */ \
/* val(hiPart) > val(lo) */ \
} \
\
/* val(i) <= val(lo) for lo <= i <= hiPart */ \
/* val(i) == val(lo) for hiPart < i < loPart */ \
/* val(i) >= val(lo) for loPart <= i <= hi */ \
\
/* Put the partitioning element in place */ \
SWAP(*lo, *hiPart); \
\
/* val(i) <= val(hiPart) for lo <= i < hiPart */ \
/* val(i) == val(lo) for hiPart <= i < loPart */ \
/* val(i) >= val(hiPart) for loPart <= i < hi */ \
\
/* Sort the subarrays [lo, hiPart-1] and [loPart, hi]. */ \
/* We sort the smaller one first to minimize stack usage. */ \
if (hiPart - lo >= hi - loPart) { \
if (lo + 1 < hiPart) { \
/* Store the bigger subarray */ \
loStack[stackPos] = lo; \
hiStack[stackPos] = hiPart; \
++stackPos; \
} \
if (loPart + 1 < hi) { \
/* Sort the smaller subarray */ \
lo = loPart; \
continue; \
} \
} \
else { \
if (loPart + 1 < hi) { \
/* Store the bigger subarray */ \
loStack[stackPos] = loPart; \
hiStack[stackPos] = hi; \
++stackPos; \
} \
if (lo + 1 < hiPart) { \
/* Sort the smaller subarray */ \
hi = hiPart; \
continue; \
} \
} \
\
/* Pop the next subarray off the stack */ \
if (stackPos--) { \
lo = loStack[stackPos]; \
hi = hiStack[stackPos]; \
continue; \
} \
\
break; \
} \
} \
}
/****************************************************************************
*
* BSEARCH
*
* This macro binary searches a sorted array to find an existing entry or
* the position where a TRACKED_NEW entry should be placed. It returns the index of
* the first entry for which the expression is false (zero or negative), or
* count if the expression is true (positive) for all entries.
*
* Typically the expression will return:
* > 0 if (sortKey > elem)
* <= 0 if (sortKey <= elem)
*
* The final parameter to the macro is the address of a variable which is
* filled with the resulting index.
*
***/
//===========================================================================
#define BSEARCH(T, ptr, count, expr, addrOfIndex) { \
\
const T * low = (ptr); \
const T * high = (ptr) + (count); /* first entry for which */ \
/* expr is false */ \
\
if (low != high) \
for (;;) { \
const T & elem = *(low + (high - low) / 2); \
int result = (expr); \
if (result > 0) { \
if (&elem == low) \
break; \
low = &elem; \
} \
else { \
high = &elem; \
if (&elem == low) \
break; \
} \
} \
\
*(addrOfIndex) = high - (ptr); \
\
}

View File

@ -1,151 +1,151 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
CBaseSpareList::CBaseSpareList ()
: m_allocHead(nil),
m_spareHead(nil),
m_chunkSize(0)
{
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects = 0;
#endif
}
//===========================================================================
void * CBaseSpareList::Alloc (unsigned objectSize, const char typeName[]) {
// if there aren't any spare nodes available then make more
if (!m_spareHead)
GrowSpareList(objectSize, typeName);
// dequeue the head of the spare list
void * const object = m_spareHead;
m_spareHead = m_spareHead->spareNext;
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects++;
#endif
// initialize memory to a freaky value in debug mode
#ifdef HS_DEBUGGING
MemSet(object, (byte) ((unsigned) object >> 4), objectSize);
#endif
return object;
}
//===========================================================================
void CBaseSpareList::Free (void * object, unsigned objectSize) {
// initialize memory to a freaky value in debug mode
#ifdef HS_DEBUGGING
MemSet(object, (byte) ((unsigned) object >> 4), objectSize);
#endif
// link memory block onto head of spare list
((SpareNode *) object)->spareNext = m_spareHead;
m_spareHead = (SpareNode *) object;
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects--;
#endif
}
//===========================================================================
void CBaseSpareList::GrowSpareList (unsigned objectSize, const char typeName[]) {
// Grow the allocation by a substantial amount each time
// to reduce the time spent in memory managament
m_chunkSize *= 2;
const unsigned MIN_ALLOC = max(1, 256/objectSize);
const unsigned MAX_ALLOC = max(512, 32*1024/objectSize);
if (m_chunkSize < MIN_ALLOC)
m_chunkSize = MIN_ALLOC;
else if (m_chunkSize > MAX_ALLOC)
m_chunkSize = MAX_ALLOC;
// allocate a block of memory to hold a bunch
// of T-objects, but allocate them as "raw" memory
AllocNode * allocNode = (AllocNode *) MemAlloc(
sizeof(AllocNode) + objectSize * m_chunkSize,
0, // flags
typeName, // file
0 // line
);
// link allocation onto head of allocation list
allocNode->allocNext = m_allocHead;
m_allocHead = allocNode;
// chain newly created raw memory units together onto the spare list
SpareNode * spareCurr = (SpareNode *) (allocNode + 1);
SpareNode * spareEnd = (SpareNode *) ((byte *) spareCurr + objectSize * m_chunkSize);
do {
spareCurr->spareNext = m_spareHead;
m_spareHead = spareCurr;
spareCurr = (SpareNode *) ((byte *) spareCurr + objectSize);
} while (spareCurr < spareEnd);
}
//===========================================================================
void CBaseSpareList::CleanUp (const char typeName[]) {
// warn of resource leaks
#ifdef SPARELIST_TRACK_MEMORY
if (m_unfreedObjects && !ErrorGetOption(kErrOptDisableMemLeakChecking)) {
#ifdef CLIENT
{
char buffer[256];
StrPrintf(buffer, arrsize(buffer), "Memory leak: %s", typeName);
FATAL(buffer);
}
#else
{
DEBUG_MSG("Memory leak: %s", typeName);
}
#endif
}
#endif
// walk chain of AllocNodes and free each of them
while (m_allocHead) {
AllocNode * allocNext = m_allocHead->allocNext;
FREE(m_allocHead);
m_allocHead = allocNext;
}
m_spareHead = nil;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/****************************************************************************
*
* Exported functions
*
***/
//===========================================================================
CBaseSpareList::CBaseSpareList ()
: m_allocHead(nil),
m_spareHead(nil),
m_chunkSize(0)
{
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects = 0;
#endif
}
//===========================================================================
void * CBaseSpareList::Alloc (unsigned objectSize, const char typeName[]) {
// if there aren't any spare nodes available then make more
if (!m_spareHead)
GrowSpareList(objectSize, typeName);
// dequeue the head of the spare list
void * const object = m_spareHead;
m_spareHead = m_spareHead->spareNext;
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects++;
#endif
// initialize memory to a freaky value in debug mode
#ifdef HS_DEBUGGING
MemSet(object, (byte) ((unsigned) object >> 4), objectSize);
#endif
return object;
}
//===========================================================================
void CBaseSpareList::Free (void * object, unsigned objectSize) {
// initialize memory to a freaky value in debug mode
#ifdef HS_DEBUGGING
MemSet(object, (byte) ((unsigned) object >> 4), objectSize);
#endif
// link memory block onto head of spare list
((SpareNode *) object)->spareNext = m_spareHead;
m_spareHead = (SpareNode *) object;
#ifdef SPARELIST_TRACK_MEMORY
m_unfreedObjects--;
#endif
}
//===========================================================================
void CBaseSpareList::GrowSpareList (unsigned objectSize, const char typeName[]) {
// Grow the allocation by a substantial amount each time
// to reduce the time spent in memory managament
m_chunkSize *= 2;
const unsigned MIN_ALLOC = max(1, 256/objectSize);
const unsigned MAX_ALLOC = max(512, 32*1024/objectSize);
if (m_chunkSize < MIN_ALLOC)
m_chunkSize = MIN_ALLOC;
else if (m_chunkSize > MAX_ALLOC)
m_chunkSize = MAX_ALLOC;
// allocate a block of memory to hold a bunch
// of T-objects, but allocate them as "raw" memory
AllocNode * allocNode = (AllocNode *) MemAlloc(
sizeof(AllocNode) + objectSize * m_chunkSize,
0, // flags
typeName, // file
0 // line
);
// link allocation onto head of allocation list
allocNode->allocNext = m_allocHead;
m_allocHead = allocNode;
// chain newly created raw memory units together onto the spare list
SpareNode * spareCurr = (SpareNode *) (allocNode + 1);
SpareNode * spareEnd = (SpareNode *) ((byte *) spareCurr + objectSize * m_chunkSize);
do {
spareCurr->spareNext = m_spareHead;
m_spareHead = spareCurr;
spareCurr = (SpareNode *) ((byte *) spareCurr + objectSize);
} while (spareCurr < spareEnd);
}
//===========================================================================
void CBaseSpareList::CleanUp (const char typeName[]) {
// warn of resource leaks
#ifdef SPARELIST_TRACK_MEMORY
if (m_unfreedObjects && !ErrorGetOption(kErrOptDisableMemLeakChecking)) {
#ifdef CLIENT
{
char buffer[256];
StrPrintf(buffer, arrsize(buffer), "Memory leak: %s", typeName);
FATAL(buffer);
}
#else
{
DEBUG_MSG("Memory leak: %s", typeName);
}
#endif
}
#endif
// walk chain of AllocNodes and free each of them
while (m_allocHead) {
AllocNode * allocNext = m_allocHead->allocNext;
FREE(m_allocHead);
m_allocHead = allocNext;
}
m_spareHead = nil;
}

View File

@ -1,131 +1,131 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSPARELIST_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSPARELIST_H
#ifdef HS_DEBUGGING
#define SPARELIST_TRACK_MEMORY
#endif
/****************************************************************************
*
* CBaseSpareList
*
***/
class CBaseSpareList {
public:
CBaseSpareList ();
protected:
struct SpareNode {
SpareNode * spareNext;
};
SpareNode * m_spareHead;
void * Alloc (unsigned objectSize, const char typeName[]);
void CleanUp (const char typeName[]);
void Free (void * object, unsigned objectSize);
private:
union AllocNode {
AllocNode * allocNext;
qword align;
};
AllocNode * m_allocHead;
unsigned m_chunkSize;
#ifdef SPARELIST_TRACK_MEMORY
unsigned m_unfreedObjects;
#endif
void GrowSpareList (unsigned objectSize, const char typeName[]);
};
/****************************************************************************
*
* TSpareList
*
***/
template<class T>
class TSpareList : public CBaseSpareList {
private:
enum { OBJECT_SIZE = MAX(sizeof(T), sizeof(SpareNode)) };
public:
~TSpareList () { CleanUp(); }
void * Alloc ();
void CleanUp ();
void Delete (T * node);
void Free (T * node);
T * New ();
};
//===========================================================================
template<class T>
void * TSpareList<T>::Alloc () {
return CBaseSpareList::Alloc(OBJECT_SIZE, typeid(T).raw_name());
}
//===========================================================================
template<class T>
void TSpareList<T>::CleanUp () {
CBaseSpareList::CleanUp(typeid(T).raw_name());
}
//===========================================================================
template<class T>
void TSpareList<T>::Delete (T * node) {
node->~T();
CBaseSpareList::Free(node, OBJECT_SIZE);
}
//===========================================================================
template<class T>
void TSpareList<T>::Free (T * node) {
CBaseSpareList::Free(node, OBJECT_SIZE);
}
//===========================================================================
template<class T>
T * TSpareList<T>::New () {
return new(CBaseSpareList::Alloc(OBJECT_SIZE, typeid(T).raw_name())) T;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSPARELIST_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSpareList.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSPARELIST_H
#ifdef HS_DEBUGGING
#define SPARELIST_TRACK_MEMORY
#endif
/****************************************************************************
*
* CBaseSpareList
*
***/
class CBaseSpareList {
public:
CBaseSpareList ();
protected:
struct SpareNode {
SpareNode * spareNext;
};
SpareNode * m_spareHead;
void * Alloc (unsigned objectSize, const char typeName[]);
void CleanUp (const char typeName[]);
void Free (void * object, unsigned objectSize);
private:
union AllocNode {
AllocNode * allocNext;
qword align;
};
AllocNode * m_allocHead;
unsigned m_chunkSize;
#ifdef SPARELIST_TRACK_MEMORY
unsigned m_unfreedObjects;
#endif
void GrowSpareList (unsigned objectSize, const char typeName[]);
};
/****************************************************************************
*
* TSpareList
*
***/
template<class T>
class TSpareList : public CBaseSpareList {
private:
enum { OBJECT_SIZE = MAX(sizeof(T), sizeof(SpareNode)) };
public:
~TSpareList () { CleanUp(); }
void * Alloc ();
void CleanUp ();
void Delete (T * node);
void Free (T * node);
T * New ();
};
//===========================================================================
template<class T>
void * TSpareList<T>::Alloc () {
return CBaseSpareList::Alloc(OBJECT_SIZE, typeid(T).raw_name());
}
//===========================================================================
template<class T>
void TSpareList<T>::CleanUp () {
CBaseSpareList::CleanUp(typeid(T).raw_name());
}
//===========================================================================
template<class T>
void TSpareList<T>::Delete (T * node) {
node->~T();
CBaseSpareList::Free(node, OBJECT_SIZE);
}
//===========================================================================
template<class T>
void TSpareList<T>::Free (T * node) {
CBaseSpareList::Free(node, OBJECT_SIZE);
}
//===========================================================================
template<class T>
T * TSpareList<T>::New () {
return new(CBaseSpareList::Alloc(OBJECT_SIZE, typeid(T).raw_name())) T;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,140 +1,140 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtStr.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSTR_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtStr.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSTR_H
/*****************************************************************************
*
* String functions
*
***/
inline char CharLowerFast (char ch) { return ((ch >= 'A') && (ch <= 'Z')) ? (char )(ch + 'a' - 'A') : ch; }
inline wchar CharLowerFast (wchar ch) { return ((ch >= L'A') && (ch <= L'Z')) ? (wchar)(ch + L'a' - L'A') : ch; }
inline char CharUpperFast (char ch) { return ((ch >= 'a') && (ch <= 'z')) ? (char )(ch + 'A' - 'a') : ch; }
inline wchar CharUpperFast (wchar ch) { return ((ch >= L'a') && (ch <= L'z')) ? (wchar)(ch + L'A' - L'a') : ch; }
unsigned StrBytes (const char str[]); // includes space for terminator
unsigned StrBytes (const wchar str[]); // includes space for terminator
char * StrChr (char * str, char ch, unsigned chars = (unsigned)-1);
wchar * StrChr (wchar * str, wchar ch, unsigned chars = (unsigned)-1);
const char * StrChr (const char str[], char ch, unsigned chars = (unsigned)-1);
const wchar * StrChr (const wchar str[], wchar ch, unsigned chars = (unsigned)-1);
unsigned StrPrintf (char * dest, unsigned count, const char format[], ...);
unsigned StrPrintf (wchar * dest, unsigned count, const wchar format[], ...);
unsigned StrPrintfV (char * dest, unsigned count, const char format[], va_list args);
unsigned StrPrintfV (wchar * dest, unsigned count, const wchar format[], va_list args);
unsigned StrLen (const char str[]);
unsigned StrLen (const wchar str[]);
char * StrDup (const char str[]);
wchar * StrDup (const wchar str[]);
char * StrDupLen (const char str[], unsigned chars);
wchar * StrDupLen (const wchar str[], unsigned chars);
wchar * StrDupToUnicode (const char str[]);
char * StrDupToAnsi (const wchar str[]);
int StrCmp (const char str1[], const char str2[], unsigned chars = (unsigned)-1);
int StrCmp (const wchar str1[], const wchar str2[], unsigned chars = (unsigned)-1);
int StrCmpI (const char str1[], const char str2[], unsigned chars = (unsigned)-1);
int StrCmpI (const wchar str1[], const wchar str2[], unsigned chars = (unsigned)-1);
char * StrStr (char * source, const char match[]);
const char * StrStr (const char source[], const char match[]);
wchar * StrStr (wchar * source, const wchar match[]);
const wchar * StrStr (const wchar source[], const wchar match[]);
char * StrStrI (char * source, const char match[]);
const char * StrStrI (const char source[], const char match[]);
wchar * StrStrI (wchar * source, const wchar match[]);
const wchar * StrStrI (const wchar source[], const wchar match[]);
char * StrChrR (char * str, char ch);
wchar * StrChrR (wchar * str, wchar ch);
const char * StrChrR (const char str[], char ch);
const wchar * StrChrR (const wchar str[], wchar ch);
void StrCopy (char * dest, const char source[], unsigned chars);
void StrCopy (wchar * dest, const wchar source[], unsigned chars);
unsigned StrCopyLen (char * dest, const char source[], unsigned chars);
unsigned StrCopyLen (wchar * dest, const wchar source[], unsigned chars);
void StrPack (char * dest, const char source[], unsigned chars);
void StrPack (wchar * dest, const wchar source[], unsigned chars);
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars);
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars, unsigned codePage);
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars);
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars, unsigned codePage);
unsigned StrUnicodeToUtf8 (char * dest, const wchar source[], unsigned destChars);
unsigned StrUtf8ToUnicode (wchar * dest, const char source[], unsigned destChars);
float StrToFloat (const char source[], const char ** endptr);
float StrToFloat (const wchar source[], const wchar ** endptr);
int StrToInt (const char source[], const char ** endptr);
int StrToInt (const wchar source[], const wchar ** endptr);
unsigned StrToUnsigned (char source[], char ** endptr, int radix);
unsigned StrToUnsigned (wchar source[], wchar ** endptr, int radix);
unsigned StrToUnsigned (const char source[], const char ** endptr, int radix);
unsigned StrToUnsigned (const wchar source[], const wchar ** endptr, int radix);
void StrLower (char * dest, unsigned chars = (unsigned) -1);
void StrLower (wchar * dest, unsigned chars = (unsigned) -1);
void StrLower (char * dest, const char source[], unsigned chars);
void StrLower (wchar * dest, const wchar source[], unsigned chars);
dword StrHash (const char str[], unsigned chars = (unsigned)-1);
dword StrHash (const wchar str[], unsigned chars = (unsigned)-1);
dword StrHashI (const char str[], unsigned chars = (unsigned)-1);
dword StrHashI (const wchar str[], unsigned chars = (unsigned)-1);
bool StrTokenize (const char * source[], char * dest, unsigned chars, const char whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
bool StrTokenize (const wchar * source[], wchar * dest, unsigned chars, const wchar whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
bool StrTokenize (const char * source[], ARRAY(char) * destArray, const char whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
bool StrTokenize (const wchar * source[], ARRAY(wchar) * destArray, const wchar whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtStr.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSTR_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtStr.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSTR_H
/*****************************************************************************
*
* String functions
*
***/
inline char CharLowerFast (char ch) { return ((ch >= 'A') && (ch <= 'Z')) ? (char )(ch + 'a' - 'A') : ch; }
inline wchar CharLowerFast (wchar ch) { return ((ch >= L'A') && (ch <= L'Z')) ? (wchar)(ch + L'a' - L'A') : ch; }
inline char CharUpperFast (char ch) { return ((ch >= 'a') && (ch <= 'z')) ? (char )(ch + 'A' - 'a') : ch; }
inline wchar CharUpperFast (wchar ch) { return ((ch >= L'a') && (ch <= L'z')) ? (wchar)(ch + L'A' - L'a') : ch; }
unsigned StrBytes (const char str[]); // includes space for terminator
unsigned StrBytes (const wchar str[]); // includes space for terminator
char * StrChr (char * str, char ch, unsigned chars = (unsigned)-1);
wchar * StrChr (wchar * str, wchar ch, unsigned chars = (unsigned)-1);
const char * StrChr (const char str[], char ch, unsigned chars = (unsigned)-1);
const wchar * StrChr (const wchar str[], wchar ch, unsigned chars = (unsigned)-1);
unsigned StrPrintf (char * dest, unsigned count, const char format[], ...);
unsigned StrPrintf (wchar * dest, unsigned count, const wchar format[], ...);
unsigned StrPrintfV (char * dest, unsigned count, const char format[], va_list args);
unsigned StrPrintfV (wchar * dest, unsigned count, const wchar format[], va_list args);
unsigned StrLen (const char str[]);
unsigned StrLen (const wchar str[]);
char * StrDup (const char str[]);
wchar * StrDup (const wchar str[]);
char * StrDupLen (const char str[], unsigned chars);
wchar * StrDupLen (const wchar str[], unsigned chars);
wchar * StrDupToUnicode (const char str[]);
char * StrDupToAnsi (const wchar str[]);
int StrCmp (const char str1[], const char str2[], unsigned chars = (unsigned)-1);
int StrCmp (const wchar str1[], const wchar str2[], unsigned chars = (unsigned)-1);
int StrCmpI (const char str1[], const char str2[], unsigned chars = (unsigned)-1);
int StrCmpI (const wchar str1[], const wchar str2[], unsigned chars = (unsigned)-1);
char * StrStr (char * source, const char match[]);
const char * StrStr (const char source[], const char match[]);
wchar * StrStr (wchar * source, const wchar match[]);
const wchar * StrStr (const wchar source[], const wchar match[]);
char * StrStrI (char * source, const char match[]);
const char * StrStrI (const char source[], const char match[]);
wchar * StrStrI (wchar * source, const wchar match[]);
const wchar * StrStrI (const wchar source[], const wchar match[]);
char * StrChrR (char * str, char ch);
wchar * StrChrR (wchar * str, wchar ch);
const char * StrChrR (const char str[], char ch);
const wchar * StrChrR (const wchar str[], wchar ch);
void StrCopy (char * dest, const char source[], unsigned chars);
void StrCopy (wchar * dest, const wchar source[], unsigned chars);
unsigned StrCopyLen (char * dest, const char source[], unsigned chars);
unsigned StrCopyLen (wchar * dest, const wchar source[], unsigned chars);
void StrPack (char * dest, const char source[], unsigned chars);
void StrPack (wchar * dest, const wchar source[], unsigned chars);
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars);
unsigned StrToAnsi (char * dest, const wchar source[], unsigned destChars, unsigned codePage);
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars);
unsigned StrToUnicode (wchar * dest, const char source[], unsigned destChars, unsigned codePage);
unsigned StrUnicodeToUtf8 (char * dest, const wchar source[], unsigned destChars);
unsigned StrUtf8ToUnicode (wchar * dest, const char source[], unsigned destChars);
float StrToFloat (const char source[], const char ** endptr);
float StrToFloat (const wchar source[], const wchar ** endptr);
int StrToInt (const char source[], const char ** endptr);
int StrToInt (const wchar source[], const wchar ** endptr);
unsigned StrToUnsigned (char source[], char ** endptr, int radix);
unsigned StrToUnsigned (wchar source[], wchar ** endptr, int radix);
unsigned StrToUnsigned (const char source[], const char ** endptr, int radix);
unsigned StrToUnsigned (const wchar source[], const wchar ** endptr, int radix);
void StrLower (char * dest, unsigned chars = (unsigned) -1);
void StrLower (wchar * dest, unsigned chars = (unsigned) -1);
void StrLower (char * dest, const char source[], unsigned chars);
void StrLower (wchar * dest, const wchar source[], unsigned chars);
dword StrHash (const char str[], unsigned chars = (unsigned)-1);
dword StrHash (const wchar str[], unsigned chars = (unsigned)-1);
dword StrHashI (const char str[], unsigned chars = (unsigned)-1);
dword StrHashI (const wchar str[], unsigned chars = (unsigned)-1);
bool StrTokenize (const char * source[], char * dest, unsigned chars, const char whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
bool StrTokenize (const wchar * source[], wchar * dest, unsigned chars, const wchar whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
bool StrTokenize (const char * source[], ARRAY(char) * destArray, const char whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);
bool StrTokenize (const wchar * source[], ARRAY(wchar) * destArray, const wchar whitespace[], unsigned maxWhitespaceSkipCount = (unsigned)-1);

View File

@ -1,286 +1,286 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSubst.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
#define SUBST_BLOCK SubstParsedData<chartype>::SubstBlock<chartype>
/*****************************************************************************
*
* Internal functions
*
***/
//============================================================================
template <typename chartype>
bool IVarSubstitute (
ARRAY(chartype) * dst,
const chartype src[],
unsigned varCount,
const chartype * varNames[], // [varCount]
const chartype * varValues[] // [varCount]
) {
ASSERT(dst);
ASSERT(src);
ASSERT(varNames);
ASSERT(varValues);
dst->Reserve(StrLen(src) * 5/4);
bool result = true;
while (*src) {
// Copy non-substituted strings and escape %% symbols
if ((*src != L'%') || (*++src == L'%')) {
dst->Push(*src++);
continue;
}
// Find variable definition
const chartype * varStart = src;
const chartype * varEnd = StrChr(varStart, L'%');
if (!varEnd) {
// Skip % character and continue
result = false;
continue;
}
// Validate variable name length
chartype varBuffer[256];
if (varEnd - varStart >= arrsize(varBuffer)) {
result = false;
src = varEnd + 1;
continue;
}
// Copy variable name excluding trailing '%'
StrCopy(varBuffer, varStart, varEnd - varStart + 1);
src = varEnd + 1;
// Find the variable value and perform substitution
bool found = false;
for (unsigned i = 0; i < varCount; ++i) {
if (StrCmp(varBuffer, varNames[i]))
continue;
dst->Add(varValues[i], StrLen(varValues[i]));
found = true;
break;
}
// Check that variable definition exists
result = result && found;
}
// Terminate string
dst->Push(0);
return result;
}
//============================================================================
template <typename chartype>
bool IParseForSubst (
SubstParsedData<chartype> * dest,
const chartype src[]
) {
const chartype * current = src;
bool result = true;
while (*current) {
// Copy non-substituted strings and escape %% symbols
if ((*current != L'%') || (*++current == L'%')) {
current++;
continue;
}
// Find variable definition
const chartype * varStart = current;
const chartype * varEnd = StrChr(varStart, L'%');
if (!varEnd) {
// Skip % character and continue
result = false;
continue;
}
// We've found a variable, copy the current data to a new object
if (current != src) {
int strLen = (current - src) - 1;
SUBST_BLOCK * block = NEW(SUBST_BLOCK);
block->isVar = false;
block->strLen = strLen;
block->data = (chartype*)ALLOCZERO((strLen + 1) * sizeof(chartype));
MemCopy(block->data, src, strLen * sizeof(chartype));
dest->blocks.Add(block);
}
// Validate variable name length
chartype varBuffer[256];
if (varEnd - varStart >= arrsize(varBuffer)) {
result = false;
src = current = varEnd + 1;
continue;
}
// Copy variable name excluding trailing '%'
int strLen = (varEnd - varStart);
SUBST_BLOCK * block = NEW(SUBST_BLOCK);
block->isVar = true;
block->strLen = strLen;
block->data = (chartype*)ALLOCZERO((strLen + 1) * sizeof(chartype));
MemCopy(block->data, varStart, strLen * sizeof(chartype));
dest->blocks.Add(block);
src = current = varEnd + 1;
}
// Check and see if there's any data remaining
if (current != src) {
int strLen = (current - src);
SUBST_BLOCK * block = NEW(SUBST_BLOCK);
block->isVar = false;
block->strLen = strLen;
block->data = (chartype*)ALLOCZERO((strLen + 1) * sizeof(chartype));
MemCopy(block->data, src, strLen * sizeof(chartype));
dest->blocks.Add(block);
}
return result;
}
//============================================================================
template <typename chartype>
bool IVarSubstPreParsed (
ARRAY(chartype) * dst,
const SubstParsedData<chartype> * src,
unsigned varCount,
const chartype * varNames[], // [varCount]
const chartype * varValues[] // [varCount]
) {
unsigned approxTotalSize = 0;
for (unsigned i = 0; i < src->blocks.Count(); ++i) {
approxTotalSize += src->blocks[i]->strLen;
}
dst->Reserve(approxTotalSize * 5/4);
bool foundAll = true;
for (unsigned blockIndex = 0; blockIndex < src->blocks.Count(); ++blockIndex) {
SUBST_BLOCK * block = src->blocks[blockIndex];
if (block->isVar) {
bool found = false;
for (unsigned varIndex = 0; varIndex < varCount; ++varIndex) {
if (StrCmp(block->data, varNames[varIndex])) {
continue;
}
dst->Add(varValues[varIndex], StrLen(varValues[varIndex]));
found = true;
break;
}
foundAll &= found;
}
else {
dst->Add(block->data, block->strLen);
}
}
dst->Push(0);
return foundAll;
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
bool ParseForSubst (
SubstParsedData<wchar> * dest,
const wchar src[]
) {
return IParseForSubst(dest, src);
}
//============================================================================
bool ParseForSubst (
SubstParsedData<char> * dest,
const char src[]
) {
return IParseForSubst(dest, src);
}
//============================================================================
bool VarSubstitute (
ARRAY(wchar) * dst,
const wchar src[],
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
) {
return IVarSubstitute(dst, src, varCount, varNames, varValues);
}
//============================================================================
bool VarSubstitute (
ARRAY(char) * dst,
const char src[],
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
) {
return IVarSubstitute(dst, src, varCount, varNames, varValues);
}
//============================================================================
bool VarSubstitute (
ARRAY(wchar) * dst,
const SubstParsedData<wchar> * src,
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
) {
return IVarSubstPreParsed(dst, src, varCount, varNames, varValues);
}
//============================================================================
bool VarSubstitute (
ARRAY(char) * dst,
const SubstParsedData<char> * src,
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
) {
return IVarSubstPreParsed(dst, src, varCount, varNames, varValues);
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSubst.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
#define SUBST_BLOCK SubstParsedData<chartype>::SubstBlock<chartype>
/*****************************************************************************
*
* Internal functions
*
***/
//============================================================================
template <typename chartype>
bool IVarSubstitute (
ARRAY(chartype) * dst,
const chartype src[],
unsigned varCount,
const chartype * varNames[], // [varCount]
const chartype * varValues[] // [varCount]
) {
ASSERT(dst);
ASSERT(src);
ASSERT(varNames);
ASSERT(varValues);
dst->Reserve(StrLen(src) * 5/4);
bool result = true;
while (*src) {
// Copy non-substituted strings and escape %% symbols
if ((*src != L'%') || (*++src == L'%')) {
dst->Push(*src++);
continue;
}
// Find variable definition
const chartype * varStart = src;
const chartype * varEnd = StrChr(varStart, L'%');
if (!varEnd) {
// Skip % character and continue
result = false;
continue;
}
// Validate variable name length
chartype varBuffer[256];
if (varEnd - varStart >= arrsize(varBuffer)) {
result = false;
src = varEnd + 1;
continue;
}
// Copy variable name excluding trailing '%'
StrCopy(varBuffer, varStart, varEnd - varStart + 1);
src = varEnd + 1;
// Find the variable value and perform substitution
bool found = false;
for (unsigned i = 0; i < varCount; ++i) {
if (StrCmp(varBuffer, varNames[i]))
continue;
dst->Add(varValues[i], StrLen(varValues[i]));
found = true;
break;
}
// Check that variable definition exists
result = result && found;
}
// Terminate string
dst->Push(0);
return result;
}
//============================================================================
template <typename chartype>
bool IParseForSubst (
SubstParsedData<chartype> * dest,
const chartype src[]
) {
const chartype * current = src;
bool result = true;
while (*current) {
// Copy non-substituted strings and escape %% symbols
if ((*current != L'%') || (*++current == L'%')) {
current++;
continue;
}
// Find variable definition
const chartype * varStart = current;
const chartype * varEnd = StrChr(varStart, L'%');
if (!varEnd) {
// Skip % character and continue
result = false;
continue;
}
// We've found a variable, copy the current data to a new object
if (current != src) {
int strLen = (current - src) - 1;
SUBST_BLOCK * block = NEW(SUBST_BLOCK);
block->isVar = false;
block->strLen = strLen;
block->data = (chartype*)ALLOCZERO((strLen + 1) * sizeof(chartype));
MemCopy(block->data, src, strLen * sizeof(chartype));
dest->blocks.Add(block);
}
// Validate variable name length
chartype varBuffer[256];
if (varEnd - varStart >= arrsize(varBuffer)) {
result = false;
src = current = varEnd + 1;
continue;
}
// Copy variable name excluding trailing '%'
int strLen = (varEnd - varStart);
SUBST_BLOCK * block = NEW(SUBST_BLOCK);
block->isVar = true;
block->strLen = strLen;
block->data = (chartype*)ALLOCZERO((strLen + 1) * sizeof(chartype));
MemCopy(block->data, varStart, strLen * sizeof(chartype));
dest->blocks.Add(block);
src = current = varEnd + 1;
}
// Check and see if there's any data remaining
if (current != src) {
int strLen = (current - src);
SUBST_BLOCK * block = NEW(SUBST_BLOCK);
block->isVar = false;
block->strLen = strLen;
block->data = (chartype*)ALLOCZERO((strLen + 1) * sizeof(chartype));
MemCopy(block->data, src, strLen * sizeof(chartype));
dest->blocks.Add(block);
}
return result;
}
//============================================================================
template <typename chartype>
bool IVarSubstPreParsed (
ARRAY(chartype) * dst,
const SubstParsedData<chartype> * src,
unsigned varCount,
const chartype * varNames[], // [varCount]
const chartype * varValues[] // [varCount]
) {
unsigned approxTotalSize = 0;
for (unsigned i = 0; i < src->blocks.Count(); ++i) {
approxTotalSize += src->blocks[i]->strLen;
}
dst->Reserve(approxTotalSize * 5/4);
bool foundAll = true;
for (unsigned blockIndex = 0; blockIndex < src->blocks.Count(); ++blockIndex) {
SUBST_BLOCK * block = src->blocks[blockIndex];
if (block->isVar) {
bool found = false;
for (unsigned varIndex = 0; varIndex < varCount; ++varIndex) {
if (StrCmp(block->data, varNames[varIndex])) {
continue;
}
dst->Add(varValues[varIndex], StrLen(varValues[varIndex]));
found = true;
break;
}
foundAll &= found;
}
else {
dst->Add(block->data, block->strLen);
}
}
dst->Push(0);
return foundAll;
}
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
bool ParseForSubst (
SubstParsedData<wchar> * dest,
const wchar src[]
) {
return IParseForSubst(dest, src);
}
//============================================================================
bool ParseForSubst (
SubstParsedData<char> * dest,
const char src[]
) {
return IParseForSubst(dest, src);
}
//============================================================================
bool VarSubstitute (
ARRAY(wchar) * dst,
const wchar src[],
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
) {
return IVarSubstitute(dst, src, varCount, varNames, varValues);
}
//============================================================================
bool VarSubstitute (
ARRAY(char) * dst,
const char src[],
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
) {
return IVarSubstitute(dst, src, varCount, varNames, varValues);
}
//============================================================================
bool VarSubstitute (
ARRAY(wchar) * dst,
const SubstParsedData<wchar> * src,
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
) {
return IVarSubstPreParsed(dst, src, varCount, varNames, varValues);
}
//============================================================================
bool VarSubstitute (
ARRAY(char) * dst,
const SubstParsedData<char> * src,
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
) {
return IVarSubstPreParsed(dst, src, varCount, varNames, varValues);
}

View File

@ -1,103 +1,103 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSubst.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSUBST_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSubst.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSUBST_H
template<typename chartype>
struct SubstParsedData {
template<typename chartype>
struct SubstBlock {
bool isVar;
chartype * data;
unsigned strLen;
SubstBlock()
: isVar(false)
, data(nil)
{
}
~SubstBlock() {
FREE(data);
}
};
ARRAY(SubstBlock<chartype>*) blocks;
~SubstParsedData() {
for (unsigned i = 0; i < blocks.Count(); ++i) {
SubstBlock<chartype> * block = blocks[i];
DEL(block);
}
}
};
bool ParseForSubst (
SubstParsedData<wchar> * dest,
const wchar src[]
);
bool ParseForSubst (
SubstParsedData<char> * dest,
const char src[]
);
// Return value is for validation purposes only; it may be ignored
bool VarSubstitute (
ARRAY(wchar) * dst,
const wchar src[],
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
);
bool VarSubstitute (
ARRAY(char) * dst,
const char src[],
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
);
bool VarSubstitute (
ARRAY(wchar) * dst,
const SubstParsedData<wchar> * src,
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
);
bool VarSubstitute (
ARRAY(char) * dst,
const SubstParsedData<char> * src,
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSubst.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSUBST_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSubst.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSUBST_H
template<typename chartype>
struct SubstParsedData {
template<typename chartype>
struct SubstBlock {
bool isVar;
chartype * data;
unsigned strLen;
SubstBlock()
: isVar(false)
, data(nil)
{
}
~SubstBlock() {
FREE(data);
}
};
ARRAY(SubstBlock<chartype>*) blocks;
~SubstParsedData() {
for (unsigned i = 0; i < blocks.Count(); ++i) {
SubstBlock<chartype> * block = blocks[i];
DEL(block);
}
}
};
bool ParseForSubst (
SubstParsedData<wchar> * dest,
const wchar src[]
);
bool ParseForSubst (
SubstParsedData<char> * dest,
const char src[]
);
// Return value is for validation purposes only; it may be ignored
bool VarSubstitute (
ARRAY(wchar) * dst,
const wchar src[],
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
);
bool VarSubstitute (
ARRAY(char) * dst,
const char src[],
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
);
bool VarSubstitute (
ARRAY(wchar) * dst,
const SubstParsedData<wchar> * src,
unsigned varCount,
const wchar * varNames[], // [varCount]
const wchar * varValues[] // [varCount]
);
bool VarSubstitute (
ARRAY(char) * dst,
const SubstParsedData<char> * src,
unsigned varCount,
const char * varNames[], // [varCount]
const char * varValues[] // [varCount]
);

View File

@ -1,118 +1,118 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSync.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSYNC_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSync.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSYNC_H
/****************************************************************************
*
* Atomic operations
*
***/
// *value += increment; return original value of *value; thread safe
long AtomicAdd (long * value, long increment);
// *value = value; return original value of *value; thread safe
long AtomicSet (long * value, long set);
#define ATOMIC_ONCE(code) { \
static long s_count = 1; \
if (AtomicSet(&s_count, 0)) \
code; \
} //
/****************************************************************************
*
* CLock
* (reader/writer lock)
*
***/
class CLockWaitSet;
class CLock {
private:
CLockWaitSet * m_waitSet;
long m_spinLock;
unsigned m_readerCount;
unsigned m_writerCount;
public:
CLock ();
~CLock ();
void EnterRead ();
void EnterWrite ();
void LeaveRead ();
void LeaveWrite ();
};
/*****************************************************************************
*
* CEvent
*
***/
#ifdef HS_BUILD_FOR_WIN32
typedef HANDLE EventHandle;
#else
# error "CEvent: Not implemented on this platform"
#endif
const unsigned kEventWaitForever = (unsigned)-1;
enum ECEventResetBehavior {
kEventManualReset,
kEventAutoReset,
};
class CEvent {
EventHandle m_handle;
public:
CEvent (
ECEventResetBehavior resetType,
bool initialSet = false
);
~CEvent ();
void Signal ();
void Reset ();
bool Wait (unsigned waitMs);
const EventHandle & Handle () const { return m_handle; }
};
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSync.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSYNC_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtSync.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTSYNC_H
/****************************************************************************
*
* Atomic operations
*
***/
// *value += increment; return original value of *value; thread safe
long AtomicAdd (long * value, long increment);
// *value = value; return original value of *value; thread safe
long AtomicSet (long * value, long set);
#define ATOMIC_ONCE(code) { \
static long s_count = 1; \
if (AtomicSet(&s_count, 0)) \
code; \
} //
/****************************************************************************
*
* CLock
* (reader/writer lock)
*
***/
class CLockWaitSet;
class CLock {
private:
CLockWaitSet * m_waitSet;
long m_spinLock;
unsigned m_readerCount;
unsigned m_writerCount;
public:
CLock ();
~CLock ();
void EnterRead ();
void EnterWrite ();
void LeaveRead ();
void LeaveWrite ();
};
/*****************************************************************************
*
* CEvent
*
***/
#ifdef HS_BUILD_FOR_WIN32
typedef HANDLE EventHandle;
#else
# error "CEvent: Not implemented on this platform"
#endif
const unsigned kEventWaitForever = (unsigned)-1;
enum ECEventResetBehavior {
kEventManualReset,
kEventAutoReset,
};
class CEvent {
EventHandle m_handle;
public:
CEvent (
ECEventResetBehavior resetType,
bool initialSet = false
);
~CEvent ();
void Signal ();
void Reset ();
bool Wait (unsigned waitMs);
const EventHandle & Handle () const { return m_handle; }
};

View File

@ -1,76 +1,76 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTime.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
void TimeGetElapsedDesc (
dword minutesElapsed,
TimeElapsedDesc * desc
) {
const unsigned kMinutesPerHour = 60;
const unsigned kMinutesPerDay = 1440;
const unsigned kMinutesPerWeek = 10080;
const unsigned kMinutesPerMonth = 43830;
const unsigned kMinutesPerYear = 525960;
dword & elapsed = minutesElapsed;
desc->years = (elapsed / kMinutesPerYear); elapsed -= desc->years * kMinutesPerYear;
desc->months = (elapsed / kMinutesPerMonth); elapsed -= desc->months * kMinutesPerMonth;
desc->weeks = (elapsed / kMinutesPerWeek); elapsed -= desc->weeks * kMinutesPerWeek;
desc->days = (elapsed / kMinutesPerDay); elapsed -= desc->days * kMinutesPerDay;
desc->hours = (elapsed / kMinutesPerHour); elapsed -= desc->hours * kMinutesPerHour;
desc->minutes = elapsed;
}
//============================================================================
dword TimeGetSecondsSince2001Utc () {
qword time = TimeGetTime();
dword seconds = (dword)((time - kTime1601To2001) / kTimeIntervalsPerSecond);
return seconds;
}
//============================================================================
dword TimeGetSecondsSince1970Utc () {
qword time = TimeGetTime();
dword seconds = (dword)((time - kTime1601To1970) / kTimeIntervalsPerSecond);
return seconds;
}
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTime.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
//===========================================================================
void TimeGetElapsedDesc (
dword minutesElapsed,
TimeElapsedDesc * desc
) {
const unsigned kMinutesPerHour = 60;
const unsigned kMinutesPerDay = 1440;
const unsigned kMinutesPerWeek = 10080;
const unsigned kMinutesPerMonth = 43830;
const unsigned kMinutesPerYear = 525960;
dword & elapsed = minutesElapsed;
desc->years = (elapsed / kMinutesPerYear); elapsed -= desc->years * kMinutesPerYear;
desc->months = (elapsed / kMinutesPerMonth); elapsed -= desc->months * kMinutesPerMonth;
desc->weeks = (elapsed / kMinutesPerWeek); elapsed -= desc->weeks * kMinutesPerWeek;
desc->days = (elapsed / kMinutesPerDay); elapsed -= desc->days * kMinutesPerDay;
desc->hours = (elapsed / kMinutesPerHour); elapsed -= desc->hours * kMinutesPerHour;
desc->minutes = elapsed;
}
//============================================================================
dword TimeGetSecondsSince2001Utc () {
qword time = TimeGetTime();
dword seconds = (dword)((time - kTime1601To2001) / kTimeIntervalsPerSecond);
return seconds;
}
//============================================================================
dword TimeGetSecondsSince1970Utc () {
qword time = TimeGetTime();
dword seconds = (dword)((time - kTime1601To1970) / kTimeIntervalsPerSecond);
return seconds;
}

View File

@ -1,113 +1,113 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTime.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTIME_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTime.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTIME_H
/*****************************************************************************
*
* Time formatting functions
*
***/
struct TimeDesc {
unsigned year;
unsigned month; // [1, 12]
unsigned day;
unsigned dayOfWeek; // [0, 6]
unsigned hour; // [0, 23]
unsigned minute; // [0, 59]
unsigned second; // [0, 59]
};
struct TimeElapsedDesc {
unsigned years;
unsigned months; // [0, 12]
unsigned days; // [0, 7]
unsigned weeks; // [0, 6]
unsigned hours; // [0, 23]
unsigned minutes; // [0, 59]
};
void TimeGetDesc (
qword time,
TimeDesc * desc
);
void TimeGetElapsedDesc (
dword minutesElapsed,
TimeElapsedDesc * desc
);
void TimePrettyPrint (
qword time,
unsigned chars,
wchar * buffer
);
/*****************************************************************************
*
* Time query functions
*
***/
const qword kTimeIntervalsPerMs = 10000;
const qword kTimeIntervalsPerSecond = 1000 * kTimeIntervalsPerMs;
const qword kTimeIntervalsPerMinute = 60 * kTimeIntervalsPerSecond;
const qword kTimeIntervalsPerHour = 60 * kTimeIntervalsPerMinute;
const qword kTimeIntervalsPerDay = 24 * kTimeIntervalsPerHour;
// millisecond timer; wraps ~49 days
dword TimeGetMs ();
// 100 nanosecond intervals; won't wrap in our lifetimes
qword TimeGetTime ();
qword TimeGetLocalTime ();
// Minutes elapsed since 2001 UTC
dword TimeGetMinutes ();
// Seconds elapsed since 00:00:00 January 1, 2001 UTC
dword TimeGetSecondsSince2001Utc ();
// Seconds elapsed since 00:00:00 January 1, 1970 UTC (the Unix Epoch)
dword TimeGetSecondsSince1970Utc ();
// These magic numbers taken from Microsoft's "Shared Source CLI implementation" source code.
// http://msdn.microsoft.com/library/en-us/Dndotnet/html/mssharsourcecli.asp
static const qword kTime1601To1970 = 11644473600 * kTimeIntervalsPerSecond;
static const qword kTime1601To2001 = 12622780800 * kTimeIntervalsPerSecond;
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTime.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTIME_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTime.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTIME_H
/*****************************************************************************
*
* Time formatting functions
*
***/
struct TimeDesc {
unsigned year;
unsigned month; // [1, 12]
unsigned day;
unsigned dayOfWeek; // [0, 6]
unsigned hour; // [0, 23]
unsigned minute; // [0, 59]
unsigned second; // [0, 59]
};
struct TimeElapsedDesc {
unsigned years;
unsigned months; // [0, 12]
unsigned days; // [0, 7]
unsigned weeks; // [0, 6]
unsigned hours; // [0, 23]
unsigned minutes; // [0, 59]
};
void TimeGetDesc (
qword time,
TimeDesc * desc
);
void TimeGetElapsedDesc (
dword minutesElapsed,
TimeElapsedDesc * desc
);
void TimePrettyPrint (
qword time,
unsigned chars,
wchar * buffer
);
/*****************************************************************************
*
* Time query functions
*
***/
const qword kTimeIntervalsPerMs = 10000;
const qword kTimeIntervalsPerSecond = 1000 * kTimeIntervalsPerMs;
const qword kTimeIntervalsPerMinute = 60 * kTimeIntervalsPerSecond;
const qword kTimeIntervalsPerHour = 60 * kTimeIntervalsPerMinute;
const qword kTimeIntervalsPerDay = 24 * kTimeIntervalsPerHour;
// millisecond timer; wraps ~49 days
dword TimeGetMs ();
// 100 nanosecond intervals; won't wrap in our lifetimes
qword TimeGetTime ();
qword TimeGetLocalTime ();
// Minutes elapsed since 2001 UTC
dword TimeGetMinutes ();
// Seconds elapsed since 00:00:00 January 1, 2001 UTC
dword TimeGetSecondsSince2001Utc ();
// Seconds elapsed since 00:00:00 January 1, 1970 UTC (the Unix Epoch)
dword TimeGetSecondsSince1970Utc ();
// These magic numbers taken from Microsoft's "Shared Source CLI implementation" source code.
// http://msdn.microsoft.com/library/en-us/Dndotnet/html/mssharsourcecli.asp
static const qword kTime1601To1970 = 11644473600 * kTimeIntervalsPerSecond;
static const qword kTime1601To2001 = 12622780800 * kTimeIntervalsPerSecond;

View File

@ -1,67 +1,67 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
#ifdef HS_BUILD_FOR_WIN32
//============================================================================
void ThreadLocalAlloc (unsigned * id) {
ASSERT(id);
*id = TlsAlloc();
}
//============================================================================
void ThreadLocalFree (unsigned id) {
(void)TlsFree(id);
}
//============================================================================
void * ThreadLocalGetValue (unsigned id) {
return TlsGetValue(id);
}
//============================================================================
void ThreadLocalSetValue (unsigned id, void * value) {
TlsSetValue(id, value);
}
#else
# error "TLS not implemented for this platform"
#endif
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
/*****************************************************************************
*
* Exports
*
***/
#ifdef HS_BUILD_FOR_WIN32
//============================================================================
void ThreadLocalAlloc (unsigned * id) {
ASSERT(id);
*id = TlsAlloc();
}
//============================================================================
void ThreadLocalFree (unsigned id) {
(void)TlsFree(id);
}
//============================================================================
void * ThreadLocalGetValue (unsigned id) {
return TlsGetValue(id);
}
//============================================================================
void ThreadLocalSetValue (unsigned id, void * value) {
TlsSetValue(id, value);
}
#else
# error "TLS not implemented for this platform"
#endif

View File

@ -1,56 +1,56 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTLS_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTLS_H
/*****************************************************************************
*
* Thread local storage functions
*
***/
const unsigned kTlsInvalidValue = (unsigned) -1;
void ThreadLocalAlloc (unsigned * id);
void ThreadLocalFree (unsigned id);
void * ThreadLocalGetValue (unsigned id);
void ThreadLocalSetValue (unsigned id, void * value);
// Thread capability functions - prevents deadlocks and performance
// bottlenecks by disallowing some threads certain operations.
void ThreadAllowBlock ();
void ThreadDenyBlock ();
void ThreadAssertCanBlock (const char file[], int line);
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTLS_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTls.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTLS_H
/*****************************************************************************
*
* Thread local storage functions
*
***/
const unsigned kTlsInvalidValue = (unsigned) -1;
void ThreadLocalAlloc (unsigned * id);
void ThreadLocalFree (unsigned id);
void * ThreadLocalGetValue (unsigned id);
void ThreadLocalSetValue (unsigned id, void * value);
// Thread capability functions - prevents deadlocks and performance
// bottlenecks by disallowing some threads certain operations.
void ThreadAllowBlock ();
void ThreadDenyBlock ();
void ThreadAssertCanBlock (const char file[], int line);

View File

@ -1,41 +1,41 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTypes.h
*
*
* By Eric Anderson (10/10/2005)
* Copyright 2005 Cyan Worlds, Inc.
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTYPES_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTypes.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTYPES_H
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTypes.h
*
*
* By Eric Anderson (10/10/2005)
* Copyright 2005 Cyan Worlds, Inc.
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTYPES_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtTypes.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTTYPES_H

View File

@ -1,87 +1,87 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtUuid.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
const Uuid kNilGuid;
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
Uuid::Uuid (const wchar str[]) {
GuidFromString(str, this);
}
//============================================================================
Uuid::Uuid (const byte buf[], unsigned length) {
GuidFromHex(buf, length, this);
}
//============================================================================
unsigned GuidHash (const Uuid & uuid) {
CHashValue hash(&uuid.data, sizeof(uuid.data));
return hash.GetHash();
}
//============================================================================
static const wchar s_hexChars[] = L"0123456789ABCDEF";
const wchar * GuidToHex (const Uuid & uuid, wchar * dst, unsigned chars) {
wchar * str = ALLOCA(wchar, sizeof(uuid.data) * 2 + 1);
wchar * cur = str;
for (unsigned i = 0; i < sizeof(uuid.data); ++i) {
*cur++ = s_hexChars[(uuid.data[i] >> 4) & 0x0f];
*cur++ = s_hexChars[uuid.data[i] & 0x0f];
}
*cur = 0;
StrCopy(dst, str, chars);
return dst;
}
//============================================================================
bool GuidFromHex (const byte buf[], unsigned length, Uuid * uuid) {
ASSERT(length == msizeof(Uuid, data));
MemCopy(uuid->data, buf, msizeof(Uuid, data));
return true;
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtUuid.cpp
*
***/
#include "../Pch.h"
#pragma hdrstop
const Uuid kNilGuid;
/*****************************************************************************
*
* Exports
*
***/
//============================================================================
Uuid::Uuid (const wchar str[]) {
GuidFromString(str, this);
}
//============================================================================
Uuid::Uuid (const byte buf[], unsigned length) {
GuidFromHex(buf, length, this);
}
//============================================================================
unsigned GuidHash (const Uuid & uuid) {
CHashValue hash(&uuid.data, sizeof(uuid.data));
return hash.GetHash();
}
//============================================================================
static const wchar s_hexChars[] = L"0123456789ABCDEF";
const wchar * GuidToHex (const Uuid & uuid, wchar * dst, unsigned chars) {
wchar * str = ALLOCA(wchar, sizeof(uuid.data) * 2 + 1);
wchar * cur = str;
for (unsigned i = 0; i < sizeof(uuid.data); ++i) {
*cur++ = s_hexChars[(uuid.data[i] >> 4) & 0x0f];
*cur++ = s_hexChars[uuid.data[i] & 0x0f];
}
*cur = 0;
StrCopy(dst, str, chars);
return dst;
}
//============================================================================
bool GuidFromHex (const byte buf[], unsigned length, Uuid * uuid) {
ASSERT(length == msizeof(Uuid, data));
MemCopy(uuid->data, buf, msizeof(Uuid, data));
return true;
}

View File

@ -1,103 +1,103 @@
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtUuid.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTUUID_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtUuid.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTUUID_H
/*****************************************************************************
*
* Types
*
***/
struct Uuid;
/*****************************************************************************
*
* Constants
*
***/
extern const Uuid kNilGuid;
/*****************************************************************************
*
* Functions
*
***/
// Using 'Guid' here instead of 'Uuid' to avoid name clash with windows API =(
Uuid GuidGenerate ();
void GuidClear (Uuid * uuid);
bool GuidFromString (const wchar str[], Uuid * uuid);
bool GuidFromString (const char str[], Uuid * uuid);
int GuidCompare (const Uuid & a, const Uuid & b);
inline bool GuidsAreEqual (const Uuid & a, const Uuid & b) { return 0 == GuidCompare(a, b); }
bool GuidIsNil (const Uuid & uuid);
unsigned GuidHash (const Uuid & uuid);
const wchar * GuidToString (const Uuid & uuid, wchar * dst, unsigned chars); // returns dst
const char * GuidToString (const Uuid & uuid, char * dst, unsigned chars); // returns dst
const wchar * GuidToHex (const Uuid & uuid, wchar * dst, unsigned chars); // returns dst
bool GuidFromHex (const byte buf[], unsigned length, Uuid * uuid);
/*****************************************************************************
*
* Uuid
*
***/
#include <PshPack1.h>
struct Uuid {
union {
dword dwords[4];
byte data[16];
};
Uuid () {}
Uuid (const wchar str[]);
Uuid (const byte buf[], unsigned length);
operator bool () const { return !GuidIsNil(*this); }
inline bool operator ! () const { return GuidIsNil(*this); }
inline bool operator < (const Uuid & rhs) const { return GuidCompare(*this, rhs) < 0; }
inline bool operator == (const Uuid & rhs) const { return GuidsAreEqual(*this, rhs); }
inline bool operator == (int rhs) const { ASSERT(!rhs); return GuidsAreEqual(*this, kNilGuid); }
inline bool operator != (const Uuid & rhs) const { return !GuidsAreEqual(*this, rhs); }
inline bool operator != (int rhs) const { ASSERT(!rhs); return !GuidsAreEqual(*this, kNilGuid); }
};
#include <PopPack.h>
/*==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==*/
/*****************************************************************************
*
* $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtUuid.h
*
***/
#ifdef PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTUUID_H
#error "Header $/Plasma20/Sources/Plasma/NucleusLib/pnUtils/Private/pnUtUuid.h included more than once"
#endif
#define PLASMA20_SOURCES_PLASMA_NUCLEUSLIB_PNUTILS_PRIVATE_PNUTUUID_H
/*****************************************************************************
*
* Types
*
***/
struct Uuid;
/*****************************************************************************
*
* Constants
*
***/
extern const Uuid kNilGuid;
/*****************************************************************************
*
* Functions
*
***/
// Using 'Guid' here instead of 'Uuid' to avoid name clash with windows API =(
Uuid GuidGenerate ();
void GuidClear (Uuid * uuid);
bool GuidFromString (const wchar str[], Uuid * uuid);
bool GuidFromString (const char str[], Uuid * uuid);
int GuidCompare (const Uuid & a, const Uuid & b);
inline bool GuidsAreEqual (const Uuid & a, const Uuid & b) { return 0 == GuidCompare(a, b); }
bool GuidIsNil (const Uuid & uuid);
unsigned GuidHash (const Uuid & uuid);
const wchar * GuidToString (const Uuid & uuid, wchar * dst, unsigned chars); // returns dst
const char * GuidToString (const Uuid & uuid, char * dst, unsigned chars); // returns dst
const wchar * GuidToHex (const Uuid & uuid, wchar * dst, unsigned chars); // returns dst
bool GuidFromHex (const byte buf[], unsigned length, Uuid * uuid);
/*****************************************************************************
*
* Uuid
*
***/
#include <PshPack1.h>
struct Uuid {
union {
dword dwords[4];
byte data[16];
};
Uuid () {}
Uuid (const wchar str[]);
Uuid (const byte buf[], unsigned length);
operator bool () const { return !GuidIsNil(*this); }
inline bool operator ! () const { return GuidIsNil(*this); }
inline bool operator < (const Uuid & rhs) const { return GuidCompare(*this, rhs) < 0; }
inline bool operator == (const Uuid & rhs) const { return GuidsAreEqual(*this, rhs); }
inline bool operator == (int rhs) const { ASSERT(!rhs); return GuidsAreEqual(*this, kNilGuid); }
inline bool operator != (const Uuid & rhs) const { return !GuidsAreEqual(*this, rhs); }
inline bool operator != (int rhs) const { ASSERT(!rhs); return !GuidsAreEqual(*this, kNilGuid); }
};
#include <PopPack.h>