Restructure repository to include all source folders

Move git root from Client/ to src/ to track all source code:
- Client: Game client source (moved to Client/Client/)
- Server: Game server source
- GameTools: Development tools
- CryptoSource: Encryption utilities
- database: Database scripts
- Script: Game scripts
- rylCoder_16.02.2008_src: Legacy coder tools
- GMFont, Game: Additional resources

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-29 20:17:20 +09:00
parent 5d3cd64a25
commit dd97ddec92
11602 changed files with 1446576 additions and 0 deletions

View File

@@ -0,0 +1,451 @@
/* lzoconf.h -- configuration for the LZO real-time data compression library
This file is part of the LZO real-time data compression library.
Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
All Rights Reserved.
The LZO library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
The LZO library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the LZO library; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Markus F.X.J. Oberhumer
<markus@oberhumer.com>
http://www.oberhumer.com/opensource/lzo/
*/
#ifndef __LZOCONF_H
#define __LZOCONF_H
#define LZO_VERSION 0x1080
#define LZO_VERSION_STRING "1.08"
#define LZO_VERSION_DATE "Jul 12 2002"
/* internal Autoconf configuration file - only used when building LZO */
#if defined(LZO_HAVE_CONFIG_H)
# include <config.h>
#endif
#include <limits.h>
#ifdef __cplusplus
extern "C" {
#endif
/***********************************************************************
// LZO requires a conforming <limits.h>
************************************************************************/
#if !defined(CHAR_BIT) || (CHAR_BIT != 8)
# error "invalid CHAR_BIT"
#endif
#if !defined(UCHAR_MAX) || !defined(UINT_MAX) || !defined(ULONG_MAX)
# error "check your compiler installation"
#endif
#if (USHRT_MAX < 1) || (UINT_MAX < 1) || (ULONG_MAX < 1)
# error "your limits.h macros are broken"
#endif
/* workaround a cpp bug under hpux 10.20 */
#define LZO_0xffffffffL 4294967295ul
#if !defined(LZO_UINT32_C)
# if (UINT_MAX < LZO_0xffffffffL)
# define LZO_UINT32_C(c) c ## UL
# else
# define LZO_UINT32_C(c) c ## U
# endif
#endif
/***********************************************************************
// architecture defines
************************************************************************/
#if !defined(__LZO_WIN) && !defined(__LZO_DOS) && !defined(__LZO_OS2)
# if defined(__WINDOWS__) || defined(_WINDOWS) || defined(_Windows)
# define __LZO_WIN
# elif defined(__WIN32__) || defined(_WIN32) || defined(WIN32)
# define __LZO_WIN
# elif defined(__NT__) || defined(__NT_DLL__) || defined(__WINDOWS_386__)
# define __LZO_WIN
# elif defined(__DOS__) || defined(__MSDOS__) || defined(MSDOS)
# define __LZO_DOS
# elif defined(__OS2__) || defined(__OS2V2__) || defined(OS2)
# define __LZO_OS2
# elif defined(__palmos__)
# define __LZO_PALMOS
# elif defined(__TOS__) || defined(__atarist__)
# define __LZO_TOS
# endif
#endif
#if (UINT_MAX < LZO_0xffffffffL)
# if defined(__LZO_WIN)
# define __LZO_WIN16
# elif defined(__LZO_DOS)
# define __LZO_DOS16
# elif defined(__LZO_PALMOS)
# define __LZO_PALMOS16
# elif defined(__LZO_TOS)
# define __LZO_TOS16
# elif defined(__C166__)
# else
/* porting hint: for pure 16-bit architectures try compiling
* everything with -D__LZO_STRICT_16BIT */
# error "16-bit target not supported - contact me for porting hints"
# endif
#endif
#if !defined(__LZO_i386)
# if defined(__LZO_DOS) || defined(__LZO_WIN16)
# define __LZO_i386
# elif defined(__i386__) || defined(__386__) || defined(_M_IX86)
# define __LZO_i386
# endif
#endif
#if defined(__LZO_STRICT_16BIT)
# if (UINT_MAX < LZO_0xffffffffL)
# include <lzo16bit.h>
# endif
#endif
/* memory checkers */
#if !defined(__LZO_CHECKER)
# if defined(__BOUNDS_CHECKING_ON)
# define __LZO_CHECKER
# elif defined(__CHECKER__)
# define __LZO_CHECKER
# elif defined(__INSURE__)
# define __LZO_CHECKER
# elif defined(__PURIFY__)
# define __LZO_CHECKER
# endif
#endif
/***********************************************************************
// integral and pointer types
************************************************************************/
/* Integral types with 32 bits or more */
#if !defined(LZO_UINT32_MAX)
# if (UINT_MAX >= LZO_0xffffffffL)
typedef unsigned int lzo_uint32;
typedef int lzo_int32;
# define LZO_UINT32_MAX UINT_MAX
# define LZO_INT32_MAX INT_MAX
# define LZO_INT32_MIN INT_MIN
# elif (ULONG_MAX >= LZO_0xffffffffL)
typedef unsigned long lzo_uint32;
typedef long lzo_int32;
# define LZO_UINT32_MAX ULONG_MAX
# define LZO_INT32_MAX LONG_MAX
# define LZO_INT32_MIN LONG_MIN
# else
# error "lzo_uint32"
# endif
#endif
/* lzo_uint is used like size_t */
#if !defined(LZO_UINT_MAX)
# if (UINT_MAX >= LZO_0xffffffffL)
typedef unsigned int lzo_uint;
typedef int lzo_int;
# define LZO_UINT_MAX UINT_MAX
# define LZO_INT_MAX INT_MAX
# define LZO_INT_MIN INT_MIN
# elif (ULONG_MAX >= LZO_0xffffffffL)
typedef unsigned long lzo_uint;
typedef long lzo_int;
# define LZO_UINT_MAX ULONG_MAX
# define LZO_INT_MAX LONG_MAX
# define LZO_INT_MIN LONG_MIN
# else
# error "lzo_uint"
# endif
#endif
typedef int lzo_bool;
/***********************************************************************
// memory models
************************************************************************/
/* Memory model for the public code segment. */
#if !defined(__LZO_CMODEL)
# if defined(__LZO_DOS16) || defined(__LZO_WIN16)
# define __LZO_CMODEL __far
# elif defined(__LZO_i386) && defined(__WATCOMC__)
# define __LZO_CMODEL __near
# else
# define __LZO_CMODEL
# endif
#endif
/* Memory model for the public data segment. */
#if !defined(__LZO_DMODEL)
# if defined(__LZO_DOS16) || defined(__LZO_WIN16)
# define __LZO_DMODEL __far
# elif defined(__LZO_i386) && defined(__WATCOMC__)
# define __LZO_DMODEL __near
# else
# define __LZO_DMODEL
# endif
#endif
/* Memory model that allows to access memory at offsets of lzo_uint. */
#if !defined(__LZO_MMODEL)
# if (LZO_UINT_MAX <= UINT_MAX)
# define __LZO_MMODEL
# elif defined(__LZO_DOS16) || defined(__LZO_WIN16)
# define __LZO_MMODEL __huge
# define LZO_999_UNSUPPORTED
# elif defined(__LZO_PALMOS16) || defined(__LZO_TOS16)
# define __LZO_MMODEL
# else
# error "__LZO_MMODEL"
# endif
#endif
/* no typedef here because of const-pointer issues */
#define lzo_byte unsigned char __LZO_MMODEL
#define lzo_bytep unsigned char __LZO_MMODEL *
#define lzo_charp char __LZO_MMODEL *
#define lzo_voidp void __LZO_MMODEL *
#define lzo_shortp short __LZO_MMODEL *
#define lzo_ushortp unsigned short __LZO_MMODEL *
#define lzo_uint32p lzo_uint32 __LZO_MMODEL *
#define lzo_int32p lzo_int32 __LZO_MMODEL *
#define lzo_uintp lzo_uint __LZO_MMODEL *
#define lzo_intp lzo_int __LZO_MMODEL *
#define lzo_voidpp lzo_voidp __LZO_MMODEL *
#define lzo_bytepp lzo_bytep __LZO_MMODEL *
#ifndef lzo_sizeof_dict_t
# define lzo_sizeof_dict_t sizeof(lzo_bytep)
#endif
/***********************************************************************
// calling conventions and function types
************************************************************************/
/* linkage */
#if !defined(__LZO_EXTERN_C)
# ifdef __cplusplus
# define __LZO_EXTERN_C extern "C"
# else
# define __LZO_EXTERN_C extern
# endif
#endif
/* calling convention */
#if !defined(__LZO_CDECL)
# if defined(__LZO_DOS16) || defined(__LZO_WIN16)
# define __LZO_CDECL __LZO_CMODEL __cdecl
# elif defined(__LZO_i386) && defined(_MSC_VER)
# define __LZO_CDECL __LZO_CMODEL __cdecl
# elif defined(__LZO_i386) && defined(__WATCOMC__)
# define __LZO_CDECL __LZO_CMODEL __cdecl
# else
# define __LZO_CDECL __LZO_CMODEL
# endif
#endif
#if !defined(__LZO_ENTRY)
# define __LZO_ENTRY __LZO_CDECL
#endif
/* C++ exception specification for extern "C" function types */
#if !defined(__cplusplus)
# undef LZO_NOTHROW
# define LZO_NOTHROW
#elif !defined(LZO_NOTHROW)
# define LZO_NOTHROW
#endif
typedef int
(__LZO_ENTRY *lzo_compress_t) ( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_ENTRY *lzo_decompress_t) ( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_ENTRY *lzo_optimize_t) ( lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_ENTRY *lzo_compress_dict_t)(const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem,
const lzo_byte *dict, lzo_uint dict_len );
typedef int
(__LZO_ENTRY *lzo_decompress_dict_t)(const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem,
const lzo_byte *dict, lzo_uint dict_len );
/* assembler versions always use __cdecl */
typedef int
(__LZO_CDECL *lzo_compress_asm_t)( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
typedef int
(__LZO_CDECL *lzo_decompress_asm_t)( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
/* a progress indicator callback function */
typedef void (__LZO_ENTRY *lzo_progress_callback_t) (lzo_uint, lzo_uint);
/***********************************************************************
// export information
************************************************************************/
/* DLL export information */
#if !defined(__LZO_EXPORT1)
# define __LZO_EXPORT1
#endif
#if !defined(__LZO_EXPORT2)
# define __LZO_EXPORT2
#endif
/* exported calling convention for C functions */
#if !defined(LZO_PUBLIC)
# define LZO_PUBLIC(_rettype) \
__LZO_EXPORT1 _rettype __LZO_EXPORT2 __LZO_ENTRY
#endif
#if !defined(LZO_EXTERN)
# define LZO_EXTERN(_rettype) __LZO_EXTERN_C LZO_PUBLIC(_rettype)
#endif
#if !defined(LZO_PRIVATE)
# define LZO_PRIVATE(_rettype) static _rettype __LZO_ENTRY
#endif
/* exported __cdecl calling convention for assembler functions */
#if !defined(LZO_PUBLIC_CDECL)
# define LZO_PUBLIC_CDECL(_rettype) \
__LZO_EXPORT1 _rettype __LZO_EXPORT2 __LZO_CDECL
#endif
#if !defined(LZO_EXTERN_CDECL)
# define LZO_EXTERN_CDECL(_rettype) __LZO_EXTERN_C LZO_PUBLIC_CDECL(_rettype)
#endif
/* exported global variables (LZO currently uses no static variables and
* is fully thread safe) */
#if !defined(LZO_PUBLIC_VAR)
# define LZO_PUBLIC_VAR(_type) \
__LZO_EXPORT1 _type __LZO_EXPORT2 __LZO_DMODEL
#endif
#if !defined(LZO_EXTERN_VAR)
# define LZO_EXTERN_VAR(_type) extern LZO_PUBLIC_VAR(_type)
#endif
/***********************************************************************
// error codes and prototypes
************************************************************************/
/* Error codes for the compression/decompression functions. Negative
* values are errors, positive values will be used for special but
* normal events.
*/
#define LZO_E_OK 0
#define LZO_E_ERROR (-1)
#define LZO_E_OUT_OF_MEMORY (-2) /* not used right now */
#define LZO_E_NOT_COMPRESSIBLE (-3) /* not used right now */
#define LZO_E_INPUT_OVERRUN (-4)
#define LZO_E_OUTPUT_OVERRUN (-5)
#define LZO_E_LOOKBEHIND_OVERRUN (-6)
#define LZO_E_EOF_NOT_FOUND (-7)
#define LZO_E_INPUT_NOT_CONSUMED (-8)
/* lzo_init() should be the first function you call.
* Check the return code !
*
* lzo_init() is a macro to allow checking that the library and the
* compiler's view of various types are consistent.
*/
#define lzo_init() __lzo_init2(LZO_VERSION,(int)sizeof(short),(int)sizeof(int),\
(int)sizeof(long),(int)sizeof(lzo_uint32),(int)sizeof(lzo_uint),\
(int)lzo_sizeof_dict_t,(int)sizeof(char *),(int)sizeof(lzo_voidp),\
(int)sizeof(lzo_compress_t))
LZO_EXTERN(int) __lzo_init2(unsigned,int,int,int,int,int,int,int,int,int);
/* version functions (useful for shared libraries) */
LZO_EXTERN(unsigned) lzo_version(void);
LZO_EXTERN(const char *) lzo_version_string(void);
LZO_EXTERN(const char *) lzo_version_date(void);
LZO_EXTERN(const lzo_charp) _lzo_version_string(void);
LZO_EXTERN(const lzo_charp) _lzo_version_date(void);
/* string functions */
LZO_EXTERN(int)
lzo_memcmp(const lzo_voidp _s1, const lzo_voidp _s2, lzo_uint _len);
LZO_EXTERN(lzo_voidp)
lzo_memcpy(lzo_voidp _dest, const lzo_voidp _src, lzo_uint _len);
LZO_EXTERN(lzo_voidp)
lzo_memmove(lzo_voidp _dest, const lzo_voidp _src, lzo_uint _len);
LZO_EXTERN(lzo_voidp)
lzo_memset(lzo_voidp _s, int _c, lzo_uint _len);
/* checksum functions */
LZO_EXTERN(lzo_uint32)
lzo_adler32(lzo_uint32 _adler, const lzo_byte *_buf, lzo_uint _len);
LZO_EXTERN(lzo_uint32)
lzo_crc32(lzo_uint32 _c, const lzo_byte *_buf, lzo_uint _len);
/* misc. */
LZO_EXTERN(lzo_bool) lzo_assert(int _expr);
LZO_EXTERN(int) _lzo_config_check(void);
typedef union { lzo_bytep p; lzo_uint u; } __lzo_pu_u;
typedef union { lzo_bytep p; lzo_uint32 u32; } __lzo_pu32_u;
typedef union { void *vp; lzo_bytep bp; lzo_uint32 u32; long l; } lzo_align_t;
/* align a char pointer on a boundary that is a multiple of `size' */
LZO_EXTERN(unsigned) __lzo_align_gap(const lzo_voidp _ptr, lzo_uint _size);
#define LZO_PTR_ALIGN_UP(_ptr,_size) \
((_ptr) + (lzo_uint) __lzo_align_gap((const lzo_voidp)(_ptr),(lzo_uint)(_size)))
/* deprecated - only for backward compatibility */
#define LZO_ALIGN(_ptr,_size) LZO_PTR_ALIGN_UP(_ptr,_size)
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* already included */

View File

@@ -0,0 +1,30 @@
#include "stdafx.h"
#include "minilzo.h"
#include "miniLZOWrapper.h"
#if _MSC_VER >= 1300
#define THREAD_LOCAL_STORAGE __declspec(thread) static
#else
#define THREAD_LOCAL_STORAGE
#endif
bool CMiniLZO::CheckLZOUsable()
{
return LZO_E_OK == lzo_init();
}
bool CMiniLZO::Compress(const char* in, unsigned long in_len,
char* out, unsigned long* lp_out_len)
{
THREAD_LOCAL_STORAGE lzo_voidp wrkmem[LZO1X_1_MEM_COMPRESS];
return (LZO_E_OK == lzo1x_1_compress(reinterpret_cast<const lzo_byte*>(in), in_len,
reinterpret_cast<lzo_byte*>(out), reinterpret_cast<lzo_uintp>(lp_out_len), wrkmem));
}
bool CMiniLZO::Decompress(const char* in, unsigned long in_len,
char* out, unsigned long* buffersize_in_out_len)
{
return (LZO_E_OK == lzo1x_decompress_safe(reinterpret_cast<const lzo_byte*>(in), in_len,
reinterpret_cast<lzo_byte*>(out), reinterpret_cast<lzo_uintp>(buffersize_in_out_len), 0));
}

View File

@@ -0,0 +1,20 @@
#ifndef _MINI_LZO_WRAPPER_H_
#define _MINI_LZO_WRAPPER_H_
namespace CMiniLZO
{
bool CheckLZOUsable();
bool Compress(const char* in, unsigned long in_len,
char* out, unsigned long* lp_out_len);
bool Decompress(const char* in, unsigned long in_len,
char* out, unsigned long* buffersize_in_out_len);
inline unsigned long GetLeastCompressBuffer(unsigned long dwInputBlockSize)
{
return dwInputBlockSize + (dwInputBlockSize / 64) + 16 + 3;
}
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,100 @@
/* minilzo.h -- mini subset of the LZO real-time data compression library
This file is part of the LZO real-time data compression library.
Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
All Rights Reserved.
The LZO library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
The LZO library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with the LZO library; see the file COPYING.
If not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Markus F.X.J. Oberhumer
<markus@oberhumer.com>
http://www.oberhumer.com/opensource/lzo/
*/
/*
* NOTE:
* the full LZO package can be found at
* http://www.oberhumer.com/opensource/lzo/
*/
#ifndef __MINILZO_H
#define __MINILZO_H
#define MINILZO_VERSION 0x1080
#ifdef __LZOCONF_H
# error "you cannot use both LZO and miniLZO"
#endif
#undef LZO_HAVE_CONFIG_H
#include "lzoconf.h"
#if !defined(LZO_VERSION) || (LZO_VERSION != MINILZO_VERSION)
# error "version mismatch in header files"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/***********************************************************************
//
************************************************************************/
/* Memory required for the wrkmem parameter.
* When the required size is 0, you can also pass a NULL pointer.
*/
#define LZO1X_MEM_COMPRESS LZO1X_1_MEM_COMPRESS
#define LZO1X_1_MEM_COMPRESS ((lzo_uint32) (16384L * lzo_sizeof_dict_t))
#define LZO1X_MEM_DECOMPRESS (0)
/* compression */
LZO_EXTERN(int)
lzo1x_1_compress ( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem );
/* decompression */
LZO_EXTERN(int)
lzo1x_decompress ( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem /* NOT USED */ );
/* safe decompression with overrun testing */
LZO_EXTERN(int)
lzo1x_decompress_safe ( const lzo_byte *src, lzo_uint src_len,
lzo_byte *dst, lzo_uintp dst_len,
lzo_voidp wrkmem /* NOT USED */ );
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* already included */

View File

@@ -0,0 +1,70 @@
#pragma once
class CDLLModule
{
public:
CDLLModule() : m_hDLL(NULL)
{
}
virtual ~CDLLModule() //destructor, free the library
{
Release();
}
//////////////////////////////////////////////////////////////////
// See if dll been loaded, returning true dose not mean that all
// functions of the dll is valid.
BOOL IsLoaded(void)
{
return m_hDLL != NULL;
}
VOID Release()
{
if( m_hDLL )
::FreeLibrary( m_hDLL );
m_hDLL = NULL;
}
/////////////////////////////////////////////////////////
// pure virtual, must implemented in derived class
// used macros to generate the implementation
virtual BOOL Init( LPCTSTR szDll ) = 0;
protected:
HMODULE m_hDLL;
};
//////////////////////////////////////////////////////////////////////
// macros to implement the Init function
#define DECLARE_DLL_FUNCTION(ret, cc, func, params) \
ret (cc *func)params;
#define BEGIN_DLL_INIT() \
BOOL Init( LPCTSTR szDll ) \
{ \
if( m_hDLL ) \
::FreeLibrary( m_hDLL ); \
m_hDLL = ::LoadLibrary( szDll ); \
BOOL bOk = FALSE;
#define INIT_DLL_TWIN_FUNCTION(ret, cc, func, params, origin) \
if( m_hDLL ) { \
func = (ret (cc* )params) GetProcAddress( m_hDLL, origin ); \
} else \
func = NULL; \
if( func ) \
bOk = TRUE;
#define END_DLL_INIT() \
return bOk; \
}
#define INIT_DLL_FUNCTION(ret, cc, func, params) \
if( m_hDLL ) { \
func = (ret (cc* )params)GetProcAddress( m_hDLL, #func ); \
} else \
func = NULL; \
if( func ) \
bOk = TRUE;

View File

@@ -0,0 +1,21 @@
#ifndef _CUSTOM_DEBUG_MACROS_
#define _CUSTOM_DEBUG_MACROS_
#define _QUOTE(x) # x
#define QUOTE(x) _QUOTE(x)
#define __FILE__LINE__ __FILE__ "(" QUOTE(__LINE__) ") : "
#define NOTE(x) message(x)
#define FILE_LINE message(__FILE__LINE__)
#define TODO(x) message(__FILE__LINE__"\n"\
" -------------------------------------------------\n"\
"| TODO : " x "\n"\
" -------------------------------------------------\n")
#define FIXME(x) message(__FILE__LINE__"\n"\
" -------------------------------------------------\n"\
"| FIXME : " x "\n"\
" -------------------------------------------------\n")
#define todo(x) message(__FILE__LINE__" TODO : " x "\n")
#define fixme(x) message(__FILE__LINE__" FIXME : " x "\n")
#define note(x) message(__FILE__LINE__" NOTE : " x "\n")
#endif

View File

@@ -0,0 +1,82 @@
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <lmerr.h>
#include <stdlib.h>
#include <winsock2.h>
#include <windows.h>
#include "DebugUtils.h"
//
// Set application-name for prefix of log filename
//
void DbgUtils::SetProgramName(TCHAR* pszOutBuffer, int nBufferSize, TCHAR* pszProgramName)
{
if(0 == pszProgramName)
{
TCHAR szDrive[MAX_PATH], szDir[MAX_PATH], szFilename[MAX_PATH], szExt[MAX_PATH];
// Figure out what the report file will be named, and store it away
GetModuleFileName(0, pszOutBuffer, nBufferSize);
PTSTR pszDot = pszOutBuffer;
// Look for the '.' before the "EXE" extension. Replace '.' to '\0'
if((pszDot = _tcsrchr( pszDot, _T('.'))))
{
*pszDot = 0;
}
_tsplitpath(pszOutBuffer, szDrive, szDir, szFilename, szExt);
_tcsncpy(pszOutBuffer, szFilename, nBufferSize);
}
else
{
_tcsncpy(pszOutBuffer, pszProgramName, nBufferSize);
}
}
DbgUtils::CConvertErrorToText& DbgUtils::CConvertErrorToText::GetInstance()
{
static CConvertErrorToText convertErrorToText;
return convertErrorToText;
}
DbgUtils::CConvertErrorToText::CConvertErrorToText()
: m_hNetMsg(LoadLibraryEx(TEXT("netmsg.dll"), NULL, LOAD_LIBRARY_AS_DATAFILE))
{
}
DbgUtils::CConvertErrorToText::~CConvertErrorToText()
{
if(0 != m_hNetMsg)
{
FreeLibrary(m_hNetMsg);
}
}
unsigned long DbgUtils::CConvertErrorToText::GetErrorTextBuffer(TCHAR* lpMessage,
unsigned long dwBufferLen,
unsigned long dwLastError)
{
unsigned long dwFormatFlags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM;
LPCVOID lpModule = 0;
if (dwLastError >= NERR_BASE && dwLastError <= MAX_NERR && 0 != m_hNetMsg)
{
lpModule = m_hNetMsg;
dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE;
}
return FormatMessage(dwFormatFlags, lpModule, dwLastError,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMessage, dwBufferLen, 0);
}

View File

@@ -0,0 +1,29 @@
#ifndef _DEBUG_UTILS_H_
#define _DEBUG_UTILS_H_
#include <tchar.h>
namespace DbgUtils
{
class CConvertErrorToText;
void SetProgramName(TCHAR* pszOutBuffer, int nBufferSize, TCHAR* pszProgamName = 0);
};
class DbgUtils::CConvertErrorToText
{
public:
unsigned long GetErrorTextBuffer(TCHAR* lpMessage,
unsigned long dwBufferLen, unsigned long dwLastError);
static CConvertErrorToText& GetInstance();
private:
CConvertErrorToText();
~CConvertErrorToText();
HMODULE m_hNetMsg;
};
#endif

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,174 @@
#pragma once
#include <dbghelp.h>
#include <cstdio>
#include "DLLModule.h"
#pragma comment(lib, "dbghelp.lib")
class CDBGFuncClass : public CDLLModule
{
public :
DECLARE_DLL_FUNCTION( BOOL, WINAPI, MiniDumpWriteDump, ( HANDLE, unsigned long, HANDLE, MINIDUMP_TYPE, CONST PMINIDUMP_EXCEPTION_INFORMATION, CONST PMINIDUMP_USER_STREAM_INFORMATION, CONST PMINIDUMP_CALLBACK_INFORMATION ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymEnumSymbols, ( HANDLE, ULONG64, PCSTR, PSYM_ENUMERATESYMBOLS_CALLBACK, PVOID ) )
DECLARE_DLL_FUNCTION( ULONG, WINAPI, SymSetContext, ( HANDLE, PIMAGEHLP_STACK_FRAME, PIMAGEHLP_CONTEXT ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymFromAddr, ( HANDLE, DWORD64, PDWORD64, PSYMBOL_INFO ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, StackWalk, ( unsigned long, HANDLE, HANDLE, LPSTACKFRAME, PVOID, PREAD_PROCESS_MEMORY_ROUTINE, PFUNCTION_TABLE_ACCESS_ROUTINE, PGET_MODULE_BASE_ROUTINE, PTRANSLATE_ADDRESS_ROUTINE ) )
// DECLARE_DLL_FUNCTION( BOOL, WINAPI, StackWalk64, ( unsigned long, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64 ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymGetLineFromAddr, ( HANDLE, unsigned long, PDWORD, PIMAGEHLP_LINE ) ) // ImageHlp
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymGetLineFromAddr64, ( HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64 ) )
DECLARE_DLL_FUNCTION( PVOID, WINAPI, SymFunctionTableAccess, ( HANDLE, unsigned long ) ) // ImageHlp
// DECLARE_DLL_FUNCTION( PVOID, WINAPI, SymFunctionTableAccess64, ( HANDLE, DWORD64 ) )
DECLARE_DLL_FUNCTION( DWORD64,WINAPI, SymGetModuleBase64, ( HANDLE, DWORD64 ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymInitialize, ( HANDLE, PSTR, BOOL ) )
DECLARE_DLL_FUNCTION( unsigned long, WINAPI, SymSetOptions, ( unsigned long ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymCleanup, ( HANDLE ) )
DECLARE_DLL_FUNCTION( unsigned long, WINAPI, SymGetModuleBase, ( HANDLE, unsigned long ) )
// DECLARE_DLL_FUNCTION( DWORD64,WINAPI, SymGetModuleBase64, ( HANDLE, DWORD64 ) )
DECLARE_DLL_FUNCTION( BOOL, WINAPI, SymGetTypeInfo, ( HANDLE, DWORD64, ULONG, IMAGEHLP_SYMBOL_TYPE_INFO, PVOID ) )
public:
BEGIN_DLL_INIT()
INIT_DLL_FUNCTION( BOOL, WINAPI, MiniDumpWriteDump, ( HANDLE, unsigned long, HANDLE, MINIDUMP_TYPE, CONST PMINIDUMP_EXCEPTION_INFORMATION, CONST PMINIDUMP_USER_STREAM_INFORMATION, CONST PMINIDUMP_CALLBACK_INFORMATION ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, SymEnumSymbols, ( HANDLE, ULONG64, PCSTR, PSYM_ENUMERATESYMBOLS_CALLBACK, PVOID ) )
INIT_DLL_FUNCTION( ULONG, WINAPI, SymSetContext, ( HANDLE, PIMAGEHLP_STACK_FRAME, PIMAGEHLP_CONTEXT ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, SymFromAddr, ( HANDLE, DWORD64, PDWORD64, PSYMBOL_INFO ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, StackWalk, ( unsigned long, HANDLE, HANDLE, LPSTACKFRAME, PVOID, PREAD_PROCESS_MEMORY_ROUTINE, PFUNCTION_TABLE_ACCESS_ROUTINE, PGET_MODULE_BASE_ROUTINE, PTRANSLATE_ADDRESS_ROUTINE ) )
// INIT_DLL_FUNCTION( BOOL, WINAPI, StackWalk64, ( unsigned long, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64 ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, SymGetLineFromAddr, ( HANDLE, unsigned long, PDWORD, PIMAGEHLP_LINE ) ) // ImageHlp
INIT_DLL_FUNCTION( BOOL, WINAPI, SymGetLineFromAddr64, ( HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64 ) )
INIT_DLL_FUNCTION( PVOID, WINAPI, SymFunctionTableAccess, ( HANDLE, unsigned long ) )
// INIT_DLL_FUNCTION( PVOID, WINAPI, SymFunctionTableAccess64, ( HANDLE, DWORD64 ) )
INIT_DLL_FUNCTION( DWORD64,WINAPI, SymGetModuleBase64, ( HANDLE, DWORD64 ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, SymInitialize, ( HANDLE, PSTR, BOOL ) )
INIT_DLL_FUNCTION( unsigned long, WINAPI, SymSetOptions, ( unsigned long ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, SymCleanup, ( HANDLE ) )
INIT_DLL_FUNCTION( unsigned long, WINAPI, SymGetModuleBase, ( HANDLE, unsigned long ) )
// INIT_DLL_FUNCTION( DWORD64,WINAPI, SymGetModuleBase64, ( HANDLE, DWORD64 ) )
INIT_DLL_FUNCTION( BOOL, WINAPI, SymGetTypeInfo, ( HANDLE, DWORD64, ULONG, IMAGEHLP_SYMBOL_TYPE_INFO, PVOID ) )
END_DLL_INIT()
};
enum BasicType // Stolen from CVCONST.H in the DIA 2.0 SDK
{
btNoType = 0,
btVoid = 1,
btChar = 2,
btWChar = 3,
btInt = 6,
btUInt = 7,
btFloat = 8,
btBCD = 9,
btBool = 10,
btLong = 13,
btULong = 14,
btCurrency = 25,
btDate = 26,
btVariant = 27,
btComplex = 28,
btBit = 29,
btBSTR = 30,
btHresult = 31
};
class CExceptionReport
{
public:
static CExceptionReport& GetInstance();
typedef int (WINAPI *UserFunc)(TCHAR* szBuffer, const int nBufferSize);
enum Features
{
CATCH_EXCEPTION = (1 << 0),
USE_MINIDUMP = (1 << 1),
USE_REPORT = (1 << 2)
};
void Enable(unsigned long dwEnableFeature);
void Disable(unsigned long dwDisableFeature);
void SetDumpLevel(MINIDUMP_TYPE eMiniDumpType) { m_eMiniDumpType = eMiniDumpType; }
void SetUserFunc(UserFunc lpUserFunc) { m_lpUserFunc = lpUserFunc; }
void WriteExceptionReport(PEXCEPTION_POINTERS pExceptionInfo);
static void SetProgramName(TCHAR* pszOutBuffer, int nBufferSize, TCHAR* pszProgramName);
static int WriteBasicInfo(TCHAR* szBuffer_Out, const int nBufferSize, PEXCEPTION_RECORD pExceptionRecord);
static int WriteRegistersInfo(TCHAR* szBuffer_Out, const int nBufferSize, PCONTEXT pContext);
static int WriteMemoryDump(TCHAR* szBuffer_Out, const int nBufferSize, PCONTEXT pContext,
unsigned int nMaxIPDump = 16, unsigned int nMaxStackDump = 1024);
static int WriteStackDetails(TCHAR* szBuffer_Out, const int nBufferSize,
PCONTEXT pContext, BOOL bWriteVariables, BOOL& bHasSymbol_Out, const int nStackDepth = 256);
static int Dump(TCHAR* szBuffer_Out, const int nBufferSize,
DWORD64 pData, unsigned long dwSize, BOOL bAlign);
CDBGFuncClass& GetDBGFuncClass() { return m_DBGHELP; }
private:
CExceptionReport();
~CExceptionReport();
void CloseLogFile();
LONG ProcessException(PEXCEPTION_POINTERS lpExceptionInfo);
LONG ProcessSecondException(PEXCEPTION_POINTERS lpExceptionInfo);
static LONG WINAPI UnhandledExceptionFilter(PEXCEPTION_POINTERS lpExceptionInfo) { return CExceptionReport::GetInstance().ProcessException(lpExceptionInfo); }
static LONG WINAPI UnhandledSecondExceptionFilter(PEXCEPTION_POINTERS lpExceptionInfo) { return CExceptionReport::GetInstance().ProcessSecondException(lpExceptionInfo); }
static void StoreCoreDump(void);
static LPTSTR GetExceptionString( unsigned long dwCode );
static BOOL GetLogicalAddress(PVOID addr, PTSTR szModule, unsigned long len, unsigned long& section, unsigned long& offset );
static BOOL CALLBACK EnumerateSymbolsCallback(PSYMBOL_INFO,ULONG, PVOID);
static BOOL FormatSymbolValue(PSYMBOL_INFO, STACKFRAME *, TCHAR * pszBuffer, unsigned nBufferSize);
static int DumpTypeIndex(TCHAR* szBuffer_Out,
const int nBufferSize, DWORD64 modBase, unsigned long dwTypeIndex,
unsigned int nestingLevel, DWORD_PTR offset, BOOL & bHandled);
static int FormatOutputValue(TCHAR* pszCurrBuffer,
const int nBufferSize, BasicType basicType, DWORD64 length, PVOID pAddress);
static BasicType GetBasicType(unsigned long typeIndex, DWORD64 modBase);
// ---------------------------------------------------------------------
// Data
enum
{
SHIFT_NUM = 4,
BYTES_PER_LINE = 16,
MAX_TEMP_VALUE = 5,
MAX_LOG_BUFFER = 65535 // 64-kb log buffer
};
CDBGFuncClass m_DBGHELP;
UserFunc m_lpUserFunc;
LPTOP_LEVEL_EXCEPTION_FILTER m_OldFilter;
TCHAR m_szLogPrefixName[MAX_PATH];
TCHAR m_szModuleName[MAX_PATH];
TCHAR m_szTempBuffer[MAX_PATH];
TCHAR m_szLogBuffer[MAX_LOG_BUFFER];
CONTEXT m_tempContext;
SYSTEMTIME m_tempSystemTime;
MINIDUMP_EXCEPTION_INFORMATION m_miniDumpInfo;
FILE* m_logFile;
BOOL m_bHasSymbol;
unsigned long m_dwFeaturesFlag;
MINIDUMP_TYPE m_eMiniDumpType;
};

View File

@@ -0,0 +1,194 @@
#include "stdafx.h"
#include <utility>
#include <algorithm>
#include <functional>
#include "DebugUtils.h"
#include "PerformanceCheck.h"
CPerformanceCheck& CPerformanceCheck::GetInstance()
{
static CPerformanceCheck performanceCheck;
return performanceCheck;
}
CPerformanceCheck::CPerformanceCheck()
: m_fnPreFix(0), m_fnPostFix(0)
{
ClockPerSec(m_Frequency, Frequency);
m_fFrequency = static_cast<double>(m_Frequency.QuadPart);
}
CPerformanceCheck::~CPerformanceCheck()
{
PerformanceCheckLock::Syncronize sync(m_TableLock);
m_InstrumentTable.clear();
}
void CPerformanceCheck::SetUserMessageFunc(FnPrintUserMessage fnPreFix, FnPrintUserMessage fnPostFix)
{
m_fnPreFix = fnPreFix;
m_fnPostFix = fnPostFix;
}
inline unsigned long perf_sdbmHash(const unsigned char *str)
{
unsigned long hash = 0;
int c;
while (c = *str++) { hash = c + (hash << 6) + (hash << 16) - hash; }
return hash;
}
void CPerformanceCheck::AddTime(const char* szfunctionName, double fEstimateTime)
{
unsigned long dwHashedKey = perf_sdbmHash(reinterpret_cast<const unsigned char*>(szfunctionName));
PerformanceCheckLock::Syncronize sync(m_TableLock);
fEstimateTime /= m_fFrequency;
std::pair<PerformanceTable::iterator, PerformanceTable::iterator> itrPair =
m_InstrumentTable.equal_range(dwHashedKey);
for(;itrPair.first != itrPair.second; ++itrPair.first)
{
Instrument& instrument = itrPair.first->second;
if(0 == strcmp(szfunctionName, instrument.m_szFunctionName))
{
// <20><><EFBFBD>̺<EFBFBD><CCBA><EFBFBD><EFBFBD><EFBFBD> ã<><C3A3> <20><><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD> <20><><EFBFBD>Ѵ<EFBFBD>.
instrument.m_fProcessTime += fEstimateTime;
if(instrument.m_fMinTime > fEstimateTime) { instrument.m_fMinTime = fEstimateTime; }
if(instrument.m_fMaxTime < fEstimateTime) { instrument.m_fMaxTime = fEstimateTime; }
++instrument.m_dwCalled;
return;
}
}
// <20><><EFBFBD>̺<EFBFBD><CCBA><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ʴ<EFBFBD> <20><><EFBFBD><EFBFBD>, <20>о<EFBFBD> <20>ִ´<D6B4>.
m_InstrumentTable.insert(std::make_pair(dwHashedKey, Instrument(dwHashedKey, fEstimateTime, szfunctionName)));
}
bool CPerformanceCheck::PrintAllTime(const char* fileName, bool bReset)
{
if(m_InstrumentTable.empty())
{
return false;
}
char strLogPath[MAX_PATH];
char strLogFileName[MAX_PATH];
DbgUtils::SetProgramName(strLogPath, MAX_PATH, 0);
// create the directory if it doesn't exist
if (INVALID_FILE_ATTRIBUTES == GetFileAttributes(strLogPath))
{
if (!CreateDirectory(strLogPath, 0))
{
return false;
}
}
// create log file name in good order
unsigned long dwSpinCount = 0;
unsigned long dwMaxFileSize = 50 * 1024 * 1024;
while(true)
{
_sntprintf(strLogFileName, MAX_PATH, "%s/PerformanceLog-%s-%05d.log",
strLogPath, fileName, dwSpinCount);
HANDLE hLogFile = CreateFile(strLogFileName, GENERIC_WRITE,
FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 );
if(INVALID_HANDLE_VALUE == hLogFile)
{
break;
}
else
{
unsigned long dwHighValue = 0;
unsigned long dwFileSize = GetFileSize(hLogFile, &dwHighValue);
CloseHandle(hLogFile);
if(dwHighValue == 0 && dwFileSize < dwMaxFileSize)
{
break;
}
}
++dwSpinCount;
}
// create log file
PerformanceCheckLock::Syncronize sync(m_TableLock);
FILE* logFile = fopen(strLogFileName, "at");
if(0 == logFile)
{
return false;
}
if(0 != m_fnPreFix)
{
m_fnPreFix(logFile);
}
fprintf(logFile,
" Average : Minimum : Maximum : Total : # : Profile Name\n"
"------------------------------------------------------------------------------------------------\n" );
double fTotalAvgTime = 0;
PerformanceTable::iterator pos;
PerformanceTable::iterator end;
for(pos = m_InstrumentTable.begin(),
end = m_InstrumentTable.end();
pos != end; ++pos)
{
const Instrument& instrument = pos->second;
if(0 == instrument.m_szFunctionName)
{
continue;
}
const double fAvgTime = (0.0f == instrument.m_fProcessTime) ?
0.0f : (instrument.m_fProcessTime / instrument.m_dwCalled); // Average
fTotalAvgTime += fAvgTime;
fprintf(logFile, " %3.6f %3.6f %3.6f %8.1f %10d %s\n",
fAvgTime, instrument.m_fMinTime, instrument.m_fMaxTime,
instrument.m_fProcessTime, instrument.m_dwCalled, instrument.m_szFunctionName);
}
fprintf(logFile, "\n\n Total AvgTime : %3.6f\n\n\n", fTotalAvgTime);
if(0 != m_fnPostFix)
{
m_fnPostFix(logFile);
}
fclose(logFile);
if(bReset)
{
for(pos = m_InstrumentTable.begin(),
end = m_InstrumentTable.end();
pos != end; ++pos)
{
pos->second.Initialize();
}
}
return true;
}

View File

@@ -0,0 +1,196 @@
#ifndef _FUNCTION_PERFORMANCE_CHECK_H_
#define _FUNCTION_PERFORMANCE_CHECK_H_
#include <winsock2.h>
#include <windows.h>
#include <map>
#include "../../Thread/Lock.h"
#include "../../Pattern/Singleton.h"
#define _USING_REALCLOCK
#if defined(_USING_REALCLOCK) && _M_IX86 >= 500
#define RealClock(Large_Integer_In) \
{ __asm rdtsc __asm mov Large_Integer_In.HighPart, edx __asm mov Large_Integer_In.LowPart, eax }
#define ClockSnapShot(Large_Integer_Out, UniqueVariableName) \
LARGE_INTEGER SnapShot##UniqueVariableName; \
RealClock(SnapShot##UniqueVariableName); \
Large_Integer_Out = SnapShot##UniqueVariableName
#define ClockPerSec(Large_Integer_Frequency_Out, UniqueVariableName) \
LARGE_INTEGER Start##UniqueVariableName, Stop##UniqueVariableName; \
RealClock(Start##UniqueVariableName) \
Sleep(1000); \
RealClock(Stop##UniqueVariableName) \
Large_Integer_Frequency_Out.QuadPart = \
Stop##UniqueVariableName.QuadPart - Start##UniqueVariableName.QuadPart - 57UL
#else
#define ClockSnapShot(Large_Integer_Out, UniqueVariableName) \
QueryPerformanceCounter(&Large_Integer_Out)
#define ClockPerSec(Large_Integer_Frequency_Out, UniqueVariableName) \
QueryPerformanceFrequency(&Large_Integer_Frequency_Out)
#endif
// ------------------------------------------------------------------------------------------------
// <20><> <20>Լ<EFBFBD><D4BC><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD>.
// identifiler<65><72> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>ԵǹǷ<C7B9>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><>Ģ<EFBFBD><C4A2> <20><><EFBFBD><EFBFBD><EFBFBD>ϰ<EFBFBD> <20><> <20><>.
// blockName<6D><65> <20>ݵ<EFBFBD><DDB5><EFBFBD> <20><><EFBFBD>ڿ<EFBFBD> <20><><EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD> <20><> <20><>.
#define DeclareBlockTimingCheck(blockName, identifiler) \
CPerformanceInstrument blockInstrument##identifiler(blockName);
#define BlockTimingCheckStart(identifiler) \
blockInstrument##identifiler.Start();
#define BlockTimingCheckStop(identifiler) \
blockInstrument##identifiler.Stop();
// ------------------------------------------------------------------------------------------------
// <20><> <20>Լ<EFBFBD><D4BC><EFBFBD><EFBFBD><EFBFBD> <20>Ѱ<EFBFBD><D1B0><EFBFBD> <20><> <20><> <20><><EFBFBD><EFBFBD>.
#define FunctionTimingCheck \
CPerformanceInstrument functionInstrument(__FUNCTION__); \
CAutoInstrument autofunctionInstrument(functionInstrument);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>Ϸ<EFBFBD> <20><><EFBFBD><EFBFBD>. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20>ʱ<EFBFBD>ȭ<EFBFBD>Ѵ<EFBFBD>.
#define GetFunctionTimingResult(fileName) \
CPerformanceCheck::GetInstance().PrintAllTime(fileName);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>Ϸ<EFBFBD> <20><><EFBFBD><EFBFBD>. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ʱ<EFBFBD>ȭ<EFBFBD><C8AD><EFBFBD><EFBFBD> <20>ʴ´<CAB4>.
#define GetFunctionTimingResultNoReset(fileName) \
CPerformanceCheck::GetInstance().PrintAllTime(fileName, false);
class CPerformanceCheck
{
public:
static CPerformanceCheck& GetInstance();
typedef void (*FnPrintUserMessage) (FILE* fDescriptor);
void SetUserMessageFunc(FnPrintUserMessage fnPreFix = 0, FnPrintUserMessage fnPostFix = 0);
void AddTime(const char* szfunctionName, double fEstimateTime);
bool PrintAllTime(const char* fileName, bool bReset = true);
private:
CPerformanceCheck();
~CPerformanceCheck();
// <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
struct Instrument
{
double m_fProcessTime;
double m_fMinTime;
double m_fMaxTime;
unsigned long m_dwHashKey;
unsigned long m_dwCalled;
const char* m_szFunctionName;
Instrument(unsigned long dwHashKey, double fProcessTime, const char* szFunctionName)
: m_dwHashKey(dwHashKey), m_fProcessTime(fProcessTime), m_dwCalled(1),
m_fMinTime(fProcessTime), m_fMaxTime(fProcessTime),
m_szFunctionName(szFunctionName) { }
Instrument()
: m_fProcessTime(0.0f), m_fMinTime(0.0f), m_fMaxTime(0.0f),
m_dwCalled(1), m_dwHashKey(0),
m_szFunctionName(NULL) { }
void Initialize()
{
m_fProcessTime = m_fMinTime = m_fMaxTime = 0.0f;
m_dwCalled = 0;
}
};
typedef CCSLock PerformanceCheckLock;
typedef std::multimap<unsigned long, Instrument> PerformanceTable;
PerformanceCheckLock m_TableLock;
CACHE_PAD(PerformanceCheckLockPad, sizeof(PerformanceCheckLock));
LARGE_INTEGER m_Frequency;
double m_fFrequency;
PerformanceTable m_InstrumentTable;
FnPrintUserMessage m_fnPreFix;
FnPrintUserMessage m_fnPostFix;
};
class CPerformanceInstrument
{
public:
CPerformanceInstrument(char* szfunctionName)
: m_szfunctionName(szfunctionName)
{
m_startTime.QuadPart = 0;
CPerformanceCheck::GetInstance().AddTime(m_szfunctionName, 0);
}
CPerformanceInstrument()
: m_szfunctionName(0)
{
m_startTime.QuadPart = 0;
}
void SetName(char* szfunctionName) { m_szfunctionName = szfunctionName; }
~CPerformanceInstrument() { }
inline void Start();
inline void Stop();
private:
LARGE_INTEGER m_startTime;
LARGE_INTEGER m_stopTime;
char* m_szfunctionName;
};
inline void CPerformanceInstrument::Start()
{
m_stopTime.QuadPart = 0;
ClockSnapShot(m_startTime, startTime);
}
inline void CPerformanceInstrument::Stop()
{
ClockSnapShot(m_stopTime, stopTime);
if(0 == m_stopTime.QuadPart) { ++m_stopTime.QuadPart; }
CPerformanceCheck::GetInstance().AddTime(m_szfunctionName,
static_cast<double>(m_stopTime.QuadPart - m_startTime.QuadPart));
}
class CAutoInstrument
{
public:
CAutoInstrument(CPerformanceInstrument& PerformanceInstrument)
: m_PerformanceInstrument(PerformanceInstrument) { m_PerformanceInstrument.Start(); }
~CAutoInstrument() { m_PerformanceInstrument.Stop(); }
private:
CPerformanceInstrument& m_PerformanceInstrument;
};
#endif

View File

@@ -0,0 +1,192 @@
#include "stdafx.h"
#include "MappedFile.h"
CMemoryMappedFile::CMemoryMappedFile()
: m_hFile(INVALID_HANDLE_VALUE), m_hMap(0)
{
}
CMemoryMappedFile::~CMemoryMappedFile()
{
Close();
}
bool CMemoryMappedFile::OpenFile(const char* szFileName, OpenMode eOpenMode)
{
DWORD dwOpenMode = 0;
DWORD dwShareMode = 0;
DWORD dwProtect = 0;
switch(eOpenMode)
{
case READ:
dwOpenMode = GENERIC_READ;
dwShareMode = FILE_SHARE_READ;
dwProtect = PAGE_READONLY;
m_dwFileViewMode = FILE_MAP_READ;
break;
case READ_WRITE:
dwOpenMode = GENERIC_READ | GENERIC_WRITE;
dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
dwProtect = PAGE_READWRITE;
m_dwFileViewMode = FILE_MAP_WRITE;
break;
};
Close();
m_hFile = CreateFile(szFileName, dwOpenMode,
dwShareMode, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if(INVALID_HANDLE_VALUE != m_hFile)
{
m_hMap = CreateFileMapping(m_hFile, 0, dwProtect, 0, 0, 0);
if(NULL != m_hMap)
{
return true;
}
else
{
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
}
}
return false;
}
// <20>޸𸮿<DEB8> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϰų<CFB0> <20><><EFBFBD><EFBFBD>.
bool CMemoryMappedFile::CreateSharedMemory(DWORD dwLowSize, DWORD dwHighSize, const char* szFileName)
{
Close();
m_hMap = CreateFileMapping(INVALID_HANDLE_VALUE, 0,
PAGE_READWRITE, dwHighSize, dwLowSize, szFileName);
return (0 != m_hMap);
}
bool CMemoryMappedFile::OpenSharedMemory(const char* szFileName, OpenMode eOpenMode)
{
Close();
switch(eOpenMode)
{
case READ:
m_dwFileViewMode = FILE_MAP_READ;
break;
case READ_WRITE:
m_dwFileViewMode = FILE_MAP_WRITE;
break;
};
m_hMap = OpenFileMapping(m_dwFileViewMode, FALSE, szFileName);
return (0 != m_hMap);
}
void CMemoryMappedFile::Close()
{
if(0 != m_hMap)
{
CloseHandle(m_hMap);
m_hMap = 0;
}
if(INVALID_HANDLE_VALUE != m_hFile)
{
CloseHandle(m_hFile);
m_hFile = INVALID_HANDLE_VALUE;
}
}
bool CMemoryMappedFile::IsOpen()
{
return (0 != m_hMap);
}
void* CMemoryMappedFile::GetFileView(DWORD dwLowPosition,
DWORD dwHighPosition,
DWORD dwMappingSize)
{
return MapViewOfFileEx(m_hMap, m_dwFileViewMode,
dwHighPosition, dwLowPosition, dwMappingSize, 0);
}
inline bool CMemoryMappedFile::CloseFileView(void* lpView)
{
if(0 != lpView)
{
return (TRUE == UnmapViewOfFile(lpView));
}
return false;
}
inline bool CMemoryMappedFile::FlushFileView(void* lpView, DWORD dwBytesToFlush)
{
return (TRUE == FlushViewOfFile(lpView, dwBytesToFlush));
}
bool CMemoryMappedFile::GetFileSize(unsigned long& dwLowSize, unsigned long& dwHighSize)
{
if(INVALID_HANDLE_VALUE != m_hFile)
{
dwLowSize = ::GetFileSize(m_hFile, &dwHighSize);
return true;
}
return false;
}
CFileMappedView::CFileMappedView(CMemoryMappedFile& mappedFile)
: m_MappedFile(mappedFile), m_FilePointer(0)
{
}
CFileMappedView::~CFileMappedView()
{
Close();
}
void* CFileMappedView::GetPointer(DWORD dwLowPosition,
DWORD dwHighPosition,
DWORD dwMappingSize)
{
Close();
m_FilePointer = m_MappedFile.GetFileView(
dwLowPosition, dwHighPosition, dwMappingSize);
return m_FilePointer;
}
void CFileMappedView::Flush(DWORD dwBytesToFlush)
{
m_MappedFile.FlushFileView(m_FilePointer, dwBytesToFlush);
}
void CFileMappedView::Close()
{
m_MappedFile.CloseFileView(m_FilePointer);
m_FilePointer = 0;
}

View File

@@ -0,0 +1,74 @@
#ifndef _GAMA_NETWORKLIB_MEMORY_MAPPED_FILE_
#define _GAMA_NETWORKLIB_MEMORY_MAPPED_FILE_
#include <winsock2.h>
#include <windows.h>
// forward decl
class CMemoryMappedFile;
class CFileMappedView
{
public:
CFileMappedView(CMemoryMappedFile& mappedFile);
~CFileMappedView();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ؼ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>͸<EFBFBD> <20><><EFBFBD><EFBFBD> <20>´<EFBFBD>.
void* GetPointer(DWORD dwLowPosition = 0,
DWORD dwHighPosition = 0, DWORD dwMappingSize = 0);
void Flush(DWORD dwBytesToFlush = 0); // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> Flush<73>Ѵ<EFBFBD>. (IPC<50><43><EFBFBD><EFBFBD> <20>ʿ<EFBFBD>)
void Close(); // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ݴ´<DDB4>.
private:
CMemoryMappedFile& m_MappedFile;
void* m_FilePointer;
};
class CMemoryMappedFile
{
public:
enum OpenMode
{
READ,
READ_WRITE
};
CMemoryMappedFile();
~CMemoryMappedFile();
// <20>̹<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>.
bool OpenFile(const char* szFileName, OpenMode eOpenMode);
// <20>޸𸮿<DEB8> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϰų<CFB0> <20><><EFBFBD><EFBFBD>.
bool CreateSharedMemory(DWORD dwLowSize, DWORD dwHighSize = 0, const char* szFileName = 0);
bool OpenSharedMemory(const char* szFileName, OpenMode eOpenMode);
bool IsOpen(); // <20>̹<EFBFBD> <20><><EFBFBD><EFBFBD> <20>ִ<EFBFBD><D6B4><EFBFBD> <20><><EFBFBD>ɴ<EFBFBD>.
void Close(); // <20><><EFBFBD><EFBFBD> <20>ִ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ݴ´<DDB4>.
// <20><><EFBFBD><EFBFBD> <20>ִ<EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD≯<EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ũ<><20>ش<EFBFBD>.
bool GetFileSize(unsigned long& dwLowSize, unsigned long& dwHighSize);
private:
// <20><><EFBFBD><EFBFBD> <20><20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<EFBFBD>.
void* GetFileView(DWORD dwLowPosition,
DWORD dwHighPosition = 0, DWORD dwMappingSize = 0);
static bool FlushFileView(void* lpView, DWORD dwBytesToFlush); // <20><><EFBFBD><EFBFBD> <20>並 Flush<73>Ѵ<EFBFBD>.
static bool CloseFileView(void* lpView); // <20><><EFBFBD><EFBFBD> <20><20>ݴ´<DDB4>.
HANDLE m_hFile;
HANDLE m_hMap;
DWORD m_dwFileViewMode;
friend class CFileMappedView;
};
#endif

View File

@@ -0,0 +1,220 @@
#ifndef _MATH_CONVERT_INLINE_H_
#define _MATH_CONVERT_INLINE_H_
#include <cstdlib>
#include <tchar.h>
inline void Math::Convert::Hex08ToStr( TCHAR *szDest, BYTE hex )
{
*((WORD *) szDest) = m_FastHeToBi[ hex ]; szDest += 2;
*(szDest) = '\0';
}
inline void Math::Convert::Hex16ToStr( TCHAR *szDest, WORD hex )
{
LPBYTE pSrc = (LPBYTE) &hex;
#ifdef BIG_ENDIAN
*((WORD *) (szDest + 0)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 2)) = m_FastHeToBi[ *(pSrc++) ];
#else
*((WORD *) (szDest + 2)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 0)) = m_FastHeToBi[ *(pSrc++) ];
#endif
*(szDest + 4) = '\0';
}
inline void Math::Convert::Hex32ToStr( TCHAR *szDest, unsigned long hex )
{
LPBYTE pSrc = (LPBYTE) &hex;
#ifdef BIG_ENDIAN
*((WORD *) (szDest + 0)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 2)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 4)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 6)) = m_FastHeToBi[ *(pSrc++) ];
#else
*((WORD *) (szDest + 6)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 4)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 2)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 0)) = m_FastHeToBi[ *(pSrc++) ];
#endif
*(szDest + 8) = '\0';
}
inline void Math::Convert::Hex64ToStr( TCHAR *szDest, DWORD64 hex )
{
LPBYTE pSrc = (LPBYTE) &hex;
#ifdef BIG_ENDIAN
*((WORD *) (szDest + 0)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 2)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 4)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 6)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 8)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 10)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 12)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 14)) = m_FastHeToBi[ *(pSrc++) ];
#else
*((WORD *) (szDest + 14)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 12)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 10)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 8)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 6)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 4)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 2)) = m_FastHeToBi[ *(pSrc++) ];
*((WORD *) (szDest + 0)) = m_FastHeToBi[ *(pSrc++) ];
#endif
*(szDest + 16) = '\0';
}
//
// this function returns the equivalent binary value for an individual character specified in the ascii format
inline TCHAR Math::Convert::BiToHe(TCHAR cBin)
{
if((cBin >= '0') && (cBin <= '9'))
{
return (cBin - '0');
}
else if((cBin >= 'A') && (cBin <= 'F'))
{
return (cBin - 'A' + 0xA);
}
if((cBin >= 'a') && (cBin <= 'f'))
{
return (cBin -'a' + 0xA);
}
return cBin;
}
inline void Math::Convert::AcToHe(char *szDst, char *szSrc, int iCount)
{
while(iCount--)
{
*szDst = BiToHe(*szSrc) << 4;
*szSrc++;
*szDst += BiToHe(*szSrc);
*szSrc++;
*szDst++;
}
}
inline BYTE Math::Convert::StrToHex08(const TCHAR *szSrc)
{
const TCHAR* pStart = szSrc + 2;
BYTE cHex = 0;
TCHAR c1, c2;
for (int i=0; i<1; ++i)
{
c1 = BiToHe(*pStart++);
c1 <<= (8*(7-i)+4);
c2 = BiToHe(*pStart++);
c2 <<= (8*(7-i));
cHex += (c1 + c2);
}
return cHex;
}
inline WORD Math::Convert::StrToHex16(const TCHAR *szSrc)
{
const TCHAR* pStart = szSrc + 2;
WORD sHex = 0;
for (int i=0; i<2; i++)
{
WORD s1 = BiToHe(*pStart++);
s1 <<= (8*(1-i)+4);
WORD s2 = BiToHe(*pStart++);
s2 <<= (8*(1-i));
WORD sRet = s1 + s2;
sHex += sRet;
}
return sHex;
}
// convert string to hexadecimal value
inline unsigned long Math::Convert::StrToHex32(const TCHAR *szSrc)
{
const TCHAR* pStart = szSrc + 2;
unsigned long nHex = 0;
for (int i=0; i<4; i++)
{
unsigned long n1 = BiToHe(*pStart++);
n1 <<= (8*(3-i)+4);
unsigned long n2 = BiToHe(*pStart++);
n2 <<= (8*(3-i));
unsigned long nRet = n1 + n2;
nHex += nRet;
}
return nHex;
}
// convert string to hexadecimal value
inline DWORD64 Math::Convert::StrToHex64(const TCHAR *szSrc)
{
const TCHAR* pStart = szSrc + 2;
DWORD64 dlHex = 0;
for (int i=0; i<8; i++)
{
DWORD64 dl1 = BiToHe(*pStart++);
dl1 <<= (8*(7-i)+4);
DWORD64 dl2 = BiToHe(*pStart++);
dl2 <<= (8*(7-i));
DWORD64 dlRet = dl1 + dl2;
dlHex += dlRet;
}
return dlHex;
}
inline BYTE Math::Convert::Atoc(const TCHAR *szSrc)
{
return (0 == _tcsncmp(szSrc, _T("0x"), 2)) ? StrToHex08(szSrc) : (BYTE) _ttol(szSrc);
}
//
// TCHAR *<2A><> <20><>Ĩ<EFBFBD>ô<EFBFBD>! (By Standil)
//
inline WORD Math::Convert::Atos(const TCHAR *szSrc)
{
return (0 == _tcsncmp(szSrc, _T("0x"), 2)) ? StrToHex16(szSrc) : _ttoi(szSrc);
}
//
// TCHAR *<2A><> <20><>Ĩ<EFBFBD>ô<EFBFBD>! (By Standil)
//
inline unsigned long Math::Convert::Atoi(const TCHAR *szSrc)
{
return (0 == _tcsncmp(szSrc, _T("0x"), 2)) ? StrToHex32(szSrc) : _ttol(szSrc);
}
//
// TCHAR *<2A><> <20><>Ĩ<EFBFBD>ô<EFBFBD>! (By Standil)
//
inline DWORD64 Math::Convert::Atol64(const TCHAR *szSrc)
{
return (0 == _tcsncmp(szSrc, _T("0x"), 2)) ? StrToHex64(szSrc) : _ttoi64(szSrc);
}
#endif

View File

@@ -0,0 +1,100 @@
// FastMath.cpp: implementation of the CFastMath class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Math.h"
#include "Random.h"
Math::RandomInt st_random;
///////////////////////////////////////////////////////////////////////////////////////////////
// utility functions
// 0 -0x7FFFFFFF.
unsigned long Math::Random::ComplexRandom(int nEndExtent, int nBeginExtent)
{
// <20><><EFBFBD><EFBFBD> <20>ҽ<EFBFBD><D2BD><EFBFBD> 100<30><30> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 0~99<39><39><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>µ<EFBFBD>
// <20><><EFBFBD><EFBFBD> <20>ۼ<EFBFBD><DBBC><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 100<30><30> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 0~100<30><30><EFBFBD><EFBFBD> <20><><EFBFBD>´<EFBFBD>.
// <20>׷<EFBFBD><D7B7><EFBFBD> -1<><31> <20>ϰ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<EFBFBD>.
if(nBeginExtent == 0)
return st_random.Next(nEndExtent);
return st_random.Next(nBeginExtent, nEndExtent);
/*
if (nEndExtent < 1 || nEndExtent <= nBeginExtent)
{
return nBeginExtent;
}
static unsigned long x = 1;
static unsigned long c = 0;
static unsigned long a = 2083801278UL;
#define addto(rh,rl,ah,al) (rl) = ((rl) + (al)) & 0xFFFFFFFFUL; \
(rh) = ((rh) + (ah) + (((rl) < (al)) ? 1 : 0)) & 0xFFFFFFFFUL
unsigned long xl = (x & 0xFFFFUL);
unsigned long xh = (x >> 16) & 0xFFFFUL;
unsigned long al = (a & 0xFFFFUL);
unsigned long ah = (a >> 16) & 0xFFFFUL;
unsigned long tmp;
x = c;
c = 0;
tmp = xl * al;
addto(c, x, 0, tmp);
tmp = xl * ah;
addto(c, x, (tmp >> 16), (tmp & 0xFFFFUL) << 16);
tmp = xh * ah;
addto(c, x, tmp, 1);
tmp = xh * al;
addto(c, x, (tmp >> 16), (tmp & 0xFFFFUL) << 16);
return (x % (nEndExtent - nBeginExtent)) + nBeginExtent; // return x & 0x7FFFFFFFUL;
*/
}
int Math::Random::SimpleRandom(unsigned long dwSeed, int nEndExtent, int nBeginExtent)
{
return( nBeginExtent + ((((dwSeed * 214013L + 2531011L) >> 16) & 0x7FFF) % (nEndExtent - nBeginExtent)) );
}
// This table only works on Little Endian(Byte Order) machine.
const unsigned short Math::Convert::m_FastHeToBi[0x100] =
{
0x3030, 0x3130, 0x3230, 0x3330, 0x3430, 0x3530, 0x3630, 0x3730,
0x3830, 0x3930, 0x4130, 0x4230, 0x4330, 0x4430, 0x4530, 0x4630,
0x3031, 0x3131, 0x3231, 0x3331, 0x3431, 0x3531, 0x3631, 0x3731,
0x3831, 0x3931, 0x4131, 0x4231, 0x4331, 0x4431, 0x4531, 0x4631,
0x3032, 0x3132, 0x3232, 0x3332, 0x3432, 0x3532, 0x3632, 0x3732,
0x3832, 0x3932, 0x4132, 0x4232, 0x4332, 0x4432, 0x4532, 0x4632,
0x3033, 0x3133, 0x3233, 0x3333, 0x3433, 0x3533, 0x3633, 0x3733,
0x3833, 0x3933, 0x4133, 0x4233, 0x4333, 0x4433, 0x4533, 0x4633,
0x3034, 0x3134, 0x3234, 0x3334, 0x3434, 0x3534, 0x3634, 0x3734,
0x3834, 0x3934, 0x4134, 0x4234, 0x4334, 0x4434, 0x4534, 0x4634,
0x3035, 0x3135, 0x3235, 0x3335, 0x3435, 0x3535, 0x3635, 0x3735,
0x3835, 0x3935, 0x4135, 0x4235, 0x4335, 0x4435, 0x4535, 0x4635,
0x3036, 0x3136, 0x3236, 0x3336, 0x3436, 0x3536, 0x3636, 0x3736,
0x3836, 0x3936, 0x4136, 0x4236, 0x4336, 0x4436, 0x4536, 0x4636,
0x3037, 0x3137, 0x3237, 0x3337, 0x3437, 0x3537, 0x3637, 0x3737,
0x3837, 0x3937, 0x4137, 0x4237, 0x4337, 0x4437, 0x4537, 0x4637,
0x3038, 0x3138, 0x3238, 0x3338, 0x3438, 0x3538, 0x3638, 0x3738,
0x3838, 0x3938, 0x4138, 0x4238, 0x4338, 0x4438, 0x4538, 0x4638,
0x3039, 0x3139, 0x3239, 0x3339, 0x3439, 0x3539, 0x3639, 0x3739,
0x3839, 0x3939, 0x4139, 0x4239, 0x4339, 0x4439, 0x4539, 0x4639,
0x3041, 0x3141, 0x3241, 0x3341, 0x3441, 0x3541, 0x3641, 0x3741,
0x3841, 0x3941, 0x4141, 0x4241, 0x4341, 0x4441, 0x4541, 0x4641,
0x3042, 0x3142, 0x3242, 0x3342, 0x3442, 0x3542, 0x3642, 0x3742,
0x3842, 0x3942, 0x4142, 0x4242, 0x4342, 0x4442, 0x4542, 0x4642,
0x3043, 0x3143, 0x3243, 0x3343, 0x3443, 0x3543, 0x3643, 0x3743,
0x3843, 0x3943, 0x4143, 0x4243, 0x4343, 0x4443, 0x4543, 0x4643,
0x3044, 0x3144, 0x3244, 0x3344, 0x3444, 0x3544, 0x3644, 0x3744,
0x3844, 0x3944, 0x4144, 0x4244, 0x4344, 0x4444, 0x4544, 0x4644,
0x3045, 0x3145, 0x3245, 0x3345, 0x3445, 0x3545, 0x3645, 0x3745,
0x3845, 0x3945, 0x4145, 0x4245, 0x4345, 0x4445, 0x4545, 0x4645,
0x3046, 0x3146, 0x3246, 0x3346, 0x3446, 0x3546, 0x3646, 0x3746,
0x3846, 0x3946, 0x4146, 0x4246, 0x4346, 0x4446, 0x4546, 0x4646,
};

View File

@@ -0,0 +1,99 @@
// FastMath.h: interface for the CFastMath class.
//
//////////////////////////////////////////////////////////////////////
#ifndef _CUSTOM_MATH_FUNCTIONS_H_
#define _CUSTOM_MATH_FUNCTIONS_H_
#include <winsock2.h>
#include <windows.h>
#include <cmath>
namespace Math
{
namespace Convert
{
extern const unsigned short m_FastHeToBi[0x100];
// SPX, IPX <20>ּ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD> <20>Լ<EFBFBD>
inline TCHAR BiToHe(TCHAR cBin);
inline void AcToHe(char *szDst, char *szSrc, int iCount);
// String<6E><67> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ٲ<EFBFBD>(String<6E><67> 0x<30><78> <20><><EFBFBD><EFBFBD> Hex string<6E>̴<EFBFBD>.)
inline BYTE StrToHex08(const TCHAR *szSrc);
inline WORD StrToHex16(const TCHAR *szSrc);
inline unsigned long StrToHex32(const TCHAR *szSrc);
inline DWORD64 StrToHex64(const TCHAR *szSrc);
// String<6E><67> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ٲ<EFBFBD>(0x<30><78> <20>ٴ<EFBFBD><D9B4><EFBFBD>, <20><><EFBFBD><EFBFBD> <20>ʴ<EFBFBD><CAB4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20>ٲ<EFBFBD> <20><> <20>ִ<EFBFBD>)
inline BYTE Atoc(const TCHAR *szSrc);
inline WORD Atos(const TCHAR *szSrc);
inline unsigned long Atoi(const TCHAR *szSrc);
inline DWORD64 Atol64(const TCHAR *szSrc);
// <20><><EFBFBD><EFBFBD> Hex String<6E><67><EFBFBD><EFBFBD> <20>ٲ<EFBFBD>
inline void Hex08ToStr(TCHAR *szDest, BYTE hex);
inline void Hex16ToStr(TCHAR *szDest, WORD hex);
inline void Hex32ToStr(TCHAR *szDest, unsigned long hex);
inline void Hex64ToStr(TCHAR *szDest, DWORD64 hex);
};
namespace Random
{
// <20><><EFBFBD>ϰ<EFBFBD><CFB0><EFBFBD> nBeginExtent ~ nEndExtent - 1<><31> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>´<EFBFBD>.
unsigned long ComplexRandom(int nEndExtent, int nBeginExtent = 0); // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>.
int SimpleRandom(unsigned long dwSeed, int nEndExtent, int nBeginExtent = 0);
};
namespace HashFunc
{
// -------------------------------------------------------------------------------------------------
// String-to-Hash <20>Լ<EFBFBD><D4BC><EFBFBD> : http://www.cs.yorku.ca/~oz/hash.html <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
inline unsigned long djb2Hash(const unsigned char *str); // first reported by dan bernstein
inline unsigned long sdbmHash(const unsigned char *str); // this is one of the algorithms used in berkeley db
inline unsigned long looseHash(const unsigned char *str); // <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ؽ<EFBFBD>. <20>׳<EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>.
};
namespace Const
{
static float PI = 3.14159f;
}
};
#include "Convert.inl"
inline unsigned long Math::HashFunc::djb2Hash(const unsigned char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ }
return hash;
}
inline unsigned long Math::HashFunc::sdbmHash(const unsigned char *str)
{
unsigned long hash = 0;
int c;
while (c = *str++) { hash = c + (hash << 6) + (hash << 16) - hash; }
return hash;
}
inline unsigned long Math::HashFunc::looseHash(const unsigned char *str)
{
unsigned int hash = 0;
int c;
while (c = *str++) { hash += c; }
return hash;
}
#endif // !defined(AFX_FASTMATH_H__ED69578B_18C1_42EA_9C5E_888DC38101C2__INCLUDED_)

View File

@@ -0,0 +1,65 @@
// mtrand.cpp, see include file mtrand.h for information
#include "stdafx.h"
#include "PseudoRandom.h"
#include <time.h>
// non-inline function definitions and static member definitions cannot
// reside in header file because of the risk of multiple declarations
// initialization of static private members
/*unsigned long MersenneTwister::state[Constant1] = {0x0UL};
int MersenneTwister::position = 0;*/
namespace Math
{
MersenneTwister::MersenneTwister(BOOL useCurrentTime) {
if ( useCurrentTime) {
time_t t; time(&t);
SetSeed(unsigned long(t));
} else {
SetSeed(5489UL);
}
}
void MersenneTwister::GenerateState() { // generate new state vector
for (int i = 0; i < (Constant1 - Constant2); ++i)
state[i] = state[i + Constant2] ^ Twiddle(state[i], state[i + 1]);
for (int i = Constant1 - Constant2; i < (Constant1 - 1); ++i)
state[i] = state[i + Constant2 - Constant1] ^ Twiddle(state[i], state[i + 1]);
state[Constant1 - 1] = state[Constant2 - 1] ^ Twiddle(state[Constant1 - 1], state[0]);
position = 0; // reset position
}
void MersenneTwister::SetSeed(unsigned long s) { // initialized by 32 bit seed
for ( int i=0; i<Constant1; ++i) { state[i]= 0x0UL; }
//state[Constant1] = {0x0UL};
state[0] = s & 0xFFFFFFFFUL; // for > 32 bit machines
for (int i = 1; i < Constant1; ++i) {
state[i] = 1812433253UL * (state[i - 1] ^ (state[i - 1] >> 30)) + i;
// see Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier
// in the previous versions, MSBs of the seed affect only MSBs of the array state
// 2002/01/09 modified by Makoto Matsumoto
state[i] &= 0xFFFFFFFFUL; // for > 32 bit machines
}
position = Constant1; // force GenerateState() to be called for next random number
}
void MersenneTwister::SetSeed(const unsigned long* array, int size) { // initialized by array
SetSeed(19650218UL);
int i = 1, j = 0;
for (int k = ((Constant1 > size) ? Constant1 : size); k; --k) {
state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1664525UL))
+ array[j] + j; // non linear
state[i] &= 0xFFFFFFFFUL; // for > 32 bit machines
++j; j %= size;
if ((++i) == Constant1) { state[0] = state[Constant1 - 1]; i = 1; }
}
for (int k = Constant1 - 1; k; --k) {
state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >> 30)) * 1566083941UL)) - i;
state[i] &= 0xFFFFFFFFUL; // for > 32 bit machines
if ((++i) == Constant1) { state[0] = state[Constant1 - 1]; i = 1; }
}
state[0] = 0x80000000UL; // MSB is 1; assuring non-zero initial array
position = Constant1; // force GenerateState() to be called for next random number
}
}

View File

@@ -0,0 +1,224 @@
#pragma once
namespace Math
{
/**
The Mersenne Twister random number generator
usage:
PseudoRandomInt foo; //initializes random sequence by the current time
PseudoRandomInt foo(false); // the default seed 5489UL is used
foo.SetSeed(230194019);
foo.Next()
foo.Next(10,4300); //returns unsigned long between 10 and 4300
PseudoRandomFloat foo;
foo.Next(); // return double between [0..1)
foo.Next(245); // return double between [0..245)
PseudoRandomFloatClosed foo;
foo.Next(); // return double between [0..1]
PseudoRandomFloatOpen foo;
foo.Next(); // return double between (0..1)
details:
The Mersenne twister is a pseudorandom number generator that was developed in 1997 by Makoto Matsumoto
(<28><><EFBFBD><EFBFBD> <20><>) and Takuji Nishimura (<28><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>). It provides for fast generation of very high quality random
numbers - having been designed specifically to rectify many of the flaws found in older algorithms.
It has the following desirable properties:
It was designed to have a colossal period of 219937-1 (the creators of the algorithm proved this property).
It has a very high order of dimensional equidistribution (see linear congruential generator). Note that this means, by default, that there is negligible serial correlation between successive values in the output sequence.
It is faster than all but the most statistically unsound generators.
It is statistically random in all the bits of its output.
This implementation is based C++ code by Takuji Nishimura and Makoto Matsumoto, Jasper Bedaux, Isaku Wada
*/
class MersenneTwister {
public:
// default constructor: uses default seed only if this is the first instance
MersenneTwister(BOOL useCurrentTime=TRUE);
// constructor with 32 bit int as seed
MersenneTwister(unsigned long s) { SetSeed(s); }
// constructor with array of size 32 bit ints as seed
MersenneTwister(const unsigned long* array, int size) { SetSeed(array, size); }
// the two seed functions
void SetSeed(unsigned long); // seed with 32 bit integer
void SetSeed(const unsigned long*, int size); // seed with array
// overload operator() to make this a generator (functor)
//unsigned long operator()() { return GenerateRandom(); }
//unsigned long Next() { return (*this)(); }
~MersenneTwister() {} // destructor
protected: // used by derived classes, otherwise not accessible; use the ()-operator
unsigned long GenerateRandom() { // generate 32 bit random integer
if (position == Constant1) GenerateState(); // new state vector needed
// GenerateState() is split off to be non-inline, because it is only called once
// in every 624 calls and otherwise irand() would become too big to get inlined
unsigned long x = state[position++];
x ^= (x >> 11);
x ^= (x << 7) & 0x9D2C5680UL;
x ^= (x << 15) & 0xEFC60000UL;
return x ^ (x >> 18);
}
private:
enum { Constant1 = 624, Constant2 = 397 };
unsigned long state[Constant1]; // state vector array
int position; // position in state array
// private functions used to generate the pseudo random numbers
unsigned long Twiddle(unsigned long u, unsigned long v) {
return (((u & 0x80000000UL) | (v & 0x7FFFFFFFUL)) >> 1) ^ ((v & 1UL) ? 0x9908B0DFUL : 0x0UL);
} // used by GenerateState()
void GenerateState(); // generate new state
// make copy constructor and assignment operator unavailable, they don't make sense
MersenneTwister(const MersenneTwister&); // copy constructor not defined
void operator=(const MersenneTwister&); // assignment operator not defined
};
class PseudoRandomInt : public MersenneTwister {
public:
PseudoRandomInt(BOOL useCurrentTime=TRUE): MersenneTwister(useCurrentTime) {}
PseudoRandomInt(unsigned long seed) : MersenneTwister(seed) {}
PseudoRandomInt(const unsigned long* seed, int size) : MersenneTwister(seed, size) {}
unsigned long operator()() { return GenerateRandom(); }
unsigned long Next() { return (*this)(); }
unsigned long Next(unsigned long minval, unsigned long maxval) {
return minval+(Next()%(maxval-minval));
}
};
// generates double floating point numbers in the half-open interval [0, 1)
class PseudoRandomFloat : public MersenneTwister {
public:
PseudoRandomFloat(BOOL useCurrentTime=TRUE) : MersenneTwister(useCurrentTime) {}
PseudoRandomFloat(unsigned long seed) : MersenneTwister(seed) {}
PseudoRandomFloat(const unsigned long* seed, int size) : MersenneTwister(seed, size) {}
~PseudoRandomFloat() {}
double operator()() {
return static_cast<double>(GenerateRandom()) * (1. / 4294967296.); } // divided by 2^32
double Next() { return (*this)(); }
double Next(double mul) { return Next()*mul; }
private:
PseudoRandomFloat(const PseudoRandomFloat&); // copy constructor not defined
void operator=(const PseudoRandomFloat&); // assignment operator not defined
};
// generates double floating point numbers in the closed interval [0, 1]
class PseudoRandomFloatClosed : public MersenneTwister {
public:
PseudoRandomFloatClosed(BOOL useCurrentTime=TRUE) : MersenneTwister(useCurrentTime) {}
PseudoRandomFloatClosed(unsigned long seed) : MersenneTwister(seed) {}
PseudoRandomFloatClosed(const unsigned long* seed, int size) : MersenneTwister(seed, size) {}
~PseudoRandomFloatClosed() {}
double operator()() {
return static_cast<double>(GenerateRandom()) * (1. / 4294967295.); } // divided by 2^32 - 1
double Next() { return (*this)(); }
double Next(double mul) { return Next()*mul; }
private:
PseudoRandomFloatClosed(const PseudoRandomFloatClosed&); // copy constructor not defined
void operator=(const PseudoRandomFloatClosed&); // assignment operator not defined
};
// generates double floating point numbers in the open interval (0, 1)
class PseudoRandomFloatOpen : public MersenneTwister {
public:
PseudoRandomFloatOpen(BOOL useCurrentTime=TRUE) : MersenneTwister(useCurrentTime) {}
PseudoRandomFloatOpen(unsigned long seed) : MersenneTwister(seed) {}
PseudoRandomFloatOpen(const unsigned long* seed, int size) : MersenneTwister(seed, size) {}
~PseudoRandomFloatOpen() {}
double operator()() {
return (static_cast<double>(GenerateRandom()) + .5) * (1. / 4294967296.); } // divided by 2^32
double Next() { return (*this)(); }
double Next(double mul) { return Next()*mul; }
private:
PseudoRandomFloatOpen(const PseudoRandomFloatOpen&); // copy constructor not defined
void operator=(const PseudoRandomFloatOpen&); // assignment operator not defined
};
// generates 53 bit resolution doubles in the half-open interval [0, 1)
class PseudoRandomFloat53Bit : public MersenneTwister {
public:
PseudoRandomFloat53Bit(BOOL useCurrentTime=TRUE) : MersenneTwister(useCurrentTime) {}
PseudoRandomFloat53Bit(unsigned long seed) : MersenneTwister(seed) {}
PseudoRandomFloat53Bit(const unsigned long* seed, int size) : MersenneTwister(seed, size) {}
~PseudoRandomFloat53Bit() {}
double operator()() {
return (static_cast<double>(GenerateRandom() >> 5) * 67108864. +
static_cast<double>(GenerateRandom() >> 6)) * (1. / 9007199254740992.); }
double Next() { return (*this)(); }
double Next(double mul) { return Next()*mul; }
private:
PseudoRandomFloat53Bit(const PseudoRandomFloat53Bit&); // copy constructor not defined
void operator=(const PseudoRandomFloat53Bit&); // assignment operator not defined
};
// typedef MersenneTwister PseudoRandom;
// Pseudorandom series(21301391);
// mtrand.h
// C++ include file for MT19937, with initialization improved 2002/1/26.
// Coded by Takuji Nishimura and Makoto Matsumoto.
// Ported to C++ by Jasper Bedaux 2003/1/1 (see http://www.bedaux.net/mtrand/).
// The generators returning floating point numbers are based on
// a version by Isaku Wada, 2002/01/09
//
// Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. The names of its contributors may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Any feedback is very welcome.
// http://www.math.keio.ac.jp/matumoto/emt.html
// email: matumoto@math.keio.ac.jp
//
// Feedback about the C++ port should be sent to Jasper Bedaux,
// see http://www.bedaux.net/mtrand/ for e-mail address and info.
}

View File

@@ -0,0 +1,63 @@
#include "stdafx.h"
#include "Random.h"
namespace Math
{
RandomInt::RandomInt()
{
SetSeed(GetTickCount());
}
RandomInt::RandomInt(unsigned long seed) : random(seed)
{
}
void RandomInt::SetSeed(unsigned long seed)
{
random.SetSeed(seed);
}
unsigned int RandomInt::Next()
{
return random.Next();
}
unsigned int RandomInt::Next(unsigned int excludedMax)
{
if(excludedMax == 0)
return excludedMax;
return Next(0, excludedMax);
}
unsigned int RandomInt::Next(unsigned int includedMin, unsigned int excludedMax)
{
if(includedMin == excludedMax)
return includedMin;
return random.Next(includedMin, excludedMax);
}
RandomDouble::RandomDouble()
{
SetSeed(GetTickCount());
}
RandomDouble::RandomDouble(unsigned long seed) : random(seed)
{
}
void RandomDouble::SetSeed(unsigned long seed)
{
random.SetSeed(seed);
}
double RandomDouble::Next()
{
return random.Next();
}
}

View File

@@ -0,0 +1,45 @@
#pragma once
#include "PseudoRandom.h"
namespace Math
{
class RandomInt
{
private:
PseudoRandomInt random;
// unable to copy
RandomInt(const RandomInt& );
void operator =(const RandomInt&);
public:
RandomInt();
RandomInt(unsigned long seed);
void SetSeed(unsigned long seed);
virtual unsigned int Next();
virtual unsigned int Next(unsigned int excludedMax);
virtual unsigned int Next(unsigned int includedMin, unsigned int excludedMax);
};
class RandomDouble
{
private:
PseudoRandomFloatClosed random;
// unable to copy
RandomDouble(const RandomDouble& );
void operator =(const RandomDouble&);
public:
RandomDouble();
RandomDouble(unsigned long seed);
void SetSeed(unsigned long seed);
virtual double Next(); // generates a float number [0, 1]
};
}

View File

@@ -0,0 +1,187 @@
#include "stdafx.h"
#include <winsock2.h>
#include <windows.h>
#include "RegFunctions.h"
#include <fstream>
bool Registry::WriteString(const char *FileName_In, const char *Section_In,
const char *KeyName_In, const char *Value_In)
{
return 0 != WritePrivateProfileString(Section_In, KeyName_In, Value_In, FileName_In);
}
unsigned long Registry::ReadInt(const char *FileName_In, const char *Section_In, const char *KeyName_In)
{
return static_cast<unsigned long>(GetPrivateProfileInt(Section_In, KeyName_In, 0, FileName_In));
}
bool Registry::ReadString(const char *FileName_In, const char *Section_In,
const char *KeyName_In, char *Buffer_Out, int nBufferSize)
{
return 0 != GetPrivateProfileString(Section_In, KeyName_In,
NULL, Buffer_Out, nBufferSize, FileName_In);
}
bool Registry::WriteStruct(const char *FileName_In, const char *Section_In,
const char *KeyName_In, void *Value_In, const int Size_in)
{
return 0 != WritePrivateProfileStruct(Section_In, KeyName_In, Value_In, Size_in, FileName_In);
}
bool Registry::ReadStruct(const char *FileName_In, const char *Section_In,
const char *KeyName_In, void *Value_Out, const int Size_in)
{
return 0 != GetPrivateProfileStruct(Section_In, KeyName_In, Value_Out, Size_in, FileName_In);
}
Registry::CSetupFile::CSetupFile()
{
}
Registry::CSetupFile::CSetupFile(const char* szFileName)
{
Open(szFileName);
}
Registry::CSetupFile::~CSetupFile()
{
}
inline unsigned long sdbmHash(const unsigned char *str)
{
unsigned long hash = 0;
int c;
while (c = *str++) { hash = c + (hash << 6) + (hash << 16) - hash; }
return hash;
}
bool Registry::CSetupFile::Open(const char* szFileName)
{
std::string fileLine;
std::string szSection;
std::string szKey;
std::string szValue;
fileLine.reserve(4096);
szSection.reserve(1024);
szKey.reserve(1024);
szValue.reserve(4096);
std::fstream file(szFileName, std::ios_base::in);
std::string::size_type nPosition = std::string::npos;
std::string::size_type nEndPosition = std::string::npos;
std::string::size_type nDataPosition = std::string::npos;
std::string::size_type nDataEndPosition = std::string::npos;
unsigned long dwSectionValue = 0;
if(file.is_open())
{
while(std::getline(file, fileLine))
{
nPosition = fileLine.find_first_not_of(" \r\n\t");
if(std::string::npos != nPosition)
{
if('[' == fileLine[nPosition])
{
// <20><><EFBFBD>Ǹ<EFBFBD><C7B8><EFBFBD>
nEndPosition = fileLine.find_first_of(']', nPosition);
if(std::string::npos != nEndPosition)
{
szSection.assign(fileLine.begin() + nPosition + 1,
fileLine.begin() + nEndPosition);
dwSectionValue = sdbmHash(reinterpret_cast<const unsigned char*>(szSection.c_str()));
}
}
else if(0 != fileLine.compare(nPosition, sizeof(char) * 2, "//"))
{
// <20>ּ<EFBFBD> <20>ƴ<EFBFBD>
nEndPosition = fileLine.find_first_of('=', nPosition);
if(std::string::npos != nEndPosition)
{
// nEndPosition <20>¿<EFBFBD><C2BF><EFBFBD> Key - Value Pair<69><72>.
nDataEndPosition = fileLine.find_last_not_of("= \t", nEndPosition);
if(std::string::npos != nDataEndPosition)
{
// Ű <20>о<EFBFBD><D0BE><EFBFBD>.
szKey.assign(fileLine.begin() + nPosition,
fileLine.begin() + nDataEndPosition + 1);
nDataPosition = fileLine.find_first_not_of("= \t", nEndPosition);
if(std::string::npos != nDataPosition)
{
nDataEndPosition = fileLine.find_last_not_of(" \r\n\t");
if(std::string::npos != nDataEndPosition)
{
// <20><> <20>о<EFBFBD><D0BE><EFBFBD>
m_SetupMap.insert(SetupMap::value_type(
sdbmHash(reinterpret_cast<const unsigned char*>(szKey.c_str())) + dwSectionValue,
Data(szSection, szKey,
std::string(fileLine.begin() + nDataPosition, fileLine.begin() + nDataEndPosition + 1))));
}
}
}
}
}
}
}
}
return false;
}
void Registry::CSetupFile::Clear()
{
m_SetupMap.clear();
}
const char* Registry::CSetupFile::GetString(const char* szSection, const char* szKey,
const char* szDefaultValue)
{
DWORD dwHashValue = sdbmHash(reinterpret_cast<const unsigned char*>(szSection))
+ sdbmHash(reinterpret_cast<const unsigned char*>(szKey));
std::pair<SetupMap::iterator, SetupMap::iterator> pos_pair = m_SetupMap.equal_range(dwHashValue);
for(; pos_pair.first != pos_pair.second; ++pos_pair.first)
{
Data& data = pos_pair.first->second;
if(0 == data.m_szSection.compare(szSection) &&
0 == data.m_szKey.compare(szKey))
{
return data.m_szValue.c_str();
}
}
return szDefaultValue;
}
unsigned int Registry::CSetupFile::GetInt(const char* szSection, const char* szKey,
unsigned int nDefaultValue)
{
const char* szStr = GetString(szSection, szKey);
if(0 != szStr)
{
return atoi(szStr);
}
return nDefaultValue;
}

View File

@@ -0,0 +1,59 @@
#ifndef _REGISTRY_FUNCTIONS_H_
#define _REGISTRY_FUNCTIONS_H_
#include <map>
#include <string>
namespace Registry
{
bool WriteString(const char *FileName_In, const char *Section_In,
const char *KeyName_In, const char *Value_In);
unsigned long ReadInt(const char *FileName_In,
const char *Section_In, const char *KeyName_In);
bool ReadString(const char *FileName_In, const char *Section_In,
const char *KeyName_In, char *Buffer_Out, int nBufferSize);
bool WriteStruct(const char *FileName_In, const char *Section_In,
const char *KeyName_In, void *Value_In, const int Size_in);
bool ReadStruct(const char *FileName_In, const char *Section_In,
const char *KeyName_In, void *Value_Out, const int Size_in);
class CSetupFile
{
public:
CSetupFile();
CSetupFile(const char* szFileName);
~CSetupFile();
bool Open(const char* szFileName);
void Clear();
const char* GetString(const char* szSection, const char* szKey, const char* szDefaultValue = 0);
unsigned int GetInt(const char* szSection, const char* szKey, unsigned int nDefaultValue = 0);
private:
struct Data
{
std::string m_szSection;
std::string m_szKey;
std::string m_szValue;
Data(const std::string& szSection, const std::string& szKey, const std::string& szValue)
: m_szSection(szSection), m_szKey(szKey), m_szValue(szValue)
{
}
};
typedef std::multimap<unsigned long, Data> SetupMap;
SetupMap m_SetupMap;
};
};
#endif

View File

@@ -0,0 +1,225 @@
/******************************************************************************
Module: EnsureCleanup.h
Notices: Copyright (c) 2000 Jeffrey Richter
Purpose: These classes ensure object cleanup when an object goes out of scope.
See Appendix B.
******************************************************************************/
#ifndef _ENSURE_CLEAN_UP_BY_JEFFERY_RICHTER
#define _ENSURE_CLEAN_UP_BY_JEFFERY_RICHTER
#pragma once // Include this header file once per compilation unit
#include <winsock2.h>
#include <windows.h>
// Data type representing the address of the object's cleanup function.
// I used UINT_PTR so that this class works properly in 64-bit Windows.
typedef VOID (WINAPI* PFNENSURECLEANUP)(UINT_PTR);
// Each template instantiation requires a data type, address of cleanup
// function, and a value that indicates an invalid value.
template<class TYPE, PFNENSURECLEANUP pfn, UINT_PTR tInvalid = NULL>
class CEnsureCleanup
{
public:
// Default constructor assumes an invalid value (nothing to cleanup)
CEnsureCleanup() { m_t = tInvalid; }
// This constructor sets the value to the specified value
CEnsureCleanup(TYPE t) : m_t((UINT_PTR) t) { }
// The destructor performs the cleanup.
~CEnsureCleanup() { Cleanup(); }
// Helper methods to tell if the value represents a valid object or not..
BOOL IsValid() { return(m_t != tInvalid); }
BOOL IsInvalid() { return(!IsValid()); }
// Re-assigning the object forces the current object to be cleaned-up.
TYPE operator=(TYPE t)
{
Cleanup();
m_t = (UINT_PTR) t;
return(*this);
}
// Returns the value (supports both 32-bit and 64-bit Windows).
operator TYPE()
{
// If TYPE is a 32-bit value, cast m_t to 32-bit TYPE
// If TYPE is a 64-bit value, case m_t to 64-bit TYPE
return((sizeof(TYPE) == 4) ? (TYPE) PtrToUint(m_t) : (TYPE) m_t);
}
// Cleanup the object if the value represents a valid object
void Cleanup()
{
if (IsValid())
{
// In 64-bit Windows, all parameters are 64-bits,
// so no casting is required
pfn(m_t); // Close the object.
m_t = tInvalid; // We no longer represent a valid object.
}
}
private:
UINT_PTR m_t; // The member representing the object
};
///////////////////////////////////////////////////////////////////////////////
// Macros to make it easier to declare instances of the template
// class for specific data types.
#define MakeCleanupClass(className, tData, pfnCleanup) \
typedef CEnsureCleanup<tData, (PFNENSURECLEANUP) pfnCleanup> className;
#define MakeCleanupClassX(className, tData, pfnCleanup, tInvalid) \
typedef CEnsureCleanup<tData, (PFNENSURECLEANUP) pfnCleanup, \
(INT_PTR) tInvalid> className;
///////////////////////////////////////////////////////////////////////////////
// Instances of the template C++ class for common data types.
MakeCleanupClass(CEnsureCloseHandle, HANDLE, CloseHandle);
MakeCleanupClassX(CEnsureCloseFile, HANDLE, CloseHandle, INVALID_HANDLE_VALUE);
MakeCleanupClass(CEnsureLocalFree, HLOCAL, LocalFree);
MakeCleanupClass(CEnsureGlobalFree, HGLOBAL, GlobalFree);
MakeCleanupClass(CEnsureRegCloseKey, HKEY, RegCloseKey);
MakeCleanupClass(CEnsureCloseServiceHandle, SC_HANDLE, CloseServiceHandle);
MakeCleanupClass(CEnsureCloseWindowStation, HWINSTA, CloseWindowStation);
MakeCleanupClass(CEnsureCloseDesktop, HDESK, CloseDesktop);
MakeCleanupClass(CEnsureUnmapViewOfFile, PVOID, UnmapViewOfFile);
MakeCleanupClass(CEnsureFreeLibrary, HMODULE, FreeLibrary);
///////////////////////////////////////////////////////////////////////////////
// Special class for releasing a reserved region.
// Special class is required because VirtualFree requires 3 parameters
class CEnsureReleaseRegion
{
public:
CEnsureReleaseRegion(PVOID pv = NULL) : m_pv(pv) { }
~CEnsureReleaseRegion() { Cleanup(); }
PVOID operator=(PVOID pv)
{
Cleanup();
m_pv = pv;
return(m_pv);
}
operator PVOID() { return(m_pv); }
void Cleanup()
{
if (m_pv != NULL)
{
VirtualFree(m_pv, 0, MEM_RELEASE);
m_pv = NULL;
}
}
private:
PVOID m_pv;
};
///////////////////////////////////////////////////////////////////////////////
// Special class for freeing a block from a heap
// Special class is required because HeapFree requires 3 parameters
class CEnsureHeapFree
{
public:
CEnsureHeapFree(PVOID pv = NULL, HANDLE hHeap = GetProcessHeap())
: m_pv(pv), m_hHeap(hHeap) { }
~CEnsureHeapFree() { Cleanup(); }
PVOID operator=(PVOID pv)
{
Cleanup();
m_pv = pv;
return(m_pv);
}
operator PVOID() { return(m_pv); }
void Cleanup()
{
if (m_pv != NULL)
{
HeapFree(m_hHeap, 0, m_pv);
m_pv = NULL;
}
}
private:
HANDLE m_hHeap;
PVOID m_pv;
};
template<typename T>
class CEnsureDelete
{
public:
CEnsureDelete(T* ptr) : m_ptr(ptr) { }
~CEnsureDelete() { if(NULL != m_ptr) { delete m_ptr; } }
private:
// <20><><EFBFBD><20><> <20><> <20><><EFBFBD><EFBFBD> <20><>.
CEnsureDelete& operator =(const CEnsureDelete& ensureDelete);
CEnsureDelete(const CEnsureDelete& ensureDelete);
T* m_ptr;
};
template<typename T>
class CEnsureDeleteArray
{
public:
CEnsureDeleteArray(T* ptrArray) : m_ptrArray(ptrArray) { }
~CEnsureDeleteArray() { if(NULL != m_ptrArray) { delete [] m_ptrArray; } }
private:
// <20><><EFBFBD><20><> <20><> <20><><EFBFBD><EFBFBD> <20><>.
CEnsureDeleteArray& operator =(const CEnsureDeleteArray& ensureDeleteArray);
CEnsureDeleteArray(const CEnsureDeleteArray& ensureDeleteArray);
T* m_ptrArray;
};
template<typename T>
class CEnsureRelease
{
public:
CEnsureRelease(T& t) : m_t(&t) { }
CEnsureRelease(T* t) : m_t(t) { }
~CEnsureRelease() { if(NULL != m_t) { m_t->Release(); } }
private:
// <20><><EFBFBD><20><> <20><> <20><><EFBFBD><EFBFBD> <20><>.
CEnsureRelease& operator =(const CEnsureRelease& ensureRelease);
CEnsureRelease(const CEnsureRelease& ensureRelease);
T* m_t;
};
#endif

View File

@@ -0,0 +1,264 @@
#include "stdafx.h"
#include "Pulse.h"
#include <mmsystem.h>
#include <BaseLibrary/Log/ServerLog.h>
CPulse& CPulse::GetInstance()
{
static CPulse Pulse;
return Pulse;
}
CPulse::CPulse()
: m_dwPulse(0),
m_dwLastTick(timeGetTime()),
m_dwHeavyTrafficCount(0),
m_bTPPOverTwoTime(FALSE),
m_nTicksPerPulse(0),
m_nTicksPerSec(0)
{
SetTicksPerPulse(DEFAULT_TICKS_PER_PULSE);
}
CPulse::~CPulse()
{
}
void CPulse::SetTicksPerPulse(long nTicksPerPulse)
{
if(nTicksPerPulse <= 0)
{
nTicksPerPulse = DEFAULT_TICKS_PER_PULSE;
}
m_nTicksPerPulse = nTicksPerPulse;
m_nTicksPerSec = 1000 / nTicksPerPulse;
}
unsigned long CPulse::GetRemainTime() const
{
long nElapsed = timeGetTime() - m_dwLastTick;
if (nElapsed < m_nTicksPerPulse)
{
return (m_nTicksPerPulse - nElapsed);
}
return 0;
}
unsigned long CPulse::CheckSleep()
{
long nElapsed = timeGetTime() - m_dwLastTick;
if (nElapsed < m_nTicksPerPulse)
{
// <20><EFBFBD>ð<EFBFBD><C3B0><EFBFBD> TPP<50><50><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> Sleep
unsigned long dwSleep = (m_nTicksPerPulse - nElapsed) - 1;
unsigned long dwTicksPerPulse = m_nTicksPerPulse;
if(m_nTicksPerPulse < 0)
{
dwTicksPerPulse = 0;
}
if(dwTicksPerPulse < dwSleep)
{
dwSleep = 0;
}
Sleep(dwSleep);
m_dwHeavyTrafficCount = 0;
m_bTPPOverTwoTime = FALSE;
}
else if(((++m_dwHeavyTrafficCount) > 5) || (nElapsed > (m_nTicksPerPulse * 2)))
{
// <20><20>ð<EFBFBD><C3B0><EFBFBD> TPP<50><50> <20>ι<CEB9><E8BAB8> ū <20><><EFBFBD><EFBFBD> <20>Ǵ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> Ʈ<><C6AE><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ʹ<EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
DETLOG3(g_Log, "Time Overflow : Elapsed time is %u, (TPP is %d), HeavyTrafficCount is %u"
, nElapsed, m_nTicksPerPulse, m_dwHeavyTrafficCount);
m_bTPPOverTwoTime = TRUE;
}
else
{
DETLOG1(g_Log, "Traffic is %u", m_dwHeavyTrafficCount);
m_bTPPOverTwoTime = FALSE;
}
m_dwLastTick = timeGetTime();
++m_dwPulse;
if(0 == m_dwPulse)
{
// <20><><EFBFBD><EFBFBD> <20>޽<EFBFBD><DEBD><EFBFBD> <20>ѹ<EFBFBD><D1B9><EFBFBD> <20><><EFBFBD>Ƽ<EFBFBD> <20>ٽ<EFBFBD> 0<><30><EFBFBD><EFBFBD> <20><><EFBFBD>ƿԴٸ<D4B4>,
// <20>ѹ<EFBFBD> <20><> <20><><EFBFBD>ؼ<EFBFBD> 0<><30> <20><> <20><> <20><><EFBFBD><EFBFBD> <20>Ѵ<EFBFBD>.
++m_dwPulse;
}
return m_dwPulse;
}
/*
#include "../stdafx.h"
#include "Pulse.h"
#define DEFAULT_TPP 100
CPulse g_Pulse;
// constructor and destructor
CPulse::CPulse() : m_dwPulse(0), m_dwExtraTick(GetTickCount()), m_dwLastTick(GetTickCount()), m_dwHeavyTrafficCount(0), m_TPPOverTwoTime(false)
//, m_SleepOperation(NULL)
{
SetTicksPerPulse(DEFAULT_TPP);
for (int i=0; i<PULSETABLE_NUM; ++i)
::ZeroMemory(&m_PulseTable[i], sizeof(PULSE_TIMER));
DETLOG1(g_Log, "this:0x%08x.", this);
}
CPulse::~CPulse()
{
DETLOG1(g_Log, "this:0x%08x.", this);
}
void CPulse::SetTicksPerPulse(unsigned long dwTicksPerPulse)
{
m_nTicksPerPulse = dwTicksPerPulse;
}
//void CPulse::SetSleepOperation(Operation pOperation)
//{
// m_SleepOperation = pOperation;
//}
unsigned long CPulse::CheckSleep(void)
{
m_dwExtraTick = GetTickCount();
unsigned long nElapsed = m_dwExtraTick - m_dwLastTick;
if (nElapsed <= m_nTicksPerPulse) {
// <20><EFBFBD>ð<EFBFBD><C3B0><EFBFBD> TPP<50><50><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> Sleep
if (nElapsed < m_nTicksPerPulse) {
//if (m_SleepOperation) {
// // <20><><EFBFBD><EFBFBD> <20><><EFBFBD>۷<EFBFBD><DBB7>̼<EFBFBD><CCBC><EFBFBD> <20><><EFBFBD><EFBFBD>
// m_SleepOperation();
// // <20><><EFBFBD>ν<EFBFBD><CEBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD>Ŀ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ð<EFBFBD><C3B0><EFBFBD> Ȯ<><C8AE><EFBFBD>ؼ<EFBFBD> TPP<50><50><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><ECBFA1> Sleep
// m_dwExtraTick = GetTickCount();
// nElapsed = m_dwExtraTick - m_dwLastTick;
// if (nElapsed < m_nTicksPerPulse) {
// Sleep((m_nTicksPerPulse - nElapsed) - 1);
// }
//} else {
Sleep((m_nTicksPerPulse - nElapsed) - 1);
//}
}
m_dwLastTick = GetTickCount();
m_dwHeavyTrafficCount = 0;
m_TPPOverTwoTime = false;
} else if(((++m_dwHeavyTrafficCount) > 5) || (nElapsed > (m_nTicksPerPulse * 2))) {
// <20><20>ð<EFBFBD><C3B0><EFBFBD> TPP<50><50> <20>ι<CEB9><E8BAB8> ū <20><><EFBFBD><EFBFBD> <20>Ǵ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> Ʈ<><C6AE><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ʹ<EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
DETLOG2(g_Log, "Time Overflow : <20><20>ð<EFBFBD><C3B0><EFBFBD> %d <20><> TPP <20><> <20>ι<CEB9><E8BAB8> ũ<>ų<EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> Ʈ<><C6AE><EFBFBD><EFBFBD><EFBFBD><EFBFBD> %d <20>Դϴ<D4B4>.", nElapsed, m_dwHeavyTrafficCount);
m_dwLastTick = GetTickCount();
m_TPPOverTwoTime = true;
} else {
DETLOG1(g_Log, "Ʈ<><C6AE><EFBFBD><EFBFBD><EFBFBD><EFBFBD> %d <20>Դϴ<D4B4>.", m_dwHeavyTrafficCount);
// m_nTicksPerPulse < nElapsed <= m_nTicksPerPulse * 2
m_dwLastTick = GetTickCount() - (nElapsed - m_nTicksPerPulse);
m_TPPOverTwoTime = false;
}
return ++m_dwPulse;
}
bool CPulse::InstallTimer(int nOperation, unsigned long dwPulse, Operation pOperation)
{
if (nOperation <= 0 || nOperation >= PULSETABLE_NUM) {
return false;
}
for (int i=0; i < PULSETABLE_NUM; ++i) {
if (0 == m_PulseTable[i].m_nOperation) {
m_PulseTable[i].m_nOperation = nOperation;
m_PulseTable[i].m_dwPulse = dwPulse;
m_PulseTable[i].m_pOperation = pOperation;
return true;
}
}
// TODO : <20><><EFBFBD><EFBFBD><EFBFBD>α<EFBFBD>
return false;
}
bool CPulse::UninstallTimer(int nOperation)
{
if(nOperation <= 0 || nOperation >= PULSETABLE_NUM)
{
return false;
}
for (int i=0; i<PULSETABLE_NUM; ++i) {
if (nOperation == m_PulseTable[i].m_nOperation) {
m_PulseTable[i].m_nOperation = 0;
m_PulseTable[i].m_dwPulse = 0;
m_PulseTable[i].m_pOperation = NULL;
// TODO : <20><><EFBFBD>̺<EFBFBD><CCBA><EFBFBD> shift up
ShiftupTable(i + 1);
return true;
}
}
// TODO : <20><><EFBFBD><EFBFBD><EFBFBD>α<EFBFBD>
return false;
}
void CPulse::Operate(void)
{
int i = 0;
while (m_PulseTable[i].m_nOperation) {
if (0 == (GetCurrentPulse() % m_PulseTable[i].m_dwPulse)) {
if (m_PulseTable[i].m_nOperation) {
m_PulseTable[i].m_pOperation();
}
}
++i;
}
}
void CPulse::ShiftupTable(int nStartIndex)
{
for (int i=nStartIndex; i<(PULSETABLE_NUM - 1); ++i) {
// TODO : <20><><EFBFBD>̺<EFBFBD><CCBA><EFBFBD> shift up
m_PulseTable[i].m_nOperation = m_PulseTable[i+1].m_nOperation;
m_PulseTable[i].m_dwPulse = m_PulseTable[i+1].m_dwPulse;
m_PulseTable[i].m_pOperation = m_PulseTable[i+1].m_pOperation;
}
m_PulseTable[PULSETABLE_NUM].m_nOperation = 0;
m_PulseTable[PULSETABLE_NUM].m_dwPulse = 0;
m_PulseTable[PULSETABLE_NUM].m_pOperation = NULL;
}
*/

View File

@@ -0,0 +1,53 @@
#ifndef _RYL_BASE_LIBRARY_PULSE_H_
#define _RYL_BASE_LIBRARY_PULSE_H_
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "winmm.lib")
// Single Thread<61><64><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.
class CPulse
{
public:
enum PulseConst
{
DEFAULT_TICKS_PER_PULSE = 100
};
static CPulse& GetInstance();
unsigned long CheckSleep();
void SetTicksPerPulse(long nTicksPerPulse);
long GetTicksPerPulse() const { return m_nTicksPerPulse; }
long GetTicksPerSec() const { return m_nTicksPerSec; }
unsigned long GetRemainTime() const;
BOOL GetTPPOverTwoTime() const { return m_bTPPOverTwoTime; }
unsigned long GetCurrentPulse() const { return m_dwPulse; }
unsigned long GetLastTick() const { return m_dwLastTick; }
inline bool ProcessBySecond(unsigned long dwCycleSec) const { return (0 == (m_dwPulse % (dwCycleSec * m_nTicksPerSec))); }
inline bool ProcessByMinute(unsigned long dwCycleMin) const { return ProcessBySecond(dwCycleMin * 60); }
inline bool ProcessByHour(unsigned long dwCycleHour) const { return ProcessBySecond(dwCycleHour * 3600); }
private:
CPulse();
~CPulse();
unsigned long m_dwPulse;
unsigned long m_dwLastTick;
unsigned long m_dwHeavyTrafficCount;
long m_nTicksPerPulse;
long m_nTicksPerSec;
BOOL m_bTPPOverTwoTime;
};
#endif

View File

@@ -0,0 +1,23 @@
#ifndef _COMMON_H_
#define _COMMON_H_
#ifndef _QWORD_DEFINED
#define _QWORD_DEFINED
typedef __int64 QWORD, *LPQWORD;
#endif
#define MAKEQWORD(a, b) \
((QWORD)( ((QWORD) ((unsigned long) (a))) << 32 | ((unsigned long) (b))))
#define LODWORD(l) \
((unsigned long)(l))
#define HIDWORD(l) \
((unsigned long)(((QWORD)(l) >> 32) & 0xFFFFFFFF))
// Read 4K of data at a time (used in the C++ streams, Win32 I/O, and assembly functions)
#define MAX_BUFFER_SIZE 4096
// Map a "view" size of 10MB (used in the filemap function)
#define MAX_VIEW_SIZE 10485760
#endif

View File

@@ -0,0 +1,371 @@
#include "stdafx.h"
#include <crtdbg.h>
#include "Common.h"
#include "Crc32Static.h"
using namespace std;
// Static CRC table
unsigned long CCrc32Static::s_arrdwCrc32Table[256] =
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
};
//***********************************************
CCrc32Static::CCrc32Static()
{
}
//***********************************************
CCrc32Static::~CCrc32Static()
{
}
//***********************************************
inline void CCrc32Static::CalcCrc32(const BYTE byte, unsigned long &dwCrc32)
{
dwCrc32 = ((dwCrc32) >> 8) ^ s_arrdwCrc32Table[(byte) ^ ((dwCrc32) & 0x000000FF)];
}
//***********************************************
bool CCrc32Static::GetFileSizeQW(const HANDLE hFile, QWORD &qwSize)
{
_ASSERTE(hFile != INVALID_HANDLE_VALUE);
bool bSuccess = true;
try
{
unsigned long dwLo = 0, dwHi = 0;
dwLo = GetFileSize(hFile, &dwHi);
if(dwLo == INVALID_FILE_SIZE && GetLastError() != NO_ERROR)
{
bSuccess = false;
qwSize = 0;
}
else
{
qwSize = MAKEQWORD(dwHi, dwLo);
}
}
catch (...)
{
bSuccess = false;
}
return bSuccess;
}
//***********************************************
unsigned long CCrc32Static::StringCrc32(LPCTSTR szString, unsigned long &dwCrc32)
{
_ASSERTE(szString);
unsigned long dwErrorCode = NO_ERROR;
dwCrc32 = 0xFFFFFFFF;
try
{
while (*szString != _T('\0'))
{
CalcCrc32((BYTE)*szString, dwCrc32);
szString++;
}
}
catch (...)
{
// An unknown exception happened
dwErrorCode = ERROR_CRC;
}
dwCrc32 = ~dwCrc32;
return dwErrorCode;
}
//***********************************************
unsigned long CCrc32Static::BufferCrc32(const char *szBuffer, size_t size, unsigned long &dwCrc32)
{
_ASSERTE(szBuffer);
unsigned long dwErrorCode = NO_ERROR;
dwCrc32 = 0xFFFFFFFF;
try
{
for (size_t nIndex = 0; nIndex < size; ++nIndex)
{
CalcCrc32((BYTE)*szBuffer, dwCrc32);
++szBuffer;
}
}
catch (...)
{
// An unknown exception happened
dwErrorCode = ERROR_CRC;
}
dwCrc32 = ~dwCrc32;
return dwErrorCode;
}
//***********************************************
unsigned long CCrc32Static::FileCrc32Filemap(LPCTSTR szFilename, unsigned long &dwCrc32)
{
_ASSERTE(szFilename);
_ASSERTE(lstrlen(szFilename));
unsigned long dwErrorCode = NO_ERROR;
HANDLE hFile = NULL, hFilemap = NULL;
dwCrc32 = 0xFFFFFFFF;
try
{
// Open the file
hFile = CreateFile(szFilename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if(hFile == INVALID_HANDLE_VALUE)
dwErrorCode = GetLastError();
else
{
QWORD qwFileSize = 0, qwFileOffset = 0;
unsigned long dwByteCount, dwViewSize;
unsigned long dwBaseAddress;
// Get the file size
if(!GetFileSizeQW(hFile, qwFileSize))
dwErrorCode = ERROR_BAD_LENGTH;
else if(qwFileSize != 0) // We cannot CRC zero byte files
{
// Create the file mapping
hFilemap = CreateFileMapping(hFile,
NULL,
PAGE_READONLY,
0,
0,
NULL);
if(hFilemap == NULL)
dwErrorCode = GetLastError();
else
{
LPBYTE pByte;
// Loop while we map a section of the file and CRC it
while (qwFileSize > 0)
{
if(qwFileSize < MAX_VIEW_SIZE)
dwViewSize = LODWORD(qwFileSize);
else
dwViewSize = MAX_VIEW_SIZE;
dwBaseAddress = (unsigned long)MapViewOfFile(hFilemap,
FILE_MAP_READ,
HIDWORD(qwFileOffset),
LODWORD(qwFileOffset),
dwViewSize);
dwByteCount = dwViewSize;
pByte = (LPBYTE)dwBaseAddress;
while (dwByteCount-- > 0)
{
CalcCrc32(*pByte, dwCrc32);
pByte++;
}
UnmapViewOfFile((LPVOID)dwBaseAddress);
qwFileOffset += dwViewSize;
qwFileSize -= dwViewSize;
}
}
}
}
}
catch (...)
{
// An unknown exception happened
dwErrorCode = ERROR_CRC;
}
if(hFile != NULL) CloseHandle(hFile);
if(hFilemap != NULL) CloseHandle(hFilemap);
dwCrc32 = ~dwCrc32;
return dwErrorCode;
}
//***********************************************
unsigned long CCrc32Static::FileCrc32Assembly(LPCTSTR szFilename, unsigned long &dwCrc32)
{
_ASSERTE(szFilename);
_ASSERTE(lstrlen(szFilename));
unsigned long dwErrorCode = NO_ERROR;
HANDLE hFile = NULL;
dwCrc32 = 0xFFFFFFFF;
try
{
// Open the file
hFile = CreateFile(szFilename,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_ARCHIVE | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_SEQUENTIAL_SCAN,
NULL);
if(hFile == INVALID_HANDLE_VALUE)
dwErrorCode = GetLastError();
else
{
// There is a bug in the Microsoft compilers where inline assembly
// code cannot access static member variables. This is a work around
// for that bug. For more info see Knowledgebase article Q88092
LPVOID ptrCrc32Table = &s_arrdwCrc32Table;
BYTE buffer[MAX_BUFFER_SIZE];
unsigned long dwBytesRead;
BOOL bSuccess = ReadFile(hFile, buffer, sizeof(buffer), &dwBytesRead, NULL);
while (bSuccess && dwBytesRead)
{
// Register use:
// eax - CRC32 value
// ebx - a lot of things
// ecx - CRC32 value
// edx - address of end of buffer
// esi - address of start of buffer
// edi - CRC32 table
__asm
{
// Save the esi and edi registers
push esi
push edi
mov eax, dwCrc32 // Load the pointer to dwCrc32
mov ecx, [eax] // Dereference the pointer to load dwCrc32
mov edi, ptrCrc32Table // Load the CRC32 table
lea esi, buffer // Load buffer
mov ebx, dwBytesRead // Load dwBytesRead
lea edx, [esi + ebx] // Calculate the end of the buffer
crc32loop:
xor eax, eax // Clear the eax register
mov bl, byte ptr [esi] // Load the current source byte
mov al, cl // Copy crc value into eax
inc esi // Advance the source pointer
xor al, bl // Create the index into the CRC32 table
shr ecx, 8
mov ebx, [edi + eax * 4] // Get the value out of the table
xor ecx, ebx // xor with the current byte
cmp edx, esi // Have we reached the end of the buffer?
jne crc32loop
// Restore the edi and esi registers
pop edi
pop esi
mov eax, dwCrc32 // Load the pointer to dwCrc32
mov [eax], ecx // Write the result
}
bSuccess = ReadFile(hFile, buffer, sizeof(buffer), &dwBytesRead, NULL);
}
}
}
catch (...)
{
// An unknown exception happened
dwErrorCode = ERROR_CRC;
}
if(hFile != NULL) CloseHandle(hFile);
dwCrc32 = ~dwCrc32;
return dwErrorCode;
}

View File

@@ -0,0 +1,27 @@
#ifndef _CRC32STATIC_H_
#define _CRC32STATIC_H_
#include <windows.h>
class CCrc32Static
{
public:
CCrc32Static();
virtual ~CCrc32Static();
static unsigned long StringCrc32(const char *szString, unsigned long &dwCrc32);
static unsigned long BufferCrc32(const char *szBuffer, size_t size, unsigned long &dwCrc32);
static unsigned long FileCrc32Win32(const char *szFilename, unsigned long &dwCrc32);
static unsigned long FileCrc32Filemap(const char *szFilename, unsigned long &dwCrc32);
static unsigned long FileCrc32Assembly(const char *szFilename, unsigned long &dwCrc32);
protected:
static bool GetFileSizeQW(const HANDLE hFile, __int64 &qwSize);
static inline void CalcCrc32(const unsigned char byte, unsigned long &dwCrc32);
static unsigned long s_arrdwCrc32Table[256];
};
#endif

View File

@@ -0,0 +1,72 @@
#include "stdafx.h"
#include "Crc8Static.h"
unsigned char CCrc8Static::s_arrcCrc8Table[] = {
0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83,
0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41,
0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e,
0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc,
0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0,
0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62,
0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d,
0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff,
0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5,
0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07,
0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58,
0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a,
0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6,
0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24,
0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b,
0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9,
0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f,
0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd,
0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92,
0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50,
0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c,
0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee,
0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1,
0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73,
0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49,
0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b,
0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4,
0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16,
0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a,
0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8,
0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7,
0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35,
};
/********************************************************************\
Routine: crc8
Purpose: Calculate 8-bit cyclic redundancy checksum for a full
buffer
Input:
unsigned char *data data buffer
int len data length in bytes
Function value:
unsighend char CRC-8 code
\********************************************************************/
unsigned char CCrc8Static::BufferCrc8(const char *szBuffer, size_t size)
{
const char* szBufferPos = szBuffer;
const char* szBufferEnd = szBuffer + size;
unsigned char crc8_code = 0;
unsigned char nIndex = 0;
for (; szBufferPos != szBufferEnd; ++szBufferPos)
{
nIndex = (*szBufferPos) ^ crc8_code;
crc8_code = s_arrcCrc8Table[nIndex];
}
return crc8_code;
}

View File

@@ -0,0 +1,18 @@
#ifndef _CRC8STATIC_H_
#define _CRC8STATIC_H_
#include "Common.h"
class CCrc8Static
{
public:
static unsigned char StringCrc8(const char *szString) { return BufferCrc8(szString, strlen(szString)); }
static unsigned char BufferCrc8(const char *szBuffer, size_t size);
protected:
static unsigned char s_arrcCrc8Table[256];
};
#endif