i must test these before calling them good - as gcc isn't on the windows

machine i push, test, fix, and then push again - pvs studio <3
This commit is contained in:
DarthArgus
2016-07-24 20:37:39 -07:00
parent 5217465f67
commit d2c830306f
19 changed files with 7743 additions and 7936 deletions
@@ -13,260 +13,255 @@
using namespace std;
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
//----------------------------------------
ServerTrackObject::ServerTrackObject(unsigned mapped_track, unsigned real_track, GenericConnection *con)
: m_mappedTrack(mapped_track), m_realTrack(real_track), m_connection(con)
//----------------------------------------
{
}
//----------------------------------------
ServerTrackObject::ServerTrackObject(unsigned mapped_track, unsigned real_track, GenericConnection *con)
: m_mappedTrack(mapped_track), m_realTrack(real_track), m_connection(con)
//----------------------------------------
{
}
//----------------------------------------
GenericAPICore::GenericAPICore(const char *host,
short port,
unsigned reqTimeout,
unsigned reconnectTimeout,
unsigned noDataTimeoutSecs,
unsigned noAckTimeoutSecs,
unsigned incomingBufSizeInKB,
unsigned outgoingBufSizeInKB,
unsigned keepAlive,
unsigned maxRecvMessageSizeInKB)
: m_currTrack(0),
m_reconnectTimeout(0),
m_outCount(0),
m_pendingCount(0),
m_requestTimeout(reqTimeout),
m_currentConnections(0), m_maxConnections(0),
m_suspended(false),
m_nextConnectionIndex(0)
//----------------------------------------
{
GenericConnection *con = new GenericConnection(host, port, this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB);
m_serverConnections.push_back(con);
}
//----------------------------------------
GenericAPICore::GenericAPICore(const char *game, const char *hosts[],
const short port[],
unsigned arraySize,
unsigned reqTimeout,
unsigned reconnectTimeout,
unsigned noDataTimeoutSecs,
unsigned noAckTimeoutSecs,
unsigned incomingBufSizeInKB,
unsigned outgoingBufSizeInKB,
unsigned keepAlive,
unsigned maxRecvMessageSizeInKB)
: m_currTrack(0),
m_reconnectTimeout(0),
m_outCount(0),
m_pendingCount(0),
m_requestTimeout(reqTimeout),
m_currentConnections(0), m_maxConnections(0),
m_suspended(false),
m_nextConnectionIndex(0),
m_game(game)
//----------------------------------------
{
for (unsigned i=0; i<arraySize; i++)
{
GenericConnection *con = new GenericConnection(hosts[i], port[i], this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB);
//----------------------------------------
GenericAPICore::GenericAPICore(const char *host,
short port,
unsigned reqTimeout,
unsigned reconnectTimeout,
unsigned noDataTimeoutSecs,
unsigned noAckTimeoutSecs,
unsigned incomingBufSizeInKB,
unsigned outgoingBufSizeInKB,
unsigned keepAlive,
unsigned maxRecvMessageSizeInKB)
: m_currTrack(0),
m_reconnectTimeout(0),
m_outCount(0),
m_pendingCount(0),
m_requestTimeout(reqTimeout),
m_currentConnections(0), m_maxConnections(0),
m_suspended(false),
m_nextConnectionIndex(0)
//----------------------------------------
{
GenericConnection *con = new GenericConnection(host, port, this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB);
m_serverConnections.push_back(con);
}
}
//----------------------------------------
GenericAPICore::~GenericAPICore()
//----------------------------------------
{
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
{
GenericConnection *con = *conIter;
delete con;
}
m_serverConnections.clear();
for(map<unsigned, GenericResponse *>::iterator iter = m_pending.begin(); iter != m_pending.end(); ++iter)
{
delete (*iter).second;
}
m_pending.empty();
while(m_outCount > 0)
//----------------------------------------
GenericAPICore::GenericAPICore(const char *game, const char *hosts[],
const short port[],
unsigned arraySize,
unsigned reqTimeout,
unsigned reconnectTimeout,
unsigned noDataTimeoutSecs,
unsigned noAckTimeoutSecs,
unsigned incomingBufSizeInKB,
unsigned outgoingBufSizeInKB,
unsigned keepAlive,
unsigned maxRecvMessageSizeInKB)
: m_currTrack(0),
m_reconnectTimeout(0),
m_outCount(0),
m_pendingCount(0),
m_requestTimeout(reqTimeout),
m_currentConnections(0), m_maxConnections(0),
m_suspended(false),
m_nextConnectionIndex(0),
m_game(game)
//----------------------------------------
{
delete m_outboundQueue.front().second;
delete m_outboundQueue.front().first;
m_outboundQueue.pop();
--m_outCount;
}
}
//----------------------------------------
unsigned GenericAPICore::submitRequest(GenericRequest *req, GenericResponse *res)
//----------------------------------------
{
++m_outCount;
if(m_currTrack == 0)
{
m_currTrack++;
}
req->setTrack(m_currTrack);
res->setTrack(m_currTrack);
time_t timeout = time(nullptr) + m_requestTimeout;
req->setTimeout(timeout);
res->setTimeout(timeout);
m_outboundQueue.push(pair<GenericRequest *, GenericResponse *>(req, res));
return(m_currTrack++);
}
//----------------------------------------
void GenericAPICore::process()
//----------------------------------------
{
GenericRequest *req;
GenericResponse *res;
if (!m_suspended)
{
// Process timeout on pending requests
while((m_outCount > 0) && ((req = m_outboundQueue.front().first)->getTimeout() <= time(nullptr)))
for (unsigned i = 0; i < arraySize; i++)
{
--m_outCount;
res = m_outboundQueue.front().second;
GenericConnection *con = new GenericConnection(hosts[i], port[i], this, reconnectTimeout, noDataTimeoutSecs, noAckTimeoutSecs, incomingBufSizeInKB, outgoingBufSizeInKB, keepAlive, maxRecvMessageSizeInKB);
m_serverConnections.push_back(con);
}
}
//----------------------------------------
GenericAPICore::~GenericAPICore()
//----------------------------------------
{
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
{
GenericConnection *con = *conIter;
delete con;
}
m_serverConnections.clear();
for (map<unsigned, GenericResponse *>::iterator iter = m_pending.begin(); iter != m_pending.end(); ++iter)
{
delete (*iter).second;
}
m_pending.clear();
while (m_outCount > 0)
{
delete m_outboundQueue.front().second;
delete m_outboundQueue.front().first;
m_outboundQueue.pop();
responseCallback(res);
delete res;
delete req;
--m_outCount;
}
}
// Process timeout on pending responses
while((m_pendingCount > 0) && ((res = (*m_pending.begin()).second)->getTimeout() <= time(nullptr)))
//----------------------------------------
unsigned GenericAPICore::submitRequest(GenericRequest *req, GenericResponse *res)
//----------------------------------------
{
++m_outCount;
if (m_currTrack == 0)
{
--m_pendingCount;
m_pending.erase(m_pending.begin());
responseCallback(res);
delete res;
m_currTrack++;
}
req->setTrack(m_currTrack);
res->setTrack(m_currTrack);
time_t timeout = time(nullptr) + m_requestTimeout;
while(m_outCount > 0)
req->setTimeout(timeout);
res->setTimeout(timeout);
m_outboundQueue.push(pair<GenericRequest *, GenericResponse *>(req, res));
return(m_currTrack++);
}
//----------------------------------------
void GenericAPICore::process()
//----------------------------------------
{
GenericRequest *req;
GenericResponse *res;
if (!m_suspended)
{
pair<GenericRequest *, GenericResponse *> out_pair = m_outboundQueue.front();
req = out_pair.first;
res = out_pair.second;
GenericConnection *con = nullptr;
if (req->getMappedServerTrack() == 0) // request has no originating "owner" server
// Process timeout on pending requests
while ((m_outCount > 0) && ((req = m_outboundQueue.front().first)->getTimeout() <= time(nullptr)))
{
con = getNextActiveConnection(); // it does not matter which server we send this to
--m_outCount;
res = m_outboundQueue.front().second;
m_outboundQueue.pop();
responseCallback(res);
delete res;
delete req;
}
else
// Process timeout on pending responses
while ((m_pendingCount > 0) && ((res = (*m_pending.begin()).second)->getTimeout() <= time(nullptr)))
{
ServerTrackObject *stobj = findServer(req->getMappedServerTrack());
if (stobj)
--m_pendingCount;
m_pending.erase(m_pending.begin());
responseCallback(res);
delete res;
}
while (m_outCount > 0)
{
pair<GenericRequest *, GenericResponse *> out_pair = m_outboundQueue.front();
req = out_pair.first;
res = out_pair.second;
GenericConnection *con = nullptr;
if (req->getMappedServerTrack() == 0) // request has no originating "owner" server
{
con = stobj->getConnection(); // the server connection to respond to
req->setServerTrack(stobj->getRealServerTrack()); // map server track back to REAL server track
//printf("\nUnmapping %d to %d", stobj->getMappedServerTrack(), req->getMappedServerTrack()); //debug
delete stobj;
con = getNextActiveConnection(); // it does not matter which server we send this to
}
else
{
ServerTrackObject *stobj = findServer(req->getMappedServerTrack());
if (stobj)
{
con = stobj->getConnection(); // the server connection to respond to
req->setServerTrack(stobj->getRealServerTrack()); // map server track back to REAL server track
//printf("\nUnmapping %d to %d", stobj->getMappedServerTrack(), req->getMappedServerTrack()); //debug
delete stobj;
}
}
if (con != nullptr)
{
Base::ByteStream msg;
req->pack(msg);
con->Send(msg);
m_pending.insert(pair<unsigned, GenericResponse *>(res->getTrack(), res));
--m_outCount;
++m_pendingCount;
m_outboundQueue.pop();
delete req;
}
else
{
//no active connections
break; //from while loop
}
}
}
if (con != nullptr)
{
Base::ByteStream msg;
req->pack(msg);
con->Send(msg);
m_pending.insert(pair<unsigned, GenericResponse *>(res->getTrack(), res));
--m_outCount;
++m_pendingCount;
m_outboundQueue.pop();
delete req;
}
else
{
//no active connections
break; //from while loop
}
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
{
GenericConnection *con = *conIter;
con->process();
}
}
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
{
GenericConnection *con = *conIter;
con->process();
}
}
//----------------------------------------
GenericConnection *GenericAPICore::getNextActiveConnection()
//----------------------------------------
{
unsigned startIndex = m_nextConnectionIndex;
unsigned maxIndex = m_serverConnections.size() - 1;
GenericConnection *con = nullptr;
//----------------------------------------
GenericConnection *GenericAPICore::getNextActiveConnection()
//----------------------------------------
{
unsigned startIndex = m_nextConnectionIndex;
unsigned maxIndex = m_serverConnections.size() - 1;
//loop until we find an active connection, or until we get back
// to where we started
do
{
if (m_serverConnections[m_nextConnectionIndex]->isConnected())
{
con = m_serverConnections[m_nextConnectionIndex];
if (m_nextConnectionIndex == maxIndex)
m_nextConnectionIndex = 0;
else
m_nextConnectionIndex++;
}
else if (++m_nextConnectionIndex > maxIndex)
{
//went past end of vector, start back at 0
m_nextConnectionIndex = 0;
}
} while (con == nullptr && m_nextConnectionIndex != startIndex);
GenericConnection *con = nullptr;
return con;
}
//loop until we find an active connection, or until we get back
// to where we started
do
{
if (m_serverConnections[m_nextConnectionIndex]->isConnected())
{
con = m_serverConnections[m_nextConnectionIndex];
if (m_nextConnectionIndex == maxIndex)
m_nextConnectionIndex = 0;
else
m_nextConnectionIndex++;
}
else if (++m_nextConnectionIndex > maxIndex)
{
//went past end of vector, start back at 0
m_nextConnectionIndex = 0;
}
}while (con == nullptr && m_nextConnectionIndex != startIndex);
//----------------------------------------
void GenericAPICore::countOpenConnections()
//----------------------------------------
{
m_currentConnections = 0;
m_maxConnections = m_serverConnections.size();
return con;
}
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
{
GenericConnection *con = *conIter;
if (con->isConnected())
++m_currentConnections;
}
}
//----------------------------------------
void GenericAPICore::countOpenConnections()
//----------------------------------------
{
m_currentConnections = 0;
m_maxConnections = m_serverConnections.size();
for (std::vector<GenericConnection *>::iterator conIter = m_serverConnections.begin(); conIter != m_serverConnections.end(); conIter++)
{
GenericConnection *con = *conIter;
if (con->isConnected())
++m_currentConnections;
}
}
//----------------------------------------
ServerTrackObject *GenericAPICore::findServer(unsigned server_track)
//----------------------------------------
{
std::map<unsigned, ServerTrackObject *>::iterator iter = m_serverTracks.find(server_track);
if (iter == m_serverTracks.end())
return nullptr;
ServerTrackObject *stobj = (*iter).second;
m_serverTracks.erase(server_track);
return stobj;
}
//----------------------------------------
ServerTrackObject *GenericAPICore::findServer(unsigned server_track)
//----------------------------------------
{
std::map<unsigned, ServerTrackObject *>::iterator iter = m_serverTracks.find(server_track);
if (iter == m_serverTracks.end())
return nullptr;
ServerTrackObject *stobj = (*iter).second;
m_serverTracks.erase(server_track);
return stobj;
}
#ifdef EXTERNAL_DISTRO
};
#endif
#endif
@@ -15,187 +15,188 @@
#define GAME_RESOURCE 1
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
using namespace std;
using namespace Base;
using namespace std;
using namespace Base;
GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB)
: m_bConnected(CON_NONE),
m_apiCore(apiCore),
m_con(nullptr),
m_host(host),
m_port(port),
m_conState(CON_DISCONNECT),
m_reconnectTimeout(reconnectTimeout)
{
TcpManager::TcpParams params;
params.incomingBufferSize = incomingBufSizeInKB * 1024;
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
params.maxConnections = 1;
params.port = 0;
params.maxRecvMessageSize = maxRecvMessageSizeInKB*1024;
params.keepAliveDelay = keepAlive * 1000;
params.noDataTimeout = noDataTimeoutSecs * 1000;
//params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
m_manager = new TcpManager(params);
}
GenericConnection::~GenericConnection()
{
if(m_con)
GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB)
: m_bConnected(CON_NONE),
m_apiCore(apiCore),
m_con(nullptr),
m_host(host),
m_port(port),
m_conState(CON_DISCONNECT),
m_reconnectTimeout(reconnectTimeout),
m_conTimeout(0)
{
m_con->SetHandler(nullptr);
m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont
m_con->Release();
TcpManager::TcpParams params;
params.incomingBufferSize = incomingBufSizeInKB * 1024;
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
params.maxConnections = 1;
params.port = 0;
params.maxRecvMessageSize = maxRecvMessageSizeInKB * 1024;
params.keepAliveDelay = keepAlive * 1000;
params.noDataTimeout = noDataTimeoutSecs * 1000;
//params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
m_manager = new TcpManager(params);
}
m_manager->Release();
}
void GenericConnection::disconnect()
{
if (m_con)
GenericConnection::~GenericConnection()
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
if (m_con)
{
m_con->SetHandler(nullptr);
m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont
m_con->Release();
}
m_manager->Release();
}
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
}
void GenericConnection::OnTerminated(TcpConnection *)
{
// m_apiCore->OnDisconnect(m_host.c_str(), m_port);
m_apiCore->OnDisconnect(this);
if(m_con)
void GenericConnection::disconnect()
{
m_con->Release();
m_con = nullptr;
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
}
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
}
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
}
void GenericConnection::OnRoutePacket(TcpConnection *, const unsigned char *data, int dataLen)
{
short type;
unsigned track;
ByteStream msg(data, dataLen);
ByteStream::ReadIterator iter = msg.begin();
get(iter, type);
get(iter, track);
GenericResponse *res = nullptr;
if(track == 0) // notification message from the server, not as a response to a request from this API
void GenericConnection::OnTerminated(TcpConnection *)
{
if (type == ATGAME_REQUEST_CONNECT)
{ // this is a special case, for when we have identified our game code to server
m_bConnected = CON_IDENTIFIED;
m_apiCore->OnConnect(this);
// m_apiCore->OnDisconnect(m_host.c_str(), m_port);
m_apiCore->OnDisconnect(this);
if (m_con)
{
m_con->Release();
m_con = nullptr;
}
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
}
void GenericConnection::OnRoutePacket(TcpConnection *, const unsigned char *data, int dataLen)
{
short type;
unsigned track;
ByteStream msg(data, dataLen);
ByteStream::ReadIterator iter = msg.begin();
get(iter, type);
get(iter, track);
GenericResponse *res = nullptr;
if (track == 0) // notification message from the server, not as a response to a request from this API
{
if (type == ATGAME_REQUEST_CONNECT)
{ // this is a special case, for when we have identified our game code to server
m_bConnected = CON_IDENTIFIED;
m_apiCore->OnConnect(this);
}
else
{
m_apiCore->responseCallback(type, iter, this);
}
}
else
{
m_apiCore->responseCallback(type, iter, this);
map<unsigned, GenericResponse *>::iterator mapIter = m_apiCore->m_pending.find(track);
if (mapIter != m_apiCore->m_pending.end())
{
res = (*mapIter).second;
iter = msg.begin();
res->unpack(iter);
m_apiCore->responseCallback(res);
m_apiCore->m_pendingCount--;
m_apiCore->m_pending.erase(mapIter);
delete res;
}
}
}
else
void GenericConnection::process()
{
map<unsigned, GenericResponse *>::iterator mapIter = m_apiCore->m_pending.find(track);
if(mapIter != m_apiCore->m_pending.end())
switch (m_conState)
{
res = (*mapIter).second;
iter = msg.begin();
res->unpack(iter);
m_apiCore->responseCallback(res);
m_apiCore->m_pendingCount--;
m_apiCore->m_pending.erase(mapIter);
delete res;
}
}
}
case CON_DISCONNECT:
// create connection object, attempting to connect and
// checking for connection in next state, CON_NEGOTIATE
m_con = m_manager->EstablishConnection(m_host.c_str(), m_port);
if (m_con)
{
m_con->SetHandler(this);
m_conState = CON_NEGOTIATE;
m_conTimeout = time(nullptr) + m_reconnectTimeout;
}
break;
case CON_NEGOTIATE:
// check for connection
void GenericConnection::process()
{
switch(m_conState)
{
case CON_DISCONNECT:
// create connection object, attempting to connect and
// checking for connection in next state, CON_NEGOTIATE
m_con = m_manager->EstablishConnection(m_host.c_str(), m_port);
if(m_con)
{
m_con->SetHandler(this);
m_conState = CON_NEGOTIATE;
m_conTimeout = time(nullptr) + m_reconnectTimeout;
}
break;
case CON_NEGOTIATE:
// check for connection
if (m_con->GetStatus() == TcpConnection::StatusConnected)
{
// we're connected
m_conState = CON_CONNECT;
m_bConnected = CON_CONNECTED;
// instead of calling OnConnect() right now, we are going to submit a connection packet
// identifying us
// m_apiCore->OnConnect(this);
Base::ByteStream msg;
put(msg, (short)REQUEST_SET_API);
put(msg, (unsigned)0); // track
put(msg, (unsigned)API_VERSION_CODE);
put(msg, GAME_RESOURCE); // identify us as a game connection resource
if(m_con->GetStatus() == TcpConnection::StatusConnected)
{
// we're connected
m_conState = CON_CONNECT;
m_bConnected = CON_CONNECTED;
// instead of calling OnConnect() right now, we are going to submit a connection packet
// identifying us
// m_apiCore->OnConnect(this);
Base::ByteStream msg;
put(msg, (short)REQUEST_SET_API);
put(msg, (unsigned)0); // track
put(msg, (unsigned)API_VERSION_CODE);
put(msg, GAME_RESOURCE); // identify us as a game connection resource
// now add in the game identifiers
put(msg, (unsigned)m_apiCore->m_gameIdentifiers.size()); // number of strings to read
for(unsigned index = 0; index < m_apiCore->m_gameIdentifiers.size(); index++)
put(msg, std::string(m_apiCore->m_gameIdentifiers[index]));
Send(msg);
}
else if(time(nullptr) > m_conTimeout)
{
// we did not connect
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
// now add in the game identifiers
put(msg, (unsigned)m_apiCore->m_gameIdentifiers.size()); // number of strings to read
for (unsigned index = 0; index < m_apiCore->m_gameIdentifiers.size(); index++)
put(msg, std::string(m_apiCore->m_gameIdentifiers[index]));
Send(msg);
}
else if (time(nullptr) > m_conTimeout)
{
// we did not connect
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
}
break;
case CON_CONNECT:
// do nothing
break;
default:
// this should not occur, but we revert to CON_DISCONNECT if it does
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
}
break;
case CON_CONNECT:
// do nothing
break;
default:
// this should not occur, but we revert to CON_DISCONNECT if it does
m_conState = CON_DISCONNECT;
m_bConnected = CON_NONE;
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
m_bConnected = CON_NONE;
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
}
}
m_manager->GiveTime();
}
m_manager->GiveTime();
}
void GenericConnection::Send(Base::ByteStream &msg)
{
if(m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
void GenericConnection::Send(Base::ByteStream &msg)
{
m_con->Send((const char *)msg.getBuffer(), msg.getSize());
if (m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
{
m_con->Send((const char *)msg.getBuffer(), msg.getSize());
}
}
}
#ifdef EXTERNAL_DISTRO
};
#endif
#endif
@@ -9,36 +9,35 @@
//----------------------------------------
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
using namespace Base;
using namespace Base;
//-------------------------------------------
GenericRequest::GenericRequest(short type, unsigned server_track)
: m_type(type), m_server_track(server_track)
//-------------------------------------------
{
}
//-------------------------------------------
GenericRequest::GenericRequest(short type, unsigned server_track)
: m_type(type), m_server_track(server_track), m_track(0), m_timeout(0)
//-------------------------------------------
{
}
//-------------------------------------------
GenericResponse::GenericResponse(short type, unsigned result, void *user)
: m_type(type), m_result(result), m_user(user)
//-------------------------------------------
{
}
//-------------------------------------------
GenericResponse::GenericResponse(short type, unsigned result, void *user)
: m_type(type), m_result(result), m_user(user), m_track(0), m_timeout(0)
//-------------------------------------------
{
}
//-----------------------------------------
void GenericResponse::unpack(ByteStream::ReadIterator &iter)
//-----------------------------------------
{
get(iter, m_type);
get(iter, m_track);
get(iter, m_result);
}
//-----------------------------------------
void GenericResponse::unpack(ByteStream::ReadIterator &iter)
//-----------------------------------------
{
get(iter, m_type);
get(iter, m_track);
get(iter, m_result);
}
#ifdef EXTERNAL_DISTRO
};
#endif
#endif
@@ -16,28 +16,27 @@ class StructureListMessage;
#define DECLARE_CS_CMD( _name ) void handle_##_name( GameServerCSRequestMessage & message );
class CentralCSHandler
{
public:
static void install();
static void remove();
static CentralCSHandler & getInstance();
void handle( const CSToolRequest& msg, uint32 loginServerId );
void handle(const CSToolRequest& msg, uint32 loginServerId);
~CentralCSHandler();
void handleFindObjectResponse( int iIndex, bool bFound );
void handleStructureListResponse( StructureListMessage& msg );
void handleFindObjectResponse(int iIndex, bool bFound);
void handleStructureListResponse(StructureListMessage& msg);
// only need to DECLARE_CS_CMD for commands handled at the CentralServer.
DECLARE_CS_CMD( list_structures );
DECLARE_CS_CMD( login_character );
DECLARE_CS_CMD( warp_player );
DECLARE_CS_CMD(list_structures);
DECLARE_CS_CMD(login_character);
DECLARE_CS_CMD(warp_player);
protected:
static CentralCSHandler * smp_instance;
typedef void( CentralCSHandler::*CentralCSHandlerFunc )( GameServerCSRequestMessage & );
typedef void(CentralCSHandler::*CentralCSHandlerFunc)(GameServerCSRequestMessage &);
class HandlerEntry
{
@@ -52,75 +51,70 @@ protected:
TYPE_ARBITRARY_GAME_SERVER // send to a game server, we don't care which one. This is used
// if all game servers have what we're looking for, so we don't care who gets it.
};
HandlerEntry( const std::string & in_name, CentralCSHandlerFunc in_func, EntryType in_type ) :
name( in_name ),
type( in_type ),
func( in_func )
HandlerEntry(const std::string & in_name, CentralCSHandlerFunc in_func, EntryType in_type) :
name(in_name),
type(in_type),
func(in_func)
{
}
HandlerEntry( const std::string & in_name, EntryType in_type ) :
name(in_name),
type( in_type )
HandlerEntry(const std::string & in_name, EntryType in_type) :
name(in_name),
type(in_type),
func(nullptr)
{
}
std::string name;
EntryType type;
CentralCSHandlerFunc func; // will be nullptr unless it's of TYPE_CENTRAL.
};
class CSCharacterFindInfo
{
public:
CSCharacterFindInfo( NetworkId & id, int numServers, GameServerCSRequestMessage &req, bool bHandleAtCentral ) :
commandLine( req.getCommandString() ),
command( req.getCommandName() ),
iAccessLevel( req.getAccessLevel() ),
user(req.getUserName() ),
iToolId( req.getToolId() ),
iAccount( req.getAccountId() ),
responsesWaiting( numServers ),
iLoginServerId( req.getLoginServerID() ),
bCentral( bHandleAtCentral )
CSCharacterFindInfo(NetworkId & id, int numServers, GameServerCSRequestMessage &req, bool bHandleAtCentral) :
commandLine(req.getCommandString()),
command(req.getCommandName()),
iAccessLevel(req.getAccessLevel()),
user(req.getUserName()),
iToolId(req.getToolId()),
iAccount(req.getAccountId()),
responsesWaiting(numServers),
iLoginServerId(req.getLoginServerID()),
bCentral(bHandleAtCentral)
{
}
std::string commandLine;
std::string command;
uint32 iAccessLevel;
std::string user;
uint32 iToolId;
int iAccount;
int responsesWaiting;
int responsesWaiting;
int iLoginServerId;
bool bCentral; // if offline, should we handle this at the Central Server or the DB?
protected:
};
typedef std::map< int, CSCharacterFindInfo * > CentralCharFindMap;
CentralCharFindMap m_findMap;
typedef std::map< std::string, HandlerEntry * > CentralCSHandlerMap;
CentralCSHandlerMap m_entries;
private:
CentralCSHandler() :
m_findMap(),
m_entries()
m_findMap(),
m_entries()
{
};
};
@@ -1,8 +1,6 @@
// ConnectionServerConnection.cpp
// copyright 2001 Verant Interactive
//-----------------------------------------------------------------------
#include "FirstCentralServer.h"
@@ -40,48 +38,50 @@ struct OnConnectionServerConnectionClosed {};
//-----------------------------------------------------------------------
ConnectionServerConnection::ConnectionServerConnection(const std::string & a, const uint16 p) :
ServerConnection (a, p, NetworkSetupData()),
m_chatServicePort (0),
m_csServicePort (0),
m_clientServicePortPrivate (0),
m_clientServicePortPublic (0),
m_gameServicePort (0),
m_id (0),
m_pingPort (0),
m_connectionServerNumber (0),
m_gameServiceAddress (),
m_playerCount (0),
m_freeTrialCount (0),
m_emptySceneCount (0),
m_tutorialSceneCount (0),
m_falconSceneCount (0),
m_clientServiceAddress (),
m_chatServiceAddress (),
m_customerServiceAddress ()
ServerConnection(a, p, NetworkSetupData()),
m_chatServicePort(0),
m_csServicePort(0),
m_clientServicePortPrivate(0),
m_clientServicePortPublic(0),
m_gameServicePort(0),
m_id(0),
m_pingPort(0),
m_connectionServerNumber(0),
m_gameServiceAddress(),
m_playerCount(0),
m_freeTrialCount(0),
m_emptySceneCount(0),
m_tutorialSceneCount(0),
m_falconSceneCount(0),
m_clientServiceAddress(),
m_chatServiceAddress(),
m_customerServiceAddress(),
m_voiceChatServicePort(0)
{
}
//-----------------------------------------------------------------------
ConnectionServerConnection::ConnectionServerConnection(UdpConnectionMT * u, TcpClient * t) :
ServerConnection (u, t),
m_chatServicePort (0),
m_csServicePort (0),
m_clientServicePortPrivate (0),
m_clientServicePortPublic (0),
m_gameServicePort (0),
m_id (0),
m_pingPort (0),
m_connectionServerNumber (0),
m_gameServiceAddress (),
m_playerCount (0),
m_freeTrialCount (0),
m_emptySceneCount (0),
m_tutorialSceneCount (0),
m_falconSceneCount (0),
m_clientServiceAddress (),
m_chatServiceAddress (),
m_customerServiceAddress ()
ServerConnection(u, t),
m_chatServicePort(0),
m_csServicePort(0),
m_clientServicePortPrivate(0),
m_clientServicePortPublic(0),
m_gameServicePort(0),
m_id(0),
m_pingPort(0),
m_connectionServerNumber(0),
m_gameServiceAddress(),
m_playerCount(0),
m_freeTrialCount(0),
m_emptySceneCount(0),
m_tutorialSceneCount(0),
m_falconSceneCount(0),
m_clientServiceAddress(),
m_chatServiceAddress(),
m_customerServiceAddress(),
m_voiceChatServicePort(0)
{
}
@@ -89,12 +89,12 @@ m_customerServiceAddress ()
ConnectionServerConnection::~ConnectionServerConnection()
{
// remove ConnectionServerConnection *'s from the
// remove ConnectionServerConnection *'s from the
// s_pseudoClientConnectionMap
std::map<unsigned int, std::pair<TransferRequestMoveValidation::TransferRequestSource, ConnectionServerConnection *> >::iterator i;
for(i = s_pseudoClientConnectionMap.begin(); i != s_pseudoClientConnectionMap.end();)
for (i = s_pseudoClientConnectionMap.begin(); i != s_pseudoClientConnectionMap.end();)
{
if(i->second.second == this)
if (i->second.second == this)
{
if (i->second.first == TransferRequestMoveValidation::TRS_transfer_server)
{
@@ -121,7 +121,7 @@ bool ConnectionServerConnection::sendToPseudoClientConnection(unsigned int stati
{
bool result = false;
std::map<unsigned int, std::pair<TransferRequestMoveValidation::TransferRequestSource, ConnectionServerConnection *> >::iterator f = s_pseudoClientConnectionMap.find(stationId);
if(f != s_pseudoClientConnectionMap.end())
if (f != s_pseudoClientConnectionMap.end())
{
result = true;
f->second.second->send(message, true);
@@ -166,9 +166,9 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
{
Archive::ReadIterator ri = message.begin();
GameNetworkMessage m(ri);
ri = message.begin();
ri = message.begin();
if(m.isType("NewCentralConnectionServer"))
if (m.isType("NewCentralConnectionServer"))
{
const NewCentralConnectionServer ncs(ri);
@@ -178,7 +178,7 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
m_clientServicePortPrivate = ncs.getClientServicePortPrivate();
m_clientServicePortPublic = ncs.getClientServicePortPublic();
m_gameServicePort = ncs.getGameServicePort();
m_pingPort = ncs.getPingPort ();
m_pingPort = ncs.getPingPort();
m_connectionServerNumber = ncs.getConnectionServerNumber();
m_gameServiceAddress = ncs.getGameServiceAddress();
m_clientServiceAddress = ncs.getClientServiceAddress();
@@ -207,8 +207,8 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
//Send to CS servers
const EnumerateServers e2(true, getCustomerServiceAddress(), getCustomerServicePort(), ct);
if ( !getCustomerServiceAddress().empty()
&& (getCustomerServicePort() != 0))
if (!getCustomerServiceAddress().empty()
&& (getCustomerServicePort() != 0))
{
CentralServer::getInstance().broadcastToCustomerServiceServers(e2);
}
@@ -218,10 +218,10 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
}
//Send to login Servers
if ( (getClientServicePortPrivate() != 0) || (getClientServicePortPublic() != 0) )
if ((getClientServicePortPrivate() != 0) || (getClientServicePortPublic() != 0))
{
const LoginConnectionServerAddress csa(m_id, getClientServiceAddress(), getClientServicePortPrivate(),
getClientServicePortPublic(), getPlayerCount(), getPingPort ());
getClientServicePortPublic(), getPlayerCount(), getPingPort());
CentralServer::getInstance().sendToAllLoginServers(csa);
}
}
@@ -235,12 +235,12 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
CentralServer::getInstance().sendToAllLoginServers(ulc);
}
else if(m.isType("TaskSpawnProcess"))
else if (m.isType("TaskSpawnProcess"))
{
const TaskSpawnProcess spawn(ri);
CentralServer::getInstance().sendTaskMessage(spawn);
}
else if(m.isType("NewPseudoClientConnection"))
else if (m.isType("NewPseudoClientConnection"))
{
const GenericValueTypeMessage<std::pair<unsigned int, int8> > info(ri);
s_pseudoClientConnectionMap[info.getValue().first] = std::make_pair(static_cast<TransferRequestMoveValidation::TransferRequestSource>(info.getValue().second), this);
@@ -248,20 +248,20 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
// remove corresponding "non pseudo client connection"
CentralServer::getInstance().removeFromAccountConnectionMap(static_cast<StationId>(info.getValue().first));
}
else if(m.isType("DestroyPseudoClientConnection"))
else if (m.isType("DestroyPseudoClientConnection"))
{
const GenericValueTypeMessage<unsigned int> info(ri);
std::map<unsigned int, std::pair<TransferRequestMoveValidation::TransferRequestSource, ConnectionServerConnection *> >::iterator f = s_pseudoClientConnectionMap.find(info.getValue());
if(f != s_pseudoClientConnectionMap.end())
if (f != s_pseudoClientConnectionMap.end())
{
s_pseudoClientConnectionMap.erase(f);
}
}
else if(m.isType("TransferReceiveDataFromGameServer"))
else if (m.isType("TransferReceiveDataFromGameServer"))
{
const GenericValueTypeMessage<TransferCharacterData> transferReply(ri);
if(transferReply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
if (transferReply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
{
CentralServer::getInstance().sendToTransferServer(transferReply);
}
@@ -275,7 +275,7 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
LOG("CustomerService", ("CharacterTransfer: Sending TransferLoginCharacterToDestinationServer to CentralServer (via LoginServer) (%s) for (%s)", transferReply.getValue().getDestinationGalaxy().c_str(), login.getValue().toString().c_str()));
}
}
else if(m.isType("ApplyTransferDataSuccess"))
else if (m.isType("ApplyTransferDataSuccess"))
{
const GenericValueTypeMessage<TransferCharacterData> success(ri);
@@ -290,7 +290,7 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
// send the message back to the transfer server, which then
// sends a disable login request to the source central server,
// "removing" the account on the source galaxy.
if(success.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
if (success.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
{
CentralServer::getInstance().sendToTransferServer(success);
}
@@ -303,14 +303,14 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(toggleLoginStatus));
}
}
else if(m.isType("ApplyTransferDataFail"))
else if (m.isType("ApplyTransferDataFail"))
{
const GenericValueTypeMessage<TransferCharacterData> fail(ri);
// send the message back to the transfer server, which then
// sends a delete request to the destination central server,
// "removing" the account on the destination galaxy.
if(fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
if (fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
{
CentralServer::getInstance().sendToTransferServer(fail);
}
@@ -329,11 +329,11 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget));
}
}
else if(m.isType("TransferCreateCharacterFailed"))
else if (m.isType("TransferCreateCharacterFailed"))
{
const GenericValueTypeMessage<TransferCharacterData> fail(ri);
if(fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
if (fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
{
CentralServer::getInstance().sendToTransferServer(fail);
}
@@ -348,11 +348,11 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget));
}
}
else if(m.isType("ReplyTransferDataFail"))
else if (m.isType("ReplyTransferDataFail"))
{
const GenericValueTypeMessage<TransferCharacterData> reply(ri);
if(reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
if (reply.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
{
CentralServer::getInstance().sendToTransferServer(reply);
}
@@ -367,11 +367,11 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget));
}
}
else if(m.isType("TransferFailGameServerClosedConnectionWithConnectionServer"))
else if (m.isType("TransferFailGameServerClosedConnectionWithConnectionServer"))
{
const GenericValueTypeMessage<TransferCharacterData> fail(ri);
if(fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
if (fail.getValue().getTransferRequestSource() == TransferRequestMoveValidation::TRS_transfer_server)
{
CentralServer::getInstance().sendToTransferServer(fail);
}
@@ -386,12 +386,12 @@ void ConnectionServerConnection::onReceive(const Archive::ByteStream & message)
IGNORE_RETURN(CentralServer::getInstance().sendToArbitraryLoginServer(closeRequestTarget));
}
}
else if(m.isType("AccountFeatureIdRequest"))
else if (m.isType("AccountFeatureIdRequest"))
{
const AccountFeatureIdRequest msg(ri);
CentralServer::getInstance().sendToArbitraryLoginServer(msg);
}
else if(m.isType("AdjustAccountFeatureIdRequest"))
else if (m.isType("AdjustAccountFeatureIdRequest"))
{
const AdjustAccountFeatureIdRequest msg(ri);
CentralServer::getInstance().sendToArbitraryLoginServer(msg);
@@ -408,7 +408,7 @@ ConnectionServerConnection * ConnectionServerConnection::getConnectionForAccount
{
ConnectionServerConnection * result = 0;
std::map<unsigned int, std::pair<TransferRequestMoveValidation::TransferRequestSource, ConnectionServerConnection *> >::iterator f = s_pseudoClientConnectionMap.find(stationId);
if(f != s_pseudoClientConnectionMap.end())
if (f != s_pseudoClientConnectionMap.end())
{
result = f->second.second;
}
@@ -424,4 +424,4 @@ void ConnectionServerConnection::removeFromAccountConnectionMap(unsigned int sta
{
s_pseudoClientConnectionMap.erase(f);
}
}
}
@@ -223,7 +223,7 @@ bool ConnectionServer::decryptToken(const KeyShare::Token & token, char* session
uint32 len = apiSessionIdWidth + sizeof(StationId);
unsigned char * keyBuffer = new unsigned char[len + 1];
unsigned char * keyBufferPointer = keyBuffer;
memset(keyBuffer, 0, len);
memset(keyBuffer, 0, sizeof(*keyBuffer));
bool retval = cs.loginServerKeys->decipherToken(token, keyBuffer, len);
@@ -21,7 +21,6 @@
class Vector;
//========================================================================
template <class DataType, class ReturnType>
class TemplateBase
@@ -40,12 +39,12 @@ public:
DataType max_value;
Range(void) {}
Range(const Range &s) :
min_value(s.min_value),
Range(const Range &s) :
min_value(s.min_value),
max_value(s.max_value) {}
Range & operator=(const Range &s)
{
min_value = s.min_value;
min_value = s.min_value;
max_value = s.max_value;
return *this;
}
@@ -58,8 +57,8 @@ public:
DataType base;
DieRoll(void) {}
DieRoll(const DieRoll &s) :
num_dice(s.num_dice),
DieRoll(const DieRoll &s) :
num_dice(s.num_dice),
die_sides(s.die_sides),
base(s.base) {}
DieRoll & operator =(const DieRoll &s)
@@ -112,81 +111,80 @@ protected:
} m_data; // storage for complex-type data
bool m_loaded; // flag that this parameter has been loaded
TemplateBase(void);
TemplateBase(const TemplateBase<DataType, ReturnType> &);
TemplateBase<DataType, ReturnType> & operator =(const TemplateBase<DataType, ReturnType> &);
TemplateBase(void);
TemplateBase(const TemplateBase<DataType, ReturnType> &);
TemplateBase<DataType, ReturnType> & operator =(const TemplateBase<DataType, ReturnType> &);
virtual ~TemplateBase();
virtual void cleanSingleParam(void);
void loadWeightedListFromIff(Iff &file);
void saveWeightedListToIff(Iff &file) const;
void loadWeightedListFromIff(Iff &file);
void saveWeightedListToIff(Iff &file) const;
virtual TemplateBase<DataType, ReturnType> * createNewParam(void) = 0;
virtual ReturnType getSingle(void) const;
virtual ReturnType getRange(void) const;
virtual ReturnType getDieRoll(void) const;
void setValue(const DataType & min_value, const DataType & max_value);
void setValue(const DataType & num_dice, const DataType & die_sides, const DataType & base);
void setValue(const DataType & min_value, const DataType & max_value);
void setValue(const DataType & num_dice, const DataType & die_sides, const DataType & base);
};
template <class DataType, class ReturnType>
inline TemplateBase<DataType, ReturnType>::TemplateBase(void) :
m_dataType(NONE),
m_loaded(false)
m_dataType(NONE),
m_loaded(false),
m_data(nullptr)
{
} // TemplateBase::TemplateBase(void)
template <class DataType, class ReturnType>
inline TemplateBase<DataType, ReturnType>::TemplateBase(const TemplateBase<
DataType, ReturnType> & source)
DataType, ReturnType> & source) : m_loaded(false)
{
m_dataType = source.m_dataType;
switch (m_dataType)
{
case SINGLE:
m_dataSingle = source.m_dataSingle;
break;
case WEIGHTED_LIST:
m_data.weightedList = new WeightedList(*source.m_data.weightedList);
break;
case RANGE:
m_data.range = new Range(*source.m_data.range);
break;
case DIE_ROLL:
m_data.dieRoll = new DieRoll(*source.m_data.dieRoll);
break;
case NONE:
default:
break;
case SINGLE:
m_dataSingle = source.m_dataSingle;
break;
case WEIGHTED_LIST:
m_data.weightedList = new WeightedList(*source.m_data.weightedList);
break;
case RANGE:
m_data.range = new Range(*source.m_data.range);
break;
case DIE_ROLL:
m_data.dieRoll = new DieRoll(*source.m_data.dieRoll);
break;
case NONE:
default:
break;
}
} // TemplateBase::TemplateBase(const TemplateBase &)
template <class DataType, class ReturnType>
inline TemplateBase<DataType, ReturnType> & TemplateBase<DataType, ReturnType>::
operator =(const TemplateBase<DataType, ReturnType> &source)
operator =(const TemplateBase<DataType, ReturnType> &source)
{
cleanData();
m_dataType = source.m_dataType;
switch (m_dataType)
{
case SINGLE:
m_dataSingle = source.m_dataSingle;
break;
case WEIGHTED_LIST:
m_data.weightedList = new WeightedList(*source.m_data.weightedList);
break;
case RANGE:
m_data.range = new Range(*source.m_data.range);
break;
case DIE_ROLL:
m_data.dieRoll = new DieRoll(*source.m_data.dieRoll);
break;
case NONE:
default:
break;
case SINGLE:
m_dataSingle = source.m_dataSingle;
break;
case WEIGHTED_LIST:
m_data.weightedList = new WeightedList(*source.m_data.weightedList);
break;
case RANGE:
m_data.range = new Range(*source.m_data.range);
break;
case DIE_ROLL:
m_data.dieRoll = new DieRoll(*source.m_data.dieRoll);
break;
case NONE:
default:
break;
}
return *this;
} // TemplateBase::operator =
@@ -199,34 +197,34 @@ inline void TemplateBase<DataType, ReturnType>::cleanData(void)
{
switch (m_dataType)
{
case SINGLE:
cleanSingleParam();
break;
case WEIGHTED_LIST:
{
typename WeightedList::iterator end = m_data.weightedList->end();
for (typename WeightedList::iterator iter = m_data.weightedList->begin();
iter != end;
++iter)
{
delete (*iter).value;
(*iter).value = nullptr;
}
delete m_data.weightedList;
m_data.weightedList = nullptr;
}
break;
case RANGE:
delete m_data.range;
m_data.range = nullptr;
break;
case DIE_ROLL:
delete m_data.dieRoll;
m_data.dieRoll = nullptr;
break;
case NONE:
default:
break;
case SINGLE:
cleanSingleParam();
break;
case WEIGHTED_LIST:
{
typename WeightedList::iterator end = m_data.weightedList->end();
for (typename WeightedList::iterator iter = m_data.weightedList->begin();
iter != end;
++iter)
{
delete (*iter).value;
(*iter).value = nullptr;
}
delete m_data.weightedList;
m_data.weightedList = nullptr;
}
break;
case RANGE:
delete m_data.range;
m_data.range = nullptr;
break;
case DIE_ROLL:
delete m_data.dieRoll;
m_data.dieRoll = nullptr;
break;
case NONE:
default:
break;
}
m_dataType = NONE;
m_loaded = false;
@@ -247,38 +245,38 @@ inline bool TemplateBase<DataType, ReturnType>::isLoaded(void) const
template <class DataType, class ReturnType>
inline ReturnType TemplateBase<DataType, ReturnType>::getValue(void) const
{
static DataType dummyReturn;
static DataType dummyReturn;
switch (m_dataType)
{
case SINGLE:
return getSingle();
case WEIGHTED_LIST:
case SINGLE:
return getSingle();
case WEIGHTED_LIST:
{
int weight = Random::random(1, 100);
typename WeightedList::const_iterator end = m_data.weightedList->end();
for (typename WeightedList::const_iterator iter = m_data.weightedList->begin();
iter != end;
++iter)
{
weight -= (*iter).weight;
if (weight <= 0)
{
int weight = Random::random(1, 100);
typename WeightedList::const_iterator end = m_data.weightedList->end();
for (typename WeightedList::const_iterator iter = m_data.weightedList->begin();
iter != end;
++iter)
{
weight -= (*iter).weight;
if (weight <= 0)
{
return dynamic_cast<const TemplateBase<DataType, ReturnType> *>
((*iter).value)->getValue();
}
}
DEBUG_FATAL(true, ("weighted list does not equal 100"));
return dynamic_cast<const TemplateBase<DataType, ReturnType> *>
((*iter).value)->getValue();
}
break;
case RANGE:
return getRange();
case DIE_ROLL:
return getDieRoll();
case NONE:
default:
DEBUG_FATAL(true, ("Unknown data type %d for template param", m_dataType));
break;
}
DEBUG_FATAL(true, ("weighted list does not equal 100"));
}
break;
case RANGE:
return getRange();
case DIE_ROLL:
return getDieRoll();
case NONE:
default:
DEBUG_FATAL(true, ("Unknown data type %d for template param", m_dataType));
break;
}
return dummyReturn;
} // TemplateBase::getValue
@@ -322,7 +320,7 @@ inline ReturnType TemplateBase<DataType, ReturnType>::getSingle(void) const
template <class DataType, class ReturnType>
inline ReturnType TemplateBase<DataType, ReturnType>::getRange(void) const
{
static DataType dummyReturn;
static DataType dummyReturn;
DEBUG_FATAL(true, ("getRange not supported"));
return dummyReturn;
@@ -331,7 +329,7 @@ static DataType dummyReturn;
template <class DataType, class ReturnType>
inline ReturnType TemplateBase<DataType, ReturnType>::getDieRoll(void) const
{
static DataType dummyReturn;
static DataType dummyReturn;
DEBUG_FATAL(true, ("getDieRoll not supported"));
return dummyReturn;
@@ -347,7 +345,7 @@ inline void TemplateBase<DataType, ReturnType>::setValue(const DataType & value)
}
template <class DataType, class ReturnType>
inline void TemplateBase<DataType, ReturnType>::setValue(const DataType & min_value,
inline void TemplateBase<DataType, ReturnType>::setValue(const DataType & min_value,
const DataType & max_value)
{
cleanData();
@@ -359,7 +357,7 @@ inline void TemplateBase<DataType, ReturnType>::setValue(const DataType & min_va
}
template <class DataType, class ReturnType>
inline void TemplateBase<DataType, ReturnType>::setValue(const DataType & num_dice,
inline void TemplateBase<DataType, ReturnType>::setValue(const DataType & num_dice,
const DataType & die_sides, const DataType & base)
{
cleanData();
@@ -398,7 +396,7 @@ inline void TemplateBase<DataType, ReturnType>::cleanSingleParam(void)
template <class DataType, class ReturnType>
inline void TemplateBase<DataType, ReturnType>::loadWeightedListFromIff(Iff &file)
{
WeightedValue weightedValue;
WeightedValue weightedValue;
NOT_NULL(m_data.weightedList);
@@ -423,7 +421,7 @@ WeightedValue weightedValue;
template <class DataType, class ReturnType>
inline void TemplateBase<DataType, ReturnType>::saveWeightedListToIff(Iff &file) const
{
int32 intData;
int32 intData;
NOT_NULL(m_data.weightedList);
@@ -441,14 +439,13 @@ int32 intData;
}
} // TemplateBase::saveWeightedListToIff
//========================================================================
// class IntegerParam
class IntegerParam : public TemplateBase<int, int>
{
public:
IntegerParam(void);
IntegerParam(void);
virtual ~IntegerParam();
virtual void loadFromIff(Iff &file);
@@ -478,7 +475,6 @@ private:
// derived template param
};
inline char IntegerParam::getDeltaType(void) const
{
return m_dataDeltaType;
@@ -535,7 +531,7 @@ inline void IntegerParam::setValue(const int & num_dice, const int & die_sides,
inline const IntegerParam::DieRoll * IntegerParam::getDieRollStruct(void) const
{
if(m_dataType == DIE_ROLL)
if (m_dataType == DIE_ROLL)
{
return m_data.dieRoll;
}
@@ -547,7 +543,7 @@ inline const IntegerParam::DieRoll * IntegerParam::getDieRollStruct(void) const
inline const IntegerParam::Range * IntegerParam::getRangeStruct(void) const
{
if(m_dataType == RANGE)
if (m_dataType == RANGE)
{
return m_data.range;
}
@@ -563,7 +559,7 @@ inline const IntegerParam::Range * IntegerParam::getRangeStruct(void) const
class FloatParam : public TemplateBase<float, float>
{
public:
FloatParam(void);
FloatParam(void);
virtual ~FloatParam();
virtual void loadFromIff(Iff &file);
@@ -590,7 +586,6 @@ private:
// derived template param
};
inline char FloatParam::getDeltaType(void) const
{
return m_dataDeltaType;
@@ -631,7 +626,7 @@ inline void FloatParam::setValue(const float & min_value, const float & max_valu
inline const FloatParam::Range * FloatParam::getRangeStruct() const
{
if(m_dataType == RANGE)
if (m_dataType == RANGE)
{
return m_data.range;
}
@@ -647,7 +642,7 @@ inline const FloatParam::Range * FloatParam::getRangeStruct() const
class BoolParam : public TemplateBase<bool, bool>
{
public:
BoolParam(void);
BoolParam(void);
virtual ~BoolParam();
virtual void loadFromIff(Iff &file);
@@ -662,14 +657,13 @@ inline TemplateBase<bool, bool> *BoolParam::createNewParam(void)
return new BoolParam;
}
//========================================================================
//
class StringParam : public TemplateBase<std::string, const std::string &>
{
public:
StringParam(void);
StringParam(void);
virtual ~StringParam();
virtual void cleanSingleParam(void);
@@ -681,13 +675,11 @@ protected:
virtual TemplateBase<std::string, const std::string &> *createNewParam(void);
};
inline TemplateBase<std::string, const std::string &> *StringParam::createNewParam(void)
{
return new StringParam;
}
//========================================================================
// class VectorParam
@@ -705,7 +697,7 @@ struct VectorParamData
class VectorParam : public TemplateBase<VectorParamData, const VectorParamData &>
{
public:
VectorParam(void);
VectorParam(void);
virtual ~VectorParam();
virtual void cleanSingleParam(void);
@@ -717,28 +709,26 @@ protected:
virtual TemplateBase<VectorParamData, const VectorParamData &> *createNewParam(void);
};
inline TemplateBase<VectorParamData, const VectorParamData &> *VectorParam::createNewParam(void)
{
return new VectorParam;
}
//========================================================================
// class StringId param
struct StringIdParamData
{
{
StringParam table;
StringParam index;
StringIdParamData(void) : table() , index() {}
StringIdParamData(void) : table(), index() {}
};
class StringIdParam : public TemplateBase<StringIdParamData, StringIdParamData>
{
public:
StringIdParam(void);
StringIdParam(void);
virtual ~StringIdParam();
virtual void cleanSingleParam(void);
@@ -757,7 +747,6 @@ inline TemplateBase<StringIdParamData, StringIdParamData> *StringIdParam::create
return new StringIdParam;
}
//========================================================================
// class TriggerVolume param
@@ -788,11 +777,11 @@ inline float TriggerVolumeData::getRadius(void) const
} // TriggerVolumeData::getRadius
struct TriggerVolumeParamData
{
{
StringParam name;
FloatParam radius;
TriggerVolumeParamData(void) : name() , radius() {}
TriggerVolumeParamData(void) : name(), radius() {}
private:
// no copying
@@ -800,11 +789,11 @@ private:
// TriggerVolumeParamData & operator =(const TriggerVolumeParamData &);
};
class TriggerVolumeParam : public TemplateBase<TriggerVolumeParamData,
class TriggerVolumeParam : public TemplateBase<TriggerVolumeParamData,
TriggerVolumeParamData>
{
public:
TriggerVolumeParam(void);
TriggerVolumeParam(void);
virtual ~TriggerVolumeParam();
virtual void cleanSingleParam(void);
@@ -823,7 +812,6 @@ inline TemplateBase<TriggerVolumeParamData, TriggerVolumeParamData> *TriggerVolu
return new TriggerVolumeParam;
}
//========================================================================
// class DynamicVariableParamData - used by class DynamicVariableParam
@@ -842,7 +830,7 @@ public:
STRING,
LIST
} m_type;
union
union
{
IntegerParam *iparam;
FloatParam *fparam;
@@ -850,8 +838,8 @@ public:
std::vector<DynamicVariableParamData *> *lparam;
} m_data;
DynamicVariableParamData(void);
DynamicVariableParamData(const std::string &name, DataType type);
DynamicVariableParamData(void);
DynamicVariableParamData(const std::string &name, DataType type);
virtual ~DynamicVariableParamData();
void loadFromIff(Iff &file);
void saveToIff(Iff &file) const;
@@ -862,21 +850,20 @@ private:
DynamicVariableParamData & operator =(const DynamicVariableParamData &);
};
inline DynamicVariableParamData::DynamicVariableParamData(void) :
inline DynamicVariableParamData::DynamicVariableParamData(void) :
m_name(),
m_type(UNKNOWN)
{
memset(&m_data, 0, sizeof(m_data));
}
//========================================================================
//
class DynamicVariableParam : public TemplateBase<DynamicVariableParamData, const DynamicVariableParamData &>
{
public:
DynamicVariableParam(void);
DynamicVariableParam(void);
virtual ~DynamicVariableParam();
virtual void cleanSingleParam(void);
@@ -900,9 +887,8 @@ private:
DynamicVariableParam & operator =(const DynamicVariableParam &);
};
inline TemplateBase<DynamicVariableParamData, const DynamicVariableParamData &> *
DynamicVariableParam::createNewParam(void)
DynamicVariableParam::createNewParam(void)
{
return new DynamicVariableParam();
}
@@ -922,7 +908,6 @@ inline void DynamicVariableParam::setIsLoaded(void)
m_loaded = true;
}
//========================================================================
//
@@ -930,7 +915,7 @@ template <class SP>
class StructParam : public TemplateBase<SP *, SP *>
{
public:
StructParam(void);
StructParam(void);
virtual ~StructParam();
bool isInitialized(void) const;
@@ -1000,34 +985,34 @@ inline void StructParam<SP>::loadFromIff(Iff &file)
typename StructParam<SP>::DataTypeId dataType = static_cast<typename StructParam<SP>::DataTypeId>(file.read_int8());
switch (dataType)
{
case TemplateBase<SP *, SP *>::SINGLE:
{
Tag id = file.read_int32();
SP * structTemplate = DataResourceList<SP>::fetch(id);
NOT_NULL(structTemplate);
// we need to exit the chunk because the iff class doesn't
// support chunk nesting
file.exitChunk();
structTemplate->loadFromIff(file);
// we need to enter a fake chunk because whoever called this
// function assumes we are still in a chunk
file.enterChunk();
this->setValue(structTemplate);
this->m_loaded = true;
}
break;
case TemplateBase<SP *, SP *>::WEIGHTED_LIST:
this->setValue(new typename TemplateBase<SP *, SP *>::WeightedList);
this->loadWeightedListFromIff(file);
break;
case TemplateBase<SP *, SP *>::NONE:
this->cleanData();
break;
case TemplateBase<SP *, SP *>::RANGE:
case TemplateBase<SP *, SP *>::DIE_ROLL:
default:
DEBUG_FATAL(true, ("loaded unknown data type %d for template struct param", this->m_dataType));
break;
case TemplateBase<SP *, SP *>::SINGLE:
{
Tag id = file.read_int32();
SP * structTemplate = DataResourceList<SP>::fetch(id);
NOT_NULL(structTemplate);
// we need to exit the chunk because the iff class doesn't
// support chunk nesting
file.exitChunk();
structTemplate->loadFromIff(file);
// we need to enter a fake chunk because whoever called this
// function assumes we are still in a chunk
file.enterChunk();
this->setValue(structTemplate);
this->m_loaded = true;
}
break;
case TemplateBase<SP *, SP *>::WEIGHTED_LIST:
this->setValue(new typename TemplateBase<SP *, SP *>::WeightedList);
this->loadWeightedListFromIff(file);
break;
case TemplateBase<SP *, SP *>::NONE:
this->cleanData();
break;
case TemplateBase<SP *, SP *>::RANGE:
case TemplateBase<SP *, SP *>::DIE_ROLL:
default:
DEBUG_FATAL(true, ("loaded unknown data type %d for template struct param", this->m_dataType));
break;
}
} // StructParam<SP>::loadFromIff
@@ -1043,35 +1028,32 @@ inline void StructParam<SP>::saveToIff(Iff &file) const
file.insertChunkData(&type, sizeof(type));
switch (this->m_dataType)
{
case TemplateBase<SP *, SP *>::SINGLE:
{
int32 tag = this->m_dataSingle->getId();
file.insertChunkData(&tag, sizeof(tag));
// we need to exit the chunk because the iff class doesn't
// support chunk nesting
file.exitChunk();
this->m_dataSingle->saveToIff(file);
// we need to insert a fake chunk because whoever called this
// function assumes we are still in a chunk
file.insertChunk(TAG(X, X, X, X));
}
break;
case TemplateBase<SP *, SP *>::WEIGHTED_LIST:
this->saveWeightedListToIff(file);
break;
case TemplateBase<SP *, SP *>::NONE:
break;
case TemplateBase<SP *, SP *>::RANGE:
case TemplateBase<SP *, SP *>::DIE_ROLL:
default:
DEBUG_FATAL(true, ("saving unknown data type %d for template struct param", this->m_dataType));
break;
case TemplateBase<SP *, SP *>::SINGLE:
{
int32 tag = this->m_dataSingle->getId();
file.insertChunkData(&tag, sizeof(tag));
// we need to exit the chunk because the iff class doesn't
// support chunk nesting
file.exitChunk();
this->m_dataSingle->saveToIff(file);
// we need to insert a fake chunk because whoever called this
// function assumes we are still in a chunk
file.insertChunk(TAG(X, X, X, X));
}
break;
case TemplateBase<SP *, SP *>::WEIGHTED_LIST:
this->saveWeightedListToIff(file);
break;
case TemplateBase<SP *, SP *>::NONE:
break;
case TemplateBase<SP *, SP *>::RANGE:
case TemplateBase<SP *, SP *>::DIE_ROLL:
default:
DEBUG_FATAL(true, ("saving unknown data type %d for template struct param", this->m_dataType));
break;
}
} // StructParam<SP>::saveToIff
//========================================================================
#endif // _INCLUDED_TemplateParameter_H
+84 -85
View File
@@ -6,112 +6,111 @@
#include <time.h>
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
namespace Base
{
namespace Base
{
class CAutoLog
{
public:
enum eLogLevel {
eLOG_NONE = 0, // log entries are discarded
eLOG_ERROR = 1, // log errors only
eLOG_ALERT = 2, // log alerts and errors only
eLOG_NORMAL = 3, // log all normal events, no debug
eLOG_DEBUG = 4 // log everything
};
class CAutoLog
{
public:
enum eLogLevel {
eLOG_NONE = 0, // log entries are discarded
eLOG_ERROR = 1, // log errors only
eLOG_ALERT = 2, // log alerts and errors only
eLOG_NORMAL = 3, // log all normal events, no debug
eLOG_DEBUG = 4 // log everything
};
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_NORMAL.
void SetLogLevel(eLogLevel loglevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_NORMAL.
void SetLogLevel(eLogLevel loglevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetPrintLevel(eLogLevel printlevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetPrintLevel(eLogLevel printlevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetFlushLevel(eLogLevel flushlevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetFlushLevel(eLogLevel flushlevel);
// constructor, no file loaded
CAutoLog();
// constructor, no file loaded
CAutoLog();
// version of constructor that calls Open(file)
CAutoLog(const char * file);
// version of constructor that calls Open(file)
CAutoLog(const char * file);
// destructor, will close file if opened
~CAutoLog();
// destructor, will close file if opened
~CAutoLog();
// Open log file. If a file is already open, function will fail.
// returns true if no error
bool Open(const char * file);
// Open log file. If a file is already open, function will fail.
// returns true if no error
bool Open(const char * file);
// Close log file if opened.
void Close(void);
// Close log file if opened.
void Close(void);
// Make an entry in the log. Format and variable arguments are identical to printf.
// severity will be compared to master log level to determine if the log entry will be made
// severity will be compared to master print level to determine if the log entry will be printed to stdout
void Log(eLogLevel severity, char * format, ...);
// Make an entry in the log. Format and variable arguments are identical to printf.
// severity will be compared to master log level to determine if the log entry will be made
// severity will be compared to master print level to determine if the log entry will be printed to stdout
void Log(eLogLevel severity, char * format, ...);
// Equivalent to the above with the approriate severity argument
void LogError(char * format, ...);
void LogAlert(char * format, ...);
void Log(char * format, ...);
void LogDebug(char * format, ...);
// Equivalent to the above with the approriate severity argument
void LogError(char * format, ...);
void LogAlert(char * format, ...);
void Log(char * format, ...);
void LogDebug(char * format, ...);
private:
FILE * pFile; // current log file opened
char * pFilename; // current log file opened
int nTodaysDayOfYear; // remember the current day to detect change of day
void Archive(void); // archives current log
private:
FILE * pFile; // current log file opened
char * pFilename; // current log file opened
int nTodaysDayOfYear; // remember the current day to detect change of day
void Archive(void); // archives current log
static eLogLevel nLogMask; // master severity level
static eLogLevel nPrintMask; // master severity level
static eLogLevel nFlushMask; // master severity level
};
static eLogLevel nLogMask; // master severity level
static eLogLevel nPrintMask; // master severity level
static eLogLevel nFlushMask; // master severity level
};
//-------------------------------------
inline void CAutoLog::SetLogLevel(eLogLevel loglevel)
{
nLogMask = loglevel;
}
//-------------------------------------
inline void CAutoLog::SetLogLevel(eLogLevel loglevel)
{
nLogMask = loglevel;
}
//-------------------------------------
inline void CAutoLog::SetPrintLevel(eLogLevel printlevel)
{
nPrintMask = printlevel;
}
//-------------------------------------
inline void CAutoLog::SetPrintLevel(eLogLevel printlevel)
{
nPrintMask = printlevel;
}
//-------------------------------------
inline void CAutoLog::SetFlushLevel(eLogLevel flushlevel)
{
nFlushMask = flushlevel;
}
//-------------------------------------
inline void CAutoLog::SetFlushLevel(eLogLevel flushlevel)
{
nFlushMask = flushlevel;
}
//-------------------------------------
inline CAutoLog::CAutoLog()
{
pFilename = nullptr;
pFile = (FILE *)-1;
nTodaysDayOfYear = 0;
}
//-------------------------------------
inline CAutoLog::CAutoLog()
{
pFilename = nullptr;
pFile = (FILE *)-1;
}
//-------------------------------------
inline CAutoLog::CAutoLog(const char * file)
{
pFilename = nullptr;
pFile = (FILE *)-1;
Open(file);
}
//-------------------------------------
inline CAutoLog::CAutoLog(const char * file)
{
pFilename = nullptr;
pFile = (FILE *)-1;
Open(file);
}
//-------------------------------------
inline CAutoLog::~CAutoLog()
{
Close();
}
};
//-------------------------------------
inline CAutoLog::~CAutoLog()
{
Close();
}
};
#ifdef EXTERNAL_DISTRO
};
};
#endif
#endif
@@ -3,476 +3,473 @@
using namespace std;
namespace ChatSystem
namespace ChatSystem
{
// AVATAR ITERATOR CORE
// AVATAR ITERATOR CORE
AvatarIteratorCore::AvatarIteratorCore()
: m_map(nullptr)
{
}
AvatarIteratorCore::AvatarIteratorCore(std::map<unsigned, ChatAvatar *> *mapIn, std::map<unsigned, ChatAvatar *>::iterator iter)
: m_map(mapIn),
m_mapIter(iter)
{
}
AvatarIteratorCore::~AvatarIteratorCore()
{
}
AvatarIteratorCore &AvatarIteratorCore::operator=(const AvatarIteratorCore& rhs)
{
m_map = rhs.m_map;
m_mapIter = rhs.m_mapIter;
return (*this);
}
ChatAvatar *AvatarIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
AvatarIteratorCore::AvatarIteratorCore()
: m_map(nullptr), m_mapIter()
{
returnVal = (*m_mapIter).second;
}
return returnVal;
}
bool AvatarIteratorCore::increment()
{
bool returnVal = false;
m_mapIter++;
if (!outOfBounds())
AvatarIteratorCore::AvatarIteratorCore(std::map<unsigned, ChatAvatar *> *mapIn, std::map<unsigned, ChatAvatar *>::iterator iter)
: m_map(mapIn),
m_mapIter(iter)
{
returnVal = true;
}
return returnVal;
}
bool AvatarIteratorCore::decrement()
{
bool returnVal = false;
m_mapIter--;
if (!outOfBounds())
AvatarIteratorCore::~AvatarIteratorCore()
{
returnVal = true;
}
return returnVal;
}
bool AvatarIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_map)
AvatarIteratorCore &AvatarIteratorCore::operator=(const AvatarIteratorCore& rhs)
{
if (m_mapIter != m_map->end())
m_map = rhs.m_map;
m_mapIter = rhs.m_mapIter;
return (*this);
}
ChatAvatar *AvatarIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
{
returnVal = false;
returnVal = (*m_mapIter).second;
}
return returnVal;
}
return returnVal;
}
// MODERATOR ITERATOR CORE
ModeratorIteratorCore::ModeratorIteratorCore()
: m_set(nullptr)
{
}
ModeratorIteratorCore::ModeratorIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
ModeratorIteratorCore::~ModeratorIteratorCore()
{
}
ModeratorIteratorCore &ModeratorIteratorCore::operator=(const ModeratorIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *ModeratorIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
bool AvatarIteratorCore::increment()
{
returnVal = (*m_setIter);
}
bool returnVal = false;
return returnVal;
}
bool ModeratorIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool ModeratorIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool ModeratorIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
m_mapIter++;
if (!outOfBounds())
{
returnVal = false;
returnVal = true;
}
return returnVal;
}
return returnVal;
}
// TEMPORARY MODERATOR ITERATOR CORE
TemporaryModeratorIteratorCore::TemporaryModeratorIteratorCore()
: m_set(nullptr)
{
}
TemporaryModeratorIteratorCore::TemporaryModeratorIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
TemporaryModeratorIteratorCore::~TemporaryModeratorIteratorCore()
{
}
TemporaryModeratorIteratorCore &TemporaryModeratorIteratorCore::operator=(const TemporaryModeratorIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *TemporaryModeratorIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
bool AvatarIteratorCore::decrement()
{
returnVal = (*m_setIter);
}
bool returnVal = false;
return returnVal;
}
bool TemporaryModeratorIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool TemporaryModeratorIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool TemporaryModeratorIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
m_mapIter--;
if (!outOfBounds())
{
returnVal = false;
returnVal = true;
}
return returnVal;
}
return returnVal;
}
// VOICE ITERATOR CORE
VoiceIteratorCore::VoiceIteratorCore()
: m_set(nullptr)
{
}
VoiceIteratorCore::VoiceIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
VoiceIteratorCore::~VoiceIteratorCore()
{
}
VoiceIteratorCore &VoiceIteratorCore::operator=(const VoiceIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *VoiceIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
bool AvatarIteratorCore::outOfBounds()
{
returnVal = (*m_setIter);
}
bool returnVal = true;
return returnVal;
}
bool VoiceIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool VoiceIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool VoiceIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
if (m_map)
{
returnVal = false;
if (m_mapIter != m_map->end())
{
returnVal = false;
}
}
return returnVal;
}
return returnVal;
}
// MODERATOR ITERATOR CORE
// INVITE ITERATOR CORE
InviteIteratorCore::InviteIteratorCore()
: m_set(nullptr)
{
}
InviteIteratorCore::InviteIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
InviteIteratorCore::~InviteIteratorCore()
{
}
InviteIteratorCore &InviteIteratorCore::operator=(const InviteIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *InviteIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
ModeratorIteratorCore::ModeratorIteratorCore()
: m_set(nullptr), m_setIter()
{
returnVal = (*m_setIter);
}
return returnVal;
}
bool InviteIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
ModeratorIteratorCore::ModeratorIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
returnVal = true;
}
return returnVal;
}
bool InviteIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
ModeratorIteratorCore::~ModeratorIteratorCore()
{
returnVal = true;
}
return returnVal;
}
bool InviteIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
ModeratorIteratorCore &ModeratorIteratorCore::operator=(const ModeratorIteratorCore& rhs)
{
if (m_setIter != m_set->end())
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *ModeratorIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
{
returnVal = false;
returnVal = (*m_setIter);
}
return returnVal;
}
return returnVal;
}
// BAN ITERATOR CORE
BanIteratorCore::BanIteratorCore()
: m_set(nullptr)
{
}
BanIteratorCore::BanIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
BanIteratorCore::~BanIteratorCore()
{
}
BanIteratorCore &BanIteratorCore::operator=(const BanIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *BanIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
bool ModeratorIteratorCore::increment()
{
returnVal = (*m_setIter);
}
bool returnVal = false;
return returnVal;
}
bool BanIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool BanIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool BanIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
m_setIter++;
if (!outOfBounds())
{
returnVal = false;
returnVal = true;
}
return returnVal;
}
return returnVal;
}
bool ModeratorIteratorCore::decrement()
{
bool returnVal = false;
};
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool ModeratorIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
{
returnVal = false;
}
}
return returnVal;
}
// TEMPORARY MODERATOR ITERATOR CORE
TemporaryModeratorIteratorCore::TemporaryModeratorIteratorCore()
: m_set(nullptr), m_setIter()
{
}
TemporaryModeratorIteratorCore::TemporaryModeratorIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
TemporaryModeratorIteratorCore::~TemporaryModeratorIteratorCore()
{
}
TemporaryModeratorIteratorCore &TemporaryModeratorIteratorCore::operator=(const TemporaryModeratorIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *TemporaryModeratorIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
{
returnVal = (*m_setIter);
}
return returnVal;
}
bool TemporaryModeratorIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool TemporaryModeratorIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool TemporaryModeratorIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
{
returnVal = false;
}
}
return returnVal;
}
// VOICE ITERATOR CORE
VoiceIteratorCore::VoiceIteratorCore()
: m_set(nullptr), m_setIter()
{
}
VoiceIteratorCore::VoiceIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
VoiceIteratorCore::~VoiceIteratorCore()
{
}
VoiceIteratorCore &VoiceIteratorCore::operator=(const VoiceIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *VoiceIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
{
returnVal = (*m_setIter);
}
return returnVal;
}
bool VoiceIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool VoiceIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool VoiceIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
{
returnVal = false;
}
}
return returnVal;
}
// INVITE ITERATOR CORE
InviteIteratorCore::InviteIteratorCore()
: m_set(nullptr), m_setIter()
{
}
InviteIteratorCore::InviteIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
InviteIteratorCore::~InviteIteratorCore()
{
}
InviteIteratorCore &InviteIteratorCore::operator=(const InviteIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *InviteIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
{
returnVal = (*m_setIter);
}
return returnVal;
}
bool InviteIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool InviteIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool InviteIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
{
returnVal = false;
}
}
return returnVal;
}
// BAN ITERATOR CORE
BanIteratorCore::BanIteratorCore()
: m_set(nullptr), m_setIter()
{
}
BanIteratorCore::BanIteratorCore(std::set<ChatAvatar *> *setIn, std::set<ChatAvatar *>::iterator iter)
: m_set(setIn),
m_setIter(iter)
{
}
BanIteratorCore::~BanIteratorCore()
{
}
BanIteratorCore &BanIteratorCore::operator=(const BanIteratorCore& rhs)
{
m_set = rhs.m_set;
m_setIter = rhs.m_setIter;
return (*this);
}
ChatAvatar *BanIteratorCore::getCurAvatar()
{
ChatAvatar *returnVal = nullptr;
if (!outOfBounds())
{
returnVal = (*m_setIter);
}
return returnVal;
}
bool BanIteratorCore::increment()
{
bool returnVal = false;
m_setIter++;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool BanIteratorCore::decrement()
{
bool returnVal = false;
m_setIter--;
if (!outOfBounds())
{
returnVal = true;
}
return returnVal;
}
bool BanIteratorCore::outOfBounds()
{
bool returnVal = true;
if (m_set)
{
if (m_setIter != m_set->end())
{
returnVal = false;
}
}
return returnVal;
}
};
File diff suppressed because it is too large Load Diff
@@ -1,186 +1,184 @@
#include "ChatAvatarCore.h"
#include "ChatAvatar.h"
namespace ChatSystem
namespace ChatSystem
{
using namespace Plat_Unicode;
using namespace Base;
using namespace Plat_Unicode;
using namespace Base;
ChatAvatarCore::ChatAvatarCore()
: m_inboxLimit(0),
m_loginPriority(0),
m_userID(0),
m_avatarID(0),
m_serverID(0),
m_gatewayID(0),
m_attributes(0)
{
}
ChatAvatarCore::ChatAvatarCore()
: m_inboxLimit(0),
m_loginPriority(0),
m_userID(0),
m_avatarID(0),
m_serverID(0),
m_gatewayID(0)
{
}
ChatAvatarCore::ChatAvatarCore(unsigned avatarID, unsigned userID, const unsigned short *name, const unsigned short *address, const unsigned short *gateway, const unsigned short *server, unsigned gatewayID, unsigned serverID, const unsigned short *loginLocation, unsigned attributes)
: m_name(name),
m_address(address),
m_server(server),
m_gateway(gateway),
m_loginLocation(loginLocation),
m_attributes(attributes),
m_inboxLimit(0),
m_loginPriority(0),
m_userID(userID),
m_avatarID(avatarID),
m_serverID(serverID),
m_gatewayID(gatewayID)
{
}
ChatAvatarCore::ChatAvatarCore(unsigned avatarID, unsigned userID, const unsigned short *name, const unsigned short *address, const unsigned short *gateway, const unsigned short *server, unsigned gatewayID, unsigned serverID, const unsigned short *loginLocation, unsigned attributes)
: m_name(name),
m_address(address),
m_server(server),
m_gateway(gateway),
m_loginLocation(loginLocation),
m_attributes(attributes),
m_inboxLimit(0),
m_loginPriority(0),
m_userID(userID),
m_avatarID(avatarID),
m_serverID(serverID),
m_gatewayID(gatewayID)
{
}
ChatAvatarCore::ChatAvatarCore(unsigned avatarID, unsigned userID, const ChatUnicodeString &name, const ChatUnicodeString &address, const ChatUnicodeString &gateway, const ChatUnicodeString &server, unsigned gatewayID, unsigned serverID, const ChatUnicodeString &loginLocation, unsigned attributes)
: m_name(name.string_data, name.string_length),
m_address(address.string_data, address.string_length),
m_server(server.string_data, server.string_length),
m_gateway(gateway.string_data, gateway.string_length),
m_loginLocation(loginLocation.string_data, loginLocation.string_length),
m_attributes(attributes),
m_inboxLimit(0),
m_loginPriority(0),
m_userID(userID),
m_avatarID(avatarID),
m_serverID(serverID),
m_gatewayID(gatewayID)
{
}
ChatAvatarCore::ChatAvatarCore(unsigned avatarID, unsigned userID, const ChatUnicodeString &name, const ChatUnicodeString &address, const ChatUnicodeString &gateway, const ChatUnicodeString &server, unsigned gatewayID, unsigned serverID, const ChatUnicodeString &loginLocation, unsigned attributes)
: m_name(name.string_data, name.string_length),
m_address(address.string_data, address.string_length),
m_server(server.string_data, server.string_length),
m_gateway(gateway.string_data, gateway.string_length),
m_loginLocation(loginLocation.string_data, loginLocation.string_length),
m_attributes(attributes),
m_inboxLimit(0),
m_loginPriority(0),
m_userID(userID),
m_avatarID(avatarID),
m_serverID(serverID),
m_gatewayID(gatewayID)
{
}
ChatAvatarCore::ChatAvatarCore(unsigned avatarID, unsigned userID, const String &name, const String &address, const String &gateway, const String &server, unsigned gatewayID, unsigned serverID, const Plat_Unicode::String &loginLocation, unsigned attributes)
: m_name(name),
m_address(address),
m_server(server),
m_gateway(gateway),
m_loginLocation(loginLocation),
m_attributes(attributes),
m_inboxLimit(0),
m_loginPriority(0),
m_userID(userID),
m_avatarID(avatarID),
m_serverID(serverID),
m_gatewayID(gatewayID)
{
}
ChatAvatarCore::ChatAvatarCore(unsigned avatarID, unsigned userID, const String &name, const String &address, const String &gateway, const String &server, unsigned gatewayID, unsigned serverID, const Plat_Unicode::String &loginLocation, unsigned attributes)
: m_name(name),
m_address(address),
m_server(server),
m_gateway(gateway),
m_loginLocation(loginLocation),
m_attributes(attributes),
m_inboxLimit(0),
m_loginPriority(0),
m_userID(userID),
m_avatarID(avatarID),
m_serverID(serverID),
m_gatewayID(gatewayID)
{
}
ChatAvatarCore::ChatAvatarCore(ByteStream::ReadIterator &iter)
{
get(iter, m_avatarID);
get(iter, m_userID);
ASSERT_VALID_STRING_LENGTH(get(iter, m_name));
ASSERT_VALID_STRING_LENGTH(get(iter, m_address));
get(iter, (uint32 &)m_attributes);
ASSERT_VALID_STRING_LENGTH(get(iter, m_loginLocation));
ASSERT_VALID_STRING_LENGTH(get(iter, m_server));
ASSERT_VALID_STRING_LENGTH(get(iter, m_gateway));
get(iter, m_serverID);
get(iter, m_gatewayID);
m_loginPriority = 0;
m_inboxLimit = 0;
}
ChatAvatarCore::ChatAvatarCore(ByteStream::ReadIterator &iter)
{
get(iter, m_avatarID);
get(iter, m_userID);
ASSERT_VALID_STRING_LENGTH(get(iter, m_name));
ASSERT_VALID_STRING_LENGTH(get(iter, m_address));
get(iter, (uint32 &)m_attributes);
ASSERT_VALID_STRING_LENGTH(get(iter, m_loginLocation));
ASSERT_VALID_STRING_LENGTH(get(iter, m_server));
ASSERT_VALID_STRING_LENGTH(get(iter, m_gateway));
get(iter, m_serverID);
get(iter, m_gatewayID);
ChatAvatarCore::ChatAvatarCore(const ChatAvatarCore &rhs)
: m_name(rhs.m_name),
m_address(rhs.m_address),
m_server(rhs.m_server),
m_gateway(rhs.m_gateway),
m_loginLocation(rhs.m_loginLocation),
m_email(rhs.m_email),
m_statusMessage(rhs.m_statusMessage),
m_attributes(rhs.m_attributes),
m_inboxLimit(rhs.m_inboxLimit),
m_loginPriority(rhs.m_loginPriority),
m_userID(rhs.m_userID),
m_avatarID(rhs.m_avatarID),
m_serverID(rhs.m_serverID),
m_gatewayID(rhs.m_gatewayID)
{
}
m_loginPriority = 0;
m_inboxLimit = 0;
}
ChatAvatarCore &ChatAvatarCore::operator=(const ChatAvatarCore &rhs)
{
m_name = rhs.m_name;
m_address = rhs.m_address;
m_userID = rhs.m_userID;
m_avatarID = rhs.m_avatarID;
m_server = rhs.m_server;
m_gateway = rhs.m_gateway;
m_serverID = rhs.m_serverID;
m_gatewayID = rhs.m_gatewayID;
m_attributes = rhs.m_attributes;
m_inboxLimit = rhs.m_inboxLimit;
m_loginPriority = rhs.m_loginPriority;
m_loginLocation = rhs.m_loginLocation;
m_email = rhs.m_email;
m_inboxLimit = rhs.m_inboxLimit;
m_statusMessage = rhs.m_statusMessage;
ChatAvatarCore::ChatAvatarCore(const ChatAvatarCore &rhs)
: m_name(rhs.m_name),
m_address(rhs.m_address),
m_server(rhs.m_server),
m_gateway(rhs.m_gateway),
m_loginLocation(rhs.m_loginLocation),
m_email(rhs.m_email),
m_statusMessage(rhs.m_statusMessage),
m_attributes(rhs.m_attributes),
m_inboxLimit(rhs.m_inboxLimit),
m_loginPriority(rhs.m_loginPriority),
m_userID(rhs.m_userID),
m_avatarID(rhs.m_avatarID),
m_serverID(rhs.m_serverID),
m_gatewayID(rhs.m_gatewayID)
{
}
return(*this);
}
ChatAvatarCore &ChatAvatarCore::operator=(const ChatAvatarCore &rhs)
{
m_name = rhs.m_name;
m_address = rhs.m_address;
m_userID = rhs.m_userID;
m_avatarID = rhs.m_avatarID;
m_server = rhs.m_server;
m_gateway = rhs.m_gateway;
m_serverID = rhs.m_serverID;
m_gatewayID = rhs.m_gatewayID;
m_attributes = rhs.m_attributes;
m_inboxLimit = rhs.m_inboxLimit;
m_loginPriority = rhs.m_loginPriority;
m_loginLocation = rhs.m_loginLocation;
m_email = rhs.m_email;
m_inboxLimit = rhs.m_inboxLimit;
m_statusMessage = rhs.m_statusMessage;
ChatAvatar *ChatAvatarCore::getNewChatAvatar() const
{
ChatUnicodeString addr(m_address.data(), m_address.size());
ChatUnicodeString name(m_name.data(), m_name.size());
ChatUnicodeString gateway(m_gateway.data(), m_gateway.size());
ChatUnicodeString server(m_server.data(), m_server.size());
return(*this);
}
ChatAvatar *newChatAvatar = new ChatAvatar(m_avatarID,
m_userID,
name,
addr,
gateway,
server,
m_gatewayID,
m_serverID,
m_loginLocation,
m_attributes);
ChatAvatar *ChatAvatarCore::getNewChatAvatar() const
{
ChatUnicodeString addr(m_address.data(), m_address.size());
ChatUnicodeString name(m_name.data(), m_name.size());
ChatUnicodeString gateway(m_gateway.data(), m_gateway.size());
ChatUnicodeString server(m_server.data(), m_server.size());
newChatAvatar->setLoginPriority(m_loginPriority);
newChatAvatar->setInboxLimit(m_inboxLimit);
newChatAvatar->setForwardingEmail(m_email);
newChatAvatar->setStatusMessage(m_statusMessage);
ChatAvatar *newChatAvatar = new ChatAvatar(m_avatarID,
m_userID,
name,
addr,
gateway,
server,
m_gatewayID,
m_serverID,
m_loginLocation,
m_attributes);
return (newChatAvatar);
}
newChatAvatar->setLoginPriority(m_loginPriority);
newChatAvatar->setInboxLimit(m_inboxLimit);
newChatAvatar->setForwardingEmail(m_email);
newChatAvatar->setStatusMessage(m_statusMessage);
void ChatAvatarCore::serialize(Base::ByteStream &msg)
{
put(msg, m_avatarID);
put(msg, m_userID);
put(msg, m_name);
put(msg, m_address);
put(msg, (uint32)m_attributes);
put(msg, m_loginLocation);
}
return (newChatAvatar);
}
void ChatAvatarCore::setAttributes(unsigned long attributes)
{
m_attributes = attributes;
}
void ChatAvatarCore::serialize(Base::ByteStream &msg)
{
put(msg, m_avatarID);
put(msg, m_userID);
put(msg, m_name);
put(msg, m_address);
put(msg, (uint32)m_attributes);
put(msg, m_loginLocation);
}
void ChatAvatarCore::setLoginPriority(int loginPriority)
{
m_loginPriority = loginPriority;
}
void ChatAvatarCore::setAttributes(unsigned long attributes)
{
m_attributes = attributes;
}
void ChatAvatarCore::setEmail(const Plat_Unicode::String email)
{
m_email = email;
}
void ChatAvatarCore::setLoginPriority(int loginPriority)
{
m_loginPriority = loginPriority;
}
void ChatAvatarCore::setInboxLimit(unsigned inboxLimit)
{
m_inboxLimit = inboxLimit;
}
void ChatAvatarCore::setEmail(const Plat_Unicode::String email)
{
m_email = email;
}
void ChatAvatarCore::setInboxLimit(unsigned inboxLimit)
{
m_inboxLimit = inboxLimit;
}
void ChatAvatarCore::setStatusMessage(const Plat_Unicode::String &statusMessage)
{
m_statusMessage = statusMessage;
}
};
void ChatAvatarCore::setStatusMessage(const Plat_Unicode::String &statusMessage)
{
m_statusMessage = statusMessage;
}
};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+83 -84
View File
@@ -6,110 +6,109 @@
#include <time.h>
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
namespace Base
{
namespace Base
{
class CAutoLog
{
public:
enum eLogLevel {
eLOG_NONE = 0, // log entries are discarded
eLOG_ERROR = 1, // log errors only
eLOG_ALERT = 2, // log alerts and errors only
eLOG_NORMAL = 3, // log all normal events, no debug
eLOG_DEBUG = 4 // log everything
};
class CAutoLog
{
public:
enum eLogLevel {
eLOG_NONE = 0, // log entries are discarded
eLOG_ERROR = 1, // log errors only
eLOG_ALERT = 2, // log alerts and errors only
eLOG_NORMAL = 3, // log all normal events, no debug
eLOG_DEBUG = 4 // log everything
};
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_NORMAL.
void SetLogLevel(eLogLevel loglevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_NORMAL.
void SetLogLevel(eLogLevel loglevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetPrintLevel(eLogLevel printlevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetPrintLevel(eLogLevel printlevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetFlushLevel(eLogLevel flushlevel);
// Global setting for all AutoLog instances for this application. Can be set on the fly. Default is eLOG_ERROR.
void SetFlushLevel(eLogLevel flushlevel);
// constructor, no file loaded
CAutoLog();
// constructor, no file loaded
CAutoLog();
// version of constructor that calls Open(file)
CAutoLog(const char * file);
// version of constructor that calls Open(file)
CAutoLog(const char * file);
// destructor, will close file if opened
~CAutoLog();
// destructor, will close file if opened
~CAutoLog();
// Open log file. If a file is already open, function will fail.
// returns true if no error
bool Open(const char * file);
// Open log file. If a file is already open, function will fail.
// returns true if no error
bool Open(const char * file);
// Close log file if opened.
void Close(void);
// Close log file if opened.
void Close(void);
// Make an entry in the log. Format and variable arguments are identical to printf.
// severity will be compared to master log level to determine if the log entry will be made
// severity will be compared to master print level to determine if the log entry will be printed to stdout
void Log(eLogLevel severity, char * format, ...);
// Make an entry in the log. Format and variable arguments are identical to printf.
// severity will be compared to master log level to determine if the log entry will be made
// severity will be compared to master print level to determine if the log entry will be printed to stdout
void Log(eLogLevel severity, char * format, ...);
// Equivalent to the above with the approriate severity argument
void LogError(char * format, ...);
void LogAlert(char * format, ...);
void Log(char * format, ...);
void LogDebug(char * format, ...);
// Equivalent to the above with the approriate severity argument
void LogError(char * format, ...);
void LogAlert(char * format, ...);
void Log(char * format, ...);
void LogDebug(char * format, ...);
private:
FILE * pFile; // current log file opened
char * pFilename; // current log file opened
int nTodaysDayOfYear; // remember the current day to detect change of day
void Archive(void); // archives current log
private:
FILE * pFile; // current log file opened
char * pFilename; // current log file opened
int nTodaysDayOfYear; // remember the current day to detect change of day
void Archive(void); // archives current log
static eLogLevel nLogMask; // master severity level
static eLogLevel nPrintMask; // master severity level
static eLogLevel nFlushMask; // master severity level
};
static eLogLevel nLogMask; // master severity level
static eLogLevel nPrintMask; // master severity level
static eLogLevel nFlushMask; // master severity level
};
//-------------------------------------
inline void CAutoLog::SetLogLevel(eLogLevel loglevel)
{
nLogMask = loglevel;
}
//-------------------------------------
inline void CAutoLog::SetLogLevel(eLogLevel loglevel)
{
nLogMask = loglevel;
}
//-------------------------------------
inline void CAutoLog::SetPrintLevel(eLogLevel printlevel)
{
nPrintMask = printlevel;
}
//-------------------------------------
inline void CAutoLog::SetPrintLevel(eLogLevel printlevel)
{
nPrintMask = printlevel;
}
//-------------------------------------
inline void CAutoLog::SetFlushLevel(eLogLevel flushlevel)
{
nFlushMask = flushlevel;
}
//-------------------------------------
inline void CAutoLog::SetFlushLevel(eLogLevel flushlevel)
{
nFlushMask = flushlevel;
}
//-------------------------------------
inline CAutoLog::CAutoLog()
{
pFilename = nullptr;
pFile = (FILE *)-1;
nTodaysDayOfYear = 0;
}
//-------------------------------------
inline CAutoLog::CAutoLog()
{
pFilename = nullptr;
pFile = (FILE *)-1;
}
//-------------------------------------
inline CAutoLog::CAutoLog(const char * file)
{
pFilename = nullptr;
pFile = (FILE *)-1;
Open(file);
}
//-------------------------------------
inline CAutoLog::CAutoLog(const char * file)
{
pFilename = nullptr;
pFile = (FILE *)-1;
Open(file);
}
//-------------------------------------
inline CAutoLog::~CAutoLog()
{
Close();
}
};
//-------------------------------------
inline CAutoLog::~CAutoLog()
{
Close();
}
};
#ifdef EXTERNAL_DISTRO
};
#endif
@@ -2,297 +2,286 @@
#include "GenericAPI/GenericConnection.h"
#include "GenericAPI/GenericMessage.h"
using namespace UdpLibrary;
#ifdef USE_SERIALIZE_LIB
#include <Base/serialize.h>
#include <Base/serialize.h>
#endif
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
namespace GenericAPI
{
namespace GenericAPI
{
using namespace std;
using namespace Base;
using namespace std;
using namespace Base;
unsigned GenericConnection::ms_crcBytes = 0;
unsigned GenericConnection::ms_crcBytes = 0;
GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned noAckTimeoutSecs, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB, unsigned holdTime)
: m_bConnected(false),
m_apiCore(apiCore),
m_con(nullptr),
m_host(host),
m_nextHost(host),
m_port(port),
m_nextPort(port),
m_lastTrack(123455), //random choice != 1
m_conState(CON_DISCONNECT),
m_reconnectTimeout(reconnectTimeout)
{
GenericConnection::GenericConnection(const char *host, short port, GenericAPICore *apiCore, unsigned reconnectTimeout, unsigned noDataTimeoutSecs, unsigned noAckTimeoutSecs, unsigned incomingBufSizeInKB, unsigned outgoingBufSizeInKB, unsigned keepAlive, unsigned maxRecvMessageSizeInKB, unsigned holdTime)
: m_bConnected(false),
m_apiCore(apiCore),
m_con(nullptr),
m_host(host),
m_nextHost(host),
m_port(port),
m_nextPort(port),
m_lastTrack(123455), //random choice != 1
m_conState(CON_DISCONNECT),
m_reconnectTimeout(reconnectTimeout),
m_conTimeout(100)
{
#ifdef USE_TCP_LIBRARY
TcpManager::TcpParams params;
params.incomingBufferSize = incomingBufSizeInKB * 1024;
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
params.maxConnections = 1;
params.port = 0;
params.maxRecvMessageSize = maxRecvMessageSizeInKB*1024;
params.keepAliveDelay = keepAlive * 1000;
params.noDataTimeout = noDataTimeoutSecs * 1000;
//params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
m_manager = new TcpManager(params);
#else //default to UDP_LIBRARY
UdpManager::Params params;
TcpManager::TcpParams params;
params.keepAliveDelay = keepAlive * 1000;
params.maxDataHoldTime = holdTime;
params.incomingBufferSize = incomingBufSizeInKB * 1024;
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
params.maxConnections = 1;
params.port = 0;
params.noDataTimeout = noDataTimeoutSecs * 1000;
params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
params.crcBytes = ms_crcBytes;
m_manager = new UdpManager(&params);
params.incomingBufferSize = incomingBufSizeInKB * 1024;
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
params.maxConnections = 1;
params.port = 0;
params.maxRecvMessageSize = maxRecvMessageSizeInKB * 1024;
params.keepAliveDelay = keepAlive * 1000;
params.noDataTimeout = noDataTimeoutSecs * 1000;
//params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
m_manager = new TcpManager(params);
#else //default to UDP_LIBRARY
UdpManager::Params params;
params.keepAliveDelay = keepAlive * 1000;
params.maxDataHoldTime = holdTime;
params.incomingBufferSize = incomingBufSizeInKB * 1024;
params.outgoingBufferSize = outgoingBufSizeInKB * 1024;
params.maxConnections = 1;
params.port = 0;
params.noDataTimeout = noDataTimeoutSecs * 1000;
params.oldestUnacknowledgedTimeout = noAckTimeoutSecs * 1000;
params.crcBytes = ms_crcBytes;
m_manager = new UdpManager(&params);
#endif //USE_TCP_LIBRARY
}
GenericConnection::~GenericConnection()
{
if(m_con)
{
m_con->SetHandler(nullptr);
m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont
m_con->Release();
}
m_manager->Release();
}
void GenericConnection::changeHostPort(const char *host, short port)
{
if (host &&
strcmp(host, "") != 0)
{
m_nextHost = host;
m_nextPort = port;
}
}
void GenericConnection::disconnect()
{
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
}
m_conState = CON_DISCONNECT;
m_bConnected = false;
}
#ifdef USE_TCP_LIBRARY
void GenericConnection::OnTerminated(TcpConnection *con)
#else //default to UDP_LIBRARY
void GenericConnection::OnTerminated(UdpConnection *con)
#endif
{
m_apiCore->OnDisconnect(m_host.c_str(), m_port);
if(m_con)
{
m_con->Release();
m_con = nullptr;
}
m_conState = CON_DISCONNECT;
m_bConnected = false;
}
#ifdef USE_TCP_LIBRARY
void GenericConnection::OnRoutePacket(TcpConnection *con, const unsigned char *data, int dataLen)
#else //default to UDP_LIBRARY
void GenericConnection::OnRoutePacket(UdpConnection *con, const unsigned char *data, int dataLen)
#endif
{
short type;
unsigned track;
#ifdef USE_SERIALIZE_LIB
unsigned bytes = 0;
unsigned fieldLen = soe::Read(data, dataLen, type);
if (fieldLen == 0)
return;//invalid message
bytes += fieldLen;
fieldLen = soe::Read(data+bytes, dataLen-bytes, track);
if (fieldLen == 0)
return;//invalid message
bytes += fieldLen;
#else
ByteStream msg(data, dataLen);
ByteStream::ReadIterator iter = msg.begin();
get(iter, type);
get(iter, track);
#endif
GenericResponse *res = nullptr;
// the following if block is a temporary fix that prevents
// a crash with a game team in which they occasionally find
// themselves receiving a dupe track in consecutive calls to
// OnRoutePacket (which then leads to a callback being called
// twice and data being invalid on the second call -> crash!).
if (track != 0 &&
track == m_lastTrack)
{
printf("!!! ERROR !!! Got a duplicate track ID %u\n", track);
return;
}
m_lastTrack = track;
// end temporary fix.
if(track == 0)
{
#ifdef USE_SERIALIZE_LIB
m_apiCore->responseCallback(type, data+bytes, dataLen-bytes);
#else
m_apiCore->responseCallback(type, iter);
#endif
}
else
{
map<unsigned, GenericResponse *>::iterator mapIter = m_apiCore->m_pending.find(track);
if(mapIter != m_apiCore->m_pending.end())
{
res = (*mapIter).second;
#ifdef USE_SERIALIZE_LIB
res->unpack(data, dataLen);
#else
iter = msg.begin();
res->unpack(iter);
#endif
m_apiCore->m_pending.erase(mapIter);
m_apiCore->m_pendingCount--;
m_apiCore->responseCallback(res);
delete res;
}
}
}
void GenericConnection::process(bool giveTime)
{
switch(m_conState)
{
case CON_DISCONNECT:
// if host/port was changed, it takes effect here
m_host = m_nextHost;
m_port = m_nextPort;
// create connection object, attempting to connect and
// checking for connection in next state, CON_NEGOTIATE
m_con = m_manager->EstablishConnection(m_host.c_str(), m_port);
if(m_con)
GenericConnection::~GenericConnection()
{
m_con->SetHandler(this);
m_conState = CON_NEGOTIATE;
m_conTimeout = time(nullptr) + m_reconnectTimeout;
}
break;
case CON_NEGOTIATE:
// check for connection
if (m_con)
{
m_con->SetHandler(nullptr);
m_con->Disconnect();//don't worry about onterminated being called, we've set it's handler to nullptr, so it wont
m_con->Release();
}
#ifdef USE_TCP_LIBRARY
if(m_con->GetStatus() == TcpConnection::StatusConnected)
#else //default to UDP_LIBRARY
if(m_con->GetStatus() == UdpConnection::cStatusConnected)
#endif
{
// we're connected
m_conState = CON_CONNECT;
m_apiCore->OnConnect(m_host.c_str(), m_port);
m_bConnected = true;
m_manager->Release();
}
else if(time(nullptr) > m_conTimeout)
void GenericConnection::changeHostPort(const char *host, short port)
{
// we did not connect
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
if (host &&
strcmp(host, "") != 0)
{
m_nextHost = host;
m_nextPort = port;
}
}
void GenericConnection::disconnect()
{
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
}
m_conState = CON_DISCONNECT;
m_bConnected = false;
m_bConnected = false;
}
break;
case CON_CONNECT:
// do nothing
break;
default:
// this should not occur, but we revert to CON_DISCONNECT if it does
m_conState = CON_DISCONNECT;
m_bConnected = false;
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
}
}
if (giveTime)
{
m_manager->GiveTime();
}
}
#ifdef USE_TCP_LIBRARY
void GenericConnection::OnTerminated(TcpConnection *con)
#else //default to UDP_LIBRARY
void GenericConnection::OnTerminated(UdpConnection *con)
#endif
{
m_apiCore->OnDisconnect(m_host.c_str(), m_port);
if (m_con)
{
m_con->Release();
m_con = nullptr;
}
m_conState = CON_DISCONNECT;
m_bConnected = false;
}
#ifdef USE_TCP_LIBRARY
void GenericConnection::OnRoutePacket(TcpConnection *con, const unsigned char *data, int dataLen)
#else //default to UDP_LIBRARY
void GenericConnection::OnRoutePacket(UdpConnection *con, const unsigned char *data, int dataLen)
#endif
{
short type;
unsigned track;
#ifdef USE_SERIALIZE_LIB
void GenericConnection::Send(const unsigned char *data, int dataLen)
{
#ifdef USE_TCP_LIBRARY
if(m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
{
m_con->Send((const char *)data, dataLen);
}
#else//USE_TCP_LIBRARY
if(m_con && m_con->GetStatus() == UdpConnection::cStatusConnected)
{
m_con->Send(cUdpChannelReliable1, data, dataLen);
}
#endif//USE_TCP_LIBRARY
}
unsigned bytes = 0;
unsigned fieldLen = soe::Read(data, dataLen, type);
if (fieldLen == 0)
return;//invalid message
bytes += fieldLen;
fieldLen = soe::Read(data + bytes, dataLen - bytes, track);
if (fieldLen == 0)
return;//invalid message
bytes += fieldLen;
#else
ByteStream msg(data, dataLen);
ByteStream::ReadIterator iter = msg.begin();
get(iter, type);
get(iter, track);
#endif
GenericResponse *res = nullptr;
// the following if block is a temporary fix that prevents
// a crash with a game team in which they occasionally find
// themselves receiving a dupe track in consecutive calls to
// OnRoutePacket (which then leads to a callback being called
// twice and data being invalid on the second call -> crash!).
if (track != 0 &&
track == m_lastTrack)
{
printf("!!! ERROR !!! Got a duplicate track ID %u\n", track);
return;
}
m_lastTrack = track;
// end temporary fix.
if (track == 0)
{
#ifdef USE_SERIALIZE_LIB
m_apiCore->responseCallback(type, data + bytes, dataLen - bytes);
#else
m_apiCore->responseCallback(type, iter);
#endif
}
else
{
map<unsigned, GenericResponse *>::iterator mapIter = m_apiCore->m_pending.find(track);
if (mapIter != m_apiCore->m_pending.end())
{
res = (*mapIter).second;
#ifdef USE_SERIALIZE_LIB
res->unpack(data, dataLen);
#else
iter = msg.begin();
res->unpack(iter);
#endif
m_apiCore->m_pending.erase(mapIter);
m_apiCore->m_pendingCount--;
m_apiCore->responseCallback(res);
delete res;
}
}
}
void GenericConnection::process(bool giveTime)
{
switch (m_conState)
{
case CON_DISCONNECT:
// if host/port was changed, it takes effect here
m_host = m_nextHost;
m_port = m_nextPort;
// create connection object, attempting to connect and
// checking for connection in next state, CON_NEGOTIATE
m_con = m_manager->EstablishConnection(m_host.c_str(), m_port);
if (m_con)
{
m_con->SetHandler(this);
m_conState = CON_NEGOTIATE;
m_conTimeout = time(nullptr) + m_reconnectTimeout;
}
break;
case CON_NEGOTIATE:
// check for connection
#ifdef USE_TCP_LIBRARY
if (m_con->GetStatus() == TcpConnection::StatusConnected)
#else //default to UDP_LIBRARY
if (m_con->GetStatus() == UdpConnection::cStatusConnected)
#endif
{
// we're connected
m_conState = CON_CONNECT;
m_apiCore->OnConnect(m_host.c_str(), m_port);
m_bConnected = true;
}
else if (time(nullptr) > m_conTimeout)
{
// we did not connect
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
m_conState = CON_DISCONNECT;
m_bConnected = false;
}
break;
case CON_CONNECT:
// do nothing
break;
default:
// this should not occur, but we revert to CON_DISCONNECT if it does
m_conState = CON_DISCONNECT;
m_bConnected = false;
if (m_con)
{
m_con->Disconnect();
//no need to release, since callback to onTerminated releases it, and callback is allways made m_con->Release();
m_con = nullptr;
}
}
if (giveTime)
{
m_manager->GiveTime();
}
}
#ifdef USE_SERIALIZE_LIB
void GenericConnection::Send(const unsigned char *data, int dataLen)
{
#ifdef USE_TCP_LIBRARY
if (m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
{
m_con->Send((const char *)data, dataLen);
}
#else//USE_TCP_LIBRARY
if (m_con && m_con->GetStatus() == UdpConnection::cStatusConnected)
{
m_con->Send(cUdpChannelReliable1, data, dataLen);
}
#endif//USE_TCP_LIBRARY
}
#else //USE_SERIALIZE_LIB
void GenericConnection::Send(Base::ByteStream &msg)
{
#ifdef USE_TCP_LIBRARY
if(m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
{
m_con->Send((const char *)msg.getBuffer(), msg.getSize());
}
#else //USE_TCP_LIBRARY
if(m_con && m_con->GetStatus() == UdpConnection::cStatusConnected)
{
m_con->Send(cUdpChannelReliable1, msg.getBuffer(), msg.getSize());
}
#endif//USE_TCP_LIBRARY
}
void GenericConnection::Send(Base::ByteStream &msg)
{
#ifdef USE_TCP_LIBRARY
if (m_con && m_con->GetStatus() == TcpConnection::StatusConnected)
{
m_con->Send((const char *)msg.getBuffer(), msg.getSize());
}
#else //USE_TCP_LIBRARY
if (m_con && m_con->GetStatus() == UdpConnection::cStatusConnected)
{
m_con->Send(cUdpChannelReliable1, msg.getBuffer(), msg.getSize());
}
#endif//USE_TCP_LIBRARY
}
#endif //USE_SERIALIZE_LIB
};
};
#ifdef EXTERNAL_DISTRO
};
#endif
#endif
@@ -1,32 +1,31 @@
#include "GenericMessage.h"
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
namespace GenericAPI
{
namespace GenericAPI
{
GenericMessage::GenericMessage(short type)
: m_type(type)
{
}
GenericMessage::GenericMessage(short type)
: m_type(type)
{
}
GenericRequest::GenericRequest(short type)
: GenericMessage(type)
{
}
GenericRequest::GenericRequest(short type)
: GenericMessage(type)
{
}
GenericResponse::GenericResponse(short type, unsigned result, void *user)
: GenericMessage(type),
m_result(result),
m_user(user)
{
}
};
GenericResponse::GenericResponse(short type, unsigned result, void *user)
: GenericMessage(type),
m_result(result),
m_user(user),
m_track(0),
m_timeout(100)
{
}
};
#ifdef EXTERNAL_DISTRO
};
#endif
#endif
@@ -24,360 +24,314 @@
//-----------------------------------------------------------------
#ifdef EXTERNAL_DISTRO
namespace NAMESPACE
namespace NAMESPACE
{
#endif
namespace Plat_Unicode
{
String narrowToWide (const NarrowString & nstr);
String & narrowToWide (const NarrowString & nstr, String & str); //lint !e1929 // function returning a reference
NarrowString wideToNarrow (const String & nstr);
NarrowString & wideToNarrow (const String & nstr, NarrowString & str); //lint !e1929 // function returning a reference
NarrowString toLower (const NarrowString & nstr);
NarrowString toUpper (const NarrowString & nstr);
String toLower (const String & nstr);
String toUpper (const String & nstr);
const String getTrim (const String & str, const unicode_char_t * white = whitespace);
String & trim (String & str, const unicode_char_t * white = whitespace);
bool getFirstToken (const String & str, size_t pos, size_t & endpos, String & token, const unicode_char_t * sepChars = whitespace);
bool getNthToken (const String & str, const size_t n, size_t & pos, size_t & endpos, String & token, const unicode_char_t * sepChars = whitespace);
size_t skipWhitespace (const String & str, size_t pos, const unicode_char_t * white = whitespace);
const NarrowString getTrim (const NarrowString & str, const char * white = ascii_whitespace);
NarrowString & trim (NarrowString & str, const char * white = ascii_whitespace);
bool getFirstToken (const NarrowString & str, size_t pos, size_t & endpos, NarrowString & token, const char * sepChars = ascii_whitespace);
bool getNthToken (const NarrowString & str, const size_t n, size_t & pos, size_t & endpos, NarrowString & token, const char * sepChars = ascii_whitespace);
size_t skipWhitespace (const NarrowString & str, size_t pos, const char * white = ascii_whitespace);
enum FieldAlignment
namespace Plat_Unicode
{
FA_LEFT,
FA_RIGHT,
FA_CENTER
};
String narrowToWide(const NarrowString & nstr);
String & narrowToWide(const NarrowString & nstr, String & str); //lint !e1929 // function returning a reference
String & appendStringField (String & dst, const String & src, size_t width, FieldAlignment fa = FA_LEFT, unicode_char_t pad = ' ', bool truncate = false);
String & appendStringField (String & dst, const NarrowString & src, size_t width, FieldAlignment fa = FA_LEFT, unicode_char_t pad = ' ', bool truncate = false);
// ======================================================================
NarrowString wideToNarrow(const String & nstr);
NarrowString & wideToNarrow(const String & nstr, NarrowString & str); //lint !e1929 // function returning a reference
NarrowString toLower(const NarrowString & nstr);
NarrowString toUpper(const NarrowString & nstr);
String toLower(const String & nstr);
String toUpper(const String & nstr);
//-----------------------------------------------------------------
/**
* Hacky code to correctly handle Cyrillic.
*/
const String getTrim(const String & str, const unicode_char_t * white = whitespace);
String & trim(String & str, const unicode_char_t * white = whitespace);
inline unicode_char_t trueUpper(unicode_char_t letter)
{
if ((cyrillic_lower_first <= letter) && (letter <= cyrillic_lower_last)) {
return letter + (cyrillic_upper_first - cyrillic_lower_first);
} else {
return static_cast<unicode_char_t>(toupper(letter));
}
}
bool getFirstToken(const String & str, size_t pos, size_t & endpos, String & token, const unicode_char_t * sepChars = whitespace);
bool getNthToken(const String & str, const size_t n, size_t & pos, size_t & endpos, String & token, const unicode_char_t * sepChars = whitespace);
size_t skipWhitespace(const String & str, size_t pos, const unicode_char_t * white = whitespace);
inline unicode_char_t trueLower(unicode_char_t letter)
{
if ((cyrillic_upper_first <= letter) && (letter <= cyrillic_upper_last)) {
return letter - (cyrillic_upper_first - cyrillic_lower_first);
} else {
return static_cast<unicode_char_t>(tolower(letter));
}
}
/**
* Compare substrings of str2 and str1, each starting with pos and containing n characters
*/
const NarrowString getTrim(const NarrowString & str, const char * white = ascii_whitespace);
NarrowString & trim(NarrowString & str, const char * white = ascii_whitespace);
bool getFirstToken(const NarrowString & str, size_t pos, size_t & endpos, NarrowString & token, const char * sepChars = ascii_whitespace);
bool getNthToken(const NarrowString & str, const size_t n, size_t & pos, size_t & endpos, NarrowString & token, const char * sepChars = ascii_whitespace);
size_t skipWhitespace(const NarrowString & str, size_t pos, const char * white = ascii_whitespace);
/**
* Compares str1 and str2, where str1 is a String and str2 is templated,
* thus could be a std::string as well. Set reverseCompare to true if you
* want to begin comparison at end of string--a useful optimization if your
* strings tend to differ at the end.
*/
template <typename T> bool caseInsensitiveCompare (const String & str1, const T & str2, bool reverseCompare = false)
{
const size_t len1 = str1.size();
const size_t len2 = str2.size();
if (len1 != len2)
enum FieldAlignment
{
return false;
}
FA_LEFT,
FA_RIGHT,
FA_CENTER
};
if (!reverseCompare)
String & appendStringField(String & dst, const String & src, size_t width, FieldAlignment fa = FA_LEFT, unicode_char_t pad = ' ', bool truncate = false);
String & appendStringField(String & dst, const NarrowString & src, size_t width, FieldAlignment fa = FA_LEFT, unicode_char_t pad = ' ', bool truncate = false);
// ======================================================================
//-----------------------------------------------------------------
/**
* Hacky code to correctly handle Cyrillic.
*/
inline unicode_char_t trueUpper(unicode_char_t letter)
{
for (size_t i = 0; i < len1; i++)
{
if ( trueLower(str1[i]) != trueLower(str2[i]) )
return false;
if ((cyrillic_lower_first <= letter) && (letter <= cyrillic_lower_last)) {
return letter + (cyrillic_upper_first - cyrillic_lower_first);
}
}
else
{
for (size_t i = len1; i > 0; i--)
{
if ( trueLower(str1[i-1]) != trueLower(str2[i-1]) )
return false;
else {
return static_cast<unicode_char_t>(toupper(letter));
}
}
return true;
}
/**
* Compares str1 and str2, where str1 is a String and str2 is templated,
* thus could be a std::string as well. Unlike caseInsensitiveCompare, this
* version returns an int for < or > comparisons, and comparison must start
* at the front. Note that this kind of comparison does not allow the shortcut
* of first comparing sizes--every character must be compared up to the last one.
*/
template <typename T> int caseInsensitiveCompareInt (const String & str1, const T & str2)
{
const size_t len1 = str1.size();
const size_t len2 = str2.size();
size_t len;
if (len1 < len2)
len = len1;
else
len = len2;
// iterate over smallest length
for (size_t i = 0; i < len; i++)
inline unicode_char_t trueLower(unicode_char_t letter)
{
if ( trueLower(str1[i]) < trueLower(str2[i]) )
if ((cyrillic_upper_first <= letter) && (letter <= cyrillic_upper_last)) {
return letter - (cyrillic_upper_first - cyrillic_lower_first);
}
else {
return static_cast<unicode_char_t>(tolower(letter));
}
}
/**
* Compare substrings of str2 and str1, each starting with pos and containing n characters
*/
/**
* Compares str1 and str2, where str1 is a String and str2 is templated,
* thus could be a std::string as well. Set reverseCompare to true if you
* want to begin comparison at end of string--a useful optimization if your
* strings tend to differ at the end.
*/
template <typename T> bool caseInsensitiveCompare(const String & str1, const T & str2, bool reverseCompare = false)
{
const size_t len1 = str1.size();
const size_t len2 = str2.size();
if (len1 != len2)
{
return false;
}
if (!reverseCompare)
{
for (size_t i = 0; i < len1; i++)
{
if (trueLower(str1[i]) != trueLower(str2[i]))
return false;
}
}
else
{
for (size_t i = len1; i > 0; i--)
{
if (trueLower(str1[i - 1]) != trueLower(str2[i - 1]))
return false;
}
}
return true;
}
/**
* Compares str1 and str2, where str1 is a String and str2 is templated,
* thus could be a std::string as well. Unlike caseInsensitiveCompare, this
* version returns an int for < or > comparisons, and comparison must start
* at the front. Note that this kind of comparison does not allow the shortcut
* of first comparing sizes--every character must be compared up to the last one.
*/
template <typename T> int caseInsensitiveCompareInt(const String & str1, const T & str2)
{
const size_t len1 = str1.size();
const size_t len2 = str2.size();
size_t len;
if (len1 < len2)
len = len1;
else
len = len2;
// iterate over smallest length
for (size_t i = 0; i < len; i++)
{
if (trueLower(str1[i]) < trueLower(str2[i]))
return -1;
else if (trueLower(str1[i]) > trueLower(str2[i]))
return 1;
}
// Equal so far, thus: if len1 < len2, the result is less-than, else
// if len1 = len2, the result is equal, else the result is greater-than.
if (len1 < len2)
return -1;
else if ( trueLower(str1[i]) > trueLower(str2[i]) )
else if (len1 == len2)
return 0;
else
return 1;
}
// Equal so far, thus: if len1 < len2, the result is less-than, else
// if len1 = len2, the result is equal, else the result is greater-than.
/**
* Optimized implementation of isWhitespace. Must be kept in line with ::whitespace array
*/
if (len1 < len2)
return -1;
else if (len1 == len2)
return 0;
else
return 1;
}
template <typename T> bool isWhitespace(T c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t';
}
/**
* Optimized implementation of isWhitespace. Must be kept in line with ::whitespace array
*/
template <typename T> bool isWhitespace (T c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t';
}
/*
* @todo: uncomment when caseInsensitiveCompare matures
*
template <typename T> class CompareNoCasePredicate
{
public:
bool operator()( T & a, T & b ) const
{
return caseInsensitiveCompare (a, b) < 0;
template <typename T> class CompareNoCasePredicate
{
public:
bool operator()(T & a, T & b) const
{
return caseInsensitiveCompare(a, b) < 0;
};
};
template <typename T> class EqualsNoCasePredicate
{
public:
bool operator()(T & a, T & b) const
{
return caseInsensitiveCompare(a, b) == 0;
};
};
//-----------------------------------------------------------------
//-- implementation
//-----------------------------------------------------------------
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by value
*/
inline String narrowToWide(const NarrowString & nstr)
{
return String(nstr.begin(), nstr.end()); // STL original
}
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by reference
*/
inline String & narrowToWide(const NarrowString & nstr, String & str)
{
return str.assign(nstr.begin(), nstr.end()); // STL original
}
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by value
* This should only be used when the Unicode string is known to contain only 8 bit assignable values
*/
inline NarrowString wideToNarrow(const String & str)
{
return NarrowString(str.begin(), str.end()); // STL original
}
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by reference
* This should only be used when the Unicode string is known to contain only 8 bit assignable values
*/
inline NarrowString & wideToNarrow(const String & str, NarrowString & nstr)
{
return nstr.assign(str.begin(), str.end()); // STL original
}
/**
* Get the trimmed version of str by value.
*/
inline const String getTrim(const String & str, const unicode_char_t * white)
{
const size_t first_nonspace = str.find_first_not_of(white);
const size_t last_nonspace = str.find_last_not_of(white);
return (first_nonspace == str.npos ? str : str.substr(first_nonspace, last_nonspace == str.npos ? last_nonspace : (last_nonspace - first_nonspace + 1)));
}
//-----------------------------------------------------------------
/**
* Trim the specified string and return a reference to it.
*/
inline String & trim(String & str, const unicode_char_t * white)
{
return (str = getTrim(str, white));
}
/**
* Get the trimmed version of str by value.
*/
inline const NarrowString getTrim(const NarrowString & str, const char * white)
{
const size_t first_nonspace = str.find_first_not_of(white);
const size_t last_nonspace = str.find_last_not_of(white);
return (first_nonspace == str.npos ? str : str.substr(first_nonspace, last_nonspace == str.npos ? last_nonspace : (last_nonspace - first_nonspace + 1)));
}
//-----------------------------------------------------------------
/**
* Trim the specified string and return a reference to it.
*/
inline NarrowString & trim(NarrowString & str, const char * white)
{
return (str = getTrim(str, white));
}
/**
* Return the first non-white position starting with pos. returns str.npos if there is no non-white characer after pos
*/
inline size_t skipWhitespace(const String & str, size_t pos, const unicode_char_t * white)
{
return str.find_first_not_of(white, pos);
}
//-----------------------------------------------------------------
/**
* Return the first non-white position starting with pos. returns str.npos if there is no non-white characer after pos
*/
inline size_t skipWhitespace(const NarrowString & str, size_t pos, const char * white)
{
return str.find_first_not_of(white, pos);
}
//-----------------------------------------------------------------
/**
* Append src to dst, padding the field as needed, and truncating the field if desired.
*/
inline String & appendStringField(String & dst, const NarrowString & src, size_t width, FieldAlignment fa, unicode_char_t pad, bool truncate)
{
return appendStringField(dst, narrowToWide(src), width, fa, pad, truncate);
}
// ======================================================================
};
template <typename T> class EqualsNoCasePredicate
// ======================================================================
// Extensions to Base/Archive for String
// ======================================================================
//class Base::ByteStream;
//-----------------------------------------------------------------------
namespace Base
{
public:
bool operator()( T & a, T & b ) const
{
return caseInsensitiveCompare (a, b) == 0;
};
extern unsigned get(ByteStream::ReadIterator & source, Plat_Unicode::String & target);
extern void put(ByteStream & target, const Plat_Unicode::String & source);
//---------------------------------------------------------------------
// namespace Base
};
*/
//-----------------------------------------------------------------
//-- implementation
//-----------------------------------------------------------------
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by value
*/
inline String narrowToWide (const NarrowString & nstr)
{
// return String (nstr.begin (), nstr.end ()); // STLPort original
String s;
unsigned index = 0;
s.resize(nstr.size());
const NarrowString::const_iterator end = nstr.end();
for (NarrowString::const_iterator iter = nstr.begin(); iter != end; ++iter)
{
// Cast to unsigned char so that we don't pick up a negative value
// for the unsigned short
s[index++] = (unsigned char)*iter;
}
return s;
}
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by reference
*/
inline String & narrowToWide (const NarrowString & nstr, String & str)
{
// return str.assign (nstr.begin (), nstr.end ()); // STLport original
unsigned index = 0;
str.resize(nstr.size());
const NarrowString::const_iterator end = nstr.end();
for (NarrowString::const_iterator iter = nstr.begin(); iter != end; ++iter)
{
str[index++] = *iter;
}
return str;
}
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by value
* This should only be used when the Unicode string is known to contain only 8 bit assignable values
*/
inline NarrowString wideToNarrow (const String & str)
{
// return NarrowString (str.begin (), str.end ()); // STLPort original
NarrowString s;
unsigned index = 0;
s.resize(str.size());
const String::const_iterator end = str.end();
for (String::const_iterator iter = str.begin(); iter != end; ++iter)
{
s[index++] = (char)*iter;
}
return s;
}
//-----------------------------------------------------------------
/**
* Utility to convert a string and obtain the result by reference
* This should only be used when the Unicode string is known to contain only 8 bit assignable values
*/
inline NarrowString & wideToNarrow (const String & str, NarrowString & nstr)
{
// return nstr.assign (str.begin (), str.end ()); // STLPort original
unsigned index = 0;
nstr.resize(str.size());
const String::const_iterator end = str.end();
for (String::const_iterator iter = str.begin(); iter != end; ++iter)
{
nstr[index++] = (char)*iter;
}
return nstr;
}
/**
* Get the trimmed version of str by value.
*/
inline const String getTrim (const String & str, const unicode_char_t * white)
{
const size_t first_nonspace = str.find_first_not_of ( white );
const size_t last_nonspace = str.find_last_not_of ( white );
return (first_nonspace == str.npos ? str : str.substr (first_nonspace, last_nonspace == str.npos ? last_nonspace : (last_nonspace - first_nonspace + 1)));
}
//-----------------------------------------------------------------
/**
* Trim the specified string and return a reference to it.
*/
inline String & trim (String & str, const unicode_char_t * white)
{
return (str = getTrim (str, white));
}
/**
* Get the trimmed version of str by value.
*/
inline const NarrowString getTrim (const NarrowString & str, const char * white)
{
const size_t first_nonspace = str.find_first_not_of ( white );
const size_t last_nonspace = str.find_last_not_of ( white );
return (first_nonspace == str.npos ? str : str.substr (first_nonspace, last_nonspace == str.npos ? last_nonspace : (last_nonspace - first_nonspace + 1)));
}
//-----------------------------------------------------------------
/**
* Trim the specified string and return a reference to it.
*/
inline NarrowString & trim (NarrowString & str, const char * white)
{
return (str = getTrim (str, white));
}
/**
* Return the first non-white position starting with pos. returns str.npos if there is no non-white characer after pos
*/
inline size_t skipWhitespace (const String & str, size_t pos, const unicode_char_t * white)
{
return str.find_first_not_of (white, pos);
}
//-----------------------------------------------------------------
/**
* Return the first non-white position starting with pos. returns str.npos if there is no non-white characer after pos
*/
inline size_t skipWhitespace (const NarrowString & str, size_t pos, const char * white)
{
return str.find_first_not_of (white, pos);
}
//-----------------------------------------------------------------
/**
* Append src to dst, padding the field as needed, and truncating the field if desired.
*/
inline String & appendStringField (String & dst, const NarrowString & src, size_t width, FieldAlignment fa, unicode_char_t pad, bool truncate)
{
return appendStringField (dst, narrowToWide (src), width, fa, pad, truncate);
}
// ======================================================================
};
// ======================================================================
// Extensions to Base/Archive for String
// ======================================================================
//class Base::ByteStream;
//-----------------------------------------------------------------------
namespace Base
{
extern unsigned get(ByteStream::ReadIterator & source, Plat_Unicode::String & target);
extern void put(ByteStream & target, const Plat_Unicode::String & source);
//---------------------------------------------------------------------
// namespace Base
};
#ifdef EXTERNAL_DISTRO
};
#endif