code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
#if !defined(AFX_CTERRABILLINGCTRL_LOGCTRL_H__1DC2AC1C_FE9B_490E_A4F0_2AF95AA14FDB__INCLUDED_)
#define AFX_CTERRABILLINGCTRL_LOGCTRL_H__1DC2AC1C_FE9B_490E_A4F0_2AF95AA14FDB__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CTerraBillingCtrl_LogCtrl
{
private:
BOOL m_bOK;
char m_szFileName[_MAX_PATH];
FILE* m_fp;
int m_NextUpdateTime;
int m_generationHour;
private:
inline BOOL OpenFile(void);
inline void CloseFile(void);
public:
BOOL isOK(void) const;
void Update(void);
void Write(const char* format, ... );
static char* GetYESNOstring(BOOL bYESorNO);
public:
CTerraBillingCtrl_LogCtrl();
virtual ~CTerraBillingCtrl_LogCtrl();
};
#endif
| C++ |
#if !defined(AFX_CTERRABILLINGCTRL_COMMUNICATIONCTRL_H__62234542_B22F_4A33_A2EF_4D23000EC4FB__INCLUDED_)
#define AFX_CTERRABILLINGCTRL_COMMUNICATIONCTRL_H__62234542_B22F_4A33_A2EF_4D23000EC4FB__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CTerraBillingCtrl_CommunicationCtrl
{
private:
BOOL m_bOK;
SOCKET m_sock;
unsigned long m_addr;
unsigned short m_port;
struct tagThreadVar{
BOOL bLive;
BOOL bReqExit;
};
struct tagThreadVar m_ThreadVar;
public:
enum enumStep{
step_disconnect_try=0,
step_disconnect,
step_connect_try,
step_connect,
};
private:
enum enumStep m_Step;
private:
inline BOOL SocketCreate(void);
inline void SocketDestory(void);
inline BOOL Connect(void);
inline void Disconnect(void);
private:
static unsigned int __stdcall ThreadFunction(void* pV);
int RealThreadFunction(void);
public:
BOOL isOK(void) const;
BOOL Start(void);
BOOL Send(const struct tagAddBillPacket& pPacket);
BOOL TryConnect(const unsigned long addr,const unsigned short port);
BOOL TryDisconnect(void);
enum enumStep GetStep(void);
public:
CTerraBillingCtrl_CommunicationCtrl();
virtual ~CTerraBillingCtrl_CommunicationCtrl();
};
#endif
| C++ |
#include "../../Global.h"
#include "CTerraBillingCtrl_Encoder.h"
#include "CTerraBillingCtrl_CircularQueueCtrl.h"
extern CTerraBillingCtrl_CircularQueueCtrl* gcpTerraBillingCtrl_TransmiteCircularQueueCtrl;
#include "tagTerraBilling.h"
extern struct tagTerraBilling gTerraBilling;
CTerraBillingCtrl_Encoder::CTerraBillingCtrl_Encoder()
{
m_bOK=FALSE;
m_bOK=TRUE;
}
CTerraBillingCtrl_Encoder::~CTerraBillingCtrl_Encoder()
{
}
BOOL CTerraBillingCtrl_Encoder::isOK(void) const
{
return m_bOK;
}
void CTerraBillingCtrl_Encoder::Transmite_Server_Reset(void)
{
struct tagAddBillPacket Packet;
memset(&Packet,0x00,sizeof(struct tagAddBillPacket));
Packet.Packet_Type = htonl(tagAddBillPacket::packet_type_server_reset);
memcpy(Packet.Game_Server,gTerraBilling.serverGUIDstring,tagAddBillPacket::maxbytes_serverGUIDstring);
Packet.Game_No = htonl(gTerraBilling.Game_No);
gcpTerraBillingCtrl_TransmiteCircularQueueCtrl->Push(&Packet);
}
void CTerraBillingCtrl_Encoder::Transmite_Server_Conn(void)
{
struct tagAddBillPacket Packet;
memset(&Packet,0x00,sizeof(struct tagAddBillPacket));
Packet.Packet_Type = htonl(tagAddBillPacket::packet_type_server_conn);
memcpy(Packet.Game_Server,gTerraBilling.serverGUIDstring,tagAddBillPacket::maxbytes_serverGUIDstring);
Packet.Game_No = htonl(gTerraBilling.Game_No);
gcpTerraBillingCtrl_TransmiteCircularQueueCtrl->Push(&Packet);
}
#ifdef _MASTER_SERVER
void CTerraBillingCtrl_Encoder::
Transmite_Billing_Authorization(const i3client_t* pPlayer)
{
struct tagAddBillPacket Packet;
memset(&Packet,0x00,sizeof(struct tagAddBillPacket));
Packet.Packet_Type = htonl(tagAddBillPacket::packet_type_billing_authorization);
char session[_MAX_PATH];
wsprintf(session,"%d-%s-01234567890123456789012345678901",pPlayer->idx,pPlayer->id);
strncpy(Packet.Session,session,tagAddBillPacket::maxbytes_session);
wsprintf(Packet.User_CC,"TICT");
strncpy(Packet.User_ID,pPlayer->id,tagAddBillPacket::maxbytes_user_id);
wsprintf(Packet.User_IP,"%d.%d.%d.%d",
pPlayer->sock.addr.sin_addr.S_un.S_un_b.s_b1,
pPlayer->sock.addr.sin_addr.S_un.S_un_b.s_b2,
pPlayer->sock.addr.sin_addr.S_un.S_un_b.s_b3,
pPlayer->sock.addr.sin_addr.S_un.S_un_b.s_b4);
Packet.Game_No = htonl(gTerraBilling.Game_No);
gcpTerraBillingCtrl_TransmiteCircularQueueCtrl->Push(&Packet);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::
Transmite_Game_Start(const playerCharacter_t* pPlayerRecord) const
{
static struct tagAddBillPacket Packet;
memset(&Packet,0x00,sizeof(struct tagAddBillPacket));
Packet.Packet_Type = htonl(tagAddBillPacket::packet_type_game_start);
memcpy(Packet.Game_Server,gTerraBilling.serverGUIDstring,tagAddBillPacket::maxbytes_serverGUIDstring);
static char buffer[_MAX_PATH];
wsprintf(buffer,"%d",pPlayerRecord->idx);
strncpy(Packet.Session,buffer,tagAddBillPacket::maxbytes_session);
wsprintf(Packet.User_CC,"TICT");
strncpy(Packet.User_ID,pPlayerRecord->userID,tagAddBillPacket::maxbytes_user_id);
wsprintf(Packet.User_IP,"%d:%d:%d:%d",
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b1,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b2,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b3,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b4);
Packet.Game_No = htonl(gTerraBilling.Game_No);
gcpTerraBillingCtrl_TransmiteCircularQueueCtrl->Push(&Packet);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::
Transmite_Game_End(const char* pszPlayerIdx,const char* pPlayerID,const char* pIPaddress,const char* pUser_Status) const
{
static struct tagAddBillPacket Packet;
memset(&Packet,0x00,sizeof(struct tagAddBillPacket));
Packet.Packet_Type = htonl(tagAddBillPacket::packet_type_game_end);
strncpy(Packet.Session,pszPlayerIdx,tagAddBillPacket::maxbytes_session);
wsprintf(Packet.User_CC,"TICT");
strncpy(Packet.User_ID,pPlayerID,tagAddBillPacket::maxbytes_user_id);
strncpy(Packet.User_IP,pIPaddress,tagAddBillPacket::maxbytes_user_ip);
strncpy(Packet.User_Status,pUser_Status,tagAddBillPacket::maxbytes_user_status);
Packet.Game_No = htonl(gTerraBilling.Game_No);
gcpTerraBillingCtrl_TransmiteCircularQueueCtrl->Push(&Packet);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::
Transmite_Game_End(const struct tagAddBillPacket& Packet) const
{
Transmite_Game_End(Packet.Session,Packet.User_ID,Packet.User_IP,Packet.User_Status);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::
Transmite_Game_End(const playerCharacter_t* pPlayerRecord) const
{
static char strPlayerIdx[_MAX_PATH];
wsprintf(strPlayerIdx,"%d",pPlayerRecord->idx);
static char strIPaddress[tagAddBillPacket::maxbytes_user_ip];
wsprintf(strIPaddress,"%d:%d:%d:%d",
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b1,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b2,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b3,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b4);
Transmite_Game_End(
strPlayerIdx,
pPlayerRecord->userID,
strIPaddress,
pPlayerRecord->AddBill.User_Status);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::
Transmite_User_Sync(
BOOL bExist,
const char* pszPlayerIdx,
const char* pPlayerID,
const char* pIPaddress,
const char* pUser_Status) const
{
static struct tagAddBillPacket Packet;
memset(&Packet,0x00,sizeof(struct tagAddBillPacket));
Packet.Packet_Type = htonl(tagAddBillPacket::packet_type_user_sync);
if(TRUE == bExist) Packet.Packet_Result = htonl(1);
else Packet.Packet_Result = htonl(0);
strncpy(Packet.Session,pszPlayerIdx,tagAddBillPacket::maxbytes_session);
strncpy(Packet.User_ID,pPlayerID,tagAddBillPacket::maxbytes_user_id);
strncpy(Packet.User_IP,pIPaddress,tagAddBillPacket::maxbytes_user_ip);
strncpy(Packet.User_Status,pUser_Status,tagAddBillPacket::maxbytes_user_status);
gcpTerraBillingCtrl_TransmiteCircularQueueCtrl->Push(&Packet);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::Transmite_User_Sync(const struct tagAddBillPacket& Packet) const
{
Transmite_User_Sync(
FALSE,
Packet.Session,
Packet.User_ID,
Packet.User_IP,
Packet.User_Status);
}
#endif
#ifdef _GAME_SERVER
void CTerraBillingCtrl_Encoder::Transmite_User_Sync(const playerCharacter_t* pPlayerRecord) const
{
static char strPlayerIdx[_MAX_PATH];
wsprintf(strPlayerIdx,"%d",pPlayerRecord->idx);
static char strIPaddress[tagAddBillPacket::maxbytes_user_ip];
wsprintf(strIPaddress,"%d.%d.%d.%d",
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b1,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b2,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b3,
pPlayerRecord->sock.addr.sin_addr.S_un.S_un_b.s_b4);
Transmite_User_Sync(
TRUE,
strPlayerIdx,
pPlayerRecord->userID,
strIPaddress,
pPlayerRecord->AddBill.User_Status);
}
#endif
| C++ |
#if !defined(AFX_CTERRABILLINGCTRL_RECEIVECIRCUALRQUEUECTRL_H__CAC70141_0F1A_40C4_97EA_44AE33CE941B__INCLUDED_)
#define AFX_CTERRABILLINGCTRL_RECEIVECIRCUALRQUEUECTRL_H__CAC70141_0F1A_40C4_97EA_44AE33CE941B__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#include "tagAddBill.h"
#include "CTerraBillingCtrl_CircularQueueCtrl.h"
class CTerraBillingCtrl_ReceiveCircualrQueueCtrl : public CTerraBillingCtrl_CircularQueueCtrl
{
private:
BOOL m_bOK;
enum{
MaxBytes_LineBuffer= sizeof(struct tagAddBillPacket) * 2,
};
unsigned char m_LineBuffer[MaxBytes_LineBuffer];
int m_LineBufferStoreBytes;
public:
BOOL isOK(void) const;
BOOL Push(const unsigned char* pNewData,const int NewDataBytes);
public:
CTerraBillingCtrl_ReceiveCircualrQueueCtrl(const int Number);
virtual ~CTerraBillingCtrl_ReceiveCircualrQueueCtrl();
};
#endif
| C++ |
#if !defined(AFX_CTERRABILLINGCTRL_ENCODER_H__CDF45D1F_C7F7_4963_8751_F14D246399C9__INCLUDED_)
#define AFX_CTERRABILLINGCTRL_ENCODER_H__CDF45D1F_C7F7_4963_8751_F14D246399C9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CTerraBillingCtrl_Encoder
{
private:
BOOL m_bOK;
public:
BOOL isOK(void) const;
void Transmite_Server_Conn(void);
void Transmite_Server_Reset(void);
#ifdef _GAME_SERVER
void Transmite_Game_Start(const playerCharacter_t* pPlayerRecord) const;
void Transmite_Game_End(const playerCharacter_t* pPlayerRecord) const;
void Transmite_Game_End(
const char* pszPlayerIdx,
const char* pPlayerID,
const char* pIPaddress,
const char* pUser_Status) const;
void Transmite_Game_End(const struct tagAddBillPacket& Packet) const;
void Transmite_User_Sync(
BOOL bExist,
const char* pszPlayerIdx,
const char* pPlayerID,
const char* pIPaddress,
const char* pUser_Status) const;
void Transmite_User_Sync(const struct tagAddBillPacket& Packet) const;
void Transmite_User_Sync(const playerCharacter_t* pPlayerRecord) const;
#endif
#ifdef _MASTER_SERVER
public:
void Transmite_Billing_Authorization(const i3client_t* pPlayer);
#endif
public:
CTerraBillingCtrl_Encoder();
virtual ~CTerraBillingCtrl_Encoder();
};
#endif
| C++ |
#include "../../global.h"
#include "CTerraBillingCtrl_CircularQueueCtrl.h"
#include <assert.h>
#include <windowsx.h>
CTerraBillingCtrl_CircularQueueCtrl::
CTerraBillingCtrl_CircularQueueCtrl(const int Number)
{
assert(Number > 0);
m_bOK=FALSE;
m_pBuffer=NULL;
m_Number=0;
m_ReadIdx = 0;
m_WriteIdx = 0;
InitializeCriticalSection(&m_critcalsection);
if(FALSE == Init(Number)) return;
m_bOK=TRUE;
}
CTerraBillingCtrl_CircularQueueCtrl::~CTerraBillingCtrl_CircularQueueCtrl()
{
DeleteCriticalSection(&m_critcalsection);
if(NULL != m_pBuffer){ GlobalFreePtr(m_pBuffer); m_pBuffer=NULL; }
}
BOOL CTerraBillingCtrl_CircularQueueCtrl::isOK(void) const
{
return m_bOK;
}
BOOL CTerraBillingCtrl_CircularQueueCtrl::
Init(const int Number)
{
m_Number = Number;
m_pBuffer=(struct tagAddBillPacket*)GlobalAllocPtr(GMEM_FIXED,sizeof(struct tagAddBillPacket) * m_Number);
if(NULL == m_pBuffer) return FALSE;
memset(m_pBuffer,0x00,sizeof(struct tagAddBillPacket) * m_Number);
return TRUE;
}
inline BOOL CTerraBillingCtrl_CircularQueueCtrl::
isEmpty(void) const
{
if(m_ReadIdx == m_WriteIdx) return TRUE;
return FALSE;
}
inline BOOL CTerraBillingCtrl_CircularQueueCtrl::
isFull(void) const
{
int tempWriteIdx = m_WriteIdx;
tempWriteIdx+=1;
if(tempWriteIdx >= m_Number) tempWriteIdx=0;
if(tempWriteIdx == m_ReadIdx) return TRUE;
return FALSE;
}
BOOL CTerraBillingCtrl_CircularQueueCtrl::
Push(const struct tagAddBillPacket* pData)
{
EnterCriticalSection(&m_critcalsection);
if(TRUE == isFull()){
LeaveCriticalSection(&m_critcalsection);
return FALSE;
}
m_pBuffer[m_WriteIdx] = *pData;
m_WriteIdx+=1;
if(m_WriteIdx >= m_Number) m_WriteIdx=0;
LeaveCriticalSection(&m_critcalsection);
return TRUE;
}
BOOL CTerraBillingCtrl_CircularQueueCtrl::
Pop(struct tagAddBillPacket& Data)
{
EnterCriticalSection(&m_critcalsection);
if(TRUE == isEmpty()){
LeaveCriticalSection(&m_critcalsection);
return FALSE;
}
Data = m_pBuffer[m_ReadIdx];
m_ReadIdx+=1;
if(m_ReadIdx >= m_Number) m_ReadIdx=0;
LeaveCriticalSection(&m_critcalsection);
return TRUE;
}
void CTerraBillingCtrl_CircularQueueCtrl::Clear(void)
{
m_ReadIdx=m_WriteIdx=0;
}
| C++ |
#include "../../global.h"
#include "CTerraBillingCtrl_ReceiveCircualrQueueCtrl.h"
CTerraBillingCtrl_ReceiveCircualrQueueCtrl::
CTerraBillingCtrl_ReceiveCircualrQueueCtrl(const int Number):CTerraBillingCtrl_CircularQueueCtrl(Number)
{
m_bOK=FALSE;
if(FALSE == CTerraBillingCtrl_CircularQueueCtrl::isOK()) return;
m_LineBufferStoreBytes=0;
m_bOK=TRUE;
}
CTerraBillingCtrl_ReceiveCircualrQueueCtrl::~CTerraBillingCtrl_ReceiveCircualrQueueCtrl()
{
}
BOOL CTerraBillingCtrl_ReceiveCircualrQueueCtrl::isOK(void) const
{
return m_bOK;
}
BOOL CTerraBillingCtrl_ReceiveCircualrQueueCtrl::
Push(const unsigned char* pNewData,const int NewDataBytes)
{
EnterCriticalSection(&m_critcalsection);
int RemainBytesBeforeCompletePacket=0;
int RemainBytesNewData = NewDataBytes;
unsigned char* pTempInsetStNewData =(unsigned char*)pNewData;
while(TRUE){
RemainBytesBeforeCompletePacket = sizeof(struct tagAddBillPacket) - m_LineBufferStoreBytes;
if(RemainBytesBeforeCompletePacket > RemainBytesNewData){
if(0 == m_LineBufferStoreBytes) memcpy(&m_LineBuffer[0],pTempInsetStNewData,RemainBytesNewData);
else memcpy(&m_LineBuffer[m_LineBufferStoreBytes-1],pTempInsetStNewData,RemainBytesNewData);
m_LineBufferStoreBytes += RemainBytesNewData;
break;
}
if(0 == m_LineBufferStoreBytes) memcpy(&m_LineBuffer[0],pTempInsetStNewData,RemainBytesBeforeCompletePacket);
else memcpy(&m_LineBuffer[m_LineBufferStoreBytes-1],pTempInsetStNewData,RemainBytesBeforeCompletePacket);
if(FALSE == CTerraBillingCtrl_CircularQueueCtrl::Push((struct tagAddBillPacket*)m_LineBuffer)){
LeaveCriticalSection(&m_critcalsection);
return FALSE;
}
pTempInsetStNewData += RemainBytesBeforeCompletePacket;
RemainBytesNewData -= RemainBytesBeforeCompletePacket;
if(RemainBytesNewData <= 0) break;
}
LeaveCriticalSection(&m_critcalsection);
return TRUE;
} | C++ |
#if !defined(AFX_CTERRABILLINGCTRL_H__F366D29E_FA42_4018_8DBA_0A9E735D3184__INCLUDED_)
#define AFX_CTERRABILLINGCTRL_H__F366D29E_FA42_4018_8DBA_0A9E735D3184__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CTerraBillingCtrl
{
private:
enum{
MaxNum_TrnamisteCircularQueueEle = 512,
MaxNum_ReceiveCircularQueueEle = 512,
};
BOOL m_bOK;
enum enumStep{
step_none=0,
step_connect_try,
step_transmite_packet_conn_and_reset,
step_service,
step_disconnect_try,
};
enum enumStep m_Step;
private:
BOOL Init(void);
BOOL LoadServerConfigFile(void);
inline void TransmiteAllPacketInTransmiteCircularQueue(void) const;
#ifdef _MASTER_SERVER
public:
inline i3client_t* GetPlayerRecodPointer(const struct tagAddBillPacket& Packet) const;
inline void Decoder_billing_authorization(const struct tagAddBillPacket& Packet) const;
#endif
public:
BOOL isOK(void) const;
void Process(void);
inline void Process_step_service(void);
BOOL ServiceStart(void);
void ServiceEnd(void);
static void OpenNotePadMessage(const char* pMessage);
public:
#ifdef _GAME_SERVER
void Player_GameStart(playerCharacter_t* pPlayerRecord);
void Player_GameEnd(playerCharacter_t* pPlayerRecord);
#endif
public:
CTerraBillingCtrl();
virtual ~CTerraBillingCtrl();
};
#endif
| C++ |
#include "Checksum.h"
void checksum::add(DWORD value)
{
union { DWORD value; BYTE bytes[4]; } data;
data.value = value;
for(UINT i = 0; i < sizeof(data.bytes); i++)
add(data.bytes[i]);
}
void checksum::add(WORD value)
{
union { DWORD value; BYTE bytes[2]; } data;
data.value = value;
for(UINT i = 0; i < sizeof(data.bytes); i++)
add(data.bytes[i]);
}
void checksum::add(BYTE value)
{
BYTE cipher = (value ^ (r >> 8));
r = (cipher + r) * c1 + c2;
sum += cipher;
}
void checksum::add(LPBYTE b, UINT length)
{
for(UINT i = 0; i < length; i++)
add(b[i]);
} | C++ |
#include "../global.h"
void Normalize( float* n )
{
float length;
length = n[0]*n[0] + n[1]*n[1] + n[2]*n[2];
length = (float)sqrt(length);
if (length == 0.0f) length = 0.000001f;
n[0] /= length;
n[1] /= length;
n[2] /= length;
}
void RotateXCoord(vec3_t A, float Angle)
{
float c,s;
float tempY, tempZ;
s = ( float ) sin(DEG2RAD(Angle));
c = ( float ) cos(DEG2RAD(Angle));
tempY = A[1];
tempZ = A[2];
A[1] = tempY * c - tempZ * s;
A[2] = tempY * s + tempZ * c;
}
void RotateYCoord(vec3_t A, float Angle)
{
float c,s;
float tempX, tempZ;
s = (float) sin(DEG2RAD(Angle));
c = (float) cos(DEG2RAD(Angle));
tempX = A[0];
tempZ = A[2];
A[0] = tempX * c + tempZ * s;
A[2] = tempZ * c - tempX * s;
}
void RotateZCoord(vec3_t A, float Angle)
{
float c,s;
float tempX, tempY;
s = (float) sin(DEG2RAD(Angle));
c = (float) cos(DEG2RAD(Angle));
tempX = A[0];
tempY = A[1];
A[0] = tempX * c - tempY * s;
A[1] = tempX * s + tempY * c;
}
void vectoangles( const vec3_t value1, vec3_t angles )
{
float forward;
float yaw, pitch;
if ( value1[1] == 0 && value1[0] == 0 )
{
yaw = 0;
if ( value1[2] > 0 )
{
pitch = 90;
}
else
{
pitch = 270;
}
}
else {
if ( value1[0] )
{
yaw = (float) ( atan2 ( value1[1], value1[0] ) * 180 / M_PI );
}
else if ( value1[1] > 0 )
{
yaw = 90;
}
else
{
yaw = 270;
}
if ( yaw < 0 ) {
yaw += 360;
}
forward = (float) sqrt ( value1[0]*value1[0] + value1[1]*value1[1] );
pitch = (float) ( atan2(value1[2], forward) * 180 / M_PI );
if ( pitch < 0 )
{
pitch += 360;
}
}
angles[PITCH] = -pitch;
angles[YAW] = yaw;
angles[ROLL] = 0;
} | C++ |
class CTimer
{
int m_stopped;
int m_inited;
int m_usingQPF;
double m_lastElapsedTime;
double m_baseTime;
double m_stopTime;
double m_currSysTime;
double m_currElapsedTime;
double m_baseMilliTime;
double m_currSysMilliTime;
double m_currElapsedMilliTime;
LONGLONG m_QPFTicksPerSec;
LONGLONG m_QPFStopTime;
LONGLONG m_QPFLastElapsedTime;
LONGLONG m_QPFBaseTime;
LARGE_INTEGER m_QPFTime;
public:
CTimer();
virtual ~CTimer();
void Start();
void Stop();
void Advance();
void Reset();
float Tick();
inline float GetAppTime() { return (float) ( m_currSysTime - m_baseTime ); }
inline float GetElapsedTime() { return (float) m_currElapsedTime; }
inline float GetSysTime() { return (float) m_currSysTime; }
inline float GetAppMilliTime() { return (float) ( m_currSysMilliTime - m_baseMilliTime ); }
inline float GetElapsedMilliTime() { return (float) m_currElapsedMilliTime; }
};
| C++ |
#include <time.h>
#include "../global.h"
int MonthEndDay[12]={ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int YunMonthEndDay[12]={ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
CDays gDays;
CDays::CDays()
{
Init();
}
CDays::~CDays()
{
}
void CDays::Init()
{
int tot=0,ytot=0;
for(int i=0;i<12;i++)
{
MonthTot[i] = tot;
YunMonthTot[i] = ytot;
tot+= MonthEndDay[i];
ytot+= MonthEndDay[i];
if(i == 1) ytot ++;
}
}
int CDays::IfYunYear(int year)
{
int leap;
leap=(year%400==0) || (year%100!=0 && year%4==0);
if(leap) return true;
return false;
}
int CDays::GetDays(tm tmDate)
{
struct tm *today=0;
time_t ltime;
time(<ime);
today=localtime(<ime);
return GetDays(today->tm_year+1900,today->tm_mon, today->tm_mday,
tmDate.tm_year+1900,tmDate.tm_mon, tmDate.tm_mday);
}
int CDays::GetDays(int yy,int mm,int dd)
{
struct tm *today=0;
time_t ltime;
time(<ime);
today=localtime(<ime);
return GetDays(today->tm_year+1900,today->tm_mon, today->tm_mday, yy,mm,dd);
}
int CDays::GetDays(int fyy,int fmm,int fdd, int tyy,int tmm,int tdd)
{
int today_tot_date=0;
int dist_tot_date=0;
if(IfYunYear(fyy))
{
today_tot_date = YunMonthTot[fmm-1] + fdd;
}
else
{
today_tot_date = MonthTot[fmm-1] + fdd;
}
int diff_year=0;
if(fyy > tyy)
{
dist_tot_date=0;
int startmm = tmm;
if(IfYunYear(tyy))
{
dist_tot_date = YunMonthEndDay[tmm-1]-tdd;
}
else
{
dist_tot_date = MonthEndDay[tmm-1]-tdd;
}
for(int i=tyy ; i <= fyy ;i++)
{
for(int j=startmm; j <12;j++ )
{
if(i == fyy && j == fmm-1) break;
if(IfYunYear(i))
{
dist_tot_date += YunMonthEndDay[j];
}
else
{
dist_tot_date += MonthEndDay[j];
}
}
if(startmm != 0) startmm = 0;
}
dist_tot_date += fdd;
return dist_tot_date;
}
else
{
for(int i=fyy ; i < tyy ;i++)
{
if(IfYunYear(i)) diff_year += 366;
else diff_year += 365;
}
if(IfYunYear(tyy))
{
dist_tot_date = diff_year+ YunMonthTot[tmm-1] + tdd;
}
else
{
dist_tot_date = diff_year + MonthTot[tmm-1] + tdd;
}
return (dist_tot_date - today_tot_date);
}
return 0;
}
| C++ |
#include "../global.h"
CTimer::CTimer()
{
m_stopped = true;
m_inited = false;
m_usingQPF = false;
m_lastElapsedTime = 0.0;
m_baseTime = 0.0;
m_stopTime = 0.0;
m_currSysTime = 0.0;
m_currElapsedTime = 0.0;
m_baseMilliTime = 0.0;
m_currSysMilliTime = 0.0;
m_currElapsedMilliTime = 0.0;
m_QPFTicksPerSec = 0;
m_QPFStopTime = 0;
m_QPFLastElapsedTime = 0;
m_QPFBaseTime = 0;
}
CTimer::~CTimer()
{
}
void CTimer::Start()
{
if( !m_inited )
{
LARGE_INTEGER qwTicksPerSec;
m_usingQPF = QueryPerformanceFrequency( &qwTicksPerSec );
if( m_usingQPF )
m_QPFTicksPerSec = qwTicksPerSec.QuadPart;
if( m_usingQPF )
{
QueryPerformanceCounter( &m_QPFTime );
m_QPFBaseTime = m_QPFTime.QuadPart;
m_currSysTime = m_QPFBaseTime / (double) m_QPFTicksPerSec;
m_baseTime = m_currSysTime;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_baseMilliTime = m_baseTime * 1000.0;
}
else
{
m_currSysTime = timeGetTime() * 0.001;
m_baseTime = m_currSysTime;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_baseMilliTime = m_baseTime * 1000.0;
}
m_inited = true;
}
if( m_usingQPF )
{
QueryPerformanceCounter( &m_QPFTime );
m_currSysTime = m_QPFTime.QuadPart / (double) m_QPFTicksPerSec;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_QPFStopTime = 0;
m_QPFLastElapsedTime = m_QPFTime.QuadPart;
}
else
{
m_currSysTime = timeGetTime() * 0.001;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_stopTime = 0.0f;
m_lastElapsedTime = m_currSysTime;
}
m_stopped = false;
}
void CTimer::Stop()
{
if( m_stopped ) return;
if( m_usingQPF )
{
QueryPerformanceCounter( &m_QPFTime );
m_currSysTime = m_QPFTime.QuadPart / (double) m_QPFTicksPerSec;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_QPFStopTime = m_QPFTime.QuadPart;
m_QPFLastElapsedTime = m_QPFTime.QuadPart;
}
else
{
m_currSysTime = timeGetTime() * 0.001;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_stopTime = m_currSysTime;
m_lastElapsedTime = m_currSysTime;
}
m_stopped = true;
}
void CTimer::Advance()
{
if( m_usingQPF )
m_QPFStopTime += m_QPFTicksPerSec / 10;
else
m_stopTime += 0.1f;
}
void CTimer::Reset()
{
if( m_usingQPF )
{
QueryPerformanceCounter( &m_QPFTime );
m_currSysTime = m_QPFTime.QuadPart / (double) m_QPFTicksPerSec;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_QPFBaseTime = m_QPFTime.QuadPart;
m_QPFLastElapsedTime = m_QPFTime.QuadPart;
m_QPFStopTime = 0;
m_baseTime = m_QPFBaseTime / (double) m_QPFTicksPerSec;
}
else
{
m_currSysTime = timeGetTime() * 0.001;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_baseTime = m_currSysTime;
m_lastElapsedTime = m_currSysTime;
m_stopTime = 0.0;
}
m_stopped = false;
}
float CTimer::Tick()
{
if( m_stopped )
{
if( m_usingQPF )
{
m_currSysTime = m_QPFStopTime / (double) m_QPFTicksPerSec;
m_currSysMilliTime = m_currSysTime * 1000.0;
}
else
{
m_currSysTime = m_stopTime;
m_currSysMilliTime = m_currSysTime * 1000.0;
}
}
else
{
if( m_usingQPF )
{
QueryPerformanceCounter( &m_QPFTime );
m_currSysTime = m_QPFTime.QuadPart / (double) m_QPFTicksPerSec;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_currElapsedTime = (double) ( m_QPFTime.QuadPart - m_QPFLastElapsedTime ) / (double) m_QPFTicksPerSec;
m_QPFLastElapsedTime = m_QPFTime.QuadPart;
m_currElapsedMilliTime = m_currElapsedTime * 1000.0;
}
else
{
m_currSysTime = timeGetTime() * 0.001;
m_currSysMilliTime = m_currSysTime * 1000.0;
m_currElapsedTime = (double) ( m_currSysTime - m_lastElapsedTime );
m_lastElapsedTime = m_currSysTime;
m_currElapsedMilliTime = m_currElapsedTime * 1000.0;
}
}
return (float) m_currElapsedTime;
}
| C++ |
#if !defined(AFX_DAYS_H__7EFDED9F_F832_404E_A17B_4963F280A015__INCLUDED_)
#define AFX_DAYS_H__7EFDED9F_F832_404E_A17B_4963F280A015__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CDays
{
public:
CDays();
virtual ~CDays();
void Init();
int GetDays(tm tmDate);
int GetDays(int yy,int mm,int dd);
int IfYunYear(int year);
int GetDays(int fyy,int fmm,int fdd, int tyy,int tmm,int tdd);
public:
int MonthTot[12];
int YunMonthTot[12];
};
extern CDays gDays;
#endif
| C++ |
#include "../global.h"
char *curpos, *endpos;
int SetTokenBuffer( byte *buffer , int size )
{
curpos = (char *)buffer;
endpos = curpos + size;
if( size <= 0 )
return false;
return true;
}
char* NextToken()
{
char *token;
while (curpos < endpos)
{
while (*curpos == ' ' || *curpos == '\t' || *curpos == '\n' || *curpos == '\r')
if (++curpos == endpos) return NULL;
if (curpos[0] == '/' && curpos[1] == '/')
{
while (*curpos++ != '\n')
if (curpos == endpos) return NULL;
continue;
}
token = curpos;
while (*curpos != ' ' && *curpos != '\t' && *curpos != '\n' && *curpos != '\r')
if (++curpos == endpos) break;
*curpos++ = '\0';
return token;
}
return NULL;
}
char* NextArg()
{
char *arg;
while (curpos < endpos)
{
while (*curpos == ' ' || *curpos == '\t')
if (++curpos == endpos) return NULL;
if( *curpos == '\n' || *curpos == '\r' ||
(curpos[0] == '/' && curpos[1] == '/') )
return NULL;
arg = curpos;
while (*curpos != ' ' && *curpos != '\t' && *curpos != '\n' && *curpos != '\r')
if (++curpos == endpos) break;
*curpos++ = '\0';
return arg;
}
return NULL;
} | C++ |
#if !defined(AFX_CTOOLS_H__43C7808A_48D1_458A_ABF8_DF7A81B432B7__INCLUDED_)
#define AFX_CTOOLS_H__43C7808A_48D1_458A_ABF8_DF7A81B432B7__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#include "datastruct.h"
class CTools
{
private:
BOOL m_bOK;
public:
BOOL isOK(void) const;
static i3client_t* GetClientRecord(const int Idx);
static characterTable_t* GetCharactorGenTableRecord(const int GenIdx);
static characterData_t* GetCharactorWithCharacterID(const i3client_t* pClient,const int characterID);
public:
static BOOL IsItemUseFlag(item_t *pItem, ENUM_ITEM_USE_FLAG flag);
public:
CTools();
virtual ~CTools();
};
#endif
| C++ |
#if !defined(AFX_CPREMIUMPLAYERCTRL_H__630C6208_F656_4AB1_91F4_4BEFF42A5CA3__INCLUDED_)
#define AFX_CPREMIUMPLAYERCTRL_H__630C6208_F656_4AB1_91F4_4BEFF42A5CA3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CPremiumPlayerCtrl
{
public:
enum enumMapIdx{
Ariyan=0,
Light_Lake=1,
Aurora_Canyon=2,
Arth_Crystal_Mine=3,
The_Temple_of_Artzran=4,
Bazmo_Fortress=5,
Illusion_Temple=6,
Dragon_Labyrinth=7,
Dark_Lake=8,
Sien=9,
Sien_Canyon=10,
Sodo=11,
Laznan_Level1=12,
Laznan_Level2=13,
Laznan_Level3=14,
Laznan_Level4=15,
Laznan_Level5=16,
Judgment_Canyon=17,
Temptation_Corridor=18,
Forgetting_Corridor=19,
Dan_Colosseum=20,
Gyorun_Colosseum=21,
};
struct i3client_t::tagPremiumInfo m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Max];
private:
BOOL m_bOK;
void Init_PremiumLevelTable_Free(void);
void Init_PremiumLevelTable_Pay(void);
void LoadIniFile(const char* szpIniFileName,struct i3client_t::tagPremiumInfo* pPremium);
void SaveIniFile(const char* szpIniFileName,const struct i3client_t::tagPremiumInfo* pPremium);
public:
BOOL isOK(void) const;
void SetData(enum i3client_t::tagPremiumInfo::enumMeberShipType MemberShipType,i3client_t* pPlayerRecord) const;
BOOL isAccessMap(const int MapIdx,const i3client_t* pPlayerRecord) const;
BOOL LoadIniFile(void);
public:
void Test_SetPremiumPlayerInfo(i3client_t* pPlayerRecord) const;
public:
CPremiumPlayerCtrl();
virtual ~CPremiumPlayerCtrl();
};
#endif
| C++ |
#include "global.h"
#include "CPremiumPlayerCtrl.h"
CPremiumPlayerCtrl::CPremiumPlayerCtrl()
{
m_bOK=FALSE;
if(FALSE == LoadIniFile()) return;
m_bOK=TRUE;
}
CPremiumPlayerCtrl::~CPremiumPlayerCtrl()
{
}
BOOL CPremiumPlayerCtrl::isOK(void) const
{
return m_bOK;
}
BOOL CPremiumPlayerCtrl::LoadIniFile(void)
{
char szWorkDir[_MAX_PATH];
::GetCurrentDirectory(_MAX_PATH,szWorkDir);
char szIniFileName[_MAX_PATH];
wsprintf(szIniFileName,"%s\\free.Premium.ini",szWorkDir);
LoadIniFile(szIniFileName,&m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Free]);
wsprintf(szIniFileName,"%s\\pay.Premium.ini",szWorkDir);
LoadIniFile(szIniFileName,&m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Pay]);
return TRUE;
}
BOOL CPremiumPlayerCtrl::
isAccessMap(const int MapIdx,const i3client_t* pPlayerRecord) const
{
if(MapIdx < 0) return FALSE;
if(MapIdx > i3client_t::tagPremiumInfo::maxmap_number) return FALSE;
return pPlayerRecord->PremiumInfo.Map[MapIdx].Cur.bAllow;
}
void CPremiumPlayerCtrl::
SetData(enum i3client_t::tagPremiumInfo::enumMeberShipType MemberShipType,i3client_t* pPlayerRecord) const
{
switch(MemberShipType){
default:
case i3client_t::tagPremiumInfo::enumMeberShipType::Free:
memcpy(&(pPlayerRecord->PremiumInfo),
&(m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Free]),
sizeof(struct i3client_t::tagPremiumInfo));
return;
case i3client_t::tagPremiumInfo::enumMeberShipType::Pay:
memcpy(&(pPlayerRecord->PremiumInfo),
&(m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Pay]),
sizeof(struct i3client_t::tagPremiumInfo));
return;
}
}
void CPremiumPlayerCtrl::Init_PremiumLevelTable_Pay(void)
{
struct i3client_t::tagPremiumInfo* pPremium = &(m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Pay]);
memset(pPremium,0x00,sizeof(struct i3client_t::tagPremiumInfo));
pPremium->iMemberShipType = i3client_t::tagPremiumInfo::enumMeberShipType::Pay;
for(int idx=0; idx < i3client_t::tagPremiumInfo::maxmap_number; idx++){
pPremium->Map[idx].Default.bAllow = TRUE;
pPremium->Map[idx].Default.iRemainSecond=0x7fffffff;
pPremium->Map[idx].Default.bDecreseRemainSecond=FALSE;
pPremium->Map[idx].Default.bDecreseAllRemainSecond = FALSE;
pPremium->Map[idx].Default.fAddExpRatio = 1.0f;
pPremium->Map[idx].Default.fAddGenExpRatio = 1.0f;
pPremium->Map[idx].Default.fAddGenCapabilityRatio=1.0f;
pPremium->Map[idx].Default.fAddItemDropRatio = 1.0f;
pPremium->Map[idx].Default.fAddNarkRatio = 1.0f;
pPremium->Map[idx].Cur = pPremium->Map[idx].Default;
}
pPremium->Gamble.fAddPriceRatio = 1.0f;
for(idx=0; idx < i3client_t::tagPremiumInfo::tagGamble::maxnum_apperance_item_group; idx++){
pPremium->Gamble.ItemGroupArray[idx].bApperance=TRUE;
}
pPremium->ItemOptionUpgrade.iMaxlevel = 10;
pPremium->ItemOptionUpgrade.fAddPriceRatio = 1.0f;
pPremium->Die.fExpRatio = 1.0f;
pPremium->Die.fNakRatio = 1.0f;
pPremium->bCreatePremiumBooth = FALSE;
pPremium->iMaxLevelItemCraft = 10;
pPremium->fItemPrecocityTimeRatio = 1.0f;
pPremium->bItemRecycle = TRUE;
pPremium->GonyounPracticeBattle.lDate = time(NULL);
pPremium->GonyounPracticeBattle.iMaxCount = 5;
pPremium->GonyounPracticeBattle.iDecreseCount = pPremium->GonyounPracticeBattle.iMaxCount;
pPremium->WorldChatting.lDate = 0;
pPremium->WorldChatting.iMaxCount = 10000;
pPremium->WorldChatting.iDecreaseCount = pPremium->WorldChatting.iMaxCount;
pPremium->Status.iDefaultInitCount= 1;
pPremium->Status.iInitCount=1000;
}
char* GetFLOATString(const float fValue)
{
static char str[20];
sprintf(str,"%3.02f",fValue);
return str;
}
char* GetINTString(const int iValue)
{
static char str[20];
wsprintf((char*)str,"%d",iValue);
return str;
}
char* GetBOOLString(const BOOL bIs)
{
static char str[2][10]={"YES","NO"};
if(TRUE == bIs) return str[0];
return str[1];
}
void CPremiumPlayerCtrl::Init_PremiumLevelTable_Free(void)
{
char szWorkDir[_MAX_PATH];
::GetCurrentDirectory(_MAX_PATH,szWorkDir);
char szIniFileName[_MAX_PATH];
wsprintf(szIniFileName,"%s\\free.Premium.ini",szWorkDir);
char AppName[_MAX_PATH];
char Session[_MAX_PATH];
struct i3client_t::tagPremiumInfo* pPremium = &(m_PremiumLevelTable[i3client_t::tagPremiumInfo::enumMeberShipType::Free]);
memset(pPremium,0x00,sizeof(struct i3client_t::tagPremiumInfo));
pPremium->iMemberShipType = i3client_t::tagPremiumInfo::enumMeberShipType::Free;
for(int idx=0; idx < i3client_t::tagPremiumInfo::maxmap_number; idx++){
wsprintf(AppName,"Map%02d",idx);
pPremium->Map[idx].Default.bAllow = TRUE;
::WritePrivateProfileString(AppName,"Allow",GetBOOLString(pPremium->Map[idx].Default.bAllow),szIniFileName);
pPremium->Map[idx].Default.iRemainSecond=0x7fffffff;
::WritePrivateProfileString(AppName,"iRemainSecond",GetINTString(pPremium->Map[idx].Default.iRemainSecond),szIniFileName);
pPremium->Map[idx].Default.bDecreseRemainSecond=FALSE;
::WritePrivateProfileString(AppName,"bDecreseRemainSecond",GetBOOLString(pPremium->Map[idx].Default.bDecreseRemainSecond),szIniFileName);
pPremium->Map[idx].Default.bDecreseAllRemainSecond = FALSE;
::WritePrivateProfileString(AppName,"bDecreseAllRemainSecond",GetBOOLString(pPremium->Map[idx].Default.bDecreseAllRemainSecond),szIniFileName);
pPremium->Map[idx].Default.fAddExpRatio = 1.0f;
::WritePrivateProfileString(AppName,"fAddExpRatio",GetFLOATString(pPremium->Map[idx].Default.fAddExpRatio),szIniFileName);
pPremium->Map[idx].Default.fAddGenExpRatio = 1.0f;
::WritePrivateProfileString(AppName,"fAddGenExpRatio",GetFLOATString(pPremium->Map[idx].Default.fAddGenExpRatio),szIniFileName);
pPremium->Map[idx].Default.fAddGenCapabilityRatio=1.0f;
::WritePrivateProfileString(AppName,"fAddGenCapabilityRatio",GetFLOATString(pPremium->Map[idx].Default.fAddGenCapabilityRatio),szIniFileName);
pPremium->Map[idx].Default.fAddItemDropRatio = 1.0f;
::WritePrivateProfileString(AppName,"fAddItemDropRatio",GetFLOATString(pPremium->Map[idx].Default.fAddItemDropRatio),szIniFileName);
pPremium->Map[idx].Default.fAddNarkRatio = 1.0f;
::WritePrivateProfileString(AppName,"fAddNarkRatio",GetFLOATString(pPremium->Map[idx].Default.fAddNarkRatio),szIniFileName);
pPremium->Map[idx].Cur = pPremium->Map[idx].Default;
}
pPremium->Map[Light_Lake].Cur.bAllow=FALSE;
wsprintf(AppName,"Gameble");
pPremium->Gamble.fAddPriceRatio = 1.0f;
::WritePrivateProfileString(AppName,"fAddPriceRatio",GetFLOATString(pPremium->Gamble.fAddPriceRatio),szIniFileName);
for(idx=0; idx < i3client_t::tagPremiumInfo::tagGamble::maxnum_apperance_item_group; idx++){
wsprintf(Session,"Group%02d");
pPremium->Gamble.ItemGroupArray[idx].bApperance=TRUE;
::WritePrivateProfileString(AppName,Session,GetBOOLString(pPremium->Gamble.ItemGroupArray[idx].bApperance),szIniFileName);
}
wsprintf(AppName,"ItemOptionUpgrade");
pPremium->ItemOptionUpgrade.iMaxlevel = 10;
::WritePrivateProfileString(AppName,"iMaxlevel",GetINTString(pPremium->ItemOptionUpgrade.iMaxlevel),szIniFileName);
pPremium->ItemOptionUpgrade.fAddPriceRatio = 1.0f;
::WritePrivateProfileString(AppName,"fAddPriceRatio",GetFLOATString(pPremium->ItemOptionUpgrade.fAddPriceRatio),szIniFileName);
wsprintf(AppName,"Die");
pPremium->Die.fExpRatio = 1.0f;
::WritePrivateProfileString(AppName,"fExpRatio",GetFLOATString(pPremium->Die.fExpRatio),szIniFileName);
pPremium->Die.fNakRatio = 1.0f;
::WritePrivateProfileString(AppName,"fNakRatio",GetFLOATString(pPremium->Die.fNakRatio),szIniFileName);
pPremium->bCreatePremiumBooth = FALSE;
::WritePrivateProfileString("PremiumBooth","Use",GetBOOLString(pPremium->bCreatePremiumBooth),szIniFileName);
pPremium->iMaxLevelItemCraft = 10;
::WritePrivateProfileString("ItemCraft","iMaxLevel",GetINTString(pPremium->iMaxLevelItemCraft),szIniFileName);
pPremium->fItemPrecocityTimeRatio = 1.0f;
::WritePrivateProfileString("ItemPrecocity","TimeRatio",GetFLOATString(pPremium->fItemPrecocityTimeRatio),szIniFileName);
pPremium->bItemRecycle = TRUE;
::WritePrivateProfileString("ItemRecycle","Use",GetBOOLString(pPremium->bItemRecycle),szIniFileName);
pPremium->GonyounPracticeBattle.lDate = time(NULL);
pPremium->GonyounPracticeBattle.iMaxCount = 5;
::WritePrivateProfileString("GonyounPracticeBattle","iMaxCount",GetINTString(pPremium->GonyounPracticeBattle.iMaxCount),szIniFileName);
pPremium->GonyounPracticeBattle.iDecreseCount = pPremium->GonyounPracticeBattle.iMaxCount;
pPremium->WorldChatting.lDate = time(NULL);
pPremium->WorldChatting.iMaxCount = 10;
::WritePrivateProfileString("WorldChatting","iMaxCount",GetINTString(pPremium->WorldChatting.iMaxCount),szIniFileName);
pPremium->WorldChatting.iDecreaseCount = pPremium->WorldChatting.iMaxCount;
pPremium->Status.iDefaultInitCount= 1;
::WritePrivateProfileString("Status","iDefaultInitCount",GetINTString(pPremium->Status.iDefaultInitCount),szIniFileName);
pPremium->Status.iInitCount=1000;
::WritePrivateProfileString("Status","iInitCount",GetINTString(pPremium->Status.iInitCount),szIniFileName);
}
BOOL GetBOOL(const char* pStr)
{
if(0 == strcmp(pStr,"YES")) return TRUE;
if(0 == strcmp(pStr,"yes")) return TRUE;
if(0 == strcmp(pStr,"Yes")) return TRUE;
return FALSE;
}
int GetINT(const char* pStr)
{
return atoi(pStr);
}
float GetFLOAT(const char* pStr)
{
return atof(pStr);
}
void CPremiumPlayerCtrl::
LoadIniFile(const char* szpIniFileName,struct i3client_t::tagPremiumInfo* pPremium)
{
char AppName[_MAX_PATH];
char inStr[_MAX_PATH];
char Session[_MAX_PATH];
for(int idx=0; idx < i3client_t::tagPremiumInfo::maxmap_number; idx++){
wsprintf(AppName,"Map%02d",idx);
::GetPrivateProfileString(AppName,"Allow","YES",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.bAllow = GetBOOL(inStr);
::GetPrivateProfileString(AppName,"iRemainSecond","2147483647",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.iRemainSecond=GetINT(inStr);
::GetPrivateProfileString(AppName,"bDecreseRemainSecond","NO",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.bDecreseRemainSecond=GetBOOL(inStr);
::GetPrivateProfileString(AppName,"bDecreseAllRemainSecond","NO",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.bDecreseAllRemainSecond = GetBOOL(inStr);
::GetPrivateProfileString(AppName,"fAddExpRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.fAddExpRatio = GetFLOAT(inStr);
::GetPrivateProfileString(AppName,"fAddGenExpRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.fAddGenExpRatio = GetFLOAT(inStr);
::GetPrivateProfileString(AppName,"fAddGenCapabilityRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.fAddGenCapabilityRatio=GetFLOAT(inStr);
::GetPrivateProfileString(AppName,"fAddItemDropRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.fAddItemDropRatio =GetFLOAT(inStr);
::GetPrivateProfileString(AppName,"fAddNarkRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Map[idx].Default.fAddNarkRatio = GetFLOAT(inStr);
pPremium->Map[idx].Cur = pPremium->Map[idx].Default;
}
wsprintf(AppName,"Gameble");
::GetPrivateProfileString(AppName,"fAddPriceRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Gamble.fAddPriceRatio = GetFLOAT(inStr);
for(idx=0; idx < i3client_t::tagPremiumInfo::tagGamble::maxnum_apperance_item_group; idx++){
wsprintf(Session,"Group%02d");
::GetPrivateProfileString(AppName,Session,"YES",inStr,_MAX_PATH,szpIniFileName);
pPremium->Gamble.ItemGroupArray[idx].bApperance=GetBOOL(inStr);
}
wsprintf(AppName,"ItemOptionUpgrade");
::GetPrivateProfileString(AppName,"iMaxlevel","10",inStr,_MAX_PATH,szpIniFileName);
pPremium->ItemOptionUpgrade.iMaxlevel = GetINT(inStr);
::GetPrivateProfileString(AppName,"fAddPriceRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->ItemOptionUpgrade.fAddPriceRatio = GetFLOAT(inStr);
wsprintf(AppName,"Die");
::GetPrivateProfileString(AppName,"fExpRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Die.fExpRatio = GetFLOAT(inStr);
::GetPrivateProfileString(AppName,"fNakRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->Die.fNakRatio = GetFLOAT(inStr);
::GetPrivateProfileString("PremiumBooth","Use","FALSE",inStr,_MAX_PATH,szpIniFileName);
pPremium->bCreatePremiumBooth = GetBOOL(inStr);
::GetPrivateProfileString("ItemCraft","iMaxLevel","10",inStr,_MAX_PATH,szpIniFileName);
pPremium->iMaxLevelItemCraft = GetINT(inStr);
::GetPrivateProfileString("ItemPrecocity","TimeRatio","1.0f",inStr,_MAX_PATH,szpIniFileName);
pPremium->fItemPrecocityTimeRatio = GetFLOAT(inStr);
::GetPrivateProfileString("ItemRecycle","Use","YES",inStr,_MAX_PATH,szpIniFileName);
pPremium->bItemRecycle = GetBOOL(inStr);
pPremium->GonyounPracticeBattle.lDate = time(NULL);
::GetPrivateProfileString("GonyounPracticeBattle","iMaxCount","5",inStr,_MAX_PATH,szpIniFileName);
pPremium->GonyounPracticeBattle.iMaxCount = GetINT(inStr);
pPremium->GonyounPracticeBattle.iDecreseCount = pPremium->GonyounPracticeBattle.iMaxCount;
pPremium->WorldChatting.lDate = time(NULL);
::GetPrivateProfileString("WorldChatting","iMaxCount","10",inStr,_MAX_PATH,szpIniFileName);
pPremium->WorldChatting.iMaxCount = GetINT(inStr);
pPremium->WorldChatting.iDecreaseCount = pPremium->WorldChatting.iMaxCount;
::GetPrivateProfileString("Status","iDefaultInitCount","1",inStr,_MAX_PATH,szpIniFileName);
pPremium->Status.iDefaultInitCount= GetINT(inStr);
::GetPrivateProfileString("Status","iInitCount","1000",inStr,_MAX_PATH,szpIniFileName);
pPremium->Status.iInitCount=GetINT(inStr);
}
void CPremiumPlayerCtrl::SaveIniFile(const char* szpIniFileName,const struct i3client_t::tagPremiumInfo* pPremium)
{
char AppName[_MAX_PATH];
char Session[_MAX_PATH];
for(int idx=0; idx < i3client_t::tagPremiumInfo::maxmap_number; idx++){
wsprintf(AppName,"Map%02d",idx);
::WritePrivateProfileString(AppName,"Allow",GetBOOLString(pPremium->Map[idx].Default.bAllow),szpIniFileName);
::WritePrivateProfileString(AppName,"iRemainSecond",GetINTString(pPremium->Map[idx].Default.iRemainSecond),szpIniFileName);
::WritePrivateProfileString(AppName,"bDecreseRemainSecond",GetBOOLString(pPremium->Map[idx].Default.bDecreseRemainSecond),szpIniFileName);
::WritePrivateProfileString(AppName,"bDecreseAllRemainSecond",GetBOOLString(pPremium->Map[idx].Default.bDecreseAllRemainSecond),szpIniFileName);
::WritePrivateProfileString(AppName,"fAddExpRatio",GetFLOATString(pPremium->Map[idx].Default.fAddExpRatio),szpIniFileName);
::WritePrivateProfileString(AppName,"fAddGenExpRatio",GetFLOATString(pPremium->Map[idx].Default.fAddGenExpRatio),szpIniFileName);
::WritePrivateProfileString(AppName,"fAddGenCapabilityRatio",GetFLOATString(pPremium->Map[idx].Default.fAddGenCapabilityRatio),szpIniFileName);
::WritePrivateProfileString(AppName,"fAddItemDropRatio",GetFLOATString(pPremium->Map[idx].Default.fAddItemDropRatio),szpIniFileName);
::WritePrivateProfileString(AppName,"fAddNarkRatio",GetFLOATString(pPremium->Map[idx].Default.fAddNarkRatio),szpIniFileName);
}
wsprintf(AppName,"Gameble");
::WritePrivateProfileString(AppName,"fAddPriceRatio",GetFLOATString(pPremium->Gamble.fAddPriceRatio),szpIniFileName);
for(idx=0; idx < i3client_t::tagPremiumInfo::tagGamble::maxnum_apperance_item_group; idx++){
wsprintf(Session,"Group%02d");
::WritePrivateProfileString(AppName,Session,GetBOOLString(pPremium->Gamble.ItemGroupArray[idx].bApperance),szpIniFileName);
}
wsprintf(AppName,"ItemOptionUpgrade");
::WritePrivateProfileString(AppName,"iMaxlevel",GetINTString(pPremium->ItemOptionUpgrade.iMaxlevel),szpIniFileName);
::WritePrivateProfileString(AppName,"fAddPriceRatio",GetFLOATString(pPremium->ItemOptionUpgrade.fAddPriceRatio),szpIniFileName);
wsprintf(AppName,"Die");
::WritePrivateProfileString(AppName,"fExpRatio",GetFLOATString(pPremium->Die.fExpRatio),szpIniFileName);
::WritePrivateProfileString(AppName,"fNakRatio",GetFLOATString(pPremium->Die.fNakRatio),szpIniFileName);
::WritePrivateProfileString("PremiumBooth","Use",GetBOOLString(pPremium->bCreatePremiumBooth),szpIniFileName);
::WritePrivateProfileString("ItemCraft","iMaxLevel",GetINTString(pPremium->iMaxLevelItemCraft),szpIniFileName);
::WritePrivateProfileString("ItemPrecocity","TimeRatio",GetFLOATString(pPremium->fItemPrecocityTimeRatio),szpIniFileName);
::WritePrivateProfileString("ItemRecycle","Use",GetBOOLString(pPremium->bItemRecycle),szpIniFileName);
::WritePrivateProfileString("GonyounPracticeBattle","iMaxCount",GetINTString(pPremium->GonyounPracticeBattle.iMaxCount),szpIniFileName);
::WritePrivateProfileString("WorldChatting","iMaxCount",GetINTString(pPremium->WorldChatting.iMaxCount),szpIniFileName);
::WritePrivateProfileString("Status","iDefaultInitCount",GetINTString(pPremium->Status.iDefaultInitCount),szpIniFileName);
::WritePrivateProfileString("Status","iInitCount",GetINTString(pPremium->Status.iInitCount),szpIniFileName);
}
| C++ |
#include "../Global.h"
char *g_lTableToken[] =
{
"_kr",
"_en",
"_jp",
"_ch",
"_tw",
};
CGameConfigFlag gGameConfigFlag;
void CGameConfigFlag::SetFlag()
{
m_nFlag=0;
if(m_bPrecocity_Time) m_nFlag +=1 << 1;
if(m_bDie_Reduce_panality) m_nFlag +=1 << 2;
if(m_bMap_Attr_Ratio) m_nFlag +=1 << 3;
if(m_bItem_Upgrade_Limit) m_nFlag +=1 << 4;
if(m_bItem_Craft_Limit) m_nFlag +=1 << 5;
if(m_bWorld_Chat_Limit) m_nFlag +=1 << 6;
return ;
}
void CGameConfigFlag::SetFlag(int flag)
{
m_nFlag = flag;
int f=0;
if(flag & (1 << 1)) m_bPrecocity_Time=TRUE;
if(flag & (1 << 2)) m_bDie_Reduce_panality=TRUE;
if(flag & (1 << 3)) m_bMap_Attr_Ratio=TRUE;
if(flag & (1 << 4)) m_bItem_Upgrade_Limit=TRUE;
if(flag & (1 << 5)) m_bItem_Craft_Limit=TRUE;
if(flag & (1 << 6)) m_bWorld_Chat_Limit=TRUE;
}
int CGameConfigFlag::LoadFlagFile()
{
FILE *fp;
int size;
byte *buffer;
char *token;
char filename[128];
sprintf( filename, "flag%s.cfg", g_lTableToken[g_config.languageType] );
fp = fopen(filename, "rb" );
if( !fp )
{
MessageBox(NULL, "does not exist 'flag.cfg' file", "Error", MB_ICONHAND|MB_OK);
return false;
}
fseek(fp,0,SEEK_END);
size = ftell(fp);
buffer = new byte[size+1];
fseek(fp,0,SEEK_SET);
fread(buffer,size,1,fp);
if(NULL != fp){ fclose(fp); fp=NULL; }
curpos = (char *)buffer;
endpos = curpos + size;
while ((token = NextToken()) != NULL)
{
if( !stricmp( token, "CHARACTER_STORAGE" ) )
{
token = NextArg();
if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bCharacter_Storage = TRUE;
else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bCharacter_Storage = FALSE;
}
else if( !stricmp( token, "PRECOCITY_TIME" ) )
{
token = NextArg();
if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bPrecocity_Time = TRUE;
else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bPrecocity_Time = FALSE;
}
else if( !stricmp( token, "DIE_REDUCE_PANALTY" ) )
{
token = NextArg();
if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bDie_Reduce_panality = TRUE;
else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bDie_Reduce_panality = FALSE;
}
else if( !stricmp( token, "MAP_ATTR_RATIO" ) )
{
token = NextArg();
if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bMap_Attr_Ratio = TRUE;
else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bMap_Attr_Ratio = FALSE;
}
else if( !stricmp( token, "ITEM_UPGRADE_LIMIT" ) )
{
token = NextArg();
if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bItem_Craft_Limit = TRUE;
else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bItem_Craft_Limit = FALSE;
}
else if( !stricmp( token, "WORLD_CHAT_LIMIT" ) )
{
token = NextArg();
if(!stricmp( token, "TRUE" )) gGameConfigFlag.m_bWorld_Chat_Limit = TRUE;
else if (!stricmp( token, "FALSE" )) gGameConfigFlag.m_bWorld_Chat_Limit = FALSE;
}
}
if(NULL != fp){ fclose(fp); fp=NULL; }
if(NULL != buffer){ delete []buffer; buffer=NULL; }
SetFlag();
return true;
}
| C++ |
#if !defined(AFX_GAMECONFIGFLAG_H__64911BCF_348E_4592_AE6E_C851A9E5E8B1__INCLUDED_)
#define AFX_GAMECONFIGFLAG_H__64911BCF_348E_4592_AE6E_C851A9E5E8B1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
class CGameConfigFlag
{
public:
CGameConfigFlag()
{
Init();
}
virtual ~CGameConfigFlag()
{
}
void Init()
{
m_bCharacter_Storage =FALSE;
m_bPrecocity_Time =FALSE;
m_bDie_Reduce_panality =FALSE;
m_bMap_Attr_Ratio =FALSE;
m_bItem_Upgrade_Limit =FALSE;
m_bItem_Craft_Limit =FALSE;
m_bWorld_Chat_Limit =FALSE;
m_nFlag=0;
}
int LoadFlagFile();
int GetFlag()
{
return m_nFlag;
}
void SetFlag(int flag);
void SetFlag();
public:
BOOL m_bCharacter_Storage;
BOOL m_bPrecocity_Time;
BOOL m_bDie_Reduce_panality;
BOOL m_bMap_Attr_Ratio;
BOOL m_bItem_Upgrade_Limit;
BOOL m_bItem_Craft_Limit;
BOOL m_bWorld_Chat_Limit;
int m_nFlag;
};
extern CGameConfigFlag gGameConfigFlag;
#endif
| C++ |
#ifndef __INI_H__
#define __INI_H__
#include <windows.h>
#include <tchar.h>
#ifdef __AFXWIN_H__
#include <afxtempl.h>
#endif
#define BASE_BINARY 2
#define BASE_OCTAL 8
#define BASE_DECIMAL 10
#define BASE_HEXADECIMAL 16
typedef BOOL (CALLBACK *SUBSTRPROC)(LPCTSTR, LPVOID);
class CIni
{
public:
CIni();
CIni(LPCTSTR lpPathName);
virtual ~CIni();
void SetPathName(LPCTSTR lpPathName);
DWORD GetPathName(LPTSTR lpBuffer, DWORD dwBufSize) const;
#ifdef __AFXWIN_H__
CString GetPathName() const;
#endif
DWORD GetString(LPCTSTR lpSection, LPCTSTR lpKey, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDefault = NULL) const;
#ifdef __AFXWIN_H__
CString GetString(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpDefault = NULL) const;
#endif
BOOL WriteString(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpValue) const;
BOOL AppendString(LPCTSTR Section, LPCTSTR lpKey, LPCTSTR lpString) const;
DWORD GetArray(LPCTSTR lpSection, LPCTSTR lpKey, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter = NULL, BOOL bTrimString = TRUE) const;
#ifdef __AFXWIN_H__
void GetArray(LPCTSTR lpSection, LPCTSTR lpKey, CStringArray* pArray, LPCTSTR lpDelimiter = NULL, BOOL bTrimString = TRUE) const;
BOOL WriteArray(LPCTSTR lpSection, LPCTSTR lpKey, const CStringArray* pArray, int nWriteCount = -1, LPCTSTR lpDelimiter = NULL) const;
#endif
int GetInt(LPCTSTR lpSection, LPCTSTR lpKey, int nDefault, int nBase = BASE_DECIMAL) const;
BOOL WriteInt(LPCTSTR lpSection, LPCTSTR lpKey, int nValue, int nBase = BASE_DECIMAL) const;
BOOL IncreaseInt(LPCTSTR lpSection, LPCTSTR lpKey, int nIncrease = 1, int nBase = BASE_DECIMAL) const;
UINT GetUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nDefault, int nBase = BASE_DECIMAL) const;
BOOL WriteUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nValue, int nBase = BASE_DECIMAL) const;
BOOL IncreaseUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nIncrease = 1, int nBase = BASE_DECIMAL) const;
BOOL GetBool(LPCTSTR lpSection, LPCTSTR lpKey, BOOL bDefault) const;
BOOL WriteBool(LPCTSTR lpSection, LPCTSTR lpKey, BOOL bValue) const;
BOOL InvertBool(LPCTSTR lpSection, LPCTSTR lpKey) const;
double GetDouble(LPCTSTR lpSection, LPCTSTR lpKey, double fDefault) const;
BOOL WriteDouble(LPCTSTR lpSection, LPCTSTR lpKey, double fValue, int nPrecision = -1) const;
BOOL IncreaseDouble(LPCTSTR lpSection, LPCTSTR lpKey, double fIncrease, int nPrecision = -1) const;
TCHAR GetChar(LPCTSTR lpSection, LPCTSTR lpKey, TCHAR cDefault) const;
BOOL WriteChar(LPCTSTR lpSection, LPCTSTR lpKey, TCHAR c) const;
POINT GetPoint(LPCTSTR lpSection, LPCTSTR lpKey, POINT ptDefault) const;
BOOL WritePoint(LPCTSTR lpSection, LPCTSTR lpKey, POINT pt) const;
RECT GetRect(LPCTSTR lpSection, LPCTSTR lpKey, RECT rcDefault) const;
BOOL WriteRect(LPCTSTR lpSection, LPCTSTR lpKey, RECT rc) const;
DWORD GetDataBlock(LPCTSTR lpSection, LPCTSTR lpKey, LPVOID lpBuffer, DWORD dwBufSize, DWORD dwOffset = 0) const;
BOOL WriteDataBlock(LPCTSTR lpSection, LPCTSTR lpKey, LPCVOID lpData, DWORD dwDataSize) const;
BOOL AppendDataBlock(LPCTSTR lpSection, LPCTSTR lpKey, LPCVOID lpData, DWORD dwDataSize) const;
BOOL IsSectionExist(LPCTSTR lpSection) const;
DWORD GetSectionNames(LPTSTR lpBuffer, DWORD dwBufSize) const;
#ifdef __AFXWIN_H__
void GetSectionNames(CStringArray* pArray) const;
#endif
BOOL CopySection(LPCTSTR lpSrcSection, LPCTSTR lpDestSection, BOOL bFailIfExist) const;
BOOL MoveSection(LPCTSTR lpSrcSection, LPCTSTR lpDestSection, BOOL bFailIfExist = TRUE) const;
BOOL DeleteSection(LPCTSTR lpSection) const;
BOOL IsKeyExist(LPCTSTR lpSection, LPCTSTR lpKey) const;
DWORD GetKeyLines(LPCTSTR lpSection, LPTSTR lpBuffer, DWORD dwBufSize) const;
#ifdef __AFXWIN_H__
void GetKeyLines(LPCTSTR lpSection, CStringArray* pArray) const;
#endif
DWORD GetKeyNames(LPCTSTR lpSection, LPTSTR lpBuffer, DWORD dwBufSize) const;
#ifdef __AFXWIN_H__
void GetKeyNames(LPCTSTR lpSection, CStringArray* pArray) const;
#endif
BOOL CopyKey(LPCTSTR lpSrcSection, LPCTSTR lpSrcKey, LPCTSTR lpDestSection, LPCTSTR lpDestKey, BOOL bFailIfExist) const;
BOOL MoveKey(LPCTSTR lpSrcSection, LPCTSTR lpSrcKey, LPCTSTR lpDestSection, LPCTSTR lpDestKey, BOOL bFailIfExist = TRUE) const;
BOOL DeleteKey(LPCTSTR lpSection, LPCTSTR lpKey) const;
static BOOL ParseDNTString(LPCTSTR lpString, SUBSTRPROC lpFnStrProc, LPVOID lpParam = NULL);
static BOOL StringToBool(LPCTSTR lpString, BOOL bDefault = FALSE);
protected:
static LPTSTR __StrDupEx(LPCTSTR lpStart, LPCTSTR lpEnd);
static BOOL __TrimString(LPTSTR lpBuffer);
LPTSTR __GetStringDynamic(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpDefault = NULL) const;
static DWORD __StringSplit(LPCTSTR lpString, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter = NULL, BOOL bTrimString = TRUE);
static void __ToBinaryString(UINT nNumber, LPTSTR lpBuffer, DWORD dwBufSize);
static int __ValidateBase(int nBase);
static void __IntToString(int nNumber, LPTSTR lpBuffer, int nBase);
static void __UIntToString(UINT nNumber, LPTSTR lpBuffer, int nBase);
static BOOL CALLBACK __SubStrCompare(LPCTSTR lpString1, LPVOID lpParam);
static BOOL CALLBACK __KeyPairProc(LPCTSTR lpString, LPVOID lpParam);
#ifdef __AFXWIN_H__
static BOOL CALLBACK __SubStrAdd(LPCTSTR lpString, LPVOID lpParam);
#endif
LPTSTR m_pszPathName;
};
#endif | C++ |
#include "Ini.h"
#include <string.h>
#include <stdio.h>
#include <assert.h>
#define DEF_PROFILE_NUM_LEN 64
#define DEF_PROFILE_THRESHOLD 512
#define DEF_PROFILE_DELIMITER _T(",")
#define DEF_PROFILE_TESTSTRING _T("{63788286-AE30-4D6B-95DF-3B451C1C79F9}")
struct STR_LIMIT
{
LPTSTR lpTarget;
DWORD dwRemain;
DWORD dwTotalCopied;
};
CIni::CIni()
{
m_pszPathName = NULL;
}
CIni::CIni(LPCTSTR lpPathName)
{
m_pszPathName = NULL;
SetPathName(lpPathName);
}
CIni::~CIni()
{
if (m_pszPathName != NULL)
delete [] m_pszPathName;
}
void CIni::SetPathName(LPCTSTR lpPathName)
{
if (lpPathName == NULL)
{
if (m_pszPathName != NULL)
*m_pszPathName = _T('\0');
}
else
{
if (m_pszPathName != NULL)
delete [] m_pszPathName;
m_pszPathName = _tcsdup(lpPathName);
}
}
DWORD CIni::GetPathName(LPTSTR lpBuffer, DWORD dwBufSize) const
{
*lpBuffer = _T('\0');
DWORD dwLen = 0;
if (lpBuffer != NULL)
{
_tcsncpy(lpBuffer, m_pszPathName, dwBufSize);
dwLen = _tcslen(lpBuffer);
}
else
{
dwLen = _tcslen(m_pszPathName);
}
return dwLen;
}
#ifdef __AFXWIN_H__
CString CIni::GetPathName() const
{
return CString(m_pszPathName);
}
#endif
DWORD CIni::GetString(LPCTSTR lpSection, LPCTSTR lpKey, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDefault) const
{
if (lpBuffer != NULL)
*lpBuffer = _T('\0');
LPTSTR psz = __GetStringDynamic(lpSection, lpKey, lpDefault);
DWORD dwLen = _tcslen(psz);
if (lpBuffer != NULL)
{
_tcsncpy(lpBuffer, psz, dwBufSize);
dwLen = min(dwLen, dwBufSize);
}
delete [] psz;
return dwLen;
}
#ifdef __AFXWIN_H__
CString CIni::GetString(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpDefault) const
{
LPTSTR psz = __GetStringDynamic(lpSection, lpKey, lpDefault);
CString str(psz);
delete [] psz;
return str;
}
#endif
BOOL CIni::WriteString(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpValue) const
{
if (lpSection == NULL || lpKey == NULL)
return FALSE;
return ::WritePrivateProfileString(lpSection, lpKey, lpValue == NULL ? _T("") : lpValue, m_pszPathName);
}
BOOL CIni::AppendString(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpString) const
{
if (lpString == NULL)
return FALSE;
TCHAR* psz = __GetStringDynamic(lpSection, lpKey);
TCHAR* pNewString = new TCHAR[_tcslen(psz) + _tcslen(lpString) + 1];
_stprintf(pNewString, _T("%s%s"), psz, lpString);
const BOOL RES = WriteString(lpSection, lpKey, pNewString);
delete [] pNewString;
delete [] psz;
return RES;
}
DWORD CIni::GetArray(LPCTSTR lpSection, LPCTSTR lpKey, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter, BOOL bTrimString) const
{
if (lpBuffer != NULL)
*lpBuffer = _T('\0');
if (lpSection == NULL || lpKey == NULL)
return 0;
LPTSTR psz = __GetStringDynamic(lpSection, lpKey);
DWORD dwCopied = 0;
if (*psz != _T('\0'))
{
if (lpBuffer == NULL)
{
const DWORD MAX_LEN = _tcslen(psz) + 2;
LPTSTR p = new TCHAR[MAX_LEN + 1];
dwCopied = __StringSplit(psz, p, MAX_LEN, lpDelimiter, bTrimString);
delete [] p;
}
else
{
dwCopied = __StringSplit(psz, lpBuffer, dwBufSize, lpDelimiter, bTrimString);
}
}
delete [] psz;
return dwCopied;
}
#ifdef __AFXWIN_H__
void CIni::GetArray(LPCTSTR lpSection, LPCTSTR lpKey, CStringArray *pArray, LPCTSTR lpDelimiter, BOOL bTrimString) const
{
if (pArray != NULL)
pArray->RemoveAll();
const DWORD LEN = GetArray(lpSection, lpKey, NULL, 0, lpDelimiter);
if (LEN == 0)
return;
LPTSTR psz = new TCHAR[LEN + 3];
GetArray(lpSection, lpKey, psz, LEN + 2, lpDelimiter);
ParseDNTString(psz, __SubStrAdd, (LPVOID)pArray);
delete [] psz;
}
#endif
#ifdef __AFXWIN_H__
BOOL CIni::WriteArray(LPCTSTR lpSection, LPCTSTR lpKey, const CStringArray *pArray, int nWriteCount, LPCTSTR lpDelimiter) const
{
if (pArray == NULL)
return FALSE;
if (nWriteCount < 0)
nWriteCount = pArray->GetSize();
else
nWriteCount = min(nWriteCount, pArray->GetSize());
const CString DELIMITER = (lpDelimiter == NULL || *lpDelimiter == _T('\0')) ? _T(",") : lpDelimiter;
CString sLine;
for (int i = 0; i < nWriteCount; i++)
{
sLine += pArray->GetAt(i);
if (i != nWriteCount - 1)
sLine += DELIMITER;
}
return WriteString(lpSection, lpKey, sLine);
}
#endif
int CIni::GetInt(LPCTSTR lpSection, LPCTSTR lpKey, int nDefault, int nBase) const
{
TCHAR sz[DEF_PROFILE_NUM_LEN + 1] = _T("");
GetString(lpSection, lpKey, sz, DEF_PROFILE_NUM_LEN);
return *sz == _T('\0') ? nDefault : int(_tcstoul(sz, NULL, __ValidateBase(nBase)));
}
UINT CIni::GetUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nDefault, int nBase) const
{
TCHAR sz[DEF_PROFILE_NUM_LEN + 1] = _T("");
GetString(lpSection, lpKey, sz, DEF_PROFILE_NUM_LEN);
return *sz == _T('\0') ? nDefault : UINT(_tcstoul(sz, NULL, __ValidateBase(nBase)));
}
BOOL CIni::GetBool(LPCTSTR lpSection, LPCTSTR lpKey, BOOL bDefault) const
{
TCHAR sz[DEF_PROFILE_NUM_LEN + 1] = _T("");
GetString(lpSection, lpKey, sz, DEF_PROFILE_NUM_LEN);
return StringToBool(sz, bDefault);
}
double CIni::GetDouble(LPCTSTR lpSection, LPCTSTR lpKey, double fDefault) const
{
TCHAR sz[DEF_PROFILE_NUM_LEN + 1] = _T("");
GetString(lpSection, lpKey, sz, DEF_PROFILE_NUM_LEN);
return *sz == _T('\0') ? fDefault : _tcstod(sz, NULL);
}
BOOL CIni::WriteInt(LPCTSTR lpSection, LPCTSTR lpKey, int nValue, int nBase) const
{
TCHAR szValue[DEF_PROFILE_NUM_LEN + 1] = _T("");
__IntToString(nValue, szValue, nBase);
return WriteString(lpSection, lpKey, szValue);
}
BOOL CIni::WriteUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nValue, int nBase) const
{
TCHAR szValue[DEF_PROFILE_NUM_LEN + 1] = _T("");
__UIntToString(nValue, szValue, nBase);
return WriteString(lpSection, lpKey, szValue);
}
BOOL CIni::WriteDouble(LPCTSTR lpSection, LPCTSTR lpKey, double fValue, int nPrecision) const
{
TCHAR szFmt[16] = _T("%f");
if (nPrecision > 0)
_stprintf(szFmt, _T("%%.%df"), nPrecision);
TCHAR szValue[DEF_PROFILE_NUM_LEN + 1] = _T("");
_stprintf(szValue, szFmt, fValue);
return WriteString(lpSection, lpKey, szValue);
}
BOOL CIni::IncreaseDouble(LPCTSTR lpSection, LPCTSTR lpKey, double fIncrease, int nPrecision) const
{
double f = GetDouble(lpSection, lpKey, 0.0);
f += fIncrease;
return WriteDouble(lpSection, lpKey, f, nPrecision);
}
BOOL CIni::WriteBool(LPCTSTR lpSection, LPCTSTR lpKey, BOOL bValue) const
{
return WriteInt(lpSection, lpKey, bValue ? 1 : 0, BASE_DECIMAL);
}
BOOL CIni::InvertBool(LPCTSTR lpSection, LPCTSTR lpKey) const
{
return WriteBool(lpSection, lpKey, !GetBool(lpSection, lpKey, FALSE));
}
BOOL CIni::IncreaseInt(LPCTSTR lpSection, LPCTSTR lpKey, int nIncrease, int nBase) const
{
int nVal = GetInt(lpSection, lpKey, 0, nBase);
nVal += nIncrease;
return WriteInt(lpSection, lpKey, nVal, nBase);
}
BOOL CIni::IncreaseUInt(LPCTSTR lpSection, LPCTSTR lpKey, UINT nIncrease, int nBase) const
{
UINT nVal = GetUInt(lpSection, lpKey, 0, nBase);
nVal += nIncrease;
return WriteUInt(lpSection, lpKey, nVal, nBase);
}
TCHAR CIni::GetChar(LPCTSTR lpSection, LPCTSTR lpKey, TCHAR cDefault) const
{
TCHAR sz[2] = _T("");
GetString(lpSection, lpKey, sz, 1);
return *sz == _T('\0') ? cDefault : sz[0];
}
BOOL CIni::WriteChar(LPCTSTR lpSection, LPCTSTR lpKey, TCHAR c) const
{
TCHAR sz[2] = { c, _T('\0') };
return WriteString(lpSection, lpKey, sz);
}
DWORD CIni::GetDataBlock(LPCTSTR lpSection, LPCTSTR lpKey, LPVOID lpBuffer, DWORD dwBufSize, DWORD dwOffset) const
{
LPTSTR psz = __GetStringDynamic(lpSection, lpKey);
DWORD dwLen = _tcslen(psz) / 2;
if (dwLen <= dwOffset)
{
delete [] psz;
return 0;
}
for (int i = 0; psz[i] != _T('\0'); i++)
{
TCHAR c = psz[i];
if ((c >= _T('0') && c <= _T('9'))
|| (c >= _T('a') && c <= _T('f'))
|| (c >= _T('A') && c <= _T('F')))
{
}
else
{
delete [] psz;
return 0;
}
}
DWORD dwProcLen = 0;
LPBYTE lpb = (LPBYTE)lpBuffer;
if (lpb != NULL)
{
dwProcLen = min(dwLen - dwOffset, dwBufSize);
LPCTSTR p = &psz[dwOffset * 2];
for (DWORD i = 0; i < dwProcLen; i++)
{
TCHAR sz[3] = _T("");
_tcsncpy(sz, p, 2);
lpb[i] = BYTE(_tcstoul(sz, NULL, 16));
p = &p[2];
}
}
else
{
dwProcLen = dwLen - dwOffset;
}
delete [] psz;
return dwProcLen;
}
BOOL CIni::WriteDataBlock(LPCTSTR lpSection, LPCTSTR lpKey, LPCVOID lpData, DWORD dwDataSize) const
{
const BYTE* lpb = (const BYTE*)lpData;
if (lpb == NULL)
return FALSE;
LPTSTR psz = new TCHAR[dwDataSize * 2 + 1];
for (DWORD i = 0, j = 0; i < dwDataSize; i++, j += 2)
_stprintf(&psz[j], _T("%02X"), lpb[i]);
const BOOL RES = WriteString(lpSection, lpKey, psz);
delete [] psz;
return RES;
}
BOOL CIni::AppendDataBlock(LPCTSTR lpSection, LPCTSTR lpKey, LPCVOID lpData, DWORD dwDataSize) const
{
const BYTE* lpb = (const BYTE*)lpData;
if (lpb == NULL)
return FALSE;
LPTSTR psz = new TCHAR[dwDataSize * 2 + 1];
for (DWORD i = 0, j = 0; i < dwDataSize; i++, j += 2)
_stprintf(&psz[j], _T("%02X"), lpb[i]);
const BOOL RES = AppendString(lpSection, lpKey, psz);
delete [] psz;
return RES;
}
POINT CIni::GetPoint(LPCTSTR lpSection, LPCTSTR lpKey, POINT ptDefault) const
{
POINT pt;
if (GetDataBlock(lpSection, lpKey, &pt, sizeof(POINT)) != sizeof(POINT))
pt = ptDefault;
return pt;
}
RECT CIni::GetRect(LPCTSTR lpSection, LPCTSTR lpKey, RECT rcDefault) const
{
RECT rc;
if (GetDataBlock(lpSection, lpKey, &rc, sizeof(RECT)) != sizeof(RECT))
rc = rcDefault;
return rc;
}
BOOL CIni::WritePoint(LPCTSTR lpSection, LPCTSTR lpKey, POINT pt) const
{
return WriteDataBlock(lpSection, lpKey, &pt, sizeof(POINT));
}
BOOL CIni::WriteRect(LPCTSTR lpSection, LPCTSTR lpKey, RECT rc) const
{
return WriteDataBlock(lpSection, lpKey, &rc, sizeof(RECT));
}
DWORD CIni::GetKeyLines(LPCTSTR lpSection, LPTSTR lpBuffer, DWORD dwBufSize) const
{
if (lpBuffer != NULL)
*lpBuffer = _T('\0');
if (lpSection == NULL)
return 0;
if (lpBuffer == NULL)
{
DWORD dwLen = DEF_PROFILE_THRESHOLD;
LPTSTR psz = new TCHAR[dwLen + 1];
DWORD dwCopied = ::GetPrivateProfileSection(lpSection, psz, dwLen, m_pszPathName);
while (dwCopied + 2 >= dwLen)
{
dwLen += DEF_PROFILE_THRESHOLD;
delete [] psz;
psz = new TCHAR[dwLen + 1];
dwCopied = ::GetPrivateProfileSection(lpSection, psz, dwLen, m_pszPathName);
}
delete [] psz;
return dwCopied + 2;
}
else
{
return ::GetPrivateProfileSection(lpSection, lpBuffer, dwBufSize, m_pszPathName);
}
}
DWORD CIni::GetKeyNames(LPCTSTR lpSection, LPTSTR lpBuffer, DWORD dwBufSize) const
{
if (lpBuffer != NULL)
*lpBuffer = _T('\0');
if (lpSection == NULL)
return 0;
STR_LIMIT sl;
sl.lpTarget = lpBuffer;
sl.dwRemain = dwBufSize;
sl.dwTotalCopied = 0;
const DWORD LEN = GetKeyLines(lpSection, NULL, 0);
if (LEN == 0)
return 0;
LPTSTR psz = new TCHAR[LEN + 1];
GetKeyLines(lpSection, psz, LEN);
ParseDNTString(psz, __KeyPairProc, (LPVOID)(&sl));
delete [] psz;
if (lpBuffer != NULL)
lpBuffer[sl.dwTotalCopied] = _T('\0');
return sl.dwTotalCopied;
}
DWORD CIni::GetSectionNames(LPTSTR lpBuffer, DWORD dwBufSize) const
{
if (lpBuffer == NULL)
{
DWORD dwLen = DEF_PROFILE_THRESHOLD;
LPTSTR psz = new TCHAR[dwLen + 1];
DWORD dwCopied = ::GetPrivateProfileSectionNames(psz, dwLen, m_pszPathName);
while (dwCopied + 2 >= dwLen)
{
dwLen += DEF_PROFILE_THRESHOLD;
delete [] psz;
psz = new TCHAR[dwLen + 1];
dwCopied = ::GetPrivateProfileSectionNames(psz, dwLen, m_pszPathName);
}
delete [] psz;
return dwCopied + 2;
}
else
{
return ::GetPrivateProfileSectionNames(lpBuffer, dwBufSize, m_pszPathName);
}
}
#ifdef __AFXWIN_H__
void CIni::GetSectionNames(CStringArray *pArray) const
{
if (pArray != NULL)
pArray->RemoveAll();
const DWORD LEN = GetSectionNames(NULL, 0);
if (LEN == 0)
return;
LPTSTR psz = new TCHAR[LEN + 1];
GetSectionNames(psz, LEN);
ParseDNTString(psz, __SubStrAdd, pArray);
delete [] psz;
}
#endif
#ifdef __AFXWIN_H__
void CIni::GetKeyLines(LPCTSTR lpSection, CStringArray *pArray) const
{
if (pArray != NULL)
pArray->RemoveAll();
const DWORD LEN = GetKeyLines(lpSection, NULL, 0);
if (LEN == 0)
return;
LPTSTR psz = new TCHAR[LEN + 1];
GetKeyLines(lpSection, psz, LEN);
ParseDNTString(psz, __SubStrAdd, pArray);
delete [] psz;
}
#endif
#ifdef __AFXWIN_H__
void CIni::GetKeyNames(LPCTSTR lpSection, CStringArray *pArray) const
{
if (pArray == NULL)
return;
pArray->RemoveAll();
const LEN = GetKeyNames(lpSection, NULL, 0);
LPTSTR psz = new TCHAR[LEN + 1];
GetKeyNames(lpSection, psz, LEN);
ParseDNTString(psz, __SubStrAdd, (LPVOID)pArray);
delete [] psz;
}
#endif
BOOL CIni::DeleteSection(LPCTSTR lpSection) const
{
return ::WritePrivateProfileString(lpSection, NULL, _T(""), m_pszPathName);
}
BOOL CIni::DeleteKey(LPCTSTR lpSection, LPCTSTR lpKey) const
{
return ::WritePrivateProfileString(lpSection, lpKey, NULL, m_pszPathName);
}
BOOL CIni::IsSectionExist(LPCTSTR lpSection) const
{
if (lpSection == NULL)
return FALSE;
const DWORD LEN = GetSectionNames(NULL, 0);
if (LEN == 0)
return FALSE;
LPTSTR psz = new TCHAR[LEN + 1];
GetSectionNames(psz, LEN);
BOOL RES = !ParseDNTString(psz, __SubStrCompare, (LPVOID)lpSection);
delete [] psz;
return RES;
}
BOOL CIni::IsKeyExist(LPCTSTR lpSection, LPCTSTR lpKey) const
{
if (lpSection == NULL || lpKey == NULL)
return FALSE;
LPTSTR psz = __GetStringDynamic(lpSection, lpKey, DEF_PROFILE_TESTSTRING);
const BOOL RES = (_tcscmp(psz, DEF_PROFILE_TESTSTRING) != 0);
delete [] psz;
return RES;
}
BOOL CIni::CopySection(LPCTSTR lpSrcSection, LPCTSTR lpDestSection, BOOL bFailIfExist) const
{
if (lpSrcSection == NULL || lpDestSection == NULL)
return FALSE;
if (_tcsicmp(lpSrcSection, lpDestSection) == 0)
return FALSE;
if (!IsSectionExist(lpSrcSection))
return FALSE;
if (bFailIfExist && IsSectionExist(lpDestSection))
return FALSE;
DeleteSection(lpDestSection);
const DWORD SRC_LEN = GetKeyLines(lpSrcSection, NULL, 0);
LPTSTR psz = new TCHAR[SRC_LEN + 2];
GetKeyLines(lpSrcSection, psz, SRC_LEN);
const BOOL RES = ::WritePrivateProfileSection(lpDestSection, psz, m_pszPathName);
delete [] psz;
return RES;
}
BOOL CIni::CopyKey(LPCTSTR lpSrcSection, LPCTSTR lpSrcKey, LPCTSTR lpDestSection, LPCTSTR lpDestKey, BOOL bFailIfExist) const
{
if (lpSrcSection == NULL || lpSrcKey == NULL || lpDestKey == NULL)
return FALSE;
if (_tcsicmp(lpSrcSection, lpDestSection) == 0
&& _tcsicmp(lpSrcKey, lpDestKey) == 0)
return FALSE;
if (!IsKeyExist(lpSrcSection, lpSrcKey))
return FALSE;
if (bFailIfExist && IsKeyExist(lpDestSection, lpDestKey))
return FALSE;
LPTSTR psz = __GetStringDynamic(lpSrcSection, lpSrcKey);
const BOOL RES = WriteString(lpDestSection, lpDestKey, psz);
delete [] psz;
return RES;
}
BOOL CIni::MoveSection(LPCTSTR lpSrcSection, LPCTSTR lpDestSection, BOOL bFailIfExist) const
{
return CopySection(lpSrcSection, lpDestSection, bFailIfExist)
&& DeleteSection(lpSrcSection);
}
BOOL CIni::MoveKey(LPCTSTR lpSrcSection, LPCTSTR lpSrcKey, LPCTSTR lpDestSection, LPCTSTR lpDestKey, BOOL bFailIfExist) const
{
return CopyKey(lpSrcSection, lpSrcKey, lpDestSection, lpDestKey, bFailIfExist)
&& DeleteKey(lpSrcSection, lpSrcKey);
}
LPTSTR CIni::__GetStringDynamic(LPCTSTR lpSection, LPCTSTR lpKey, LPCTSTR lpDefault) const
{
TCHAR* psz = NULL;
if (lpSection == NULL || lpKey == NULL)
{
if (lpDefault == NULL)
{
psz = new TCHAR[1];
*psz = _T('\0');
}
else
{
psz = new TCHAR[_tcslen(lpDefault) + 1];
_tcscpy(psz, lpDefault);
}
return psz;
}
DWORD dwLen = DEF_PROFILE_THRESHOLD;
psz = new TCHAR[dwLen + 1];
DWORD dwCopied = ::GetPrivateProfileString(lpSection, lpKey, lpDefault == NULL ? _T("") : lpDefault, psz, dwLen, m_pszPathName);
while (dwCopied + 1 >= dwLen)
{
dwLen += DEF_PROFILE_THRESHOLD;
delete [] psz;
psz = new TCHAR[dwLen + 1];
dwCopied = ::GetPrivateProfileString(lpSection, lpKey, lpDefault == NULL ? _T("") : lpDefault, psz, dwLen, m_pszPathName);
}
return psz;
}
DWORD CIni::__StringSplit(LPCTSTR lpString, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter, BOOL bTrimString)
{
if (lpString == NULL || lpBuffer == NULL || dwBufSize == 0)
return 0;
DWORD dwCopied = 0;
*lpBuffer = _T('\0');
if (*lpString == _T('\0'))
return 0;
if (lpDelimiter != NULL && *lpDelimiter == _T('\0'))
{
_tcsncpy(lpBuffer, lpString, dwBufSize - 1);
return _tcslen(lpBuffer);
}
LPTSTR pszDel = (lpDelimiter == NULL) ? _tcsdup(DEF_PROFILE_DELIMITER) : _tcsdup(lpDelimiter);
const DWORD DEL_LEN = _tcslen(pszDel);
LPTSTR lpTarget = lpBuffer;
LPCTSTR lpPos = lpString;
LPCTSTR lpEnd = _tcsstr(lpPos, pszDel);
while (lpEnd != NULL)
{
LPTSTR pszSeg = __StrDupEx(lpPos, lpEnd);
if (bTrimString)
__TrimString(pszSeg);
const DWORD SEG_LEN = _tcslen(pszSeg);
const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied);
if (COPY_LEN > 0)
{
dwCopied += COPY_LEN + 1;
_tcsncpy(lpTarget, pszSeg, COPY_LEN);
lpTarget[COPY_LEN] = _T('\0');
lpTarget = &lpTarget[SEG_LEN + 1];
}
delete [] pszSeg;
lpPos = &lpEnd[DEL_LEN];
lpEnd = _tcsstr(lpPos, pszDel);
}
LPTSTR pszSeg = _tcsdup(lpPos);
if (bTrimString)
__TrimString(pszSeg);
const DWORD SEG_LEN = _tcslen(pszSeg);
const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied);
if (COPY_LEN > 0)
{
dwCopied += COPY_LEN + 1;
_tcsncpy(lpTarget, pszSeg, COPY_LEN);
lpTarget[COPY_LEN] = _T('\0');
}
delete [] pszSeg;
lpBuffer[dwCopied] = _T('\0');
delete [] pszDel;
return dwCopied;
}
BOOL CIni::ParseDNTString(LPCTSTR lpString, SUBSTRPROC lpFnStrProc, LPVOID lpParam)
{
if (lpString == NULL || lpFnStrProc == NULL)
return FALSE;
LPCTSTR p = lpString;
DWORD dwLen = _tcslen(p);
while (dwLen > 0)
{
if (!lpFnStrProc(p, lpParam))
return FALSE;
p = &p[dwLen + 1];
dwLen = _tcslen(p);
}
return TRUE;
}
BOOL CALLBACK CIni::__SubStrCompare(LPCTSTR lpString1, LPVOID lpParam)
{
assert(lpString1 != NULL);
LPCTSTR lpString2 = (LPCTSTR)lpParam;
assert(lpString2 != NULL);
return _tcsicmp(lpString1, lpString2) != 0;
}
BOOL CALLBACK CIni:: __KeyPairProc(LPCTSTR lpString, LPVOID lpParam)
{
STR_LIMIT* psl = (STR_LIMIT*)lpParam;
if (lpString == NULL || psl== NULL)
return FALSE;
LPCTSTR p = _tcschr(lpString, _T('='));
if (p == NULL || p == lpString)
return TRUE;
LPTSTR psz = new TCHAR[_tcslen(lpString) + 1];
for (int i = 0; &lpString[i] < p; i++)
psz[i] = lpString[i];
psz[i] = _T('\0');
__TrimString(psz);
DWORD dwNameLen = _tcslen(psz);
DWORD dwCopyLen = 0;
if (psl->lpTarget != NULL)
{
dwCopyLen = (psl->dwRemain > 1) ? min(dwNameLen, psl->dwRemain - 1) : 0;
_tcsncpy(psl->lpTarget, psz, dwCopyLen);
psl->lpTarget[dwCopyLen] = _T('\0');
psl->lpTarget = &(psl->lpTarget[dwCopyLen + 1]);
psl->dwRemain -= dwCopyLen + 1;
}
else
{
dwCopyLen = dwNameLen;
}
delete [] psz;
psl->dwTotalCopied += dwCopyLen + 1;
return TRUE;
}
#ifdef __AFXWIN_H__
BOOL CALLBACK CIni::__SubStrAdd(LPCTSTR lpString, LPVOID lpParam)
{
CStringArray* pArray = (CStringArray*)lpParam;
if (pArray == NULL || lpString == NULL)
return FALSE;
pArray->Add(lpString);
return TRUE;
}
#endif
void CIni::__ToBinaryString(UINT nNumber, LPTSTR lpBuffer, DWORD dwBufSize)
{
if (dwBufSize == 0)
return;
DWORD dwIndex = 0;
do
{
lpBuffer[dwIndex++] = (nNumber % 2) ? _T('1') : _T('0');
nNumber /= 2;
} while (nNumber > 0 && dwIndex < dwBufSize);
lpBuffer[dwIndex] = _T('\0');
_tcsrev(lpBuffer);
}
int CIni::__ValidateBase(int nBase)
{
switch (nBase)
{
case BASE_BINARY:
case BASE_OCTAL:
case BASE_HEXADECIMAL:
break;
default:
nBase = BASE_DECIMAL;
}
return nBase;
}
void CIni::__IntToString(int nNumber, LPTSTR lpBuffer, int nBase)
{
switch (nBase)
{
case BASE_BINARY:
case BASE_OCTAL:
case BASE_HEXADECIMAL:
__UIntToString((UINT)nNumber, lpBuffer, nBase);
break;
default:
_stprintf(lpBuffer, _T("%d"), nNumber);
break;
}
}
void CIni::__UIntToString(UINT nNumber, LPTSTR lpBuffer, int nBase)
{
switch (nBase)
{
case BASE_BINARY:
__ToBinaryString(nNumber, lpBuffer, DEF_PROFILE_NUM_LEN);
break;
case BASE_OCTAL:
_stprintf(lpBuffer, _T("%o"), nNumber);
break;
case BASE_HEXADECIMAL:
_stprintf(lpBuffer, _T("%X"), nNumber);
break;
default:
_stprintf(lpBuffer, _T("%u"), nNumber);
break;
}
}
BOOL CIni::StringToBool(LPCTSTR lpString, BOOL bDefault)
{
if (lpString == NULL || *lpString == _T('\0'))
return bDefault;
return (_tcsicmp(lpString, _T("true")) == 0
|| _tcsicmp(lpString, _T("yes")) == 0
|| _tcstol(lpString, NULL, BASE_DECIMAL) != 0);
}
BOOL CIni::__TrimString(LPTSTR lpString)
{
if (lpString == NULL)
return FALSE;
BOOL bTrimmed = FALSE;
unsigned int nLen = _tcslen(lpString);
while (nLen >= 0
&& (lpString[nLen - 1] == _T(' ')
|| lpString[nLen - 1] == _T('\t')
|| lpString[nLen - 1] == _T('\r')
|| lpString[nLen - 1] == _T('\n')))
{
lpString[--nLen] = _T('\0');
bTrimmed = TRUE;
}
LPCTSTR p = lpString;
while (*p == _T(' ')
|| *p == _T('\t')
|| *p == _T('\r')
|| *p == _T('\n'))
{
p = &p[1];
bTrimmed = TRUE;
}
if (p != lpString)
{
LPTSTR psz = _tcsdup(p);
_tcscpy(lpString, psz);
delete [] psz;
}
return bTrimmed;
}
LPTSTR CIni::__StrDupEx(LPCTSTR lpStart, LPCTSTR lpEnd)
{
const DWORD LEN = ((DWORD)lpEnd - (DWORD)lpStart) / sizeof(TCHAR);
LPTSTR psz = new TCHAR[LEN + 1];
_tcsncpy(psz, lpStart, LEN);
psz[LEN] = _T('\0');
return psz;
}
| C++ |
#if !defined(AFX_HICOCOONCTRL_H__E11D0F86_3974_4625_BFB5_3527DCA2E2A1__INCLUDED_)
#define AFX_HICOCOONCTRL_H__E11D0F86_3974_4625_BFB5_3527DCA2E2A1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#include "DaumGameAuth.h"
class CHiCocoonCtrl
{
private:
BOOL m_bOK;
private:
CDaumGameAuth m_DaumGameAuth;
public:
enum tagCoCoonAUth
{
maxbytes_CoCoonAuth=200,
};
public:
BOOL IsOK();
public:
BOOL SetAuth(char* auth);
BOOL GetTimeExpired();
CDaumGameAuth GetDaumGameAuth();
public:
CHiCocoonCtrl();
virtual ~CHiCocoonCtrl();
};
BOOL ProcessHiCocoonLogin(CDaumGameAuth* DaumGameAuth, char* IN_Hicocoonauth, char* OUT_ID);
#endif
| C++ |
#include "DaumGameCrypt.h"
#ifdef _WIN32
#include <comutil.h>
#pragma comment(lib, "comsupp.lib")
#endif
CDaumGameCrypt::CDaumGameCrypt( void ) : m_bInit( FALSE )
{
Init();
}
CDaumGameCrypt::~CDaumGameCrypt( void )
{
Destroy();
}
BOOL CDaumGameCrypt::Init( void )
{
if( m_bInit == TRUE )
return FALSE;
#ifdef _WIN32
CoInitialize( NULL );
m_pEncrypt.CreateInstance( DAUM::CLSID_Encrypt, NULL, CLSCTX_INPROC_SERVER );
m_pDecrypt.CreateInstance( DAUM::CLSID_Decrypt, NULL, CLSCTX_INPROC_SERVER );
#else
m_pCryptor = new ::daum_encrypt_type;
#endif
m_bInit = TRUE;
return TRUE;
}
void CDaumGameCrypt::Destroy( void )
{
if( m_bInit == FALSE )
return;
#ifdef _WIN32
m_pEncrypt = NULL;
m_pDecrypt = NULL;
CoUninitialize();
#else
if( m_pCryptor ) {
delete m_pCryptor;
m_pCryptor = NULL;
}
#endif
m_bInit = FALSE;
}
BOOL CDaumGameCrypt::SetKey( LPCTSTR szKey )
{
#ifdef _WIN32
try {
m_pEncrypt->Init( _bstr_t( szKey ) );
m_pDecrypt->Init( _bstr_t( szKey ) );
}
catch( _com_error e ) {
return FALSE;
}
#else
daum_encrypt_init( m_pCryptor, (LPTSTR) szKey );
#endif
return TRUE;
}
BOOL CDaumGameCrypt::Encrypt( IN LPCTSTR szText, OUT LPTSTR szEncryptText, int nMaxSize )
{
#ifdef _WIN32
try {
m_pEncrypt->PutInput( _bstr_t( szText ) );
_tcsncpy( szEncryptText, (LPCTSTR) _bstr_t( m_pEncrypt->GetOutput() ), nMaxSize );
}
catch( _com_error e ) {
return FALSE;
}
#else
if( daum_encrypt( m_pCryptor, (LPTSTR) szText, _tcslen( szText ), szEncryptText, &nMaxSize ) != 0 )
return FALSE;
#endif
return TRUE;
}
BOOL CDaumGameCrypt::Decrypt( IN LPCTSTR szEncryptedText, OUT LPTSTR szText, int nMaxSize )
{
#ifdef _WIN32
try {
m_pDecrypt->PutInput( _bstr_t( szEncryptedText ) );
_tcsncpy( szText, (LPCTSTR) _bstr_t( m_pDecrypt->GetOutput() ), nMaxSize );
}
catch( _com_error e ) {
return FALSE;
}
#else
if( daum_decrypt( m_pCryptor, (LPTSTR) szEncryptedText, _tcslen( szEncryptedText ), szText, &nMaxSize ) != 0 )
return FALSE;
#endif
return TRUE;
}
| C++ |
#include "DaumGameAuth.h"
#include <stdlib.h>
#include <time.h>
#define SAFE_DELETE(p) if( p ) { delete (p); (p) = NULL; }
CDaumGameAuth::CDaumGameAuth( void ) : m_pCryptor( NULL )
{
}
CDaumGameAuth::~CDaumGameAuth( void )
{
SAFE_DELETE( m_pCryptor );
}
BOOL CDaumGameAuth::Init( LPCTSTR szKey )
{
SAFE_DELETE( m_pCryptor );
m_pCryptor = new CDaumGameCrypt;
m_pCryptor->SetKey( szKey );
return TRUE;
}
BOOL CDaumGameAuth::SetSource( LPCTSTR szSourceString )
{
memset(m_szSourceString, 0x00, MAX_SOURCE_LENGTH);
if( m_pCryptor->Decrypt( szSourceString, m_szSourceString, MAX_SOURCE_LENGTH ) == FALSE )
return FALSE;
return TRUE;
}
BOOL CDaumGameAuth::GetData( IN LPCTSTR szKeyName, OUT LPTSTR szBuffer, int nMaxLength )
{
TCHAR szFullKeyName[ MAX_KEY_LENGTH ];
TCHAR *pData, *pDestData;
int nBufferSize;
*szBuffer = '\0';
_tcscpy( szFullKeyName, szKeyName );
_tcscat( szFullKeyName, "=" );
pData = _tcsstr( m_szSourceString, szFullKeyName );
if( pData == NULL )
return FALSE;
pData += _tcslen( szFullKeyName );
if( (pDestData = _tcschr( pData, '|' )) == NULL )
pDestData = pData + _tcslen( pData );
nBufferSize = (int) (INT_PTR) ((TCHAR *) pDestData - (TCHAR *) pData);
if( nMaxLength <= nBufferSize )
nBufferSize = nMaxLength - 1;
_tcsncpy( szBuffer, pData, nBufferSize );
*(szBuffer + nBufferSize) = '\0';
return TRUE;
}
BOOL CDaumGameAuth::IsTimeExpired( void )
{
TCHAR szTime[256];
if( GetData( _T("TS"), szTime, 256 ) == FALSE )
return TRUE;
if( _ttoi( szTime ) <= (time( NULL ) - EXPIRED_SECS) )
return TRUE;
return FALSE;
}
| C++ |
#if _MSC_VER >= 1000
#pragma once
#endif
#ifndef _CDAUMGAMECRYPT_H_
#define _CDAUMGAMECRYPT_H_
#include <tchar.h>
#ifdef _WIN32
#import "DaumCrypt.DLL" rename_namespace("DAUM"), named_guids
const IID IID_IEncrypt = {0x40E692F5,0xCC5D,0x4609,{0x94,0x8D,0x09,0x88,0x12,0x5F,0xF8,0xB4}};
const IID IID_IDecrypt = {0xBA5723E0,0x7F1C,0x4418,{0x94,0x91,0x21,0x19,0xEF,0x75,0xEB,0x83}};
const CLSID CLSID_Encrypt = {0x285659A3,0x6F2B,0x4036,{0x94,0xAC,0x53,0x4E,0x4D,0x23,0x88,0x86}};
const CLSID CLSID_Decrypt = {0x9AC5B738,0x6E08,0x4148,{0xB3,0x37,0x63,0xCE,0xC5,0x09,0x0C,0x49}};
MIDL_INTERFACE("40E692F5-CC5D-4609-948D-0988125FF8B4")
IEncrypt : public IDispatch
{
public:
virtual HRESULT STDMETHODCALLTYPE Init(BSTR key) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Input( BSTR *pVal) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Input( BSTR newVal) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Output( BSTR *pVal) = 0;
};
MIDL_INTERFACE("BA5723E0-7F1C-4418-9491-2119EF75EB83")
IDecrypt : public IDispatch
{
public:
virtual HRESULT STDMETHODCALLTYPE Init(BSTR key) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Input( BSTR *pVal) = 0;
virtual HRESULT STDMETHODCALLTYPE put_Input( BSTR newVal) = 0;
virtual HRESULT STDMETHODCALLTYPE get_Output( BSTR *pVal) = 0;
};
#else
#include <daumencrypt.h>
#endif
class CDaumGameCrypt
{
public:
CDaumGameCrypt( void );
~CDaumGameCrypt( void );
public:
BOOL Init( void );
void Destroy( void );
BOOL SetKey( LPCTSTR szKey );
BOOL Encrypt( IN LPCTSTR szText, OUT LPTSTR szEncryptText, int nMaxSize );
BOOL Decrypt( IN LPCTSTR szEncryptedText, OUT LPTSTR szText, int nMaxSize );
protected:
BOOL m_bInit;
#ifdef _WIN32
DAUM::IEncryptPtr m_pEncrypt;
DAUM::IDecryptPtr m_pDecrypt;
#else
daum_encrypt_type* m_pCryptor;
#endif
};
#endif
| C++ |
#if _MSC_VER >= 1000
#pragma once
#endif
#ifndef _CDAUMGAMEAUTH_H_
#define _CDAUMGAMEAUTH_H_
#include "DaumGameCrypt.h"
class CDaumGameAuth
{
public:
CDaumGameAuth( void );
~CDaumGameAuth( void );
BOOL Init( IN LPCTSTR szKey );
BOOL SetSource( IN LPCTSTR szSourceString );
BOOL GetData( IN LPCTSTR szKeyName, OUT LPTSTR szBuffer, IN int nMaxLength );
BOOL IsTimeExpired( void );
CDaumGameCrypt *GetGameCrypt(){return m_pCryptor;};
protected:
enum {
MAX_SOURCE_LENGTH = 1024,
MAX_KEY_LENGTH = 256
};
enum {
EXPIRED_SECS = 4 * 60 * 60
};
protected:
CDaumGameCrypt *m_pCryptor;
TCHAR m_szSourceString[MAX_SOURCE_LENGTH];
};
#endif
| C++ |
#include "../Global.h"
#include "HiCocoonCtrl.h"
CHiCocoonCtrl::CHiCocoonCtrl()
{
m_bOK = FALSE;
BOOL Result = FALSE;
Result = m_DaumGameAuth.Init (
_T("z6DuDLA1NcyXge3psD63Uu0o3GqpAzyBjm7pD0hNDYKefE37fNM1tVng34ejixgA") );
if ( Result == FALSE)
return;
m_bOK = TRUE;
}
CHiCocoonCtrl::~CHiCocoonCtrl()
{
}
BOOL CHiCocoonCtrl::IsOK()
{
return m_bOK;
}
BOOL CHiCocoonCtrl::SetAuth(char* auth)
{
if ( auth == NULL)
return FALSE;
BOOL Result = FALSE;
Result = m_DaumGameAuth.SetSource( auth );
return Result;
}
BOOL CHiCocoonCtrl::GetTimeExpired()
{
return m_DaumGameAuth.IsTimeExpired();
}
CDaumGameAuth CHiCocoonCtrl::GetDaumGameAuth()
{
return m_DaumGameAuth;
}
| C++ |
#include "Global.h"
HINSTANCE hInst;
TCHAR* g_strAppTitle = TEXT( "GTH Master Server Test Ver.06-04-13" );
TCHAR* g_strWindowClass = TEXT( "MS" );
TCHAR* g_systemStatusMessage = TEXT( "MS: Shut down State" );
HWND g_hWnd;
i3notice_t g_notice[MAXNOTICE];
i3masterServerConfig_t g_config;
int g_systemOn;
i3client_t g_clients[MAX_CLIENTS];
i3client_t *g_curClient;
int g_clientNumber;
int g_maxClientNumber;
CTimer *g_timer;
CDBAccount* g_DBAccountServer=NULL;
CTerraDBCtrl* g_TerraDBCtrl=NULL;
CDBGame* g_DBGameServer[MAX_SERVER_GROUP];
CLogSystem *g_logSystem;
unsigned int g_globalTime;
serverGroup_t g_serverGroup[MAX_SERVER_GROUP];
characterTable_t g_characterTable[NUM_TABLE_GEN_TYPE];
int g_numCharacterTable;
int g_filterYn;
int g_filterIdx;
char g_filterMessage[MAX_FILTER_MESSAGE][256];
masterServerInfo_t g_masterServerInfo[MAX_MASTER_SERVER];
serverGroupInfo_t g_serverGroupInfo[MAX_SERVER_GROUP];
char g_hostName[HOSTNAMESTRING];
int g_concurrentClients;
int g_maxConcurrentClients;
tcpSocket *g_pBillingSocket ;
void GTH_InitGlobalVariable()
{
int i;
g_systemOn = false;
g_filterYn = 1;
g_concurrentClients = 0;
g_maxConcurrentClients = 0;
g_filterIdx = 0;
if ( g_timer ) { delete g_timer; g_timer = NULL; }
g_timer = new CTimer;
if ( g_DBAccountServer ) { delete g_DBAccountServer; g_DBAccountServer = NULL; }
g_DBAccountServer = new CDBAccount;
for (i=0; i<MAX_SERVER_GROUP; i++)
{
if ( g_DBGameServer[i] ) { delete g_DBGameServer[i]; g_DBGameServer[i] = NULL; }
g_DBGameServer[i] = new CDBGame;
}
if ( g_logSystem ) { delete g_logSystem; g_logSystem = NULL; }
g_logSystem = new CLogSystem;
}
void GTH_DestroyGlobalVariable()
{
int i;
if ( g_timer ) { delete g_timer; g_timer = NULL; }
if(NULL != g_DBAccountServer ) { delete g_DBAccountServer; g_DBAccountServer = NULL; }
for (i=0; i<MAX_SERVER_GROUP; i++)
{
if(NULL != g_DBGameServer[i]){ delete g_DBGameServer[i]; g_DBGameServer[i] = NULL; }
}
if(NULL != g_logSystem ) { delete g_logSystem; g_logSystem = NULL; }
if (NULL != g_pBillingSocket )
{
delete g_pBillingSocket;
g_pBillingSocket = NULL;
}
}
| C++ |
#include "global.h"
#include "datastruct.h"
#include "CTools.h"
CTools::CTools()
{
m_bOK=FALSE;
m_bOK=TRUE;
}
CTools::~CTools()
{
}
BOOL CTools::isOK(void) const
{
return m_bOK;
}
i3client_t* CTools::GetClientRecord(const int Idx)
{
if(Idx < 0) return NULL;
if(Idx > MAX_CLIENTS) return NULL;
if(!g_clients[Idx].active) return NULL;
return &g_clients[Idx];
}
characterTable_t* CTools::GetCharactorGenTableRecord(const int GenIdx)
{
if(GenIdx < 0) return NULL;
if(GenIdx >= NUM_TABLE_GEN_TYPE) return NULL;
return &g_characterTable[GenIdx];
}
characterData_t* CTools::
GetCharactorWithCharacterID(const i3client_t* pClient,const int characterID)
{
if(characterID < 0) return NULL;
if(characterID >= MAX_CHARACTER_DATA) return NULL;
for(int idx=0; idx < MAX_CHARACTER_DATA; idx++){
if(g_curClient->data[idx].characterID == characterID)
return &g_curClient->data[idx];
}
return NULL;
}
BOOL CTools::IsItemUseFlag(item_t *pItem, ENUM_ITEM_USE_FLAG flag)
{
if ( pItem->ItemExtendInfo.UseFlag & flag)
return TRUE;
return FALSE;
} | C++ |
#if !defined(AFX_CHECKSUM_H__25AE8BA5_981D_4BF5_B9FA_CB7B5259ECE3__INCLUDED_)
#define AFX_CHECKSUM_H__25AE8BA5_981D_4BF5_B9FA_CB7B5259ECE3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#include <windows.h>
class checksum {
public:
checksum() { clear(); }
void clear() { sum = 0; r = 55665; c1 = 52845; c2 = 22719;}
void add(DWORD w);
void add(BOOL w) { add((DWORD)w); }
void add(UINT w) { add((DWORD)w); }
void add(WORD w);
void add(LPBYTE b, UINT length);
void add(BYTE b);
DWORD get() { return sum; }
protected:
WORD r;
WORD c1;
WORD c2;
DWORD sum;
};
#endif
| C++ |
#include "netlib.h"
#include "queue.h"
CSendingQueue::CSendingQueue()
{
m_first = 0;
m_last = -1;
m_count = 0;
m_size = SENDING_QUEUE_SIZE;
m_overflow = false;
m_maxCount = 0;
memset( m_queue , 0 , sizeof(i3packetqueue_t) * SENDING_QUEUE_SIZE );
}
CSendingQueue::~CSendingQueue()
{
}
int CSendingQueue::Push (int socket, byte *buf, int len, struct sockaddr_in *addr)
{
if (m_count >= m_size)
{
m_overflow = true;
return 0;
}
if (m_last < m_size - 1)
m_last ++;
else
m_last = 0;
m_queue[m_last].socket = socket;
m_queue[m_last].len = len;
memcpy( &m_queue[m_last].packet, buf, len );
memcpy( &m_queue[m_last].addr, addr, sizeof(sockaddr_in) );
m_count ++;
if (m_count > m_maxCount)
m_maxCount = m_count;
return 1;
}
int CSendingQueue::Pop (int *socket, byte *buf, int *len, struct sockaddr_in *addr)
{
if (m_count <= 0)
{
return 0;
}
*socket = m_queue[m_first].socket;
*len = m_queue[m_first].len;
memcpy( buf, &m_queue[m_first].packet, m_queue[m_first].len );
memcpy( addr, &m_queue[m_first].addr, sizeof(sockaddr_in) );
if (m_first < m_size - 1)
m_first ++;
else
m_first = 0;
m_count --;
return 1;
}
void CSendingQueue::Clear()
{
CSendingQueue();
}
CReceivingQueue::CReceivingQueue()
{
m_first = 0;
m_last = -1;
m_count = 0;
m_size = RECEIVING_QUEUE_SIZE;
m_overflow = false;
m_maxCount = 0;
memset( m_queue , 0 , sizeof(i3packetqueue_t) * RECEIVING_QUEUE_SIZE );
}
CReceivingQueue::~CReceivingQueue()
{
}
int CReceivingQueue::Push (int socket, byte *buf, int len, struct sockaddr_in *addr)
{
if (m_count >= m_size)
{
m_overflow = true;
return 0;
}
if (m_last < m_size - 1)
m_last ++;
else
m_last = 0;
m_queue[m_last].socket = socket;
m_queue[m_last].len = len;
memcpy( &m_queue[m_last].packet, buf, len );
memcpy( &m_queue[m_last].addr, addr, sizeof(sockaddr_in) );
m_count ++;
if (m_count > m_maxCount)
m_maxCount = m_count;
return 1;
}
int CReceivingQueue::Pop (int *socket, byte *buf, int *len, struct sockaddr_in *addr)
{
if (m_count <= 0)
{
return 0;
}
*socket = m_queue[m_first].socket;
*len = m_queue[m_first].len;
memcpy( buf, &m_queue[m_first].packet, m_queue[m_first].len );
memcpy( addr, &m_queue[m_first].addr, sizeof(sockaddr_in) );
if (m_first < m_size - 1)
m_first ++;
else
m_first = 0;
m_count --;
return 1;
}
void CReceivingQueue::Clear()
{
CReceivingQueue();
}
| C++ |
#include "netlib.h"
#include "queue.h"
#include <time.h>
extern i3sizebuf_t netMessage;
extern i3sizebuf_t recvMessage;
extern int msgReadCount;
extern int msgBadRead;
extern int readSizePerSecond;
extern CRITICAL_SECTION spCrit;
void MSG_BeginWriting(i3sizebuf_t *sb)
{
EnterCriticalSection( &spCrit );
}
void MSG_EndWriting(i3sizebuf_t *sb)
{
LeaveCriticalSection( &spCrit );
}
void MSG_Clear( i3sizebuf_t *sb )
{
SZ_Clear( sb );
}
void MSG_WriteChar (i3sizebuf_t *sb, int c)
{
byte *buf;
buf = SZ_GetSpace (sb, 1);
buf[0] = c;
}
void MSG_WriteByte (i3sizebuf_t *sb, int c)
{
byte *buf;
buf = SZ_GetSpace (sb, 1);
buf[0] = c;
}
void MSG_WriteShort (i3sizebuf_t *sb, int c)
{
byte *buf;
buf = SZ_GetSpace (sb, 2);
buf[0] = c&0xff;
buf[1] = c>>8;
}
void MSG_WriteLong (i3sizebuf_t *sb, int c)
{
byte *buf;
buf = SZ_GetSpace (sb, 4);
buf[0] = c&0xff;
buf[1] = (c>>8)&0xff;
buf[2] = (c>>16)&0xff;
buf[3] = c>>24;
}
void MSG_Write64Int(i3sizebuf_t *sb,const __int64 in_n64Value)
{
byte* pBuffer=NULL;
pBuffer = SZ_GetSpace (sb, 8);
pBuffer[0] = (in_n64Value>>0)&0xff;
pBuffer[1] = (in_n64Value>>8)&0xff;
pBuffer[2] = (in_n64Value>>16)&0xff;
pBuffer[3] = (in_n64Value>>24)&0xff;
pBuffer[4] = (in_n64Value>>32)&0xff;
pBuffer[5] = (in_n64Value>>40)&0xff;
pBuffer[6] = (in_n64Value>>48)&0xff;
pBuffer[7] = (in_n64Value>>56)&0xff;
}
void MSG_WriteString (i3sizebuf_t *sb, char *s)
{
if (!s)
SZ_Write (sb, "", 1);
else
SZ_Write (sb, s, strlen(s)+1);
}
void MSG_WriteFloat (i3sizebuf_t *sb, float f)
{
union
{
float f;
int l;
} dat;
dat.f = f;
SZ_Write (sb, &dat.l, 4);
}
void MSG_WriteAngle (i3sizebuf_t *sb, float f)
{
MSG_WriteByte (sb, ((int)f*256/360) & 255);
}
void MSG_WriteVector(i3sizebuf_t *sb, vec3_t v)
{
MSG_WriteFloat(sb, v[0]);
MSG_WriteFloat(sb, v[1]);
MSG_WriteFloat(sb, v[2]);
}
void MSG_ReadVector(vec3_t v)
{
readSizePerSecond += 16;
v[0] = MSG_ReadFloat();
v[1] = MSG_ReadFloat();
v[2] = MSG_ReadFloat();
}
void MSG_BeginReading (void)
{
msgReadCount = 0;
msgBadRead = false;
}
int MSG_ReadChar (void)
{
readSizePerSecond += 1;
int c;
if (msgReadCount+1 > recvMessage.cursize)
{
msgBadRead = true;
return -1;
}
c = (signed char)recvMessage.data[msgReadCount];
msgReadCount++;
return c;
}
int MSG_ReadByte (void)
{
readSizePerSecond += 1;
int c;
if (msgReadCount+1 > recvMessage.cursize)
{
msgBadRead = true;
return -1;
}
c = (unsigned char)recvMessage.data[msgReadCount];
msgReadCount++;
return c;
}
int MSG_ReadShort (void)
{
readSizePerSecond += 2;
int c;
if (msgReadCount+2 > recvMessage.cursize)
{
msgBadRead = true;
return -1;
}
c = (short)(recvMessage.data[msgReadCount]
+ (recvMessage.data[msgReadCount+1]<<8));
msgReadCount += 2;
return c;
}
int MSG_ReadLong (void)
{
readSizePerSecond += 4;
int c;
if (msgReadCount+4 > recvMessage.cursize)
{
msgBadRead = true;
return -1;
}
c = recvMessage.data[msgReadCount]
+ (recvMessage.data[msgReadCount+1]<<8)
+ (recvMessage.data[msgReadCount+2]<<16)
+ (recvMessage.data[msgReadCount+3]<<24);
msgReadCount += 4;
return c;
}
__int64 MSG_Read64Int (void)
{
readSizePerSecond += 8;
__int64 c;
if (msgReadCount+8 > recvMessage.cursize)
{
msgBadRead = true;
return -1;
}
c = recvMessage.data[msgReadCount]
+ ((__int64)(recvMessage.data[msgReadCount+1])<<8)
+ ((__int64)(recvMessage.data[msgReadCount+2])<<16)
+ ((__int64)(recvMessage.data[msgReadCount+3])<<24)
+ ((__int64)(recvMessage.data[msgReadCount+4])<<32)
+ ((__int64)(recvMessage.data[msgReadCount+5])<<40)
+ ((__int64)(recvMessage.data[msgReadCount+6])<<48)
+ ((__int64)(recvMessage.data[msgReadCount+7])<<56);
msgReadCount += 8;
return c;
}
char *MSG_ReadString (void)
{
static char string[2048];
int l,c;
l = 0;
do
{
c = MSG_ReadChar ();
if (c == -1 || c == 0)
break;
string[l] = c;
l++;
} while (l < sizeof(string)-1);
string[l] = 0;
readSizePerSecond += l;
return string;
}
float MSG_ReadFloat (void)
{
readSizePerSecond += 4;
union
{
byte b[4];
float f;
int l;
} dat;
dat.b[0] = recvMessage.data[msgReadCount];
dat.b[1] = recvMessage.data[msgReadCount+1];
dat.b[2] = recvMessage.data[msgReadCount+2];
dat.b[3] = recvMessage.data[msgReadCount+3];
msgReadCount += 4;
return dat.f;
}
float MSG_ReadAngle (void)
{
readSizePerSecond += 1;
return float( MSG_ReadByte() * (360.0/256) );
}
void SZ_Clear (i3sizebuf_t *buf)
{
buf->cursize = 0;
buf->overwriting = 0;
}
unsigned char *SZ_GetSpace (i3sizebuf_t *buf, int length)
{
unsigned char *data;
if (buf->cursize + length > buf->maxsize)
{
buf->overflowed = true;
SZ_Clear (buf);
}
data = buf->data + buf->cursize;
buf->cursize += length;
return data;
}
void SZ_Write (i3sizebuf_t *buf, void *data, int length)
{
memcpy (SZ_GetSpace(buf,length),data,length);
}
void SZ_Alloc (i3sizebuf_t *buf, int startsize)
{
buf->maxsize = startsize;
buf->cursize = 0;
buf->overwriting = 0;
}
void SZ_Free (i3sizebuf_t *buf)
{
buf->cursize = 0;
buf->overwriting = 0;
}
void SZ_Load (i3sizebuf_t *buf, void *data)
{
memcpy (data, buf->data, buf->cursize);
}
| C++ |
#ifndef _NETLIB_H_
#define _NETLIB_H_
#pragma warning( disable : 4786 )
#pragma warning( disable : 4251 )
#define NETLIB_VERSION "03.10.03"
#include <stdio.h>
#include <math.h>
#include <ctime>
#include <map>
#include <stack>
#include <winsock.h>
#define _COMPILE_FOR_SERVER
#ifdef _COMPILE_FOR_SERVER
#define _USE_SENDING_THREAD
#define _USE_RECEIVING_THREAD
#endif
#define NET_MAXMESSAGE 8192
#define MAX_DATAGRAM 1024
#define NET_HEADERSIZE (sizeof(unsigned int) + sizeof(unsigned int) + sizeof(unsigned int) +sizeof(unsigned short) )
#define NET_DATAGRAMSIZE (MAX_DATAGRAM + NET_HEADERSIZE)
#define NET_MAXWAITINGMESSAGE 8
#define NETFLAG_LENGTH_MASK 0x0fff
#define NETFLAG_SOM 1 << 0
#define NETFLAG_RELIABLE 1 << 1
#define NETFLAG_ACK 1 << 2
#define NETFLAG_EOM 1 << 3
#define NETFLAG_ENCRYPT 1 << 0
#define NETFLAG_ENCRYPT_CHECKSUM 0X7FFFFFFF
#define NET_RESENDTIME 800
#define NET_MAXIMUM_PACKETMAP_SIZE 100
#define NET_SENDTIME_UNRELIABLE 0
#define MAXHOSTNAMELEN 256
#define MAX_CHANNELS 20
typedef float vec3_t[3];
typedef struct
{
int allowoverflow;
int overflowed;
byte data[NET_MAXMESSAGE];
int maxsize;
int cursize;
int overwriting;
} i3sizebuf_t;
#pragma pack ( push , 1 )
typedef struct
{
unsigned int sequence;
unsigned int encrypt: 1;
unsigned int checksum : 31;
unsigned int lastSendTime;
unsigned short length;
byte data[MAX_DATAGRAM];
} i3packet_t;
#pragma pack ( pop )
typedef std::map<UINT, i3packet_t*> PacketMap;
typedef PacketMap::iterator PacketMapItor;
typedef PacketMap::value_type PacketMapPair;
enum
{
SocketType_Reliable,
SocketType_Unreliable
};
enum
{
PacketBlock_None,
PacketBlock_Wait,
};
typedef struct i3socket_s
{
i3socket_s()
{
sendPacketMap = NULL;
recvPacketMap = NULL;
socket = INVALID_SOCKET;
socketType = SocketType_Reliable;
}
int socket;
int socketType;
unsigned int connecttime;
unsigned int lastReceiveTime;
unsigned int lastSendTime;
unsigned int latencyTime;
int disconnected;
int canSend;
int sendNext;
unsigned int resendSequence;
unsigned int ackSequence;
unsigned int sendSequence;
unsigned int unreliableSendSequence;
int sendMessageLength;
byte sendMessage [NET_MAXMESSAGE];
unsigned int receiveSequence;
unsigned int unreliableReceiveSequence;
int receiveMessageLength;
byte receiveMessage [NET_MAXMESSAGE];
int packetBlockSequence;
struct sockaddr_in addr;
PacketMap *sendPacketMap;
PacketMap *recvPacketMap;
} i3socket_t;
enum
{
PacketAnalysis_None = 0,
PacketAnalysis_Skip,
PacketAnalysis_Ack,
PacketAnalysis_Start,
};
void SZ_Write (i3sizebuf_t *buf, void *data, int length);
void SZ_Clear (i3sizebuf_t *buf);
void SZ_Alloc (i3sizebuf_t *buf, int startsize);
unsigned char *SZ_GetSpace (i3sizebuf_t *buf, int length);
void SZ_Load (i3sizebuf_t *buf, void *data);
void MSG_BeginWriting(i3sizebuf_t *sb);
void MSG_EndWriting(i3sizebuf_t *sb);
void MSG_Clear( i3sizebuf_t *sb );
void MSG_WriteChar (i3sizebuf_t *sb, int c);
void MSG_WriteByte (i3sizebuf_t *sb, int c);
void MSG_WriteShort (i3sizebuf_t *sb, int c);
void MSG_WriteLong (i3sizebuf_t *sb, int c);
void MSG_Write64Int (i3sizebuf_t *sb, __int64 in_n64Value);
void MSG_WriteFloat (i3sizebuf_t *sb, float f);
void MSG_WriteString (i3sizebuf_t *sb, char *s);
void MSG_WriteAngle (i3sizebuf_t *sb, float f);
void MSG_WriteVector(i3sizebuf_t *sb, vec3_t v);
void MSG_BeginReading (void);
int MSG_ReadChar (void);
int MSG_ReadByte (void);
int MSG_ReadShort (void);
int MSG_ReadLong (void);
__int64 MSG_Read64Int (void);
float MSG_ReadFloat (void);
char *MSG_ReadString (void);
float MSG_ReadAngle (void);
void MSG_ReadVector(vec3_t v);
int NET_AddrCompare (struct sockaddr *addr1, struct sockaddr *addr2);
char *NET_AddrToString (struct sockaddr *addr);
int NET_StringToAddr (char *string, struct sockaddr *addr);
char *NET_GetLocalAddress();
char *NET_GetHostName();
char *NET_AddrToIPString (struct sockaddr *addr);
int NET_SendPacket (i3socket_t *sock, i3sizebuf_t *data, BOOL encrypt = FALSE);
int NET_SendPacket_Unreliable(i3socket_t *sock, i3sizebuf_t *data, BOOL encrypt = FALSE);
int NET_ReadPacket(int *socket, byte *buf, struct sockaddr_in *addr);
int NET_ControlPacket(i3socket_t *sock, i3packet_t *packet);
int NET_ControlRecvBank( i3socket_t *sock );
int NET_ControlSendBank( i3socket_t *sock );
int NET_CheckSockProblem( i3socket_t *sock, int checkTime = -1 );
int NET_PreviewMessage(i3packet_t *p);
int NET_Write (int socket, byte *buf, int len, struct sockaddr_in *addr);
int NET_Read (int socket, byte *buf, int len, struct sockaddr_in *addr);
int NET_ReadFromReceivingQueue (int *socket, byte *buf, struct sockaddr_in *addr);
int NET_WriteToSendingQueue (int socket, byte *buf, int len, struct sockaddr_in *addr);
void NET_InitNetTime();
unsigned int NET_GetNetTime();
int NET_OpenNetwork();
void NET_InitPacketMap( i3socket_t *sock );
int NET_InitSocket(i3socket_t *sock, struct sockaddr_in *addr, int socket, int socketType );
int NET_OpenSocketForServer(i3socket_t *sock, char *serverIP, int port, int socketType = SocketType_Reliable );
int NET_OpenSocketForClient(i3socket_t *sock, char *serverIP, int port, int socketType = SocketType_Reliable );
void NET_CloseSocket(i3socket_t *sock);
void NET_ClearSocket(i3socket_t *sock);
void NET_CloseNetwork();
int NET_CreateSendingThread();
int NET_CreateReceivingThread();
void NET_DestroySendingThread();
void NET_DestroyReceivingThread();
DWORD WINAPI NET_SendingThread(LPVOID param);
DWORD WINAPI NET_ReceivingThread(LPVOID param);
char *NET_ErrorString ();
int NET_AddListenChannel( int socket );
int NET_DeleteListenChannel( int socket );
#define NET_SendMessage NET_SendPacket
#define NET_SendUnreliableMessage NET_SendPacket_Unreliable
void ErrorLog( char *filename, char* str, ... );
extern void TRACE(LPCTSTR lpszFormat, ...);
void Crypt(TCHAR *inp, DWORD inplen, TCHAR* key = "", DWORD keylen = 0);
#endif | C++ |
#include "netlib.h"
#include "queue.h"
#include <time.h>
extern i3sizebuf_t netMessage;
extern i3sizebuf_t recvMessage;
extern i3packet_t packetBuffer;
extern int totalPacketsSend;
extern int totalPacketsReceived;
extern int packetsSent;
extern int packetsReceived;
extern int packetsReSent;
extern int packetsDropCount;
extern int packetsDupCount;
extern int packetsAckSent;
extern int packetsAckReceived;
extern int un_packetsSent;
extern int un_packetsReceived;
extern int un_packetsDropCount;
extern unsigned int g_netTime;
extern unsigned int prevTime;
extern unsigned int curTime;
extern unsigned int g_globalTime;
extern int channel[ MAX_CHANNELS ];
extern int channelNumber;
extern HANDLE hThread;
extern DWORD SendingThreadID, ReceivingThreadID;
extern int runSendingThread, runReceivingThread;
extern CSendingQueue *sendingQueue;
extern CReceivingQueue *receivingQueue;
extern HANDLE hSQMutex, hRQMutex;
extern FILE *packetErrorLog;
extern int lastRecvSequence;
extern int myRecvSequence;
extern CRITICAL_SECTION spCrit;
using namespace std;
#include <string>
#include <vector>
#include "../CheckSum.h"
FILE *g_logFile;
vector<string> g_logFilename;
int sendFirstWrite = true;
int recvFirstWrite = true;
int g_lastWriteSequence = -1;
void WriteCompletePacket( int idx, int type )
{
return;
int *firstwrite;
char filename[256];
char msg[128];
if( type == 0 )
{
strcpy( filename, "send.txt" );
firstwrite = &sendFirstWrite;
strcpy( msg, "-" );
}
else if( type == 1 )
{
strcpy( filename, "recv.txt" );
firstwrite = &recvFirstWrite;
strcpy( msg, "-" );
if( g_lastWriteSequence < 0 ) g_lastWriteSequence = idx;
else if( g_lastWriteSequence != idx )
{
int checkSequence = 1;
}
else g_lastWriteSequence = idx;
}
else if( type == 2 )
{
strcpy( filename, "recv.txt" );
firstwrite = &recvFirstWrite;
sprintf( msg, "dup : %d<%d", myRecvSequence, lastRecvSequence );
}
else if( type == 3 )
{
strcpy( filename, "recv.txt" );
firstwrite = &recvFirstWrite;
sprintf( msg, "drop : %d>%d", myRecvSequence, lastRecvSequence );
}
FILE *fp;
if( (*firstwrite) )
{
fp = fopen( filename, "wt" );
(*firstwrite) = false;
}
else
{
fp = fopen( filename, "at" );
}
fprintf( fp, "%s[%d]packet complete\n", msg, idx );
fclose( fp );
}
void NET_WriteErrorLog( char* str, struct sockaddr_in *addr )
{
return;
char cTime[32];
time_t logtime;
time( &logtime );
strcpy( cTime, ctime( &logtime ) );
cTime[24] = '\0';
#ifdef _COMPILE_FOR_SERVER
packetErrorLog = fopen( "net_error.txt", "at" );
#else
packetErrorLog = fopen( "../net_error.txt", "at" );
#endif
fprintf( packetErrorLog, "%s : %s(%s)\n", cTime, str, inet_ntoa( addr->sin_addr ) );
fclose( packetErrorLog );
}
int NET_AddrCompare (struct sockaddr *addr1, struct sockaddr *addr2)
{
if (addr1->sa_family != addr2->sa_family)
return -1;
if (((struct sockaddr_in *)addr1)->sin_addr.s_addr != ((struct sockaddr_in *)addr2)->sin_addr.s_addr)
return -1;
if (((struct sockaddr_in *)addr1)->sin_port != ((struct sockaddr_in *)addr2)->sin_port)
return 1;
return 0;
}
char *NET_AddrToString (struct sockaddr *addr)
{
static char buffer[22];
int haddr;
haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr);
sprintf(buffer, "%d.%d.%d.%d:%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff, ntohs(((struct sockaddr_in *)addr)->sin_port));
return buffer;
}
int NET_StringToAddr (char *string, struct sockaddr *addr)
{
int ha1, ha2, ha3, ha4, hp;
int ipaddr;
sscanf(string, "%d.%d.%d.%d:%d", &ha1, &ha2, &ha3, &ha4, &hp);
ipaddr = (ha1 << 24) | (ha2 << 16) | (ha3 << 8) | ha4;
addr->sa_family = AF_INET;
((struct sockaddr_in *)addr)->sin_addr.s_addr = htonl(ipaddr);
((struct sockaddr_in *)addr)->sin_port = htons((unsigned short)hp);
return 0;
}
char *NET_GetLocalAddress()
{
struct hostent *hostEntry;
int haddr;
static char buffer[16];
char hostName[MAXHOSTNAMELEN];
if ( gethostname(hostName, MAXHOSTNAMELEN) == SOCKET_ERROR ) return NULL;
hostEntry = gethostbyname( hostName );
if (hostEntry == NULL) return NULL;
haddr = ntohl( *(int *)hostEntry->h_addr );
sprintf(buffer, "%d.%d.%d.%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff);
return buffer;
}
char *NET_AddrToIPString (struct sockaddr *addr)
{
static char buffer[16];
int haddr;
haddr = ntohl(((struct sockaddr_in *)addr)->sin_addr.s_addr);
sprintf(buffer, "%d.%d.%d.%d", (haddr >> 24) & 0xff, (haddr >> 16) & 0xff, (haddr >> 8) & 0xff, haddr & 0xff);
return buffer;
}
char *NET_GetHostName()
{
static char hostNameString[MAXHOSTNAMELEN];
if ( gethostname(hostNameString, MAXHOSTNAMELEN) == SOCKET_ERROR ) return NULL;
return hostNameString;
}
void NET_ClearBank( PacketMap *pm )
{
for( PacketMapItor itor = pm->begin(); itor != pm->end(); ++itor )
{
if( ((*itor).second) == NULL ) continue;
delete ((*itor).second);
}
pm->clear();
}
int NET_InsertPacketBank( PacketMap *pm, i3packet_t *packet )
{
PacketMapItor itor = pm->find( packet->sequence );
i3packet_t *pk;
if( itor != pm->end() ) return false;
pk = new i3packet_t;
memcpy( pk, packet, sizeof( i3packet_t ) );
pm->insert( PacketMapPair( packet->sequence, pk ) );
return true;
}
int NET_DeletePacketBank( PacketMap *pm, UINT sequence )
{
PacketMapItor itor = pm->find( sequence );
if( itor == pm->end() ) return false;
delete (*itor).second;
pm->erase( itor );
return true;
}
int NET_SendPacket (i3socket_t *sock, i3sizebuf_t *data, BOOL bEncrypt)
{
unsigned int packetLen;
unsigned int dataLen;
byte som;
byte eom;
unsigned int encrypt = 0;
if (data->cursize == 0)
{
packetsDropCount++;
return 0;
}
if (data->cursize > NET_MAXMESSAGE)
{
packetsDropCount++;
return 0;
}
memcpy(sock->sendMessage, data->data, data->cursize);
sock->sendMessageLength = data->cursize;
som = 0xff;
while( 1 )
{
if (sock->sendMessageLength <= MAX_DATAGRAM)
{
dataLen = sock->sendMessageLength;
eom = NETFLAG_EOM;
som = 0;
}
else
{
dataLen = MAX_DATAGRAM;
eom = 0;
if( som == 0xff ) som = NETFLAG_SOM;
else som = 0;
}
packetLen = NET_HEADERSIZE + dataLen;
if( sock->socketType == SocketType_Reliable)
packetBuffer.length = ((NETFLAG_RELIABLE | eom) << 12) | packetLen;
else
packetBuffer.length = ((NETFLAG_RELIABLE | eom | som) << 12) | packetLen;
packetBuffer.sequence = sock->sendSequence++;
packetBuffer.lastSendTime = g_netTime;
packetBuffer.encrypt = bEncrypt;
memcpy( packetBuffer.data, sock->sendMessage, dataLen );
if (bEncrypt == TRUE)
{
Crypt((TCHAR*)packetBuffer.data, dataLen);
checksum packetsum;
packetsum.clear();
packetsum.add((BYTE*)packetBuffer.data, dataLen);
packetBuffer.checksum = packetsum.get();
}
if( sock->sendPacketMap != NULL )
{
if( sock->socketType == SocketType_Reliable ) NET_InsertPacketBank( sock->sendPacketMap, &packetBuffer );
}
#ifndef _USE_SENDING_THREAD
if (NET_Write(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1)
#else
if (NET_WriteToSendingQueue(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1)
#endif
return -1;
sock->lastSendTime = NET_GetNetTime();
totalPacketsSend ++;
packetsSent ++;
if( eom != 0 ) break;
sock->sendMessageLength -= MAX_DATAGRAM;
memcpy( sock->sendMessage, sock->sendMessage+MAX_DATAGRAM, sock->sendMessageLength );
}
return 1;
}
int NET_SendPacket_Unreliable(i3socket_t *sock, i3sizebuf_t *data, BOOL bEncrypt)
{
if( sock->socketType == SocketType_Unreliable )
{
return( NET_SendPacket( sock, data ) );
}
unsigned int packetLen;
unsigned int dataLen;
byte eom;
if (data->cursize == 0)
{
un_packetsDropCount++;
return 0;
}
if (data->cursize > MAX_DATAGRAM)
{
un_packetsDropCount++;
return 0;
}
memcpy(sock->sendMessage, data->data, data->cursize);
sock->sendMessageLength = data->cursize;
dataLen = sock->sendMessageLength;
eom = NETFLAG_EOM;
packetLen = NET_HEADERSIZE + dataLen;
packetBuffer.length = ((NETFLAG_RELIABLE | eom) << 12) | packetLen;
packetBuffer.sequence = sock->unreliableSendSequence ++;
packetBuffer.lastSendTime = NET_SENDTIME_UNRELIABLE;
unsigned int CheckSum = 0;
packetBuffer.encrypt = bEncrypt;
memcpy( packetBuffer.data, sock->sendMessage, dataLen );
if (bEncrypt == TRUE)
{
Crypt((TCHAR*)packetBuffer.data, dataLen);
checksum packetsum;
packetsum.clear();
packetsum.add((BYTE*)packetBuffer.data, dataLen);
packetBuffer.checksum = packetsum.get();
}
#ifndef _USE_SENDING_THREAD
if (NET_Write(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1)
#else
if (NET_WriteToSendingQueue(sock->socket, (byte *)&packetBuffer, packetLen, &sock->addr) == -1)
#endif
return -1;
sock->lastSendTime = NET_GetNetTime();
totalPacketsSend ++;
un_packetsSent ++;
return 1;
}
int NET_ControlSendBank( i3socket_t *sock )
{
int packetLen;
if( sock->sendPacketMap == NULL ) return 0;
if( sock->sendPacketMap->empty() ) return 0;
int sendSize = sock->sendPacketMap->size();
i3packet_t *packet;
for( PacketMapItor itor = sock->sendPacketMap->begin(); itor != sock->sendPacketMap->end(); ++itor )
{
if( g_netTime - ((*itor).second)->lastSendTime < NET_RESENDTIME ) continue;
packet = (*itor).second;
packet->lastSendTime = g_netTime;
packetLen = ( packet->length & NETFLAG_LENGTH_MASK );
packetsReSent ++;
totalPacketsSend ++;
#ifndef _USE_SENDING_THREAD
if (NET_Write(sock->socket, (byte *)packet, packetLen, &sock->addr) == -1)
#else
if (NET_WriteToSendingQueue(sock->socket, (byte *)packet, packetLen, &sock->addr) == -1)
#endif
return -1;
}
return 1;
}
int NET_ControlRecvBank( i3socket_t *sock )
{
if( sock->recvPacketMap == NULL ) return false;
if( sock->recvPacketMap->empty() ) return false;
i3packet_t packet;
unsigned int length;
unsigned int flags;
unsigned int sequence;
int recvSize = sock->recvPacketMap->size();
while( 1 )
{
for( PacketMapItor itor = sock->recvPacketMap->begin(); itor != sock->recvPacketMap->end(); ++itor )
{
if( ((*itor).second)->sequence != sock->receiveSequence ) continue;
break;
}
if( itor == sock->recvPacketMap->end() || sock->recvPacketMap->size() == 0 ) return false;
memcpy( &packet, (*itor).second, sizeof( i3packet_t ) );
NET_DeletePacketBank( sock->recvPacketMap, packet.sequence );
length = packet.length & NETFLAG_LENGTH_MASK;
flags = packet.length >> 12;
sequence = packet.sequence;
length -= NET_HEADERSIZE;
sock->receiveSequence++;
memcpy(sock->receiveMessage + sock->receiveMessageLength, packet.data, length);
sock->receiveMessageLength += length;
if (flags & NETFLAG_EOM)
{
SZ_Clear(&recvMessage);
SZ_Write(&recvMessage, sock->receiveMessage, sock->receiveMessageLength);
sock->receiveMessageLength = 0;
return true;
}
}
return false;
}
int NET_ControlPacket_ReliableSocket( i3socket_t *sock, i3packet_t *packet )
{
unsigned int length;
unsigned int flags;
unsigned int sequence;
i3packet_t ackPacket;
int ret = PacketAnalysis_Skip;
int count;
sock->lastReceiveTime = g_netTime;
length = packet->length & NETFLAG_LENGTH_MASK;
flags = packet->length >> 12;
sequence = packet->sequence;
memset( &ackPacket, 0, sizeof( i3packet_t ) );
totalPacketsReceived ++;
if( flags & NETFLAG_ACK )
{
packetsAckReceived ++;
if( sock->sendPacketMap != NULL ) NET_DeletePacketBank( sock->sendPacketMap, sequence );
sock->latencyTime = sock->lastReceiveTime - sock->lastSendTime;
return ret = PacketAnalysis_Ack;
}
UINT DataSize = length - NET_HEADERSIZE;
if ( packet->encrypt )
{
checksum packetsum;
packetsum.clear();
packetsum.add((BYTE*)packetBuffer.data, DataSize);
if ( packetBuffer.checksum != packetsum.get() )
{
packetsDupCount++;
ret = PacketAnalysis_Skip;
return ret;
}
Crypt((TCHAR*)packet->data, DataSize);
}
if (flags & NETFLAG_RELIABLE)
{
if( packet->lastSendTime != NET_SENDTIME_UNRELIABLE )
{
packetsReceived ++;
ackPacket.length = (NETFLAG_ACK << 12) | NET_HEADERSIZE;
ackPacket.sequence = sequence;
ackPacket.lastSendTime = g_netTime;
#ifndef _USE_SENDING_THREAD
NET_Write(sock->socket, (byte *)&ackPacket, NET_HEADERSIZE, &sock->addr);
#else
NET_WriteToSendingQueue(sock->socket, (byte *)&ackPacket, NET_HEADERSIZE, &sock->addr);
#endif
packetsAckSent ++;
lastRecvSequence = sequence;
myRecvSequence = sock->receiveSequence;
if( sequence == sock->receiveSequence )
{
if ( ( sock->receiveMessageLength + length ) >= NET_MAXMESSAGE )
{
ret = PacketAnalysis_Skip;
}
else
{
sock->receiveSequence++;
length -= NET_HEADERSIZE;
memcpy(sock->receiveMessage + sock->receiveMessageLength, packet->data, length);
sock->receiveMessageLength += length;
if (flags & NETFLAG_EOM)
{
SZ_Clear(&recvMessage);
SZ_Write(&recvMessage, sock->receiveMessage, sock->receiveMessageLength);
sock->receiveMessageLength = 0;
ret = PacketAnalysis_Start;
}
else
{
ret = PacketAnalysis_Skip;
}
}
}
else if( sequence < sock->receiveSequence )
{
packetsDupCount++;
ret = PacketAnalysis_Skip;
}
else if( sequence > sock->receiveSequence )
{
packetsDropCount ++;
if( sock->recvPacketMap != NULL ) NET_InsertPacketBank( sock->recvPacketMap, packet );
ret = PacketAnalysis_Skip;
}
}
else
{
un_packetsReceived ++;
length -= NET_HEADERSIZE;
if (sequence != sock->unreliableReceiveSequence)
{
count = sequence - sock->unreliableReceiveSequence;
un_packetsDropCount += count;
}
if ( sequence < sock->unreliableReceiveSequence )
{
packetsDupCount++;
ret = PacketAnalysis_Skip;
return ret;
}
sock->unreliableReceiveSequence = sequence + 1;
SZ_Clear (&recvMessage);
SZ_Write (&recvMessage, packet->data, length);
ret = PacketAnalysis_Start;
}
}
if( ret != PacketAnalysis_Start )
{
if( NET_ControlRecvBank( sock ) ) ret = PacketAnalysis_Start;
}
return ret;
}
int NET_ControlPacket_UnreliableSocket(i3socket_t *sock, i3packet_t *packet)
{
unsigned int length;
unsigned int flags;
unsigned int sequence;
i3packet_t ackPacket;
int ret = PacketAnalysis_None;
if( packet->length == 0 ) return PacketAnalysis_None;
sock->lastReceiveTime = g_netTime;
length = packet->length & NETFLAG_LENGTH_MASK;
flags = packet->length >> 12;
sequence = packet->sequence;
memset( &ackPacket, 0, sizeof( i3packet_t ) );
totalPacketsReceived ++;
if( flags & NETFLAG_ACK )
{
return ret = PacketAnalysis_Ack;
}
UINT DataSize = length - NET_HEADERSIZE;
if (packet->encrypt)
{
checksum packetsum;
packetsum.clear();
packetsum.add((BYTE*)packetBuffer.data, DataSize);
if ( packetBuffer.checksum != packetsum.get() )
{
packetsDupCount++;
ret = PacketAnalysis_Skip;
return ret;
}
Crypt((TCHAR*)packet->data, DataSize);
}
if (flags & NETFLAG_RELIABLE)
{
packetsReceived ++;
lastRecvSequence = sequence;
myRecvSequence = sock->receiveSequence;
sock->receiveSequence++;
length -= NET_HEADERSIZE;
if( sock->packetBlockSequence >= 0 )
{
if( sequence != sock->packetBlockSequence + 1 )
{
packetsDropCount++;
ret = PacketAnalysis_Skip;
if( flags & NETFLAG_EOM )
{
sock->receiveMessageLength = 0;
sock->packetBlockSequence = -1;
}
}
else
{
sock->packetBlockSequence ++;
memcpy(sock->receiveMessage + sock->receiveMessageLength, packet->data, length);
sock->receiveMessageLength += length;
if( flags & NETFLAG_EOM )
{
sock->packetBlockSequence = -1;
SZ_Clear(&recvMessage);
SZ_Write(&recvMessage, sock->receiveMessage, sock->receiveMessageLength);
sock->receiveMessageLength = 0;
ret = PacketAnalysis_Start;
}
else
{
ret = PacketAnalysis_Skip;
}
}
}
else if(flags & NETFLAG_SOM)
{
sock->packetBlockSequence = sequence;
memcpy(sock->receiveMessage + sock->receiveMessageLength, packet->data, length);
sock->receiveMessageLength += length;
ret = PacketAnalysis_Skip;
}
else if (flags & NETFLAG_EOM)
{
memcpy(sock->receiveMessage + sock->receiveMessageLength, packet->data, length);
sock->receiveMessageLength += length;
SZ_Clear(&recvMessage);
SZ_Write(&recvMessage, sock->receiveMessage, sock->receiveMessageLength);
sock->receiveMessageLength = 0;
ret = PacketAnalysis_Start;
}
else
{
ret = PacketAnalysis_Skip;
}
}
return ret;
}
int NET_ControlPacket(i3socket_t *sock, i3packet_t *packet)
{
if( sock->socketType == SocketType_Reliable )
return( NET_ControlPacket_ReliableSocket( sock, packet ) );
else
return( NET_ControlPacket_UnreliableSocket( sock, packet ) );
}
int NET_CheckSockProblem( i3socket_t *sock, int checkTime )
{
if( sock->sendPacketMap == NULL || sock->recvPacketMap == NULL ) return false;
if( sock->socketType == SocketType_Unreliable ) return true;
if( sock->sendPacketMap->size() > NET_MAXIMUM_PACKETMAP_SIZE || sock->recvPacketMap->size() > NET_MAXIMUM_PACKETMAP_SIZE )
{
return false;
}
if( checkTime < 0 ) return true;
if( g_netTime - sock->lastReceiveTime > checkTime )
{
return false;
}
return true;
}
int NET_Write (int socket, byte *buf, int len, struct sockaddr_in *addr)
{
int ret;
ret = sendto (socket, (char *)buf, len, 0, (struct sockaddr *)addr, sizeof(struct sockaddr_in));
if (ret == -1)
{
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
return 0;
}
return 0;
}
return ret;
}
int NET_Read (int socket, byte *buf, int len, struct sockaddr_in *addr)
{
int addrlen = sizeof (struct sockaddr_in);
int ret;
ret = recvfrom (socket, (char *)buf, len, 0, (struct sockaddr *)addr, &addrlen);
if (ret == -1){
int errno;
errno = WSAGetLastError();
if(errno == WSAEWOULDBLOCK || errno == WSAECONNREFUSED){
return 0;
}else{
return 0;
}
}
return ret;
}
void NET_InitNetTime()
{
prevTime = curTime = timeGetTime();
g_netTime = 0;
}
unsigned int NET_GetNetTime()
{
unsigned int tempTime;
curTime = timeGetTime();
if (curTime >= prevTime)
{
g_netTime = g_netTime + (curTime - prevTime);
}
else
{
tempTime = (unsigned int)pow(2, 32) - prevTime;
g_netTime = g_netTime + tempTime + curTime;
}
prevTime = curTime;
return g_netTime;
}
void NET_InitPacketMap( i3socket_t *sock )
{
if( sock->sendPacketMap != NULL )
{
NET_ClearBank( sock->sendPacketMap );
delete sock->sendPacketMap;
sock->sendPacketMap = NULL;
}
if( sock->recvPacketMap != NULL )
{
NET_ClearBank( sock->recvPacketMap );
delete sock->recvPacketMap;
sock->recvPacketMap = NULL;
}
}
int NET_InitSocket(i3socket_t *sock, struct sockaddr_in *addr, int socket, int socketType)
{
NET_InitPacketMap( sock );
sock->socket = socket;
sock->socketType = socketType;
sock->connecttime = g_netTime;
sock->lastReceiveTime = g_netTime;
sock->lastSendTime = g_netTime;
sock->latencyTime = 0;
sock->disconnected = false;
sock->canSend = true;
sock->sendNext = false;
sock->resendSequence = 0;
sock->ackSequence = 0;
sock->sendSequence = 0;
sock->unreliableSendSequence = 0;
sock->sendMessageLength = 0;
sock->receiveSequence = 0;
sock->unreliableReceiveSequence = 0;
sock->receiveMessageLength = 0;
sock->packetBlockSequence = -1;
memcpy(&sock->addr, addr, sizeof(sockaddr_in));
sock->sendPacketMap = new PacketMap;
sock->recvPacketMap = new PacketMap;
sock->sendPacketMap->clear();
sock->recvPacketMap->clear();
return 1;
}
int NET_OpenNetwork()
{
WORD wVersionRequested;
WSADATA wsaData;
int i;
wVersionRequested = MAKEWORD( 2, 2 );
if (WSAStartup( wVersionRequested, &wsaData ) != 0 )
{
return false;
}
NET_InitNetTime();
SZ_Alloc(&netMessage, NET_MAXMESSAGE);
SZ_Alloc(&recvMessage, NET_MAXMESSAGE);
channelNumber = 0;
for (i=0; i<MAX_CHANNELS; i++)
channel[i] = -1;
runSendingThread = 0;
runReceivingThread = 0;
totalPacketsSend = 0;
totalPacketsReceived = 0;
packetsSent = 0;
packetsReceived = 0;
packetsReSent = 0;
packetsDropCount = 0;
packetsDupCount = 0;
packetsAckSent = 0;
packetsAckReceived = 0;
un_packetsSent = 0;
un_packetsReceived = 0;
un_packetsDropCount = 0;
InitializeCriticalSection( &spCrit );
return true;
}
int NET_OpenSocketForServer(i3socket_t *sock, char *serverIP, int port, int socketType )
{
SOCKET hSocket;
struct sockaddr_in addr;
unsigned long _true = 1;
hSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (hSocket == INVALID_SOCKET)
{
return 0;
}
if (ioctlsocket (hSocket, FIONBIO, &_true) == -1)
{
return 0;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
if ( serverIP )
addr.sin_addr.s_addr = inet_addr(serverIP);
else
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons( port );
if ( bind(hSocket, (LPSOCKADDR) &addr, sizeof(addr)) != 0 )
{
return 0;
}
NET_InitSocket(sock, &addr, hSocket, socketType);
if ( NET_AddListenChannel( sock->socket ) == 0 )
{
return 0;
}
sock->socketType = socketType;
return 1;
}
int NET_OpenSocketForClient(i3socket_t *sock, char *serverIP, int port, int socketType )
{
SOCKET hSocket;
struct sockaddr_in addr;
unsigned long _true = 1;
hSocket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (hSocket == INVALID_SOCKET)
{
return 0;
}
if (ioctlsocket (hSocket, FIONBIO, &_true) == -1)
{
return 0;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(serverIP);
addr.sin_port = htons( port );
NET_InitSocket(sock, &addr, hSocket, socketType);
if ( NET_AddListenChannel( sock->socket ) == 0 )
{
return 0;
}
sock->socketType = socketType;
return 1;
}
void NET_CloseSocket(i3socket_t *sock)
{
NET_DeleteListenChannel ( sock->socket );
closesocket(sock->socket);
sock->socket = INVALID_SOCKET;
}
void NET_ClearSocket(i3socket_t *sock)
{
if (sock->socket != INVALID_SOCKET)
{
closesocket(sock->socket);
sock->socket = INVALID_SOCKET;
}
}
void NET_CloseNetwork()
{
WSACleanup();
DeleteCriticalSection( &spCrit );
}
int NET_CreateSendingThread()
{
hSQMutex = CreateMutex(NULL, FALSE, NULL);
hThread = CreateThread(NULL, 0, NET_SendingThread, NULL, 0, &SendingThreadID);
if ( !hThread )
{
return 0;
}
CloseHandle(hThread);
return 1;
}
int NET_CreateReceivingThread()
{
hRQMutex = CreateMutex(NULL, FALSE, NULL);
hThread = CreateThread(NULL, 0, NET_ReceivingThread, NULL, 0, &ReceivingThreadID);
if ( !hThread )
{
return 0;
}
CloseHandle(hThread);
return 1;
}
DWORD WINAPI NET_SendingThread(LPVOID param)
{
int socket, len;
struct sockaddr_in addr;
i3packet_t buf;
if ( sendingQueue ) { delete sendingQueue; sendingQueue = NULL; }
sendingQueue = new CSendingQueue;
runSendingThread = 1;
while ( runSendingThread )
{
Sleep(1); //lucky CPU
WaitForSingleObject(hSQMutex, INFINITE);
if (sendingQueue->m_count > 0)
{
sendingQueue->Pop(&socket, (byte *)&buf, &len, &addr);
NET_Write(socket, (byte *)&buf, len, &addr);
}
ReleaseMutex(hSQMutex);
}
CloseHandle(hSQMutex);
if ( sendingQueue ) { delete sendingQueue; sendingQueue = NULL; }
return 0;
}
DWORD WINAPI NET_ReceivingThread(LPVOID param)
{
int socket, len;
int addrlen = sizeof (struct sockaddr_in);
struct sockaddr_in addr;
i3packet_t buf;
int i;
if ( receivingQueue ) { delete receivingQueue; receivingQueue = NULL; }
receivingQueue = new CReceivingQueue;
runReceivingThread = 1;
while ( runReceivingThread )
{
Sleep(1); //lucky CPU
for (i=0; i<channelNumber; i++)
{
socket = channel[i];
len = NET_Read(socket, (byte *)&buf, NET_DATAGRAMSIZE, &addr);
if (len > 0)
{
WaitForSingleObject(hRQMutex, INFINITE);
receivingQueue->Push(socket, (byte *)&buf, len, &addr);
ReleaseMutex(hRQMutex);
}
}
}
CloseHandle(hRQMutex);
if ( receivingQueue ) { delete receivingQueue; receivingQueue = NULL; }
return 0;
}
int NET_ReadFromReceivingQueue (int *socket, byte *buf, struct sockaddr_in *addr)
{
int len;
if ( !runReceivingThread ) return 0;
WaitForSingleObject(hRQMutex, INFINITE);
if (receivingQueue->m_count > 0)
{
receivingQueue->Pop(socket, buf, &len, addr);
}
else
len = 0;
ReleaseMutex(hRQMutex);
return len;
}
int NET_WriteToSendingQueue (int socket, byte *buf, int len, struct sockaddr_in *addr)
{
int ret;
if ( !runSendingThread ) return -1;
WaitForSingleObject(hSQMutex, INFINITE);
ret = sendingQueue->Push(socket, buf, len, addr);
ReleaseMutex(hSQMutex);
return ret;
}
void NET_DestroySendingThread()
{
runSendingThread = 0;
}
void NET_DestroyReceivingThread()
{
runReceivingThread = 0;
}
char *NET_ErrorString ()
{
int code;
code = WSAGetLastError ();
switch (code)
{
case WSAEINTR: return "WSAEINTR";
case WSAEBADF: return "WSAEBADF";
case WSAEACCES: return "WSAEACCES";
case WSAEDISCON: return "WSAEDISCON";
case WSAEFAULT: return "WSAEFAULT";
case WSAEINVAL: return "WSAEINVAL";
case WSAEMFILE: return "WSAEMFILE";
case WSAEWOULDBLOCK: return "WSAEWOULDBLOCK";
case WSAEINPROGRESS: return "WSAEINPROGRESS";
case WSAEALREADY: return "WSAEALREADY";
case WSAENOTSOCK: return "WSAENOTSOCK";
case WSAEDESTADDRREQ: return "WSAEDESTADDRREQ";
case WSAEMSGSIZE: return "WSAEMSGSIZE";
case WSAEPROTOTYPE: return "WSAEPROTOTYPE";
case WSAENOPROTOOPT: return "WSAENOPROTOOPT";
case WSAEPROTONOSUPPORT: return "WSAEPROTONOSUPPORT";
case WSAESOCKTNOSUPPORT: return "WSAESOCKTNOSUPPORT";
case WSAEOPNOTSUPP: return "WSAEOPNOTSUPP";
case WSAEPFNOSUPPORT: return "WSAEPFNOSUPPORT";
case WSAEAFNOSUPPORT: return "WSAEAFNOSUPPORT";
case WSAEADDRINUSE: return "WSAEADDRINUSE";
case WSAEADDRNOTAVAIL: return "WSAEADDRNOTAVAIL";
case WSAENETDOWN: return "WSAENETDOWN";
case WSAENETUNREACH: return "WSAENETUNREACH";
case WSAENETRESET: return "WSAENETRESET";
case WSAECONNABORTED: return "WSWSAECONNABORTEDAEINTR";
case WSAECONNRESET: return "WSAECONNRESET";
case WSAENOBUFS: return "WSAENOBUFS";
case WSAEISCONN: return "WSAEISCONN";
case WSAENOTCONN: return "WSAENOTCONN";
case WSAESHUTDOWN: return "WSAESHUTDOWN";
case WSAETOOMANYREFS: return "WSAETOOMANYREFS";
case WSAETIMEDOUT: return "WSAETIMEDOUT";
case WSAECONNREFUSED: return "WSAECONNREFUSED";
case WSAELOOP: return "WSAELOOP";
case WSAENAMETOOLONG: return "WSAENAMETOOLONG";
case WSAEHOSTDOWN: return "WSAEHOSTDOWN";
case WSASYSNOTREADY: return "WSASYSNOTREADY";
case WSAVERNOTSUPPORTED: return "WSAVERNOTSUPPORTED";
case WSANOTINITIALISED: return "WSANOTINITIALISED";
case WSAHOST_NOT_FOUND: return "WSAHOST_NOT_FOUND";
case WSATRY_AGAIN: return "WSATRY_AGAIN";
case WSANO_RECOVERY: return "WSANO_RECOVERY";
case WSANO_DATA: return "WSANO_DATA";
default: return "NO ERROR";
}
}
int NET_AddListenChannel( int socket )
{
if ( channelNumber < MAX_CHANNELS )
{
channel[channelNumber] = socket;
channelNumber ++;
}
else
{
return 0;
}
return 1;
}
int NET_DeleteListenChannel( int socket )
{
int i;
for (i=0; i<channelNumber; i++)
{
if ( channel[i] == socket )
{
if (i == channelNumber - 1)
channel[i] = -1;
else
channel[i] = channel[channelNumber];
channelNumber --;
return 1;
}
}
return 0;
}
int NET_ReadPacket(int *socket, byte *buf, struct sockaddr_in *addr)
{
int length;
#ifndef _USE_RECEIVING_THREAD
length = NET_Read(*socket, buf, NET_DATAGRAMSIZE, addr);
#else
length = NET_ReadFromReceivingQueue (socket, buf, addr);
#endif
return length;
}
int NET_PreviewMessage(i3packet_t *p)
{
int length;
length = p->length & NETFLAG_LENGTH_MASK;
length -= NET_HEADERSIZE;
if (length < 1) return false;
SZ_Clear (&recvMessage);
SZ_Write (&recvMessage, p->data, length);
return true;
}
void NET_SetMessageOption_EnableOverwriting(i3sizebuf_t *data, int identity)
{
data->overwriting = identity;
}
#include <tchar.h>
void Crypt(TCHAR *inp, DWORD inplen, TCHAR* key, DWORD keylen)
{
TCHAR Sbox[129], Sbox2[129];
unsigned long i, j, t, x;
static const TCHAR OurUnSecuredKey[] = "gth99comAAA" ;
static const int OurKeyLen = _tcslen(OurUnSecuredKey);
TCHAR temp , k;
i = j = k = t = x = 0;
temp = 0;
ZeroMemory(Sbox, sizeof(Sbox));
ZeroMemory(Sbox2, sizeof(Sbox2));
for(i = 0; i < 128U; i++)
{
Sbox[i] = (TCHAR)i;
}
j = 0;
if(keylen)
{
for(i = 0; i < 128U ; i++)
{
if(j == keylen)
{
j = 0;
}
Sbox2[i] = key[j++];
}
}
else
{
for(i = 0; i < 128U ; i++)
{
if(j == OurKeyLen)
{
j = 0;
}
Sbox2[i] = OurUnSecuredKey[j++];
}
}
j = 0 ;
for(i = 0; i < 128; i++)
{
j = (j + (unsigned long) Sbox[i] + (unsigned long) Sbox2[i]) % 128U ;
temp = Sbox[i];
Sbox[i] = Sbox[j];
Sbox[j] = temp;
}
i = j = 0;
for(x = 0; x < inplen; x++)
{
i = (i + 1U) % 128U;
j = (j + (unsigned long) Sbox[i]) % 128U;
temp = Sbox[i];
Sbox[i] = Sbox[j] ;
Sbox[j] = temp;
t = ((unsigned long) Sbox[i] + (unsigned long) Sbox[j]) % 128U ;
k = Sbox[t];
inp[x] = (inp[x] ^ k);
}
} | C++ |
#define SENDING_QUEUE_SIZE 3000
#define RECEIVING_QUEUE_SIZE 3000
typedef struct
{
int socket;
int len;
i3packet_t packet;
sockaddr_in addr;
} i3packetqueue_t;
class CSendingQueue
{
private:
int m_first;
int m_last;
int m_size;
int m_overflow;
i3packetqueue_t m_queue[SENDING_QUEUE_SIZE];
public:
int m_count;
int m_maxCount;
CSendingQueue();
~CSendingQueue();
int Push (int socket, byte *buf, int len, struct sockaddr_in *addr);
int Pop (int *socket, byte *buf, int *len, struct sockaddr_in *addr);
void Clear ();
};
class CReceivingQueue
{
private:
int m_first;
int m_last;
int m_size;
int m_overflow;
i3packetqueue_t m_queue[RECEIVING_QUEUE_SIZE];
public:
int m_count;
int m_maxCount;
CReceivingQueue();
~CReceivingQueue();
int Push (int socket, byte *buf, int len, struct sockaddr_in *addr);
int Pop (int *socket, byte *buf, int *len, struct sockaddr_in *addr);
void Clear ();
};
| C++ |
#include "netlib.h"
#include "queue.h"
#include <time.h>
i3sizebuf_t netMessage;
i3sizebuf_t recvMessage;
i3packet_t packetBuffer;
int msgReadCount;
int msgBadRead;
int totalPacketsSend;
int totalPacketsReceived;
int packetsSent;
int packetsReceived;
int packetsReSent;
int packetsDropCount;
int packetsDupCount;
int packetsAckSent;
int packetsAckReceived;
int un_packetsSent;
int un_packetsReceived;
int un_packetsDropCount;
unsigned int g_netTime;
unsigned int prevTime, curTime;
int channel[ MAX_CHANNELS ];
int channelNumber;
HANDLE hThread;
DWORD SendingThreadID, ReceivingThreadID;
int runSendingThread, runReceivingThread;
CSendingQueue *sendingQueue;
CReceivingQueue *receivingQueue;
HANDLE hSQMutex, hRQMutex;
FILE *packetErrorLog;
int readSizePerSecond;
int lastRecvSequence;
int myRecvSequence;
CRITICAL_SECTION spCrit;
| C++ |
#if !defined(AFX_CLOGFILECTRL_H__509985E6_F7C3_4BA8_9399_5E5D4617A358__INCLUDED_)
#define AFX_CLOGFILECTRL_H__509985E6_F7C3_4BA8_9399_5E5D4617A358__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#include <WINDOWS.H>
#include <STDIO.H>
#include <sqltypes.h>
class CLogFileCtrl
{
protected:
typedef struct
{
SQLSMALLINT year;
SQLUSMALLINT month;
SQLUSMALLINT day;
SQLUSMALLINT hour;
SQLUSMALLINT minute;
SQLUSMALLINT second;
SQLUINTEGER fraction;
} timeStamp_t;
protected:
FILE* m_fp;
BOOL m_bActive;
CRITICAL_SECTION m_critcalsection;
enum
{
MAX_MESSAGE_BUFFER = 4096,
MAX_USERINFO_BUFFER = 4096,
MAX_LOG_BUFFER = MAX_MESSAGE_BUFFER + MAX_USERINFO_BUFFER,
};
public:
BOOL Open(const char* in_strfileName);
BOOL Close(void);
public:
void SetActive(const BOOL in_bActive);
BOOL IsActive(void);
void GetTimeStamp(timeStamp_t* out_pTimeStamp);
public:
void WriteLog(const char* in_strMessage, const char* in_strUserInfo = NULL);
public:
CLogFileCtrl();
~CLogFileCtrl();
};
#endif
| C++ |
#ifndef _LOG_H_
#define _LOG_H_
class CLogSystem
{
private:
time_t m_logTime;
FILE* m_fpLog;
FILE* m_fpDebug;
char m_logFileName[PATHSTRING];
char m_debugFileName[PATHSTRING];
unsigned int m_updateTime;
int m_updateCycle;
int m_generationHour;
BOOL m_bCreateLog;
BOOL m_bCreateDebug;
public:
CLogSystem();
~CLogSystem();
void Initialize(const BOOL in_bCreateLog,const BOOL in_bCreateDebug);
BOOL Open(void);
BOOL Close(void);
int Update();
void Write( const char *format, ... );
void WriteToLog( const char *format, ... );
};
enum
{
LOG_CLASS_LEVELUP = 0,
LOG_CLASS_GENLEVELUP,
LOG_CLASS_ITEM,
LOG_CLASS_PCDIE,
LOG_CLASS_CONNECT,
LOG_CLASS_DISCONNECT,
LOG_CLASS_PCCREATE,
LOG_CLASS_PCDELETE,
};
typedef struct
{
SQLSMALLINT year;
SQLUSMALLINT month;
SQLUSMALLINT day;
SQLUSMALLINT hour;
SQLUSMALLINT minute;
SQLUSMALLINT second;
SQLUINTEGER fraction;
} timeStamp_t;
void GetTimeStamp(timeStamp_t *timeStamp);
#endif
| C++ |
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include "global.h"
CLogSystem::CLogSystem()
{
m_updateTime = 0;
m_generationHour = -1;
m_fpLog = NULL;
m_fpDebug = NULL;
m_bCreateLog = FALSE;
m_bCreateDebug = FALSE;
}
CLogSystem::~CLogSystem()
{
if(NULL != m_fpLog){ fclose(m_fpLog); m_fpLog=NULL; }
if(NULL != m_fpDebug){ fclose(m_fpDebug); m_fpDebug=NULL; }
}
void CLogSystem::Initialize(const BOOL in_bCreateLog,const BOOL in_bCreateDebug)
{
m_updateTime = g_globalTime;
m_updateCycle = 1000;
m_bCreateLog = in_bCreateLog;
m_bCreateDebug = in_bCreateDebug;
}
BOOL CLogSystem::Open(void)
{
struct tm* date_tm=NULL;
time( &m_logTime );
date_tm = localtime( &m_logTime );
if (m_generationHour != date_tm->tm_hour)
{
m_generationHour = date_tm->tm_hour;
date_tm->tm_year += 1900;
date_tm->tm_mon += 1;
if(TRUE == m_bCreateLog ){
sprintf(m_logFileName, "logs/MS%02d_%04d%02d%02d_%02d.log",
g_config.serverNo, date_tm->tm_year, date_tm->tm_mon, date_tm->tm_mday, date_tm->tm_hour);
}
if(TRUE == m_bCreateDebug ){
sprintf(m_debugFileName, "debugs/MS%02d_%04d%02d%02d_%02d.dbg",
g_config.serverNo, date_tm->tm_year, date_tm->tm_mon, date_tm->tm_mday, date_tm->tm_hour);
}
}
if(TRUE == m_bCreateLog ){
m_fpLog = fopen( m_logFileName , "a+" );
if(NULL == m_fpLog) return FALSE;
}
if(TRUE == m_bCreateDebug ){
m_fpDebug = fopen( m_debugFileName , "a+" );
if(NULL == m_fpDebug) return FALSE;
}
return true;
}
BOOL CLogSystem::Close(void)
{
if(NULL != m_fpLog){ fclose(m_fpLog); m_fpLog=NULL; }
if(NULL != m_fpDebug){ fclose(m_fpDebug); m_fpDebug=NULL; }
return TRUE;
}
int CLogSystem::Update()
{
if (m_updateTime > g_globalTime) return false;
m_updateTime = g_globalTime + m_updateCycle;
if(FALSE == Close()) return FALSE;
if(FALSE == Open()) return false;
return true;
}
void CLogSystem::Write( const char *format, ... )
{
if ( !m_bCreateDebug ) return;
va_list argptr;
const int maxbytes=4095;
char buffer[maxbytes+1];
char cTime[26];
va_start(argptr, format);
_vsnprintf(buffer, maxbytes, format, argptr);
buffer[maxbytes]=NULL;
va_end(argptr);
time( &m_logTime );
strcpy(cTime, ctime(&m_logTime));
cTime[24] ='\0';
fprintf(m_fpDebug, "[%s] %s\n", cTime, buffer);
}
void CLogSystem::WriteToLog( const char *format, ... )
{
if ( !m_bCreateLog ) return;
va_list argptr;
const int maxbytes=4095;
char buffer[maxbytes+1];
char cTimeStamp[30];
timeStamp_t timeStamp;
va_start(argptr, format);
_vsnprintf(buffer, maxbytes, format, argptr);
buffer[maxbytes]=NULL;
va_end(argptr);
GetTimeStamp( &timeStamp );
sprintf(cTimeStamp, "%4d-%02d-%02d %02d:%02d:%02d",
timeStamp.year, timeStamp.month, timeStamp.day, timeStamp.hour, timeStamp.minute, timeStamp.second);
fprintf(m_fpLog, "%s;%s\n", cTimeStamp, buffer);
}
void GetTimeStamp(timeStamp_t *timeStamp)
{
time_t curTime;
struct tm *date_tm;
time( &curTime );
date_tm = localtime( &curTime );
timeStamp->year = date_tm->tm_year += 1900;
timeStamp->month = date_tm->tm_mon += 1;
timeStamp->day = date_tm->tm_mday;
timeStamp->hour = date_tm->tm_hour;
timeStamp->minute = date_tm->tm_min;
timeStamp->second = date_tm->tm_sec;
timeStamp->fraction = 0;
}
| C++ |
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include "..\global.h"
#include "CLogSystem.h"
CLogSystem::CLogSystem()
{
m_updateTime = 0;
m_generationHour = -1;
}
CLogSystem::~CLogSystem()
{
}
void CLogSystem::Initialize(const BOOL in_bCreateLog,const BOOL in_bCreateDebug)
{
m_updateTime = g_globalTime;
m_updateCycle = 1000;
m_UserLogFileCtrl.SetActive(in_bCreateLog);
m_DebugLogFileCtrl.SetActive(in_bCreateDebug);
}
void CLogSystem::Open(void)
{
struct tm* date_tm=NULL;
time_t logTime;
time( &logTime );
date_tm = localtime( &logTime );
if(m_generationHour != date_tm->tm_hour){
m_generationHour = date_tm->tm_hour;
date_tm->tm_year += 1900;
date_tm->tm_mon += 1;
sprintf(m_logFileName, "logs/MS%02d_%04d%02d%02d_%02d.log",
g_config.serverNo,
date_tm->tm_year,
date_tm->tm_mon,
date_tm->tm_mday,
date_tm->tm_hour);
sprintf(m_debugFileName, "debugs/MS%02d_%04d%02d%02d_%02d.dbg",
g_config.serverNo,
date_tm->tm_year,
date_tm->tm_mon,
date_tm->tm_mday,
date_tm->tm_hour);
}
m_UserLogFileCtrl.Open(m_logFileName);
m_DebugLogFileCtrl.Open(m_debugFileName);
}
void CLogSystem::Close(void)
{
m_UserLogFileCtrl.Close();
m_DebugLogFileCtrl.Close();
}
void CLogSystem::Update(void)
{
if (m_updateTime > g_globalTime) return;
m_updateTime = g_globalTime + m_updateCycle;
Close();
Open();
}
void CLogSystem::Write( const char *format, ... )
{
if(FALSE == m_DebugLogFileCtrl.IsActive()) return;
va_list argptr;
const int maxbytes=4095;
char buffer[maxbytes+1];
va_start(argptr, format);
_vsnprintf(buffer, maxbytes, format, argptr);
buffer[maxbytes]=NULL;
va_end(argptr);
m_DebugLogFileCtrl.WriteLog(buffer);
}
void CLogSystem::WriteToLog( const char *format, ... )
{
if(FALSE == m_UserLogFileCtrl.IsActive()) return;
va_list argptr;
const int maxbytes=4095;
char buffer[maxbytes+1];
va_start(argptr, format);
_vsnprintf(buffer, maxbytes, format, argptr);
buffer[maxbytes]=NULL;
va_end(argptr);
m_UserLogFileCtrl.WriteLog(buffer);
}
| C++ |
#if !defined(AFX_CLOGSYSTEM_H__D9072BAC_8B47_4A18_9D72_5DE66B9FE3A1__INCLUDED_)
#define AFX_CLOGSYSTEM_H__D9072BAC_8B47_4A18_9D72_5DE66B9FE3A1__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#include "CLogFileCtrl.h"
class CLogSystem
{
private:
char m_logFileName[_MAX_PATH];
char m_debugFileName[_MAX_PATH];
unsigned int m_updateTime;
int m_updateCycle;
int m_generationHour;
CLogFileCtrl m_UserLogFileCtrl;
CLogFileCtrl m_DebugLogFileCtrl;
public:
void Initialize(const BOOL in_bCreateLog,const BOOL in_bCreateDebug);
void Open(void);
void Close(void);
void Update(void);
void Write( const char *format, ... );
void WriteToLog( const char *format, ... );
public:
CLogSystem();
~CLogSystem();
};
enum
{
LOG_CLASS_LEVELUP = 0,
LOG_CLASS_GENLEVELUP,
LOG_CLASS_ITEM,
LOG_CLASS_PCDIE,
LOG_CLASS_CONNECT,
LOG_CLASS_DISCONNECT,
LOG_CLASS_PCCREATE,
LOG_CLASS_PCDELETE,
};
typedef struct
{
SQLSMALLINT year;
SQLUSMALLINT month;
SQLUSMALLINT day;
SQLUSMALLINT hour;
SQLUSMALLINT minute;
SQLUSMALLINT second;
SQLUINTEGER fraction;
} timeStamp_t;
#endif
| C++ |
#include "CLogFileCtrl.h"
#include <TIME.H>
CLogFileCtrl::CLogFileCtrl()
{
m_fp = NULL;
m_bActive = FALSE;
InitializeCriticalSection(&m_critcalsection);
}
CLogFileCtrl::~CLogFileCtrl()
{
DeleteCriticalSection(&m_critcalsection);
if( NULL != m_fp)
{
fclose(m_fp);
m_fp = NULL;
}
}
void CLogFileCtrl::SetActive(const BOOL in_bActive)
{
m_bActive = in_bActive;
}
BOOL CLogFileCtrl::IsActive(void)
{
return m_bActive;
}
BOOL CLogFileCtrl::Open(const char* in_strfileName)
{
EnterCriticalSection(&m_critcalsection);
if ( FALSE == m_bActive)
{
LeaveCriticalSection(&m_critcalsection);
return FALSE;
}
if(NULL != m_fp)
{
fclose(m_fp);
m_fp=NULL;
}
m_fp = fopen( in_strfileName, "a+" );
if(NULL == m_fp )
{
LeaveCriticalSection(&m_critcalsection);
return FALSE;
}
LeaveCriticalSection(&m_critcalsection);
return TRUE;
}
BOOL CLogFileCtrl::Close(void)
{
EnterCriticalSection(&m_critcalsection);
if(NULL != m_fp)
{
fclose(m_fp);
m_fp=NULL;
}
LeaveCriticalSection(&m_critcalsection);
return TRUE;
}
void CLogFileCtrl::WriteLog(const char* in_strMessage, const char* in_strUserInfo)
{
EnterCriticalSection(&m_critcalsection);
if(FALSE == m_bActive)
{
LeaveCriticalSection(&m_critcalsection);
return;
}
if(NULL == m_fp)
{
LeaveCriticalSection(&m_critcalsection);
return;
}
char strTimeStamp[30]="";
timeStamp_t timeStamp;
GetTimeStamp( &timeStamp );
sprintf(strTimeStamp, "%4d-%02d-%02d %02d:%02d:%02d",
timeStamp.year, timeStamp.month, timeStamp.day, timeStamp.hour, timeStamp.minute, timeStamp.second);
strTimeStamp[29] = NULL;
char MessageBUffer[MAX_MESSAGE_BUFFER];
char LogBuffer[MAX_LOG_BUFFER];
char UserBuffer[MAX_USERINFO_BUFFER];
memset(MessageBUffer, 0x00, MAX_MESSAGE_BUFFER);
memset(LogBuffer, 0x00, MAX_LOG_BUFFER);
memset(UserBuffer, 0x00, MAX_USERINFO_BUFFER);
if ( NULL != in_strMessage)
{
_snprintf(MessageBUffer, MAX_MESSAGE_BUFFER, in_strMessage);
MessageBUffer[MAX_MESSAGE_BUFFER-1] = NULL;
}
if ( NULL != in_strUserInfo)
{
_snprintf(UserBuffer, MAX_MESSAGE_BUFFER, in_strUserInfo);
UserBuffer[MAX_USERINFO_BUFFER-1] = NULL;
}
int size = strlen(UserBuffer);
if ( NULL == in_strUserInfo)
fprintf(m_fp, "%s;%s\n", strTimeStamp, in_strMessage);
else
fprintf(m_fp, "%s;%s%s\n", strTimeStamp, in_strUserInfo, in_strMessage);
LogBuffer[MAX_LOG_BUFFER-1] = NULL;
if ( m_fp != NULL)
fprintf(m_fp, LogBuffer);
LeaveCriticalSection(&m_critcalsection);
return;
}
void CLogFileCtrl::GetTimeStamp(timeStamp_t* out_pTimeStamp)
{
time_t curTime;
struct tm* date_tm=NULL;
time( &curTime );
date_tm = localtime( &curTime );
out_pTimeStamp->year = date_tm->tm_year += 1900;
out_pTimeStamp->month = date_tm->tm_mon += 1;
out_pTimeStamp->day = date_tm->tm_mday;
out_pTimeStamp->hour = date_tm->tm_hour;
out_pTimeStamp->minute = date_tm->tm_min;
out_pTimeStamp->second = date_tm->tm_sec;
out_pTimeStamp->fraction = 0;
}
| C++ |
#define COLUMNSIZE 200
#define QUERYSIZE 4096
#define OUTCONNECTIONSIZE 1024
#define MAXNOTICE 5
#define MAX_QUERY_PER_FRAME 50
typedef struct
{
char date[11];
char content[256];
} i3notice_t;
class CDBServer
{
protected:
RETCODE m_rCode;
HENV m_hEnv;
HDBC m_hDbc;
HSTMT m_hStmt;
char m_query[QUERYSIZE+1];
public:
CDBServer();
~CDBServer();
int Initialize(char *DSN, int DSNType);
int Initialize(char *DSN, int DSNType, char *UID, char *PWD);
void PrintError ( SQLSMALLINT handleType = SQL_HANDLE_STMT ) ;
HSTMT GetStmt () { return m_hStmt ; }
void Close();
char *ReturnString();
};
class CDBAccount : public CDBServer
{
public:
CDBAccount();
~CDBAccount();
public:
void MalCheckAccount(i3client_t* pClient);
void CheckAccount_Monitor(i3client_t* pClient,const char* szpID,const char* szpPassword);
public:
void SaveServerStatus(
const int iServerGroupIdx,
const char* szpServerGroupName,
const int iAcceptPlayerCnt);
void SaveCharactorPostion(const i3client_t* pClient,const int CharacterID);
int CheckAccount(i3client_t *client, char *id, char *password);
void CheckAccountHicocoon(i3client_t *client, char *id);
int CheckUserID(i3client_t *client);
int InsertLogin(i3client_t *client);
int DeleteLogin(i3client_t *client);
int DeleteLoginHost( char *hostName );
int InsertServerGroupUsers(int serverGroupID, int currentUsers, int maxUsers);
};
class CDBGame : public CDBServer
{
public:
CDBGame();
~CDBGame();
void LoadPremiumInfo(i3client_t* pClient);
int CheckCharacterName(i3client_t *client, int serverGroupID, char *charName);
int LoadAllGame(i3client_t *client);
int LoadAllItem(i3client_t *client);
int LoadAllQuest(i3client_t *client);
int LoadAllQuestStatus(i3client_t *client);
int LoadAllSkill(i3client_t *client);
int DeleteCharacter(i3client_t *client, int characterID);
int CreateCharacter(i3client_t *client);
int UpdateGameOwnItemInfo(i3client_t *client, characterData_t *data);
int DeleteItem (i3client_t *client, int characterID, int idx) ;
int LoadCharacterSlot(void);
int SaveCharacterSlot(i3client_t* pClient,int type);
};
class CTerraDBCtrl : public CDBServer
{
public:
void SelectTmember(i3client_t* pClient,const char* pTID);
public:
CTerraDBCtrl();
~CTerraDBCtrl();
};
enum
{
QUERY_CHECK_ACCOUNT,
QUERY_CHECK_USERID,
QUERY_INSERT_LOGIN,
QUERY_DELETE_LOGIN,
QUERY_DELETE_LOGIN_HOST,
QUERY_CHECK_CHARACTER_NAME,
QUERY_LOAD_ALL_GAME,
QUERY_LOAD_ALL_SKILL,
QUERY_LOAD_ALL_ITEM,
QUERY_LOAD_ALL_QUEST,
QUERY_LOAD_ALL_QUESTSTATUS,
QUERY_CREATE_CHARACTER,
QUERY_DELETE_CHARACTER,
QUERY_UPDATE_GAMEOWNITEMINFO,
QUERY_INSERT_SERVER_GROUP_USERS,
QUERY_DELETE_ITEM,
QUERY_LOAD_CHARACTER_SLOT,
QUERY_SAVE_CHARACTER_SLOT,
QUERY_LOAD_PREMIUMINFO,
QUERY_SAVE_CHARACTOR_POSTION,
QUERY_SAVESERVERSTATUS,
QUERY_TERRA_CHECK,
QUERY_CHECK_ACCOUNT_HICOCOON,
};
enum
{
LOGIN_CHAR_FREE_NEW=0,
LOGIN_CHAR_FREE_LEFT,
LOGIN_CHAR_FREE_CENTER,
LOGIN_CHAR_FREE_RIGHT,
LOGIN_CHAR_PU_NEW=10,
LOGIN_CHAR_PU,
};
#define MAX_QUERY_NUMBER 1000
typedef struct
{
public:
struct tagCheckAccountVar{
struct i3client_t::tagIdentification Identity;
int dbCheckAccount;
};
struct tagPremiumVar{
public:
struct tagWorldChatting{
long lDate;
int iDecreaseCount;
};
public:
enum i3client_t::tagPremiumInfo::enumMeberShipType iMemberShipType;
int iRemainSecond;
struct tagWorldChatting WorldChatting;
};
struct tagSaveCharactorPosition{
int CharacterID;
};
struct tagLoadCharaterSlot{
int iCharacterSlotType;
struct tm tmDate;
};
struct tagQUERY_TERRA_CHECK{
char TLoginName[i3client_t::tagTerra::MaxBytesTLoginName+1];
};
public:
int ownerIdx;
char ownerID[IDSTRING+1];
int queryType;
char query[QUERYSIZE+1];
HSTMT hStmt;
RETCODE retCode;
void *retStructVariable;
union{
struct tagCheckAccountVar CheckAccountVar;
struct tagPremiumVar PremiumVar;
struct tagSaveCharactorPosition SaveCharactorPosition;
struct tagLoadCharaterSlot LoadCharaterSlot;
struct tagQUERY_TERRA_CHECK TerraCheck;
};
} querySet_t;
class CQueryQueue
{
private:
int m_first;
int m_last;
int m_size;
int m_overflow;
querySet_t m_queue[MAX_QUERY_NUMBER];
public:
int m_count;
int m_maxCount;
CQueryQueue();
~CQueryQueue();
int Push (querySet_t *qSet);
int Pop (querySet_t *qSet);
void Clear ();
};
int DB_CreateQueryExecuterThread();
void DB_DestroyQueryExecuterThread();
DWORD WINAPI DB_QueryExecuterThread(LPVOID param);
void DB_ProcessQueryResultQueue();
void DB_ResultQuery_CheckAccount(const querySet_t& request,querySet_t& result);
void DB_ResultQuery_CheckUserID(querySet_t *request, querySet_t *result );
void DB_ResultQuery_LoadAllGame(querySet_t *request, querySet_t *result);
void DB_ResultQuery_LoadAllItem(querySet_t *request, querySet_t *result);
void DB_ResultQuery_CheckCharacterName(querySet_t *request, querySet_t *result);
void DB_ResultQuery_LoadAllSkill(querySet_t *request, querySet_t *result);
void DB_ResultQuery_LoadAllQuest(querySet_t *request, querySet_t *result);
void DB_ResultQuery_LoadAllQuestStatus(querySet_t *request, querySet_t *result);
void DB_ResultQuery_LoadCharaterSlot(querySet_t& request,querySet_t& result);
void DB_Waiting_ProcessRemainderQuery();
bool DB_ReconnectAccount ( querySet_t & request ) ;
bool DB_ReconnectGame ( querySet_t & request ) ;
bool DB_Reconnect ( querySet_t & request ) ;
bool CheckDisconnect ( HSTMT hStmt ) ;
| C++ |
#pragma once
#include "CriticalSection.h"
#include "Billing.h"
#include "Thread.h"
class CRecvBuffer
{
public:
CRecvBuffer (int packetCount = 256) ;
~CRecvBuffer () ;
void Clear () ;
bool Input (unsigned char * data, int size) ;
bool Get (PACKET_GAME * packetGame) ;
size_t GetDataSize () { return m_dataSize ; }
private:
const int m_bufferSize ;
unsigned char * m_pBuffer ;
int m_dataSize ;
int m_write ;
int m_read ;
bool m_init ;
CCriticalSection m_cs ;
void RemoveBuffer () ;
};
class CInternetAddress : public SOCKADDR_IN
{
public:
explicit CInternetAddress (unsigned long address, unsigned short port) ;
} ;
class tcpSocket : public CThread
{
public:
tcpSocket () ;
virtual ~tcpSocket () ;
bool Create () ;
bool Connect (unsigned long addr, unsigned short port) ;
bool Send ( PACKET_GAME * pPacket ) ;
void Close () ;
virtual int Run () ;
CRecvBuffer m_recv ;
private:
bool m_run ;
SOCKET m_sock ;
unsigned long m_addr ;
unsigned short m_port ;
} ;
| C++ |
#include "Thread.h"
#include <process.h>
CThread::CThread ()
: m_hThread (INVALID_HANDLE_VALUE)
{
}
CThread::~CThread ()
{
if (m_hThread != INVALID_HANDLE_VALUE)
{
::CloseHandle (m_hThread) ;
}
}
HANDLE CThread::GetHandle () const
{
return m_hThread ;
}
bool CThread::Start ()
{
if (m_hThread == INVALID_HANDLE_VALUE)
{
unsigned int threadID = 0 ;
m_hThread = (HANDLE)::_beginthreadex (0, 0, ThreadFunction, (void*)this, 0, &threadID) ;
if (m_hThread == INVALID_HANDLE_VALUE)
{
return false ;
}
}
else
{
return false ;
}
return true ;
}
bool CThread::Wait () const
{
if (!Wait (INFINITE))
{
return false ;
}
return true ;
}
bool CThread::Wait (DWORD timeoutMillis) const
{
bool ok ;
DWORD result = ::WaitForSingleObject (m_hThread, timeoutMillis) ;
if (WAIT_TIMEOUT == result)
{
ok = false ;
}
else if (WAIT_OBJECT_0 == result)
{
ok = true ;
}
else
{
ok = false ;
}
return ok ;
}
unsigned int __stdcall CThread::ThreadFunction (void* pV)
{
int result = 0 ;
CThread* pThis = (CThread*)pV ;
if (pThis)
{
result = pThis->Run () ;
}
return result ;
}
| C++ |
#include "..\\global.h"
#define CANT_FIND_CLIENT -1
void ProcessBillingQueue ()
{
PACKET_GAME packetGame ;
while ( g_pBillingSocket->m_recv.Get ( &packetGame ) )
{
switch ( ntohl (packetGame.PacketType) )
{
case SeverAlive:
Billing_ProcessServerAlive (&packetGame) ;
break ;
case BillingAuth:
Billing_ProcessAuth (&packetGame) ;
break ;
default:
Billing_WrongPacket (&packetGame) ;
break ;
}
}
}
void Billing_ProcessServerAlive (PPACKET_GAME pPacket)
{
}
void Billing_SendAuth(LPSTR UserID)
{
PACKET_GAME packetGame = { 0, } ;
packetGame.PacketType = htonl (BillingAuth) ;
strncpy (packetGame.UserID, UserID,
sizeof (packetGame.UserID)) ;
packetGame.GameNo = htonl (1) ;
g_pBillingSocket->Send (&packetGame) ;
}
void Billing_ProcessAuth (PPACKET_GAME pPacket)
{
int idx = Billing_FindClientbyUserID (pPacket->UserID) ;
if (CANT_FIND_CLIENT == idx) return ;
i3client_t *client = &g_clients[idx] ;
if (g_config.bCheckBilling)
{
if (0 != ntohl (pPacket->PacketResult))
{
switch ( ntohl (pPacket->PacketResult) )
{
case 3 :
GTH_ReplyLoginV2(client, FALSE,tagMCPaket_MSC_REPLYLOGIN::enumError::billing_network_error);
break;
case 10 :
case 11 :
case 33 :
GTH_ReplyLoginV2 (client, FALSE,tagMCPaket_MSC_REPLYLOGIN::enumError::billing_point_not_enough);
break;
default :
GTH_ReplyLoginV2 (client, FALSE,tagMCPaket_MSC_REPLYLOGIN::enumError::billing_error);
break;
}
return;
}
}
memcpy( &client->billMethod, &pPacket->BillMethod, 2);
memcpy( &client->billRemain, &pPacket->BillRemain, sizeof(int) );
memcpy( &client->billExpire, &pPacket->BillExpire, 12);
g_DBAccountServer->InsertLogin( client );
g_logSystem->Write("ID:%s is connected(%d).(%s)",
client->id,
client->dbCheckAccount,
NET_AddrToString((sockaddr*)&client->sock.addr));
}
void Billing_WrongPacket (PPACKET_GAME pPacket)
{
g_logSystem->Write ("Wrong Billing Packet: "
"Type: %d, "
"Result: %d, "
"GameServer: %s, "
"User_ID: %s, "
"User_IP: %s, "
"Game_No: %d, "
"BillMethod: %c%c, "
"BillExpire: %c%c%c%c%c%c%c%c%c%c%c%c, "
"BillRemain: %d",
ntohl (pPacket->PacketType),
ntohl (pPacket->PacketResult),
pPacket->GameServer,
pPacket->UserID,
pPacket->UserIP,
ntohl (pPacket->GameNo),
pPacket->BillMethod[0], pPacket->BillMethod[1],
pPacket->BillExpire[0],
pPacket->BillExpire[1],
pPacket->BillExpire[2],
pPacket->BillExpire[3],
pPacket->BillExpire[4],
pPacket->BillExpire[5],
pPacket->BillExpire[6],
pPacket->BillExpire[7],
pPacket->BillExpire[8],
pPacket->BillExpire[9],
pPacket->BillExpire[10],
pPacket->BillExpire[11],
ntohl (pPacket->BillRemain) ) ;
}
int Billing_FindClientbyUserID ( char *userID )
{
i3client_t *client = &g_clients[0] ;
for (int idx = 0 ; idx < MAX_CLIENTS ; ++idx, ++client)
{
if (!client->active) continue ;
if (!stricmp (userID, client->id))
return idx ;
}
return CANT_FIND_CLIENT ;
}
bool InitBilling ()
{
if (!g_config.bCheckBilling)
{
char tempString[MAX_PATH];
sprintf(tempString,"CHECK!! Billing System Do not Active By Server.cfg File!!\n");
OutputDebugString(tempString);
g_logSystem->Write ("CHECK!! Billing System Do not Active By Server.cfg File!!");
return TRUE;
}
if ( NULL != g_pBillingSocket )
{
delete g_pBillingSocket ;
g_pBillingSocket = NULL ;
}
g_pBillingSocket = new tcpSocket ;
if (!g_pBillingSocket->Create ())
{
char tbuf[128] ;
sprintf (tbuf, "ret: %d", WSAGetLastError ()) ;
MessageBox (NULL, tbuf, "Error", MB_OK) ;
}
if (!g_pBillingSocket->Connect (inet_addr (g_config.billingServerIP),
g_config.billingServerPort))
{
MessageBox(NULL,"Can't Connect Billing Server!!","Error",MB_OK);
return FALSE;
}
g_logSystem->Write ("Billing System Initialize Complete!!");
g_pBillingSocket->Start () ;
return true;
}
| C++ |
#pragma once
#include <windows.h>
class CThread
{
public:
CThread () ;
virtual ~CThread () ;
HANDLE GetHandle () const ;
bool Wait () const ;
bool Wait (DWORD timeoutMillis) const ;
bool Start () ;
private:
virtual int Run () = 0 ;
static unsigned int __stdcall ThreadFunction (void* pV) ;
HANDLE m_hThread ;
CThread (const CThread& rhs) ;
CThread &operator= (const CThread& rhs) ;
} ;
| C++ |
#include "..\\global.h"
extern CLogSystem *g_logSystem;
tcpSocket::tcpSocket ()
: m_sock (INVALID_SOCKET),
m_run (true)
{
}
tcpSocket::~tcpSocket ()
{
Close () ;
}
void tcpSocket::Close ()
{
m_run = false ;
if ( INVALID_SOCKET != m_sock )
{
closesocket ( m_sock ) ;
m_sock = INVALID_SOCKET ;
}
}
bool tcpSocket::Create ()
{
m_sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP) ;
if ( INVALID_SOCKET == m_sock )
{
return false ;
}
return true ;
}
bool tcpSocket::Connect (unsigned long addr, unsigned short port)
{
if ( INVALID_SOCKET == m_sock )
{
return false ;
}
CInternetAddress servAddr (addr, port) ;
int result = connect ( m_sock, (sockaddr*)&servAddr, sizeof (servAddr ) ) ;
if ( SOCKET_ERROR == result )
{
return false ;
}
m_addr = addr ;
m_port = port ;
return true ;
}
int tcpSocket::Run ()
{
int ret ;
PACKET_GAME packetGame ;
while (m_run)
{
ret = recv ( m_sock, (char*)&packetGame, sizeof (packetGame), 0 ) ;
if ( SOCKET_ERROR == ret )
{
g_logSystem->Write ( "tcpSocket::Run (), Socket error: %d",
WSAGetLastError () ) ;
break ;
}
if (!m_recv.Input ((unsigned char*)&packetGame, ret))
{
g_logSystem->Write ( "tcpSocket::Run(), "
"tcpSocket recv buffer overflow" ) ;
}
}
return 0 ;
}
bool tcpSocket::Send (PACKET_GAME * pPacket)
{
if ( !m_run ) return false ;
int ret = send ( m_sock, (char*) pPacket, sizeof (PACKET_GAME), 0 ) ;
if ( SOCKET_ERROR == ret )
{
g_logSystem->Write ( "tcpSocket::Send (), "
"socket error: %d\nRetry connection...", WSAGetLastError () );
Close () ;
Wait (200) ;
m_recv.Clear();
Create () ;
if ( !Connect (m_addr, m_port) )
{
g_logSystem->Write ( "tcpSocket::Send (), "
"Fail to connect server: %d", WSAGetLastError () ) ;
return false ;
}
Start () ;
ret = send ( m_sock, (char*) pPacket, sizeof (PACKET_GAME), 0 ) ;
if ( SOCKET_ERROR == ret )
{
g_logSystem->Write ( "tcpSocket::Send (), "
"Socket error: %d", WSAGetLastError () );
return false ;
}
}
return true ;
}
CInternetAddress::CInternetAddress (unsigned long address, unsigned short port)
{
sin_family = AF_INET ;
sin_port = htons (port) ;
sin_addr.s_addr = address ;
}
CRecvBuffer::CRecvBuffer (int packetCount)
: m_bufferSize (packetCount * sizeof (PACKET_GAME)),
m_init (true)
{
m_pBuffer = new unsigned char [m_bufferSize] ;
if ( NULL == m_pBuffer )
{
m_init = false ;
RemoveBuffer () ;
}
Clear () ;
}
CRecvBuffer::~CRecvBuffer ()
{
RemoveBuffer () ;
}
void CRecvBuffer::RemoveBuffer ()
{
if ( NULL != m_pBuffer )
{
delete [] m_pBuffer ;
m_pBuffer = NULL ;
}
}
void CRecvBuffer::Clear ()
{
m_dataSize = 0 ;
m_write = 0 ;
m_read = 0 ;
}
bool CRecvBuffer::Input (unsigned char *pData, int size)
{
if ( size + m_dataSize > m_bufferSize || !m_init)
{
return false ;
}
CCriticalSection::Owner lock (m_cs) ;
if ( m_write + size >= m_bufferSize )
{
int part1 = m_bufferSize - m_write ;
int part2 = size - part1 ;
memcpy (&m_pBuffer[m_write], pData, part1) ;
memcpy (m_pBuffer, &pData[part1], part2) ;
m_write = part2 ;
}
else
{
memcpy (&m_pBuffer[m_write], pData, size) ;
m_write += size ;
}
m_dataSize += size ;
return true ;
}
bool CRecvBuffer::Get (PACKET_GAME *packetGame)
{
if ( sizeof (PACKET_GAME) > m_dataSize )
{
return false ;
}
CCriticalSection::Owner lock (m_cs) ;
if ( m_bufferSize - m_read > sizeof (PACKET_GAME) )
{
memcpy ( packetGame, &m_pBuffer[m_read], sizeof (PACKET_GAME) ) ;
m_read += sizeof (PACKET_GAME) ;
}
else
{
int part1 = m_bufferSize - m_read ;
int part2 = sizeof (PACKET_GAME) - part1 ;
memcpy ( packetGame, &m_pBuffer[m_read], part1 ) ;
memcpy ( &packetGame[part1], m_pBuffer, part2 ) ;
}
m_dataSize -= sizeof (PACKET_GAME) ;
return true ;
}
| C++ |
#pragma once
#include <windows.h>
class CCriticalSection
{
public:
class Owner
{
public:
explicit Owner (CCriticalSection& crit) ;
~Owner () ;
private:
CCriticalSection& m_crit ;
Owner (const Owner& rhs) ;
Owner &operator= (const Owner& rhs) ;
} ;
CCriticalSection () ;
~CCriticalSection () ;
void Enter () ;
void Leave () ;
private:
CRITICAL_SECTION m_cs ;
} ;
| C++ |
#include "CriticalSection.h"
CCriticalSection::CCriticalSection ()
{
::InitializeCriticalSection (&m_cs) ;
}
CCriticalSection::~CCriticalSection ()
{
::DeleteCriticalSection (&m_cs) ;
}
void CCriticalSection::Enter ()
{
::EnterCriticalSection (&m_cs) ;
}
void CCriticalSection::Leave ()
{
::LeaveCriticalSection (&m_cs) ;
}
CCriticalSection::Owner::Owner (CCriticalSection& cs)
: m_crit (cs)
{
m_crit.Enter () ;
}
CCriticalSection::Owner::~Owner ()
{
m_crit.Leave () ;
}
| C++ |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
namespace latinime {
struct LatinCapitalSmallPair {
unsigned short capital;
unsigned short small;
};
// Generated from http://unicode.org/Public/UNIDATA/UnicodeData.txt
//
// 1. Run the following code. Bascially taken from
// Dictionary::toLowerCase(unsigned short c) in dictionary.cpp.
// Then, get the list of chars where cc != ccc.
//
// unsigned short c, cc, ccc, ccc2;
// for (c = 0; c < 0xFFFF ; c++) {
// if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
// cc = BASE_CHARS[c];
// } else {
// cc = c;
// }
//
// // tolower
// int isBase = 0;
// if (cc >='A' && cc <= 'Z') {
// ccc = (cc | 0x20);
// ccc2 = ccc;
// isBase = 1;
// } else if (cc > 0x7F) {
// ccc = u_tolower(cc);
// ccc2 = latin_tolower(cc);
// } else {
// ccc = cc;
// ccc2 = ccc;
// }
// if (!isBase && cc != ccc) {
// wprintf(L" 0x%04X => 0x%04X => 0x%04X %lc => %lc => %lc \n",
// c, cc, ccc, c, cc, ccc);
// //assert(ccc == ccc2);
// }
// }
//
// Initially, started with an empty latin_tolower() as below.
//
// unsigned short latin_tolower(unsigned short c) {
// return c;
// }
//
//
// 2. Process the list obtained by 1 by the following perl script and apply
// 'sort -u' as well. Get the SORTED_CHAR_MAP[].
// Note that '$1' in the perl script is 'cc' in the above C code.
//
// while(<>) {
// / 0x\w* => 0x(\w*) =/;
// open(HDL, "grep -iw ^" . $1 . " UnicodeData.txt | ");
// $line = <HDL>;
// chomp $line;
// @cols = split(/;/, $line);
// print " { 0x$1, 0x$cols[13] }, // $cols[1]\n";
// }
//
//
// 3. Update the latin_tolower() function above with SORTED_CHAR_MAP. Enable
// the assert(ccc == ccc2) above and confirm the function exits successfully.
//
static const struct LatinCapitalSmallPair SORTED_CHAR_MAP[] = {
{ 0x00C4, 0x00E4 }, // LATIN CAPITAL LETTER A WITH DIAERESIS
{ 0x00C5, 0x00E5 }, // LATIN CAPITAL LETTER A WITH RING ABOVE
{ 0x00C6, 0x00E6 }, // LATIN CAPITAL LETTER AE
{ 0x00D0, 0x00F0 }, // LATIN CAPITAL LETTER ETH
{ 0x00D5, 0x00F5 }, // LATIN CAPITAL LETTER O WITH TILDE
{ 0x00D6, 0x00F6 }, // LATIN CAPITAL LETTER O WITH DIAERESIS
{ 0x00D8, 0x00F8 }, // LATIN CAPITAL LETTER O WITH STROKE
{ 0x00DC, 0x00FC }, // LATIN CAPITAL LETTER U WITH DIAERESIS
{ 0x00DE, 0x00FE }, // LATIN CAPITAL LETTER THORN
{ 0x0110, 0x0111 }, // LATIN CAPITAL LETTER D WITH STROKE
{ 0x0126, 0x0127 }, // LATIN CAPITAL LETTER H WITH STROKE
{ 0x0141, 0x0142 }, // LATIN CAPITAL LETTER L WITH STROKE
{ 0x014A, 0x014B }, // LATIN CAPITAL LETTER ENG
{ 0x0152, 0x0153 }, // LATIN CAPITAL LIGATURE OE
{ 0x0166, 0x0167 }, // LATIN CAPITAL LETTER T WITH STROKE
{ 0x0181, 0x0253 }, // LATIN CAPITAL LETTER B WITH HOOK
{ 0x0182, 0x0183 }, // LATIN CAPITAL LETTER B WITH TOPBAR
{ 0x0184, 0x0185 }, // LATIN CAPITAL LETTER TONE SIX
{ 0x0186, 0x0254 }, // LATIN CAPITAL LETTER OPEN O
{ 0x0187, 0x0188 }, // LATIN CAPITAL LETTER C WITH HOOK
{ 0x0189, 0x0256 }, // LATIN CAPITAL LETTER AFRICAN D
{ 0x018A, 0x0257 }, // LATIN CAPITAL LETTER D WITH HOOK
{ 0x018B, 0x018C }, // LATIN CAPITAL LETTER D WITH TOPBAR
{ 0x018E, 0x01DD }, // LATIN CAPITAL LETTER REVERSED E
{ 0x018F, 0x0259 }, // LATIN CAPITAL LETTER SCHWA
{ 0x0190, 0x025B }, // LATIN CAPITAL LETTER OPEN E
{ 0x0191, 0x0192 }, // LATIN CAPITAL LETTER F WITH HOOK
{ 0x0193, 0x0260 }, // LATIN CAPITAL LETTER G WITH HOOK
{ 0x0194, 0x0263 }, // LATIN CAPITAL LETTER GAMMA
{ 0x0196, 0x0269 }, // LATIN CAPITAL LETTER IOTA
{ 0x0197, 0x0268 }, // LATIN CAPITAL LETTER I WITH STROKE
{ 0x0198, 0x0199 }, // LATIN CAPITAL LETTER K WITH HOOK
{ 0x019C, 0x026F }, // LATIN CAPITAL LETTER TURNED M
{ 0x019D, 0x0272 }, // LATIN CAPITAL LETTER N WITH LEFT HOOK
{ 0x019F, 0x0275 }, // LATIN CAPITAL LETTER O WITH MIDDLE TILDE
{ 0x01A2, 0x01A3 }, // LATIN CAPITAL LETTER OI
{ 0x01A4, 0x01A5 }, // LATIN CAPITAL LETTER P WITH HOOK
{ 0x01A6, 0x0280 }, // LATIN LETTER YR
{ 0x01A7, 0x01A8 }, // LATIN CAPITAL LETTER TONE TWO
{ 0x01A9, 0x0283 }, // LATIN CAPITAL LETTER ESH
{ 0x01AC, 0x01AD }, // LATIN CAPITAL LETTER T WITH HOOK
{ 0x01AE, 0x0288 }, // LATIN CAPITAL LETTER T WITH RETROFLEX HOOK
{ 0x01B1, 0x028A }, // LATIN CAPITAL LETTER UPSILON
{ 0x01B2, 0x028B }, // LATIN CAPITAL LETTER V WITH HOOK
{ 0x01B3, 0x01B4 }, // LATIN CAPITAL LETTER Y WITH HOOK
{ 0x01B5, 0x01B6 }, // LATIN CAPITAL LETTER Z WITH STROKE
{ 0x01B7, 0x0292 }, // LATIN CAPITAL LETTER EZH
{ 0x01B8, 0x01B9 }, // LATIN CAPITAL LETTER EZH REVERSED
{ 0x01BC, 0x01BD }, // LATIN CAPITAL LETTER TONE FIVE
{ 0x01E4, 0x01E5 }, // LATIN CAPITAL LETTER G WITH STROKE
{ 0x01EA, 0x01EB }, // LATIN CAPITAL LETTER O WITH OGONEK
{ 0x01F6, 0x0195 }, // LATIN CAPITAL LETTER HWAIR
{ 0x01F7, 0x01BF }, // LATIN CAPITAL LETTER WYNN
{ 0x021C, 0x021D }, // LATIN CAPITAL LETTER YOGH
{ 0x0220, 0x019E }, // LATIN CAPITAL LETTER N WITH LONG RIGHT LEG
{ 0x0222, 0x0223 }, // LATIN CAPITAL LETTER OU
{ 0x0224, 0x0225 }, // LATIN CAPITAL LETTER Z WITH HOOK
{ 0x0226, 0x0227 }, // LATIN CAPITAL LETTER A WITH DOT ABOVE
{ 0x022E, 0x022F }, // LATIN CAPITAL LETTER O WITH DOT ABOVE
{ 0x023A, 0x2C65 }, // LATIN CAPITAL LETTER A WITH STROKE
{ 0x023B, 0x023C }, // LATIN CAPITAL LETTER C WITH STROKE
{ 0x023D, 0x019A }, // LATIN CAPITAL LETTER L WITH BAR
{ 0x023E, 0x2C66 }, // LATIN CAPITAL LETTER T WITH DIAGONAL STROKE
{ 0x0241, 0x0242 }, // LATIN CAPITAL LETTER GLOTTAL STOP
{ 0x0243, 0x0180 }, // LATIN CAPITAL LETTER B WITH STROKE
{ 0x0244, 0x0289 }, // LATIN CAPITAL LETTER U BAR
{ 0x0245, 0x028C }, // LATIN CAPITAL LETTER TURNED V
{ 0x0246, 0x0247 }, // LATIN CAPITAL LETTER E WITH STROKE
{ 0x0248, 0x0249 }, // LATIN CAPITAL LETTER J WITH STROKE
{ 0x024A, 0x024B }, // LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL
{ 0x024C, 0x024D }, // LATIN CAPITAL LETTER R WITH STROKE
{ 0x024E, 0x024F }, // LATIN CAPITAL LETTER Y WITH STROKE
{ 0x0370, 0x0371 }, // GREEK CAPITAL LETTER HETA
{ 0x0372, 0x0373 }, // GREEK CAPITAL LETTER ARCHAIC SAMPI
{ 0x0376, 0x0377 }, // GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA
{ 0x0391, 0x03B1 }, // GREEK CAPITAL LETTER ALPHA
{ 0x0392, 0x03B2 }, // GREEK CAPITAL LETTER BETA
{ 0x0393, 0x03B3 }, // GREEK CAPITAL LETTER GAMMA
{ 0x0394, 0x03B4 }, // GREEK CAPITAL LETTER DELTA
{ 0x0395, 0x03B5 }, // GREEK CAPITAL LETTER EPSILON
{ 0x0396, 0x03B6 }, // GREEK CAPITAL LETTER ZETA
{ 0x0397, 0x03B7 }, // GREEK CAPITAL LETTER ETA
{ 0x0398, 0x03B8 }, // GREEK CAPITAL LETTER THETA
{ 0x0399, 0x03B9 }, // GREEK CAPITAL LETTER IOTA
{ 0x039A, 0x03BA }, // GREEK CAPITAL LETTER KAPPA
{ 0x039B, 0x03BB }, // GREEK CAPITAL LETTER LAMDA
{ 0x039C, 0x03BC }, // GREEK CAPITAL LETTER MU
{ 0x039D, 0x03BD }, // GREEK CAPITAL LETTER NU
{ 0x039E, 0x03BE }, // GREEK CAPITAL LETTER XI
{ 0x039F, 0x03BF }, // GREEK CAPITAL LETTER OMICRON
{ 0x03A0, 0x03C0 }, // GREEK CAPITAL LETTER PI
{ 0x03A1, 0x03C1 }, // GREEK CAPITAL LETTER RHO
{ 0x03A3, 0x03C3 }, // GREEK CAPITAL LETTER SIGMA
{ 0x03A4, 0x03C4 }, // GREEK CAPITAL LETTER TAU
{ 0x03A5, 0x03C5 }, // GREEK CAPITAL LETTER UPSILON
{ 0x03A6, 0x03C6 }, // GREEK CAPITAL LETTER PHI
{ 0x03A7, 0x03C7 }, // GREEK CAPITAL LETTER CHI
{ 0x03A8, 0x03C8 }, // GREEK CAPITAL LETTER PSI
{ 0x03A9, 0x03C9 }, // GREEK CAPITAL LETTER OMEGA
{ 0x03CF, 0x03D7 }, // GREEK CAPITAL KAI SYMBOL
{ 0x03D8, 0x03D9 }, // GREEK LETTER ARCHAIC KOPPA
{ 0x03DA, 0x03DB }, // GREEK LETTER STIGMA
{ 0x03DC, 0x03DD }, // GREEK LETTER DIGAMMA
{ 0x03DE, 0x03DF }, // GREEK LETTER KOPPA
{ 0x03E0, 0x03E1 }, // GREEK LETTER SAMPI
{ 0x03E2, 0x03E3 }, // COPTIC CAPITAL LETTER SHEI
{ 0x03E4, 0x03E5 }, // COPTIC CAPITAL LETTER FEI
{ 0x03E6, 0x03E7 }, // COPTIC CAPITAL LETTER KHEI
{ 0x03E8, 0x03E9 }, // COPTIC CAPITAL LETTER HORI
{ 0x03EA, 0x03EB }, // COPTIC CAPITAL LETTER GANGIA
{ 0x03EC, 0x03ED }, // COPTIC CAPITAL LETTER SHIMA
{ 0x03EE, 0x03EF }, // COPTIC CAPITAL LETTER DEI
{ 0x03F7, 0x03F8 }, // GREEK CAPITAL LETTER SHO
{ 0x03FA, 0x03FB }, // GREEK CAPITAL LETTER SAN
{ 0x03FD, 0x037B }, // GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL
{ 0x03FE, 0x037C }, // GREEK CAPITAL DOTTED LUNATE SIGMA SYMBOL
{ 0x03FF, 0x037D }, // GREEK CAPITAL REVERSED DOTTED LUNATE SIGMA SYMBOL
{ 0x0402, 0x0452 }, // CYRILLIC CAPITAL LETTER DJE
{ 0x0404, 0x0454 }, // CYRILLIC CAPITAL LETTER UKRAINIAN IE
{ 0x0405, 0x0455 }, // CYRILLIC CAPITAL LETTER DZE
{ 0x0406, 0x0456 }, // CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I
{ 0x0408, 0x0458 }, // CYRILLIC CAPITAL LETTER JE
{ 0x0409, 0x0459 }, // CYRILLIC CAPITAL LETTER LJE
{ 0x040A, 0x045A }, // CYRILLIC CAPITAL LETTER NJE
{ 0x040B, 0x045B }, // CYRILLIC CAPITAL LETTER TSHE
{ 0x040F, 0x045F }, // CYRILLIC CAPITAL LETTER DZHE
{ 0x0410, 0x0430 }, // CYRILLIC CAPITAL LETTER A
{ 0x0411, 0x0431 }, // CYRILLIC CAPITAL LETTER BE
{ 0x0412, 0x0432 }, // CYRILLIC CAPITAL LETTER VE
{ 0x0413, 0x0433 }, // CYRILLIC CAPITAL LETTER GHE
{ 0x0414, 0x0434 }, // CYRILLIC CAPITAL LETTER DE
{ 0x0415, 0x0435 }, // CYRILLIC CAPITAL LETTER IE
{ 0x0416, 0x0436 }, // CYRILLIC CAPITAL LETTER ZHE
{ 0x0417, 0x0437 }, // CYRILLIC CAPITAL LETTER ZE
{ 0x0418, 0x0438 }, // CYRILLIC CAPITAL LETTER I
{ 0x041A, 0x043A }, // CYRILLIC CAPITAL LETTER KA
{ 0x041B, 0x043B }, // CYRILLIC CAPITAL LETTER EL
{ 0x041C, 0x043C }, // CYRILLIC CAPITAL LETTER EM
{ 0x041D, 0x043D }, // CYRILLIC CAPITAL LETTER EN
{ 0x041E, 0x043E }, // CYRILLIC CAPITAL LETTER O
{ 0x041F, 0x043F }, // CYRILLIC CAPITAL LETTER PE
{ 0x0420, 0x0440 }, // CYRILLIC CAPITAL LETTER ER
{ 0x0421, 0x0441 }, // CYRILLIC CAPITAL LETTER ES
{ 0x0422, 0x0442 }, // CYRILLIC CAPITAL LETTER TE
{ 0x0423, 0x0443 }, // CYRILLIC CAPITAL LETTER U
{ 0x0424, 0x0444 }, // CYRILLIC CAPITAL LETTER EF
{ 0x0425, 0x0445 }, // CYRILLIC CAPITAL LETTER HA
{ 0x0426, 0x0446 }, // CYRILLIC CAPITAL LETTER TSE
{ 0x0427, 0x0447 }, // CYRILLIC CAPITAL LETTER CHE
{ 0x0428, 0x0448 }, // CYRILLIC CAPITAL LETTER SHA
{ 0x0429, 0x0449 }, // CYRILLIC CAPITAL LETTER SHCHA
{ 0x042A, 0x044A }, // CYRILLIC CAPITAL LETTER HARD SIGN
{ 0x042B, 0x044B }, // CYRILLIC CAPITAL LETTER YERU
{ 0x042C, 0x044C }, // CYRILLIC CAPITAL LETTER SOFT SIGN
{ 0x042D, 0x044D }, // CYRILLIC CAPITAL LETTER E
{ 0x042E, 0x044E }, // CYRILLIC CAPITAL LETTER YU
{ 0x042F, 0x044F }, // CYRILLIC CAPITAL LETTER YA
{ 0x0460, 0x0461 }, // CYRILLIC CAPITAL LETTER OMEGA
{ 0x0462, 0x0463 }, // CYRILLIC CAPITAL LETTER YAT
{ 0x0464, 0x0465 }, // CYRILLIC CAPITAL LETTER IOTIFIED E
{ 0x0466, 0x0467 }, // CYRILLIC CAPITAL LETTER LITTLE YUS
{ 0x0468, 0x0469 }, // CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS
{ 0x046A, 0x046B }, // CYRILLIC CAPITAL LETTER BIG YUS
{ 0x046C, 0x046D }, // CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS
{ 0x046E, 0x046F }, // CYRILLIC CAPITAL LETTER KSI
{ 0x0470, 0x0471 }, // CYRILLIC CAPITAL LETTER PSI
{ 0x0472, 0x0473 }, // CYRILLIC CAPITAL LETTER FITA
{ 0x0474, 0x0475 }, // CYRILLIC CAPITAL LETTER IZHITSA
{ 0x0478, 0x0479 }, // CYRILLIC CAPITAL LETTER UK
{ 0x047A, 0x047B }, // CYRILLIC CAPITAL LETTER ROUND OMEGA
{ 0x047C, 0x047D }, // CYRILLIC CAPITAL LETTER OMEGA WITH TITLO
{ 0x047E, 0x047F }, // CYRILLIC CAPITAL LETTER OT
{ 0x0480, 0x0481 }, // CYRILLIC CAPITAL LETTER KOPPA
{ 0x048A, 0x048B }, // CYRILLIC CAPITAL LETTER SHORT I WITH TAIL
{ 0x048C, 0x048D }, // CYRILLIC CAPITAL LETTER SEMISOFT SIGN
{ 0x048E, 0x048F }, // CYRILLIC CAPITAL LETTER ER WITH TICK
{ 0x0490, 0x0491 }, // CYRILLIC CAPITAL LETTER GHE WITH UPTURN
{ 0x0492, 0x0493 }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE
{ 0x0494, 0x0495 }, // CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK
{ 0x0496, 0x0497 }, // CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER
{ 0x0498, 0x0499 }, // CYRILLIC CAPITAL LETTER ZE WITH DESCENDER
{ 0x049A, 0x049B }, // CYRILLIC CAPITAL LETTER KA WITH DESCENDER
{ 0x049C, 0x049D }, // CYRILLIC CAPITAL LETTER KA WITH VERTICAL STROKE
{ 0x049E, 0x049F }, // CYRILLIC CAPITAL LETTER KA WITH STROKE
{ 0x04A0, 0x04A1 }, // CYRILLIC CAPITAL LETTER BASHKIR KA
{ 0x04A2, 0x04A3 }, // CYRILLIC CAPITAL LETTER EN WITH DESCENDER
{ 0x04A4, 0x04A5 }, // CYRILLIC CAPITAL LIGATURE EN GHE
{ 0x04A6, 0x04A7 }, // CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK
{ 0x04A8, 0x04A9 }, // CYRILLIC CAPITAL LETTER ABKHASIAN HA
{ 0x04AA, 0x04AB }, // CYRILLIC CAPITAL LETTER ES WITH DESCENDER
{ 0x04AC, 0x04AD }, // CYRILLIC CAPITAL LETTER TE WITH DESCENDER
{ 0x04AE, 0x04AF }, // CYRILLIC CAPITAL LETTER STRAIGHT U
{ 0x04B0, 0x04B1 }, // CYRILLIC CAPITAL LETTER STRAIGHT U WITH STROKE
{ 0x04B2, 0x04B3 }, // CYRILLIC CAPITAL LETTER HA WITH DESCENDER
{ 0x04B4, 0x04B5 }, // CYRILLIC CAPITAL LIGATURE TE TSE
{ 0x04B6, 0x04B7 }, // CYRILLIC CAPITAL LETTER CHE WITH DESCENDER
{ 0x04B8, 0x04B9 }, // CYRILLIC CAPITAL LETTER CHE WITH VERTICAL STROKE
{ 0x04BA, 0x04BB }, // CYRILLIC CAPITAL LETTER SHHA
{ 0x04BC, 0x04BD }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE
{ 0x04BE, 0x04BF }, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH DESCENDER
{ 0x04C0, 0x04CF }, // CYRILLIC LETTER PALOCHKA
{ 0x04C3, 0x04C4 }, // CYRILLIC CAPITAL LETTER KA WITH HOOK
{ 0x04C5, 0x04C6 }, // CYRILLIC CAPITAL LETTER EL WITH TAIL
{ 0x04C7, 0x04C8 }, // CYRILLIC CAPITAL LETTER EN WITH HOOK
{ 0x04C9, 0x04CA }, // CYRILLIC CAPITAL LETTER EN WITH TAIL
{ 0x04CB, 0x04CC }, // CYRILLIC CAPITAL LETTER KHAKASSIAN CHE
{ 0x04CD, 0x04CE }, // CYRILLIC CAPITAL LETTER EM WITH TAIL
{ 0x04D4, 0x04D5 }, // CYRILLIC CAPITAL LIGATURE A IE
{ 0x04D8, 0x04D9 }, // CYRILLIC CAPITAL LETTER SCHWA
{ 0x04E0, 0x04E1 }, // CYRILLIC CAPITAL LETTER ABKHASIAN DZE
{ 0x04E8, 0x04E9 }, // CYRILLIC CAPITAL LETTER BARRED O
{ 0x04F6, 0x04F7 }, // CYRILLIC CAPITAL LETTER GHE WITH DESCENDER
{ 0x04FA, 0x04FB }, // CYRILLIC CAPITAL LETTER GHE WITH STROKE AND HOOK
{ 0x04FC, 0x04FD }, // CYRILLIC CAPITAL LETTER HA WITH HOOK
{ 0x04FE, 0x04FF }, // CYRILLIC CAPITAL LETTER HA WITH STROKE
{ 0x0500, 0x0501 }, // CYRILLIC CAPITAL LETTER KOMI DE
{ 0x0502, 0x0503 }, // CYRILLIC CAPITAL LETTER KOMI DJE
{ 0x0504, 0x0505 }, // CYRILLIC CAPITAL LETTER KOMI ZJE
{ 0x0506, 0x0507 }, // CYRILLIC CAPITAL LETTER KOMI DZJE
{ 0x0508, 0x0509 }, // CYRILLIC CAPITAL LETTER KOMI LJE
{ 0x050A, 0x050B }, // CYRILLIC CAPITAL LETTER KOMI NJE
{ 0x050C, 0x050D }, // CYRILLIC CAPITAL LETTER KOMI SJE
{ 0x050E, 0x050F }, // CYRILLIC CAPITAL LETTER KOMI TJE
{ 0x0510, 0x0511 }, // CYRILLIC CAPITAL LETTER REVERSED ZE
{ 0x0512, 0x0513 }, // CYRILLIC CAPITAL LETTER EL WITH HOOK
{ 0x0514, 0x0515 }, // CYRILLIC CAPITAL LETTER LHA
{ 0x0516, 0x0517 }, // CYRILLIC CAPITAL LETTER RHA
{ 0x0518, 0x0519 }, // CYRILLIC CAPITAL LETTER YAE
{ 0x051A, 0x051B }, // CYRILLIC CAPITAL LETTER QA
{ 0x051C, 0x051D }, // CYRILLIC CAPITAL LETTER WE
{ 0x051E, 0x051F }, // CYRILLIC CAPITAL LETTER ALEUT KA
{ 0x0520, 0x0521 }, // CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK
{ 0x0522, 0x0523 }, // CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK
{ 0x0524, 0x0525 }, // CYRILLIC CAPITAL LETTER PE WITH DESCENDER
{ 0x0531, 0x0561 }, // ARMENIAN CAPITAL LETTER AYB
{ 0x0532, 0x0562 }, // ARMENIAN CAPITAL LETTER BEN
{ 0x0533, 0x0563 }, // ARMENIAN CAPITAL LETTER GIM
{ 0x0534, 0x0564 }, // ARMENIAN CAPITAL LETTER DA
{ 0x0535, 0x0565 }, // ARMENIAN CAPITAL LETTER ECH
{ 0x0536, 0x0566 }, // ARMENIAN CAPITAL LETTER ZA
{ 0x0537, 0x0567 }, // ARMENIAN CAPITAL LETTER EH
{ 0x0538, 0x0568 }, // ARMENIAN CAPITAL LETTER ET
{ 0x0539, 0x0569 }, // ARMENIAN CAPITAL LETTER TO
{ 0x053A, 0x056A }, // ARMENIAN CAPITAL LETTER ZHE
{ 0x053B, 0x056B }, // ARMENIAN CAPITAL LETTER INI
{ 0x053C, 0x056C }, // ARMENIAN CAPITAL LETTER LIWN
{ 0x053D, 0x056D }, // ARMENIAN CAPITAL LETTER XEH
{ 0x053E, 0x056E }, // ARMENIAN CAPITAL LETTER CA
{ 0x053F, 0x056F }, // ARMENIAN CAPITAL LETTER KEN
{ 0x0540, 0x0570 }, // ARMENIAN CAPITAL LETTER HO
{ 0x0541, 0x0571 }, // ARMENIAN CAPITAL LETTER JA
{ 0x0542, 0x0572 }, // ARMENIAN CAPITAL LETTER GHAD
{ 0x0543, 0x0573 }, // ARMENIAN CAPITAL LETTER CHEH
{ 0x0544, 0x0574 }, // ARMENIAN CAPITAL LETTER MEN
{ 0x0545, 0x0575 }, // ARMENIAN CAPITAL LETTER YI
{ 0x0546, 0x0576 }, // ARMENIAN CAPITAL LETTER NOW
{ 0x0547, 0x0577 }, // ARMENIAN CAPITAL LETTER SHA
{ 0x0548, 0x0578 }, // ARMENIAN CAPITAL LETTER VO
{ 0x0549, 0x0579 }, // ARMENIAN CAPITAL LETTER CHA
{ 0x054A, 0x057A }, // ARMENIAN CAPITAL LETTER PEH
{ 0x054B, 0x057B }, // ARMENIAN CAPITAL LETTER JHEH
{ 0x054C, 0x057C }, // ARMENIAN CAPITAL LETTER RA
{ 0x054D, 0x057D }, // ARMENIAN CAPITAL LETTER SEH
{ 0x054E, 0x057E }, // ARMENIAN CAPITAL LETTER VEW
{ 0x054F, 0x057F }, // ARMENIAN CAPITAL LETTER TIWN
{ 0x0550, 0x0580 }, // ARMENIAN CAPITAL LETTER REH
{ 0x0551, 0x0581 }, // ARMENIAN CAPITAL LETTER CO
{ 0x0552, 0x0582 }, // ARMENIAN CAPITAL LETTER YIWN
{ 0x0553, 0x0583 }, // ARMENIAN CAPITAL LETTER PIWR
{ 0x0554, 0x0584 }, // ARMENIAN CAPITAL LETTER KEH
{ 0x0555, 0x0585 }, // ARMENIAN CAPITAL LETTER OH
{ 0x0556, 0x0586 }, // ARMENIAN CAPITAL LETTER FEH
{ 0x10A0, 0x2D00 }, // GEORGIAN CAPITAL LETTER AN
{ 0x10A1, 0x2D01 }, // GEORGIAN CAPITAL LETTER BAN
{ 0x10A2, 0x2D02 }, // GEORGIAN CAPITAL LETTER GAN
{ 0x10A3, 0x2D03 }, // GEORGIAN CAPITAL LETTER DON
{ 0x10A4, 0x2D04 }, // GEORGIAN CAPITAL LETTER EN
{ 0x10A5, 0x2D05 }, // GEORGIAN CAPITAL LETTER VIN
{ 0x10A6, 0x2D06 }, // GEORGIAN CAPITAL LETTER ZEN
{ 0x10A7, 0x2D07 }, // GEORGIAN CAPITAL LETTER TAN
{ 0x10A8, 0x2D08 }, // GEORGIAN CAPITAL LETTER IN
{ 0x10A9, 0x2D09 }, // GEORGIAN CAPITAL LETTER KAN
{ 0x10AA, 0x2D0A }, // GEORGIAN CAPITAL LETTER LAS
{ 0x10AB, 0x2D0B }, // GEORGIAN CAPITAL LETTER MAN
{ 0x10AC, 0x2D0C }, // GEORGIAN CAPITAL LETTER NAR
{ 0x10AD, 0x2D0D }, // GEORGIAN CAPITAL LETTER ON
{ 0x10AE, 0x2D0E }, // GEORGIAN CAPITAL LETTER PAR
{ 0x10AF, 0x2D0F }, // GEORGIAN CAPITAL LETTER ZHAR
{ 0x10B0, 0x2D10 }, // GEORGIAN CAPITAL LETTER RAE
{ 0x10B1, 0x2D11 }, // GEORGIAN CAPITAL LETTER SAN
{ 0x10B2, 0x2D12 }, // GEORGIAN CAPITAL LETTER TAR
{ 0x10B3, 0x2D13 }, // GEORGIAN CAPITAL LETTER UN
{ 0x10B4, 0x2D14 }, // GEORGIAN CAPITAL LETTER PHAR
{ 0x10B5, 0x2D15 }, // GEORGIAN CAPITAL LETTER KHAR
{ 0x10B6, 0x2D16 }, // GEORGIAN CAPITAL LETTER GHAN
{ 0x10B7, 0x2D17 }, // GEORGIAN CAPITAL LETTER QAR
{ 0x10B8, 0x2D18 }, // GEORGIAN CAPITAL LETTER SHIN
{ 0x10B9, 0x2D19 }, // GEORGIAN CAPITAL LETTER CHIN
{ 0x10BA, 0x2D1A }, // GEORGIAN CAPITAL LETTER CAN
{ 0x10BB, 0x2D1B }, // GEORGIAN CAPITAL LETTER JIL
{ 0x10BC, 0x2D1C }, // GEORGIAN CAPITAL LETTER CIL
{ 0x10BD, 0x2D1D }, // GEORGIAN CAPITAL LETTER CHAR
{ 0x10BE, 0x2D1E }, // GEORGIAN CAPITAL LETTER XAN
{ 0x10BF, 0x2D1F }, // GEORGIAN CAPITAL LETTER JHAN
{ 0x10C0, 0x2D20 }, // GEORGIAN CAPITAL LETTER HAE
{ 0x10C1, 0x2D21 }, // GEORGIAN CAPITAL LETTER HE
{ 0x10C2, 0x2D22 }, // GEORGIAN CAPITAL LETTER HIE
{ 0x10C3, 0x2D23 }, // GEORGIAN CAPITAL LETTER WE
{ 0x10C4, 0x2D24 }, // GEORGIAN CAPITAL LETTER HAR
{ 0x10C5, 0x2D25 }, // GEORGIAN CAPITAL LETTER HOE
{ 0x1E00, 0x1E01 }, // LATIN CAPITAL LETTER A WITH RING BELOW
{ 0x1E02, 0x1E03 }, // LATIN CAPITAL LETTER B WITH DOT ABOVE
{ 0x1E04, 0x1E05 }, // LATIN CAPITAL LETTER B WITH DOT BELOW
{ 0x1E06, 0x1E07 }, // LATIN CAPITAL LETTER B WITH LINE BELOW
{ 0x1E08, 0x1E09 }, // LATIN CAPITAL LETTER C WITH CEDILLA AND ACUTE
{ 0x1E0A, 0x1E0B }, // LATIN CAPITAL LETTER D WITH DOT ABOVE
{ 0x1E0C, 0x1E0D }, // LATIN CAPITAL LETTER D WITH DOT BELOW
{ 0x1E0E, 0x1E0F }, // LATIN CAPITAL LETTER D WITH LINE BELOW
{ 0x1E10, 0x1E11 }, // LATIN CAPITAL LETTER D WITH CEDILLA
{ 0x1E12, 0x1E13 }, // LATIN CAPITAL LETTER D WITH CIRCUMFLEX BELOW
{ 0x1E14, 0x1E15 }, // LATIN CAPITAL LETTER E WITH MACRON AND GRAVE
{ 0x1E16, 0x1E17 }, // LATIN CAPITAL LETTER E WITH MACRON AND ACUTE
{ 0x1E18, 0x1E19 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX BELOW
{ 0x1E1A, 0x1E1B }, // LATIN CAPITAL LETTER E WITH TILDE BELOW
{ 0x1E1C, 0x1E1D }, // LATIN CAPITAL LETTER E WITH CEDILLA AND BREVE
{ 0x1E1E, 0x1E1F }, // LATIN CAPITAL LETTER F WITH DOT ABOVE
{ 0x1E20, 0x1E21 }, // LATIN CAPITAL LETTER G WITH MACRON
{ 0x1E22, 0x1E23 }, // LATIN CAPITAL LETTER H WITH DOT ABOVE
{ 0x1E24, 0x1E25 }, // LATIN CAPITAL LETTER H WITH DOT BELOW
{ 0x1E26, 0x1E27 }, // LATIN CAPITAL LETTER H WITH DIAERESIS
{ 0x1E28, 0x1E29 }, // LATIN CAPITAL LETTER H WITH CEDILLA
{ 0x1E2A, 0x1E2B }, // LATIN CAPITAL LETTER H WITH BREVE BELOW
{ 0x1E2C, 0x1E2D }, // LATIN CAPITAL LETTER I WITH TILDE BELOW
{ 0x1E2E, 0x1E2F }, // LATIN CAPITAL LETTER I WITH DIAERESIS AND ACUTE
{ 0x1E30, 0x1E31 }, // LATIN CAPITAL LETTER K WITH ACUTE
{ 0x1E32, 0x1E33 }, // LATIN CAPITAL LETTER K WITH DOT BELOW
{ 0x1E34, 0x1E35 }, // LATIN CAPITAL LETTER K WITH LINE BELOW
{ 0x1E36, 0x1E37 }, // LATIN CAPITAL LETTER L WITH DOT BELOW
{ 0x1E38, 0x1E39 }, // LATIN CAPITAL LETTER L WITH DOT BELOW AND MACRON
{ 0x1E3A, 0x1E3B }, // LATIN CAPITAL LETTER L WITH LINE BELOW
{ 0x1E3C, 0x1E3D }, // LATIN CAPITAL LETTER L WITH CIRCUMFLEX BELOW
{ 0x1E3E, 0x1E3F }, // LATIN CAPITAL LETTER M WITH ACUTE
{ 0x1E40, 0x1E41 }, // LATIN CAPITAL LETTER M WITH DOT ABOVE
{ 0x1E42, 0x1E43 }, // LATIN CAPITAL LETTER M WITH DOT BELOW
{ 0x1E44, 0x1E45 }, // LATIN CAPITAL LETTER N WITH DOT ABOVE
{ 0x1E46, 0x1E47 }, // LATIN CAPITAL LETTER N WITH DOT BELOW
{ 0x1E48, 0x1E49 }, // LATIN CAPITAL LETTER N WITH LINE BELOW
{ 0x1E4A, 0x1E4B }, // LATIN CAPITAL LETTER N WITH CIRCUMFLEX BELOW
{ 0x1E4C, 0x1E4D }, // LATIN CAPITAL LETTER O WITH TILDE AND ACUTE
{ 0x1E4E, 0x1E4F }, // LATIN CAPITAL LETTER O WITH TILDE AND DIAERESIS
{ 0x1E50, 0x1E51 }, // LATIN CAPITAL LETTER O WITH MACRON AND GRAVE
{ 0x1E52, 0x1E53 }, // LATIN CAPITAL LETTER O WITH MACRON AND ACUTE
{ 0x1E54, 0x1E55 }, // LATIN CAPITAL LETTER P WITH ACUTE
{ 0x1E56, 0x1E57 }, // LATIN CAPITAL LETTER P WITH DOT ABOVE
{ 0x1E58, 0x1E59 }, // LATIN CAPITAL LETTER R WITH DOT ABOVE
{ 0x1E5A, 0x1E5B }, // LATIN CAPITAL LETTER R WITH DOT BELOW
{ 0x1E5C, 0x1E5D }, // LATIN CAPITAL LETTER R WITH DOT BELOW AND MACRON
{ 0x1E5E, 0x1E5F }, // LATIN CAPITAL LETTER R WITH LINE BELOW
{ 0x1E60, 0x1E61 }, // LATIN CAPITAL LETTER S WITH DOT ABOVE
{ 0x1E62, 0x1E63 }, // LATIN CAPITAL LETTER S WITH DOT BELOW
{ 0x1E64, 0x1E65 }, // LATIN CAPITAL LETTER S WITH ACUTE AND DOT ABOVE
{ 0x1E66, 0x1E67 }, // LATIN CAPITAL LETTER S WITH CARON AND DOT ABOVE
{ 0x1E68, 0x1E69 }, // LATIN CAPITAL LETTER S WITH DOT BELOW AND DOT ABOVE
{ 0x1E6A, 0x1E6B }, // LATIN CAPITAL LETTER T WITH DOT ABOVE
{ 0x1E6C, 0x1E6D }, // LATIN CAPITAL LETTER T WITH DOT BELOW
{ 0x1E6E, 0x1E6F }, // LATIN CAPITAL LETTER T WITH LINE BELOW
{ 0x1E70, 0x1E71 }, // LATIN CAPITAL LETTER T WITH CIRCUMFLEX BELOW
{ 0x1E72, 0x1E73 }, // LATIN CAPITAL LETTER U WITH DIAERESIS BELOW
{ 0x1E74, 0x1E75 }, // LATIN CAPITAL LETTER U WITH TILDE BELOW
{ 0x1E76, 0x1E77 }, // LATIN CAPITAL LETTER U WITH CIRCUMFLEX BELOW
{ 0x1E78, 0x1E79 }, // LATIN CAPITAL LETTER U WITH TILDE AND ACUTE
{ 0x1E7A, 0x1E7B }, // LATIN CAPITAL LETTER U WITH MACRON AND DIAERESIS
{ 0x1E7C, 0x1E7D }, // LATIN CAPITAL LETTER V WITH TILDE
{ 0x1E7E, 0x1E7F }, // LATIN CAPITAL LETTER V WITH DOT BELOW
{ 0x1E80, 0x1E81 }, // LATIN CAPITAL LETTER W WITH GRAVE
{ 0x1E82, 0x1E83 }, // LATIN CAPITAL LETTER W WITH ACUTE
{ 0x1E84, 0x1E85 }, // LATIN CAPITAL LETTER W WITH DIAERESIS
{ 0x1E86, 0x1E87 }, // LATIN CAPITAL LETTER W WITH DOT ABOVE
{ 0x1E88, 0x1E89 }, // LATIN CAPITAL LETTER W WITH DOT BELOW
{ 0x1E8A, 0x1E8B }, // LATIN CAPITAL LETTER X WITH DOT ABOVE
{ 0x1E8C, 0x1E8D }, // LATIN CAPITAL LETTER X WITH DIAERESIS
{ 0x1E8E, 0x1E8F }, // LATIN CAPITAL LETTER Y WITH DOT ABOVE
{ 0x1E90, 0x1E91 }, // LATIN CAPITAL LETTER Z WITH CIRCUMFLEX
{ 0x1E92, 0x1E93 }, // LATIN CAPITAL LETTER Z WITH DOT BELOW
{ 0x1E94, 0x1E95 }, // LATIN CAPITAL LETTER Z WITH LINE BELOW
{ 0x1E9E, 0x00DF }, // LATIN CAPITAL LETTER SHARP S
{ 0x1EA0, 0x1EA1 }, // LATIN CAPITAL LETTER A WITH DOT BELOW
{ 0x1EA2, 0x1EA3 }, // LATIN CAPITAL LETTER A WITH HOOK ABOVE
{ 0x1EA4, 0x1EA5 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND ACUTE
{ 0x1EA6, 0x1EA7 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND GRAVE
{ 0x1EA8, 0x1EA9 }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EAA, 0x1EAB }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND TILDE
{ 0x1EAC, 0x1EAD }, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EAE, 0x1EAF }, // LATIN CAPITAL LETTER A WITH BREVE AND ACUTE
{ 0x1EB0, 0x1EB1 }, // LATIN CAPITAL LETTER A WITH BREVE AND GRAVE
{ 0x1EB2, 0x1EB3 }, // LATIN CAPITAL LETTER A WITH BREVE AND HOOK ABOVE
{ 0x1EB4, 0x1EB5 }, // LATIN CAPITAL LETTER A WITH BREVE AND TILDE
{ 0x1EB6, 0x1EB7 }, // LATIN CAPITAL LETTER A WITH BREVE AND DOT BELOW
{ 0x1EB8, 0x1EB9 }, // LATIN CAPITAL LETTER E WITH DOT BELOW
{ 0x1EBA, 0x1EBB }, // LATIN CAPITAL LETTER E WITH HOOK ABOVE
{ 0x1EBC, 0x1EBD }, // LATIN CAPITAL LETTER E WITH TILDE
{ 0x1EBE, 0x1EBF }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND ACUTE
{ 0x1EC0, 0x1EC1 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND GRAVE
{ 0x1EC2, 0x1EC3 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1EC4, 0x1EC5 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND TILDE
{ 0x1EC6, 0x1EC7 }, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EC8, 0x1EC9 }, // LATIN CAPITAL LETTER I WITH HOOK ABOVE
{ 0x1ECA, 0x1ECB }, // LATIN CAPITAL LETTER I WITH DOT BELOW
{ 0x1ECC, 0x1ECD }, // LATIN CAPITAL LETTER O WITH DOT BELOW
{ 0x1ECE, 0x1ECF }, // LATIN CAPITAL LETTER O WITH HOOK ABOVE
{ 0x1ED0, 0x1ED1 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND ACUTE
{ 0x1ED2, 0x1ED3 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND GRAVE
{ 0x1ED4, 0x1ED5 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND HOOK ABOVE
{ 0x1ED6, 0x1ED7 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND TILDE
{ 0x1ED8, 0x1ED9 }, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX AND DOT BELOW
{ 0x1EDA, 0x1EDB }, // LATIN CAPITAL LETTER O WITH HORN AND ACUTE
{ 0x1EDC, 0x1EDD }, // LATIN CAPITAL LETTER O WITH HORN AND GRAVE
{ 0x1EDE, 0x1EDF }, // LATIN CAPITAL LETTER O WITH HORN AND HOOK ABOVE
{ 0x1EE0, 0x1EE1 }, // LATIN CAPITAL LETTER O WITH HORN AND TILDE
{ 0x1EE2, 0x1EE3 }, // LATIN CAPITAL LETTER O WITH HORN AND DOT BELOW
{ 0x1EE4, 0x1EE5 }, // LATIN CAPITAL LETTER U WITH DOT BELOW
{ 0x1EE6, 0x1EE7 }, // LATIN CAPITAL LETTER U WITH HOOK ABOVE
{ 0x1EE8, 0x1EE9 }, // LATIN CAPITAL LETTER U WITH HORN AND ACUTE
{ 0x1EEA, 0x1EEB }, // LATIN CAPITAL LETTER U WITH HORN AND GRAVE
{ 0x1EEC, 0x1EED }, // LATIN CAPITAL LETTER U WITH HORN AND HOOK ABOVE
{ 0x1EEE, 0x1EEF }, // LATIN CAPITAL LETTER U WITH HORN AND TILDE
{ 0x1EF0, 0x1EF1 }, // LATIN CAPITAL LETTER U WITH HORN AND DOT BELOW
{ 0x1EF2, 0x1EF3 }, // LATIN CAPITAL LETTER Y WITH GRAVE
{ 0x1EF4, 0x1EF5 }, // LATIN CAPITAL LETTER Y WITH DOT BELOW
{ 0x1EF6, 0x1EF7 }, // LATIN CAPITAL LETTER Y WITH HOOK ABOVE
{ 0x1EF8, 0x1EF9 }, // LATIN CAPITAL LETTER Y WITH TILDE
{ 0x1EFA, 0x1EFB }, // LATIN CAPITAL LETTER MIDDLE-WELSH LL
{ 0x1EFC, 0x1EFD }, // LATIN CAPITAL LETTER MIDDLE-WELSH V
{ 0x1EFE, 0x1EFF }, // LATIN CAPITAL LETTER Y WITH LOOP
{ 0x1F08, 0x1F00 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI
{ 0x1F09, 0x1F01 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA
{ 0x1F0A, 0x1F02 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA
{ 0x1F0B, 0x1F03 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA
{ 0x1F0C, 0x1F04 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA
{ 0x1F0D, 0x1F05 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA
{ 0x1F0E, 0x1F06 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI
{ 0x1F0F, 0x1F07 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI
{ 0x1F18, 0x1F10 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI
{ 0x1F19, 0x1F11 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA
{ 0x1F1A, 0x1F12 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND VARIA
{ 0x1F1B, 0x1F13 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND VARIA
{ 0x1F1C, 0x1F14 }, // GREEK CAPITAL LETTER EPSILON WITH PSILI AND OXIA
{ 0x1F1D, 0x1F15 }, // GREEK CAPITAL LETTER EPSILON WITH DASIA AND OXIA
{ 0x1F28, 0x1F20 }, // GREEK CAPITAL LETTER ETA WITH PSILI
{ 0x1F29, 0x1F21 }, // GREEK CAPITAL LETTER ETA WITH DASIA
{ 0x1F2A, 0x1F22 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA
{ 0x1F2B, 0x1F23 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA
{ 0x1F2C, 0x1F24 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA
{ 0x1F2D, 0x1F25 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA
{ 0x1F2E, 0x1F26 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI
{ 0x1F2F, 0x1F27 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI
{ 0x1F38, 0x1F30 }, // GREEK CAPITAL LETTER IOTA WITH PSILI
{ 0x1F39, 0x1F31 }, // GREEK CAPITAL LETTER IOTA WITH DASIA
{ 0x1F3A, 0x1F32 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND VARIA
{ 0x1F3B, 0x1F33 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND VARIA
{ 0x1F3C, 0x1F34 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND OXIA
{ 0x1F3D, 0x1F35 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND OXIA
{ 0x1F3E, 0x1F36 }, // GREEK CAPITAL LETTER IOTA WITH PSILI AND PERISPOMENI
{ 0x1F3F, 0x1F37 }, // GREEK CAPITAL LETTER IOTA WITH DASIA AND PERISPOMENI
{ 0x1F48, 0x1F40 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI
{ 0x1F49, 0x1F41 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA
{ 0x1F4A, 0x1F42 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND VARIA
{ 0x1F4B, 0x1F43 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND VARIA
{ 0x1F4C, 0x1F44 }, // GREEK CAPITAL LETTER OMICRON WITH PSILI AND OXIA
{ 0x1F4D, 0x1F45 }, // GREEK CAPITAL LETTER OMICRON WITH DASIA AND OXIA
{ 0x1F59, 0x1F51 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA
{ 0x1F5B, 0x1F53 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND VARIA
{ 0x1F5D, 0x1F55 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND OXIA
{ 0x1F5F, 0x1F57 }, // GREEK CAPITAL LETTER UPSILON WITH DASIA AND PERISPOMENI
{ 0x1F68, 0x1F60 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI
{ 0x1F69, 0x1F61 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA
{ 0x1F6A, 0x1F62 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA
{ 0x1F6B, 0x1F63 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA
{ 0x1F6C, 0x1F64 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA
{ 0x1F6D, 0x1F65 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA
{ 0x1F6E, 0x1F66 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI
{ 0x1F6F, 0x1F67 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI
{ 0x1F88, 0x1F80 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F89, 0x1F81 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F8A, 0x1F82 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F8B, 0x1F83 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F8C, 0x1F84 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F8D, 0x1F85 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F8E, 0x1F86 }, // GREEK CAPITAL LETTER ALPHA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F8F, 0x1F87 }, // GREEK CAPITAL LETTER ALPHA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F98, 0x1F90 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PROSGEGRAMMENI
{ 0x1F99, 0x1F91 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PROSGEGRAMMENI
{ 0x1F9A, 0x1F92 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1F9B, 0x1F93 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1F9C, 0x1F94 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1F9D, 0x1F95 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1F9E, 0x1F96 }, // GREEK CAPITAL LETTER ETA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1F9F, 0x1F97 }, // GREEK CAPITAL LETTER ETA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FA8, 0x1FA0 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PROSGEGRAMMENI
{ 0x1FA9, 0x1FA1 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PROSGEGRAMMENI
{ 0x1FAA, 0x1FA2 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND VARIA AND PROSGEGRAMMENI
{ 0x1FAB, 0x1FA3 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND VARIA AND PROSGEGRAMMENI
{ 0x1FAC, 0x1FA4 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND OXIA AND PROSGEGRAMMENI
{ 0x1FAD, 0x1FA5 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND OXIA AND PROSGEGRAMMENI
{ 0x1FAE, 0x1FA6 }, // GREEK CAPITAL LETTER OMEGA WITH PSILI AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FAF, 0x1FA7 }, // GREEK CAPITAL LETTER OMEGA WITH DASIA AND PERISPOMENI AND PROSGEGRAMMENI
{ 0x1FB8, 0x1FB0 }, // GREEK CAPITAL LETTER ALPHA WITH VRACHY
{ 0x1FB9, 0x1FB1 }, // GREEK CAPITAL LETTER ALPHA WITH MACRON
{ 0x1FBA, 0x1F70 }, // GREEK CAPITAL LETTER ALPHA WITH VARIA
{ 0x1FBB, 0x1F71 }, // GREEK CAPITAL LETTER ALPHA WITH OXIA
{ 0x1FBC, 0x1FB3 }, // GREEK CAPITAL LETTER ALPHA WITH PROSGEGRAMMENI
{ 0x1FC8, 0x1F72 }, // GREEK CAPITAL LETTER EPSILON WITH VARIA
{ 0x1FC9, 0x1F73 }, // GREEK CAPITAL LETTER EPSILON WITH OXIA
{ 0x1FCA, 0x1F74 }, // GREEK CAPITAL LETTER ETA WITH VARIA
{ 0x1FCB, 0x1F75 }, // GREEK CAPITAL LETTER ETA WITH OXIA
{ 0x1FCC, 0x1FC3 }, // GREEK CAPITAL LETTER ETA WITH PROSGEGRAMMENI
{ 0x1FD8, 0x1FD0 }, // GREEK CAPITAL LETTER IOTA WITH VRACHY
{ 0x1FD9, 0x1FD1 }, // GREEK CAPITAL LETTER IOTA WITH MACRON
{ 0x1FDA, 0x1F76 }, // GREEK CAPITAL LETTER IOTA WITH VARIA
{ 0x1FDB, 0x1F77 }, // GREEK CAPITAL LETTER IOTA WITH OXIA
{ 0x1FE8, 0x1FE0 }, // GREEK CAPITAL LETTER UPSILON WITH VRACHY
{ 0x1FE9, 0x1FE1 }, // GREEK CAPITAL LETTER UPSILON WITH MACRON
{ 0x1FEA, 0x1F7A }, // GREEK CAPITAL LETTER UPSILON WITH VARIA
{ 0x1FEB, 0x1F7B }, // GREEK CAPITAL LETTER UPSILON WITH OXIA
{ 0x1FEC, 0x1FE5 }, // GREEK CAPITAL LETTER RHO WITH DASIA
{ 0x1FF8, 0x1F78 }, // GREEK CAPITAL LETTER OMICRON WITH VARIA
{ 0x1FF9, 0x1F79 }, // GREEK CAPITAL LETTER OMICRON WITH OXIA
{ 0x1FFA, 0x1F7C }, // GREEK CAPITAL LETTER OMEGA WITH VARIA
{ 0x1FFB, 0x1F7D }, // GREEK CAPITAL LETTER OMEGA WITH OXIA
{ 0x1FFC, 0x1FF3 }, // GREEK CAPITAL LETTER OMEGA WITH PROSGEGRAMMENI
{ 0x2126, 0x03C9 }, // OHM SIGN
{ 0x212A, 0x006B }, // KELVIN SIGN
{ 0x212B, 0x00E5 }, // ANGSTROM SIGN
{ 0x2132, 0x214E }, // TURNED CAPITAL F
{ 0x2160, 0x2170 }, // ROMAN NUMERAL ONE
{ 0x2161, 0x2171 }, // ROMAN NUMERAL TWO
{ 0x2162, 0x2172 }, // ROMAN NUMERAL THREE
{ 0x2163, 0x2173 }, // ROMAN NUMERAL FOUR
{ 0x2164, 0x2174 }, // ROMAN NUMERAL FIVE
{ 0x2165, 0x2175 }, // ROMAN NUMERAL SIX
{ 0x2166, 0x2176 }, // ROMAN NUMERAL SEVEN
{ 0x2167, 0x2177 }, // ROMAN NUMERAL EIGHT
{ 0x2168, 0x2178 }, // ROMAN NUMERAL NINE
{ 0x2169, 0x2179 }, // ROMAN NUMERAL TEN
{ 0x216A, 0x217A }, // ROMAN NUMERAL ELEVEN
{ 0x216B, 0x217B }, // ROMAN NUMERAL TWELVE
{ 0x216C, 0x217C }, // ROMAN NUMERAL FIFTY
{ 0x216D, 0x217D }, // ROMAN NUMERAL ONE HUNDRED
{ 0x216E, 0x217E }, // ROMAN NUMERAL FIVE HUNDRED
{ 0x216F, 0x217F }, // ROMAN NUMERAL ONE THOUSAND
{ 0x2183, 0x2184 }, // ROMAN NUMERAL REVERSED ONE HUNDRED
{ 0x24B6, 0x24D0 }, // CIRCLED LATIN CAPITAL LETTER A
{ 0x24B7, 0x24D1 }, // CIRCLED LATIN CAPITAL LETTER B
{ 0x24B8, 0x24D2 }, // CIRCLED LATIN CAPITAL LETTER C
{ 0x24B9, 0x24D3 }, // CIRCLED LATIN CAPITAL LETTER D
{ 0x24BA, 0x24D4 }, // CIRCLED LATIN CAPITAL LETTER E
{ 0x24BB, 0x24D5 }, // CIRCLED LATIN CAPITAL LETTER F
{ 0x24BC, 0x24D6 }, // CIRCLED LATIN CAPITAL LETTER G
{ 0x24BD, 0x24D7 }, // CIRCLED LATIN CAPITAL LETTER H
{ 0x24BE, 0x24D8 }, // CIRCLED LATIN CAPITAL LETTER I
{ 0x24BF, 0x24D9 }, // CIRCLED LATIN CAPITAL LETTER J
{ 0x24C0, 0x24DA }, // CIRCLED LATIN CAPITAL LETTER K
{ 0x24C1, 0x24DB }, // CIRCLED LATIN CAPITAL LETTER L
{ 0x24C2, 0x24DC }, // CIRCLED LATIN CAPITAL LETTER M
{ 0x24C3, 0x24DD }, // CIRCLED LATIN CAPITAL LETTER N
{ 0x24C4, 0x24DE }, // CIRCLED LATIN CAPITAL LETTER O
{ 0x24C5, 0x24DF }, // CIRCLED LATIN CAPITAL LETTER P
{ 0x24C6, 0x24E0 }, // CIRCLED LATIN CAPITAL LETTER Q
{ 0x24C7, 0x24E1 }, // CIRCLED LATIN CAPITAL LETTER R
{ 0x24C8, 0x24E2 }, // CIRCLED LATIN CAPITAL LETTER S
{ 0x24C9, 0x24E3 }, // CIRCLED LATIN CAPITAL LETTER T
{ 0x24CA, 0x24E4 }, // CIRCLED LATIN CAPITAL LETTER U
{ 0x24CB, 0x24E5 }, // CIRCLED LATIN CAPITAL LETTER V
{ 0x24CC, 0x24E6 }, // CIRCLED LATIN CAPITAL LETTER W
{ 0x24CD, 0x24E7 }, // CIRCLED LATIN CAPITAL LETTER X
{ 0x24CE, 0x24E8 }, // CIRCLED LATIN CAPITAL LETTER Y
{ 0x24CF, 0x24E9 }, // CIRCLED LATIN CAPITAL LETTER Z
{ 0x2C00, 0x2C30 }, // GLAGOLITIC CAPITAL LETTER AZU
{ 0x2C01, 0x2C31 }, // GLAGOLITIC CAPITAL LETTER BUKY
{ 0x2C02, 0x2C32 }, // GLAGOLITIC CAPITAL LETTER VEDE
{ 0x2C03, 0x2C33 }, // GLAGOLITIC CAPITAL LETTER GLAGOLI
{ 0x2C04, 0x2C34 }, // GLAGOLITIC CAPITAL LETTER DOBRO
{ 0x2C05, 0x2C35 }, // GLAGOLITIC CAPITAL LETTER YESTU
{ 0x2C06, 0x2C36 }, // GLAGOLITIC CAPITAL LETTER ZHIVETE
{ 0x2C07, 0x2C37 }, // GLAGOLITIC CAPITAL LETTER DZELO
{ 0x2C08, 0x2C38 }, // GLAGOLITIC CAPITAL LETTER ZEMLJA
{ 0x2C09, 0x2C39 }, // GLAGOLITIC CAPITAL LETTER IZHE
{ 0x2C0A, 0x2C3A }, // GLAGOLITIC CAPITAL LETTER INITIAL IZHE
{ 0x2C0B, 0x2C3B }, // GLAGOLITIC CAPITAL LETTER I
{ 0x2C0C, 0x2C3C }, // GLAGOLITIC CAPITAL LETTER DJERVI
{ 0x2C0D, 0x2C3D }, // GLAGOLITIC CAPITAL LETTER KAKO
{ 0x2C0E, 0x2C3E }, // GLAGOLITIC CAPITAL LETTER LJUDIJE
{ 0x2C0F, 0x2C3F }, // GLAGOLITIC CAPITAL LETTER MYSLITE
{ 0x2C10, 0x2C40 }, // GLAGOLITIC CAPITAL LETTER NASHI
{ 0x2C11, 0x2C41 }, // GLAGOLITIC CAPITAL LETTER ONU
{ 0x2C12, 0x2C42 }, // GLAGOLITIC CAPITAL LETTER POKOJI
{ 0x2C13, 0x2C43 }, // GLAGOLITIC CAPITAL LETTER RITSI
{ 0x2C14, 0x2C44 }, // GLAGOLITIC CAPITAL LETTER SLOVO
{ 0x2C15, 0x2C45 }, // GLAGOLITIC CAPITAL LETTER TVRIDO
{ 0x2C16, 0x2C46 }, // GLAGOLITIC CAPITAL LETTER UKU
{ 0x2C17, 0x2C47 }, // GLAGOLITIC CAPITAL LETTER FRITU
{ 0x2C18, 0x2C48 }, // GLAGOLITIC CAPITAL LETTER HERU
{ 0x2C19, 0x2C49 }, // GLAGOLITIC CAPITAL LETTER OTU
{ 0x2C1A, 0x2C4A }, // GLAGOLITIC CAPITAL LETTER PE
{ 0x2C1B, 0x2C4B }, // GLAGOLITIC CAPITAL LETTER SHTA
{ 0x2C1C, 0x2C4C }, // GLAGOLITIC CAPITAL LETTER TSI
{ 0x2C1D, 0x2C4D }, // GLAGOLITIC CAPITAL LETTER CHRIVI
{ 0x2C1E, 0x2C4E }, // GLAGOLITIC CAPITAL LETTER SHA
{ 0x2C1F, 0x2C4F }, // GLAGOLITIC CAPITAL LETTER YERU
{ 0x2C20, 0x2C50 }, // GLAGOLITIC CAPITAL LETTER YERI
{ 0x2C21, 0x2C51 }, // GLAGOLITIC CAPITAL LETTER YATI
{ 0x2C22, 0x2C52 }, // GLAGOLITIC CAPITAL LETTER SPIDERY HA
{ 0x2C23, 0x2C53 }, // GLAGOLITIC CAPITAL LETTER YU
{ 0x2C24, 0x2C54 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS
{ 0x2C25, 0x2C55 }, // GLAGOLITIC CAPITAL LETTER SMALL YUS WITH TAIL
{ 0x2C26, 0x2C56 }, // GLAGOLITIC CAPITAL LETTER YO
{ 0x2C27, 0x2C57 }, // GLAGOLITIC CAPITAL LETTER IOTATED SMALL YUS
{ 0x2C28, 0x2C58 }, // GLAGOLITIC CAPITAL LETTER BIG YUS
{ 0x2C29, 0x2C59 }, // GLAGOLITIC CAPITAL LETTER IOTATED BIG YUS
{ 0x2C2A, 0x2C5A }, // GLAGOLITIC CAPITAL LETTER FITA
{ 0x2C2B, 0x2C5B }, // GLAGOLITIC CAPITAL LETTER IZHITSA
{ 0x2C2C, 0x2C5C }, // GLAGOLITIC CAPITAL LETTER SHTAPIC
{ 0x2C2D, 0x2C5D }, // GLAGOLITIC CAPITAL LETTER TROKUTASTI A
{ 0x2C2E, 0x2C5E }, // GLAGOLITIC CAPITAL LETTER LATINATE MYSLITE
{ 0x2C60, 0x2C61 }, // LATIN CAPITAL LETTER L WITH DOUBLE BAR
{ 0x2C62, 0x026B }, // LATIN CAPITAL LETTER L WITH MIDDLE TILDE
{ 0x2C63, 0x1D7D }, // LATIN CAPITAL LETTER P WITH STROKE
{ 0x2C64, 0x027D }, // LATIN CAPITAL LETTER R WITH TAIL
{ 0x2C67, 0x2C68 }, // LATIN CAPITAL LETTER H WITH DESCENDER
{ 0x2C69, 0x2C6A }, // LATIN CAPITAL LETTER K WITH DESCENDER
{ 0x2C6B, 0x2C6C }, // LATIN CAPITAL LETTER Z WITH DESCENDER
{ 0x2C6D, 0x0251 }, // LATIN CAPITAL LETTER ALPHA
{ 0x2C6E, 0x0271 }, // LATIN CAPITAL LETTER M WITH HOOK
{ 0x2C6F, 0x0250 }, // LATIN CAPITAL LETTER TURNED A
{ 0x2C70, 0x0252 }, // LATIN CAPITAL LETTER TURNED ALPHA
{ 0x2C72, 0x2C73 }, // LATIN CAPITAL LETTER W WITH HOOK
{ 0x2C75, 0x2C76 }, // LATIN CAPITAL LETTER HALF H
{ 0x2C7E, 0x023F }, // LATIN CAPITAL LETTER S WITH SWASH TAIL
{ 0x2C7F, 0x0240 }, // LATIN CAPITAL LETTER Z WITH SWASH TAIL
{ 0x2C80, 0x2C81 }, // COPTIC CAPITAL LETTER ALFA
{ 0x2C82, 0x2C83 }, // COPTIC CAPITAL LETTER VIDA
{ 0x2C84, 0x2C85 }, // COPTIC CAPITAL LETTER GAMMA
{ 0x2C86, 0x2C87 }, // COPTIC CAPITAL LETTER DALDA
{ 0x2C88, 0x2C89 }, // COPTIC CAPITAL LETTER EIE
{ 0x2C8A, 0x2C8B }, // COPTIC CAPITAL LETTER SOU
{ 0x2C8C, 0x2C8D }, // COPTIC CAPITAL LETTER ZATA
{ 0x2C8E, 0x2C8F }, // COPTIC CAPITAL LETTER HATE
{ 0x2C90, 0x2C91 }, // COPTIC CAPITAL LETTER THETHE
{ 0x2C92, 0x2C93 }, // COPTIC CAPITAL LETTER IAUDA
{ 0x2C94, 0x2C95 }, // COPTIC CAPITAL LETTER KAPA
{ 0x2C96, 0x2C97 }, // COPTIC CAPITAL LETTER LAULA
{ 0x2C98, 0x2C99 }, // COPTIC CAPITAL LETTER MI
{ 0x2C9A, 0x2C9B }, // COPTIC CAPITAL LETTER NI
{ 0x2C9C, 0x2C9D }, // COPTIC CAPITAL LETTER KSI
{ 0x2C9E, 0x2C9F }, // COPTIC CAPITAL LETTER O
{ 0x2CA0, 0x2CA1 }, // COPTIC CAPITAL LETTER PI
{ 0x2CA2, 0x2CA3 }, // COPTIC CAPITAL LETTER RO
{ 0x2CA4, 0x2CA5 }, // COPTIC CAPITAL LETTER SIMA
{ 0x2CA6, 0x2CA7 }, // COPTIC CAPITAL LETTER TAU
{ 0x2CA8, 0x2CA9 }, // COPTIC CAPITAL LETTER UA
{ 0x2CAA, 0x2CAB }, // COPTIC CAPITAL LETTER FI
{ 0x2CAC, 0x2CAD }, // COPTIC CAPITAL LETTER KHI
{ 0x2CAE, 0x2CAF }, // COPTIC CAPITAL LETTER PSI
{ 0x2CB0, 0x2CB1 }, // COPTIC CAPITAL LETTER OOU
{ 0x2CB2, 0x2CB3 }, // COPTIC CAPITAL LETTER DIALECT-P ALEF
{ 0x2CB4, 0x2CB5 }, // COPTIC CAPITAL LETTER OLD COPTIC AIN
{ 0x2CB6, 0x2CB7 }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC EIE
{ 0x2CB8, 0x2CB9 }, // COPTIC CAPITAL LETTER DIALECT-P KAPA
{ 0x2CBA, 0x2CBB }, // COPTIC CAPITAL LETTER DIALECT-P NI
{ 0x2CBC, 0x2CBD }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC NI
{ 0x2CBE, 0x2CBF }, // COPTIC CAPITAL LETTER OLD COPTIC OOU
{ 0x2CC0, 0x2CC1 }, // COPTIC CAPITAL LETTER SAMPI
{ 0x2CC2, 0x2CC3 }, // COPTIC CAPITAL LETTER CROSSED SHEI
{ 0x2CC4, 0x2CC5 }, // COPTIC CAPITAL LETTER OLD COPTIC SHEI
{ 0x2CC6, 0x2CC7 }, // COPTIC CAPITAL LETTER OLD COPTIC ESH
{ 0x2CC8, 0x2CC9 }, // COPTIC CAPITAL LETTER AKHMIMIC KHEI
{ 0x2CCA, 0x2CCB }, // COPTIC CAPITAL LETTER DIALECT-P HORI
{ 0x2CCC, 0x2CCD }, // COPTIC CAPITAL LETTER OLD COPTIC HORI
{ 0x2CCE, 0x2CCF }, // COPTIC CAPITAL LETTER OLD COPTIC HA
{ 0x2CD0, 0x2CD1 }, // COPTIC CAPITAL LETTER L-SHAPED HA
{ 0x2CD2, 0x2CD3 }, // COPTIC CAPITAL LETTER OLD COPTIC HEI
{ 0x2CD4, 0x2CD5 }, // COPTIC CAPITAL LETTER OLD COPTIC HAT
{ 0x2CD6, 0x2CD7 }, // COPTIC CAPITAL LETTER OLD COPTIC GANGIA
{ 0x2CD8, 0x2CD9 }, // COPTIC CAPITAL LETTER OLD COPTIC DJA
{ 0x2CDA, 0x2CDB }, // COPTIC CAPITAL LETTER OLD COPTIC SHIMA
{ 0x2CDC, 0x2CDD }, // COPTIC CAPITAL LETTER OLD NUBIAN SHIMA
{ 0x2CDE, 0x2CDF }, // COPTIC CAPITAL LETTER OLD NUBIAN NGI
{ 0x2CE0, 0x2CE1 }, // COPTIC CAPITAL LETTER OLD NUBIAN NYI
{ 0x2CE2, 0x2CE3 }, // COPTIC CAPITAL LETTER OLD NUBIAN WAU
{ 0x2CEB, 0x2CEC }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC SHEI
{ 0x2CED, 0x2CEE }, // COPTIC CAPITAL LETTER CRYPTOGRAMMIC GANGIA
{ 0xA640, 0xA641 }, // CYRILLIC CAPITAL LETTER ZEMLYA
{ 0xA642, 0xA643 }, // CYRILLIC CAPITAL LETTER DZELO
{ 0xA644, 0xA645 }, // CYRILLIC CAPITAL LETTER REVERSED DZE
{ 0xA646, 0xA647 }, // CYRILLIC CAPITAL LETTER IOTA
{ 0xA648, 0xA649 }, // CYRILLIC CAPITAL LETTER DJERV
{ 0xA64A, 0xA64B }, // CYRILLIC CAPITAL LETTER MONOGRAPH UK
{ 0xA64C, 0xA64D }, // CYRILLIC CAPITAL LETTER BROAD OMEGA
{ 0xA64E, 0xA64F }, // CYRILLIC CAPITAL LETTER NEUTRAL YER
{ 0xA650, 0xA651 }, // CYRILLIC CAPITAL LETTER YERU WITH BACK YER
{ 0xA652, 0xA653 }, // CYRILLIC CAPITAL LETTER IOTIFIED YAT
{ 0xA654, 0xA655 }, // CYRILLIC CAPITAL LETTER REVERSED YU
{ 0xA656, 0xA657 }, // CYRILLIC CAPITAL LETTER IOTIFIED A
{ 0xA658, 0xA659 }, // CYRILLIC CAPITAL LETTER CLOSED LITTLE YUS
{ 0xA65A, 0xA65B }, // CYRILLIC CAPITAL LETTER BLENDED YUS
{ 0xA65C, 0xA65D }, // CYRILLIC CAPITAL LETTER IOTIFIED CLOSED LITTLE YUS
{ 0xA65E, 0xA65F }, // CYRILLIC CAPITAL LETTER YN
{ 0xA662, 0xA663 }, // CYRILLIC CAPITAL LETTER SOFT DE
{ 0xA664, 0xA665 }, // CYRILLIC CAPITAL LETTER SOFT EL
{ 0xA666, 0xA667 }, // CYRILLIC CAPITAL LETTER SOFT EM
{ 0xA668, 0xA669 }, // CYRILLIC CAPITAL LETTER MONOCULAR O
{ 0xA66A, 0xA66B }, // CYRILLIC CAPITAL LETTER BINOCULAR O
{ 0xA66C, 0xA66D }, // CYRILLIC CAPITAL LETTER DOUBLE MONOCULAR O
{ 0xA680, 0xA681 }, // CYRILLIC CAPITAL LETTER DWE
{ 0xA682, 0xA683 }, // CYRILLIC CAPITAL LETTER DZWE
{ 0xA684, 0xA685 }, // CYRILLIC CAPITAL LETTER ZHWE
{ 0xA686, 0xA687 }, // CYRILLIC CAPITAL LETTER CCHE
{ 0xA688, 0xA689 }, // CYRILLIC CAPITAL LETTER DZZE
{ 0xA68A, 0xA68B }, // CYRILLIC CAPITAL LETTER TE WITH MIDDLE HOOK
{ 0xA68C, 0xA68D }, // CYRILLIC CAPITAL LETTER TWE
{ 0xA68E, 0xA68F }, // CYRILLIC CAPITAL LETTER TSWE
{ 0xA690, 0xA691 }, // CYRILLIC CAPITAL LETTER TSSE
{ 0xA692, 0xA693 }, // CYRILLIC CAPITAL LETTER TCHE
{ 0xA694, 0xA695 }, // CYRILLIC CAPITAL LETTER HWE
{ 0xA696, 0xA697 }, // CYRILLIC CAPITAL LETTER SHWE
{ 0xA722, 0xA723 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL ALEF
{ 0xA724, 0xA725 }, // LATIN CAPITAL LETTER EGYPTOLOGICAL AIN
{ 0xA726, 0xA727 }, // LATIN CAPITAL LETTER HENG
{ 0xA728, 0xA729 }, // LATIN CAPITAL LETTER TZ
{ 0xA72A, 0xA72B }, // LATIN CAPITAL LETTER TRESILLO
{ 0xA72C, 0xA72D }, // LATIN CAPITAL LETTER CUATRILLO
{ 0xA72E, 0xA72F }, // LATIN CAPITAL LETTER CUATRILLO WITH COMMA
{ 0xA732, 0xA733 }, // LATIN CAPITAL LETTER AA
{ 0xA734, 0xA735 }, // LATIN CAPITAL LETTER AO
{ 0xA736, 0xA737 }, // LATIN CAPITAL LETTER AU
{ 0xA738, 0xA739 }, // LATIN CAPITAL LETTER AV
{ 0xA73A, 0xA73B }, // LATIN CAPITAL LETTER AV WITH HORIZONTAL BAR
{ 0xA73C, 0xA73D }, // LATIN CAPITAL LETTER AY
{ 0xA73E, 0xA73F }, // LATIN CAPITAL LETTER REVERSED C WITH DOT
{ 0xA740, 0xA741 }, // LATIN CAPITAL LETTER K WITH STROKE
{ 0xA742, 0xA743 }, // LATIN CAPITAL LETTER K WITH DIAGONAL STROKE
{ 0xA744, 0xA745 }, // LATIN CAPITAL LETTER K WITH STROKE AND DIAGONAL STROKE
{ 0xA746, 0xA747 }, // LATIN CAPITAL LETTER BROKEN L
{ 0xA748, 0xA749 }, // LATIN CAPITAL LETTER L WITH HIGH STROKE
{ 0xA74A, 0xA74B }, // LATIN CAPITAL LETTER O WITH LONG STROKE OVERLAY
{ 0xA74C, 0xA74D }, // LATIN CAPITAL LETTER O WITH LOOP
{ 0xA74E, 0xA74F }, // LATIN CAPITAL LETTER OO
{ 0xA750, 0xA751 }, // LATIN CAPITAL LETTER P WITH STROKE THROUGH DESCENDER
{ 0xA752, 0xA753 }, // LATIN CAPITAL LETTER P WITH FLOURISH
{ 0xA754, 0xA755 }, // LATIN CAPITAL LETTER P WITH SQUIRREL TAIL
{ 0xA756, 0xA757 }, // LATIN CAPITAL LETTER Q WITH STROKE THROUGH DESCENDER
{ 0xA758, 0xA759 }, // LATIN CAPITAL LETTER Q WITH DIAGONAL STROKE
{ 0xA75A, 0xA75B }, // LATIN CAPITAL LETTER R ROTUNDA
{ 0xA75C, 0xA75D }, // LATIN CAPITAL LETTER RUM ROTUNDA
{ 0xA75E, 0xA75F }, // LATIN CAPITAL LETTER V WITH DIAGONAL STROKE
{ 0xA760, 0xA761 }, // LATIN CAPITAL LETTER VY
{ 0xA762, 0xA763 }, // LATIN CAPITAL LETTER VISIGOTHIC Z
{ 0xA764, 0xA765 }, // LATIN CAPITAL LETTER THORN WITH STROKE
{ 0xA766, 0xA767 }, // LATIN CAPITAL LETTER THORN WITH STROKE THROUGH DESCENDER
{ 0xA768, 0xA769 }, // LATIN CAPITAL LETTER VEND
{ 0xA76A, 0xA76B }, // LATIN CAPITAL LETTER ET
{ 0xA76C, 0xA76D }, // LATIN CAPITAL LETTER IS
{ 0xA76E, 0xA76F }, // LATIN CAPITAL LETTER CON
{ 0xA779, 0xA77A }, // LATIN CAPITAL LETTER INSULAR D
{ 0xA77B, 0xA77C }, // LATIN CAPITAL LETTER INSULAR F
{ 0xA77D, 0x1D79 }, // LATIN CAPITAL LETTER INSULAR G
{ 0xA77E, 0xA77F }, // LATIN CAPITAL LETTER TURNED INSULAR G
{ 0xA780, 0xA781 }, // LATIN CAPITAL LETTER TURNED L
{ 0xA782, 0xA783 }, // LATIN CAPITAL LETTER INSULAR R
{ 0xA784, 0xA785 }, // LATIN CAPITAL LETTER INSULAR S
{ 0xA786, 0xA787 }, // LATIN CAPITAL LETTER INSULAR T
{ 0xA78B, 0xA78C }, // LATIN CAPITAL LETTER SALTILLO
{ 0xFF21, 0xFF41 }, // FULLWIDTH LATIN CAPITAL LETTER A
{ 0xFF22, 0xFF42 }, // FULLWIDTH LATIN CAPITAL LETTER B
{ 0xFF23, 0xFF43 }, // FULLWIDTH LATIN CAPITAL LETTER C
{ 0xFF24, 0xFF44 }, // FULLWIDTH LATIN CAPITAL LETTER D
{ 0xFF25, 0xFF45 }, // FULLWIDTH LATIN CAPITAL LETTER E
{ 0xFF26, 0xFF46 }, // FULLWIDTH LATIN CAPITAL LETTER F
{ 0xFF27, 0xFF47 }, // FULLWIDTH LATIN CAPITAL LETTER G
{ 0xFF28, 0xFF48 }, // FULLWIDTH LATIN CAPITAL LETTER H
{ 0xFF29, 0xFF49 }, // FULLWIDTH LATIN CAPITAL LETTER I
{ 0xFF2A, 0xFF4A }, // FULLWIDTH LATIN CAPITAL LETTER J
{ 0xFF2B, 0xFF4B }, // FULLWIDTH LATIN CAPITAL LETTER K
{ 0xFF2C, 0xFF4C }, // FULLWIDTH LATIN CAPITAL LETTER L
{ 0xFF2D, 0xFF4D }, // FULLWIDTH LATIN CAPITAL LETTER M
{ 0xFF2E, 0xFF4E }, // FULLWIDTH LATIN CAPITAL LETTER N
{ 0xFF2F, 0xFF4F }, // FULLWIDTH LATIN CAPITAL LETTER O
{ 0xFF30, 0xFF50 }, // FULLWIDTH LATIN CAPITAL LETTER P
{ 0xFF31, 0xFF51 }, // FULLWIDTH LATIN CAPITAL LETTER Q
{ 0xFF32, 0xFF52 }, // FULLWIDTH LATIN CAPITAL LETTER R
{ 0xFF33, 0xFF53 }, // FULLWIDTH LATIN CAPITAL LETTER S
{ 0xFF34, 0xFF54 }, // FULLWIDTH LATIN CAPITAL LETTER T
{ 0xFF35, 0xFF55 }, // FULLWIDTH LATIN CAPITAL LETTER U
{ 0xFF36, 0xFF56 }, // FULLWIDTH LATIN CAPITAL LETTER V
{ 0xFF37, 0xFF57 }, // FULLWIDTH LATIN CAPITAL LETTER W
{ 0xFF38, 0xFF58 }, // FULLWIDTH LATIN CAPITAL LETTER X
{ 0xFF39, 0xFF59 }, // FULLWIDTH LATIN CAPITAL LETTER Y
{ 0xFF3A, 0xFF5A } // FULLWIDTH LATIN CAPITAL LETTER Z
};
static int compare_pair_capital(const void *a, const void *b) {
return (int)(*(unsigned short *)a)
- (int)((struct LatinCapitalSmallPair*)b)->capital;
}
unsigned short latin_tolower(unsigned short c) {
struct LatinCapitalSmallPair *p =
(struct LatinCapitalSmallPair *)bsearch(&c, SORTED_CHAR_MAP,
sizeof(SORTED_CHAR_MAP) / sizeof(SORTED_CHAR_MAP[0]),
sizeof(SORTED_CHAR_MAP[0]),
compare_pair_capital);
return p ? p->small : c;
}
} // namespace latinime
| C++ |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_DICTIONARY_H
#define LATINIME_DICTIONARY_H
namespace latinime {
// 22-bit address = ~4MB dictionary size limit, which on average would be about 200k-300k words
#define ADDRESS_MASK 0x3FFFFF
// The bit that decides if an address follows in the next 22 bits
#define FLAG_ADDRESS_MASK 0x40
// The bit that decides if this is a terminal node for a word. The node could still have children,
// if the word has other endings.
#define FLAG_TERMINAL_MASK 0x80
#define FLAG_BIGRAM_READ 0x80
#define FLAG_BIGRAM_CHILDEXIST 0x40
#define FLAG_BIGRAM_CONTINUED 0x80
#define FLAG_BIGRAM_FREQ 0x7F
class Dictionary {
public:
Dictionary(void *dict, int typedLetterMultipler, int fullWordMultiplier, int dictSize);
int getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize);
int getBigrams(unsigned short *word, int length, int *codes, int codesSize,
unsigned short *outWords, int *frequencies, int maxWordLength, int maxBigrams,
int maxAlternatives);
bool isValidWord(unsigned short *word, int length);
void setAsset(void *asset) { mAsset = asset; }
void *getAsset() { return mAsset; }
~Dictionary();
private:
void getVersionNumber();
bool checkIfDictVersionIsLatest();
int getAddress(int *pos);
int getBigramAddress(int *pos, bool advance);
int getFreq(int *pos);
int getBigramFreq(int *pos);
void searchForTerminalNode(int address, int frequency);
bool getFirstBitOfByte(int *pos) { return (mDict[*pos] & 0x80) > 0; }
bool getSecondBitOfByte(int *pos) { return (mDict[*pos] & 0x40) > 0; }
bool getTerminal(int *pos) { return (mDict[*pos] & FLAG_TERMINAL_MASK) > 0; }
int getCount(int *pos) { return mDict[(*pos)++] & 0xFF; }
unsigned short getChar(int *pos);
int wideStrLen(unsigned short *str);
bool sameAsTyped(unsigned short *word, int length);
bool checkFirstCharacter(unsigned short *word);
bool addWord(unsigned short *word, int length, int frequency);
bool addWordBigram(unsigned short *word, int length, int frequency);
unsigned short toLowerCase(unsigned short c);
void getWordsRec(int pos, int depth, int maxDepth, bool completion, int frequency,
int inputIndex, int diffs);
int isValidWordRec(int pos, unsigned short *word, int offset, int length);
void registerNextLetter(unsigned short c);
unsigned char *mDict;
void *mAsset;
int *mFrequencies;
int *mBigramFreq;
int mMaxWords;
int mMaxBigrams;
int mMaxWordLength;
unsigned short *mOutputChars;
unsigned short *mBigramChars;
int *mInputCodes;
int mInputLength;
int mMaxAlternatives;
unsigned short mWord[128];
int mSkipPos;
int mMaxEditDistance;
int mFullWordMultiplier;
int mTypedLetterMultiplier;
int mDictSize;
int *mNextLettersFrequencies;
int mNextLettersSize;
int mVersion;
int mBigram;
};
// ----------------------------------------------------------------------------
}; // namespace latinime
#endif // LATINIME_DICTIONARY_H
| C++ |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LATINIME_CHAR_UTILS_H
#define LATINIME_CHAR_UTILS_H
namespace latinime {
unsigned short latin_tolower(unsigned short c);
}; // namespace latinime
#endif // LATINIME_CHAR_UTILS_H
| C++ |
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
//#define LOG_TAG "dictionary.cpp"
//#include <cutils/log.h>
#define LOGI
#include "dictionary.h"
#include "basechars.h"
#include "char_utils.h"
#define DEBUG_DICT 0
#define DICTIONARY_VERSION_MIN 200
#define DICTIONARY_HEADER_SIZE 2
#define NOT_VALID_WORD -99
namespace latinime {
Dictionary::Dictionary(void *dict, int typedLetterMultiplier, int fullWordMultiplier, int size)
{
mDict = (unsigned char*) dict;
mTypedLetterMultiplier = typedLetterMultiplier;
mFullWordMultiplier = fullWordMultiplier;
mDictSize = size;
getVersionNumber();
}
Dictionary::~Dictionary()
{
}
int Dictionary::getSuggestions(int *codes, int codesSize, unsigned short *outWords, int *frequencies,
int maxWordLength, int maxWords, int maxAlternatives, int skipPos,
int *nextLetters, int nextLettersSize)
{
int suggWords;
mFrequencies = frequencies;
mOutputChars = outWords;
mInputCodes = codes;
mInputLength = codesSize;
mMaxAlternatives = maxAlternatives;
mMaxWordLength = maxWordLength;
mMaxWords = maxWords;
mSkipPos = skipPos;
mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
mNextLettersFrequencies = nextLetters;
mNextLettersSize = nextLettersSize;
if (checkIfDictVersionIsLatest()) {
getWordsRec(DICTIONARY_HEADER_SIZE, 0, mInputLength * 3, false, 1, 0, 0);
} else {
getWordsRec(0, 0, mInputLength * 3, false, 1, 0, 0);
}
// Get the word count
suggWords = 0;
while (suggWords < mMaxWords && mFrequencies[suggWords] > 0) suggWords++;
if (DEBUG_DICT) LOGI("Returning %d words", suggWords);
if (DEBUG_DICT) {
LOGI("Next letters: ");
for (int k = 0; k < nextLettersSize; k++) {
if (mNextLettersFrequencies[k] > 0) {
LOGI("%c = %d,", k, mNextLettersFrequencies[k]);
}
}
LOGI("\n");
}
return suggWords;
}
void
Dictionary::registerNextLetter(unsigned short c)
{
if (c < mNextLettersSize) {
mNextLettersFrequencies[c]++;
}
}
void
Dictionary::getVersionNumber()
{
mVersion = (mDict[0] & 0xFF);
mBigram = (mDict[1] & 0xFF);
LOGI("IN NATIVE SUGGEST Version: %d Bigram : %d \n", mVersion, mBigram);
}
// Checks whether it has the latest dictionary or the old dictionary
bool
Dictionary::checkIfDictVersionIsLatest()
{
return (mVersion >= DICTIONARY_VERSION_MIN) && (mBigram == 1 || mBigram == 0);
}
unsigned short
Dictionary::getChar(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
unsigned short ch = (unsigned short) (mDict[(*pos)++] & 0xFF);
// If the code is 255, then actual 16 bit code follows (in big endian)
if (ch == 0xFF) {
ch = ((mDict[*pos] & 0xFF) << 8) | (mDict[*pos + 1] & 0xFF);
(*pos) += 2;
}
return ch;
}
int
Dictionary::getAddress(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
if ((mDict[*pos] & FLAG_ADDRESS_MASK) == 0) {
*pos += 1;
} else {
address += (mDict[*pos] & (ADDRESS_MASK >> 16)) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & 0xFF;
if (checkIfDictVersionIsLatest()) {
// skipping bigram
int bigramExist = (mDict[*pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
(*pos) += 3;
nextBigramExist = (mDict[(*pos)++] & FLAG_BIGRAM_CONTINUED);
}
} else {
(*pos)++;
}
}
return freq;
}
int
Dictionary::wideStrLen(unsigned short *str)
{
if (!str) return 0;
unsigned short *end = str;
while (*end)
end++;
return end - str;
}
bool
Dictionary::addWord(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxWords) {
if (frequency > mFrequencies[insertAt]
|| (mFrequencies[insertAt] == frequency
&& length < wideStrLen(mOutputChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
if (insertAt < mMaxWords) {
memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
(char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
(mMaxWords - insertAt - 1) * sizeof(mFrequencies[0]));
mFrequencies[insertAt] = frequency;
memmove((char*) mOutputChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mOutputChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxWords - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mOutputChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
return true;
}
return false;
}
bool
Dictionary::addWordBigram(unsigned short *word, int length, int frequency)
{
word[length] = 0;
if (DEBUG_DICT) {
char s[length + 1];
for (int i = 0; i <= length; i++) s[i] = word[i];
LOGI("Bigram: Found word = %s, freq = %d : \n", s, frequency);
}
// Find the right insertion point
int insertAt = 0;
while (insertAt < mMaxBigrams) {
if (frequency > mBigramFreq[insertAt]
|| (mBigramFreq[insertAt] == frequency
&& length < wideStrLen(mBigramChars + insertAt * mMaxWordLength))) {
break;
}
insertAt++;
}
LOGI("Bigram: InsertAt -> %d maxBigrams: %d\n", insertAt, mMaxBigrams);
if (insertAt < mMaxBigrams) {
memmove((char*) mBigramFreq + (insertAt + 1) * sizeof(mBigramFreq[0]),
(char*) mBigramFreq + insertAt * sizeof(mBigramFreq[0]),
(mMaxBigrams - insertAt - 1) * sizeof(mBigramFreq[0]));
mBigramFreq[insertAt] = frequency;
memmove((char*) mBigramChars + (insertAt + 1) * mMaxWordLength * sizeof(short),
(char*) mBigramChars + (insertAt ) * mMaxWordLength * sizeof(short),
(mMaxBigrams - insertAt - 1) * sizeof(short) * mMaxWordLength);
unsigned short *dest = mBigramChars + (insertAt ) * mMaxWordLength;
while (length--) {
*dest++ = *word++;
}
*dest = 0; // NULL terminate
if (DEBUG_DICT) LOGI("Bigram: Added word at %d\n", insertAt);
return true;
}
return false;
}
unsigned short
Dictionary::toLowerCase(unsigned short c) {
if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
c = BASE_CHARS[c];
}
if (c >='A' && c <= 'Z') {
c |= 32;
} else if (c > 127) {
c = latin_tolower(c);
}
return c;
}
bool
Dictionary::sameAsTyped(unsigned short *word, int length)
{
if (length != mInputLength) {
return false;
}
int *inputCodes = mInputCodes;
while (length--) {
if ((unsigned int) *inputCodes != (unsigned int) *word) {
return false;
}
inputCodes += mMaxAlternatives;
word++;
}
return true;
}
static char QUOTE = '\'';
void
Dictionary::getWordsRec(int pos, int depth, int maxDepth, bool completion, int snr, int inputIndex,
int diffs)
{
// Optimization: Prune out words that are too long compared to how much was typed.
if (depth > maxDepth) {
return;
}
if (diffs > mMaxEditDistance) {
return;
}
int count = getCount(&pos);
int *currentChars = NULL;
if (mInputLength <= inputIndex) {
completion = true;
} else {
currentChars = mInputCodes + (inputIndex * mMaxAlternatives);
}
for (int i = 0; i < count; i++) {
// -- at char
unsigned short c = getChar(&pos);
// -- at flag/add
unsigned short lowerC = toLowerCase(c);
bool terminal = getTerminal(&pos);
int childrenAddress = getAddress(&pos);
// -- after address or flag
int freq = 1;
if (terminal) freq = getFreq(&pos);
// -- after add or freq
// If we are only doing completions, no need to look at the typed characters.
if (completion) {
mWord[depth] = c;
if (terminal) {
addWord(mWord, depth + 1, freq * snr);
if (depth >= mInputLength && mSkipPos < 0) {
registerNextLetter(mWord[mInputLength]);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
completion, snr, inputIndex, diffs);
}
} else if ((c == QUOTE && currentChars[0] != QUOTE) || mSkipPos == depth) {
// Skip the ' or other letter and continue deeper
mWord[depth] = c;
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth, false, snr, inputIndex, diffs);
}
} else {
int j = 0;
while (currentChars[j] > 0) {
if (currentChars[j] == lowerC || currentChars[j] == c) {
int addedWeight = j == 0 ? mTypedLetterMultiplier : 1;
mWord[depth] = c;
if (mInputLength == inputIndex + 1) {
if (terminal) {
if (//INCLUDE_TYPED_WORD_IF_VALID ||
!sameAsTyped(mWord, depth + 1)) {
int finalFreq = freq * snr * addedWeight;
if (mSkipPos < 0) finalFreq *= mFullWordMultiplier;
addWord(mWord, depth + 1, finalFreq);
}
}
if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1,
maxDepth, true, snr * addedWeight, inputIndex + 1,
diffs + (j > 0));
}
} else if (childrenAddress != 0) {
getWordsRec(childrenAddress, depth + 1, maxDepth,
false, snr * addedWeight, inputIndex + 1, diffs + (j > 0));
}
}
j++;
if (mSkipPos >= 0) break;
}
}
}
}
int
Dictionary::getBigramAddress(int *pos, bool advance)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int address = 0;
address += (mDict[*pos] & 0x3F) << 16;
address += (mDict[*pos + 1] & 0xFF) << 8;
address += (mDict[*pos + 2] & 0xFF);
if (advance) {
*pos += 3;
}
if (address < 0 || address >= mDictSize) return 0;
return address;
}
int
Dictionary::getBigramFreq(int *pos)
{
if (*pos < 0 || *pos >= mDictSize) return 0;
int freq = mDict[(*pos)++] & FLAG_BIGRAM_FREQ;
return freq;
}
int
Dictionary::getBigrams(unsigned short *prevWord, int prevWordLength, int *codes, int codesSize,
unsigned short *bigramChars, int *bigramFreq, int maxWordLength, int maxBigrams,
int maxAlternatives)
{
mBigramFreq = bigramFreq;
mBigramChars = bigramChars;
mInputCodes = codes;
mInputLength = codesSize;
mMaxWordLength = maxWordLength;
mMaxBigrams = maxBigrams;
mMaxAlternatives = maxAlternatives;
if (mBigram == 1 && checkIfDictVersionIsLatest()) {
int pos = isValidWordRec(DICTIONARY_HEADER_SIZE, prevWord, 0, prevWordLength);
LOGI("Pos -> %d\n", pos);
if (pos < 0) {
return 0;
}
int bigramCount = 0;
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0 && bigramCount < maxBigrams) {
int bigramAddress = getBigramAddress(&pos, true);
int frequency = (FLAG_BIGRAM_FREQ & mDict[pos]);
// search for all bigrams and store them
searchForTerminalNode(bigramAddress, frequency);
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
bigramCount++;
}
}
return bigramCount;
}
return 0;
}
void
Dictionary::searchForTerminalNode(int addressLookingFor, int frequency)
{
// track word with such address and store it in an array
unsigned short word[mMaxWordLength];
int pos;
int followDownBranchAddress = DICTIONARY_HEADER_SIZE;
bool found = false;
char followingChar = ' ';
int depth = -1;
while(!found) {
bool followDownAddressSearchStop = false;
bool firstAddress = true;
bool haveToSearchAll = true;
if (depth >= 0) {
word[depth] = (unsigned short) followingChar;
}
pos = followDownBranchAddress; // pos start at count
int count = mDict[pos] & 0xFF;
LOGI("count - %d\n",count);
pos++;
for (int i = 0; i < count; i++) {
// pos at data
pos++;
// pos now at flag
if (!getFirstBitOfByte(&pos)) { // non-terminal
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = false;
}
}
}
pos += 3;
} else if (getFirstBitOfByte(&pos)) { // terminal
if (addressLookingFor == (pos-1)) { // found !!
depth++;
word[depth] = (0xFF & mDict[pos-1]);
found = true;
break;
}
if (getSecondBitOfByte(&pos)) { // address + freq (4 byte)
if (!followDownAddressSearchStop) {
int addr = getBigramAddress(&pos, false);
if (addr > addressLookingFor) {
followDownAddressSearchStop = true;
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
} else if (!haveToSearchAll) {
break;
}
} else {
followDownBranchAddress = addr;
followingChar = (char)(0xFF & mDict[pos-1]);
if (firstAddress) {
firstAddress = false;
haveToSearchAll = true;
}
}
}
pos += 4;
} else { // freq only (2 byte)
pos += 2;
}
// skipping bigram
int bigramExist = (mDict[pos] & FLAG_BIGRAM_READ);
if (bigramExist > 0) {
int nextBigramExist = 1;
while (nextBigramExist > 0) {
pos += 3;
nextBigramExist = (mDict[pos++] & FLAG_BIGRAM_CONTINUED);
}
} else {
pos++;
}
}
}
depth++;
if (followDownBranchAddress == 0) {
LOGI("ERROR!!! Cannot find bigram!!");
break;
}
}
if (checkFirstCharacter(word)) {
addWordBigram(word, depth, frequency);
}
}
bool
Dictionary::checkFirstCharacter(unsigned short *word)
{
// Checks whether this word starts with same character or neighboring characters of
// what user typed.
int *inputCodes = mInputCodes;
int maxAlt = mMaxAlternatives;
while (maxAlt > 0) {
if ((unsigned int) *inputCodes == (unsigned int) *word) {
return true;
}
inputCodes++;
maxAlt--;
}
return false;
}
bool
Dictionary::isValidWord(unsigned short *word, int length)
{
if (checkIfDictVersionIsLatest()) {
return (isValidWordRec(DICTIONARY_HEADER_SIZE, word, 0, length) != NOT_VALID_WORD);
} else {
return (isValidWordRec(0, word, 0, length) != NOT_VALID_WORD);
}
}
int
Dictionary::isValidWordRec(int pos, unsigned short *word, int offset, int length) {
// returns address of bigram data of that word
// return -99 if not found
int count = getCount(&pos);
unsigned short currentChar = (unsigned short) word[offset];
for (int j = 0; j < count; j++) {
unsigned short c = getChar(&pos);
int terminal = getTerminal(&pos);
int childPos = getAddress(&pos);
if (c == currentChar) {
if (offset == length - 1) {
if (terminal) {
return (pos+1);
}
} else {
if (childPos != 0) {
int t = isValidWordRec(childPos, word, offset + 1, length);
if (t > 0) {
return t;
}
}
}
}
if (terminal) {
getFreq(&pos);
}
// There could be two instances of each alphabet - upper and lower case. So continue
// looking ...
}
return NOT_VALID_WORD;
}
} // namespace latinime
| C++ |
/*
**
** Copyright 2009, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <jni.h>
#include "dictionary.h"
// ----------------------------------------------------------------------------
using namespace latinime;
//
// helper function to throw an exception
//
static void throwException(JNIEnv *env, const char* ex, const char* fmt, int data)
{
if (jclass cls = env->FindClass(ex)) {
char msg[1000];
sprintf(msg, fmt, data);
env->ThrowNew(cls, msg);
env->DeleteLocalRef(cls);
}
}
static jint latinime_BinaryDictionary_open
(JNIEnv *env, jobject object, jobject dictDirectBuffer,
jint typedLetterMultiplier, jint fullWordMultiplier, jint size)
{
void *dict = env->GetDirectBufferAddress(dictDirectBuffer);
if (dict == NULL) {
fprintf(stderr, "DICT: Dictionary buffer is null\n");
return 0;
}
Dictionary *dictionary = new Dictionary(dict, typedLetterMultiplier, fullWordMultiplier, size);
return (jint) dictionary;
}
static int latinime_BinaryDictionary_getSuggestions(
JNIEnv *env, jobject object, jint dict, jintArray inputArray, jint arraySize,
jcharArray outputArray, jintArray frequencyArray, jint maxWordLength, jint maxWords,
jint maxAlternatives, jint skipPos, jintArray nextLettersArray, jint nextLettersSize)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *nextLetters = nextLettersArray != NULL ? env->GetIntArrayElements(nextLettersArray, NULL)
: NULL;
int count = dictionary->getSuggestions(inputCodes, arraySize, (unsigned short*) outputChars,
frequencies, maxWordLength, maxWords, maxAlternatives, skipPos, nextLetters,
nextLettersSize);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
if (nextLetters) {
env->ReleaseIntArrayElements(nextLettersArray, nextLetters, 0);
}
return count;
}
static int latinime_BinaryDictionary_getBigrams
(JNIEnv *env, jobject object, jint dict, jcharArray prevWordArray, jint prevWordLength,
jintArray inputArray, jint inputArraySize, jcharArray outputArray,
jintArray frequencyArray, jint maxWordLength, jint maxBigrams, jint maxAlternatives)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return 0;
jchar *prevWord = env->GetCharArrayElements(prevWordArray, NULL);
int *inputCodes = env->GetIntArrayElements(inputArray, NULL);
jchar *outputChars = env->GetCharArrayElements(outputArray, NULL);
int *frequencies = env->GetIntArrayElements(frequencyArray, NULL);
int count = dictionary->getBigrams((unsigned short*) prevWord, prevWordLength, inputCodes,
inputArraySize, (unsigned short*) outputChars, frequencies, maxWordLength, maxBigrams,
maxAlternatives);
env->ReleaseCharArrayElements(prevWordArray, prevWord, JNI_ABORT);
env->ReleaseIntArrayElements(inputArray, inputCodes, JNI_ABORT);
env->ReleaseCharArrayElements(outputArray, outputChars, 0);
env->ReleaseIntArrayElements(frequencyArray, frequencies, 0);
return count;
}
static jboolean latinime_BinaryDictionary_isValidWord
(JNIEnv *env, jobject object, jint dict, jcharArray wordArray, jint wordLength)
{
Dictionary *dictionary = (Dictionary*) dict;
if (dictionary == NULL) return (jboolean) false;
jchar *word = env->GetCharArrayElements(wordArray, NULL);
jboolean result = dictionary->isValidWord((unsigned short*) word, wordLength);
env->ReleaseCharArrayElements(wordArray, word, JNI_ABORT);
return result;
}
static void latinime_BinaryDictionary_close
(JNIEnv *env, jobject object, jint dict)
{
Dictionary *dictionary = (Dictionary*) dict;
delete (Dictionary*) dict;
}
// ----------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
{"openNative", "(Ljava/nio/ByteBuffer;III)I",
(void*)latinime_BinaryDictionary_open},
{"closeNative", "(I)V", (void*)latinime_BinaryDictionary_close},
{"getSuggestionsNative", "(I[II[C[IIIII[II)I", (void*)latinime_BinaryDictionary_getSuggestions},
{"isValidWordNative", "(I[CI)Z", (void*)latinime_BinaryDictionary_isValidWord},
{"getBigramsNative", "(I[CI[II[C[IIII)I", (void*)latinime_BinaryDictionary_getBigrams}
};
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
fprintf(stderr,
"Native registration unable to find class '%s'\n", className);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
fprintf(stderr, "RegisterNatives failed for '%s'\n", className);
return JNI_FALSE;
}
return JNI_TRUE;
}
static int registerNatives(JNIEnv *env)
{
const char* const kClassPathName = "org/pocketworkstation/pckeyboard/BinaryDictionary";
return registerNativeMethods(env,
kClassPathName, gMethods, sizeof(gMethods) / sizeof(gMethods[0]));
}
/*
* Returns the JNI version on success, -1 on failure.
*/
jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
fprintf(stderr, "ERROR: GetEnv failed\n");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
fprintf(stderr, "ERROR: BinaryDictionary native registration failed\n");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
| C++ |
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
#include <QStringList>
#include <QDir>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
}
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> infoList;
#ifdef Q_OS_LINUX
QStringList portNamePrefixes, portNameList;
portNamePrefixes << "ttyS*"; // list normal serial ports first
QDir dir("/dev");
portNameList = dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);
// remove the values which are not serial ports for e.g. /dev/ttysa
for (int i = 0; i < portNameList.size(); i++) {
bool ok;
QString current = portNameList.at(i);
// remove the ttyS part, and check, if the other part is a number
current.remove(0,4).toInt(&ok, 10);
if (!ok) {
portNameList.removeAt(i);
i--;
}
}
// get the non standard serial ports names
// (USB-serial, bluetooth-serial, 18F PICs, and so on)
// if you know an other name prefix for serial ports please let us know
portNamePrefixes.clear();
portNamePrefixes << "ttyACM*" << "ttyUSB*" << "rfcomm*";
portNameList.append(dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name));
foreach (QString str , portNameList) {
QextPortInfo inf;
inf.physName = "/dev/"+str;
inf.portName = str;
if (str.contains("ttyS")) {
inf.friendName = "Serial port "+str.remove(0, 4);
}
else if (str.contains("ttyUSB")) {
inf.friendName = "USB-serial adapter "+str.remove(0, 6);
}
else if (str.contains("rfcomm")) {
inf.friendName = "Bluetooth-serial adapter "+str.remove(0, 6);
}
inf.enumName = "/dev"; // is there a more helpful name for this?
infoList.append(inf);
}
#else
qCritical("Enumeration for POSIX systems (except Linux) is not implemented yet.");
#endif
return infoList;
}
void QextSerialEnumerator::setUpNotifications( )
{
qCritical("Notifications for *Nix/FreeBSD are not implemented yet");
}
| C++ |
#ifndef _QEXTSERIALPORT_H_
#define _QEXTSERIALPORT_H_
#include "qextserialport_global.h"
/*if all warning messages are turned off, flag portability warnings to be turned off as well*/
#ifdef _TTY_NOWARN_
#define _TTY_NOWARN_PORT_
#endif
/*macros for warning and debug messages*/
#ifdef _TTY_NOWARN_PORT_
#define TTY_PORTABILITY_WARNING(s)
#else
#define TTY_PORTABILITY_WARNING(s) qWarning(s)
#endif /*_TTY_NOWARN_PORT_*/
#ifdef _TTY_NOWARN_
#define TTY_WARNING(s)
#else
#define TTY_WARNING(s) qWarning(s)
#endif /*_TTY_NOWARN_*/
/*line status constants*/
#define LS_CTS 0x01
#define LS_DSR 0x02
#define LS_DCD 0x04
#define LS_RI 0x08
#define LS_RTS 0x10
#define LS_DTR 0x20
#define LS_ST 0x40
#define LS_SR 0x80
/*error constants*/
#define E_NO_ERROR 0
#define E_INVALID_FD 1
#define E_NO_MEMORY 2
#define E_CAUGHT_NON_BLOCKED_SIGNAL 3
#define E_PORT_TIMEOUT 4
#define E_INVALID_DEVICE 5
#define E_BREAK_CONDITION 6
#define E_FRAMING_ERROR 7
#define E_IO_ERROR 8
#define E_BUFFER_OVERRUN 9
#define E_RECEIVE_OVERFLOW 10
#define E_RECEIVE_PARITY_ERROR 11
#define E_TRANSMIT_OVERFLOW 12
#define E_READ_FAILED 13
#define E_WRITE_FAILED 14
#define E_FILE_NOT_FOUND 15
enum BaudRateType
{
BAUD50, //POSIX ONLY
BAUD75, //POSIX ONLY
BAUD110,
BAUD134, //POSIX ONLY
BAUD150, //POSIX ONLY
BAUD200, //POSIX ONLY
BAUD300,
BAUD600,
BAUD1200,
BAUD1800, //POSIX ONLY
BAUD2400,
BAUD4800,
BAUD9600,
BAUD14400, //WINDOWS ONLY
BAUD19200,
BAUD38400,
BAUD56000, //WINDOWS ONLY
BAUD57600,
BAUD76800, //POSIX ONLY
BAUD115200,
BAUD128000, //WINDOWS ONLY
BAUD256000 //WINDOWS ONLY
};
enum DataBitsType
{
DATA_5,
DATA_6,
DATA_7,
DATA_8
};
enum ParityType
{
PAR_NONE,
PAR_ODD,
PAR_EVEN,
PAR_MARK, //WINDOWS ONLY
PAR_SPACE
};
enum StopBitsType
{
STOP_1,
STOP_1_5, //WINDOWS ONLY
STOP_2
};
enum FlowType
{
FLOW_OFF,
FLOW_HARDWARE,
FLOW_XONXOFF
};
/**
* structure to contain port settings
*/
struct PortSettings
{
BaudRateType BaudRate;
DataBitsType DataBits;
ParityType Parity;
StopBitsType StopBits;
FlowType FlowControl;
long Timeout_Millisec;
};
#include <QIODevice>
#include <QMutex>
#ifdef Q_OS_UNIX
#include <stdio.h>
#include <termios.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <QSocketNotifier>
#elif (defined Q_OS_WIN)
#include <windows.h>
#include <QThread>
#include <QReadWriteLock>
#include <QtCore/private/qwineventnotifier_p.h>
#endif
/*!
Encapsulates a serial port on both POSIX and Windows systems.
\note
Be sure to check the full list of members, as QIODevice provides quite a lot of
functionality for QextSerialPort.
\section Usage
QextSerialPort offers both a polling and event driven API. Event driven is typically easier
to use, since you never have to worry about checking for new data.
\b Example
\code
QextSerialPort* port = new QextSerialPort("COM1", QextSerialPort::EventDriven);
connect(port, SIGNAL(readyRead()), myClass, SLOT(onDataAvailable()));
port->open();
void MyClass::onDataAvailable() {
int avail = port->bytesAvailable();
if( avail > 0 ) {
QByteArray usbdata;
usbdata.resize(avail);
int read = port->read(usbdata.data(), usbdata.size());
if( read > 0 ) {
processNewData(usbdata);
}
}
}
\endcode
\section Compatibility
The user will be notified of errors and possible portability conflicts at run-time
by default - this behavior can be turned off by defining _TTY_NOWARN_
(to turn off all warnings) or _TTY_NOWARN_PORT_ (to turn off portability warnings) in the project.
On Windows NT/2000/XP this class uses Win32 serial port functions by default. The user may
select POSIX behavior under NT, 2000, or XP ONLY by defining Q_OS_UNIX in the project.
No guarantees are made as to the quality of POSIX support under NT/2000 however.
\author Stefan Sander, Michal Policht, Brandon Fosdick, Liam Staskawicz
*/
class QEXTSERIALPORT_EXPORT QextSerialPort: public QIODevice
{
Q_OBJECT
public:
enum QueryMode {
Polling,
EventDriven
};
QextSerialPort(QueryMode mode = EventDriven);
QextSerialPort(const QString & name, QueryMode mode = EventDriven);
QextSerialPort(PortSettings const& s, QueryMode mode = EventDriven);
QextSerialPort(const QString & name, PortSettings const& s, QueryMode mode = EventDriven);
~QextSerialPort();
void setPortName(const QString & name);
QString portName() const;
/**!
* Get query mode.
* \return query mode.
*/
inline QueryMode queryMode() const { return _queryMode; }
/*!
* Set desired serial communication handling style. You may choose from polling
* or event driven approach. This function does nothing when port is open; to
* apply changes port must be reopened.
*
* In event driven approach read() and write() functions are acting
* asynchronously. They return immediately and the operation is performed in
* the background, so they doesn't freeze the calling thread.
* To determine when operation is finished, QextSerialPort runs separate thread
* and monitors serial port events. Whenever the event occurs, adequate signal
* is emitted.
*
* When polling is set, read() and write() are acting synchronously. Signals are
* not working in this mode and some functions may not be available. The advantage
* of polling is that it generates less overhead due to lack of signals emissions
* and it doesn't start separate thread to monitor events.
*
* Generally event driven approach is more capable and friendly, although some
* applications may need as low overhead as possible and then polling comes.
*
* \param mode query mode.
*/
void setQueryMode(QueryMode mode);
void setBaudRate(BaudRateType);
BaudRateType baudRate() const;
void setDataBits(DataBitsType);
DataBitsType dataBits() const;
void setParity(ParityType);
ParityType parity() const;
void setStopBits(StopBitsType);
StopBitsType stopBits() const;
void setFlowControl(FlowType);
FlowType flowControl() const;
void setTimeout(long);
bool open(OpenMode mode);
bool isSequential() const;
void close();
void flush();
qint64 size() const;
qint64 bytesAvailable() const;
QByteArray readAll();
void ungetChar(char c);
ulong lastError() const;
void translateError(ulong error);
void setDtr(bool set=true);
void setRts(bool set=true);
ulong lineStatus();
QString errorString();
#ifdef Q_OS_WIN
virtual bool waitForReadyRead(int msecs); ///< @todo implement.
virtual qint64 bytesToWrite() const;
static QString fullPortNameWin(const QString & name);
#endif
protected:
QMutex* mutex;
QString port;
PortSettings Settings;
ulong lastErr;
QueryMode _queryMode;
// platform specific members
#ifdef Q_OS_UNIX
int fd;
QSocketNotifier *readNotifier;
struct termios Posix_CommConfig;
struct termios old_termios;
struct timeval Posix_Timeout;
struct timeval Posix_Copy_Timeout;
#elif (defined Q_OS_WIN)
HANDLE Win_Handle;
OVERLAPPED overlap;
COMMCONFIG Win_CommConfig;
COMMTIMEOUTS Win_CommTimeouts;
QWinEventNotifier *winEventNotifier;
DWORD eventMask;
QList<OVERLAPPED*> pendingWrites;
QReadWriteLock* bytesToWriteLock;
qint64 _bytesToWrite;
#endif
void construct(); // common construction
void platformSpecificDestruct();
void platformSpecificInit();
qint64 readData(char * data, qint64 maxSize);
qint64 writeData(const char * data, qint64 maxSize);
#ifdef Q_OS_WIN
private slots:
void onWinEvent(HANDLE h);
#endif
private:
Q_DISABLE_COPY(QextSerialPort)
signals:
// /**
// * This signal is emitted whenever port settings are updated.
// * \param valid \p true if settings are valid, \p false otherwise.
// *
// * @todo implement.
// */
// // void validSettings(bool valid);
/*!
* This signal is emitted whenever dsr line has changed its state. You may
* use this signal to check if device is connected.
* \param status \p true when DSR signal is on, \p false otherwise.
*
* \see lineStatus().
*/
void dsrChanged(bool status);
};
#endif
| C++ |
#include <stdio.h>
#include "qextserialport.h"
/*!
Default constructor. Note that the name of the device used by a QextSerialPort constructed with
this constructor will be determined by #defined constants, or lack thereof - the default behavior
is the same as _TTY_LINUX_. Possible naming conventions and their associated constants are:
\verbatim
Constant Used By Naming Convention
---------- ------------- ------------------------
Q_OS_WIN Windows COM1, COM2
_TTY_IRIX_ SGI/IRIX /dev/ttyf1, /dev/ttyf2
_TTY_HPUX_ HP-UX /dev/tty1p0, /dev/tty2p0
_TTY_SUN_ SunOS/Solaris /dev/ttya, /dev/ttyb
_TTY_DIGITAL_ Digital UNIX /dev/tty01, /dev/tty02
_TTY_FREEBSD_ FreeBSD /dev/ttyd0, /dev/ttyd1
_TTY_OPENBSD_ OpenBSD /dev/tty00, /dev/tty01
_TTY_LINUX_ Linux /dev/ttyS0, /dev/ttyS1
<none> Linux /dev/ttyS0, /dev/ttyS1
\endverbatim
This constructor assigns the device name to the name of the first port on the specified system.
See the other constructors if you need to open a different port.
*/
QextSerialPort::QextSerialPort(QextSerialPort::QueryMode mode)
: QIODevice()
{
#ifdef Q_OS_WIN
setPortName("COM1");
#elif defined(_TTY_IRIX_)
setPortName("/dev/ttyf1");
#elif defined(_TTY_HPUX_)
setPortName("/dev/tty1p0");
#elif defined(_TTY_SUN_)
setPortName("/dev/ttya");
#elif defined(_TTY_DIGITAL_)
setPortName("/dev/tty01");
#elif defined(_TTY_FREEBSD_)
setPortName("/dev/ttyd1");
#elif defined(_TTY_OPENBSD_)
setPortName("/dev/tty00");
#else
setPortName("/dev/ttyS0");
#endif
construct();
setQueryMode(mode);
platformSpecificInit();
}
/*!
Constructs a serial port attached to the port specified by name.
name is the name of the device, which is windowsystem-specific,
e.g."COM1" or "/dev/ttyS0".
*/
QextSerialPort::QextSerialPort(const QString & name, QextSerialPort::QueryMode mode)
: QIODevice()
{
construct();
setQueryMode(mode);
setPortName(name);
platformSpecificInit();
}
/*!
Constructs a port with default name and specified settings.
*/
QextSerialPort::QextSerialPort(const PortSettings& settings, QextSerialPort::QueryMode mode)
: QIODevice()
{
construct();
setBaudRate(settings.BaudRate);
setDataBits(settings.DataBits);
setParity(settings.Parity);
setStopBits(settings.StopBits);
setFlowControl(settings.FlowControl);
setTimeout(settings.Timeout_Millisec);
setQueryMode(mode);
platformSpecificInit();
}
/*!
Constructs a port with specified name and settings.
*/
QextSerialPort::QextSerialPort(const QString & name, const PortSettings& settings, QextSerialPort::QueryMode mode)
: QIODevice()
{
construct();
setPortName(name);
setBaudRate(settings.BaudRate);
setDataBits(settings.DataBits);
setParity(settings.Parity);
setStopBits(settings.StopBits);
setFlowControl(settings.FlowControl);
setTimeout(settings.Timeout_Millisec);
setQueryMode(mode);
platformSpecificInit();
}
/*!
Common constructor function for setting up default port settings.
(115200 Baud, 8N1, Hardware flow control where supported, otherwise no flow control, and 0 ms timeout).
*/
void QextSerialPort::construct()
{
lastErr = E_NO_ERROR;
Settings.BaudRate=BAUD115200;
Settings.DataBits=DATA_8;
Settings.Parity=PAR_NONE;
Settings.StopBits=STOP_1;
Settings.FlowControl=FLOW_HARDWARE;
Settings.Timeout_Millisec=500;
mutex = new QMutex( QMutex::Recursive );
setOpenMode(QIODevice::NotOpen);
}
void QextSerialPort::setQueryMode(QueryMode mechanism)
{
_queryMode = mechanism;
}
/*!
Sets the name of the device associated with the object, e.g. "COM1", or "/dev/ttyS0".
*/
void QextSerialPort::setPortName(const QString & name)
{
#ifdef Q_OS_WIN
port = fullPortNameWin( name );
#else
port = name;
#endif
}
/*!
Returns the name set by setPortName().
*/
QString QextSerialPort::portName() const
{
return port;
}
/*!
Reads all available data from the device, and returns it as a QByteArray.
This function has no way of reporting errors; returning an empty QByteArray()
can mean either that no data was currently available for reading, or that an error occurred.
*/
QByteArray QextSerialPort::readAll()
{
int avail = this->bytesAvailable();
return (avail > 0) ? this->read(avail) : QByteArray();
}
/*!
Returns the baud rate of the serial port. For a list of possible return values see
the definition of the enum BaudRateType.
*/
BaudRateType QextSerialPort::baudRate(void) const
{
return Settings.BaudRate;
}
/*!
Returns the number of data bits used by the port. For a list of possible values returned by
this function, see the definition of the enum DataBitsType.
*/
DataBitsType QextSerialPort::dataBits() const
{
return Settings.DataBits;
}
/*!
Returns the type of parity used by the port. For a list of possible values returned by
this function, see the definition of the enum ParityType.
*/
ParityType QextSerialPort::parity() const
{
return Settings.Parity;
}
/*!
Returns the number of stop bits used by the port. For a list of possible return values, see
the definition of the enum StopBitsType.
*/
StopBitsType QextSerialPort::stopBits() const
{
return Settings.StopBits;
}
/*!
Returns the type of flow control used by the port. For a list of possible values returned
by this function, see the definition of the enum FlowType.
*/
FlowType QextSerialPort::flowControl() const
{
return Settings.FlowControl;
}
/*!
Returns true if device is sequential, otherwise returns false. Serial port is sequential device
so this function always returns true. Check QIODevice::isSequential() documentation for more
information.
*/
bool QextSerialPort::isSequential() const
{
return true;
}
QString QextSerialPort::errorString()
{
switch(lastErr)
{
case E_NO_ERROR: return "No Error has occurred";
case E_INVALID_FD: return "Invalid file descriptor (port was not opened correctly)";
case E_NO_MEMORY: return "Unable to allocate memory tables (POSIX)";
case E_CAUGHT_NON_BLOCKED_SIGNAL: return "Caught a non-blocked signal (POSIX)";
case E_PORT_TIMEOUT: return "Operation timed out (POSIX)";
case E_INVALID_DEVICE: return "The file opened by the port is not a valid device";
case E_BREAK_CONDITION: return "The port detected a break condition";
case E_FRAMING_ERROR: return "The port detected a framing error (usually caused by incorrect baud rate settings)";
case E_IO_ERROR: return "There was an I/O error while communicating with the port";
case E_BUFFER_OVERRUN: return "Character buffer overrun";
case E_RECEIVE_OVERFLOW: return "Receive buffer overflow";
case E_RECEIVE_PARITY_ERROR: return "The port detected a parity error in the received data";
case E_TRANSMIT_OVERFLOW: return "Transmit buffer overflow";
case E_READ_FAILED: return "General read operation failure";
case E_WRITE_FAILED: return "General write operation failure";
case E_FILE_NOT_FOUND: return "The "+this->portName()+" file doesn't exists";
default: return QString("Unknown error: %1").arg(lastErr);
}
}
/*!
Standard destructor.
*/
QextSerialPort::~QextSerialPort()
{
if (isOpen()) {
close();
}
platformSpecificDestruct();
delete mutex;
}
| C++ |
#include <QMutexLocker>
#include <QDebug>
#include <QRegExp>
#include "qextserialport.h"
void QextSerialPort::platformSpecificInit()
{
Win_Handle=INVALID_HANDLE_VALUE;
ZeroMemory(&overlap, sizeof(OVERLAPPED));
overlap.hEvent = CreateEvent(NULL, true, false, NULL);
winEventNotifier = 0;
bytesToWriteLock = new QReadWriteLock;
_bytesToWrite = 0;
}
/*!
Standard destructor.
*/
void QextSerialPort::platformSpecificDestruct() {
CloseHandle(overlap.hEvent);
delete bytesToWriteLock;
}
QString QextSerialPort::fullPortNameWin(const QString & name)
{
QRegExp rx("^COM(\\d+)");
QString fullName(name);
if(fullName.contains(rx)) {
int portnum = rx.cap(1).toInt();
if(portnum > 9) // COM ports greater than 9 need \\.\ prepended
fullName.prepend("\\\\.\\");
}
return fullName;
}
/*!
Opens a serial port. Note that this function does not specify which device to open. If you need
to open a device by name, see QextSerialPort::open(const char*). This function has no effect
if the port associated with the class is already open. The port is also configured to the current
settings, as stored in the Settings structure.
*/
bool QextSerialPort::open(OpenMode mode) {
unsigned long confSize = sizeof(COMMCONFIG);
Win_CommConfig.dwSize = confSize;
DWORD dwFlagsAndAttributes = 0;
if (queryMode() == QextSerialPort::EventDriven)
dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED;
QMutexLocker lock(mutex);
if (mode == QIODevice::NotOpen)
return isOpen();
if (!isOpen()) {
/*open the port*/
Win_Handle=CreateFileA(port.toAscii(), GENERIC_READ|GENERIC_WRITE,
0, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL);
if (Win_Handle!=INVALID_HANDLE_VALUE) {
QIODevice::open(mode);
/*configure port settings*/
GetCommConfig(Win_Handle, &Win_CommConfig, &confSize);
GetCommState(Win_Handle, &(Win_CommConfig.dcb));
/*set up parameters*/
Win_CommConfig.dcb.fBinary=TRUE;
Win_CommConfig.dcb.fInX=FALSE;
Win_CommConfig.dcb.fOutX=FALSE;
Win_CommConfig.dcb.fAbortOnError=FALSE;
Win_CommConfig.dcb.fNull=FALSE;
setBaudRate(Settings.BaudRate);
setDataBits(Settings.DataBits);
setStopBits(Settings.StopBits);
setParity(Settings.Parity);
setFlowControl(Settings.FlowControl);
setTimeout(Settings.Timeout_Millisec);
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
//init event driven approach
if (queryMode() == QextSerialPort::EventDriven) {
Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
Win_CommTimeouts.ReadTotalTimeoutConstant = 0;
Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0;
Win_CommTimeouts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) {
qWarning() << "failed to set Comm Mask. Error code:", GetLastError();
return false;
}
winEventNotifier = new QWinEventNotifier(overlap.hEvent, this);
connect(winEventNotifier, SIGNAL(activated(HANDLE)), this, SLOT(onWinEvent(HANDLE)));
WaitCommEvent(Win_Handle, &eventMask, &overlap);
}
}
} else {
return false;
}
return isOpen();
}
/*!
Closes a serial port. This function has no effect if the serial port associated with the class
is not currently open.
*/
void QextSerialPort::close()
{
QMutexLocker lock(mutex);
if (isOpen()) {
flush();
QIODevice::close(); // mark ourselves as closed
CancelIo(Win_Handle);
if (CloseHandle(Win_Handle))
Win_Handle = INVALID_HANDLE_VALUE;
if (winEventNotifier)
winEventNotifier->deleteLater();
_bytesToWrite = 0;
foreach(OVERLAPPED* o, pendingWrites) {
CloseHandle(o->hEvent);
delete o;
}
pendingWrites.clear();
}
}
/*!
Flushes all pending I/O to the serial port. This function has no effect if the serial port
associated with the class is not currently open.
*/
void QextSerialPort::flush() {
QMutexLocker lock(mutex);
if (isOpen()) {
FlushFileBuffers(Win_Handle);
}
}
/*!
This function will return the number of bytes waiting in the receive queue of the serial port.
It is included primarily to provide a complete QIODevice interface, and will not record errors
in the lastErr member (because it is const). This function is also not thread-safe - in
multithreading situations, use QextSerialPort::bytesAvailable() instead.
*/
qint64 QextSerialPort::size() const {
int availBytes;
COMSTAT Win_ComStat;
DWORD Win_ErrorMask=0;
ClearCommError(Win_Handle, &Win_ErrorMask, &Win_ComStat);
availBytes = Win_ComStat.cbInQue;
return (qint64)availBytes;
}
/*!
Returns the number of bytes waiting in the port's receive queue. This function will return 0 if
the port is not currently open, or -1 on error.
*/
qint64 QextSerialPort::bytesAvailable() const {
QMutexLocker lock(mutex);
if (isOpen()) {
DWORD Errors;
COMSTAT Status;
if (ClearCommError(Win_Handle, &Errors, &Status)) {
return Status.cbInQue + QIODevice::bytesAvailable();
}
return (qint64)-1;
}
return 0;
}
/*!
Translates a system-specific error code to a QextSerialPort error code. Used internally.
*/
void QextSerialPort::translateError(ulong error) {
if (error&CE_BREAK) {
lastErr=E_BREAK_CONDITION;
}
else if (error&CE_FRAME) {
lastErr=E_FRAMING_ERROR;
}
else if (error&CE_IOE) {
lastErr=E_IO_ERROR;
}
else if (error&CE_MODE) {
lastErr=E_INVALID_FD;
}
else if (error&CE_OVERRUN) {
lastErr=E_BUFFER_OVERRUN;
}
else if (error&CE_RXPARITY) {
lastErr=E_RECEIVE_PARITY_ERROR;
}
else if (error&CE_RXOVER) {
lastErr=E_RECEIVE_OVERFLOW;
}
else if (error&CE_TXFULL) {
lastErr=E_TRANSMIT_OVERFLOW;
}
}
/*!
Reads a block of data from the serial port. This function will read at most maxlen bytes from
the serial port and place them in the buffer pointed to by data. Return value is the number of
bytes actually read, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::readData(char *data, qint64 maxSize)
{
DWORD retVal;
QMutexLocker lock(mutex);
retVal = 0;
if (queryMode() == QextSerialPort::EventDriven) {
OVERLAPPED overlapRead;
ZeroMemory(&overlapRead, sizeof(OVERLAPPED));
if (!ReadFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, & overlapRead)) {
if (GetLastError() == ERROR_IO_PENDING)
GetOverlappedResult(Win_Handle, & overlapRead, & retVal, true);
else {
lastErr = E_READ_FAILED;
retVal = (DWORD)-1;
}
}
} else if (!ReadFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, NULL)) {
lastErr = E_READ_FAILED;
retVal = (DWORD)-1;
}
return (qint64)retVal;
}
/*!
Writes a block of data to the serial port. This function will write len bytes
from the buffer pointed to by data to the serial port. Return value is the number
of bytes actually written, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::writeData(const char *data, qint64 maxSize)
{
QMutexLocker lock( mutex );
DWORD retVal = 0;
if (queryMode() == QextSerialPort::EventDriven) {
OVERLAPPED* newOverlapWrite = new OVERLAPPED;
ZeroMemory(newOverlapWrite, sizeof(OVERLAPPED));
newOverlapWrite->hEvent = CreateEvent(NULL, true, false, NULL);
if (WriteFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, newOverlapWrite)) {
CloseHandle(newOverlapWrite->hEvent);
delete newOverlapWrite;
}
else if (GetLastError() == ERROR_IO_PENDING) {
// writing asynchronously...not an error
QWriteLocker writelocker(bytesToWriteLock);
_bytesToWrite += maxSize;
pendingWrites.append(newOverlapWrite);
}
else {
qDebug() << "serialport write error:" << GetLastError();
lastErr = E_WRITE_FAILED;
retVal = (DWORD)-1;
if(!CancelIo(newOverlapWrite->hEvent))
qDebug() << "serialport: couldn't cancel IO";
if(!CloseHandle(newOverlapWrite->hEvent))
qDebug() << "serialport: couldn't close OVERLAPPED handle";
delete newOverlapWrite;
}
} else if (!WriteFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, NULL)) {
lastErr = E_WRITE_FAILED;
retVal = (DWORD)-1;
}
return (qint64)retVal;
}
/*!
This function is included to implement the full QIODevice interface, and currently has no
purpose within this class. This function is meaningless on an unbuffered device and currently
only prints a warning message to that effect.
*/
void QextSerialPort::ungetChar(char c) {
/*meaningless on unbuffered sequential device - return error and print a warning*/
TTY_WARNING("QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless");
}
/*!
Sets the flow control used by the port. Possible values of flow are:
\verbatim
FLOW_OFF No flow control
FLOW_HARDWARE Hardware (RTS/CTS) flow control
FLOW_XONXOFF Software (XON/XOFF) flow control
\endverbatim
*/
void QextSerialPort::setFlowControl(FlowType flow) {
QMutexLocker lock(mutex);
if (Settings.FlowControl!=flow) {
Settings.FlowControl=flow;
}
if (isOpen()) {
switch(flow) {
/*no flow control*/
case FLOW_OFF:
Win_CommConfig.dcb.fOutxCtsFlow=FALSE;
Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_DISABLE;
Win_CommConfig.dcb.fInX=FALSE;
Win_CommConfig.dcb.fOutX=FALSE;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
/*software (XON/XOFF) flow control*/
case FLOW_XONXOFF:
Win_CommConfig.dcb.fOutxCtsFlow=FALSE;
Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_DISABLE;
Win_CommConfig.dcb.fInX=TRUE;
Win_CommConfig.dcb.fOutX=TRUE;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
case FLOW_HARDWARE:
Win_CommConfig.dcb.fOutxCtsFlow=TRUE;
Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_HANDSHAKE;
Win_CommConfig.dcb.fInX=FALSE;
Win_CommConfig.dcb.fOutX=FALSE;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
}
}
}
/*!
Sets the parity associated with the serial port. The possible values of parity are:
\verbatim
PAR_SPACE Space Parity
PAR_MARK Mark Parity
PAR_NONE No Parity
PAR_EVEN Even Parity
PAR_ODD Odd Parity
\endverbatim
*/
void QextSerialPort::setParity(ParityType parity) {
QMutexLocker lock(mutex);
if (Settings.Parity!=parity) {
Settings.Parity=parity;
}
if (isOpen()) {
Win_CommConfig.dcb.Parity=(unsigned char)parity;
switch (parity) {
/*space parity*/
case PAR_SPACE:
if (Settings.DataBits==DATA_8) {
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Space parity with 8 data bits is not supported by POSIX systems.");
}
Win_CommConfig.dcb.fParity=TRUE;
break;
/*mark parity - WINDOWS ONLY*/
case PAR_MARK:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Mark parity is not supported by POSIX systems");
Win_CommConfig.dcb.fParity=TRUE;
break;
/*no parity*/
case PAR_NONE:
Win_CommConfig.dcb.fParity=FALSE;
break;
/*even parity*/
case PAR_EVEN:
Win_CommConfig.dcb.fParity=TRUE;
break;
/*odd parity*/
case PAR_ODD:
Win_CommConfig.dcb.fParity=TRUE;
break;
}
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
}
/*!
Sets the number of data bits used by the serial port. Possible values of dataBits are:
\verbatim
DATA_5 5 data bits
DATA_6 6 data bits
DATA_7 7 data bits
DATA_8 8 data bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
5 data bits cannot be used with 2 stop bits.
\par
1.5 stop bits can only be used with 5 data bits.
\par
8 data bits cannot be used with space parity on POSIX systems.
*/
void QextSerialPort::setDataBits(DataBitsType dataBits) {
QMutexLocker lock(mutex);
if (Settings.DataBits!=dataBits) {
if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) ||
(Settings.StopBits==STOP_1_5 && dataBits!=DATA_5)) {
}
else {
Settings.DataBits=dataBits;
}
}
if (isOpen()) {
switch(dataBits) {
/*5 data bits*/
case DATA_5:
if (Settings.StopBits==STOP_2) {
TTY_WARNING("QextSerialPort: 5 Data bits cannot be used with 2 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=5;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*6 data bits*/
case DATA_6:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=6;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*7 data bits*/
case DATA_7:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=7;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*8 data bits*/
case DATA_8:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=8;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
}
}
}
/*!
Sets the number of stop bits used by the serial port. Possible values of stopBits are:
\verbatim
STOP_1 1 stop bit
STOP_1_5 1.5 stop bits
STOP_2 2 stop bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
2 stop bits cannot be used with 5 data bits.
\par
1.5 stop bits cannot be used with 6 or more data bits.
\par
POSIX does not support 1.5 stop bits.
*/
void QextSerialPort::setStopBits(StopBitsType stopBits) {
QMutexLocker lock(mutex);
if (Settings.StopBits!=stopBits) {
if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) ||
(stopBits==STOP_1_5 && Settings.DataBits!=DATA_5)) {
}
else {
Settings.StopBits=stopBits;
}
}
if (isOpen()) {
switch (stopBits) {
/*one stop bit*/
case STOP_1:
Win_CommConfig.dcb.StopBits=ONESTOPBIT;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
/*1.5 stop bits*/
case STOP_1_5:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: 1.5 stop bit operation is not supported by POSIX.");
if (Settings.DataBits!=DATA_5) {
TTY_WARNING("QextSerialPort: 1.5 stop bits can only be used with 5 data bits");
}
else {
Win_CommConfig.dcb.StopBits=ONE5STOPBITS;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*two stop bits*/
case STOP_2:
if (Settings.DataBits==DATA_5) {
TTY_WARNING("QextSerialPort: 2 stop bits cannot be used with 5 data bits");
}
else {
Win_CommConfig.dcb.StopBits=TWOSTOPBITS;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
}
}
}
/*!
Sets the baud rate of the serial port. Note that not all rates are applicable on
all platforms. The following table shows translations of the various baud rate
constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an *
are speeds that are usable on both Windows and POSIX.
\verbatim
RATE Windows Speed POSIX Speed
----------- ------------- -----------
BAUD50 110 50
BAUD75 110 75
*BAUD110 110 110
BAUD134 110 134.5
BAUD150 110 150
BAUD200 110 200
*BAUD300 300 300
*BAUD600 600 600
*BAUD1200 1200 1200
BAUD1800 1200 1800
*BAUD2400 2400 2400
*BAUD4800 4800 4800
*BAUD9600 9600 9600
BAUD14400 14400 9600
*BAUD19200 19200 19200
*BAUD38400 38400 38400
BAUD56000 56000 38400
*BAUD57600 57600 57600
BAUD76800 57600 76800
*BAUD115200 115200 115200
BAUD128000 128000 115200
BAUD256000 256000 115200
\endverbatim
*/
void QextSerialPort::setBaudRate(BaudRateType baudRate) {
QMutexLocker lock(mutex);
if (Settings.BaudRate!=baudRate) {
switch (baudRate) {
case BAUD50:
case BAUD75:
case BAUD134:
case BAUD150:
case BAUD200:
Settings.BaudRate=BAUD110;
break;
case BAUD1800:
Settings.BaudRate=BAUD1200;
break;
case BAUD76800:
Settings.BaudRate=BAUD57600;
break;
default:
Settings.BaudRate=baudRate;
break;
}
}
if (isOpen()) {
switch (baudRate) {
/*50 baud*/
case BAUD50:
TTY_WARNING("QextSerialPort: Windows does not support 50 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*75 baud*/
case BAUD75:
TTY_WARNING("QextSerialPort: Windows does not support 75 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*110 baud*/
case BAUD110:
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*134.5 baud*/
case BAUD134:
TTY_WARNING("QextSerialPort: Windows does not support 134.5 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*150 baud*/
case BAUD150:
TTY_WARNING("QextSerialPort: Windows does not support 150 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*200 baud*/
case BAUD200:
TTY_WARNING("QextSerialPort: Windows does not support 200 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*300 baud*/
case BAUD300:
Win_CommConfig.dcb.BaudRate=CBR_300;
break;
/*600 baud*/
case BAUD600:
Win_CommConfig.dcb.BaudRate=CBR_600;
break;
/*1200 baud*/
case BAUD1200:
Win_CommConfig.dcb.BaudRate=CBR_1200;
break;
/*1800 baud*/
case BAUD1800:
TTY_WARNING("QextSerialPort: Windows does not support 1800 baud operation. Switching to 1200 baud.");
Win_CommConfig.dcb.BaudRate=CBR_1200;
break;
/*2400 baud*/
case BAUD2400:
Win_CommConfig.dcb.BaudRate=CBR_2400;
break;
/*4800 baud*/
case BAUD4800:
Win_CommConfig.dcb.BaudRate=CBR_4800;
break;
/*9600 baud*/
case BAUD9600:
Win_CommConfig.dcb.BaudRate=CBR_9600;
break;
/*14400 baud*/
case BAUD14400:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 14400 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_14400;
break;
/*19200 baud*/
case BAUD19200:
Win_CommConfig.dcb.BaudRate=CBR_19200;
break;
/*38400 baud*/
case BAUD38400:
Win_CommConfig.dcb.BaudRate=CBR_38400;
break;
/*56000 baud*/
case BAUD56000:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 56000 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_56000;
break;
/*57600 baud*/
case BAUD57600:
Win_CommConfig.dcb.BaudRate=CBR_57600;
break;
/*76800 baud*/
case BAUD76800:
TTY_WARNING("QextSerialPort: Windows does not support 76800 baud operation. Switching to 57600 baud.");
Win_CommConfig.dcb.BaudRate=CBR_57600;
break;
/*115200 baud*/
case BAUD115200:
Win_CommConfig.dcb.BaudRate=CBR_115200;
break;
/*128000 baud*/
case BAUD128000:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 128000 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_128000;
break;
/*256000 baud*/
case BAUD256000:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 256000 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_256000;
break;
}
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
}
/*!
Sets DTR line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setDtr(bool set) {
QMutexLocker lock(mutex);
if (isOpen()) {
if (set) {
EscapeCommFunction(Win_Handle, SETDTR);
}
else {
EscapeCommFunction(Win_Handle, CLRDTR);
}
}
}
/*!
Sets RTS line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setRts(bool set) {
QMutexLocker lock(mutex);
if (isOpen()) {
if (set) {
EscapeCommFunction(Win_Handle, SETRTS);
}
else {
EscapeCommFunction(Win_Handle, CLRRTS);
}
}
}
/*!
Returns the line status as stored by the port function. This function will retrieve the states
of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines
can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned
long with specific bits indicating which lines are high. The following constants should be used
to examine the states of individual lines:
\verbatim
Mask Line
------ ----
LS_CTS CTS
LS_DSR DSR
LS_DCD DCD
LS_RI RI
\endverbatim
This function will return 0 if the port associated with the class is not currently open.
*/
ulong QextSerialPort::lineStatus(void) {
unsigned long Status=0, Temp=0;
QMutexLocker lock(mutex);
if (isOpen()) {
GetCommModemStatus(Win_Handle, &Temp);
if (Temp&MS_CTS_ON) {
Status|=LS_CTS;
}
if (Temp&MS_DSR_ON) {
Status|=LS_DSR;
}
if (Temp&MS_RING_ON) {
Status|=LS_RI;
}
if (Temp&MS_RLSD_ON) {
Status|=LS_DCD;
}
}
return Status;
}
bool QextSerialPort::waitForReadyRead(int msecs)
{
//@todo implement
return false;
}
qint64 QextSerialPort::bytesToWrite() const
{
QReadLocker rl(bytesToWriteLock);
return _bytesToWrite;
}
/*
Triggered when there's activity on our HANDLE.
*/
void QextSerialPort::onWinEvent(HANDLE h)
{
QMutexLocker lock(mutex);
if(h == overlap.hEvent) {
if (eventMask & EV_RXCHAR) {
if (sender() != this && bytesAvailable() > 0)
emit readyRead();
}
if (eventMask & EV_TXEMPTY) {
/*
A write completed. Run through the list of OVERLAPPED writes, and if
they completed successfully, take them off the list and delete them.
Otherwise, leave them on there so they can finish.
*/
qint64 totalBytesWritten = 0;
QList<OVERLAPPED*> overlapsToDelete;
foreach(OVERLAPPED* o, pendingWrites) {
DWORD numBytes = 0;
if (GetOverlappedResult(Win_Handle, o, & numBytes, false)) {
overlapsToDelete.append(o);
totalBytesWritten += numBytes;
} else if( GetLastError() != ERROR_IO_INCOMPLETE ) {
overlapsToDelete.append(o);
qWarning() << "CommEvent overlapped write error:" << GetLastError();
}
}
if (sender() != this && totalBytesWritten > 0) {
QWriteLocker writelocker(bytesToWriteLock);
emit bytesWritten(totalBytesWritten);
_bytesToWrite = 0;
}
foreach(OVERLAPPED* o, overlapsToDelete) {
OVERLAPPED *toDelete = pendingWrites.takeAt(pendingWrites.indexOf(o));
CloseHandle(toDelete->hEvent);
delete toDelete;
}
}
if (eventMask & EV_DSR) {
if (lineStatus() & LS_DSR)
emit dsrChanged(true);
else
emit dsrChanged(false);
}
}
WaitCommEvent(Win_Handle, &eventMask, &overlap);
}
/*!
Sets the read and write timeouts for the port to millisec milliseconds.
Setting 0 indicates that timeouts are not used for read nor write operations;
however read() and write() functions will still block. Set -1 to provide
non-blocking behaviour (read() and write() will return immediately).
\note this function does nothing in event driven mode.
*/
void QextSerialPort::setTimeout(long millisec) {
QMutexLocker lock(mutex);
Settings.Timeout_Millisec = millisec;
if (millisec == -1) {
Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
Win_CommTimeouts.ReadTotalTimeoutConstant = 0;
} else {
Win_CommTimeouts.ReadIntervalTimeout = millisec;
Win_CommTimeouts.ReadTotalTimeoutConstant = millisec;
}
Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
Win_CommTimeouts.WriteTotalTimeoutMultiplier = millisec;
Win_CommTimeouts.WriteTotalTimeoutConstant = 0;
if (queryMode() != QextSerialPort::EventDriven)
SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
}
| C++ |
/*!
* \file qextserialenumerator.h
* \author Michal Policht
* \see QextSerialEnumerator
*/
#ifndef _QEXTSERIALENUMERATOR_H_
#define _QEXTSERIALENUMERATOR_H_
#include <QString>
#include <QList>
#include <QObject>
#include "qextserialport_global.h"
#ifdef Q_OS_WIN
#include <windows.h>
#include <setupapi.h>
#include <dbt.h>
#endif /*Q_OS_WIN*/
#ifdef Q_OS_MAC
#include <IOKit/usb/IOUSBLib.h>
#endif
/*!
* Structure containing port information.
*/
struct QextPortInfo {
QString portName; ///< Port name.
QString physName; ///< Physical name.
QString friendName; ///< Friendly name.
QString enumName; ///< Enumerator name.
int vendorID; ///< Vendor ID.
int productID; ///< Product ID
};
#ifdef Q_OS_WIN
#ifdef QT_GUI_LIB
#include <QWidget>
class QextSerialEnumerator;
class QextSerialRegistrationWidget : public QWidget
{
Q_OBJECT
public:
QextSerialRegistrationWidget( QextSerialEnumerator* qese ) {
this->qese = qese;
}
~QextSerialRegistrationWidget( ) { }
protected:
QextSerialEnumerator* qese;
bool winEvent( MSG* message, long* result );
};
#endif // QT_GUI_LIB
#endif // Q_OS_WIN
/*!
Provides list of ports available in the system.
\section Usage
To poll the system for a list of connected devices, simply use getPorts(). Each
QextPortInfo structure will populated with information about the corresponding device.
\b Example
\code
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
foreach( QextPortInfo port, ports ) {
// inspect port...
}
\endcode
To enable event-driven notification of device connection events, first call
setUpNotifications() and then connect to the deviceDiscovered() and deviceRemoved()
signals. Event-driven behavior is currently available only on Windows and OS X.
\b Example
\code
QextSerialEnumerator* enumerator = new QextSerialEnumerator();
connect(enumerator, SIGNAL(deviceDiscovered(const QextPortInfo &)),
myClass, SLOT(onDeviceDiscovered(const QextPortInfo &)));
connect(enumerator, SIGNAL(deviceRemoved(const QextPortInfo &)),
myClass, SLOT(onDeviceRemoved(const QextPortInfo &)));
\endcode
\section Credits
Windows implementation is based on Zach Gorman's work from
<a href="http://www.codeproject.com">The Code Project</a> (http://www.codeproject.com/system/setupdi.asp).
OS X implementation, see
http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/AH_Finding_Devices/chapter_4_section_2.html
\author Michal Policht, Liam Staskawicz
*/
class QEXTSERIALPORT_EXPORT QextSerialEnumerator : public QObject
{
Q_OBJECT
public:
QextSerialEnumerator( );
~QextSerialEnumerator( );
#ifdef Q_OS_WIN
LRESULT onDeviceChangeWin( WPARAM wParam, LPARAM lParam );
private:
/*!
* Get value of specified property from the registry.
* \param key handle to an open key.
* \param property property name.
* \return property value.
*/
static QString getRegKeyValue(HKEY key, LPCTSTR property);
/*!
* Get specific property from registry.
* \param devInfo pointer to the device information set that contains the interface
* and its underlying device. Returned by SetupDiGetClassDevs() function.
* \param devData pointer to an SP_DEVINFO_DATA structure that defines the device instance.
* this is returned by SetupDiGetDeviceInterfaceDetail() function.
* \param property registry property. One of defined SPDRP_* constants.
* \return property string.
*/
static QString getDeviceProperty(HDEVINFO devInfo, PSP_DEVINFO_DATA devData, DWORD property);
/*!
* Search for serial ports using setupapi.
* \param infoList list with result.
*/
static void setupAPIScan(QList<QextPortInfo> & infoList);
void setUpNotificationWin( );
static bool getDeviceDetailsWin( QextPortInfo* portInfo, HDEVINFO devInfo,
PSP_DEVINFO_DATA devData, WPARAM wParam = DBT_DEVICEARRIVAL );
static void enumerateDevicesWin( const GUID & guidDev, QList<QextPortInfo>* infoList );
bool matchAndDispatchChangedDevice(const QString & deviceID, const GUID & guid, WPARAM wParam);
#ifdef QT_GUI_LIB
QextSerialRegistrationWidget* notificationWidget;
#endif
#endif /*Q_OS_WIN*/
#ifdef Q_OS_UNIX
#ifdef Q_OS_MAC
private:
/*!
* Search for serial ports using IOKit.
* \param infoList list with result.
*/
static void scanPortsOSX(QList<QextPortInfo> & infoList);
static void iterateServicesOSX(io_object_t service, QList<QextPortInfo> & infoList);
static bool getServiceDetailsOSX( io_object_t service, QextPortInfo* portInfo );
void setUpNotificationOSX( );
void onDeviceDiscoveredOSX( io_object_t service );
void onDeviceTerminatedOSX( io_object_t service );
friend void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
friend void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
IONotificationPortRef notificationPortRef;
#else // Q_OS_MAC
private:
/*!
* Search for serial ports on unix.
* \param infoList list with result.
*/
static void scanPortsNix(QList<QextPortInfo> & infoList);
#endif // Q_OS_MAC
#endif /* Q_OS_UNIX */
public:
/*!
Get list of ports.
\return list of ports currently available in the system.
*/
static QList<QextPortInfo> getPorts();
/*!
Enable event-driven notifications of board discovery/removal.
*/
void setUpNotifications( );
signals:
/*!
A new device has been connected to the system.
setUpNotifications() must be called first to enable event-driven device notifications.
Currently only implemented on Windows and OS X.
\param info The device that has been discovered.
*/
void deviceDiscovered( const QextPortInfo & info );
/*!
A device has been disconnected from the system.
setUpNotifications() must be called first to enable event-driven device notifications.
Currently only implemented on Windows and OS X.
\param info The device that was disconnected.
*/
void deviceRemoved( const QextPortInfo & info );
};
#endif /*_QEXTSERIALENUMERATOR_H_*/
| C++ |
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
#include <IOKit/serial/IOSerialKeys.h>
#include <CoreFoundation/CFNumber.h>
#include <sys/param.h>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
IONotificationPortDestroy( notificationPortRef );
}
// static
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> infoList;
io_iterator_t serialPortIterator = 0;
kern_return_t kernResult = KERN_FAILURE;
CFMutableDictionaryRef matchingDictionary;
// first try to get any serialbsd devices, then try any USBCDC devices
if( !(matchingDictionary = IOServiceMatching(kIOSerialBSDServiceValue) ) ) {
qWarning("IOServiceMatching returned a NULL dictionary.");
return infoList;
}
CFDictionaryAddValue(matchingDictionary, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
// then create the iterator with all the matching devices
if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
return infoList;
}
iterateServicesOSX(serialPortIterator, infoList);
IOObjectRelease(serialPortIterator);
serialPortIterator = 0;
if( !(matchingDictionary = IOServiceNameMatching("AppleUSBCDC")) ) {
qWarning("IOServiceNameMatching returned a NULL dictionary.");
return infoList;
}
if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
return infoList;
}
iterateServicesOSX(serialPortIterator, infoList);
IOObjectRelease(serialPortIterator);
return infoList;
}
void QextSerialEnumerator::iterateServicesOSX(io_object_t service, QList<QextPortInfo> & infoList)
{
// Iterate through all modems found.
io_object_t usbService;
while( ( usbService = IOIteratorNext(service) ) )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
getServiceDetailsOSX( usbService, &info );
infoList.append(info);
}
}
bool QextSerialEnumerator::getServiceDetailsOSX( io_object_t service, QextPortInfo* portInfo )
{
bool retval = true;
CFTypeRef bsdPathAsCFString = NULL;
CFTypeRef productNameAsCFString = NULL;
CFTypeRef vendorIdAsCFNumber = NULL;
CFTypeRef productIdAsCFNumber = NULL;
// check the name of the modem's callout device
bsdPathAsCFString = IORegistryEntryCreateCFProperty(service, CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault, 0);
// wander up the hierarchy until we find the level that can give us the
// vendor/product IDs and the product name, if available
io_registry_entry_t parent;
kern_return_t kernResult = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
while( kernResult == KERN_SUCCESS && !vendorIdAsCFNumber && !productIdAsCFNumber )
{
if(!productNameAsCFString)
productNameAsCFString = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR("Product Name"),
kCFAllocatorDefault, 0);
vendorIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR(kUSBVendorID),
kCFAllocatorDefault, 0);
productIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR(kUSBProductID),
kCFAllocatorDefault, 0);
io_registry_entry_t oldparent = parent;
kernResult = IORegistryEntryGetParentEntry(parent, kIOServicePlane, &parent);
IOObjectRelease(oldparent);
}
io_string_t ioPathName;
IORegistryEntryGetPath( service, kIOServicePlane, ioPathName );
portInfo->physName = ioPathName;
if( bsdPathAsCFString )
{
char path[MAXPATHLEN];
if( CFStringGetCString((CFStringRef)bsdPathAsCFString, path,
PATH_MAX, kCFStringEncodingUTF8) )
portInfo->portName = path;
CFRelease(bsdPathAsCFString);
}
if(productNameAsCFString)
{
char productName[MAXPATHLEN];
if( CFStringGetCString((CFStringRef)productNameAsCFString, productName,
PATH_MAX, kCFStringEncodingUTF8) )
portInfo->friendName = productName;
CFRelease(productNameAsCFString);
}
if(vendorIdAsCFNumber)
{
SInt32 vID;
if(CFNumberGetValue((CFNumberRef)vendorIdAsCFNumber, kCFNumberSInt32Type, &vID))
portInfo->vendorID = vID;
CFRelease(vendorIdAsCFNumber);
}
if(productIdAsCFNumber)
{
SInt32 pID;
if(CFNumberGetValue((CFNumberRef)productIdAsCFNumber, kCFNumberSInt32Type, &pID))
portInfo->productID = pID;
CFRelease(productIdAsCFNumber);
}
IOObjectRelease(service);
return retval;
}
// IOKit callbacks registered via setupNotifications()
void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator )
{
QextSerialEnumerator* qese = (QextSerialEnumerator*)ctxt;
io_object_t serialService;
while ((serialService = IOIteratorNext(serialPortIterator)))
qese->onDeviceDiscoveredOSX(serialService);
}
void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator )
{
QextSerialEnumerator* qese = (QextSerialEnumerator*)ctxt;
io_object_t serialService;
while ((serialService = IOIteratorNext(serialPortIterator)))
qese->onDeviceTerminatedOSX(serialService);
}
/*
A device has been discovered via IOKit.
Create a QextPortInfo if possible, and emit the signal indicating that we've found it.
*/
void QextSerialEnumerator::onDeviceDiscoveredOSX( io_object_t service )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
if( getServiceDetailsOSX( service, &info ) )
emit deviceDiscovered( info );
}
/*
Notification via IOKit that a device has been removed.
Create a QextPortInfo if possible, and emit the signal indicating that it's gone.
*/
void QextSerialEnumerator::onDeviceTerminatedOSX( io_object_t service )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
if( getServiceDetailsOSX( service, &info ) )
emit deviceRemoved( info );
}
/*
Create matching dictionaries for the devices we want to get notifications for,
and add them to the current run loop. Invoke the callbacks that will be responding
to these notifications once to arm them, and discover any devices that
are currently connected at the time notifications are setup.
*/
void QextSerialEnumerator::setUpNotifications( )
{
kern_return_t kernResult;
mach_port_t masterPort;
CFRunLoopSourceRef notificationRunLoopSource;
CFMutableDictionaryRef classesToMatch;
CFMutableDictionaryRef cdcClassesToMatch;
io_iterator_t portIterator;
kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
if (KERN_SUCCESS != kernResult) {
qDebug() << "IOMasterPort returned:" << kernResult;
return;
}
classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
if (classesToMatch == NULL)
qDebug("IOServiceMatching returned a NULL dictionary.");
else
CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
if( !(cdcClassesToMatch = IOServiceNameMatching("AppleUSBCDC") ) ) {
qWarning("couldn't create cdc matching dict");
return;
}
// Retain an additional reference since each call to IOServiceAddMatchingNotification consumes one.
classesToMatch = (CFMutableDictionaryRef) CFRetain(classesToMatch);
cdcClassesToMatch = (CFMutableDictionaryRef) CFRetain(cdcClassesToMatch);
notificationPortRef = IONotificationPortCreate(masterPort);
if(notificationPortRef == NULL) {
qDebug("IONotificationPortCreate return a NULL IONotificationPortRef.");
return;
}
notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
if (notificationRunLoopSource == NULL) {
qDebug("IONotificationPortGetRunLoopSource returned NULL CFRunLoopSourceRef.");
return;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, classesToMatch,
deviceDiscoveredCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and grab any devices that are already connected
deviceDiscoveredCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, cdcClassesToMatch,
deviceDiscoveredCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and grab any devices that are already connected
deviceDiscoveredCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, classesToMatch,
deviceTerminatedCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and clear any devices that are terminated
deviceTerminatedCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, cdcClassesToMatch,
deviceTerminatedCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and clear any devices that are terminated
deviceTerminatedCallbackOSX( this, portIterator );
}
| C++ |
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
#include <objbase.h>
#include <initguid.h>
#include "qextserialport.h"
#include <QRegExp>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
#if (defined QT_GUI_LIB)
notificationWidget = 0;
#endif // Q_OS_WIN
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
#if (defined QT_GUI_LIB)
if( notificationWidget )
delete notificationWidget;
#endif
}
// see http://msdn.microsoft.com/en-us/library/ms791134.aspx for list of GUID classes
#ifndef GUID_DEVCLASS_PORTS
DEFINE_GUID(GUID_DEVCLASS_PORTS, 0x4D36E978, 0xE325, 0x11CE, 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 );
#endif
/* Gordon Schumacher's macros for TCHAR -> QString conversions and vice versa */
#ifdef UNICODE
#define QStringToTCHAR(x) (wchar_t*) x.utf16()
#define PQStringToTCHAR(x) (wchar_t*) x->utf16()
#define TCHARToQString(x) QString::fromUtf16((ushort*)(x))
#define TCHARToQStringN(x,y) QString::fromUtf16((ushort*)(x),(y))
#else
#define QStringToTCHAR(x) x.local8Bit().constData()
#define PQStringToTCHAR(x) x->local8Bit().constData()
#define TCHARToQString(x) QString::fromLocal8Bit((x))
#define TCHARToQStringN(x,y) QString::fromLocal8Bit((x),(y))
#endif /*UNICODE*/
//static
QString QextSerialEnumerator::getRegKeyValue(HKEY key, LPCTSTR property)
{
DWORD size = 0;
DWORD type;
RegQueryValueEx(key, property, NULL, NULL, NULL, & size);
BYTE* buff = new BYTE[size];
QString result;
if( RegQueryValueEx(key, property, NULL, &type, buff, & size) == ERROR_SUCCESS )
result = TCHARToQString(buff);
RegCloseKey(key);
delete [] buff;
return result;
}
//static
QString QextSerialEnumerator::getDeviceProperty(HDEVINFO devInfo, PSP_DEVINFO_DATA devData, DWORD property)
{
DWORD buffSize = 0;
SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, NULL, 0, & buffSize);
BYTE* buff = new BYTE[buffSize];
SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, buff, buffSize, NULL);
QString result = TCHARToQString(buff);
delete [] buff;
return result;
}
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> ports;
enumerateDevicesWin(GUID_DEVCLASS_PORTS, &ports);
return ports;
}
void QextSerialEnumerator::enumerateDevicesWin( const GUID & guid, QList<QextPortInfo>* infoList )
{
HDEVINFO devInfo;
if( (devInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT)) != INVALID_HANDLE_VALUE)
{
SP_DEVINFO_DATA devInfoData;
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for(int i = 0; SetupDiEnumDeviceInfo(devInfo, i, &devInfoData); i++)
{
QextPortInfo info;
info.productID = info.vendorID = 0;
getDeviceDetailsWin( &info, devInfo, &devInfoData );
infoList->append(info);
}
SetupDiDestroyDeviceInfoList(devInfo);
}
}
#ifdef QT_GUI_LIB
bool QextSerialRegistrationWidget::winEvent( MSG* message, long* result )
{
if ( message->message == WM_DEVICECHANGE ) {
qese->onDeviceChangeWin( message->wParam, message->lParam );
*result = 1;
return true;
}
return false;
}
#endif
void QextSerialEnumerator::setUpNotifications( )
{
#ifdef QT_GUI_LIB
if(notificationWidget)
return;
notificationWidget = new QextSerialRegistrationWidget(this);
DEV_BROADCAST_DEVICEINTERFACE dbh;
ZeroMemory(&dbh, sizeof(dbh));
dbh.dbcc_size = sizeof(dbh);
dbh.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
CopyMemory(&dbh.dbcc_classguid, &GUID_DEVCLASS_PORTS, sizeof(GUID));
if( RegisterDeviceNotification( notificationWidget->winId( ), &dbh, DEVICE_NOTIFY_WINDOW_HANDLE ) == NULL)
qWarning() << "RegisterDeviceNotification failed:" << GetLastError();
// setting up notifications doesn't tell us about devices already connected
// so get those manually
foreach( QextPortInfo port, getPorts() )
emit deviceDiscovered( port );
#else
qWarning("QextSerialEnumerator: GUI not enabled - can't register for device notifications.");
#endif // QT_GUI_LIB
}
LRESULT QextSerialEnumerator::onDeviceChangeWin( WPARAM wParam, LPARAM lParam )
{
if ( DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam )
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
if( pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE )
{
PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
// delimiters are different across APIs...change to backslash. ugh.
QString deviceID = TCHARToQString(pDevInf->dbcc_name).toUpper().replace("#", "\\");
matchAndDispatchChangedDevice(deviceID, GUID_DEVCLASS_PORTS, wParam);
}
}
return 0;
}
bool QextSerialEnumerator::matchAndDispatchChangedDevice(const QString & deviceID, const GUID & guid, WPARAM wParam)
{
bool rv = false;
DWORD dwFlag = (DBT_DEVICEARRIVAL == wParam) ? DIGCF_PRESENT : DIGCF_ALLCLASSES;
HDEVINFO devInfo;
if( (devInfo = SetupDiGetClassDevs(&guid,NULL,NULL,dwFlag)) != INVALID_HANDLE_VALUE )
{
SP_DEVINFO_DATA spDevInfoData;
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; SetupDiEnumDeviceInfo(devInfo, i, &spDevInfoData); i++)
{
DWORD nSize=0 ;
TCHAR buf[MAX_PATH];
if ( SetupDiGetDeviceInstanceId(devInfo, &spDevInfoData, buf, MAX_PATH, &nSize) &&
deviceID.contains(TCHARToQString(buf))) // we found a match
{
rv = true;
QextPortInfo info;
info.productID = info.vendorID = 0;
getDeviceDetailsWin( &info, devInfo, &spDevInfoData, wParam );
if( wParam == DBT_DEVICEARRIVAL )
emit deviceDiscovered(info);
else if( wParam == DBT_DEVICEREMOVECOMPLETE )
emit deviceRemoved(info);
break;
}
}
SetupDiDestroyDeviceInfoList(devInfo);
}
return rv;
}
bool QextSerialEnumerator::getDeviceDetailsWin( QextPortInfo* portInfo, HDEVINFO devInfo, PSP_DEVINFO_DATA devData, WPARAM wParam )
{
portInfo->friendName = getDeviceProperty(devInfo, devData, SPDRP_FRIENDLYNAME);
if( wParam == DBT_DEVICEARRIVAL)
portInfo->physName = getDeviceProperty(devInfo, devData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME);
portInfo->enumName = getDeviceProperty(devInfo, devData, SPDRP_ENUMERATOR_NAME);
QString hardwareIDs = getDeviceProperty(devInfo, devData, SPDRP_HARDWAREID);
HKEY devKey = SetupDiOpenDevRegKey(devInfo, devData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
portInfo->portName = QextSerialPort::fullPortNameWin( getRegKeyValue(devKey, TEXT("PortName")) );
QRegExp idRx("VID_(\\w+)&PID_(\\w+)");
if( hardwareIDs.toUpper().contains(idRx) )
{
bool dummy;
portInfo->vendorID = idRx.cap(1).toInt(&dummy, 16);
portInfo->productID = idRx.cap(2).toInt(&dummy, 16);
//qDebug() << "got vid:" << vid << "pid:" << pid;
}
return true;
}
| C++ |
#include <fcntl.h>
#include <stdio.h>
#include "qextserialport.h"
#include <QMutexLocker>
#include <QDebug>
void QextSerialPort::platformSpecificInit()
{
fd = 0;
readNotifier = 0;
}
/*!
Standard destructor.
*/
void QextSerialPort::platformSpecificDestruct()
{}
/*!
Sets the baud rate of the serial port. Note that not all rates are applicable on
all platforms. The following table shows translations of the various baud rate
constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an *
are speeds that are usable on both Windows and POSIX.
\note
BAUD76800 may not be supported on all POSIX systems. SGI/IRIX systems do not support
BAUD1800.
\verbatim
RATE Windows Speed POSIX Speed
----------- ------------- -----------
BAUD50 110 50
BAUD75 110 75
*BAUD110 110 110
BAUD134 110 134.5
BAUD150 110 150
BAUD200 110 200
*BAUD300 300 300
*BAUD600 600 600
*BAUD1200 1200 1200
BAUD1800 1200 1800
*BAUD2400 2400 2400
*BAUD4800 4800 4800
*BAUD9600 9600 9600
BAUD14400 14400 9600
*BAUD19200 19200 19200
*BAUD38400 38400 38400
BAUD56000 56000 38400
*BAUD57600 57600 57600
BAUD76800 57600 76800
*BAUD115200 115200 115200
BAUD128000 128000 115200
BAUD256000 256000 115200
\endverbatim
*/
void QextSerialPort::setBaudRate(BaudRateType baudRate)
{
QMutexLocker lock(mutex);
if (Settings.BaudRate!=baudRate) {
switch (baudRate) {
case BAUD14400:
Settings.BaudRate=BAUD9600;
break;
case BAUD56000:
Settings.BaudRate=BAUD38400;
break;
case BAUD76800:
#ifndef B76800
Settings.BaudRate=BAUD57600;
#else
Settings.BaudRate=baudRate;
#endif
break;
case BAUD128000:
case BAUD256000:
Settings.BaudRate=BAUD115200;
break;
default:
Settings.BaudRate=baudRate;
break;
}
}
if (isOpen()) {
switch (baudRate) {
/*50 baud*/
case BAUD50:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 50 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B50;
#else
cfsetispeed(&Posix_CommConfig, B50);
cfsetospeed(&Posix_CommConfig, B50);
#endif
break;
/*75 baud*/
case BAUD75:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 75 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B75;
#else
cfsetispeed(&Posix_CommConfig, B75);
cfsetospeed(&Posix_CommConfig, B75);
#endif
break;
/*110 baud*/
case BAUD110:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B110;
#else
cfsetispeed(&Posix_CommConfig, B110);
cfsetospeed(&Posix_CommConfig, B110);
#endif
break;
/*134.5 baud*/
case BAUD134:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 134.5 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B134;
#else
cfsetispeed(&Posix_CommConfig, B134);
cfsetospeed(&Posix_CommConfig, B134);
#endif
break;
/*150 baud*/
case BAUD150:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 150 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B150;
#else
cfsetispeed(&Posix_CommConfig, B150);
cfsetospeed(&Posix_CommConfig, B150);
#endif
break;
/*200 baud*/
case BAUD200:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 200 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B200;
#else
cfsetispeed(&Posix_CommConfig, B200);
cfsetospeed(&Posix_CommConfig, B200);
#endif
break;
/*300 baud*/
case BAUD300:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B300;
#else
cfsetispeed(&Posix_CommConfig, B300);
cfsetospeed(&Posix_CommConfig, B300);
#endif
break;
/*600 baud*/
case BAUD600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B600;
#else
cfsetispeed(&Posix_CommConfig, B600);
cfsetospeed(&Posix_CommConfig, B600);
#endif
break;
/*1200 baud*/
case BAUD1200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B1200;
#else
cfsetispeed(&Posix_CommConfig, B1200);
cfsetospeed(&Posix_CommConfig, B1200);
#endif
break;
/*1800 baud*/
case BAUD1800:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows and IRIX do not support 1800 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B1800;
#else
cfsetispeed(&Posix_CommConfig, B1800);
cfsetospeed(&Posix_CommConfig, B1800);
#endif
break;
/*2400 baud*/
case BAUD2400:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B2400;
#else
cfsetispeed(&Posix_CommConfig, B2400);
cfsetospeed(&Posix_CommConfig, B2400);
#endif
break;
/*4800 baud*/
case BAUD4800:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B4800;
#else
cfsetispeed(&Posix_CommConfig, B4800);
cfsetospeed(&Posix_CommConfig, B4800);
#endif
break;
/*9600 baud*/
case BAUD9600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B9600;
#else
cfsetispeed(&Posix_CommConfig, B9600);
cfsetospeed(&Posix_CommConfig, B9600);
#endif
break;
/*14400 baud*/
case BAUD14400:
TTY_WARNING("QextSerialPort: POSIX does not support 14400 baud operation. Switching to 9600 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B9600;
#else
cfsetispeed(&Posix_CommConfig, B9600);
cfsetospeed(&Posix_CommConfig, B9600);
#endif
break;
/*19200 baud*/
case BAUD19200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B19200;
#else
cfsetispeed(&Posix_CommConfig, B19200);
cfsetospeed(&Posix_CommConfig, B19200);
#endif
break;
/*38400 baud*/
case BAUD38400:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B38400;
#else
cfsetispeed(&Posix_CommConfig, B38400);
cfsetospeed(&Posix_CommConfig, B38400);
#endif
break;
/*56000 baud*/
case BAUD56000:
TTY_WARNING("QextSerialPort: POSIX does not support 56000 baud operation. Switching to 38400 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B38400;
#else
cfsetispeed(&Posix_CommConfig, B38400);
cfsetospeed(&Posix_CommConfig, B38400);
#endif
break;
/*57600 baud*/
case BAUD57600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B57600;
#else
cfsetispeed(&Posix_CommConfig, B57600);
cfsetospeed(&Posix_CommConfig, B57600);
#endif
break;
/*76800 baud*/
case BAUD76800:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows and some POSIX systems do not support 76800 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
#ifdef B76800
Posix_CommConfig.c_cflag|=B76800;
#else
TTY_WARNING("QextSerialPort: QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud.");
Posix_CommConfig.c_cflag|=B57600;
#endif //B76800
#else //CBAUD
#ifdef B76800
cfsetispeed(&Posix_CommConfig, B76800);
cfsetospeed(&Posix_CommConfig, B76800);
#else
TTY_WARNING("QextSerialPort: QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud.");
cfsetispeed(&Posix_CommConfig, B57600);
cfsetospeed(&Posix_CommConfig, B57600);
#endif //B76800
#endif //CBAUD
break;
/*115200 baud*/
case BAUD115200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
/*128000 baud*/
case BAUD128000:
TTY_WARNING("QextSerialPort: POSIX does not support 128000 baud operation. Switching to 115200 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
/*256000 baud*/
case BAUD256000:
TTY_WARNING("QextSerialPort: POSIX does not support 256000 baud operation. Switching to 115200 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
}
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
}
/*!
Sets the number of data bits used by the serial port. Possible values of dataBits are:
\verbatim
DATA_5 5 data bits
DATA_6 6 data bits
DATA_7 7 data bits
DATA_8 8 data bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
5 data bits cannot be used with 2 stop bits.
\par
8 data bits cannot be used with space parity on POSIX systems.
*/
void QextSerialPort::setDataBits(DataBitsType dataBits)
{
QMutexLocker lock(mutex);
if (Settings.DataBits!=dataBits) {
if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) ||
(Settings.StopBits==STOP_1_5 && dataBits!=DATA_5) ||
(Settings.Parity==PAR_SPACE && dataBits==DATA_8)) {
}
else {
Settings.DataBits=dataBits;
}
}
if (isOpen()) {
switch(dataBits) {
/*5 data bits*/
case DATA_5:
if (Settings.StopBits==STOP_2) {
TTY_WARNING("QextSerialPort: 5 Data bits cannot be used with 2 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS5;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*6 data bits*/
case DATA_6:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS6;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*7 data bits*/
case DATA_7:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS7;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*8 data bits*/
case DATA_8:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS8;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
}
}
}
/*!
Sets the parity associated with the serial port. The possible values of parity are:
\verbatim
PAR_SPACE Space Parity
PAR_MARK Mark Parity
PAR_NONE No Parity
PAR_EVEN Even Parity
PAR_ODD Odd Parity
\endverbatim
\note
This function is subject to the following limitations:
\par
POSIX systems do not support mark parity.
\par
POSIX systems support space parity only if tricked into doing so, and only with
fewer than 8 data bits. Use space parity very carefully with POSIX systems.
*/
void QextSerialPort::setParity(ParityType parity)
{
QMutexLocker lock(mutex);
if (Settings.Parity!=parity) {
if (parity==PAR_MARK || (parity==PAR_SPACE && Settings.DataBits==DATA_8)) {
}
else {
Settings.Parity=parity;
}
}
if (isOpen()) {
switch (parity) {
/*space parity*/
case PAR_SPACE:
if (Settings.DataBits==DATA_8) {
TTY_PORTABILITY_WARNING("QextSerialPort: Space parity is only supported in POSIX with 7 or fewer data bits");
}
else {
/*space parity not directly supported - add an extra data bit to simulate it*/
Posix_CommConfig.c_cflag&=~(PARENB|CSIZE);
switch(Settings.DataBits) {
case DATA_5:
Settings.DataBits=DATA_6;
Posix_CommConfig.c_cflag|=CS6;
break;
case DATA_6:
Settings.DataBits=DATA_7;
Posix_CommConfig.c_cflag|=CS7;
break;
case DATA_7:
Settings.DataBits=DATA_8;
Posix_CommConfig.c_cflag|=CS8;
break;
case DATA_8:
break;
}
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*mark parity - WINDOWS ONLY*/
case PAR_MARK:
TTY_WARNING("QextSerialPort: Mark parity is not supported by POSIX.");
break;
/*no parity*/
case PAR_NONE:
Posix_CommConfig.c_cflag&=(~PARENB);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*even parity*/
case PAR_EVEN:
Posix_CommConfig.c_cflag&=(~PARODD);
Posix_CommConfig.c_cflag|=PARENB;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*odd parity*/
case PAR_ODD:
Posix_CommConfig.c_cflag|=(PARENB|PARODD);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
}
}
}
/*!
Sets the number of stop bits used by the serial port. Possible values of stopBits are:
\verbatim
STOP_1 1 stop bit
STOP_1_5 1.5 stop bits
STOP_2 2 stop bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
2 stop bits cannot be used with 5 data bits.
\par
POSIX does not support 1.5 stop bits.
*/
void QextSerialPort::setStopBits(StopBitsType stopBits)
{
QMutexLocker lock(mutex);
if (Settings.StopBits!=stopBits) {
if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) || stopBits==STOP_1_5) {}
else {
Settings.StopBits=stopBits;
}
}
if (isOpen()) {
switch (stopBits) {
/*one stop bit*/
case STOP_1:
Settings.StopBits=stopBits;
Posix_CommConfig.c_cflag&=(~CSTOPB);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*1.5 stop bits*/
case STOP_1_5:
TTY_WARNING("QextSerialPort: 1.5 stop bit operation is not supported by POSIX.");
break;
/*two stop bits*/
case STOP_2:
if (Settings.DataBits==DATA_5) {
TTY_WARNING("QextSerialPort: 2 stop bits cannot be used with 5 data bits");
}
else {
Settings.StopBits=stopBits;
Posix_CommConfig.c_cflag|=CSTOPB;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
}
}
}
/*!
Sets the flow control used by the port. Possible values of flow are:
\verbatim
FLOW_OFF No flow control
FLOW_HARDWARE Hardware (RTS/CTS) flow control
FLOW_XONXOFF Software (XON/XOFF) flow control
\endverbatim
\note
FLOW_HARDWARE may not be supported on all versions of UNIX. In cases where it is
unsupported, FLOW_HARDWARE is the same as FLOW_OFF.
*/
void QextSerialPort::setFlowControl(FlowType flow)
{
QMutexLocker lock(mutex);
if (Settings.FlowControl!=flow) {
Settings.FlowControl=flow;
}
if (isOpen()) {
switch(flow) {
/*no flow control*/
case FLOW_OFF:
Posix_CommConfig.c_cflag&=(~CRTSCTS);
Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY));
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*software (XON/XOFF) flow control*/
case FLOW_XONXOFF:
Posix_CommConfig.c_cflag&=(~CRTSCTS);
Posix_CommConfig.c_iflag|=(IXON|IXOFF|IXANY);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
case FLOW_HARDWARE:
Posix_CommConfig.c_cflag|=CRTSCTS;
Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY));
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
}
}
}
/*!
Sets the read and write timeouts for the port to millisec milliseconds.
Note that this is a per-character timeout, i.e. the port will wait this long for each
individual character, not for the whole read operation. This timeout also applies to the
bytesWaiting() function.
\note
POSIX does not support millisecond-level control for I/O timeout values. Any
timeout set using this function will be set to the next lowest tenth of a second for
the purposes of detecting read or write timeouts. For example a timeout of 550 milliseconds
will be seen by the class as a timeout of 500 milliseconds for the purposes of reading and
writing the port. However millisecond-level control is allowed by the select() system call,
so for example a 550-millisecond timeout will be seen as 550 milliseconds on POSIX systems for
the purpose of detecting available bytes in the read buffer.
*/
void QextSerialPort::setTimeout(long millisec)
{
QMutexLocker lock(mutex);
Settings.Timeout_Millisec = millisec;
Posix_Copy_Timeout.tv_sec = millisec / 1000;
Posix_Copy_Timeout.tv_usec = millisec % 1000;
if (isOpen()) {
if (millisec == -1)
fcntl(fd, F_SETFL, O_NDELAY);
else
//O_SYNC should enable blocking ::write()
//however this seems not working on Linux 2.6.21 (works on OpenBSD 4.2)
fcntl(fd, F_SETFL, O_SYNC);
tcgetattr(fd, & Posix_CommConfig);
Posix_CommConfig.c_cc[VTIME] = millisec/100;
tcsetattr(fd, TCSAFLUSH, & Posix_CommConfig);
}
}
/*!
Opens the serial port associated to this class.
This function has no effect if the port associated with the class is already open.
The port is also configured to the current settings, as stored in the Settings structure.
*/
bool QextSerialPort::open(OpenMode mode)
{
QMutexLocker lock(mutex);
if (mode == QIODevice::NotOpen)
return isOpen();
if (!isOpen()) {
qDebug() << "trying to open file" << port.toAscii();
//note: linux 2.6.21 seems to ignore O_NDELAY flag
if ((fd = ::open(port.toAscii() ,O_RDWR | O_NOCTTY | O_NDELAY)) != -1) {
qDebug("file opened succesfully");
setOpenMode(mode); // Flag the port as opened
tcgetattr(fd, &old_termios); // Save the old termios
Posix_CommConfig = old_termios; // Make a working copy
cfmakeraw(&Posix_CommConfig); // Enable raw access
/*set up other port settings*/
Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
Posix_CommConfig.c_oflag&=(~OPOST);
Posix_CommConfig.c_cc[VMIN]= 0;
#ifdef _POSIX_VDISABLE // Is a disable character available on this system?
// Some systems allow for per-device disable-characters, so get the
// proper value for the configured device
const long vdisable = fpathconf(fd, _PC_VDISABLE);
Posix_CommConfig.c_cc[VINTR] = vdisable;
Posix_CommConfig.c_cc[VQUIT] = vdisable;
Posix_CommConfig.c_cc[VSTART] = vdisable;
Posix_CommConfig.c_cc[VSTOP] = vdisable;
Posix_CommConfig.c_cc[VSUSP] = vdisable;
#endif //_POSIX_VDISABLE
setBaudRate(Settings.BaudRate);
setDataBits(Settings.DataBits);
setParity(Settings.Parity);
setStopBits(Settings.StopBits);
setFlowControl(Settings.FlowControl);
setTimeout(Settings.Timeout_Millisec);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
if (queryMode() == QextSerialPort::EventDriven) {
readNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead()));
}
} else {
qDebug() << "could not open file:" << strerror(errno);
lastErr = E_FILE_NOT_FOUND;
}
}
return isOpen();
}
/*!
Closes a serial port. This function has no effect if the serial port associated with the class
is not currently open.
*/
void QextSerialPort::close()
{
QMutexLocker lock(mutex);
if( isOpen() )
{
// Force a flush and then restore the original termios
flush();
// Using both TCSAFLUSH and TCSANOW here discards any pending input
tcsetattr(fd, TCSAFLUSH | TCSANOW, &old_termios); // Restore termios
// Be a good QIODevice and call QIODevice::close() before POSIX close()
// so the aboutToClose() signal is emitted at the proper time
QIODevice::close(); // Flag the device as closed
// QIODevice::close() doesn't actually close the port, so do that here
::close(fd);
if(readNotifier) {
delete readNotifier;
readNotifier = 0;
}
}
}
/*!
Flushes all pending I/O to the serial port. This function has no effect if the serial port
associated with the class is not currently open.
*/
void QextSerialPort::flush()
{
QMutexLocker lock(mutex);
if (isOpen())
tcflush(fd, TCIOFLUSH);
}
/*!
This function will return the number of bytes waiting in the receive queue of the serial port.
It is included primarily to provide a complete QIODevice interface, and will not record errors
in the lastErr member (because it is const). This function is also not thread-safe - in
multithreading situations, use QextSerialPort::bytesWaiting() instead.
*/
qint64 QextSerialPort::size() const
{
int numBytes;
if (ioctl(fd, FIONREAD, &numBytes)<0) {
numBytes = 0;
}
return (qint64)numBytes;
}
/*!
Returns the number of bytes waiting in the port's receive queue. This function will return 0 if
the port is not currently open, or -1 on error.
*/
qint64 QextSerialPort::bytesAvailable() const
{
QMutexLocker lock(mutex);
if (isOpen()) {
int bytesQueued;
if (ioctl(fd, FIONREAD, &bytesQueued) == -1) {
return (qint64)-1;
}
return bytesQueued + QIODevice::bytesAvailable();
}
return 0;
}
/*!
This function is included to implement the full QIODevice interface, and currently has no
purpose within this class. This function is meaningless on an unbuffered device and currently
only prints a warning message to that effect.
*/
void QextSerialPort::ungetChar(char)
{
/*meaningless on unbuffered sequential device - return error and print a warning*/
TTY_WARNING("QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless");
}
/*!
Translates a system-specific error code to a QextSerialPort error code. Used internally.
*/
void QextSerialPort::translateError(ulong error)
{
switch (error) {
case EBADF:
case ENOTTY:
lastErr=E_INVALID_FD;
break;
case EINTR:
lastErr=E_CAUGHT_NON_BLOCKED_SIGNAL;
break;
case ENOMEM:
lastErr=E_NO_MEMORY;
break;
}
}
/*!
Sets DTR line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setDtr(bool set)
{
QMutexLocker lock(mutex);
if (isOpen()) {
int status;
ioctl(fd, TIOCMGET, &status);
if (set) {
status|=TIOCM_DTR;
}
else {
status&=~TIOCM_DTR;
}
ioctl(fd, TIOCMSET, &status);
}
}
/*!
Sets RTS line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setRts(bool set)
{
QMutexLocker lock(mutex);
if (isOpen()) {
int status;
ioctl(fd, TIOCMGET, &status);
if (set) {
status|=TIOCM_RTS;
}
else {
status&=~TIOCM_RTS;
}
ioctl(fd, TIOCMSET, &status);
}
}
/*!
Returns the line status as stored by the port function. This function will retrieve the states
of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines
can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned
long with specific bits indicating which lines are high. The following constants should be used
to examine the states of individual lines:
\verbatim
Mask Line
------ ----
LS_CTS CTS
LS_DSR DSR
LS_DCD DCD
LS_RI RI
LS_RTS RTS (POSIX only)
LS_DTR DTR (POSIX only)
LS_ST Secondary TXD (POSIX only)
LS_SR Secondary RXD (POSIX only)
\endverbatim
This function will return 0 if the port associated with the class is not currently open.
*/
unsigned long QextSerialPort::lineStatus()
{
unsigned long Status=0, Temp=0;
QMutexLocker lock(mutex);
if (isOpen()) {
ioctl(fd, TIOCMGET, &Temp);
if (Temp&TIOCM_CTS) {
Status|=LS_CTS;
}
if (Temp&TIOCM_DSR) {
Status|=LS_DSR;
}
if (Temp&TIOCM_RI) {
Status|=LS_RI;
}
if (Temp&TIOCM_CD) {
Status|=LS_DCD;
}
if (Temp&TIOCM_DTR) {
Status|=LS_DTR;
}
if (Temp&TIOCM_RTS) {
Status|=LS_RTS;
}
if (Temp&TIOCM_ST) {
Status|=LS_ST;
}
if (Temp&TIOCM_SR) {
Status|=LS_SR;
}
}
return Status;
}
/*!
Reads a block of data from the serial port. This function will read at most maxSize bytes from
the serial port and place them in the buffer pointed to by data. Return value is the number of
bytes actually read, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::readData(char * data, qint64 maxSize)
{
QMutexLocker lock(mutex);
int retVal = ::read(fd, data, maxSize);
if (retVal == -1)
lastErr = E_READ_FAILED;
return retVal;
}
/*!
Writes a block of data to the serial port. This function will write maxSize bytes
from the buffer pointed to by data to the serial port. Return value is the number
of bytes actually written, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::writeData(const char * data, qint64 maxSize)
{
QMutexLocker lock(mutex);
int retVal = ::write(fd, data, maxSize);
if (retVal == -1)
lastErr = E_WRITE_FAILED;
return (qint64)retVal;
}
| C++ |
/* qesptest.h
**************************************/
#ifndef _QESPTEST_H_
#define _QESPTEST_H_
#include <QWidget>
class QLineEdit;
class QTextEdit;
class QextSerialPort;
class QSpinBox;
class QespTest : public QWidget
{
Q_OBJECT
public:
QespTest(QWidget *parent=0);
virtual ~QespTest();
private:
QLineEdit *message;
QSpinBox* delaySpinBox;
QTextEdit *received_msg;
QextSerialPort *port;
private slots:
void transmitMsg();
void receiveMsg();
void appendCR();
void appendLF();
void closePort();
void openPort();
};
#endif
| C++ |
/* QespTest.cpp
**************************************/
#include "QespTest.h"
#include <qextserialport.h>
#include <QLayout>
#include <QLineEdit>
#include <QTextEdit>
#include <QPushButton>
#include <QSpinBox>
QespTest::QespTest(QWidget* parent)
: QWidget(parent)
{
//modify the port settings on your own
#ifdef _TTY_POSIX_
port = new QextSerialPort("/dev/ttyS0", QextSerialPort::Polling);
#else
port = new QextSerialPort("COM1", QextSerialPort::Polling);
#endif /*_TTY_POSIX*/
port->setBaudRate(BAUD19200);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
//set timeouts to 500 ms
port->setTimeout(500);
message = new QLineEdit(this);
// transmit receive
QPushButton *transmitButton = new QPushButton("Transmit");
connect(transmitButton, SIGNAL(clicked()), SLOT(transmitMsg()));
QPushButton *receiveButton = new QPushButton("Receive");
connect(receiveButton, SIGNAL(clicked()), SLOT(receiveMsg()));
QHBoxLayout* trLayout = new QHBoxLayout;
trLayout->addWidget(transmitButton);
trLayout->addWidget(receiveButton);
//CR LF
QPushButton *CRButton = new QPushButton("CR");
connect(CRButton, SIGNAL(clicked()), SLOT(appendCR()));
QPushButton *LFButton = new QPushButton("LF");
connect(LFButton, SIGNAL(clicked()), SLOT(appendLF()));
QHBoxLayout *crlfLayout = new QHBoxLayout;
crlfLayout->addWidget(CRButton);
crlfLayout->addWidget(LFButton);
//open close
QPushButton *openButton = new QPushButton("Open");
connect(openButton, SIGNAL(clicked()), SLOT(openPort()));
QPushButton *closeButton = new QPushButton("Close");
connect(closeButton, SIGNAL(clicked()), SLOT(closePort()));
QHBoxLayout *ocLayout = new QHBoxLayout;
ocLayout->addWidget(openButton);
ocLayout->addWidget(closeButton);
received_msg = new QTextEdit();
QVBoxLayout *myVBox = new QVBoxLayout;
myVBox->addWidget(message);
myVBox->addLayout(crlfLayout);
myVBox->addLayout(trLayout);
myVBox->addLayout(ocLayout);
myVBox->addWidget(received_msg);
setLayout(myVBox);
qDebug("isOpen : %d", port->isOpen());
}
QespTest::~QespTest()
{
delete port;
port = NULL;
}
void QespTest::transmitMsg()
{
int i = port->write((message->text()).toAscii(),
(message->text()).length());
qDebug("trasmitted : %d", i);
}
void QespTest::receiveMsg()
{
char buff[1024];
int numBytes;
numBytes = port->bytesAvailable();
if(numBytes > 1024)
numBytes = 1024;
int i = port->read(buff, numBytes);
if (i != -1)
buff[i] = '\0';
else
buff[0] = '\0';
QString msg = buff;
received_msg->append(msg);
received_msg->ensureCursorVisible();
qDebug("bytes available: %d", numBytes);
qDebug("received: %d", i);
}
void QespTest::appendCR()
{
message->insert("\x0D");
}
void QespTest::appendLF()
{
message->insert("\x0A");
}
void QespTest::closePort()
{
port->close();
qDebug("is open: %d", port->isOpen());
}
void QespTest::openPort()
{
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered);
qDebug("is open: %d", port->isOpen());
}
| C++ |
#ifndef PORTLISTENER_H_
#define PORTLISTENER_H_
#include <QObject>
#include "qextserialport.h"
class PortListener : public QObject
{
Q_OBJECT
public:
PortListener(const QString & portName);
private:
QextSerialPort *port;
private slots:
void onReadyRead();
void onDsrChanged(bool status);
};
#endif /*PORTLISTENER_H_*/
| C++ |
#include "PortListener.h"
#include <QtDebug>
PortListener::PortListener(const QString & portName)
{
qDebug() << "hi there";
this->port = new QextSerialPort(portName, QextSerialPort::EventDriven);
port->setBaudRate(BAUD56000);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
if (port->open(QIODevice::ReadWrite) == true) {
connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(port, SIGNAL(dsrChanged(bool)), this, SLOT(onDsrChanged(bool)));
if (!(port->lineStatus() & LS_DSR))
qDebug() << "warning: device is not turned on";
qDebug() << "listening for data on" << port->portName();
}
else {
qDebug() << "device failed to open:" << port->errorString();
}
}
void PortListener::onReadyRead()
{
QByteArray bytes;
int a = port->bytesAvailable();
bytes.resize(a);
port->read(bytes.data(), bytes.size());
qDebug() << "bytes read:" << bytes.size();
qDebug() << "bytes:" << bytes;
}
void PortListener::onDsrChanged(bool status)
{
if (status)
qDebug() << "device was turned on";
else
qDebug() << "device was turned off";
}
| C++ |
/**
* @file main.cpp
* @brief Main file.
* @author Michal Policht
*/
#include <QCoreApplication>
#include "PortListener.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QString portName = "COM1"; // update this to use your port of choice
PortListener *listener = new PortListener(portName); // signals get hooked up internally
// start the event loop and wait for signals
return app.exec();
}
| C++ |
/**
* @file main.cpp
* @brief Main file.
* @author Michał Policht
*/
#include <qextserialenumerator.h>
#include <QList>
#include <QtDebug>
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
qDebug() << "List of ports:";
for (int i = 0; i < ports.size(); i++) {
qDebug() << "port name:" << ports.at(i).portName;
qDebug() << "friendly name:" << ports.at(i).friendName;
qDebug() << "physical name:" << ports.at(i).physName;
qDebug() << "enumerator name:" << ports.at(i).enumName;
qDebug() << "vendor ID:" << QString::number(ports.at(i).vendorID, 16);
qDebug() << "product ID:" << QString::number(ports.at(i).productID, 16);
qDebug() << "===================================";
}
return EXIT_SUCCESS;
}
| C++ |
#ifndef DBF_H_INCLUDED
#define DBF_H_INCLUDED
#include <math.h>
#include "../stdafx.h"
#define DFN_STRING 0x01
#define DFN_DECIMAL 0x02
typedef struct tag_dbf_header_info
{
ULONG cntRecord;
USHORT cntField;
USHORT szRecord;
} _DBF_HEADER_INFO;
typedef struct tag_field_info
{
CHAR csNm[12];
UCHAR field_type;
UCHAR field_size;
USHORT offset;
} _FIELD_INFO;
typedef struct tag_output_info
{
char csNm[12];
WCHAR wcsDescription[48];
UCHAR field_type;
UCHAR field_size;
USHORT offset;
} _OUTPUT_INFO;
class CDbf
{
public:
CDbf();
~CDbf();
void parse_record(WCHAR* pData);
void set_path(CString strPath);
void add_data_field (CHAR* pszField, CString strDesc);
void move_to_first();
void move_to_next();
void setData(CString str_file_path, CString str_file_name, ULONG cnt, char* asz_field_name);
void getRecordInfo(ULONG option, void *param, WCHAR* pRec);
private:
void parse_header();
public:
CFile f;
ULONG m_cnt_selected_field_info;
_OUTPUT_INFO m_selected_field_info[32];
_DBF_HEADER_INFO hdr;
CHAR pbuf[2048];
ULONG m_idx_record;
ULONG m_cursor;
};
#endif | C++ |
#ifndef DBF_ROAD_ADDR_H_INCLUDED
#define DBF_ROAD_ADDR_H_INCLUDED
#include "shape.h"
#include "../stdafx.h"
typedef struct tag_road_addr
{
ULONG cd_region_level12;
ULONG cd_region_level3;
ULONG cd_road;
ULONG road_addr;
ULONG land_addr;
} _ROAD_ADDR;
class CRoadAddr
{
public:
void set();
void main();
void parse(_ROAD_ADDR* pTgt, WCHAR* pSrc);
private:
CShape m_shape;
};
#endif | C++ |
#include <math.h>
#include "util.h"
unsigned long u32_big_2_lit(unsigned char *buf)
{
unsigned long ret = 0;
unsigned char i;
for(i=0; i<4; i++)
{
ret += (unsigned long)( (buf[i]) * pow(256.,3-i) );
}
return ret;
}
unsigned long u32_lit_2_big(unsigned long ul)
{
unsigned char val[4];
memcpy(&val[0],&ul,4);
return (val[0]<<24) + (val[1]<<16) + (val[2]<<8) + val[3];
}
unsigned short u16_big_2_lit(unsigned char *buf)
{
unsigned short ret = 0;
unsigned char i;
for(i=0; i<2; i++)
{
ret += (unsigned short)( (buf[i]) * pow(256.,1-i) );
}
return ret;
}
| C++ |
#ifndef DBF_H_INCLUDED
#define DBF_H_INCLUDED
#include <math.h>
#include "stdafx.h"
#define DFN_STRING 0x01
#define DFN_DECIMAL 0x02
typedef struct tag_dbf_header_info
{
ULONG cntRecord;
USHORT cntField;
USHORT szRecord;
} _DBF_HEADER_INFO;
typedef struct tag_field_info
{
CHAR csNm[12];
UCHAR field_type;
UCHAR field_size;
USHORT offset;
} _FIELD_INFO;
class CDbf
{
public:
CDbf();
~CDbf();
void parse_record(WCHAR* pData);
void set_path(CString strPath);
void add_data_field (CHAR* pszField, CString strDesc);
void move_to_first();
void move_to_next();
void setData(CString str_file_path, CString str_file_name, ULONG cnt, char* asz_field_name);
void getRecordInfo(ULONG option, void *param, WCHAR* pRec);
public:
CFile f;
ULONG m_cnt_selected_field_info;
_FIELD_INFO m_selected_field_info[32];
_DBF_HEADER_INFO hdr;
CHAR pbuf[2048];
ULONG m_idx_record;
ULONG m_cursor;
private:
ULONG erase_blank_reverse(CHAR* pSrc,ULONG sz);
ULONG erase_blank_forward(CHAR* pSrc,ULONG sz);
};
#endif | C++ |
#ifndef TAXI_PARSER_H_INLCUDED
#define TAXI_PARSER_H_INLCUDED
#include "common.h"
#include "stdafx.h"
typedef struct tag_hdr
{
ULONG ver;
ULONG type;
ULONG len;
ULONG bizID;
ULONG carID;
ULONG TctFlag;
ULONG GpsType;
} _HDR;
typedef struct tag_record
{
double x;
double y;
double z;
CTime t;
ULONG arc;
ULONG speed;
BOOL accuracy;
BOOL beCustomer;
BOOL beOnLoad;
BOOL passRealNode;
BOOL beValid;
} _REC;
class CTaxiParser
{
public:
void read_1st_line(CString str);
void read_2nd_line(CString str);
ULONG read_3rd_line(CString str);
void read_data_line(CString str);
ULONG getNumber(CString InputStr, CString *OutputStr);
void writedata();
void set_time(ULONG a, ULONG b, ULONG c, ULONG d, ULONG e, ULONG f);
CTime add_time(CTime t, ULONG sec);
public:
_HDR m_hdr;
_REC m_rec;
CTime m_t_tmp;
ULONG m_cnt_rec;
};
#endif | C++ |
#ifndef DBF_ROAD_ADDR_H_INCLUDED
#define DBF_ROAD_ADDR_H_INCLUDED
#include "shape.h"
#include "../stdafx.h"
typedef struct tag_road_addr
{
ULONG cd_region_level12;
ULONG cd_region_level3;
ULONG cd_road;
ULONG road_addr;
ULONG land_addr;
} _ROAD_ADDR;
class CRoadAddr
{
public:
void set();
void main();
void parse(_ROAD_ADDR* pTgt, WCHAR* pSrc);
private:
CShape m_shape;
};
#endif | C++ |
#include <math.h>
#include "util.h"
unsigned long u32_big_2_lit(unsigned char *buf)
{
unsigned long ret = 0;
unsigned char i;
for(i=0; i<4; i++)
{
ret += (unsigned long)( (buf[i]) * pow(256.,3-i) );
}
return ret;
}
unsigned long u32_lit_2_big(unsigned long ul)
{
unsigned char val[4];
memcpy(&val[0],&ul,4);
return (val[0]<<24) + (val[1]<<16) + (val[2]<<8) + val[3];
}
unsigned short u16_big_2_lit(unsigned char *buf)
{
unsigned short ret = 0;
unsigned char i;
for(i=0; i<2; i++)
{
ret += (unsigned short)( (buf[i]) * pow(256.,1-i) );
}
return ret;
}
| C++ |
#include "coordination.h"
void CCoordination::Convert(ULONG from_coord, ULONG to_coord, _REC_SHP *p_from_Rec, _REC_SHP* p_to_Rec)
{
} | C++ |
#include "renderer.h"
void CRenderer::Draw(_REC_SHP* pRec_shp, ULONG parameter)
{
}
| C++ |
#ifndef COORDINATION_H_INCLUDED
#define COORDINATION_H_INCLUDED
#include "common.h"
class CCoordination
{
public:
void Convert(ULONG from_coord, ULONG to_coord, _REC_SHP *p_from_Rec, _REC_SHP* p_to_Rec);
};
#endif
| C++ |
#ifndef DB_CONNECTOR_H_INCLUDED
#define DB_CONNECTOR_H_INCLUDED
#include "common.h"
class CDbConnector
{
public:
void Insert(CString str_query);
};
#endif
| C++ |
#ifndef RENDERER_H_INCLUDED
#define RENDERER_H_INCLUDED
#include "common.h"
class CRenderer
{
public:
void Draw(_REC_SHP* prec_shp, ULONG parameter);
};
#endif | C++ |
#include "DbConnector.h"
void CDbConnector::Insert(CString str_query)
{
} | C++ |
// Copyright 2009-2011 Google Inc, Shannon Weyrick <weyrick@mozek.us>
#include <iostream>
#include <fstream>
#include <getopt.h>
#include "parser/ParseError.h"
#include "parser/Parser.h"
#include "parser/Toker.h"
#include "model/VarDefImpl.h"
#include "model/Context.h"
#include "model/TypeDef.h"
#include "builder/BuilderOptions.h"
#include "builder/llvm/LLVMJitBuilder.h"
#include "builder/llvm/LLVMLinkerBuilder.h"
#include "Crack.h"
using namespace std;
typedef enum {
jitBuilder,
nativeBuilder,
doubleBuilder = 1001
} builderType;
struct option longopts[] = {
{"builder", true, 0, 'B'},
{"builder-opts", true, 0, 'b'},
{"dump", false, 0, 'd'},
{"help", false, 0, 'h'},
{"debug", false, 0, 'g'},
{"double-builder", false, 0, doubleBuilder},
{"optimize", true, 0, 'O'},
{"verbosity", false, 0, 'v'},
{"no-cache", false, 0, 'C'},
{"no-bootstrap", false, 0, 'n'},
{"no-default-paths", false, 0, 'G'},
{"migration-warnings", false, 0, 'm'},
{"lib", true, 0, 'l'},
{"version", false, 0, 0},
{"stats", false, 0, 0},
{0, 0, 0, 0}
};
static std::string prog;
void version() {
cout << prog << " " << CRACK_VERSION_STRING << endl;
}
void usage(int retval) {
version();
cout << "Usage:" << endl;
cout << " " << prog << " [options] <source file>" << endl;
cout << " -B <name> --builder Main builder to use (llvm-jit or"
" llvm-native)" << endl;
cout << " -b <opts> --builder-opts Builder options in the form "
"foo=bar,baz=bip" << endl;
cout << " -d --dump Dump IR to stdout instead of "
"running or compiling" << endl;
cout << " --double-builder Run multiple internal builders, "
"even in JIT mode." << endl;
cout << " -G --no-default-paths Do not include default module"
" search paths" << endl;
/*
cout << " -C --no-cache Do not cache or use cached modules"
<< endl;
*/
cout << " -C Turn on module caching (unfinished, not fully working)" << endl;
cout << " -g --debug Generate DWARF debug information"
<< endl;
cout << " -O <N> --optimize N Use optimization level N (default"
" 2)" << endl;
cout << " -l <path> --lib Add directory to module search "
"path" << endl;
cout << " -m --migration-warnings Include migration warnings"
<< endl;
cout << " -n --no-bootstrap Do not load bootstrapping modules"
<< endl;
cout << " -v --verbose Verbose output, use more than once"
" for greater effect" << endl;
cout << " --version Emit the version number and exit"
<< endl;
cout << " --stats Emit statistics about compile "
"time operations." << endl;
exit(retval);
}
int main(int argc, char **argv) {
int rc = 0;
prog = basename(argv[0]);
if (argc < 2)
usage(0);
// top level interface
Crack crack;
crack.options->optimizeLevel = 2;
builderType bType = (prog == "crackc") ?
nativeBuilder:
jitBuilder;
string libPath;
if (getenv("CRACK_LIB_PATH"))
libPath = getenv("CRACK_LIB_PATH");
// parse the main module
int opt, idx;
char *subopts, *value;
char * const token[] = { NULL };
bool optionsError = false;
bool useDoubleBuilder = false;
while ((opt = getopt_long(argc, argv, "+B:b:dgO:nCGml:v", longopts, &idx)) !=
-1) {
switch (opt) {
case 0:
// long option tied to a flag variable
if (strcmp(longopts[idx].name,"version") == 0) {
version();
exit(0);
}
if (strcmp(longopts[idx].name,"stats") == 0) {
crack.options->statsMode = true;
}
break;
case '?':
optionsError = true;
break;
case 'B':
if (strncmp("llvm-native",optarg,11) == 0)
bType = nativeBuilder;
else if (strncmp("llvm-jit",optarg,8) == 0)
bType = jitBuilder;
else {
cerr << "Unknown builder: " << optarg << endl;
exit(1);
}
break;
case 'b':
if (!*optarg) {
cerr << "Bad builder options, use the form: foo=bar,baz=bip"
<< endl;
exit(1);
}
subopts = optarg;
while (*subopts != '\0') {
switch (getsubopt(&subopts, token, &value)) {
default:
string v(value);
string::size_type pos;
if ((pos = v.find('=')) != string::npos) {
// as key,val
crack.options->optionMap[v.substr(0,pos)] =
v.substr(pos+1);
}
else {
// as bool
crack.options->optionMap[v] = "true";
}
}
}
break;
case 'd':
crack.options->dumpMode = true;
break;
case 'C':
crack.options->cacheMode = true;
break;
case 'h':
usage(0);
break;
case 'g':
crack.options->debugMode = true;
break;
case 'O':
if (!*optarg || *optarg > '3' || *optarg < '0' || optarg[1]) {
cerr << "Bad value for -O/--optimize: " << optarg
<< "expected 0-3" << endl;
exit(1);
}
crack.options->optimizeLevel = atoi(optarg);
break;
case 'v':
crack.options->verbosity++;
break;
case 'n':
crack.noBootstrap = true;
break;
case 'G':
crack.useGlobalLibs = false;
break;
case 'm':
crack.emitMigrationWarnings = true;
break;
case 'l':
if (libPath.empty()) {
libPath = optarg;
}
else {
libPath.push_back(':');
libPath.append(optarg);
}
break;
case doubleBuilder:
useDoubleBuilder = true;
break;
}
}
// check for options errors
if (optionsError)
usage(1);
if (bType == jitBuilder) {
// immediate execution in JIT
crack.setBuilder(new builder::mvll::LLVMJitBuilder());
if (useDoubleBuilder)
crack.setCompileTimeBuilder(new builder::mvll::LLVMJitBuilder());
}
else {
// compile to native binary
crack.setBuilder(new builder::mvll::LLVMLinkerBuilder());
crack.setCompileTimeBuilder(new builder::mvll::LLVMJitBuilder());
}
if (!libPath.empty())
crack.addToSourceLibPath(libPath);
// are there any more arguments?
if (optind == argc) {
cerr << "You need to define a script or the '-' option to read "
"from standard input." << endl;
rc = -1;
} else if (!strcmp(argv[optind], "-")) {
crack.setArgv(argc - optind, &argv[optind]);
// ensure a reasonable output file name in native mode
if (bType == nativeBuilder &&
crack.options->optionMap.find("out") ==
crack.options->optionMap.end()) {
crack.options->optionMap["out"] = "crack_output";
}
rc = crack.runScript(cin, "<stdin>");
} else {
// it's the script name - run it.
ifstream src(argv[optind]);
if (!src.good()) {
cerr << "Unable to open: " << argv[optind] << endl;
rc = -1;
}
else {
crack.setArgv(argc - optind, &argv[optind]);
rc = crack.runScript(src, argv[optind]);
}
}
if (bType == jitBuilder && !crack.options->dumpMode)
crack.callModuleDestructors();
if (crack.options->statsMode) {
crack.printStats(cerr);
}
return rc;
}
| C++ |
#ifndef SPUG_TYPEINFO_H
#define SPUG_TYPEINFO_H
#include "RCPtr.h"
#include "RCBase.h"
#include <typeinfo>
#include <cxxabi.h>
namespace spug {
SPUG_RCPTR(TypeInfo);
/**
* Wrapper around std::type_info. Currently provides name demangling.
*/
class TypeInfo : public RCBase {
private:
// primitive type info
const std::type_info &ti;
mutable const char *realName;
// copying verboten
TypeInfo(const TypeInfo &other);
void operator =(const TypeInfo &other);
TypeInfo(const std::type_info &primInfo) : ti(primInfo), realName(0) {}
public:
/**
* Returns the TypeInfo instance for a given instance.
*
* \todo keep a registry of types.
*/
template <typename T>
static TypeInfoPtr get(const T &inst) {
return new TypeInfo(typeid(inst));
}
/** Returns the demangled class name. */
const char *getName() const {
int status;
if (!realName)
realName = abi::__cxa_demangle(ti.name(), 0, 0, &status);
return realName;
}
};
} // namespace spug
#endif
| C++ |
/*===========================================================================*\
RCBase.h - reference counted object base class
Copyright (C) 2005 Michael A. Muller
This file is part of spug++.
spug++ is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
spug++ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spug++. If not, see <http://www.gnu.org/licenses/>.
\*===========================================================================*/
#ifndef SPUG_RCBASE_H
#define SPUG_RCBASE_H
namespace spug {
/**
* Reference counting base class. This class is not thread-safe.
*/
class RCBase {
private:
int refCount;
public:
RCBase() : refCount(0) {}
virtual ~RCBase() {}
/** increment the reference count */
void incref() { ++refCount; }
/** decrement the reference count */
void decref() { if (!--refCount) delete this; }
/** return the reference count */
int refcnt() const { return refCount; }
};
}
#endif
| C++ |
/*===========================================================================*\
RCPtr.h - reference counted pointer template.
Copyright (C) 2005 Michael A. Muller
This file is part of spug++.
spug++ is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
spug++ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spug++. If not, see <http://www.gnu.org/licenses/>.
\*===========================================================================*/
#ifndef SPUG_RCPTR_H
#define SPUG_RCPTR_H
#include <iostream>
#include <typeinfo>
#include <exception>
#include <assert.h>
namespace spug {
/**
* Another intrusive reference-counted pointer class. This class is all about
* convenience - users are free to access the underlying pointer if they want
* to.
*
* This is meant to be used to manage an instance of RCBase. It can be used
* with any class that implements incref() and decref().
*/
template <class T>
class RCPtr {
private:
// The raw pointer
T *obj;
public:
/** Copy constructor. */
RCPtr(const RCPtr<T> &other) : obj(other.obj) {
if (obj) obj->incref();
}
/** Constructs a RCPtr from a T*. */
RCPtr(T *obj0) : obj(obj0) {
if (obj) obj->incref();
}
/** Construct from a derived class RCPtr */
template <class U>
RCPtr(const RCPtr<U> &other) : obj(0) {
if (other.get()) {
obj = dynamic_cast<T *>(other.get());
if (!obj)
throw std::bad_cast();
else
obj->incref();
}
}
/** Constructs a RCPtr initialized to NULL. */
RCPtr() : obj(0) {}
~RCPtr() {
if (obj) obj->decref();
}
/** Copies another *RCPtrBase* to the receiver. */
RCPtr<T> &operator =(const RCPtr<T> &other) {
*this = other.obj;
return *this;
}
/** Assigns a T* to the receiver. */
RCPtr<T> &operator =(T *obj0) {
// increment the new object, release the existing object. The
// order is important, as the old object could reference the new
// one.
if (obj0) obj0->incref();
if (obj) obj->decref();
// link to the new one
obj = obj0;
return *this;
}
/**
* Convenience function, equivalent to dynamic_cast<T>(other);
*/
template <class U>
static T *cast(U *other) {
return dynamic_cast<T *>(other);
}
/**
* Like "cast()" but assert that the object is of the correct type.
* Null values will also fail.
*/
template <class U>
static T *acast(U *other) {
T *result = dynamic_cast<T *>(other);
assert(result);
return result;
}
/**
* Convenience function, equivalent to dynamic_cast<T>(other.get());
*/
template <class U>
static T *rcast(const RCPtr<U> &other) {
return dynamic_cast<T *>(other.get());
}
/**
* Like "rcast()" but assert that the object is of the correct type.
* Null values will also fail.
*/
template <class U>
static T *arcast(const RCPtr<U> &other) {
T *result = dynamic_cast<T *>(other.get());
assert(result);
return result;
}
/**
* Used to invoke a member function on the receiver's *ManagedObject*
*/
T *operator ->() const {
return obj;
}
/** Used to deal directly with the receiver's member object. */
T &operator *() const {
return *obj;
}
/** allows us to easily check for NULL in a conditional statement. */
operator int() const {
return (obj != NULL);
}
/**
Allows us to compare the pointer value of two Managed Object
Pointers.
*/
template <class U>
int operator ==(const RCPtr<U> &other) const {
return obj == other.get();
}
template <class U>
int operator !=(const RCPtr<U> &other) const {
return obj != other.get();
}
int operator !=(const void *ptr) const {
return obj != ptr;
}
/**
Allows us to compare the pointer value to any kind of pointer.
Basically, this exists to permit comparison to NULL.
*/
int operator ==(const void *ptr) const {
return (void*)obj == ptr;
}
/**
Allows us to compare the pointer value to any kind of pointer.
Basically, this exists to permit comparison to NULL.
*/
friend int operator ==(const void *ptr1, const RCPtr<T> &ptr2) {
return (void*)ptr2.obj == ptr1;
}
/**
Allows us to compare the pointer value to any kind of pointer.
Basically, this exists to permit comparison to NULL.
*/
int operator ==(int ptr) const {
return (int)obj == ptr;
}
/**
Allows us to compare the pointer value to any kind of pointer.
Basically, this exists to permit comparison to NULL.
*/
friend int operator ==(int ptr1, const RCPtr<T> &ptr2) {
return (int)ptr2.obj == ptr1;
}
/**
* Returns the underlying raw pointer.
*/
T *get() const {
return obj;
}
};
} // namespace spug
/**
macro to easily define RCPtr instances, complete with a forward
declaration.
*/
#define SPUG_RCPTR(cls) class cls; typedef spug::RCPtr<cls> cls##Ptr;
#endif
| C++ |
/*===========================================================================*\
This header mainly defines the macro SPUG_FMT() - which can be used to
format a spug::String in-place using the stream operator:
void foo(const spug::String &str);
foo(SPUG_FSTR("this is an integer: " << 100 << " this is a float: " <<
1.0
)
)
Copyright (C) 2007 Michael A. Muller
This file is part of spug++.
spug++ is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
spug++ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spug++. If not, see <http://www.gnu.org/licenses/>.
\*===========================================================================*/
#ifndef SPUG_STRINGFMT_H
#define SPUG_STRINGFMT_H
#include <sstream>
namespace spug {
/**
* For some reason, on gcc 4.1, an std::ostringstream temporary doesn't
* behave the same as an ostring with regards to the "<<" operator - in
* particular, 'std::ostringstream() << "string val"' will treat the
* string as a void*, printing its address. This class solves that
* problem.
*/
class StringFmt {
private:
std::ostringstream out;
public:
template <typename T>
std::ostream &operator <<(const T &val) {
out << val;
return out;
}
};
}
#define SPUG_FSTR(msg) \
static_cast<const std::ostringstream&>(spug::StringFmt() << msg).str()
#endif
| C++ |
// Copyright 2012 Google Inc.
// macro that is effectively an assert with iostream output.
#ifndef SPUG_CHECK_H
#define SPUG_CHECK_H
#include <iostream>
#include <stdlib.h>
#define SPUG_CHECK(condition, msg) \
if (!(condition)) { \
std::cerr << __FILE__ << ':' << __FUNCTION__ << ':' << __LINE__ << \
": [" << #condition << "] " << msg << std::endl; \
abort(); \
}
#endif
| C++ |
/*===========================================================================*\
Copyright (C) 2006 Michael A. Muller
This file is part of spug++.
spug++ is free software: you can redistribute it and/or modify it under the
terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
spug++ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with spug++. If not, see <http://www.gnu.org/licenses/>.
\*===========================================================================*/
#ifndef SPUG_EXCEPTION_H
#define SPUG_EXCEPTION_H
#include <exception>
#include <string>
#include <iostream>
#include "TypeInfo.h"
namespace spug {
/**
* Simple exception base class that allows exceptions to be thrown with an
* informative message.
*/
class Exception : public std::exception {
protected:
std::string msg;
public:
Exception() {}
Exception(const char *msg) : msg(msg) {}
Exception(const std::string &msg) : msg(msg) {}
~Exception() throw () {}
virtual const char *getClassName() const {
return TypeInfo::get(*this)->getName();
}
/**
* Returns the user supplied message string.
*/
virtual std::string getMessage() const {
return msg;
}
friend std::ostream &
operator <<(std::ostream &out, const Exception &err);
};
inline std::ostream &operator <<(std::ostream &out, const Exception &err) {
out << err.getClassName() << ": " << err.getMessage();
return out;
}
// some macros to make it extremely easy to define derived exceptions
// Defines an exception class derived from an arbitrary base class
#define SPUG_DERIVED_EXCEPTION(cls, base) \
class cls : public base { \
public: \
cls() {} \
cls(const char *msg) : base(msg) {} \
cls(const std::string &msg) : base(msg) {} \
virtual const char *getClassName() const { return #cls; } \
};
// defines an exception class derived from spug::Exception
#define SPUG_EXCEPTION(cls) SPUG_DERIVED_EXCEPTION(cls, spug::Exception)
}
#endif
| C++ |
// Copyright 2009 Google Inc.
#ifndef PARSER_H
#define PARSER_H
#include <list>
#include <string>
#include <vector>
#include <map>
#include <iostream>
#include <spug/Exception.h>
#include "Toker.h"
#include "model/FuncCall.h"
#include "model/GenericParm.h"
#include "model/Context.h"
namespace model {
SPUG_RCPTR(ArgDef);
SPUG_RCPTR(FuncDef);
SPUG_RCPTR(Expr);
class Generic;
SPUG_RCPTR(Initializers);
class Namespace;
SPUG_RCPTR(TypeDef);
SPUG_RCPTR(VarDef);
};
namespace parser {
class Parser;
// Callback interface.
struct ParserCallback {
virtual void run(parser::Parser *parser, Toker *toker,
model::Context *context
) = 0;
};
class Parser {
public:
// parse events that can be tied to a callback
enum Event {
funcDef, // after open paren for args in a functino def.
funcEnter, // after first curly brace of the function block.
funcLeave, // before the last curly brace of the function block.
funcForward, // right after a forward declaration
classDef, // after "class" keyword in a class def
classEnter, // after opening brace at the beginning of a class def.
classLeave, // before closing brace at the end of a class def.
variableDef, // after the semicolon, assignment or comma of a variable
// definition.
exprBegin, // beginning of an expression.
controlStmt, // after the starting keyword of a control statement
// (including "import" and the empty statement)
noCallbacks, // special event that you can't add callbacks to.
eventSentinel // MUST BE THE LAST SYMBOL IN THE ENUM.
};
private:
enum { noPrec, logOrPrec, logAndPrec, bitOrPrec, bitXorPrec,
bitAndPrec, cmpPrec, shiftPrec, addPrec, multPrec, unaryPrec
};
Toker &toker;
// the module context, and the current context.
model::ContextPtr moduleCtx, context;
// sequential identifier used in nested block namespaces
int nestID;
/**
* This class essentially lets us manage the context stack with the
* program's stack. We push the context by creating an instance, and
* pop it by calling restore() or falling through to the destructor.
*/
friend class ContextStackFrame;
class ContextStackFrame {
private:
bool restored;
Parser &parser;
model::ContextPtr context;
public:
ContextStackFrame(Parser &parser,
model::Context *context
) :
restored(false),
parser(parser),
context(parser.context) {
parser.context = context;
}
~ContextStackFrame() {
if (!restored)
restore();
}
void restore() {
assert(!restored);
parser.context = context;
restored = true;
}
model::Context &parent() {
assert(!restored);
return *context;
}
};
typedef std::map<std::string, unsigned> OpPrecMap;
OpPrecMap opPrecMap;
// callbacks for each event type.
typedef std::vector<ParserCallback *> CallbackVec;
CallbackVec callbacks[eventSentinel];
/**
* Add a new definition to the current context or nearest definition
* context.
*/
void addDef(model::VarDef *context);
void addFuncDef(model::FuncDef *funcDef);
/**
* Returns the next token from the tokenizer and stores its location in
* the current context.
*/
Token getToken();
/**
* Returns the precedence of the specified operator.
*/
unsigned getPrecedence(const std::string &op);
/** Special kind of error function used for unexpected tokens. */
void unexpected(const Token &tok, const char *userMsg = 0);
/**
* Get the next token and make sure it is of type 'type' otherwise
* unexpected(tok, error);
*/
void expectToken(Token::Type type, const char *error);
/** Look up a binary operator, either as a stand-alone operator
* defintiion with two args or a method with one arg.
*
* @param name the operator name (e.g. "oper +")
* @param args a two element arg list, lhs and rhs values. This will be
* modified on return to include the correct argument list for the
* function or method.
* @returns the function, null if there was no match.
*/
model::FuncDefPtr lookUpBinOp(const std::string &name,
model::FuncCall::ExprVec &args
);
/**
* Parse an annotation and execute it.
*/
void parseAnnotation();
/**
* Parse a single statement.
* @param defsAllowed true if a definition may be provided instead of a
* statement. Statements in block contexts may be definitions,
* simple statements in conditionals must not be.
* @returns the context that this statement terminates to. If non-null,
* the statement is terminal in all contexts from the current context
* to the returned context (non-inclusive).
*/
model::ContextPtr parseStatement(bool defsAllowed);
/**
* Parse a block - a sequence of statements in the same execution
* context. A block is "nested" if it is inside the implicit file scope
* block and wrapped in curly brackets.
* @returns the context that this statement terminates to. See
* parseStatement().
*/
model::ContextPtr parseBlock(bool nested, Event closeEvent);
/**
* Creates a variable reference complete with an implicit "this" if
* necessary.
*/
model::ExprPtr createVarRef(model::Expr *receiver, model::VarDef *var,
const Token &tok);
/**
* Create an assignment expression, complete with an implicit "this" if
* necessary.
*/
model::ExprPtr createAssign(model::Expr *container, const Token &ident,
model::VarDef *var,
model::Expr *val
);
/**
* Create a variable reference expression for the identifier, complete
* with an implicit "this" if necessary.
* @param undefinedError If this is not null, it is an alternate error
* to use if the variable is undefined and it also makes the function
* return null rather than raising a parse error if the variable is
* an OverloadDef with multiple variations.
*/
model::ExprPtr createVarRef(model::Expr *receiver, const Token &ident,
const char *undefinedError = 0
);
/**
* Parse the rest of an explicit "oper" name.
*/
std::string parseOperSpec();
/**
* Parse and emit a function call.
*/
model::FuncCallPtr parseFuncCall(const Token &ident,
const std::string &funcName,
model::Namespace *ns,
model::Expr *container
);
/**
* Parse the kinds of things that can come after an identifier.
*
* @param container the aggregate that the identifier is scoped to, as
* in "container.ident" This can be null, in which case the
* identifier is scoped to the local context.
* @param ident The identifier's token.
*/
model::ExprPtr parsePostIdent(model::Expr *container,
const Token &ident
);
/**
* Parse an interpolated string.
*
* @param expr the receiver of the interpolated string operation.
*/
model::ExprPtr parseIString(model::Expr *expr);
/**
* Parse a sequence constant.
*
* @param containerType the type of the sequence that we are
* initializing.
*/
model::ExprPtr parseConstSequence(model::TypeDef *containerType);
/**
* Parse a "typeof" expression.
*/
model::TypeDefPtr parseTypeof();
/**
* If the expression is a VarRef referencing a TypeDef, return the
* TypeDef. Otherwise returns null.
*/
static model::TypeDef *convertTypeRef(model::Expr *expr);
/**
* Parse the ternary operator's expression.
* @param cond the conditional expression.
*/
model::ExprPtr parseTernary(model::Expr *cond);
/**
* Parse a secondary expression. Secondary expressions include a the
* dot operator, binary operators and the bracket operators and their
* associated expressions.
*
* @param expr the primary expression that this secondary expression
* modifies.
* @param precedence the current level of operator precedence.
*/
model::ExprPtr parseSecondary(model::Expr *expr,
unsigned precedence = 0
);
/**
* Parse an expression.
*
* @param precedence The function will not parse an operator of lower
* precedence than this parameter. So if we're parsing the right
* side of 'x * y', and the precedence of '*' is 10, and we encounter
* the sequence 'a + b' ('+' has precedence of 8), we'll stop parsing
* after the 'a'.
*/
model::ExprPtr parseExpression(unsigned precedence = 0);
void parseMethodArgs(std::vector<model::ExprPtr> &args,
Token::Type terminator = Token::rparen
);
/**
* Parse the "specializer" after a generic type name.
* @param tok the left bracket token of the generic specifier.
* @param generic defined when doing this within a generic definition.
*/
model::TypeDef *parseSpecializer(const Token &tok,
model::TypeDef *typeDef,
model::Generic *generic = 0
);
model::ExprPtr parseConstructor(const Token &tok, model::TypeDef *type,
Token::Type terminator
);
model::TypeDefPtr parseTypeSpec(const char *errorMsg = 0,
model::Generic *generic = 0
);
void parseModuleName(std::vector<std::string> &moduleName);
void parseArgDefs(std::vector<model::ArgDefPtr> &args, bool isMethod);
/**
* Parse the initializer list after an oper init.
*/
void parseInitializers(model::Initializers *inits, model::Expr *receiver);
enum FuncFlags {
normal, // normal function
hasMemberInits, // function with member/base class initializers
// ("oper new")
hasMemberDels, // function with member/base class destructors
// ("oper del")
reverseOp // reverse binary operator.
};
/**
* Parse a function definition.
* @param returnType function return type.
* @param nameTok the last token parsed in the function name.
* @param name the full (but unqualified) function name.
* @param funcFlags flags defining special processing rules for the
* function (whether initializers or destructors need to be parsed
* and emitted).
* @param expectedArgCount if > -1, this is the expected number of arguments.
* @returns the number of actual arguments.
*/
int parseFuncDef(model::TypeDef *returnType, const Token &nameTok,
const std::string &name,
FuncFlags funcFlags,
int expectedArgCount
);
/**
* Parse a variable definition initializer. Deals with the special
* syntax for constructors and sequence constants.
*/
model::ExprPtr parseInitializer(model::TypeDef *type,
const std::string &varName
);
/**
* Parse an alias statement.
*/
void parseAlias();
/**
* Parse a definition. Returns false if there was no definition.
* This will always parse the type specializer if it exists, and will
* update "type" to point to its specialization.
* @param type the parsed type.
*/
bool parseDef(model::TypeDef *&type);
/** Parse a constant definition. */
void parseConstDef();
// statements
/**
* Parse a clause, which can either be a an expression statement or a
* definition.
*/
void parseClause(bool defsAllowed);
/*
* @returns the context that this statement terminates to. See
* parseStatement().
*/
model::ContextPtr parseIfClause();
/** Parse the condition in a 'while', 'for' or 'if' statement */
model::ExprPtr parseCondExpr();
/*
* @returns the context that this statement terminates to. See
* parseStatement().
*/
model::ContextPtr parseIfStmt();
void parseWhileStmt();
void parseForStmt();
void parseReturnStmt();
model::ContextPtr parseTryStmt();
model::ContextPtr parseThrowStmt();
/**
* Parse an import statement. 'ns' is the namespace in which to alias
* imported symbols.
*/
void parseImportStmt(model::Namespace *ns);
/**
* Parse a function definition after an "oper" keyword.
*/
void parsePostOper(model::TypeDef *returnType);
/** Parse the generic parameter list */
void parseGenericParms(model::GenericParmVec &parms);
void recordIStr(model::Generic *generic);
void recordBlock(model::Generic *generic);
void recordParenthesized(model::Generic *generic);
model::TypeDefPtr parseClassDef();
public:
// XXX should be protected, once required functionality is migrated out.
// error checking functions
model::VarDefPtr checkForExistingDef(const Token &tok,
const std::string &name,
bool overloadOk = false
);
// XXX should be protected, once required functionality is migrated out.
// checks if "existingDef" is an OverloadDef that contains an overload
// matching argDefs. Raises an error if this is an illegal overload,
// otherwise returns the function that we're overriding if the override
// needs to be considered (for implementation of a virtual or forward
// function).
model::FuncDefPtr checkForOverride(model::VarDef *existingDef,
const model::ArgVec &argDefs,
model::Namespace *ownerNS,
const Token &nameTok,
const std::string &name
);
// current parser state.
enum State { st_base, st_optElse, st_notBase } state;
Parser(Toker &toker, model::Context *context);
void parse();
void parseClassBody();
/**
* Throws a parse error about an attempt to override a variable that has
* been defined in the same context.
* @param tok the last parsed token
* @param existing the existing variable definition.
*/
void redefineError(const Token &tok,
const model::VarDef *existing
);
/**
* throws a ParseError, properly formatted with the location and
* message text.
*/
void error(const Token &tok, const std::string &msg);
/** Writes a warning message to standard error. */
void warn(const Location &loc, const std::string &msg);
/** Writes a warning message to standard error. */
void warn(const Token &tok, const std::string & msg);
/**
* Add a new callback to the parser. It is the responsibility of the
* caller to manage the lifecycle of the callback and to insure that it
* remains in existence until it is removed with removeCallback().
*/
void addCallback(Event event, ParserCallback *callback);
/**
* Remove an existing callback. This removes only the first added
* instance of the callback, so if the same callback has been added N
* times, N - 1 instances will remain.
* Returns true if the callback was removed, false if it was not found.
*/
bool removeCallback(Event event, ParserCallback *callback);
/**
* Run all callbacks associated with the event.
*
* Returns true if any callbacks were called.
*/
bool runCallbacks(Event event);
};
} // namespace parser
#endif
| C++ |
// Copyright 2003 Michael A. Muller
// Copyright 2009 Google Inc.
#include "Token.h"
using namespace std;
using namespace parser;
Token::Token() :
type(Token::end) {
}
Token::Token(Type type, const std::string &data, const Location &loc) :
type(type),
data(data),
loc(loc) {
}
| C++ |
// Copyright 2003 Michael A. Muller
#ifndef LOCATION_H
#define LOCATION_H
#include <spug/RCBase.h>
#include <spug/RCPtr.h>
#include <iostream>
#include <string>
#include <map>
namespace parser {
// forward declaration of Location map so we can befriend it.
class LocationMap;
class LocationImpl : public spug::RCBase {
friend class LocationMap;
private:
std::string name;
int lineNumber;
public:
LocationImpl(const char *name, int lineNumber) :
name(name),
lineNumber(lineNumber) {
}
/** so that we can construct one of these prior to assigning it */
LocationImpl();
/**
* Returns the file/stream name. The name is guaranteed to be in
* existence for as long as the instance is
*/
const char *getName() const {
return name.c_str();
}
/** returns the source line number */
int getLineNumber() const {
return lineNumber;
}
bool operator ==(const LocationImpl &other) const {
return name == other.name && lineNumber == other.lineNumber;
}
bool operator !=(const LocationImpl &other) const {
return !(*this == other);
}
friend std::ostream &
operator <<(std::ostream &out, const LocationImpl &loc) {
return out << loc.name << ':' << std::dec << loc.lineNumber;
}
};
SPUG_RCPTR(LocationImpl);
/**
* Describes a location in source code.
*
* These are managed in the LocationMap
*/
class Location : public LocationImplPtr {
friend class LocationMap;
private:
public:
/**
* You probably don't want to use this: use LocationMap::getLocation()
* to keep them cached instead.
*/
Location(LocationImpl *impl) : LocationImplPtr(impl) {}
/** so that we can construct one of these prior to assigning it */
Location() {}
/**
* Returns the file/stream name. The name is guaranteed to be in
* existence for as long as the instance is
*/
const char *getName() const {
return get()->getName();
}
/** returns the source line number */
int getLineNumber() const {
return get()->getLineNumber();
}
friend std::ostream &
operator <<(std::ostream &out, const Location &loc) {
return out << *loc;
}
};
} // namespace parser
#endif
| C++ |
// Copyright 2009 Google Inc., Shannon Weyrick <weyrick@mozek.us>
#include "Parser.h"
#include <assert.h>
#include <sstream>
#include <stdexcept>
#include <spug/Exception.h>
#include <spug/StringFmt.h>
#include "model/Annotation.h"
#include "model/ArgDef.h"
#include "model/AssignExpr.h"
#include "model/Branchpoint.h"
#include "model/CompositeNamespace.h"
#include "model/CleanupFrame.h"
#include "model/Generic.h"
#include "model/VarDefImpl.h"
#include "model/Context.h"
#include "model/FuncDef.h"
#include "model/FuncCall.h"
#include "model/GetRegisterExpr.h"
#include "model/Expr.h"
#include "model/ImportedDef.h"
#include "model/Initializers.h"
#include "model/IntConst.h"
#include "model/MultiExpr.h"
#include "model/FloatConst.h"
#include "model/ModuleDef.h"
#include "model/NullConst.h"
#include "model/ResultExpr.h"
#include "model/SetRegisterExpr.h"
#include "model/StrConst.h"
#include "model/StubDef.h"
#include "model/TypeDef.h"
#include "model/OverloadDef.h"
#include "model/VarDef.h"
#include "model/VarRef.h"
#include "builder/Builder.h"
#include "ParseError.h"
#include <cstdlib>
#define __STDC_LIMIT_MACROS 1
#include <stdint.h>
using namespace std;
using namespace parser;
using namespace model;
void Parser::addDef(VarDef *varDef) {
FuncDef *func = FuncDefPtr::cast(varDef);
ContextPtr defContext = context->getDefContext();
VarDefPtr storedDef = defContext->addDef(varDef);
// if this was a function that was added to an ancestor context, we need to
// rebuild any intermediate overload definitions.
if (func && defContext != context)
context->insureOverloadPath(defContext.get(),
OverloadDefPtr::arcast(storedDef)
);
// if the definition context is a class context and the definition is a
// function and this isn't the "Class" class (which is its own meta-class),
// add it to the meta-class.
TypeDef *type;
if (defContext->scope == Context::instance && func) {
type = TypeDefPtr::arcast(defContext->ns);
if (type != type->type.get())
type->type->addAlias(storedDef.get());
}
}
void Parser::addFuncDef(FuncDef *funcDef) {
addDef(funcDef);
}
Token Parser::getToken() {
Token tok = toker.getToken();
context->setLocation(tok.getLocation());
// short-circuit the parser for an annotation, which can occur anywhere.
while (tok.isAnn() || tok.getType() == Token::popErrCtx) {
if (tok.isAnn())
parseAnnotation();
else
context->popErrorContext();
tok = toker.getToken();
context->setLocation(tok.getLocation());
}
return tok;
}
unsigned Parser::getPrecedence(const string &op) {
OpPrecMap::iterator iter = opPrecMap.find(op);
assert(iter != opPrecMap.end() && "got operator with no precedence");
return iter->second;
}
void Parser::unexpected(const Token &tok, const char *userMsg) {
Location loc = tok.getLocation();
stringstream msg;
msg << "token " << tok.getData() << " was not expected at this time";
// add the user message, if provided
if (userMsg)
msg << ", " << userMsg;
error(tok, msg.str());
}
void Parser::expectToken(Token::Type type, const char *error) {
Token tok = getToken();
if (tok.getType() != type)
unexpected(tok, error);
}
FuncDefPtr Parser::lookUpBinOp(const string &op, FuncCall::ExprVec &args) {
FuncCall::ExprVec exprs(1);
exprs[0] = args[1];
string fullName = "oper " + op;
// The default types of constants are PDNTs - integer constants default to
// the int type, float constants default to float type (as long as the
// constants fit into the minimum sizes of these types). We usually don't
// want to check for methods on constants because if we did, the constant's
// method would match a non-const UNT, so something like "int64 + 1" would
// match "int + int".
// The one exception to this rule is when we are performing a binary
// operation on two constants - if the compiler were smarter, it would fold
// these into a single constant. But for now, we basically want to do a
// method check if both values are equivalent constant types (both float or
// both int) or only on the float if one is a float and the other is an
// int, float being a more inclusive type for constants.
// We can simplify the logic on this by introducing the concept of
// "weights". A non-const value is "heavier" than a const value, a float
// const is heavier than an integer constsnt. We do a method check (or a
// reverse method check) on a value if it is of the same weight or heavier
// than tha other type.
// The weight calculation amounts to: int const has a weight of 1, float
// const has a weight of 2, non-const has a weight of 3.
int leftWeight = (IntConstPtr::rcast(args[0]) ? 0 : 2) +
(FloatConstPtr::rcast(args[0]) ? 0 : 1);
int rightWeight = (IntConstPtr::rcast(args[1]) ? 0 : 2) +
(FloatConstPtr::rcast(args[1]) ? 0 : 1);
bool checkLeftMethods = leftWeight >= rightWeight;
bool checkRightMethods = rightWeight >= leftWeight;
// see if it is a method of the left-hand type
FuncDefPtr func;
if (checkLeftMethods)
func = context->lookUp(fullName, exprs, args[0]->type.get());
// not there, try the right-hand type
if (!func && checkRightMethods) {
exprs[0] = args[0];
func = context->lookUp("oper r" + op, exprs, args[1]->type.get());
}
// not there either, check for a non-method operator.
if (!func) {
exprs[0] = args[0];
exprs.push_back(args[1]);
func = context->lookUp(fullName, exprs);
}
args = exprs;
return func;
}
void Parser::parseClause(bool defsAllowed) {
Token tok = getToken();
state = st_notBase;
ExprPtr expr;
VarDefPtr def;
TypeDefPtr primaryType;
if (tok.isTypeof()) {
primaryType = parseTypeof();
} else if (tok.isAlias()) {
if (!defsAllowed)
error(tok, "Aliasing is not allowed in this context.");
parseAlias();
} else if (tok.isIdent()) {
// if the identifier is a type, deal with it later. Otherwise deal with
// it as a variable
def = context->ns->lookUp(tok.getData());
primaryType = TypeDefPtr::rcast(def);
if (!primaryType) {
if (!def) {
// XXX think I want to move this into expression, it's just as valid
// for an existing identifier (in a parent context) as for a
// non-existing one.
// unknown identifier. if the next token(s) is ':=' (the "define"
// operator) then this is an assignment
Token tok2 = getToken();
if (tok2.isDefine()) {
if (!defsAllowed)
error(tok, "definition is not allowed in this context.");
expr = parseExpression();
context->emitVarDef(expr->type.get(), tok, expr.get());
// trick the expression processing into not happening
expr = 0;
} else {
error(tok, SPUG_FSTR("Unknown identifier " << tok.getData()));
}
} else {
toker.putBack(tok);
runCallbacks(exprBegin);
expr = parseExpression();
}
}
// not an identifier
} else if (tok.isConst()) {
if (!defsAllowed)
error(tok, "definition is not allowed in this context");
parseConstDef();
return;
} else {
toker.putBack(tok);
runCallbacks(exprBegin);
expr = parseExpression();
}
// if we got a type, try to parse a definition.
if (primaryType) {
TypeDef *typeDef = primaryType.get();
context->checkAccessible(typeDef);
if (parseDef(typeDef)) {
if (!defsAllowed)
error(tok, "definition is not allowed in this context");
// bypass expression emission and semicolon parsing (parseDef()
// consumes it's own semicolon)
return;
} else {
// we didn't parse a definition
// see if this is a define of a variable that happens to bear the
// same name as a class.
Token tok2 = getToken();
if (def && tok2.isDefine()) {
if (def->getOwner() == context->ns.get())
redefineError(tok2, def.get());
expr = parseExpression();
context->emitVarDef(expr->type.get(), tok, expr.get());
// don't do expression processing
expr = 0;
} else if (tok2.isAssign()) {
error(tok2, "You cannot assign to a constant, class or function.");
} else {
// try treating the class as a primary.
toker.putBack(tok2);
expr = context->createVarRef(typeDef);
expr = parseSecondary(expr.get());
}
}
}
// if we got an expression, emit it.
if (expr) {
context->createCleanupFrame();
expr->emit(*context)->handleTransient(*context);
context->closeCleanupFrame();
}
// consume a semicolon, put back a block terminator
tok = getToken();
if (tok.isEnd() || tok.isRCurly())
toker.putBack(tok);
else if (!tok.isSemi())
unexpected(tok, "expected semicolon or a block terminator");
}
void Parser::parseAnnotation() {
AnnotationPtr ann;
{
// create a new context whose construct is tha annotation construct.
ContextPtr parentContext = context;
ContextPtr ctx = context->createSubContext(Context::module);
ContextStackFrame cstack(*this, ctx.get());
context->construct = context->getCompileTimeConstruct();
Token tok = toker.getToken();
context->setLocation(tok.getLocation());
// if we get an import keyword, parse the import statement.
if (tok.isImport()) {
parseImportStmt(parentContext->compileNS.get());
return;
}
if (!tok.isIdent())
error(tok, "Identifier or import statement expected after '@' sign");
// lookup the annotation
ann = context->lookUpAnnotation(tok.getData());
if (!ann)
error(tok, SPUG_FSTR("Undefined annotation " << tok.getData()));
}
// invoke in the outer context
ann->invoke(this, &toker, context.get());
}
ContextPtr Parser::parseStatement(bool defsAllowed) {
// peek at the next token
Token tok = getToken();
state = st_notBase;
// check for statements
if (tok.isSemi()) {
// null statement
runCallbacks(controlStmt);
return 0;
} else if (tok.isIf()) {
runCallbacks(controlStmt);
return parseIfStmt();
} else if (tok.isWhile()) {
runCallbacks(controlStmt);
parseWhileStmt();
// while statements are never terminal, there's always the possibility
// that we could never execute the body.
return 0;
} else if (tok.isElse()) {
unexpected(tok, "'else' with no matching 'if'");
} else if (tok.isReturn()) {
runCallbacks(controlStmt);
if (context->scope == Context::module)
error(tok, "Return statement not allowed in module scope");
parseReturnStmt();
return context->getToplevel()->getParent();
} else if (tok.isImport()) {
runCallbacks(controlStmt);
parseImportStmt(context->ns.get());
return 0;
} else if (tok.isClass()) {
if (!defsAllowed)
error(tok, "class definitions are not allowed in this context");
parseClassDef();
return 0;
} else if (tok.isBreak()) {
runCallbacks(controlStmt);
Branchpoint *branch = context->getBreak();
if (!branch)
error(tok,
"Break can only be used in the body of a while, for or "
"switch statement."
);
context->builder.emitBreak(*context, branch);
tok = getToken();
if (!tok.isSemi())
toker.putBack(tok);
assert(branch->context);
return branch->context;
} else if (tok.isContinue()) {
runCallbacks(controlStmt);
Branchpoint *branch = context->getContinue();
if (!branch)
error(tok,
"Continue can only be used in the body of a while or for "
"loop."
);
context->builder.emitContinue(*context, branch);
tok = getToken();
if (!tok.isSemi())
toker.putBack(tok);
assert(branch->context);
return branch->context;
} else if (tok.isFor()) {
parseForStmt();
// for statements are like while - never terminal
return 0;
} else if (tok.isThrow()) {
return parseThrowStmt();
} else if (tok.isTry()) {
return parseTryStmt();
}
toker.putBack(tok);
state = st_base;
parseClause(defsAllowed);
return 0;
}
ContextPtr Parser::parseBlock(bool nested, Parser::Event closeEvent) {
Token tok;
ContextPtr terminal;
// keeps track of whether we've emitted a warning about stuff after a
// terminal statement.
bool gotStuffAfterTerminalStatement = false;
while (true) {
state = st_base;
// peek at the next token
tok = getToken();
// check for a different block terminator depending on whether we are
// nested or not.
bool gotBlockTerminator = false;
if (tok.isRCurly()) {
if (!nested)
unexpected(tok, "expected statement or end-of-file.");
gotBlockTerminator = true;
} else if (tok.isEnd()) {
if (nested)
unexpected(tok, "expected statement or closing brace.");
gotBlockTerminator = true;
}
if (gotBlockTerminator) {
// if there are callbacks, we have to put the last token back and
// then run the callbacks and then make sure that we got the same
// terminator again (since the callbacks can insert tokens into the
// stream).
if (callbacks[closeEvent].size()) {
toker.putBack(tok);
runCallbacks(closeEvent);
Token tempTok = toker.getToken();
if (!tempTok.isRCurly()) {
// if the token is not what it was before, one of the callbacks
// has changed the token stream and we need to go back to the
// loop.
toker.putBack(tempTok);
continue;
}
}
// make sure that the context contains no forward declarations
context->checkForUnresolvedForwards();
// generate all of the cleanups, but not if we already did this (got
// a terminal statement) or we're at the top-level module (in which
// case we'll want to generate cleanups in a static cleanup function)
if (!context->terminal && nested)
context->builder.closeAllCleanups(*context);
return terminal;
}
toker.putBack(tok);
// if we already got a terminal statement, anything else is just dead
// code - warn them about the first thing. TODO: convert this to a
// warning once we can turn off code generation.
if (context->terminal && !gotStuffAfterTerminalStatement) {
error(tok, "unreachable code");
gotStuffAfterTerminalStatement = true;
}
terminal = parseStatement(true);
if (terminal)
if (terminal != context)
context->terminal = true;
else
terminal = 0;
}
}
ExprPtr Parser::createVarRef(Expr *container, VarDef *var, const Token &tok) {
// if the definition is for an instance variable, emit an implicit
// "this" dereference. Otherwise just emit the variable
if (TypeDefPtr::cast(var->getOwner()) &&
!var->isStatic()
) {
// make sure this is not a method - can't deal with that yet.
if (OverloadDefPtr::cast(var))
error(tok, SPUG_FSTR("Trying to get the value of " << tok.getData() <<
", first class methods are not supported yet."
)
);
// if there's no container, try to use an implicit "this"
ExprPtr receiver = container ? container :
context->makeThisRef(tok.getData());
return context->createFieldRef(receiver.get(), var);
} else {
return context->createVarRef(var);
}
}
ExprPtr Parser::createVarRef(Expr *container, const Token &ident,
const char *undefinedError
) {
Namespace &varNS = container ? *container->type : *context->ns;
VarDefPtr var = varNS.lookUp(ident.getData());
if (!var)
error(ident,
undefinedError ? undefinedError :
SPUG_FSTR("Undefined variable: " << ident.getData()).c_str()
);
context->checkAccessible(var.get());
// check for an overload definition - if it is one, make sure there's only
// a single overload.
OverloadDef *ovld = OverloadDefPtr::rcast(var);
if (ovld) {
if (!ovld->isSingleFunction())
if (undefinedError)
return 0;
else
error(ident,
SPUG_FSTR("Cannot reference function " << ident.getData() <<
" because there are multiple overloads."
)
);
else if (undefinedError)
// this is a funnny edge condition - we could have come here after
// failing to match an overload, in which case we're looking for a
// variable. In that case, resolving to an overload is a failure.
return 0;
// make sure that the implementation has been defined
ovld->createImpl();
}
return createVarRef(container, var.get(), ident);
}
ExprPtr Parser::createAssign(Expr *container, const Token &ident,
VarDef *var,
Expr *val
) {
if (TypeDefPtr::cast(var->getOwner())) {
// if there's no container, try to use an implicit "this"
ExprPtr receiver = container ? container :
context->makeThisRef(ident.getData());
return AssignExpr::create(*context, receiver.get(), var, val);
} else {
return AssignExpr::create(*context, var, val);
}
}
// obj.oper <symbol>
string Parser::parseOperSpec() {
Token tok = getToken();
const string &ident = tok.isIdent() ? tok.getData() : "";
if (tok.isMinus() || tok.isTilde() || tok.isBang() ||
tok.isEQ() || tok.isNE() || tok.isLT() || tok.isLE() ||
tok.isGE() || tok.isGT() || tok.isPlus() || tok.isSlash() ||
tok.isAsterisk() || tok.isPercent() ||
ident == "init" || ident == "release" || ident == "bind" ||
ident == "del" || ident == "call" || tok.isAugAssign()
) {
return "oper " + tok.getData();
} else if (tok.isIncr() || tok.isDecr()) {
// make sure the next token is an "x"
Token tok2 = getToken();
if (!tok2.isIdent() || tok2.getData() != "x")
unexpected(tok2,
SPUG_FSTR("expected an 'x' after oper " <<
tok.getData()
).c_str()
);
return "oper " + tok.getData() + "x";
} else if (ident == "x") {
tok = getToken();
if (tok.isIncr() || tok.isDecr())
return "oper x" + tok.getData();
else
unexpected(tok,
"Expected an increment or decrement operator after oper x."
);
} else if (tok.isLBracket()) {
tok = getToken();
if (!tok.isRBracket())
error(tok, "Expected right bracket in 'oper ['");
// see if this is "[]="
tok = getToken();
if (tok.isAssign()) {
return "oper []=";
} else {
toker.putBack(tok);
return "oper []";
}
} else if (ident == "to") {
TypeDefPtr type = parseTypeSpec();
return "oper to " + type->getFullName();
} else if (ident == "r") {
tok = getToken();
if (tok.isBinOp())
return "oper r" + tok.getData();
else
error(tok, "Expected a binary operator after reverse designator");
} else {
unexpected(tok, "expected legal operator name or symbol.");
}
}
FuncCallPtr Parser::parseFuncCall(const Token &ident, const string &funcName,
Namespace *ns,
Expr *container
) {
VarRefPtr var;
// parse the arg list
FuncCall::ExprVec args;
parseMethodArgs(args);
// look up the variable
// lookup the method from the variable context's type context
// if the container is a class, assume that this is a lookup in a specific
// base class and allow looking up overrides for it (this won't work if we
// ever give class objects a vtable because it will break meta-class
// methods, but we need to replace the specific lookup syntax anyway)
// XXX needs to handle callable objects.
FuncDefPtr func = context->lookUp(funcName, args, ns,
container && container->type->meta
);
if (!func) {
// first try to resolve the identifier as a non-function, then get the
// "oper call" from it.
var = createVarRef(container, ident,
SPUG_FSTR("No method exists matching " <<
ident.getData() << "()"
).c_str()
);
if (var) {
func = context->lookUp("oper call", args, var->type.get());
container = var.get();
}
}
// no function, not a callable variable - give an error.
if (!func) {
ostringstream msg;
msg << "No method exists matching " << funcName << "(" << args << ")";
context->maybeExplainOverload(msg, funcName, ns);
error(ident, msg.str());
}
context->checkAccessible(func.get());
// if the definition is for an instance variable, emit an implicit
// "this" dereference. Otherwise just emit the variable
ExprPtr receiver;
bool squashVirtual = false;
if (func->flags & FuncDef::method) {
// keep track of whether we need to verify that "this" is an instance
// of the container (assumes the container is a TypeDef)
bool verifyThisIsContainer = false;
// if we've got a container and the container is not a class, or the
// container _is_ a class but the function is a method of its
// meta-class, use the container as the receiver.
if (container)
if (container->type->meta && !TypeDefPtr::acast(func->getOwner())->meta) {
// the container is a class and the function is an explicit
// call of a (presumably base class) method.
// make sure that the function is not abstract
if (func->flags & FuncDef::abstract)
error(ident, SPUG_FSTR("Abstract function " << funcName << "(" <<
args << ") can not be called."
)
);
squashVirtual = true;
verifyThisIsContainer = true;
} else {
receiver = container;
}
// if we didn't get the receiver from the container, lookup the
// "this" variable.
if (!receiver) {
receiver = context->makeThisRef(funcName);
if (verifyThisIsContainer &&
!receiver->type->isDerivedFrom(container->type->meta))
error(ident, SPUG_FSTR("'this' is not an instance of " <<
container->type->meta->name
)
);
}
}
FuncCallPtr funcCall = context->builder.createFuncCall(func.get(),
squashVirtual
);
funcCall->args = args;
funcCall->receiver = receiver;
return funcCall;
}
ExprPtr Parser::parsePostIdent(Expr *container, const Token &ident) {
Namespace *ns = container ? container->type.get() : context->ns.get();
Token tok1 = getToken();
if (ident.isOper() && tok1.isAssign())
error(tok1, "Expected operator identifier after 'oper' keyword");
// is it ident := expr?
if (tok1.isDefine()) {
// make sure that the variable is not defined in this context.
VarDefPtr def = ns->lookUp(ident.getData());
if (def && def->getOwner() == context->ns.get())
redefineError(tok1, def.get());
ExprPtr val = parseExpression();
if (!val) {
tok1 = getToken();
error(tok1, "expression expected");
}
// emit the variable with a null initializer and then create a separate
// assignment expression.
VarDefPtr var = context->emitVarDef(val->type.get(), ident, 0);
return createAssign(container, ident, var.get(), val.get());
// is it an assignment?
} else if ((tok1.isAssign() || tok1.isAugAssign()) && !ident.isOper()) {
VarDefPtr var = ns->lookUp(ident.getData());
if (!var)
error(tok1,
SPUG_FSTR("attempted to assign undefined variable " <<
ident.getData()
)
);
context->checkAccessible(var.get());
// make sure the variable is not a constant.
if (var->isConstant())
error(tok1, "You cannot assign to a constant, class or function.");
// parse an expression
ExprPtr val = parseExpression();
if (!val) {
tok1 = getToken();
error(tok1, "expression expected");
}
// check for augmented assignment
if (tok1.isAugAssign()) {
// create a reference for the lvalue
ExprPtr varRef = createVarRef(container, var.get(), ident);
// see if the variable's type has an augmented assignment operator
FuncCall::ExprVec args(2);
args[0] = varRef;
args[1] = val;
FuncDefPtr funcDef;
if (funcDef = lookUpBinOp(tok1.getData(), args)) {
FuncCallPtr funcCall =
context->builder.createFuncCall(funcDef.get());
funcCall->args = args;
if (funcDef->flags & FuncDef::method)
funcCall->receiver =
(funcDef->flags & FuncDef::reverse) ? val : varRef;
return funcCall;
}
// it doesn't. verify that it has the plain version of the operator
// and construct an assignment from it.
args[0] = varRef;
args[1] = val;
const string &tok1Data = tok1.getData();
const string &oper = tok1Data.substr(0, tok1Data.size() - 1);
if (funcDef = lookUpBinOp(oper, args)) {
FuncCallPtr funcCall =
context->builder.createFuncCall(funcDef.get());
funcCall->args = args;
if (funcDef->flags & FuncDef::method)
funcCall->receiver =
(funcDef->flags & FuncDef::reverse) ? val : varRef;
return createAssign(container, ident, var.get(), funcCall.get());
} else {
error(tok1, SPUG_FSTR("Neither " << oper << "= nor " << oper <<
" is defined for types " <<
varRef->type->name << " and " <<
val->type->name
)
);
}
}
// if this is an instance variable, emit a field assignment.
// Otherwise emit a normal variable assignment.
return createAssign(container, ident, var.get(), val.get());
} // should not fall through - always returns or throws.
// if this is an explicit operator call, give it special treatment.
string funcName;
if (ident.isOper()) {
toker.putBack(tok1);
funcName = parseOperSpec();
tok1 = getToken();
} else {
funcName = ident.getData();
}
if (tok1.isLParen()) {
// function/method invocation
return parseFuncCall(ident, funcName, ns, container);
} else {
if (ident.isOper())
unexpected(tok1,
SPUG_FSTR("expected parameter list after " <<
funcName
).c_str()
);
// for anything else, it's a variable reference
toker.putBack(tok1);
return createVarRef(container, ident);
}
}
// ` ... `
// ^ ^
ExprPtr Parser::parseIString(Expr *expr) {
// wrap the formatter expression in a register setter so it will get stored
// for reuse.
ExprPtr formatter = new SetRegisterExpr(expr);
ExprPtr reg = new GetRegisterExpr(expr->type.get());
// create an expression sequence for the formatter
MultiExprPtr seq = new MultiExpr();
// look up an "enter()" function
FuncDefPtr func = context->lookUpNoArgs("enter", true, expr->type.get());
if (func) {
FuncCallPtr funcCall = context->builder.createFuncCall(func.get());
if (func->flags & FuncDef::method)
funcCall->receiver = reg;
seq->add(funcCall.get());
}
// parse all of the subtokens
Token tok;
while (!(tok = getToken()).isIstrEnd()) {
ExprPtr arg;
if (tok.isString()) {
if (tok.getData().size() == 0) continue;
arg = context->getStrConst(tok.getData());
} else if (tok.isIdent()) {
// get a variable definition
arg = createVarRef(0, tok);
toker.continueIString();
} else if (tok.isLParen()) {
arg = parseExpression();
tok = getToken();
if (!tok.isRParen())
unexpected(tok, "expected a right paren");
toker.continueIString();
} else {
unexpected(tok,
"expected an identifer or a parenthesized expression "
"after the $ in an interpolated string"
);
}
// look up a format method for the argument
FuncCall::ExprVec args(1);
args[0] = arg;
func = context->lookUp("format", args, expr->type.get());
if (!func)
error(tok,
SPUG_FSTR("No format method exists for objects of type " <<
arg->type->getDisplayName()
)
);
FuncCallPtr funcCall = context->builder.createFuncCall(func.get());
funcCall->args = args;
if (func->flags & FuncDef::method)
funcCall->receiver = reg;
seq->add(funcCall.get());
}
func = context->lookUpNoArgs("leave", true, expr->type.get());
if (func) {
FuncCallPtr funcCall = context->builder.createFuncCall(func.get());
if (func->flags & FuncDef::method)
funcCall->receiver = reg;
seq->add(funcCall.get());
seq->type = funcCall->type;
} else {
seq->add(reg.get());
seq->type = reg->type;
}
// we're going to create a ternary, use a null value as the false clause if
// the type is not void, otherwise omit the false clause
ExprPtr falseClause;
if (seq->type != context->construct->voidType)
falseClause = new NullConst(seq->type.get());
return context->createTernary(formatter.get(), seq.get(), falseClause.get());
}
// [ expr, expr, ... ]
// ^ ^
ExprPtr Parser::parseConstSequence(TypeDef *containerType) {
vector<ExprPtr> elems;
Token tok = getToken();
while (!tok.isRBracket()) {
// parse the next element
toker.putBack(tok);
elems.push_back(parseExpression());
tok = getToken();
if (tok.isComma())
tok = getToken();
else if (!tok.isRBracket())
unexpected(tok, "Expected comma or right bracket after element");
}
return context->emitConstSequence(containerType, elems);
}
// typeof ( expr )
// ^ ^
TypeDefPtr Parser::parseTypeof() {
Token tok = getToken();
if (!tok.isLParen())
unexpected(tok,
"Expected parenthesized expression after 'typeof' keyword."
);
TypeDefPtr result = parseExpression()->type;
tok = getToken();
if (!tok.isRParen())
unexpected(tok,
"Expected closing paren after 'typeof' expression."
);
return result;
}
TypeDef *Parser::convertTypeRef(Expr *expr) {
VarRef *ref = VarRefPtr::cast(expr);
if (!ref)
return 0;
return TypeDefPtr::rcast(ref->def);
}
// cond ? trueVal : falseVal
// ^ ^
ExprPtr Parser::parseTernary(Expr *cond) {
ExprPtr trueVal = parseExpression();
Token tok = getToken();
if (!tok.isColon())
unexpected(tok, "expected colon.");
ExprPtr falseVal = parseExpression();
return context->createTernary(cond, trueVal.get(), falseVal.get());
}
ExprPtr Parser::parseSecondary(Expr *expr0, unsigned precedence) {
ExprPtr expr = expr0;
Token tok = getToken();
while (true) {
if (tok.isDot()) {
tok = getToken();
// if the next token is "class", this is the class operator.
if (tok.isClass()) {
FuncDefPtr funcDef =
context->lookUpNoArgs("oper class", true, expr->type.get());
if (!funcDef)
error(tok, SPUG_FSTR("class operator not defined for " <<
expr->type->name
)
);
FuncCallPtr funcCall =
context->builder.createFuncCall(funcDef.get());
funcCall->receiver = expr;
expr = funcCall;
tok = getToken();
continue;
} else if (!tok.isIdent() && !tok.isOper()) {
// make sure it's an identifier
error(tok, "identifier expected");
}
expr = parsePostIdent(expr.get(), tok);
} else if (tok.isLBracket()) {
// the array indexing operators
// ... unless this is a type, in which case it is a specializer.
TypeDef *generic = convertTypeRef(expr.get());
// XXX try setting expr to generic
if (generic) {
TypeDef *type = parseSpecializer(tok, generic);
// check for a constructor
tok = getToken();
if (tok.isLParen()) {
expr = parseConstructor(tok, type, Token::rparen);
tok = getToken();
} else {
// otherwise just create a reference to the type.
expr = context->createVarRef(type);
}
continue;
}
FuncCall::ExprVec args;
parseMethodArgs(args, Token::rbracket);
// check for an assignment operator
Token tok2 = getToken();
FuncCallPtr funcCall;
if (tok2.isAssign()) {
// this is "a[i] = v"
args.push_back(parseExpression());
FuncDefPtr funcDef =
context->lookUp("oper []=", args, expr->type.get());
if (!funcDef)
error(tok,
SPUG_FSTR("'oper []=' not defined for " <<
expr->type->name << " with these arguments."
)
);
funcCall = context->builder.createFuncCall(funcDef.get());
funcCall->receiver = expr;
funcCall->args = args;
} else {
// this is "a[i]"
toker.putBack(tok2);
FuncDefPtr funcDef =
context->lookUp("oper []", args, expr->type.get());
if (!funcDef)
error(tok, SPUG_FSTR("'oper []' not defined for " <<
expr->type->name <<
" with these arguments: (" << args << ")"
)
);
funcCall = context->builder.createFuncCall(funcDef.get());
funcCall->receiver = expr;
funcCall->args = args;
}
expr = funcCall;
} else if (tok.isLParen()) {
// XXX need to unify this to expr->call(args);
// is the expression a type
TypeDef *type = convertTypeRef(expr.get());
if (type) {
expr = parseConstructor(tok, type, Token::rparen);
} else {
// assume it's a functor
FuncCall::ExprVec args;
parseMethodArgs(args);
FuncDefPtr funcDef =
context->lookUp("oper call", args, expr->type.get());
if (!funcDef)
error(tok, SPUG_FSTR("'oper call' not defined for " <<
expr->type->name <<
" with these arguments: (" << args << ")"
)
);
FuncCallPtr funcCall =
context->builder.createFuncCall(funcDef.get());
funcCall->receiver = expr;
funcCall->args = args;
expr = funcCall;
}
} else if (tok.isIncr() || tok.isDecr()) {
FuncCall::ExprVec args;
string symbol = "oper x" + tok.getData();
FuncDefPtr funcDef = context->lookUp(symbol, args, expr->type.get());
if (!funcDef) {
args.push_back(expr);
funcDef = context->lookUp(symbol, args);
}
if (!funcDef)
error(tok, SPUG_FSTR(symbol << " is not defined for type "
<< expr->type->name));
FuncCallPtr funcCall = context->builder.createFuncCall(funcDef.get());
funcCall->args = args;
if (funcDef->flags & FuncDef::method)
funcCall->receiver = expr;
expr = funcCall;
} else if (tok.isBinOp()) {
// get the precedence of the new operator, if it's lower than the
// or the same as that of the current operator, quit.
unsigned newPrec = getPrecedence(tok.getData());
if (newPrec <= precedence)
break;
// parse the right-hand-side expression
ExprPtr rhs = parseExpression(newPrec);
FuncCall::ExprVec exprs(2);
exprs[0] = expr;
exprs[1] = rhs;
FuncDefPtr func = lookUpBinOp(tok.getData(), exprs);
if (!func)
error(tok,
SPUG_FSTR("Operator " << expr->type->name << " " <<
tok.getData() << " " << rhs->type->name <<
" undefined."
)
);
FuncCallPtr funcCall = context->builder.createFuncCall(func.get());
funcCall->args = exprs;
if (func->flags & FuncDef::method)
funcCall->receiver =
(func->flags & FuncDef::reverse) ? rhs : expr;
expr = funcCall;
expr = expr->foldConstants();
} else if (tok.isIstrBegin()) {
expr = parseIString(expr.get());
} else if (tok.isQuest()) {
if (precedence >= logOrPrec)
break;
expr = parseTernary(expr.get());
} else if (tok.isBang()) {
// this is special wacky collection syntax Type![1, 2, 3]
TypeDef *type = convertTypeRef(expr.get());
if (!type)
error(tok,
"Exclamation point can not follow a non-type expression"
);
// check for a square bracket
tok = toker.getToken();
if (!tok.isLBracket())
error(tok,
"Sequence initializer ('[ ... ]') expected after "
"'type!'"
);
expr = parseConstSequence(type);
} else {
// next token is not part of the expression
break;
}
// get the next token
tok = getToken();
}
toker.putBack(tok);
return expr;
}
namespace {
ExprPtr parseConstInt(Context &context,
const string &val,
int base) {
// if the constant starts with an 'i' or 'b', this is a string whose
// bytes comprise the integer value.
if (val[0] == 'b') {
if (val.size() != 2)
context.error("Byte constants from strings must be exactly one "
"byte long."
);
TypeDef *byteType = context.construct->byteType.get();
return context.builder.createIntConst(context, val[1], byteType);
} else if (val[0] == 'i') {
if (val.size() < 2 || val.size() > 9)
context.error("Integer constants from strings must be between one "
"and 8 bytes long"
);
// construct an integer from the bytes in the string
int64_t n = 0;
for (int i = 1; i < val.size(); ++i)
n = n << 8 | val[i];
return context.builder.createIntConst(context, n);
}
// if it's not negative, we first try to parse it as unsigned
// if it's small enough to fit in a signed, we do that, otherwise
// we keep it unsigned
unsigned long long bigcval = strtoull(val.c_str(), NULL, base);
if (bigcval <= INT64_MAX) {
// signed
return context.builder.createIntConst(context,
strtoll(val.c_str(),
NULL,
base
)
);
} else {
// unsigned
return context.builder.createUIntConst(context, bigcval);
}
}
} // anonymous namespace
ExprPtr Parser::parseExpression(unsigned precedence) {
ExprPtr expr;
// check for null
Token tok = getToken();
if (tok.isNull()) {
expr = new NullConst(context->construct->voidptrType.get());
// check for a nested parenthesized expression
} else if (tok.isLParen()) {
expr = parseExpression();
tok = getToken();
if (!tok.isRParen())
unexpected(tok, "expected a right paren");
// check for a "typeof"
} else if (tok.isTypeof()) {
expr = context->createVarRef(parseTypeof().get());
// check for a method
} else if (tok.isIdent()) {
expr = parsePostIdent(0, tok);
// for a string constant
} else if (tok.isString()) {
// check for subsequent string constants, concatenate them.
ostringstream result;
while (tok.isString()) {
result << tok.getData();
tok = getToken();
}
toker.putBack(tok);
expr = context->getStrConst(result.str());
// for an interpolated string
} else if (tok.isIstrBegin()) {
assert(false && "istring expressions not yet implemented");
// XXX we need to create a StringFormatter and pass it to parseIString()
// as the formatter.
// expr = parseIString(formatter);
// for a numeric constants
} else if (tok.isInteger()) {
expr = parseConstInt(*context, tok.getData(), 10);
} else if (tok.isFloat()) {
expr = context->builder.createFloatConst(*context,
atof(tok.getData().c_str())
);
} else if (tok.isOctal()) {
expr = parseConstInt(*context, tok.getData(), 8);
} else if (tok.isHex()) {
expr = parseConstInt(*context, tok.getData(), 16);
} else if (tok.isBinary()) {
expr = parseConstInt(*context, tok.getData(), 2);
} else if (tok.isPlus()) {
// eat + if expression is a numeric constant and fail if it's not
tok = getToken();
if (tok.isInteger())
expr = parseConstInt(*context, tok.getData(), 10);
else if(tok.isFloat())
expr = context->builder.createFloatConst(*context,
atof(tok.getData().c_str())
);
else if (tok.isOctal())
expr = parseConstInt(*context, tok.getData(), 8);
else if (tok.isHex())
expr = parseConstInt(*context, tok.getData(), 16);
else if (tok.isBinary())
expr = parseConstInt(*context, tok.getData(), 2);
else
unexpected(tok, "unexpected unary +");
// for the unary operators
} else if (tok.isBang() || tok.isMinus() || tok.isTilde() ||
tok.isDecr() || tok.isIncr()) {
FuncCall::ExprVec args;
string symbol = tok.getData();
// parse the expression
ExprPtr operand = parseExpression(getPrecedence(symbol + "x"));
// try to look it up for the expression, then for the context.
symbol = "oper " + symbol;
if (tok.isIncr() || tok.isDecr())
symbol += "x";
FuncDefPtr funcDef = context->lookUp(symbol, args,
operand->type.get()
);
if (!funcDef) {
args.push_back(operand);
funcDef = context->lookUp(symbol, args);
}
if (!funcDef)
error(tok, SPUG_FSTR(symbol << " is not defined for type "
<< operand->type->name));
FuncCallPtr funcCall = context->builder.createFuncCall(funcDef.get());
funcCall->args = args;
if (funcDef->flags & FuncDef::method)
funcCall->receiver = operand;
expr = funcCall->foldConstants();
} else if (tok.isLCurly()) {
unexpected(tok, "blocks as expressions are not supported yet");
} else {
unexpected(tok, "expected an expression");
}
return parseSecondary(expr.get(), precedence);
}
// func( arg, arg)
// ^ ^
// Type var = { arg, arg } ;
// ^ ^
void Parser::parseMethodArgs(FuncCall::ExprVec &args, Token::Type terminator) {
Token tok = getToken();
while (true) {
if (tok.getType() == terminator)
return;
// XXX should be verifying arg types against signature
// get the next argument value
toker.putBack(tok);
ExprPtr arg = parseExpression();
args.push_back(arg);
// comma signals another argument
tok = getToken();
if (tok.isComma())
tok = getToken();
}
}
// type [ subtype, ... ]
// ^ ^
TypeDef *Parser::parseSpecializer(const Token &lbrack, TypeDef *typeDef,
Generic *generic
) {
if (typeDef && !typeDef->generic)
error(lbrack,
SPUG_FSTR("You cannot specialize non-generic type " <<
typeDef->getDisplayName()
)
);
TypeDef::TypeVecObjPtr types = new TypeDef::TypeVecObj();
Token tok;
while (true) {
TypeDefPtr subType = parseTypeSpec(0, generic);
types->push_back(subType);
tok = getToken();
if (generic) generic->addToken(tok);
if (tok.isRBracket())
break;
else if (!tok.isComma())
error(tok, "comma expected in specializer list.");
}
// XXX needs to verify the numbers and types of specializers
if (typeDef && !generic)
typeDef = typeDef->getSpecialization(*context, types.get());
return typeDef;
}
// Class( arg, arg )
// ^ ^
// Class var = { arg, arg } ;
// ^ ^
ExprPtr Parser::parseConstructor(const Token &tok, TypeDef *type,
Token::Type terminator
) {
// parse an arg list
FuncCall::ExprVec args;
parseMethodArgs(args, terminator);
// look up the new operator for the class
FuncDefPtr func = context->lookUp("oper new", args, type);
if (!func) {
if (type->abstract)
error(tok, SPUG_FSTR("You can not create an instance of abstract "
"class " << type->name << " without an "
"explicit 'oper new'."
)
);
else
error(tok, SPUG_FSTR("No constructor for " << type->name <<
" with these argument types: (" << args << ")"));
} else if (func->returnType != type) {
if (type->abstract)
error(tok, SPUG_FSTR("You can not create an instance of abstract "
"class " << type->name << " without an "
"explicit 'oper new'."
)
);
else
error(tok, SPUG_FSTR("'oper new' method " << *func <<
" does not return " << type->name
)
);
}
FuncCallPtr funcCall = context->builder.createFuncCall(func.get());
funcCall->args = args;
return funcCall;
}
TypeDefPtr Parser::parseTypeSpec(const char *errorMsg, Generic *generic) {
Token tok = getToken();
TypeDefPtr typeofType;
if (tok.isTypeof()) {
if (generic) {
// record the typeof expression, return a bogus type
generic->addToken(tok);
recordParenthesized(generic);
return context->construct->voidType;
} else {
typeofType = parseTypeof();
}
} else if (!tok.isIdent()) {
unexpected(tok, "type identifier expected");
}
if (generic) generic->addToken(tok);
TypeDef *typeDef = typeofType.get();
if (!typeDef && (!generic || !generic->getParm(tok.getData()))) {
VarDefPtr def = context->ns->lookUp(tok.getData());
typeDef = TypeDefPtr::rcast(def);
if (!typeDef)
error(tok, SPUG_FSTR(tok.getData() <<
(errorMsg ? errorMsg : " is not a type.")
)
);
}
// see if there's a bracket operator
tok = getToken();
if (tok.isLBracket()) {
if (generic) generic->addToken(tok);
typeDef = parseSpecializer(tok, typeDef, generic);
} else {
toker.putBack(tok);
}
// make sure this isn't an unspecialized generic
if (!generic && typeDef->generic)
error(tok, SPUG_FSTR("Generic type " << typeDef->name <<
" must be specialized to be used."
)
);
return typeDef;
}
void Parser::parseModuleName(vector<string> &moduleName) {
Token tok = getToken();
while (true) {
moduleName.push_back(tok.getData());
tok = getToken();
if (!tok.isDot()) {
toker.putBack(tok);
return;
}
tok = getToken();
if (!tok.isIdent())
unexpected(tok, "identifier expected");
}
}
// type funcName ( type argName, ... ) {
// ^ ^
void Parser::parseArgDefs(vector<ArgDefPtr> &args, bool isMethod) {
// load the next token so we can check for the immediate closing paren of
// an empty argument list.
Token tok = getToken();
while (!tok.isRParen()) {
// parse the next argument type
toker.putBack(tok);
TypeDefPtr argType = parseTypeSpec();
tok = getToken();
if (!tok.isIdent())
error(tok, "identifier (argument name) expected.");
// make sure we're not redefining an existing variable
// XXX complain extra loud if the variable is defined in the current
// context (and make sure that the current context is the function
// context)
std::string varName = tok.getData();
checkForExistingDef(tok, varName);
// XXX need to check for a default variable assignment
ArgDefPtr argDef = context->builder.createArgDef(argType.get(), varName);
args.push_back(argDef);
addDef(argDef.get());
// if the variable has an "oper release", we can't allow it to be
// assigned because doing so would require that we do a release for a
// binding owned by the caller (due to an optimization). So mark the
// variable as constant.
if (context->lookUpNoArgs("oper release", true, argType.get()))
argDef->constant = true;
// check for a comma
tok = getToken();
if (tok.isComma())
tok = getToken();
else if (!tok.isRParen())
unexpected(tok, "expected ',' or ')' after argument definition");
}
}
// oper init(...) : init1(expr), ... {
// ^ ^
void Parser::parseInitializers(Initializers *inits, Expr *receiver) {
ContextPtr classCtx = context->getClassContext();
TypeDefPtr type = TypeDefPtr::rcast(classCtx->ns);
while (true) {
// get an identifier
Token tok = getToken();
if (!tok.isIdent())
unexpected(tok, "identifier expected in initializer list.");
// try to look up an instance variable
VarDefPtr varDef = context->ns->lookUp(tok.getData());
if (!varDef || TypeDefPtr::rcast(varDef)) {
// not a variable def, parse a type def.
toker.putBack(tok);
TypeDefPtr base =
parseTypeSpec(" is neither a base class nor an instance variable");
// try to find it in our base classes
if (!type->isParent(base.get()))
error(tok,
SPUG_FSTR(base->getDisplayName() <<
" is not a direct base class of " <<
type->name
)
);
// parse the arg list
expectToken(Token::lparen, "expected an ergument list.");
FuncCall::ExprVec args;
parseMethodArgs(args);
// look up the appropriate constructor
FuncDefPtr operInit = context->lookUp("oper init", args, base.get());
if (!operInit || operInit->getOwner() != base.get())
error(tok, SPUG_FSTR("No matching constructor found for " <<
base->getDisplayName()
)
);
FuncCallPtr funcCall = context->builder.createFuncCall(operInit.get());
funcCall->args = args;
funcCall->receiver = receiver;
if (!inits->addBaseInitializer(base.get(), funcCall.get()))
error(tok,
SPUG_FSTR("Base class " << base->getDisplayName() <<
" already initialized."
)
);
// make sure that it is a direct member of this class.
} else if (varDef->getOwner() != type.get() &&
// it's likely that this is just a case of a parameter
// shadowing an instance veriable, which is legal. Try
// looking up the variable at class scope.
(!(varDef = type->lookUp(tok.getData())) ||
varDef->getOwner() != type.get()
)
) {
error(tok,
SPUG_FSTR(tok.getData() << " is not an immediate member of " <<
type->name
)
);
// make sure that it's an instance variable
} else if (!varDef->hasInstSlot()) {
error(tok,
SPUG_FSTR(tok.getData() << " is not an instance variable.")
);
} else {
// this is a normal, member initializer
// this will be our initializer
ExprPtr initializer;
// get the next token
Token tok2 = getToken();
if (tok2.isLParen()) {
// it's a left paren - treat this as a constructor.
FuncCall::ExprVec args;
parseMethodArgs(args);
// look up the appropriate constructor
FuncDefPtr operNew =
context->lookUp("oper new", args, varDef->type.get());
if (!operNew)
error(tok2,
SPUG_FSTR("No matching constructor found for instance "
"variable " << varDef->name <<
" of type " << varDef->type->name
)
);
// construct a function call
FuncCallPtr funcCall;
initializer = funcCall =
context->builder.createFuncCall(operNew.get());
funcCall->args = args;
} else if (tok2.isAssign()) {
// it's the assignement operator, parse an expression
initializer = parseInitializer(varDef->type.get(), varDef->name);
} else {
unexpected(tok2,
"expected constructor arg list or assignment operator"
);
}
// generate an assignment, add it to the initializers
if (!inits->addFieldInitializer(varDef.get(), initializer.get()))
error(tok,
SPUG_FSTR("Instance variable " << varDef->name <<
" already initialized."
)
);
}
// check for a comma
tok = getToken();
if (!tok.isComma()) {
toker.putBack(tok);
break;
}
}
}
int Parser::parseFuncDef(TypeDef *returnType, const Token &nameTok,
const string &name,
Parser::FuncFlags funcFlags,
int expectedArgCount
) {
runCallbacks(funcDef);
// check for an existing, non-function definition.
VarDefPtr existingDef = checkForExistingDef(nameTok, name, true);
FuncDef::Flags nextFuncFlags = context->nextFuncFlags;
// if this is a class context, we're defining a method. We take the strict
// definition of "in a class context," only functions immediately in a
// class context are methods of that class.
ContextPtr classCtx;
if (context->scope == Context::composite && context->parent &&
context->parent->scope == Context::instance
)
classCtx = context->parent;
bool isMethod = classCtx && (!nextFuncFlags ||
nextFuncFlags & FuncDef::method
);
TypeDef *classTypeDef = 0;
// push a new context, arg defs will be stored in the new context.
NamespacePtr ownerNS = context->ns;
ContextPtr subCtx = context->createSubContext(Context::local, 0,
&name
);
ContextStackFrame cstack(*this, subCtx.get());
context->returnType = returnType;
context->toplevel = true;
// if this is a method, add the "this" variable
ExprPtr receiver;
if (isMethod) {
assert(classCtx && "method not in class context.");
classTypeDef = TypeDefPtr::arcast(classCtx->ns);
ArgDefPtr argDef = context->builder.createArgDef(classTypeDef, "this");
addDef(argDef.get());
receiver = context->createVarRef(argDef.get());
}
// parse the arguments
ArgVec argDefs;
parseArgDefs(argDefs, isMethod);
// if we are expecting an argument definition, check for it.
if (expectedArgCount > -1 && argDefs.size() != expectedArgCount)
error(nameTok,
SPUG_FSTR("Expected " << expectedArgCount <<
" arguments for function " << name
)
);
// a function is virtual if a) it is a method, b) the class has a vtable
// and c) it is neither implicitly or explicitly final.
bool isVirtual = isMethod && classTypeDef->hasVTable &&
!TypeDef::isImplicitFinal(name) &&
(!nextFuncFlags || nextFuncFlags & FuncDef::virtualized);
// If we're overriding/implementing a previously declared virtual
// function, we'll store it here.
FuncDefPtr override = checkForOverride(existingDef.get(), argDefs,
ownerNS.get(),
nameTok,
name
);
// if we're "overriding" a forward declaration, use the namespace of the
// forward declaration.
if (override && override->flags & FuncDef::forward)
context->ns = override->ns;
// make sure that the return type is exactly the same as the override
if (override && override->returnType != returnType)
error(nameTok,
SPUG_FSTR("Function return type of " <<
returnType->getDisplayName() <<
" does not match that of the function it overrides (" <<
override->returnType->getDisplayName() << ")"
)
);
// figure out what the flags are going to be.
FuncDef::Flags flags =
(isMethod ? FuncDef::method : FuncDef::noFlags) |
(isVirtual ? FuncDef::virtualized : FuncDef::noFlags) |
(funcFlags == reverseOp ? FuncDef::reverse : FuncDef::noFlags);
Token tok3 = getToken();
InitializersPtr inits;
if (tok3.isSemi()) {
// forward declaration or stub - see if we've got a stub
// definition
toker.putBack(tok3);
StubDef *stub;
FuncDefPtr funcDef;
if (existingDef && (stub = StubDefPtr::rcast(existingDef))) {
funcDef =
context->builder.createExternFunc(*context, FuncDef::noFlags,
name,
returnType,
0,
argDefs,
stub->address,
name.c_str()
);
stub->getOwner()->removeDef(stub);
cstack.restore();
addFuncDef(funcDef.get());
} else if (override) {
// forward declarations of overrides don't make any sense.
TypeDef *base = TypeDefPtr::acast(override->getOwner());
warn(tok3, SPUG_FSTR("Unnecessary forward declaration for overriden "
"function " << name << " (defined in ancestor "
"class " << base->getDisplayName() << ")"
)
);
} else {
// it's a forward declaration or abstract function
// see if the "next function" flags indicate an abstract function
if (nextFuncFlags & FuncDef::abstract) {
// abstract function - make sure we're in an abstract class
if (!classTypeDef || !classTypeDef->abstract)
error(tok3,
"Abstract functions can only be defined in an abstract "
"class."
);
// verify that the class has no dependents
vector<TypeDefPtr> deps;
classTypeDef->getDependents(deps);
if (deps.size()) {
stringstream msg;
msg << "You cannot declare an abstract function after "
"the nested derived class";
if (deps.size() == 1)
msg << " " << deps[0]->name << ".";
else {
msg << "es: ";
for (int i = 0; i < deps.size(); ++i)
msg << (i ? ", " : "") << deps[i]->name;
msg << ".";
}
error(tok3, msg.str());
}
flags = flags | FuncDef::abstract | FuncDef::virtualized |
FuncDef::method;
} else {
flags = flags | FuncDef::forward;
}
funcDef = context->builder.createFuncForward(*context, flags, name,
returnType,
argDefs,
override.get()
);
runCallbacks(funcForward);
cstack.restore();
addFuncDef(funcDef.get());
context->nextFuncFlags = FuncDef::noFlags;
// if this is a constructor for a non-abstract class, and the user
// hasn't introduced their own "oper new", generate one for the new
// constructor now.
if (funcFlags & hasMemberInits && !classTypeDef->abstract &&
!classTypeDef->gotExplicitOperNew
)
classTypeDef->createNewFunc(*classCtx, funcDef.get());
}
return argDefs.size();
} else if (funcFlags == hasMemberInits) {
inits = new Initializers();
if (tok3.isColon()) {
parseInitializers(inits.get(), receiver.get());
tok3 = getToken();
}
}
if (!tok3.isLCurly()) {
unexpected(tok3, "expected '{' in function definition");
}
// if we got a forward declaration, make sure the args and the context are
// the same
if (override && override->flags & FuncDef::forward) {
if(!override->matchesWithNames(argDefs))
error(tok3,
SPUG_FSTR("Argument list of function " << name <<
" doesn't match the names of its forward "
"declaration:\n forward: " << override->args <<
"\n defined: " << argDefs
)
);
if (override->getOwner() != context->getParent()->getDefContext()->ns.get())
error(tok3,
SPUG_FSTR("Function " << name <<
" can not be defined in a different namespace from "
"its forward declaration."
)
);
}
// parse the body
FuncDefPtr funcDef =
context->builder.emitBeginFunc(*context, flags, name, returnType,
argDefs,
override.get()
);
// store the new definition in the parent context if it's not already in
// there (if there was a forward declaration)
if (!funcDef->getOwner()) {
ContextStackFrame cstack(*this, context->getParent().get());
addFuncDef(funcDef.get());
}
// if there were initializers, emit them.
if (inits)
classTypeDef->emitInitializers(*context, inits.get());
// run begin function callbacks.
runCallbacks(funcEnter);
// if this is an "oper del" with base & member cleanups, store them in the
// current cleanup frame
if (funcFlags == hasMemberDels) {
assert(classCtx && "emitting a destructor outside of class context");
classTypeDef->addDestructorCleanups(*context);
}
ContextPtr terminal = parseBlock(true, funcLeave);
// if the block doesn't always terminate, either give an error or
// return void if the function return type is void
if (!terminal)
if (context->construct->voidType->matches(*context->returnType)) {
// remove the cleanup stack - we have already done cleanups at
// the block level.
context->cleanupFrame = 0;
context->builder.emitReturn(*context, 0);
} else {
// XXX we don't have the closing curly brace location,
// currently reporting the error on the top brace
error(tok3, "missing return statement for non-void function.");
}
context->builder.emitEndFunc(*context, funcDef.get());
cstack.restore();
// clear the next function flags (we're done with them)
context->nextFuncFlags = FuncDef::noFlags;
// if this is an init function for a non-abstract class, and the user
// hasn't introduced an explicit "oper new", and we haven't already done
// this for a forward declaration, generate the corresponding "oper new".
if (inits && !classTypeDef->gotExplicitOperNew &&
!classTypeDef->abstract &&
(!override || !(override->flags & FuncDef::forward))
)
classTypeDef->createNewFunc(*classCtx, funcDef.get());
return argDefs.size();
}
// type var = ... ;
// ^ ^
ExprPtr Parser::parseInitializer(TypeDef *type, const std::string &varName) {
ExprPtr initializer;
// check for special initializer syntax.
Token tok = getToken();
if (tok.isLCurly()) {
// got constructor args, parse an arg list terminated by a right
// curly.
initializer = parseConstructor(tok, type, Token::rcurly);
} else if (tok.isLBracket()) {
initializer = parseConstSequence(type);
} else {
toker.putBack(tok);
initializer = parseExpression();
}
// make sure the initializer matches the declared type.
TypeDefPtr oldType = initializer->type;
initializer = initializer->convert(*context, type);
if (!initializer)
error(tok, SPUG_FSTR("Invalid type " << oldType->getDisplayName() <<
" for initializer for variable " << varName <<
" of type " << type->getDisplayName() << "."
)
);
return initializer;
}
// alias name = existing_def, ... ;
// ^ ^
void Parser::parseAlias() {
while (true) {
Token tok = getToken();
if (!tok.isIdent())
unexpected(tok, "Identifier expected after 'alias'.");
string aliasName = tok.getData();
// make sure the alias doesn't hide anything
checkForExistingDef(tok, aliasName);
tok = getToken();
if (!tok.isAssign())
unexpected(tok, "Expected assignment operator in alias definition.");
// get the context where we're going to define the alias
ContextPtr defContext = context->getDefContext();
VarDefPtr existing;
tok = getToken();
if (tok.isTypeof()) {
// parse the typeof
existing = parseTypeof();
} else if (tok.isIdent()) {
// try looking up the reference
existing = context->lookUp(tok.getData());
if (!existing)
error(tok, SPUG_FSTR(tok.getData() <<
" is not an existing definition."
)
);
// if it's a generic see if we've got a specializer.
TypeDef *type;
if ((type = TypeDefPtr::rcast(existing)) && type->generic) {
tok = getToken();
if (tok.isLBracket())
existing = parseSpecializer(tok, type);
else
toker.putBack(tok);
}
} else {
unexpected(tok, "Identifier expected after alias definition.");
}
OverloadDefPtr ovld =
defContext->ns->addAlias(aliasName, existing.get());
// for overloads, we need to update any necessary intermediate
// overloads.
if (ovld && defContext != context)
context->insureOverloadPath(defContext.get(), ovld.get());
// if this is module context, and this is a public alias for a def not
// owned by the module, add the alias to the list of exports.
ModuleDef *mod;
if ((mod = ModuleDefPtr::rcast(context->ns)) &&
aliasName[0] != '_' &&
existing->getOwner() != mod
)
mod->exports[aliasName] = true;
tok = getToken();
if (tok.isSemi()) {
toker.putBack(tok);
return;
} else if (!tok.isComma()) {
unexpected(tok, "Expected comma or semicolon after alias.");
}
}
}
// type var = initializer, var2 ;
// ^ ^
// type function() { }
// ^ ^
bool Parser::parseDef(TypeDef *&type) {
Token tok2 = getToken();
// if we get a '[', parse the specializer and get a generic type.
if (tok2.isLBracket()) {
type = parseSpecializer(tok2, type);
tok2 = getToken();
} else if(type->generic) {
error(tok2, SPUG_FSTR("Generic type " << type->name <<
" must be specialized to be used."
)
);
}
while (true) {
if (tok2.isIdent()) {
string varName = tok2.getData();
// this could be a variable or a function
Token tok3 = getToken();
if (tok3.isSemi() || tok3.isComma()) {
// it's a variable.
runCallbacks(variableDef);
// make sure we're not hiding anything else
checkForExistingDef(tok2, tok2.getData());
// we should now _always_ have a default constructor (unless the
// type is void).
assert(type->defaultInitializer ||
type == context->construct->voidType.get());
// Emit a variable definition and store it in the context (in a
// cleanup frame so transient initializers get destroyed here)
context->emitVarDef(type, tok2, 0);
if (tok3.isSemi())
return true;
else {
tok2 = getToken();
continue;
}
} else if (tok3.isAssign()) {
runCallbacks(variableDef);
ExprPtr initializer;
// make sure we're not hiding anything else
checkForExistingDef(tok2, tok2.getData());
initializer = parseInitializer(type, varName);
context->emitVarDef(type, tok2, initializer.get());
// if this is a comma, we need to go back and parse
// another definition for the type.
Token tok4 = getToken();
if (tok4.isComma()) {
tok2 = getToken();
continue;
} else if (tok4.isSemi()) {
return true;
} else {
unexpected(tok4,
"Expected comma or semicolon after variable "
"definition."
);
}
} else if (tok3.isLParen()) {
// function definition
parseFuncDef(type, tok2, tok2.getData(), normal, -1);
return true;
} else {
unexpected(tok3,
"expected variable initializer or function "
"definition."
);
}
} else if (tok2.isOper()) {
// deal with an operator
parsePostOper(type);
return true;
}
// if we haven't "continued", were done.
toker.putBack(tok2);
return false;
}
}
// const type var = value, ... ;
// ^ ^
// const var := value ;
// ^ ^
void Parser::parseConstDef() {
Token tok = getToken();
if (!tok.isIdent())
unexpected(tok, "identifier or type expected after 'const'");
TypeDefPtr type = context->lookUp(tok.getData());
if (type) {
// assume that this is the "const type var = value, ...;" syntax. The
// altSyntaxPossible flag indicates whether it is still possible that
// this could be the alternate "const var := value" syntax.
Token varName = getToken();
bool altSyntaxPossible = true;
// check for a type specializer
if (varName.isLBracket()) {
type = parseSpecializer(varName, type.get());
varName = getToken();
altSyntaxPossible = false;
}
// parse as many constants as we get
while (true) {
// get the variable
if (!varName.isIdent()) {
// if we haven't committed to the typed syntax, check for a :=
// here.
if (altSyntaxPossible && varName.isDefine())
break;
unexpected(varName, "variable name expected in constant definition");
}
// if we got an identifier, we're now locked into the typed syntax.
altSyntaxPossible = false;
Token tok2 = getToken();
if (!tok2.isAssign())
unexpected(tok2,
"Expected assignment operator in constant definition"
);
// parse the initializer
ExprPtr expr = parseInitializer(type.get(), varName.getData());
context->emitVarDef(type.get(), varName, expr.get(), true);
// see if there are more constants in this definition.
tok2 = getToken();
if (tok2.isSemi()) {
toker.putBack(tok2);
return;
} else if (!tok2.isComma()) {
unexpected(tok2, "Comma or semicolon expected.");
}
// get the next variable identifier
varName = getToken();
}
// if we exit the loop, it's because we've disovered that this is
// actually a case of the "const var := val" syntax. Verify that the
// type is not defined in this context.
if (type->getOwner() == context->ns.get())
redefineError(varName, type.get());
} else {
// it's just an identifier
Token tok2 = getToken();
if (!tok2.isDefine())
unexpected(tok2, "':=' operator expected in const definition");
}
// parse the initializer
ExprPtr expr = parseExpression();
context->emitVarDef(expr->type.get(), tok, expr.get(), true);
}
ContextPtr Parser::parseIfClause() {
Token tok = getToken();
ContextPtr terminal;
stringstream nsName;
nsName << ++nestID;
string nsNameStr = nsName.str();
ContextStackFrame cstack(*this, context->createSubContext(context->scope,
0,
&nsNameStr).get());
if (tok.isLCurly()) {
return parseBlock(true, noCallbacks);
} else {
toker.putBack(tok);
return parseStatement(false);
}
}
ExprPtr Parser::parseCondExpr() {
TypeDef *boolType = context->construct->boolType.get();
ExprPtr cond = parseExpression()->convert(*context, boolType);
if (!cond)
error(getToken(), "Condition is not boolean.");
return cond;
}
// clause := expr ; (';' can be replaced with EOF)
// | { block }
// if ( expr ) clause
// ^ ^
// if ( expr ) clause else clause
// ^ ^
ContextPtr Parser::parseIfStmt() {
// create a subcontext for variables defined in the condition.
ContextStackFrame cstack(*this, context->createSubContext(true).get());
Token tok = getToken();
if (!tok.isLParen())
unexpected(tok, "expected left paren after if");
ExprPtr cond = parseCondExpr();
tok = getToken();
if (!tok.isRParen())
unexpected(tok, "expected closing paren");
BranchpointPtr pos = context->builder.emitIf(*context, cond.get());
ContextPtr terminalIf = parseIfClause();
ContextPtr terminalElse;
// check for the "else"
state = st_optElse;
tok = getToken();
if (tok.isElse()) {
pos = context->builder.emitElse(*context, pos.get(), terminalIf);
terminalElse = parseIfClause();
context->builder.emitEndIf(*context, pos.get(), terminalElse);
} else {
toker.putBack(tok);
context->builder.emitEndIf(*context, pos.get(), terminalIf);
}
// absorb the flags from the context (an annotation would set flags in the
// nested if context)
context->parent->nextFuncFlags = context->nextFuncFlags;
context->parent->nextClassFlags = context->nextClassFlags;
// the if is terminal if both conditions are terminal. The terminal
// context is the innermost of the two.
if (terminalIf && terminalElse)
if (terminalIf->encloses(*terminalElse))
return terminalElse;
else
return terminalIf;
else
return 0;
}
// while ( expr ) stmt ; (';' can be replaced with EOF)
// ^ ^
// while ( expr ) { ... }
// ^ ^
void Parser::parseWhileStmt() {
// create a subcontext for the break and for variables defined in the
// condition.
ContextStackFrame cstack(*this, context->createSubContext().get());
Token tok = getToken();
if (!tok.isLParen())
unexpected(tok, "expected left paren after while");
// parse the condition
ExprPtr cond = parseCondExpr();
tok = getToken();
if (!tok.isRParen())
unexpected(tok, "expected right paren after conditional expression");
BranchpointPtr pos =
context->builder.emitBeginWhile(*context, cond.get(), false);
context->setBreak(pos.get());
context->setContinue(pos.get());
ContextPtr terminal = parseIfClause();
context->builder.emitEndWhile(*context, pos.get(), terminal);
}
// for ( ... ) { ... }
// ^ ^
// for ( ... ) stmt ; (';' can be replaced with EOF)
// ^ ^
void Parser::parseForStmt() {
// create a subcontext for the break and for variables defined in the
// condition.
ContextStackFrame cstack(*this, context->createSubContext().get());
Token tok = getToken();
if (!tok.isLParen())
unexpected(tok, "expected left paren after for");
// the condition, before and after body expressions.
ExprPtr cond, beforeBody, afterBody;
bool iterForm = false;
// check for 'ident in', 'ident :in', 'ident on' or 'ident :on'
tok = getToken();
if (tok.isIdent()) {
bool definesVar, varIsIter;
Token tok2 = getToken();
if (tok2.isIn()) {
definesVar = false;
varIsIter = false;
iterForm = true;
} else if (tok2.isColon()) {
Token tok3 = getToken();
definesVar = true;
if (tok3.isIn()) {
varIsIter = false;
iterForm = true;
} else if (tok3.isOn()) {
varIsIter = true;
iterForm = true;
} else {
toker.putBack(tok3);
}
} else if (tok2.isOn()) {
definesVar = false;
varIsIter = true;
iterForm = true;
}
if (iterForm) {
// got iteration - parse the expression that we're iterating over
// and expand the iteration expressions.
// parse the list expression
ExprPtr expr = parseExpression();
// let the context expand an iteration expression
context->expandIteration(tok.getData(), definesVar, varIsIter,
expr.get(),
cond,
beforeBody,
afterBody
);
// check for a closing paren
tok = getToken();
if (!tok.isRParen())
unexpected(tok, "expected closing parenthesis");
} else {
toker.putBack(tok2);
}
}
// if we fall through to here, this is a C-like for statement
if (!iterForm) {
toker.putBack(tok);
// parse the initialization clause (if any)
tok = getToken();
if (!tok.isSemi()) {
toker.putBack(tok);
parseClause(true);
}
// check for a conditional expression
tok = getToken();
if (tok.isSemi()) {
// no conditional, create one from a constant
TypeDef *boolType = context->construct->boolType.get();
cond = context->builder.createIntConst(*context, 1)->convert(*context,
boolType
);
} else {
toker.putBack(tok);
cond = parseCondExpr();
tok = getToken();
if (!tok.isSemi())
unexpected(tok, "expected semicolon after condition");
}
// check for an after-body expression
tok = getToken();
if (!tok.isRParen()) {
toker.putBack(tok);
afterBody = parseExpression();
tok = getToken();
if (!tok.isRParen())
unexpected(tok, "expected closing parenthesis");
}
}
// emit the loop
BranchpointPtr pos =
context->builder.emitBeginWhile(*context, cond.get(), afterBody);
context->setBreak(pos.get());
context->setContinue(pos.get());
// emit the before-body expression if there was one
if (beforeBody) {
context->createCleanupFrame();
beforeBody->emit(*context)->handleTransient(*context);
context->closeCleanupFrame();
}
// parse the loop body
ContextPtr terminal = parseIfClause();
// emit the after-body expression if there was one.
if (afterBody) {
context->builder.emitPostLoop(*context, pos.get(), terminal);
context->createCleanupFrame();
afterBody->emit(*context)->handleTransient(*context);
context->closeCleanupFrame();
terminal = false;
}
context->builder.emitEndWhile(*context, pos.get(), terminal);
// close any variables created for the loop context.
context->builder.closeAllCleanups(*context);
}
void Parser::parseReturnStmt() {
// check for a return with no expression
Token tok = getToken();
bool returnVoid = false;
if (tok.isSemi()) {
returnVoid = true;
} else if (tok.isEnd() || tok.isRCurly()) {
toker.putBack(tok);
returnVoid = true;
}
if (returnVoid) {
if (!context->returnType->matches(*context->construct->voidType))
error(tok,
SPUG_FSTR("Missing return expression for function "
"returning " << context->returnType->name
)
);
context->builder.emitReturn(*context, 0);
return;
}
// parse the return expression, make sure that it matches the return type.
toker.putBack(tok);
ExprPtr orgExpr = parseExpression();
ExprPtr expr = orgExpr->convert(*context, context->returnType.get());
if (!expr)
error(tok,
SPUG_FSTR("Invalid return type " << orgExpr->type->name <<
" for function returning " << context->returnType->name
)
);
else if (!expr &&
!context->construct->voidType->matches(*context->returnType))
error(tok,
SPUG_FSTR("Missing return value for function returning " <<
context->returnType->name
)
);
// if the expression is of type void, emit it now and don't try to get the
// builder to generate it.
if (expr->type == context->construct->voidType) {
context->createCleanupFrame();
expr->emit(*context)->handleTransient(*context);
context->closeCleanupFrame();
expr = 0;
}
// emit the return statement
context->builder.emitReturn(*context, expr.get());
tok = getToken();
if (tok.isEnd() || tok.isRCurly())
toker.putBack(tok);
else if (!tok.isSemi())
unexpected(tok, "expected semicolon or block terminator");
}
// import module-and-defs ;
// ^ ^
void Parser::parseImportStmt(Namespace *ns) {
ModuleDefPtr mod;
string canonicalName;
builder::Builder &builder = context->construct->getCurBuilder();
Token tok = getToken();
if (tok.isIdent()) {
toker.putBack(tok);
vector<string> moduleName;
parseModuleName(moduleName);
mod = context->construct->loadModule(moduleName.begin(),
moduleName.end(),
canonicalName
);
if (!mod)
error(tok, SPUG_FSTR("unable to find module " << canonicalName));
// make sure the module is finished (no recursive imports)
else if (!mod->finished)
error(tok,
SPUG_FSTR("Attempting to import module " << canonicalName <<
" recursively."
)
);
} else if (!tok.isString()) {
unexpected(tok, "expected string constant");
}
string name = tok.getData();
// parse all following symbols
vector<ImportedDef> syms;
while (true) {
tok = getToken();
if (tok.isIdent()) {
syms.push_back(ImportedDef(tok.getData()));
tok = getToken();
// see if this is "local_name = source_name" notation
if (tok.isAssign()) {
tok = getToken();
if (!tok.isIdent())
unexpected(tok,
SPUG_FSTR("Identifier expected in import alias "
"expression for " <<
syms.back().local
).c_str()
);
syms.back().source = tok.getData();
tok = getToken();
}
if (tok.isSemi()) {
break;
} else if (!tok.isComma()) {
unexpected(tok, "expected comma or semicolon");
}
} else if (tok.isSemi()) {
break;
} else {
unexpected(tok, "expected identifier or semicolon");
}
}
if (!mod) {
try {
builder.importSharedLibrary(name, syms, *context, ns);
} catch (const spug::Exception &ex) {
error(tok, ex.getMessage());
}
} else {
builder.initializeImport(mod.get(),
syms,
// HACK check for annotation?
ns == context->compileNS.get()
);
// alias all of the names in the new module
for (ImportedDefVec::iterator iter = syms.begin();
iter != syms.end();
++iter
) {
// make sure that the symbol is not private
if (iter->source[0] == '_')
error(tok,
SPUG_FSTR("Can not import private symbol " << iter->source <<
"."
)
);
// make sure we don't already have it
if (ns->lookUp(iter->local))
error(tok, SPUG_FSTR("imported name " << iter->local <<
" hides existing definition."
)
);
VarDefPtr symVal = mod->lookUp(iter->source);
if (!symVal)
error(tok, SPUG_FSTR("name " << iter->source <<
" is not defined in module " <<
canonicalName
)
);
// make sure the symbol either belongs to the module or was
// explicitly exported by the module (no implicit second-order
// imports).
if (symVal->getOwner() != mod.get() &&
mod->exports.find(iter->source) == mod->exports.end()
)
error(tok, SPUG_FSTR("Name " << iter->source <<
" does not belong to module " <<
canonicalName << ". Second-order imports "
"are not allowed. Import it from " <<
symVal->getOwner()->getNamespaceName() <<
" instead."
)
);
builder.registerImportedDef(*context, symVal.get());
ns->addAlias(iter->local, symVal.get());
}
}
}
// try { ... } catch (...) { ... }
// ^ ^
ContextPtr Parser::parseTryStmt() {
Token tok = toker.getToken();
if (!tok.isLCurly())
unexpected(tok, "Curly bracket expected after try.");
BranchpointPtr pos = context->builder.emitBeginTry(*context);
// create a subcontext for the try statement
ContextStackFrame cstack(*this, context->createSubContext().get());
context->setCatchBranchpoint(pos.get());
ContextPtr terminal;
{
ContextStackFrame cstack(*this, context->createSubContext().get());
terminal = parseBlock(true, noCallbacks); // XXX add tryLeave callback
}
bool lastWasTerminal = terminal;
// strip the catch branchpoint so that exceptions thrown in the
// finally/catch clauses are thrown to outer contexts.
context->setCatchBranchpoint(0);
tok = toker.getToken();
if (!tok.isCatch())
unexpected(tok, "catch expected after try block.");
while (true) {
// parse the exception specifier
tok = toker.getToken();
if (!tok.isLParen())
unexpected(tok,
"parenthesized catch expression expected after catch "
"keyword."
);
TypeDefPtr exceptionType = parseTypeSpec();
// parse the exception variable
Token varTok = toker.getToken();
if (!varTok.isIdent())
unexpected(tok, "variable name expected after exception type.");
ExprPtr exceptionObj =
context->builder.emitCatch(*context, pos.get(), exceptionType.get(),
lastWasTerminal
);
tok = toker.getToken();
if (!tok.isRParen())
unexpected(tok,
"closing parenthesis expected after exception variable."
);
// parse the catch body
tok = toker.getToken();
if (!tok.isLCurly())
unexpected(tok,
"Curly bracket expected after catch clause."
);
{
ContextStackFrame cstack(*this, context->createSubContext().get());
// create a variable definition for the exception variable
context->emitVarDef(exceptionType.get(), varTok, exceptionObj.get());
// give the builder an opportunity to add an exception cleanup
context->builder.emitExceptionCleanup(*context);
// XXX add catchLeave callback
ContextPtr terminalCatch = parseBlock(true, noCallbacks);
lastWasTerminal = terminalCatch;
if (terminalCatch) {
if (terminal && terminal->encloses(*terminalCatch))
// need to replace the terminal context to the closer terminal
// context for the catch
terminal = terminalCatch;
} else {
// non-terminal catch, therefore the entire try/catch statement
// is not terminal.
terminal = 0;
}
}
// see if there's another catch
tok = toker.getToken();
if (!tok.isCatch()) {
toker.putBack(tok);
context->builder.emitEndTry(*context, pos.get(), lastWasTerminal);
return terminal;
}
}
}
ContextPtr Parser::parseThrowStmt() {
Token tok = toker.getToken();
if (tok.isSemi()) {
// XXX need to get this working and to verify that we are in a catch
error(tok, "Rethrowing exceptions not supported yet.");
// context->builder.emitThrow(*context, 0);
} else {
toker.putBack(tok);
ExprPtr expr = parseExpression();
if (!expr->type->isDerivedFrom(context->construct->vtableBaseType.get()))
error(tok, SPUG_FSTR("Object of type " <<
expr->type->getDisplayName() <<
" is not derived from VTableBase."
)
);
tok = toker.getToken();
if (!tok.isSemi())
unexpected(tok, "Semicolon expected after throw expression.");
context->builder.emitThrow(*context, expr.get());
}
// get the terminal context - if it's a toplevel context, we actually want
// to go one step further up.
ContextPtr terminal = context->getCatch();
if (terminal->toplevel)
terminal = terminal->parent;
return terminal;
}
// oper name ( args ) { ... }
// ^ ^
void Parser::parsePostOper(TypeDef *returnType) {
bool reversed = false;
Token tok = getToken();
if (tok.isIdent()) {
const string &ident = tok.getData();
bool isInit = ident == "init";
if (isInit || ident == "release" || ident == "bind" || ident == "del") {
// these can only be defined in an instance context
if (context->scope != Context::composite)
error(tok,
SPUG_FSTR("oper " << ident <<
" can only be defined in a class scope."
)
);
// these opers must be of type "void"
if (!returnType)
context->returnType = returnType =
context->construct->voidType.get();
else if (returnType != context->construct->voidType.get())
error(tok,
SPUG_FSTR("oper " << ident <<
" must be of return type 'void'"
)
);
expectToken(Token::lparen, "expected argument list");
// the operators other than "init" require an empty args list.
int expectedArgCount;
if (!isInit)
expectedArgCount = 0;
else
expectedArgCount = -1;
FuncFlags flags;
if (isInit)
flags = hasMemberInits;
else if (ident == "del")
flags = hasMemberDels;
else
flags = normal;
parseFuncDef(returnType, tok, "oper " + ident, flags,
expectedArgCount
);
} else if (ident == "x") {
// "oper x++" or "oper x--"
if (!returnType)
error(tok, "operator requires a return type");
tok = getToken();
if (tok.isIncr() || tok.isDecr()) {
expectToken(Token::lparen, "expected argument list.");
parseFuncDef(returnType, tok, "oper x" + tok.getData(),
normal,
(context->scope == Context::composite) ? 0 : 1
);
} else {
error(tok, "++ or -- expected after 'oper x' definition");
}
} else if (ident == "call") {
// check for instance scope
if (context->scope != Context::composite)
error(tok, "'oper call' can only be defined in a class scope.");
if (!returnType)
error(tok, "'call' operator requires a return type");
expectToken(Token::lparen, "expected argument list");
parseFuncDef(returnType, tok, "oper call", normal, -1);
} else if (ident == "to") {
TypeDefPtr type = parseTypeSpec();
// check for instance scope
if (context->scope != Context::composite)
error(tok,
SPUG_FSTR("oper to " << type->getDisplayName() <<
" can only be defined in a class scope."
)
);
// make sure that our return types is the type that we're converting
// to.
if (!returnType)
returnType = type.get();
else if (returnType != type.get())
error(tok, SPUG_FSTR("oper to " << type->getDisplayName() <<
" must return " << type->getDisplayName()
)
);
expectToken(Token::lparen, "expected argument list");
parseFuncDef(returnType, tok, "oper to " + type->getFullName(),
normal,
0
);
} else if (ident == "r") {
reversed = true;
tok = getToken();
} else {
unexpected(tok,
SPUG_FSTR(ident << " is not a legal operator").c_str()
);
}
// if we're done here, leave before processing symbolic operators
if (!reversed) return;
}
// not an identifier (or was a "r" for a reverse operator)
// all others require a return type
if (!returnType)
error(tok, "operator requires a return type");
if (tok.isLBracket()) {
// "oper []" or "oper []="
if (reversed) error(tok, "Only binary operators are reversible");
expectToken(Token::rbracket, "expected right bracket.");
tok = getToken();
if (context->scope != Context::composite)
error(tok,
"Bracket operators may only be defined in class scope."
);
if (tok.isAssign()) {
expectToken(Token::lparen, "expected argument list.");
parseFuncDef(returnType, tok, "oper []=", normal, -1);
} else {
parseFuncDef(returnType, tok, "oper []", normal, -1);
}
} else if (tok.isMinus()) {
// minus is special because it can be either unary or binary
if (reversed) error(tok, "Only binary operators are reversible");
expectToken(Token::lparen, "expected argument list.");
int numArgs = parseFuncDef(returnType, tok, "oper " + tok.getData(),
normal,
-1
);
int receiverCount = (context->scope == Context::composite);
if (numArgs != 1 - receiverCount && numArgs != 2 - receiverCount)
error(tok, SPUG_FSTR("'oper -' must have " << 1 - receiverCount <<
" or " << 2 - receiverCount <<
" arguments."
)
);
} else if (tok.isTilde() || tok.isBang()) {
if (reversed) error(tok, "Only binary operators are reversible");
expectToken(Token::lparen, "expected an argument list.");
// in composite context, these should have no arguments.
int numArgs = (context->scope == Context::composite) ? 0 : 1;
parseFuncDef(returnType, tok, "oper " + tok.getData(), normal,
numArgs
);
} else if (tok.isIncr() || tok.isDecr()) {
if (reversed) error(tok, "Only binary operators are reversible");
string sym = tok.getData();
tok = getToken();
if (!tok.isIdent() || tok.getData() != "x")
unexpected(tok,
"increment/decrement operators must include an 'x' "
"token to indicate pre or post: ex: oper ++x()"
);
expectToken(Token::lparen, "expected argument list.");
parseFuncDef(returnType, tok, "oper " + sym + "x",
normal,
(context->scope == Context::composite) ? 0 : 1
);
} else if (tok.isBinOp() || tok.isAugAssign()) {
// binary operators
if (reversed && tok.isAugAssign())
error(tok, "Only binary operators are reversible");
// in composite context, these should have just one argument.
int numArgs = (context->scope == Context::composite) ? 1 : 2;
expectToken(Token::lparen, "expected argument list.");
string name = (reversed ? "oper r" : "oper ") + tok.getData();
parseFuncDef(returnType, tok, name, reversed ? reverseOp: normal,
numArgs
);
} else {
unexpected(tok, "identifier or symbol expected after 'oper' keyword");
}
}
// [ n1, n2, ... ]
// ^ ^
void Parser::parseGenericParms(GenericParmVec &parms) {
Token tok = getToken();
while (true) {
if (tok.isIdent())
parms.push_back(new GenericParm(tok.getData()));
tok = getToken();
if (tok.isRBracket())
return;
else if (!tok.isComma())
unexpected(tok,
"comma or closing bracket expected in generic parameter "
"list."
);
else
tok = getToken();
}
}
void Parser::recordIStr(Generic *generic) {
int depth = 0;
while (true) {
Token tok = toker.getToken();
generic->addToken(tok);
if (tok.isLParen())
++depth;
else if (tok.isRParen() && !--depth)
toker.continueIString();
else if (tok.isIdent() && !depth)
toker.continueIString();
else if (tok.isIstrEnd())
return;
}
}
void Parser::recordBlock(Generic *generic) {
int bracketCount = 1;
while (bracketCount) {
// get the next token, use the low-level token so as not to process
// annotations.
Token tok = toker.getToken();
generic->addToken(tok);
if (tok.isLCurly())
++bracketCount;
else if (tok.isRCurly())
--bracketCount;
else if (tok.isIstrBegin())
recordIStr(generic);
else if (tok.isEnd())
error(tok, "Premature end of file");
}
}
void Parser::recordParenthesized(Generic *generic) {
Token tok = getToken();
if (!tok.isLParen())
unexpected(tok, "left parenthesis expected");
generic->addToken(tok);
int parenCount = 1;
while (parenCount) {
tok = getToken();
if (tok.isLParen())
++parenCount;
else if (tok.isRParen())
--parenCount;
generic->addToken(tok);
}
}
// class name : base, base { ... }
// ^ ^
// class name;
// ^ ^
TypeDefPtr Parser::parseClassDef() {
runCallbacks(classDef);
Token tok = getToken();
if (!tok.isIdent())
unexpected(tok, "Expected class name");
string className = tok.getData();
// check for an existing definition of the symbol
TypeDefPtr existing = checkForExistingDef(tok, className);
// check for a generic parameter list
tok = getToken();
Generic *generic = 0;
if (tok.isLBracket()) {
if (existing)
error(tok, "Generic classes can not be forward declared");
generic = new Generic();
parseGenericParms(generic->parms);
generic->ns = context->ns;
generic->compileNS = context->compileNS;
tok = getToken();
generic->addToken(tok);
}
// parse base class list
vector<TypeDefPtr> bases;
vector<TypeDefPtr> ancestors; // keeps track of all ancestors
if (tok.isColon())
while (true) {
// parse the base class name
TypeDefPtr baseClass = parseTypeSpec(0, generic);
if (!generic) {
// make sure that the class is not a forward declaration.
if (baseClass->forward)
error(tok,
SPUG_FSTR("you may not derive from forward declared "
"class " << baseClass->name
)
);
// make sure it's safe to add this as a base class given the
// existing set, and add it to the list.
baseClass->addToAncestors(*context, ancestors);
bases.push_back(baseClass);
}
tok = getToken();
if (generic) generic->addToken(tok);
if (tok.isLCurly())
break;
else if (!tok.isComma())
unexpected(tok, "expected comma or opening brace");
}
else if (tok.isSemi())
// forward declaration
return context->createForwardClass(className);
else if (!tok.isLCurly())
unexpected(tok, "expected colon or opening brace.");
// get any user flags
TypeDef::Flags flags = context->nextClassFlags;
context->nextClassFlags = TypeDef::noFlags;
// if we're recording a generic definition, just record the rest of the
// block, create a generic type and quit.
if (generic) {
recordBlock(generic);
TypeDefPtr result = new TypeDef(context->construct->classType.get(),
className,
true
);
result->genericInfo = generic;
result->generic = new TypeDef::SpecializationCache();
if (flags & TypeDef::abstractClass)
result->abstract = true;
addDef(result.get());
return result;
}
// if no base classes were specified, and Object has been defined, make
// Object the implicit base class.
if (!bases.size() && context->construct->objectType)
bases.push_back(context->construct->objectType);
// create a class context
ContextPtr classContext =
new Context(context->builder, Context::instance, context.get(), 0);
// emit the beginning of the class, hook it up to the class context and
// store a reference to it in the parent context.
TypeDefPtr type =
context->builder.emitBeginClass(*classContext, className, bases,
existing.get()
);
if (!existing)
addDef(type.get());
type->aliasBaseMetaTypes();
// check for an abstract class
if (flags & TypeDef::abstractClass)
type->abstract = true;
// add the "cast" methods
if (type->hasVTable) {
type->createCast(*classContext, true);
type->createCast(*classContext, false);
}
// create a lexical context which delegates to both the class context and
// the parent context.
NamespacePtr lexicalNS =
new CompositeNamespace(type.get(), context->ns.get());
ContextPtr lexicalContext =
classContext->createSubContext(Context::composite, lexicalNS.get());
// push the new context
ContextStackFrame cstack(*this, lexicalContext.get());
// parse the body
parseClassBody();
type->rectify(*classContext);
classContext->builder.emitEndClass(*classContext);
cstack.restore();
return type;
}
Parser::Parser(Toker &toker, model::Context *context) :
toker(toker),
nestID(0),
moduleCtx(context),
context(context) {
// build the precedence table
enum { noPrec, logOrPrec, logAndPrec, bitOrPrec, bitXorPrec, bitAndPrec,
cmpPrec, shiftPrec, addPrec, multPrec, unaryPrec
};
struct { const char *op; unsigned prec; } map[] = {
// unary operators are distinguished from their non-unary forms by
// appending an "x"
{"!x", unaryPrec},
{"-x", unaryPrec},
{"--x", unaryPrec},
{"++x", unaryPrec},
{"~x", unaryPrec},
{"*", multPrec},
{"/", multPrec},
{"%", multPrec},
{"+", addPrec},
{"<<", shiftPrec},
{">>", shiftPrec},
{"-", addPrec},
{"==", cmpPrec},
{"!=", cmpPrec},
{"<", cmpPrec},
{">", cmpPrec},
{"<=", cmpPrec},
{">=", cmpPrec},
{"is", cmpPrec},
{"&", bitAndPrec},
{"^", bitXorPrec},
{"|", bitOrPrec},
{"&&", logAndPrec},
{"||", logOrPrec},
{0, noPrec}
};
for (int i = 0; map[i].op; ++i)
opPrecMap[map[i].op] = map[i].prec;
}
void Parser::parse() {
// outer parser just parses an un-nested block
parseBlock(false, noCallbacks);
}
// class name { ... }
// ^ ^
void Parser::parseClassBody() {
runCallbacks(classEnter);
// parse the class body
while (true) {
state = st_base;
// check for a closing brace or a nested class definition
Token tok = getToken();
if (tok.isRCurly()) {
// run callbacks, this can change the token stream so make sure we've
// still got an end curly
toker.putBack(tok);
if (runCallbacks(classLeave)) {
Token tok2 = toker.getToken();
if (!tok2.isRCurly()) {
toker.putBack(tok2);
continue;
}
} else {
toker.getToken();
}
break;
} else if (tok.isSemi()) {
// ignore stray semicolons
continue;
} else if (tok.isClass()) {
state = st_notBase;
TypeDefPtr newType = parseClassDef();
continue;
// check for "oper" keyword
} else if (tok.isOper()) {
state = st_notBase;
parsePostOper(0);
continue;
// check for "alias" keyword.
} else if (tok.isAlias()) {
state = st_notBase;
parseAlias();
continue;
}
// parse some other kind of definition
toker.putBack(tok);
state = st_notBase;
TypeDefPtr type = parseTypeSpec();
TypeDef *tempType = type.get();
parseDef(tempType);
}
// make sure all forward declarations have been defined.
context->parent->checkForUnresolvedForwards();
}
VarDefPtr Parser::checkForExistingDef(const Token &tok, const string &name,
bool overloadOk
) {
ContextPtr classContext;
VarDefPtr existing = context->lookUp(name);
if (existing) {
Namespace *existingNS = existing->getOwner();
TypeDef *existingClass = 0;
// if it's ok to overload, make sure that the existing definition is a
// function or an overload def or a stub.
if (overloadOk && (FuncDefPtr::rcast(existing) ||
OverloadDefPtr::rcast(existing) ||
StubDefPtr::rcast(existing)
)
)
return existing;
// check for forward declarations
if (existingNS == context->getDefContext()->ns.get()) {
// forward function
FuncDef *funcDef;
if ((funcDef = FuncDefPtr::rcast(existing)) &&
funcDef->flags & FuncDef::forward
)
// treat a forward declaration the same as an overload.
return existing;
// forward class
TypeDef *typeDef;
if ((typeDef = TypeDefPtr::rcast(existing)) &&
typeDef->forward
)
return existing;
// redefinition in the same context is otherwise an error
redefineError(tok, existing.get());
}
}
return 0;
}
FuncDefPtr Parser::checkForOverride(VarDef *existingDef,
const ArgVec &argDefs,
Namespace *ownerNS,
const Token &nameTok,
const string &name
) {
OverloadDef *existingOvldDef = OverloadDefPtr::cast(existingDef);
FuncDefPtr override;
// if 1) the definition isn't an overload or 2) there is no function in the
// overload with the same arguments, or 3) there is one but it's
// overridable, we're done.
if (!existingOvldDef ||
!(override = existingOvldDef->getSigMatch(argDefs)) ||
override->isOverridable()
)
return override;
// if the owner namespace is a composite namespace, get the class namespace.
CompositeNamespace *cns = CompositeNamespacePtr::cast(ownerNS);
if (cns)
ownerNS = cns->getParent(0).get();
// if the override is not in the same context or a derived context, we're
// done and the caller should not consider the override so we return null.
TypeDefPtr overrideOwner, curClass;
if (override->getOwner() != ownerNS &&
(!(overrideOwner = TypeDefPtr::cast(override->getOwner())) ||
!(curClass = TypeDefPtr::cast(ownerNS)) ||
!curClass->isDerivedFrom(overrideOwner.get())
)
)
return 0;
// otherwise this is an illegal override
error(nameTok,
SPUG_FSTR("Definition of " << name << " hides previous overload.")
);
}
void Parser::redefineError(const Token &tok, const VarDef *existing) {
error(tok,
SPUG_FSTR("Symbol " << existing->name <<
" is already defined in this context."
)
);
}
void Parser::error(const Token &tok, const std::string &msg) {
context->error(tok.getLocation(), msg);
}
void Parser::warn(const Location &loc, const std::string &msg) {
context->warn(loc, msg);
}
void Parser::warn(const Token &tok, const std::string &msg) {
warn(tok.getLocation(), msg);
}
void Parser::addCallback(Parser::Event event, ParserCallback *callback) {
assert(event < eventSentinel);
callbacks[event].push_back(callback);
}
bool Parser::removeCallback(Parser::Event event, ParserCallback *callback) {
assert(event < eventSentinel);
CallbackVec &cbs = callbacks[event];
for (CallbackVec::iterator iter = cbs.begin(); iter != cbs.end(); ++iter)
if (*iter == callback) {
cbs.erase(iter);
return true;
}
// callback was not found
return false;
}
bool Parser::runCallbacks(Event event) {
assert(event < eventSentinel);
CallbackVec &cbs = callbacks[event];
bool gotCallbacks = cbs.size();
for (int i = 0; i < cbs.size(); ++i)
cbs[i]->run(this, &toker, context.get());
return gotCallbacks;
}
| C++ |
// Copyright 2003 Michael A. Muller
#include "ParseError.h"
#include "Token.h"
#include "sstream"
using namespace std;
using namespace parser;
void ParseError::abort(const Token &tok, const char *msg) {
Location loc = tok.getLocation();
stringstream text;
cout << loc.getName() << ':' << loc.getLineNumber() << ": " << msg << endl;
text << loc.getName() << ':' << loc.getLineNumber() << ": " << msg;
throw ParseError(text.str().c_str());
}
| C++ |
// Copyright 2003 Michael A. Muller
// Copyright 2009 Google Inc.
#include <limits.h>
#include <sstream>
#include <stdexcept>
#include <vector>
#include "Toker.h"
#include "ParseError.h"
using namespace std;
using namespace parser;
bool Toker::getChar(char &ch) {
bool result;
if (putbackIndex < putbackSize) {
ch = putbackBuf[putbackIndex++];
result = true;
} else {
result = src.read(&ch, 1);
}
if (result && ch == '\n')
locationMap.incrementLineNumber();
return result;
}
void Toker::ungetChar(char ch) {
assert(putbackIndex && "Toker putback overflow");
putbackBuf[--putbackIndex] = ch;
if (ch == '\n')
locationMap.decrementLineNumber();
}
void Toker::initIndent(bool indented) {
if (indented) {
indentedString = true;
indentLevel = 0;
minIndentLevel = INT_MAX;
} else {
indentedString = false;
}
}
void Toker::evaluateIndentation(const string &val) {
bool inPrefix = false;
int indent;
for (int i = 0; i < val.size(); ++i) {
if (val[i] == '\n') {
inPrefix = true;
indent = 0;
} else if (inPrefix) {
if (val[i] == ' ') {
indent += 1;
} else if (val[i] == '\t') {
indent = (indent / tabWidth + 1) * tabWidth;
} else if (val[i] == '\n') {
// ignore blank lines
indent = 0;
} else {
inPrefix = false;
if (indent < minIndentLevel)
minIndentLevel = indent;
}
}
}
if (inPrefix && indent && indent < minIndentLevel)
minIndentLevel = indent;
}
void Toker::fixIndentation(string &val) {
string result;
bool inPrefix = false;
int indent;
for (int i = 0; i < val.size(); ++i) {
if (val[i] == '\n') {
inPrefix = true;
indent = 0;
} else if (inPrefix) {
if (val[i] == ' ')
indent += 1;
else if (val[i] == '\t')
indent = (indent / tabWidth + 1) * tabWidth;
else {
inPrefix = false;
if (indent >= minIndentLevel)
indent -= minIndentLevel;
result.push_back('\n');
result.append(indent, ' ');
result.push_back(val[i]);
}
} else {
result.push_back(val[i]);
}
}
// if we ended in a prefix, flush it.
if (inPrefix) {
result.push_back('\n');
if (indent >= minIndentLevel)
indent -= minIndentLevel;
result.append(indent, ' ');
}
val = result;
}
Toker::Toker(std::istream &src, const char *sourceName, int lineNumber) :
src(src),
state(st_none),
putbackIndex(putbackSize),
indentedString(false) {
locationMap.setName(sourceName, lineNumber);
}
Token Toker::fixIdent(const string &data, const Location &loc) {
if (data == "break")
return Token(Token::breakKw, data, loc);
else if (data == "catch")
return Token(Token::catchKw, data, loc);
else if (data == "class")
return Token(Token::classKw, data, loc);
else if (data == "continue")
return Token(Token::continueKw, data, loc);
else if (data == "else")
return Token(Token::elseKw, data, loc);
else if (data == "if")
return Token(Token::ifKw, data, loc);
else if (data == "import")
return Token(Token::importKw, data, loc);
else if (data == "in")
return Token(Token::inKw, data, loc);
else if (data == "is")
return Token(Token::isKw, data, loc);
else if (data == "null")
return Token(Token::nullKw, data, loc);
else if (data == "return")
return Token(Token::returnKw, data, loc);
else if (data == "throw")
return Token(Token::throwKw, data, loc);
else if (data == "try")
return Token(Token::tryKw, data, loc);
else if (data == "while")
return Token(Token::whileKw, data, loc);
else if (data == "on")
return Token(Token::onKw, data, loc);
else if (data == "oper")
return Token(Token::operKw, data, loc);
else if (data == "for")
return Token(Token::forKw, data, loc);
else if (data == "typeof")
return Token(Token::typeofKw, data, loc);
else if (data == "const")
return Token(Token::constKw, data, loc);
else if (data == "module")
return Token(Token::moduleKw, data, loc);
else if (data == "lambda")
return Token(Token::lambdaKw, data, loc);
else if (data == "enum")
return Token(Token::enumKw, data, loc);
else if (data == "alias")
return Token(Token::aliasKw, data, loc);
else if (data == "case")
return Token(Token::caseKw, data, loc);
else if (data == "switch")
return Token(Token::switchKw, data, loc);
else
return Token(Token::ident, data,
locationMap.getLocation()
);
}
Token Toker::readToken() {
char ch, terminator;
// information on the preceeding characters for compound symbols
char symchars[4];
int sci = 0;
Token::Type t1, t2, t3;
// for parsing octal and hex character code escape sequences.
char codeChar;
int codeLen;
stringstream buf;
// we should only be able to enter this in one of two states.
assert((state == st_none || state == st_istr) &&
"readToken(): tokenizer in invalid state"
);
while (true) {
// read the next character from the stream
if (!getChar(ch)) break;
// processing varies according to state
switch (state) {
case st_none:
if (isspace(ch)) {
;
} else if (ch == 'i' || ch == 'b') {
// deal with i'str' and b'c' tokens
buf << ch;
state = st_strint;
} else if (ch == 'r') {
// deal with r'raw string' tokens
buf << ch;
state = st_rawStr;
} else if (ch == 'I') {
// deal with I'indented string' tokens.
buf << ch;
state = st_indentStr;
} else if (isalpha(ch) || ch == '_' || ch < 0) {
buf << ch;
state = st_ident;
} else if (ch == '#') {
state = st_comment;
} else if (ch == ';') {
return Token(Token::semi, ";", locationMap.getLocation());
} else if (ch == ',') {
return Token(Token::comma, ",", locationMap.getLocation());
} else if (ch == '=') {
symchars[sci++] = ch; t1 = Token::assign; t2 =Token::eq;
state = st_digram;
} else if (ch == '!') {
symchars[sci++] = ch; t1 = Token::bang; t2 =Token::ne;
state = st_digram;
} else if (ch == '>') {
symchars[sci++] = ch; t1 = Token::gt; t2 = Token::ge;
t3 = Token::bitRSh;
state = st_ltgt;
} else if (ch == '<') {
symchars[sci++] = ch; t1 = Token::lt; t2 =Token::le;
t3 = Token::bitLSh;
state = st_ltgt;
} else if (ch == '(') {
return Token(Token::lparen, "(", locationMap.getLocation());
} else if (ch == ')') {
return Token(Token::rparen, ")", locationMap.getLocation());
} else if (ch == '{') {
return Token(Token::lcurly, "{", locationMap.getLocation());
} else if (ch == '}') {
return Token(Token::rcurly, "}", locationMap.getLocation());
} else if (ch == '[') {
return Token(Token::lbracket, "[",
locationMap.getLocation()
);
} else if (ch == ']') {
return Token(Token::rbracket, "]",
locationMap.getLocation()
);
} else if (ch == '$') {
return Token(Token::dollar, "$",
locationMap.getLocation()
);
} else if (ch == '+') {
state = st_plus;
} else if (ch == '-') {
state = st_minus;
} else if (ch == '&') {
state = st_amp;
} else if (ch == '|') {
state = st_pipe;
} else if (ch == '*') {
t1 = Token::asterisk;
t2 = Token::assignAsterisk;
symchars[sci++] = ch;
state = st_postaug;
} else if (ch == '%') {
t1 = Token::percent; t2 = Token::assignPercent;
symchars[sci++] = ch;
state = st_postaug;
} else if (ch == '/') {
state = st_slash;
} else if (ch == '^') {
t1 = Token::bitXor;
t2 = Token::assignXor;
symchars[sci++] = ch;
state = st_postaug;
} else if (ch == '"' || ch == '\'') {
terminator = ch;
initIndent(false);
state = st_string;
t1 = Token::string;
} else if (ch == ':') {
symchars[sci++] = ch; t1 = Token::colon;
t2 = Token::define;
state = st_digram;
} else if (ch == '.') {
state = st_period;
} else if (ch == '@') {
return Token(Token::ann, "@", locationMap.getLocation());
} else if (isdigit(ch)) {
if (ch == '0') {
state = st_zero;
} else {
// [1-9]
buf << ch;
state = st_number;
}
} else if (ch == '~') {
return Token(Token::tilde, "~", locationMap.getLocation());
} else if (ch == '`') {
initIndent(false);
state = st_istr;
return Token(Token::istrBegin, "`",
locationMap.getLocation()
);
} else if (ch == '?') {
return Token(Token::quest, "?", locationMap.getLocation());
} else {
ParseError::abort(Token(Token::dot, "",
locationMap.getLocation()
),
"unknown token"
);
}
break;
case st_amp:
state = st_none;
if (ch == '&') {
return Token(Token::logicAnd, "&&",
locationMap.getLocation()
);
} else if (ch == '=') {
return Token(Token::assignAnd, "&=",
locationMap.getLocation()
);
} else {
ungetChar(ch);
return Token(Token::bitAnd, "&",
locationMap.getLocation()
);
}
break;
case st_pipe:
state = st_none;
if (ch == '|') {
return Token(Token::logicOr, "||",
locationMap.getLocation()
);
} else if (ch == '=') {
return Token(Token::assignOr, "|=",
locationMap.getLocation()
);
} else {
ungetChar(ch);
return Token(Token::bitOr, "|",
locationMap.getLocation()
);
}
break;
case st_minus:
state = st_none;
if (ch == '-') {
return Token(Token::decr, "--", locationMap.getLocation());
} else if (ch == '=') {
return Token(Token::assignMinus, "-=",
locationMap.getLocation()
);
} else {
ungetChar(ch);
return Token(Token::minus, "-", locationMap.getLocation());
}
break;
case st_ltgt:
if (ch == symchars[0]) {
symchars[sci++] = ch;
t1 = t3;
t2 = (ch == '<') ? Token::assignLSh : Token::assignRSh;
state = st_postaug;
break;
}
// fall through to digram
case st_digram:
state = st_none;
if (ch == '=') {
symchars[sci++] = ch;
symchars[sci++] = 0;
return Token(t2, symchars, locationMap.getLocation());
} else {
symchars[1] = 0;
ungetChar(ch);
return Token(t1, symchars, locationMap.getLocation());
}
break;
case st_period:
// check for float
if (isdigit(ch)) {
state = st_float;
buf << "." << ch;
}
else {
ungetChar(ch);
state = st_none;
return Token(Token::dot, ".", locationMap.getLocation());
}
break;
// integer or byte coded as a string
case st_strint:
if (ch == '"' || ch == '\'') {
state = st_string;
t1 = Token::integer;
terminator = ch;
break;
}
// fall through to ident processing via rawStr
// raw string
case st_rawStr:
if (ch == '"' || ch == '\'') {
state = st_rawStrBody;
terminator = ch;
buf.str("");
break;
}
// fall through to ident processing via st_indentStr
// indented string
case st_indentStr:
if (ch == '"' || ch == '\'') {
state = st_string;
initIndent(true);
terminator = ch;
buf.str("");
t1 = Token::string;
break;
} else if (state == st_indentStr && ch == '`') {
state = st_istr;
initIndent(true);
return Token(Token::istrBegin, "`",
locationMap.getLocation()
);
} else {
// last guy in the chain needs to set the state.
state = st_ident;
}
// fall through to ident processing
case st_ident:
// if we got a non-alphanumeric, non-underscore we're done
if (!isalnum(ch) && ch != '_' && ch > 0) {
ungetChar(ch);
state = st_none;
return fixIdent(buf.str(), locationMap.getLocation());
}
buf << ch;
break;
case st_slash:
if (ch == '/') {
state = st_comment;
} else if (ch == '=') {
state = st_none;
return Token(Token::assignSlash, "/=",
locationMap.getLocation()
);
} else if (ch == '*') {
state = st_ccomment;
} else {
ungetChar(ch);
state = st_none;
return Token(Token::slash, "/", locationMap.getLocation());
}
break;
case st_comment:
// newline character takes us out of the comment state
if (ch == '\n')
state = st_none;
break;
case st_ccomment:
if (ch == '*')
state = st_ccomment2;
break;
case st_ccomment2:
if (ch == '/')
state = st_none;
else
state = st_ccomment;
break;
case st_string:
// check for the terminator
if (ch == terminator) {
state = st_none;
string val = buf.str();
if (indentedString)
reindent(val);
return Token(t1, val, locationMap.getLocation());
} else if (ch == '\\') {
state = st_strEscapeChar;
} else {
buf << ch;
}
break;
case st_strEscapeChar:
case st_istrEscapeChar:
switch (ch) {
case 't':
buf << '\t';
break;
case 'n':
buf << '\n';
break;
case 'a':
buf << '\a';
break;
case 'r':
buf << '\r';
break;
case 'b':
buf << '\b';
break;
case 'x':
state = (state == st_strEscapeChar) ?
st_strHex :
st_istrHex;
codeChar = codeLen = 0;
break;
case '\n':
if (indentedString) {
indentLevel = 0;
state = (state == st_strEscapeChar) ?
st_strEscapedIndentedNewline :
st_istrEscapedIndentedNewline;
}
break;
default:
if (isdigit(ch) && ch < '8') {
codeChar = ch - '0';
codeLen = 1;
state = (state == st_strEscapeChar) ?
st_strOctal :
st_istrOctal;
} else {
buf << ch;
}
}
// if we haven't moved on to one of the character code states,
// return to the normal string processing state
if (state == st_strEscapeChar)
state = st_string;
else if (state == st_istrEscapeChar)
state = st_istr;
break;
case st_strEscapedIndentedNewline:
case st_istrEscapedIndentedNewline:
if (ch == ' ') {
++indentLevel;
} else if (ch == '\t') {
indentLevel = (indentLevel / tabWidth + 1) * tabWidth;
} else {
ungetChar(ch);
if (indentLevel < minIndentLevel)
minIndentLevel = indentLevel;
state = (state == st_strEscapedIndentedNewline) ?
st_string : st_istr;
}
break;
case st_strOctal:
case st_istrOctal:
if (isdigit(ch) && ch < '8' && codeLen < 3) {
codeChar = (codeChar << 3) | (ch - '0');
++codeLen;
} else {
buf << codeChar;
ungetChar(ch);
state = (state == st_strOctal) ? st_string : st_istr;
}
break;
case st_strHex:
case st_istrHex:
if (isdigit(ch)) {
ch = ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
ch = ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'F') {
ch = ch - 'A' + 10;
} else {
ParseError::abort(Token(Token::string, buf.str(),
locationMap.getLocation()
),
"invalid hex code escape sequence (must "
"be two hex digits)"
);
}
codeChar = (codeChar << 4) | ch;
++codeLen;
if (codeLen == 2) {
buf << codeChar;
state = (state == st_strHex) ? st_string : st_istr;
}
break;
case st_binary:
if (ch == '0' || ch == '1')
buf << ch;
else {
ungetChar(ch);
if (buf.str().size() == 0) {
ParseError::abort(Token(Token::string, buf.str(),
locationMap.getLocation()
),
"invalid binary constant"
);
}
state = st_none;
return Token(Token::binLit,
buf.str(),
locationMap.getLocation()
);
}
break;
case st_rawStrBody:
// check for the terminator
if (ch == terminator) {
state = st_none;
return Token(Token::string, buf.str(),
locationMap.getLocation()
);
}
buf << ch;
if (ch == '\\')
state = st_rawStrEscape;
break;
case st_rawStrEscape:
// the only thing special about escape chars in raw strings is
// that they can't preceed a terminator. This is how python
// does it, I'm not sure why, but barring compelling reasons
// to do anything else...
buf << ch;
state = st_rawStrBody;
break;
case st_octal:
if (ch >= '0' && ch <= '7')
buf << ch;
else {
ungetChar(ch);
if (buf.str().size() == 0) {
ParseError::abort(Token(Token::string, buf.str(),
locationMap.getLocation()
),
"invalid octal constant"
);
}
state = st_none;
return Token(Token::octalLit,
buf.str(),
locationMap.getLocation()
);
}
break;
case st_hex:
if (isxdigit(ch))
buf << ch;
else {
ungetChar(ch);
if (buf.str().size() == 0) {
ParseError::abort(Token(Token::string, buf.str(),
locationMap.getLocation()
),
"invalid hex constant"
);
}
state = st_none;
return Token(Token::hexLit,
buf.str(),
locationMap.getLocation()
);
}
break;
case st_zero:
// got a zero, check for hex, octal, and binary constants
if (ch == 'x' || ch == 'X') {
state = st_hex; // eats the 'x', ready to parse
// first hex digit
} else if (ch == 'o' || ch == 'O') {
state = st_octal; // eats the 'o', ready to parse
// first octal digit
// since strtol expects old style of octal, we
// add the leading 0
buf << '0';
} else if (ch == 'b' || ch == 'b') {
state = st_binary; // eats the 'b', ready to parse
// first binary digit
} else if (ch == '.') {
buf << ch;
state = st_float; // float
} else if (isdigit(ch)) {
// old school style octal
state = st_octal;
ungetChar(ch); // need to read this in octal state
// will fail there if it's > 7
} else {
ungetChar(ch);
state = st_none;
return Token(Token::integer, "0",
locationMap.getLocation()
);
}
break;
case st_number:
if (isdigit(ch)) {
buf << ch;
} else if (ch == '.') {
state = st_intdot;
} else if (ch == 'e' || ch == 'E') {
buf << ch;
state = st_exponent;
} else {
ungetChar(ch);
state = st_none;
return Token(Token::integer, buf.str(),
locationMap.getLocation()
);
}
break;
case st_intdot:
// integer followed by a period, could be a float if followed
// by another digit...
if (isdigit(ch)) {
buf << '.' << ch;
state = st_float;
} else {
// unget both the last character and the period since
// neither is part of this integer.
ungetChar(ch);
ungetChar('.');
state = st_none;
return Token(Token::integer, buf.str(),
locationMap.getLocation()
);
}
break;
case st_float:
if (isdigit(ch)) {
buf << ch;
} else if ((ch == 'e') || (ch == 'E')) {
state = st_exponent;
buf << ch;
} else {
ungetChar(ch);
Token::Type tt = (state == st_float) ? Token::floatLit :
Token::integer;
state = st_none;
return Token(tt,
buf.str(),
locationMap.getLocation()
);
}
break;
case st_exponent:
// eat possible + or - immediately and make sure
// we have at least one digit in exponent
if ((ch == '+') || (ch == '-')) {
buf << ch;
state = st_exponent2;
break;
}
// fall through to exponent2...
case st_exponent2:
// after E+/-, make sure we got at least one digit.
if (isdigit(ch)) {
buf << ch;
state = st_exponent3;
} else {
ParseError::abort(Token(Token::string, buf.str(),
locationMap.getLocation()
),
"invalid float specification");
}
break;
case st_exponent3:
if (isdigit(ch)) {
buf << ch;
} else {
ungetChar(ch);
state = st_none;
return Token(Token::floatLit, buf.str(),
locationMap.getLocation()
);
}
break;
case st_istr:
// note that we don't reindent in any of these values,
// reindenting of i-strings is done at the next level up.
if (ch == '`') {
if (buf.tellp()) {
// if we've accumulated some raw data since the last
// token was returned, return it as a string now and
// putback the '`' so we can do the istrEnd the next
// time.
ungetChar(ch);
return Token(Token::string, buf.str(),
locationMap.getLocation()
);
} else {
state = st_none;
return Token(Token::istrEnd, "`",
locationMap.getLocation()
);
}
} else if (ch == '$') {
state = st_none;
return Token(Token::string, buf.str(),
locationMap.getLocation()
);
} else if (ch == '\\') {
state = st_istrEscapeChar;
} else {
buf << ch;
}
break;
case st_plus:
state = st_none;
if (ch == '+') {
return Token(Token::decr, "++", locationMap.getLocation());
} else if (ch == '=') {
return Token(Token::assignPlus, "+=",
locationMap.getLocation()
);
} else {
ungetChar(ch);
return Token(Token::plus, "+", locationMap.getLocation());
}
break;
// we just scanned a sequence of characters that can be used for
// augmented assignment.
case st_postaug:
state = st_none;
if (ch == '=') {
symchars[sci++] = ch;
symchars[sci++] = 0;
return Token(t2, symchars, locationMap.getLocation());
} else {
symchars[sci++] = 0;
ungetChar(ch);
return Token(t1, symchars, locationMap.getLocation());
}
break;
default:
throw logic_error("tokenizer in illegal state");
}
}
// if we got here, we got to the end of the stream, make sure it was
// expected
if (state == st_none || state == st_comment) {
state = st_none;
return Token(Token::end, "", locationMap.getLocation());
} else if (state == st_ident) {
// it's ok for identifiers to be up against the end of the stream
state = st_none;
return Token(Token::ident, buf.str(), locationMap.getLocation());
} else {
ParseError::abort(Token(Token::end, "", locationMap.getLocation()),
"End of stream in the middle of a token"
);
}
}
Token Toker::getToken() {
// if any tokens have been put back, use them first
if (tokens.size()) {
Token temp = tokens.back();
tokens.pop_back();
// if we're currently in the i-string state, leave it if we don't pass
// a string. If we're not in it and we've got an i-string begin, get
// in it.
if (state == st_istr && !temp.isString() && !temp.isIstrBegin())
state = st_none;
else if (temp.isIstrBegin())
state = st_istr;
return temp;
} else {
vector<Token> toks;
toks.push_back(readToken());
// we want to read all of the i-string tokens as a batch so that we
// can apply the indentation transforms to them all collectively.
if (indentedString && toks.front().isIstrBegin()) {
// we have to approximate the parser here so that we can go back
// into i-string mode after parsing an expression
int parens = 0;
while (!toks.back().isIstrEnd() && !toks.back().isEnd()) {
Token &tok = toks.back();
if (parens) {
if (tok.isLParen()) {
++parens;
} else if (tok.isRParen()) {
--parens;
if (!parens)
continueIString();
} else if (tok.isIstrBegin()) {
ParseError::abort(tok,
"Nested i-strings are not "
"currently supported."
);
}
} else if (tok.isLParen()) {
++parens;
} else if (tok.isIdent()) {
continueIString();
}
toks.push_back(readToken());
}
for (int i = 0; i < toks.size(); ++i)
if (toks[i].isString())
evaluateIndentation(toks[i].data);
for (int i = 0; i < toks.size(); ++i)
if (toks[i].isString())
fixIndentation(toks[i].data);
// push everything but the first token
for (int i = toks.size() - 1; i; --i)
tokens.push_back(toks[i]);
}
return toks[0];
}
}
| C++ |
// Copyright 2003 Michael A. Muller
// Portions Copyright 2009 Google Inc.
#ifndef TOKER_H
#define TOKER_H
#include <assert.h>
#include <list>
#include <string>
#include "Token.h"
#include "LocationMap.h"
namespace parser {
/** The tokenizer. */
class Toker {
private:
// the "put-back" list - where tokens are stored after they've been put
// back
std::list<Token> tokens;
// source stream
std::istream &src;
// tracks the location
LocationMap locationMap;
// "fixes identifiers" by converting them to keywords if appropriate -
// if the identifier in 'raw' is a keyword, returns a keyword token,
// otherwise just returns the identifier token.
Token fixIdent(const std::string &raw, const Location &loc);
// reads the next token directly from the source stream
Token readToken();
// info for tracking the state of the tokenizer.
enum {
st_none,
st_ident,
st_slash,
st_minus,
st_plus,
st_digram,
st_comment,
st_ccomment,
st_ccomment2,
st_string,
st_strEscapeChar,
st_istrEscapeChar,
st_strOctal,
st_istrOctal,
st_strHex,
st_istrHex,
st_number,
st_intdot,
st_period,
st_zero,
st_float,
st_exponent,
st_exponent2,
st_exponent3,
st_amp,
st_istr,
st_pipe,
st_ltgt,
st_postaug,
st_hex,
st_octal,
st_binary,
st_strint,
st_rawStr,
st_rawStrBody,
st_rawStrEscape,
st_strEscapedIndentedNewline,
st_istrEscapedIndentedNewline,
st_indentStr
} state;
// the putback queue
enum { putbackSize = 2 };
char putbackBuf[putbackSize];
int putbackIndex;
// stuff for dealing with indentation.
// set to true if we are parsing an indented string
bool indentedString;
// indentLevel and minIndentLevel are only used for
// "escape-newline-whitespace" sequences to keep track of the smallest
// of them.
int indentLevel, minIndentLevel;
// size of a tab.
enum { tabWidth = 8 };
// get the next character from the stream.
bool getChar(char &ch);
// put back the character
void ungetChar(char ch);
// initialize all of the indentation state variables for a string,
// initialize for an indented string if indented is true.
void initIndent(bool indented);
// update minIndentLevel with the smallest indent level in the string.
// This ignores lines consisting entirely of whitespace and newlines at
// the end of the string
void evaluateIndentation(const std::string &val);
// reformat all indentation in the string, truncating all whitespace
// prefixes by minIndentLevel.
void fixIndentation(std::string &val);
// reindent the buffer based on the accumulated indentation state.
void reindent(std::string &val) {
evaluateIndentation(val);
fixIndentation(val);
}
public:
/** constructs a tokenizer from the source stream */
Toker(std::istream &src, const char *sourceName, int lineNumber = 1);
/**
* Returns the next token in the stream.
*/
Token getToken();
/**
* Puts the token back onto the stream. A subsequent getNext() will
* return the token.
*/
void putBack(const Token &token) {
tokens.push_back(token);
}
/**
* Tells the toker to continue scanning an interpolating string that was
* interrupted by a $ sequence.
*/
void continueIString() {
assert(state == st_none && "continueIString in invalid state");
state = st_istr;
}
/** Returns the tokenizer's location map. */
LocationMap &getLocationMap() { return locationMap; }
};
} // namespace parser
#endif
| C++ |
// Copyright 2003 Michael A. Muller
#include "Location.h"
Location::Location() :
name(""),
lineNumber(0) {
}
Location::Location(const char *name, int lineNumber) :
name(name),
lineNumber(lineNumber) {
}
| C++ |
// Copyright 2003 Michael A. Muller
#ifndef LOCATIONMAP_H
#define LOCATIONMAP_H
#include <string>
namespace parser {
/**
* Keeps track of a set of location objects. This class also tracks the state
* of an input stream - it has a "current file" and "current line" which it
* uses to optimize lifecycle management of the location objects.
*/
class LocationMap {
private:
std::string name;
int lineNumber;
typedef std::pair<std::string, int> LocTuple;
typedef std::map<LocTuple, Location> LocMap;
LocMap locMap;
Location lastLoc;
public:
/** sets the current source name and optionally the line number */
void setName(const char *newName, int newLineNumber = 1) {
LocMap::iterator item =
locMap.find(LocTuple(newName, newLineNumber));
if (item != locMap.end()) {
lastLoc = item->second;
} else {
lastLoc = new LocationImpl(newName, newLineNumber);
}
name = newName;
lineNumber = newLineNumber;
}
/** sets the current source line number */
void setLineNumber(int lineNumber) {
lineNumber = lineNumber;
}
/** returns a location object for the current location */
Location getLocation() const {
return lastLoc;
}
/** Returns a Location object for the specified location */
Location getLocation(const char *name, int lineNumber) {
setName(name, lineNumber);
return lastLoc;
}
/** increment the line number */
void incrementLineNumber() {
setName(lastLoc->name.c_str(), lastLoc->lineNumber + 1);
}
/** Decrement the line number (needed for character putbacks) */
void decrementLineNumber() {
setName(lastLoc->name.c_str(), lastLoc->lineNumber - 1);
}
};
} // namespace parser
#endif
| C++ |
// Copyright 2003 Michael A. Muller
#ifndef PARSEERROR_H
#define PARSEERROR_H
#include <spug/Exception.h>
namespace parser {
class Token;
/**
* Exception class for parsing errors.
*/
class ParseError : public spug::Exception {
public:
ParseError() {}
ParseError(const char *msg) : spug::Exception(msg) {}
ParseError(const std::string &msg) : spug::Exception(msg) {}
virtual const char *getClassName() const { return "ParseError"; }
static void abort(const Token &tok, const char *msg);
};
} // namespace parser
#endif
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.