diff --git a/Resources/NetHook/DataDumper.cpp b/Resources/NetHook/DataDumper.cpp deleted file mode 100644 index f9e91a7a..00000000 --- a/Resources/NetHook/DataDumper.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "DataDumper.h" -#include "logger.h" -#include "utils.h" - -#include "zip.h" -#include "bitbuf.h" - -#include "steam/clientmsgs.h" -#include "steammessages_base.pb.h" - -CDataDumper::CDataDumper() : - m_uiMsgNum(0) -{ - time_t tCurrentTime; - time(&tCurrentTime); - - sprintf_s(m_szSessionDir, sizeof( m_szSessionDir ), "%d\\", tCurrentTime); - - g_Logger->CreateDir(m_szSessionDir); -} - -void CDataDumper::DataEncrypted(const uint8* pubPlaintextData, uint32 cubPlaintextData) -{ - this->HandleNetMsg(k_eNetOutgoing, (EMsg) *(short *) pubPlaintextData, pubPlaintextData, cubPlaintextData); -} - -void CDataDumper::DataDecrypted(const uint8* pubPlaintextData, uint32 cubPlaintextData) -{ - this->HandleNetMsg(k_eNetIncoming, (EMsg) *(short *) pubPlaintextData, pubPlaintextData, cubPlaintextData); -} - -bool CDataDumper::HandleNetMsg( ENetDirection eDirection, EMsg eMsg, const uint8 *pData, uint32 cubData ) -{ - eMsg = (EMsg)((int)eMsg & (~0x80000000)); - - if ( eMsg == k_EMsgMulti ) - return this->MultiplexMsgMulti(eDirection, pData, cubData); - - const char* szFile = this->GetFileName(eDirection, eMsg); - g_Logger->LogFileData(szFile, pData, cubData); - - g_Logger->LogConsole("Wrote %d bytes to %s\n", cubData, szFile); - - return true; -} - -const char* CDataDumper::GetFileName(ENetDirection eDirection, EMsg eMsg) -{ - static char szFileName[MAX_PATH]; - - sprintf_s(szFileName, sizeof( szFileName ), "%s%d_%s_%d_%s.bin", m_szSessionDir, - ++m_uiMsgNum, (eDirection == k_eNetIncoming ? "in" : "out"), eMsg, - g_Crypto->GetMessage(eMsg)); - - return szFileName; -} - -const char* CDataDumper::GetFileName( const char* file ) -{ - static char szFileName[MAX_PATH]; - - sprintf_s(szFileName, sizeof( szFileName ), "%s%s", m_szSessionDir, - file); - - return szFileName; -} - -bool CDataDumper::MultiplexMsgMulti( ENetDirection eDirection, const uint8 *pData, uint32 cubData ) -{ - struct ProtoHdr - { - EMsg msg; - int headerLength; - }; - - - ProtoHdr *pProtoHdr = (ProtoHdr*) pData; - - g_Logger->LogConsole("Multi: msg %d length %d\n", (pProtoHdr->msg & (~0x80000000)), pProtoHdr->headerLength ); - - CMsgProtoBufHeader protoheader; - protoheader.ParseFromArray( pData + 8, pProtoHdr->headerLength ); - - g_Logger->LogConsole("MultiProto\n"); - - CMsgMulti multi; - multi.ParseFromArray( pData + 8 + pProtoHdr->headerLength, cubData - 8 - pProtoHdr->headerLength ); - - g_Logger->LogConsole("MultiMsg: %d %d\n", multi.size_unzipped(), multi.message_body().length() ); - - uint8 *pMsgData = NULL; - uint32 cubMsgData = 0; - bool bDecomp = false; - - if ( multi.has_size_unzipped() && multi.size_unzipped() != 0 ) - { - // decompress our data - - uint8 *pDecompressed = new uint8[ multi.size_unzipped() ]; - uint8 *pCompressed = (uint8 *)( multi.message_body().c_str() ); - uint32 cubCompressed = multi.message_body().length(); - - g_Logger->LogConsole("decomp: %x comp: %x cubcomp: %d unzipped: %d\n", pDecompressed, pCompressed, cubCompressed, multi.size_unzipped()); - - bool bZip = CZip::Inflate( pCompressed, cubCompressed, pDecompressed, multi.size_unzipped() ); - - if ( !bZip ) - { - delete [] pDecompressed; - - g_Logger->LogConsole("Unable to decompress buffer\n"); - - return true; - } - - pMsgData = pDecompressed; - cubMsgData = multi.size_unzipped(); - bDecomp = bZip; - } - else - { - pMsgData = (uint8 *)( multi.message_body().c_str() ); - cubMsgData = multi.message_body().length(); - } - - bf_read reader( pMsgData, cubMsgData ); - - while ( reader.GetNumBytesLeft() > 0 ) - { - uint32 cubPayload = (uint32)reader.ReadLong(); - int off = reader.GetNumBitsRead() >> 3; - - uint8 *pPayload = (uint8 *)( pMsgData + off ); - EMsg *pEMsg = (EMsg *)pPayload; - - reader.SeekRelative( cubPayload << 3 ); - - this->HandleNetMsg( eDirection, *pEMsg, pPayload, cubPayload ); - } - - if ( bDecomp ) - delete [] pMsgData; - - return true; -} \ No newline at end of file diff --git a/Resources/NetHook/DataDumper.h b/Resources/NetHook/DataDumper.h deleted file mode 100644 index 85dace47..00000000 --- a/Resources/NetHook/DataDumper.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef DATADUMPER_H_ -#define DATADUMPER_H_ -#ifdef _WIN32 -#pragma once -#endif - -#include "time.h" - -#include "crypto.h" -#include "steam/emsg.h" - -enum ENetDirection -{ - k_eNetIncoming, - k_eNetOutgoing, -}; - -class CDataDumper : public ICryptoCallback -{ -public: - CDataDumper(); - - void DataEncrypted(const uint8* pubPlaintextData, uint32 cubPlaintextData); - void DataDecrypted(const uint8* pubPlaintextData, uint32 cubPlaintextData); - - const char* GetFileName( const char* file ); - -private: - bool HandleNetMsg( ENetDirection eDirection, EMsg eMsg, const uint8 *pData, uint32 cubData ); - bool MultiplexMsgMulti( ENetDirection eDirection, const uint8 *pData, uint32 cubData ); - - const char* GetFileName( ENetDirection eDirection, EMsg eMsg ); - - char m_szSessionDir[MAX_PATH]; - uint32 m_uiMsgNum; -}; - -extern CDataDumper* g_Dumper; - -#endif // !DATADUMPER_H_ \ No newline at end of file diff --git a/Resources/NetHook/NetHook.sln b/Resources/NetHook/NetHook.sln deleted file mode 100644 index 33b2d704..00000000 --- a/Resources/NetHook/NetHook.sln +++ /dev/null @@ -1,20 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual Studio 2010 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NetHook", "NetHook.vcxproj", "{04A24EE0-87D6-4CFB-BE63-7A9BC777B1A8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - Release|Win32 = Release|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {04A24EE0-87D6-4CFB-BE63-7A9BC777B1A8}.Debug|Win32.ActiveCfg = Debug|Win32 - {04A24EE0-87D6-4CFB-BE63-7A9BC777B1A8}.Debug|Win32.Build.0 = Debug|Win32 - {04A24EE0-87D6-4CFB-BE63-7A9BC777B1A8}.Release|Win32.ActiveCfg = Release|Win32 - {04A24EE0-87D6-4CFB-BE63-7A9BC777B1A8}.Release|Win32.Build.0 = Release|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/Resources/NetHook/NetHook.vcproj b/Resources/NetHook/NetHook.vcproj deleted file mode 100644 index 7dcccd99..00000000 --- a/Resources/NetHook/NetHook.vcproj +++ /dev/null @@ -1,863 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Resources/NetHook/NetHook.vcxproj b/Resources/NetHook/NetHook.vcxproj deleted file mode 100644 index af6d9c06..00000000 --- a/Resources/NetHook/NetHook.vcxproj +++ /dev/null @@ -1,268 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {04A24EE0-87D6-4CFB-BE63-7A9BC777B1A8} - NetHook - Win32Proj - - - - DynamicLibrary - NotSet - true - - - DynamicLibrary - NotSet - - - - - - - - - - - - - <_ProjectFileVersion>10.0.30319.1 - $(SolutionDir)$(Configuration)\ - $(Configuration)\ - true - $(SolutionDir)$(Configuration)\ - $(Configuration)\ - false - AllRules.ruleset - - - AllRules.ruleset - - - - - - Disabled - tier0;tier1;public;.;G:\dev\C++\Open Steamworks\Open Steamworks;C:\Users\ryan\Documents\development\Open Steamworks\Open Steamworks;%(AdditionalIncludeDirectories) - WIN32;_WIN32;_DEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) - true - EnableFastChecks - MultiThreadedDebugDLL - - - Level3 - EditAndContinue - - - Ws2_32.lib;steam.lib;%(AdditionalDependencies) - G:\dev\C++\Open Steamworks;C:\Users\ryan\Documents\development\Open Steamworks;%(AdditionalLibraryDirectories) - %(IgnoreSpecificDefaultLibraries) - true - Console - MachineX86 - - - - - MaxSpeed - true - tier0;tier1;public;.;C:\opensteamworks\Open Steamworks;%(AdditionalIncludeDirectories) - WIN32;_WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) - MultiThreadedDLL - true - - - Level3 - ProgramDatabase - - - Ws2_32.lib;%(AdditionalDependencies) - true - Windows - true - true - MachineX86 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Resources/NetHook/NetHook.vcxproj.filters b/Resources/NetHook/NetHook.vcxproj.filters deleted file mode 100644 index 9336e021..00000000 --- a/Resources/NetHook/NetHook.vcxproj.filters +++ /dev/null @@ -1,526 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93ff0feb-41ba-4a2c-9515-743871565253} - - - {ed4f167c-f6fc-4a3f-b5c7-5c0d4571646f} - - - {fa004520-6c3d-4c8b-9247-46be82bbb9f6} - - - {7674315e-74a1-451d-a9f1-1a33fb9f8a3a} - - - {cefb79e7-d12e-4d17-ab50-23b2365add3d} - - - {b948904a-73d7-445e-bfa7-146fcdf8dffa} - - - {f03368a7-6e2f-45f0-aabc-6aa1fcdee7f9} - - - {9b6b88a4-c98c-4a87-b335-1fc72128660a} - - - {ce62386e-1161-49e4-9f21-f912acbb45e2} - - - {f9881518-2823-4cab-ae08-0a00f32a3207} - - - {66a163d1-a739-4f18-8b60-d2b5790462c3} - - - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - Source Files - - - tier1\Source - - - tier1\Source - - - tier1\Source - - - tier1\Source - - - tier1\Source - - - Helpers - - - Helpers - - - Helpers - - - Source Files - - - - - Headers - - - Headers - - - Headers - - - Headers - - - Headers - - - Headers - - - Steam Headers - - - Steam Headers - - - Steam Headers - - - Steam Headers - - - Steam Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier1\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - tier0\Headers - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - mathlib - - - Helpers - - - Helpers - - - Helpers - - - Helpers - - - public - - - public - - - public - - - zlib - - - zlib - - - Headers - - - - - - - - - \ No newline at end of file diff --git a/Resources/NetHook/clientapp.cpp b/Resources/NetHook/clientapp.cpp deleted file mode 100644 index ca7ad35f..00000000 --- a/Resources/NetHook/clientapp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include - -#include "clientapp.h" - -#include "utils.h" -#include "logger.h" -#include "crypto.h" -#include "DataDumper.h" - -#include "interface.h" - -#define STEAMTYPES_H -#include "usercommon.h" -#include "ESteamError.h" -#include "isteamclient009.h" -#include "isteamgameserver010.h" -#include "steammessages_base.pb.h" - -CDataDumper* g_Dumper; - -BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) -{ - if ( fdwReason == DLL_PROCESS_ATTACH ) - { - GOOGLE_PROTOBUF_VERIFY_VERSION; - - AllocConsole(); - LoadLibrary("steamclient.dll"); - - g_Logger = new CLogger(".\\"); - g_Dumper = new CDataDumper(); - g_Crypto = new CCrypto(g_Dumper); - } - else if ( fdwReason == DLL_PROCESS_DETACH ) - { - delete g_Crypto; - delete g_Dumper; - delete g_Logger; - } - - return TRUE; -} diff --git a/Resources/NetHook/clientapp.h b/Resources/NetHook/clientapp.h deleted file mode 100644 index ef929a52..00000000 --- a/Resources/NetHook/clientapp.h +++ /dev/null @@ -1,31 +0,0 @@ - -#ifndef CLIENTAPP_H_ -#define CLIENTAPP_H_ -#ifdef _WIN32 -#pragma once -#endif - - -#define STEAM_API_EXPORTS - -#include "steam/steamtypes.h" - -typedef int ( STEAM_CALL *SteamExeFrameFn )( int, int ); -typedef int ( STEAM_CALL *SteamDllMainFn )( int , char ** ); - - -#define CLIENTAPP( entry ) \ - SteamExeFrameFn g_SteamExeFrame = NULL; \ - int entry( int argc, char **argv ); \ - S_API int STEAM_CALL SteamDllMain( int argc, char **argv ) \ - { \ - return entry( argc, argv ); \ - } \ - S_API int STEAM_CALL SteamDllMainEx( int argc, char **argv, SteamExeFrameFn frameFn ) \ - { \ - g_SteamExeFrame = frameFn; \ - return entry( argc, argv ); \ - } - - -#endif // !CLIENTAPP_H_ diff --git a/Resources/NetHook/crypto.cpp b/Resources/NetHook/crypto.cpp deleted file mode 100644 index c6cf40e3..00000000 --- a/Resources/NetHook/crypto.cpp +++ /dev/null @@ -1,173 +0,0 @@ -#include "crypto.h" - -#include "DataDumper.h" -#include "logger.h" -#include "utils.h" - -#include "csimplescan.h" -#include "csimpledetour.h" - -#include "steam/steamtypes.h" - -#include "tier0/dbg.h" -#undef GetMessage - -CCrypto* g_Crypto = NULL; - -bool (__cdecl *Encrypt_Orig)(const uint8*, uint32, uint8*, uint32*, uint32); -bool (__cdecl *Decrypt_Orig)(const uint8*, uint32, uint8*, uint32*, const uint8*, uint32); -bool (__cdecl *GetMessageFn)( int * ); - -CCrypto::CCrypto(ICryptoCallback* callback) : - m_Callback(callback) -{ - CSimpleScan steamClientScan( "steamclient.dll" ); - - bool bRet = steamClientScan.FindFunction( - "\x55\x8B\xEC\x6A\xFF\x68\x01\x47\x32\x38\x64\xA1\x00\x00\x00\x00\x50\x64\x89\x25\x00\x00\x00\x00\x81\xEC\x04\x09\x00\x00", - "xxxxxx????xxxxxxxxxxxxxxxxxxxx", - (void **)& Encrypt_Orig - ); - - g_Logger->LogConsole( "CCrypto::SymmetricEncrypt = 0x%x \n", Encrypt_Orig ); - - - bRet = steamClientScan.FindFunction( - "\x55\x8B\xEC\x6A\xFF\x68\x21\x74\x28\x38\x64\xA1\x00\x00\x00\x00\x50\x64\x89\x25\x00\x00\x00\x00\x81\xEC\xE8\x04\x00\x00", - "xxxxxx????xxxxxxxxxxxxxxxxxxx", - (void **)& Decrypt_Orig - ); - - g_Logger->LogConsole( "CCrypto::SymmetricDecrypt = 0x%x\n", Decrypt_Orig ); - - /* - "51 A1 FC 24 33 38 | 8B 08 85 C9 75 05 89 0C 24 EB 28 E8 DA 09 E7 FF 8D 14 24 52 6A 04 6A 00 68 BC" - "\x51\xA1\xFF\xFF\xFF\xFF\x8B\x08\x85\xC9\x75\x05\x89\x0C\x24\xEB\x28\xE8" - "xx????" - - "\x51\xA1\x00\x95\x32\x38\x8B\x08\x85\xC9\x75\x05\x89\x0C\x24\xEB\x28\xE8\xA1\xBF\xE5\xFF\x8D\x14\x24\x52" - "\x6A\x04\x6A\x00\x68\x9C\x35\x36\x38\x6A\x00\x68\xF8\xEF\x38\x38\x8B\xC8\x89\x44\x24\x18", - "xx????xxxxx?xxxx?x????xxxx" - "xxxxxxxxxxxxxxxxxxxxxx", - */ - - bRet = steamClientScan.FindFunction( - "\x51\xA1\x00\x95\x32\x38\x8B\x08\x85\xC9\x75\x05\x89\x0C\x24\xEB\x28\xE8", - "xx????xxxxxxxxxxxx", - (void **) &GetMessageFn - ); - - g_Logger->LogConsole( "CMessageList::GetMessage = 0x%x\n", GetMessageFn ); - - for ( int x = 0; x < 7003; ++x ) - { - //g_Logger->AppendFile( g_Dumper->GetFileName( "emsg_list.txt" ), "\t%s = %d,\r\n", this->GetMessage( (EMsg)x ), x ); - } - - - static bool (__cdecl *encrypt)(const uint8*, uint32, uint8*, uint32*, uint32) = &CCrypto::SymmetricEncrypt; - static bool (__cdecl *decrypt)(const uint8*, uint32, uint8*, uint32*, const uint8*, uint32) = &CCrypto::SymmetricDecrypt; - - Encrypt_Detour = new CSimpleDetour((void **) &Encrypt_Orig, *(void**) &encrypt); - Decrypt_Detour = new CSimpleDetour((void **) &Decrypt_Orig, *(void**) &decrypt); - - Encrypt_Detour->Attach(); - Decrypt_Detour->Attach(); -} - -CCrypto::~CCrypto() -{ - Encrypt_Detour->Detach(); - Decrypt_Detour->Detach(); - - delete Encrypt_Detour; - delete Decrypt_Detour; -} - -// This call got strangely optimized. Don't clobber ECX. -__declspec(naked) bool __cdecl CCrypto::SymmetricEncrypt( const uint8 *pubPlaintextData, uint32 cubPlaintextData, uint8 *pubEncryptedData, uint32 *pcubEncryptedData, uint32 cubKey ) -{ - __asm { - // prologue - push ebp; - mov ebp, esp; - sub esp, __LOCAL_SIZE; - - // this needs to be saved (aes key) - push ecx; - } - - if ( g_Crypto ) - g_Crypto->m_Callback->DataEncrypted(pubPlaintextData, cubPlaintextData); - - __asm { - // call it manually here, prevent - // it from 'helpfully' using ECX - - // prep aes key in register - pop ecx; - - // push args - push cubKey; - push pcubEncryptedData; - push pubEncryptedData; - push cubPlaintextData; - push pubPlaintextData; - - // call! - call Encrypt_Orig; - - // cleanup - add esp, 0x14; - - // epilogue - mov esp, ebp; - pop ebp; - ret; - } -} - -// This function is considerably less retarded -bool __cdecl CCrypto::SymmetricDecrypt( const uint8 *pubEncryptedData, uint32 cubEncryptedData, uint8 *pubPlaintextData, uint32 *pcubPlaintextData, const uint8 *pubKey, uint32 cubKey ) -{ - bool ret = (*Decrypt_Orig)(pubEncryptedData, cubEncryptedData, pubPlaintextData, pcubPlaintextData, pubKey, cubKey); - - if ( g_Crypto ) - g_Crypto->m_Callback->DataDecrypted(pubPlaintextData, *pcubPlaintextData); - - return ret; -} - -const char* CCrypto::GetMessage( EMsg eMsg ) -{ - static char *szMsg = new char[ 200 ]; - - int ieMsg = (int)eMsg; - - bool bRet = false; - - __asm - { - pushad - - lea esi, [ szMsg ] - mov ecx, 200 - mov edi, ieMsg - - push 0xFF - - call GetMessageFn - mov bRet, al - - popad - } - - if ( bRet ) - { - return szMsg; - } - else - { - return "INVALID"; - } -} \ No newline at end of file diff --git a/Resources/NetHook/crypto.h b/Resources/NetHook/crypto.h deleted file mode 100644 index 4e879c16..00000000 --- a/Resources/NetHook/crypto.h +++ /dev/null @@ -1,43 +0,0 @@ - -#ifndef CRYPTO_H_ -#define CRYPTO_H_ -#ifdef _WIN32 -#pragma once -#endif - -#define _WINSOCKAPI_ // god damn winsock headers - -#include "logger.h" -#include "csimpledetour.h" -#include "steam/steamtypes.h" -#include "steam/emsg.h" -#undef GetMessage - -class ICryptoCallback -{ -public: - virtual void DataEncrypted(const uint8* pubPlaintextData, uint32 cubPlaintextData) = 0; - virtual void DataDecrypted(const uint8* pubPlaintextData, uint32 cubPlaintextData) = 0; -}; - -class CCrypto -{ -public: - CCrypto(ICryptoCallback* callback); - ~CCrypto(); - - const char* GetMessage( EMsg eMsg ); - -private: - ICryptoCallback* m_Callback; - - CSimpleDetour* Encrypt_Detour; - CSimpleDetour* Decrypt_Detour; - - static bool __cdecl SymmetricEncrypt( const uint8 *pubPlaintextData, uint32 cubPlaintextData, uint8 *pubEncryptedData, uint32 *pcubEncryptedData, uint32 cubKey ); - static bool __cdecl SymmetricDecrypt( const uint8 *pubEncryptedData, uint32 cubEncryptedData, uint8 *pubPlaintextData, uint32 *pcubPlaintextData, const uint8 *pubKey, uint32 cubKey ); -}; - -extern CCrypto* g_Crypto; - -#endif // !CRYPTO_H_ diff --git a/Resources/NetHook/csimpledetour.cpp b/Resources/NetHook/csimpledetour.cpp deleted file mode 100644 index f3024065..00000000 --- a/Resources/NetHook/csimpledetour.cpp +++ /dev/null @@ -1,34 +0,0 @@ - -#include "csimpledetour.h" - - -CSimpleDetour::CSimpleDetour(void **old, void *replacement) -{ - m_fnOld = old; - m_fnReplacement = replacement; -} - -void CSimpleDetour::Attach() -{ - DetourTransactionBegin(); - DetourUpdateThread(GetCurrentThread()); - - DetourAttach(m_fnOld, m_fnReplacement); - - DetourTransactionCommit(); - - m_bAttached = true; -} - -void CSimpleDetour::Detach() -{ - if (!m_bAttached) - return; - - DetourTransactionBegin(); - DetourUpdateThread(GetCurrentThread()); - - DetourDetach(m_fnOld, m_fnReplacement); - - DetourTransactionCommit(); -} \ No newline at end of file diff --git a/Resources/NetHook/csimpledetour.h b/Resources/NetHook/csimpledetour.h deleted file mode 100644 index b1f9470f..00000000 --- a/Resources/NetHook/csimpledetour.h +++ /dev/null @@ -1,56 +0,0 @@ - -#ifndef CSIMPLEDETOUR_H_ -#define CSIMPLEDETOUR_H_ -#ifdef _WIN32 -#pragma once -#endif - - -#include "detours.h" - - -class CSimpleDetour -{ - -public: - CSimpleDetour( void **old, void *replacement ); - - void Attach(); - void Detach(); - -private: - void **m_fnOld; - void *m_fnReplacement; - - bool m_bAttached; - -}; - - -#define SETUP_SIMPLE_DETOUR(name, old, replacement) \ - CSimpleDetour name(&(void * &)old, (void *)(&(void * &)replacement)) - - -#define SETUP_DETOUR_FUNCTION( ret, conv, name, params ) \ - ret conv name##_H params; \ - ret ( conv *name##_T ) params = name; \ - CSimpleDetour *Detour_##name = new CSimpleDetour( &(void * &)name##_T, (void *)(&(void * &)name##_H) ); \ - ret conv name##_H params - -#define SETUP_DETOUR_FUNCTION_LATE( ret, conv, name, params ) \ - ret conv name##_H params; \ - ret ( conv *name##_T ) params = NULL; \ - CSimpleDetour *Detour_##name = NULL; \ - ret conv name##_H params - -#define SETUP_DETOUR_LATE( name ) \ - Detour_##name = new CSimpleDetour( &(void * &)name##_T, (void *)(&(void * &)name##_H) ) - -#define SETUP_DETOUR_EXTERN( ret, conv, name, params ) \ - extern ret ( conv *name##_T ) params; \ - extern CSimpleDetour *Detour_##name - -#define SETUP_DETOUR_TRAMP( ret, conv, name, params ) \ - ret ( conv *name##_T ) params = NULL; \ - -#endif // !CSIMPLEDETOUR_H_ diff --git a/Resources/NetHook/csimplescan.cpp b/Resources/NetHook/csimplescan.cpp deleted file mode 100644 index 3f6b0d93..00000000 --- a/Resources/NetHook/csimplescan.cpp +++ /dev/null @@ -1,44 +0,0 @@ - - -#include "csimplescan.h" - - -CSimpleScan::CSimpleScan() -{ - m_bInterfaceSet = false; -} - -CSimpleScan::CSimpleScan( const char *filename ) -{ - SetDLL( filename ); -} - -bool CSimpleScan::SetDLL( const char *filename ) -{ - m_Interface = Sys_GetFactory( filename ); - - CSigScan::sigscan_dllfunc = m_Interface; - - if ( !CSigScan::GetDllMemInfo() ) - return m_bInterfaceSet = false; - - m_bInterfaceSet = ( m_Interface != NULL ); - - return m_bInterfaceSet; -} - -bool CSimpleScan::FindFunction( const char *sig, const char *mask, void **func ) -{ - if ( !m_bInterfaceSet ) - return false; - - - m_Signature.Init( ( unsigned char * )sig, ( char * )mask, strlen( mask ) ); - - if ( !m_Signature.is_set ) - return false; - - *func = m_Signature.sig_addr; - - return true; -} \ No newline at end of file diff --git a/Resources/NetHook/csimplescan.h b/Resources/NetHook/csimplescan.h deleted file mode 100644 index e6f1b662..00000000 --- a/Resources/NetHook/csimplescan.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef CSIMPLESCAN_H -#define CSIMPLESCAN_H - -#include "sigscan.h" - -class CSimpleScan -{ - -public: - CSimpleScan(); - CSimpleScan( const char *filename ); - - bool SetDLL( const char *filename ); - bool FindFunction( const char *sig, const char *mask, void **func ); - -private: - bool m_bInterfaceSet; - bool m_bDllInfo; - - CreateInterfaceFn m_Interface; - CSigScan m_Signature; - -}; - -#endif //CSIMPLESCAN_H \ No newline at end of file diff --git a/Resources/NetHook/detours.h b/Resources/NetHook/detours.h deleted file mode 100644 index 33b3a328..00000000 --- a/Resources/NetHook/detours.h +++ /dev/null @@ -1,532 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// Core Detours Functionality (detours.h of detours.lib) -// -// Microsoft Research Detours Package, Version 2.1. -// -// Copyright (c) Microsoft Corporation. All rights reserved. -// - -#pragma once -#ifndef _DETOURS_H_ -#define _DETOURS_H_ - -#include - -#define DETOURS_VERSION 20100 // 2.1.0 - -////////////////////////////////////////////////////////////////////////////// -// - -#if (_MSC_VER < 1299) -typedef LONG LONG_PTR; -typedef ULONG ULONG_PTR; -#endif - -#ifndef __in_z -#define __in_z -#endif - -////////////////////////////////////////////////////////////////////////////// -// -#ifndef GUID_DEFINED -#define GUID_DEFINED -typedef struct _GUID -{ - DWORD Data1; - WORD Data2; - WORD Data3; - BYTE Data4[ 8 ]; -} GUID; - -#ifdef INITGUID -#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ - const GUID name \ - = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } -#else -#define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ - const GUID name -#endif // INITGUID -#endif // !GUID_DEFINED - -#if defined(__cplusplus) -#ifndef _REFGUID_DEFINED -#define _REFGUID_DEFINED -#define REFGUID const GUID & -#endif // !_REFGUID_DEFINED -#else // !__cplusplus -#ifndef _REFGUID_DEFINED -#define _REFGUID_DEFINED -#define REFGUID const GUID * const -#endif // !_REFGUID_DEFINED -#endif // !__cplusplus - -// -////////////////////////////////////////////////////////////////////////////// - -#ifdef __cplusplus -extern "C" { -#endif // __cplusplus - - /////////////////////////////////////////////////// Instruction Target Macros. - // -#define DETOUR_INSTRUCTION_TARGET_NONE ((PVOID)0) -#define DETOUR_INSTRUCTION_TARGET_DYNAMIC ((PVOID)(LONG_PTR)-1) -#define DETOUR_SECTION_HEADER_SIGNATURE 0x00727444 // "Dtr\0" - - extern const GUID DETOUR_EXE_RESTORE_GUID; - -#define DETOUR_TRAMPOLINE_SIGNATURE 0x21727444 // Dtr! - typedef struct _DETOUR_TRAMPOLINE DETOUR_TRAMPOLINE, *PDETOUR_TRAMPOLINE; - - /////////////////////////////////////////////////////////// Binary Structures. - // -#pragma pack(push, 8) - typedef struct _DETOUR_SECTION_HEADER - { - DWORD cbHeaderSize; - DWORD nSignature; - DWORD nDataOffset; - DWORD cbDataSize; - - DWORD nOriginalImportVirtualAddress; - DWORD nOriginalImportSize; - DWORD nOriginalBoundImportVirtualAddress; - DWORD nOriginalBoundImportSize; - - DWORD nOriginalIatVirtualAddress; - DWORD nOriginalIatSize; - DWORD nOriginalSizeOfImage; - DWORD cbPrePE; - - DWORD nOriginalClrFlags; - DWORD reserved1; - DWORD reserved2; - DWORD reserved3; - - // Followed by cbPrePE bytes of data. - } DETOUR_SECTION_HEADER, *PDETOUR_SECTION_HEADER; - - typedef struct _DETOUR_SECTION_RECORD - { - DWORD cbBytes; - DWORD nReserved; - GUID guid; - } DETOUR_SECTION_RECORD, *PDETOUR_SECTION_RECORD; - - typedef struct _DETOUR_CLR_HEADER - { - // Header versioning - ULONG cb; - USHORT MajorRuntimeVersion; - USHORT MinorRuntimeVersion; - - // Symbol table and startup information - IMAGE_DATA_DIRECTORY MetaData; - ULONG Flags; - - // Followed by the rest of the header. - } DETOUR_CLR_HEADER, *PDETOUR_CLR_HEADER; - - typedef struct _DETOUR_EXE_RESTORE - { - ULONG cb; - - PIMAGE_DOS_HEADER pidh; - PIMAGE_NT_HEADERS pinh; - PULONG pclrFlags; - DWORD impDirProt; - - IMAGE_DOS_HEADER idh; - IMAGE_NT_HEADERS inh; - ULONG clrFlags; - } DETOUR_EXE_RESTORE, *PDETOUR_EXE_RESTORE; - -#pragma pack(pop) - -#define DETOUR_SECTION_HEADER_DECLARE(cbSectionSize) \ - { \ - sizeof(DETOUR_SECTION_HEADER),\ - DETOUR_SECTION_HEADER_SIGNATURE,\ - sizeof(DETOUR_SECTION_HEADER),\ - (cbSectionSize),\ - \ - 0,\ - 0,\ - 0,\ - 0,\ - \ - 0,\ - 0,\ - 0,\ - 0,\ - } - - ///////////////////////////////////////////////////////////// Binary Typedefs. - // - typedef BOOL (CALLBACK *PF_DETOUR_BINARY_BYWAY_CALLBACK)(PVOID pContext, - PCHAR pszFile, - PCHAR *ppszOutFile); - - typedef BOOL (CALLBACK *PF_DETOUR_BINARY_FILE_CALLBACK)(PVOID pContext, - PCHAR pszOrigFile, - PCHAR pszFile, - PCHAR *ppszOutFile); - - typedef BOOL (CALLBACK *PF_DETOUR_BINARY_SYMBOL_CALLBACK)(PVOID pContext, - ULONG nOrigOrdinal, - ULONG nOrdinal, - ULONG *pnOutOrdinal, - PCHAR pszOrigSymbol, - PCHAR pszSymbol, - PCHAR *ppszOutSymbol); - - typedef BOOL (CALLBACK *PF_DETOUR_BINARY_COMMIT_CALLBACK)(PVOID pContext); - - typedef BOOL (CALLBACK *PF_DETOUR_ENUMERATE_EXPORT_CALLBACK)(PVOID pContext, - ULONG nOrdinal, - PCHAR pszName, - PVOID pCode); - - typedef VOID * PDETOUR_BINARY; - typedef VOID * PDETOUR_LOADED_BINARY; - - //////////////////////////////////////////////////////////// Detours 2.1 APIs. - // - - LONG WINAPI DetourTransactionBegin(); - LONG WINAPI DetourTransactionAbort(); - LONG WINAPI DetourTransactionCommit(); - LONG WINAPI DetourTransactionCommitEx(PVOID **pppFailedPointer); - - LONG WINAPI DetourUpdateThread(HANDLE hThread); - - LONG WINAPI DetourAttach(PVOID *ppPointer, - PVOID pDetour); - - LONG WINAPI DetourAttachEx(PVOID *ppPointer, - PVOID pDetour, - PDETOUR_TRAMPOLINE *ppRealTrampoline, - PVOID *ppRealTarget, - PVOID *ppRealDetour); - - LONG WINAPI DetourDetach(PVOID *ppPointer, - PVOID pDetour); - - VOID WINAPI DetourSetIgnoreTooSmall(BOOL fIgnore); - - ////////////////////////////////////////////////////////////// Code Functions. - // - PVOID WINAPI DetourFindFunction(PCSTR pszModule, PCSTR pszFunction); - PVOID WINAPI DetourCodeFromPointer(PVOID pPointer, PVOID *ppGlobals); - - PVOID WINAPI DetourCopyInstruction(PVOID pDst, PVOID pSrc, PVOID *ppTarget); - PVOID WINAPI DetourCopyInstructionEx(PVOID pDst, - PVOID pSrc, - PVOID *ppTarget, - LONG *plExtra); - - ///////////////////////////////////////////////////// Loaded Binary Functions. - // - HMODULE WINAPI DetourEnumerateModules(HMODULE hModuleLast); - PVOID WINAPI DetourGetEntryPoint(HMODULE hModule); - ULONG WINAPI DetourGetModuleSize(HMODULE hModule); - BOOL WINAPI DetourEnumerateExports(HMODULE hModule, - PVOID pContext, - PF_DETOUR_ENUMERATE_EXPORT_CALLBACK pfExport); - - PVOID WINAPI DetourFindPayload(HMODULE hModule, REFGUID rguid, DWORD *pcbData); - DWORD WINAPI DetourGetSizeOfPayloads(HMODULE hModule); - - ///////////////////////////////////////////////// Persistent Binary Functions. - // - - PDETOUR_BINARY WINAPI DetourBinaryOpen(HANDLE hFile); - PVOID WINAPI DetourBinaryEnumeratePayloads(PDETOUR_BINARY pBinary, - GUID *pGuid, - DWORD *pcbData, - DWORD *pnIterator); - PVOID WINAPI DetourBinaryFindPayload(PDETOUR_BINARY pBinary, - REFGUID rguid, - DWORD *pcbData); - PVOID WINAPI DetourBinarySetPayload(PDETOUR_BINARY pBinary, - REFGUID rguid, - PVOID pData, - DWORD cbData); - BOOL WINAPI DetourBinaryDeletePayload(PDETOUR_BINARY pBinary, REFGUID rguid); - BOOL WINAPI DetourBinaryPurgePayloads(PDETOUR_BINARY pBinary); - BOOL WINAPI DetourBinaryResetImports(PDETOUR_BINARY pBinary); - BOOL WINAPI DetourBinaryEditImports(PDETOUR_BINARY pBinary, - PVOID pContext, - PF_DETOUR_BINARY_BYWAY_CALLBACK pfByway, - PF_DETOUR_BINARY_FILE_CALLBACK pfFile, - PF_DETOUR_BINARY_SYMBOL_CALLBACK pfSymbol, - PF_DETOUR_BINARY_COMMIT_CALLBACK pfCommit); - BOOL WINAPI DetourBinaryWrite(PDETOUR_BINARY pBinary, HANDLE hFile); - BOOL WINAPI DetourBinaryClose(PDETOUR_BINARY pBinary); - - /////////////////////////////////////////////////// Create Process & Load Dll. - // - typedef BOOL (WINAPI *PDETOUR_CREATE_PROCESS_ROUTINEA) - (LPCSTR lpApplicationName, - LPSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCSTR lpCurrentDirectory, - LPSTARTUPINFOA lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation); - - typedef BOOL (WINAPI *PDETOUR_CREATE_PROCESS_ROUTINEW) - (LPCWSTR lpApplicationName, - LPWSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCWSTR lpCurrentDirectory, - LPSTARTUPINFOW lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation); - - BOOL WINAPI DetourCreateProcessWithDllA(LPCSTR lpApplicationName, - __in_z LPSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCSTR lpCurrentDirectory, - LPSTARTUPINFOA lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation, - LPCSTR lpDetouredDllFullName, - LPCSTR lpDllName, - PDETOUR_CREATE_PROCESS_ROUTINEA - pfCreateProcessA); - - BOOL WINAPI DetourCreateProcessWithDllW(LPCWSTR lpApplicationName, - __in_z LPWSTR lpCommandLine, - LPSECURITY_ATTRIBUTES lpProcessAttributes, - LPSECURITY_ATTRIBUTES lpThreadAttributes, - BOOL bInheritHandles, - DWORD dwCreationFlags, - LPVOID lpEnvironment, - LPCWSTR lpCurrentDirectory, - LPSTARTUPINFOW lpStartupInfo, - LPPROCESS_INFORMATION lpProcessInformation, - LPCSTR lpDetouredDllFullName, - LPCSTR lpDllName, - PDETOUR_CREATE_PROCESS_ROUTINEW - pfCreateProcessW); - -#ifdef UNICODE -#define DetourCreateProcessWithDll DetourCreateProcessWithDllW -#define PDETOUR_CREATE_PROCESS_ROUTINE PDETOUR_CREATE_PROCESS_ROUTINEW -#else -#define DetourCreateProcessWithDll DetourCreateProcessWithDllA -#define PDETOUR_CREATE_PROCESS_ROUTINE PDETOUR_CREATE_PROCESS_ROUTINEA -#endif // !UNICODE - - BOOL WINAPI DetourCopyPayloadToProcess(HANDLE hProcess, - REFGUID rguid, - PVOID pvData, - DWORD cbData); - BOOL WINAPI DetourRestoreAfterWith(); - BOOL WINAPI DetourRestoreAfterWithEx(PVOID pvData, DWORD cbData); - - HMODULE WINAPI DetourGetDetouredMarker(); - - // - ////////////////////////////////////////////////////////////////////////////// -#ifdef __cplusplus -} -#endif // __cplusplus - -//////////////////////////////////////////////// Detours Internal Definitions. -// -#ifdef __cplusplus -#ifdef DETOURS_INTERNAL - -#ifndef __deref_out -#define __deref_out -#endif - -#ifndef __deref -#define __deref -#endif - -////////////////////////////////////////////////////////////////////////////// -// -#if (_MSC_VER < 1299) -#include -typedef IMAGEHLP_MODULE IMAGEHLP_MODULE64; -typedef PIMAGEHLP_MODULE PIMAGEHLP_MODULE64; -typedef IMAGEHLP_SYMBOL SYMBOL_INFO; -typedef PIMAGEHLP_SYMBOL PSYMBOL_INFO; - -static inline -LONG InterlockedCompareExchange(LONG *ptr, LONG nval, LONG oval) -{ - return (LONG)::InterlockedCompareExchange((PVOID*)ptr, (PVOID)nval, (PVOID)oval); -} -#else -#include -#endif - -#ifdef IMAGEAPI // defined by DBGHELP.H -typedef LPAPI_VERSION (NTAPI *PF_ImagehlpApiVersionEx)(LPAPI_VERSION AppVersion); - -typedef BOOL (NTAPI *PF_SymInitialize)(IN HANDLE hProcess, - IN LPCSTR UserSearchPath, - IN BOOL fInvadeProcess); -typedef DWORD (NTAPI *PF_SymSetOptions)(IN DWORD SymOptions); -typedef DWORD (NTAPI *PF_SymGetOptions)(VOID); -typedef DWORD64 (NTAPI *PF_SymLoadModule64)(IN HANDLE hProcess, - IN HANDLE hFile, - IN PSTR ImageName, - IN PSTR ModuleName, - IN DWORD64 BaseOfDll, - IN DWORD SizeOfDll); -typedef BOOL (NTAPI *PF_SymGetModuleInfo64)(IN HANDLE hProcess, - IN DWORD64 qwAddr, - OUT PIMAGEHLP_MODULE64 ModuleInfo); -typedef BOOL (NTAPI *PF_SymFromName)(IN HANDLE hProcess, - IN LPSTR Name, - OUT PSYMBOL_INFO Symbol); - -typedef struct _DETOUR_SYM_INFO -{ - HANDLE hProcess; - HMODULE hDbgHelp; - PF_ImagehlpApiVersionEx pfImagehlpApiVersionEx; - PF_SymInitialize pfSymInitialize; - PF_SymSetOptions pfSymSetOptions; - PF_SymGetOptions pfSymGetOptions; - PF_SymLoadModule64 pfSymLoadModule64; - PF_SymGetModuleInfo64 pfSymGetModuleInfo64; - PF_SymFromName pfSymFromName; -} DETOUR_SYM_INFO, *PDETOUR_SYM_INFO; - -PDETOUR_SYM_INFO DetourLoadDbgHelp(VOID); - -#endif // IMAGEAPI - -#ifndef DETOUR_TRACE -#if DETOUR_DEBUG -#define DETOUR_TRACE(x) printf x -#define DETOUR_BREAK() DebugBreak() -#include -#include -#else -#define DETOUR_TRACE(x) -#define DETOUR_BREAK() -#endif -#endif - -#ifdef DETOURS_IA64 -__declspec(align(16)) struct DETOUR_IA64_BUNDLE -{ -public: - union - { - BYTE data[16]; - UINT64 wide[2]; - }; - -public: - struct DETOUR_IA64_METADATA; - - typedef BOOL (DETOUR_IA64_BUNDLE::* DETOUR_IA64_METACOPY) - (const DETOUR_IA64_METADATA *pMeta, DETOUR_IA64_BUNDLE *pDst) const; - - enum { - A_UNIT = 1u, - I_UNIT = 2u, - M_UNIT = 3u, - B_UNIT = 4u, - F_UNIT = 5u, - L_UNIT = 6u, - X_UNIT = 7u, - UNIT_MASK = 7u, - STOP = 8u - }; - struct DETOUR_IA64_METADATA - { - ULONG nTemplate : 8; // Instruction template. - ULONG nUnit0 : 4; // Unit for slot 0 - ULONG nUnit1 : 4; // Unit for slot 1 - ULONG nUnit2 : 4; // Unit for slot 2 - DETOUR_IA64_METACOPY pfCopy; // Function pointer. - }; - -protected: - BOOL CopyBytes(const DETOUR_IA64_METADATA *pMeta, DETOUR_IA64_BUNDLE *pDst) const; - BOOL CopyBytesMMB(const DETOUR_IA64_METADATA *pMeta, DETOUR_IA64_BUNDLE *pDst) const; - BOOL CopyBytesMBB(const DETOUR_IA64_METADATA *pMeta, DETOUR_IA64_BUNDLE *pDst) const; - BOOL CopyBytesBBB(const DETOUR_IA64_METADATA *pMeta, DETOUR_IA64_BUNDLE *pDst) const; - BOOL CopyBytesMLX(const DETOUR_IA64_METADATA *pMeta, DETOUR_IA64_BUNDLE *pDst) const; - - static const DETOUR_IA64_METADATA s_rceCopyTable[33]; - -public: - // 120 112 104 96 88 80 72 64 56 48 40 32 24 16 8 0 - // f. e. d. c. b. a. 9. 8. 7. 6. 5. 4. 3. 2. 1. 0. - - // 00 - // f.e. d.c. b.a. 9.8. 7.6. 5.4. 3.2. 1.0. - // 0000 0000 0000 0000 0000 0000 0000 001f : Template [4..0] - // 0000 0000 0000 0000 0000 03ff ffff ffe0 : Zero [ 41.. 5] - // 0000 0000 0000 0000 0000 3c00 0000 0000 : Zero [ 45.. 42] - // 0000 0000 0007 ffff ffff c000 0000 0000 : One [ 82.. 46] - // 0000 0000 0078 0000 0000 0000 0000 0000 : One [ 86.. 83] - // 0fff ffff ff80 0000 0000 0000 0000 0000 : Two [123.. 87] - // f000 0000 0000 0000 0000 0000 0000 0000 : Two [127..124] - BYTE GetTemplate() const; - BYTE GetInst0() const; - BYTE GetInst1() const; - BYTE GetInst2() const; - BYTE GetUnit0() const; - BYTE GetUnit1() const; - BYTE GetUnit2() const; - UINT64 GetData0() const; - UINT64 GetData1() const; - UINT64 GetData2() const; - -public: - BOOL IsBrl() const; - VOID SetBrl(); - VOID SetBrl(UINT64 target); - UINT64 GetBrlTarget() const; - VOID SetBrlTarget(UINT64 target); - VOID SetBrlImm(UINT64 imm); - UINT64 GetBrlImm() const; - - BOOL IsMovlGp() const; - UINT64 GetMovlGp() const; - VOID SetMovlGp(UINT64 gp); - - VOID SetInst0(BYTE nInst); - VOID SetInst1(BYTE nInst); - VOID SetInst2(BYTE nInst); - VOID SetData0(UINT64 nData); - VOID SetData1(UINT64 nData); - VOID SetData2(UINT64 nData); - BOOL SetNop0(); - BOOL SetNop1(); - BOOL SetNop2(); - BOOL SetStop(); - - BOOL Copy(DETOUR_IA64_BUNDLE *pDst) const; -}; -#endif // DETOURS_IA64 - -////////////////////////////////////////////////////////////////////////////// - -#endif // DETOURS_INTERNAL -#endif // __cplusplus - -#endif // _DETOURS_H_ -// -//////////////////////////////////////////////////////////////// End of File. diff --git a/Resources/NetHook/detours.lib b/Resources/NetHook/detours.lib deleted file mode 100644 index 3bdca075..00000000 Binary files a/Resources/NetHook/detours.lib and /dev/null differ diff --git a/Resources/NetHook/google/protobuf/descriptor.cc b/Resources/NetHook/google/protobuf/descriptor.cc deleted file mode 100644 index 81c4ac0f..00000000 --- a/Resources/NetHook/google/protobuf/descriptor.cc +++ /dev/null @@ -1,4401 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#undef PACKAGE // autoheader #defines this. :( - -namespace google { -namespace protobuf { - -const FieldDescriptor::CppType -FieldDescriptor::kTypeToCppTypeMap[MAX_TYPE + 1] = { - static_cast(0), // 0 is reserved for errors - - CPPTYPE_DOUBLE, // TYPE_DOUBLE - CPPTYPE_FLOAT, // TYPE_FLOAT - CPPTYPE_INT64, // TYPE_INT64 - CPPTYPE_UINT64, // TYPE_UINT64 - CPPTYPE_INT32, // TYPE_INT32 - CPPTYPE_UINT64, // TYPE_FIXED64 - CPPTYPE_UINT32, // TYPE_FIXED32 - CPPTYPE_BOOL, // TYPE_BOOL - CPPTYPE_STRING, // TYPE_STRING - CPPTYPE_MESSAGE, // TYPE_GROUP - CPPTYPE_MESSAGE, // TYPE_MESSAGE - CPPTYPE_STRING, // TYPE_BYTES - CPPTYPE_UINT32, // TYPE_UINT32 - CPPTYPE_ENUM, // TYPE_ENUM - CPPTYPE_INT32, // TYPE_SFIXED32 - CPPTYPE_INT64, // TYPE_SFIXED64 - CPPTYPE_INT32, // TYPE_SINT32 - CPPTYPE_INT64, // TYPE_SINT64 -}; - -const char * const FieldDescriptor::kTypeToName[MAX_TYPE + 1] = { - "ERROR", // 0 is reserved for errors - - "double", // TYPE_DOUBLE - "float", // TYPE_FLOAT - "int64", // TYPE_INT64 - "uint64", // TYPE_UINT64 - "int32", // TYPE_INT32 - "fixed64", // TYPE_FIXED64 - "fixed32", // TYPE_FIXED32 - "bool", // TYPE_BOOL - "string", // TYPE_STRING - "group", // TYPE_GROUP - "message", // TYPE_MESSAGE - "bytes", // TYPE_BYTES - "uint32", // TYPE_UINT32 - "enum", // TYPE_ENUM - "sfixed32", // TYPE_SFIXED32 - "sfixed64", // TYPE_SFIXED64 - "sint32", // TYPE_SINT32 - "sint64", // TYPE_SINT64 -}; - -const char * const FieldDescriptor::kLabelToName[MAX_LABEL + 1] = { - "ERROR", // 0 is reserved for errors - - "optional", // LABEL_OPTIONAL - "required", // LABEL_REQUIRED - "repeated", // LABEL_REPEATED -}; - -#ifndef _MSC_VER // MSVC doesn't need these and won't even accept them. -const int FieldDescriptor::kMaxNumber; -const int FieldDescriptor::kFirstReservedNumber; -const int FieldDescriptor::kLastReservedNumber; -#endif - -namespace { - -const string kEmptyString; - -string ToCamelCase(const string& input) { - bool capitalize_next = false; - string result; - result.reserve(input.size()); - - for (int i = 0; i < input.size(); i++) { - if (input[i] == '_') { - capitalize_next = true; - } else if (capitalize_next) { - // Note: I distrust ctype.h due to locales. - if ('a' <= input[i] && input[i] <= 'z') { - result.push_back(input[i] - 'a' + 'A'); - } else { - result.push_back(input[i]); - } - capitalize_next = false; - } else { - result.push_back(input[i]); - } - } - - // Lower-case the first letter. - if (!result.empty() && 'A' <= result[0] && result[0] <= 'Z') { - result[0] = result[0] - 'A' + 'a'; - } - - return result; -} - -// A DescriptorPool contains a bunch of hash_maps to implement the -// various Find*By*() methods. Since hashtable lookups are O(1), it's -// most efficient to construct a fixed set of large hash_maps used by -// all objects in the pool rather than construct one or more small -// hash_maps for each object. -// -// The keys to these hash_maps are (parent, name) or (parent, number) -// pairs. Unfortunately STL doesn't provide hash functions for pair<>, -// so we must invent our own. -// -// TODO(kenton): Use StringPiece rather than const char* in keys? It would -// be a lot cleaner but we'd just have to convert it back to const char* -// for the open source release. - -typedef pair PointerStringPair; - -struct PointerStringPairEqual { - inline bool operator()(const PointerStringPair& a, - const PointerStringPair& b) const { - return a.first == b.first && strcmp(a.second, b.second) == 0; - } -}; - -template -struct PointerIntegerPairHash { - size_t operator()(const PairType& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - return reinterpret_cast(p.first) * ((1 << 16) - 1) + p.second; - } - - // Used only by MSVC and platforms where hash_map is not available. - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; - inline bool operator()(const PairType& a, const PairType& b) const { - return a.first < b.first || - (a.first == b.first && a.second < b.second); - } -}; - -typedef pair DescriptorIntPair; -typedef pair EnumIntPair; - -struct PointerStringPairHash { - size_t operator()(const PointerStringPair& p) const { - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - hash cstring_hash; - return reinterpret_cast(p.first) * ((1 << 16) - 1) + - cstring_hash(p.second); - } - - // Used only by MSVC and platforms where hash_map is not available. - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; - inline bool operator()(const PointerStringPair& a, - const PointerStringPair& b) const { - if (a.first < b.first) return true; - if (a.first > b.first) return false; - return strcmp(a.second, b.second) < 0; - } -}; - - -struct Symbol { - enum Type { - NULL_SYMBOL, MESSAGE, FIELD, ENUM, ENUM_VALUE, SERVICE, METHOD, PACKAGE - }; - Type type; - union { - const Descriptor* descriptor; - const FieldDescriptor* field_descriptor; - const EnumDescriptor* enum_descriptor; - const EnumValueDescriptor* enum_value_descriptor; - const ServiceDescriptor* service_descriptor; - const MethodDescriptor* method_descriptor; - const FileDescriptor* package_file_descriptor; - }; - - inline Symbol() : type(NULL_SYMBOL) { descriptor = NULL; } - inline bool IsNull() const { return type == NULL_SYMBOL; } - inline bool IsType() const { - return type == MESSAGE || type == ENUM; - } - inline bool IsAggregate() const { - return type == MESSAGE || type == PACKAGE - || type == ENUM || type == SERVICE; - } - -#define CONSTRUCTOR(TYPE, TYPE_CONSTANT, FIELD) \ - inline explicit Symbol(const TYPE* value) { \ - type = TYPE_CONSTANT; \ - this->FIELD = value; \ - } - - CONSTRUCTOR(Descriptor , MESSAGE , descriptor ) - CONSTRUCTOR(FieldDescriptor , FIELD , field_descriptor ) - CONSTRUCTOR(EnumDescriptor , ENUM , enum_descriptor ) - CONSTRUCTOR(EnumValueDescriptor, ENUM_VALUE, enum_value_descriptor ) - CONSTRUCTOR(ServiceDescriptor , SERVICE , service_descriptor ) - CONSTRUCTOR(MethodDescriptor , METHOD , method_descriptor ) - CONSTRUCTOR(FileDescriptor , PACKAGE , package_file_descriptor) -#undef CONSTRUCTOR - - const FileDescriptor* GetFile() const { - switch (type) { - case NULL_SYMBOL: return NULL; - case MESSAGE : return descriptor ->file(); - case FIELD : return field_descriptor ->file(); - case ENUM : return enum_descriptor ->file(); - case ENUM_VALUE : return enum_value_descriptor->type()->file(); - case SERVICE : return service_descriptor ->file(); - case METHOD : return method_descriptor ->service()->file(); - case PACKAGE : return package_file_descriptor; - } - return NULL; - } -}; - -const Symbol kNullSymbol; - -typedef hash_map, streq> - SymbolsByNameMap; -typedef hash_map - SymbolsByParentMap; -typedef hash_map, streq> - FilesByNameMap; -typedef hash_map - FieldsByNameMap; -typedef hash_map > - FieldsByNumberMap; -typedef hash_map > - EnumValuesByNumberMap; -// This is a map rather than a hash_map, since we use it to iterate -// through all the extensions that extend a given Descriptor, and an -// ordered data structure that implements lower_bound is convenient -// for that. -typedef map - ExtensionsGroupedByDescriptorMap; - -} // anonymous namespace - -// =================================================================== -// DescriptorPool::Tables - -class DescriptorPool::Tables { - public: - Tables(); - ~Tables(); - - // Checkpoint the state of the tables. Future calls to Rollback() will - // return the Tables to this state. This is used when building files, since - // some kinds of validation errors cannot be detected until the file's - // descriptors have already been added to the tables. BuildFile() calls - // Checkpoint() before it starts building and Rollback() if it encounters - // an error. - void Checkpoint(); - - // Roll back the Tables to the state of the last Checkpoint(), removing - // everything that was added after that point. - void Rollback(); - - // The stack of files which are currently being built. Used to detect - // cyclic dependencies when loading files from a DescriptorDatabase. Not - // used when fallback_database_ == NULL. - vector pending_files_; - - // A set of files which we have tried to load from the fallback database - // and encountered errors. We will not attempt to load them again. - // Not used when fallback_database_ == NULL. - hash_set known_bad_files_; - - // The set of descriptors for which we've already loaded the full - // set of extensions numbers from fallback_database_. - hash_set extensions_loaded_from_db_; - - // ----------------------------------------------------------------- - // Finding items. - - // Find symbols. This returns a null Symbol (symbol.IsNull() is true) - // if not found. - inline Symbol FindSymbol(const string& key) const; - - // This implements the body of DescriptorPool::Find*ByName(). It should - // really be a private method of DescriptorPool, but that would require - // declaring Symbol in descriptor.h, which would drag all kinds of other - // stuff into the header. Yay C++. - Symbol FindByNameHelper( - const DescriptorPool* pool, const string& name) const; - - // These return NULL if not found. - inline const FileDescriptor* FindFile(const string& key) const; - inline const FieldDescriptor* FindExtension(const Descriptor* extendee, - int number); - inline void FindAllExtensions(const Descriptor* extendee, - vector* out) const; - - // ----------------------------------------------------------------- - // Adding items. - - // These add items to the corresponding tables. They return false if - // the key already exists in the table. For AddSymbol(), the string passed - // in must be one that was constructed using AllocateString(), as it will - // be used as a key in the symbols_by_name_ map without copying. - bool AddSymbol(const string& full_name, Symbol symbol); - bool AddFile(const FileDescriptor* file); - bool AddExtension(const FieldDescriptor* field); - - // ----------------------------------------------------------------- - // Allocating memory. - - // Allocate an object which will be reclaimed when the pool is - // destroyed. Note that the object's destructor will never be called, - // so its fields must be plain old data (primitive data types and - // pointers). All of the descriptor types are such objects. - template Type* Allocate(); - - // Allocate an array of objects which will be reclaimed when the - // pool in destroyed. Again, destructors are never called. - template Type* AllocateArray(int count); - - // Allocate a string which will be destroyed when the pool is destroyed. - // The string is initialized to the given value for convenience. - string* AllocateString(const string& value); - - // Allocate a protocol message object. Some older versions of GCC have - // trouble understanding explicit template instantiations in some cases, so - // in those cases we have to pass a dummy pointer of the right type as the - // parameter instead of specifying the type explicitly. - template Type* AllocateMessage(Type* dummy = NULL); - - // Allocate a FileDescriptorTables object. - FileDescriptorTables* AllocateFileTables(); - - private: - vector strings_; // All strings in the pool. - vector messages_; // All messages in the pool. - vector file_tables_; // All file tables in the pool. - vector allocations_; // All other memory allocated in the pool. - - SymbolsByNameMap symbols_by_name_; - FilesByNameMap files_by_name_; - ExtensionsGroupedByDescriptorMap extensions_; - - int strings_before_checkpoint_; - int messages_before_checkpoint_; - int file_tables_before_checkpoint_; - int allocations_before_checkpoint_; - vector symbols_after_checkpoint_; - vector files_after_checkpoint_; - vector extensions_after_checkpoint_; - - // Allocate some bytes which will be reclaimed when the pool is - // destroyed. - void* AllocateBytes(int size); -}; - -// Contains tables specific to a particular file. These tables are not -// modified once the file has been constructed, so they need not be -// protected by a mutex. This makes operations that depend only on the -// contents of a single file -- e.g. Descriptor::FindFieldByName() -- -// lock-free. -// -// For historical reasons, the definitions of the methods of -// FileDescriptorTables and DescriptorPool::Tables are interleaved below. -// These used to be a single class. -class FileDescriptorTables { - public: - FileDescriptorTables(); - ~FileDescriptorTables(); - - // Empty table, used with placeholder files. - static const FileDescriptorTables kEmpty; - - // ----------------------------------------------------------------- - // Finding items. - - // Find symbols. These return a null Symbol (symbol.IsNull() is true) - // if not found. - inline Symbol FindNestedSymbol(const void* parent, - const string& name) const; - inline Symbol FindNestedSymbolOfType(const void* parent, - const string& name, - const Symbol::Type type) const; - - // These return NULL if not found. - inline const FieldDescriptor* FindFieldByNumber( - const Descriptor* parent, int number) const; - inline const FieldDescriptor* FindFieldByLowercaseName( - const void* parent, const string& lowercase_name) const; - inline const FieldDescriptor* FindFieldByCamelcaseName( - const void* parent, const string& camelcase_name) const; - inline const EnumValueDescriptor* FindEnumValueByNumber( - const EnumDescriptor* parent, int number) const; - - // ----------------------------------------------------------------- - // Adding items. - - // These add items to the corresponding tables. They return false if - // the key already exists in the table. For AddAliasUnderParent(), the - // string passed in must be one that was constructed using AllocateString(), - // as it will be used as a key in the symbols_by_parent_ map without copying. - bool AddAliasUnderParent(const void* parent, const string& name, - Symbol symbol); - bool AddFieldByNumber(const FieldDescriptor* field); - bool AddEnumValueByNumber(const EnumValueDescriptor* value); - - // Adds the field to the lowercase_name and camelcase_name maps. Never - // fails because we allow duplicates; the first field by the name wins. - void AddFieldByStylizedNames(const FieldDescriptor* field); - - private: - SymbolsByParentMap symbols_by_parent_; - FieldsByNameMap fields_by_lowercase_name_; - FieldsByNameMap fields_by_camelcase_name_; - FieldsByNumberMap fields_by_number_; // Not including extensions. - EnumValuesByNumberMap enum_values_by_number_; -}; - -DescriptorPool::Tables::Tables() - : strings_before_checkpoint_(0), - messages_before_checkpoint_(0), - allocations_before_checkpoint_(0) {} - -DescriptorPool::Tables::~Tables() { - // Note that the deletion order is important, since the destructors of some - // messages may refer to objects in allocations_. - STLDeleteElements(&messages_); - for (int i = 0; i < allocations_.size(); i++) { - operator delete(allocations_[i]); - } - STLDeleteElements(&strings_); - STLDeleteElements(&file_tables_); -} - -FileDescriptorTables::FileDescriptorTables() {} -FileDescriptorTables::~FileDescriptorTables() {} - -const FileDescriptorTables FileDescriptorTables::kEmpty; - -void DescriptorPool::Tables::Checkpoint() { - strings_before_checkpoint_ = strings_.size(); - messages_before_checkpoint_ = messages_.size(); - file_tables_before_checkpoint_ = file_tables_.size(); - allocations_before_checkpoint_ = allocations_.size(); - - symbols_after_checkpoint_.clear(); - files_after_checkpoint_.clear(); - extensions_after_checkpoint_.clear(); -} - -void DescriptorPool::Tables::Rollback() { - for (int i = 0; i < symbols_after_checkpoint_.size(); i++) { - symbols_by_name_.erase(symbols_after_checkpoint_[i]); - } - for (int i = 0; i < files_after_checkpoint_.size(); i++) { - files_by_name_.erase(files_after_checkpoint_[i]); - } - for (int i = 0; i < extensions_after_checkpoint_.size(); i++) { - extensions_.erase(extensions_after_checkpoint_[i]); - } - - symbols_after_checkpoint_.clear(); - files_after_checkpoint_.clear(); - extensions_after_checkpoint_.clear(); - - STLDeleteContainerPointers( - strings_.begin() + strings_before_checkpoint_, strings_.end()); - STLDeleteContainerPointers( - messages_.begin() + messages_before_checkpoint_, messages_.end()); - STLDeleteContainerPointers( - file_tables_.begin() + file_tables_before_checkpoint_, file_tables_.end()); - for (int i = allocations_before_checkpoint_; i < allocations_.size(); i++) { - operator delete(allocations_[i]); - } - - strings_.resize(strings_before_checkpoint_); - messages_.resize(messages_before_checkpoint_); - file_tables_.resize(file_tables_before_checkpoint_); - allocations_.resize(allocations_before_checkpoint_); -} - -// ------------------------------------------------------------------- - -inline Symbol DescriptorPool::Tables::FindSymbol(const string& key) const { - const Symbol* result = FindOrNull(symbols_by_name_, key.c_str()); - if (result == NULL) { - return kNullSymbol; - } else { - return *result; - } -} - -inline Symbol FileDescriptorTables::FindNestedSymbol( - const void* parent, const string& name) const { - const Symbol* result = - FindOrNull(symbols_by_parent_, PointerStringPair(parent, name.c_str())); - if (result == NULL) { - return kNullSymbol; - } else { - return *result; - } -} - -inline Symbol FileDescriptorTables::FindNestedSymbolOfType( - const void* parent, const string& name, const Symbol::Type type) const { - Symbol result = FindNestedSymbol(parent, name); - if (result.type != type) return kNullSymbol; - return result; -} - -Symbol DescriptorPool::Tables::FindByNameHelper( - const DescriptorPool* pool, const string& name) const { - MutexLockMaybe lock(pool->mutex_); - Symbol result = FindSymbol(name); - - if (result.IsNull() && pool->underlay_ != NULL) { - // Symbol not found; check the underlay. - result = - pool->underlay_->tables_->FindByNameHelper(pool->underlay_, name); - } - - if (result.IsNull()) { - // Symbol still not found, so check fallback database. - if (pool->TryFindSymbolInFallbackDatabase(name)) { - result = FindSymbol(name); - } - } - - return result; -} - -inline const FileDescriptor* DescriptorPool::Tables::FindFile( - const string& key) const { - return FindPtrOrNull(files_by_name_, key.c_str()); -} - -inline const FieldDescriptor* FileDescriptorTables::FindFieldByNumber( - const Descriptor* parent, int number) const { - return FindPtrOrNull(fields_by_number_, make_pair(parent, number)); -} - -inline const FieldDescriptor* FileDescriptorTables::FindFieldByLowercaseName( - const void* parent, const string& lowercase_name) const { - return FindPtrOrNull(fields_by_lowercase_name_, - PointerStringPair(parent, lowercase_name.c_str())); -} - -inline const FieldDescriptor* FileDescriptorTables::FindFieldByCamelcaseName( - const void* parent, const string& camelcase_name) const { - return FindPtrOrNull(fields_by_camelcase_name_, - PointerStringPair(parent, camelcase_name.c_str())); -} - -inline const EnumValueDescriptor* FileDescriptorTables::FindEnumValueByNumber( - const EnumDescriptor* parent, int number) const { - return FindPtrOrNull(enum_values_by_number_, make_pair(parent, number)); -} - -inline const FieldDescriptor* DescriptorPool::Tables::FindExtension( - const Descriptor* extendee, int number) { - return FindPtrOrNull(extensions_, make_pair(extendee, number)); -} - -inline void DescriptorPool::Tables::FindAllExtensions( - const Descriptor* extendee, vector* out) const { - ExtensionsGroupedByDescriptorMap::const_iterator it = - extensions_.lower_bound(make_pair(extendee, 0)); - for (; it != extensions_.end() && it->first.first == extendee; ++it) { - out->push_back(it->second); - } -} - -// ------------------------------------------------------------------- - -bool DescriptorPool::Tables::AddSymbol( - const string& full_name, Symbol symbol) { - if (InsertIfNotPresent(&symbols_by_name_, full_name.c_str(), symbol)) { - symbols_after_checkpoint_.push_back(full_name.c_str()); - return true; - } else { - return false; - } -} - -bool FileDescriptorTables::AddAliasUnderParent( - const void* parent, const string& name, Symbol symbol) { - PointerStringPair by_parent_key(parent, name.c_str()); - return InsertIfNotPresent(&symbols_by_parent_, by_parent_key, symbol); -} - -bool DescriptorPool::Tables::AddFile(const FileDescriptor* file) { - if (InsertIfNotPresent(&files_by_name_, file->name().c_str(), file)) { - files_after_checkpoint_.push_back(file->name().c_str()); - return true; - } else { - return false; - } -} - -void FileDescriptorTables::AddFieldByStylizedNames( - const FieldDescriptor* field) { - const void* parent; - if (field->is_extension()) { - if (field->extension_scope() == NULL) { - parent = field->file(); - } else { - parent = field->extension_scope(); - } - } else { - parent = field->containing_type(); - } - - PointerStringPair lowercase_key(parent, field->lowercase_name().c_str()); - InsertIfNotPresent(&fields_by_lowercase_name_, lowercase_key, field); - - PointerStringPair camelcase_key(parent, field->camelcase_name().c_str()); - InsertIfNotPresent(&fields_by_camelcase_name_, camelcase_key, field); -} - -bool FileDescriptorTables::AddFieldByNumber(const FieldDescriptor* field) { - DescriptorIntPair key(field->containing_type(), field->number()); - return InsertIfNotPresent(&fields_by_number_, key, field); -} - -bool FileDescriptorTables::AddEnumValueByNumber( - const EnumValueDescriptor* value) { - EnumIntPair key(value->type(), value->number()); - return InsertIfNotPresent(&enum_values_by_number_, key, value); -} - -bool DescriptorPool::Tables::AddExtension(const FieldDescriptor* field) { - DescriptorIntPair key(field->containing_type(), field->number()); - if (InsertIfNotPresent(&extensions_, key, field)) { - extensions_after_checkpoint_.push_back(key); - return true; - } else { - return false; - } -} - -// ------------------------------------------------------------------- - -template -Type* DescriptorPool::Tables::Allocate() { - return reinterpret_cast(AllocateBytes(sizeof(Type))); -} - -template -Type* DescriptorPool::Tables::AllocateArray(int count) { - return reinterpret_cast(AllocateBytes(sizeof(Type) * count)); -} - -string* DescriptorPool::Tables::AllocateString(const string& value) { - string* result = new string(value); - strings_.push_back(result); - return result; -} - -template -Type* DescriptorPool::Tables::AllocateMessage(Type* dummy) { - Type* result = new Type; - messages_.push_back(result); - return result; -} - -FileDescriptorTables* DescriptorPool::Tables::AllocateFileTables() { - FileDescriptorTables* result = new FileDescriptorTables; - file_tables_.push_back(result); - return result; -} - -void* DescriptorPool::Tables::AllocateBytes(int size) { - // TODO(kenton): Would it be worthwhile to implement this in some more - // sophisticated way? Probably not for the open source release, but for - // internal use we could easily plug in one of our existing memory pool - // allocators... - if (size == 0) return NULL; - - void* result = operator new(size); - allocations_.push_back(result); - return result; -} - -// =================================================================== -// DescriptorPool - -DescriptorPool::ErrorCollector::~ErrorCollector() {} - -DescriptorPool::DescriptorPool() - : mutex_(NULL), - fallback_database_(NULL), - default_error_collector_(NULL), - underlay_(NULL), - tables_(new Tables), - enforce_dependencies_(true), - allow_unknown_(false) {} - -DescriptorPool::DescriptorPool(DescriptorDatabase* fallback_database, - ErrorCollector* error_collector) - : mutex_(new Mutex), - fallback_database_(fallback_database), - default_error_collector_(error_collector), - underlay_(NULL), - tables_(new Tables), - enforce_dependencies_(true), - allow_unknown_(false) { -} - -DescriptorPool::DescriptorPool(const DescriptorPool* underlay) - : mutex_(NULL), - fallback_database_(NULL), - default_error_collector_(NULL), - underlay_(underlay), - tables_(new Tables), - enforce_dependencies_(true), - allow_unknown_(false) {} - -DescriptorPool::~DescriptorPool() { - if (mutex_ != NULL) delete mutex_; -} - -// DescriptorPool::BuildFile() defined later. -// DescriptorPool::BuildFileCollectingErrors() defined later. - -void DescriptorPool::InternalDontEnforceDependencies() { - enforce_dependencies_ = false; -} - -bool DescriptorPool::InternalIsFileLoaded(const string& filename) const { - MutexLockMaybe lock(mutex_); - return tables_->FindFile(filename) != NULL; -} - -// generated_pool ==================================================== - -namespace { - - -EncodedDescriptorDatabase* generated_database_ = NULL; -DescriptorPool* generated_pool_ = NULL; -GOOGLE_PROTOBUF_DECLARE_ONCE(generated_pool_init_); - -void DeleteGeneratedPool() { - delete generated_database_; - generated_database_ = NULL; - delete generated_pool_; - generated_pool_ = NULL; -} - -void InitGeneratedPool() { - generated_database_ = new EncodedDescriptorDatabase; - generated_pool_ = new DescriptorPool(generated_database_); - - internal::OnShutdown(&DeleteGeneratedPool); -} - -inline void InitGeneratedPoolOnce() { - ::google::protobuf::GoogleOnceInit(&generated_pool_init_, &InitGeneratedPool); -} - -} // anonymous namespace - -const DescriptorPool* DescriptorPool::generated_pool() { - InitGeneratedPoolOnce(); - return generated_pool_; -} - -DescriptorPool* DescriptorPool::internal_generated_pool() { - InitGeneratedPoolOnce(); - return generated_pool_; -} - -void DescriptorPool::InternalAddGeneratedFile( - const void* encoded_file_descriptor, int size) { - // So, this function is called in the process of initializing the - // descriptors for generated proto classes. Each generated .pb.cc file - // has an internal procedure called AddDescriptors() which is called at - // process startup, and that function calls this one in order to register - // the raw bytes of the FileDescriptorProto representing the file. - // - // We do not actually construct the descriptor objects right away. We just - // hang on to the bytes until they are actually needed. We actually construct - // the descriptor the first time one of the following things happens: - // * Someone calls a method like descriptor(), GetDescriptor(), or - // GetReflection() on the generated types, which requires returning the - // descriptor or an object based on it. - // * Someone looks up the descriptor in DescriptorPool::generated_pool(). - // - // Once one of these happens, the DescriptorPool actually parses the - // FileDescriptorProto and generates a FileDescriptor (and all its children) - // based on it. - // - // Note that FileDescriptorProto is itself a generated protocol message. - // Therefore, when we parse one, we have to be very careful to avoid using - // any descriptor-based operations, since this might cause infinite recursion - // or deadlock. - InitGeneratedPoolOnce(); - GOOGLE_CHECK(generated_database_->Add(encoded_file_descriptor, size)); -} - - -// Find*By* methods ================================================== - -// TODO(kenton): There's a lot of repeated code here, but I'm not sure if -// there's any good way to factor it out. Think about this some time when -// there's nothing more important to do (read: never). - -const FileDescriptor* DescriptorPool::FindFileByName(const string& name) const { - MutexLockMaybe lock(mutex_); - const FileDescriptor* result = tables_->FindFile(name); - if (result != NULL) return result; - if (underlay_ != NULL) { - const FileDescriptor* result = underlay_->FindFileByName(name); - if (result != NULL) return result; - } - if (TryFindFileInFallbackDatabase(name)) { - const FileDescriptor* result = tables_->FindFile(name); - if (result != NULL) return result; - } - return NULL; -} - -const FileDescriptor* DescriptorPool::FindFileContainingSymbol( - const string& symbol_name) const { - MutexLockMaybe lock(mutex_); - Symbol result = tables_->FindSymbol(symbol_name); - if (!result.IsNull()) return result.GetFile(); - if (underlay_ != NULL) { - const FileDescriptor* result = - underlay_->FindFileContainingSymbol(symbol_name); - if (result != NULL) return result; - } - if (TryFindSymbolInFallbackDatabase(symbol_name)) { - Symbol result = tables_->FindSymbol(symbol_name); - if (!result.IsNull()) return result.GetFile(); - } - return NULL; -} - -const Descriptor* DescriptorPool::FindMessageTypeByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::MESSAGE) ? result.descriptor : NULL; -} - -const FieldDescriptor* DescriptorPool::FindFieldByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - if (result.type == Symbol::FIELD && - !result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* DescriptorPool::FindExtensionByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - if (result.type == Symbol::FIELD && - result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const EnumDescriptor* DescriptorPool::FindEnumTypeByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::ENUM) ? result.enum_descriptor : NULL; -} - -const EnumValueDescriptor* DescriptorPool::FindEnumValueByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::ENUM_VALUE) ? - result.enum_value_descriptor : NULL; -} - -const ServiceDescriptor* DescriptorPool::FindServiceByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::SERVICE) ? result.service_descriptor : NULL; -} - -const MethodDescriptor* DescriptorPool::FindMethodByName( - const string& name) const { - Symbol result = tables_->FindByNameHelper(this, name); - return (result.type == Symbol::METHOD) ? result.method_descriptor : NULL; -} - -const FieldDescriptor* DescriptorPool::FindExtensionByNumber( - const Descriptor* extendee, int number) const { - MutexLockMaybe lock(mutex_); - const FieldDescriptor* result = tables_->FindExtension(extendee, number); - if (result != NULL) { - return result; - } - if (underlay_ != NULL) { - const FieldDescriptor* result = - underlay_->FindExtensionByNumber(extendee, number); - if (result != NULL) return result; - } - if (TryFindExtensionInFallbackDatabase(extendee, number)) { - const FieldDescriptor* result = tables_->FindExtension(extendee, number); - if (result != NULL) { - return result; - } - } - return NULL; -} - -void DescriptorPool::FindAllExtensions( - const Descriptor* extendee, vector* out) const { - MutexLockMaybe lock(mutex_); - - // Initialize tables_->extensions_ from the fallback database first - // (but do this only once per descriptor). - if (fallback_database_ != NULL && - tables_->extensions_loaded_from_db_.count(extendee) == 0) { - vector numbers; - if (fallback_database_->FindAllExtensionNumbers(extendee->full_name(), - &numbers)) { - for (int i = 0; i < numbers.size(); ++i) { - int number = numbers[i]; - if (tables_->FindExtension(extendee, number) == NULL) { - TryFindExtensionInFallbackDatabase(extendee, number); - } - } - tables_->extensions_loaded_from_db_.insert(extendee); - } - } - - tables_->FindAllExtensions(extendee, out); - if (underlay_ != NULL) { - underlay_->FindAllExtensions(extendee, out); - } -} - -// ------------------------------------------------------------------- - -const FieldDescriptor* -Descriptor::FindFieldByNumber(int key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByNumber(this, key); - if (result == NULL || result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindFieldByLowercaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByLowercaseName(this, key); - if (result == NULL || result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindFieldByCamelcaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByCamelcaseName(this, key); - if (result == NULL || result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindFieldByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); - if (!result.IsNull() && !result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -Descriptor::FindExtensionByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); - if (!result.IsNull() && result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -Descriptor::FindExtensionByLowercaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByLowercaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -Descriptor::FindExtensionByCamelcaseName(const string& key) const { - const FieldDescriptor* result = - file()->tables_->FindFieldByCamelcaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const Descriptor* -Descriptor::FindNestedTypeByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); - if (!result.IsNull()) { - return result.descriptor; - } else { - return NULL; - } -} - -const EnumDescriptor* -Descriptor::FindEnumTypeByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); - if (!result.IsNull()) { - return result.enum_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -Descriptor::FindEnumValueByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); - if (!result.IsNull()) { - return result.enum_value_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -EnumDescriptor::FindValueByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); - if (!result.IsNull()) { - return result.enum_value_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -EnumDescriptor::FindValueByNumber(int key) const { - return file()->tables_->FindEnumValueByNumber(this, key); -} - -const MethodDescriptor* -ServiceDescriptor::FindMethodByName(const string& key) const { - Symbol result = - file()->tables_->FindNestedSymbolOfType(this, key, Symbol::METHOD); - if (!result.IsNull()) { - return result.method_descriptor; - } else { - return NULL; - } -} - -const Descriptor* -FileDescriptor::FindMessageTypeByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::MESSAGE); - if (!result.IsNull()) { - return result.descriptor; - } else { - return NULL; - } -} - -const EnumDescriptor* -FileDescriptor::FindEnumTypeByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM); - if (!result.IsNull()) { - return result.enum_descriptor; - } else { - return NULL; - } -} - -const EnumValueDescriptor* -FileDescriptor::FindEnumValueByName(const string& key) const { - Symbol result = - tables_->FindNestedSymbolOfType(this, key, Symbol::ENUM_VALUE); - if (!result.IsNull()) { - return result.enum_value_descriptor; - } else { - return NULL; - } -} - -const ServiceDescriptor* -FileDescriptor::FindServiceByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::SERVICE); - if (!result.IsNull()) { - return result.service_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -FileDescriptor::FindExtensionByName(const string& key) const { - Symbol result = tables_->FindNestedSymbolOfType(this, key, Symbol::FIELD); - if (!result.IsNull() && result.field_descriptor->is_extension()) { - return result.field_descriptor; - } else { - return NULL; - } -} - -const FieldDescriptor* -FileDescriptor::FindExtensionByLowercaseName(const string& key) const { - const FieldDescriptor* result = tables_->FindFieldByLowercaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -const FieldDescriptor* -FileDescriptor::FindExtensionByCamelcaseName(const string& key) const { - const FieldDescriptor* result = tables_->FindFieldByCamelcaseName(this, key); - if (result == NULL || !result->is_extension()) { - return NULL; - } else { - return result; - } -} - -bool Descriptor::IsExtensionNumber(int number) const { - // Linear search should be fine because we don't expect a message to have - // more than a couple extension ranges. - for (int i = 0; i < extension_range_count(); i++) { - if (number >= extension_range(i)->start && - number < extension_range(i)->end) { - return true; - } - } - return false; -} - -// ------------------------------------------------------------------- - -bool DescriptorPool::TryFindFileInFallbackDatabase(const string& name) const { - if (fallback_database_ == NULL) return false; - - if (tables_->known_bad_files_.count(name) > 0) return false; - - FileDescriptorProto file_proto; - if (!fallback_database_->FindFileByName(name, &file_proto) || - BuildFileFromDatabase(file_proto) == NULL) { - tables_->known_bad_files_.insert(name); - return false; - } - - return true; -} - -bool DescriptorPool::TryFindSymbolInFallbackDatabase(const string& name) const { - if (fallback_database_ == NULL) return false; - - FileDescriptorProto file_proto; - if (!fallback_database_->FindFileContainingSymbol(name, &file_proto)) { - return false; - } - - if (tables_->FindFile(file_proto.name()) != NULL) { - // We've already loaded this file, and it apparently doesn't contain the - // symbol we're looking for. Some DescriptorDatabases return false - // positives. - return false; - } - - if (BuildFileFromDatabase(file_proto) == NULL) { - return false; - } - - return true; -} - -bool DescriptorPool::TryFindExtensionInFallbackDatabase( - const Descriptor* containing_type, int field_number) const { - if (fallback_database_ == NULL) return false; - - FileDescriptorProto file_proto; - if (!fallback_database_->FindFileContainingExtension( - containing_type->full_name(), field_number, &file_proto)) { - return false; - } - - if (tables_->FindFile(file_proto.name()) != NULL) { - // We've already loaded this file, and it apparently doesn't contain the - // extension we're looking for. Some DescriptorDatabases return false - // positives. - return false; - } - - if (BuildFileFromDatabase(file_proto) == NULL) { - return false; - } - - return true; -} - -// =================================================================== - -string FieldDescriptor::DefaultValueAsString(bool quote_string_type) const { - GOOGLE_CHECK(has_default_value()) << "No default value"; - switch (cpp_type()) { - case CPPTYPE_INT32: - return SimpleItoa(default_value_int32()); - break; - case CPPTYPE_INT64: - return SimpleItoa(default_value_int64()); - break; - case CPPTYPE_UINT32: - return SimpleItoa(default_value_uint32()); - break; - case CPPTYPE_UINT64: - return SimpleItoa(default_value_uint64()); - break; - case CPPTYPE_FLOAT: - return SimpleFtoa(default_value_float()); - break; - case CPPTYPE_DOUBLE: - return SimpleDtoa(default_value_double()); - break; - case CPPTYPE_BOOL: - return default_value_bool() ? "true" : "false"; - break; - case CPPTYPE_STRING: - if (quote_string_type) { - return "\"" + CEscape(default_value_string()) + "\""; - } else { - if (type() == TYPE_BYTES) { - return CEscape(default_value_string()); - } else { - return default_value_string(); - } - } - break; - case CPPTYPE_ENUM: - return default_value_enum()->name(); - break; - case CPPTYPE_MESSAGE: - GOOGLE_LOG(DFATAL) << "Messages can't have default values!"; - break; - } - GOOGLE_LOG(FATAL) << "Can't get here: failed to get default value as string"; - return ""; -} - -// CopyTo methods ==================================================== - -void FileDescriptor::CopyTo(FileDescriptorProto* proto) const { - proto->set_name(name()); - if (!package().empty()) proto->set_package(package()); - - for (int i = 0; i < dependency_count(); i++) { - proto->add_dependency(dependency(i)->name()); - } - - for (int i = 0; i < message_type_count(); i++) { - message_type(i)->CopyTo(proto->add_message_type()); - } - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->CopyTo(proto->add_enum_type()); - } - for (int i = 0; i < service_count(); i++) { - service(i)->CopyTo(proto->add_service()); - } - for (int i = 0; i < extension_count(); i++) { - extension(i)->CopyTo(proto->add_extension()); - } - - if (&options() != &FileOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void Descriptor::CopyTo(DescriptorProto* proto) const { - proto->set_name(name()); - - for (int i = 0; i < field_count(); i++) { - field(i)->CopyTo(proto->add_field()); - } - for (int i = 0; i < nested_type_count(); i++) { - nested_type(i)->CopyTo(proto->add_nested_type()); - } - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->CopyTo(proto->add_enum_type()); - } - for (int i = 0; i < extension_range_count(); i++) { - DescriptorProto::ExtensionRange* range = proto->add_extension_range(); - range->set_start(extension_range(i)->start); - range->set_end(extension_range(i)->end); - } - for (int i = 0; i < extension_count(); i++) { - extension(i)->CopyTo(proto->add_extension()); - } - - if (&options() != &MessageOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void FieldDescriptor::CopyTo(FieldDescriptorProto* proto) const { - proto->set_name(name()); - proto->set_number(number()); - - // Some compilers do not allow static_cast directly between two enum types, - // so we must cast to int first. - proto->set_label(static_cast( - implicit_cast(label()))); - proto->set_type(static_cast( - implicit_cast(type()))); - - if (is_extension()) { - if (!containing_type()->is_unqualified_placeholder_) { - proto->set_extendee("."); - } - proto->mutable_extendee()->append(containing_type()->full_name()); - } - - if (cpp_type() == CPPTYPE_MESSAGE) { - if (message_type()->is_placeholder_) { - // We don't actually know if the type is a message type. It could be - // an enum. - proto->clear_type(); - } - - if (!message_type()->is_unqualified_placeholder_) { - proto->set_type_name("."); - } - proto->mutable_type_name()->append(message_type()->full_name()); - } else if (cpp_type() == CPPTYPE_ENUM) { - if (!enum_type()->is_unqualified_placeholder_) { - proto->set_type_name("."); - } - proto->mutable_type_name()->append(enum_type()->full_name()); - } - - if (has_default_value()) { - proto->set_default_value(DefaultValueAsString(false)); - } - - if (&options() != &FieldOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void EnumDescriptor::CopyTo(EnumDescriptorProto* proto) const { - proto->set_name(name()); - - for (int i = 0; i < value_count(); i++) { - value(i)->CopyTo(proto->add_value()); - } - - if (&options() != &EnumOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void EnumValueDescriptor::CopyTo(EnumValueDescriptorProto* proto) const { - proto->set_name(name()); - proto->set_number(number()); - - if (&options() != &EnumValueOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void ServiceDescriptor::CopyTo(ServiceDescriptorProto* proto) const { - proto->set_name(name()); - - for (int i = 0; i < method_count(); i++) { - method(i)->CopyTo(proto->add_method()); - } - - if (&options() != &ServiceOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -void MethodDescriptor::CopyTo(MethodDescriptorProto* proto) const { - proto->set_name(name()); - - if (!input_type()->is_unqualified_placeholder_) { - proto->set_input_type("."); - } - proto->mutable_input_type()->append(input_type()->full_name()); - - if (!output_type()->is_unqualified_placeholder_) { - proto->set_output_type("."); - } - proto->mutable_output_type()->append(output_type()->full_name()); - - if (&options() != &MethodOptions::default_instance()) { - proto->mutable_options()->CopyFrom(options()); - } -} - -// DebugString methods =============================================== - -namespace { - -// Used by each of the option formatters. -bool RetrieveOptions(const Message &options, vector *option_entries) { - option_entries->clear(); - const Reflection* reflection = options.GetReflection(); - vector fields; - reflection->ListFields(options, &fields); - for (int i = 0; i < fields.size(); i++) { - // Doesn't make sense to have message type fields here - if (fields[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - continue; - } - int count = 1; - bool repeated = false; - if (fields[i]->is_repeated()) { - count = reflection->FieldSize(options, fields[i]); - repeated = true; - } - for (int j = 0; j < count; j++) { - string fieldval; - TextFormat::PrintFieldValueToString(options, fields[i], - repeated ? count : -1, &fieldval); - option_entries->push_back(fields[i]->name() + " = " + fieldval); - } - } - return !option_entries->empty(); -} - -// Formats options that all appear together in brackets. Does not include -// brackets. -bool FormatBracketedOptions(const Message &options, string *output) { - vector all_options; - if (RetrieveOptions(options, &all_options)) { - output->append(JoinStrings(all_options, ", ")); - } - return !all_options.empty(); -} - -// Formats options one per line -bool FormatLineOptions(int depth, const Message &options, string *output) { - string prefix(depth * 2, ' '); - vector all_options; - if (RetrieveOptions(options, &all_options)) { - for (int i = 0; i < all_options.size(); i++) { - strings::SubstituteAndAppend(output, "$0option $1;\n", - prefix, all_options[i]); - } - } - return !all_options.empty(); -} - -} // anonymous namespace - -string FileDescriptor::DebugString() const { - string contents = "syntax = \"proto2\";\n\n"; - - for (int i = 0; i < dependency_count(); i++) { - strings::SubstituteAndAppend(&contents, "import \"$0\";\n", - dependency(i)->name()); - } - - if (!package().empty()) { - strings::SubstituteAndAppend(&contents, "package $0;\n\n", package()); - } - - if (FormatLineOptions(0, options(), &contents)) { - contents.append("\n"); // add some space if we had options - } - - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->DebugString(0, &contents); - contents.append("\n"); - } - - // Find all the 'group' type extensions; we will not output their nested - // definitions (those will be done with their group field descriptor). - set groups; - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(extension(i)->message_type()); - } - } - - for (int i = 0; i < message_type_count(); i++) { - if (groups.count(message_type(i)) == 0) { - strings::SubstituteAndAppend(&contents, "message $0", - message_type(i)->name()); - message_type(i)->DebugString(0, &contents); - contents.append("\n"); - } - } - - for (int i = 0; i < service_count(); i++) { - service(i)->DebugString(&contents); - contents.append("\n"); - } - - const Descriptor* containing_type = NULL; - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->containing_type() != containing_type) { - if (i > 0) contents.append("}\n\n"); - containing_type = extension(i)->containing_type(); - strings::SubstituteAndAppend(&contents, "extend .$0 {\n", - containing_type->full_name()); - } - extension(i)->DebugString(1, &contents); - } - if (extension_count() > 0) contents.append("}\n\n"); - - return contents; -} - -string Descriptor::DebugString() const { - string contents; - strings::SubstituteAndAppend(&contents, "message $0", name()); - DebugString(0, &contents); - return contents; -} - -void Descriptor::DebugString(int depth, string *contents) const { - string prefix(depth * 2, ' '); - ++depth; - contents->append(" {\n"); - - FormatLineOptions(depth, options(), contents); - - // Find all the 'group' types for fields and extensions; we will not output - // their nested definitions (those will be done with their group field - // descriptor). - set groups; - for (int i = 0; i < field_count(); i++) { - if (field(i)->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(field(i)->message_type()); - } - } - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->type() == FieldDescriptor::TYPE_GROUP) { - groups.insert(extension(i)->message_type()); - } - } - - for (int i = 0; i < nested_type_count(); i++) { - if (groups.count(nested_type(i)) == 0) { - strings::SubstituteAndAppend(contents, "$0 message $1", - prefix, nested_type(i)->name()); - nested_type(i)->DebugString(depth, contents); - } - } - for (int i = 0; i < enum_type_count(); i++) { - enum_type(i)->DebugString(depth, contents); - } - for (int i = 0; i < field_count(); i++) { - field(i)->DebugString(depth, contents); - } - - for (int i = 0; i < extension_range_count(); i++) { - strings::SubstituteAndAppend(contents, "$0 extensions $1 to $2;\n", - prefix, - extension_range(i)->start, - extension_range(i)->end - 1); - } - - // Group extensions by what they extend, so they can be printed out together. - const Descriptor* containing_type = NULL; - for (int i = 0; i < extension_count(); i++) { - if (extension(i)->containing_type() != containing_type) { - if (i > 0) strings::SubstituteAndAppend(contents, "$0 }\n", prefix); - containing_type = extension(i)->containing_type(); - strings::SubstituteAndAppend(contents, "$0 extend .$1 {\n", - prefix, containing_type->full_name()); - } - extension(i)->DebugString(depth + 1, contents); - } - if (extension_count() > 0) - strings::SubstituteAndAppend(contents, "$0 }\n", prefix); - - strings::SubstituteAndAppend(contents, "$0}\n", prefix); -} - -string FieldDescriptor::DebugString() const { - string contents; - int depth = 0; - if (is_extension()) { - strings::SubstituteAndAppend(&contents, "extend .$0 {\n", - containing_type()->full_name()); - depth = 1; - } - DebugString(depth, &contents); - if (is_extension()) { - contents.append("}\n"); - } - return contents; -} - -void FieldDescriptor::DebugString(int depth, string *contents) const { - string prefix(depth * 2, ' '); - string field_type; - switch (type()) { - case TYPE_MESSAGE: - field_type = "." + message_type()->full_name(); - break; - case TYPE_ENUM: - field_type = "." + enum_type()->full_name(); - break; - default: - field_type = kTypeToName[type()]; - } - - strings::SubstituteAndAppend(contents, "$0$1 $2 $3 = $4", - prefix, - kLabelToName[label()], - field_type, - type() == TYPE_GROUP ? message_type()->name() : - name(), - number()); - - bool bracketed = false; - if (has_default_value()) { - bracketed = true; - strings::SubstituteAndAppend(contents, " [default = $0", - DefaultValueAsString(true)); - } - - string formatted_options; - if (FormatBracketedOptions(options(), &formatted_options)) { - contents->append(bracketed ? ", " : " ["); - bracketed = true; - contents->append(formatted_options); - } - - if (bracketed) { - contents->append("]"); - } - - if (type() == TYPE_GROUP) { - message_type()->DebugString(depth, contents); - } else { - contents->append(";\n"); - } -} - -string EnumDescriptor::DebugString() const { - string contents; - DebugString(0, &contents); - return contents; -} - -void EnumDescriptor::DebugString(int depth, string *contents) const { - string prefix(depth * 2, ' '); - ++depth; - strings::SubstituteAndAppend(contents, "$0enum $1 {\n", - prefix, name()); - - FormatLineOptions(depth, options(), contents); - - for (int i = 0; i < value_count(); i++) { - value(i)->DebugString(depth, contents); - } - strings::SubstituteAndAppend(contents, "$0}\n", prefix); -} - -string EnumValueDescriptor::DebugString() const { - string contents; - DebugString(0, &contents); - return contents; -} - -void EnumValueDescriptor::DebugString(int depth, string *contents) const { - string prefix(depth * 2, ' '); - strings::SubstituteAndAppend(contents, "$0$1 = $2", - prefix, name(), number()); - - string formatted_options; - if (FormatBracketedOptions(options(), &formatted_options)) { - strings::SubstituteAndAppend(contents, " [$0]", formatted_options); - } - contents->append(";\n"); -} - -string ServiceDescriptor::DebugString() const { - string contents; - DebugString(&contents); - return contents; -} - -void ServiceDescriptor::DebugString(string *contents) const { - strings::SubstituteAndAppend(contents, "service $0 {\n", name()); - - FormatLineOptions(1, options(), contents); - - for (int i = 0; i < method_count(); i++) { - method(i)->DebugString(1, contents); - } - - contents->append("}\n"); -} - -string MethodDescriptor::DebugString() const { - string contents; - DebugString(0, &contents); - return contents; -} - -void MethodDescriptor::DebugString(int depth, string *contents) const { - string prefix(depth * 2, ' '); - ++depth; - strings::SubstituteAndAppend(contents, "$0rpc $1(.$2) returns (.$3)", - prefix, name(), - input_type()->full_name(), - output_type()->full_name()); - - string formatted_options; - if (FormatLineOptions(depth, options(), &formatted_options)) { - strings::SubstituteAndAppend(contents, " {\n$0$1}\n", - formatted_options, prefix); - } else { - contents->append(";\n"); - } -} -// =================================================================== - -namespace { - -// Represents an options message to interpret. Extension names in the option -// name are respolved relative to name_scope. element_name and orig_opt are -// used only for error reporting (since the parser records locations against -// pointers in the original options, not the mutable copy). The Message must be -// one of the Options messages in descriptor.proto. -struct OptionsToInterpret { - OptionsToInterpret(const string& ns, - const string& el, - const Message* orig_opt, - Message* opt) - : name_scope(ns), - element_name(el), - original_options(orig_opt), - options(opt) { - } - string name_scope; - string element_name; - const Message* original_options; - Message* options; -}; - -} // namespace - -class DescriptorBuilder { - public: - DescriptorBuilder(const DescriptorPool* pool, - DescriptorPool::Tables* tables, - DescriptorPool::ErrorCollector* error_collector); - ~DescriptorBuilder(); - - const FileDescriptor* BuildFile(const FileDescriptorProto& proto); - - private: - friend class OptionInterpreter; - - const DescriptorPool* pool_; - DescriptorPool::Tables* tables_; // for convenience - DescriptorPool::ErrorCollector* error_collector_; - - // As we build descriptors we store copies of the options messages in - // them. We put pointers to those copies in this vector, as we build, so we - // can later (after cross-linking) interpret those options. - vector options_to_interpret_; - - bool had_errors_; - string filename_; - FileDescriptor* file_; - FileDescriptorTables* file_tables_; - - // If LookupSymbol() finds a symbol that is in a file which is not a declared - // dependency of this file, it will fail, but will set - // possible_undeclared_dependency_ to point at that file. This is only used - // by AddNotDefinedError() to report a more useful error message. - // possible_undeclared_dependency_name_ is the name of the symbol that was - // actually found in possible_undeclared_dependency_, which may be a parent - // of the symbol actually looked for. - const FileDescriptor* possible_undeclared_dependency_; - string possible_undeclared_dependency_name_; - - void AddError(const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error); - - // Adds an error indicating that undefined_symbol was not defined. Must - // only be called after LookupSymbol() fails. - void AddNotDefinedError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& undefined_symbol); - - // Silly helper which determines if the given file is in the given package. - // I.e., either file->package() == package_name or file->package() is a - // nested package within package_name. - bool IsInPackage(const FileDescriptor* file, const string& package_name); - - // Like tables_->FindSymbol(), but additionally: - // - Search the pool's underlay if not found in tables_. - // - Insure that the resulting Symbol is from one of the file's declared - // dependencies. - Symbol FindSymbol(const string& name); - - // Like FindSymbol() but does not require that the symbol is in one of the - // file's declared dependencies. - Symbol FindSymbolNotEnforcingDeps(const string& name); - - // Like FindSymbol(), but looks up the name relative to some other symbol - // name. This first searches siblings of relative_to, then siblings of its - // parents, etc. For example, LookupSymbol("foo.bar", "baz.qux.corge") makes - // the following calls, returning the first non-null result: - // FindSymbol("baz.qux.foo.bar"), FindSymbol("baz.foo.bar"), - // FindSymbol("foo.bar"). If AllowUnknownDependencies() has been called - // on the DescriptorPool, this will generate a placeholder type if - // the name is not found (unless the name itself is malformed). The - // placeholder_type parameter indicates what kind of placeholder should be - // constructed in this case. The resolve_mode parameter determines whether - // any symbol is returned, or only symbols that are types. Note, however, - // that LookupSymbol may still return a non-type symbol in LOOKUP_TYPES mode, - // if it believes that's all it could refer to. The caller should always - // check that it receives the type of symbol it was expecting. - enum PlaceholderType { - PLACEHOLDER_MESSAGE, - PLACEHOLDER_ENUM, - PLACEHOLDER_EXTENDABLE_MESSAGE - }; - enum ResolveMode { - LOOKUP_ALL, LOOKUP_TYPES - }; - Symbol LookupSymbol(const string& name, const string& relative_to, - PlaceholderType placeholder_type = PLACEHOLDER_MESSAGE, - ResolveMode resolve_mode = LOOKUP_ALL); - - // Like LookupSymbol() but will not return a placeholder even if - // AllowUnknownDependencies() has been used. - Symbol LookupSymbolNoPlaceholder(const string& name, - const string& relative_to, - ResolveMode resolve_mode = LOOKUP_ALL); - - // Creates a placeholder type suitable for return from LookupSymbol(). May - // return kNullSymbol if the name is not a valid type name. - Symbol NewPlaceholder(const string& name, PlaceholderType placeholder_type); - - // Creates a placeholder file. Never returns NULL. This is used when an - // import is not found and AllowUnknownDependencies() is enabled. - const FileDescriptor* NewPlaceholderFile(const string& name); - - // Calls tables_->AddSymbol() and records an error if it fails. Returns - // true if successful or false if failed, though most callers can ignore - // the return value since an error has already been recorded. - bool AddSymbol(const string& full_name, - const void* parent, const string& name, - const Message& proto, Symbol symbol); - - // Like AddSymbol(), but succeeds if the symbol is already defined as long - // as the existing definition is also a package (because it's OK to define - // the same package in two different files). Also adds all parents of the - // packgae to the symbol table (e.g. AddPackage("foo.bar", ...) will add - // "foo.bar" and "foo" to the table). - void AddPackage(const string& name, const Message& proto, - const FileDescriptor* file); - - // Checks that the symbol name contains only alphanumeric characters and - // underscores. Records an error otherwise. - void ValidateSymbolName(const string& name, const string& full_name, - const Message& proto); - - // Like ValidateSymbolName(), but the name is allowed to contain periods and - // an error is indicated by returning false (not recording the error). - bool ValidateQualifiedName(const string& name); - - // Used by BUILD_ARRAY macro (below) to avoid having to have the type - // specified as a macro parameter. - template - inline void AllocateArray(int size, Type** output) { - *output = tables_->AllocateArray(size); - } - - // Allocates a copy of orig_options in tables_ and stores it in the - // descriptor. Remembers its uninterpreted options, to be interpreted - // later. DescriptorT must be one of the Descriptor messages from - // descriptor.proto. - template void AllocateOptions( - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor); - // Specialization for FileOptions. - void AllocateOptions(const FileOptions& orig_options, - FileDescriptor* descriptor); - - // Implementation for AllocateOptions(). Don't call this directly. - template void AllocateOptionsImpl( - const string& name_scope, - const string& element_name, - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor); - - // These methods all have the same signature for the sake of the BUILD_ARRAY - // macro, below. - void BuildMessage(const DescriptorProto& proto, - const Descriptor* parent, - Descriptor* result); - void BuildFieldOrExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result, - bool is_extension); - void BuildField(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result) { - BuildFieldOrExtension(proto, parent, result, false); - } - void BuildExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result) { - BuildFieldOrExtension(proto, parent, result, true); - } - void BuildExtensionRange(const DescriptorProto::ExtensionRange& proto, - const Descriptor* parent, - Descriptor::ExtensionRange* result); - void BuildEnum(const EnumDescriptorProto& proto, - const Descriptor* parent, - EnumDescriptor* result); - void BuildEnumValue(const EnumValueDescriptorProto& proto, - const EnumDescriptor* parent, - EnumValueDescriptor* result); - void BuildService(const ServiceDescriptorProto& proto, - const void* dummy, - ServiceDescriptor* result); - void BuildMethod(const MethodDescriptorProto& proto, - const ServiceDescriptor* parent, - MethodDescriptor* result); - - // Must be run only after building. - // - // NOTE: Options will not be available during cross-linking, as they - // have not yet been interpreted. Defer any handling of options to the - // Validate*Options methods. - void CrossLinkFile(FileDescriptor* file, const FileDescriptorProto& proto); - void CrossLinkMessage(Descriptor* message, const DescriptorProto& proto); - void CrossLinkField(FieldDescriptor* field, - const FieldDescriptorProto& proto); - void CrossLinkEnum(EnumDescriptor* enum_type, - const EnumDescriptorProto& proto); - void CrossLinkEnumValue(EnumValueDescriptor* enum_value, - const EnumValueDescriptorProto& proto); - void CrossLinkService(ServiceDescriptor* service, - const ServiceDescriptorProto& proto); - void CrossLinkMethod(MethodDescriptor* method, - const MethodDescriptorProto& proto); - - // Must be run only after cross-linking. - void InterpretOptions(); - - // A helper class for interpreting options. - class OptionInterpreter { - public: - // Creates an interpreter that operates in the context of the pool of the - // specified builder, which must not be NULL. We don't take ownership of the - // builder. - explicit OptionInterpreter(DescriptorBuilder* builder); - - ~OptionInterpreter(); - - // Interprets the uninterpreted options in the specified Options message. - // On error, calls AddError() on the underlying builder and returns false. - // Otherwise returns true. - bool InterpretOptions(OptionsToInterpret* options_to_interpret); - - private: - // Interprets uninterpreted_option_ on the specified message, which - // must be the mutable copy of the original options message to which - // uninterpreted_option_ belongs. - bool InterpretSingleOption(Message* options); - - // Adds the uninterpreted_option to the given options message verbatim. - // Used when AllowUnknownDependencies() is in effect and we can't find - // the option's definition. - void AddWithoutInterpreting(const UninterpretedOption& uninterpreted_option, - Message* options); - - // A recursive helper function that drills into the intermediate fields - // in unknown_fields to check if field innermost_field is set on the - // innermost message. Returns false and sets an error if so. - bool ExamineIfOptionIsSet( - vector::const_iterator intermediate_fields_iter, - vector::const_iterator intermediate_fields_end, - const FieldDescriptor* innermost_field, const string& debug_msg_name, - const UnknownFieldSet& unknown_fields); - - // Validates the value for the option field of the currently interpreted - // option and then sets it on the unknown_field. - bool SetOptionValue(const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields); - - // Convenience functions to set an int field the right way, depending on - // its wire type (a single int CppType can represent multiple wire types). - void SetInt32(int number, int32 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - void SetInt64(int number, int64 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - void SetUInt32(int number, uint32 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - void SetUInt64(int number, uint64 value, FieldDescriptor::Type type, - UnknownFieldSet* unknown_fields); - - // A helper function that adds an error at the specified location of the - // option we're currently interpreting, and returns false. - bool AddOptionError(DescriptorPool::ErrorCollector::ErrorLocation location, - const string& msg) { - builder_->AddError(options_to_interpret_->element_name, - *uninterpreted_option_, location, msg); - return false; - } - - // A helper function that adds an error at the location of the option name - // and returns false. - bool AddNameError(const string& msg) { - return AddOptionError(DescriptorPool::ErrorCollector::OPTION_NAME, msg); - } - - // A helper function that adds an error at the location of the option name - // and returns false. - bool AddValueError(const string& msg) { - return AddOptionError(DescriptorPool::ErrorCollector::OPTION_VALUE, msg); - } - - // We interpret against this builder's pool. Is never NULL. We don't own - // this pointer. - DescriptorBuilder* builder_; - - // The options we're currently interpreting, or NULL if we're not in a call - // to InterpretOptions. - const OptionsToInterpret* options_to_interpret_; - - // The option we're currently interpreting within options_to_interpret_, or - // NULL if we're not in a call to InterpretOptions(). This points to a - // submessage of the original option, not the mutable copy. Therefore we - // can use it to find locations recorded by the parser. - const UninterpretedOption* uninterpreted_option_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OptionInterpreter); - }; - - // Work-around for broken compilers: According to the C++ standard, - // OptionInterpreter should have access to the private members of any class - // which has declared DescriptorBuilder as a friend. Unfortunately some old - // versions of GCC and other compilers do not implement this correctly. So, - // we have to have these intermediate methods to provide access. We also - // redundantly declare OptionInterpreter a friend just to make things extra - // clear for these bad compilers. - friend class OptionInterpreter; - static inline bool get_allow_unknown(const DescriptorPool* pool) { - return pool->allow_unknown_; - } - static inline bool get_is_placeholder(const Descriptor* descriptor) { - return descriptor->is_placeholder_; - } - - // Must be run only after options have been interpreted. - // - // NOTE: Validation code must only reference the options in the mutable - // descriptors, which are the ones that have been interpreted. The const - // proto references are passed in only so they can be provided to calls to - // AddError(). Do not look at their options, which have not been interpreted. - void ValidateFileOptions(FileDescriptor* file, - const FileDescriptorProto& proto); - void ValidateMessageOptions(Descriptor* message, - const DescriptorProto& proto); - void ValidateFieldOptions(FieldDescriptor* field, - const FieldDescriptorProto& proto); - void ValidateEnumOptions(EnumDescriptor* enm, - const EnumDescriptorProto& proto); - void ValidateEnumValueOptions(EnumValueDescriptor* enum_value, - const EnumValueDescriptorProto& proto); - void ValidateServiceOptions(ServiceDescriptor* service, - const ServiceDescriptorProto& proto); - void ValidateMethodOptions(MethodDescriptor* method, - const MethodDescriptorProto& proto); - - void ValidateMapKey(FieldDescriptor* field, - const FieldDescriptorProto& proto); -}; - -const FileDescriptor* DescriptorPool::BuildFile( - const FileDescriptorProto& proto) { - GOOGLE_CHECK(fallback_database_ == NULL) - << "Cannot call BuildFile on a DescriptorPool that uses a " - "DescriptorDatabase. You must instead find a way to get your file " - "into the underlying database."; - GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. - return DescriptorBuilder(this, tables_.get(), NULL).BuildFile(proto); -} - -const FileDescriptor* DescriptorPool::BuildFileCollectingErrors( - const FileDescriptorProto& proto, - ErrorCollector* error_collector) { - GOOGLE_CHECK(fallback_database_ == NULL) - << "Cannot call BuildFile on a DescriptorPool that uses a " - "DescriptorDatabase. You must instead find a way to get your file " - "into the underlying database."; - GOOGLE_CHECK(mutex_ == NULL); // Implied by the above GOOGLE_CHECK. - return DescriptorBuilder(this, tables_.get(), - error_collector).BuildFile(proto); -} - -const FileDescriptor* DescriptorPool::BuildFileFromDatabase( - const FileDescriptorProto& proto) const { - mutex_->AssertHeld(); - return DescriptorBuilder(this, tables_.get(), - default_error_collector_).BuildFile(proto); -} - -DescriptorBuilder::DescriptorBuilder( - const DescriptorPool* pool, - DescriptorPool::Tables* tables, - DescriptorPool::ErrorCollector* error_collector) - : pool_(pool), - tables_(tables), - error_collector_(error_collector), - had_errors_(false), - possible_undeclared_dependency_(NULL) {} - -DescriptorBuilder::~DescriptorBuilder() {} - -void DescriptorBuilder::AddError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& error) { - if (error_collector_ == NULL) { - if (!had_errors_) { - GOOGLE_LOG(ERROR) << "Invalid proto descriptor for file \"" << filename_ - << "\":"; - } - GOOGLE_LOG(ERROR) << " " << element_name << ": " << error; - } else { - error_collector_->AddError(filename_, element_name, - &descriptor, location, error); - } - had_errors_ = true; -} - -void DescriptorBuilder::AddNotDefinedError( - const string& element_name, - const Message& descriptor, - DescriptorPool::ErrorCollector::ErrorLocation location, - const string& undefined_symbol) { - if (possible_undeclared_dependency_ == NULL) { - AddError(element_name, descriptor, location, - "\"" + undefined_symbol + "\" is not defined."); - } else { - AddError(element_name, descriptor, location, - "\"" + possible_undeclared_dependency_name_ + - "\" seems to be defined in \"" + - possible_undeclared_dependency_->name() + "\", which is not " - "imported by \"" + filename_ + "\". To use it here, please " - "add the necessary import."); - } -} - -bool DescriptorBuilder::IsInPackage(const FileDescriptor* file, - const string& package_name) { - return HasPrefixString(file->package(), package_name) && - (file->package().size() == package_name.size() || - file->package()[package_name.size()] == '.'); -} - -Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const string& name) { - Symbol result; - - // We need to search our pool and all its underlays. - const DescriptorPool* pool = pool_; - while (true) { - // If we are looking at an underlay, we must lock its mutex_, since we are - // accessing the underlay's tables_ dircetly. - MutexLockMaybe lock((pool == pool_) ? NULL : pool->mutex_); - - // Note that we don't have to check fallback_database_ here because the - // symbol has to be in one of its file's direct dependencies, and we have - // already loaded those by the time we get here. - result = pool->tables_->FindSymbol(name); - if (!result.IsNull()) break; - if (pool->underlay_ == NULL) return kNullSymbol; - pool = pool->underlay_; - } - - return result; -} - -Symbol DescriptorBuilder::FindSymbol(const string& name) { - Symbol result = FindSymbolNotEnforcingDeps(name); - - if (!pool_->enforce_dependencies_) { - // Hack for CompilerUpgrader. - return result; - } - - // Only find symbols which were defined in this file or one of its - // dependencies. - const FileDescriptor* file = result.GetFile(); - if (file == file_) return result; - for (int i = 0; i < file_->dependency_count(); i++) { - if (file == file_->dependency(i)) return result; - } - - if (result.type == Symbol::PACKAGE) { - // Arg, this is overcomplicated. The symbol is a package name. It could - // be that the package was defined in multiple files. result.GetFile() - // returns the first file we saw that used this package. We've determined - // that that file is not a direct dependency of the file we are currently - // building, but it could be that some other file which *is* a direct - // dependency also defines the same package. We can't really rule out this - // symbol unless none of the dependencies define it. - if (IsInPackage(file_, name)) return result; - for (int i = 0; i < file_->dependency_count(); i++) { - // Note: A dependency may be NULL if it was not found or had errors. - if (file_->dependency(i) != NULL && - IsInPackage(file_->dependency(i), name)) { - return result; - } - } - } - - possible_undeclared_dependency_ = file; - possible_undeclared_dependency_name_ = name; - return kNullSymbol; -} - -Symbol DescriptorBuilder::LookupSymbolNoPlaceholder( - const string& name, const string& relative_to, ResolveMode resolve_mode) { - possible_undeclared_dependency_ = NULL; - - if (name.size() > 0 && name[0] == '.') { - // Fully-qualified name. - return FindSymbol(name.substr(1)); - } - - // If name is something like "Foo.Bar.baz", and symbols named "Foo" are - // defined in multiple parent scopes, we only want to find "Bar.baz" in the - // innermost one. E.g., the following should produce an error: - // message Bar { message Baz {} } - // message Foo { - // message Bar { - // } - // optional Bar.Baz baz = 1; - // } - // So, we look for just "Foo" first, then look for "Bar.baz" within it if - // found. - int name_dot_pos = name.find_first_of('.'); - string first_part_of_name; - if (name_dot_pos == string::npos) { - first_part_of_name = name; - } else { - first_part_of_name = name.substr(0, name_dot_pos); - } - - string scope_to_try(relative_to); - - while (true) { - // Chop off the last component of the scope. - string::size_type dot_pos = scope_to_try.find_last_of('.'); - if (dot_pos == string::npos) { - return FindSymbol(name); - } else { - scope_to_try.erase(dot_pos); - } - - // Append ".first_part_of_name" and try to find. - string::size_type old_size = scope_to_try.size(); - scope_to_try.append(1, '.'); - scope_to_try.append(first_part_of_name); - Symbol result = FindSymbol(scope_to_try); - if (!result.IsNull()) { - if (first_part_of_name.size() < name.size()) { - // name is a compound symbol, of which we only found the first part. - // Now try to look up the rest of it. - if (result.IsAggregate()) { - scope_to_try.append(name, first_part_of_name.size(), - name.size() - first_part_of_name.size()); - return FindSymbol(scope_to_try); - } else { - // We found a symbol but it's not an aggregate. Continue the loop. - } - } else { - if (resolve_mode == LOOKUP_TYPES && !result.IsType()) { - // We found a symbol but it's not a type. Continue the loop. - } else { - return result; - } - } - } - - // Not found. Remove the name so we can try again. - scope_to_try.erase(old_size); - } -} - -Symbol DescriptorBuilder::LookupSymbol( - const string& name, const string& relative_to, - PlaceholderType placeholder_type, ResolveMode resolve_mode) { - Symbol result = LookupSymbolNoPlaceholder( - name, relative_to, resolve_mode); - if (result.IsNull() && pool_->allow_unknown_) { - // Not found, but AllowUnknownDependencies() is enabled. Return a - // placeholder instead. - result = NewPlaceholder(name, placeholder_type); - } - return result; -} - -Symbol DescriptorBuilder::NewPlaceholder(const string& name, - PlaceholderType placeholder_type) { - // Compute names. - const string* placeholder_full_name; - const string* placeholder_name; - const string* placeholder_package; - - if (!ValidateQualifiedName(name)) return kNullSymbol; - if (name[0] == '.') { - // Fully-qualified. - placeholder_full_name = tables_->AllocateString(name.substr(1)); - } else { - placeholder_full_name = tables_->AllocateString(name); - } - - string::size_type dotpos = placeholder_full_name->find_last_of('.'); - if (dotpos != string::npos) { - placeholder_package = tables_->AllocateString( - placeholder_full_name->substr(0, dotpos)); - placeholder_name = tables_->AllocateString( - placeholder_full_name->substr(dotpos + 1)); - } else { - placeholder_package = &kEmptyString; - placeholder_name = placeholder_full_name; - } - - // Create the placeholders. - FileDescriptor* placeholder_file = tables_->Allocate(); - memset(placeholder_file, 0, sizeof(*placeholder_file)); - - placeholder_file->name_ = - tables_->AllocateString(*placeholder_full_name + ".placeholder.proto"); - placeholder_file->package_ = placeholder_package; - placeholder_file->pool_ = pool_; - placeholder_file->options_ = &FileOptions::default_instance(); - placeholder_file->tables_ = &FileDescriptorTables::kEmpty; - // All other fields are zero or NULL. - - if (placeholder_type == PLACEHOLDER_ENUM) { - placeholder_file->enum_type_count_ = 1; - placeholder_file->enum_types_ = - tables_->AllocateArray(1); - - EnumDescriptor* placeholder_enum = &placeholder_file->enum_types_[0]; - memset(placeholder_enum, 0, sizeof(*placeholder_enum)); - - placeholder_enum->full_name_ = placeholder_full_name; - placeholder_enum->name_ = placeholder_name; - placeholder_enum->file_ = placeholder_file; - placeholder_enum->options_ = &EnumOptions::default_instance(); - placeholder_enum->is_placeholder_ = true; - placeholder_enum->is_unqualified_placeholder_ = (name[0] != '.'); - - // Enums must have at least one value. - placeholder_enum->value_count_ = 1; - placeholder_enum->values_ = tables_->AllocateArray(1); - - EnumValueDescriptor* placeholder_value = &placeholder_enum->values_[0]; - memset(placeholder_value, 0, sizeof(*placeholder_value)); - - placeholder_value->name_ = tables_->AllocateString("PLACEHOLDER_VALUE"); - // Note that enum value names are siblings of their type, not children. - placeholder_value->full_name_ = - placeholder_package->empty() ? placeholder_value->name_ : - tables_->AllocateString(*placeholder_package + ".PLACEHOLDER_VALUE"); - - placeholder_value->number_ = 0; - placeholder_value->type_ = placeholder_enum; - placeholder_value->options_ = &EnumValueOptions::default_instance(); - - return Symbol(placeholder_enum); - } else { - placeholder_file->message_type_count_ = 1; - placeholder_file->message_types_ = - tables_->AllocateArray(1); - - Descriptor* placeholder_message = &placeholder_file->message_types_[0]; - memset(placeholder_message, 0, sizeof(*placeholder_message)); - - placeholder_message->full_name_ = placeholder_full_name; - placeholder_message->name_ = placeholder_name; - placeholder_message->file_ = placeholder_file; - placeholder_message->options_ = &MessageOptions::default_instance(); - placeholder_message->is_placeholder_ = true; - placeholder_message->is_unqualified_placeholder_ = (name[0] != '.'); - - if (placeholder_type == PLACEHOLDER_EXTENDABLE_MESSAGE) { - placeholder_message->extension_range_count_ = 1; - placeholder_message->extension_ranges_ = - tables_->AllocateArray(1); - placeholder_message->extension_ranges_->start = 1; - // kMaxNumber + 1 because ExtensionRange::end is exclusive. - placeholder_message->extension_ranges_->end = - FieldDescriptor::kMaxNumber + 1; - } - - return Symbol(placeholder_message); - } -} - -const FileDescriptor* DescriptorBuilder::NewPlaceholderFile( - const string& name) { - FileDescriptor* placeholder = tables_->Allocate(); - memset(placeholder, 0, sizeof(*placeholder)); - - placeholder->name_ = tables_->AllocateString(name); - placeholder->package_ = &kEmptyString; - placeholder->pool_ = pool_; - placeholder->options_ = &FileOptions::default_instance(); - placeholder->tables_ = &FileDescriptorTables::kEmpty; - // All other fields are zero or NULL. - - return placeholder; -} - -bool DescriptorBuilder::AddSymbol( - const string& full_name, const void* parent, const string& name, - const Message& proto, Symbol symbol) { - // If the caller passed NULL for the parent, the symbol is at file scope. - // Use its file as the parent instead. - if (parent == NULL) parent = file_; - - if (tables_->AddSymbol(full_name, symbol)) { - if (!file_tables_->AddAliasUnderParent(parent, name, symbol)) { - GOOGLE_LOG(DFATAL) << "\"" << full_name << "\" not previously defined in " - "symbols_by_name_, but was defined in symbols_by_parent_; " - "this shouldn't be possible."; - return false; - } - return true; - } else { - const FileDescriptor* other_file = tables_->FindSymbol(full_name).GetFile(); - if (other_file == file_) { - string::size_type dot_pos = full_name.find_last_of('.'); - if (dot_pos == string::npos) { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + full_name + "\" is already defined."); - } else { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + full_name.substr(dot_pos + 1) + - "\" is already defined in \"" + - full_name.substr(0, dot_pos) + "\"."); - } - } else { - // Symbol seems to have been defined in a different file. - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + full_name + "\" is already defined in file \"" + - other_file->name() + "\"."); - } - return false; - } -} - -void DescriptorBuilder::AddPackage( - const string& name, const Message& proto, const FileDescriptor* file) { - if (tables_->AddSymbol(name, Symbol(file))) { - // Success. Also add parent package, if any. - string::size_type dot_pos = name.find_last_of('.'); - if (dot_pos == string::npos) { - // No parents. - ValidateSymbolName(name, name, proto); - } else { - // Has parent. - string* parent_name = tables_->AllocateString(name.substr(0, dot_pos)); - AddPackage(*parent_name, proto, file); - ValidateSymbolName(name.substr(dot_pos + 1), name, proto); - } - } else { - Symbol existing_symbol = tables_->FindSymbol(name); - // It's OK to redefine a package. - if (existing_symbol.type != Symbol::PACKAGE) { - // Symbol seems to have been defined in a different file. - AddError(name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + name + "\" is already defined (as something other than " - "a package) in file \"" + existing_symbol.GetFile()->name() + - "\"."); - } - } -} - -void DescriptorBuilder::ValidateSymbolName( - const string& name, const string& full_name, const Message& proto) { - if (name.empty()) { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "Missing name."); - } else { - for (int i = 0; i < name.size(); i++) { - // I don't trust isalnum() due to locales. :( - if ((name[i] < 'a' || 'z' < name[i]) && - (name[i] < 'A' || 'Z' < name[i]) && - (name[i] < '0' || '9' < name[i]) && - (name[i] != '_')) { - AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, - "\"" + name + "\" is not a valid identifier."); - } - } - } -} - -bool DescriptorBuilder::ValidateQualifiedName(const string& name) { - bool last_was_period = false; - - for (int i = 0; i < name.size(); i++) { - // I don't trust isalnum() due to locales. :( - if (('a' <= name[i] && name[i] <= 'z') || - ('A' <= name[i] && name[i] <= 'Z') || - ('0' <= name[i] && name[i] <= '9') || - (name[i] == '_')) { - last_was_period = false; - } else if (name[i] == '.') { - if (last_was_period) return false; - last_was_period = true; - } else { - return false; - } - } - - return !name.empty() && !last_was_period; -} - -// ------------------------------------------------------------------- - -// This generic implementation is good for all descriptors except -// FileDescriptor. -template void DescriptorBuilder::AllocateOptions( - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor) { - AllocateOptionsImpl(descriptor->full_name(), descriptor->full_name(), - orig_options, descriptor); -} - -// We specialize for FileDescriptor. -void DescriptorBuilder::AllocateOptions(const FileOptions& orig_options, - FileDescriptor* descriptor) { - // We add the dummy token so that LookupSymbol does the right thing. - AllocateOptionsImpl(descriptor->package() + ".dummy", descriptor->name(), - orig_options, descriptor); -} - -template void DescriptorBuilder::AllocateOptionsImpl( - const string& name_scope, - const string& element_name, - const typename DescriptorT::OptionsType& orig_options, - DescriptorT* descriptor) { - // We need to use a dummy pointer to work around a bug in older versions of - // GCC. Otherwise, the following two lines could be replaced with: - // typename DescriptorT::OptionsType* options = - // tables_->AllocateMessage(); - typename DescriptorT::OptionsType* const dummy = NULL; - typename DescriptorT::OptionsType* options = tables_->AllocateMessage(dummy); - options->CopyFrom(orig_options); - descriptor->options_ = options; - - // Don't add to options_to_interpret_ unless there were uninterpreted - // options. This not only avoids unnecessary work, but prevents a - // bootstrapping problem when building descriptors for descriptor.proto. - // descriptor.proto does not contain any uninterpreted options, but - // attempting to interpret options anyway will cause - // OptionsType::GetDescriptor() to be called which may then deadlock since - // we're still trying to build it. - if (options->uninterpreted_option_size() > 0) { - options_to_interpret_.push_back( - OptionsToInterpret(name_scope, element_name, &orig_options, options)); - } -} - - -// A common pattern: We want to convert a repeated field in the descriptor -// to an array of values, calling some method to build each value. -#define BUILD_ARRAY(INPUT, OUTPUT, NAME, METHOD, PARENT) \ - OUTPUT->NAME##_count_ = INPUT.NAME##_size(); \ - AllocateArray(INPUT.NAME##_size(), &OUTPUT->NAME##s_); \ - for (int i = 0; i < INPUT.NAME##_size(); i++) { \ - METHOD(INPUT.NAME(i), PARENT, OUTPUT->NAME##s_ + i); \ - } - -const FileDescriptor* DescriptorBuilder::BuildFile( - const FileDescriptorProto& proto) { - filename_ = proto.name(); - - // Check if the file already exists and is identical to the one being built. - // Note: This only works if the input is canonical -- that is, it - // fully-qualifies all type names, has no UninterpretedOptions, etc. - // This is fine, because this idempotency "feature" really only exists to - // accomodate one hack in the proto1->proto2 migration layer. - const FileDescriptor* existing_file = tables_->FindFile(filename_); - if (existing_file != NULL) { - // File already in pool. Compare the existing one to the input. - FileDescriptorProto existing_proto; - existing_file->CopyTo(&existing_proto); - if (existing_proto.SerializeAsString() == proto.SerializeAsString()) { - // They're identical. Return the existing descriptor. - return existing_file; - } - - // Not a match. The error will be detected and handled later. - } - - // Check to see if this file is already on the pending files list. - // TODO(kenton): Allow recursive imports? It may not work with some - // (most?) programming languages. E.g., in C++, a forward declaration - // of a type is not sufficient to allow it to be used even in a - // generated header file due to inlining. This could perhaps be - // worked around using tricks involving inserting #include statements - // mid-file, but that's pretty ugly, and I'm pretty sure there are - // some languages out there that do not allow recursive dependencies - // at all. - for (int i = 0; i < tables_->pending_files_.size(); i++) { - if (tables_->pending_files_[i] == proto.name()) { - string error_message("File recursively imports itself: "); - for (; i < tables_->pending_files_.size(); i++) { - error_message.append(tables_->pending_files_[i]); - error_message.append(" -> "); - } - error_message.append(proto.name()); - - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - error_message); - return NULL; - } - } - - // If we have a fallback_database_, attempt to load all dependencies now, - // before checkpointing tables_. This avoids confusion with recursive - // checkpoints. - if (pool_->fallback_database_ != NULL) { - tables_->pending_files_.push_back(proto.name()); - for (int i = 0; i < proto.dependency_size(); i++) { - if (tables_->FindFile(proto.dependency(i)) == NULL && - (pool_->underlay_ == NULL || - pool_->underlay_->FindFileByName(proto.dependency(i)) == NULL)) { - // We don't care what this returns since we'll find out below anyway. - pool_->TryFindFileInFallbackDatabase(proto.dependency(i)); - } - } - tables_->pending_files_.pop_back(); - } - - // Checkpoint the tables so that we can roll back if something goes wrong. - tables_->Checkpoint(); - - FileDescriptor* result = tables_->Allocate(); - file_ = result; - - file_tables_ = tables_->AllocateFileTables(); - file_->tables_ = file_tables_; - - if (!proto.has_name()) { - AddError("", proto, DescriptorPool::ErrorCollector::OTHER, - "Missing field: FileDescriptorProto.name."); - } - - result->name_ = tables_->AllocateString(proto.name()); - if (proto.has_package()) { - result->package_ = tables_->AllocateString(proto.package()); - } else { - // We cannot rely on proto.package() returning a valid string if - // proto.has_package() is false, because we might be running at static - // initialization time, in which case default values have not yet been - // initialized. - result->package_ = tables_->AllocateString(""); - } - result->pool_ = pool_; - - // Add to tables. - if (!tables_->AddFile(result)) { - AddError(proto.name(), proto, DescriptorPool::ErrorCollector::OTHER, - "A file with this name is already in the pool."); - // Bail out early so that if this is actually the exact same file, we - // don't end up reporting that every single symbol is already defined. - tables_->Rollback(); - return NULL; - } - if (!result->package().empty()) { - AddPackage(result->package(), proto, result); - } - - // Make sure all dependencies are loaded. - set seen_dependencies; - result->dependency_count_ = proto.dependency_size(); - result->dependencies_ = - tables_->AllocateArray(proto.dependency_size()); - for (int i = 0; i < proto.dependency_size(); i++) { - if (!seen_dependencies.insert(proto.dependency(i)).second) { - AddError(proto.name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Import \"" + proto.dependency(i) + "\" was listed twice."); - } - - const FileDescriptor* dependency = tables_->FindFile(proto.dependency(i)); - if (dependency == NULL && pool_->underlay_ != NULL) { - dependency = pool_->underlay_->FindFileByName(proto.dependency(i)); - } - - if (dependency == NULL) { - if (pool_->allow_unknown_) { - dependency = NewPlaceholderFile(proto.dependency(i)); - } else { - string message; - if (pool_->fallback_database_ == NULL) { - message = "Import \"" + proto.dependency(i) + - "\" has not been loaded."; - } else { - message = "Import \"" + proto.dependency(i) + - "\" was not found or had errors."; - } - AddError(proto.name(), proto, - DescriptorPool::ErrorCollector::OTHER, - message); - } - } - - result->dependencies_[i] = dependency; - } - - // Convert children. - BUILD_ARRAY(proto, result, message_type, BuildMessage , NULL); - BUILD_ARRAY(proto, result, enum_type , BuildEnum , NULL); - BUILD_ARRAY(proto, result, service , BuildService , NULL); - BUILD_ARRAY(proto, result, extension , BuildExtension, NULL); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - // Note that the following steps must occur in exactly the specified order. - - // Cross-link. - CrossLinkFile(result, proto); - - // Interpret any remaining uninterpreted options gathered into - // options_to_interpret_ during descriptor building. Cross-linking has made - // extension options known, so all interpretations should now succeed. - if (!had_errors_) { - OptionInterpreter option_interpreter(this); - for (vector::iterator iter = - options_to_interpret_.begin(); - iter != options_to_interpret_.end(); ++iter) { - option_interpreter.InterpretOptions(&(*iter)); - } - options_to_interpret_.clear(); - } - - // Validate options. - if (!had_errors_) { - ValidateFileOptions(result, proto); - } - - if (had_errors_) { - tables_->Rollback(); - return NULL; - } else { - tables_->Checkpoint(); - return result; - } -} - -void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, - const Descriptor* parent, - Descriptor* result) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->containing_type_ = parent; - result->is_placeholder_ = false; - result->is_unqualified_placeholder_ = false; - - BUILD_ARRAY(proto, result, field , BuildField , result); - BUILD_ARRAY(proto, result, nested_type , BuildMessage , result); - BUILD_ARRAY(proto, result, enum_type , BuildEnum , result); - BUILD_ARRAY(proto, result, extension_range, BuildExtensionRange, result); - BUILD_ARRAY(proto, result, extension , BuildExtension , result); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); - - // Check that no fields have numbers in extension ranges. - for (int i = 0; i < result->field_count(); i++) { - const FieldDescriptor* field = result->field(i); - for (int j = 0; j < result->extension_range_count(); j++) { - const Descriptor::ExtensionRange* range = result->extension_range(j); - if (range->start <= field->number() && field->number() < range->end) { - AddError(field->full_name(), proto.extension_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Extension range $0 to $1 includes field \"$2\" ($3).", - range->start, range->end - 1, - field->name(), field->number())); - } - } - } - - // Check that extension ranges don't overlap. - for (int i = 0; i < result->extension_range_count(); i++) { - const Descriptor::ExtensionRange* range1 = result->extension_range(i); - for (int j = i + 1; j < result->extension_range_count(); j++) { - const Descriptor::ExtensionRange* range2 = result->extension_range(j); - if (range1->end > range2->start && range2->end > range1->start) { - AddError(result->full_name(), proto.extension_range(j), - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension range $0 to $1 overlaps with " - "already-defined range $2 to $3.", - range2->start, range2->end - 1, - range1->start, range1->end - 1)); - } - } - } -} - -void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, - const Descriptor* parent, - FieldDescriptor* result, - bool is_extension) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->number_ = proto.number(); - result->is_extension_ = is_extension; - - // If .proto files follow the style guide then the name should already be - // lower-cased. If that's the case we can just reuse the string we already - // allocated rather than allocate a new one. - string lowercase_name(proto.name()); - LowerString(&lowercase_name); - if (lowercase_name == proto.name()) { - result->lowercase_name_ = result->name_; - } else { - result->lowercase_name_ = tables_->AllocateString(lowercase_name); - } - - // Don't bother with the above optimization for camel-case names since - // .proto files that follow the guide shouldn't be using names in this - // format, so the optimization wouldn't help much. - result->camelcase_name_ = tables_->AllocateString(ToCamelCase(proto.name())); - - // Some compilers do not allow static_cast directly between two enum types, - // so we must cast to int first. - result->type_ = static_cast( - implicit_cast(proto.type())); - result->label_ = static_cast( - implicit_cast(proto.label())); - - // Some of these may be filled in when cross-linking. - result->containing_type_ = NULL; - result->extension_scope_ = NULL; - result->experimental_map_key_ = NULL; - result->message_type_ = NULL; - result->enum_type_ = NULL; - - result->has_default_value_ = proto.has_default_value(); - if (proto.has_default_value() && result->is_repeated()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Repeated fields can't have default values."); - } - - if (proto.has_type()) { - if (proto.has_default_value()) { - char* end_pos = NULL; - switch (result->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - result->default_value_int32_ = - strtol(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_INT64: - result->default_value_int64_ = - strto64(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_UINT32: - result->default_value_uint32_ = - strtoul(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_UINT64: - result->default_value_uint64_ = - strtou64(proto.default_value().c_str(), &end_pos, 0); - break; - case FieldDescriptor::CPPTYPE_FLOAT: - if (proto.default_value() == "inf") { - result->default_value_float_ = numeric_limits::infinity(); - } else if (proto.default_value() == "-inf") { - result->default_value_float_ = -numeric_limits::infinity(); - } else if (proto.default_value() == "nan") { - result->default_value_float_ = numeric_limits::quiet_NaN(); - } else { - result->default_value_float_ = - NoLocaleStrtod(proto.default_value().c_str(), &end_pos); - } - break; - case FieldDescriptor::CPPTYPE_DOUBLE: - if (proto.default_value() == "inf") { - result->default_value_double_ = numeric_limits::infinity(); - } else if (proto.default_value() == "-inf") { - result->default_value_double_ = -numeric_limits::infinity(); - } else if (proto.default_value() == "nan") { - result->default_value_double_ = numeric_limits::quiet_NaN(); - } else { - result->default_value_double_ = - NoLocaleStrtod(proto.default_value().c_str(), &end_pos); - } - break; - case FieldDescriptor::CPPTYPE_BOOL: - if (proto.default_value() == "true") { - result->default_value_bool_ = true; - } else if (proto.default_value() == "false") { - result->default_value_bool_ = false; - } else { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Boolean default must be true or false."); - } - break; - case FieldDescriptor::CPPTYPE_ENUM: - // This will be filled in when cross-linking. - result->default_value_enum_ = NULL; - break; - case FieldDescriptor::CPPTYPE_STRING: - if (result->type() == FieldDescriptor::TYPE_BYTES) { - result->default_value_string_ = tables_->AllocateString( - UnescapeCEscapeString(proto.default_value())); - } else { - result->default_value_string_ = - tables_->AllocateString(proto.default_value()); - } - break; - case FieldDescriptor::CPPTYPE_MESSAGE: - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Messages can't have default values."); - result->has_default_value_ = false; - break; - } - - if (end_pos != NULL) { - // end_pos is only set non-NULL by the parsers for numeric types, above. - // This checks that the default was non-empty and had no extra junk - // after the end of the number. - if (proto.default_value().empty() || *end_pos != '\0') { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Couldn't parse default value."); - } - } - } else { - // No explicit default value - switch (result->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: - result->default_value_int32_ = 0; - break; - case FieldDescriptor::CPPTYPE_INT64: - result->default_value_int64_ = 0; - break; - case FieldDescriptor::CPPTYPE_UINT32: - result->default_value_uint32_ = 0; - break; - case FieldDescriptor::CPPTYPE_UINT64: - result->default_value_uint64_ = 0; - break; - case FieldDescriptor::CPPTYPE_FLOAT: - result->default_value_float_ = 0.0f; - break; - case FieldDescriptor::CPPTYPE_DOUBLE: - result->default_value_double_ = 0.0; - break; - case FieldDescriptor::CPPTYPE_BOOL: - result->default_value_bool_ = false; - break; - case FieldDescriptor::CPPTYPE_ENUM: - // This will be filled in when cross-linking. - result->default_value_enum_ = NULL; - break; - case FieldDescriptor::CPPTYPE_STRING: - result->default_value_string_ = &kEmptyString; - break; - case FieldDescriptor::CPPTYPE_MESSAGE: - break; - } - } - } - - if (result->number() <= 0) { - AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, - "Field numbers must be positive integers."); - } else if (result->number() > FieldDescriptor::kMaxNumber) { - AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Field numbers cannot be greater than $0.", - FieldDescriptor::kMaxNumber)); - } else if (result->number() >= FieldDescriptor::kFirstReservedNumber && - result->number() <= FieldDescriptor::kLastReservedNumber) { - AddError(result->full_name(), proto, DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute( - "Field numbers $0 through $1 are reserved for the protocol " - "buffer library implementation.", - FieldDescriptor::kFirstReservedNumber, - FieldDescriptor::kLastReservedNumber)); - } - - if (is_extension) { - if (!proto.has_extendee()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "FieldDescriptorProto.extendee not set for extension field."); - } - - result->extension_scope_ = parent; - } else { - if (proto.has_extendee()) { - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "FieldDescriptorProto.extendee set for non-extension field."); - } - - result->containing_type_ = parent; - } - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); -} - -void DescriptorBuilder::BuildExtensionRange( - const DescriptorProto::ExtensionRange& proto, - const Descriptor* parent, - Descriptor::ExtensionRange* result) { - result->start = proto.start(); - result->end = proto.end(); - if (result->start <= 0) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - "Extension numbers must be positive integers."); - } - - if (result->end > FieldDescriptor::kMaxNumber + 1) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension numbers cannot be greater than $0.", - FieldDescriptor::kMaxNumber)); - } - - if (result->start >= result->end) { - AddError(parent->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - "Extension range end number must be greater than start number."); - } -} - -void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, - const Descriptor* parent, - EnumDescriptor* result) { - const string& scope = (parent == NULL) ? - file_->package() : parent->full_name(); - string* full_name = tables_->AllocateString(scope); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - result->containing_type_ = parent; - result->is_placeholder_ = false; - result->is_unqualified_placeholder_ = false; - - if (proto.value_size() == 0) { - // We cannot allow enums with no values because this would mean there - // would be no valid default value for fields of this type. - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Enums must contain at least one value."); - } - - BUILD_ARRAY(proto, result, value, BuildEnumValue, result); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); -} - -void DescriptorBuilder::BuildEnumValue(const EnumValueDescriptorProto& proto, - const EnumDescriptor* parent, - EnumValueDescriptor* result) { - result->name_ = tables_->AllocateString(proto.name()); - result->number_ = proto.number(); - result->type_ = parent; - - // Note: full_name for enum values is a sibling to the parent's name, not a - // child of it. - string* full_name = tables_->AllocateString(*parent->full_name_); - full_name->resize(full_name->size() - parent->name_->size()); - full_name->append(*result->name_); - result->full_name_ = full_name; - - ValidateSymbolName(proto.name(), *full_name, proto); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - // Again, enum values are weird because we makes them appear as siblings - // of the enum type instead of children of it. So, we use - // parent->containing_type() as the value's parent. - bool added_to_outer_scope = - AddSymbol(result->full_name(), parent->containing_type(), result->name(), - proto, Symbol(result)); - - // However, we also want to be able to search for values within a single - // enum type, so we add it as a child of the enum type itself, too. - // Note: This could fail, but if it does, the error has already been - // reported by the above AddSymbol() call, so we ignore the return code. - bool added_to_inner_scope = - file_tables_->AddAliasUnderParent(parent, result->name(), Symbol(result)); - - if (added_to_inner_scope && !added_to_outer_scope) { - // This value did not conflict with any values defined in the same enum, - // but it did conflict with some other symbol defined in the enum type's - // scope. Let's print an additional error to explain this. - string outer_scope; - if (parent->containing_type() == NULL) { - outer_scope = file_->package(); - } else { - outer_scope = parent->containing_type()->full_name(); - } - - if (outer_scope.empty()) { - outer_scope = "the global scope"; - } else { - outer_scope = "\"" + outer_scope + "\""; - } - - AddError(result->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Note that enum values use C++ scoping rules, meaning that " - "enum values are siblings of their type, not children of it. " - "Therefore, \"" + result->name() + "\" must be unique within " - + outer_scope + ", not just within \"" + parent->name() + "\"."); - } - - // An enum is allowed to define two numbers that refer to the same value. - // FindValueByNumber() should return the first such value, so we simply - // ignore AddEnumValueByNumber()'s return code. - file_tables_->AddEnumValueByNumber(result); -} - -void DescriptorBuilder::BuildService(const ServiceDescriptorProto& proto, - const void* dummy, - ServiceDescriptor* result) { - string* full_name = tables_->AllocateString(file_->package()); - if (!full_name->empty()) full_name->append(1, '.'); - full_name->append(proto.name()); - - ValidateSymbolName(proto.name(), *full_name, proto); - - result->name_ = tables_->AllocateString(proto.name()); - result->full_name_ = full_name; - result->file_ = file_; - - BUILD_ARRAY(proto, result, method, BuildMethod, result); - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - AddSymbol(result->full_name(), NULL, result->name(), - proto, Symbol(result)); -} - -void DescriptorBuilder::BuildMethod(const MethodDescriptorProto& proto, - const ServiceDescriptor* parent, - MethodDescriptor* result) { - result->name_ = tables_->AllocateString(proto.name()); - result->service_ = parent; - - string* full_name = tables_->AllocateString(parent->full_name()); - full_name->append(1, '.'); - full_name->append(*result->name_); - result->full_name_ = full_name; - - ValidateSymbolName(proto.name(), *full_name, proto); - - // These will be filled in when cross-linking. - result->input_type_ = NULL; - result->output_type_ = NULL; - - // Copy options. - if (!proto.has_options()) { - result->options_ = NULL; // Will set to default_instance later. - } else { - AllocateOptions(proto.options(), result); - } - - AddSymbol(result->full_name(), parent, result->name(), - proto, Symbol(result)); -} - -#undef BUILD_ARRAY - -// ------------------------------------------------------------------- - -void DescriptorBuilder::CrossLinkFile( - FileDescriptor* file, const FileDescriptorProto& proto) { - if (file->options_ == NULL) { - file->options_ = &FileOptions::default_instance(); - } - - for (int i = 0; i < file->message_type_count(); i++) { - CrossLinkMessage(&file->message_types_[i], proto.message_type(i)); - } - - for (int i = 0; i < file->extension_count(); i++) { - CrossLinkField(&file->extensions_[i], proto.extension(i)); - } - - for (int i = 0; i < file->enum_type_count(); i++) { - CrossLinkEnum(&file->enum_types_[i], proto.enum_type(i)); - } - - for (int i = 0; i < file->service_count(); i++) { - CrossLinkService(&file->services_[i], proto.service(i)); - } -} - -void DescriptorBuilder::CrossLinkMessage( - Descriptor* message, const DescriptorProto& proto) { - if (message->options_ == NULL) { - message->options_ = &MessageOptions::default_instance(); - } - - for (int i = 0; i < message->nested_type_count(); i++) { - CrossLinkMessage(&message->nested_types_[i], proto.nested_type(i)); - } - - for (int i = 0; i < message->enum_type_count(); i++) { - CrossLinkEnum(&message->enum_types_[i], proto.enum_type(i)); - } - - for (int i = 0; i < message->field_count(); i++) { - CrossLinkField(&message->fields_[i], proto.field(i)); - } - - for (int i = 0; i < message->extension_count(); i++) { - CrossLinkField(&message->extensions_[i], proto.extension(i)); - } -} - -void DescriptorBuilder::CrossLinkField( - FieldDescriptor* field, const FieldDescriptorProto& proto) { - if (field->options_ == NULL) { - field->options_ = &FieldOptions::default_instance(); - } - - if (proto.has_extendee()) { - Symbol extendee = LookupSymbol(proto.extendee(), field->full_name(), - PLACEHOLDER_EXTENDABLE_MESSAGE); - if (extendee.IsNull()) { - AddNotDefinedError(field->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - proto.extendee()); - return; - } else if (extendee.type != Symbol::MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "\"" + proto.extendee() + "\" is not a message type."); - return; - } - field->containing_type_ = extendee.descriptor; - - if (!field->containing_type()->IsExtensionNumber(field->number())) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("\"$0\" does not declare $1 as an " - "extension number.", - field->containing_type()->full_name(), - field->number())); - } - } - - if (proto.has_type_name()) { - // Assume we are expecting a message type unless the proto contains some - // evidence that it expects an enum type. This only makes a difference if - // we end up creating a placeholder. - bool expecting_enum = (proto.type() == FieldDescriptorProto::TYPE_ENUM) || - proto.has_default_value(); - - Symbol type = - LookupSymbol(proto.type_name(), field->full_name(), - expecting_enum ? PLACEHOLDER_ENUM : PLACEHOLDER_MESSAGE, - LOOKUP_TYPES); - - if (type.IsNull()) { - AddNotDefinedError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - proto.type_name()); - return; - } - - if (!proto.has_type()) { - // Choose field type based on symbol. - if (type.type == Symbol::MESSAGE) { - field->type_ = FieldDescriptor::TYPE_MESSAGE; - } else if (type.type == Symbol::ENUM) { - field->type_ = FieldDescriptor::TYPE_ENUM; - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "\"" + proto.type_name() + "\" is not a type."); - return; - } - } - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (type.type != Symbol::MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "\"" + proto.type_name() + "\" is not a message type."); - return; - } - field->message_type_ = type.descriptor; - - if (field->has_default_value()) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Messages can't have default values."); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - if (type.type != Symbol::ENUM) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "\"" + proto.type_name() + "\" is not an enum type."); - return; - } - field->enum_type_ = type.enum_descriptor; - - if (field->enum_type()->is_placeholder_) { - // We can't look up default values for placeholder types. We'll have - // to just drop them. - field->has_default_value_ = false; - } - - if (field->has_default_value()) { - // We can't just use field->enum_type()->FindValueByName() here - // because that locks the pool's mutex, which we have already locked - // at this point. - Symbol default_value = - LookupSymbolNoPlaceholder(proto.default_value(), - field->enum_type()->full_name()); - - if (default_value.type == Symbol::ENUM_VALUE && - default_value.enum_value_descriptor->type() == field->enum_type()) { - field->default_value_enum_ = default_value.enum_value_descriptor; - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::DEFAULT_VALUE, - "Enum type \"" + field->enum_type()->full_name() + - "\" has no value named \"" + proto.default_value() + "\"."); - } - } else if (field->enum_type()->value_count() > 0) { - // All enums must have at least one value, or we would have reported - // an error elsewhere. We use the first defined value as the default - // if a default is not explicitly defined. - field->default_value_enum_ = field->enum_type()->value(0); - } - } else { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Field with primitive type has type_name."); - } - } else { - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE || - field->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Field with message or enum type missing type_name."); - } - } - - // Add the field to the fields-by-number table. - // Note: We have to do this *after* cross-linking because extensions do not - // know their containing type until now. - if (!file_tables_->AddFieldByNumber(field)) { - const FieldDescriptor* conflicting_field = - file_tables_->FindFieldByNumber(field->containing_type(), - field->number()); - if (field->is_extension()) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Extension number $0 has already been used " - "in \"$1\" by extension \"$2\".", - field->number(), - field->containing_type()->full_name(), - conflicting_field->full_name())); - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NUMBER, - strings::Substitute("Field number $0 has already been used in " - "\"$1\" by field \"$2\".", - field->number(), - field->containing_type()->full_name(), - conflicting_field->name())); - } - } - - if (field->is_extension()) { - // No need for error checking: if the extension number collided, - // we've already been informed of it by the if() above. - tables_->AddExtension(field); - } - - // Add the field to the lowercase-name and camelcase-name tables. - file_tables_->AddFieldByStylizedNames(field); -} - -void DescriptorBuilder::CrossLinkEnum( - EnumDescriptor* enum_type, const EnumDescriptorProto& proto) { - if (enum_type->options_ == NULL) { - enum_type->options_ = &EnumOptions::default_instance(); - } - - for (int i = 0; i < enum_type->value_count(); i++) { - CrossLinkEnumValue(&enum_type->values_[i], proto.value(i)); - } -} - -void DescriptorBuilder::CrossLinkEnumValue( - EnumValueDescriptor* enum_value, const EnumValueDescriptorProto& proto) { - if (enum_value->options_ == NULL) { - enum_value->options_ = &EnumValueOptions::default_instance(); - } -} - -void DescriptorBuilder::CrossLinkService( - ServiceDescriptor* service, const ServiceDescriptorProto& proto) { - if (service->options_ == NULL) { - service->options_ = &ServiceOptions::default_instance(); - } - - for (int i = 0; i < service->method_count(); i++) { - CrossLinkMethod(&service->methods_[i], proto.method(i)); - } -} - -void DescriptorBuilder::CrossLinkMethod( - MethodDescriptor* method, const MethodDescriptorProto& proto) { - if (method->options_ == NULL) { - method->options_ = &MethodOptions::default_instance(); - } - - Symbol input_type = LookupSymbol(proto.input_type(), method->full_name()); - if (input_type.IsNull()) { - AddNotDefinedError(method->full_name(), proto, - DescriptorPool::ErrorCollector::INPUT_TYPE, - proto.input_type()); - } else if (input_type.type != Symbol::MESSAGE) { - AddError(method->full_name(), proto, - DescriptorPool::ErrorCollector::INPUT_TYPE, - "\"" + proto.input_type() + "\" is not a message type."); - } else { - method->input_type_ = input_type.descriptor; - } - - Symbol output_type = LookupSymbol(proto.output_type(), method->full_name()); - if (output_type.IsNull()) { - AddNotDefinedError(method->full_name(), proto, - DescriptorPool::ErrorCollector::OUTPUT_TYPE, - proto.output_type()); - } else if (output_type.type != Symbol::MESSAGE) { - AddError(method->full_name(), proto, - DescriptorPool::ErrorCollector::OUTPUT_TYPE, - "\"" + proto.output_type() + "\" is not a message type."); - } else { - method->output_type_ = output_type.descriptor; - } -} - -// ------------------------------------------------------------------- - -#define VALIDATE_OPTIONS_FROM_ARRAY(descriptor, array_name, type) \ - for (int i = 0; i < descriptor->array_name##_count(); ++i) { \ - Validate##type##Options(descriptor->array_name##s_ + i, \ - proto.array_name(i)); \ - } - -// Determine if the file uses optimize_for = LITE_RUNTIME, being careful to -// avoid problems that exist at init time. -static bool IsLite(const FileDescriptor* file) { - // TODO(kenton): I don't even remember how many of these conditions are - // actually possible. I'm just being super-safe. - return file != NULL && - &file->options() != NULL && - &file->options() != &FileOptions::default_instance() && - file->options().optimize_for() == FileOptions::LITE_RUNTIME; -} - -void DescriptorBuilder::ValidateFileOptions(FileDescriptor* file, - const FileDescriptorProto& proto) { - VALIDATE_OPTIONS_FROM_ARRAY(file, message_type, Message); - VALIDATE_OPTIONS_FROM_ARRAY(file, enum_type, Enum); - VALIDATE_OPTIONS_FROM_ARRAY(file, service, Service); - VALIDATE_OPTIONS_FROM_ARRAY(file, extension, Field); - - // Lite files can only be imported by other Lite files. - if (!IsLite(file)) { - for (int i = 0; i < file->dependency_count(); i++) { - if (IsLite(file->dependency(i))) { - AddError( - file->name(), proto, - DescriptorPool::ErrorCollector::OTHER, - "Files that do not use optimize_for = LITE_RUNTIME cannot import " - "files which do use this option. This file is not lite, but it " - "imports \"" + file->dependency(i)->name() + "\" which is."); - break; - } - } - } -} - -void DescriptorBuilder::ValidateMessageOptions(Descriptor* message, - const DescriptorProto& proto) { - VALIDATE_OPTIONS_FROM_ARRAY(message, field, Field); - VALIDATE_OPTIONS_FROM_ARRAY(message, nested_type, Message); - VALIDATE_OPTIONS_FROM_ARRAY(message, enum_type, Enum); - VALIDATE_OPTIONS_FROM_ARRAY(message, extension, Field); -} - -void DescriptorBuilder::ValidateFieldOptions(FieldDescriptor* field, - const FieldDescriptorProto& proto) { - if (field->options().has_experimental_map_key()) { - ValidateMapKey(field, proto); - } - - // Only repeated primitive fields may be packed. - if (field->options().packed() && !field->is_packable()) { - AddError( - field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "[packed = true] can only be specified for repeated primitive fields."); - } - - // Note: Default instance may not yet be initialized here, so we have to - // avoid reading from it. - if (field->containing_type_ != NULL && - &field->containing_type()->options() != - &MessageOptions::default_instance() && - field->containing_type()->options().message_set_wire_format()) { - if (field->is_extension()) { - if (!field->is_optional() || - field->type() != FieldDescriptor::TYPE_MESSAGE) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::TYPE, - "Extensions of MessageSets must be optional messages."); - } - } else { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "MessageSets cannot have fields, only extensions."); - } - } - - // Lite extensions can only be of Lite types. - if (IsLite(field->file()) && - field->containing_type_ != NULL && - !IsLite(field->containing_type()->file())) { - AddError(field->full_name(), proto, - DescriptorPool::ErrorCollector::EXTENDEE, - "Extensions to non-lite types can only be declared in non-lite " - "files. Note that you cannot extend a non-lite type to contain " - "a lite type, but the reverse is allowed."); - } -} - -void DescriptorBuilder::ValidateEnumOptions(EnumDescriptor* enm, - const EnumDescriptorProto& proto) { - VALIDATE_OPTIONS_FROM_ARRAY(enm, value, EnumValue); -} - -void DescriptorBuilder::ValidateEnumValueOptions( - EnumValueDescriptor* enum_value, const EnumValueDescriptorProto& proto) { - // Nothing to do so far. -} -void DescriptorBuilder::ValidateServiceOptions(ServiceDescriptor* service, - const ServiceDescriptorProto& proto) { - if (IsLite(service->file())) { - AddError(service->full_name(), proto, - DescriptorPool::ErrorCollector::NAME, - "Files with optimize_for = LITE_RUNTIME cannot define services."); - } - - VALIDATE_OPTIONS_FROM_ARRAY(service, method, Method); -} - -void DescriptorBuilder::ValidateMethodOptions(MethodDescriptor* method, - const MethodDescriptorProto& proto) { - // Nothing to do so far. -} - -void DescriptorBuilder::ValidateMapKey(FieldDescriptor* field, - const FieldDescriptorProto& proto) { - if (!field->is_repeated()) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "map type is only allowed for repeated fields."); - return; - } - - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "map type is only allowed for fields with a message type."); - return; - } - - const Descriptor* item_type = field->message_type(); - if (item_type == NULL) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Could not find field type."); - return; - } - - // Find the field in item_type named by "experimental_map_key" - const string& key_name = field->options().experimental_map_key(); - const Symbol key_symbol = LookupSymbol( - key_name, - // We append ".key_name" to the containing type's name since - // LookupSymbol() searches for peers of the supplied name, not - // children of the supplied name. - item_type->full_name() + "." + key_name); - - if (key_symbol.IsNull() || key_symbol.field_descriptor->is_extension()) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "Could not find field named \"" + key_name + "\" in type \"" + - item_type->full_name() + "\"."); - return; - } - const FieldDescriptor* key_field = key_symbol.field_descriptor; - - if (key_field->is_repeated()) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "map_key must not name a repeated field."); - return; - } - - if (key_field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - AddError(field->full_name(), proto, DescriptorPool::ErrorCollector::TYPE, - "map key must name a scalar or string field."); - return; - } - - field->experimental_map_key_ = key_field; -} - -#undef VALIDATE_OPTIONS_FROM_ARRAY - -// ------------------------------------------------------------------- - -DescriptorBuilder::OptionInterpreter::OptionInterpreter( - DescriptorBuilder* builder) : builder_(builder) { - GOOGLE_CHECK(builder_); -} - -DescriptorBuilder::OptionInterpreter::~OptionInterpreter() { -} - -bool DescriptorBuilder::OptionInterpreter::InterpretOptions( - OptionsToInterpret* options_to_interpret) { - // Note that these may be in different pools, so we can't use the same - // descriptor and reflection objects on both. - Message* options = options_to_interpret->options; - const Message* original_options = options_to_interpret->original_options; - - bool failed = false; - options_to_interpret_ = options_to_interpret; - - // Find the uninterpreted_option field in the mutable copy of the options - // and clear them, since we're about to interpret them. - const FieldDescriptor* uninterpreted_options_field = - options->GetDescriptor()->FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(uninterpreted_options_field != NULL) - << "No field named \"uninterpreted_option\" in the Options proto."; - options->GetReflection()->ClearField(options, uninterpreted_options_field); - - // Find the uninterpreted_option field in the original options. - const FieldDescriptor* original_uninterpreted_options_field = - original_options->GetDescriptor()-> - FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(original_uninterpreted_options_field != NULL) - << "No field named \"uninterpreted_option\" in the Options proto."; - - const int num_uninterpreted_options = original_options->GetReflection()-> - FieldSize(*original_options, original_uninterpreted_options_field); - for (int i = 0; i < num_uninterpreted_options; ++i) { - uninterpreted_option_ = down_cast( - &original_options->GetReflection()->GetRepeatedMessage( - *original_options, original_uninterpreted_options_field, i)); - if (!InterpretSingleOption(options)) { - // Error already added by InterpretSingleOption(). - failed = true; - break; - } - } - // Reset these, so we don't have any dangling pointers. - uninterpreted_option_ = NULL; - options_to_interpret_ = NULL; - - if (!failed) { - // InterpretSingleOption() added the interpreted options in the - // UnknownFieldSet, in case the option isn't yet known to us. Now we - // serialize the options message and deserialize it back. That way, any - // option fields that we do happen to know about will get moved from the - // UnknownFieldSet into the real fields, and thus be available right away. - // If they are not known, that's OK too. They will get reparsed into the - // UnknownFieldSet and wait there until the message is parsed by something - // that does know about the options. - string buf; - options->AppendToString(&buf); - GOOGLE_CHECK(options->ParseFromString(buf)) - << "Protocol message serialized itself in invalid fashion."; - } - - return !failed; -} - -bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( - Message* options) { - // First do some basic validation. - if (uninterpreted_option_->name_size() == 0) { - // This should never happen unless the parser has gone seriously awry or - // someone has manually created the uninterpreted option badly. - return AddNameError("Option must have a name."); - } - if (uninterpreted_option_->name(0).name_part() == "uninterpreted_option") { - return AddNameError("Option must not use reserved name " - "\"uninterpreted_option\"."); - } - - const Descriptor* options_descriptor = NULL; - // Get the options message's descriptor from the builder's pool, so that we - // get the version that knows about any extension options declared in the - // file we're currently building. The descriptor should be there as long as - // the file we're building imported "google/protobuf/descriptors.proto". - - // Note that we use DescriptorBuilder::FindSymbol(), not - // DescriptorPool::FindMessageTypeByName() because we're already holding the - // pool's mutex, and the latter method locks it again. - Symbol symbol = builder_->FindSymbolNotEnforcingDeps( - options->GetDescriptor()->full_name()); - if (!symbol.IsNull() && symbol.type == Symbol::MESSAGE) { - options_descriptor = symbol.descriptor; - } else { - // The options message's descriptor was not in the builder's pool, so use - // the standard version from the generated pool. We're not holding the - // generated pool's mutex, so we can search it the straightforward way. - options_descriptor = options->GetDescriptor(); - } - GOOGLE_CHECK(options_descriptor); - - // We iterate over the name parts to drill into the submessages until we find - // the leaf field for the option. As we drill down we remember the current - // submessage's descriptor in |descriptor| and the next field in that - // submessage in |field|. We also track the fields we're drilling down - // through in |intermediate_fields|. As we go, we reconstruct the full option - // name in |debug_msg_name|, for use in error messages. - const Descriptor* descriptor = options_descriptor; - const FieldDescriptor* field = NULL; - vector intermediate_fields; - string debug_msg_name = ""; - - for (int i = 0; i < uninterpreted_option_->name_size(); ++i) { - const string& name_part = uninterpreted_option_->name(i).name_part(); - if (debug_msg_name.size() > 0) { - debug_msg_name += "."; - } - if (uninterpreted_option_->name(i).is_extension()) { - debug_msg_name += "(" + name_part + ")"; - // Search for the extension's descriptor as an extension in the builder's - // pool. Note that we use DescriptorBuilder::LookupSymbol(), not - // DescriptorPool::FindExtensionByName(), for two reasons: 1) It allows - // relative lookups, and 2) because we're already holding the pool's - // mutex, and the latter method locks it again. - Symbol symbol = builder_->LookupSymbol(name_part, - options_to_interpret_->name_scope); - if (!symbol.IsNull() && symbol.type == Symbol::FIELD) { - field = symbol.field_descriptor; - } - // If we don't find the field then the field's descriptor was not in the - // builder's pool, but there's no point in looking in the generated - // pool. We require that you import the file that defines any extensions - // you use, so they must be present in the builder's pool. - } else { - debug_msg_name += name_part; - // Search for the field's descriptor as a regular field. - field = descriptor->FindFieldByName(name_part); - } - - if (field == NULL) { - if (get_allow_unknown(builder_->pool_)) { - // We can't find the option, but AllowUnknownDependencies() is enabled, - // so we will just leave it as uninterpreted. - AddWithoutInterpreting(*uninterpreted_option_, options); - return true; - } else { - return AddNameError("Option \"" + debug_msg_name + "\" unknown."); - } - } else if (field->containing_type() != descriptor) { - if (get_is_placeholder(field->containing_type())) { - // The field is an extension of a placeholder type, so we can't - // reliably verify whether it is a valid extension to use here (e.g. - // we don't know if it is an extension of the correct *Options message, - // or if it has a valid field number, etc.). Just leave it as - // uninterpreted instead. - AddWithoutInterpreting(*uninterpreted_option_, options); - return true; - } else { - // This can only happen if, due to some insane misconfiguration of the - // pools, we find the options message in one pool but the field in - // another. This would probably imply a hefty bug somewhere. - return AddNameError("Option field \"" + debug_msg_name + - "\" is not a field or extension of message \"" + - descriptor->name() + "\"."); - } - } else if (field->is_repeated()) { - return AddNameError("Option field \"" + debug_msg_name + - "\" is repeated. Repeated options are not " - "supported."); - } else if (i < uninterpreted_option_->name_size() - 1) { - if (field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - return AddNameError("Option \"" + debug_msg_name + - "\" is an atomic type, not a message."); - } else { - // Drill down into the submessage. - intermediate_fields.push_back(field); - descriptor = field->message_type(); - } - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - return AddNameError("Option field \"" + debug_msg_name + - "\" cannot be of message type."); - } - } - - // We've found the leaf field. Now we use UnknownFieldSets to set its value - // on the options message. We do so because the message may not yet know - // about its extension fields, so we may not be able to set the fields - // directly. But the UnknownFieldSets will serialize to the same wire-format - // message, so reading that message back in once the extension fields are - // known will populate them correctly. - - // First see if the option is already set. - if (!ExamineIfOptionIsSet( - intermediate_fields.begin(), - intermediate_fields.end(), - field, debug_msg_name, - options->GetReflection()->GetUnknownFields(*options))) { - return false; // ExamineIfOptionIsSet() already added the error. - } - - - // First set the value on the UnknownFieldSet corresponding to the - // innermost message. - scoped_ptr unknown_fields(new UnknownFieldSet()); - if (!SetOptionValue(field, unknown_fields.get())) { - return false; // SetOptionValue() already added the error. - } - - // Now wrap the UnknownFieldSet with UnknownFieldSets corresponding to all - // the intermediate messages. - for (vector::reverse_iterator iter = - intermediate_fields.rbegin(); - iter != intermediate_fields.rend(); ++iter) { - scoped_ptr parent_unknown_fields(new UnknownFieldSet()); - switch ((*iter)->type()) { - case FieldDescriptor::TYPE_MESSAGE: { - io::StringOutputStream outstr( - parent_unknown_fields->AddLengthDelimited((*iter)->number())); - io::CodedOutputStream out(&outstr); - internal::WireFormat::SerializeUnknownFields(*unknown_fields, &out); - GOOGLE_CHECK(!out.HadError()) - << "Unexpected failure while serializing option submessage " - << debug_msg_name << "\"."; - break; - } - - case FieldDescriptor::TYPE_GROUP: { - parent_unknown_fields->AddGroup((*iter)->number()) - ->MergeFrom(*unknown_fields); - break; - } - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: " - << (*iter)->type(); - return false; - } - unknown_fields.reset(parent_unknown_fields.release()); - } - - // Now merge the UnknownFieldSet corresponding to the top-level message into - // the options message. - options->GetReflection()->MutableUnknownFields(options)->MergeFrom( - *unknown_fields); - - return true; -} - -void DescriptorBuilder::OptionInterpreter::AddWithoutInterpreting( - const UninterpretedOption& uninterpreted_option, Message* options) { - const FieldDescriptor* field = - options->GetDescriptor()->FindFieldByName("uninterpreted_option"); - GOOGLE_CHECK(field != NULL); - - options->GetReflection()->AddMessage(options, field) - ->CopyFrom(uninterpreted_option); -} - -bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( - vector::const_iterator intermediate_fields_iter, - vector::const_iterator intermediate_fields_end, - const FieldDescriptor* innermost_field, const string& debug_msg_name, - const UnknownFieldSet& unknown_fields) { - // We do linear searches of the UnknownFieldSet and its sub-groups. This - // should be fine since it's unlikely that any one options structure will - // contain more than a handful of options. - - if (intermediate_fields_iter == intermediate_fields_end) { - // We're at the innermost submessage. - for (int i = 0; i < unknown_fields.field_count(); i++) { - if (unknown_fields.field(i).number() == innermost_field->number()) { - return AddNameError("Option \"" + debug_msg_name + - "\" was already set."); - } - } - return true; - } - - for (int i = 0; i < unknown_fields.field_count(); i++) { - if (unknown_fields.field(i).number() == - (*intermediate_fields_iter)->number()) { - const UnknownField* unknown_field = &unknown_fields.field(i); - FieldDescriptor::Type type = (*intermediate_fields_iter)->type(); - // Recurse into the next submessage. - switch (type) { - case FieldDescriptor::TYPE_MESSAGE: - if (unknown_field->type() == UnknownField::TYPE_LENGTH_DELIMITED) { - UnknownFieldSet intermediate_unknown_fields; - if (intermediate_unknown_fields.ParseFromString( - unknown_field->length_delimited()) && - !ExamineIfOptionIsSet(intermediate_fields_iter + 1, - intermediate_fields_end, - innermost_field, debug_msg_name, - intermediate_unknown_fields)) { - return false; // Error already added. - } - } - break; - - case FieldDescriptor::TYPE_GROUP: - if (unknown_field->type() == UnknownField::TYPE_GROUP) { - if (!ExamineIfOptionIsSet(intermediate_fields_iter + 1, - intermediate_fields_end, - innermost_field, debug_msg_name, - unknown_field->group())) { - return false; // Error already added. - } - } - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_MESSAGE: " << type; - return false; - } - } - } - return true; -} - -bool DescriptorBuilder::OptionInterpreter::SetOptionValue( - const FieldDescriptor* option_field, - UnknownFieldSet* unknown_fields) { - // We switch on the CppType to validate. - switch (option_field->cpp_type()) { - - case FieldDescriptor::CPPTYPE_INT32: - if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > - static_cast(kint32max)) { - return AddValueError("Value out of range for int32 option \"" + - option_field->full_name() + "\"."); - } else { - SetInt32(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } - } else if (uninterpreted_option_->has_negative_int_value()) { - if (uninterpreted_option_->negative_int_value() < - static_cast(kint32min)) { - return AddValueError("Value out of range for int32 option \"" + - option_field->full_name() + "\"."); - } else { - SetInt32(option_field->number(), - uninterpreted_option_->negative_int_value(), - option_field->type(), unknown_fields); - } - } else { - return AddValueError("Value must be integer for int32 option \"" + - option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_INT64: - if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > - static_cast(kint64max)) { - return AddValueError("Value out of range for int64 option \"" + - option_field->full_name() + "\"."); - } else { - SetInt64(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } - } else if (uninterpreted_option_->has_negative_int_value()) { - SetInt64(option_field->number(), - uninterpreted_option_->negative_int_value(), - option_field->type(), unknown_fields); - } else { - return AddValueError("Value must be integer for int64 option \"" + - option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_UINT32: - if (uninterpreted_option_->has_positive_int_value()) { - if (uninterpreted_option_->positive_int_value() > kuint32max) { - return AddValueError("Value out of range for uint32 option \"" + - option_field->name() + "\"."); - } else { - SetUInt32(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } - } else { - return AddValueError("Value must be non-negative integer for uint32 " - "option \"" + option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_UINT64: - if (uninterpreted_option_->has_positive_int_value()) { - SetUInt64(option_field->number(), - uninterpreted_option_->positive_int_value(), - option_field->type(), unknown_fields); - } else { - return AddValueError("Value must be non-negative integer for uint64 " - "option \"" + option_field->full_name() + "\"."); - } - break; - - case FieldDescriptor::CPPTYPE_FLOAT: { - float value; - if (uninterpreted_option_->has_double_value()) { - value = uninterpreted_option_->double_value(); - } else if (uninterpreted_option_->has_positive_int_value()) { - value = uninterpreted_option_->positive_int_value(); - } else if (uninterpreted_option_->has_negative_int_value()) { - value = uninterpreted_option_->negative_int_value(); - } else { - return AddValueError("Value must be number for float option \"" + - option_field->full_name() + "\"."); - } - unknown_fields->AddFixed32(option_field->number(), - google::protobuf::internal::WireFormatLite::EncodeFloat(value)); - break; - } - - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value; - if (uninterpreted_option_->has_double_value()) { - value = uninterpreted_option_->double_value(); - } else if (uninterpreted_option_->has_positive_int_value()) { - value = uninterpreted_option_->positive_int_value(); - } else if (uninterpreted_option_->has_negative_int_value()) { - value = uninterpreted_option_->negative_int_value(); - } else { - return AddValueError("Value must be number for double option \"" + - option_field->full_name() + "\"."); - } - unknown_fields->AddFixed64(option_field->number(), - google::protobuf::internal::WireFormatLite::EncodeDouble(value)); - break; - } - - case FieldDescriptor::CPPTYPE_BOOL: - uint64 value; - if (!uninterpreted_option_->has_identifier_value()) { - return AddValueError("Value must be identifier for boolean option " - "\"" + option_field->full_name() + "\"."); - } - if (uninterpreted_option_->identifier_value() == "true") { - value = 1; - } else if (uninterpreted_option_->identifier_value() == "false") { - value = 0; - } else { - return AddValueError("Value must be \"true\" or \"false\" for boolean " - "option \"" + option_field->full_name() + "\"."); - } - unknown_fields->AddVarint(option_field->number(), value); - break; - - case FieldDescriptor::CPPTYPE_ENUM: { - if (!uninterpreted_option_->has_identifier_value()) { - return AddValueError("Value must be identifier for enum-valued option " - "\"" + option_field->full_name() + "\"."); - } - const EnumDescriptor* enum_type = option_field->enum_type(); - const string& value_name = uninterpreted_option_->identifier_value(); - const EnumValueDescriptor* enum_value = NULL; - - if (enum_type->file()->pool() != DescriptorPool::generated_pool()) { - // Note that the enum value's fully-qualified name is a sibling of the - // enum's name, not a child of it. - string fully_qualified_name = enum_type->full_name(); - fully_qualified_name.resize(fully_qualified_name.size() - - enum_type->name().size()); - fully_qualified_name += value_name; - - // Search for the enum value's descriptor in the builder's pool. Note - // that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not - // DescriptorPool::FindEnumValueByName() because we're already holding - // the pool's mutex, and the latter method locks it again. - Symbol symbol = - builder_->FindSymbolNotEnforcingDeps(fully_qualified_name); - if (!symbol.IsNull() && symbol.type == Symbol::ENUM_VALUE) { - if (symbol.enum_value_descriptor->type() != enum_type) { - return AddValueError("Enum type \"" + enum_type->full_name() + - "\" has no value named \"" + value_name + "\" for option \"" + - option_field->full_name() + - "\". This appears to be a value from a sibling type."); - } else { - enum_value = symbol.enum_value_descriptor; - } - } - } else { - // The enum type is in the generated pool, so we can search for the - // value there. - enum_value = enum_type->FindValueByName(value_name); - } - - if (enum_value == NULL) { - return AddValueError("Enum type \"" + - option_field->enum_type()->full_name() + - "\" has no value named \"" + value_name + "\" for " - "option \"" + option_field->full_name() + "\"."); - } else { - // Sign-extension is not a problem, since we cast directly from int32 to - // uint64, without first going through uint32. - unknown_fields->AddVarint(option_field->number(), - static_cast(static_cast(enum_value->number()))); - } - break; - } - - case FieldDescriptor::CPPTYPE_STRING: - if (!uninterpreted_option_->has_string_value()) { - return AddValueError("Value must be quoted string for string option " - "\"" + option_field->full_name() + "\"."); - } - // The string has already been unquoted and unescaped by the parser. - unknown_fields->AddLengthDelimited(option_field->number(), - uninterpreted_option_->string_value()); - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: - // We don't currently support defining a message-typed option, so we - // should never actually get here. - return AddValueError("Option \"" + option_field->full_name() + - "\" is a message. To set fields within it, use " - "syntax like \"" + option_field->name() + - ".foo = value\"."); - break; - } - - return true; -} - -void DescriptorBuilder::OptionInterpreter::SetInt32(int number, int32 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_INT32: - unknown_fields->AddVarint(number, - static_cast(static_cast(value))); - break; - - case FieldDescriptor::TYPE_SFIXED32: - unknown_fields->AddFixed32(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_SINT32: - unknown_fields->AddVarint(number, - google::protobuf::internal::WireFormatLite::ZigZagEncode32(value)); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT32: " << type; - break; - } -} - -void DescriptorBuilder::OptionInterpreter::SetInt64(int number, int64 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_INT64: - unknown_fields->AddVarint(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_SFIXED64: - unknown_fields->AddFixed64(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_SINT64: - unknown_fields->AddVarint(number, - google::protobuf::internal::WireFormatLite::ZigZagEncode64(value)); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_INT64: " << type; - break; - } -} - -void DescriptorBuilder::OptionInterpreter::SetUInt32(int number, uint32 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_UINT32: - unknown_fields->AddVarint(number, static_cast(value)); - break; - - case FieldDescriptor::TYPE_FIXED32: - unknown_fields->AddFixed32(number, static_cast(value)); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT32: " << type; - break; - } -} - -void DescriptorBuilder::OptionInterpreter::SetUInt64(int number, uint64 value, - FieldDescriptor::Type type, UnknownFieldSet* unknown_fields) { - switch (type) { - case FieldDescriptor::TYPE_UINT64: - unknown_fields->AddVarint(number, value); - break; - - case FieldDescriptor::TYPE_FIXED64: - unknown_fields->AddFixed64(number, value); - break; - - default: - GOOGLE_LOG(FATAL) << "Invalid wire type for CPPTYPE_UINT64: " << type; - break; - } -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/descriptor.h b/Resources/NetHook/google/protobuf/descriptor.h deleted file mode 100644 index 7f87dd80..00000000 --- a/Resources/NetHook/google/protobuf/descriptor.h +++ /dev/null @@ -1,1367 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains classes which describe a type of protocol message. -// You can use a message's descriptor to learn at runtime what fields -// it contains and what the types of those fields are. The Message -// interface also allows you to dynamically access and modify individual -// fields by passing the FieldDescriptor of the field you are interested -// in. -// -// Most users will not care about descriptors, because they will write -// code specific to certain protocol types and will simply use the classes -// generated by the protocol compiler directly. Advanced users who want -// to operate on arbitrary types (not known at compile time) may want to -// read descriptors in order to learn about the contents of a message. -// A very small number of users will want to construct their own -// Descriptors, either because they are implementing Message manually or -// because they are writing something like the protocol compiler. -// -// For an example of how you might use descriptors, see the code example -// at the top of message.h. - -#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_H__ -#define GOOGLE_PROTOBUF_DESCRIPTOR_H__ - -#include -#include -#include - - -namespace google { -namespace protobuf { - -// Defined in this file. -class Descriptor; -class FieldDescriptor; -class EnumDescriptor; -class EnumValueDescriptor; -class ServiceDescriptor; -class MethodDescriptor; -class FileDescriptor; -class DescriptorDatabase; -class DescriptorPool; - -// Defined in descriptor.proto -class DescriptorProto; -class FieldDescriptorProto; -class EnumDescriptorProto; -class EnumValueDescriptorProto; -class ServiceDescriptorProto; -class MethodDescriptorProto; -class FileDescriptorProto; -class MessageOptions; -class FieldOptions; -class EnumOptions; -class EnumValueOptions; -class ServiceOptions; -class MethodOptions; -class FileOptions; -class UninterpretedOption; - -// Defined in message.h -class Message; - -// Defined in descriptor.cc -class DescriptorBuilder; -class FileDescriptorTables; - -// Defined in unknown_field_set.h. -class UnknownField; - -// Describes a type of protocol message, or a particular group within a -// message. To obtain the Descriptor for a given message object, call -// Message::GetDescriptor(). Generated message classes also have a -// static method called descriptor() which returns the type's descriptor. -// Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT Descriptor { - public: - // The name of the message type, not including its scope. - const string& name() const; - - // The fully-qualified name of the message type, scope delimited by - // periods. For example, message type "Foo" which is declared in package - // "bar" has full name "bar.Foo". If a type "Baz" is nested within - // Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that - // comes after the last '.', use name(). - const string& full_name() const; - - // Index of this descriptor within the file or containing type's message - // type array. - int index() const; - - // The .proto file in which this message type was defined. Never NULL. - const FileDescriptor* file() const; - - // If this Descriptor describes a nested type, this returns the type - // in which it is nested. Otherwise, returns NULL. - const Descriptor* containing_type() const; - - // Get options for this message type. These are specified in the .proto file - // by placing lines like "option foo = 1234;" in the message definition. - // Allowed options are defined by MessageOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. - const MessageOptions& options() const; - - // Write the contents of this Descriptor into the given DescriptorProto. - // The target DescriptorProto must be clear before calling this; if it - // isn't, the result may be garbage. - void CopyTo(DescriptorProto* proto) const; - - // Write the contents of this decriptor in a human-readable form. Output - // will be suitable for re-parsing. - string DebugString() const; - - // Field stuff ----------------------------------------------------- - - // The number of fields in this message type. - int field_count() const; - // Gets a field by index, where 0 <= index < field_count(). - // These are returned in the order they were defined in the .proto file. - const FieldDescriptor* field(int index) const; - - // Looks up a field by declared tag number. Returns NULL if no such field - // exists. - const FieldDescriptor* FindFieldByNumber(int number) const; - // Looks up a field by name. Returns NULL if no such field exists. - const FieldDescriptor* FindFieldByName(const string& name) const; - - // Looks up a field by lowercased name (as returned by lowercase_name()). - // This lookup may be ambiguous if multiple field names differ only by case, - // in which case the field returned is chosen arbitrarily from the matches. - const FieldDescriptor* FindFieldByLowercaseName( - const string& lowercase_name) const; - - // Looks up a field by camel-case name (as returned by camelcase_name()). - // This lookup may be ambiguous if multiple field names differ in a way that - // leads them to have identical camel-case names, in which case the field - // returned is chosen arbitrarily from the matches. - const FieldDescriptor* FindFieldByCamelcaseName( - const string& camelcase_name) const; - - // Nested type stuff ----------------------------------------------- - - // The number of nested types in this message type. - int nested_type_count() const; - // Gets a nested type by index, where 0 <= index < nested_type_count(). - // These are returned in the order they were defined in the .proto file. - const Descriptor* nested_type(int index) const; - - // Looks up a nested type by name. Returns NULL if no such nested type - // exists. - const Descriptor* FindNestedTypeByName(const string& name) const; - - // Enum stuff ------------------------------------------------------ - - // The number of enum types in this message type. - int enum_type_count() const; - // Gets an enum type by index, where 0 <= index < enum_type_count(). - // These are returned in the order they were defined in the .proto file. - const EnumDescriptor* enum_type(int index) const; - - // Looks up an enum type by name. Returns NULL if no such enum type exists. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - - // Looks up an enum value by name, among all enum types in this message. - // Returns NULL if no such value exists. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - - // Extensions ------------------------------------------------------ - - // A range of field numbers which are designated for third-party - // extensions. - struct ExtensionRange { - int start; // inclusive - int end; // exclusive - }; - - // The number of extension ranges in this message type. - int extension_range_count() const; - // Gets an extension range by index, where 0 <= index < - // extension_range_count(). These are returned in the order they were defined - // in the .proto file. - const ExtensionRange* extension_range(int index) const; - - // Returns true if the number is in one of the extension ranges. - bool IsExtensionNumber(int number) const; - - // The number of extensions -- extending *other* messages -- that were - // defined nested within this message type's scope. - int extension_count() const; - // Get an extension by index, where 0 <= index < extension_count(). - // These are returned in the order they were defined in the .proto file. - const FieldDescriptor* extension(int index) const; - - // Looks up a named extension (which extends some *other* message type) - // defined within this message type's scope. - const FieldDescriptor* FindExtensionByName(const string& name) const; - - // Similar to FindFieldByLowercaseName(), but finds extensions defined within - // this message type's scope. - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; - - // Similar to FindFieldByCamelcaseName(), but finds extensions defined within - // this message type's scope. - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; - - private: - typedef MessageOptions OptionsType; - - // Internal version of DebugString; controls the level of indenting for - // correct depth - void DebugString(int depth, string *contents) const; - - const string* name_; - const string* full_name_; - const FileDescriptor* file_; - const Descriptor* containing_type_; - const MessageOptions* options_; - - // True if this is a placeholder for an unknown type. - bool is_placeholder_; - // True if this is a placeholder and the type name wasn't fully-qualified. - bool is_unqualified_placeholder_; - - int field_count_; - FieldDescriptor* fields_; - int nested_type_count_; - Descriptor* nested_types_; - int enum_type_count_; - EnumDescriptor* enum_types_; - int extension_range_count_; - ExtensionRange* extension_ranges_; - int extension_count_; - FieldDescriptor* extensions_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() in descriptor.cc - // and update them to initialize the field. - - // Must be constructed using DescriptorPool. - Descriptor() {} - friend class DescriptorBuilder; - friend class EnumDescriptor; - friend class FieldDescriptor; - friend class MethodDescriptor; - friend class FileDescriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Descriptor); -}; - -// Describes a single field of a message. To get the descriptor for a given -// field, first get the Descriptor for the message in which it is defined, -// then call Descriptor::FindFieldByName(). To get a FieldDescriptor for -// an extension, do one of the following: -// - Get the Descriptor or FileDescriptor for its containing scope, then -// call Descriptor::FindExtensionByName() or -// FileDescriptor::FindExtensionByName(). -// - Given a DescriptorPool, call DescriptorPool::FindExtensionByNumber(). -// - Given a Reflection for a message object, call -// Reflection::FindKnownExtensionByName() or -// Reflection::FindKnownExtensionByNumber(). -// Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FieldDescriptor { - public: - // Identifies a field type. 0 is reserved for errors. The order is weird - // for historical reasons. Types 12 and up are new in proto2. - enum Type { - TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire. - TYPE_FLOAT = 2, // float, exactly four bytes on the wire. - TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers - // take 10 bytes. Use TYPE_SINT64 if negative - // values are likely. - TYPE_UINT64 = 4, // uint64, varint on the wire. - TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers - // take 10 bytes. Use TYPE_SINT32 if negative - // values are likely. - TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire. - TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire. - TYPE_BOOL = 8, // bool, varint on the wire. - TYPE_STRING = 9, // UTF-8 text. - TYPE_GROUP = 10, // Tag-delimited message. Deprecated. - TYPE_MESSAGE = 11, // Length-delimited message. - - TYPE_BYTES = 12, // Arbitrary byte array. - TYPE_UINT32 = 13, // uint32, varint on the wire - TYPE_ENUM = 14, // Enum, varint on the wire - TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire - TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire - TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire - TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire - - MAX_TYPE = 18, // Constant useful for defining lookup tables - // indexed by Type. - }; - - // Specifies the C++ data type used to represent the field. There is a - // fixed mapping from Type to CppType where each Type maps to exactly one - // CppType. 0 is reserved for errors. - enum CppType { - CPPTYPE_INT32 = 1, // TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32 - CPPTYPE_INT64 = 2, // TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64 - CPPTYPE_UINT32 = 3, // TYPE_UINT32, TYPE_FIXED32 - CPPTYPE_UINT64 = 4, // TYPE_UINT64, TYPE_FIXED64 - CPPTYPE_DOUBLE = 5, // TYPE_DOUBLE - CPPTYPE_FLOAT = 6, // TYPE_FLOAT - CPPTYPE_BOOL = 7, // TYPE_BOOL - CPPTYPE_ENUM = 8, // TYPE_ENUM - CPPTYPE_STRING = 9, // TYPE_STRING, TYPE_BYTES - CPPTYPE_MESSAGE = 10, // TYPE_MESSAGE, TYPE_GROUP - - MAX_CPPTYPE = 10, // Constant useful for defining lookup tables - // indexed by CppType. - }; - - // Identifies whether the field is optional, required, or repeated. 0 is - // reserved for errors. - enum Label { - LABEL_OPTIONAL = 1, // optional - LABEL_REQUIRED = 2, // required - LABEL_REPEATED = 3, // repeated - - MAX_LABEL = 3, // Constant useful for defining lookup tables - // indexed by Label. - }; - - // Valid field numbers are positive integers up to kMaxNumber. - static const int kMaxNumber = (1 << 29) - 1; - - // First field number reserved for the protocol buffer library implementation. - // Users may not declare fields that use reserved numbers. - static const int kFirstReservedNumber = 19000; - // Last field number reserved for the protocol buffer library implementation. - // Users may not declare fields that use reserved numbers. - static const int kLastReservedNumber = 19999; - - const string& name() const; // Name of this field within the message. - const string& full_name() const; // Fully-qualified name of the field. - const FileDescriptor* file() const;// File in which this field was defined. - bool is_extension() const; // Is this an extension field? - int number() const; // Declared tag number. - - // Same as name() except converted to lower-case. This (and especially the - // FindFieldByLowercaseName() method) can be useful when parsing formats - // which prefer to use lowercase naming style. (Although, technically - // field names should be lowercased anyway according to the protobuf style - // guide, so this only makes a difference when dealing with old .proto files - // which do not follow the guide.) - const string& lowercase_name() const; - - // Same as name() except converted to camel-case. In this conversion, any - // time an underscore appears in the name, it is removed and the next - // letter is capitalized. Furthermore, the first letter of the name is - // lower-cased. Examples: - // FooBar -> fooBar - // foo_bar -> fooBar - // fooBar -> fooBar - // This (and especially the FindFieldByCamelcaseName() method) can be useful - // when parsing formats which prefer to use camel-case naming style. - const string& camelcase_name() const; - - Type type() const; // Declared type of this field. - CppType cpp_type() const; // C++ type of this field. - Label label() const; // optional/required/repeated - - bool is_required() const; // shorthand for label() == LABEL_REQUIRED - bool is_optional() const; // shorthand for label() == LABEL_OPTIONAL - bool is_repeated() const; // shorthand for label() == LABEL_REPEATED - bool is_packable() const; // shorthand for is_repeated() && - // IsTypePackable(type()) - - // Index of this field within the message's field array, or the file or - // extension scope's extensions array. - int index() const; - - // Does this field have an explicitly-declared default value? - bool has_default_value() const; - - // Get the field default value if cpp_type() == CPPTYPE_INT32. If no - // explicit default was defined, the default is 0. - int32 default_value_int32() const; - // Get the field default value if cpp_type() == CPPTYPE_INT64. If no - // explicit default was defined, the default is 0. - int64 default_value_int64() const; - // Get the field default value if cpp_type() == CPPTYPE_UINT32. If no - // explicit default was defined, the default is 0. - uint32 default_value_uint32() const; - // Get the field default value if cpp_type() == CPPTYPE_UINT64. If no - // explicit default was defined, the default is 0. - uint64 default_value_uint64() const; - // Get the field default value if cpp_type() == CPPTYPE_FLOAT. If no - // explicit default was defined, the default is 0.0. - float default_value_float() const; - // Get the field default value if cpp_type() == CPPTYPE_DOUBLE. If no - // explicit default was defined, the default is 0.0. - double default_value_double() const; - // Get the field default value if cpp_type() == CPPTYPE_BOOL. If no - // explicit default was defined, the default is false. - bool default_value_bool() const; - // Get the field default value if cpp_type() == CPPTYPE_ENUM. If no - // explicit default was defined, the default is the first value defined - // in the enum type (all enum types are required to have at least one value). - // This never returns NULL. - const EnumValueDescriptor* default_value_enum() const; - // Get the field default value if cpp_type() == CPPTYPE_STRING. If no - // explicit default was defined, the default is the empty string. - const string& default_value_string() const; - - // The Descriptor for the message of which this is a field. For extensions, - // this is the extended type. Never NULL. - const Descriptor* containing_type() const; - - // An extension may be declared within the scope of another message. If this - // field is an extension (is_extension() is true), then extension_scope() - // returns that message, or NULL if the extension was declared at global - // scope. If this is not an extension, extension_scope() is undefined (may - // assert-fail). - const Descriptor* extension_scope() const; - - // If type is TYPE_MESSAGE or TYPE_GROUP, returns a descriptor for the - // message or the group type. Otherwise, undefined. - const Descriptor* message_type() const; - // If type is TYPE_ENUM, returns a descriptor for the enum. Otherwise, - // undefined. - const EnumDescriptor* enum_type() const; - - // EXPERIMENTAL; DO NOT USE. - // If this field is a map field, experimental_map_key() is the field - // that is the key for this map. - // experimental_map_key()->containing_type() is the same as message_type(). - const FieldDescriptor* experimental_map_key() const; - - // Get the FieldOptions for this field. This includes things listed in - // square brackets after the field definition. E.g., the field: - // optional string text = 1 [ctype=CORD]; - // has the "ctype" option set. Allowed options are defined by FieldOptions - // in google/protobuf/descriptor.proto, and any available extensions of that - // message. - const FieldOptions& options() const; - - // See Descriptor::CopyTo(). - void CopyTo(FieldDescriptorProto* proto) const; - - // See Descriptor::DebugString(). - string DebugString() const; - - // Helper method to get the CppType for a particular Type. - static CppType TypeToCppType(Type type); - - // Return true iff [packed = true] is valid for fields of this type. - static inline bool IsTypePackable(Type field_type); - - private: - typedef FieldOptions OptionsType; - - // See Descriptor::DebugString(). - void DebugString(int depth, string *contents) const; - - // formats the default value appropriately and returns it as a string. - // Must have a default value to call this. If quote_string_type is true, then - // types of CPPTYPE_STRING whill be surrounded by quotes and CEscaped. - string DefaultValueAsString(bool quote_string_type) const; - - const string* name_; - const string* full_name_; - const string* lowercase_name_; - const string* camelcase_name_; - const FileDescriptor* file_; - int number_; - Type type_; - Label label_; - bool is_extension_; - const Descriptor* containing_type_; - const Descriptor* extension_scope_; - const Descriptor* message_type_; - const EnumDescriptor* enum_type_; - const FieldDescriptor* experimental_map_key_; - const FieldOptions* options_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() in - // descriptor.cc and update them to initialize the field. - - bool has_default_value_; - union { - int32 default_value_int32_; - int64 default_value_int64_; - uint32 default_value_uint32_; - uint64 default_value_uint64_; - float default_value_float_; - double default_value_double_; - bool default_value_bool_; - - const EnumValueDescriptor* default_value_enum_; - const string* default_value_string_; - }; - - static const CppType kTypeToCppTypeMap[MAX_TYPE + 1]; - - static const char * const kTypeToName[MAX_TYPE + 1]; - - static const char * const kLabelToName[MAX_LABEL + 1]; - - // Must be constructed using DescriptorPool. - FieldDescriptor() {} - friend class DescriptorBuilder; - friend class FileDescriptor; - friend class Descriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldDescriptor); -}; - -// Describes an enum type defined in a .proto file. To get the EnumDescriptor -// for a generated enum type, call TypeName_descriptor(). Use DescriptorPool -// to construct your own descriptors. -class LIBPROTOBUF_EXPORT EnumDescriptor { - public: - // The name of this enum type in the containing scope. - const string& name() const; - - // The fully-qualified name of the enum type, scope delimited by periods. - const string& full_name() const; - - // Index of this enum within the file or containing message's enum array. - int index() const; - - // The .proto file in which this enum type was defined. Never NULL. - const FileDescriptor* file() const; - - // The number of values for this EnumDescriptor. Guaranteed to be greater - // than zero. - int value_count() const; - // Gets a value by index, where 0 <= index < value_count(). - // These are returned in the order they were defined in the .proto file. - const EnumValueDescriptor* value(int index) const; - - // Looks up a value by name. Returns NULL if no such value exists. - const EnumValueDescriptor* FindValueByName(const string& name) const; - // Looks up a value by number. Returns NULL if no such value exists. If - // multiple values have this number, the first one defined is returned. - const EnumValueDescriptor* FindValueByNumber(int number) const; - - // If this enum type is nested in a message type, this is that message type. - // Otherwise, NULL. - const Descriptor* containing_type() const; - - // Get options for this enum type. These are specified in the .proto file by - // placing lines like "option foo = 1234;" in the enum definition. Allowed - // options are defined by EnumOptions in google/protobuf/descriptor.proto, - // and any available extensions of that message. - const EnumOptions& options() const; - - // See Descriptor::CopyTo(). - void CopyTo(EnumDescriptorProto* proto) const; - - // See Descriptor::DebugString(). - string DebugString() const; - - private: - typedef EnumOptions OptionsType; - - // See Descriptor::DebugString(). - void DebugString(int depth, string *contents) const; - - const string* name_; - const string* full_name_; - const FileDescriptor* file_; - const Descriptor* containing_type_; - const EnumOptions* options_; - - // True if this is a placeholder for an unknown type. - bool is_placeholder_; - // True if this is a placeholder and the type name wasn't fully-qualified. - bool is_unqualified_placeholder_; - - int value_count_; - EnumValueDescriptor* values_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() in - // descriptor.cc and update them to initialize the field. - - // Must be constructed using DescriptorPool. - EnumDescriptor() {} - friend class DescriptorBuilder; - friend class Descriptor; - friend class FieldDescriptor; - friend class EnumValueDescriptor; - friend class FileDescriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumDescriptor); -}; - -// Describes an individual enum constant of a particular type. To get the -// EnumValueDescriptor for a given enum value, first get the EnumDescriptor -// for its type, then use EnumDescriptor::FindValueByName() or -// EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct -// your own descriptors. -class LIBPROTOBUF_EXPORT EnumValueDescriptor { - public: - const string& name() const; // Name of this enum constant. - int index() const; // Index within the enums's Descriptor. - int number() const; // Numeric value of this enum constant. - - // The full_name of an enum value is a sibling symbol of the enum type. - // e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually - // "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT - // "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform - // with C++ scoping rules for enums. - const string& full_name() const; - - // The type of this value. Never NULL. - const EnumDescriptor* type() const; - - // Get options for this enum value. These are specified in the .proto file - // by adding text like "[foo = 1234]" after an enum value definition. - // Allowed options are defined by EnumValueOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. - const EnumValueOptions& options() const; - - // See Descriptor::CopyTo(). - void CopyTo(EnumValueDescriptorProto* proto) const; - - // See Descriptor::DebugString(). - string DebugString() const; - - private: - typedef EnumValueOptions OptionsType; - - // See Descriptor::DebugString(). - void DebugString(int depth, string *contents) const; - - const string* name_; - const string* full_name_; - int number_; - const EnumDescriptor* type_; - const EnumValueOptions* options_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() - // in descriptor.cc and update them to initialize the field. - - // Must be constructed using DescriptorPool. - EnumValueDescriptor() {} - friend class DescriptorBuilder; - friend class EnumDescriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumValueDescriptor); -}; - -// Describes an RPC service. To get the ServiceDescriptor for a service, -// call Service::GetDescriptor(). Generated service classes also have a -// static method called descriptor() which returns the type's -// ServiceDescriptor. Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT ServiceDescriptor { - public: - // The name of the service, not including its containing scope. - const string& name() const; - // The fully-qualified name of the service, scope delimited by periods. - const string& full_name() const; - // Index of this service within the file's services array. - int index() const; - - // The .proto file in which this service was defined. Never NULL. - const FileDescriptor* file() const; - - // Get options for this service type. These are specified in the .proto file - // by placing lines like "option foo = 1234;" in the service definition. - // Allowed options are defined by ServiceOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. - const ServiceOptions& options() const; - - // The number of methods this service defines. - int method_count() const; - // Gets a MethodDescriptor by index, where 0 <= index < method_count(). - // These are returned in the order they were defined in the .proto file. - const MethodDescriptor* method(int index) const; - - // Look up a MethodDescriptor by name. - const MethodDescriptor* FindMethodByName(const string& name) const; - - // See Descriptor::CopyTo(). - void CopyTo(ServiceDescriptorProto* proto) const; - - // See Descriptor::DebugString(). - string DebugString() const; - - private: - typedef ServiceOptions OptionsType; - - // See Descriptor::DebugString(). - void DebugString(string *contents) const; - - const string* name_; - const string* full_name_; - const FileDescriptor* file_; - const ServiceOptions* options_; - int method_count_; - MethodDescriptor* methods_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() in - // descriptor.cc and update them to initialize the field. - - // Must be constructed using DescriptorPool. - ServiceDescriptor() {} - friend class DescriptorBuilder; - friend class FileDescriptor; - friend class MethodDescriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ServiceDescriptor); -}; - -// Describes an individual service method. To obtain a MethodDescriptor given -// a service, first get its ServiceDescriptor, then call -// ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your -// own descriptors. -class LIBPROTOBUF_EXPORT MethodDescriptor { - public: - // Name of this method, not including containing scope. - const string& name() const; - // The fully-qualified name of the method, scope delimited by periods. - const string& full_name() const; - // Index within the service's Descriptor. - int index() const; - - // Gets the service to which this method belongs. Never NULL. - const ServiceDescriptor* service() const; - - // Gets the type of protocol message which this method accepts as input. - const Descriptor* input_type() const; - // Gets the type of protocol message which this message produces as output. - const Descriptor* output_type() const; - - // Get options for this method. These are specified in the .proto file by - // placing lines like "option foo = 1234;" in curly-braces after a method - // declaration. Allowed options are defined by MethodOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. - const MethodOptions& options() const; - - // See Descriptor::CopyTo(). - void CopyTo(MethodDescriptorProto* proto) const; - - // See Descriptor::DebugString(). - string DebugString() const; - - private: - typedef MethodOptions OptionsType; - - // See Descriptor::DebugString(). - void DebugString(int depth, string *contents) const; - - const string* name_; - const string* full_name_; - const ServiceDescriptor* service_; - const Descriptor* input_type_; - const Descriptor* output_type_; - const MethodOptions* options_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() in - // descriptor.cc and update them to initialize the field. - - // Must be constructed using DescriptorPool. - MethodDescriptor() {} - friend class DescriptorBuilder; - friend class ServiceDescriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MethodDescriptor); -}; - -// Describes a whole .proto file. To get the FileDescriptor for a compiled-in -// file, get the descriptor for something defined in that file and call -// descriptor->file(). Use DescriptorPool to construct your own descriptors. -class LIBPROTOBUF_EXPORT FileDescriptor { - public: - // The filename, relative to the source tree. - // e.g. "google/protobuf/descriptor.proto" - const string& name() const; - - // The package, e.g. "google.protobuf.compiler". - const string& package() const; - - // The DescriptorPool in which this FileDescriptor and all its contents were - // allocated. Never NULL. - const DescriptorPool* pool() const; - - // The number of files imported by this one. - int dependency_count() const; - // Gets an imported file by index, where 0 <= index < dependency_count(). - // These are returned in the order they were defined in the .proto file. - const FileDescriptor* dependency(int index) const; - - // Number of top-level message types defined in this file. (This does not - // include nested types.) - int message_type_count() const; - // Gets a top-level message type, where 0 <= index < message_type_count(). - // These are returned in the order they were defined in the .proto file. - const Descriptor* message_type(int index) const; - - // Number of top-level enum types defined in this file. (This does not - // include nested types.) - int enum_type_count() const; - // Gets a top-level enum type, where 0 <= index < enum_type_count(). - // These are returned in the order they were defined in the .proto file. - const EnumDescriptor* enum_type(int index) const; - - // Number of services defined in this file. - int service_count() const; - // Gets a service, where 0 <= index < service_count(). - // These are returned in the order they were defined in the .proto file. - const ServiceDescriptor* service(int index) const; - - // Number of extensions defined at file scope. (This does not include - // extensions nested within message types.) - int extension_count() const; - // Gets an extension's descriptor, where 0 <= index < extension_count(). - // These are returned in the order they were defined in the .proto file. - const FieldDescriptor* extension(int index) const; - - // Get options for this file. These are specified in the .proto file by - // placing lines like "option foo = 1234;" at the top level, outside of any - // other definitions. Allowed options are defined by FileOptions in - // google/protobuf/descriptor.proto, and any available extensions of that - // message. - const FileOptions& options() const; - - // Find a top-level message type by name. Returns NULL if not found. - const Descriptor* FindMessageTypeByName(const string& name) const; - // Find a top-level enum type by name. Returns NULL if not found. - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - // Find an enum value defined in any top-level enum by name. Returns NULL if - // not found. - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - // Find a service definition by name. Returns NULL if not found. - const ServiceDescriptor* FindServiceByName(const string& name) const; - // Find a top-level extension definition by name. Returns NULL if not found. - const FieldDescriptor* FindExtensionByName(const string& name) const; - // Similar to FindExtensionByName(), but searches by lowercased-name. See - // Descriptor::FindFieldByLowercaseName(). - const FieldDescriptor* FindExtensionByLowercaseName(const string& name) const; - // Similar to FindExtensionByName(), but searches by camelcased-name. See - // Descriptor::FindFieldByCamelcaseName(). - const FieldDescriptor* FindExtensionByCamelcaseName(const string& name) const; - - // See Descriptor::CopyTo(). - void CopyTo(FileDescriptorProto* proto) const; - - // See Descriptor::DebugString(). - string DebugString() const; - - private: - typedef FileOptions OptionsType; - - const string* name_; - const string* package_; - const DescriptorPool* pool_; - int dependency_count_; - const FileDescriptor** dependencies_; - int message_type_count_; - Descriptor* message_types_; - int enum_type_count_; - EnumDescriptor* enum_types_; - int service_count_; - ServiceDescriptor* services_; - int extension_count_; - FieldDescriptor* extensions_; - const FileOptions* options_; - - const FileDescriptorTables* tables_; - // IMPORTANT: If you add a new field, make sure to search for all instances - // of Allocate() and AllocateArray() in - // descriptor.cc and update them to initialize the field. - - FileDescriptor() {} - friend class DescriptorBuilder; - friend class Descriptor; - friend class FieldDescriptor; - friend class EnumDescriptor; - friend class ServiceDescriptor; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileDescriptor); -}; - -// =================================================================== - -// Used to construct descriptors. -// -// Normally you won't want to build your own descriptors. Message classes -// constructed by the protocol compiler will provide them for you. However, -// if you are implementing Message on your own, or if you are writing a -// program which can operate on totally arbitrary types and needs to load -// them from some sort of database, you might need to. -// -// Since Descriptors are composed of a whole lot of cross-linked bits of -// data that would be a pain to put together manually, the -// DescriptorPool class is provided to make the process easier. It can -// take a FileDescriptorProto (defined in descriptor.proto), validate it, -// and convert it to a set of nicely cross-linked Descriptors. -// -// DescriptorPool also helps with memory management. Descriptors are -// composed of many objects containing static data and pointers to each -// other. In all likelihood, when it comes time to delete this data, -// you'll want to delete it all at once. In fact, it is not uncommon to -// have a whole pool of descriptors all cross-linked with each other which -// you wish to delete all at once. This class represents such a pool, and -// handles the memory management for you. -// -// You can also search for descriptors within a DescriptorPool by name, and -// extensions by number. -class LIBPROTOBUF_EXPORT DescriptorPool { - public: - // Create a normal, empty DescriptorPool. - DescriptorPool(); - - // Constructs a DescriptorPool that, when it can't find something among the - // descriptors already in the pool, looks for it in the given - // DescriptorDatabase. - // Notes: - // - If a DescriptorPool is constructed this way, its BuildFile*() methods - // must not be called (they will assert-fail). The only way to populate - // the pool with descriptors is to call the Find*By*() methods. - // - The Find*By*() methods may block the calling thread if the - // DescriptorDatabase blocks. This in turn means that parsing messages - // may block if they need to look up extensions. - // - The Find*By*() methods will use mutexes for thread-safety, thus making - // them slower even when they don't have to fall back to the database. - // In fact, even the Find*By*() methods of descriptor objects owned by - // this pool will be slower, since they will have to obtain locks too. - // - An ErrorCollector may optionally be given to collect validation errors - // in files loaded from the database. If not given, errors will be printed - // to GOOGLE_LOG(ERROR). Remember that files are built on-demand, so this - // ErrorCollector may be called from any thread that calls one of the - // Find*By*() methods. - class ErrorCollector; - explicit DescriptorPool(DescriptorDatabase* fallback_database, - ErrorCollector* error_collector = NULL); - - ~DescriptorPool(); - - // Get a pointer to the generated pool. Generated protocol message classes - // which are compiled into the binary will allocate their descriptors in - // this pool. Do not add your own descriptors to this pool. - static const DescriptorPool* generated_pool(); - - // Find a FileDescriptor in the pool by file name. Returns NULL if not - // found. - const FileDescriptor* FindFileByName(const string& name) const; - - // Find the FileDescriptor in the pool which defines the given symbol. - // If any of the Find*ByName() methods below would succeed, then this is - // equivalent to calling that method and calling the result's file() method. - // Otherwise this returns NULL. - const FileDescriptor* FindFileContainingSymbol( - const string& symbol_name) const; - - // Looking up descriptors ------------------------------------------ - // These find descriptors by fully-qualified name. These will find both - // top-level descriptors and nested descriptors. They return NULL if not - // found. - - const Descriptor* FindMessageTypeByName(const string& name) const; - const FieldDescriptor* FindFieldByName(const string& name) const; - const FieldDescriptor* FindExtensionByName(const string& name) const; - const EnumDescriptor* FindEnumTypeByName(const string& name) const; - const EnumValueDescriptor* FindEnumValueByName(const string& name) const; - const ServiceDescriptor* FindServiceByName(const string& name) const; - const MethodDescriptor* FindMethodByName(const string& name) const; - - // Finds an extension of the given type by number. The extendee must be - // a member of this DescriptorPool or one of its underlays. - const FieldDescriptor* FindExtensionByNumber(const Descriptor* extendee, - int number) const; - - // Finds extensions of extendee. The extensions will be appended to - // out in an undefined order. Only extensions defined directly in - // this DescriptorPool or one of its underlays are guaranteed to be - // found: extensions defined in the fallback database might not be found - // depending on the database implementation. - void FindAllExtensions(const Descriptor* extendee, - vector* out) const; - - // Building descriptors -------------------------------------------- - - // When converting a FileDescriptorProto to a FileDescriptor, various - // errors might be detected in the input. The caller may handle these - // programmatically by implementing an ErrorCollector. - class LIBPROTOBUF_EXPORT ErrorCollector { - public: - inline ErrorCollector() {} - virtual ~ErrorCollector(); - - // These constants specify what exact part of the construct is broken. - // This is useful e.g. for mapping the error back to an exact location - // in a .proto file. - enum ErrorLocation { - NAME, // the symbol name, or the package name for files - NUMBER, // field or extension range number - TYPE, // field type - EXTENDEE, // field extendee - DEFAULT_VALUE, // field default value - INPUT_TYPE, // method input type - OUTPUT_TYPE, // method output type - OPTION_NAME, // name in assignment - OPTION_VALUE, // value in option assignment - OTHER // some other problem - }; - - // Reports an error in the FileDescriptorProto. - virtual void AddError( - const string& filename, // File name in which the error occurred. - const string& element_name, // Full name of the erroneous element. - const Message* descriptor, // Descriptor of the erroneous element. - ErrorLocation location, // One of the location constants, above. - const string& message // Human-readable error message. - ) = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); - }; - - // Convert the FileDescriptorProto to real descriptors and place them in - // this DescriptorPool. All dependencies of the file must already be in - // the pool. Returns the resulting FileDescriptor, or NULL if there were - // problems with the input (e.g. the message was invalid, or dependencies - // were missing). Details about the errors are written to GOOGLE_LOG(ERROR). - const FileDescriptor* BuildFile(const FileDescriptorProto& proto); - - // Same as BuildFile() except errors are sent to the given ErrorCollector. - const FileDescriptor* BuildFileCollectingErrors( - const FileDescriptorProto& proto, - ErrorCollector* error_collector); - - // By default, it is an error if a FileDescriptorProto contains references - // to types or other files that are not found in the DescriptorPool (or its - // backing DescriptorDatabase, if any). If you call - // AllowUnknownDependencies(), however, then unknown types and files - // will be replaced by placeholder descriptors. This can allow you to - // perform some useful operations with a .proto file even if you do not - // have access to other .proto files on which it depends. However, some - // heuristics must be used to fill in the gaps in information, and these - // can lead to descriptors which are inaccurate. For example, the - // DescriptorPool may be forced to guess whether an unknown type is a message - // or an enum, as well as what package it resides in. Furthermore, - // placeholder types will not be discoverable via FindMessageTypeByName() - // and similar methods, which could confuse some descriptor-based algorithms. - // Generally, the results of this option should only be relied upon for - // debugging purposes. - void AllowUnknownDependencies() { allow_unknown_ = true; } - - // Internal stuff -------------------------------------------------- - // These methods MUST NOT be called from outside the proto2 library. - // These methods may contain hidden pitfalls and may be removed in a - // future library version. - - // Create a DescriptorPool which is overlaid on top of some other pool. - // If you search for a descriptor in the overlay and it is not found, the - // underlay will be searched as a backup. If the underlay has its own - // underlay, that will be searched next, and so on. This also means that - // files built in the overlay will be cross-linked with the underlay's - // descriptors if necessary. The underlay remains property of the caller; - // it must remain valid for the lifetime of the newly-constructed pool. - // - // Example: Say you want to parse a .proto file at runtime in order to use - // its type with a DynamicMessage. Say this .proto file has dependencies, - // but you know that all the dependencies will be things that are already - // compiled into the binary. For ease of use, you'd like to load the types - // right out of generated_pool() rather than have to parse redundant copies - // of all these .protos and runtime. But, you don't want to add the parsed - // types directly into generated_pool(): this is not allowed, and would be - // bad design anyway. So, instead, you could use generated_pool() as an - // underlay for a new DescriptorPool in which you add only the new file. - // - // WARNING: Use of underlays can lead to many subtle gotchas. Instead, - // try to formulate what you want to do in terms of DescriptorDatabases. - explicit DescriptorPool(const DescriptorPool* underlay); - - // Called by generated classes at init time to add their descriptors to - // generated_pool. Do NOT call this in your own code! filename must be a - // permanent string (e.g. a string literal). - static void InternalAddGeneratedFile( - const void* encoded_file_descriptor, int size); - - - // For internal use only: Gets a non-const pointer to the generated pool. - // This is called at static-initialization time only, so thread-safety is - // not a concern. If both an underlay and a fallback database are present, - // the fallback database takes precedence. - static DescriptorPool* internal_generated_pool(); - - // For internal use only: Changes the behavior of BuildFile() such that it - // allows the file to make reference to message types declared in other files - // which it did not officially declare as dependencies. - void InternalDontEnforceDependencies(); - - // For internal use only. - void internal_set_underlay(const DescriptorPool* underlay) { - underlay_ = underlay; - } - - // For internal (unit test) use only: Returns true if a FileDescriptor has - // been constructed for the given file, false otherwise. Useful for testing - // lazy descriptor initialization behavior. - bool InternalIsFileLoaded(const string& filename) const; - - private: - friend class Descriptor; - friend class FieldDescriptor; - friend class EnumDescriptor; - friend class ServiceDescriptor; - friend class FileDescriptor; - friend class DescriptorBuilder; - - // Tries to find something in the fallback database and link in the - // corresponding proto file. Returns true if successful, in which case - // the caller should search for the thing again. These are declared - // const because they are called by (semantically) const methods. - bool TryFindFileInFallbackDatabase(const string& name) const; - bool TryFindSymbolInFallbackDatabase(const string& name) const; - bool TryFindExtensionInFallbackDatabase(const Descriptor* containing_type, - int field_number) const; - - // Like BuildFile() but called internally when the file has been loaded from - // fallback_database_. Declared const because it is called by (semantically) - // const methods. - const FileDescriptor* BuildFileFromDatabase( - const FileDescriptorProto& proto) const; - - // If fallback_database_ is NULL, this is NULL. Otherwise, this is a mutex - // which must be locked while accessing tables_. - Mutex* mutex_; - - // See constructor. - DescriptorDatabase* fallback_database_; - ErrorCollector* default_error_collector_; - const DescriptorPool* underlay_; - - // This class contains a lot of hash maps with complicated types that - // we'd like to keep out of the header. - class Tables; - scoped_ptr tables_; - - bool enforce_dependencies_; - bool allow_unknown_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPool); -}; - -// inline methods ==================================================== - -// These macros makes this repetitive code more readable. -#define PROTOBUF_DEFINE_ACCESSOR(CLASS, FIELD, TYPE) \ - inline TYPE CLASS::FIELD() const { return FIELD##_; } - -// Strings fields are stored as pointers but returned as const references. -#define PROTOBUF_DEFINE_STRING_ACCESSOR(CLASS, FIELD) \ - inline const string& CLASS::FIELD() const { return *FIELD##_; } - -// Arrays take an index parameter, obviously. -#define PROTOBUF_DEFINE_ARRAY_ACCESSOR(CLASS, FIELD, TYPE) \ - inline TYPE CLASS::FIELD(int index) const { return FIELD##s_ + index; } - -#define PROTOBUF_DEFINE_OPTIONS_ACCESSOR(CLASS, TYPE) \ - inline const TYPE& CLASS::options() const { return *options_; } - -PROTOBUF_DEFINE_STRING_ACCESSOR(Descriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(Descriptor, full_name) -PROTOBUF_DEFINE_ACCESSOR(Descriptor, file, const FileDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(Descriptor, containing_type, const Descriptor*) - -PROTOBUF_DEFINE_ACCESSOR(Descriptor, field_count, int) -PROTOBUF_DEFINE_ACCESSOR(Descriptor, nested_type_count, int) -PROTOBUF_DEFINE_ACCESSOR(Descriptor, enum_type_count, int) - -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, field, const FieldDescriptor*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, nested_type, const Descriptor*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, enum_type, const EnumDescriptor*) - -PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_range_count, int) -PROTOBUF_DEFINE_ACCESSOR(Descriptor, extension_count, int) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension_range, - const Descriptor::ExtensionRange*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(Descriptor, extension, - const FieldDescriptor*) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(Descriptor, MessageOptions); - -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, full_name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, lowercase_name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, camelcase_name) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, file, const FileDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, number, int) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, is_extension, bool) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, type, FieldDescriptor::Type) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, label, FieldDescriptor::Label) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, containing_type, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, extension_scope, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, message_type, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, enum_type, const EnumDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, experimental_map_key, - const FieldDescriptor*) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FieldDescriptor, FieldOptions); -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, has_default_value, bool) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int32 , int32 ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_int64 , int64 ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint32, uint32) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_uint64, uint64) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_float , float ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_double, double) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_bool , bool ) -PROTOBUF_DEFINE_ACCESSOR(FieldDescriptor, default_value_enum, - const EnumValueDescriptor*) -PROTOBUF_DEFINE_STRING_ACCESSOR(FieldDescriptor, default_value_string) - -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumDescriptor, full_name) -PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, file, const FileDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, containing_type, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(EnumDescriptor, value_count, int) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(EnumDescriptor, value, - const EnumValueDescriptor*) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumDescriptor, EnumOptions); - -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumValueDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(EnumValueDescriptor, full_name) -PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, number, int) -PROTOBUF_DEFINE_ACCESSOR(EnumValueDescriptor, type, const EnumDescriptor*) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(EnumValueDescriptor, EnumValueOptions); - -PROTOBUF_DEFINE_STRING_ACCESSOR(ServiceDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(ServiceDescriptor, full_name) -PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, file, const FileDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(ServiceDescriptor, method_count, int) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(ServiceDescriptor, method, - const MethodDescriptor*) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(ServiceDescriptor, ServiceOptions); - -PROTOBUF_DEFINE_STRING_ACCESSOR(MethodDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(MethodDescriptor, full_name) -PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, service, const ServiceDescriptor*) -PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, input_type, const Descriptor*) -PROTOBUF_DEFINE_ACCESSOR(MethodDescriptor, output_type, const Descriptor*) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(MethodDescriptor, MethodOptions); - -PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, name) -PROTOBUF_DEFINE_STRING_ACCESSOR(FileDescriptor, package) -PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, pool, const DescriptorPool*) -PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, dependency_count, int) -PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, message_type_count, int) -PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, enum_type_count, int) -PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, service_count, int) -PROTOBUF_DEFINE_ACCESSOR(FileDescriptor, extension_count, int) -PROTOBUF_DEFINE_OPTIONS_ACCESSOR(FileDescriptor, FileOptions); - -PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, message_type, const Descriptor*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, enum_type, const EnumDescriptor*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, service, - const ServiceDescriptor*) -PROTOBUF_DEFINE_ARRAY_ACCESSOR(FileDescriptor, extension, - const FieldDescriptor*) - -#undef PROTOBUF_DEFINE_ACCESSOR -#undef PROTOBUF_DEFINE_STRING_ACCESSOR -#undef PROTOBUF_DEFINE_ARRAY_ACCESSOR - -// A few accessors differ from the macros... - -inline bool FieldDescriptor::is_required() const { - return label() == LABEL_REQUIRED; -} - -inline bool FieldDescriptor::is_optional() const { - return label() == LABEL_OPTIONAL; -} - -inline bool FieldDescriptor::is_repeated() const { - return label() == LABEL_REPEATED; -} - -inline bool FieldDescriptor::is_packable() const { - return is_repeated() && IsTypePackable(type()); -} - -// To save space, index() is computed by looking at the descriptor's position -// in the parent's array of children. -inline int FieldDescriptor::index() const { - if (!is_extension_) { - return this - containing_type_->fields_; - } else if (extension_scope_ != NULL) { - return this - extension_scope_->extensions_; - } else { - return this - file_->extensions_; - } -} - -inline int Descriptor::index() const { - if (containing_type_ == NULL) { - return this - file_->message_types_; - } else { - return this - containing_type_->nested_types_; - } -} - -inline int EnumDescriptor::index() const { - if (containing_type_ == NULL) { - return this - file_->enum_types_; - } else { - return this - containing_type_->enum_types_; - } -} - -inline int EnumValueDescriptor::index() const { - return this - type_->values_; -} - -inline int ServiceDescriptor::index() const { - return this - file_->services_; -} - -inline int MethodDescriptor::index() const { - return this - service_->methods_; -} - -inline FieldDescriptor::CppType FieldDescriptor::cpp_type() const { - return kTypeToCppTypeMap[type_]; -} - -inline FieldDescriptor::CppType FieldDescriptor::TypeToCppType(Type type) { - return kTypeToCppTypeMap[type]; -} - -inline bool FieldDescriptor::IsTypePackable(Type field_type) { - return (field_type != FieldDescriptor::TYPE_STRING && - field_type != FieldDescriptor::TYPE_GROUP && - field_type != FieldDescriptor::TYPE_MESSAGE && - field_type != FieldDescriptor::TYPE_BYTES); -} - -inline const FileDescriptor* FileDescriptor::dependency(int index) const { - return dependencies_[index]; -} - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_DESCRIPTOR_H__ diff --git a/Resources/NetHook/google/protobuf/descriptor.pb.cc b/Resources/NetHook/google/protobuf/descriptor.pb.cc deleted file mode 100644 index f61e7cd0..00000000 --- a/Resources/NetHook/google/protobuf/descriptor.pb.cc +++ /dev/null @@ -1,7029 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! - -#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION -#include "google/protobuf/descriptor.pb.h" -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { - -namespace { - -const ::google::protobuf::Descriptor* FileDescriptorSet_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - FileDescriptorSet_reflection_ = NULL; -const ::google::protobuf::Descriptor* FileDescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - FileDescriptorProto_reflection_ = NULL; -const ::google::protobuf::Descriptor* DescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - DescriptorProto_reflection_ = NULL; -const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - DescriptorProto_ExtensionRange_reflection_ = NULL; -const ::google::protobuf::Descriptor* FieldDescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - FieldDescriptorProto_reflection_ = NULL; -const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor_ = NULL; -const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor_ = NULL; -const ::google::protobuf::Descriptor* EnumDescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - EnumDescriptorProto_reflection_ = NULL; -const ::google::protobuf::Descriptor* EnumValueDescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - EnumValueDescriptorProto_reflection_ = NULL; -const ::google::protobuf::Descriptor* ServiceDescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ServiceDescriptorProto_reflection_ = NULL; -const ::google::protobuf::Descriptor* MethodDescriptorProto_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - MethodDescriptorProto_reflection_ = NULL; -const ::google::protobuf::Descriptor* FileOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - FileOptions_reflection_ = NULL; -const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor_ = NULL; -const ::google::protobuf::Descriptor* MessageOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - MessageOptions_reflection_ = NULL; -const ::google::protobuf::Descriptor* FieldOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - FieldOptions_reflection_ = NULL; -const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor_ = NULL; -const ::google::protobuf::Descriptor* EnumOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - EnumOptions_reflection_ = NULL; -const ::google::protobuf::Descriptor* EnumValueOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - EnumValueOptions_reflection_ = NULL; -const ::google::protobuf::Descriptor* ServiceOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - ServiceOptions_reflection_ = NULL; -const ::google::protobuf::Descriptor* MethodOptions_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - MethodOptions_reflection_ = NULL; -const ::google::protobuf::Descriptor* UninterpretedOption_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - UninterpretedOption_reflection_ = NULL; -const ::google::protobuf::Descriptor* UninterpretedOption_NamePart_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - UninterpretedOption_NamePart_reflection_ = NULL; - -} // namespace - - -void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto() { - protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - const ::google::protobuf::FileDescriptor* file = - ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( - "google/protobuf/descriptor.proto"); - GOOGLE_CHECK(file != NULL); - FileDescriptorSet_descriptor_ = file->message_type(0); - static const int FileDescriptorSet_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, file_), - }; - FileDescriptorSet_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - FileDescriptorSet_descriptor_, - FileDescriptorSet::default_instance_, - FileDescriptorSet_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorSet, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(FileDescriptorSet)); - FileDescriptorProto_descriptor_ = file->message_type(1); - static const int FileDescriptorProto_offsets_[8] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, dependency_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, message_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, enum_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, service_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, extension_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, options_), - }; - FileDescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - FileDescriptorProto_descriptor_, - FileDescriptorProto::default_instance_, - FileDescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileDescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(FileDescriptorProto)); - DescriptorProto_descriptor_ = file->message_type(2); - static const int DescriptorProto_offsets_[7] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, field_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, extension_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, nested_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, enum_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, extension_range_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, options_), - }; - DescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - DescriptorProto_descriptor_, - DescriptorProto::default_instance_, - DescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(DescriptorProto)); - DescriptorProto_ExtensionRange_descriptor_ = DescriptorProto_descriptor_->nested_type(0); - static const int DescriptorProto_ExtensionRange_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, start_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, end_), - }; - DescriptorProto_ExtensionRange_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - DescriptorProto_ExtensionRange_descriptor_, - DescriptorProto_ExtensionRange::default_instance_, - DescriptorProto_ExtensionRange_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DescriptorProto_ExtensionRange, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(DescriptorProto_ExtensionRange)); - FieldDescriptorProto_descriptor_ = file->message_type(3); - static const int FieldDescriptorProto_offsets_[8] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, number_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, label_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, type_name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, extendee_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, default_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, options_), - }; - FieldDescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - FieldDescriptorProto_descriptor_, - FieldDescriptorProto::default_instance_, - FieldDescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldDescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(FieldDescriptorProto)); - FieldDescriptorProto_Type_descriptor_ = FieldDescriptorProto_descriptor_->enum_type(0); - FieldDescriptorProto_Label_descriptor_ = FieldDescriptorProto_descriptor_->enum_type(1); - EnumDescriptorProto_descriptor_ = file->message_type(4); - static const int EnumDescriptorProto_offsets_[3] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, options_), - }; - EnumDescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - EnumDescriptorProto_descriptor_, - EnumDescriptorProto::default_instance_, - EnumDescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumDescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(EnumDescriptorProto)); - EnumValueDescriptorProto_descriptor_ = file->message_type(5); - static const int EnumValueDescriptorProto_offsets_[3] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, number_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, options_), - }; - EnumValueDescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - EnumValueDescriptorProto_descriptor_, - EnumValueDescriptorProto::default_instance_, - EnumValueDescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueDescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(EnumValueDescriptorProto)); - ServiceDescriptorProto_descriptor_ = file->message_type(6); - static const int ServiceDescriptorProto_offsets_[3] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, method_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, options_), - }; - ServiceDescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - ServiceDescriptorProto_descriptor_, - ServiceDescriptorProto::default_instance_, - ServiceDescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceDescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(ServiceDescriptorProto)); - MethodDescriptorProto_descriptor_ = file->message_type(7); - static const int MethodDescriptorProto_offsets_[4] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, input_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, output_type_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, options_), - }; - MethodDescriptorProto_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - MethodDescriptorProto_descriptor_, - MethodDescriptorProto::default_instance_, - MethodDescriptorProto_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodDescriptorProto, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(MethodDescriptorProto)); - FileOptions_descriptor_ = file->message_type(8); - static const int FileOptions_offsets_[8] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_package_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_outer_classname_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_multiple_files_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, optimize_for_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, cc_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, java_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, py_generic_services_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, uninterpreted_option_), - }; - FileOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - FileOptions_descriptor_, - FileOptions::default_instance_, - FileOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FileOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(FileOptions)); - FileOptions_OptimizeMode_descriptor_ = FileOptions_descriptor_->enum_type(0); - MessageOptions_descriptor_ = file->message_type(9); - static const int MessageOptions_offsets_[3] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, message_set_wire_format_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, no_standard_descriptor_accessor_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, uninterpreted_option_), - }; - MessageOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - MessageOptions_descriptor_, - MessageOptions::default_instance_, - MessageOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MessageOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(MessageOptions)); - FieldOptions_descriptor_ = file->message_type(10); - static const int FieldOptions_offsets_[5] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, ctype_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, packed_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, deprecated_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, experimental_map_key_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, uninterpreted_option_), - }; - FieldOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - FieldOptions_descriptor_, - FieldOptions::default_instance_, - FieldOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(FieldOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(FieldOptions)); - FieldOptions_CType_descriptor_ = FieldOptions_descriptor_->enum_type(0); - EnumOptions_descriptor_ = file->message_type(11); - static const int EnumOptions_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, uninterpreted_option_), - }; - EnumOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - EnumOptions_descriptor_, - EnumOptions::default_instance_, - EnumOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(EnumOptions)); - EnumValueOptions_descriptor_ = file->message_type(12); - static const int EnumValueOptions_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, uninterpreted_option_), - }; - EnumValueOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - EnumValueOptions_descriptor_, - EnumValueOptions::default_instance_, - EnumValueOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnumValueOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(EnumValueOptions)); - ServiceOptions_descriptor_ = file->message_type(13); - static const int ServiceOptions_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, uninterpreted_option_), - }; - ServiceOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - ServiceOptions_descriptor_, - ServiceOptions::default_instance_, - ServiceOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServiceOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(ServiceOptions)); - MethodOptions_descriptor_ = file->message_type(14); - static const int MethodOptions_offsets_[1] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, uninterpreted_option_), - }; - MethodOptions_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - MethodOptions_descriptor_, - MethodOptions::default_instance_, - MethodOptions_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _unknown_fields_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MethodOptions, _extensions_), - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(MethodOptions)); - UninterpretedOption_descriptor_ = file->message_type(15); - static const int UninterpretedOption_offsets_[6] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, name_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, identifier_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, positive_int_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, negative_int_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, double_value_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, string_value_), - }; - UninterpretedOption_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - UninterpretedOption_descriptor_, - UninterpretedOption::default_instance_, - UninterpretedOption_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(UninterpretedOption)); - UninterpretedOption_NamePart_descriptor_ = UninterpretedOption_descriptor_->nested_type(0); - static const int UninterpretedOption_NamePart_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, name_part_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, is_extension_), - }; - UninterpretedOption_NamePart_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - UninterpretedOption_NamePart_descriptor_, - UninterpretedOption_NamePart::default_instance_, - UninterpretedOption_NamePart_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(UninterpretedOption_NamePart, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(UninterpretedOption_NamePart)); -} - -namespace { - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); -inline void protobuf_AssignDescriptorsOnce() { - ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, - &protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto); -} - -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - FileDescriptorSet_descriptor_, &FileDescriptorSet::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - FileDescriptorProto_descriptor_, &FileDescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - DescriptorProto_descriptor_, &DescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - DescriptorProto_ExtensionRange_descriptor_, &DescriptorProto_ExtensionRange::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - FieldDescriptorProto_descriptor_, &FieldDescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - EnumDescriptorProto_descriptor_, &EnumDescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - EnumValueDescriptorProto_descriptor_, &EnumValueDescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ServiceDescriptorProto_descriptor_, &ServiceDescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - MethodDescriptorProto_descriptor_, &MethodDescriptorProto::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - FileOptions_descriptor_, &FileOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - MessageOptions_descriptor_, &MessageOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - FieldOptions_descriptor_, &FieldOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - EnumOptions_descriptor_, &EnumOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - EnumValueOptions_descriptor_, &EnumValueOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - ServiceOptions_descriptor_, &ServiceOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - MethodOptions_descriptor_, &MethodOptions::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - UninterpretedOption_descriptor_, &UninterpretedOption::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - UninterpretedOption_NamePart_descriptor_, &UninterpretedOption_NamePart::default_instance()); -} - -} // namespace - -void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto() { - delete FileDescriptorSet::default_instance_; - delete FileDescriptorSet_reflection_; - delete FileDescriptorProto::default_instance_; - delete FileDescriptorProto_reflection_; - delete DescriptorProto::default_instance_; - delete DescriptorProto_reflection_; - delete DescriptorProto_ExtensionRange::default_instance_; - delete DescriptorProto_ExtensionRange_reflection_; - delete FieldDescriptorProto::default_instance_; - delete FieldDescriptorProto_reflection_; - delete EnumDescriptorProto::default_instance_; - delete EnumDescriptorProto_reflection_; - delete EnumValueDescriptorProto::default_instance_; - delete EnumValueDescriptorProto_reflection_; - delete ServiceDescriptorProto::default_instance_; - delete ServiceDescriptorProto_reflection_; - delete MethodDescriptorProto::default_instance_; - delete MethodDescriptorProto_reflection_; - delete FileOptions::default_instance_; - delete FileOptions_reflection_; - delete MessageOptions::default_instance_; - delete MessageOptions_reflection_; - delete FieldOptions::default_instance_; - delete FieldOptions_reflection_; - delete EnumOptions::default_instance_; - delete EnumOptions_reflection_; - delete EnumValueOptions::default_instance_; - delete EnumValueOptions_reflection_; - delete ServiceOptions::default_instance_; - delete ServiceOptions_reflection_; - delete MethodOptions::default_instance_; - delete MethodOptions_reflection_; - delete UninterpretedOption::default_instance_; - delete UninterpretedOption_reflection_; - delete UninterpretedOption_NamePart::default_instance_; - delete UninterpretedOption_NamePart_reflection_; -} - -void protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() { - static bool already_here = false; - if (already_here) return; - already_here = true; - GOOGLE_PROTOBUF_VERIFY_VERSION; - - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - "\n google/protobuf/descriptor.proto\022\017goog" - "le.protobuf\"G\n\021FileDescriptorSet\0222\n\004file" - "\030\001 \003(\0132$.google.protobuf.FileDescriptorP" - "roto\"\334\002\n\023FileDescriptorProto\022\014\n\004name\030\001 \001" - "(\t\022\017\n\007package\030\002 \001(\t\022\022\n\ndependency\030\003 \003(\t\022" - "6\n\014message_type\030\004 \003(\0132 .google.protobuf." - "DescriptorProto\0227\n\tenum_type\030\005 \003(\0132$.goo" - "gle.protobuf.EnumDescriptorProto\0228\n\007serv" - "ice\030\006 \003(\0132\'.google.protobuf.ServiceDescr" - "iptorProto\0228\n\textension\030\007 \003(\0132%.google.p" - "rotobuf.FieldDescriptorProto\022-\n\007options\030" - "\010 \001(\0132\034.google.protobuf.FileOptions\"\251\003\n\017" - "DescriptorProto\022\014\n\004name\030\001 \001(\t\0224\n\005field\030\002" - " \003(\0132%.google.protobuf.FieldDescriptorPr" - "oto\0228\n\textension\030\006 \003(\0132%.google.protobuf" - ".FieldDescriptorProto\0225\n\013nested_type\030\003 \003" - "(\0132 .google.protobuf.DescriptorProto\0227\n\t" - "enum_type\030\004 \003(\0132$.google.protobuf.EnumDe" - "scriptorProto\022H\n\017extension_range\030\005 \003(\0132/" - ".google.protobuf.DescriptorProto.Extensi" - "onRange\0220\n\007options\030\007 \001(\0132\037.google.protob" - "uf.MessageOptions\032,\n\016ExtensionRange\022\r\n\005s" - "tart\030\001 \001(\005\022\013\n\003end\030\002 \001(\005\"\224\005\n\024FieldDescrip" - "torProto\022\014\n\004name\030\001 \001(\t\022\016\n\006number\030\003 \001(\005\022:" - "\n\005label\030\004 \001(\0162+.google.protobuf.FieldDes" - "criptorProto.Label\0228\n\004type\030\005 \001(\0162*.googl" - "e.protobuf.FieldDescriptorProto.Type\022\021\n\t" - "type_name\030\006 \001(\t\022\020\n\010extendee\030\002 \001(\t\022\025\n\rdef" - "ault_value\030\007 \001(\t\022.\n\007options\030\010 \001(\0132\035.goog" - "le.protobuf.FieldOptions\"\266\002\n\004Type\022\017\n\013TYP" - "E_DOUBLE\020\001\022\016\n\nTYPE_FLOAT\020\002\022\016\n\nTYPE_INT64" - "\020\003\022\017\n\013TYPE_UINT64\020\004\022\016\n\nTYPE_INT32\020\005\022\020\n\014T" - "YPE_FIXED64\020\006\022\020\n\014TYPE_FIXED32\020\007\022\r\n\tTYPE_" - "BOOL\020\010\022\017\n\013TYPE_STRING\020\t\022\016\n\nTYPE_GROUP\020\n\022" - "\020\n\014TYPE_MESSAGE\020\013\022\016\n\nTYPE_BYTES\020\014\022\017\n\013TYP" - "E_UINT32\020\r\022\r\n\tTYPE_ENUM\020\016\022\021\n\rTYPE_SFIXED" - "32\020\017\022\021\n\rTYPE_SFIXED64\020\020\022\017\n\013TYPE_SINT32\020\021" - "\022\017\n\013TYPE_SINT64\020\022\"C\n\005Label\022\022\n\016LABEL_OPTI" - "ONAL\020\001\022\022\n\016LABEL_REQUIRED\020\002\022\022\n\016LABEL_REPE" - "ATED\020\003\"\214\001\n\023EnumDescriptorProto\022\014\n\004name\030\001" - " \001(\t\0228\n\005value\030\002 \003(\0132).google.protobuf.En" - "umValueDescriptorProto\022-\n\007options\030\003 \001(\0132" - "\034.google.protobuf.EnumOptions\"l\n\030EnumVal" - "ueDescriptorProto\022\014\n\004name\030\001 \001(\t\022\016\n\006numbe" - "r\030\002 \001(\005\0222\n\007options\030\003 \001(\0132!.google.protob" - "uf.EnumValueOptions\"\220\001\n\026ServiceDescripto" - "rProto\022\014\n\004name\030\001 \001(\t\0226\n\006method\030\002 \003(\0132&.g" - "oogle.protobuf.MethodDescriptorProto\0220\n\007" - "options\030\003 \001(\0132\037.google.protobuf.ServiceO" - "ptions\"\177\n\025MethodDescriptorProto\022\014\n\004name\030" - "\001 \001(\t\022\022\n\ninput_type\030\002 \001(\t\022\023\n\013output_type" - "\030\003 \001(\t\022/\n\007options\030\004 \001(\0132\036.google.protobu" - "f.MethodOptions\"\244\003\n\013FileOptions\022\024\n\014java_" - "package\030\001 \001(\t\022\034\n\024java_outer_classname\030\010 " - "\001(\t\022\"\n\023java_multiple_files\030\n \001(\010:\005false\022" - "F\n\014optimize_for\030\t \001(\0162).google.protobuf." - "FileOptions.OptimizeMode:\005SPEED\022!\n\023cc_ge" - "neric_services\030\020 \001(\010:\004true\022#\n\025java_gener" - "ic_services\030\021 \001(\010:\004true\022!\n\023py_generic_se" - "rvices\030\022 \001(\010:\004true\022C\n\024uninterpreted_opti" - "on\030\347\007 \003(\0132$.google.protobuf.Uninterprete" - "dOption\":\n\014OptimizeMode\022\t\n\005SPEED\020\001\022\r\n\tCO" - "DE_SIZE\020\002\022\020\n\014LITE_RUNTIME\020\003*\t\010\350\007\020\200\200\200\200\002\"\270" - "\001\n\016MessageOptions\022&\n\027message_set_wire_fo" - "rmat\030\001 \001(\010:\005false\022.\n\037no_standard_descrip" - "tor_accessor\030\002 \001(\010:\005false\022C\n\024uninterpret" - "ed_option\030\347\007 \003(\0132$.google.protobuf.Unint" - "erpretedOption*\t\010\350\007\020\200\200\200\200\002\"\224\002\n\014FieldOptio" - "ns\022:\n\005ctype\030\001 \001(\0162#.google.protobuf.Fiel" - "dOptions.CType:\006STRING\022\016\n\006packed\030\002 \001(\010\022\031" - "\n\ndeprecated\030\003 \001(\010:\005false\022\034\n\024experimenta" - "l_map_key\030\t \001(\t\022C\n\024uninterpreted_option\030" - "\347\007 \003(\0132$.google.protobuf.UninterpretedOp" - "tion\"/\n\005CType\022\n\n\006STRING\020\000\022\010\n\004CORD\020\001\022\020\n\014S" - "TRING_PIECE\020\002*\t\010\350\007\020\200\200\200\200\002\"]\n\013EnumOptions\022" - "C\n\024uninterpreted_option\030\347\007 \003(\0132$.google." - "protobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"" - "b\n\020EnumValueOptions\022C\n\024uninterpreted_opt" - "ion\030\347\007 \003(\0132$.google.protobuf.Uninterpret" - "edOption*\t\010\350\007\020\200\200\200\200\002\"`\n\016ServiceOptions\022C\n" - "\024uninterpreted_option\030\347\007 \003(\0132$.google.pr" - "otobuf.UninterpretedOption*\t\010\350\007\020\200\200\200\200\002\"_\n" - "\rMethodOptions\022C\n\024uninterpreted_option\030\347" - "\007 \003(\0132$.google.protobuf.UninterpretedOpt" - "ion*\t\010\350\007\020\200\200\200\200\002\"\205\002\n\023UninterpretedOption\022;" - "\n\004name\030\002 \003(\0132-.google.protobuf.Uninterpr" - "etedOption.NamePart\022\030\n\020identifier_value\030" - "\003 \001(\t\022\032\n\022positive_int_value\030\004 \001(\004\022\032\n\022neg" - "ative_int_value\030\005 \001(\003\022\024\n\014double_value\030\006 " - "\001(\001\022\024\n\014string_value\030\007 \001(\014\0323\n\010NamePart\022\021\n" - "\tname_part\030\001 \002(\t\022\024\n\014is_extension\030\002 \002(\010B)" - "\n\023com.google.protobufB\020DescriptorProtosH" - "\001", 3681); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "google/protobuf/descriptor.proto", &protobuf_RegisterTypes); - FileDescriptorSet::default_instance_ = new FileDescriptorSet(); - FileDescriptorProto::default_instance_ = new FileDescriptorProto(); - DescriptorProto::default_instance_ = new DescriptorProto(); - DescriptorProto_ExtensionRange::default_instance_ = new DescriptorProto_ExtensionRange(); - FieldDescriptorProto::default_instance_ = new FieldDescriptorProto(); - EnumDescriptorProto::default_instance_ = new EnumDescriptorProto(); - EnumValueDescriptorProto::default_instance_ = new EnumValueDescriptorProto(); - ServiceDescriptorProto::default_instance_ = new ServiceDescriptorProto(); - MethodDescriptorProto::default_instance_ = new MethodDescriptorProto(); - FileOptions::default_instance_ = new FileOptions(); - MessageOptions::default_instance_ = new MessageOptions(); - FieldOptions::default_instance_ = new FieldOptions(); - EnumOptions::default_instance_ = new EnumOptions(); - EnumValueOptions::default_instance_ = new EnumValueOptions(); - ServiceOptions::default_instance_ = new ServiceOptions(); - MethodOptions::default_instance_ = new MethodOptions(); - UninterpretedOption::default_instance_ = new UninterpretedOption(); - UninterpretedOption_NamePart::default_instance_ = new UninterpretedOption_NamePart(); - FileDescriptorSet::default_instance_->InitAsDefaultInstance(); - FileDescriptorProto::default_instance_->InitAsDefaultInstance(); - DescriptorProto::default_instance_->InitAsDefaultInstance(); - DescriptorProto_ExtensionRange::default_instance_->InitAsDefaultInstance(); - FieldDescriptorProto::default_instance_->InitAsDefaultInstance(); - EnumDescriptorProto::default_instance_->InitAsDefaultInstance(); - EnumValueDescriptorProto::default_instance_->InitAsDefaultInstance(); - ServiceDescriptorProto::default_instance_->InitAsDefaultInstance(); - MethodDescriptorProto::default_instance_->InitAsDefaultInstance(); - FileOptions::default_instance_->InitAsDefaultInstance(); - MessageOptions::default_instance_->InitAsDefaultInstance(); - FieldOptions::default_instance_->InitAsDefaultInstance(); - EnumOptions::default_instance_->InitAsDefaultInstance(); - EnumValueOptions::default_instance_->InitAsDefaultInstance(); - ServiceOptions::default_instance_->InitAsDefaultInstance(); - MethodOptions::default_instance_->InitAsDefaultInstance(); - UninterpretedOption::default_instance_->InitAsDefaultInstance(); - UninterpretedOption_NamePart::default_instance_->InitAsDefaultInstance(); - ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto); -} - -// Force AddDescriptors() to be called at static initialization time. -struct StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto { - StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto() { - protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - } -} static_descriptor_initializer_google_2fprotobuf_2fdescriptor_2eproto_; - - -// =================================================================== - -#ifndef _MSC_VER -const int FileDescriptorSet::kFileFieldNumber; -#endif // !_MSC_VER - -FileDescriptorSet::FileDescriptorSet() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void FileDescriptorSet::InitAsDefaultInstance() { -} - -FileDescriptorSet::FileDescriptorSet(const FileDescriptorSet& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void FileDescriptorSet::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -FileDescriptorSet::~FileDescriptorSet() { - SharedDtor(); -} - -void FileDescriptorSet::SharedDtor() { - if (this != default_instance_) { - } -} - -void FileDescriptorSet::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* FileDescriptorSet::descriptor() { - protobuf_AssignDescriptorsOnce(); - return FileDescriptorSet_descriptor_; -} - -const FileDescriptorSet& FileDescriptorSet::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -FileDescriptorSet* FileDescriptorSet::default_instance_ = NULL; - -FileDescriptorSet* FileDescriptorSet::New() const { - return new FileDescriptorSet; -} - -void FileDescriptorSet::Clear() { - file_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool FileDescriptorSet::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .google.protobuf.FileDescriptorProto file = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_file: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_file())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(10)) goto parse_file; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void FileDescriptorSet::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // repeated .google.protobuf.FileDescriptorProto file = 1; - for (int i = 0; i < this->file_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 1, this->file(i), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* FileDescriptorSet::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // repeated .google.protobuf.FileDescriptorProto file = 1; - for (int i = 0; i < this->file_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 1, this->file(i), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int FileDescriptorSet::ByteSize() const { - int total_size = 0; - - // repeated .google.protobuf.FileDescriptorProto file = 1; - total_size += 1 * this->file_size(); - for (int i = 0; i < this->file_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->file(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void FileDescriptorSet::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const FileDescriptorSet* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void FileDescriptorSet::MergeFrom(const FileDescriptorSet& from) { - GOOGLE_CHECK_NE(&from, this); - file_.MergeFrom(from.file_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void FileDescriptorSet::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void FileDescriptorSet::CopyFrom(const FileDescriptorSet& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool FileDescriptorSet::IsInitialized() const { - - for (int i = 0; i < file_size(); i++) { - if (!this->file(i).IsInitialized()) return false; - } - return true; -} - -void FileDescriptorSet::Swap(FileDescriptorSet* other) { - if (other != this) { - file_.Swap(&other->file_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata FileDescriptorSet::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = FileDescriptorSet_descriptor_; - metadata.reflection = FileDescriptorSet_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string FileDescriptorProto::_default_name_; -const ::std::string FileDescriptorProto::_default_package_; -#ifndef _MSC_VER -const int FileDescriptorProto::kNameFieldNumber; -const int FileDescriptorProto::kPackageFieldNumber; -const int FileDescriptorProto::kDependencyFieldNumber; -const int FileDescriptorProto::kMessageTypeFieldNumber; -const int FileDescriptorProto::kEnumTypeFieldNumber; -const int FileDescriptorProto::kServiceFieldNumber; -const int FileDescriptorProto::kExtensionFieldNumber; -const int FileDescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -FileDescriptorProto::FileDescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void FileDescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::FileOptions*>(&::google::protobuf::FileOptions::default_instance()); -} - -FileDescriptorProto::FileDescriptorProto(const FileDescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void FileDescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - package_ = const_cast< ::std::string*>(&_default_package_); - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -FileDescriptorProto::~FileDescriptorProto() { - SharedDtor(); -} - -void FileDescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (package_ != &_default_package_) { - delete package_; - } - if (this != default_instance_) { - delete options_; - } -} - -void FileDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* FileDescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return FileDescriptorProto_descriptor_; -} - -const FileDescriptorProto& FileDescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -FileDescriptorProto* FileDescriptorProto::default_instance_ = NULL; - -FileDescriptorProto* FileDescriptorProto::New() const { - return new FileDescriptorProto; -} - -void FileDescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - if (_has_bit(1)) { - if (package_ != &_default_package_) { - package_->clear(); - } - } - if (_has_bit(7)) { - if (options_ != NULL) options_->::google::protobuf::FileOptions::Clear(); - } - } - dependency_.Clear(); - message_type_.Clear(); - enum_type_.Clear(); - service_.Clear(); - extension_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool FileDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_package; - break; - } - - // optional string package = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_package: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_package())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->package().data(), this->package().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(26)) goto parse_dependency; - break; - } - - // repeated string dependency = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_dependency: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->add_dependency())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->dependency(0).data(), this->dependency(0).length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(26)) goto parse_dependency; - if (input->ExpectTag(34)) goto parse_message_type; - break; - } - - // repeated .google.protobuf.DescriptorProto message_type = 4; - case 4: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_message_type: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_message_type())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(34)) goto parse_message_type; - if (input->ExpectTag(42)) goto parse_enum_type; - break; - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; - case 5: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_enum_type: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_enum_type())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(42)) goto parse_enum_type; - if (input->ExpectTag(50)) goto parse_service; - break; - } - - // repeated .google.protobuf.ServiceDescriptorProto service = 6; - case 6: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_service: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_service())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(50)) goto parse_service; - if (input->ExpectTag(58)) goto parse_extension; - break; - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 7; - case 7: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_extension: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_extension())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(58)) goto parse_extension; - if (input->ExpectTag(66)) goto parse_options; - break; - } - - // optional .google.protobuf.FileOptions options = 8; - case 8: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void FileDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // optional string package = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->package().data(), this->package().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 2, this->package(), output); - } - - // repeated string dependency = 3; - for (int i = 0; i < this->dependency_size(); i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->dependency(i).data(), this->dependency(i).length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 3, this->dependency(i), output); - } - - // repeated .google.protobuf.DescriptorProto message_type = 4; - for (int i = 0; i < this->message_type_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, this->message_type(i), output); - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; - for (int i = 0; i < this->enum_type_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, this->enum_type(i), output); - } - - // repeated .google.protobuf.ServiceDescriptorProto service = 6; - for (int i = 0; i < this->service_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, this->service(i), output); - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 7; - for (int i = 0; i < this->extension_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, this->extension(i), output); - } - - // optional .google.protobuf.FileOptions options = 8; - if (_has_bit(7)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* FileDescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional string package = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->package().data(), this->package().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->package(), target); - } - - // repeated string dependency = 3; - for (int i = 0; i < this->dependency_size(); i++) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->dependency(i).data(), this->dependency(i).length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = ::google::protobuf::internal::WireFormatLite:: - WriteStringToArray(3, this->dependency(i), target); - } - - // repeated .google.protobuf.DescriptorProto message_type = 4; - for (int i = 0; i < this->message_type_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 4, this->message_type(i), target); - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; - for (int i = 0; i < this->enum_type_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 5, this->enum_type(i), target); - } - - // repeated .google.protobuf.ServiceDescriptorProto service = 6; - for (int i = 0; i < this->service_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 6, this->service(i), target); - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 7; - for (int i = 0; i < this->extension_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 7, this->extension(i), target); - } - - // optional .google.protobuf.FileOptions options = 8; - if (_has_bit(7)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 8, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int FileDescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional string package = 2; - if (has_package()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->package()); - } - - // optional .google.protobuf.FileOptions options = 8; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - // repeated string dependency = 3; - total_size += 1 * this->dependency_size(); - for (int i = 0; i < this->dependency_size(); i++) { - total_size += ::google::protobuf::internal::WireFormatLite::StringSize( - this->dependency(i)); - } - - // repeated .google.protobuf.DescriptorProto message_type = 4; - total_size += 1 * this->message_type_size(); - for (int i = 0; i < this->message_type_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->message_type(i)); - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; - total_size += 1 * this->enum_type_size(); - for (int i = 0; i < this->enum_type_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->enum_type(i)); - } - - // repeated .google.protobuf.ServiceDescriptorProto service = 6; - total_size += 1 * this->service_size(); - for (int i = 0; i < this->service_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->service(i)); - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 7; - total_size += 1 * this->extension_size(); - for (int i = 0; i < this->extension_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->extension(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void FileDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const FileDescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void FileDescriptorProto::MergeFrom(const FileDescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - dependency_.MergeFrom(from.dependency_); - message_type_.MergeFrom(from.message_type_); - enum_type_.MergeFrom(from.enum_type_); - service_.MergeFrom(from.service_); - extension_.MergeFrom(from.extension_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(1)) { - set_package(from.package()); - } - if (from._has_bit(7)) { - mutable_options()->::google::protobuf::FileOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void FileDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void FileDescriptorProto::CopyFrom(const FileDescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool FileDescriptorProto::IsInitialized() const { - - for (int i = 0; i < message_type_size(); i++) { - if (!this->message_type(i).IsInitialized()) return false; - } - for (int i = 0; i < enum_type_size(); i++) { - if (!this->enum_type(i).IsInitialized()) return false; - } - for (int i = 0; i < service_size(); i++) { - if (!this->service(i).IsInitialized()) return false; - } - for (int i = 0; i < extension_size(); i++) { - if (!this->extension(i).IsInitialized()) return false; - } - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void FileDescriptorProto::Swap(FileDescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - std::swap(package_, other->package_); - dependency_.Swap(&other->dependency_); - message_type_.Swap(&other->message_type_); - enum_type_.Swap(&other->enum_type_); - service_.Swap(&other->service_); - extension_.Swap(&other->extension_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata FileDescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = FileDescriptorProto_descriptor_; - metadata.reflection = FileDescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int DescriptorProto_ExtensionRange::kStartFieldNumber; -const int DescriptorProto_ExtensionRange::kEndFieldNumber; -#endif // !_MSC_VER - -DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void DescriptorProto_ExtensionRange::InitAsDefaultInstance() { -} - -DescriptorProto_ExtensionRange::DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void DescriptorProto_ExtensionRange::SharedCtor() { - _cached_size_ = 0; - start_ = 0; - end_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -DescriptorProto_ExtensionRange::~DescriptorProto_ExtensionRange() { - SharedDtor(); -} - -void DescriptorProto_ExtensionRange::SharedDtor() { - if (this != default_instance_) { - } -} - -void DescriptorProto_ExtensionRange::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* DescriptorProto_ExtensionRange::descriptor() { - protobuf_AssignDescriptorsOnce(); - return DescriptorProto_ExtensionRange_descriptor_; -} - -const DescriptorProto_ExtensionRange& DescriptorProto_ExtensionRange::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::default_instance_ = NULL; - -DescriptorProto_ExtensionRange* DescriptorProto_ExtensionRange::New() const { - return new DescriptorProto_ExtensionRange; -} - -void DescriptorProto_ExtensionRange::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - start_ = 0; - end_ = 0; - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool DescriptorProto_ExtensionRange::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional int32 start = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &start_))); - _set_bit(0); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_end; - break; - } - - // optional int32 end = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_end: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &end_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void DescriptorProto_ExtensionRange::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional int32 start = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->start(), output); - } - - // optional int32 end = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->end(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* DescriptorProto_ExtensionRange::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional int32 start = 1; - if (_has_bit(0)) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->start(), target); - } - - // optional int32 end = 2; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->end(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int DescriptorProto_ExtensionRange::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional int32 start = 1; - if (has_start()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->start()); - } - - // optional int32 end = 2; - if (has_end()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->end()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void DescriptorProto_ExtensionRange::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const DescriptorProto_ExtensionRange* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void DescriptorProto_ExtensionRange::MergeFrom(const DescriptorProto_ExtensionRange& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_start(from.start()); - } - if (from._has_bit(1)) { - set_end(from.end()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void DescriptorProto_ExtensionRange::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void DescriptorProto_ExtensionRange::CopyFrom(const DescriptorProto_ExtensionRange& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool DescriptorProto_ExtensionRange::IsInitialized() const { - - return true; -} - -void DescriptorProto_ExtensionRange::Swap(DescriptorProto_ExtensionRange* other) { - if (other != this) { - std::swap(start_, other->start_); - std::swap(end_, other->end_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata DescriptorProto_ExtensionRange::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = DescriptorProto_ExtensionRange_descriptor_; - metadata.reflection = DescriptorProto_ExtensionRange_reflection_; - return metadata; -} - - -// ------------------------------------------------------------------- - -const ::std::string DescriptorProto::_default_name_; -#ifndef _MSC_VER -const int DescriptorProto::kNameFieldNumber; -const int DescriptorProto::kFieldFieldNumber; -const int DescriptorProto::kExtensionFieldNumber; -const int DescriptorProto::kNestedTypeFieldNumber; -const int DescriptorProto::kEnumTypeFieldNumber; -const int DescriptorProto::kExtensionRangeFieldNumber; -const int DescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -DescriptorProto::DescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void DescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::MessageOptions*>(&::google::protobuf::MessageOptions::default_instance()); -} - -DescriptorProto::DescriptorProto(const DescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void DescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -DescriptorProto::~DescriptorProto() { - SharedDtor(); -} - -void DescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (this != default_instance_) { - delete options_; - } -} - -void DescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* DescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return DescriptorProto_descriptor_; -} - -const DescriptorProto& DescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -DescriptorProto* DescriptorProto::default_instance_ = NULL; - -DescriptorProto* DescriptorProto::New() const { - return new DescriptorProto; -} - -void DescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - if (_has_bit(6)) { - if (options_ != NULL) options_->::google::protobuf::MessageOptions::Clear(); - } - } - field_.Clear(); - extension_.Clear(); - nested_type_.Clear(); - enum_type_.Clear(); - extension_range_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool DescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_field; - break; - } - - // repeated .google.protobuf.FieldDescriptorProto field = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_field: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_field())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_field; - if (input->ExpectTag(26)) goto parse_nested_type; - break; - } - - // repeated .google.protobuf.DescriptorProto nested_type = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_nested_type: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_nested_type())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(26)) goto parse_nested_type; - if (input->ExpectTag(34)) goto parse_enum_type; - break; - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; - case 4: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_enum_type: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_enum_type())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(34)) goto parse_enum_type; - if (input->ExpectTag(42)) goto parse_extension_range; - break; - } - - // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; - case 5: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_extension_range: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_extension_range())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(42)) goto parse_extension_range; - if (input->ExpectTag(50)) goto parse_extension; - break; - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 6; - case 6: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_extension: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_extension())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(50)) goto parse_extension; - if (input->ExpectTag(58)) goto parse_options; - break; - } - - // optional .google.protobuf.MessageOptions options = 7; - case 7: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void DescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // repeated .google.protobuf.FieldDescriptorProto field = 2; - for (int i = 0; i < this->field_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, this->field(i), output); - } - - // repeated .google.protobuf.DescriptorProto nested_type = 3; - for (int i = 0; i < this->nested_type_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->nested_type(i), output); - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; - for (int i = 0; i < this->enum_type_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, this->enum_type(i), output); - } - - // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; - for (int i = 0; i < this->extension_range_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 5, this->extension_range(i), output); - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 6; - for (int i = 0; i < this->extension_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 6, this->extension(i), output); - } - - // optional .google.protobuf.MessageOptions options = 7; - if (_has_bit(6)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 7, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* DescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // repeated .google.protobuf.FieldDescriptorProto field = 2; - for (int i = 0; i < this->field_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, this->field(i), target); - } - - // repeated .google.protobuf.DescriptorProto nested_type = 3; - for (int i = 0; i < this->nested_type_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->nested_type(i), target); - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; - for (int i = 0; i < this->enum_type_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 4, this->enum_type(i), target); - } - - // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; - for (int i = 0; i < this->extension_range_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 5, this->extension_range(i), target); - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 6; - for (int i = 0; i < this->extension_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 6, this->extension(i), target); - } - - // optional .google.protobuf.MessageOptions options = 7; - if (_has_bit(6)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 7, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int DescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional .google.protobuf.MessageOptions options = 7; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - // repeated .google.protobuf.FieldDescriptorProto field = 2; - total_size += 1 * this->field_size(); - for (int i = 0; i < this->field_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->field(i)); - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 6; - total_size += 1 * this->extension_size(); - for (int i = 0; i < this->extension_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->extension(i)); - } - - // repeated .google.protobuf.DescriptorProto nested_type = 3; - total_size += 1 * this->nested_type_size(); - for (int i = 0; i < this->nested_type_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->nested_type(i)); - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; - total_size += 1 * this->enum_type_size(); - for (int i = 0; i < this->enum_type_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->enum_type(i)); - } - - // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; - total_size += 1 * this->extension_range_size(); - for (int i = 0; i < this->extension_range_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->extension_range(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void DescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const DescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void DescriptorProto::MergeFrom(const DescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - field_.MergeFrom(from.field_); - extension_.MergeFrom(from.extension_); - nested_type_.MergeFrom(from.nested_type_); - enum_type_.MergeFrom(from.enum_type_); - extension_range_.MergeFrom(from.extension_range_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(6)) { - mutable_options()->::google::protobuf::MessageOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void DescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void DescriptorProto::CopyFrom(const DescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool DescriptorProto::IsInitialized() const { - - for (int i = 0; i < field_size(); i++) { - if (!this->field(i).IsInitialized()) return false; - } - for (int i = 0; i < extension_size(); i++) { - if (!this->extension(i).IsInitialized()) return false; - } - for (int i = 0; i < nested_type_size(); i++) { - if (!this->nested_type(i).IsInitialized()) return false; - } - for (int i = 0; i < enum_type_size(); i++) { - if (!this->enum_type(i).IsInitialized()) return false; - } - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void DescriptorProto::Swap(DescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - field_.Swap(&other->field_); - extension_.Swap(&other->extension_); - nested_type_.Swap(&other->nested_type_); - enum_type_.Swap(&other->enum_type_); - extension_range_.Swap(&other->extension_range_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata DescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = DescriptorProto_descriptor_; - metadata.reflection = DescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor() { - protobuf_AssignDescriptorsOnce(); - return FieldDescriptorProto_Type_descriptor_; -} -bool FieldDescriptorProto_Type_IsValid(int value) { - switch(value) { - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - return true; - default: - return false; - } -} - -#ifndef _MSC_VER -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_DOUBLE; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FLOAT; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_INT64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_UINT64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_INT32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FIXED64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_FIXED32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_BOOL; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_STRING; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_GROUP; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_MESSAGE; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_BYTES; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_UINT32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_ENUM; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SFIXED32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SFIXED64; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SINT32; -const FieldDescriptorProto_Type FieldDescriptorProto::TYPE_SINT64; -const FieldDescriptorProto_Type FieldDescriptorProto::Type_MIN; -const FieldDescriptorProto_Type FieldDescriptorProto::Type_MAX; -const int FieldDescriptorProto::Type_ARRAYSIZE; -#endif // _MSC_VER -const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor() { - protobuf_AssignDescriptorsOnce(); - return FieldDescriptorProto_Label_descriptor_; -} -bool FieldDescriptorProto_Label_IsValid(int value) { - switch(value) { - case 1: - case 2: - case 3: - return true; - default: - return false; - } -} - -#ifndef _MSC_VER -const FieldDescriptorProto_Label FieldDescriptorProto::LABEL_OPTIONAL; -const FieldDescriptorProto_Label FieldDescriptorProto::LABEL_REQUIRED; -const FieldDescriptorProto_Label FieldDescriptorProto::LABEL_REPEATED; -const FieldDescriptorProto_Label FieldDescriptorProto::Label_MIN; -const FieldDescriptorProto_Label FieldDescriptorProto::Label_MAX; -const int FieldDescriptorProto::Label_ARRAYSIZE; -#endif // _MSC_VER -const ::std::string FieldDescriptorProto::_default_name_; -const ::std::string FieldDescriptorProto::_default_type_name_; -const ::std::string FieldDescriptorProto::_default_extendee_; -const ::std::string FieldDescriptorProto::_default_default_value_; -#ifndef _MSC_VER -const int FieldDescriptorProto::kNameFieldNumber; -const int FieldDescriptorProto::kNumberFieldNumber; -const int FieldDescriptorProto::kLabelFieldNumber; -const int FieldDescriptorProto::kTypeFieldNumber; -const int FieldDescriptorProto::kTypeNameFieldNumber; -const int FieldDescriptorProto::kExtendeeFieldNumber; -const int FieldDescriptorProto::kDefaultValueFieldNumber; -const int FieldDescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -FieldDescriptorProto::FieldDescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void FieldDescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::FieldOptions*>(&::google::protobuf::FieldOptions::default_instance()); -} - -FieldDescriptorProto::FieldDescriptorProto(const FieldDescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void FieldDescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - number_ = 0; - label_ = 1; - type_ = 1; - type_name_ = const_cast< ::std::string*>(&_default_type_name_); - extendee_ = const_cast< ::std::string*>(&_default_extendee_); - default_value_ = const_cast< ::std::string*>(&_default_default_value_); - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -FieldDescriptorProto::~FieldDescriptorProto() { - SharedDtor(); -} - -void FieldDescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (type_name_ != &_default_type_name_) { - delete type_name_; - } - if (extendee_ != &_default_extendee_) { - delete extendee_; - } - if (default_value_ != &_default_default_value_) { - delete default_value_; - } - if (this != default_instance_) { - delete options_; - } -} - -void FieldDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* FieldDescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return FieldDescriptorProto_descriptor_; -} - -const FieldDescriptorProto& FieldDescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -FieldDescriptorProto* FieldDescriptorProto::default_instance_ = NULL; - -FieldDescriptorProto* FieldDescriptorProto::New() const { - return new FieldDescriptorProto; -} - -void FieldDescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - number_ = 0; - label_ = 1; - type_ = 1; - if (_has_bit(4)) { - if (type_name_ != &_default_type_name_) { - type_name_->clear(); - } - } - if (_has_bit(5)) { - if (extendee_ != &_default_extendee_) { - extendee_->clear(); - } - } - if (_has_bit(6)) { - if (default_value_ != &_default_default_value_) { - default_value_->clear(); - } - } - if (_has_bit(7)) { - if (options_ != NULL) options_->::google::protobuf::FieldOptions::Clear(); - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool FieldDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_extendee; - break; - } - - // optional string extendee = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_extendee: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_extendee())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->extendee().data(), this->extendee().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(24)) goto parse_number; - break; - } - - // optional int32 number = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_number: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &number_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(32)) goto parse_label; - break; - } - - // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - case 4: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_label: - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - if (::google::protobuf::FieldDescriptorProto_Label_IsValid(value)) { - set_label(static_cast< ::google::protobuf::FieldDescriptorProto_Label >(value)); - } else { - mutable_unknown_fields()->AddVarint(4, value); - } - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(40)) goto parse_type; - break; - } - - // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - case 5: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_type: - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - if (::google::protobuf::FieldDescriptorProto_Type_IsValid(value)) { - set_type(static_cast< ::google::protobuf::FieldDescriptorProto_Type >(value)); - } else { - mutable_unknown_fields()->AddVarint(5, value); - } - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(50)) goto parse_type_name; - break; - } - - // optional string type_name = 6; - case 6: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_type_name: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_type_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->type_name().data(), this->type_name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(58)) goto parse_default_value; - break; - } - - // optional string default_value = 7; - case 7: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_default_value: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_default_value())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->default_value().data(), this->default_value().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(66)) goto parse_options; - break; - } - - // optional .google.protobuf.FieldOptions options = 8; - case 8: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void FieldDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // optional string extendee = 2; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->extendee().data(), this->extendee().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 2, this->extendee(), output); - } - - // optional int32 number = 3; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(3, this->number(), output); - } - - // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 4, this->label(), output); - } - - // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 5, this->type(), output); - } - - // optional string type_name = 6; - if (_has_bit(4)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->type_name().data(), this->type_name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 6, this->type_name(), output); - } - - // optional string default_value = 7; - if (_has_bit(6)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->default_value().data(), this->default_value().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 7, this->default_value(), output); - } - - // optional .google.protobuf.FieldOptions options = 8; - if (_has_bit(7)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 8, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* FieldDescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional string extendee = 2; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->extendee().data(), this->extendee().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->extendee(), target); - } - - // optional int32 number = 3; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(3, this->number(), target); - } - - // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 4, this->label(), target); - } - - // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - if (_has_bit(3)) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 5, this->type(), target); - } - - // optional string type_name = 6; - if (_has_bit(4)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->type_name().data(), this->type_name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 6, this->type_name(), target); - } - - // optional string default_value = 7; - if (_has_bit(6)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->default_value().data(), this->default_value().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 7, this->default_value(), target); - } - - // optional .google.protobuf.FieldOptions options = 8; - if (_has_bit(7)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 8, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int FieldDescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional int32 number = 3; - if (has_number()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->number()); - } - - // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - if (has_label()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->label()); - } - - // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - if (has_type()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); - } - - // optional string type_name = 6; - if (has_type_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->type_name()); - } - - // optional string extendee = 2; - if (has_extendee()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->extendee()); - } - - // optional string default_value = 7; - if (has_default_value()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->default_value()); - } - - // optional .google.protobuf.FieldOptions options = 8; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void FieldDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const FieldDescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void FieldDescriptorProto::MergeFrom(const FieldDescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(1)) { - set_number(from.number()); - } - if (from._has_bit(2)) { - set_label(from.label()); - } - if (from._has_bit(3)) { - set_type(from.type()); - } - if (from._has_bit(4)) { - set_type_name(from.type_name()); - } - if (from._has_bit(5)) { - set_extendee(from.extendee()); - } - if (from._has_bit(6)) { - set_default_value(from.default_value()); - } - if (from._has_bit(7)) { - mutable_options()->::google::protobuf::FieldOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void FieldDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void FieldDescriptorProto::CopyFrom(const FieldDescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool FieldDescriptorProto::IsInitialized() const { - - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void FieldDescriptorProto::Swap(FieldDescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - std::swap(number_, other->number_); - std::swap(label_, other->label_); - std::swap(type_, other->type_); - std::swap(type_name_, other->type_name_); - std::swap(extendee_, other->extendee_); - std::swap(default_value_, other->default_value_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata FieldDescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = FieldDescriptorProto_descriptor_; - metadata.reflection = FieldDescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string EnumDescriptorProto::_default_name_; -#ifndef _MSC_VER -const int EnumDescriptorProto::kNameFieldNumber; -const int EnumDescriptorProto::kValueFieldNumber; -const int EnumDescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -EnumDescriptorProto::EnumDescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void EnumDescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::EnumOptions*>(&::google::protobuf::EnumOptions::default_instance()); -} - -EnumDescriptorProto::EnumDescriptorProto(const EnumDescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void EnumDescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -EnumDescriptorProto::~EnumDescriptorProto() { - SharedDtor(); -} - -void EnumDescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (this != default_instance_) { - delete options_; - } -} - -void EnumDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* EnumDescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return EnumDescriptorProto_descriptor_; -} - -const EnumDescriptorProto& EnumDescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -EnumDescriptorProto* EnumDescriptorProto::default_instance_ = NULL; - -EnumDescriptorProto* EnumDescriptorProto::New() const { - return new EnumDescriptorProto; -} - -void EnumDescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - if (_has_bit(2)) { - if (options_ != NULL) options_->::google::protobuf::EnumOptions::Clear(); - } - } - value_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool EnumDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_value; - break; - } - - // repeated .google.protobuf.EnumValueDescriptorProto value = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_value: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_value())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_value; - if (input->ExpectTag(26)) goto parse_options; - break; - } - - // optional .google.protobuf.EnumOptions options = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void EnumDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // repeated .google.protobuf.EnumValueDescriptorProto value = 2; - for (int i = 0; i < this->value_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, this->value(i), output); - } - - // optional .google.protobuf.EnumOptions options = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* EnumDescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // repeated .google.protobuf.EnumValueDescriptorProto value = 2; - for (int i = 0; i < this->value_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, this->value(i), target); - } - - // optional .google.protobuf.EnumOptions options = 3; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int EnumDescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional .google.protobuf.EnumOptions options = 3; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - // repeated .google.protobuf.EnumValueDescriptorProto value = 2; - total_size += 1 * this->value_size(); - for (int i = 0; i < this->value_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->value(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void EnumDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const EnumDescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void EnumDescriptorProto::MergeFrom(const EnumDescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - value_.MergeFrom(from.value_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(2)) { - mutable_options()->::google::protobuf::EnumOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void EnumDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void EnumDescriptorProto::CopyFrom(const EnumDescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool EnumDescriptorProto::IsInitialized() const { - - for (int i = 0; i < value_size(); i++) { - if (!this->value(i).IsInitialized()) return false; - } - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void EnumDescriptorProto::Swap(EnumDescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - value_.Swap(&other->value_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata EnumDescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = EnumDescriptorProto_descriptor_; - metadata.reflection = EnumDescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string EnumValueDescriptorProto::_default_name_; -#ifndef _MSC_VER -const int EnumValueDescriptorProto::kNameFieldNumber; -const int EnumValueDescriptorProto::kNumberFieldNumber; -const int EnumValueDescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -EnumValueDescriptorProto::EnumValueDescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void EnumValueDescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::EnumValueOptions*>(&::google::protobuf::EnumValueOptions::default_instance()); -} - -EnumValueDescriptorProto::EnumValueDescriptorProto(const EnumValueDescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void EnumValueDescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - number_ = 0; - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -EnumValueDescriptorProto::~EnumValueDescriptorProto() { - SharedDtor(); -} - -void EnumValueDescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (this != default_instance_) { - delete options_; - } -} - -void EnumValueDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* EnumValueDescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return EnumValueDescriptorProto_descriptor_; -} - -const EnumValueDescriptorProto& EnumValueDescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -EnumValueDescriptorProto* EnumValueDescriptorProto::default_instance_ = NULL; - -EnumValueDescriptorProto* EnumValueDescriptorProto::New() const { - return new EnumValueDescriptorProto; -} - -void EnumValueDescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - number_ = 0; - if (_has_bit(2)) { - if (options_ != NULL) options_->::google::protobuf::EnumValueOptions::Clear(); - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool EnumValueDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_number; - break; - } - - // optional int32 number = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_number: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &number_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(26)) goto parse_options; - break; - } - - // optional .google.protobuf.EnumValueOptions options = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void EnumValueDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // optional int32 number = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->number(), output); - } - - // optional .google.protobuf.EnumValueOptions options = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* EnumValueDescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional int32 number = 2; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->number(), target); - } - - // optional .google.protobuf.EnumValueOptions options = 3; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int EnumValueDescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional int32 number = 2; - if (has_number()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->number()); - } - - // optional .google.protobuf.EnumValueOptions options = 3; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void EnumValueDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const EnumValueDescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void EnumValueDescriptorProto::MergeFrom(const EnumValueDescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(1)) { - set_number(from.number()); - } - if (from._has_bit(2)) { - mutable_options()->::google::protobuf::EnumValueOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void EnumValueDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void EnumValueDescriptorProto::CopyFrom(const EnumValueDescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool EnumValueDescriptorProto::IsInitialized() const { - - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void EnumValueDescriptorProto::Swap(EnumValueDescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - std::swap(number_, other->number_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata EnumValueDescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = EnumValueDescriptorProto_descriptor_; - metadata.reflection = EnumValueDescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string ServiceDescriptorProto::_default_name_; -#ifndef _MSC_VER -const int ServiceDescriptorProto::kNameFieldNumber; -const int ServiceDescriptorProto::kMethodFieldNumber; -const int ServiceDescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -ServiceDescriptorProto::ServiceDescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void ServiceDescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::ServiceOptions*>(&::google::protobuf::ServiceOptions::default_instance()); -} - -ServiceDescriptorProto::ServiceDescriptorProto(const ServiceDescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void ServiceDescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -ServiceDescriptorProto::~ServiceDescriptorProto() { - SharedDtor(); -} - -void ServiceDescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (this != default_instance_) { - delete options_; - } -} - -void ServiceDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ServiceDescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ServiceDescriptorProto_descriptor_; -} - -const ServiceDescriptorProto& ServiceDescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -ServiceDescriptorProto* ServiceDescriptorProto::default_instance_ = NULL; - -ServiceDescriptorProto* ServiceDescriptorProto::New() const { - return new ServiceDescriptorProto; -} - -void ServiceDescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - if (_has_bit(2)) { - if (options_ != NULL) options_->::google::protobuf::ServiceOptions::Clear(); - } - } - method_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool ServiceDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_method; - break; - } - - // repeated .google.protobuf.MethodDescriptorProto method = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_method: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_method())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_method; - if (input->ExpectTag(26)) goto parse_options; - break; - } - - // optional .google.protobuf.ServiceOptions options = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void ServiceDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // repeated .google.protobuf.MethodDescriptorProto method = 2; - for (int i = 0; i < this->method_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, this->method(i), output); - } - - // optional .google.protobuf.ServiceOptions options = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 3, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* ServiceDescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // repeated .google.protobuf.MethodDescriptorProto method = 2; - for (int i = 0; i < this->method_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, this->method(i), target); - } - - // optional .google.protobuf.ServiceOptions options = 3; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 3, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int ServiceDescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional .google.protobuf.ServiceOptions options = 3; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - // repeated .google.protobuf.MethodDescriptorProto method = 2; - total_size += 1 * this->method_size(); - for (int i = 0; i < this->method_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->method(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ServiceDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const ServiceDescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void ServiceDescriptorProto::MergeFrom(const ServiceDescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - method_.MergeFrom(from.method_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(2)) { - mutable_options()->::google::protobuf::ServiceOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void ServiceDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ServiceDescriptorProto::CopyFrom(const ServiceDescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool ServiceDescriptorProto::IsInitialized() const { - - for (int i = 0; i < method_size(); i++) { - if (!this->method(i).IsInitialized()) return false; - } - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void ServiceDescriptorProto::Swap(ServiceDescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - method_.Swap(&other->method_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata ServiceDescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ServiceDescriptorProto_descriptor_; - metadata.reflection = ServiceDescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string MethodDescriptorProto::_default_name_; -const ::std::string MethodDescriptorProto::_default_input_type_; -const ::std::string MethodDescriptorProto::_default_output_type_; -#ifndef _MSC_VER -const int MethodDescriptorProto::kNameFieldNumber; -const int MethodDescriptorProto::kInputTypeFieldNumber; -const int MethodDescriptorProto::kOutputTypeFieldNumber; -const int MethodDescriptorProto::kOptionsFieldNumber; -#endif // !_MSC_VER - -MethodDescriptorProto::MethodDescriptorProto() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void MethodDescriptorProto::InitAsDefaultInstance() { - options_ = const_cast< ::google::protobuf::MethodOptions*>(&::google::protobuf::MethodOptions::default_instance()); -} - -MethodDescriptorProto::MethodDescriptorProto(const MethodDescriptorProto& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void MethodDescriptorProto::SharedCtor() { - _cached_size_ = 0; - name_ = const_cast< ::std::string*>(&_default_name_); - input_type_ = const_cast< ::std::string*>(&_default_input_type_); - output_type_ = const_cast< ::std::string*>(&_default_output_type_); - options_ = NULL; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MethodDescriptorProto::~MethodDescriptorProto() { - SharedDtor(); -} - -void MethodDescriptorProto::SharedDtor() { - if (name_ != &_default_name_) { - delete name_; - } - if (input_type_ != &_default_input_type_) { - delete input_type_; - } - if (output_type_ != &_default_output_type_) { - delete output_type_; - } - if (this != default_instance_) { - delete options_; - } -} - -void MethodDescriptorProto::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* MethodDescriptorProto::descriptor() { - protobuf_AssignDescriptorsOnce(); - return MethodDescriptorProto_descriptor_; -} - -const MethodDescriptorProto& MethodDescriptorProto::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -MethodDescriptorProto* MethodDescriptorProto::default_instance_ = NULL; - -MethodDescriptorProto* MethodDescriptorProto::New() const { - return new MethodDescriptorProto; -} - -void MethodDescriptorProto::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_ != &_default_name_) { - name_->clear(); - } - } - if (_has_bit(1)) { - if (input_type_ != &_default_input_type_) { - input_type_->clear(); - } - } - if (_has_bit(2)) { - if (output_type_ != &_default_output_type_) { - output_type_->clear(); - } - } - if (_has_bit(3)) { - if (options_ != NULL) options_->::google::protobuf::MethodOptions::Clear(); - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool MethodDescriptorProto::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string name = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_input_type; - break; - } - - // optional string input_type = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_input_type: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_input_type())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->input_type().data(), this->input_type().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(26)) goto parse_output_type; - break; - } - - // optional string output_type = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_output_type: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_output_type())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->output_type().data(), this->output_type().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(34)) goto parse_options; - break; - } - - // optional .google.protobuf.MethodOptions options = 4; - case 4: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_options: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, mutable_options())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void MethodDescriptorProto::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name(), output); - } - - // optional string input_type = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->input_type().data(), this->input_type().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 2, this->input_type(), output); - } - - // optional string output_type = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->output_type().data(), this->output_type().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 3, this->output_type(), output); - } - - // optional .google.protobuf.MethodOptions options = 4; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 4, this->options(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* MethodDescriptorProto::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string name = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name().data(), this->name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name(), target); - } - - // optional string input_type = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->input_type().data(), this->input_type().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 2, this->input_type(), target); - } - - // optional string output_type = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->output_type().data(), this->output_type().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 3, this->output_type(), target); - } - - // optional .google.protobuf.MethodOptions options = 4; - if (_has_bit(3)) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 4, this->options(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int MethodDescriptorProto::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string name = 1; - if (has_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name()); - } - - // optional string input_type = 2; - if (has_input_type()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->input_type()); - } - - // optional string output_type = 3; - if (has_output_type()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->output_type()); - } - - // optional .google.protobuf.MethodOptions options = 4; - if (has_options()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->options()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MethodDescriptorProto::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const MethodDescriptorProto* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void MethodDescriptorProto::MergeFrom(const MethodDescriptorProto& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name(from.name()); - } - if (from._has_bit(1)) { - set_input_type(from.input_type()); - } - if (from._has_bit(2)) { - set_output_type(from.output_type()); - } - if (from._has_bit(3)) { - mutable_options()->::google::protobuf::MethodOptions::MergeFrom(from.options()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void MethodDescriptorProto::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void MethodDescriptorProto::CopyFrom(const MethodDescriptorProto& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MethodDescriptorProto::IsInitialized() const { - - if (has_options()) { - if (!this->options().IsInitialized()) return false; - } - return true; -} - -void MethodDescriptorProto::Swap(MethodDescriptorProto* other) { - if (other != this) { - std::swap(name_, other->name_); - std::swap(input_type_, other->input_type_); - std::swap(output_type_, other->output_type_); - std::swap(options_, other->options_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata MethodDescriptorProto::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = MethodDescriptorProto_descriptor_; - metadata.reflection = MethodDescriptorProto_reflection_; - return metadata; -} - - -// =================================================================== - -const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor() { - protobuf_AssignDescriptorsOnce(); - return FileOptions_OptimizeMode_descriptor_; -} -bool FileOptions_OptimizeMode_IsValid(int value) { - switch(value) { - case 1: - case 2: - case 3: - return true; - default: - return false; - } -} - -#ifndef _MSC_VER -const FileOptions_OptimizeMode FileOptions::SPEED; -const FileOptions_OptimizeMode FileOptions::CODE_SIZE; -const FileOptions_OptimizeMode FileOptions::LITE_RUNTIME; -const FileOptions_OptimizeMode FileOptions::OptimizeMode_MIN; -const FileOptions_OptimizeMode FileOptions::OptimizeMode_MAX; -const int FileOptions::OptimizeMode_ARRAYSIZE; -#endif // _MSC_VER -const ::std::string FileOptions::_default_java_package_; -const ::std::string FileOptions::_default_java_outer_classname_; -#ifndef _MSC_VER -const int FileOptions::kJavaPackageFieldNumber; -const int FileOptions::kJavaOuterClassnameFieldNumber; -const int FileOptions::kJavaMultipleFilesFieldNumber; -const int FileOptions::kOptimizeForFieldNumber; -const int FileOptions::kCcGenericServicesFieldNumber; -const int FileOptions::kJavaGenericServicesFieldNumber; -const int FileOptions::kPyGenericServicesFieldNumber; -const int FileOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -FileOptions::FileOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void FileOptions::InitAsDefaultInstance() { -} - -FileOptions::FileOptions(const FileOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void FileOptions::SharedCtor() { - _cached_size_ = 0; - java_package_ = const_cast< ::std::string*>(&_default_java_package_); - java_outer_classname_ = const_cast< ::std::string*>(&_default_java_outer_classname_); - java_multiple_files_ = false; - optimize_for_ = 1; - cc_generic_services_ = true; - java_generic_services_ = true; - py_generic_services_ = true; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -FileOptions::~FileOptions() { - SharedDtor(); -} - -void FileOptions::SharedDtor() { - if (java_package_ != &_default_java_package_) { - delete java_package_; - } - if (java_outer_classname_ != &_default_java_outer_classname_) { - delete java_outer_classname_; - } - if (this != default_instance_) { - } -} - -void FileOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* FileOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return FileOptions_descriptor_; -} - -const FileOptions& FileOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -FileOptions* FileOptions::default_instance_ = NULL; - -FileOptions* FileOptions::New() const { - return new FileOptions; -} - -void FileOptions::Clear() { - _extensions_.Clear(); - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (java_package_ != &_default_java_package_) { - java_package_->clear(); - } - } - if (_has_bit(1)) { - if (java_outer_classname_ != &_default_java_outer_classname_) { - java_outer_classname_->clear(); - } - } - java_multiple_files_ = false; - optimize_for_ = 1; - cc_generic_services_ = true; - java_generic_services_ = true; - py_generic_services_ = true; - } - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool FileOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional string java_package = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_java_package())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->java_package().data(), this->java_package().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(66)) goto parse_java_outer_classname; - break; - } - - // optional string java_outer_classname = 8; - case 8: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_java_outer_classname: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_java_outer_classname())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->java_outer_classname().data(), this->java_outer_classname().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(72)) goto parse_optimize_for; - break; - } - - // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - case 9: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_optimize_for: - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - if (::google::protobuf::FileOptions_OptimizeMode_IsValid(value)) { - set_optimize_for(static_cast< ::google::protobuf::FileOptions_OptimizeMode >(value)); - } else { - mutable_unknown_fields()->AddVarint(9, value); - } - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(80)) goto parse_java_multiple_files; - break; - } - - // optional bool java_multiple_files = 10 [default = false]; - case 10: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_java_multiple_files: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &java_multiple_files_))); - _set_bit(2); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(128)) goto parse_cc_generic_services; - break; - } - - // optional bool cc_generic_services = 16 [default = true]; - case 16: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_cc_generic_services: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &cc_generic_services_))); - _set_bit(4); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(136)) goto parse_java_generic_services; - break; - } - - // optional bool java_generic_services = 17 [default = true]; - case 17: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_java_generic_services: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &java_generic_services_))); - _set_bit(5); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(144)) goto parse_py_generic_services; - break; - } - - // optional bool py_generic_services = 18 [default = true]; - case 18: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_py_generic_services: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &py_generic_services_))); - _set_bit(6); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - break; - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void FileOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional string java_package = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->java_package().data(), this->java_package().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->java_package(), output); - } - - // optional string java_outer_classname = 8; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->java_outer_classname().data(), this->java_outer_classname().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 8, this->java_outer_classname(), output); - } - - // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 9, this->optimize_for(), output); - } - - // optional bool java_multiple_files = 10 [default = false]; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(10, this->java_multiple_files(), output); - } - - // optional bool cc_generic_services = 16 [default = true]; - if (_has_bit(4)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(16, this->cc_generic_services(), output); - } - - // optional bool java_generic_services = 17 [default = true]; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(17, this->java_generic_services(), output); - } - - // optional bool py_generic_services = 18 [default = true]; - if (_has_bit(6)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(18, this->py_generic_services(), output); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* FileOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional string java_package = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->java_package().data(), this->java_package().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->java_package(), target); - } - - // optional string java_outer_classname = 8; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->java_outer_classname().data(), this->java_outer_classname().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 8, this->java_outer_classname(), target); - } - - // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - if (_has_bit(3)) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 9, this->optimize_for(), target); - } - - // optional bool java_multiple_files = 10 [default = false]; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(10, this->java_multiple_files(), target); - } - - // optional bool cc_generic_services = 16 [default = true]; - if (_has_bit(4)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(16, this->cc_generic_services(), target); - } - - // optional bool java_generic_services = 17 [default = true]; - if (_has_bit(5)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(17, this->java_generic_services(), target); - } - - // optional bool py_generic_services = 18 [default = true]; - if (_has_bit(6)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(18, this->py_generic_services(), target); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int FileOptions::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional string java_package = 1; - if (has_java_package()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->java_package()); - } - - // optional string java_outer_classname = 8; - if (has_java_outer_classname()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->java_outer_classname()); - } - - // optional bool java_multiple_files = 10 [default = false]; - if (has_java_multiple_files()) { - total_size += 1 + 1; - } - - // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - if (has_optimize_for()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->optimize_for()); - } - - // optional bool cc_generic_services = 16 [default = true]; - if (has_cc_generic_services()) { - total_size += 2 + 1; - } - - // optional bool java_generic_services = 17 [default = true]; - if (has_java_generic_services()) { - total_size += 2 + 1; - } - - // optional bool py_generic_services = 18 [default = true]; - if (has_py_generic_services()) { - total_size += 2 + 1; - } - - } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void FileOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const FileOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void FileOptions::MergeFrom(const FileOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_java_package(from.java_package()); - } - if (from._has_bit(1)) { - set_java_outer_classname(from.java_outer_classname()); - } - if (from._has_bit(2)) { - set_java_multiple_files(from.java_multiple_files()); - } - if (from._has_bit(3)) { - set_optimize_for(from.optimize_for()); - } - if (from._has_bit(4)) { - set_cc_generic_services(from.cc_generic_services()); - } - if (from._has_bit(5)) { - set_java_generic_services(from.java_generic_services()); - } - if (from._has_bit(6)) { - set_py_generic_services(from.py_generic_services()); - } - } - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void FileOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void FileOptions::CopyFrom(const FileOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool FileOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void FileOptions::Swap(FileOptions* other) { - if (other != this) { - std::swap(java_package_, other->java_package_); - std::swap(java_outer_classname_, other->java_outer_classname_); - std::swap(java_multiple_files_, other->java_multiple_files_); - std::swap(optimize_for_, other->optimize_for_); - std::swap(cc_generic_services_, other->cc_generic_services_); - std::swap(java_generic_services_, other->java_generic_services_); - std::swap(py_generic_services_, other->py_generic_services_); - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata FileOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = FileOptions_descriptor_; - metadata.reflection = FileOptions_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int MessageOptions::kMessageSetWireFormatFieldNumber; -const int MessageOptions::kNoStandardDescriptorAccessorFieldNumber; -const int MessageOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -MessageOptions::MessageOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void MessageOptions::InitAsDefaultInstance() { -} - -MessageOptions::MessageOptions(const MessageOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void MessageOptions::SharedCtor() { - _cached_size_ = 0; - message_set_wire_format_ = false; - no_standard_descriptor_accessor_ = false; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MessageOptions::~MessageOptions() { - SharedDtor(); -} - -void MessageOptions::SharedDtor() { - if (this != default_instance_) { - } -} - -void MessageOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* MessageOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return MessageOptions_descriptor_; -} - -const MessageOptions& MessageOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -MessageOptions* MessageOptions::default_instance_ = NULL; - -MessageOptions* MessageOptions::New() const { - return new MessageOptions; -} - -void MessageOptions::Clear() { - _extensions_.Clear(); - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - message_set_wire_format_ = false; - no_standard_descriptor_accessor_ = false; - } - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool MessageOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional bool message_set_wire_format = 1 [default = false]; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &message_set_wire_format_))); - _set_bit(0); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_no_standard_descriptor_accessor; - break; - } - - // optional bool no_standard_descriptor_accessor = 2 [default = false]; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_no_standard_descriptor_accessor: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &no_standard_descriptor_accessor_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - break; - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void MessageOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional bool message_set_wire_format = 1 [default = false]; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(1, this->message_set_wire_format(), output); - } - - // optional bool no_standard_descriptor_accessor = 2 [default = false]; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->no_standard_descriptor_accessor(), output); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* MessageOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional bool message_set_wire_format = 1 [default = false]; - if (_has_bit(0)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->message_set_wire_format(), target); - } - - // optional bool no_standard_descriptor_accessor = 2 [default = false]; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->no_standard_descriptor_accessor(), target); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int MessageOptions::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional bool message_set_wire_format = 1 [default = false]; - if (has_message_set_wire_format()) { - total_size += 1 + 1; - } - - // optional bool no_standard_descriptor_accessor = 2 [default = false]; - if (has_no_standard_descriptor_accessor()) { - total_size += 1 + 1; - } - - } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MessageOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const MessageOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void MessageOptions::MergeFrom(const MessageOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_message_set_wire_format(from.message_set_wire_format()); - } - if (from._has_bit(1)) { - set_no_standard_descriptor_accessor(from.no_standard_descriptor_accessor()); - } - } - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void MessageOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void MessageOptions::CopyFrom(const MessageOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MessageOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void MessageOptions::Swap(MessageOptions* other) { - if (other != this) { - std::swap(message_set_wire_format_, other->message_set_wire_format_); - std::swap(no_standard_descriptor_accessor_, other->no_standard_descriptor_accessor_); - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata MessageOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = MessageOptions_descriptor_; - metadata.reflection = MessageOptions_reflection_; - return metadata; -} - - -// =================================================================== - -const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor() { - protobuf_AssignDescriptorsOnce(); - return FieldOptions_CType_descriptor_; -} -bool FieldOptions_CType_IsValid(int value) { - switch(value) { - case 0: - case 1: - case 2: - return true; - default: - return false; - } -} - -#ifndef _MSC_VER -const FieldOptions_CType FieldOptions::STRING; -const FieldOptions_CType FieldOptions::CORD; -const FieldOptions_CType FieldOptions::STRING_PIECE; -const FieldOptions_CType FieldOptions::CType_MIN; -const FieldOptions_CType FieldOptions::CType_MAX; -const int FieldOptions::CType_ARRAYSIZE; -#endif // _MSC_VER -const ::std::string FieldOptions::_default_experimental_map_key_; -#ifndef _MSC_VER -const int FieldOptions::kCtypeFieldNumber; -const int FieldOptions::kPackedFieldNumber; -const int FieldOptions::kDeprecatedFieldNumber; -const int FieldOptions::kExperimentalMapKeyFieldNumber; -const int FieldOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -FieldOptions::FieldOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void FieldOptions::InitAsDefaultInstance() { -} - -FieldOptions::FieldOptions(const FieldOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void FieldOptions::SharedCtor() { - _cached_size_ = 0; - ctype_ = 0; - packed_ = false; - deprecated_ = false; - experimental_map_key_ = const_cast< ::std::string*>(&_default_experimental_map_key_); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -FieldOptions::~FieldOptions() { - SharedDtor(); -} - -void FieldOptions::SharedDtor() { - if (experimental_map_key_ != &_default_experimental_map_key_) { - delete experimental_map_key_; - } - if (this != default_instance_) { - } -} - -void FieldOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* FieldOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return FieldOptions_descriptor_; -} - -const FieldOptions& FieldOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -FieldOptions* FieldOptions::default_instance_ = NULL; - -FieldOptions* FieldOptions::New() const { - return new FieldOptions; -} - -void FieldOptions::Clear() { - _extensions_.Clear(); - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - ctype_ = 0; - packed_ = false; - deprecated_ = false; - if (_has_bit(3)) { - if (experimental_map_key_ != &_default_experimental_map_key_) { - experimental_map_key_->clear(); - } - } - } - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool FieldOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - int value; - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( - input, &value))); - if (::google::protobuf::FieldOptions_CType_IsValid(value)) { - set_ctype(static_cast< ::google::protobuf::FieldOptions_CType >(value)); - } else { - mutable_unknown_fields()->AddVarint(1, value); - } - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_packed; - break; - } - - // optional bool packed = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_packed: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &packed_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(24)) goto parse_deprecated; - break; - } - - // optional bool deprecated = 3 [default = false]; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_deprecated: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &deprecated_))); - _set_bit(2); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(74)) goto parse_experimental_map_key; - break; - } - - // optional string experimental_map_key = 9; - case 9: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_experimental_map_key: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_experimental_map_key())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->experimental_map_key().data(), this->experimental_map_key().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - break; - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void FieldOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormatLite::WriteEnum( - 1, this->ctype(), output); - } - - // optional bool packed = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->packed(), output); - } - - // optional bool deprecated = 3 [default = false]; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(3, this->deprecated(), output); - } - - // optional string experimental_map_key = 9; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->experimental_map_key().data(), this->experimental_map_key().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 9, this->experimental_map_key(), output); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* FieldOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; - if (_has_bit(0)) { - target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( - 1, this->ctype(), target); - } - - // optional bool packed = 2; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->packed(), target); - } - - // optional bool deprecated = 3 [default = false]; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(3, this->deprecated(), target); - } - - // optional string experimental_map_key = 9; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->experimental_map_key().data(), this->experimental_map_key().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 9, this->experimental_map_key(), target); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int FieldOptions::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; - if (has_ctype()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::EnumSize(this->ctype()); - } - - // optional bool packed = 2; - if (has_packed()) { - total_size += 1 + 1; - } - - // optional bool deprecated = 3 [default = false]; - if (has_deprecated()) { - total_size += 1 + 1; - } - - // optional string experimental_map_key = 9; - if (has_experimental_map_key()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->experimental_map_key()); - } - - } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void FieldOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const FieldOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void FieldOptions::MergeFrom(const FieldOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_ctype(from.ctype()); - } - if (from._has_bit(1)) { - set_packed(from.packed()); - } - if (from._has_bit(2)) { - set_deprecated(from.deprecated()); - } - if (from._has_bit(3)) { - set_experimental_map_key(from.experimental_map_key()); - } - } - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void FieldOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void FieldOptions::CopyFrom(const FieldOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool FieldOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void FieldOptions::Swap(FieldOptions* other) { - if (other != this) { - std::swap(ctype_, other->ctype_); - std::swap(packed_, other->packed_); - std::swap(deprecated_, other->deprecated_); - std::swap(experimental_map_key_, other->experimental_map_key_); - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata FieldOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = FieldOptions_descriptor_; - metadata.reflection = FieldOptions_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int EnumOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -EnumOptions::EnumOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void EnumOptions::InitAsDefaultInstance() { -} - -EnumOptions::EnumOptions(const EnumOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void EnumOptions::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -EnumOptions::~EnumOptions() { - SharedDtor(); -} - -void EnumOptions::SharedDtor() { - if (this != default_instance_) { - } -} - -void EnumOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* EnumOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return EnumOptions_descriptor_; -} - -const EnumOptions& EnumOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -EnumOptions* EnumOptions::default_instance_ = NULL; - -EnumOptions* EnumOptions::New() const { - return new EnumOptions; -} - -void EnumOptions::Clear() { - _extensions_.Clear(); - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool EnumOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void EnumOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* EnumOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int EnumOptions::ByteSize() const { - int total_size = 0; - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void EnumOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const EnumOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void EnumOptions::MergeFrom(const EnumOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void EnumOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void EnumOptions::CopyFrom(const EnumOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool EnumOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void EnumOptions::Swap(EnumOptions* other) { - if (other != this) { - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata EnumOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = EnumOptions_descriptor_; - metadata.reflection = EnumOptions_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int EnumValueOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -EnumValueOptions::EnumValueOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void EnumValueOptions::InitAsDefaultInstance() { -} - -EnumValueOptions::EnumValueOptions(const EnumValueOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void EnumValueOptions::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -EnumValueOptions::~EnumValueOptions() { - SharedDtor(); -} - -void EnumValueOptions::SharedDtor() { - if (this != default_instance_) { - } -} - -void EnumValueOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* EnumValueOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return EnumValueOptions_descriptor_; -} - -const EnumValueOptions& EnumValueOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -EnumValueOptions* EnumValueOptions::default_instance_ = NULL; - -EnumValueOptions* EnumValueOptions::New() const { - return new EnumValueOptions; -} - -void EnumValueOptions::Clear() { - _extensions_.Clear(); - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool EnumValueOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void EnumValueOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* EnumValueOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int EnumValueOptions::ByteSize() const { - int total_size = 0; - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void EnumValueOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const EnumValueOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void EnumValueOptions::MergeFrom(const EnumValueOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void EnumValueOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void EnumValueOptions::CopyFrom(const EnumValueOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool EnumValueOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void EnumValueOptions::Swap(EnumValueOptions* other) { - if (other != this) { - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata EnumValueOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = EnumValueOptions_descriptor_; - metadata.reflection = EnumValueOptions_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int ServiceOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -ServiceOptions::ServiceOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void ServiceOptions::InitAsDefaultInstance() { -} - -ServiceOptions::ServiceOptions(const ServiceOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void ServiceOptions::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -ServiceOptions::~ServiceOptions() { - SharedDtor(); -} - -void ServiceOptions::SharedDtor() { - if (this != default_instance_) { - } -} - -void ServiceOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* ServiceOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return ServiceOptions_descriptor_; -} - -const ServiceOptions& ServiceOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -ServiceOptions* ServiceOptions::default_instance_ = NULL; - -ServiceOptions* ServiceOptions::New() const { - return new ServiceOptions; -} - -void ServiceOptions::Clear() { - _extensions_.Clear(); - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool ServiceOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void ServiceOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* ServiceOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int ServiceOptions::ByteSize() const { - int total_size = 0; - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void ServiceOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const ServiceOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void ServiceOptions::MergeFrom(const ServiceOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void ServiceOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void ServiceOptions::CopyFrom(const ServiceOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool ServiceOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void ServiceOptions::Swap(ServiceOptions* other) { - if (other != this) { - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata ServiceOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = ServiceOptions_descriptor_; - metadata.reflection = ServiceOptions_reflection_; - return metadata; -} - - -// =================================================================== - -#ifndef _MSC_VER -const int MethodOptions::kUninterpretedOptionFieldNumber; -#endif // !_MSC_VER - -MethodOptions::MethodOptions() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void MethodOptions::InitAsDefaultInstance() { -} - -MethodOptions::MethodOptions(const MethodOptions& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void MethodOptions::SharedCtor() { - _cached_size_ = 0; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -MethodOptions::~MethodOptions() { - SharedDtor(); -} - -void MethodOptions::SharedDtor() { - if (this != default_instance_) { - } -} - -void MethodOptions::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* MethodOptions::descriptor() { - protobuf_AssignDescriptorsOnce(); - return MethodOptions_descriptor_; -} - -const MethodOptions& MethodOptions::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -MethodOptions* MethodOptions::default_instance_ = NULL; - -MethodOptions* MethodOptions::New() const { - return new MethodOptions; -} - -void MethodOptions::Clear() { - _extensions_.Clear(); - uninterpreted_option_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool MethodOptions::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - case 999: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_uninterpreted_option: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_uninterpreted_option())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(7994)) goto parse_uninterpreted_option; - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - if ((8000u <= tag)) { - DO_(_extensions_.ParseField(tag, input, default_instance_, - mutable_unknown_fields())); - continue; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void MethodOptions::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 999, this->uninterpreted_option(i), output); - } - - // Extension range [1000, 536870912) - _extensions_.SerializeWithCachedSizes( - 1000, 536870912, output); - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* MethodOptions::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 999, this->uninterpreted_option(i), target); - } - - // Extension range [1000, 536870912) - target = _extensions_.SerializeWithCachedSizesToArray( - 1000, 536870912, target); - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int MethodOptions::ByteSize() const { - int total_size = 0; - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - total_size += 2 * this->uninterpreted_option_size(); - for (int i = 0; i < this->uninterpreted_option_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->uninterpreted_option(i)); - } - - total_size += _extensions_.ByteSize(); - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void MethodOptions::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const MethodOptions* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void MethodOptions::MergeFrom(const MethodOptions& from) { - GOOGLE_CHECK_NE(&from, this); - uninterpreted_option_.MergeFrom(from.uninterpreted_option_); - _extensions_.MergeFrom(from._extensions_); - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void MethodOptions::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void MethodOptions::CopyFrom(const MethodOptions& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool MethodOptions::IsInitialized() const { - - for (int i = 0; i < uninterpreted_option_size(); i++) { - if (!this->uninterpreted_option(i).IsInitialized()) return false; - } - - if (!_extensions_.IsInitialized()) return false; return true; -} - -void MethodOptions::Swap(MethodOptions* other) { - if (other != this) { - uninterpreted_option_.Swap(&other->uninterpreted_option_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - _extensions_.Swap(&other->_extensions_); - } -} - -::google::protobuf::Metadata MethodOptions::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = MethodOptions_descriptor_; - metadata.reflection = MethodOptions_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string UninterpretedOption_NamePart::_default_name_part_; -#ifndef _MSC_VER -const int UninterpretedOption_NamePart::kNamePartFieldNumber; -const int UninterpretedOption_NamePart::kIsExtensionFieldNumber; -#endif // !_MSC_VER - -UninterpretedOption_NamePart::UninterpretedOption_NamePart() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void UninterpretedOption_NamePart::InitAsDefaultInstance() { -} - -UninterpretedOption_NamePart::UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void UninterpretedOption_NamePart::SharedCtor() { - _cached_size_ = 0; - name_part_ = const_cast< ::std::string*>(&_default_name_part_); - is_extension_ = false; - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -UninterpretedOption_NamePart::~UninterpretedOption_NamePart() { - SharedDtor(); -} - -void UninterpretedOption_NamePart::SharedDtor() { - if (name_part_ != &_default_name_part_) { - delete name_part_; - } - if (this != default_instance_) { - } -} - -void UninterpretedOption_NamePart::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* UninterpretedOption_NamePart::descriptor() { - protobuf_AssignDescriptorsOnce(); - return UninterpretedOption_NamePart_descriptor_; -} - -const UninterpretedOption_NamePart& UninterpretedOption_NamePart::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -UninterpretedOption_NamePart* UninterpretedOption_NamePart::default_instance_ = NULL; - -UninterpretedOption_NamePart* UninterpretedOption_NamePart::New() const { - return new UninterpretedOption_NamePart; -} - -void UninterpretedOption_NamePart::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (_has_bit(0)) { - if (name_part_ != &_default_name_part_) { - name_part_->clear(); - } - } - is_extension_ = false; - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool UninterpretedOption_NamePart::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // required string name_part = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_name_part())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name_part().data(), this->name_part().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_is_extension; - break; - } - - // required bool is_extension = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_is_extension: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( - input, &is_extension_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void UninterpretedOption_NamePart::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // required string name_part = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name_part().data(), this->name_part().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 1, this->name_part(), output); - } - - // required bool is_extension = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteBool(2, this->is_extension(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* UninterpretedOption_NamePart::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // required string name_part = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->name_part().data(), this->name_part().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 1, this->name_part(), target); - } - - // required bool is_extension = 2; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(2, this->is_extension(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int UninterpretedOption_NamePart::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // required string name_part = 1; - if (has_name_part()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->name_part()); - } - - // required bool is_extension = 2; - if (has_is_extension()) { - total_size += 1 + 1; - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void UninterpretedOption_NamePart::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const UninterpretedOption_NamePart* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void UninterpretedOption_NamePart::MergeFrom(const UninterpretedOption_NamePart& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_name_part(from.name_part()); - } - if (from._has_bit(1)) { - set_is_extension(from.is_extension()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void UninterpretedOption_NamePart::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void UninterpretedOption_NamePart::CopyFrom(const UninterpretedOption_NamePart& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool UninterpretedOption_NamePart::IsInitialized() const { - if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; - - return true; -} - -void UninterpretedOption_NamePart::Swap(UninterpretedOption_NamePart* other) { - if (other != this) { - std::swap(name_part_, other->name_part_); - std::swap(is_extension_, other->is_extension_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata UninterpretedOption_NamePart::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = UninterpretedOption_NamePart_descriptor_; - metadata.reflection = UninterpretedOption_NamePart_reflection_; - return metadata; -} - - -// ------------------------------------------------------------------- - -const ::std::string UninterpretedOption::_default_identifier_value_; -const ::std::string UninterpretedOption::_default_string_value_; -#ifndef _MSC_VER -const int UninterpretedOption::kNameFieldNumber; -const int UninterpretedOption::kIdentifierValueFieldNumber; -const int UninterpretedOption::kPositiveIntValueFieldNumber; -const int UninterpretedOption::kNegativeIntValueFieldNumber; -const int UninterpretedOption::kDoubleValueFieldNumber; -const int UninterpretedOption::kStringValueFieldNumber; -#endif // !_MSC_VER - -UninterpretedOption::UninterpretedOption() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void UninterpretedOption::InitAsDefaultInstance() { -} - -UninterpretedOption::UninterpretedOption(const UninterpretedOption& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void UninterpretedOption::SharedCtor() { - _cached_size_ = 0; - identifier_value_ = const_cast< ::std::string*>(&_default_identifier_value_); - positive_int_value_ = GOOGLE_ULONGLONG(0); - negative_int_value_ = GOOGLE_LONGLONG(0); - double_value_ = 0; - string_value_ = const_cast< ::std::string*>(&_default_string_value_); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -UninterpretedOption::~UninterpretedOption() { - SharedDtor(); -} - -void UninterpretedOption::SharedDtor() { - if (identifier_value_ != &_default_identifier_value_) { - delete identifier_value_; - } - if (string_value_ != &_default_string_value_) { - delete string_value_; - } - if (this != default_instance_) { - } -} - -void UninterpretedOption::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* UninterpretedOption::descriptor() { - protobuf_AssignDescriptorsOnce(); - return UninterpretedOption_descriptor_; -} - -const UninterpretedOption& UninterpretedOption::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); return *default_instance_; -} - -UninterpretedOption* UninterpretedOption::default_instance_ = NULL; - -UninterpretedOption* UninterpretedOption::New() const { - return new UninterpretedOption; -} - -void UninterpretedOption::Clear() { - if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) { - if (_has_bit(1)) { - if (identifier_value_ != &_default_identifier_value_) { - identifier_value_->clear(); - } - } - positive_int_value_ = GOOGLE_ULONGLONG(0); - negative_int_value_ = GOOGLE_LONGLONG(0); - double_value_ = 0; - if (_has_bit(5)) { - if (string_value_ != &_default_string_value_) { - string_value_->clear(); - } - } - } - name_.Clear(); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool UninterpretedOption::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_name: - DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( - input, add_name())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_name; - if (input->ExpectTag(26)) goto parse_identifier_value; - break; - } - - // optional string identifier_value = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_identifier_value: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_identifier_value())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->identifier_value().data(), this->identifier_value().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(32)) goto parse_positive_int_value; - break; - } - - // optional uint64 positive_int_value = 4; - case 4: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_positive_int_value: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( - input, &positive_int_value_))); - _set_bit(2); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(40)) goto parse_negative_int_value; - break; - } - - // optional int64 negative_int_value = 5; - case 5: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_negative_int_value: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( - input, &negative_int_value_))); - _set_bit(3); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(49)) goto parse_double_value; - break; - } - - // optional double double_value = 6; - case 6: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) { - parse_double_value: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( - input, &double_value_))); - _set_bit(4); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(58)) goto parse_string_value; - break; - } - - // optional bytes string_value = 7; - case 7: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_string_value: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_string_value())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void UninterpretedOption::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; - for (int i = 0; i < this->name_size(); i++) { - ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( - 2, this->name(i), output); - } - - // optional string identifier_value = 3; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->identifier_value().data(), this->identifier_value().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 3, this->identifier_value(), output); - } - - // optional uint64 positive_int_value = 4; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt64(4, this->positive_int_value(), output); - } - - // optional int64 negative_int_value = 5; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->negative_int_value(), output); - } - - // optional double double_value = 6; - if (_has_bit(4)) { - ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->double_value(), output); - } - - // optional bytes string_value = 7; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormatLite::WriteBytes( - 7, this->string_value(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* UninterpretedOption::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; - for (int i = 0; i < this->name_size(); i++) { - target = ::google::protobuf::internal::WireFormatLite:: - WriteMessageNoVirtualToArray( - 2, this->name(i), target); - } - - // optional string identifier_value = 3; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->identifier_value().data(), this->identifier_value().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 3, this->identifier_value(), target); - } - - // optional uint64 positive_int_value = 4; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(4, this->positive_int_value(), target); - } - - // optional int64 negative_int_value = 5; - if (_has_bit(3)) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->negative_int_value(), target); - } - - // optional double double_value = 6; - if (_has_bit(4)) { - target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->double_value(), target); - } - - // optional bytes string_value = 7; - if (_has_bit(5)) { - target = - ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( - 7, this->string_value(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int UninterpretedOption::ByteSize() const { - int total_size = 0; - - if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) { - // optional string identifier_value = 3; - if (has_identifier_value()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->identifier_value()); - } - - // optional uint64 positive_int_value = 4; - if (has_positive_int_value()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt64Size( - this->positive_int_value()); - } - - // optional int64 negative_int_value = 5; - if (has_negative_int_value()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int64Size( - this->negative_int_value()); - } - - // optional double double_value = 6; - if (has_double_value()) { - total_size += 1 + 8; - } - - // optional bytes string_value = 7; - if (has_string_value()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->string_value()); - } - - } - // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; - total_size += 1 * this->name_size(); - for (int i = 0; i < this->name_size(); i++) { - total_size += - ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( - this->name(i)); - } - - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void UninterpretedOption::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const UninterpretedOption* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void UninterpretedOption::MergeFrom(const UninterpretedOption& from) { - GOOGLE_CHECK_NE(&from, this); - name_.MergeFrom(from.name_); - if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) { - if (from._has_bit(1)) { - set_identifier_value(from.identifier_value()); - } - if (from._has_bit(2)) { - set_positive_int_value(from.positive_int_value()); - } - if (from._has_bit(3)) { - set_negative_int_value(from.negative_int_value()); - } - if (from._has_bit(4)) { - set_double_value(from.double_value()); - } - if (from._has_bit(5)) { - set_string_value(from.string_value()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void UninterpretedOption::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void UninterpretedOption::CopyFrom(const UninterpretedOption& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool UninterpretedOption::IsInitialized() const { - - for (int i = 0; i < name_size(); i++) { - if (!this->name(i).IsInitialized()) return false; - } - return true; -} - -void UninterpretedOption::Swap(UninterpretedOption* other) { - if (other != this) { - name_.Swap(&other->name_); - std::swap(identifier_value_, other->identifier_value_); - std::swap(positive_int_value_, other->positive_int_value_); - std::swap(negative_int_value_, other->negative_int_value_); - std::swap(double_value_, other->double_value_); - std::swap(string_value_, other->string_value_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata UninterpretedOption::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = UninterpretedOption_descriptor_; - metadata.reflection = UninterpretedOption_reflection_; - return metadata; -} - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace protobuf -} // namespace google - -// @@protoc_insertion_point(global_scope) diff --git a/Resources/NetHook/google/protobuf/descriptor.pb.h b/Resources/NetHook/google/protobuf/descriptor.pb.h deleted file mode 100644 index 2743b6f5..00000000 --- a/Resources/NetHook/google/protobuf/descriptor.pb.h +++ /dev/null @@ -1,4355 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: google/protobuf/descriptor.proto - -#ifndef PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto__INCLUDED -#define PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto__INCLUDED - -#include - -#include - -#if GOOGLE_PROTOBUF_VERSION < 2003000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 2003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif - -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace google { -namespace protobuf { - -// Internal implementation detail -- do not call these. -void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); -void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); -void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - -class FileDescriptorSet; -class FileDescriptorProto; -class DescriptorProto; -class DescriptorProto_ExtensionRange; -class FieldDescriptorProto; -class EnumDescriptorProto; -class EnumValueDescriptorProto; -class ServiceDescriptorProto; -class MethodDescriptorProto; -class FileOptions; -class MessageOptions; -class FieldOptions; -class EnumOptions; -class EnumValueOptions; -class ServiceOptions; -class MethodOptions; -class UninterpretedOption; -class UninterpretedOption_NamePart; - -enum FieldDescriptorProto_Type { - FieldDescriptorProto_Type_TYPE_DOUBLE = 1, - FieldDescriptorProto_Type_TYPE_FLOAT = 2, - FieldDescriptorProto_Type_TYPE_INT64 = 3, - FieldDescriptorProto_Type_TYPE_UINT64 = 4, - FieldDescriptorProto_Type_TYPE_INT32 = 5, - FieldDescriptorProto_Type_TYPE_FIXED64 = 6, - FieldDescriptorProto_Type_TYPE_FIXED32 = 7, - FieldDescriptorProto_Type_TYPE_BOOL = 8, - FieldDescriptorProto_Type_TYPE_STRING = 9, - FieldDescriptorProto_Type_TYPE_GROUP = 10, - FieldDescriptorProto_Type_TYPE_MESSAGE = 11, - FieldDescriptorProto_Type_TYPE_BYTES = 12, - FieldDescriptorProto_Type_TYPE_UINT32 = 13, - FieldDescriptorProto_Type_TYPE_ENUM = 14, - FieldDescriptorProto_Type_TYPE_SFIXED32 = 15, - FieldDescriptorProto_Type_TYPE_SFIXED64 = 16, - FieldDescriptorProto_Type_TYPE_SINT32 = 17, - FieldDescriptorProto_Type_TYPE_SINT64 = 18 -}; -LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Type_IsValid(int value); -const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MIN = FieldDescriptorProto_Type_TYPE_DOUBLE; -const FieldDescriptorProto_Type FieldDescriptorProto_Type_Type_MAX = FieldDescriptorProto_Type_TYPE_SINT64; -const int FieldDescriptorProto_Type_Type_ARRAYSIZE = FieldDescriptorProto_Type_Type_MAX + 1; - -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Type_descriptor(); -inline const ::std::string& FieldDescriptorProto_Type_Name(FieldDescriptorProto_Type value) { - return ::google::protobuf::internal::NameOfEnum( - FieldDescriptorProto_Type_descriptor(), value); -} -inline bool FieldDescriptorProto_Type_Parse( - const ::std::string& name, FieldDescriptorProto_Type* value) { - return ::google::protobuf::internal::ParseNamedEnum( - FieldDescriptorProto_Type_descriptor(), name, value); -} -enum FieldDescriptorProto_Label { - FieldDescriptorProto_Label_LABEL_OPTIONAL = 1, - FieldDescriptorProto_Label_LABEL_REQUIRED = 2, - FieldDescriptorProto_Label_LABEL_REPEATED = 3 -}; -LIBPROTOBUF_EXPORT bool FieldDescriptorProto_Label_IsValid(int value); -const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MIN = FieldDescriptorProto_Label_LABEL_OPTIONAL; -const FieldDescriptorProto_Label FieldDescriptorProto_Label_Label_MAX = FieldDescriptorProto_Label_LABEL_REPEATED; -const int FieldDescriptorProto_Label_Label_ARRAYSIZE = FieldDescriptorProto_Label_Label_MAX + 1; - -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldDescriptorProto_Label_descriptor(); -inline const ::std::string& FieldDescriptorProto_Label_Name(FieldDescriptorProto_Label value) { - return ::google::protobuf::internal::NameOfEnum( - FieldDescriptorProto_Label_descriptor(), value); -} -inline bool FieldDescriptorProto_Label_Parse( - const ::std::string& name, FieldDescriptorProto_Label* value) { - return ::google::protobuf::internal::ParseNamedEnum( - FieldDescriptorProto_Label_descriptor(), name, value); -} -enum FileOptions_OptimizeMode { - FileOptions_OptimizeMode_SPEED = 1, - FileOptions_OptimizeMode_CODE_SIZE = 2, - FileOptions_OptimizeMode_LITE_RUNTIME = 3 -}; -LIBPROTOBUF_EXPORT bool FileOptions_OptimizeMode_IsValid(int value); -const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MIN = FileOptions_OptimizeMode_SPEED; -const FileOptions_OptimizeMode FileOptions_OptimizeMode_OptimizeMode_MAX = FileOptions_OptimizeMode_LITE_RUNTIME; -const int FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE = FileOptions_OptimizeMode_OptimizeMode_MAX + 1; - -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FileOptions_OptimizeMode_descriptor(); -inline const ::std::string& FileOptions_OptimizeMode_Name(FileOptions_OptimizeMode value) { - return ::google::protobuf::internal::NameOfEnum( - FileOptions_OptimizeMode_descriptor(), value); -} -inline bool FileOptions_OptimizeMode_Parse( - const ::std::string& name, FileOptions_OptimizeMode* value) { - return ::google::protobuf::internal::ParseNamedEnum( - FileOptions_OptimizeMode_descriptor(), name, value); -} -enum FieldOptions_CType { - FieldOptions_CType_STRING = 0, - FieldOptions_CType_CORD = 1, - FieldOptions_CType_STRING_PIECE = 2 -}; -LIBPROTOBUF_EXPORT bool FieldOptions_CType_IsValid(int value); -const FieldOptions_CType FieldOptions_CType_CType_MIN = FieldOptions_CType_STRING; -const FieldOptions_CType FieldOptions_CType_CType_MAX = FieldOptions_CType_STRING_PIECE; -const int FieldOptions_CType_CType_ARRAYSIZE = FieldOptions_CType_CType_MAX + 1; - -LIBPROTOBUF_EXPORT const ::google::protobuf::EnumDescriptor* FieldOptions_CType_descriptor(); -inline const ::std::string& FieldOptions_CType_Name(FieldOptions_CType value) { - return ::google::protobuf::internal::NameOfEnum( - FieldOptions_CType_descriptor(), value); -} -inline bool FieldOptions_CType_Parse( - const ::std::string& name, FieldOptions_CType* value) { - return ::google::protobuf::internal::ParseNamedEnum( - FieldOptions_CType_descriptor(), name, value); -} -// =================================================================== - -class LIBPROTOBUF_EXPORT FileDescriptorSet : public ::google::protobuf::Message { - public: - FileDescriptorSet(); - virtual ~FileDescriptorSet(); - - FileDescriptorSet(const FileDescriptorSet& from); - - inline FileDescriptorSet& operator=(const FileDescriptorSet& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const FileDescriptorSet& default_instance(); - - void Swap(FileDescriptorSet* other); - - // implements Message ---------------------------------------------- - - FileDescriptorSet* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const FileDescriptorSet& from); - void MergeFrom(const FileDescriptorSet& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .google.protobuf.FileDescriptorProto file = 1; - inline int file_size() const; - inline void clear_file(); - static const int kFileFieldNumber = 1; - inline const ::google::protobuf::FileDescriptorProto& file(int index) const; - inline ::google::protobuf::FileDescriptorProto* mutable_file(int index); - inline ::google::protobuf::FileDescriptorProto* add_file(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& - file() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* - mutable_file(); - - // @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorSet) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto > file_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static FileDescriptorSet* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT FileDescriptorProto : public ::google::protobuf::Message { - public: - FileDescriptorProto(); - virtual ~FileDescriptorProto(); - - FileDescriptorProto(const FileDescriptorProto& from); - - inline FileDescriptorProto& operator=(const FileDescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const FileDescriptorProto& default_instance(); - - void Swap(FileDescriptorProto* other); - - // implements Message ---------------------------------------------- - - FileDescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const FileDescriptorProto& from); - void MergeFrom(const FileDescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // optional string package = 2; - inline bool has_package() const; - inline void clear_package(); - static const int kPackageFieldNumber = 2; - inline const ::std::string& package() const; - inline void set_package(const ::std::string& value); - inline void set_package(const char* value); - inline void set_package(const char* value, size_t size); - inline ::std::string* mutable_package(); - - // repeated string dependency = 3; - inline int dependency_size() const; - inline void clear_dependency(); - static const int kDependencyFieldNumber = 3; - inline const ::std::string& dependency(int index) const; - inline ::std::string* mutable_dependency(int index); - inline void set_dependency(int index, const ::std::string& value); - inline void set_dependency(int index, const char* value); - inline void set_dependency(int index, const char* value, size_t size); - inline ::std::string* add_dependency(); - inline void add_dependency(const ::std::string& value); - inline void add_dependency(const char* value); - inline void add_dependency(const char* value, size_t size); - inline const ::google::protobuf::RepeatedPtrField< ::std::string>& dependency() const; - inline ::google::protobuf::RepeatedPtrField< ::std::string>* mutable_dependency(); - - // repeated .google.protobuf.DescriptorProto message_type = 4; - inline int message_type_size() const; - inline void clear_message_type(); - static const int kMessageTypeFieldNumber = 4; - inline const ::google::protobuf::DescriptorProto& message_type(int index) const; - inline ::google::protobuf::DescriptorProto* mutable_message_type(int index); - inline ::google::protobuf::DescriptorProto* add_message_type(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& - message_type() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* - mutable_message_type(); - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; - inline int enum_type_size() const; - inline void clear_enum_type(); - static const int kEnumTypeFieldNumber = 5; - inline const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const; - inline ::google::protobuf::EnumDescriptorProto* mutable_enum_type(int index); - inline ::google::protobuf::EnumDescriptorProto* add_enum_type(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& - enum_type() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* - mutable_enum_type(); - - // repeated .google.protobuf.ServiceDescriptorProto service = 6; - inline int service_size() const; - inline void clear_service(); - static const int kServiceFieldNumber = 6; - inline const ::google::protobuf::ServiceDescriptorProto& service(int index) const; - inline ::google::protobuf::ServiceDescriptorProto* mutable_service(int index); - inline ::google::protobuf::ServiceDescriptorProto* add_service(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >& - service() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >* - mutable_service(); - - // repeated .google.protobuf.FieldDescriptorProto extension = 7; - inline int extension_size() const; - inline void clear_extension(); - static const int kExtensionFieldNumber = 7; - inline const ::google::protobuf::FieldDescriptorProto& extension(int index) const; - inline ::google::protobuf::FieldDescriptorProto* mutable_extension(int index); - inline ::google::protobuf::FieldDescriptorProto* add_extension(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& - extension() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* - mutable_extension(); - - // optional .google.protobuf.FileOptions options = 8; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 8; - inline const ::google::protobuf::FileOptions& options() const; - inline ::google::protobuf::FileOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.FileDescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::std::string* package_; - static const ::std::string _default_package_; - ::google::protobuf::RepeatedPtrField< ::std::string> dependency_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > message_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto > service_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_; - ::google::protobuf::FileOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(8 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static FileDescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT DescriptorProto_ExtensionRange : public ::google::protobuf::Message { - public: - DescriptorProto_ExtensionRange(); - virtual ~DescriptorProto_ExtensionRange(); - - DescriptorProto_ExtensionRange(const DescriptorProto_ExtensionRange& from); - - inline DescriptorProto_ExtensionRange& operator=(const DescriptorProto_ExtensionRange& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const DescriptorProto_ExtensionRange& default_instance(); - - void Swap(DescriptorProto_ExtensionRange* other); - - // implements Message ---------------------------------------------- - - DescriptorProto_ExtensionRange* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const DescriptorProto_ExtensionRange& from); - void MergeFrom(const DescriptorProto_ExtensionRange& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional int32 start = 1; - inline bool has_start() const; - inline void clear_start(); - static const int kStartFieldNumber = 1; - inline ::google::protobuf::int32 start() const; - inline void set_start(::google::protobuf::int32 value); - - // optional int32 end = 2; - inline bool has_end() const; - inline void clear_end(); - static const int kEndFieldNumber = 2; - inline ::google::protobuf::int32 end() const; - inline void set_end(::google::protobuf::int32 value); - - // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto.ExtensionRange) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::int32 start_; - ::google::protobuf::int32 end_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static DescriptorProto_ExtensionRange* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT DescriptorProto : public ::google::protobuf::Message { - public: - DescriptorProto(); - virtual ~DescriptorProto(); - - DescriptorProto(const DescriptorProto& from); - - inline DescriptorProto& operator=(const DescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const DescriptorProto& default_instance(); - - void Swap(DescriptorProto* other); - - // implements Message ---------------------------------------------- - - DescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const DescriptorProto& from); - void MergeFrom(const DescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - typedef DescriptorProto_ExtensionRange ExtensionRange; - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // repeated .google.protobuf.FieldDescriptorProto field = 2; - inline int field_size() const; - inline void clear_field(); - static const int kFieldFieldNumber = 2; - inline const ::google::protobuf::FieldDescriptorProto& field(int index) const; - inline ::google::protobuf::FieldDescriptorProto* mutable_field(int index); - inline ::google::protobuf::FieldDescriptorProto* add_field(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& - field() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* - mutable_field(); - - // repeated .google.protobuf.FieldDescriptorProto extension = 6; - inline int extension_size() const; - inline void clear_extension(); - static const int kExtensionFieldNumber = 6; - inline const ::google::protobuf::FieldDescriptorProto& extension(int index) const; - inline ::google::protobuf::FieldDescriptorProto* mutable_extension(int index); - inline ::google::protobuf::FieldDescriptorProto* add_extension(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& - extension() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* - mutable_extension(); - - // repeated .google.protobuf.DescriptorProto nested_type = 3; - inline int nested_type_size() const; - inline void clear_nested_type(); - static const int kNestedTypeFieldNumber = 3; - inline const ::google::protobuf::DescriptorProto& nested_type(int index) const; - inline ::google::protobuf::DescriptorProto* mutable_nested_type(int index); - inline ::google::protobuf::DescriptorProto* add_nested_type(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& - nested_type() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* - mutable_nested_type(); - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; - inline int enum_type_size() const; - inline void clear_enum_type(); - static const int kEnumTypeFieldNumber = 4; - inline const ::google::protobuf::EnumDescriptorProto& enum_type(int index) const; - inline ::google::protobuf::EnumDescriptorProto* mutable_enum_type(int index); - inline ::google::protobuf::EnumDescriptorProto* add_enum_type(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& - enum_type() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* - mutable_enum_type(); - - // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; - inline int extension_range_size() const; - inline void clear_extension_range(); - static const int kExtensionRangeFieldNumber = 5; - inline const ::google::protobuf::DescriptorProto_ExtensionRange& extension_range(int index) const; - inline ::google::protobuf::DescriptorProto_ExtensionRange* mutable_extension_range(int index); - inline ::google::protobuf::DescriptorProto_ExtensionRange* add_extension_range(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >& - extension_range() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >* - mutable_extension_range(); - - // optional .google.protobuf.MessageOptions options = 7; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 7; - inline const ::google::protobuf::MessageOptions& options() const; - inline ::google::protobuf::MessageOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.DescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > field_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto > extension_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto > nested_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto > enum_type_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange > extension_range_; - ::google::protobuf::MessageOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(7 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static DescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT FieldDescriptorProto : public ::google::protobuf::Message { - public: - FieldDescriptorProto(); - virtual ~FieldDescriptorProto(); - - FieldDescriptorProto(const FieldDescriptorProto& from); - - inline FieldDescriptorProto& operator=(const FieldDescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const FieldDescriptorProto& default_instance(); - - void Swap(FieldDescriptorProto* other); - - // implements Message ---------------------------------------------- - - FieldDescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const FieldDescriptorProto& from); - void MergeFrom(const FieldDescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - typedef FieldDescriptorProto_Type Type; - static const Type TYPE_DOUBLE = FieldDescriptorProto_Type_TYPE_DOUBLE; - static const Type TYPE_FLOAT = FieldDescriptorProto_Type_TYPE_FLOAT; - static const Type TYPE_INT64 = FieldDescriptorProto_Type_TYPE_INT64; - static const Type TYPE_UINT64 = FieldDescriptorProto_Type_TYPE_UINT64; - static const Type TYPE_INT32 = FieldDescriptorProto_Type_TYPE_INT32; - static const Type TYPE_FIXED64 = FieldDescriptorProto_Type_TYPE_FIXED64; - static const Type TYPE_FIXED32 = FieldDescriptorProto_Type_TYPE_FIXED32; - static const Type TYPE_BOOL = FieldDescriptorProto_Type_TYPE_BOOL; - static const Type TYPE_STRING = FieldDescriptorProto_Type_TYPE_STRING; - static const Type TYPE_GROUP = FieldDescriptorProto_Type_TYPE_GROUP; - static const Type TYPE_MESSAGE = FieldDescriptorProto_Type_TYPE_MESSAGE; - static const Type TYPE_BYTES = FieldDescriptorProto_Type_TYPE_BYTES; - static const Type TYPE_UINT32 = FieldDescriptorProto_Type_TYPE_UINT32; - static const Type TYPE_ENUM = FieldDescriptorProto_Type_TYPE_ENUM; - static const Type TYPE_SFIXED32 = FieldDescriptorProto_Type_TYPE_SFIXED32; - static const Type TYPE_SFIXED64 = FieldDescriptorProto_Type_TYPE_SFIXED64; - static const Type TYPE_SINT32 = FieldDescriptorProto_Type_TYPE_SINT32; - static const Type TYPE_SINT64 = FieldDescriptorProto_Type_TYPE_SINT64; - static inline bool Type_IsValid(int value) { - return FieldDescriptorProto_Type_IsValid(value); - } - static const Type Type_MIN = - FieldDescriptorProto_Type_Type_MIN; - static const Type Type_MAX = - FieldDescriptorProto_Type_Type_MAX; - static const int Type_ARRAYSIZE = - FieldDescriptorProto_Type_Type_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* - Type_descriptor() { - return FieldDescriptorProto_Type_descriptor(); - } - static inline const ::std::string& Type_Name(Type value) { - return FieldDescriptorProto_Type_Name(value); - } - static inline bool Type_Parse(const ::std::string& name, - Type* value) { - return FieldDescriptorProto_Type_Parse(name, value); - } - - typedef FieldDescriptorProto_Label Label; - static const Label LABEL_OPTIONAL = FieldDescriptorProto_Label_LABEL_OPTIONAL; - static const Label LABEL_REQUIRED = FieldDescriptorProto_Label_LABEL_REQUIRED; - static const Label LABEL_REPEATED = FieldDescriptorProto_Label_LABEL_REPEATED; - static inline bool Label_IsValid(int value) { - return FieldDescriptorProto_Label_IsValid(value); - } - static const Label Label_MIN = - FieldDescriptorProto_Label_Label_MIN; - static const Label Label_MAX = - FieldDescriptorProto_Label_Label_MAX; - static const int Label_ARRAYSIZE = - FieldDescriptorProto_Label_Label_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* - Label_descriptor() { - return FieldDescriptorProto_Label_descriptor(); - } - static inline const ::std::string& Label_Name(Label value) { - return FieldDescriptorProto_Label_Name(value); - } - static inline bool Label_Parse(const ::std::string& name, - Label* value) { - return FieldDescriptorProto_Label_Parse(name, value); - } - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // optional int32 number = 3; - inline bool has_number() const; - inline void clear_number(); - static const int kNumberFieldNumber = 3; - inline ::google::protobuf::int32 number() const; - inline void set_number(::google::protobuf::int32 value); - - // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - inline bool has_label() const; - inline void clear_label(); - static const int kLabelFieldNumber = 4; - inline ::google::protobuf::FieldDescriptorProto_Label label() const; - inline void set_label(::google::protobuf::FieldDescriptorProto_Label value); - - // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - inline bool has_type() const; - inline void clear_type(); - static const int kTypeFieldNumber = 5; - inline ::google::protobuf::FieldDescriptorProto_Type type() const; - inline void set_type(::google::protobuf::FieldDescriptorProto_Type value); - - // optional string type_name = 6; - inline bool has_type_name() const; - inline void clear_type_name(); - static const int kTypeNameFieldNumber = 6; - inline const ::std::string& type_name() const; - inline void set_type_name(const ::std::string& value); - inline void set_type_name(const char* value); - inline void set_type_name(const char* value, size_t size); - inline ::std::string* mutable_type_name(); - - // optional string extendee = 2; - inline bool has_extendee() const; - inline void clear_extendee(); - static const int kExtendeeFieldNumber = 2; - inline const ::std::string& extendee() const; - inline void set_extendee(const ::std::string& value); - inline void set_extendee(const char* value); - inline void set_extendee(const char* value, size_t size); - inline ::std::string* mutable_extendee(); - - // optional string default_value = 7; - inline bool has_default_value() const; - inline void clear_default_value(); - static const int kDefaultValueFieldNumber = 7; - inline const ::std::string& default_value() const; - inline void set_default_value(const ::std::string& value); - inline void set_default_value(const char* value); - inline void set_default_value(const char* value, size_t size); - inline ::std::string* mutable_default_value(); - - // optional .google.protobuf.FieldOptions options = 8; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 8; - inline const ::google::protobuf::FieldOptions& options() const; - inline ::google::protobuf::FieldOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.FieldDescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::google::protobuf::int32 number_; - int label_; - int type_; - ::std::string* type_name_; - static const ::std::string _default_type_name_; - ::std::string* extendee_; - static const ::std::string _default_extendee_; - ::std::string* default_value_; - static const ::std::string _default_default_value_; - ::google::protobuf::FieldOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(8 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static FieldDescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT EnumDescriptorProto : public ::google::protobuf::Message { - public: - EnumDescriptorProto(); - virtual ~EnumDescriptorProto(); - - EnumDescriptorProto(const EnumDescriptorProto& from); - - inline EnumDescriptorProto& operator=(const EnumDescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const EnumDescriptorProto& default_instance(); - - void Swap(EnumDescriptorProto* other); - - // implements Message ---------------------------------------------- - - EnumDescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const EnumDescriptorProto& from); - void MergeFrom(const EnumDescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // repeated .google.protobuf.EnumValueDescriptorProto value = 2; - inline int value_size() const; - inline void clear_value(); - static const int kValueFieldNumber = 2; - inline const ::google::protobuf::EnumValueDescriptorProto& value(int index) const; - inline ::google::protobuf::EnumValueDescriptorProto* mutable_value(int index); - inline ::google::protobuf::EnumValueDescriptorProto* add_value(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >& - value() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >* - mutable_value(); - - // optional .google.protobuf.EnumOptions options = 3; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 3; - inline const ::google::protobuf::EnumOptions& options() const; - inline ::google::protobuf::EnumOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.EnumDescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto > value_; - ::google::protobuf::EnumOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static EnumDescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT EnumValueDescriptorProto : public ::google::protobuf::Message { - public: - EnumValueDescriptorProto(); - virtual ~EnumValueDescriptorProto(); - - EnumValueDescriptorProto(const EnumValueDescriptorProto& from); - - inline EnumValueDescriptorProto& operator=(const EnumValueDescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const EnumValueDescriptorProto& default_instance(); - - void Swap(EnumValueDescriptorProto* other); - - // implements Message ---------------------------------------------- - - EnumValueDescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const EnumValueDescriptorProto& from); - void MergeFrom(const EnumValueDescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // optional int32 number = 2; - inline bool has_number() const; - inline void clear_number(); - static const int kNumberFieldNumber = 2; - inline ::google::protobuf::int32 number() const; - inline void set_number(::google::protobuf::int32 value); - - // optional .google.protobuf.EnumValueOptions options = 3; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 3; - inline const ::google::protobuf::EnumValueOptions& options() const; - inline ::google::protobuf::EnumValueOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.EnumValueDescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::google::protobuf::int32 number_; - ::google::protobuf::EnumValueOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static EnumValueDescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT ServiceDescriptorProto : public ::google::protobuf::Message { - public: - ServiceDescriptorProto(); - virtual ~ServiceDescriptorProto(); - - ServiceDescriptorProto(const ServiceDescriptorProto& from); - - inline ServiceDescriptorProto& operator=(const ServiceDescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ServiceDescriptorProto& default_instance(); - - void Swap(ServiceDescriptorProto* other); - - // implements Message ---------------------------------------------- - - ServiceDescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ServiceDescriptorProto& from); - void MergeFrom(const ServiceDescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // repeated .google.protobuf.MethodDescriptorProto method = 2; - inline int method_size() const; - inline void clear_method(); - static const int kMethodFieldNumber = 2; - inline const ::google::protobuf::MethodDescriptorProto& method(int index) const; - inline ::google::protobuf::MethodDescriptorProto* mutable_method(int index); - inline ::google::protobuf::MethodDescriptorProto* add_method(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >& - method() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >* - mutable_method(); - - // optional .google.protobuf.ServiceOptions options = 3; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 3; - inline const ::google::protobuf::ServiceOptions& options() const; - inline ::google::protobuf::ServiceOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.ServiceDescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto > method_; - ::google::protobuf::ServiceOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static ServiceDescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT MethodDescriptorProto : public ::google::protobuf::Message { - public: - MethodDescriptorProto(); - virtual ~MethodDescriptorProto(); - - MethodDescriptorProto(const MethodDescriptorProto& from); - - inline MethodDescriptorProto& operator=(const MethodDescriptorProto& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const MethodDescriptorProto& default_instance(); - - void Swap(MethodDescriptorProto* other); - - // implements Message ---------------------------------------------- - - MethodDescriptorProto* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const MethodDescriptorProto& from); - void MergeFrom(const MethodDescriptorProto& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional string name = 1; - inline bool has_name() const; - inline void clear_name(); - static const int kNameFieldNumber = 1; - inline const ::std::string& name() const; - inline void set_name(const ::std::string& value); - inline void set_name(const char* value); - inline void set_name(const char* value, size_t size); - inline ::std::string* mutable_name(); - - // optional string input_type = 2; - inline bool has_input_type() const; - inline void clear_input_type(); - static const int kInputTypeFieldNumber = 2; - inline const ::std::string& input_type() const; - inline void set_input_type(const ::std::string& value); - inline void set_input_type(const char* value); - inline void set_input_type(const char* value, size_t size); - inline ::std::string* mutable_input_type(); - - // optional string output_type = 3; - inline bool has_output_type() const; - inline void clear_output_type(); - static const int kOutputTypeFieldNumber = 3; - inline const ::std::string& output_type() const; - inline void set_output_type(const ::std::string& value); - inline void set_output_type(const char* value); - inline void set_output_type(const char* value, size_t size); - inline ::std::string* mutable_output_type(); - - // optional .google.protobuf.MethodOptions options = 4; - inline bool has_options() const; - inline void clear_options(); - static const int kOptionsFieldNumber = 4; - inline const ::google::protobuf::MethodOptions& options() const; - inline ::google::protobuf::MethodOptions* mutable_options(); - - // @@protoc_insertion_point(class_scope:google.protobuf.MethodDescriptorProto) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_; - static const ::std::string _default_name_; - ::std::string* input_type_; - static const ::std::string _default_input_type_; - ::std::string* output_type_; - static const ::std::string _default_output_type_; - ::google::protobuf::MethodOptions* options_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(4 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static MethodDescriptorProto* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT FileOptions : public ::google::protobuf::Message { - public: - FileOptions(); - virtual ~FileOptions(); - - FileOptions(const FileOptions& from); - - inline FileOptions& operator=(const FileOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const FileOptions& default_instance(); - - void Swap(FileOptions* other); - - // implements Message ---------------------------------------------- - - FileOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const FileOptions& from); - void MergeFrom(const FileOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - typedef FileOptions_OptimizeMode OptimizeMode; - static const OptimizeMode SPEED = FileOptions_OptimizeMode_SPEED; - static const OptimizeMode CODE_SIZE = FileOptions_OptimizeMode_CODE_SIZE; - static const OptimizeMode LITE_RUNTIME = FileOptions_OptimizeMode_LITE_RUNTIME; - static inline bool OptimizeMode_IsValid(int value) { - return FileOptions_OptimizeMode_IsValid(value); - } - static const OptimizeMode OptimizeMode_MIN = - FileOptions_OptimizeMode_OptimizeMode_MIN; - static const OptimizeMode OptimizeMode_MAX = - FileOptions_OptimizeMode_OptimizeMode_MAX; - static const int OptimizeMode_ARRAYSIZE = - FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* - OptimizeMode_descriptor() { - return FileOptions_OptimizeMode_descriptor(); - } - static inline const ::std::string& OptimizeMode_Name(OptimizeMode value) { - return FileOptions_OptimizeMode_Name(value); - } - static inline bool OptimizeMode_Parse(const ::std::string& name, - OptimizeMode* value) { - return FileOptions_OptimizeMode_Parse(name, value); - } - - // accessors ------------------------------------------------------- - - // optional string java_package = 1; - inline bool has_java_package() const; - inline void clear_java_package(); - static const int kJavaPackageFieldNumber = 1; - inline const ::std::string& java_package() const; - inline void set_java_package(const ::std::string& value); - inline void set_java_package(const char* value); - inline void set_java_package(const char* value, size_t size); - inline ::std::string* mutable_java_package(); - - // optional string java_outer_classname = 8; - inline bool has_java_outer_classname() const; - inline void clear_java_outer_classname(); - static const int kJavaOuterClassnameFieldNumber = 8; - inline const ::std::string& java_outer_classname() const; - inline void set_java_outer_classname(const ::std::string& value); - inline void set_java_outer_classname(const char* value); - inline void set_java_outer_classname(const char* value, size_t size); - inline ::std::string* mutable_java_outer_classname(); - - // optional bool java_multiple_files = 10 [default = false]; - inline bool has_java_multiple_files() const; - inline void clear_java_multiple_files(); - static const int kJavaMultipleFilesFieldNumber = 10; - inline bool java_multiple_files() const; - inline void set_java_multiple_files(bool value); - - // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; - inline bool has_optimize_for() const; - inline void clear_optimize_for(); - static const int kOptimizeForFieldNumber = 9; - inline ::google::protobuf::FileOptions_OptimizeMode optimize_for() const; - inline void set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value); - - // optional bool cc_generic_services = 16 [default = true]; - inline bool has_cc_generic_services() const; - inline void clear_cc_generic_services(); - static const int kCcGenericServicesFieldNumber = 16; - inline bool cc_generic_services() const; - inline void set_cc_generic_services(bool value); - - // optional bool java_generic_services = 17 [default = true]; - inline bool has_java_generic_services() const; - inline void clear_java_generic_services(); - static const int kJavaGenericServicesFieldNumber = 17; - inline bool java_generic_services() const; - inline void set_java_generic_services(bool value); - - // optional bool py_generic_services = 18 [default = true]; - inline bool has_py_generic_services() const; - inline void clear_py_generic_services(); - static const int kPyGenericServicesFieldNumber = 18; - inline bool py_generic_services() const; - inline void set_py_generic_services(bool value); - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FileOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.FileOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* java_package_; - static const ::std::string _default_java_package_; - ::std::string* java_outer_classname_; - static const ::std::string _default_java_outer_classname_; - bool java_multiple_files_; - int optimize_for_; - bool cc_generic_services_; - bool java_generic_services_; - bool py_generic_services_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(8 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static FileOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT MessageOptions : public ::google::protobuf::Message { - public: - MessageOptions(); - virtual ~MessageOptions(); - - MessageOptions(const MessageOptions& from); - - inline MessageOptions& operator=(const MessageOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const MessageOptions& default_instance(); - - void Swap(MessageOptions* other); - - // implements Message ---------------------------------------------- - - MessageOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const MessageOptions& from); - void MergeFrom(const MessageOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional bool message_set_wire_format = 1 [default = false]; - inline bool has_message_set_wire_format() const; - inline void clear_message_set_wire_format(); - static const int kMessageSetWireFormatFieldNumber = 1; - inline bool message_set_wire_format() const; - inline void set_message_set_wire_format(bool value); - - // optional bool no_standard_descriptor_accessor = 2 [default = false]; - inline bool has_no_standard_descriptor_accessor() const; - inline void clear_no_standard_descriptor_accessor(); - static const int kNoStandardDescriptorAccessorFieldNumber = 2; - inline bool no_standard_descriptor_accessor() const; - inline void set_no_standard_descriptor_accessor(bool value); - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MessageOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.MessageOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - bool message_set_wire_format_; - bool no_standard_descriptor_accessor_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(3 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static MessageOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT FieldOptions : public ::google::protobuf::Message { - public: - FieldOptions(); - virtual ~FieldOptions(); - - FieldOptions(const FieldOptions& from); - - inline FieldOptions& operator=(const FieldOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const FieldOptions& default_instance(); - - void Swap(FieldOptions* other); - - // implements Message ---------------------------------------------- - - FieldOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const FieldOptions& from); - void MergeFrom(const FieldOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - typedef FieldOptions_CType CType; - static const CType STRING = FieldOptions_CType_STRING; - static const CType CORD = FieldOptions_CType_CORD; - static const CType STRING_PIECE = FieldOptions_CType_STRING_PIECE; - static inline bool CType_IsValid(int value) { - return FieldOptions_CType_IsValid(value); - } - static const CType CType_MIN = - FieldOptions_CType_CType_MIN; - static const CType CType_MAX = - FieldOptions_CType_CType_MAX; - static const int CType_ARRAYSIZE = - FieldOptions_CType_CType_ARRAYSIZE; - static inline const ::google::protobuf::EnumDescriptor* - CType_descriptor() { - return FieldOptions_CType_descriptor(); - } - static inline const ::std::string& CType_Name(CType value) { - return FieldOptions_CType_Name(value); - } - static inline bool CType_Parse(const ::std::string& name, - CType* value) { - return FieldOptions_CType_Parse(name, value); - } - - // accessors ------------------------------------------------------- - - // optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; - inline bool has_ctype() const; - inline void clear_ctype(); - static const int kCtypeFieldNumber = 1; - inline ::google::protobuf::FieldOptions_CType ctype() const; - inline void set_ctype(::google::protobuf::FieldOptions_CType value); - - // optional bool packed = 2; - inline bool has_packed() const; - inline void clear_packed(); - static const int kPackedFieldNumber = 2; - inline bool packed() const; - inline void set_packed(bool value); - - // optional bool deprecated = 3 [default = false]; - inline bool has_deprecated() const; - inline void clear_deprecated(); - static const int kDeprecatedFieldNumber = 3; - inline bool deprecated() const; - inline void set_deprecated(bool value); - - // optional string experimental_map_key = 9; - inline bool has_experimental_map_key() const; - inline void clear_experimental_map_key(); - static const int kExperimentalMapKeyFieldNumber = 9; - inline const ::std::string& experimental_map_key() const; - inline void set_experimental_map_key(const ::std::string& value); - inline void set_experimental_map_key(const char* value); - inline void set_experimental_map_key(const char* value, size_t size); - inline ::std::string* mutable_experimental_map_key(); - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(FieldOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.FieldOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - int ctype_; - bool packed_; - bool deprecated_; - ::std::string* experimental_map_key_; - static const ::std::string _default_experimental_map_key_; - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(5 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static FieldOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT EnumOptions : public ::google::protobuf::Message { - public: - EnumOptions(); - virtual ~EnumOptions(); - - EnumOptions(const EnumOptions& from); - - inline EnumOptions& operator=(const EnumOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const EnumOptions& default_instance(); - - void Swap(EnumOptions* other); - - // implements Message ---------------------------------------------- - - EnumOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const EnumOptions& from); - void MergeFrom(const EnumOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.EnumOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static EnumOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT EnumValueOptions : public ::google::protobuf::Message { - public: - EnumValueOptions(); - virtual ~EnumValueOptions(); - - EnumValueOptions(const EnumValueOptions& from); - - inline EnumValueOptions& operator=(const EnumValueOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const EnumValueOptions& default_instance(); - - void Swap(EnumValueOptions* other); - - // implements Message ---------------------------------------------- - - EnumValueOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const EnumValueOptions& from); - void MergeFrom(const EnumValueOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(EnumValueOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.EnumValueOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static EnumValueOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT ServiceOptions : public ::google::protobuf::Message { - public: - ServiceOptions(); - virtual ~ServiceOptions(); - - ServiceOptions(const ServiceOptions& from); - - inline ServiceOptions& operator=(const ServiceOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const ServiceOptions& default_instance(); - - void Swap(ServiceOptions* other); - - // implements Message ---------------------------------------------- - - ServiceOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const ServiceOptions& from); - void MergeFrom(const ServiceOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(ServiceOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.ServiceOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static ServiceOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT MethodOptions : public ::google::protobuf::Message { - public: - MethodOptions(); - virtual ~MethodOptions(); - - MethodOptions(const MethodOptions& from); - - inline MethodOptions& operator=(const MethodOptions& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const MethodOptions& default_instance(); - - void Swap(MethodOptions* other); - - // implements Message ---------------------------------------------- - - MethodOptions* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const MethodOptions& from); - void MergeFrom(const MethodOptions& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - inline int uninterpreted_option_size() const; - inline void clear_uninterpreted_option(); - static const int kUninterpretedOptionFieldNumber = 999; - inline const ::google::protobuf::UninterpretedOption& uninterpreted_option(int index) const; - inline ::google::protobuf::UninterpretedOption* mutable_uninterpreted_option(int index); - inline ::google::protobuf::UninterpretedOption* add_uninterpreted_option(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& - uninterpreted_option() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* - mutable_uninterpreted_option(); - - GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(MethodOptions) - // @@protoc_insertion_point(class_scope:google.protobuf.MethodOptions) - private: - ::google::protobuf::internal::ExtensionSet _extensions_; - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption > uninterpreted_option_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static MethodOptions* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT UninterpretedOption_NamePart : public ::google::protobuf::Message { - public: - UninterpretedOption_NamePart(); - virtual ~UninterpretedOption_NamePart(); - - UninterpretedOption_NamePart(const UninterpretedOption_NamePart& from); - - inline UninterpretedOption_NamePart& operator=(const UninterpretedOption_NamePart& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const UninterpretedOption_NamePart& default_instance(); - - void Swap(UninterpretedOption_NamePart* other); - - // implements Message ---------------------------------------------- - - UninterpretedOption_NamePart* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const UninterpretedOption_NamePart& from); - void MergeFrom(const UninterpretedOption_NamePart& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // required string name_part = 1; - inline bool has_name_part() const; - inline void clear_name_part(); - static const int kNamePartFieldNumber = 1; - inline const ::std::string& name_part() const; - inline void set_name_part(const ::std::string& value); - inline void set_name_part(const char* value); - inline void set_name_part(const char* value, size_t size); - inline ::std::string* mutable_name_part(); - - // required bool is_extension = 2; - inline bool has_is_extension() const; - inline void clear_is_extension(); - static const int kIsExtensionFieldNumber = 2; - inline bool is_extension() const; - inline void set_is_extension(bool value); - - // @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption.NamePart) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::std::string* name_part_; - static const ::std::string _default_name_part_; - bool is_extension_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static UninterpretedOption_NamePart* default_instance_; -}; -// ------------------------------------------------------------------- - -class LIBPROTOBUF_EXPORT UninterpretedOption : public ::google::protobuf::Message { - public: - UninterpretedOption(); - virtual ~UninterpretedOption(); - - UninterpretedOption(const UninterpretedOption& from); - - inline UninterpretedOption& operator=(const UninterpretedOption& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const UninterpretedOption& default_instance(); - - void Swap(UninterpretedOption* other); - - // implements Message ---------------------------------------------- - - UninterpretedOption* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const UninterpretedOption& from); - void MergeFrom(const UninterpretedOption& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - typedef UninterpretedOption_NamePart NamePart; - - // accessors ------------------------------------------------------- - - // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; - inline int name_size() const; - inline void clear_name(); - static const int kNameFieldNumber = 2; - inline const ::google::protobuf::UninterpretedOption_NamePart& name(int index) const; - inline ::google::protobuf::UninterpretedOption_NamePart* mutable_name(int index); - inline ::google::protobuf::UninterpretedOption_NamePart* add_name(); - inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >& - name() const; - inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >* - mutable_name(); - - // optional string identifier_value = 3; - inline bool has_identifier_value() const; - inline void clear_identifier_value(); - static const int kIdentifierValueFieldNumber = 3; - inline const ::std::string& identifier_value() const; - inline void set_identifier_value(const ::std::string& value); - inline void set_identifier_value(const char* value); - inline void set_identifier_value(const char* value, size_t size); - inline ::std::string* mutable_identifier_value(); - - // optional uint64 positive_int_value = 4; - inline bool has_positive_int_value() const; - inline void clear_positive_int_value(); - static const int kPositiveIntValueFieldNumber = 4; - inline ::google::protobuf::uint64 positive_int_value() const; - inline void set_positive_int_value(::google::protobuf::uint64 value); - - // optional int64 negative_int_value = 5; - inline bool has_negative_int_value() const; - inline void clear_negative_int_value(); - static const int kNegativeIntValueFieldNumber = 5; - inline ::google::protobuf::int64 negative_int_value() const; - inline void set_negative_int_value(::google::protobuf::int64 value); - - // optional double double_value = 6; - inline bool has_double_value() const; - inline void clear_double_value(); - static const int kDoubleValueFieldNumber = 6; - inline double double_value() const; - inline void set_double_value(double value); - - // optional bytes string_value = 7; - inline bool has_string_value() const; - inline void clear_string_value(); - static const int kStringValueFieldNumber = 7; - inline const ::std::string& string_value() const; - inline void set_string_value(const ::std::string& value); - inline void set_string_value(const char* value); - inline void set_string_value(const void* value, size_t size); - inline ::std::string* mutable_string_value(); - - // @@protoc_insertion_point(class_scope:google.protobuf.UninterpretedOption) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart > name_; - ::std::string* identifier_value_; - static const ::std::string _default_identifier_value_; - ::google::protobuf::uint64 positive_int_value_; - ::google::protobuf::int64 negative_int_value_; - double double_value_; - ::std::string* string_value_; - static const ::std::string _default_string_value_; - friend void LIBPROTOBUF_EXPORT protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_AssignDesc_google_2fprotobuf_2fdescriptor_2eproto(); - friend void protobuf_ShutdownFile_google_2fprotobuf_2fdescriptor_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(6 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static UninterpretedOption* default_instance_; -}; -// =================================================================== - - -// =================================================================== - -// FileDescriptorSet - -// repeated .google.protobuf.FileDescriptorProto file = 1; -inline int FileDescriptorSet::file_size() const { - return file_.size(); -} -inline void FileDescriptorSet::clear_file() { - file_.Clear(); -} -inline const ::google::protobuf::FileDescriptorProto& FileDescriptorSet::file(int index) const { - return file_.Get(index); -} -inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::mutable_file(int index) { - return file_.Mutable(index); -} -inline ::google::protobuf::FileDescriptorProto* FileDescriptorSet::add_file() { - return file_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >& -FileDescriptorSet::file() const { - return file_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FileDescriptorProto >* -FileDescriptorSet::mutable_file() { - return &file_; -} - -// ------------------------------------------------------------------- - -// FileDescriptorProto - -// optional string name = 1; -inline bool FileDescriptorProto::has_name() const { - return _has_bit(0); -} -inline void FileDescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& FileDescriptorProto::name() const { - return *name_; -} -inline void FileDescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void FileDescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void FileDescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FileDescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// optional string package = 2; -inline bool FileDescriptorProto::has_package() const { - return _has_bit(1); -} -inline void FileDescriptorProto::clear_package() { - if (package_ != &_default_package_) { - package_->clear(); - } - _clear_bit(1); -} -inline const ::std::string& FileDescriptorProto::package() const { - return *package_; -} -inline void FileDescriptorProto::set_package(const ::std::string& value) { - _set_bit(1); - if (package_ == &_default_package_) { - package_ = new ::std::string; - } - package_->assign(value); -} -inline void FileDescriptorProto::set_package(const char* value) { - _set_bit(1); - if (package_ == &_default_package_) { - package_ = new ::std::string; - } - package_->assign(value); -} -inline void FileDescriptorProto::set_package(const char* value, size_t size) { - _set_bit(1); - if (package_ == &_default_package_) { - package_ = new ::std::string; - } - package_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FileDescriptorProto::mutable_package() { - _set_bit(1); - if (package_ == &_default_package_) { - package_ = new ::std::string; - } - return package_; -} - -// repeated string dependency = 3; -inline int FileDescriptorProto::dependency_size() const { - return dependency_.size(); -} -inline void FileDescriptorProto::clear_dependency() { - dependency_.Clear(); -} -inline const ::std::string& FileDescriptorProto::dependency(int index) const { - return dependency_.Get(index); -} -inline ::std::string* FileDescriptorProto::mutable_dependency(int index) { - return dependency_.Mutable(index); -} -inline void FileDescriptorProto::set_dependency(int index, const ::std::string& value) { - dependency_.Mutable(index)->assign(value); -} -inline void FileDescriptorProto::set_dependency(int index, const char* value) { - dependency_.Mutable(index)->assign(value); -} -inline void FileDescriptorProto::set_dependency(int index, const char* value, size_t size) { - dependency_.Mutable(index)->assign( - reinterpret_cast(value), size); -} -inline ::std::string* FileDescriptorProto::add_dependency() { - return dependency_.Add(); -} -inline void FileDescriptorProto::add_dependency(const ::std::string& value) { - dependency_.Add()->assign(value); -} -inline void FileDescriptorProto::add_dependency(const char* value) { - dependency_.Add()->assign(value); -} -inline void FileDescriptorProto::add_dependency(const char* value, size_t size) { - dependency_.Add()->assign(reinterpret_cast(value), size); -} -inline const ::google::protobuf::RepeatedPtrField< ::std::string>& -FileDescriptorProto::dependency() const { - return dependency_; -} -inline ::google::protobuf::RepeatedPtrField< ::std::string>* -FileDescriptorProto::mutable_dependency() { - return &dependency_; -} - -// repeated .google.protobuf.DescriptorProto message_type = 4; -inline int FileDescriptorProto::message_type_size() const { - return message_type_.size(); -} -inline void FileDescriptorProto::clear_message_type() { - message_type_.Clear(); -} -inline const ::google::protobuf::DescriptorProto& FileDescriptorProto::message_type(int index) const { - return message_type_.Get(index); -} -inline ::google::protobuf::DescriptorProto* FileDescriptorProto::mutable_message_type(int index) { - return message_type_.Mutable(index); -} -inline ::google::protobuf::DescriptorProto* FileDescriptorProto::add_message_type() { - return message_type_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& -FileDescriptorProto::message_type() const { - return message_type_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* -FileDescriptorProto::mutable_message_type() { - return &message_type_; -} - -// repeated .google.protobuf.EnumDescriptorProto enum_type = 5; -inline int FileDescriptorProto::enum_type_size() const { - return enum_type_.size(); -} -inline void FileDescriptorProto::clear_enum_type() { - enum_type_.Clear(); -} -inline const ::google::protobuf::EnumDescriptorProto& FileDescriptorProto::enum_type(int index) const { - return enum_type_.Get(index); -} -inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::mutable_enum_type(int index) { - return enum_type_.Mutable(index); -} -inline ::google::protobuf::EnumDescriptorProto* FileDescriptorProto::add_enum_type() { - return enum_type_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& -FileDescriptorProto::enum_type() const { - return enum_type_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* -FileDescriptorProto::mutable_enum_type() { - return &enum_type_; -} - -// repeated .google.protobuf.ServiceDescriptorProto service = 6; -inline int FileDescriptorProto::service_size() const { - return service_.size(); -} -inline void FileDescriptorProto::clear_service() { - service_.Clear(); -} -inline const ::google::protobuf::ServiceDescriptorProto& FileDescriptorProto::service(int index) const { - return service_.Get(index); -} -inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::mutable_service(int index) { - return service_.Mutable(index); -} -inline ::google::protobuf::ServiceDescriptorProto* FileDescriptorProto::add_service() { - return service_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >& -FileDescriptorProto::service() const { - return service_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::ServiceDescriptorProto >* -FileDescriptorProto::mutable_service() { - return &service_; -} - -// repeated .google.protobuf.FieldDescriptorProto extension = 7; -inline int FileDescriptorProto::extension_size() const { - return extension_.size(); -} -inline void FileDescriptorProto::clear_extension() { - extension_.Clear(); -} -inline const ::google::protobuf::FieldDescriptorProto& FileDescriptorProto::extension(int index) const { - return extension_.Get(index); -} -inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::mutable_extension(int index) { - return extension_.Mutable(index); -} -inline ::google::protobuf::FieldDescriptorProto* FileDescriptorProto::add_extension() { - return extension_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& -FileDescriptorProto::extension() const { - return extension_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* -FileDescriptorProto::mutable_extension() { - return &extension_; -} - -// optional .google.protobuf.FileOptions options = 8; -inline bool FileDescriptorProto::has_options() const { - return _has_bit(7); -} -inline void FileDescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::FileOptions::Clear(); - _clear_bit(7); -} -inline const ::google::protobuf::FileOptions& FileDescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::FileOptions* FileDescriptorProto::mutable_options() { - _set_bit(7); - if (options_ == NULL) options_ = new ::google::protobuf::FileOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// DescriptorProto_ExtensionRange - -// optional int32 start = 1; -inline bool DescriptorProto_ExtensionRange::has_start() const { - return _has_bit(0); -} -inline void DescriptorProto_ExtensionRange::clear_start() { - start_ = 0; - _clear_bit(0); -} -inline ::google::protobuf::int32 DescriptorProto_ExtensionRange::start() const { - return start_; -} -inline void DescriptorProto_ExtensionRange::set_start(::google::protobuf::int32 value) { - _set_bit(0); - start_ = value; -} - -// optional int32 end = 2; -inline bool DescriptorProto_ExtensionRange::has_end() const { - return _has_bit(1); -} -inline void DescriptorProto_ExtensionRange::clear_end() { - end_ = 0; - _clear_bit(1); -} -inline ::google::protobuf::int32 DescriptorProto_ExtensionRange::end() const { - return end_; -} -inline void DescriptorProto_ExtensionRange::set_end(::google::protobuf::int32 value) { - _set_bit(1); - end_ = value; -} - -// ------------------------------------------------------------------- - -// DescriptorProto - -// optional string name = 1; -inline bool DescriptorProto::has_name() const { - return _has_bit(0); -} -inline void DescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& DescriptorProto::name() const { - return *name_; -} -inline void DescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void DescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void DescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* DescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// repeated .google.protobuf.FieldDescriptorProto field = 2; -inline int DescriptorProto::field_size() const { - return field_.size(); -} -inline void DescriptorProto::clear_field() { - field_.Clear(); -} -inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::field(int index) const { - return field_.Get(index); -} -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_field(int index) { - return field_.Mutable(index); -} -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_field() { - return field_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& -DescriptorProto::field() const { - return field_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* -DescriptorProto::mutable_field() { - return &field_; -} - -// repeated .google.protobuf.FieldDescriptorProto extension = 6; -inline int DescriptorProto::extension_size() const { - return extension_.size(); -} -inline void DescriptorProto::clear_extension() { - extension_.Clear(); -} -inline const ::google::protobuf::FieldDescriptorProto& DescriptorProto::extension(int index) const { - return extension_.Get(index); -} -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::mutable_extension(int index) { - return extension_.Mutable(index); -} -inline ::google::protobuf::FieldDescriptorProto* DescriptorProto::add_extension() { - return extension_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >& -DescriptorProto::extension() const { - return extension_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::FieldDescriptorProto >* -DescriptorProto::mutable_extension() { - return &extension_; -} - -// repeated .google.protobuf.DescriptorProto nested_type = 3; -inline int DescriptorProto::nested_type_size() const { - return nested_type_.size(); -} -inline void DescriptorProto::clear_nested_type() { - nested_type_.Clear(); -} -inline const ::google::protobuf::DescriptorProto& DescriptorProto::nested_type(int index) const { - return nested_type_.Get(index); -} -inline ::google::protobuf::DescriptorProto* DescriptorProto::mutable_nested_type(int index) { - return nested_type_.Mutable(index); -} -inline ::google::protobuf::DescriptorProto* DescriptorProto::add_nested_type() { - return nested_type_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >& -DescriptorProto::nested_type() const { - return nested_type_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto >* -DescriptorProto::mutable_nested_type() { - return &nested_type_; -} - -// repeated .google.protobuf.EnumDescriptorProto enum_type = 4; -inline int DescriptorProto::enum_type_size() const { - return enum_type_.size(); -} -inline void DescriptorProto::clear_enum_type() { - enum_type_.Clear(); -} -inline const ::google::protobuf::EnumDescriptorProto& DescriptorProto::enum_type(int index) const { - return enum_type_.Get(index); -} -inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::mutable_enum_type(int index) { - return enum_type_.Mutable(index); -} -inline ::google::protobuf::EnumDescriptorProto* DescriptorProto::add_enum_type() { - return enum_type_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >& -DescriptorProto::enum_type() const { - return enum_type_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumDescriptorProto >* -DescriptorProto::mutable_enum_type() { - return &enum_type_; -} - -// repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; -inline int DescriptorProto::extension_range_size() const { - return extension_range_.size(); -} -inline void DescriptorProto::clear_extension_range() { - extension_range_.Clear(); -} -inline const ::google::protobuf::DescriptorProto_ExtensionRange& DescriptorProto::extension_range(int index) const { - return extension_range_.Get(index); -} -inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::mutable_extension_range(int index) { - return extension_range_.Mutable(index); -} -inline ::google::protobuf::DescriptorProto_ExtensionRange* DescriptorProto::add_extension_range() { - return extension_range_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >& -DescriptorProto::extension_range() const { - return extension_range_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::DescriptorProto_ExtensionRange >* -DescriptorProto::mutable_extension_range() { - return &extension_range_; -} - -// optional .google.protobuf.MessageOptions options = 7; -inline bool DescriptorProto::has_options() const { - return _has_bit(6); -} -inline void DescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::MessageOptions::Clear(); - _clear_bit(6); -} -inline const ::google::protobuf::MessageOptions& DescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::MessageOptions* DescriptorProto::mutable_options() { - _set_bit(6); - if (options_ == NULL) options_ = new ::google::protobuf::MessageOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// FieldDescriptorProto - -// optional string name = 1; -inline bool FieldDescriptorProto::has_name() const { - return _has_bit(0); -} -inline void FieldDescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& FieldDescriptorProto::name() const { - return *name_; -} -inline void FieldDescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void FieldDescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void FieldDescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FieldDescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// optional int32 number = 3; -inline bool FieldDescriptorProto::has_number() const { - return _has_bit(1); -} -inline void FieldDescriptorProto::clear_number() { - number_ = 0; - _clear_bit(1); -} -inline ::google::protobuf::int32 FieldDescriptorProto::number() const { - return number_; -} -inline void FieldDescriptorProto::set_number(::google::protobuf::int32 value) { - _set_bit(1); - number_ = value; -} - -// optional .google.protobuf.FieldDescriptorProto.Label label = 4; -inline bool FieldDescriptorProto::has_label() const { - return _has_bit(2); -} -inline void FieldDescriptorProto::clear_label() { - label_ = 1; - _clear_bit(2); -} -inline ::google::protobuf::FieldDescriptorProto_Label FieldDescriptorProto::label() const { - return static_cast< ::google::protobuf::FieldDescriptorProto_Label >(label_); -} -inline void FieldDescriptorProto::set_label(::google::protobuf::FieldDescriptorProto_Label value) { - GOOGLE_DCHECK(::google::protobuf::FieldDescriptorProto_Label_IsValid(value)); - _set_bit(2); - label_ = value; -} - -// optional .google.protobuf.FieldDescriptorProto.Type type = 5; -inline bool FieldDescriptorProto::has_type() const { - return _has_bit(3); -} -inline void FieldDescriptorProto::clear_type() { - type_ = 1; - _clear_bit(3); -} -inline ::google::protobuf::FieldDescriptorProto_Type FieldDescriptorProto::type() const { - return static_cast< ::google::protobuf::FieldDescriptorProto_Type >(type_); -} -inline void FieldDescriptorProto::set_type(::google::protobuf::FieldDescriptorProto_Type value) { - GOOGLE_DCHECK(::google::protobuf::FieldDescriptorProto_Type_IsValid(value)); - _set_bit(3); - type_ = value; -} - -// optional string type_name = 6; -inline bool FieldDescriptorProto::has_type_name() const { - return _has_bit(4); -} -inline void FieldDescriptorProto::clear_type_name() { - if (type_name_ != &_default_type_name_) { - type_name_->clear(); - } - _clear_bit(4); -} -inline const ::std::string& FieldDescriptorProto::type_name() const { - return *type_name_; -} -inline void FieldDescriptorProto::set_type_name(const ::std::string& value) { - _set_bit(4); - if (type_name_ == &_default_type_name_) { - type_name_ = new ::std::string; - } - type_name_->assign(value); -} -inline void FieldDescriptorProto::set_type_name(const char* value) { - _set_bit(4); - if (type_name_ == &_default_type_name_) { - type_name_ = new ::std::string; - } - type_name_->assign(value); -} -inline void FieldDescriptorProto::set_type_name(const char* value, size_t size) { - _set_bit(4); - if (type_name_ == &_default_type_name_) { - type_name_ = new ::std::string; - } - type_name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FieldDescriptorProto::mutable_type_name() { - _set_bit(4); - if (type_name_ == &_default_type_name_) { - type_name_ = new ::std::string; - } - return type_name_; -} - -// optional string extendee = 2; -inline bool FieldDescriptorProto::has_extendee() const { - return _has_bit(5); -} -inline void FieldDescriptorProto::clear_extendee() { - if (extendee_ != &_default_extendee_) { - extendee_->clear(); - } - _clear_bit(5); -} -inline const ::std::string& FieldDescriptorProto::extendee() const { - return *extendee_; -} -inline void FieldDescriptorProto::set_extendee(const ::std::string& value) { - _set_bit(5); - if (extendee_ == &_default_extendee_) { - extendee_ = new ::std::string; - } - extendee_->assign(value); -} -inline void FieldDescriptorProto::set_extendee(const char* value) { - _set_bit(5); - if (extendee_ == &_default_extendee_) { - extendee_ = new ::std::string; - } - extendee_->assign(value); -} -inline void FieldDescriptorProto::set_extendee(const char* value, size_t size) { - _set_bit(5); - if (extendee_ == &_default_extendee_) { - extendee_ = new ::std::string; - } - extendee_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FieldDescriptorProto::mutable_extendee() { - _set_bit(5); - if (extendee_ == &_default_extendee_) { - extendee_ = new ::std::string; - } - return extendee_; -} - -// optional string default_value = 7; -inline bool FieldDescriptorProto::has_default_value() const { - return _has_bit(6); -} -inline void FieldDescriptorProto::clear_default_value() { - if (default_value_ != &_default_default_value_) { - default_value_->clear(); - } - _clear_bit(6); -} -inline const ::std::string& FieldDescriptorProto::default_value() const { - return *default_value_; -} -inline void FieldDescriptorProto::set_default_value(const ::std::string& value) { - _set_bit(6); - if (default_value_ == &_default_default_value_) { - default_value_ = new ::std::string; - } - default_value_->assign(value); -} -inline void FieldDescriptorProto::set_default_value(const char* value) { - _set_bit(6); - if (default_value_ == &_default_default_value_) { - default_value_ = new ::std::string; - } - default_value_->assign(value); -} -inline void FieldDescriptorProto::set_default_value(const char* value, size_t size) { - _set_bit(6); - if (default_value_ == &_default_default_value_) { - default_value_ = new ::std::string; - } - default_value_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FieldDescriptorProto::mutable_default_value() { - _set_bit(6); - if (default_value_ == &_default_default_value_) { - default_value_ = new ::std::string; - } - return default_value_; -} - -// optional .google.protobuf.FieldOptions options = 8; -inline bool FieldDescriptorProto::has_options() const { - return _has_bit(7); -} -inline void FieldDescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::FieldOptions::Clear(); - _clear_bit(7); -} -inline const ::google::protobuf::FieldOptions& FieldDescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::FieldOptions* FieldDescriptorProto::mutable_options() { - _set_bit(7); - if (options_ == NULL) options_ = new ::google::protobuf::FieldOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// EnumDescriptorProto - -// optional string name = 1; -inline bool EnumDescriptorProto::has_name() const { - return _has_bit(0); -} -inline void EnumDescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& EnumDescriptorProto::name() const { - return *name_; -} -inline void EnumDescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void EnumDescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void EnumDescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* EnumDescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// repeated .google.protobuf.EnumValueDescriptorProto value = 2; -inline int EnumDescriptorProto::value_size() const { - return value_.size(); -} -inline void EnumDescriptorProto::clear_value() { - value_.Clear(); -} -inline const ::google::protobuf::EnumValueDescriptorProto& EnumDescriptorProto::value(int index) const { - return value_.Get(index); -} -inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::mutable_value(int index) { - return value_.Mutable(index); -} -inline ::google::protobuf::EnumValueDescriptorProto* EnumDescriptorProto::add_value() { - return value_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >& -EnumDescriptorProto::value() const { - return value_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::EnumValueDescriptorProto >* -EnumDescriptorProto::mutable_value() { - return &value_; -} - -// optional .google.protobuf.EnumOptions options = 3; -inline bool EnumDescriptorProto::has_options() const { - return _has_bit(2); -} -inline void EnumDescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::EnumOptions::Clear(); - _clear_bit(2); -} -inline const ::google::protobuf::EnumOptions& EnumDescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::EnumOptions* EnumDescriptorProto::mutable_options() { - _set_bit(2); - if (options_ == NULL) options_ = new ::google::protobuf::EnumOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// EnumValueDescriptorProto - -// optional string name = 1; -inline bool EnumValueDescriptorProto::has_name() const { - return _has_bit(0); -} -inline void EnumValueDescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& EnumValueDescriptorProto::name() const { - return *name_; -} -inline void EnumValueDescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void EnumValueDescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void EnumValueDescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* EnumValueDescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// optional int32 number = 2; -inline bool EnumValueDescriptorProto::has_number() const { - return _has_bit(1); -} -inline void EnumValueDescriptorProto::clear_number() { - number_ = 0; - _clear_bit(1); -} -inline ::google::protobuf::int32 EnumValueDescriptorProto::number() const { - return number_; -} -inline void EnumValueDescriptorProto::set_number(::google::protobuf::int32 value) { - _set_bit(1); - number_ = value; -} - -// optional .google.protobuf.EnumValueOptions options = 3; -inline bool EnumValueDescriptorProto::has_options() const { - return _has_bit(2); -} -inline void EnumValueDescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::EnumValueOptions::Clear(); - _clear_bit(2); -} -inline const ::google::protobuf::EnumValueOptions& EnumValueDescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::EnumValueOptions* EnumValueDescriptorProto::mutable_options() { - _set_bit(2); - if (options_ == NULL) options_ = new ::google::protobuf::EnumValueOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// ServiceDescriptorProto - -// optional string name = 1; -inline bool ServiceDescriptorProto::has_name() const { - return _has_bit(0); -} -inline void ServiceDescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& ServiceDescriptorProto::name() const { - return *name_; -} -inline void ServiceDescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void ServiceDescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void ServiceDescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* ServiceDescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// repeated .google.protobuf.MethodDescriptorProto method = 2; -inline int ServiceDescriptorProto::method_size() const { - return method_.size(); -} -inline void ServiceDescriptorProto::clear_method() { - method_.Clear(); -} -inline const ::google::protobuf::MethodDescriptorProto& ServiceDescriptorProto::method(int index) const { - return method_.Get(index); -} -inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::mutable_method(int index) { - return method_.Mutable(index); -} -inline ::google::protobuf::MethodDescriptorProto* ServiceDescriptorProto::add_method() { - return method_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >& -ServiceDescriptorProto::method() const { - return method_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::MethodDescriptorProto >* -ServiceDescriptorProto::mutable_method() { - return &method_; -} - -// optional .google.protobuf.ServiceOptions options = 3; -inline bool ServiceDescriptorProto::has_options() const { - return _has_bit(2); -} -inline void ServiceDescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::ServiceOptions::Clear(); - _clear_bit(2); -} -inline const ::google::protobuf::ServiceOptions& ServiceDescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::ServiceOptions* ServiceDescriptorProto::mutable_options() { - _set_bit(2); - if (options_ == NULL) options_ = new ::google::protobuf::ServiceOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// MethodDescriptorProto - -// optional string name = 1; -inline bool MethodDescriptorProto::has_name() const { - return _has_bit(0); -} -inline void MethodDescriptorProto::clear_name() { - if (name_ != &_default_name_) { - name_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& MethodDescriptorProto::name() const { - return *name_; -} -inline void MethodDescriptorProto::set_name(const ::std::string& value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void MethodDescriptorProto::set_name(const char* value) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(value); -} -inline void MethodDescriptorProto::set_name(const char* value, size_t size) { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* MethodDescriptorProto::mutable_name() { - _set_bit(0); - if (name_ == &_default_name_) { - name_ = new ::std::string; - } - return name_; -} - -// optional string input_type = 2; -inline bool MethodDescriptorProto::has_input_type() const { - return _has_bit(1); -} -inline void MethodDescriptorProto::clear_input_type() { - if (input_type_ != &_default_input_type_) { - input_type_->clear(); - } - _clear_bit(1); -} -inline const ::std::string& MethodDescriptorProto::input_type() const { - return *input_type_; -} -inline void MethodDescriptorProto::set_input_type(const ::std::string& value) { - _set_bit(1); - if (input_type_ == &_default_input_type_) { - input_type_ = new ::std::string; - } - input_type_->assign(value); -} -inline void MethodDescriptorProto::set_input_type(const char* value) { - _set_bit(1); - if (input_type_ == &_default_input_type_) { - input_type_ = new ::std::string; - } - input_type_->assign(value); -} -inline void MethodDescriptorProto::set_input_type(const char* value, size_t size) { - _set_bit(1); - if (input_type_ == &_default_input_type_) { - input_type_ = new ::std::string; - } - input_type_->assign(reinterpret_cast(value), size); -} -inline ::std::string* MethodDescriptorProto::mutable_input_type() { - _set_bit(1); - if (input_type_ == &_default_input_type_) { - input_type_ = new ::std::string; - } - return input_type_; -} - -// optional string output_type = 3; -inline bool MethodDescriptorProto::has_output_type() const { - return _has_bit(2); -} -inline void MethodDescriptorProto::clear_output_type() { - if (output_type_ != &_default_output_type_) { - output_type_->clear(); - } - _clear_bit(2); -} -inline const ::std::string& MethodDescriptorProto::output_type() const { - return *output_type_; -} -inline void MethodDescriptorProto::set_output_type(const ::std::string& value) { - _set_bit(2); - if (output_type_ == &_default_output_type_) { - output_type_ = new ::std::string; - } - output_type_->assign(value); -} -inline void MethodDescriptorProto::set_output_type(const char* value) { - _set_bit(2); - if (output_type_ == &_default_output_type_) { - output_type_ = new ::std::string; - } - output_type_->assign(value); -} -inline void MethodDescriptorProto::set_output_type(const char* value, size_t size) { - _set_bit(2); - if (output_type_ == &_default_output_type_) { - output_type_ = new ::std::string; - } - output_type_->assign(reinterpret_cast(value), size); -} -inline ::std::string* MethodDescriptorProto::mutable_output_type() { - _set_bit(2); - if (output_type_ == &_default_output_type_) { - output_type_ = new ::std::string; - } - return output_type_; -} - -// optional .google.protobuf.MethodOptions options = 4; -inline bool MethodDescriptorProto::has_options() const { - return _has_bit(3); -} -inline void MethodDescriptorProto::clear_options() { - if (options_ != NULL) options_->::google::protobuf::MethodOptions::Clear(); - _clear_bit(3); -} -inline const ::google::protobuf::MethodOptions& MethodDescriptorProto::options() const { - return options_ != NULL ? *options_ : *default_instance_->options_; -} -inline ::google::protobuf::MethodOptions* MethodDescriptorProto::mutable_options() { - _set_bit(3); - if (options_ == NULL) options_ = new ::google::protobuf::MethodOptions; - return options_; -} - -// ------------------------------------------------------------------- - -// FileOptions - -// optional string java_package = 1; -inline bool FileOptions::has_java_package() const { - return _has_bit(0); -} -inline void FileOptions::clear_java_package() { - if (java_package_ != &_default_java_package_) { - java_package_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& FileOptions::java_package() const { - return *java_package_; -} -inline void FileOptions::set_java_package(const ::std::string& value) { - _set_bit(0); - if (java_package_ == &_default_java_package_) { - java_package_ = new ::std::string; - } - java_package_->assign(value); -} -inline void FileOptions::set_java_package(const char* value) { - _set_bit(0); - if (java_package_ == &_default_java_package_) { - java_package_ = new ::std::string; - } - java_package_->assign(value); -} -inline void FileOptions::set_java_package(const char* value, size_t size) { - _set_bit(0); - if (java_package_ == &_default_java_package_) { - java_package_ = new ::std::string; - } - java_package_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FileOptions::mutable_java_package() { - _set_bit(0); - if (java_package_ == &_default_java_package_) { - java_package_ = new ::std::string; - } - return java_package_; -} - -// optional string java_outer_classname = 8; -inline bool FileOptions::has_java_outer_classname() const { - return _has_bit(1); -} -inline void FileOptions::clear_java_outer_classname() { - if (java_outer_classname_ != &_default_java_outer_classname_) { - java_outer_classname_->clear(); - } - _clear_bit(1); -} -inline const ::std::string& FileOptions::java_outer_classname() const { - return *java_outer_classname_; -} -inline void FileOptions::set_java_outer_classname(const ::std::string& value) { - _set_bit(1); - if (java_outer_classname_ == &_default_java_outer_classname_) { - java_outer_classname_ = new ::std::string; - } - java_outer_classname_->assign(value); -} -inline void FileOptions::set_java_outer_classname(const char* value) { - _set_bit(1); - if (java_outer_classname_ == &_default_java_outer_classname_) { - java_outer_classname_ = new ::std::string; - } - java_outer_classname_->assign(value); -} -inline void FileOptions::set_java_outer_classname(const char* value, size_t size) { - _set_bit(1); - if (java_outer_classname_ == &_default_java_outer_classname_) { - java_outer_classname_ = new ::std::string; - } - java_outer_classname_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FileOptions::mutable_java_outer_classname() { - _set_bit(1); - if (java_outer_classname_ == &_default_java_outer_classname_) { - java_outer_classname_ = new ::std::string; - } - return java_outer_classname_; -} - -// optional bool java_multiple_files = 10 [default = false]; -inline bool FileOptions::has_java_multiple_files() const { - return _has_bit(2); -} -inline void FileOptions::clear_java_multiple_files() { - java_multiple_files_ = false; - _clear_bit(2); -} -inline bool FileOptions::java_multiple_files() const { - return java_multiple_files_; -} -inline void FileOptions::set_java_multiple_files(bool value) { - _set_bit(2); - java_multiple_files_ = value; -} - -// optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9 [default = SPEED]; -inline bool FileOptions::has_optimize_for() const { - return _has_bit(3); -} -inline void FileOptions::clear_optimize_for() { - optimize_for_ = 1; - _clear_bit(3); -} -inline ::google::protobuf::FileOptions_OptimizeMode FileOptions::optimize_for() const { - return static_cast< ::google::protobuf::FileOptions_OptimizeMode >(optimize_for_); -} -inline void FileOptions::set_optimize_for(::google::protobuf::FileOptions_OptimizeMode value) { - GOOGLE_DCHECK(::google::protobuf::FileOptions_OptimizeMode_IsValid(value)); - _set_bit(3); - optimize_for_ = value; -} - -// optional bool cc_generic_services = 16 [default = true]; -inline bool FileOptions::has_cc_generic_services() const { - return _has_bit(4); -} -inline void FileOptions::clear_cc_generic_services() { - cc_generic_services_ = true; - _clear_bit(4); -} -inline bool FileOptions::cc_generic_services() const { - return cc_generic_services_; -} -inline void FileOptions::set_cc_generic_services(bool value) { - _set_bit(4); - cc_generic_services_ = value; -} - -// optional bool java_generic_services = 17 [default = true]; -inline bool FileOptions::has_java_generic_services() const { - return _has_bit(5); -} -inline void FileOptions::clear_java_generic_services() { - java_generic_services_ = true; - _clear_bit(5); -} -inline bool FileOptions::java_generic_services() const { - return java_generic_services_; -} -inline void FileOptions::set_java_generic_services(bool value) { - _set_bit(5); - java_generic_services_ = value; -} - -// optional bool py_generic_services = 18 [default = true]; -inline bool FileOptions::has_py_generic_services() const { - return _has_bit(6); -} -inline void FileOptions::clear_py_generic_services() { - py_generic_services_ = true; - _clear_bit(6); -} -inline bool FileOptions::py_generic_services() const { - return py_generic_services_; -} -inline void FileOptions::set_py_generic_services(bool value) { - _set_bit(6); - py_generic_services_ = value; -} - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int FileOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void FileOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& FileOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* FileOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* FileOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -FileOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -FileOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// MessageOptions - -// optional bool message_set_wire_format = 1 [default = false]; -inline bool MessageOptions::has_message_set_wire_format() const { - return _has_bit(0); -} -inline void MessageOptions::clear_message_set_wire_format() { - message_set_wire_format_ = false; - _clear_bit(0); -} -inline bool MessageOptions::message_set_wire_format() const { - return message_set_wire_format_; -} -inline void MessageOptions::set_message_set_wire_format(bool value) { - _set_bit(0); - message_set_wire_format_ = value; -} - -// optional bool no_standard_descriptor_accessor = 2 [default = false]; -inline bool MessageOptions::has_no_standard_descriptor_accessor() const { - return _has_bit(1); -} -inline void MessageOptions::clear_no_standard_descriptor_accessor() { - no_standard_descriptor_accessor_ = false; - _clear_bit(1); -} -inline bool MessageOptions::no_standard_descriptor_accessor() const { - return no_standard_descriptor_accessor_; -} -inline void MessageOptions::set_no_standard_descriptor_accessor(bool value) { - _set_bit(1); - no_standard_descriptor_accessor_ = value; -} - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int MessageOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void MessageOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& MessageOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* MessageOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* MessageOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -MessageOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -MessageOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// FieldOptions - -// optional .google.protobuf.FieldOptions.CType ctype = 1 [default = STRING]; -inline bool FieldOptions::has_ctype() const { - return _has_bit(0); -} -inline void FieldOptions::clear_ctype() { - ctype_ = 0; - _clear_bit(0); -} -inline ::google::protobuf::FieldOptions_CType FieldOptions::ctype() const { - return static_cast< ::google::protobuf::FieldOptions_CType >(ctype_); -} -inline void FieldOptions::set_ctype(::google::protobuf::FieldOptions_CType value) { - GOOGLE_DCHECK(::google::protobuf::FieldOptions_CType_IsValid(value)); - _set_bit(0); - ctype_ = value; -} - -// optional bool packed = 2; -inline bool FieldOptions::has_packed() const { - return _has_bit(1); -} -inline void FieldOptions::clear_packed() { - packed_ = false; - _clear_bit(1); -} -inline bool FieldOptions::packed() const { - return packed_; -} -inline void FieldOptions::set_packed(bool value) { - _set_bit(1); - packed_ = value; -} - -// optional bool deprecated = 3 [default = false]; -inline bool FieldOptions::has_deprecated() const { - return _has_bit(2); -} -inline void FieldOptions::clear_deprecated() { - deprecated_ = false; - _clear_bit(2); -} -inline bool FieldOptions::deprecated() const { - return deprecated_; -} -inline void FieldOptions::set_deprecated(bool value) { - _set_bit(2); - deprecated_ = value; -} - -// optional string experimental_map_key = 9; -inline bool FieldOptions::has_experimental_map_key() const { - return _has_bit(3); -} -inline void FieldOptions::clear_experimental_map_key() { - if (experimental_map_key_ != &_default_experimental_map_key_) { - experimental_map_key_->clear(); - } - _clear_bit(3); -} -inline const ::std::string& FieldOptions::experimental_map_key() const { - return *experimental_map_key_; -} -inline void FieldOptions::set_experimental_map_key(const ::std::string& value) { - _set_bit(3); - if (experimental_map_key_ == &_default_experimental_map_key_) { - experimental_map_key_ = new ::std::string; - } - experimental_map_key_->assign(value); -} -inline void FieldOptions::set_experimental_map_key(const char* value) { - _set_bit(3); - if (experimental_map_key_ == &_default_experimental_map_key_) { - experimental_map_key_ = new ::std::string; - } - experimental_map_key_->assign(value); -} -inline void FieldOptions::set_experimental_map_key(const char* value, size_t size) { - _set_bit(3); - if (experimental_map_key_ == &_default_experimental_map_key_) { - experimental_map_key_ = new ::std::string; - } - experimental_map_key_->assign(reinterpret_cast(value), size); -} -inline ::std::string* FieldOptions::mutable_experimental_map_key() { - _set_bit(3); - if (experimental_map_key_ == &_default_experimental_map_key_) { - experimental_map_key_ = new ::std::string; - } - return experimental_map_key_; -} - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int FieldOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void FieldOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& FieldOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* FieldOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* FieldOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -FieldOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -FieldOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// EnumOptions - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int EnumOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void EnumOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& EnumOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* EnumOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* EnumOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -EnumOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -EnumOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// EnumValueOptions - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int EnumValueOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void EnumValueOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& EnumValueOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* EnumValueOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* EnumValueOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -EnumValueOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -EnumValueOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// ServiceOptions - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int ServiceOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void ServiceOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& ServiceOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* ServiceOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* ServiceOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -ServiceOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -ServiceOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// MethodOptions - -// repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; -inline int MethodOptions::uninterpreted_option_size() const { - return uninterpreted_option_.size(); -} -inline void MethodOptions::clear_uninterpreted_option() { - uninterpreted_option_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption& MethodOptions::uninterpreted_option(int index) const { - return uninterpreted_option_.Get(index); -} -inline ::google::protobuf::UninterpretedOption* MethodOptions::mutable_uninterpreted_option(int index) { - return uninterpreted_option_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption* MethodOptions::add_uninterpreted_option() { - return uninterpreted_option_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >& -MethodOptions::uninterpreted_option() const { - return uninterpreted_option_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption >* -MethodOptions::mutable_uninterpreted_option() { - return &uninterpreted_option_; -} - -// ------------------------------------------------------------------- - -// UninterpretedOption_NamePart - -// required string name_part = 1; -inline bool UninterpretedOption_NamePart::has_name_part() const { - return _has_bit(0); -} -inline void UninterpretedOption_NamePart::clear_name_part() { - if (name_part_ != &_default_name_part_) { - name_part_->clear(); - } - _clear_bit(0); -} -inline const ::std::string& UninterpretedOption_NamePart::name_part() const { - return *name_part_; -} -inline void UninterpretedOption_NamePart::set_name_part(const ::std::string& value) { - _set_bit(0); - if (name_part_ == &_default_name_part_) { - name_part_ = new ::std::string; - } - name_part_->assign(value); -} -inline void UninterpretedOption_NamePart::set_name_part(const char* value) { - _set_bit(0); - if (name_part_ == &_default_name_part_) { - name_part_ = new ::std::string; - } - name_part_->assign(value); -} -inline void UninterpretedOption_NamePart::set_name_part(const char* value, size_t size) { - _set_bit(0); - if (name_part_ == &_default_name_part_) { - name_part_ = new ::std::string; - } - name_part_->assign(reinterpret_cast(value), size); -} -inline ::std::string* UninterpretedOption_NamePart::mutable_name_part() { - _set_bit(0); - if (name_part_ == &_default_name_part_) { - name_part_ = new ::std::string; - } - return name_part_; -} - -// required bool is_extension = 2; -inline bool UninterpretedOption_NamePart::has_is_extension() const { - return _has_bit(1); -} -inline void UninterpretedOption_NamePart::clear_is_extension() { - is_extension_ = false; - _clear_bit(1); -} -inline bool UninterpretedOption_NamePart::is_extension() const { - return is_extension_; -} -inline void UninterpretedOption_NamePart::set_is_extension(bool value) { - _set_bit(1); - is_extension_ = value; -} - -// ------------------------------------------------------------------- - -// UninterpretedOption - -// repeated .google.protobuf.UninterpretedOption.NamePart name = 2; -inline int UninterpretedOption::name_size() const { - return name_.size(); -} -inline void UninterpretedOption::clear_name() { - name_.Clear(); -} -inline const ::google::protobuf::UninterpretedOption_NamePart& UninterpretedOption::name(int index) const { - return name_.Get(index); -} -inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::mutable_name(int index) { - return name_.Mutable(index); -} -inline ::google::protobuf::UninterpretedOption_NamePart* UninterpretedOption::add_name() { - return name_.Add(); -} -inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >& -UninterpretedOption::name() const { - return name_; -} -inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::UninterpretedOption_NamePart >* -UninterpretedOption::mutable_name() { - return &name_; -} - -// optional string identifier_value = 3; -inline bool UninterpretedOption::has_identifier_value() const { - return _has_bit(1); -} -inline void UninterpretedOption::clear_identifier_value() { - if (identifier_value_ != &_default_identifier_value_) { - identifier_value_->clear(); - } - _clear_bit(1); -} -inline const ::std::string& UninterpretedOption::identifier_value() const { - return *identifier_value_; -} -inline void UninterpretedOption::set_identifier_value(const ::std::string& value) { - _set_bit(1); - if (identifier_value_ == &_default_identifier_value_) { - identifier_value_ = new ::std::string; - } - identifier_value_->assign(value); -} -inline void UninterpretedOption::set_identifier_value(const char* value) { - _set_bit(1); - if (identifier_value_ == &_default_identifier_value_) { - identifier_value_ = new ::std::string; - } - identifier_value_->assign(value); -} -inline void UninterpretedOption::set_identifier_value(const char* value, size_t size) { - _set_bit(1); - if (identifier_value_ == &_default_identifier_value_) { - identifier_value_ = new ::std::string; - } - identifier_value_->assign(reinterpret_cast(value), size); -} -inline ::std::string* UninterpretedOption::mutable_identifier_value() { - _set_bit(1); - if (identifier_value_ == &_default_identifier_value_) { - identifier_value_ = new ::std::string; - } - return identifier_value_; -} - -// optional uint64 positive_int_value = 4; -inline bool UninterpretedOption::has_positive_int_value() const { - return _has_bit(2); -} -inline void UninterpretedOption::clear_positive_int_value() { - positive_int_value_ = GOOGLE_ULONGLONG(0); - _clear_bit(2); -} -inline ::google::protobuf::uint64 UninterpretedOption::positive_int_value() const { - return positive_int_value_; -} -inline void UninterpretedOption::set_positive_int_value(::google::protobuf::uint64 value) { - _set_bit(2); - positive_int_value_ = value; -} - -// optional int64 negative_int_value = 5; -inline bool UninterpretedOption::has_negative_int_value() const { - return _has_bit(3); -} -inline void UninterpretedOption::clear_negative_int_value() { - negative_int_value_ = GOOGLE_LONGLONG(0); - _clear_bit(3); -} -inline ::google::protobuf::int64 UninterpretedOption::negative_int_value() const { - return negative_int_value_; -} -inline void UninterpretedOption::set_negative_int_value(::google::protobuf::int64 value) { - _set_bit(3); - negative_int_value_ = value; -} - -// optional double double_value = 6; -inline bool UninterpretedOption::has_double_value() const { - return _has_bit(4); -} -inline void UninterpretedOption::clear_double_value() { - double_value_ = 0; - _clear_bit(4); -} -inline double UninterpretedOption::double_value() const { - return double_value_; -} -inline void UninterpretedOption::set_double_value(double value) { - _set_bit(4); - double_value_ = value; -} - -// optional bytes string_value = 7; -inline bool UninterpretedOption::has_string_value() const { - return _has_bit(5); -} -inline void UninterpretedOption::clear_string_value() { - if (string_value_ != &_default_string_value_) { - string_value_->clear(); - } - _clear_bit(5); -} -inline const ::std::string& UninterpretedOption::string_value() const { - return *string_value_; -} -inline void UninterpretedOption::set_string_value(const ::std::string& value) { - _set_bit(5); - if (string_value_ == &_default_string_value_) { - string_value_ = new ::std::string; - } - string_value_->assign(value); -} -inline void UninterpretedOption::set_string_value(const char* value) { - _set_bit(5); - if (string_value_ == &_default_string_value_) { - string_value_ = new ::std::string; - } - string_value_->assign(value); -} -inline void UninterpretedOption::set_string_value(const void* value, size_t size) { - _set_bit(5); - if (string_value_ == &_default_string_value_) { - string_value_ = new ::std::string; - } - string_value_->assign(reinterpret_cast(value), size); -} -inline ::std::string* UninterpretedOption::mutable_string_value() { - _set_bit(5); - if (string_value_ == &_default_string_value_) { - string_value_ = new ::std::string; - } - return string_value_; -} - - -// @@protoc_insertion_point(namespace_scope) - -} // namespace protobuf -} // namespace google - -#ifndef SWIG -namespace google { -namespace protobuf { - -template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Type>() { - return ::google::protobuf::FieldDescriptorProto_Type_descriptor(); -} -template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldDescriptorProto_Label>() { - return ::google::protobuf::FieldDescriptorProto_Label_descriptor(); -} -template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FileOptions_OptimizeMode>() { - return ::google::protobuf::FileOptions_OptimizeMode_descriptor(); -} -template <> -inline const EnumDescriptor* GetEnumDescriptor< ::google::protobuf::FieldOptions_CType>() { - return ::google::protobuf::FieldOptions_CType_descriptor(); -} - -} // namespace google -} // namespace protobuf -#endif // SWIG - -// @@protoc_insertion_point(global_scope) - -#endif // PROTOBUF_google_2fprotobuf_2fdescriptor_2eproto__INCLUDED diff --git a/Resources/NetHook/google/protobuf/descriptor.proto b/Resources/NetHook/google/protobuf/descriptor.proto deleted file mode 100644 index cc04aa8e..00000000 --- a/Resources/NetHook/google/protobuf/descriptor.proto +++ /dev/null @@ -1,433 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// The messages in this file describe the definitions found in .proto files. -// A valid .proto file can be translated directly to a FileDescriptorProto -// without any other information (e.g. without reading its imports). - - - -package google.protobuf; -option java_package = "com.google.protobuf"; -option java_outer_classname = "DescriptorProtos"; - -// descriptor.proto must be optimized for speed because reflection-based -// algorithms don't work during bootstrapping. -option optimize_for = SPEED; - -// The protocol compiler can output a FileDescriptorSet containing the .proto -// files it parses. -message FileDescriptorSet { - repeated FileDescriptorProto file = 1; -} - -// Describes a complete .proto file. -message FileDescriptorProto { - optional string name = 1; // file name, relative to root of source tree - optional string package = 2; // e.g. "foo", "foo.bar", etc. - - // Names of files imported by this file. - repeated string dependency = 3; - - // All top-level definitions in this file. - repeated DescriptorProto message_type = 4; - repeated EnumDescriptorProto enum_type = 5; - repeated ServiceDescriptorProto service = 6; - repeated FieldDescriptorProto extension = 7; - - optional FileOptions options = 8; -} - -// Describes a message type. -message DescriptorProto { - optional string name = 1; - - repeated FieldDescriptorProto field = 2; - repeated FieldDescriptorProto extension = 6; - - repeated DescriptorProto nested_type = 3; - repeated EnumDescriptorProto enum_type = 4; - - message ExtensionRange { - optional int32 start = 1; - optional int32 end = 2; - } - repeated ExtensionRange extension_range = 5; - - optional MessageOptions options = 7; -} - -// Describes a field within a message. -message FieldDescriptorProto { - enum Type { - // 0 is reserved for errors. - // Order is weird for historical reasons. - TYPE_DOUBLE = 1; - TYPE_FLOAT = 2; - TYPE_INT64 = 3; // Not ZigZag encoded. Negative numbers - // take 10 bytes. Use TYPE_SINT64 if negative - // values are likely. - TYPE_UINT64 = 4; - TYPE_INT32 = 5; // Not ZigZag encoded. Negative numbers - // take 10 bytes. Use TYPE_SINT32 if negative - // values are likely. - TYPE_FIXED64 = 6; - TYPE_FIXED32 = 7; - TYPE_BOOL = 8; - TYPE_STRING = 9; - TYPE_GROUP = 10; // Tag-delimited aggregate. - TYPE_MESSAGE = 11; // Length-delimited aggregate. - - // New in version 2. - TYPE_BYTES = 12; - TYPE_UINT32 = 13; - TYPE_ENUM = 14; - TYPE_SFIXED32 = 15; - TYPE_SFIXED64 = 16; - TYPE_SINT32 = 17; // Uses ZigZag encoding. - TYPE_SINT64 = 18; // Uses ZigZag encoding. - }; - - enum Label { - // 0 is reserved for errors - LABEL_OPTIONAL = 1; - LABEL_REQUIRED = 2; - LABEL_REPEATED = 3; - // TODO(sanjay): Should we add LABEL_MAP? - }; - - optional string name = 1; - optional int32 number = 3; - optional Label label = 4; - - // If type_name is set, this need not be set. If both this and type_name - // are set, this must be either TYPE_ENUM or TYPE_MESSAGE. - optional Type type = 5; - - // For message and enum types, this is the name of the type. If the name - // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping - // rules are used to find the type (i.e. first the nested types within this - // message are searched, then within the parent, on up to the root - // namespace). - optional string type_name = 6; - - // For extensions, this is the name of the type being extended. It is - // resolved in the same manner as type_name. - optional string extendee = 2; - - // For numeric types, contains the original text representation of the value. - // For booleans, "true" or "false". - // For strings, contains the default text contents (not escaped in any way). - // For bytes, contains the C escaped value. All bytes >= 128 are escaped. - // TODO(kenton): Base-64 encode? - optional string default_value = 7; - - optional FieldOptions options = 8; -} - -// Describes an enum type. -message EnumDescriptorProto { - optional string name = 1; - - repeated EnumValueDescriptorProto value = 2; - - optional EnumOptions options = 3; -} - -// Describes a value within an enum. -message EnumValueDescriptorProto { - optional string name = 1; - optional int32 number = 2; - - optional EnumValueOptions options = 3; -} - -// Describes a service. -message ServiceDescriptorProto { - optional string name = 1; - repeated MethodDescriptorProto method = 2; - - optional ServiceOptions options = 3; -} - -// Describes a method of a service. -message MethodDescriptorProto { - optional string name = 1; - - // Input and output type names. These are resolved in the same way as - // FieldDescriptorProto.type_name, but must refer to a message type. - optional string input_type = 2; - optional string output_type = 3; - - optional MethodOptions options = 4; -} - -// =================================================================== -// Options - -// Each of the definitions above may have "options" attached. These are -// just annotations which may cause code to be generated slightly differently -// or may contain hints for code that manipulates protocol messages. -// -// Clients may define custom options as extensions of the *Options messages. -// These extensions may not yet be known at parsing time, so the parser cannot -// store the values in them. Instead it stores them in a field in the *Options -// message called uninterpreted_option. This field must have the same name -// across all *Options messages. We then use this field to populate the -// extensions when we build a descriptor, at which point all protos have been -// parsed and so all extensions are known. -// -// Extension numbers for custom options may be chosen as follows: -// * For options which will only be used within a single application or -// organization, or for experimental options, use field numbers 50000 -// through 99999. It is up to you to ensure that you do not use the -// same number for multiple options. -// * For options which will be published and used publicly by multiple -// independent entities, e-mail kenton@google.com to reserve extension -// numbers. Simply tell me how many you need and I'll send you back a -// set of numbers to use -- there's no need to explain how you intend to -// use them. If this turns out to be popular, a web service will be set up -// to automatically assign option numbers. - - -message FileOptions { - - // Sets the Java package where classes generated from this .proto will be - // placed. By default, the proto package is used, but this is often - // inappropriate because proto packages do not normally start with backwards - // domain names. - optional string java_package = 1; - - - // If set, all the classes from the .proto file are wrapped in a single - // outer class with the given name. This applies to both Proto1 - // (equivalent to the old "--one_java_file" option) and Proto2 (where - // a .proto always translates to a single class, but you may want to - // explicitly choose the class name). - optional string java_outer_classname = 8; - - // If set true, then the Java code generator will generate a separate .java - // file for each top-level message, enum, and service defined in the .proto - // file. Thus, these types will *not* be nested inside the outer class - // named by java_outer_classname. However, the outer class will still be - // generated to contain the file's getDescriptor() method as well as any - // top-level extensions defined in the file. - optional bool java_multiple_files = 10 [default=false]; - - // Generated classes can be optimized for speed or code size. - enum OptimizeMode { - SPEED = 1; // Generate complete code for parsing, serialization, - // etc. - CODE_SIZE = 2; // Use ReflectionOps to implement these methods. - LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. - } - optional OptimizeMode optimize_for = 9 [default=SPEED]; - - - - - // Should generic services be generated in each language? "Generic" services - // are not specific to any particular RPC system. They are generated by the - // main code generators in each language (without additional plugins). - // Generic services were the only kind of service generation supported by - // early versions of proto2. - // - // Generic services are now considered deprecated in favor of using plugins - // that generate code specific to your particular RPC system. If you are - // using such a plugin, set these to false. In the future, we may change - // the default to false, so if you explicitly want generic services, you - // should explicitly set these to true. - optional bool cc_generic_services = 16 [default=true]; - optional bool java_generic_services = 17 [default=true]; - optional bool py_generic_services = 18 [default=true]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message MessageOptions { - // Set true to use the old proto1 MessageSet wire format for extensions. - // This is provided for backwards-compatibility with the MessageSet wire - // format. You should not use this for any other reason: It's less - // efficient, has fewer features, and is more complicated. - // - // The message must be defined exactly as follows: - // message Foo { - // option message_set_wire_format = true; - // extensions 4 to max; - // } - // Note that the message cannot have any defined fields; MessageSets only - // have extensions. - // - // All extensions of your type must be singular messages; e.g. they cannot - // be int32s, enums, or repeated messages. - // - // Because this is an option, the above two restrictions are not enforced by - // the protocol compiler. - optional bool message_set_wire_format = 1 [default=false]; - - // Disables the generation of the standard "descriptor()" accessor, which can - // conflict with a field of the same name. This is meant to make migration - // from proto1 easier; new code should avoid fields named "descriptor". - optional bool no_standard_descriptor_accessor = 2 [default=false]; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message FieldOptions { - // The ctype option instructs the C++ code generator to use a different - // representation of the field than it normally would. See the specific - // options below. This option is not yet implemented in the open source - // release -- sorry, we'll try to include it in a future version! - optional CType ctype = 1 [default = STRING]; - enum CType { - // Default mode. - STRING = 0; - - CORD = 1; - - STRING_PIECE = 2; - } - // The packed option can be enabled for repeated primitive fields to enable - // a more efficient representation on the wire. Rather than repeatedly - // writing the tag and type for each element, the entire array is encoded as - // a single length-delimited blob. - optional bool packed = 2; - - - // Is this field deprecated? - // Depending on the target platform, this can emit Deprecated annotations - // for accessors, or it will be completely ignored; in the very least, this - // is a formalization for deprecating fields. - optional bool deprecated = 3 [default=false]; - - // EXPERIMENTAL. DO NOT USE. - // For "map" fields, the name of the field in the enclosed type that - // is the key for this map. For example, suppose we have: - // message Item { - // required string name = 1; - // required string value = 2; - // } - // message Config { - // repeated Item items = 1 [experimental_map_key="name"]; - // } - // In this situation, the map key for Item will be set to "name". - // TODO: Fully-implement this, then remove the "experimental_" prefix. - optional string experimental_map_key = 9; - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumOptions { - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message EnumValueOptions { - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message ServiceOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -message MethodOptions { - - // Note: Field numbers 1 through 32 are reserved for Google's internal RPC - // framework. We apologize for hoarding these numbers to ourselves, but - // we were already using them long before we decided to release Protocol - // Buffers. - - // The parser stores options it doesn't recognize here. See above. - repeated UninterpretedOption uninterpreted_option = 999; - - // Clients can define custom options in extensions of this message. See above. - extensions 1000 to max; -} - -// A message representing a option the parser does not recognize. This only -// appears in options protos created by the compiler::Parser class. -// DescriptorPool resolves these when building Descriptor objects. Therefore, -// options protos in descriptor objects (e.g. returned by Descriptor::options(), -// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions -// in them. -message UninterpretedOption { - // The name of the uninterpreted option. Each string represents a segment in - // a dot-separated name. is_extension is true iff a segment represents an - // extension (denoted with parentheses in options specs in .proto files). - // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents - // "foo.(bar.baz).qux". - message NamePart { - required string name_part = 1; - required bool is_extension = 2; - } - repeated NamePart name = 2; - - // The value of the uninterpreted option, in whatever type the tokenizer - // identified it as during parsing. Exactly one of these should be set. - optional string identifier_value = 3; - optional uint64 positive_int_value = 4; - optional int64 negative_int_value = 5; - optional double double_value = 6; - optional bytes string_value = 7; -} diff --git a/Resources/NetHook/google/protobuf/descriptor_database.cc b/Resources/NetHook/google/protobuf/descriptor_database.cc deleted file mode 100644 index 95708d94..00000000 --- a/Resources/NetHook/google/protobuf/descriptor_database.cc +++ /dev/null @@ -1,541 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -DescriptorDatabase::~DescriptorDatabase() {} - -// =================================================================== - -template -bool SimpleDescriptorDatabase::DescriptorIndex::AddFile( - const FileDescriptorProto& file, - Value value) { - if (!InsertIfNotPresent(&by_name_, file.name(), value)) { - GOOGLE_LOG(ERROR) << "File already exists in database: " << file.name(); - return false; - } - - // We must be careful here -- calling file.package() if file.has_package() is - // false could access an uninitialized static-storage variable if we are being - // run at startup time. - string path = file.has_package() ? file.package() : string(); - if (!path.empty()) path += '.'; - - for (int i = 0; i < file.message_type_size(); i++) { - if (!AddSymbol(path + file.message_type(i).name(), value)) return false; - if (!AddNestedExtensions(file.message_type(i), value)) return false; - } - for (int i = 0; i < file.enum_type_size(); i++) { - if (!AddSymbol(path + file.enum_type(i).name(), value)) return false; - } - for (int i = 0; i < file.extension_size(); i++) { - if (!AddSymbol(path + file.extension(i).name(), value)) return false; - if (!AddExtension(file.extension(i), value)) return false; - } - for (int i = 0; i < file.service_size(); i++) { - if (!AddSymbol(path + file.service(i).name(), value)) return false; - } - - return true; -} - -template -bool SimpleDescriptorDatabase::DescriptorIndex::AddSymbol( - const string& name, Value value) { - // We need to make sure not to violate our map invariant. - - // If the symbol name is invalid it could break our lookup algorithm (which - // relies on the fact that '.' sorts before all other characters that are - // valid in symbol names). - if (!ValidateSymbolName(name)) { - GOOGLE_LOG(ERROR) << "Invalid symbol name: " << name; - return false; - } - - // Try to look up the symbol to make sure a super-symbol doesn't already - // exist. - typename map::iterator iter = FindLastLessOrEqual(name); - - if (iter == by_symbol_.end()) { - // Apparently the map is currently empty. Just insert and be done with it. - by_symbol_.insert(make_pair(name, value)); - return true; - } - - if (IsSubSymbol(iter->first, name)) { - GOOGLE_LOG(ERROR) << "Symbol name \"" << name << "\" conflicts with the existing " - "symbol \"" << iter->first << "\"."; - return false; - } - - // OK, that worked. Now we have to make sure that no symbol in the map is - // a sub-symbol of the one we are inserting. The only symbol which could - // be so is the first symbol that is greater than the new symbol. Since - // |iter| points at the last symbol that is less than or equal, we just have - // to increment it. - ++iter; - - if (iter != by_symbol_.end() && IsSubSymbol(name, iter->first)) { - GOOGLE_LOG(ERROR) << "Symbol name \"" << name << "\" conflicts with the existing " - "symbol \"" << iter->first << "\"."; - return false; - } - - // OK, no conflicts. - - // Insert the new symbol using the iterator as a hint, the new entry will - // appear immediately before the one the iterator is pointing at. - by_symbol_.insert(iter, make_pair(name, value)); - - return true; -} - -template -bool SimpleDescriptorDatabase::DescriptorIndex::AddNestedExtensions( - const DescriptorProto& message_type, - Value value) { - for (int i = 0; i < message_type.nested_type_size(); i++) { - if (!AddNestedExtensions(message_type.nested_type(i), value)) return false; - } - for (int i = 0; i < message_type.extension_size(); i++) { - if (!AddExtension(message_type.extension(i), value)) return false; - } - return true; -} - -template -bool SimpleDescriptorDatabase::DescriptorIndex::AddExtension( - const FieldDescriptorProto& field, - Value value) { - if (!field.extendee().empty() && field.extendee()[0] == '.') { - // The extension is fully-qualified. We can use it as a lookup key in - // the by_symbol_ table. - if (!InsertIfNotPresent(&by_extension_, - make_pair(field.extendee().substr(1), - field.number()), - value)) { - GOOGLE_LOG(ERROR) << "Extension conflicts with extension already in database: " - "extend " << field.extendee() << " { " - << field.name() << " = " << field.number() << " }"; - return false; - } - } else { - // Not fully-qualified. We can't really do anything here, unfortunately. - // We don't consider this an error, though, because the descriptor is - // valid. - } - return true; -} - -template -Value SimpleDescriptorDatabase::DescriptorIndex::FindFile( - const string& filename) { - return FindWithDefault(by_name_, filename, Value()); -} - -template -Value SimpleDescriptorDatabase::DescriptorIndex::FindSymbol( - const string& name) { - typename map::iterator iter = FindLastLessOrEqual(name); - - return (iter != by_symbol_.end() && IsSubSymbol(iter->first, name)) ? - iter->second : Value(); -} - -template -Value SimpleDescriptorDatabase::DescriptorIndex::FindExtension( - const string& containing_type, - int field_number) { - return FindWithDefault(by_extension_, - make_pair(containing_type, field_number), - Value()); -} - -template -bool SimpleDescriptorDatabase::DescriptorIndex::FindAllExtensionNumbers( - const string& containing_type, - vector* output) { - typename map, Value >::const_iterator it = - by_extension_.lower_bound(make_pair(containing_type, 0)); - bool success = false; - - for (; it != by_extension_.end() && it->first.first == containing_type; - ++it) { - output->push_back(it->first.second); - success = true; - } - - return success; -} - -template -typename map::iterator -SimpleDescriptorDatabase::DescriptorIndex::FindLastLessOrEqual( - const string& name) { - // Find the last key in the map which sorts less than or equal to the - // symbol name. Since upper_bound() returns the *first* key that sorts - // *greater* than the input, we want the element immediately before that. - typename map::iterator iter = by_symbol_.upper_bound(name); - if (iter != by_symbol_.begin()) --iter; - return iter; -} - -template -bool SimpleDescriptorDatabase::DescriptorIndex::IsSubSymbol( - const string& sub_symbol, const string& super_symbol) { - return sub_symbol == super_symbol || - (HasPrefixString(super_symbol, sub_symbol) && - super_symbol[sub_symbol.size()] == '.'); -} - -template -bool SimpleDescriptorDatabase::DescriptorIndex::ValidateSymbolName( - const string& name) { - for (int i = 0; i < name.size(); i++) { - // I don't trust ctype.h due to locales. :( - if (name[i] != '.' && name[i] != '_' && - (name[i] < '0' || name[i] > '9') && - (name[i] < 'A' || name[i] > 'Z') && - (name[i] < 'a' || name[i] > 'z')) { - return false; - } - } - return true; -} - -// ------------------------------------------------------------------- - -SimpleDescriptorDatabase::SimpleDescriptorDatabase() {} -SimpleDescriptorDatabase::~SimpleDescriptorDatabase() { - STLDeleteElements(&files_to_delete_); -} - -bool SimpleDescriptorDatabase::Add(const FileDescriptorProto& file) { - FileDescriptorProto* new_file = new FileDescriptorProto; - new_file->CopyFrom(file); - return AddAndOwn(new_file); -} - -bool SimpleDescriptorDatabase::AddAndOwn(const FileDescriptorProto* file) { - files_to_delete_.push_back(file); - return index_.AddFile(*file, file); -} - -bool SimpleDescriptorDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { - return MaybeCopy(index_.FindFile(filename), output); -} - -bool SimpleDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { - return MaybeCopy(index_.FindSymbol(symbol_name), output); -} - -bool SimpleDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, - FileDescriptorProto* output) { - return MaybeCopy(index_.FindExtension(containing_type, field_number), output); -} - -bool SimpleDescriptorDatabase::FindAllExtensionNumbers( - const string& extendee_type, - vector* output) { - return index_.FindAllExtensionNumbers(extendee_type, output); -} - -bool SimpleDescriptorDatabase::MaybeCopy(const FileDescriptorProto* file, - FileDescriptorProto* output) { - if (file == NULL) return false; - output->CopyFrom(*file); - return true; -} - -// ------------------------------------------------------------------- - -EncodedDescriptorDatabase::EncodedDescriptorDatabase() {} -EncodedDescriptorDatabase::~EncodedDescriptorDatabase() { - for (int i = 0; i < files_to_delete_.size(); i++) { - operator delete(files_to_delete_[i]); - } -} - -bool EncodedDescriptorDatabase::Add( - const void* encoded_file_descriptor, int size) { - FileDescriptorProto file; - if (file.ParseFromArray(encoded_file_descriptor, size)) { - return index_.AddFile(file, make_pair(encoded_file_descriptor, size)); - } else { - GOOGLE_LOG(ERROR) << "Invalid file descriptor data passed to " - "EncodedDescriptorDatabase::Add()."; - return false; - } -} - -bool EncodedDescriptorDatabase::AddCopy( - const void* encoded_file_descriptor, int size) { - void* copy = operator new(size); - memcpy(copy, encoded_file_descriptor, size); - files_to_delete_.push_back(copy); - return Add(copy, size); -} - -bool EncodedDescriptorDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { - return MaybeParse(index_.FindFile(filename), output); -} - -bool EncodedDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { - return MaybeParse(index_.FindSymbol(symbol_name), output); -} - -bool EncodedDescriptorDatabase::FindNameOfFileContainingSymbol( - const string& symbol_name, - string* output) { - pair encoded_file = index_.FindSymbol(symbol_name); - if (encoded_file.first == NULL) return false; - - // Optimization: The name should be the first field in the encoded message. - // Try to just read it directly. - io::CodedInputStream input(reinterpret_cast(encoded_file.first), - encoded_file.second); - - const uint32 kNameTag = internal::WireFormatLite::MakeTag( - FileDescriptorProto::kNameFieldNumber, - internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - - if (input.ReadTag() == kNameTag) { - // Success! - return internal::WireFormatLite::ReadString(&input, output); - } else { - // Slow path. Parse whole message. - FileDescriptorProto file_proto; - if (!file_proto.ParseFromArray(encoded_file.first, encoded_file.second)) { - return false; - } - *output = file_proto.name(); - return true; - } -} - -bool EncodedDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, - FileDescriptorProto* output) { - return MaybeParse(index_.FindExtension(containing_type, field_number), - output); -} - -bool EncodedDescriptorDatabase::FindAllExtensionNumbers( - const string& extendee_type, - vector* output) { - return index_.FindAllExtensionNumbers(extendee_type, output); -} - -bool EncodedDescriptorDatabase::MaybeParse( - pair encoded_file, - FileDescriptorProto* output) { - if (encoded_file.first == NULL) return false; - return output->ParseFromArray(encoded_file.first, encoded_file.second); -} - -// =================================================================== - -DescriptorPoolDatabase::DescriptorPoolDatabase(const DescriptorPool& pool) - : pool_(pool) {} -DescriptorPoolDatabase::~DescriptorPoolDatabase() {} - -bool DescriptorPoolDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { - const FileDescriptor* file = pool_.FindFileByName(filename); - if (file == NULL) return false; - output->Clear(); - file->CopyTo(output); - return true; -} - -bool DescriptorPoolDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { - const FileDescriptor* file = pool_.FindFileContainingSymbol(symbol_name); - if (file == NULL) return false; - output->Clear(); - file->CopyTo(output); - return true; -} - -bool DescriptorPoolDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, - FileDescriptorProto* output) { - const Descriptor* extendee = pool_.FindMessageTypeByName(containing_type); - if (extendee == NULL) return false; - - const FieldDescriptor* extension = - pool_.FindExtensionByNumber(extendee, field_number); - if (extension == NULL) return false; - - output->Clear(); - extension->file()->CopyTo(output); - return true; -} - -bool DescriptorPoolDatabase::FindAllExtensionNumbers( - const string& extendee_type, - vector* output) { - const Descriptor* extendee = pool_.FindMessageTypeByName(extendee_type); - if (extendee == NULL) return false; - - vector extensions; - pool_.FindAllExtensions(extendee, &extensions); - - for (int i = 0; i < extensions.size(); ++i) { - output->push_back(extensions[i]->number()); - } - - return true; -} - -// =================================================================== - -MergedDescriptorDatabase::MergedDescriptorDatabase( - DescriptorDatabase* source1, - DescriptorDatabase* source2) { - sources_.push_back(source1); - sources_.push_back(source2); -} -MergedDescriptorDatabase::MergedDescriptorDatabase( - const vector& sources) - : sources_(sources) {} -MergedDescriptorDatabase::~MergedDescriptorDatabase() {} - -bool MergedDescriptorDatabase::FindFileByName( - const string& filename, - FileDescriptorProto* output) { - for (int i = 0; i < sources_.size(); i++) { - if (sources_[i]->FindFileByName(filename, output)) { - return true; - } - } - return false; -} - -bool MergedDescriptorDatabase::FindFileContainingSymbol( - const string& symbol_name, - FileDescriptorProto* output) { - for (int i = 0; i < sources_.size(); i++) { - if (sources_[i]->FindFileContainingSymbol(symbol_name, output)) { - // The symbol was found in source i. However, if one of the previous - // sources defines a file with the same name (which presumably doesn't - // contain the symbol, since it wasn't found in that source), then we - // must hide it from the caller. - FileDescriptorProto temp; - for (int j = 0; j < i; j++) { - if (sources_[j]->FindFileByName(output->name(), &temp)) { - // Found conflicting file in a previous source. - return false; - } - } - return true; - } - } - return false; -} - -bool MergedDescriptorDatabase::FindFileContainingExtension( - const string& containing_type, - int field_number, - FileDescriptorProto* output) { - for (int i = 0; i < sources_.size(); i++) { - if (sources_[i]->FindFileContainingExtension( - containing_type, field_number, output)) { - // The symbol was found in source i. However, if one of the previous - // sources defines a file with the same name (which presumably doesn't - // contain the symbol, since it wasn't found in that source), then we - // must hide it from the caller. - FileDescriptorProto temp; - for (int j = 0; j < i; j++) { - if (sources_[j]->FindFileByName(output->name(), &temp)) { - // Found conflicting file in a previous source. - return false; - } - } - return true; - } - } - return false; -} - -bool MergedDescriptorDatabase::FindAllExtensionNumbers( - const string& extendee_type, - vector* output) { - set merged_results; - vector results; - bool success = false; - - for (int i = 0; i < sources_.size(); i++) { - if (sources_[i]->FindAllExtensionNumbers(extendee_type, &results)) { - copy(results.begin(), results.end(), - insert_iterator >(merged_results, merged_results.begin())); - success = true; - } - results.clear(); - } - - copy(merged_results.begin(), merged_results.end(), - insert_iterator >(*output, output->end())); - - return success; -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/descriptor_database.h b/Resources/NetHook/google/protobuf/descriptor_database.h deleted file mode 100644 index f32b1db9..00000000 --- a/Resources/NetHook/google/protobuf/descriptor_database.h +++ /dev/null @@ -1,366 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Interface for manipulating databases of descriptors. - -#ifndef GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ -#define GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -// Defined in this file. -class DescriptorDatabase; -class SimpleDescriptorDatabase; -class EncodedDescriptorDatabase; -class DescriptorPoolDatabase; -class MergedDescriptorDatabase; - -// Abstract interface for a database of descriptors. -// -// This is useful if you want to create a DescriptorPool which loads -// descriptors on-demand from some sort of large database. If the database -// is large, it may be inefficient to enumerate every .proto file inside it -// calling DescriptorPool::BuildFile() for each one. Instead, a DescriptorPool -// can be created which wraps a DescriptorDatabase and only builds particular -// descriptors when they are needed. -class LIBPROTOBUF_EXPORT DescriptorDatabase { - public: - inline DescriptorDatabase() {} - virtual ~DescriptorDatabase(); - - // Find a file by file name. Fills in in *output and returns true if found. - // Otherwise, returns false, leaving the contents of *output undefined. - virtual bool FindFileByName(const string& filename, - FileDescriptorProto* output) = 0; - - // Find the file that declares the given fully-qualified symbol name. - // If found, fills in *output and returns true, otherwise returns false - // and leaves *output undefined. - virtual bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output) = 0; - - // Find the file which defines an extension extending the given message type - // with the given field number. If found, fills in *output and returns true, - // otherwise returns false and leaves *output undefined. containing_type - // must be a fully-qualified type name. - virtual bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output) = 0; - - // Finds the tag numbers used by all known extensions of - // extendee_type, and appends them to output in an undefined - // order. This method is best-effort: it's not guaranteed that the - // database will find all extensions, and it's not guaranteed that - // FindFileContainingExtension will return true on all of the found - // numbers. Returns true if the search was successful, otherwise - // returns false and leaves output unchanged. - // - // This method has a default implementation that always returns - // false. - virtual bool FindAllExtensionNumbers(const string& extendee_type, - vector* output) { - return false; - } - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorDatabase); -}; - -// A DescriptorDatabase into which you can insert files manually. -// -// FindFileContainingSymbol() is fully-implemented. When you add a file, its -// symbols will be indexed for this purpose. Note that the implementation -// may return false positives, but only if it isn't possible for the symbol -// to be defined in any other file. In particular, if a file defines a symbol -// "Foo", then searching for "Foo.[anything]" will match that file. This way, -// the database does not need to aggressively index all children of a symbol. -// -// FindFileContainingExtension() is mostly-implemented. It works if and only -// if the original FieldDescriptorProto defining the extension has a -// fully-qualified type name in its "extendee" field (i.e. starts with a '.'). -// If the extendee is a relative name, SimpleDescriptorDatabase will not -// attempt to resolve the type, so it will not know what type the extension is -// extending. Therefore, calling FindFileContainingExtension() with the -// extension's containing type will never actually find that extension. Note -// that this is an unlikely problem, as all FileDescriptorProtos created by the -// protocol compiler (as well as ones created by calling -// FileDescriptor::CopyTo()) will always use fully-qualified names for all -// types. You only need to worry if you are constructing FileDescriptorProtos -// yourself, or are calling compiler::Parser directly. -class LIBPROTOBUF_EXPORT SimpleDescriptorDatabase : public DescriptorDatabase { - public: - SimpleDescriptorDatabase(); - ~SimpleDescriptorDatabase(); - - // Adds the FileDescriptorProto to the database, making a copy. The object - // can be deleted after Add() returns. Returns false if the file conflicted - // with a file already in the database, in which case an error will have - // been written to GOOGLE_LOG(ERROR). - bool Add(const FileDescriptorProto& file); - - // Adds the FileDescriptorProto to the database and takes ownership of it. - bool AddAndOwn(const FileDescriptorProto* file); - - // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output); - bool FindAllExtensionNumbers(const string& extendee_type, - vector* output); - - private: - // So that it can use DescriptorIndex. - friend class EncodedDescriptorDatabase; - - // An index mapping file names, symbol names, and extension numbers to - // some sort of values. - template - class DescriptorIndex { - public: - // Helpers to recursively add particular descriptors and all their contents - // to the index. - bool AddFile(const FileDescriptorProto& file, - Value value); - bool AddSymbol(const string& name, Value value); - bool AddNestedExtensions(const DescriptorProto& message_type, - Value value); - bool AddExtension(const FieldDescriptorProto& field, - Value value); - - Value FindFile(const string& filename); - Value FindSymbol(const string& name); - Value FindExtension(const string& containing_type, int field_number); - bool FindAllExtensionNumbers(const string& containing_type, - vector* output); - - private: - map by_name_; - map by_symbol_; - map, Value> by_extension_; - - // Invariant: The by_symbol_ map does not contain any symbols which are - // prefixes of other symbols in the map. For example, "foo.bar" is a - // prefix of "foo.bar.baz" (but is not a prefix of "foo.barbaz"). - // - // This invariant is important because it means that given a symbol name, - // we can find a key in the map which is a prefix of the symbol in O(lg n) - // time, and we know that there is at most one such key. - // - // The prefix lookup algorithm works like so: - // 1) Find the last key in the map which is less than or equal to the - // search key. - // 2) If the found key is a prefix of the search key, then return it. - // Otherwise, there is no match. - // - // I am sure this algorithm has been described elsewhere, but since I - // wasn't able to find it quickly I will instead prove that it works - // myself. The key to the algorithm is that if a match exists, step (1) - // will find it. Proof: - // 1) Define the "search key" to be the key we are looking for, the "found - // key" to be the key found in step (1), and the "match key" to be the - // key which actually matches the serach key (i.e. the key we're trying - // to find). - // 2) The found key must be less than or equal to the search key by - // definition. - // 3) The match key must also be less than or equal to the search key - // (because it is a prefix). - // 4) The match key cannot be greater than the found key, because if it - // were, then step (1) of the algorithm would have returned the match - // key instead (since it finds the *greatest* key which is less than or - // equal to the search key). - // 5) Therefore, the found key must be between the match key and the search - // key, inclusive. - // 6) Since the search key must be a sub-symbol of the match key, if it is - // not equal to the match key, then search_key[match_key.size()] must - // be '.'. - // 7) Since '.' sorts before any other character that is valid in a symbol - // name, then if the found key is not equal to the match key, then - // found_key[match_key.size()] must also be '.', because any other value - // would make it sort after the search key. - // 8) Therefore, if the found key is not equal to the match key, then the - // found key must be a sub-symbol of the match key. However, this would - // contradict our map invariant which says that no symbol in the map is - // a sub-symbol of any other. - // 9) Therefore, the found key must match the match key. - // - // The above proof assumes the match key exists. In the case that the - // match key does not exist, then step (1) will return some other symbol. - // That symbol cannot be a super-symbol of the search key since if it were, - // then it would be a match, and we're assuming the match key doesn't exist. - // Therefore, step 2 will correctly return no match. - - // Find the last entry in the by_symbol_ map whose key is less than or - // equal to the given name. - typename map::iterator FindLastLessOrEqual( - const string& name); - - // True if either the arguments are equal or super_symbol identifies a - // parent symbol of sub_symbol (e.g. "foo.bar" is a parent of - // "foo.bar.baz", but not a parent of "foo.barbaz"). - bool IsSubSymbol(const string& sub_symbol, const string& super_symbol); - - // Returns true if and only if all characters in the name are alphanumerics, - // underscores, or periods. - bool ValidateSymbolName(const string& name); - }; - - - DescriptorIndex index_; - vector files_to_delete_; - - // If file is non-NULL, copy it into *output and return true, otherwise - // return false. - bool MaybeCopy(const FileDescriptorProto* file, - FileDescriptorProto* output); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SimpleDescriptorDatabase); -}; - -// Very similar to SimpleDescriptorDatabase, but stores all the descriptors -// as raw bytes and generally tries to use as little memory as possible. -// -// The same caveats regarding FindFileContainingExtension() apply as with -// SimpleDescriptorDatabase. -class LIBPROTOBUF_EXPORT EncodedDescriptorDatabase : public DescriptorDatabase { - public: - EncodedDescriptorDatabase(); - ~EncodedDescriptorDatabase(); - - // Adds the FileDescriptorProto to the database. The descriptor is provided - // in encoded form. The database does not make a copy of the bytes, nor - // does it take ownership; it's up to the caller to make sure the bytes - // remain valid for the life of the database. Returns false and logs an error - // if the bytes are not a valid FileDescriptorProto or if the file conflicted - // with a file already in the database. - bool Add(const void* encoded_file_descriptor, int size); - - // Like Add(), but makes a copy of the data, so that the caller does not - // need to keep it around. - bool AddCopy(const void* encoded_file_descriptor, int size); - - // Like FindFileContainingSymbol but returns only the name of the file. - bool FindNameOfFileContainingSymbol(const string& symbol_name, - string* output); - - // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output); - bool FindAllExtensionNumbers(const string& extendee_type, - vector* output); - - private: - SimpleDescriptorDatabase::DescriptorIndex > index_; - vector files_to_delete_; - - // If encoded_file.first is non-NULL, parse the data into *output and return - // true, otherwise return false. - bool MaybeParse(pair encoded_file, - FileDescriptorProto* output); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EncodedDescriptorDatabase); -}; - -// A DescriptorDatabase that fetches files from a given pool. -class LIBPROTOBUF_EXPORT DescriptorPoolDatabase : public DescriptorDatabase { - public: - DescriptorPoolDatabase(const DescriptorPool& pool); - ~DescriptorPoolDatabase(); - - // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output); - bool FindAllExtensionNumbers(const string& extendee_type, - vector* output); - - private: - const DescriptorPool& pool_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DescriptorPoolDatabase); -}; - -// A DescriptorDatabase that wraps two or more others. It first searches the -// first database and, if that fails, tries the second, and so on. -class LIBPROTOBUF_EXPORT MergedDescriptorDatabase : public DescriptorDatabase { - public: - // Merge just two databases. The sources remain property of the caller. - MergedDescriptorDatabase(DescriptorDatabase* source1, - DescriptorDatabase* source2); - // Merge more than two databases. The sources remain property of the caller. - // The vector may be deleted after the constructor returns but the - // DescriptorDatabases need to stick around. - MergedDescriptorDatabase(const vector& sources); - ~MergedDescriptorDatabase(); - - // implements DescriptorDatabase ----------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output); - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output); - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output); - // Merges the results of calling all databases. Returns true iff any - // of the databases returned true. - bool FindAllExtensionNumbers(const string& extendee_type, - vector* output); - - private: - vector sources_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MergedDescriptorDatabase); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_DESCRIPTOR_DATABASE_H__ diff --git a/Resources/NetHook/google/protobuf/descriptor_database_unittest.cc b/Resources/NetHook/google/protobuf/descriptor_database_unittest.cc deleted file mode 100644 index ac72ddcd..00000000 --- a/Resources/NetHook/google/protobuf/descriptor_database_unittest.cc +++ /dev/null @@ -1,748 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file makes extensive use of RFC 3092. :) - -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace { - -static void AddToDatabase(SimpleDescriptorDatabase* database, - const char* file_text) { - FileDescriptorProto file_proto; - EXPECT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); - database->Add(file_proto); -} - -static void ExpectContainsType(const FileDescriptorProto& proto, - const string& type_name) { - for (int i = 0; i < proto.message_type_size(); i++) { - if (proto.message_type(i).name() == type_name) return; - } - ADD_FAILURE() << "\"" << proto.name() - << "\" did not contain expected type \"" - << type_name << "\"."; -} - -// =================================================================== - -#if GTEST_HAS_PARAM_TEST - -// SimpleDescriptorDatabase, EncodedDescriptorDatabase, and -// DescriptorPoolDatabase call for very similar tests. Instead of writing -// three nearly-identical sets of tests, we use parameterized tests to apply -// the same code to all three. - -// The parameterized test runs against a DescriptarDatabaseTestCase. We have -// implementations for each of the three classes we want to test. -class DescriptorDatabaseTestCase { - public: - virtual ~DescriptorDatabaseTestCase() {} - - virtual DescriptorDatabase* GetDatabase() = 0; - virtual bool AddToDatabase(const FileDescriptorProto& file) = 0; -}; - -// Factory function type. -typedef DescriptorDatabaseTestCase* DescriptorDatabaseTestCaseFactory(); - -// Specialization for SimpleDescriptorDatabase. -class SimpleDescriptorDatabaseTestCase : public DescriptorDatabaseTestCase { - public: - static DescriptorDatabaseTestCase* New() { - return new SimpleDescriptorDatabaseTestCase; - } - - virtual ~SimpleDescriptorDatabaseTestCase() {} - - virtual DescriptorDatabase* GetDatabase() { - return &database_; - } - virtual bool AddToDatabase(const FileDescriptorProto& file) { - return database_.Add(file); - } - - private: - SimpleDescriptorDatabase database_; -}; - -// Specialization for EncodedDescriptorDatabase. -class EncodedDescriptorDatabaseTestCase : public DescriptorDatabaseTestCase { - public: - static DescriptorDatabaseTestCase* New() { - return new EncodedDescriptorDatabaseTestCase; - } - - virtual ~EncodedDescriptorDatabaseTestCase() {} - - virtual DescriptorDatabase* GetDatabase() { - return &database_; - } - virtual bool AddToDatabase(const FileDescriptorProto& file) { - string data; - file.SerializeToString(&data); - return database_.AddCopy(data.data(), data.size()); - } - - private: - EncodedDescriptorDatabase database_; -}; - -// Specialization for DescriptorPoolDatabase. -class DescriptorPoolDatabaseTestCase : public DescriptorDatabaseTestCase { - public: - static DescriptorDatabaseTestCase* New() { - return new EncodedDescriptorDatabaseTestCase; - } - - DescriptorPoolDatabaseTestCase() : database_(pool_) {} - virtual ~DescriptorPoolDatabaseTestCase() {} - - virtual DescriptorDatabase* GetDatabase() { - return &database_; - } - virtual bool AddToDatabase(const FileDescriptorProto& file) { - return pool_.BuildFile(file); - } - - private: - DescriptorPool pool_; - DescriptorPoolDatabase database_; -}; - -// ------------------------------------------------------------------- - -class DescriptorDatabaseTest - : public testing::TestWithParam { - protected: - virtual void SetUp() { - test_case_.reset(GetParam()()); - database_ = test_case_->GetDatabase(); - } - - void AddToDatabase(const char* file_descriptor_text) { - FileDescriptorProto file_proto; - EXPECT_TRUE(TextFormat::ParseFromString(file_descriptor_text, &file_proto)); - EXPECT_TRUE(test_case_->AddToDatabase(file_proto)); - } - - void AddToDatabaseWithError(const char* file_descriptor_text) { - FileDescriptorProto file_proto; - EXPECT_TRUE(TextFormat::ParseFromString(file_descriptor_text, &file_proto)); - EXPECT_FALSE(test_case_->AddToDatabase(file_proto)); - } - - scoped_ptr test_case_; - DescriptorDatabase* database_; -}; - -TEST_P(DescriptorDatabaseTest, FindFileByName) { - AddToDatabase( - "name: \"foo.proto\" " - "message_type { name:\"Foo\" }"); - AddToDatabase( - "name: \"bar.proto\" " - "message_type { name:\"Bar\" }"); - - { - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileByName("foo.proto", &file)); - EXPECT_EQ("foo.proto", file.name()); - ExpectContainsType(file, "Foo"); - } - - { - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileByName("bar.proto", &file)); - EXPECT_EQ("bar.proto", file.name()); - ExpectContainsType(file, "Bar"); - } - - { - // Fails to find undefined files. - FileDescriptorProto file; - EXPECT_FALSE(database_->FindFileByName("baz.proto", &file)); - } -} - -TEST_P(DescriptorDatabaseTest, FindFileContainingSymbol) { - AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - " field { name:\"qux\" }" - " nested_type { name: \"Grault\" } " - " enum_type { name: \"Garply\" } " - "} " - "enum_type { " - " name: \"Waldo\" " - " value { name:\"FRED\" } " - "} " - "extension { name: \"plugh\" } " - "service { " - " name: \"Xyzzy\" " - " method { name: \"Thud\" } " - "}" - ); - AddToDatabase( - "name: \"bar.proto\" " - "package: \"corge\" " - "message_type { name: \"Bar\" }"); - - { - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Foo", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find fields. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.qux", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find nested types. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.Grault", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find nested enums. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.Garply", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find enum types. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Waldo", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find enum values. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Waldo.FRED", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find extensions. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("plugh", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find services. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Xyzzy", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find methods. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("Xyzzy.Thud", &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - // Can find things in packages. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingSymbol("corge.Bar", &file)); - EXPECT_EQ("bar.proto", file.name()); - } - - { - // Fails to find undefined symbols. - FileDescriptorProto file; - EXPECT_FALSE(database_->FindFileContainingSymbol("Baz", &file)); - } - - { - // Names must be fully-qualified. - FileDescriptorProto file; - EXPECT_FALSE(database_->FindFileContainingSymbol("Bar", &file)); - } -} - -TEST_P(DescriptorDatabaseTest, FindFileContainingExtension) { - AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - " extension_range { start: 1 end: 1000 } " - " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }" - "}"); - AddToDatabase( - "name: \"bar.proto\" " - "package: \"corge\" " - "dependency: \"foo.proto\" " - "message_type { " - " name: \"Bar\" " - " extension_range { start: 1 end: 1000 } " - "} " - "extension { name:\"grault\" extendee: \".Foo\" number:32 } " - "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " - "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); - - { - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingExtension("Foo", 5, &file)); - EXPECT_EQ("foo.proto", file.name()); - } - - { - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingExtension("Foo", 32, &file)); - EXPECT_EQ("bar.proto", file.name()); - } - - { - // Can find extensions for qualified type names. - FileDescriptorProto file; - EXPECT_TRUE(database_->FindFileContainingExtension("corge.Bar", 70, &file)); - EXPECT_EQ("bar.proto", file.name()); - } - - { - // Can't find extensions whose extendee was not fully-qualified in the - // FileDescriptorProto. - FileDescriptorProto file; - EXPECT_FALSE(database_->FindFileContainingExtension("Bar", 56, &file)); - EXPECT_FALSE( - database_->FindFileContainingExtension("corge.Bar", 56, &file)); - } - - { - // Can't find non-existent extension numbers. - FileDescriptorProto file; - EXPECT_FALSE(database_->FindFileContainingExtension("Foo", 12, &file)); - } - - { - // Can't find extensions for non-existent types. - FileDescriptorProto file; - EXPECT_FALSE( - database_->FindFileContainingExtension("NoSuchType", 5, &file)); - } - - { - // Can't find extensions for unqualified type names. - FileDescriptorProto file; - EXPECT_FALSE(database_->FindFileContainingExtension("Bar", 70, &file)); - } -} - -TEST_P(DescriptorDatabaseTest, FindAllExtensionNumbers) { - AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - " extension_range { start: 1 end: 1000 } " - " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }" - "}"); - AddToDatabase( - "name: \"bar.proto\" " - "package: \"corge\" " - "dependency: \"foo.proto\" " - "message_type { " - " name: \"Bar\" " - " extension_range { start: 1 end: 1000 } " - "} " - "extension { name:\"grault\" extendee: \".Foo\" number:32 } " - "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " - "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); - - { - vector numbers; - EXPECT_TRUE(database_->FindAllExtensionNumbers("Foo", &numbers)); - ASSERT_EQ(2, numbers.size()); - sort(numbers.begin(), numbers.end()); - EXPECT_EQ(5, numbers[0]); - EXPECT_EQ(32, numbers[1]); - } - - { - vector numbers; - EXPECT_TRUE(database_->FindAllExtensionNumbers("corge.Bar", &numbers)); - // Note: won't find extension 56 due to the name not being fully qualified. - ASSERT_EQ(1, numbers.size()); - EXPECT_EQ(70, numbers[0]); - } - - { - // Can't find extensions for non-existent types. - vector numbers; - EXPECT_FALSE(database_->FindAllExtensionNumbers("NoSuchType", &numbers)); - } - - { - // Can't find extensions for unqualified types. - vector numbers; - EXPECT_FALSE(database_->FindAllExtensionNumbers("Bar", &numbers)); - } -} - -TEST_P(DescriptorDatabaseTest, ConflictingFileError) { - AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - "}"); - AddToDatabaseWithError( - "name: \"foo.proto\" " - "message_type { " - " name: \"Bar\" " - "}"); -} - -TEST_P(DescriptorDatabaseTest, ConflictingTypeError) { - AddToDatabase( - "name: \"foo.proto\" " - "message_type { " - " name: \"Foo\" " - "}"); - AddToDatabaseWithError( - "name: \"bar.proto\" " - "message_type { " - " name: \"Foo\" " - "}"); -} - -TEST_P(DescriptorDatabaseTest, ConflictingExtensionError) { - AddToDatabase( - "name: \"foo.proto\" " - "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }"); - AddToDatabaseWithError( - "name: \"bar.proto\" " - "extension { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " - " extendee: \".Foo\" }"); -} - -INSTANTIATE_TEST_CASE_P(Simple, DescriptorDatabaseTest, - testing::Values(&SimpleDescriptorDatabaseTestCase::New)); -INSTANTIATE_TEST_CASE_P(MemoryConserving, DescriptorDatabaseTest, - testing::Values(&EncodedDescriptorDatabaseTestCase::New)); -INSTANTIATE_TEST_CASE_P(Pool, DescriptorDatabaseTest, - testing::Values(&DescriptorPoolDatabaseTestCase::New)); - -#endif // GTEST_HAS_PARAM_TEST - -TEST(EncodedDescriptorDatabaseExtraTest, FindNameOfFileContainingSymbol) { - // Create two files, one of which is in two parts. - FileDescriptorProto file1, file2a, file2b; - file1.set_name("foo.proto"); - file1.set_package("foo"); - file1.add_message_type()->set_name("Foo"); - file2a.set_name("bar.proto"); - file2b.set_package("bar"); - file2b.add_message_type()->set_name("Bar"); - - // Normal serialization allows our optimization to kick in. - string data1 = file1.SerializeAsString(); - - // Force out-of-order serialization to test slow path. - string data2 = file2b.SerializeAsString() + file2a.SerializeAsString(); - - // Create EncodedDescriptorDatabase containing both files. - EncodedDescriptorDatabase db; - db.Add(data1.data(), data1.size()); - db.Add(data2.data(), data2.size()); - - // Test! - string filename; - EXPECT_TRUE(db.FindNameOfFileContainingSymbol("foo.Foo", &filename)); - EXPECT_EQ("foo.proto", filename); - EXPECT_TRUE(db.FindNameOfFileContainingSymbol("foo.Foo.Blah", &filename)); - EXPECT_EQ("foo.proto", filename); - EXPECT_TRUE(db.FindNameOfFileContainingSymbol("bar.Bar", &filename)); - EXPECT_EQ("bar.proto", filename); - EXPECT_FALSE(db.FindNameOfFileContainingSymbol("foo", &filename)); - EXPECT_FALSE(db.FindNameOfFileContainingSymbol("bar", &filename)); - EXPECT_FALSE(db.FindNameOfFileContainingSymbol("baz.Baz", &filename)); -} - -// =================================================================== - -class MergedDescriptorDatabaseTest : public testing::Test { - protected: - MergedDescriptorDatabaseTest() - : forward_merged_(&database1_, &database2_), - reverse_merged_(&database2_, &database1_) {} - - virtual void SetUp() { - AddToDatabase(&database1_, - "name: \"foo.proto\" " - "message_type { name:\"Foo\" extension_range { start: 1 end: 100 } } " - "extension { name:\"foo_ext\" extendee: \".Foo\" number:3 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - AddToDatabase(&database2_, - "name: \"bar.proto\" " - "message_type { name:\"Bar\" extension_range { start: 1 end: 100 } } " - "extension { name:\"bar_ext\" extendee: \".Bar\" number:5 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - - // baz.proto exists in both pools, with different definitions. - AddToDatabase(&database1_, - "name: \"baz.proto\" " - "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " - "message_type { name:\"FromPool1\" } " - "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } " - "extension { name:\"database1_only_ext\" extendee: \".Baz\" number:13 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - AddToDatabase(&database2_, - "name: \"baz.proto\" " - "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " - "message_type { name:\"FromPool2\" } " - "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - } - - SimpleDescriptorDatabase database1_; - SimpleDescriptorDatabase database2_; - - MergedDescriptorDatabase forward_merged_; - MergedDescriptorDatabase reverse_merged_; -}; - -TEST_F(MergedDescriptorDatabaseTest, FindFileByName) { - { - // Can find file that is only in database1_. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileByName("foo.proto", &file)); - EXPECT_EQ("foo.proto", file.name()); - ExpectContainsType(file, "Foo"); - } - - { - // Can find file that is only in database2_. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileByName("bar.proto", &file)); - EXPECT_EQ("bar.proto", file.name()); - ExpectContainsType(file, "Bar"); - } - - { - // In forward_merged_, database1_'s baz.proto takes precedence. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileByName("baz.proto", &file)); - EXPECT_EQ("baz.proto", file.name()); - ExpectContainsType(file, "FromPool1"); - } - - { - // In reverse_merged_, database2_'s baz.proto takes precedence. - FileDescriptorProto file; - EXPECT_TRUE(reverse_merged_.FindFileByName("baz.proto", &file)); - EXPECT_EQ("baz.proto", file.name()); - ExpectContainsType(file, "FromPool2"); - } - - { - // Can't find non-existent file. - FileDescriptorProto file; - EXPECT_FALSE(forward_merged_.FindFileByName("no_such.proto", &file)); - } -} - -TEST_F(MergedDescriptorDatabaseTest, FindFileContainingSymbol) { - { - // Can find file that is only in database1_. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("Foo", &file)); - EXPECT_EQ("foo.proto", file.name()); - ExpectContainsType(file, "Foo"); - } - - { - // Can find file that is only in database2_. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("Bar", &file)); - EXPECT_EQ("bar.proto", file.name()); - ExpectContainsType(file, "Bar"); - } - - { - // In forward_merged_, database1_'s baz.proto takes precedence. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("Baz", &file)); - EXPECT_EQ("baz.proto", file.name()); - ExpectContainsType(file, "FromPool1"); - } - - { - // In reverse_merged_, database2_'s baz.proto takes precedence. - FileDescriptorProto file; - EXPECT_TRUE(reverse_merged_.FindFileContainingSymbol("Baz", &file)); - EXPECT_EQ("baz.proto", file.name()); - ExpectContainsType(file, "FromPool2"); - } - - { - // FromPool1 only shows up in forward_merged_ because it is masked by - // database2_'s baz.proto in reverse_merged_. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("FromPool1", &file)); - EXPECT_FALSE(reverse_merged_.FindFileContainingSymbol("FromPool1", &file)); - } - - { - // Can't find non-existent symbol. - FileDescriptorProto file; - EXPECT_FALSE( - forward_merged_.FindFileContainingSymbol("NoSuchType", &file)); - } -} - -TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { - { - // Can find file that is only in database1_. - FileDescriptorProto file; - EXPECT_TRUE( - forward_merged_.FindFileContainingExtension("Foo", 3, &file)); - EXPECT_EQ("foo.proto", file.name()); - ExpectContainsType(file, "Foo"); - } - - { - // Can find file that is only in database2_. - FileDescriptorProto file; - EXPECT_TRUE( - forward_merged_.FindFileContainingExtension("Bar", 5, &file)); - EXPECT_EQ("bar.proto", file.name()); - ExpectContainsType(file, "Bar"); - } - - { - // In forward_merged_, database1_'s baz.proto takes precedence. - FileDescriptorProto file; - EXPECT_TRUE( - forward_merged_.FindFileContainingExtension("Baz", 12, &file)); - EXPECT_EQ("baz.proto", file.name()); - ExpectContainsType(file, "FromPool1"); - } - - { - // In reverse_merged_, database2_'s baz.proto takes precedence. - FileDescriptorProto file; - EXPECT_TRUE( - reverse_merged_.FindFileContainingExtension("Baz", 12, &file)); - EXPECT_EQ("baz.proto", file.name()); - ExpectContainsType(file, "FromPool2"); - } - - { - // Baz's extension 13 only shows up in forward_merged_ because it is - // masked by database2_'s baz.proto in reverse_merged_. - FileDescriptorProto file; - EXPECT_TRUE(forward_merged_.FindFileContainingExtension("Baz", 13, &file)); - EXPECT_FALSE(reverse_merged_.FindFileContainingExtension("Baz", 13, &file)); - } - - { - // Can't find non-existent extension. - FileDescriptorProto file; - EXPECT_FALSE( - forward_merged_.FindFileContainingExtension("Foo", 6, &file)); - } -} - -TEST_F(MergedDescriptorDatabaseTest, FindAllExtensionNumbers) { - { - // Message only has extension in database1_ - vector numbers; - EXPECT_TRUE(forward_merged_.FindAllExtensionNumbers("Foo", &numbers)); - ASSERT_EQ(1, numbers.size()); - EXPECT_EQ(3, numbers[0]); - } - - { - // Message only has extension in database2_ - vector numbers; - EXPECT_TRUE(forward_merged_.FindAllExtensionNumbers("Bar", &numbers)); - ASSERT_EQ(1, numbers.size()); - EXPECT_EQ(5, numbers[0]); - } - - { - // Merge results from the two databases. - vector numbers; - EXPECT_TRUE(forward_merged_.FindAllExtensionNumbers("Baz", &numbers)); - ASSERT_EQ(2, numbers.size()); - sort(numbers.begin(), numbers.end()); - EXPECT_EQ(12, numbers[0]); - EXPECT_EQ(13, numbers[1]); - } - - { - vector numbers; - EXPECT_TRUE(reverse_merged_.FindAllExtensionNumbers("Baz", &numbers)); - ASSERT_EQ(2, numbers.size()); - sort(numbers.begin(), numbers.end()); - EXPECT_EQ(12, numbers[0]); - EXPECT_EQ(13, numbers[1]); - } - - { - // Can't find extensions for a non-existent message. - vector numbers; - EXPECT_FALSE(reverse_merged_.FindAllExtensionNumbers("Blah", &numbers)); - } -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/descriptor_unittest.cc b/Resources/NetHook/google/protobuf/descriptor_unittest.cc deleted file mode 100644 index ec2c8152..00000000 --- a/Resources/NetHook/google/protobuf/descriptor_unittest.cc +++ /dev/null @@ -1,3956 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file makes extensive use of RFC 3092. :) - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { - -// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. -namespace descriptor_unittest { - -// Some helpers to make assembling descriptors faster. -DescriptorProto* AddMessage(FileDescriptorProto* file, const string& name) { - DescriptorProto* result = file->add_message_type(); - result->set_name(name); - return result; -} - -DescriptorProto* AddNestedMessage(DescriptorProto* parent, const string& name) { - DescriptorProto* result = parent->add_nested_type(); - result->set_name(name); - return result; -} - -EnumDescriptorProto* AddEnum(FileDescriptorProto* file, const string& name) { - EnumDescriptorProto* result = file->add_enum_type(); - result->set_name(name); - return result; -} - -EnumDescriptorProto* AddNestedEnum(DescriptorProto* parent, - const string& name) { - EnumDescriptorProto* result = parent->add_enum_type(); - result->set_name(name); - return result; -} - -ServiceDescriptorProto* AddService(FileDescriptorProto* file, - const string& name) { - ServiceDescriptorProto* result = file->add_service(); - result->set_name(name); - return result; -} - -FieldDescriptorProto* AddField(DescriptorProto* parent, - const string& name, int number, - FieldDescriptorProto::Label label, - FieldDescriptorProto::Type type) { - FieldDescriptorProto* result = parent->add_field(); - result->set_name(name); - result->set_number(number); - result->set_label(label); - result->set_type(type); - return result; -} - -FieldDescriptorProto* AddExtension(FileDescriptorProto* file, - const string& extendee, - const string& name, int number, - FieldDescriptorProto::Label label, - FieldDescriptorProto::Type type) { - FieldDescriptorProto* result = file->add_extension(); - result->set_name(name); - result->set_number(number); - result->set_label(label); - result->set_type(type); - result->set_extendee(extendee); - return result; -} - -FieldDescriptorProto* AddNestedExtension(DescriptorProto* parent, - const string& extendee, - const string& name, int number, - FieldDescriptorProto::Label label, - FieldDescriptorProto::Type type) { - FieldDescriptorProto* result = parent->add_extension(); - result->set_name(name); - result->set_number(number); - result->set_label(label); - result->set_type(type); - result->set_extendee(extendee); - return result; -} - -DescriptorProto::ExtensionRange* AddExtensionRange(DescriptorProto* parent, - int start, int end) { - DescriptorProto::ExtensionRange* result = parent->add_extension_range(); - result->set_start(start); - result->set_end(end); - return result; -} - -EnumValueDescriptorProto* AddEnumValue(EnumDescriptorProto* enum_proto, - const string& name, int number) { - EnumValueDescriptorProto* result = enum_proto->add_value(); - result->set_name(name); - result->set_number(number); - return result; -} - -MethodDescriptorProto* AddMethod(ServiceDescriptorProto* service, - const string& name, - const string& input_type, - const string& output_type) { - MethodDescriptorProto* result = service->add_method(); - result->set_name(name); - result->set_input_type(input_type); - result->set_output_type(output_type); - return result; -} - -// Empty enums technically aren't allowed. We need to insert a dummy value -// into them. -void AddEmptyEnum(FileDescriptorProto* file, const string& name) { - AddEnumValue(AddEnum(file, name), name + "_DUMMY", 1); -} - -// =================================================================== - -// Test simple files. -class FileDescriptorTest : public testing::Test { - protected: - virtual void SetUp() { - // Build descriptors for the following definitions: - // - // // in "foo.proto" - // message FooMessage { extensions 1; } - // enum FooEnum {FOO_ENUM_VALUE = 1;} - // service FooService {} - // extend FooMessage { optional int32 foo_extension = 1; } - // - // // in "bar.proto" - // package bar_package; - // message BarMessage { extensions 1; } - // enum BarEnum {BAR_ENUM_VALUE = 1;} - // service BarService {} - // extend BarMessage { optional int32 bar_extension = 1; } - // - // Also, we have an empty file "baz.proto". This file's purpose is to - // make sure that even though it has the same package as foo.proto, - // searching it for members of foo.proto won't work. - - FileDescriptorProto foo_file; - foo_file.set_name("foo.proto"); - AddExtensionRange(AddMessage(&foo_file, "FooMessage"), 1, 2); - AddEnumValue(AddEnum(&foo_file, "FooEnum"), "FOO_ENUM_VALUE", 1); - AddService(&foo_file, "FooService"); - AddExtension(&foo_file, "FooMessage", "foo_extension", 1, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - - FileDescriptorProto bar_file; - bar_file.set_name("bar.proto"); - bar_file.set_package("bar_package"); - bar_file.add_dependency("foo.proto"); - AddExtensionRange(AddMessage(&bar_file, "BarMessage"), 1, 2); - AddEnumValue(AddEnum(&bar_file, "BarEnum"), "BAR_ENUM_VALUE", 1); - AddService(&bar_file, "BarService"); - AddExtension(&bar_file, "bar_package.BarMessage", "bar_extension", 1, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - - FileDescriptorProto baz_file; - baz_file.set_name("baz.proto"); - - // Build the descriptors and get the pointers. - foo_file_ = pool_.BuildFile(foo_file); - ASSERT_TRUE(foo_file_ != NULL); - - bar_file_ = pool_.BuildFile(bar_file); - ASSERT_TRUE(bar_file_ != NULL); - - baz_file_ = pool_.BuildFile(baz_file); - ASSERT_TRUE(baz_file_ != NULL); - - ASSERT_EQ(1, foo_file_->message_type_count()); - foo_message_ = foo_file_->message_type(0); - ASSERT_EQ(1, foo_file_->enum_type_count()); - foo_enum_ = foo_file_->enum_type(0); - ASSERT_EQ(1, foo_enum_->value_count()); - foo_enum_value_ = foo_enum_->value(0); - ASSERT_EQ(1, foo_file_->service_count()); - foo_service_ = foo_file_->service(0); - ASSERT_EQ(1, foo_file_->extension_count()); - foo_extension_ = foo_file_->extension(0); - - ASSERT_EQ(1, bar_file_->message_type_count()); - bar_message_ = bar_file_->message_type(0); - ASSERT_EQ(1, bar_file_->enum_type_count()); - bar_enum_ = bar_file_->enum_type(0); - ASSERT_EQ(1, bar_enum_->value_count()); - bar_enum_value_ = bar_enum_->value(0); - ASSERT_EQ(1, bar_file_->service_count()); - bar_service_ = bar_file_->service(0); - ASSERT_EQ(1, bar_file_->extension_count()); - bar_extension_ = bar_file_->extension(0); - } - - DescriptorPool pool_; - - const FileDescriptor* foo_file_; - const FileDescriptor* bar_file_; - const FileDescriptor* baz_file_; - - const Descriptor* foo_message_; - const EnumDescriptor* foo_enum_; - const EnumValueDescriptor* foo_enum_value_; - const ServiceDescriptor* foo_service_; - const FieldDescriptor* foo_extension_; - - const Descriptor* bar_message_; - const EnumDescriptor* bar_enum_; - const EnumValueDescriptor* bar_enum_value_; - const ServiceDescriptor* bar_service_; - const FieldDescriptor* bar_extension_; -}; - -TEST_F(FileDescriptorTest, Name) { - EXPECT_EQ("foo.proto", foo_file_->name()); - EXPECT_EQ("bar.proto", bar_file_->name()); - EXPECT_EQ("baz.proto", baz_file_->name()); -} - -TEST_F(FileDescriptorTest, Package) { - EXPECT_EQ("", foo_file_->package()); - EXPECT_EQ("bar_package", bar_file_->package()); -} - -TEST_F(FileDescriptorTest, Dependencies) { - EXPECT_EQ(0, foo_file_->dependency_count()); - EXPECT_EQ(1, bar_file_->dependency_count()); - EXPECT_EQ(foo_file_, bar_file_->dependency(0)); -} - -TEST_F(FileDescriptorTest, FindMessageTypeByName) { - EXPECT_EQ(foo_message_, foo_file_->FindMessageTypeByName("FooMessage")); - EXPECT_EQ(bar_message_, bar_file_->FindMessageTypeByName("BarMessage")); - - EXPECT_TRUE(foo_file_->FindMessageTypeByName("BarMessage") == NULL); - EXPECT_TRUE(bar_file_->FindMessageTypeByName("FooMessage") == NULL); - EXPECT_TRUE(baz_file_->FindMessageTypeByName("FooMessage") == NULL); - - EXPECT_TRUE(foo_file_->FindMessageTypeByName("NoSuchMessage") == NULL); - EXPECT_TRUE(foo_file_->FindMessageTypeByName("FooEnum") == NULL); -} - -TEST_F(FileDescriptorTest, FindEnumTypeByName) { - EXPECT_EQ(foo_enum_, foo_file_->FindEnumTypeByName("FooEnum")); - EXPECT_EQ(bar_enum_, bar_file_->FindEnumTypeByName("BarEnum")); - - EXPECT_TRUE(foo_file_->FindEnumTypeByName("BarEnum") == NULL); - EXPECT_TRUE(bar_file_->FindEnumTypeByName("FooEnum") == NULL); - EXPECT_TRUE(baz_file_->FindEnumTypeByName("FooEnum") == NULL); - - EXPECT_TRUE(foo_file_->FindEnumTypeByName("NoSuchEnum") == NULL); - EXPECT_TRUE(foo_file_->FindEnumTypeByName("FooMessage") == NULL); -} - -TEST_F(FileDescriptorTest, FindEnumValueByName) { - EXPECT_EQ(foo_enum_value_, foo_file_->FindEnumValueByName("FOO_ENUM_VALUE")); - EXPECT_EQ(bar_enum_value_, bar_file_->FindEnumValueByName("BAR_ENUM_VALUE")); - - EXPECT_TRUE(foo_file_->FindEnumValueByName("BAR_ENUM_VALUE") == NULL); - EXPECT_TRUE(bar_file_->FindEnumValueByName("FOO_ENUM_VALUE") == NULL); - EXPECT_TRUE(baz_file_->FindEnumValueByName("FOO_ENUM_VALUE") == NULL); - - EXPECT_TRUE(foo_file_->FindEnumValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(foo_file_->FindEnumValueByName("FooMessage") == NULL); -} - -TEST_F(FileDescriptorTest, FindServiceByName) { - EXPECT_EQ(foo_service_, foo_file_->FindServiceByName("FooService")); - EXPECT_EQ(bar_service_, bar_file_->FindServiceByName("BarService")); - - EXPECT_TRUE(foo_file_->FindServiceByName("BarService") == NULL); - EXPECT_TRUE(bar_file_->FindServiceByName("FooService") == NULL); - EXPECT_TRUE(baz_file_->FindServiceByName("FooService") == NULL); - - EXPECT_TRUE(foo_file_->FindServiceByName("NoSuchService") == NULL); - EXPECT_TRUE(foo_file_->FindServiceByName("FooMessage") == NULL); -} - -TEST_F(FileDescriptorTest, FindExtensionByName) { - EXPECT_EQ(foo_extension_, foo_file_->FindExtensionByName("foo_extension")); - EXPECT_EQ(bar_extension_, bar_file_->FindExtensionByName("bar_extension")); - - EXPECT_TRUE(foo_file_->FindExtensionByName("bar_extension") == NULL); - EXPECT_TRUE(bar_file_->FindExtensionByName("foo_extension") == NULL); - EXPECT_TRUE(baz_file_->FindExtensionByName("foo_extension") == NULL); - - EXPECT_TRUE(foo_file_->FindExtensionByName("no_such_extension") == NULL); - EXPECT_TRUE(foo_file_->FindExtensionByName("FooMessage") == NULL); -} - -TEST_F(FileDescriptorTest, FindExtensionByNumber) { - EXPECT_EQ(foo_extension_, pool_.FindExtensionByNumber(foo_message_, 1)); - EXPECT_EQ(bar_extension_, pool_.FindExtensionByNumber(bar_message_, 1)); - - EXPECT_TRUE(pool_.FindExtensionByNumber(foo_message_, 2) == NULL); -} - -TEST_F(FileDescriptorTest, BuildAgain) { - // Test that if te call BuildFile again on the same input we get the same - // FileDescriptor back. - FileDescriptorProto file; - foo_file_->CopyTo(&file); - EXPECT_EQ(foo_file_, pool_.BuildFile(file)); - - // But if we change the file then it won't work. - file.set_package("some.other.package"); - EXPECT_TRUE(pool_.BuildFile(file) == NULL); -} - -// =================================================================== - -// Test simple flat messages and fields. -class DescriptorTest : public testing::Test { - protected: - virtual void SetUp() { - // Build descriptors for the following definitions: - // - // // in "foo.proto" - // message TestForeign {} - // enum TestEnum {} - // - // message TestMessage { - // required string foo = 1; - // optional TestEnum bar = 6; - // repeated TestForeign baz = 500000000; - // optional group qux = 15 {} - // } - // - // // in "bar.proto" - // package corge.grault; - // message TestMessage2 { - // required string foo = 1; - // required string bar = 2; - // required string quux = 6; - // } - // - // We cheat and use TestForeign as the type for qux rather than create - // an actual nested type. - // - // Since all primitive types (including string) use the same building - // code, there's no need to test each one individually. - // - // TestMessage2 is primarily here to test FindFieldByName and friends. - // All messages created from the same DescriptorPool share the same lookup - // table, so we need to insure that they don't interfere. - - FileDescriptorProto foo_file; - foo_file.set_name("foo.proto"); - AddMessage(&foo_file, "TestForeign"); - AddEmptyEnum(&foo_file, "TestEnum"); - - DescriptorProto* message = AddMessage(&foo_file, "TestMessage"); - AddField(message, "foo", 1, - FieldDescriptorProto::LABEL_REQUIRED, - FieldDescriptorProto::TYPE_STRING); - AddField(message, "bar", 6, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_ENUM) - ->set_type_name("TestEnum"); - AddField(message, "baz", 500000000, - FieldDescriptorProto::LABEL_REPEATED, - FieldDescriptorProto::TYPE_MESSAGE) - ->set_type_name("TestForeign"); - AddField(message, "qux", 15, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_GROUP) - ->set_type_name("TestForeign"); - - FileDescriptorProto bar_file; - bar_file.set_name("bar.proto"); - bar_file.set_package("corge.grault"); - - DescriptorProto* message2 = AddMessage(&bar_file, "TestMessage2"); - AddField(message2, "foo", 1, - FieldDescriptorProto::LABEL_REQUIRED, - FieldDescriptorProto::TYPE_STRING); - AddField(message2, "bar", 2, - FieldDescriptorProto::LABEL_REQUIRED, - FieldDescriptorProto::TYPE_STRING); - AddField(message2, "quux", 6, - FieldDescriptorProto::LABEL_REQUIRED, - FieldDescriptorProto::TYPE_STRING); - - // Build the descriptors and get the pointers. - foo_file_ = pool_.BuildFile(foo_file); - ASSERT_TRUE(foo_file_ != NULL); - - bar_file_ = pool_.BuildFile(bar_file); - ASSERT_TRUE(bar_file_ != NULL); - - ASSERT_EQ(1, foo_file_->enum_type_count()); - enum_ = foo_file_->enum_type(0); - - ASSERT_EQ(2, foo_file_->message_type_count()); - foreign_ = foo_file_->message_type(0); - message_ = foo_file_->message_type(1); - - ASSERT_EQ(4, message_->field_count()); - foo_ = message_->field(0); - bar_ = message_->field(1); - baz_ = message_->field(2); - qux_ = message_->field(3); - - ASSERT_EQ(1, bar_file_->message_type_count()); - message2_ = bar_file_->message_type(0); - - ASSERT_EQ(3, message2_->field_count()); - foo2_ = message2_->field(0); - bar2_ = message2_->field(1); - quux2_ = message2_->field(2); - } - - DescriptorPool pool_; - - const FileDescriptor* foo_file_; - const FileDescriptor* bar_file_; - - const Descriptor* message_; - const Descriptor* message2_; - const Descriptor* foreign_; - const EnumDescriptor* enum_; - - const FieldDescriptor* foo_; - const FieldDescriptor* bar_; - const FieldDescriptor* baz_; - const FieldDescriptor* qux_; - - const FieldDescriptor* foo2_; - const FieldDescriptor* bar2_; - const FieldDescriptor* quux2_; -}; - -TEST_F(DescriptorTest, Name) { - EXPECT_EQ("TestMessage", message_->name()); - EXPECT_EQ("TestMessage", message_->full_name()); - EXPECT_EQ(foo_file_, message_->file()); - - EXPECT_EQ("TestMessage2", message2_->name()); - EXPECT_EQ("corge.grault.TestMessage2", message2_->full_name()); - EXPECT_EQ(bar_file_, message2_->file()); -} - -TEST_F(DescriptorTest, ContainingType) { - EXPECT_TRUE(message_->containing_type() == NULL); - EXPECT_TRUE(message2_->containing_type() == NULL); -} - -TEST_F(DescriptorTest, FieldsByIndex) { - ASSERT_EQ(4, message_->field_count()); - EXPECT_EQ(foo_, message_->field(0)); - EXPECT_EQ(bar_, message_->field(1)); - EXPECT_EQ(baz_, message_->field(2)); - EXPECT_EQ(qux_, message_->field(3)); -} - -TEST_F(DescriptorTest, FindFieldByName) { - // All messages in the same DescriptorPool share a single lookup table for - // fields. So, in addition to testing that FindFieldByName finds the fields - // of the message, we need to test that it does *not* find the fields of - // *other* messages. - - EXPECT_EQ(foo_, message_->FindFieldByName("foo")); - EXPECT_EQ(bar_, message_->FindFieldByName("bar")); - EXPECT_EQ(baz_, message_->FindFieldByName("baz")); - EXPECT_EQ(qux_, message_->FindFieldByName("qux")); - EXPECT_TRUE(message_->FindFieldByName("no_such_field") == NULL); - EXPECT_TRUE(message_->FindFieldByName("quux") == NULL); - - EXPECT_EQ(foo2_ , message2_->FindFieldByName("foo" )); - EXPECT_EQ(bar2_ , message2_->FindFieldByName("bar" )); - EXPECT_EQ(quux2_, message2_->FindFieldByName("quux")); - EXPECT_TRUE(message2_->FindFieldByName("baz") == NULL); - EXPECT_TRUE(message2_->FindFieldByName("qux") == NULL); -} - -TEST_F(DescriptorTest, FindFieldByNumber) { - EXPECT_EQ(foo_, message_->FindFieldByNumber(1)); - EXPECT_EQ(bar_, message_->FindFieldByNumber(6)); - EXPECT_EQ(baz_, message_->FindFieldByNumber(500000000)); - EXPECT_EQ(qux_, message_->FindFieldByNumber(15)); - EXPECT_TRUE(message_->FindFieldByNumber(837592) == NULL); - EXPECT_TRUE(message_->FindFieldByNumber(2) == NULL); - - EXPECT_EQ(foo2_ , message2_->FindFieldByNumber(1)); - EXPECT_EQ(bar2_ , message2_->FindFieldByNumber(2)); - EXPECT_EQ(quux2_, message2_->FindFieldByNumber(6)); - EXPECT_TRUE(message2_->FindFieldByNumber(15) == NULL); - EXPECT_TRUE(message2_->FindFieldByNumber(500000000) == NULL); -} - -TEST_F(DescriptorTest, FieldName) { - EXPECT_EQ("foo", foo_->name()); - EXPECT_EQ("bar", bar_->name()); - EXPECT_EQ("baz", baz_->name()); - EXPECT_EQ("qux", qux_->name()); -} - -TEST_F(DescriptorTest, FieldFullName) { - EXPECT_EQ("TestMessage.foo", foo_->full_name()); - EXPECT_EQ("TestMessage.bar", bar_->full_name()); - EXPECT_EQ("TestMessage.baz", baz_->full_name()); - EXPECT_EQ("TestMessage.qux", qux_->full_name()); - - EXPECT_EQ("corge.grault.TestMessage2.foo", foo2_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.bar", bar2_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.quux", quux2_->full_name()); -} - -TEST_F(DescriptorTest, FieldFile) { - EXPECT_EQ(foo_file_, foo_->file()); - EXPECT_EQ(foo_file_, bar_->file()); - EXPECT_EQ(foo_file_, baz_->file()); - EXPECT_EQ(foo_file_, qux_->file()); - - EXPECT_EQ(bar_file_, foo2_->file()); - EXPECT_EQ(bar_file_, bar2_->file()); - EXPECT_EQ(bar_file_, quux2_->file()); -} - -TEST_F(DescriptorTest, FieldIndex) { - EXPECT_EQ(0, foo_->index()); - EXPECT_EQ(1, bar_->index()); - EXPECT_EQ(2, baz_->index()); - EXPECT_EQ(3, qux_->index()); -} - -TEST_F(DescriptorTest, FieldNumber) { - EXPECT_EQ( 1, foo_->number()); - EXPECT_EQ( 6, bar_->number()); - EXPECT_EQ(500000000, baz_->number()); - EXPECT_EQ( 15, qux_->number()); -} - -TEST_F(DescriptorTest, FieldType) { - EXPECT_EQ(FieldDescriptor::TYPE_STRING , foo_->type()); - EXPECT_EQ(FieldDescriptor::TYPE_ENUM , bar_->type()); - EXPECT_EQ(FieldDescriptor::TYPE_MESSAGE, baz_->type()); - EXPECT_EQ(FieldDescriptor::TYPE_GROUP , qux_->type()); -} - -TEST_F(DescriptorTest, FieldLabel) { - EXPECT_EQ(FieldDescriptor::LABEL_REQUIRED, foo_->label()); - EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, bar_->label()); - EXPECT_EQ(FieldDescriptor::LABEL_REPEATED, baz_->label()); - EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, qux_->label()); - - EXPECT_TRUE (foo_->is_required()); - EXPECT_FALSE(foo_->is_optional()); - EXPECT_FALSE(foo_->is_repeated()); - - EXPECT_FALSE(bar_->is_required()); - EXPECT_TRUE (bar_->is_optional()); - EXPECT_FALSE(bar_->is_repeated()); - - EXPECT_FALSE(baz_->is_required()); - EXPECT_FALSE(baz_->is_optional()); - EXPECT_TRUE (baz_->is_repeated()); -} - -TEST_F(DescriptorTest, FieldHasDefault) { - EXPECT_FALSE(foo_->has_default_value()); - EXPECT_FALSE(bar_->has_default_value()); - EXPECT_FALSE(baz_->has_default_value()); - EXPECT_FALSE(qux_->has_default_value()); -} - -TEST_F(DescriptorTest, FieldContainingType) { - EXPECT_EQ(message_, foo_->containing_type()); - EXPECT_EQ(message_, bar_->containing_type()); - EXPECT_EQ(message_, baz_->containing_type()); - EXPECT_EQ(message_, qux_->containing_type()); - - EXPECT_EQ(message2_, foo2_ ->containing_type()); - EXPECT_EQ(message2_, bar2_ ->containing_type()); - EXPECT_EQ(message2_, quux2_->containing_type()); -} - -TEST_F(DescriptorTest, FieldMessageType) { - EXPECT_TRUE(foo_->message_type() == NULL); - EXPECT_TRUE(bar_->message_type() == NULL); - - EXPECT_EQ(foreign_, baz_->message_type()); - EXPECT_EQ(foreign_, qux_->message_type()); -} - -TEST_F(DescriptorTest, FieldEnumType) { - EXPECT_TRUE(foo_->enum_type() == NULL); - EXPECT_TRUE(baz_->enum_type() == NULL); - EXPECT_TRUE(qux_->enum_type() == NULL); - - EXPECT_EQ(enum_, bar_->enum_type()); -} - -// =================================================================== - -class StylizedFieldNamesTest : public testing::Test { - protected: - void SetUp() { - FileDescriptorProto file; - file.set_name("foo.proto"); - - AddExtensionRange(AddMessage(&file, "ExtendableMessage"), 1, 1000); - - DescriptorProto* message = AddMessage(&file, "TestMessage"); - AddField(message, "foo_foo", 1, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddField(message, "FooBar", 2, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddField(message, "fooBaz", 3, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddField(message, "fooFoo", 4, // Camel-case conflict with foo_foo. - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddField(message, "foobar", 5, // Lower-case conflict with FooBar. - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - - AddNestedExtension(message, "ExtendableMessage", "bar_foo", 1, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddNestedExtension(message, "ExtendableMessage", "BarBar", 2, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddNestedExtension(message, "ExtendableMessage", "BarBaz", 3, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddNestedExtension(message, "ExtendableMessage", "barFoo", 4, // Conflict - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddNestedExtension(message, "ExtendableMessage", "barbar", 5, // Conflict - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - - AddExtension(&file, "ExtendableMessage", "baz_foo", 11, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddExtension(&file, "ExtendableMessage", "BazBar", 12, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddExtension(&file, "ExtendableMessage", "BazBaz", 13, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddExtension(&file, "ExtendableMessage", "bazFoo", 14, // Conflict - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddExtension(&file, "ExtendableMessage", "bazbar", 15, // Conflict - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - - file_ = pool_.BuildFile(file); - ASSERT_TRUE(file_ != NULL); - ASSERT_EQ(2, file_->message_type_count()); - message_ = file_->message_type(1); - ASSERT_EQ("TestMessage", message_->name()); - ASSERT_EQ(5, message_->field_count()); - ASSERT_EQ(5, message_->extension_count()); - ASSERT_EQ(5, file_->extension_count()); - } - - DescriptorPool pool_; - const FileDescriptor* file_; - const Descriptor* message_; -}; - -TEST_F(StylizedFieldNamesTest, LowercaseName) { - EXPECT_EQ("foo_foo", message_->field(0)->lowercase_name()); - EXPECT_EQ("foobar" , message_->field(1)->lowercase_name()); - EXPECT_EQ("foobaz" , message_->field(2)->lowercase_name()); - EXPECT_EQ("foofoo" , message_->field(3)->lowercase_name()); - EXPECT_EQ("foobar" , message_->field(4)->lowercase_name()); - - EXPECT_EQ("bar_foo", message_->extension(0)->lowercase_name()); - EXPECT_EQ("barbar" , message_->extension(1)->lowercase_name()); - EXPECT_EQ("barbaz" , message_->extension(2)->lowercase_name()); - EXPECT_EQ("barfoo" , message_->extension(3)->lowercase_name()); - EXPECT_EQ("barbar" , message_->extension(4)->lowercase_name()); - - EXPECT_EQ("baz_foo", file_->extension(0)->lowercase_name()); - EXPECT_EQ("bazbar" , file_->extension(1)->lowercase_name()); - EXPECT_EQ("bazbaz" , file_->extension(2)->lowercase_name()); - EXPECT_EQ("bazfoo" , file_->extension(3)->lowercase_name()); - EXPECT_EQ("bazbar" , file_->extension(4)->lowercase_name()); -} - -TEST_F(StylizedFieldNamesTest, CamelcaseName) { - EXPECT_EQ("fooFoo", message_->field(0)->camelcase_name()); - EXPECT_EQ("fooBar", message_->field(1)->camelcase_name()); - EXPECT_EQ("fooBaz", message_->field(2)->camelcase_name()); - EXPECT_EQ("fooFoo", message_->field(3)->camelcase_name()); - EXPECT_EQ("foobar", message_->field(4)->camelcase_name()); - - EXPECT_EQ("barFoo", message_->extension(0)->camelcase_name()); - EXPECT_EQ("barBar", message_->extension(1)->camelcase_name()); - EXPECT_EQ("barBaz", message_->extension(2)->camelcase_name()); - EXPECT_EQ("barFoo", message_->extension(3)->camelcase_name()); - EXPECT_EQ("barbar", message_->extension(4)->camelcase_name()); - - EXPECT_EQ("bazFoo", file_->extension(0)->camelcase_name()); - EXPECT_EQ("bazBar", file_->extension(1)->camelcase_name()); - EXPECT_EQ("bazBaz", file_->extension(2)->camelcase_name()); - EXPECT_EQ("bazFoo", file_->extension(3)->camelcase_name()); - EXPECT_EQ("bazbar", file_->extension(4)->camelcase_name()); -} - -TEST_F(StylizedFieldNamesTest, FindByLowercaseName) { - EXPECT_EQ(message_->field(0), - message_->FindFieldByLowercaseName("foo_foo")); - EXPECT_EQ(message_->field(1), - message_->FindFieldByLowercaseName("foobar")); - EXPECT_EQ(message_->field(2), - message_->FindFieldByLowercaseName("foobaz")); - EXPECT_TRUE(message_->FindFieldByLowercaseName("FooBar") == NULL); - EXPECT_TRUE(message_->FindFieldByLowercaseName("fooBaz") == NULL); - EXPECT_TRUE(message_->FindFieldByLowercaseName("bar_foo") == NULL); - EXPECT_TRUE(message_->FindFieldByLowercaseName("nosuchfield") == NULL); - - EXPECT_EQ(message_->extension(0), - message_->FindExtensionByLowercaseName("bar_foo")); - EXPECT_EQ(message_->extension(1), - message_->FindExtensionByLowercaseName("barbar")); - EXPECT_EQ(message_->extension(2), - message_->FindExtensionByLowercaseName("barbaz")); - EXPECT_TRUE(message_->FindExtensionByLowercaseName("BarBar") == NULL); - EXPECT_TRUE(message_->FindExtensionByLowercaseName("barBaz") == NULL); - EXPECT_TRUE(message_->FindExtensionByLowercaseName("foo_foo") == NULL); - EXPECT_TRUE(message_->FindExtensionByLowercaseName("nosuchfield") == NULL); - - EXPECT_EQ(file_->extension(0), - file_->FindExtensionByLowercaseName("baz_foo")); - EXPECT_EQ(file_->extension(1), - file_->FindExtensionByLowercaseName("bazbar")); - EXPECT_EQ(file_->extension(2), - file_->FindExtensionByLowercaseName("bazbaz")); - EXPECT_TRUE(file_->FindExtensionByLowercaseName("BazBar") == NULL); - EXPECT_TRUE(file_->FindExtensionByLowercaseName("bazBaz") == NULL); - EXPECT_TRUE(file_->FindExtensionByLowercaseName("nosuchfield") == NULL); -} - -TEST_F(StylizedFieldNamesTest, FindByCamelcaseName) { - EXPECT_EQ(message_->field(0), - message_->FindFieldByCamelcaseName("fooFoo")); - EXPECT_EQ(message_->field(1), - message_->FindFieldByCamelcaseName("fooBar")); - EXPECT_EQ(message_->field(2), - message_->FindFieldByCamelcaseName("fooBaz")); - EXPECT_TRUE(message_->FindFieldByCamelcaseName("foo_foo") == NULL); - EXPECT_TRUE(message_->FindFieldByCamelcaseName("FooBar") == NULL); - EXPECT_TRUE(message_->FindFieldByCamelcaseName("barFoo") == NULL); - EXPECT_TRUE(message_->FindFieldByCamelcaseName("nosuchfield") == NULL); - - EXPECT_EQ(message_->extension(0), - message_->FindExtensionByCamelcaseName("barFoo")); - EXPECT_EQ(message_->extension(1), - message_->FindExtensionByCamelcaseName("barBar")); - EXPECT_EQ(message_->extension(2), - message_->FindExtensionByCamelcaseName("barBaz")); - EXPECT_TRUE(message_->FindExtensionByCamelcaseName("bar_foo") == NULL); - EXPECT_TRUE(message_->FindExtensionByCamelcaseName("BarBar") == NULL); - EXPECT_TRUE(message_->FindExtensionByCamelcaseName("fooFoo") == NULL); - EXPECT_TRUE(message_->FindExtensionByCamelcaseName("nosuchfield") == NULL); - - EXPECT_EQ(file_->extension(0), - file_->FindExtensionByCamelcaseName("bazFoo")); - EXPECT_EQ(file_->extension(1), - file_->FindExtensionByCamelcaseName("bazBar")); - EXPECT_EQ(file_->extension(2), - file_->FindExtensionByCamelcaseName("bazBaz")); - EXPECT_TRUE(file_->FindExtensionByCamelcaseName("baz_foo") == NULL); - EXPECT_TRUE(file_->FindExtensionByCamelcaseName("BazBar") == NULL); - EXPECT_TRUE(file_->FindExtensionByCamelcaseName("nosuchfield") == NULL); -} - -// =================================================================== - -// Test enum descriptors. -class EnumDescriptorTest : public testing::Test { - protected: - virtual void SetUp() { - // Build descriptors for the following definitions: - // - // // in "foo.proto" - // enum TestEnum { - // FOO = 1; - // BAR = 2; - // } - // - // // in "bar.proto" - // package corge.grault; - // enum TestEnum2 { - // FOO = 1; - // BAZ = 3; - // } - // - // TestEnum2 is primarily here to test FindValueByName and friends. - // All enums created from the same DescriptorPool share the same lookup - // table, so we need to insure that they don't interfere. - - // TestEnum - FileDescriptorProto foo_file; - foo_file.set_name("foo.proto"); - - EnumDescriptorProto* enum_proto = AddEnum(&foo_file, "TestEnum"); - AddEnumValue(enum_proto, "FOO", 1); - AddEnumValue(enum_proto, "BAR", 2); - - // TestEnum2 - FileDescriptorProto bar_file; - bar_file.set_name("bar.proto"); - bar_file.set_package("corge.grault"); - - EnumDescriptorProto* enum2_proto = AddEnum(&bar_file, "TestEnum2"); - AddEnumValue(enum2_proto, "FOO", 1); - AddEnumValue(enum2_proto, "BAZ", 3); - - // Build the descriptors and get the pointers. - foo_file_ = pool_.BuildFile(foo_file); - ASSERT_TRUE(foo_file_ != NULL); - - bar_file_ = pool_.BuildFile(bar_file); - ASSERT_TRUE(bar_file_ != NULL); - - ASSERT_EQ(1, foo_file_->enum_type_count()); - enum_ = foo_file_->enum_type(0); - - ASSERT_EQ(2, enum_->value_count()); - foo_ = enum_->value(0); - bar_ = enum_->value(1); - - ASSERT_EQ(1, bar_file_->enum_type_count()); - enum2_ = bar_file_->enum_type(0); - - ASSERT_EQ(2, enum2_->value_count()); - foo2_ = enum2_->value(0); - baz2_ = enum2_->value(1); - } - - DescriptorPool pool_; - - const FileDescriptor* foo_file_; - const FileDescriptor* bar_file_; - - const EnumDescriptor* enum_; - const EnumDescriptor* enum2_; - - const EnumValueDescriptor* foo_; - const EnumValueDescriptor* bar_; - - const EnumValueDescriptor* foo2_; - const EnumValueDescriptor* baz2_; -}; - -TEST_F(EnumDescriptorTest, Name) { - EXPECT_EQ("TestEnum", enum_->name()); - EXPECT_EQ("TestEnum", enum_->full_name()); - EXPECT_EQ(foo_file_, enum_->file()); - - EXPECT_EQ("TestEnum2", enum2_->name()); - EXPECT_EQ("corge.grault.TestEnum2", enum2_->full_name()); - EXPECT_EQ(bar_file_, enum2_->file()); -} - -TEST_F(EnumDescriptorTest, ContainingType) { - EXPECT_TRUE(enum_->containing_type() == NULL); - EXPECT_TRUE(enum2_->containing_type() == NULL); -} - -TEST_F(EnumDescriptorTest, ValuesByIndex) { - ASSERT_EQ(2, enum_->value_count()); - EXPECT_EQ(foo_, enum_->value(0)); - EXPECT_EQ(bar_, enum_->value(1)); -} - -TEST_F(EnumDescriptorTest, FindValueByName) { - EXPECT_EQ(foo_ , enum_ ->FindValueByName("FOO")); - EXPECT_EQ(bar_ , enum_ ->FindValueByName("BAR")); - EXPECT_EQ(foo2_, enum2_->FindValueByName("FOO")); - EXPECT_EQ(baz2_, enum2_->FindValueByName("BAZ")); - - EXPECT_TRUE(enum_ ->FindValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(enum_ ->FindValueByName("BAZ" ) == NULL); - EXPECT_TRUE(enum2_->FindValueByName("BAR" ) == NULL); -} - -TEST_F(EnumDescriptorTest, FindValueByNumber) { - EXPECT_EQ(foo_ , enum_ ->FindValueByNumber(1)); - EXPECT_EQ(bar_ , enum_ ->FindValueByNumber(2)); - EXPECT_EQ(foo2_, enum2_->FindValueByNumber(1)); - EXPECT_EQ(baz2_, enum2_->FindValueByNumber(3)); - - EXPECT_TRUE(enum_ ->FindValueByNumber(416) == NULL); - EXPECT_TRUE(enum_ ->FindValueByNumber(3) == NULL); - EXPECT_TRUE(enum2_->FindValueByNumber(2) == NULL); -} - -TEST_F(EnumDescriptorTest, ValueName) { - EXPECT_EQ("FOO", foo_->name()); - EXPECT_EQ("BAR", bar_->name()); -} - -TEST_F(EnumDescriptorTest, ValueFullName) { - EXPECT_EQ("FOO", foo_->full_name()); - EXPECT_EQ("BAR", bar_->full_name()); - EXPECT_EQ("corge.grault.FOO", foo2_->full_name()); - EXPECT_EQ("corge.grault.BAZ", baz2_->full_name()); -} - -TEST_F(EnumDescriptorTest, ValueIndex) { - EXPECT_EQ(0, foo_->index()); - EXPECT_EQ(1, bar_->index()); -} - -TEST_F(EnumDescriptorTest, ValueNumber) { - EXPECT_EQ(1, foo_->number()); - EXPECT_EQ(2, bar_->number()); -} - -TEST_F(EnumDescriptorTest, ValueType) { - EXPECT_EQ(enum_ , foo_ ->type()); - EXPECT_EQ(enum_ , bar_ ->type()); - EXPECT_EQ(enum2_, foo2_->type()); - EXPECT_EQ(enum2_, baz2_->type()); -} - -// =================================================================== - -// Test service descriptors. -class ServiceDescriptorTest : public testing::Test { - protected: - virtual void SetUp() { - // Build descriptors for the following messages and service: - // // in "foo.proto" - // message FooRequest {} - // message FooResponse {} - // message BarRequest {} - // message BarResponse {} - // message BazRequest {} - // message BazResponse {} - // - // service TestService { - // rpc Foo(FooRequest) returns (FooResponse); - // rpc Bar(BarRequest) returns (BarResponse); - // } - // - // // in "bar.proto" - // package corge.grault - // service TestService2 { - // rpc Foo(FooRequest) returns (FooResponse); - // rpc Baz(BazRequest) returns (BazResponse); - // } - - FileDescriptorProto foo_file; - foo_file.set_name("foo.proto"); - - AddMessage(&foo_file, "FooRequest"); - AddMessage(&foo_file, "FooResponse"); - AddMessage(&foo_file, "BarRequest"); - AddMessage(&foo_file, "BarResponse"); - AddMessage(&foo_file, "BazRequest"); - AddMessage(&foo_file, "BazResponse"); - - ServiceDescriptorProto* service = AddService(&foo_file, "TestService"); - AddMethod(service, "Foo", "FooRequest", "FooResponse"); - AddMethod(service, "Bar", "BarRequest", "BarResponse"); - - FileDescriptorProto bar_file; - bar_file.set_name("bar.proto"); - bar_file.set_package("corge.grault"); - bar_file.add_dependency("foo.proto"); - - ServiceDescriptorProto* service2 = AddService(&bar_file, "TestService2"); - AddMethod(service2, "Foo", "FooRequest", "FooResponse"); - AddMethod(service2, "Baz", "BazRequest", "BazResponse"); - - // Build the descriptors and get the pointers. - foo_file_ = pool_.BuildFile(foo_file); - ASSERT_TRUE(foo_file_ != NULL); - - bar_file_ = pool_.BuildFile(bar_file); - ASSERT_TRUE(bar_file_ != NULL); - - ASSERT_EQ(6, foo_file_->message_type_count()); - foo_request_ = foo_file_->message_type(0); - foo_response_ = foo_file_->message_type(1); - bar_request_ = foo_file_->message_type(2); - bar_response_ = foo_file_->message_type(3); - baz_request_ = foo_file_->message_type(4); - baz_response_ = foo_file_->message_type(5); - - ASSERT_EQ(1, foo_file_->service_count()); - service_ = foo_file_->service(0); - - ASSERT_EQ(2, service_->method_count()); - foo_ = service_->method(0); - bar_ = service_->method(1); - - ASSERT_EQ(1, bar_file_->service_count()); - service2_ = bar_file_->service(0); - - ASSERT_EQ(2, service2_->method_count()); - foo2_ = service2_->method(0); - baz2_ = service2_->method(1); - } - - DescriptorPool pool_; - - const FileDescriptor* foo_file_; - const FileDescriptor* bar_file_; - - const Descriptor* foo_request_; - const Descriptor* foo_response_; - const Descriptor* bar_request_; - const Descriptor* bar_response_; - const Descriptor* baz_request_; - const Descriptor* baz_response_; - - const ServiceDescriptor* service_; - const ServiceDescriptor* service2_; - - const MethodDescriptor* foo_; - const MethodDescriptor* bar_; - - const MethodDescriptor* foo2_; - const MethodDescriptor* baz2_; -}; - -TEST_F(ServiceDescriptorTest, Name) { - EXPECT_EQ("TestService", service_->name()); - EXPECT_EQ("TestService", service_->full_name()); - EXPECT_EQ(foo_file_, service_->file()); - - EXPECT_EQ("TestService2", service2_->name()); - EXPECT_EQ("corge.grault.TestService2", service2_->full_name()); - EXPECT_EQ(bar_file_, service2_->file()); -} - -TEST_F(ServiceDescriptorTest, MethodsByIndex) { - ASSERT_EQ(2, service_->method_count()); - EXPECT_EQ(foo_, service_->method(0)); - EXPECT_EQ(bar_, service_->method(1)); -} - -TEST_F(ServiceDescriptorTest, FindMethodByName) { - EXPECT_EQ(foo_ , service_ ->FindMethodByName("Foo")); - EXPECT_EQ(bar_ , service_ ->FindMethodByName("Bar")); - EXPECT_EQ(foo2_, service2_->FindMethodByName("Foo")); - EXPECT_EQ(baz2_, service2_->FindMethodByName("Baz")); - - EXPECT_TRUE(service_ ->FindMethodByName("NoSuchMethod") == NULL); - EXPECT_TRUE(service_ ->FindMethodByName("Baz" ) == NULL); - EXPECT_TRUE(service2_->FindMethodByName("Bar" ) == NULL); -} - -TEST_F(ServiceDescriptorTest, MethodName) { - EXPECT_EQ("Foo", foo_->name()); - EXPECT_EQ("Bar", bar_->name()); -} - -TEST_F(ServiceDescriptorTest, MethodFullName) { - EXPECT_EQ("TestService.Foo", foo_->full_name()); - EXPECT_EQ("TestService.Bar", bar_->full_name()); - EXPECT_EQ("corge.grault.TestService2.Foo", foo2_->full_name()); - EXPECT_EQ("corge.grault.TestService2.Baz", baz2_->full_name()); -} - -TEST_F(ServiceDescriptorTest, MethodIndex) { - EXPECT_EQ(0, foo_->index()); - EXPECT_EQ(1, bar_->index()); -} - -TEST_F(ServiceDescriptorTest, MethodParent) { - EXPECT_EQ(service_, foo_->service()); - EXPECT_EQ(service_, bar_->service()); -} - -TEST_F(ServiceDescriptorTest, MethodInputType) { - EXPECT_EQ(foo_request_, foo_->input_type()); - EXPECT_EQ(bar_request_, bar_->input_type()); -} - -TEST_F(ServiceDescriptorTest, MethodOutputType) { - EXPECT_EQ(foo_response_, foo_->output_type()); - EXPECT_EQ(bar_response_, bar_->output_type()); -} - -// =================================================================== - -// Test nested types. -class NestedDescriptorTest : public testing::Test { - protected: - virtual void SetUp() { - // Build descriptors for the following definitions: - // - // // in "foo.proto" - // message TestMessage { - // message Foo {} - // message Bar {} - // enum Baz { A = 1; } - // enum Qux { B = 1; } - // } - // - // // in "bar.proto" - // package corge.grault; - // message TestMessage2 { - // message Foo {} - // message Baz {} - // enum Qux { A = 1; } - // enum Quux { C = 1; } - // } - // - // TestMessage2 is primarily here to test FindNestedTypeByName and friends. - // All messages created from the same DescriptorPool share the same lookup - // table, so we need to insure that they don't interfere. - // - // We add enum values to the enums in order to test searching for enum - // values across a message's scope. - - FileDescriptorProto foo_file; - foo_file.set_name("foo.proto"); - - DescriptorProto* message = AddMessage(&foo_file, "TestMessage"); - AddNestedMessage(message, "Foo"); - AddNestedMessage(message, "Bar"); - EnumDescriptorProto* baz = AddNestedEnum(message, "Baz"); - AddEnumValue(baz, "A", 1); - EnumDescriptorProto* qux = AddNestedEnum(message, "Qux"); - AddEnumValue(qux, "B", 1); - - FileDescriptorProto bar_file; - bar_file.set_name("bar.proto"); - bar_file.set_package("corge.grault"); - - DescriptorProto* message2 = AddMessage(&bar_file, "TestMessage2"); - AddNestedMessage(message2, "Foo"); - AddNestedMessage(message2, "Baz"); - EnumDescriptorProto* qux2 = AddNestedEnum(message2, "Qux"); - AddEnumValue(qux2, "A", 1); - EnumDescriptorProto* quux2 = AddNestedEnum(message2, "Quux"); - AddEnumValue(quux2, "C", 1); - - // Build the descriptors and get the pointers. - foo_file_ = pool_.BuildFile(foo_file); - ASSERT_TRUE(foo_file_ != NULL); - - bar_file_ = pool_.BuildFile(bar_file); - ASSERT_TRUE(bar_file_ != NULL); - - ASSERT_EQ(1, foo_file_->message_type_count()); - message_ = foo_file_->message_type(0); - - ASSERT_EQ(2, message_->nested_type_count()); - foo_ = message_->nested_type(0); - bar_ = message_->nested_type(1); - - ASSERT_EQ(2, message_->enum_type_count()); - baz_ = message_->enum_type(0); - qux_ = message_->enum_type(1); - - ASSERT_EQ(1, baz_->value_count()); - a_ = baz_->value(0); - ASSERT_EQ(1, qux_->value_count()); - b_ = qux_->value(0); - - ASSERT_EQ(1, bar_file_->message_type_count()); - message2_ = bar_file_->message_type(0); - - ASSERT_EQ(2, message2_->nested_type_count()); - foo2_ = message2_->nested_type(0); - baz2_ = message2_->nested_type(1); - - ASSERT_EQ(2, message2_->enum_type_count()); - qux2_ = message2_->enum_type(0); - quux2_ = message2_->enum_type(1); - - ASSERT_EQ(1, qux2_->value_count()); - a2_ = qux2_->value(0); - ASSERT_EQ(1, quux2_->value_count()); - c2_ = quux2_->value(0); - } - - DescriptorPool pool_; - - const FileDescriptor* foo_file_; - const FileDescriptor* bar_file_; - - const Descriptor* message_; - const Descriptor* message2_; - - const Descriptor* foo_; - const Descriptor* bar_; - const EnumDescriptor* baz_; - const EnumDescriptor* qux_; - const EnumValueDescriptor* a_; - const EnumValueDescriptor* b_; - - const Descriptor* foo2_; - const Descriptor* baz2_; - const EnumDescriptor* qux2_; - const EnumDescriptor* quux2_; - const EnumValueDescriptor* a2_; - const EnumValueDescriptor* c2_; -}; - -TEST_F(NestedDescriptorTest, MessageName) { - EXPECT_EQ("Foo", foo_ ->name()); - EXPECT_EQ("Bar", bar_ ->name()); - EXPECT_EQ("Foo", foo2_->name()); - EXPECT_EQ("Baz", baz2_->name()); - - EXPECT_EQ("TestMessage.Foo", foo_->full_name()); - EXPECT_EQ("TestMessage.Bar", bar_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Foo", foo2_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Baz", baz2_->full_name()); -} - -TEST_F(NestedDescriptorTest, MessageContainingType) { - EXPECT_EQ(message_ , foo_ ->containing_type()); - EXPECT_EQ(message_ , bar_ ->containing_type()); - EXPECT_EQ(message2_, foo2_->containing_type()); - EXPECT_EQ(message2_, baz2_->containing_type()); -} - -TEST_F(NestedDescriptorTest, NestedMessagesByIndex) { - ASSERT_EQ(2, message_->nested_type_count()); - EXPECT_EQ(foo_, message_->nested_type(0)); - EXPECT_EQ(bar_, message_->nested_type(1)); -} - -TEST_F(NestedDescriptorTest, FindFieldByNameDoesntFindNestedTypes) { - EXPECT_TRUE(message_->FindFieldByName("Foo") == NULL); - EXPECT_TRUE(message_->FindFieldByName("Qux") == NULL); - EXPECT_TRUE(message_->FindExtensionByName("Foo") == NULL); - EXPECT_TRUE(message_->FindExtensionByName("Qux") == NULL); -} - -TEST_F(NestedDescriptorTest, FindNestedTypeByName) { - EXPECT_EQ(foo_ , message_ ->FindNestedTypeByName("Foo")); - EXPECT_EQ(bar_ , message_ ->FindNestedTypeByName("Bar")); - EXPECT_EQ(foo2_, message2_->FindNestedTypeByName("Foo")); - EXPECT_EQ(baz2_, message2_->FindNestedTypeByName("Baz")); - - EXPECT_TRUE(message_ ->FindNestedTypeByName("NoSuchType") == NULL); - EXPECT_TRUE(message_ ->FindNestedTypeByName("Baz" ) == NULL); - EXPECT_TRUE(message2_->FindNestedTypeByName("Bar" ) == NULL); - - EXPECT_TRUE(message_->FindNestedTypeByName("Qux") == NULL); -} - -TEST_F(NestedDescriptorTest, EnumName) { - EXPECT_EQ("Baz" , baz_ ->name()); - EXPECT_EQ("Qux" , qux_ ->name()); - EXPECT_EQ("Qux" , qux2_->name()); - EXPECT_EQ("Quux", quux2_->name()); - - EXPECT_EQ("TestMessage.Baz", baz_->full_name()); - EXPECT_EQ("TestMessage.Qux", qux_->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Qux" , qux2_ ->full_name()); - EXPECT_EQ("corge.grault.TestMessage2.Quux", quux2_->full_name()); -} - -TEST_F(NestedDescriptorTest, EnumContainingType) { - EXPECT_EQ(message_ , baz_ ->containing_type()); - EXPECT_EQ(message_ , qux_ ->containing_type()); - EXPECT_EQ(message2_, qux2_ ->containing_type()); - EXPECT_EQ(message2_, quux2_->containing_type()); -} - -TEST_F(NestedDescriptorTest, NestedEnumsByIndex) { - ASSERT_EQ(2, message_->nested_type_count()); - EXPECT_EQ(foo_, message_->nested_type(0)); - EXPECT_EQ(bar_, message_->nested_type(1)); -} - -TEST_F(NestedDescriptorTest, FindEnumTypeByName) { - EXPECT_EQ(baz_ , message_ ->FindEnumTypeByName("Baz" )); - EXPECT_EQ(qux_ , message_ ->FindEnumTypeByName("Qux" )); - EXPECT_EQ(qux2_ , message2_->FindEnumTypeByName("Qux" )); - EXPECT_EQ(quux2_, message2_->FindEnumTypeByName("Quux")); - - EXPECT_TRUE(message_ ->FindEnumTypeByName("NoSuchType") == NULL); - EXPECT_TRUE(message_ ->FindEnumTypeByName("Quux" ) == NULL); - EXPECT_TRUE(message2_->FindEnumTypeByName("Baz" ) == NULL); - - EXPECT_TRUE(message_->FindEnumTypeByName("Foo") == NULL); -} - -TEST_F(NestedDescriptorTest, FindEnumValueByName) { - EXPECT_EQ(a_ , message_ ->FindEnumValueByName("A")); - EXPECT_EQ(b_ , message_ ->FindEnumValueByName("B")); - EXPECT_EQ(a2_, message2_->FindEnumValueByName("A")); - EXPECT_EQ(c2_, message2_->FindEnumValueByName("C")); - - EXPECT_TRUE(message_ ->FindEnumValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(message_ ->FindEnumValueByName("C" ) == NULL); - EXPECT_TRUE(message2_->FindEnumValueByName("B" ) == NULL); - - EXPECT_TRUE(message_->FindEnumValueByName("Foo") == NULL); -} - -// =================================================================== - -// Test extensions. -class ExtensionDescriptorTest : public testing::Test { - protected: - virtual void SetUp() { - // Build descriptors for the following definitions: - // - // enum Baz {} - // message Qux {} - // - // message Foo { - // extensions 10 to 19; - // extensions 30 to 39; - // } - // extends Foo with optional int32 foo_int32 = 10; - // extends Foo with repeated TestEnum foo_enum = 19; - // message Bar { - // extends Foo with optional Qux foo_message = 30; - // // (using Qux as the group type) - // extends Foo with repeated group foo_group = 39; - // } - - FileDescriptorProto foo_file; - foo_file.set_name("foo.proto"); - - AddEmptyEnum(&foo_file, "Baz"); - AddMessage(&foo_file, "Qux"); - - DescriptorProto* foo = AddMessage(&foo_file, "Foo"); - AddExtensionRange(foo, 10, 20); - AddExtensionRange(foo, 30, 40); - - AddExtension(&foo_file, "Foo", "foo_int32", 10, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - AddExtension(&foo_file, "Foo", "foo_enum", 19, - FieldDescriptorProto::LABEL_REPEATED, - FieldDescriptorProto::TYPE_ENUM) - ->set_type_name("Baz"); - - DescriptorProto* bar = AddMessage(&foo_file, "Bar"); - AddNestedExtension(bar, "Foo", "foo_message", 30, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_MESSAGE) - ->set_type_name("Qux"); - AddNestedExtension(bar, "Foo", "foo_group", 39, - FieldDescriptorProto::LABEL_REPEATED, - FieldDescriptorProto::TYPE_GROUP) - ->set_type_name("Qux"); - - // Build the descriptors and get the pointers. - foo_file_ = pool_.BuildFile(foo_file); - ASSERT_TRUE(foo_file_ != NULL); - - ASSERT_EQ(1, foo_file_->enum_type_count()); - baz_ = foo_file_->enum_type(0); - - ASSERT_EQ(3, foo_file_->message_type_count()); - qux_ = foo_file_->message_type(0); - foo_ = foo_file_->message_type(1); - bar_ = foo_file_->message_type(2); - } - - DescriptorPool pool_; - - const FileDescriptor* foo_file_; - - const Descriptor* foo_; - const Descriptor* bar_; - const EnumDescriptor* baz_; - const Descriptor* qux_; -}; - -TEST_F(ExtensionDescriptorTest, ExtensionRanges) { - EXPECT_EQ(0, bar_->extension_range_count()); - ASSERT_EQ(2, foo_->extension_range_count()); - - EXPECT_EQ(10, foo_->extension_range(0)->start); - EXPECT_EQ(30, foo_->extension_range(1)->start); - - EXPECT_EQ(20, foo_->extension_range(0)->end); - EXPECT_EQ(40, foo_->extension_range(1)->end); -}; - -TEST_F(ExtensionDescriptorTest, Extensions) { - EXPECT_EQ(0, foo_->extension_count()); - ASSERT_EQ(2, foo_file_->extension_count()); - ASSERT_EQ(2, bar_->extension_count()); - - EXPECT_TRUE(foo_file_->extension(0)->is_extension()); - EXPECT_TRUE(foo_file_->extension(1)->is_extension()); - EXPECT_TRUE(bar_->extension(0)->is_extension()); - EXPECT_TRUE(bar_->extension(1)->is_extension()); - - EXPECT_EQ("foo_int32" , foo_file_->extension(0)->name()); - EXPECT_EQ("foo_enum" , foo_file_->extension(1)->name()); - EXPECT_EQ("foo_message", bar_->extension(0)->name()); - EXPECT_EQ("foo_group" , bar_->extension(1)->name()); - - EXPECT_EQ(10, foo_file_->extension(0)->number()); - EXPECT_EQ(19, foo_file_->extension(1)->number()); - EXPECT_EQ(30, bar_->extension(0)->number()); - EXPECT_EQ(39, bar_->extension(1)->number()); - - EXPECT_EQ(FieldDescriptor::TYPE_INT32 , foo_file_->extension(0)->type()); - EXPECT_EQ(FieldDescriptor::TYPE_ENUM , foo_file_->extension(1)->type()); - EXPECT_EQ(FieldDescriptor::TYPE_MESSAGE, bar_->extension(0)->type()); - EXPECT_EQ(FieldDescriptor::TYPE_GROUP , bar_->extension(1)->type()); - - EXPECT_EQ(baz_, foo_file_->extension(1)->enum_type()); - EXPECT_EQ(qux_, bar_->extension(0)->message_type()); - EXPECT_EQ(qux_, bar_->extension(1)->message_type()); - - EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, foo_file_->extension(0)->label()); - EXPECT_EQ(FieldDescriptor::LABEL_REPEATED, foo_file_->extension(1)->label()); - EXPECT_EQ(FieldDescriptor::LABEL_OPTIONAL, bar_->extension(0)->label()); - EXPECT_EQ(FieldDescriptor::LABEL_REPEATED, bar_->extension(1)->label()); - - EXPECT_EQ(foo_, foo_file_->extension(0)->containing_type()); - EXPECT_EQ(foo_, foo_file_->extension(1)->containing_type()); - EXPECT_EQ(foo_, bar_->extension(0)->containing_type()); - EXPECT_EQ(foo_, bar_->extension(1)->containing_type()); - - EXPECT_TRUE(foo_file_->extension(0)->extension_scope() == NULL); - EXPECT_TRUE(foo_file_->extension(1)->extension_scope() == NULL); - EXPECT_EQ(bar_, bar_->extension(0)->extension_scope()); - EXPECT_EQ(bar_, bar_->extension(1)->extension_scope()); -}; - -TEST_F(ExtensionDescriptorTest, IsExtensionNumber) { - EXPECT_FALSE(foo_->IsExtensionNumber( 9)); - EXPECT_TRUE (foo_->IsExtensionNumber(10)); - EXPECT_TRUE (foo_->IsExtensionNumber(19)); - EXPECT_FALSE(foo_->IsExtensionNumber(20)); - EXPECT_FALSE(foo_->IsExtensionNumber(29)); - EXPECT_TRUE (foo_->IsExtensionNumber(30)); - EXPECT_TRUE (foo_->IsExtensionNumber(39)); - EXPECT_FALSE(foo_->IsExtensionNumber(40)); -} - -TEST_F(ExtensionDescriptorTest, FindExtensionByName) { - // Note that FileDescriptor::FindExtensionByName() is tested by - // FileDescriptorTest. - ASSERT_EQ(2, bar_->extension_count()); - - EXPECT_EQ(bar_->extension(0), bar_->FindExtensionByName("foo_message")); - EXPECT_EQ(bar_->extension(1), bar_->FindExtensionByName("foo_group" )); - - EXPECT_TRUE(bar_->FindExtensionByName("no_such_extension") == NULL); - EXPECT_TRUE(foo_->FindExtensionByName("foo_int32") == NULL); - EXPECT_TRUE(foo_->FindExtensionByName("foo_message") == NULL); -} - -TEST_F(ExtensionDescriptorTest, FindAllExtensions) { - vector extensions; - pool_.FindAllExtensions(foo_, &extensions); - ASSERT_EQ(4, extensions.size()); - EXPECT_EQ(10, extensions[0]->number()); - EXPECT_EQ(19, extensions[1]->number()); - EXPECT_EQ(30, extensions[2]->number()); - EXPECT_EQ(39, extensions[3]->number()); -} - -// =================================================================== - -class MiscTest : public testing::Test { - protected: - // Function which makes a field of the given type just to find out what its - // cpp_type is. - FieldDescriptor::CppType GetCppTypeForFieldType(FieldDescriptor::Type type) { - FileDescriptorProto file_proto; - file_proto.set_name("foo.proto"); - AddEmptyEnum(&file_proto, "DummyEnum"); - - DescriptorProto* message = AddMessage(&file_proto, "TestMessage"); - FieldDescriptorProto* field = - AddField(message, "foo", 1, FieldDescriptorProto::LABEL_OPTIONAL, - static_cast(static_cast(type))); - - if (type == FieldDescriptor::TYPE_MESSAGE || - type == FieldDescriptor::TYPE_GROUP) { - field->set_type_name("TestMessage"); - } else if (type == FieldDescriptor::TYPE_ENUM) { - field->set_type_name("DummyEnum"); - } - - // Build the descriptors and get the pointers. - DescriptorPool pool; - const FileDescriptor* file = pool.BuildFile(file_proto); - - if (file != NULL && - file->message_type_count() == 1 && - file->message_type(0)->field_count() == 1) { - return file->message_type(0)->field(0)->cpp_type(); - } else { - return static_cast(0); - } - } -}; - -TEST_F(MiscTest, CppTypes) { - // Test that CPP types are assigned correctly. - - typedef FieldDescriptor FD; // avoid ugly line wrapping - - EXPECT_EQ(FD::CPPTYPE_DOUBLE , GetCppTypeForFieldType(FD::TYPE_DOUBLE )); - EXPECT_EQ(FD::CPPTYPE_FLOAT , GetCppTypeForFieldType(FD::TYPE_FLOAT )); - EXPECT_EQ(FD::CPPTYPE_INT64 , GetCppTypeForFieldType(FD::TYPE_INT64 )); - EXPECT_EQ(FD::CPPTYPE_UINT64 , GetCppTypeForFieldType(FD::TYPE_UINT64 )); - EXPECT_EQ(FD::CPPTYPE_INT32 , GetCppTypeForFieldType(FD::TYPE_INT32 )); - EXPECT_EQ(FD::CPPTYPE_UINT64 , GetCppTypeForFieldType(FD::TYPE_FIXED64 )); - EXPECT_EQ(FD::CPPTYPE_UINT32 , GetCppTypeForFieldType(FD::TYPE_FIXED32 )); - EXPECT_EQ(FD::CPPTYPE_BOOL , GetCppTypeForFieldType(FD::TYPE_BOOL )); - EXPECT_EQ(FD::CPPTYPE_STRING , GetCppTypeForFieldType(FD::TYPE_STRING )); - EXPECT_EQ(FD::CPPTYPE_MESSAGE, GetCppTypeForFieldType(FD::TYPE_GROUP )); - EXPECT_EQ(FD::CPPTYPE_MESSAGE, GetCppTypeForFieldType(FD::TYPE_MESSAGE )); - EXPECT_EQ(FD::CPPTYPE_STRING , GetCppTypeForFieldType(FD::TYPE_BYTES )); - EXPECT_EQ(FD::CPPTYPE_UINT32 , GetCppTypeForFieldType(FD::TYPE_UINT32 )); - EXPECT_EQ(FD::CPPTYPE_ENUM , GetCppTypeForFieldType(FD::TYPE_ENUM )); - EXPECT_EQ(FD::CPPTYPE_INT32 , GetCppTypeForFieldType(FD::TYPE_SFIXED32)); - EXPECT_EQ(FD::CPPTYPE_INT64 , GetCppTypeForFieldType(FD::TYPE_SFIXED64)); - EXPECT_EQ(FD::CPPTYPE_INT32 , GetCppTypeForFieldType(FD::TYPE_SINT32 )); - EXPECT_EQ(FD::CPPTYPE_INT64 , GetCppTypeForFieldType(FD::TYPE_SINT64 )); -} - -TEST_F(MiscTest, DefaultValues) { - // Test that setting default values works. - FileDescriptorProto file_proto; - file_proto.set_name("foo.proto"); - - EnumDescriptorProto* enum_type_proto = AddEnum(&file_proto, "DummyEnum"); - AddEnumValue(enum_type_proto, "A", 1); - AddEnumValue(enum_type_proto, "B", 2); - - DescriptorProto* message_proto = AddMessage(&file_proto, "TestMessage"); - - typedef FieldDescriptorProto FD; // avoid ugly line wrapping - const FD::Label label = FD::LABEL_OPTIONAL; - - // Create fields of every CPP type with default values. - AddField(message_proto, "int32" , 1, label, FD::TYPE_INT32 ) - ->set_default_value("-1"); - AddField(message_proto, "int64" , 2, label, FD::TYPE_INT64 ) - ->set_default_value("-1000000000000"); - AddField(message_proto, "uint32", 3, label, FD::TYPE_UINT32) - ->set_default_value("42"); - AddField(message_proto, "uint64", 4, label, FD::TYPE_UINT64) - ->set_default_value("2000000000000"); - AddField(message_proto, "float" , 5, label, FD::TYPE_FLOAT ) - ->set_default_value("4.5"); - AddField(message_proto, "double", 6, label, FD::TYPE_DOUBLE) - ->set_default_value("10e100"); - AddField(message_proto, "bool" , 7, label, FD::TYPE_BOOL ) - ->set_default_value("true"); - AddField(message_proto, "string", 8, label, FD::TYPE_STRING) - ->set_default_value("hello"); - AddField(message_proto, "data" , 9, label, FD::TYPE_BYTES ) - ->set_default_value("\\001\\002\\003"); - - FieldDescriptorProto* enum_field = - AddField(message_proto, "enum", 10, label, FD::TYPE_ENUM); - enum_field->set_type_name("DummyEnum"); - enum_field->set_default_value("B"); - - // Strings are allowed to have empty defaults. (At one point, due to - // a bug, empty defaults for strings were rejected. Oops.) - AddField(message_proto, "empty_string", 11, label, FD::TYPE_STRING) - ->set_default_value(""); - - // Add a second set of fields with implicit defalut values. - AddField(message_proto, "implicit_int32" , 21, label, FD::TYPE_INT32 ); - AddField(message_proto, "implicit_int64" , 22, label, FD::TYPE_INT64 ); - AddField(message_proto, "implicit_uint32", 23, label, FD::TYPE_UINT32); - AddField(message_proto, "implicit_uint64", 24, label, FD::TYPE_UINT64); - AddField(message_proto, "implicit_float" , 25, label, FD::TYPE_FLOAT ); - AddField(message_proto, "implicit_double", 26, label, FD::TYPE_DOUBLE); - AddField(message_proto, "implicit_bool" , 27, label, FD::TYPE_BOOL ); - AddField(message_proto, "implicit_string", 28, label, FD::TYPE_STRING); - AddField(message_proto, "implicit_data" , 29, label, FD::TYPE_BYTES ); - AddField(message_proto, "implicit_enum" , 30, label, FD::TYPE_ENUM) - ->set_type_name("DummyEnum"); - - // Build it. - DescriptorPool pool; - const FileDescriptor* file = pool.BuildFile(file_proto); - ASSERT_TRUE(file != NULL); - - ASSERT_EQ(1, file->enum_type_count()); - const EnumDescriptor* enum_type = file->enum_type(0); - ASSERT_EQ(2, enum_type->value_count()); - const EnumValueDescriptor* enum_value_a = enum_type->value(0); - const EnumValueDescriptor* enum_value_b = enum_type->value(1); - - ASSERT_EQ(1, file->message_type_count()); - const Descriptor* message = file->message_type(0); - - ASSERT_EQ(21, message->field_count()); - - // Check the default values. - ASSERT_TRUE(message->field(0)->has_default_value()); - ASSERT_TRUE(message->field(1)->has_default_value()); - ASSERT_TRUE(message->field(2)->has_default_value()); - ASSERT_TRUE(message->field(3)->has_default_value()); - ASSERT_TRUE(message->field(4)->has_default_value()); - ASSERT_TRUE(message->field(5)->has_default_value()); - ASSERT_TRUE(message->field(6)->has_default_value()); - ASSERT_TRUE(message->field(7)->has_default_value()); - ASSERT_TRUE(message->field(8)->has_default_value()); - ASSERT_TRUE(message->field(9)->has_default_value()); - ASSERT_TRUE(message->field(10)->has_default_value()); - - EXPECT_EQ(-1 , message->field(0)->default_value_int32 ()); - EXPECT_EQ(-GOOGLE_ULONGLONG(1000000000000), - message->field(1)->default_value_int64 ()); - EXPECT_EQ(42 , message->field(2)->default_value_uint32()); - EXPECT_EQ(GOOGLE_ULONGLONG(2000000000000), - message->field(3)->default_value_uint64()); - EXPECT_EQ(4.5 , message->field(4)->default_value_float ()); - EXPECT_EQ(10e100 , message->field(5)->default_value_double()); - EXPECT_EQ(true , message->field(6)->default_value_bool ()); - EXPECT_EQ("hello" , message->field(7)->default_value_string()); - EXPECT_EQ("\001\002\003" , message->field(8)->default_value_string()); - EXPECT_EQ(enum_value_b , message->field(9)->default_value_enum ()); - EXPECT_EQ("" , message->field(10)->default_value_string()); - - ASSERT_FALSE(message->field(11)->has_default_value()); - ASSERT_FALSE(message->field(12)->has_default_value()); - ASSERT_FALSE(message->field(13)->has_default_value()); - ASSERT_FALSE(message->field(14)->has_default_value()); - ASSERT_FALSE(message->field(15)->has_default_value()); - ASSERT_FALSE(message->field(16)->has_default_value()); - ASSERT_FALSE(message->field(17)->has_default_value()); - ASSERT_FALSE(message->field(18)->has_default_value()); - ASSERT_FALSE(message->field(19)->has_default_value()); - ASSERT_FALSE(message->field(20)->has_default_value()); - - EXPECT_EQ(0 , message->field(11)->default_value_int32 ()); - EXPECT_EQ(0 , message->field(12)->default_value_int64 ()); - EXPECT_EQ(0 , message->field(13)->default_value_uint32()); - EXPECT_EQ(0 , message->field(14)->default_value_uint64()); - EXPECT_EQ(0.0f , message->field(15)->default_value_float ()); - EXPECT_EQ(0.0 , message->field(16)->default_value_double()); - EXPECT_EQ(false, message->field(17)->default_value_bool ()); - EXPECT_EQ("" , message->field(18)->default_value_string()); - EXPECT_EQ("" , message->field(19)->default_value_string()); - EXPECT_EQ(enum_value_a, message->field(20)->default_value_enum()); -} - -TEST_F(MiscTest, FieldOptions) { - // Try setting field options. - - FileDescriptorProto file_proto; - file_proto.set_name("foo.proto"); - - DescriptorProto* message_proto = AddMessage(&file_proto, "TestMessage"); - AddField(message_proto, "foo", 1, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - FieldDescriptorProto* bar_proto = - AddField(message_proto, "bar", 2, - FieldDescriptorProto::LABEL_OPTIONAL, - FieldDescriptorProto::TYPE_INT32); - - FieldOptions* options = bar_proto->mutable_options(); - options->set_ctype(FieldOptions::CORD); - - // Build the descriptors and get the pointers. - DescriptorPool pool; - const FileDescriptor* file = pool.BuildFile(file_proto); - ASSERT_TRUE(file != NULL); - - ASSERT_EQ(1, file->message_type_count()); - const Descriptor* message = file->message_type(0); - - ASSERT_EQ(2, message->field_count()); - const FieldDescriptor* foo = message->field(0); - const FieldDescriptor* bar = message->field(1); - - // "foo" had no options set, so it should return the default options. - EXPECT_EQ(&FieldOptions::default_instance(), &foo->options()); - - // "bar" had options set. - EXPECT_NE(&FieldOptions::default_instance(), options); - EXPECT_TRUE(bar->options().has_ctype()); - EXPECT_EQ(FieldOptions::CORD, bar->options().ctype()); -} - -// =================================================================== - -class AllowUnknownDependenciesTest : public testing::Test { - protected: - virtual void SetUp() { - FileDescriptorProto foo_proto, bar_proto; - - pool_.AllowUnknownDependencies(); - - ASSERT_TRUE(TextFormat::ParseFromString( - "name: 'foo.proto'" - "dependency: 'bar.proto'" - "dependency: 'baz.proto'" - "message_type {" - " name: 'Foo'" - " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'Bar' }" - " field { name:'baz' number:2 label:LABEL_OPTIONAL type_name:'Baz' }" - " field { name:'qux' number:3 label:LABEL_OPTIONAL" - " type_name: '.corge.Qux'" - " type: TYPE_ENUM" - " options {" - " uninterpreted_option {" - " name {" - " name_part: 'grault'" - " is_extension: true" - " }" - " positive_int_value: 1234" - " }" - " }" - " }" - "}", - &foo_proto)); - ASSERT_TRUE(TextFormat::ParseFromString( - "name: 'bar.proto'" - "message_type { name: 'Bar' }", - &bar_proto)); - - // Collect pointers to stuff. - bar_file_ = pool_.BuildFile(bar_proto); - ASSERT_TRUE(bar_file_ != NULL); - - ASSERT_EQ(1, bar_file_->message_type_count()); - bar_type_ = bar_file_->message_type(0); - - foo_file_ = pool_.BuildFile(foo_proto); - ASSERT_TRUE(foo_file_ != NULL); - - ASSERT_EQ(1, foo_file_->message_type_count()); - foo_type_ = foo_file_->message_type(0); - - ASSERT_EQ(3, foo_type_->field_count()); - bar_field_ = foo_type_->field(0); - baz_field_ = foo_type_->field(1); - qux_field_ = foo_type_->field(2); - } - - const FileDescriptor* bar_file_; - const Descriptor* bar_type_; - const FileDescriptor* foo_file_; - const Descriptor* foo_type_; - const FieldDescriptor* bar_field_; - const FieldDescriptor* baz_field_; - const FieldDescriptor* qux_field_; - - DescriptorPool pool_; -}; - -TEST_F(AllowUnknownDependenciesTest, PlaceholderFile) { - ASSERT_EQ(2, foo_file_->dependency_count()); - EXPECT_EQ(bar_file_, foo_file_->dependency(0)); - - const FileDescriptor* baz_file = foo_file_->dependency(1); - EXPECT_EQ("baz.proto", baz_file->name()); - EXPECT_EQ(0, baz_file->message_type_count()); - - // Placeholder files should not be findable. - EXPECT_EQ(bar_file_, pool_.FindFileByName(bar_file_->name())); - EXPECT_TRUE(pool_.FindFileByName(baz_file->name()) == NULL); -} - -TEST_F(AllowUnknownDependenciesTest, PlaceholderTypes) { - ASSERT_EQ(FieldDescriptor::TYPE_MESSAGE, bar_field_->type()); - EXPECT_EQ(bar_type_, bar_field_->message_type()); - - ASSERT_EQ(FieldDescriptor::TYPE_MESSAGE, baz_field_->type()); - const Descriptor* baz_type = baz_field_->message_type(); - EXPECT_EQ("Baz", baz_type->name()); - EXPECT_EQ("Baz", baz_type->full_name()); - EXPECT_EQ("Baz.placeholder.proto", baz_type->file()->name()); - EXPECT_EQ(0, baz_type->extension_range_count()); - - ASSERT_EQ(FieldDescriptor::TYPE_ENUM, qux_field_->type()); - const EnumDescriptor* qux_type = qux_field_->enum_type(); - EXPECT_EQ("Qux", qux_type->name()); - EXPECT_EQ("corge.Qux", qux_type->full_name()); - EXPECT_EQ("corge.Qux.placeholder.proto", qux_type->file()->name()); - - // Placeholder types should not be findable. - EXPECT_EQ(bar_type_, pool_.FindMessageTypeByName(bar_type_->full_name())); - EXPECT_TRUE(pool_.FindMessageTypeByName(baz_type->full_name()) == NULL); - EXPECT_TRUE(pool_.FindEnumTypeByName(qux_type->full_name()) == NULL); -} - -TEST_F(AllowUnknownDependenciesTest, CopyTo) { - // FieldDescriptor::CopyTo() should write non-fully-qualified type names - // for placeholder types which were not originally fully-qualified. - FieldDescriptorProto proto; - - // Bar is not a placeholder, so it is fully-qualified. - bar_field_->CopyTo(&proto); - EXPECT_EQ(".Bar", proto.type_name()); - EXPECT_EQ(FieldDescriptorProto::TYPE_MESSAGE, proto.type()); - - // Baz is an unqualified placeholder. - proto.Clear(); - baz_field_->CopyTo(&proto); - EXPECT_EQ("Baz", proto.type_name()); - EXPECT_FALSE(proto.has_type()); - - // Qux is a fully-qualified placeholder. - proto.Clear(); - qux_field_->CopyTo(&proto); - EXPECT_EQ(".corge.Qux", proto.type_name()); - EXPECT_EQ(FieldDescriptorProto::TYPE_ENUM, proto.type()); -} - -TEST_F(AllowUnknownDependenciesTest, CustomOptions) { - // Qux should still have the uninterpreted option attached. - ASSERT_EQ(1, qux_field_->options().uninterpreted_option_size()); - const UninterpretedOption& option = - qux_field_->options().uninterpreted_option(0); - ASSERT_EQ(1, option.name_size()); - EXPECT_EQ("grault", option.name(0).name_part()); -} - -TEST_F(AllowUnknownDependenciesTest, UnknownExtendee) { - // Test that we can extend an unknown type. This is slightly tricky because - // it means that the placeholder type must have an extension range. - - FileDescriptorProto extension_proto; - - ASSERT_TRUE(TextFormat::ParseFromString( - "name: 'extension.proto'" - "extension { extendee: 'UnknownType' name:'some_extension' number:123" - " label:LABEL_OPTIONAL type:TYPE_INT32 }", - &extension_proto)); - const FileDescriptor* file = pool_.BuildFile(extension_proto); - - ASSERT_TRUE(file != NULL); - - ASSERT_EQ(1, file->extension_count()); - const Descriptor* extendee = file->extension(0)->containing_type(); - EXPECT_EQ("UnknownType", extendee->name()); - ASSERT_EQ(1, extendee->extension_range_count()); - EXPECT_EQ(1, extendee->extension_range(0)->start); - EXPECT_EQ(FieldDescriptor::kMaxNumber + 1, extendee->extension_range(0)->end); -} - -TEST_F(AllowUnknownDependenciesTest, CustomOption) { - // Test that we can use a custom option without having parsed - // descriptor.proto. - - FileDescriptorProto option_proto; - - ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"unknown_custom_options.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { " - " extendee: \"google.protobuf.FileOptions\" " - " name: \"some_option\" " - " number: 123456 " - " label: LABEL_OPTIONAL " - " type: TYPE_INT32 " - "} " - "options { " - " uninterpreted_option { " - " name { " - " name_part: \"some_option\" " - " is_extension: true " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"unknown_option\" " - " is_extension: true " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"optimize_for\" " - " is_extension: false " - " } " - " identifier_value: \"SPEED\" " - " } " - "}", - &option_proto)); - - const FileDescriptor* file = pool_.BuildFile(option_proto); - ASSERT_TRUE(file != NULL); - - // Verify that no extension options were set, but they were left as - // uninterpreted_options. - vector fields; - file->options().GetReflection()->ListFields(file->options(), &fields); - ASSERT_EQ(2, fields.size()); - EXPECT_TRUE(file->options().has_optimize_for()); - EXPECT_EQ(2, file->options().uninterpreted_option_size()); -} - -// =================================================================== - -TEST(CustomOptions, OptionLocations) { - const Descriptor* message = - protobuf_unittest::TestMessageWithCustomOptions::descriptor(); - const FileDescriptor* file = message->file(); - const FieldDescriptor* field = message->FindFieldByName("field1"); - const EnumDescriptor* enm = message->FindEnumTypeByName("AnEnum"); - // TODO(benjy): Support EnumValue options, once the compiler does. - const ServiceDescriptor* service = - file->FindServiceByName("TestServiceWithCustomOptions"); - const MethodDescriptor* method = service->FindMethodByName("Foo"); - - EXPECT_EQ(GOOGLE_LONGLONG(9876543210), - file->options().GetExtension(protobuf_unittest::file_opt1)); - EXPECT_EQ(-56, - message->options().GetExtension(protobuf_unittest::message_opt1)); - EXPECT_EQ(GOOGLE_LONGLONG(8765432109), - field->options().GetExtension(protobuf_unittest::field_opt1)); - EXPECT_EQ(42, // Check that we get the default for an option we don't set. - field->options().GetExtension(protobuf_unittest::field_opt2)); - EXPECT_EQ(-789, - enm->options().GetExtension(protobuf_unittest::enum_opt1)); - EXPECT_EQ(123, - enm->value(1)->options().GetExtension( - protobuf_unittest::enum_value_opt1)); - EXPECT_EQ(GOOGLE_LONGLONG(-9876543210), - service->options().GetExtension(protobuf_unittest::service_opt1)); - EXPECT_EQ(protobuf_unittest::METHODOPT1_VAL2, - method->options().GetExtension(protobuf_unittest::method_opt1)); - - // See that the regular options went through unscathed. - EXPECT_TRUE(message->options().has_message_set_wire_format()); - EXPECT_EQ(FieldOptions::CORD, field->options().ctype()); -} - -TEST(CustomOptions, OptionTypes) { - const MessageOptions* options = NULL; - - options = - &protobuf_unittest::CustomOptionMinIntegerValues::descriptor()->options(); - EXPECT_EQ(false , options->GetExtension(protobuf_unittest::bool_opt)); - EXPECT_EQ(kint32min, options->GetExtension(protobuf_unittest::int32_opt)); - EXPECT_EQ(kint64min, options->GetExtension(protobuf_unittest::int64_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::uint32_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::uint64_opt)); - EXPECT_EQ(kint32min, options->GetExtension(protobuf_unittest::sint32_opt)); - EXPECT_EQ(kint64min, options->GetExtension(protobuf_unittest::sint64_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::fixed32_opt)); - EXPECT_EQ(0 , options->GetExtension(protobuf_unittest::fixed64_opt)); - EXPECT_EQ(kint32min, options->GetExtension(protobuf_unittest::sfixed32_opt)); - EXPECT_EQ(kint64min, options->GetExtension(protobuf_unittest::sfixed64_opt)); - - options = - &protobuf_unittest::CustomOptionMaxIntegerValues::descriptor()->options(); - EXPECT_EQ(true , options->GetExtension(protobuf_unittest::bool_opt)); - EXPECT_EQ(kint32max , options->GetExtension(protobuf_unittest::int32_opt)); - EXPECT_EQ(kint64max , options->GetExtension(protobuf_unittest::int64_opt)); - EXPECT_EQ(kuint32max, options->GetExtension(protobuf_unittest::uint32_opt)); - EXPECT_EQ(kuint64max, options->GetExtension(protobuf_unittest::uint64_opt)); - EXPECT_EQ(kint32max , options->GetExtension(protobuf_unittest::sint32_opt)); - EXPECT_EQ(kint64max , options->GetExtension(protobuf_unittest::sint64_opt)); - EXPECT_EQ(kuint32max, options->GetExtension(protobuf_unittest::fixed32_opt)); - EXPECT_EQ(kuint64max, options->GetExtension(protobuf_unittest::fixed64_opt)); - EXPECT_EQ(kint32max , options->GetExtension(protobuf_unittest::sfixed32_opt)); - EXPECT_EQ(kint64max , options->GetExtension(protobuf_unittest::sfixed64_opt)); - - options = - &protobuf_unittest::CustomOptionOtherValues::descriptor()->options(); - EXPECT_EQ(-100, options->GetExtension(protobuf_unittest::int32_opt)); - EXPECT_FLOAT_EQ(12.3456789, - options->GetExtension(protobuf_unittest::float_opt)); - EXPECT_DOUBLE_EQ(1.234567890123456789, - options->GetExtension(protobuf_unittest::double_opt)); - EXPECT_EQ("Hello, \"World\"", - options->GetExtension(protobuf_unittest::string_opt)); - - EXPECT_EQ(string("Hello\0World", 11), - options->GetExtension(protobuf_unittest::bytes_opt)); - - EXPECT_EQ(protobuf_unittest::DummyMessageContainingEnum::TEST_OPTION_ENUM_TYPE2, - options->GetExtension(protobuf_unittest::enum_opt)); - - options = - &protobuf_unittest::SettingRealsFromPositiveInts::descriptor()->options(); - EXPECT_FLOAT_EQ(12, options->GetExtension(protobuf_unittest::float_opt)); - EXPECT_DOUBLE_EQ(154, options->GetExtension(protobuf_unittest::double_opt)); - - options = - &protobuf_unittest::SettingRealsFromNegativeInts::descriptor()->options(); - EXPECT_FLOAT_EQ(-12, options->GetExtension(protobuf_unittest::float_opt)); - EXPECT_DOUBLE_EQ(-154, options->GetExtension(protobuf_unittest::double_opt)); -} - -TEST(CustomOptions, ComplexExtensionOptions) { - const MessageOptions* options = - &protobuf_unittest::VariousComplexOptions::descriptor()->options(); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1).foo(), 42); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1). - GetExtension(protobuf_unittest::quux), 324); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt1). - GetExtension(protobuf_unittest::corge).qux(), 876); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).baz(), 987); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::grault), 654); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).bar().foo(), - 743); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).bar(). - GetExtension(protobuf_unittest::quux), 1999); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2).bar(). - GetExtension(protobuf_unittest::corge).qux(), 2008); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::garply).foo(), 741); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::garply). - GetExtension(protobuf_unittest::quux), 1998); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - GetExtension(protobuf_unittest::garply). - GetExtension(protobuf_unittest::corge).qux(), 2121); - EXPECT_EQ(options->GetExtension( - protobuf_unittest::ComplexOptionType2::ComplexOptionType4::complex_opt4). - waldo(), 1971); - EXPECT_EQ(options->GetExtension(protobuf_unittest::complex_opt2). - fred().waldo(), 321); - EXPECT_EQ(9, options->GetExtension(protobuf_unittest::complex_opt3).qux()); - EXPECT_EQ(22, options->GetExtension(protobuf_unittest::complex_opt3). - complexoptiontype5().plugh()); - EXPECT_EQ(24, options->GetExtension(protobuf_unittest::complexopt6).xyzzy()); -} - -TEST(CustomOptions, OptionsFromOtherFile) { - // Test that to use a custom option, we only need to import the file - // defining the option; we do not also have to import descriptor.proto. - DescriptorPool pool; - - FileDescriptorProto file_proto; - FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); - ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); - ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - - ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" " - "options { " - " uninterpreted_option { " - " name { " - " name_part: \"file_opt1\" " - " is_extension: true " - " } " - " positive_int_value: 1234 " - " } " - // Test a non-extension option too. (At one point this failed due to a - // bug.) - " uninterpreted_option { " - " name { " - " name_part: \"java_package\" " - " is_extension: false " - " } " - " string_value: \"foo\" " - " } " - // Test that enum-typed options still work too. (At one point this also - // failed due to a bug.) - " uninterpreted_option { " - " name { " - " name_part: \"optimize_for\" " - " is_extension: false " - " } " - " identifier_value: \"SPEED\" " - " } " - "}" - , - &file_proto)); - - const FileDescriptor* file = pool.BuildFile(file_proto); - ASSERT_TRUE(file != NULL); - EXPECT_EQ(1234, file->options().GetExtension(protobuf_unittest::file_opt1)); - EXPECT_TRUE(file->options().has_java_package()); - EXPECT_EQ("foo", file->options().java_package()); - EXPECT_TRUE(file->options().has_optimize_for()); - EXPECT_EQ(FileOptions::SPEED, file->options().optimize_for()); -} - -TEST(CustomOptions, MessageOptionThreeFieldsSet) { - // This tests a bug which previously existed in custom options parsing. The - // bug occurred when you defined a custom option with message type and then - // set three fields of that option on a single definition (see the example - // below). The bug is a bit hard to explain, so check the change history if - // you want to know more. - DescriptorPool pool; - - FileDescriptorProto file_proto; - FileDescriptorProto::descriptor()->file()->CopyTo(&file_proto); - ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - - protobuf_unittest::TestMessageWithCustomOptions::descriptor() - ->file()->CopyTo(&file_proto); - ASSERT_TRUE(pool.BuildFile(file_proto) != NULL); - - // The following represents the definition: - // - // import "google/protobuf/unittest_custom_options.proto" - // package protobuf_unittest; - // message Foo { - // option (complex_opt1).foo = 1234; - // option (complex_opt1).foo2 = 1234; - // option (complex_opt1).foo3 = 1234; - // } - ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"custom_options_import.proto\" " - "package: \"protobuf_unittest\" " - "dependency: \"google/protobuf/unittest_custom_options.proto\" " - "message_type { " - " name: \"Foo\" " - " options { " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo\" " - " is_extension: false " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo2\" " - " is_extension: false " - " } " - " positive_int_value: 1234 " - " } " - " uninterpreted_option { " - " name { " - " name_part: \"complex_opt1\" " - " is_extension: true " - " } " - " name { " - " name_part: \"foo3\" " - " is_extension: false " - " } " - " positive_int_value: 1234 " - " } " - " } " - "}", - &file_proto)); - - const FileDescriptor* file = pool.BuildFile(file_proto); - ASSERT_TRUE(file != NULL); - ASSERT_EQ(1, file->message_type_count()); - - const MessageOptions& options = file->message_type(0)->options(); - EXPECT_EQ(1234, options.GetExtension(protobuf_unittest::complex_opt1).foo()); -} - - -// =================================================================== - -// The tests below trigger every unique call to AddError() in descriptor.cc, -// in the order in which they appear in that file. I'm using TextFormat here -// to specify the input descriptors because building them using code would -// be too bulky. - -class MockErrorCollector : public DescriptorPool::ErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(const string& filename, - const string& element_name, const Message* descriptor, - ErrorLocation location, const string& message) { - const char* location_name = NULL; - switch (location) { - case NAME : location_name = "NAME" ; break; - case NUMBER : location_name = "NUMBER" ; break; - case TYPE : location_name = "TYPE" ; break; - case EXTENDEE : location_name = "EXTENDEE" ; break; - case DEFAULT_VALUE: location_name = "DEFAULT_VALUE"; break; - case OPTION_NAME : location_name = "OPTION_NAME" ; break; - case OPTION_VALUE : location_name = "OPTION_VALUE" ; break; - case INPUT_TYPE : location_name = "INPUT_TYPE" ; break; - case OUTPUT_TYPE : location_name = "OUTPUT_TYPE" ; break; - case OTHER : location_name = "OTHER" ; break; - } - - strings::SubstituteAndAppend( - &text_, "$0: $1: $2: $3\n", - filename, element_name, location_name, message); - } -}; - -class ValidationErrorTest : public testing::Test { - protected: - // Parse file_text as a FileDescriptorProto in text format and add it - // to the DescriptorPool. Expect no errors. - void BuildFile(const string& file_text) { - FileDescriptorProto file_proto; - ASSERT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); - ASSERT_TRUE(pool_.BuildFile(file_proto) != NULL); - } - - // Parse file_text as a FileDescriptorProto in text format and add it - // to the DescriptorPool. Expect errors to be produced which match the - // given error text. - void BuildFileWithErrors(const string& file_text, - const string& expected_errors) { - FileDescriptorProto file_proto; - ASSERT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); - - MockErrorCollector error_collector; - EXPECT_TRUE( - pool_.BuildFileCollectingErrors(file_proto, &error_collector) == NULL); - EXPECT_EQ(expected_errors, error_collector.text_); - } - - // Builds some already-parsed file in our test pool. - void BuildFileInTestPool(const FileDescriptor* file) { - FileDescriptorProto file_proto; - file->CopyTo(&file_proto); - ASSERT_TRUE(pool_.BuildFile(file_proto) != NULL); - } - - // Build descriptor.proto in our test pool. This allows us to extend it in - // the test pool, so we can test custom options. - void BuildDescriptorMessagesInTestPool() { - BuildFileInTestPool(DescriptorProto::descriptor()->file()); - } - - DescriptorPool pool_; -}; - -TEST_F(ValidationErrorTest, AlreadyDefined) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" }" - "message_type { name: \"Foo\" }", - - "foo.proto: Foo: NAME: \"Foo\" is already defined.\n"); -} - -TEST_F(ValidationErrorTest, AlreadyDefinedInPackage) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "package: \"foo.bar\" " - "message_type { name: \"Foo\" }" - "message_type { name: \"Foo\" }", - - "foo.proto: foo.bar.Foo: NAME: \"Foo\" is already defined in " - "\"foo.bar\".\n"); -} - -TEST_F(ValidationErrorTest, AlreadyDefinedInOtherFile) { - BuildFile( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" }"); - - BuildFileWithErrors( - "name: \"bar.proto\" " - "message_type { name: \"Foo\" }", - - "bar.proto: Foo: NAME: \"Foo\" is already defined in file " - "\"foo.proto\".\n"); -} - -TEST_F(ValidationErrorTest, PackageAlreadyDefined) { - BuildFile( - "name: \"foo.proto\" " - "message_type { name: \"foo\" }"); - BuildFileWithErrors( - "name: \"bar.proto\" " - "package: \"foo.bar\"", - - "bar.proto: foo: NAME: \"foo\" is already defined (as something other " - "than a package) in file \"foo.proto\".\n"); -} - -TEST_F(ValidationErrorTest, EnumValueAlreadyDefinedInParent) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Foo\" value { name: \"FOO\" number: 1 } } " - "enum_type { name: \"Bar\" value { name: \"FOO\" number: 1 } } ", - - "foo.proto: FOO: NAME: \"FOO\" is already defined.\n" - "foo.proto: FOO: NAME: Note that enum values use C++ scoping rules, " - "meaning that enum values are siblings of their type, not children of " - "it. Therefore, \"FOO\" must be unique within the global scope, not " - "just within \"Bar\".\n"); -} - -TEST_F(ValidationErrorTest, EnumValueAlreadyDefinedInParentNonGlobal) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "package: \"pkg\" " - "enum_type { name: \"Foo\" value { name: \"FOO\" number: 1 } } " - "enum_type { name: \"Bar\" value { name: \"FOO\" number: 1 } } ", - - "foo.proto: pkg.FOO: NAME: \"FOO\" is already defined in \"pkg\".\n" - "foo.proto: pkg.FOO: NAME: Note that enum values use C++ scoping rules, " - "meaning that enum values are siblings of their type, not children of " - "it. Therefore, \"FOO\" must be unique within \"pkg\", not just within " - "\"Bar\".\n"); -} - -TEST_F(ValidationErrorTest, MissingName) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { }", - - "foo.proto: : NAME: Missing name.\n"); -} - -TEST_F(ValidationErrorTest, InvalidName) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"$\" }", - - "foo.proto: $: NAME: \"$\" is not a valid identifier.\n"); -} - -TEST_F(ValidationErrorTest, InvalidPackageName) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "package: \"foo.$\"", - - "foo.proto: foo.$: NAME: \"$\" is not a valid identifier.\n"); -} - -TEST_F(ValidationErrorTest, MissingFileName) { - BuildFileWithErrors( - "", - - ": : OTHER: Missing field: FileDescriptorProto.name.\n"); -} - -TEST_F(ValidationErrorTest, DupeDependency) { - BuildFile("name: \"foo.proto\""); - BuildFileWithErrors( - "name: \"bar.proto\" " - "dependency: \"foo.proto\" " - "dependency: \"foo.proto\" ", - - "bar.proto: bar.proto: OTHER: Import \"foo.proto\" was listed twice.\n"); -} - -TEST_F(ValidationErrorTest, UnknownDependency) { - BuildFileWithErrors( - "name: \"bar.proto\" " - "dependency: \"foo.proto\" ", - - "bar.proto: bar.proto: OTHER: Import \"foo.proto\" has not been loaded.\n"); -} - -TEST_F(ValidationErrorTest, ForeignUnimportedPackageNoCrash) { - // Used to crash: If we depend on a non-existent file and then refer to a - // package defined in a file that we didn't import, and that package is - // nested within a parent package which this file is also in, and we don't - // include that parent package in the name (i.e. we do a relative lookup)... - // Yes, really. - BuildFile( - "name: 'foo.proto' " - "package: 'outer.foo' "); - BuildFileWithErrors( - "name: 'bar.proto' " - "dependency: 'baz.proto' " - "package: 'outer.bar' " - "message_type { " - " name: 'Bar' " - " field { name:'bar' number:1 label:LABEL_OPTIONAL type_name:'foo.Foo' }" - "}", - - "bar.proto: bar.proto: OTHER: Import \"baz.proto\" has not been loaded.\n" - "bar.proto: outer.bar.Bar.bar: TYPE: \"outer.foo\" seems to be defined in " - "\"foo.proto\", which is not imported by \"bar.proto\". To use it here, " - "please add the necessary import.\n"); -} - -TEST_F(ValidationErrorTest, DupeFile) { - BuildFile( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" }"); - // Note: We should *not* get redundant errors about "Foo" already being - // defined. - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - // Add another type so that the files aren't identical (in which case there - // would be no error). - "enum_type { name: \"Bar\" }", - - "foo.proto: foo.proto: OTHER: A file with this name is already in the " - "pool.\n"); -} - -TEST_F(ValidationErrorTest, FieldInExtensionRange) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 9 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"bar\" number: 10 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"baz\" number: 19 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"qux\" number: 20 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " extension_range { start: 10 end: 20 }" - "}", - - "foo.proto: Foo.bar: NUMBER: Extension range 10 to 19 includes field " - "\"bar\" (10).\n" - "foo.proto: Foo.baz: NUMBER: Extension range 10 to 19 includes field " - "\"baz\" (19).\n"); -} - -TEST_F(ValidationErrorTest, OverlappingExtensionRanges) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 10 end: 20 }" - " extension_range { start: 20 end: 30 }" - " extension_range { start: 19 end: 21 }" - "}", - - "foo.proto: Foo: NUMBER: Extension range 19 to 20 overlaps with " - "already-defined range 10 to 19.\n" - "foo.proto: Foo: NUMBER: Extension range 19 to 20 overlaps with " - "already-defined range 20 to 29.\n"); -} - -TEST_F(ValidationErrorTest, InvalidDefaults) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - - // Invalid number. - " field { name: \"foo\" number: 1 label: LABEL_OPTIONAL type: TYPE_INT32" - " default_value: \"abc\" }" - - // Empty default value. - " field { name: \"bar\" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32" - " default_value: \"\" }" - - // Invalid boolean. - " field { name: \"baz\" number: 3 label: LABEL_OPTIONAL type: TYPE_BOOL" - " default_value: \"abc\" }" - - // Messages can't have defaults. - " field { name: \"qux\" number: 4 label: LABEL_OPTIONAL type: TYPE_MESSAGE" - " default_value: \"abc\" type_name: \"Foo\" }" - - // Same thing, but we don't know that this field has message type until - // we look up the type name. - " field { name: \"quux\" number: 5 label: LABEL_OPTIONAL" - " default_value: \"abc\" type_name: \"Foo\" }" - - // Repeateds can't have defaults. - " field { name: \"corge\" number: 6 label: LABEL_REPEATED type: TYPE_INT32" - " default_value: \"1\" }" - "}", - - "foo.proto: Foo.foo: DEFAULT_VALUE: Couldn't parse default value.\n" - "foo.proto: Foo.bar: DEFAULT_VALUE: Couldn't parse default value.\n" - "foo.proto: Foo.baz: DEFAULT_VALUE: Boolean default must be true or " - "false.\n" - "foo.proto: Foo.qux: DEFAULT_VALUE: Messages can't have default values.\n" - "foo.proto: Foo.corge: DEFAULT_VALUE: Repeated fields can't have default " - "values.\n" - // This ends up being reported later because the error is detected at - // cross-linking time. - "foo.proto: Foo.quux: DEFAULT_VALUE: Messages can't have default " - "values.\n"); -} - -TEST_F(ValidationErrorTest, NegativeFieldNumber) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: -1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", - - "foo.proto: Foo.foo: NUMBER: Field numbers must be positive integers.\n"); -} - -TEST_F(ValidationErrorTest, HugeFieldNumber) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 0x70000000 " - " label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", - - "foo.proto: Foo.foo: NUMBER: Field numbers cannot be greater than " - "536870911.\n"); -} - -TEST_F(ValidationErrorTest, ReservedFieldNumber) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field {name:\"foo\" number: 18999 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field {name:\"bar\" number: 19000 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field {name:\"baz\" number: 19999 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field {name:\"qux\" number: 20000 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", - - "foo.proto: Foo.bar: NUMBER: Field numbers 19000 through 19999 are " - "reserved for the protocol buffer library implementation.\n" - "foo.proto: Foo.baz: NUMBER: Field numbers 19000 through 19999 are " - "reserved for the protocol buffer library implementation.\n"); -} - -TEST_F(ValidationErrorTest, ExtensionMissingExtendee) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension { name: \"foo\" number: 1 label: LABEL_OPTIONAL" - " type_name: \"Foo\" }" - "}", - - "foo.proto: Foo.foo: EXTENDEE: FieldDescriptorProto.extendee not set for " - "extension field.\n"); -} - -TEST_F(ValidationErrorTest, NonExtensionWithExtendee) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " extension_range { start: 1 end: 2 }" - "}" - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 1 label: LABEL_OPTIONAL" - " type_name: \"Foo\" extendee: \"Bar\" }" - "}", - - "foo.proto: Foo.foo: EXTENDEE: FieldDescriptorProto.extendee set for " - "non-extension field.\n"); -} - -TEST_F(ValidationErrorTest, FieldNumberConflict) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " field { name: \"bar\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", - - "foo.proto: Foo.bar: NUMBER: Field number 1 has already been used in " - "\"Foo\" by field \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, BadMessageSetExtensionType) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"MessageSet\"" - " options { message_set_wire_format: true }" - " extension_range { start: 4 end: 5 }" - "}" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:4 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"MessageSet\" }" - "}", - - "foo.proto: Foo.foo: TYPE: Extensions of MessageSets must be optional " - "messages.\n"); -} - -TEST_F(ValidationErrorTest, BadMessageSetExtensionLabel) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"MessageSet\"" - " options { message_set_wire_format: true }" - " extension_range { start: 4 end: 5 }" - "}" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:4 label:LABEL_REPEATED type:TYPE_MESSAGE" - " type_name: \"Foo\" extendee: \"MessageSet\" }" - "}", - - "foo.proto: Foo.foo: TYPE: Extensions of MessageSets must be optional " - "messages.\n"); -} - -TEST_F(ValidationErrorTest, FieldInMessageSet) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " options { message_set_wire_format: true }" - " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", - - "foo.proto: Foo.foo: NAME: MessageSets cannot have fields, only " - "extensions.\n"); -} - -TEST_F(ValidationErrorTest, NegativeExtensionRangeNumber) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: -10 end: -1 }" - "}", - - "foo.proto: Foo: NUMBER: Extension numbers must be positive integers.\n"); -} - -TEST_F(ValidationErrorTest, HugeExtensionRangeNumber) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 1 end: 0x70000000 }" - "}", - - "foo.proto: Foo: NUMBER: Extension numbers cannot be greater than " - "536870911.\n"); -} - -TEST_F(ValidationErrorTest, ExtensionRangeEndBeforeStart) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension_range { start: 10 end: 10 }" - " extension_range { start: 10 end: 5 }" - "}", - - "foo.proto: Foo: NUMBER: Extension range end number must be greater than " - "start number.\n" - "foo.proto: Foo: NUMBER: Extension range end number must be greater than " - "start number.\n"); -} - -TEST_F(ValidationErrorTest, EmptyEnum) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Foo\" }" - // Also use the empty enum in a message to make sure there are no crashes - // during validation (possible if the code attempts to derive a default - // value for the field). - "message_type {" - " name: \"Bar\"" - " field { name: \"foo\" number: 1 label:LABEL_OPTIONAL type_name:\"Foo\" }" - " field { name: \"bar\" number: 2 label:LABEL_OPTIONAL type_name:\"Foo\" " - " default_value: \"NO_SUCH_VALUE\" }" - "}", - - "foo.proto: Foo: NAME: Enums must contain at least one value.\n" - "foo.proto: Bar.bar: DEFAULT_VALUE: Enum type \"Foo\" has no value named " - "\"NO_SUCH_VALUE\".\n"); -} - -TEST_F(ValidationErrorTest, UndefinedExtendee) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"Bar\" }" - "}", - - "foo.proto: Foo.foo: EXTENDEE: \"Bar\" is not defined.\n"); -} - -TEST_F(ValidationErrorTest, NonMessageExtendee) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } }" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"Bar\" }" - "}", - - "foo.proto: Foo.foo: EXTENDEE: \"Bar\" is not a message type.\n"); -} - -TEST_F(ValidationErrorTest, NotAnExtensionNumber) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - "}" - "message_type {" - " name: \"Foo\"" - " extension { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " extendee: \"Bar\" }" - "}", - - "foo.proto: Foo.foo: NUMBER: \"Bar\" does not declare 1 as an extension " - "number.\n"); -} - -TEST_F(ValidationErrorTest, UndefinedFieldType) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}", - - "foo.proto: Foo.foo: TYPE: \"Bar\" is not defined.\n"); -} - -TEST_F(ValidationErrorTest, FieldTypeDefinedInUndeclaredDependency) { - BuildFile( - "name: \"bar.proto\" " - "message_type { name: \"Bar\" } "); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}", - "foo.proto: Foo.foo: TYPE: \"Bar\" seems to be defined in \"bar.proto\", " - "which is not imported by \"foo.proto\". To use it here, please add the " - "necessary import.\n"); -} - -TEST_F(ValidationErrorTest, SearchMostLocalFirst) { - // The following should produce an error that Bar.Baz is not defined: - // message Bar { message Baz {} } - // message Foo { - // message Bar { - // // Placing "message Baz{}" here, or removing Foo.Bar altogether, - // // would fix the error. - // } - // optional Bar.Baz baz = 1; - // } - // An one point the lookup code incorrectly did not produce an error in this - // case, because when looking for Bar.Baz, it would try "Foo.Bar.Baz" first, - // fail, and ten try "Bar.Baz" and succeed, even though "Bar" should actually - // refer to the inner Bar, not the outer one. - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " nested_type { name: \"Baz\" }" - "}" - "message_type {" - " name: \"Foo\"" - " nested_type { name: \"Bar\" }" - " field { name:\"baz\" number:1 label:LABEL_OPTIONAL" - " type_name:\"Bar.Baz\" }" - "}", - - "foo.proto: Foo.baz: TYPE: \"Bar.Baz\" is not defined.\n"); -} - -TEST_F(ValidationErrorTest, SearchMostLocalFirst2) { - // This test would find the most local "Bar" first, and does, but - // proceeds to find the outer one because the inner one's not an - // aggregate. - BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - " nested_type { name: \"Baz\" }" - "}" - "message_type {" - " name: \"Foo\"" - " field { name: \"Bar\" number:1 type:TYPE_BYTES } " - " field { name:\"baz\" number:2 label:LABEL_OPTIONAL" - " type_name:\"Bar.Baz\" }" - "}"); -} - -TEST_F(ValidationErrorTest, PackageOriginallyDeclaredInTransitiveDependent) { - // Imagine we have the following: - // - // foo.proto: - // package foo.bar; - // bar.proto: - // package foo.bar; - // import "foo.proto"; - // message Bar {} - // baz.proto: - // package foo; - // import "bar.proto" - // message Baz { optional bar.Bar qux = 1; } - // - // When validating baz.proto, we will look up "bar.Bar". As part of this - // lookup, we first lookup "bar" then try to find "Bar" within it. "bar" - // should resolve to "foo.bar". Note, though, that "foo.bar" was originally - // defined in foo.proto, which is not a direct dependency of baz.proto. The - // implementation of FindSymbol() normally only returns symbols in direct - // dependencies, not indirect ones. This test insures that this does not - // prevent it from finding "foo.bar". - - BuildFile( - "name: \"foo.proto\" " - "package: \"foo.bar\" "); - BuildFile( - "name: \"bar.proto\" " - "package: \"foo.bar\" " - "dependency: \"foo.proto\" " - "message_type { name: \"Bar\" }"); - BuildFile( - "name: \"baz.proto\" " - "package: \"foo\" " - "dependency: \"bar.proto\" " - "message_type { " - " name: \"Baz\" " - " field { name:\"qux\" number:1 label:LABEL_OPTIONAL " - " type_name:\"bar.Bar\" }" - "}"); -} - -TEST_F(ValidationErrorTest, FieldTypeNotAType) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL " - " type_name:\".Foo.bar\" }" - " field { name:\"bar\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" - "}", - - "foo.proto: Foo.foo: TYPE: \".Foo.bar\" is not a type.\n"); -} - -TEST_F(ValidationErrorTest, RelativeFieldTypeNotAType) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " nested_type {" - " name: \"Bar\"" - " field { name:\"Baz\" number:2 label:LABEL_OPTIONAL type:TYPE_INT32 }" - " }" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL " - " type_name:\"Bar.Baz\" }" - "}", - "foo.proto: Foo.foo: TYPE: \"Bar.Baz\" is not a type.\n"); -} - -TEST_F(ValidationErrorTest, FieldTypeMayBeItsName) { - BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"Bar\"" - "}" - "message_type {" - " name: \"Foo\"" - " field { name:\"Bar\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\" }" - "}"); -} - -TEST_F(ValidationErrorTest, EnumFieldTypeIsMessage) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Bar\" } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_ENUM" - " type_name:\"Bar\" }" - "}", - - "foo.proto: Foo.foo: TYPE: \"Bar\" is not an enum type.\n"); -} - -TEST_F(ValidationErrorTest, MessageFieldTypeIsEnum) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE" - " type_name:\"Bar\" }" - "}", - - "foo.proto: Foo.foo: TYPE: \"Bar\" is not a message type.\n"); -} - -TEST_F(ValidationErrorTest, BadEnumDefaultValue) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type_name:\"Bar\"" - " default_value:\"NO_SUCH_VALUE\" }" - "}", - - "foo.proto: Foo.foo: DEFAULT_VALUE: Enum type \"Bar\" has no value named " - "\"NO_SUCH_VALUE\".\n"); -} - -TEST_F(ValidationErrorTest, PrimitiveWithTypeName) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_INT32" - " type_name:\"Foo\" }" - "}", - - "foo.proto: Foo.foo: TYPE: Field with primitive type has type_name.\n"); -} - -TEST_F(ValidationErrorTest, NonPrimitiveWithoutTypeName) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"Foo\"" - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_MESSAGE }" - "}", - - "foo.proto: Foo.foo: TYPE: Field with message or enum type missing " - "type_name.\n"); -} - -TEST_F(ValidationErrorTest, InputTypeNotDefined) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Bar\" output_type: \"Foo\" }" - "}", - - "foo.proto: TestService.A: INPUT_TYPE: \"Bar\" is not defined.\n"); -} - -TEST_F(ValidationErrorTest, InputTypeNotAMessage) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Bar\" output_type: \"Foo\" }" - "}", - - "foo.proto: TestService.A: INPUT_TYPE: \"Bar\" is not a message type.\n"); -} - -TEST_F(ValidationErrorTest, OutputTypeNotDefined) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Foo\" output_type: \"Bar\" }" - "}", - - "foo.proto: TestService.A: OUTPUT_TYPE: \"Bar\" is not defined.\n"); -} - -TEST_F(ValidationErrorTest, OutputTypeNotAMessage) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "enum_type { name: \"Bar\" value { name:\"DUMMY\" number:0 } } " - "service {" - " name: \"TestService\"" - " method { name: \"A\" input_type: \"Foo\" output_type: \"Bar\" }" - "}", - - "foo.proto: TestService.A: OUTPUT_TYPE: \"Bar\" is not a message type.\n"); -} - -TEST_F(ValidationErrorTest, IllegalPackedField) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {\n" - " name: \"Foo\"" - " field { name:\"packed_string\" number:1 label:LABEL_REPEATED " - " type:TYPE_STRING " - " options { uninterpreted_option {" - " name { name_part: \"packed\" is_extension: false }" - " identifier_value: \"true\" }}}\n" - " field { name:\"packed_message\" number:3 label:LABEL_REPEATED " - " type_name: \"Foo\"" - " options { uninterpreted_option {" - " name { name_part: \"packed\" is_extension: false }" - " identifier_value: \"true\" }}}\n" - " field { name:\"optional_int32\" number: 4 label: LABEL_OPTIONAL " - " type:TYPE_INT32 " - " options { uninterpreted_option {" - " name { name_part: \"packed\" is_extension: false }" - " identifier_value: \"true\" }}}\n" - "}", - - "foo.proto: Foo.packed_string: TYPE: [packed = true] can only be " - "specified for repeated primitive fields.\n" - "foo.proto: Foo.packed_message: TYPE: [packed = true] can only be " - "specified for repeated primitive fields.\n" - "foo.proto: Foo.optional_int32: TYPE: [packed = true] can only be " - "specified for repeated primitive fields.\n" - ); -} - -TEST_F(ValidationErrorTest, OptionWrongType) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING " - " options { uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " positive_int_value: 1 }" - " }" - " }" - "}\n", - - "foo.proto: TestMessage.foo: OPTION_VALUE: Value must be identifier for " - "enum-valued option \"google.protobuf.FieldOptions.ctype\".\n"); -} - -TEST_F(ValidationErrorTest, OptionExtendsAtomicType) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING " - " options { uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " name { name_part: \"foo\" " - " is_extension: true }" - " positive_int_value: 1 }" - " }" - " }" - "}\n", - - "foo.proto: TestMessage.foo: OPTION_NAME: Option \"ctype\" is an " - "atomic type, not a message.\n"); -} - -TEST_F(ValidationErrorTest, DupOption) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_UINT32 " - " options { uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " identifier_value: \"CORD\" }" - " uninterpreted_option { name { name_part: \"ctype\" " - " is_extension: false }" - " identifier_value: \"CORD\" }" - " }" - " }" - "}\n", - - "foo.proto: TestMessage.foo: OPTION_NAME: Option \"ctype\" was " - "already set.\n"); -} - -TEST_F(ValidationErrorTest, InvalidOptionName) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"foo\" number:1 label:LABEL_OPTIONAL type:TYPE_BOOL " - " options { uninterpreted_option { " - " name { name_part: \"uninterpreted_option\" " - " is_extension: false }" - " positive_int_value: 1 " - " }" - " }" - " }" - "}\n", - - "foo.proto: TestMessage.foo: OPTION_NAME: Option must not use " - "reserved name \"uninterpreted_option\".\n"); -} - -TEST_F(ValidationErrorTest, RepeatedOption) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_REPEATED " - " type: TYPE_FLOAT extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " double_value: 1.2 } }", - - "foo.proto: foo.proto: OPTION_NAME: Option field \"(foo)\" is repeated. " - "Repeated options are not supported.\n"); -} - -TEST_F(ValidationErrorTest, CustomOptionConflictingFieldNumber) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo1\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FieldOptions\" }" - "extension { name: \"foo2\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FieldOptions\" }", - - "foo.proto: foo2: NUMBER: Extension number 7672757 has already been used " - "in \"google.protobuf.FieldOptions\" by extension \"foo1\".\n"); -} - -TEST_F(ValidationErrorTest, Int32OptionValueOutOfPositiveRange) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 0x80000000 } " - "}", - - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for int32 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, Int32OptionValueOutOfNegativeRange) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " negative_int_value: -0x80000001 } " - "}", - - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for int32 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, Int32OptionValueIsNotPositiveInt) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"5\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " - "for int32 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, Int64OptionValueOutOfRange) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT64 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 0x8000000000000000 } " - "}", - - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for int64 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, Int64OptionValueIsNotPositiveInt) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_INT64 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"5\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be integer " - "for int64 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, UInt32OptionValueOutOfRange) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_UINT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " positive_int_value: 0x100000000 } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value out of range " - "for uint32 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, UInt32OptionValueIsNotPositiveInt) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_UINT32 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " double_value: -5.6 } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " - "for uint32 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, UInt64OptionValueIsNotPositiveInt) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_UINT64 extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " negative_int_value: -5 } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be non-negative integer " - "for uint64 option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, FloatOptionValueIsNotNumber) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_FLOAT extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"bar\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be number " - "for float option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, DoubleOptionValueIsNotNumber) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_DOUBLE extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"bar\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be number " - "for double option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, BoolOptionValueIsNotTrueOrFalse) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_BOOL extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"bar\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be \"true\" or \"false\" " - "for boolean option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, EnumOptionValueIsNotIdentifier) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "enum_type { name: \"FooEnum\" value { name: \"BAR\" number: 1 } " - " value { name: \"BAZ\" number: 2 } }" - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_ENUM type_name: \"FooEnum\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " string_value: \"QUUX\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be identifier for " - "enum-valued option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, EnumOptionValueIsNotEnumValueName) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "enum_type { name: \"FooEnum\" value { name: \"BAR\" number: 1 } " - " value { name: \"BAZ\" number: 2 } }" - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_ENUM type_name: \"FooEnum\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum\" has no value " - "named \"QUUX\" for option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, EnumOptionValueIsSiblingEnumValueName) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "enum_type { name: \"FooEnum1\" value { name: \"BAR\" number: 1 } " - " value { name: \"BAZ\" number: 2 } }" - "enum_type { name: \"FooEnum2\" value { name: \"QUX\" number: 1 } " - " value { name: \"QUUX\" number: 2 } }" - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_ENUM type_name: \"FooEnum1\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Enum type \"FooEnum1\" has no value " - "named \"QUUX\" for option \"foo\". This appears to be a value from a " - "sibling type.\n"); -} - -TEST_F(ValidationErrorTest, StringOptionValueIsNotString) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "extension { name: \"foo\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_STRING extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"foo\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", - - "foo.proto: foo.proto: OPTION_VALUE: Value must be quoted string for " - "string option \"foo\".\n"); -} - -TEST_F(ValidationErrorTest, TryingToSetMessageValuedOption) { - BuildDescriptorMessagesInTestPool(); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"google/protobuf/descriptor.proto\" " - "message_type { " - " name: \"TestMessage\" " - " field { name:\"baz\" number:1 label:LABEL_OPTIONAL type:TYPE_STRING }" - "}" - "extension { name: \"bar\" number: 7672757 label: LABEL_OPTIONAL " - " type: TYPE_MESSAGE type_name: \"TestMessage\" " - " extendee: \"google.protobuf.FileOptions\" }" - "options { uninterpreted_option { name { name_part: \"bar\" " - " is_extension: true } " - " identifier_value: \"QUUX\" } }", - - "foo.proto: foo.proto: OPTION_NAME: Option field \"(bar)\" cannot be of " - "message type.\n"); -} - -TEST_F(ValidationErrorTest, NotLiteImportsLite) { - BuildFile( - "name: \"bar.proto\" " - "options { optimize_for: LITE_RUNTIME } "); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"bar.proto\" ", - - "foo.proto: foo.proto: OTHER: Files that do not use optimize_for = " - "LITE_RUNTIME cannot import files which do use this option. This file " - "is not lite, but it imports \"bar.proto\" which is.\n"); -} - -TEST_F(ValidationErrorTest, LiteExtendsNotLite) { - BuildFile( - "name: \"bar.proto\" " - "message_type: {" - " name: \"Bar\"" - " extension_range { start: 1 end: 1000 }" - "}"); - - BuildFileWithErrors( - "name: \"foo.proto\" " - "dependency: \"bar.proto\" " - "options { optimize_for: LITE_RUNTIME } " - "extension { name: \"ext\" number: 123 label: LABEL_OPTIONAL " - " type: TYPE_INT32 extendee: \"Bar\" }", - - "foo.proto: ext: EXTENDEE: Extensions to non-lite types can only be " - "declared in non-lite files. Note that you cannot extend a non-lite " - "type to contain a lite type, but the reverse is allowed.\n"); -} - -TEST_F(ValidationErrorTest, NoLiteServices) { - BuildFileWithErrors( - "name: \"foo.proto\" " - "options { optimize_for: LITE_RUNTIME } " - "service { name: \"Foo\" }", - - "foo.proto: Foo: NAME: Files with optimize_for = LITE_RUNTIME cannot " - "define services.\n"); -} - -TEST_F(ValidationErrorTest, RollbackAfterError) { - // Build a file which contains every kind of construct but references an - // undefined type. All these constructs will be added to the symbol table - // before the undefined type error is noticed. The DescriptorPool will then - // have to roll everything back. - BuildFileWithErrors( - "name: \"foo.proto\" " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 }" - "} " - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"BAR\" number:1 }" - "} " - "service {" - " name: \"TestService\"" - " method {" - " name: \"Baz\"" - " input_type: \"NoSuchType\"" // error - " output_type: \"TestMessage\"" - " }" - "}", - - "foo.proto: TestService.Baz: INPUT_TYPE: \"NoSuchType\" is not defined.\n"); - - // Make sure that if we build the same file again with the error fixed, - // it works. If the above rollback was incomplete, then some symbols will - // be left defined, and this second attempt will fail since it tries to - // re-define the same symbols. - BuildFile( - "name: \"foo.proto\" " - "message_type {" - " name: \"TestMessage\"" - " field { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:1 }" - "} " - "enum_type {" - " name: \"TestEnum\"" - " value { name:\"BAR\" number:1 }" - "} " - "service {" - " name: \"TestService\"" - " method { name:\"Baz\"" - " input_type:\"TestMessage\"" - " output_type:\"TestMessage\" }" - "}"); -} - -TEST_F(ValidationErrorTest, ErrorsReportedToLogError) { - // Test that errors are reported to GOOGLE_LOG(ERROR) if no error collector is - // provided. - - FileDescriptorProto file_proto; - ASSERT_TRUE(TextFormat::ParseFromString( - "name: \"foo.proto\" " - "message_type { name: \"Foo\" } " - "message_type { name: \"Foo\" } ", - &file_proto)); - - vector errors; - - { - ScopedMemoryLog log; - EXPECT_TRUE(pool_.BuildFile(file_proto) == NULL); - errors = log.GetMessages(ERROR); - } - - ASSERT_EQ(2, errors.size()); - - EXPECT_EQ("Invalid proto descriptor for file \"foo.proto\":", errors[0]); - EXPECT_EQ(" Foo: \"Foo\" is already defined.", errors[1]); -} - -// =================================================================== -// DescriptorDatabase - -static void AddToDatabase(SimpleDescriptorDatabase* database, - const char* file_text) { - FileDescriptorProto file_proto; - EXPECT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); - database->Add(file_proto); -} - -class DatabaseBackedPoolTest : public testing::Test { - protected: - DatabaseBackedPoolTest() {} - - SimpleDescriptorDatabase database_; - - virtual void SetUp() { - AddToDatabase(&database_, - "name: \"foo.proto\" " - "message_type { name:\"Foo\" extension_range { start: 1 end: 100 } } " - "enum_type { name:\"TestEnum\" value { name:\"DUMMY\" number:0 } } " - "service { name:\"TestService\" } "); - AddToDatabase(&database_, - "name: \"bar.proto\" " - "dependency: \"foo.proto\" " - "message_type { name:\"Bar\" } " - "extension { name:\"foo_ext\" extendee: \".Foo\" number:5 " - " label:LABEL_OPTIONAL type:TYPE_INT32 } "); - } - - // We can't inject a file containing errors into a DescriptorPool, so we - // need an actual mock DescriptorDatabase to test errors. - class ErrorDescriptorDatabase : public DescriptorDatabase { - public: - ErrorDescriptorDatabase() {} - ~ErrorDescriptorDatabase() {} - - // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output) { - // error.proto and error2.proto cyclically import each other. - if (filename == "error.proto") { - output->Clear(); - output->set_name("error.proto"); - output->add_dependency("error2.proto"); - return true; - } else if (filename == "error2.proto") { - output->Clear(); - output->set_name("error2.proto"); - output->add_dependency("error.proto"); - return true; - } else { - return false; - } - } - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output) { - return false; - } - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output) { - return false; - } - }; - - // A DescriptorDatabase that counts how many times each method has been - // called and forwards to some other DescriptorDatabase. - class CallCountingDatabase : public DescriptorDatabase { - public: - CallCountingDatabase(DescriptorDatabase* wrapped_db) - : wrapped_db_(wrapped_db) { - Clear(); - } - ~CallCountingDatabase() {} - - DescriptorDatabase* wrapped_db_; - - int call_count_; - - void Clear() { - call_count_ = 0; - } - - // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output) { - ++call_count_; - return wrapped_db_->FindFileByName(filename, output); - } - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output) { - ++call_count_; - return wrapped_db_->FindFileContainingSymbol(symbol_name, output); - } - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output) { - ++call_count_; - return wrapped_db_->FindFileContainingExtension( - containing_type, field_number, output); - } - }; - - // A DescriptorDatabase which falsely always returns foo.proto when searching - // for any symbol or extension number. This shouldn't cause the - // DescriptorPool to reload foo.proto if it is already loaded. - class FalsePositiveDatabase : public DescriptorDatabase { - public: - FalsePositiveDatabase(DescriptorDatabase* wrapped_db) - : wrapped_db_(wrapped_db) {} - ~FalsePositiveDatabase() {} - - DescriptorDatabase* wrapped_db_; - - // implements DescriptorDatabase --------------------------------- - bool FindFileByName(const string& filename, - FileDescriptorProto* output) { - return wrapped_db_->FindFileByName(filename, output); - } - bool FindFileContainingSymbol(const string& symbol_name, - FileDescriptorProto* output) { - return FindFileByName("foo.proto", output); - } - bool FindFileContainingExtension(const string& containing_type, - int field_number, - FileDescriptorProto* output) { - return FindFileByName("foo.proto", output); - } - }; -}; - -TEST_F(DatabaseBackedPoolTest, FindFileByName) { - DescriptorPool pool(&database_); - - const FileDescriptor* foo = pool.FindFileByName("foo.proto"); - ASSERT_TRUE(foo != NULL); - EXPECT_EQ("foo.proto", foo->name()); - ASSERT_EQ(1, foo->message_type_count()); - EXPECT_EQ("Foo", foo->message_type(0)->name()); - - EXPECT_EQ(foo, pool.FindFileByName("foo.proto")); - - EXPECT_TRUE(pool.FindFileByName("no_such_file.proto") == NULL); -} - -TEST_F(DatabaseBackedPoolTest, FindDependencyBeforeDependent) { - DescriptorPool pool(&database_); - - const FileDescriptor* foo = pool.FindFileByName("foo.proto"); - ASSERT_TRUE(foo != NULL); - EXPECT_EQ("foo.proto", foo->name()); - ASSERT_EQ(1, foo->message_type_count()); - EXPECT_EQ("Foo", foo->message_type(0)->name()); - - const FileDescriptor* bar = pool.FindFileByName("bar.proto"); - ASSERT_TRUE(bar != NULL); - EXPECT_EQ("bar.proto", bar->name()); - ASSERT_EQ(1, bar->message_type_count()); - EXPECT_EQ("Bar", bar->message_type(0)->name()); - - ASSERT_EQ(1, bar->dependency_count()); - EXPECT_EQ(foo, bar->dependency(0)); -} - -TEST_F(DatabaseBackedPoolTest, FindDependentBeforeDependency) { - DescriptorPool pool(&database_); - - const FileDescriptor* bar = pool.FindFileByName("bar.proto"); - ASSERT_TRUE(bar != NULL); - EXPECT_EQ("bar.proto", bar->name()); - ASSERT_EQ(1, bar->message_type_count()); - ASSERT_EQ("Bar", bar->message_type(0)->name()); - - const FileDescriptor* foo = pool.FindFileByName("foo.proto"); - ASSERT_TRUE(foo != NULL); - EXPECT_EQ("foo.proto", foo->name()); - ASSERT_EQ(1, foo->message_type_count()); - ASSERT_EQ("Foo", foo->message_type(0)->name()); - - ASSERT_EQ(1, bar->dependency_count()); - EXPECT_EQ(foo, bar->dependency(0)); -} - -TEST_F(DatabaseBackedPoolTest, FindFileContainingSymbol) { - DescriptorPool pool(&database_); - - const FileDescriptor* file = pool.FindFileContainingSymbol("Foo"); - ASSERT_TRUE(file != NULL); - EXPECT_EQ("foo.proto", file->name()); - EXPECT_EQ(file, pool.FindFileByName("foo.proto")); - - EXPECT_TRUE(pool.FindFileContainingSymbol("NoSuchSymbol") == NULL); -} - -TEST_F(DatabaseBackedPoolTest, FindMessageTypeByName) { - DescriptorPool pool(&database_); - - const Descriptor* type = pool.FindMessageTypeByName("Foo"); - ASSERT_TRUE(type != NULL); - EXPECT_EQ("Foo", type->name()); - EXPECT_EQ(type->file(), pool.FindFileByName("foo.proto")); - - EXPECT_TRUE(pool.FindMessageTypeByName("NoSuchType") == NULL); -} - -TEST_F(DatabaseBackedPoolTest, FindExtensionByNumber) { - DescriptorPool pool(&database_); - - const Descriptor* foo = pool.FindMessageTypeByName("Foo"); - ASSERT_TRUE(foo != NULL); - - const FieldDescriptor* extension = pool.FindExtensionByNumber(foo, 5); - ASSERT_TRUE(extension != NULL); - EXPECT_EQ("foo_ext", extension->name()); - EXPECT_EQ(extension->file(), pool.FindFileByName("bar.proto")); - - EXPECT_TRUE(pool.FindExtensionByNumber(foo, 12) == NULL); -} - -TEST_F(DatabaseBackedPoolTest, FindAllExtensions) { - DescriptorPool pool(&database_); - - const Descriptor* foo = pool.FindMessageTypeByName("Foo"); - - for (int i = 0; i < 2; ++i) { - // Repeat the lookup twice, to check that we get consistent - // results despite the fallback database lookup mutating the pool. - vector extensions; - pool.FindAllExtensions(foo, &extensions); - ASSERT_EQ(1, extensions.size()); - EXPECT_EQ(5, extensions[0]->number()); - } -} - -TEST_F(DatabaseBackedPoolTest, ErrorWithoutErrorCollector) { - ErrorDescriptorDatabase error_database; - DescriptorPool pool(&error_database); - - vector errors; - - { - ScopedMemoryLog log; - EXPECT_TRUE(pool.FindFileByName("error.proto") == NULL); - errors = log.GetMessages(ERROR); - } - - EXPECT_FALSE(errors.empty()); -} - -TEST_F(DatabaseBackedPoolTest, ErrorWithErrorCollector) { - ErrorDescriptorDatabase error_database; - MockErrorCollector error_collector; - DescriptorPool pool(&error_database, &error_collector); - - EXPECT_TRUE(pool.FindFileByName("error.proto") == NULL); - EXPECT_EQ( - "error.proto: error.proto: OTHER: File recursively imports itself: " - "error.proto -> error2.proto -> error.proto\n" - "error2.proto: error2.proto: OTHER: Import \"error.proto\" was not " - "found or had errors.\n" - "error.proto: error.proto: OTHER: Import \"error2.proto\" was not " - "found or had errors.\n", - error_collector.text_); -} - -TEST_F(DatabaseBackedPoolTest, UnittestProto) { - // Try to load all of unittest.proto from a DescriptorDatabase. This should - // thoroughly test all paths through DescriptorBuilder to insure that there - // are no deadlocking problems when pool_->mutex_ is non-NULL. - const FileDescriptor* original_file = - protobuf_unittest::TestAllTypes::descriptor()->file(); - - DescriptorPoolDatabase database(*DescriptorPool::generated_pool()); - DescriptorPool pool(&database); - const FileDescriptor* file_from_database = - pool.FindFileByName(original_file->name()); - - ASSERT_TRUE(file_from_database != NULL); - - FileDescriptorProto original_file_proto; - original_file->CopyTo(&original_file_proto); - - FileDescriptorProto file_from_database_proto; - file_from_database->CopyTo(&file_from_database_proto); - - EXPECT_EQ(original_file_proto.DebugString(), - file_from_database_proto.DebugString()); -} - -TEST_F(DatabaseBackedPoolTest, DoesntRetryDbUnnecessarily) { - // Searching for a child of an existing descriptor should never fall back - // to the DescriptorDatabase even if it isn't found, because we know all - // children are already loaded. - CallCountingDatabase call_counter(&database_); - DescriptorPool pool(&call_counter); - - const FileDescriptor* file = pool.FindFileByName("foo.proto"); - ASSERT_TRUE(file != NULL); - const Descriptor* foo = pool.FindMessageTypeByName("Foo"); - ASSERT_TRUE(foo != NULL); - const EnumDescriptor* test_enum = pool.FindEnumTypeByName("TestEnum"); - ASSERT_TRUE(test_enum != NULL); - const ServiceDescriptor* test_service = pool.FindServiceByName("TestService"); - ASSERT_TRUE(test_service != NULL); - - EXPECT_NE(0, call_counter.call_count_); - call_counter.Clear(); - - EXPECT_TRUE(foo->FindFieldByName("no_such_field") == NULL); - EXPECT_TRUE(foo->FindExtensionByName("no_such_extension") == NULL); - EXPECT_TRUE(foo->FindNestedTypeByName("NoSuchMessageType") == NULL); - EXPECT_TRUE(foo->FindEnumTypeByName("NoSuchEnumType") == NULL); - EXPECT_TRUE(foo->FindEnumValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(test_enum->FindValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(test_service->FindMethodByName("NoSuchMethod") == NULL); - - EXPECT_TRUE(file->FindMessageTypeByName("NoSuchMessageType") == NULL); - EXPECT_TRUE(file->FindEnumTypeByName("NoSuchEnumType") == NULL); - EXPECT_TRUE(file->FindEnumValueByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(file->FindServiceByName("NO_SUCH_VALUE") == NULL); - EXPECT_TRUE(file->FindExtensionByName("no_such_extension") == NULL); - EXPECT_EQ(0, call_counter.call_count_); -} - -TEST_F(DatabaseBackedPoolTest, DoesntReloadFilesUncesessarily) { - // If FindFileContainingSymbol() or FindFileContainingExtension() return a - // file that is already in the DescriptorPool, it should not attempt to - // reload the file. - FalsePositiveDatabase false_positive_database(&database_); - MockErrorCollector error_collector; - DescriptorPool pool(&false_positive_database, &error_collector); - - // First make sure foo.proto is loaded. - const Descriptor* foo = pool.FindMessageTypeByName("Foo"); - ASSERT_TRUE(foo != NULL); - - // Try inducing false positives. - EXPECT_TRUE(pool.FindMessageTypeByName("NoSuchSymbol") == NULL); - EXPECT_TRUE(pool.FindExtensionByNumber(foo, 22) == NULL); - - // No errors should have been reported. (If foo.proto was incorrectly - // loaded multiple times, errors would have been reported.) - EXPECT_EQ("", error_collector.text_); -} - -TEST_F(DatabaseBackedPoolTest, DoesntReloadKnownBadFiles) { - ErrorDescriptorDatabase error_database; - MockErrorCollector error_collector; - DescriptorPool pool(&error_database, &error_collector); - - EXPECT_TRUE(pool.FindFileByName("error.proto") == NULL); - error_collector.text_.clear(); - EXPECT_TRUE(pool.FindFileByName("error.proto") == NULL); - EXPECT_EQ("", error_collector.text_); -} - -TEST_F(DatabaseBackedPoolTest, DoesntFallbackOnWrongType) { - // If a lookup finds a symbol of the wrong type (e.g. we pass a type name - // to FindFieldByName()), we should fail fast, without checking the fallback - // database. - CallCountingDatabase call_counter(&database_); - DescriptorPool pool(&call_counter); - - const FileDescriptor* file = pool.FindFileByName("foo.proto"); - ASSERT_TRUE(file != NULL); - const Descriptor* foo = pool.FindMessageTypeByName("Foo"); - ASSERT_TRUE(foo != NULL); - const EnumDescriptor* test_enum = pool.FindEnumTypeByName("TestEnum"); - ASSERT_TRUE(test_enum != NULL); - - EXPECT_NE(0, call_counter.call_count_); - call_counter.Clear(); - - EXPECT_TRUE(pool.FindMessageTypeByName("TestEnum") == NULL); - EXPECT_TRUE(pool.FindFieldByName("Foo") == NULL); - EXPECT_TRUE(pool.FindExtensionByName("Foo") == NULL); - EXPECT_TRUE(pool.FindEnumTypeByName("Foo") == NULL); - EXPECT_TRUE(pool.FindEnumValueByName("Foo") == NULL); - EXPECT_TRUE(pool.FindServiceByName("Foo") == NULL); - EXPECT_TRUE(pool.FindMethodByName("Foo") == NULL); - - EXPECT_EQ(0, call_counter.call_count_); -} - -// =================================================================== - - -} // namespace descriptor_unittest -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/dynamic_message.cc b/Resources/NetHook/google/protobuf/dynamic_message.cc deleted file mode 100644 index c711a2da..00000000 --- a/Resources/NetHook/google/protobuf/dynamic_message.cc +++ /dev/null @@ -1,558 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// DynamicMessage is implemented by constructing a data structure which -// has roughly the same memory layout as a generated message would have. -// Then, we use GeneratedMessageReflection to implement our reflection -// interface. All the other operations we need to implement (e.g. -// parsing, copying, etc.) are already implemented in terms of -// Reflection, so the rest is easy. -// -// The up side of this strategy is that it's very efficient. We don't -// need to use hash_maps or generic representations of fields. The -// down side is that this is a low-level memory management hack which -// can be tricky to get right. -// -// As mentioned in the header, we only expose a DynamicMessageFactory -// publicly, not the DynamicMessage class itself. This is because -// GenericMessageReflection wants to have a pointer to a "default" -// copy of the class, with all fields initialized to their default -// values. We only want to construct one of these per message type, -// so DynamicMessageFactory stores a cache of default messages for -// each type it sees (each unique Descriptor pointer). The code -// refers to the "default" copy of the class as the "prototype". -// -// Note on memory allocation: This module often calls "operator new()" -// to allocate untyped memory, rather than calling something like -// "new uint8[]". This is because "operator new()" means "Give me some -// space which I can use as I please." while "new uint8[]" means "Give -// me an array of 8-bit integers.". In practice, the later may return -// a pointer that is not aligned correctly for general use. I believe -// Item 8 of "More Effective C++" discusses this in more detail, though -// I don't have the book on me right now so I'm not sure. - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -using internal::WireFormat; -using internal::ExtensionSet; -using internal::GeneratedMessageReflection; - - -// =================================================================== -// Some helper tables and functions... - -namespace { - -// Compute the byte size of the in-memory representation of the field. -int FieldSpaceUsed(const FieldDescriptor* field) { - typedef FieldDescriptor FD; // avoid line wrapping - if (field->label() == FD::LABEL_REPEATED) { - switch (field->cpp_type()) { - case FD::CPPTYPE_INT32 : return sizeof(RepeatedField); - case FD::CPPTYPE_INT64 : return sizeof(RepeatedField); - case FD::CPPTYPE_UINT32 : return sizeof(RepeatedField); - case FD::CPPTYPE_UINT64 : return sizeof(RepeatedField); - case FD::CPPTYPE_DOUBLE : return sizeof(RepeatedField); - case FD::CPPTYPE_FLOAT : return sizeof(RepeatedField); - case FD::CPPTYPE_BOOL : return sizeof(RepeatedField); - case FD::CPPTYPE_ENUM : return sizeof(RepeatedField); - case FD::CPPTYPE_MESSAGE: return sizeof(RepeatedPtrField); - - case FD::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - return sizeof(RepeatedPtrField); - } - break; - } - } else { - switch (field->cpp_type()) { - case FD::CPPTYPE_INT32 : return sizeof(int32 ); - case FD::CPPTYPE_INT64 : return sizeof(int64 ); - case FD::CPPTYPE_UINT32 : return sizeof(uint32 ); - case FD::CPPTYPE_UINT64 : return sizeof(uint64 ); - case FD::CPPTYPE_DOUBLE : return sizeof(double ); - case FD::CPPTYPE_FLOAT : return sizeof(float ); - case FD::CPPTYPE_BOOL : return sizeof(bool ); - case FD::CPPTYPE_ENUM : return sizeof(int ); - case FD::CPPTYPE_MESSAGE: return sizeof(Message*); - - case FD::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - return sizeof(string*); - } - break; - } - } - - GOOGLE_LOG(DFATAL) << "Can't get here."; - return 0; -} - -inline int DivideRoundingUp(int i, int j) { - return (i + (j - 1)) / j; -} - -static const int kSafeAlignment = sizeof(uint64); - -inline int AlignTo(int offset, int alignment) { - return DivideRoundingUp(offset, alignment) * alignment; -} - -// Rounds the given byte offset up to the next offset aligned such that any -// type may be stored at it. -inline int AlignOffset(int offset) { - return AlignTo(offset, kSafeAlignment); -} - -#define bitsizeof(T) (sizeof(T) * 8) - -} // namespace - -// =================================================================== - -class DynamicMessage : public Message { - public: - struct TypeInfo { - int size; - int has_bits_offset; - int unknown_fields_offset; - int extensions_offset; - - // Not owned by the TypeInfo. - DynamicMessageFactory* factory; // The factory that created this object. - const DescriptorPool* pool; // The factory's DescriptorPool. - const Descriptor* type; // Type of this DynamicMessage. - - // Warning: The order in which the following pointers are defined is - // important (the prototype must be deleted *before* the offsets). - scoped_array offsets; - scoped_ptr reflection; - scoped_ptr prototype; - }; - - DynamicMessage(const TypeInfo* type_info); - ~DynamicMessage(); - - // Called on the prototype after construction to initialize message fields. - void CrossLinkPrototypes(); - - // implements Message ---------------------------------------------- - - Message* New() const; - - int GetCachedSize() const; - void SetCachedSize(int size) const; - - Metadata GetMetadata() const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessage); - - inline bool is_prototype() const { - return type_info_->prototype == this || - // If type_info_->prototype is NULL, then we must be constructing - // the prototype now, which means we must be the prototype. - type_info_->prototype == NULL; - } - - inline void* OffsetToPointer(int offset) { - return reinterpret_cast(this) + offset; - } - inline const void* OffsetToPointer(int offset) const { - return reinterpret_cast(this) + offset; - } - - const TypeInfo* type_info_; - - // TODO(kenton): Make this an atomic when C++ supports it. - mutable int cached_byte_size_; -}; - -DynamicMessage::DynamicMessage(const TypeInfo* type_info) - : type_info_(type_info), - cached_byte_size_(0) { - // We need to call constructors for various fields manually and set - // default values where appropriate. We use placement new to call - // constructors. If you haven't heard of placement new, I suggest Googling - // it now. We use placement new even for primitive types that don't have - // constructors for consistency. (In theory, placement new should be used - // any time you are trying to convert untyped memory to typed memory, though - // in practice that's not strictly necessary for types that don't have a - // constructor.) - - const Descriptor* descriptor = type_info_->type; - - new(OffsetToPointer(type_info_->unknown_fields_offset)) UnknownFieldSet; - - if (type_info_->extensions_offset != -1) { - new(OffsetToPointer(type_info_->extensions_offset)) ExtensionSet; - } - - for (int i = 0; i < descriptor->field_count(); i++) { - const FieldDescriptor* field = descriptor->field(i); - void* field_ptr = OffsetToPointer(type_info_->offsets[i]); - switch (field->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - if (!field->is_repeated()) { \ - new(field_ptr) TYPE(field->default_value_##TYPE()); \ - } else { \ - new(field_ptr) RepeatedField(); \ - } \ - break; - - HANDLE_TYPE(INT32 , int32 ); - HANDLE_TYPE(INT64 , int64 ); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE(FLOAT , float ); - HANDLE_TYPE(BOOL , bool ); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_ENUM: - if (!field->is_repeated()) { - new(field_ptr) int(field->default_value_enum()->number()); - } else { - new(field_ptr) RepeatedField(); - } - break; - - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - if (!field->is_repeated()) { - if (is_prototype()) { - new(field_ptr) const string*(&field->default_value_string()); - } else { - string* default_value = - *reinterpret_cast( - type_info_->prototype->OffsetToPointer( - type_info_->offsets[i])); - new(field_ptr) string*(default_value); - } - } else { - new(field_ptr) RepeatedPtrField(); - } - break; - } - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: { - if (!field->is_repeated()) { - new(field_ptr) Message*(NULL); - } else { - new(field_ptr) RepeatedPtrField(); - } - break; - } - } - } -} - -DynamicMessage::~DynamicMessage() { - const Descriptor* descriptor = type_info_->type; - - reinterpret_cast( - OffsetToPointer(type_info_->unknown_fields_offset))->~UnknownFieldSet(); - - if (type_info_->extensions_offset != -1) { - reinterpret_cast( - OffsetToPointer(type_info_->extensions_offset))->~ExtensionSet(); - } - - // We need to manually run the destructors for repeated fields and strings, - // just as we ran their constructors in the the DynamicMessage constructor. - // Additionally, if any singular embedded messages have been allocated, we - // need to delete them, UNLESS we are the prototype message of this type, - // in which case any embedded messages are other prototypes and shouldn't - // be touched. - for (int i = 0; i < descriptor->field_count(); i++) { - const FieldDescriptor* field = descriptor->field(i); - void* field_ptr = OffsetToPointer(type_info_->offsets[i]); - - if (field->is_repeated()) { - switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - reinterpret_cast*>(field_ptr) \ - ->~RepeatedField(); \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - reinterpret_cast*>(field_ptr) - ->~RepeatedPtrField(); - break; - } - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: - reinterpret_cast*>(field_ptr) - ->~RepeatedPtrField(); - break; - } - - } else if (field->cpp_type() == FieldDescriptor::CPPTYPE_STRING) { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: { - string* ptr = *reinterpret_cast(field_ptr); - if (ptr != &field->default_value_string()) { - delete ptr; - } - break; - } - } - } else if ((field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) && - !is_prototype()) { - Message* message = *reinterpret_cast(field_ptr); - if (message != NULL) { - delete message; - } - } - } -} - -void DynamicMessage::CrossLinkPrototypes() { - // This should only be called on the prototype message. - GOOGLE_CHECK(is_prototype()); - - DynamicMessageFactory* factory = type_info_->factory; - const Descriptor* descriptor = type_info_->type; - - // Cross-link default messages. - for (int i = 0; i < descriptor->field_count(); i++) { - const FieldDescriptor* field = descriptor->field(i); - void* field_ptr = OffsetToPointer(type_info_->offsets[i]); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !field->is_repeated()) { - // For fields with message types, we need to cross-link with the - // prototype for the field's type. - // For singular fields, the field is just a pointer which should - // point to the prototype. - *reinterpret_cast(field_ptr) = - factory->GetPrototypeNoLock(field->message_type()); - } - } -} - -Message* DynamicMessage::New() const { - void* new_base = reinterpret_cast(operator new(type_info_->size)); - memset(new_base, 0, type_info_->size); - return new(new_base) DynamicMessage(type_info_); -} - -int DynamicMessage::GetCachedSize() const { - return cached_byte_size_; -} - -void DynamicMessage::SetCachedSize(int size) const { - // This is theoretically not thread-compatible, but in practice it works - // because if multiple threads write this simultaneously, they will be - // writing the exact same value. - cached_byte_size_ = size; -} - -Metadata DynamicMessage::GetMetadata() const { - Metadata metadata; - metadata.descriptor = type_info_->type; - metadata.reflection = type_info_->reflection.get(); - return metadata; -} - -// =================================================================== - -struct DynamicMessageFactory::PrototypeMap { - typedef hash_map Map; - Map map_; -}; - -DynamicMessageFactory::DynamicMessageFactory() - : pool_(NULL), delegate_to_generated_factory_(false), - prototypes_(new PrototypeMap) { -} - -DynamicMessageFactory::DynamicMessageFactory(const DescriptorPool* pool) - : pool_(pool), delegate_to_generated_factory_(false), - prototypes_(new PrototypeMap) { -} - -DynamicMessageFactory::~DynamicMessageFactory() { - for (PrototypeMap::Map::iterator iter = prototypes_->map_.begin(); - iter != prototypes_->map_.end(); ++iter) { - delete iter->second; - } -} - -const Message* DynamicMessageFactory::GetPrototype(const Descriptor* type) { - MutexLock lock(&prototypes_mutex_); - return GetPrototypeNoLock(type); -} - -const Message* DynamicMessageFactory::GetPrototypeNoLock( - const Descriptor* type) { - if (delegate_to_generated_factory_ && - type->file()->pool() == DescriptorPool::generated_pool()) { - return MessageFactory::generated_factory()->GetPrototype(type); - } - - const DynamicMessage::TypeInfo** target = &prototypes_->map_[type]; - if (*target != NULL) { - // Already exists. - return (*target)->prototype.get(); - } - - DynamicMessage::TypeInfo* type_info = new DynamicMessage::TypeInfo; - *target = type_info; - - type_info->type = type; - type_info->pool = (pool_ == NULL) ? type->file()->pool() : pool_; - type_info->factory = this; - - // We need to construct all the structures passed to - // GeneratedMessageReflection's constructor. This includes: - // - A block of memory that contains space for all the message's fields. - // - An array of integers indicating the byte offset of each field within - // this block. - // - A big bitfield containing a bit for each field indicating whether - // or not that field is set. - - // Compute size and offsets. - int* offsets = new int[type->field_count()]; - type_info->offsets.reset(offsets); - - // Decide all field offsets by packing in order. - // We place the DynamicMessage object itself at the beginning of the allocated - // space. - int size = sizeof(DynamicMessage); - size = AlignOffset(size); - - // Next the has_bits, which is an array of uint32s. - type_info->has_bits_offset = size; - int has_bits_array_size = - DivideRoundingUp(type->field_count(), bitsizeof(uint32)); - size += has_bits_array_size * sizeof(uint32); - size = AlignOffset(size); - - // The ExtensionSet, if any. - if (type->extension_range_count() > 0) { - type_info->extensions_offset = size; - size += sizeof(ExtensionSet); - size = AlignOffset(size); - } else { - // No extensions. - type_info->extensions_offset = -1; - } - - // All the fields. - for (int i = 0; i < type->field_count(); i++) { - // Make sure field is aligned to avoid bus errors. - int field_size = FieldSpaceUsed(type->field(i)); - size = AlignTo(size, min(kSafeAlignment, field_size)); - offsets[i] = size; - size += field_size; - } - - // Add the UnknownFieldSet to the end. - size = AlignOffset(size); - type_info->unknown_fields_offset = size; - size += sizeof(UnknownFieldSet); - - // Align the final size to make sure no clever allocators think that - // alignment is not necessary. - size = AlignOffset(size); - type_info->size = size; - - // Allocate the prototype. - void* base = operator new(size); - memset(base, 0, size); - DynamicMessage* prototype = new(base) DynamicMessage(type_info); - type_info->prototype.reset(prototype); - - // Construct the reflection object. - type_info->reflection.reset( - new GeneratedMessageReflection( - type_info->type, - type_info->prototype.get(), - type_info->offsets.get(), - type_info->has_bits_offset, - type_info->unknown_fields_offset, - type_info->extensions_offset, - type_info->pool, - this, - type_info->size)); - - // Cross link prototypes. - prototype->CrossLinkPrototypes(); - - return prototype; -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/dynamic_message.h b/Resources/NetHook/google/protobuf/dynamic_message.h deleted file mode 100644 index 81dd2c63..00000000 --- a/Resources/NetHook/google/protobuf/dynamic_message.h +++ /dev/null @@ -1,136 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Defines an implementation of Message which can emulate types which are not -// known at compile-time. - -#ifndef GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__ -#define GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__ - -#include -#include - -namespace google { -namespace protobuf { - -// Defined in other files. -class Descriptor; // descriptor.h -class DescriptorPool; // descriptor.h - -// Constructs implementations of Message which can emulate types which are not -// known at compile-time. -// -// Sometimes you want to be able to manipulate protocol types that you don't -// know about at compile time. It would be nice to be able to construct -// a Message object which implements the message type given by any arbitrary -// Descriptor. DynamicMessage provides this. -// -// As it turns out, a DynamicMessage needs to construct extra -// information about its type in order to operate. Most of this information -// can be shared between all DynamicMessages of the same type. But, caching -// this information in some sort of global map would be a bad idea, since -// the cached information for a particular descriptor could outlive the -// descriptor itself. To avoid this problem, DynamicMessageFactory -// encapsulates this "cache". All DynamicMessages of the same type created -// from the same factory will share the same support data. Any Descriptors -// used with a particular factory must outlive the factory. -class LIBPROTOBUF_EXPORT DynamicMessageFactory : public MessageFactory { - public: - // Construct a DynamicMessageFactory that will search for extensions in - // the DescriptorPool in which the exendee is defined. - DynamicMessageFactory(); - - // Construct a DynamicMessageFactory that will search for extensions in - // the given DescriptorPool. - // - // DEPRECATED: Use CodedInputStream::SetExtensionRegistry() to tell the - // parser to look for extensions in an alternate pool. However, note that - // this is almost never what you want to do. Almost all users should use - // the zero-arg constructor. - DynamicMessageFactory(const DescriptorPool* pool); - - ~DynamicMessageFactory(); - - // Call this to tell the DynamicMessageFactory that if it is given a - // Descriptor d for which: - // d->file()->pool() == DescriptorPool::generated_pool(), - // then it should delegate to MessageFactory::generated_factory() instead - // of constructing a dynamic implementation of the message. In theory there - // is no down side to doing this, so it may become the default in the future. - void SetDelegateToGeneratedFactory(bool enable) { - delegate_to_generated_factory_ = enable; - } - - // implements MessageFactory --------------------------------------- - - // Given a Descriptor, constructs the default (prototype) Message of that - // type. You can then call that message's New() method to construct a - // mutable message of that type. - // - // Calling this method twice with the same Descriptor returns the same - // object. The returned object remains property of the factory and will - // be destroyed when the factory is destroyed. Also, any objects created - // by calling the prototype's New() method share some data with the - // prototype, so these must be destoyed before the DynamicMessageFactory - // is destroyed. - // - // The given descriptor must outlive the returned message, and hence must - // outlive the DynamicMessageFactory. - // - // The method is thread-safe. - const Message* GetPrototype(const Descriptor* type); - - private: - const DescriptorPool* pool_; - bool delegate_to_generated_factory_; - - // This struct just contains a hash_map. We can't #include from - // this header due to hacks needed for hash_map portability in the open source - // release. Namely, stubs/hash.h, which defines hash_map portably, is not a - // public header (for good reason), but dynamic_message.h is, and public - // headers may only #include other public headers. - struct PrototypeMap; - scoped_ptr prototypes_; - mutable Mutex prototypes_mutex_; - - friend class DynamicMessage; - const Message* GetPrototypeNoLock(const Descriptor* type); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(DynamicMessageFactory); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_DYNAMIC_MESSAGE_H__ diff --git a/Resources/NetHook/google/protobuf/dynamic_message_unittest.cc b/Resources/NetHook/google/protobuf/dynamic_message_unittest.cc deleted file mode 100644 index 41b89ab5..00000000 --- a/Resources/NetHook/google/protobuf/dynamic_message_unittest.cc +++ /dev/null @@ -1,162 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Since the reflection interface for DynamicMessage is implemented by -// GenericMessageReflection, the only thing we really have to test is -// that DynamicMessage correctly sets up the information that -// GenericMessageReflection needs to use. So, we focus on that in this -// test. Other tests, such as generic_message_reflection_unittest and -// reflection_ops_unittest, cover the rest of the functionality used by -// DynamicMessage. - -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace google { -namespace protobuf { - -class DynamicMessageTest : public testing::Test { - protected: - DescriptorPool pool_; - DynamicMessageFactory factory_; - const Descriptor* descriptor_; - const Message* prototype_; - const Descriptor* extensions_descriptor_; - const Message* extensions_prototype_; - const Descriptor* packed_descriptor_; - const Message* packed_prototype_; - - DynamicMessageTest(): factory_(&pool_) {} - - virtual void SetUp() { - // We want to make sure that DynamicMessage works (particularly with - // extensions) even if we use descriptors that are *not* from compiled-in - // types, so we make copies of the descriptors for unittest.proto and - // unittest_import.proto. - FileDescriptorProto unittest_file; - FileDescriptorProto unittest_import_file; - - unittest::TestAllTypes::descriptor()->file()->CopyTo(&unittest_file); - unittest_import::ImportMessage::descriptor()->file()->CopyTo( - &unittest_import_file); - - ASSERT_TRUE(pool_.BuildFile(unittest_import_file) != NULL); - ASSERT_TRUE(pool_.BuildFile(unittest_file) != NULL); - - descriptor_ = pool_.FindMessageTypeByName("protobuf_unittest.TestAllTypes"); - ASSERT_TRUE(descriptor_ != NULL); - prototype_ = factory_.GetPrototype(descriptor_); - - extensions_descriptor_ = - pool_.FindMessageTypeByName("protobuf_unittest.TestAllExtensions"); - ASSERT_TRUE(extensions_descriptor_ != NULL); - extensions_prototype_ = factory_.GetPrototype(extensions_descriptor_); - - packed_descriptor_ = - pool_.FindMessageTypeByName("protobuf_unittest.TestPackedTypes"); - ASSERT_TRUE(packed_descriptor_ != NULL); - packed_prototype_ = factory_.GetPrototype(packed_descriptor_); - } -}; - -TEST_F(DynamicMessageTest, Descriptor) { - // Check that the descriptor on the DynamicMessage matches the descriptor - // passed to GetPrototype(). - EXPECT_EQ(prototype_->GetDescriptor(), descriptor_); -} - -TEST_F(DynamicMessageTest, OnePrototype) { - // Check that requesting the same prototype twice produces the same object. - EXPECT_EQ(prototype_, factory_.GetPrototype(descriptor_)); -} - -TEST_F(DynamicMessageTest, Defaults) { - // Check that all default values are set correctly in the initial message. - TestUtil::ReflectionTester reflection_tester(descriptor_); - reflection_tester.ExpectClearViaReflection(*prototype_); -} - -TEST_F(DynamicMessageTest, IndependentOffsets) { - // Check that all fields have independent offsets by setting each - // one to a unique value then checking that they all still have those - // unique values (i.e. they don't stomp each other). - scoped_ptr message(prototype_->New()); - TestUtil::ReflectionTester reflection_tester(descriptor_); - - reflection_tester.SetAllFieldsViaReflection(message.get()); - reflection_tester.ExpectAllFieldsSetViaReflection(*message); -} - -TEST_F(DynamicMessageTest, Extensions) { - // Check that extensions work. - scoped_ptr message(extensions_prototype_->New()); - TestUtil::ReflectionTester reflection_tester(extensions_descriptor_); - - reflection_tester.SetAllFieldsViaReflection(message.get()); - reflection_tester.ExpectAllFieldsSetViaReflection(*message); -} - -TEST_F(DynamicMessageTest, PackedFields) { - // Check that packed fields work properly. - scoped_ptr message(packed_prototype_->New()); - TestUtil::ReflectionTester reflection_tester(packed_descriptor_); - - reflection_tester.SetPackedFieldsViaReflection(message.get()); - reflection_tester.ExpectPackedFieldsSetViaReflection(*message); -} - -TEST_F(DynamicMessageTest, SpaceUsed) { - // Test that SpaceUsed() works properly - - // Since we share the implementation with generated messages, we don't need - // to test very much here. Just make sure it appears to be working. - - scoped_ptr message(prototype_->New()); - TestUtil::ReflectionTester reflection_tester(descriptor_); - - int initial_space_used = message->SpaceUsed(); - - reflection_tester.SetAllFieldsViaReflection(message.get()); - EXPECT_LT(initial_space_used, message->SpaceUsed()); -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/extension_set.cc b/Resources/NetHook/google/protobuf/extension_set.cc deleted file mode 100644 index 6084885b..00000000 --- a/Resources/NetHook/google/protobuf/extension_set.cc +++ /dev/null @@ -1,1452 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { - -namespace { - -inline WireFormatLite::FieldType real_type(FieldType type) { - GOOGLE_DCHECK(type > 0 && type <= WireFormatLite::MAX_FIELD_TYPE); - return static_cast(type); -} - -inline WireFormatLite::CppType cpp_type(FieldType type) { - return WireFormatLite::FieldTypeToCppType(real_type(type)); -} - -// Registry stuff. -typedef hash_map, - ExtensionInfo> ExtensionRegistry; -ExtensionRegistry* registry_ = NULL; -GOOGLE_PROTOBUF_DECLARE_ONCE(registry_init_); - -void DeleteRegistry() { - delete registry_; - registry_ = NULL; -} - -void InitRegistry() { - registry_ = new ExtensionRegistry; - internal::OnShutdown(&DeleteRegistry); -} - -// This function is only called at startup, so there is no need for thread- -// safety. -void Register(const MessageLite* containing_type, - int number, ExtensionInfo info) { - ::google::protobuf::GoogleOnceInit(®istry_init_, &InitRegistry); - - if (!InsertIfNotPresent(registry_, make_pair(containing_type, number), - info)) { - GOOGLE_LOG(FATAL) << "Multiple extension registrations for type \"" - << containing_type->GetTypeName() - << "\", field number " << number << "."; - } -} - -const ExtensionInfo* FindRegisteredExtension( - const MessageLite* containing_type, int number) { - return (registry_ == NULL) ? NULL : - FindOrNull(*registry_, make_pair(containing_type, number)); -} - -} // namespace - -ExtensionFinder::~ExtensionFinder() {} - -bool GeneratedExtensionFinder::Find(int number, ExtensionInfo* output) { - const ExtensionInfo* extension = - FindRegisteredExtension(containing_type_, number); - if (extension == NULL) { - return false; - } else { - *output = *extension; - return true; - } -} - -void ExtensionSet::RegisterExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed) { - GOOGLE_CHECK_NE(type, WireFormatLite::TYPE_ENUM); - GOOGLE_CHECK_NE(type, WireFormatLite::TYPE_MESSAGE); - GOOGLE_CHECK_NE(type, WireFormatLite::TYPE_GROUP); - ExtensionInfo info(type, is_repeated, is_packed); - Register(containing_type, number, info); -} - -static bool CallNoArgValidityFunc(const void* arg, int number) { - // Note: Must use C-style cast here rather than reinterpret_cast because - // the C++ standard at one point did not allow casts between function and - // data pointers and some compilers enforce this for C++-style casts. No - // compiler enforces it for C-style casts since lots of C-style code has - // relied on these kinds of casts for a long time, despite being - // technically undefined. See: - // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#195 - // Also note: Some compilers do not allow function pointers to be "const". - // Which makes sense, I suppose, because it's meaningless. - return ((EnumValidityFunc*)arg)(number); -} - -void ExtensionSet::RegisterEnumExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed, - EnumValidityFunc* is_valid) { - GOOGLE_CHECK_EQ(type, WireFormatLite::TYPE_ENUM); - ExtensionInfo info(type, is_repeated, is_packed); - info.enum_validity_check.func = CallNoArgValidityFunc; - // See comment in CallNoArgValidityFunc() about why we use a c-style cast. - info.enum_validity_check.arg = (void*)is_valid; - Register(containing_type, number, info); -} - -void ExtensionSet::RegisterMessageExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed, - const MessageLite* prototype) { - GOOGLE_CHECK(type == WireFormatLite::TYPE_MESSAGE || - type == WireFormatLite::TYPE_GROUP); - ExtensionInfo info(type, is_repeated, is_packed); - info.message_prototype = prototype; - Register(containing_type, number, info); -} - - -// =================================================================== -// Constructors and basic methods. - -ExtensionSet::ExtensionSet() {} - -ExtensionSet::~ExtensionSet() { - for (map::iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.Free(); - } -} - -// Defined in extension_set_heavy.cc. -// void ExtensionSet::AppendToList(const Descriptor* containing_type, -// const DescriptorPool* pool, -// vector* output) const - -bool ExtensionSet::Has(int number) const { - map::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return false; - GOOGLE_DCHECK(!iter->second.is_repeated); - return !iter->second.is_cleared; -} - -int ExtensionSet::ExtensionSize(int number) const { - map::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return false; - return iter->second.GetSize(); -} - -void ExtensionSet::ClearExtension(int number) { - map::iterator iter = extensions_.find(number); - if (iter == extensions_.end()) return; - iter->second.Clear(); -} - -// =================================================================== -// Field accessors - -namespace { - -enum Cardinality { - REPEATED, - OPTIONAL -}; - -} // namespace - -#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \ - GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? REPEATED : OPTIONAL, LABEL); \ - GOOGLE_DCHECK_EQ(cpp_type((EXTENSION).type), WireFormatLite::CPPTYPE_##CPPTYPE) - -// ------------------------------------------------------------------- -// Primitives - -#define PRIMITIVE_ACCESSORS(UPPERCASE, LOWERCASE, CAMELCASE) \ - \ -LOWERCASE ExtensionSet::Get##CAMELCASE(int number, \ - LOWERCASE default_value) const { \ - map::const_iterator iter = extensions_.find(number); \ - if (iter == extensions_.end() || iter->second.is_cleared) { \ - return default_value; \ - } else { \ - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, UPPERCASE); \ - return iter->second.LOWERCASE##_value; \ - } \ -} \ - \ -void ExtensionSet::Set##CAMELCASE(int number, FieldType type, \ - LOWERCASE value, \ - const FieldDescriptor* descriptor) { \ - Extension* extension; \ - if (MaybeNewExtension(number, descriptor, &extension)) { \ - extension->type = type; \ - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_##UPPERCASE); \ - extension->is_repeated = false; \ - } else { \ - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, UPPERCASE); \ - } \ - extension->is_cleared = false; \ - extension->LOWERCASE##_value = value; \ -} \ - \ -LOWERCASE ExtensionSet::GetRepeated##CAMELCASE(int number, int index) const { \ - map::const_iterator iter = extensions_.find(number); \ - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \ - return iter->second.repeated_##LOWERCASE##_value->Get(index); \ -} \ - \ -void ExtensionSet::SetRepeated##CAMELCASE( \ - int number, int index, LOWERCASE value) { \ - map::iterator iter = extensions_.find(number); \ - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; \ - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, UPPERCASE); \ - iter->second.repeated_##LOWERCASE##_value->Set(index, value); \ -} \ - \ -void ExtensionSet::Add##CAMELCASE(int number, FieldType type, \ - bool packed, LOWERCASE value, \ - const FieldDescriptor* descriptor) { \ - Extension* extension; \ - if (MaybeNewExtension(number, descriptor, &extension)) { \ - extension->type = type; \ - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_##UPPERCASE); \ - extension->is_repeated = true; \ - extension->is_packed = packed; \ - extension->repeated_##LOWERCASE##_value = new RepeatedField(); \ - } else { \ - GOOGLE_DCHECK_TYPE(*extension, REPEATED, UPPERCASE); \ - GOOGLE_DCHECK_EQ(extension->is_packed, packed); \ - } \ - extension->repeated_##LOWERCASE##_value->Add(value); \ -} - -PRIMITIVE_ACCESSORS( INT32, int32, Int32) -PRIMITIVE_ACCESSORS( INT64, int64, Int64) -PRIMITIVE_ACCESSORS(UINT32, uint32, UInt32) -PRIMITIVE_ACCESSORS(UINT64, uint64, UInt64) -PRIMITIVE_ACCESSORS( FLOAT, float, Float) -PRIMITIVE_ACCESSORS(DOUBLE, double, Double) -PRIMITIVE_ACCESSORS( BOOL, bool, Bool) - -#undef PRIMITIVE_ACCESSORS - -// ------------------------------------------------------------------- -// Enums - -int ExtensionSet::GetEnum(int number, int default_value) const { - map::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { - // Not present. Return the default value. - return default_value; - } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, ENUM); - return iter->second.enum_value; - } -} - -void ExtensionSet::SetEnum(int number, FieldType type, int value, - const FieldDescriptor* descriptor) { - Extension* extension; - if (MaybeNewExtension(number, descriptor, &extension)) { - extension->type = type; - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_ENUM); - extension->is_repeated = false; - } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, ENUM); - } - extension->is_cleared = false; - extension->enum_value = value; -} - -int ExtensionSet::GetRepeatedEnum(int number, int index) const { - map::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); - return iter->second.repeated_enum_value->Get(index); -} - -void ExtensionSet::SetRepeatedEnum(int number, int index, int value) { - map::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, ENUM); - iter->second.repeated_enum_value->Set(index, value); -} - -void ExtensionSet::AddEnum(int number, FieldType type, - bool packed, int value, - const FieldDescriptor* descriptor) { - Extension* extension; - if (MaybeNewExtension(number, descriptor, &extension)) { - extension->type = type; - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_ENUM); - extension->is_repeated = true; - extension->is_packed = packed; - extension->repeated_enum_value = new RepeatedField(); - } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, ENUM); - GOOGLE_DCHECK_EQ(extension->is_packed, packed); - } - extension->repeated_enum_value->Add(value); -} - -// ------------------------------------------------------------------- -// Strings - -const string& ExtensionSet::GetString(int number, - const string& default_value) const { - map::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { - // Not present. Return the default value. - return default_value; - } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, STRING); - return *iter->second.string_value; - } -} - -string* ExtensionSet::MutableString(int number, FieldType type, - const FieldDescriptor* descriptor) { - Extension* extension; - if (MaybeNewExtension(number, descriptor, &extension)) { - extension->type = type; - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_STRING); - extension->is_repeated = false; - extension->string_value = new string; - } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, STRING); - } - extension->is_cleared = false; - return extension->string_value; -} - -const string& ExtensionSet::GetRepeatedString(int number, int index) const { - map::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); - return iter->second.repeated_string_value->Get(index); -} - -string* ExtensionSet::MutableRepeatedString(int number, int index) { - map::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, STRING); - return iter->second.repeated_string_value->Mutable(index); -} - -string* ExtensionSet::AddString(int number, FieldType type, - const FieldDescriptor* descriptor) { - Extension* extension; - if (MaybeNewExtension(number, descriptor, &extension)) { - extension->type = type; - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_STRING); - extension->is_repeated = true; - extension->is_packed = false; - extension->repeated_string_value = new RepeatedPtrField(); - } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, STRING); - } - return extension->repeated_string_value->Add(); -} - -// ------------------------------------------------------------------- -// Messages - -const MessageLite& ExtensionSet::GetMessage( - int number, const MessageLite& default_value) const { - map::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end()) { - // Not present. Return the default value. - return default_value; - } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); - return *iter->second.message_value; - } -} - -// Defined in extension_set_heavy.cc. -// const MessageLite& ExtensionSet::GetMessage(int number, -// const Descriptor* message_type, -// MessageFactory* factory) const - -MessageLite* ExtensionSet::MutableMessage(int number, FieldType type, - const MessageLite& prototype, - const FieldDescriptor* descriptor) { - Extension* extension; - if (MaybeNewExtension(number, descriptor, &extension)) { - extension->type = type; - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_MESSAGE); - extension->is_repeated = false; - extension->message_value = prototype.New(); - } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); - } - extension->is_cleared = false; - return extension->message_value; -} - -// Defined in extension_set_heavy.cc. -// MessageLite* ExtensionSet::MutableMessage(int number, FieldType type, -// const Descriptor* message_type, -// MessageFactory* factory) - -const MessageLite& ExtensionSet::GetRepeatedMessage( - int number, int index) const { - map::const_iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); - return iter->second.repeated_message_value->Get(index); -} - -MessageLite* ExtensionSet::MutableRepeatedMessage(int number, int index) { - map::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - GOOGLE_DCHECK_TYPE(iter->second, REPEATED, MESSAGE); - return iter->second.repeated_message_value->Mutable(index); -} - -MessageLite* ExtensionSet::AddMessage(int number, FieldType type, - const MessageLite& prototype, - const FieldDescriptor* descriptor) { - Extension* extension; - if (MaybeNewExtension(number, descriptor, &extension)) { - extension->type = type; - GOOGLE_DCHECK_EQ(cpp_type(extension->type), WireFormatLite::CPPTYPE_MESSAGE); - extension->is_repeated = true; - extension->repeated_message_value = - new RepeatedPtrField(); - } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); - } - - // RepeatedPtrField does not know how to Add() since it cannot - // allocate an abstract object, so we have to be tricky. - MessageLite* result = extension->repeated_message_value - ->AddFromCleared >(); - if (result == NULL) { - result = prototype.New(); - extension->repeated_message_value->AddAllocated(result); - } - return result; -} - -// Defined in extension_set_heavy.cc. -// MessageLite* ExtensionSet::AddMessage(int number, FieldType type, -// const Descriptor* message_type, -// MessageFactory* factory) - -#undef GOOGLE_DCHECK_TYPE - -void ExtensionSet::RemoveLast(int number) { - map::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; - GOOGLE_DCHECK(extension->is_repeated); - - switch(cpp_type(extension->type)) { - case WireFormatLite::CPPTYPE_INT32: - extension->repeated_int32_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_INT64: - extension->repeated_int64_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_UINT32: - extension->repeated_uint32_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_UINT64: - extension->repeated_uint64_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_FLOAT: - extension->repeated_float_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_DOUBLE: - extension->repeated_double_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_BOOL: - extension->repeated_bool_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_ENUM: - extension->repeated_enum_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_STRING: - extension->repeated_string_value->RemoveLast(); - break; - case WireFormatLite::CPPTYPE_MESSAGE: - extension->repeated_message_value->RemoveLast(); - break; - } -} - -void ExtensionSet::SwapElements(int number, int index1, int index2) { - map::iterator iter = extensions_.find(number); - GOOGLE_CHECK(iter != extensions_.end()) << "Index out-of-bounds (field is empty)."; - - Extension* extension = &iter->second; - GOOGLE_DCHECK(extension->is_repeated); - - switch(cpp_type(extension->type)) { - case WireFormatLite::CPPTYPE_INT32: - extension->repeated_int32_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_INT64: - extension->repeated_int64_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_UINT32: - extension->repeated_uint32_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_UINT64: - extension->repeated_uint64_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_FLOAT: - extension->repeated_float_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_DOUBLE: - extension->repeated_double_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_BOOL: - extension->repeated_bool_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_ENUM: - extension->repeated_enum_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_STRING: - extension->repeated_string_value->SwapElements(index1, index2); - break; - case WireFormatLite::CPPTYPE_MESSAGE: - extension->repeated_message_value->SwapElements(index1, index2); - break; - } -} - -// =================================================================== - -void ExtensionSet::Clear() { - for (map::iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - iter->second.Clear(); - } -} - -void ExtensionSet::MergeFrom(const ExtensionSet& other) { - for (map::const_iterator iter = other.extensions_.begin(); - iter != other.extensions_.end(); ++iter) { - const Extension& other_extension = iter->second; - - if (other_extension.is_repeated) { - Extension* extension; - bool is_new = MaybeNewExtension(iter->first, other_extension.descriptor, - &extension); - if (is_new) { - // Extension did not already exist in set. - extension->type = other_extension.type; - extension->is_repeated = true; - } else { - GOOGLE_DCHECK_EQ(extension->type, other_extension.type); - GOOGLE_DCHECK(extension->is_repeated); - } - - switch (cpp_type(other_extension.type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE, REPEATED_TYPE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - if (is_new) { \ - extension->repeated_##LOWERCASE##_value = \ - new REPEATED_TYPE; \ - } \ - extension->repeated_##LOWERCASE##_value->MergeFrom( \ - *other_extension.repeated_##LOWERCASE##_value); \ - break; - - HANDLE_TYPE( INT32, int32, RepeatedField < int32>); - HANDLE_TYPE( INT64, int64, RepeatedField < int64>); - HANDLE_TYPE( UINT32, uint32, RepeatedField < uint32>); - HANDLE_TYPE( UINT64, uint64, RepeatedField < uint64>); - HANDLE_TYPE( FLOAT, float, RepeatedField < float>); - HANDLE_TYPE( DOUBLE, double, RepeatedField < double>); - HANDLE_TYPE( BOOL, bool, RepeatedField < bool>); - HANDLE_TYPE( ENUM, enum, RepeatedField < int>); - HANDLE_TYPE( STRING, string, RepeatedPtrField< string>); -#undef HANDLE_TYPE - - case WireFormatLite::CPPTYPE_MESSAGE: - if (is_new) { - extension->repeated_message_value = - new RepeatedPtrField(); - } - // We can't call RepeatedPtrField::MergeFrom() because - // it would attempt to allocate new objects. - RepeatedPtrField* other_repeated_message = - other_extension.repeated_message_value; - for (int i = 0; i < other_repeated_message->size(); i++) { - const MessageLite& other_message = other_repeated_message->Get(i); - MessageLite* target = extension->repeated_message_value - ->AddFromCleared >(); - if (target == NULL) { - target = other_message.New(); - extension->repeated_message_value->AddAllocated(target); - } - target->CheckTypeAndMergeFrom(other_message); - } - break; - } - } else { - if (!other_extension.is_cleared) { - switch (cpp_type(other_extension.type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE, CAMELCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - Set##CAMELCASE(iter->first, other_extension.type, \ - other_extension.LOWERCASE##_value, \ - other_extension.descriptor); \ - break; - - HANDLE_TYPE( INT32, int32, Int32); - HANDLE_TYPE( INT64, int64, Int64); - HANDLE_TYPE(UINT32, uint32, UInt32); - HANDLE_TYPE(UINT64, uint64, UInt64); - HANDLE_TYPE( FLOAT, float, Float); - HANDLE_TYPE(DOUBLE, double, Double); - HANDLE_TYPE( BOOL, bool, Bool); - HANDLE_TYPE( ENUM, enum, Enum); -#undef HANDLE_TYPE - case WireFormatLite::CPPTYPE_STRING: - SetString(iter->first, other_extension.type, - *other_extension.string_value, - other_extension.descriptor); - break; - case WireFormatLite::CPPTYPE_MESSAGE: - MutableMessage(iter->first, other_extension.type, - *other_extension.message_value, - other_extension.descriptor) - ->CheckTypeAndMergeFrom(*other_extension.message_value); - break; - } - } - } - } -} - -void ExtensionSet::Swap(ExtensionSet* x) { - extensions_.swap(x->extensions_); -} - -bool ExtensionSet::IsInitialized() const { - // Extensions are never required. However, we need to check that all - // embedded messages are initialized. - for (map::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - const Extension& extension = iter->second; - if (cpp_type(extension.type) == WireFormatLite::CPPTYPE_MESSAGE) { - if (extension.is_repeated) { - for (int i = 0; i < extension.repeated_message_value->size(); i++) { - if (!extension.repeated_message_value->Get(i).IsInitialized()) { - return false; - } - } - } else { - if (!extension.is_cleared) { - if (!extension.message_value->IsInitialized()) return false; - } - } - } - } - - return true; -} - -bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, - ExtensionFinder* extension_finder, - FieldSkipper* field_skipper) { - int number = WireFormatLite::GetTagFieldNumber(tag); - WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); - - ExtensionInfo extension; - bool is_unknown; - if (!extension_finder->Find(number, &extension)) { - is_unknown = true; - } else if (extension.is_packed) { - is_unknown = (wire_type != WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - } else { - WireFormatLite::WireType expected_wire_type = - WireFormatLite::WireTypeForFieldType(real_type(extension.type)); - is_unknown = (wire_type != expected_wire_type); - } - - if (is_unknown) { - field_skipper->SkipField(input, tag); - } else if (extension.is_packed) { - uint32 size; - if (!input->ReadVarint32(&size)) return false; - io::CodedInputStream::Limit limit = input->PushLimit(size); - - switch (extension.type) { -#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - while (input->BytesUntilLimit() > 0) { \ - CPP_LOWERCASE value; \ - if (!WireFormatLite::ReadPrimitive< \ - CPP_LOWERCASE, WireFormatLite::TYPE_##UPPERCASE>( \ - input, &value)) return false; \ - Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ - true, value, extension.descriptor); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, Int32, int32); - HANDLE_TYPE( SINT64, Int64, int64); - HANDLE_TYPE( FIXED32, UInt32, uint32); - HANDLE_TYPE( FIXED64, UInt64, uint64); - HANDLE_TYPE(SFIXED32, Int32, int32); - HANDLE_TYPE(SFIXED64, Int64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); -#undef HANDLE_TYPE - - case WireFormatLite::TYPE_ENUM: - while (input->BytesUntilLimit() > 0) { - int value; - if (!WireFormatLite::ReadPrimitive( - input, &value)) return false; - if (extension.enum_validity_check.func( - extension.enum_validity_check.arg, value)) { - AddEnum(number, WireFormatLite::TYPE_ENUM, true, value, - extension.descriptor); - } - } - break; - - case WireFormatLite::TYPE_STRING: - case WireFormatLite::TYPE_BYTES: - case WireFormatLite::TYPE_GROUP: - case WireFormatLite::TYPE_MESSAGE: - GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed."; - break; - } - - input->PopLimit(limit); - } else { - switch (extension.type) { -#define HANDLE_TYPE(UPPERCASE, CPP_CAMELCASE, CPP_LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: { \ - CPP_LOWERCASE value; \ - if (!WireFormatLite::ReadPrimitive< \ - CPP_LOWERCASE, WireFormatLite::TYPE_##UPPERCASE>( \ - input, &value)) return false; \ - if (extension.is_repeated) { \ - Add##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, \ - false, value, extension.descriptor); \ - } else { \ - Set##CPP_CAMELCASE(number, WireFormatLite::TYPE_##UPPERCASE, value, \ - extension.descriptor); \ - } \ - } break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, Int32, int32); - HANDLE_TYPE( SINT64, Int64, int64); - HANDLE_TYPE( FIXED32, UInt32, uint32); - HANDLE_TYPE( FIXED64, UInt64, uint64); - HANDLE_TYPE(SFIXED32, Int32, int32); - HANDLE_TYPE(SFIXED64, Int64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); -#undef HANDLE_TYPE - - case WireFormatLite::TYPE_ENUM: { - int value; - if (!WireFormatLite::ReadPrimitive( - input, &value)) return false; - - if (!extension.enum_validity_check.func( - extension.enum_validity_check.arg, value)) { - // Invalid value. Treat as unknown. - field_skipper->SkipUnknownEnum(number, value); - } else if (extension.is_repeated) { - AddEnum(number, WireFormatLite::TYPE_ENUM, false, value, - extension.descriptor); - } else { - SetEnum(number, WireFormatLite::TYPE_ENUM, value, - extension.descriptor); - } - break; - } - - case WireFormatLite::TYPE_STRING: { - string* value = extension.is_repeated ? - AddString(number, WireFormatLite::TYPE_STRING, extension.descriptor) : - MutableString(number, WireFormatLite::TYPE_STRING, - extension.descriptor); - if (!WireFormatLite::ReadString(input, value)) return false; - break; - } - - case WireFormatLite::TYPE_BYTES: { - string* value = extension.is_repeated ? - AddString(number, WireFormatLite::TYPE_STRING, extension.descriptor) : - MutableString(number, WireFormatLite::TYPE_STRING, - extension.descriptor); - if (!WireFormatLite::ReadBytes(input, value)) return false; - break; - } - - case WireFormatLite::TYPE_GROUP: { - MessageLite* value = extension.is_repeated ? - AddMessage(number, WireFormatLite::TYPE_GROUP, - *extension.message_prototype, extension.descriptor) : - MutableMessage(number, WireFormatLite::TYPE_GROUP, - *extension.message_prototype, extension.descriptor); - if (!WireFormatLite::ReadGroup(number, input, value)) return false; - break; - } - - case WireFormatLite::TYPE_MESSAGE: { - MessageLite* value = extension.is_repeated ? - AddMessage(number, WireFormatLite::TYPE_MESSAGE, - *extension.message_prototype, extension.descriptor) : - MutableMessage(number, WireFormatLite::TYPE_MESSAGE, - *extension.message_prototype, extension.descriptor); - if (!WireFormatLite::ReadMessage(input, value)) return false; - break; - } - } - } - - return true; -} - -bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, - const MessageLite* containing_type) { - FieldSkipper skipper; - GeneratedExtensionFinder finder(containing_type); - return ParseField(tag, input, &finder, &skipper); -} - -// Defined in extension_set_heavy.cc. -// bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, -// const MessageLite* containing_type, -// UnknownFieldSet* unknown_fields) - -bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, - ExtensionFinder* extension_finder, - FieldSkipper* field_skipper) { - while (true) { - uint32 tag = input->ReadTag(); - switch (tag) { - case 0: - return true; - case WireFormatLite::kMessageSetItemStartTag: - if (!ParseMessageSetItem(input, extension_finder, field_skipper)) { - return false; - } - break; - default: - if (!ParseField(tag, input, extension_finder, field_skipper)) { - return false; - } - break; - } - } -} - -bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, - const MessageLite* containing_type) { - FieldSkipper skipper; - GeneratedExtensionFinder finder(containing_type); - return ParseMessageSet(input, &finder, &skipper); -} - -// Defined in extension_set_heavy.cc. -// bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, -// const MessageLite* containing_type, -// UnknownFieldSet* unknown_fields); - -bool ExtensionSet::ParseMessageSetItem(io::CodedInputStream* input, - ExtensionFinder* extension_finder, - FieldSkipper* field_skipper) { - // TODO(kenton): It would be nice to share code between this and - // WireFormatLite::ParseAndMergeMessageSetItem(), but I think the - // differences would be hard to factor out. - - // This method parses a group which should contain two fields: - // required int32 type_id = 2; - // required data message = 3; - - // Once we see a type_id, we'll construct a fake tag for this extension - // which is the tag it would have had under the proto2 extensions wire - // format. - uint32 fake_tag = 0; - - // If we see message data before the type_id, we'll append it to this so - // we can parse it later. This will probably never happen in practice, - // as no MessageSet encoder I know of writes the message before the type ID. - // But, it's technically valid so we should allow it. - // TODO(kenton): Use a Cord instead? Do I care? - string message_data; - - while (true) { - uint32 tag = input->ReadTag(); - if (tag == 0) return false; - - switch (tag) { - case WireFormatLite::kMessageSetTypeIdTag: { - uint32 type_id; - if (!input->ReadVarint32(&type_id)) return false; - fake_tag = WireFormatLite::MakeTag(type_id, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - - if (!message_data.empty()) { - // We saw some message data before the type_id. Have to parse it - // now. - io::CodedInputStream sub_input( - reinterpret_cast(message_data.data()), - message_data.size()); - if (!ParseField(fake_tag, &sub_input, - extension_finder, field_skipper)) { - return false; - } - message_data.clear(); - } - - break; - } - - case WireFormatLite::kMessageSetMessageTag: { - if (fake_tag == 0) { - // We haven't seen a type_id yet. Append this data to message_data. - string temp; - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->ReadString(&temp, length)) return false; - message_data.append(temp); - } else { - // Already saw type_id, so we can parse this directly. - if (!ParseField(fake_tag, input, - extension_finder, field_skipper)) { - return false; - } - } - - break; - } - - case WireFormatLite::kMessageSetItemEndTag: { - return true; - } - - default: { - if (!field_skipper->SkipField(input, tag)) return false; - } - } - } -} - -void ExtensionSet::SerializeWithCachedSizes( - int start_field_number, int end_field_number, - io::CodedOutputStream* output) const { - map::const_iterator iter; - for (iter = extensions_.lower_bound(start_field_number); - iter != extensions_.end() && iter->first < end_field_number; - ++iter) { - iter->second.SerializeFieldWithCachedSizes(iter->first, output); - } -} - -void ExtensionSet::SerializeMessageSetWithCachedSizes( - io::CodedOutputStream* output) const { - map::const_iterator iter; - for (iter = extensions_.begin(); iter != extensions_.end(); ++iter) { - iter->second.SerializeMessageSetItemWithCachedSizes(iter->first, output); - } -} - -int ExtensionSet::ByteSize() const { - int total_size = 0; - - for (map::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - total_size += iter->second.ByteSize(iter->first); - } - - return total_size; -} - -int ExtensionSet::MessageSetByteSize() const { - int total_size = 0; - - for (map::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - total_size += iter->second.MessageSetItemByteSize(iter->first); - } - - return total_size; -} - -// Defined in extension_set_heavy.cc. -// int ExtensionSet::SpaceUsedExcludingSelf() const - -bool ExtensionSet::MaybeNewExtension(int number, - const FieldDescriptor* descriptor, - Extension** result) { - pair::iterator, bool> insert_result = - extensions_.insert(make_pair(number, Extension())); - *result = &insert_result.first->second; - (*result)->descriptor = descriptor; - return insert_result.second; -} - -// =================================================================== -// Methods of ExtensionSet::Extension - -void ExtensionSet::Extension::Clear() { - if (is_repeated) { - switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - repeated_##LOWERCASE##_value->Clear(); \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); - HANDLE_TYPE(MESSAGE, message); -#undef HANDLE_TYPE - } - } else { - if (!is_cleared) { - switch (cpp_type(type)) { - case WireFormatLite::CPPTYPE_STRING: - string_value->clear(); - break; - case WireFormatLite::CPPTYPE_MESSAGE: - message_value->Clear(); - break; - default: - // No need to do anything. Get*() will return the default value - // as long as is_cleared is true and Set*() will overwrite the - // previous value. - break; - } - - is_cleared = true; - } - } -} - -void ExtensionSet::Extension::SerializeFieldWithCachedSizes( - int number, - io::CodedOutputStream* output) const { - if (is_repeated) { - if (is_packed) { - if (cached_size == 0) return; - - WireFormatLite::WriteTag(number, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(cached_size); - - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - WireFormatLite::Write##CAMELCASE##NoTag( \ - repeated_##LOWERCASE##_value->Get(i), output); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( ENUM, Enum, enum); -#undef HANDLE_TYPE - - case WireFormatLite::TYPE_STRING: - case WireFormatLite::TYPE_BYTES: - case WireFormatLite::TYPE_GROUP: - case WireFormatLite::TYPE_MESSAGE: - GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed."; - break; - } - } else { - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - WireFormatLite::Write##CAMELCASE(number, \ - repeated_##LOWERCASE##_value->Get(i), output); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( STRING, String, string); - HANDLE_TYPE( BYTES, Bytes, string); - HANDLE_TYPE( ENUM, Enum, enum); - HANDLE_TYPE( GROUP, Group, message); - HANDLE_TYPE( MESSAGE, Message, message); -#undef HANDLE_TYPE - } - } - } else if (!is_cleared) { - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - WireFormatLite::Write##CAMELCASE(number, VALUE, output); \ - break - - HANDLE_TYPE( INT32, Int32, int32_value); - HANDLE_TYPE( INT64, Int64, int64_value); - HANDLE_TYPE( UINT32, UInt32, uint32_value); - HANDLE_TYPE( UINT64, UInt64, uint64_value); - HANDLE_TYPE( SINT32, SInt32, int32_value); - HANDLE_TYPE( SINT64, SInt64, int64_value); - HANDLE_TYPE( FIXED32, Fixed32, uint32_value); - HANDLE_TYPE( FIXED64, Fixed64, uint64_value); - HANDLE_TYPE(SFIXED32, SFixed32, int32_value); - HANDLE_TYPE(SFIXED64, SFixed64, int64_value); - HANDLE_TYPE( FLOAT, Float, float_value); - HANDLE_TYPE( DOUBLE, Double, double_value); - HANDLE_TYPE( BOOL, Bool, bool_value); - HANDLE_TYPE( STRING, String, *string_value); - HANDLE_TYPE( BYTES, Bytes, *string_value); - HANDLE_TYPE( ENUM, Enum, enum_value); - HANDLE_TYPE( GROUP, Group, *message_value); - HANDLE_TYPE( MESSAGE, Message, *message_value); -#undef HANDLE_TYPE - } - } -} - -void ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizes( - int number, - io::CodedOutputStream* output) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but serialize it the normal way. - SerializeFieldWithCachedSizes(number, output); - return; - } - - if (is_cleared) return; - - // Start group. - output->WriteTag(WireFormatLite::kMessageSetItemStartTag); - - // Write type ID. - WireFormatLite::WriteUInt32(WireFormatLite::kMessageSetTypeIdNumber, - number, - output); - // Write message. - WireFormatLite::WriteMessageMaybeToArray( - WireFormatLite::kMessageSetMessageNumber, - *message_value, - output); - - // End group. - output->WriteTag(WireFormatLite::kMessageSetItemEndTag); -} - -int ExtensionSet::Extension::ByteSize(int number) const { - int result = 0; - - if (is_repeated) { - if (is_packed) { - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - result += WireFormatLite::CAMELCASE##Size( \ - repeated_##LOWERCASE##_value->Get(i)); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( ENUM, Enum, enum); -#undef HANDLE_TYPE - - // Stuff with fixed size. -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += WireFormatLite::k##CAMELCASE##Size * \ - repeated_##LOWERCASE##_value->size(); \ - break - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); -#undef HANDLE_TYPE - - case WireFormatLite::TYPE_STRING: - case WireFormatLite::TYPE_BYTES: - case WireFormatLite::TYPE_GROUP: - case WireFormatLite::TYPE_MESSAGE: - GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed."; - break; - } - - cached_size = result; - if (result > 0) { - result += io::CodedOutputStream::VarintSize32(result); - result += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(number, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); - } - } else { - int tag_size = WireFormatLite::TagSize(number, real_type(type)); - - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += tag_size * repeated_##LOWERCASE##_value->size(); \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - result += WireFormatLite::CAMELCASE##Size( \ - repeated_##LOWERCASE##_value->Get(i)); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( STRING, String, string); - HANDLE_TYPE( BYTES, Bytes, string); - HANDLE_TYPE( ENUM, Enum, enum); - HANDLE_TYPE( GROUP, Group, message); - HANDLE_TYPE( MESSAGE, Message, message); -#undef HANDLE_TYPE - - // Stuff with fixed size. -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += (tag_size + WireFormatLite::k##CAMELCASE##Size) * \ - repeated_##LOWERCASE##_value->size(); \ - break - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); -#undef HANDLE_TYPE - } - } - } else if (!is_cleared) { - result += WireFormatLite::TagSize(number, real_type(type)); - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += WireFormatLite::CAMELCASE##Size(LOWERCASE); \ - break - - HANDLE_TYPE( INT32, Int32, int32_value); - HANDLE_TYPE( INT64, Int64, int64_value); - HANDLE_TYPE( UINT32, UInt32, uint32_value); - HANDLE_TYPE( UINT64, UInt64, uint64_value); - HANDLE_TYPE( SINT32, SInt32, int32_value); - HANDLE_TYPE( SINT64, SInt64, int64_value); - HANDLE_TYPE( STRING, String, *string_value); - HANDLE_TYPE( BYTES, Bytes, *string_value); - HANDLE_TYPE( ENUM, Enum, enum_value); - HANDLE_TYPE( GROUP, Group, *message_value); - HANDLE_TYPE( MESSAGE, Message, *message_value); -#undef HANDLE_TYPE - - // Stuff with fixed size. -#define HANDLE_TYPE(UPPERCASE, CAMELCASE) \ - case WireFormatLite::TYPE_##UPPERCASE: \ - result += WireFormatLite::k##CAMELCASE##Size; \ - break - HANDLE_TYPE( FIXED32, Fixed32); - HANDLE_TYPE( FIXED64, Fixed64); - HANDLE_TYPE(SFIXED32, SFixed32); - HANDLE_TYPE(SFIXED64, SFixed64); - HANDLE_TYPE( FLOAT, Float); - HANDLE_TYPE( DOUBLE, Double); - HANDLE_TYPE( BOOL, Bool); -#undef HANDLE_TYPE - } - } - - return result; -} - -int ExtensionSet::Extension::MessageSetItemByteSize(int number) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but compute the byte size for it the - // normal way. - return ByteSize(number); - } - - if (is_cleared) return 0; - - int our_size = WireFormatLite::kMessageSetItemTagsSize; - - // type_id - our_size += io::CodedOutputStream::VarintSize32(number); - - // message - int message_size = message_value->ByteSize(); - - our_size += io::CodedOutputStream::VarintSize32(message_size); - our_size += message_size; - - return our_size; -} - -int ExtensionSet::Extension::GetSize() const { - GOOGLE_DCHECK(is_repeated); - switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - return repeated_##LOWERCASE##_value->size() - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); - HANDLE_TYPE(MESSAGE, message); -#undef HANDLE_TYPE - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return 0; -} - -void ExtensionSet::Extension::Free() { - if (is_repeated) { - switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case WireFormatLite::CPPTYPE_##UPPERCASE: \ - delete repeated_##LOWERCASE##_value; \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); - HANDLE_TYPE(MESSAGE, message); -#undef HANDLE_TYPE - } - } else { - switch (cpp_type(type)) { - case WireFormatLite::CPPTYPE_STRING: - delete string_value; - break; - case WireFormatLite::CPPTYPE_MESSAGE: - delete message_value; - break; - default: - break; - } - } -} - -// Defined in extension_set_heavy.cc. -// int ExtensionSet::Extension::SpaceUsedExcludingSelf() const - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/extension_set.h b/Resources/NetHook/google/protobuf/extension_set.h deleted file mode 100644 index 14d5d150..00000000 --- a/Resources/NetHook/google/protobuf/extension_set.h +++ /dev/null @@ -1,902 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This header is logically internal, but is made public because it is used -// from protocol-compiler-generated code, which may reside in other components. - -#ifndef GOOGLE_PROTOBUF_EXTENSION_SET_H__ -#define GOOGLE_PROTOBUF_EXTENSION_SET_H__ - -#include -#include -#include -#include -#include - -#include - -namespace google { - -namespace protobuf { - class Descriptor; // descriptor.h - class FieldDescriptor; // descriptor.h - class DescriptorPool; // descriptor.h - class MessageLite; // message_lite.h - class Message; // message.h - class MessageFactory; // message.h - class UnknownFieldSet; // unknown_field_set.h - namespace io { - class CodedInputStream; // coded_stream.h - class CodedOutputStream; // coded_stream.h - } - namespace internal { - class FieldSkipper; // wire_format_lite.h - class RepeatedPtrFieldBase; // repeated_field.h - } - template class RepeatedField; // repeated_field.h - template class RepeatedPtrField; // repeated_field.h -} - -namespace protobuf { -namespace internal { - -// Used to store values of type WireFormatLite::FieldType without having to -// #include wire_format_lite.h. Also, ensures that we use only one byte to -// store these values, which is important to keep the layout of -// ExtensionSet::Extension small. -typedef uint8 FieldType; - -// A function which, given an integer value, returns true if the number -// matches one of the defined values for the corresponding enum type. This -// is used with RegisterEnumExtension, below. -typedef bool EnumValidityFunc(int number); - -// Version of the above which takes an argument. This is needed to deal with -// extensions that are not compiled in. -typedef bool EnumValidityFuncWithArg(const void* arg, int number); - -// Information about a registered extension. -struct ExtensionInfo { - inline ExtensionInfo() {} - inline ExtensionInfo(FieldType type, bool is_repeated, bool is_packed) - : type(type), is_repeated(is_repeated), is_packed(is_packed), - descriptor(NULL) {} - - FieldType type; - bool is_repeated; - bool is_packed; - - struct EnumValidityCheck { - EnumValidityFuncWithArg* func; - const void* arg; - }; - - union { - EnumValidityCheck enum_validity_check; - const MessageLite* message_prototype; - }; - - // The descriptor for this extension, if one exists and is known. May be - // NULL. Must not be NULL if the descriptor for the extension does not - // live in the same pool as the descriptor for the containing type. - const FieldDescriptor* descriptor; -}; - -// Abstract interface for an object which looks up extension definitions. Used -// when parsing. -class LIBPROTOBUF_EXPORT ExtensionFinder { - public: - virtual ~ExtensionFinder(); - - // Find the extension with the given containing type and number. - virtual bool Find(int number, ExtensionInfo* output) = 0; -}; - -// Implementation of ExtensionFinder which finds extensions defined in .proto -// files which have been compiled into the binary. -class LIBPROTOBUF_EXPORT GeneratedExtensionFinder : public ExtensionFinder { - public: - GeneratedExtensionFinder(const MessageLite* containing_type) - : containing_type_(containing_type) {} - virtual ~GeneratedExtensionFinder() {} - - // Returns true and fills in *output if found, otherwise returns false. - virtual bool Find(int number, ExtensionInfo* output); - - private: - const MessageLite* containing_type_; -}; - -// Note: extension_set_heavy.cc defines DescriptorPoolExtensionFinder for -// finding extensions from a DescriptorPool. - -// This is an internal helper class intended for use within the protocol buffer -// library and generated classes. Clients should not use it directly. Instead, -// use the generated accessors such as GetExtension() of the class being -// extended. -// -// This class manages extensions for a protocol message object. The -// message's HasExtension(), GetExtension(), MutableExtension(), and -// ClearExtension() methods are just thin wrappers around the embedded -// ExtensionSet. When parsing, if a tag number is encountered which is -// inside one of the message type's extension ranges, the tag is passed -// off to the ExtensionSet for parsing. Etc. -class LIBPROTOBUF_EXPORT ExtensionSet { - public: - ExtensionSet(); - ~ExtensionSet(); - - // These are called at startup by protocol-compiler-generated code to - // register known extensions. The registrations are used by ParseField() - // to look up extensions for parsed field numbers. Note that dynamic parsing - // does not use ParseField(); only protocol-compiler-generated parsing - // methods do. - static void RegisterExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed); - static void RegisterEnumExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed, - EnumValidityFunc* is_valid); - static void RegisterMessageExtension(const MessageLite* containing_type, - int number, FieldType type, - bool is_repeated, bool is_packed, - const MessageLite* prototype); - - // ================================================================= - - // Add all fields which are currently present to the given vector. This - // is useful to implement Reflection::ListFields(). - void AppendToList(const Descriptor* containing_type, - const DescriptorPool* pool, - vector* output) const; - - // ================================================================= - // Accessors - // - // Generated message classes include type-safe templated wrappers around - // these methods. Generally you should use those rather than call these - // directly, unless you are doing low-level memory management. - // - // When calling any of these accessors, the extension number requested - // MUST exist in the DescriptorPool provided to the constructor. Otheriwse, - // the method will fail an assert. Normally, though, you would not call - // these directly; you would either call the generated accessors of your - // message class (e.g. GetExtension()) or you would call the accessors - // of the reflection interface. In both cases, it is impossible to - // trigger this assert failure: the generated accessors only accept - // linked-in extension types as parameters, while the Reflection interface - // requires you to provide the FieldDescriptor describing the extension. - // - // When calling any of these accessors, a protocol-compiler-generated - // implementation of the extension corresponding to the number MUST - // be linked in, and the FieldDescriptor used to refer to it MUST be - // the one generated by that linked-in code. Otherwise, the method will - // die on an assert failure. The message objects returned by the message - // accessors are guaranteed to be of the correct linked-in type. - // - // These methods pretty much match Reflection except that: - // - They're not virtual. - // - They identify fields by number rather than FieldDescriptors. - // - They identify enum values using integers rather than descriptors. - // - Strings provide Mutable() in addition to Set() accessors. - - bool Has(int number) const; - int ExtensionSize(int number) const; // Size of a repeated extension. - void ClearExtension(int number); - - // singular fields ------------------------------------------------- - - int32 GetInt32 (int number, int32 default_value) const; - int64 GetInt64 (int number, int64 default_value) const; - uint32 GetUInt32(int number, uint32 default_value) const; - uint64 GetUInt64(int number, uint64 default_value) const; - float GetFloat (int number, float default_value) const; - double GetDouble(int number, double default_value) const; - bool GetBool (int number, bool default_value) const; - int GetEnum (int number, int default_value) const; - const string & GetString (int number, const string& default_value) const; - const MessageLite& GetMessage(int number, - const MessageLite& default_value) const; - const MessageLite& GetMessage(int number, const Descriptor* message_type, - MessageFactory* factory) const; - - // |descriptor| may be NULL so long as it is known that the descriptor for - // the extension lives in the same pool as the descriptor for the containing - // type. -#define desc const FieldDescriptor* descriptor // avoid line wrapping - void SetInt32 (int number, FieldType type, int32 value, desc); - void SetInt64 (int number, FieldType type, int64 value, desc); - void SetUInt32(int number, FieldType type, uint32 value, desc); - void SetUInt64(int number, FieldType type, uint64 value, desc); - void SetFloat (int number, FieldType type, float value, desc); - void SetDouble(int number, FieldType type, double value, desc); - void SetBool (int number, FieldType type, bool value, desc); - void SetEnum (int number, FieldType type, int value, desc); - void SetString(int number, FieldType type, const string& value, desc); - string * MutableString (int number, FieldType type, desc); - MessageLite* MutableMessage(int number, FieldType type, - const MessageLite& prototype, desc); - MessageLite* MutableMessage(const FieldDescriptor* decsriptor, - MessageFactory* factory); -#undef desc - - // repeated fields ------------------------------------------------- - - int32 GetRepeatedInt32 (int number, int index) const; - int64 GetRepeatedInt64 (int number, int index) const; - uint32 GetRepeatedUInt32(int number, int index) const; - uint64 GetRepeatedUInt64(int number, int index) const; - float GetRepeatedFloat (int number, int index) const; - double GetRepeatedDouble(int number, int index) const; - bool GetRepeatedBool (int number, int index) const; - int GetRepeatedEnum (int number, int index) const; - const string & GetRepeatedString (int number, int index) const; - const MessageLite& GetRepeatedMessage(int number, int index) const; - - void SetRepeatedInt32 (int number, int index, int32 value); - void SetRepeatedInt64 (int number, int index, int64 value); - void SetRepeatedUInt32(int number, int index, uint32 value); - void SetRepeatedUInt64(int number, int index, uint64 value); - void SetRepeatedFloat (int number, int index, float value); - void SetRepeatedDouble(int number, int index, double value); - void SetRepeatedBool (int number, int index, bool value); - void SetRepeatedEnum (int number, int index, int value); - void SetRepeatedString(int number, int index, const string& value); - string * MutableRepeatedString (int number, int index); - MessageLite* MutableRepeatedMessage(int number, int index); - -#define desc const FieldDescriptor* descriptor // avoid line wrapping - void AddInt32 (int number, FieldType type, bool packed, int32 value, desc); - void AddInt64 (int number, FieldType type, bool packed, int64 value, desc); - void AddUInt32(int number, FieldType type, bool packed, uint32 value, desc); - void AddUInt64(int number, FieldType type, bool packed, uint64 value, desc); - void AddFloat (int number, FieldType type, bool packed, float value, desc); - void AddDouble(int number, FieldType type, bool packed, double value, desc); - void AddBool (int number, FieldType type, bool packed, bool value, desc); - void AddEnum (int number, FieldType type, bool packed, int value, desc); - void AddString(int number, FieldType type, const string& value, desc); - string * AddString (int number, FieldType type, desc); - MessageLite* AddMessage(int number, FieldType type, - const MessageLite& prototype, desc); - MessageLite* AddMessage(const FieldDescriptor* descriptor, - MessageFactory* factory); -#undef desc - - void RemoveLast(int number); - void SwapElements(int number, int index1, int index2); - - // ----------------------------------------------------------------- - // TODO(kenton): Hardcore memory management accessors - - // ================================================================= - // convenience methods for implementing methods of Message - // - // These could all be implemented in terms of the other methods of this - // class, but providing them here helps keep the generated code size down. - - void Clear(); - void MergeFrom(const ExtensionSet& other); - void Swap(ExtensionSet* other); - bool IsInitialized() const; - - // Parses a single extension from the input. The input should start out - // positioned immediately after the tag. |containing_type| is the default - // instance for the containing message; it is used only to look up the - // extension by number. See RegisterExtension(), above. Unlike the other - // methods of ExtensionSet, this only works for generated message types -- - // it looks up extensions registered using RegisterExtension(). - bool ParseField(uint32 tag, io::CodedInputStream* input, - ExtensionFinder* extension_finder, - FieldSkipper* field_skipper); - - // Specific versions for lite or full messages (constructs the appropriate - // FieldSkipper automatically). - bool ParseField(uint32 tag, io::CodedInputStream* input, - const MessageLite* containing_type); - bool ParseField(uint32 tag, io::CodedInputStream* input, - const Message* containing_type, - UnknownFieldSet* unknown_fields); - - // Parse an entire message in MessageSet format. Such messages have no - // fields, only extensions. - bool ParseMessageSet(io::CodedInputStream* input, - ExtensionFinder* extension_finder, - FieldSkipper* field_skipper); - - // Specific versions for lite or full messages (constructs the appropriate - // FieldSkipper automatically). - bool ParseMessageSet(io::CodedInputStream* input, - const MessageLite* containing_type); - bool ParseMessageSet(io::CodedInputStream* input, - const Message* containing_type, - UnknownFieldSet* unknown_fields); - - // Write all extension fields with field numbers in the range - // [start_field_number, end_field_number) - // to the output stream, using the cached sizes computed when ByteSize() was - // last called. Note that the range bounds are inclusive-exclusive. - void SerializeWithCachedSizes(int start_field_number, - int end_field_number, - io::CodedOutputStream* output) const; - - // Same as SerializeWithCachedSizes, but without any bounds checking. - // The caller must ensure that target has sufficient capacity for the - // serialized extensions. - // - // Returns a pointer past the last written byte. - uint8* SerializeWithCachedSizesToArray(int start_field_number, - int end_field_number, - uint8* target) const; - - // Like above but serializes in MessageSet format. - void SerializeMessageSetWithCachedSizes(io::CodedOutputStream* output) const; - uint8* SerializeMessageSetWithCachedSizesToArray(uint8* target) const; - - // Returns the total serialized size of all the extensions. - int ByteSize() const; - - // Like ByteSize() but uses MessageSet format. - int MessageSetByteSize() const; - - // Returns (an estimate of) the total number of bytes used for storing the - // extensions in memory, excluding sizeof(*this). If the ExtensionSet is - // for a lite message (and thus possibly contains lite messages), the results - // are undefined (might work, might crash, might corrupt data, might not even - // be linked in). It's up to the protocol compiler to avoid calling this on - // such ExtensionSets (easy enough since lite messages don't implement - // SpaceUsed()). - int SpaceUsedExcludingSelf() const; - - private: - - struct Extension { - union { - int32 int32_value; - int64 int64_value; - uint32 uint32_value; - uint64 uint64_value; - float float_value; - double double_value; - bool bool_value; - int enum_value; - string* string_value; - MessageLite* message_value; - - RepeatedField * repeated_int32_value; - RepeatedField * repeated_int64_value; - RepeatedField * repeated_uint32_value; - RepeatedField * repeated_uint64_value; - RepeatedField * repeated_float_value; - RepeatedField * repeated_double_value; - RepeatedField * repeated_bool_value; - RepeatedField * repeated_enum_value; - RepeatedPtrField* repeated_string_value; - RepeatedPtrField* repeated_message_value; - }; - - FieldType type; - bool is_repeated; - - // For singular types, indicates if the extension is "cleared". This - // happens when an extension is set and then later cleared by the caller. - // We want to keep the Extension object around for reuse, so instead of - // removing it from the map, we just set is_cleared = true. This has no - // meaning for repeated types; for those, the size of the RepeatedField - // simply becomes zero when cleared. - bool is_cleared; - - // For repeated types, this indicates if the [packed=true] option is set. - bool is_packed; - - // The descriptor for this extension, if one exists and is known. May be - // NULL. Must not be NULL if the descriptor for the extension does not - // live in the same pool as the descriptor for the containing type. - const FieldDescriptor* descriptor; - - // For packed fields, the size of the packed data is recorded here when - // ByteSize() is called then used during serialization. - // TODO(kenton): Use atomic when C++ supports it. - mutable int cached_size; - - // Some helper methods for operations on a single Extension. - void SerializeFieldWithCachedSizes( - int number, - io::CodedOutputStream* output) const; - uint8* SerializeFieldWithCachedSizesToArray( - int number, - uint8* target) const; - void SerializeMessageSetItemWithCachedSizes( - int number, - io::CodedOutputStream* output) const; - uint8* SerializeMessageSetItemWithCachedSizesToArray( - int number, - uint8* target) const; - int ByteSize(int number) const; - int MessageSetItemByteSize(int number) const; - void Clear(); - int GetSize() const; - void Free(); - int SpaceUsedExcludingSelf() const; - }; - - // Gets the extension with the given number, creating it if it does not - // already exist. Returns true if the extension did not already exist. - bool MaybeNewExtension(int number, const FieldDescriptor* descriptor, - Extension** result); - - // Parse a single MessageSet item -- called just after the item group start - // tag has been read. - bool ParseMessageSetItem(io::CodedInputStream* input, - ExtensionFinder* extension_finder, - FieldSkipper* field_skipper); - - - // Hack: RepeatedPtrFieldBase declares ExtensionSet as a friend. This - // friendship should automatically extend to ExtensionSet::Extension, but - // unfortunately some older compilers (e.g. GCC 3.4.4) do not implement this - // correctly. So, we must provide helpers for calling methods of that - // class. - - // Defined in extension_set_heavy.cc. - static inline int RepeatedMessage_SpaceUsedExcludingSelf( - RepeatedPtrFieldBase* field); - - // The Extension struct is small enough to be passed by value, so we use it - // directly as the value type in the map rather than use pointers. We use - // a map rather than hash_map here because we expect most ExtensionSets will - // only contain a small number of extensions whereas hash_map is optimized - // for 100 elements or more. Also, we want AppendToList() to order fields - // by field number. - map extensions_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionSet); -}; - -// These are just for convenience... -inline void ExtensionSet::SetString(int number, FieldType type, - const string& value, - const FieldDescriptor* descriptor) { - MutableString(number, type, descriptor)->assign(value); -} -inline void ExtensionSet::SetRepeatedString(int number, int index, - const string& value) { - MutableRepeatedString(number, index)->assign(value); -} -inline void ExtensionSet::AddString(int number, FieldType type, - const string& value, - const FieldDescriptor* descriptor) { - AddString(number, type, descriptor)->assign(value); -} - -// =================================================================== -// Glue for generated extension accessors - -// ------------------------------------------------------------------- -// Template magic - -// First we have a set of classes representing "type traits" for different -// field types. A type traits class knows how to implement basic accessors -// for extensions of a particular type given an ExtensionSet. The signature -// for a type traits class looks like this: -// -// class TypeTraits { -// public: -// typedef ? ConstType; -// typedef ? MutableType; -// -// static inline ConstType Get(int number, const ExtensionSet& set); -// static inline void Set(int number, ConstType value, ExtensionSet* set); -// static inline MutableType Mutable(int number, ExtensionSet* set); -// -// // Variants for repeated fields. -// static inline ConstType Get(int number, const ExtensionSet& set, -// int index); -// static inline void Set(int number, int index, -// ConstType value, ExtensionSet* set); -// static inline MutableType Mutable(int number, int index, -// ExtensionSet* set); -// static inline void Add(int number, ConstType value, ExtensionSet* set); -// static inline MutableType Add(int number, ExtensionSet* set); -// }; -// -// Not all of these methods make sense for all field types. For example, the -// "Mutable" methods only make sense for strings and messages, and the -// repeated methods only make sense for repeated types. So, each type -// traits class implements only the set of methods from this signature that it -// actually supports. This will cause a compiler error if the user tries to -// access an extension using a method that doesn't make sense for its type. -// For example, if "foo" is an extension of type "optional int32", then if you -// try to write code like: -// my_message.MutableExtension(foo) -// you will get a compile error because PrimitiveTypeTraits does not -// have a "Mutable()" method. - -// ------------------------------------------------------------------- -// PrimitiveTypeTraits - -// Since the ExtensionSet has different methods for each primitive type, -// we must explicitly define the methods of the type traits class for each -// known type. -template -class PrimitiveTypeTraits { - public: - typedef Type ConstType; - - static inline ConstType Get(int number, const ExtensionSet& set, - ConstType default_value); - static inline void Set(int number, FieldType field_type, - ConstType value, ExtensionSet* set); -}; - -template -class RepeatedPrimitiveTypeTraits { - public: - typedef Type ConstType; - - static inline Type Get(int number, const ExtensionSet& set, int index); - static inline void Set(int number, int index, Type value, ExtensionSet* set); - static inline void Add(int number, FieldType field_type, - bool is_packed, Type value, ExtensionSet* set); -}; - -#define PROTOBUF_DEFINE_PRIMITIVE_TYPE(TYPE, METHOD) \ -template<> inline TYPE PrimitiveTypeTraits::Get( \ - int number, const ExtensionSet& set, TYPE default_value) { \ - return set.Get##METHOD(number, default_value); \ -} \ -template<> inline void PrimitiveTypeTraits::Set( \ - int number, FieldType field_type, TYPE value, ExtensionSet* set) { \ - set->Set##METHOD(number, field_type, value, NULL); \ -} \ - \ -template<> inline TYPE RepeatedPrimitiveTypeTraits::Get( \ - int number, const ExtensionSet& set, int index) { \ - return set.GetRepeated##METHOD(number, index); \ -} \ -template<> inline void RepeatedPrimitiveTypeTraits::Set( \ - int number, int index, TYPE value, ExtensionSet* set) { \ - set->SetRepeated##METHOD(number, index, value); \ -} \ -template<> inline void RepeatedPrimitiveTypeTraits::Add( \ - int number, FieldType field_type, bool is_packed, \ - TYPE value, ExtensionSet* set) { \ - set->Add##METHOD(number, field_type, is_packed, value, NULL); \ -} - -PROTOBUF_DEFINE_PRIMITIVE_TYPE( int32, Int32) -PROTOBUF_DEFINE_PRIMITIVE_TYPE( int64, Int64) -PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint32, UInt32) -PROTOBUF_DEFINE_PRIMITIVE_TYPE(uint64, UInt64) -PROTOBUF_DEFINE_PRIMITIVE_TYPE( float, Float) -PROTOBUF_DEFINE_PRIMITIVE_TYPE(double, Double) -PROTOBUF_DEFINE_PRIMITIVE_TYPE( bool, Bool) - -#undef PROTOBUF_DEFINE_PRIMITIVE_TYPE - -// ------------------------------------------------------------------- -// StringTypeTraits - -// Strings support both Set() and Mutable(). -class LIBPROTOBUF_EXPORT StringTypeTraits { - public: - typedef const string& ConstType; - typedef string* MutableType; - - static inline const string& Get(int number, const ExtensionSet& set, - ConstType default_value) { - return set.GetString(number, default_value); - } - static inline void Set(int number, FieldType field_type, - const string& value, ExtensionSet* set) { - set->SetString(number, field_type, value, NULL); - } - static inline string* Mutable(int number, FieldType field_type, - ExtensionSet* set) { - return set->MutableString(number, field_type, NULL); - } -}; - -class LIBPROTOBUF_EXPORT RepeatedStringTypeTraits { - public: - typedef const string& ConstType; - typedef string* MutableType; - - static inline const string& Get(int number, const ExtensionSet& set, - int index) { - return set.GetRepeatedString(number, index); - } - static inline void Set(int number, int index, - const string& value, ExtensionSet* set) { - set->SetRepeatedString(number, index, value); - } - static inline string* Mutable(int number, int index, ExtensionSet* set) { - return set->MutableRepeatedString(number, index); - } - static inline void Add(int number, FieldType field_type, - bool /*is_packed*/, const string& value, - ExtensionSet* set) { - set->AddString(number, field_type, value, NULL); - } - static inline string* Add(int number, FieldType field_type, - ExtensionSet* set) { - return set->AddString(number, field_type, NULL); - } -}; - -// ------------------------------------------------------------------- -// EnumTypeTraits - -// ExtensionSet represents enums using integers internally, so we have to -// static_cast around. -template -class EnumTypeTraits { - public: - typedef Type ConstType; - - static inline ConstType Get(int number, const ExtensionSet& set, - ConstType default_value) { - return static_cast(set.GetEnum(number, default_value)); - } - static inline void Set(int number, FieldType field_type, - ConstType value, ExtensionSet* set) { - GOOGLE_DCHECK(IsValid(value)); - set->SetEnum(number, field_type, value, NULL); - } -}; - -template -class RepeatedEnumTypeTraits { - public: - typedef Type ConstType; - - static inline ConstType Get(int number, const ExtensionSet& set, int index) { - return static_cast(set.GetRepeatedEnum(number, index)); - } - static inline void Set(int number, int index, - ConstType value, ExtensionSet* set) { - GOOGLE_DCHECK(IsValid(value)); - set->SetRepeatedEnum(number, index, value); - } - static inline void Add(int number, FieldType field_type, - bool is_packed, ConstType value, ExtensionSet* set) { - GOOGLE_DCHECK(IsValid(value)); - set->AddEnum(number, field_type, is_packed, value, NULL); - } -}; - -// ------------------------------------------------------------------- -// MessageTypeTraits - -// ExtensionSet guarantees that when manipulating extensions with message -// types, the implementation used will be the compiled-in class representing -// that type. So, we can static_cast down to the exact type we expect. -template -class MessageTypeTraits { - public: - typedef const Type& ConstType; - typedef Type* MutableType; - - static inline ConstType Get(int number, const ExtensionSet& set, - ConstType default_value) { - return static_cast( - set.GetMessage(number, default_value)); - } - static inline MutableType Mutable(int number, FieldType field_type, - ExtensionSet* set) { - return static_cast( - set->MutableMessage(number, field_type, Type::default_instance(), NULL)); - } -}; - -template -class RepeatedMessageTypeTraits { - public: - typedef const Type& ConstType; - typedef Type* MutableType; - - static inline ConstType Get(int number, const ExtensionSet& set, int index) { - return static_cast(set.GetRepeatedMessage(number, index)); - } - static inline MutableType Mutable(int number, int index, ExtensionSet* set) { - return static_cast(set->MutableRepeatedMessage(number, index)); - } - static inline MutableType Add(int number, FieldType field_type, - ExtensionSet* set) { - return static_cast( - set->AddMessage(number, field_type, Type::default_instance(), NULL)); - } -}; - -// ------------------------------------------------------------------- -// ExtensionIdentifier - -// This is the type of actual extension objects. E.g. if you have: -// extends Foo with optional int32 bar = 1234; -// then "bar" will be defined in C++ as: -// ExtensionIdentifier, 1, false> bar(1234); -// -// Note that we could, in theory, supply the field number as a template -// parameter, and thus make an instance of ExtensionIdentifier have no -// actual contents. However, if we did that, then using at extension -// identifier would not necessarily cause the compiler to output any sort -// of reference to any simple defined in the extension's .pb.o file. Some -// linkers will actually drop object files that are not explicitly referenced, -// but that would be bad because it would cause this extension to not be -// registered at static initialization, and therefore using it would crash. - -template -class ExtensionIdentifier { - public: - typedef TypeTraitsType TypeTraits; - typedef ExtendeeType Extendee; - - ExtensionIdentifier(int number, typename TypeTraits::ConstType default_value) - : number_(number), default_value_(default_value) {} - inline int number() const { return number_; } - typename TypeTraits::ConstType default_value() const { - return default_value_; - } - - private: - const int number_; - typename TypeTraits::ConstType default_value_; -}; - -// ------------------------------------------------------------------- -// Generated accessors - -// This macro should be expanded in the context of a generated type which -// has extensions. -// -// We use "_proto_TypeTraits" as a type name below because "TypeTraits" -// causes problems if the class has a nested message or enum type with that -// name and "_TypeTraits" is technically reserved for the C++ library since -// it starts with an underscore followed by a capital letter. -#define GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(CLASSNAME) \ - /* Has, Size, Clear */ \ - template \ - inline bool HasExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id) const { \ - return _extensions_.Has(id.number()); \ - } \ - \ - template \ - inline void ClearExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id) { \ - _extensions_.ClearExtension(id.number()); \ - } \ - \ - template \ - inline int ExtensionSize( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id) const { \ - return _extensions_.ExtensionSize(id.number()); \ - } \ - \ - /* Singular accessors */ \ - template \ - inline typename _proto_TypeTraits::ConstType GetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id) const { \ - return _proto_TypeTraits::Get(id.number(), _extensions_, \ - id.default_value()); \ - } \ - \ - template \ - inline typename _proto_TypeTraits::MutableType MutableExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id) { \ - return _proto_TypeTraits::Mutable(id.number(), field_type, &_extensions_);\ - } \ - \ - template \ - inline void SetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id, \ - typename _proto_TypeTraits::ConstType value) { \ - _proto_TypeTraits::Set(id.number(), field_type, value, &_extensions_); \ - } \ - \ - /* Repeated accessors */ \ - template \ - inline typename _proto_TypeTraits::ConstType GetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id, \ - int index) const { \ - return _proto_TypeTraits::Get(id.number(), _extensions_, index); \ - } \ - \ - template \ - inline typename _proto_TypeTraits::MutableType MutableExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id, \ - int index) { \ - return _proto_TypeTraits::Mutable(id.number(), index, &_extensions_); \ - } \ - \ - template \ - inline void SetExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id, \ - int index, typename _proto_TypeTraits::ConstType value) { \ - _proto_TypeTraits::Set(id.number(), index, value, &_extensions_); \ - } \ - \ - template \ - inline typename _proto_TypeTraits::MutableType AddExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id) { \ - return _proto_TypeTraits::Add(id.number(), field_type, &_extensions_); \ - } \ - \ - template \ - inline void AddExtension( \ - const ::google::protobuf::internal::ExtensionIdentifier< \ - CLASSNAME, _proto_TypeTraits, field_type, is_packed>& id, \ - typename _proto_TypeTraits::ConstType value) { \ - _proto_TypeTraits::Add(id.number(), field_type, is_packed, \ - value, &_extensions_); \ - } - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_EXTENSION_SET_H__ diff --git a/Resources/NetHook/google/protobuf/extension_set_heavy.cc b/Resources/NetHook/google/protobuf/extension_set_heavy.cc deleted file mode 100644 index 2721f15d..00000000 --- a/Resources/NetHook/google/protobuf/extension_set_heavy.cc +++ /dev/null @@ -1,457 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Contains methods defined in extension_set.h which cannot be part of the -// lite library because they use descriptors or reflection. - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { - -// Implementation of ExtensionFinder which finds extensions in a given -// DescriptorPool, using the given MessageFactory to construct sub-objects. -// This class is implemented in extension_set_heavy.cc. -class DescriptorPoolExtensionFinder : public ExtensionFinder { - public: - DescriptorPoolExtensionFinder(const DescriptorPool* pool, - MessageFactory* factory, - const Descriptor* containing_type) - : pool_(pool), factory_(factory), containing_type_(containing_type) {} - virtual ~DescriptorPoolExtensionFinder() {} - - virtual bool Find(int number, ExtensionInfo* output); - - private: - const DescriptorPool* pool_; - MessageFactory* factory_; - const Descriptor* containing_type_; -}; - -void ExtensionSet::AppendToList(const Descriptor* containing_type, - const DescriptorPool* pool, - vector* output) const { - for (map::const_iterator iter = extensions_.begin(); - iter != extensions_.end(); ++iter) { - bool has = false; - if (iter->second.is_repeated) { - has = iter->second.GetSize() > 0; - } else { - has = !iter->second.is_cleared; - } - - if (has) { - // TODO(kenton): Looking up each field by number is somewhat unfortunate. - // Is there a better way? The problem is that descriptors are lazily- - // initialized, so they might not even be constructed until - // AppendToList() is called. - - if (iter->second.descriptor == NULL) { - output->push_back(pool->FindExtensionByNumber( - containing_type, iter->first)); - } else { - output->push_back(iter->second.descriptor); - } - } - } -} - -inline FieldDescriptor::Type real_type(FieldType type) { - GOOGLE_DCHECK(type > 0 && type <= FieldDescriptor::MAX_TYPE); - return static_cast(type); -} - -inline FieldDescriptor::CppType cpp_type(FieldType type) { - return FieldDescriptor::TypeToCppType( - static_cast(type)); -} - -#define GOOGLE_DCHECK_TYPE(EXTENSION, LABEL, CPPTYPE) \ - GOOGLE_DCHECK_EQ((EXTENSION).is_repeated ? FieldDescriptor::LABEL_REPEATED \ - : FieldDescriptor::LABEL_OPTIONAL, \ - FieldDescriptor::LABEL_##LABEL); \ - GOOGLE_DCHECK_EQ(cpp_type((EXTENSION).type), FieldDescriptor::CPPTYPE_##CPPTYPE) - -const MessageLite& ExtensionSet::GetMessage(int number, - const Descriptor* message_type, - MessageFactory* factory) const { - map::const_iterator iter = extensions_.find(number); - if (iter == extensions_.end() || iter->second.is_cleared) { - // Not present. Return the default value. - return *factory->GetPrototype(message_type); - } else { - GOOGLE_DCHECK_TYPE(iter->second, OPTIONAL, MESSAGE); - return *iter->second.message_value; - } -} - -MessageLite* ExtensionSet::MutableMessage(const FieldDescriptor* descriptor, - MessageFactory* factory) { - Extension* extension; - if (MaybeNewExtension(descriptor->number(), descriptor, &extension)) { - extension->type = descriptor->type(); - GOOGLE_DCHECK_EQ(cpp_type(extension->type), FieldDescriptor::CPPTYPE_MESSAGE); - extension->is_repeated = false; - extension->is_packed = false; - const MessageLite* prototype = - factory->GetPrototype(descriptor->message_type()); - GOOGLE_CHECK(prototype != NULL); - extension->message_value = prototype->New(); - } else { - GOOGLE_DCHECK_TYPE(*extension, OPTIONAL, MESSAGE); - } - extension->is_cleared = false; - return extension->message_value; -} - -MessageLite* ExtensionSet::AddMessage(const FieldDescriptor* descriptor, - MessageFactory* factory) { - Extension* extension; - if (MaybeNewExtension(descriptor->number(), descriptor, &extension)) { - extension->type = descriptor->type(); - GOOGLE_DCHECK_EQ(cpp_type(extension->type), FieldDescriptor::CPPTYPE_MESSAGE); - extension->is_repeated = true; - extension->repeated_message_value = - new RepeatedPtrField(); - } else { - GOOGLE_DCHECK_TYPE(*extension, REPEATED, MESSAGE); - } - - // RepeatedPtrField does not know how to Add() since it cannot - // allocate an abstract object, so we have to be tricky. - MessageLite* result = extension->repeated_message_value - ->AddFromCleared >(); - if (result == NULL) { - const MessageLite* prototype; - if (extension->repeated_message_value->size() == 0) { - prototype = factory->GetPrototype(descriptor->message_type()); - GOOGLE_CHECK(prototype != NULL); - } else { - prototype = &extension->repeated_message_value->Get(0); - } - result = prototype->New(); - extension->repeated_message_value->AddAllocated(result); - } - return result; -} - -static bool ValidateEnumUsingDescriptor(const void* arg, int number) { - return reinterpret_cast(arg) - ->FindValueByNumber(number) != NULL; -} - -bool DescriptorPoolExtensionFinder::Find(int number, ExtensionInfo* output) { - const FieldDescriptor* extension = - pool_->FindExtensionByNumber(containing_type_, number); - if (extension == NULL) { - return false; - } else { - output->type = extension->type(); - output->is_repeated = extension->is_repeated(); - output->is_packed = extension->options().packed(); - output->descriptor = extension; - if (extension->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - output->message_prototype = - factory_->GetPrototype(extension->message_type()); - GOOGLE_CHECK(output->message_prototype != NULL) - << "Extension factory's GetPrototype() returned NULL for extension: " - << extension->full_name(); - } else if (extension->cpp_type() == FieldDescriptor::CPPTYPE_ENUM) { - output->enum_validity_check.func = ValidateEnumUsingDescriptor; - output->enum_validity_check.arg = extension->enum_type(); - } - - return true; - } -} - -bool ExtensionSet::ParseField(uint32 tag, io::CodedInputStream* input, - const Message* containing_type, - UnknownFieldSet* unknown_fields) { - UnknownFieldSetFieldSkipper skipper(unknown_fields); - if (input->GetExtensionPool() == NULL) { - GeneratedExtensionFinder finder(containing_type); - return ParseField(tag, input, &finder, &skipper); - } else { - DescriptorPoolExtensionFinder finder(input->GetExtensionPool(), - input->GetExtensionFactory(), - containing_type->GetDescriptor()); - return ParseField(tag, input, &finder, &skipper); - } -} - -bool ExtensionSet::ParseMessageSet(io::CodedInputStream* input, - const Message* containing_type, - UnknownFieldSet* unknown_fields) { - UnknownFieldSetFieldSkipper skipper(unknown_fields); - if (input->GetExtensionPool() == NULL) { - GeneratedExtensionFinder finder(containing_type); - return ParseMessageSet(input, &finder, &skipper); - } else { - DescriptorPoolExtensionFinder finder(input->GetExtensionPool(), - input->GetExtensionFactory(), - containing_type->GetDescriptor()); - return ParseMessageSet(input, &finder, &skipper); - } -} - -int ExtensionSet::SpaceUsedExcludingSelf() const { - int total_size = - extensions_.size() * sizeof(map::value_type); - for (map::const_iterator iter = extensions_.begin(), - end = extensions_.end(); - iter != end; - ++iter) { - total_size += iter->second.SpaceUsedExcludingSelf(); - } - return total_size; -} - -inline int ExtensionSet::RepeatedMessage_SpaceUsedExcludingSelf( - RepeatedPtrFieldBase* field) { - return field->SpaceUsedExcludingSelf >(); -} - -int ExtensionSet::Extension::SpaceUsedExcludingSelf() const { - int total_size = 0; - if (is_repeated) { - switch (cpp_type(type)) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE: \ - total_size += sizeof(*repeated_##LOWERCASE##_value) + \ - repeated_##LOWERCASE##_value->SpaceUsedExcludingSelf();\ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE( UINT32, uint32); - HANDLE_TYPE( UINT64, uint64); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( DOUBLE, double); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, enum); - HANDLE_TYPE( STRING, string); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_MESSAGE: - // repeated_message_value is actually a RepeatedPtrField, - // but MessageLite has no SpaceUsed(), so we must directly call - // RepeatedPtrFieldBase::SpaceUsedExcludingSelf() with a different type - // handler. - total_size += sizeof(*repeated_message_value) + - RepeatedMessage_SpaceUsedExcludingSelf(repeated_message_value); - break; - } - } else { - switch (cpp_type(type)) { - case FieldDescriptor::CPPTYPE_STRING: - total_size += sizeof(*string_value) + - StringSpaceUsedExcludingSelf(*string_value); - break; - case FieldDescriptor::CPPTYPE_MESSAGE: - total_size += down_cast(message_value)->SpaceUsed(); - break; - default: - // No extra storage costs for primitive types. - break; - } - } - return total_size; -} - -// The Serialize*ToArray methods are only needed in the heavy library, as -// the lite library only generates SerializeWithCachedSizes. -uint8* ExtensionSet::SerializeWithCachedSizesToArray( - int start_field_number, int end_field_number, - uint8* target) const { - map::const_iterator iter; - for (iter = extensions_.lower_bound(start_field_number); - iter != extensions_.end() && iter->first < end_field_number; - ++iter) { - target = iter->second.SerializeFieldWithCachedSizesToArray(iter->first, - target); - } - return target; -} - -uint8* ExtensionSet::SerializeMessageSetWithCachedSizesToArray( - uint8* target) const { - map::const_iterator iter; - for (iter = extensions_.begin(); iter != extensions_.end(); ++iter) { - target = iter->second.SerializeMessageSetItemWithCachedSizesToArray( - iter->first, target); - } - return target; -} - -uint8* ExtensionSet::Extension::SerializeFieldWithCachedSizesToArray( - int number, uint8* target) const { - if (is_repeated) { - if (is_packed) { - if (cached_size == 0) return target; - - target = WireFormatLite::WriteTagToArray(number, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); - target = WireFormatLite::WriteInt32NoTagToArray(cached_size, target); - - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - target = WireFormatLite::Write##CAMELCASE##NoTagToArray( \ - repeated_##LOWERCASE##_value->Get(i), target); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( ENUM, Enum, enum); -#undef HANDLE_TYPE - - case WireFormatLite::TYPE_STRING: - case WireFormatLite::TYPE_BYTES: - case WireFormatLite::TYPE_GROUP: - case WireFormatLite::TYPE_MESSAGE: - GOOGLE_LOG(FATAL) << "Non-primitive types can't be packed."; - break; - } - } else { - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, LOWERCASE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - for (int i = 0; i < repeated_##LOWERCASE##_value->size(); i++) { \ - target = WireFormatLite::Write##CAMELCASE##ToArray(number, \ - repeated_##LOWERCASE##_value->Get(i), target); \ - } \ - break - - HANDLE_TYPE( INT32, Int32, int32); - HANDLE_TYPE( INT64, Int64, int64); - HANDLE_TYPE( UINT32, UInt32, uint32); - HANDLE_TYPE( UINT64, UInt64, uint64); - HANDLE_TYPE( SINT32, SInt32, int32); - HANDLE_TYPE( SINT64, SInt64, int64); - HANDLE_TYPE( FIXED32, Fixed32, uint32); - HANDLE_TYPE( FIXED64, Fixed64, uint64); - HANDLE_TYPE(SFIXED32, SFixed32, int32); - HANDLE_TYPE(SFIXED64, SFixed64, int64); - HANDLE_TYPE( FLOAT, Float, float); - HANDLE_TYPE( DOUBLE, Double, double); - HANDLE_TYPE( BOOL, Bool, bool); - HANDLE_TYPE( STRING, String, string); - HANDLE_TYPE( BYTES, Bytes, string); - HANDLE_TYPE( ENUM, Enum, enum); - HANDLE_TYPE( GROUP, Group, message); - HANDLE_TYPE( MESSAGE, Message, message); -#undef HANDLE_TYPE - } - } - } else if (!is_cleared) { - switch (real_type(type)) { -#define HANDLE_TYPE(UPPERCASE, CAMELCASE, VALUE) \ - case FieldDescriptor::TYPE_##UPPERCASE: \ - target = WireFormatLite::Write##CAMELCASE##ToArray( \ - number, VALUE, target); \ - break - - HANDLE_TYPE( INT32, Int32, int32_value); - HANDLE_TYPE( INT64, Int64, int64_value); - HANDLE_TYPE( UINT32, UInt32, uint32_value); - HANDLE_TYPE( UINT64, UInt64, uint64_value); - HANDLE_TYPE( SINT32, SInt32, int32_value); - HANDLE_TYPE( SINT64, SInt64, int64_value); - HANDLE_TYPE( FIXED32, Fixed32, uint32_value); - HANDLE_TYPE( FIXED64, Fixed64, uint64_value); - HANDLE_TYPE(SFIXED32, SFixed32, int32_value); - HANDLE_TYPE(SFIXED64, SFixed64, int64_value); - HANDLE_TYPE( FLOAT, Float, float_value); - HANDLE_TYPE( DOUBLE, Double, double_value); - HANDLE_TYPE( BOOL, Bool, bool_value); - HANDLE_TYPE( STRING, String, *string_value); - HANDLE_TYPE( BYTES, Bytes, *string_value); - HANDLE_TYPE( ENUM, Enum, enum_value); - HANDLE_TYPE( GROUP, Group, *message_value); - HANDLE_TYPE( MESSAGE, Message, *message_value); -#undef HANDLE_TYPE - } - } - return target; -} - -uint8* ExtensionSet::Extension::SerializeMessageSetItemWithCachedSizesToArray( - int number, - uint8* target) const { - if (type != WireFormatLite::TYPE_MESSAGE || is_repeated) { - // Not a valid MessageSet extension, but serialize it the normal way. - GOOGLE_LOG(WARNING) << "Invalid message set extension."; - return SerializeFieldWithCachedSizesToArray(number, target); - } - - if (is_cleared) return target; - - // Start group. - target = io::CodedOutputStream::WriteTagToArray( - WireFormatLite::kMessageSetItemStartTag, target); - // Write type ID. - target = WireFormatLite::WriteUInt32ToArray( - WireFormatLite::kMessageSetTypeIdNumber, number, target); - // Write message. - target = WireFormatLite::WriteMessageToArray( - WireFormatLite::kMessageSetMessageNumber, *message_value, target); - // End group. - target = io::CodedOutputStream::WriteTagToArray( - WireFormatLite::kMessageSetItemEndTag, target); - return target; -} - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/extension_set_unittest.cc b/Resources/NetHook/google/protobuf/extension_set_unittest.cc deleted file mode 100644 index 000f846c..00000000 --- a/Resources/NetHook/google/protobuf/extension_set_unittest.cc +++ /dev/null @@ -1,642 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { -namespace { - -// This test closely mirrors google/protobuf/compiler/cpp/unittest.cc -// except that it uses extensions rather than regular fields. - -TEST(ExtensionSetTest, Defaults) { - // Check that all default values are set correctly in the initial message. - unittest::TestAllExtensions message; - - TestUtil::ExpectExtensionsClear(message); - - // Messages should return pointers to default instances until first use. - // (This is not checked by ExpectClear() since it is not actually true after - // the fields have been set and then cleared.) - EXPECT_EQ(&unittest::OptionalGroup_extension::default_instance(), - &message.GetExtension(unittest::optionalgroup_extension)); - EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_EQ(&unittest::ForeignMessage::default_instance(), - &message.GetExtension( - unittest::optional_foreign_message_extension)); - EXPECT_EQ(&unittest_import::ImportMessage::default_instance(), - &message.GetExtension(unittest::optional_import_message_extension)); -} - -TEST(ExtensionSetTest, Accessors) { - // Set every field to a unique value then go back and check all those - // values. - unittest::TestAllExtensions message; - - TestUtil::SetAllExtensions(&message); - TestUtil::ExpectAllExtensionsSet(message); - - TestUtil::ModifyRepeatedExtensions(&message); - TestUtil::ExpectRepeatedExtensionsModified(message); -} - -TEST(ExtensionSetTest, Clear) { - // Set every field to a unique value, clear the message, then check that - // it is cleared. - unittest::TestAllExtensions message; - - TestUtil::SetAllExtensions(&message); - message.Clear(); - TestUtil::ExpectExtensionsClear(message); - - // Unlike with the defaults test, we do NOT expect that requesting embedded - // messages will return a pointer to the default instance. Instead, they - // should return the objects that were created when mutable_blah() was - // called. - EXPECT_NE(&unittest::OptionalGroup_extension::default_instance(), - &message.GetExtension(unittest::optionalgroup_extension)); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.GetExtension( - unittest::optional_foreign_message_extension)); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &message.GetExtension(unittest::optional_import_message_extension)); - - // Make sure setting stuff again after clearing works. (This takes slightly - // different code paths since the objects are reused.) - TestUtil::SetAllExtensions(&message); - TestUtil::ExpectAllExtensionsSet(message); -} - -TEST(ExtensionSetTest, ClearOneField) { - // Set every field to a unique value, then clear one value and insure that - // only that one value is cleared. - unittest::TestAllExtensions message; - - TestUtil::SetAllExtensions(&message); - int64 original_value = - message.GetExtension(unittest::optional_int64_extension); - - // Clear the field and make sure it shows up as cleared. - message.ClearExtension(unittest::optional_int64_extension); - EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension)); - EXPECT_EQ(0, message.GetExtension(unittest::optional_int64_extension)); - - // Other adjacent fields should not be cleared. - EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension)); - - // Make sure if we set it again, then all fields are set. - message.SetExtension(unittest::optional_int64_extension, original_value); - TestUtil::ExpectAllExtensionsSet(message); -} - -TEST(ExtensionSetTest, CopyFrom) { - unittest::TestAllExtensions message1, message2; - string data; - - TestUtil::SetAllExtensions(&message1); - message2.CopyFrom(message1); - TestUtil::ExpectAllExtensionsSet(message2); -} - -TEST(ExtensionSetTest, CopyFromUpcasted) { - unittest::TestAllExtensions message1, message2; - string data; - const Message& upcasted_message = message1; - - TestUtil::SetAllExtensions(&message1); - message2.CopyFrom(upcasted_message); - TestUtil::ExpectAllExtensionsSet(message2); -} - -TEST(ExtensionSetTest, SwapWithEmpty) { - unittest::TestAllExtensions message1, message2; - TestUtil::SetAllExtensions(&message1); - - TestUtil::ExpectAllExtensionsSet(message1); - TestUtil::ExpectExtensionsClear(message2); - message1.Swap(&message2); - TestUtil::ExpectAllExtensionsSet(message2); - TestUtil::ExpectExtensionsClear(message1); -} - -TEST(ExtensionSetTest, SwapWithSelf) { - unittest::TestAllExtensions message; - TestUtil::SetAllExtensions(&message); - - TestUtil::ExpectAllExtensionsSet(message); - message.Swap(&message); - TestUtil::ExpectAllExtensionsSet(message); -} - -TEST(ExtensionSetTest, SerializationToArray) { - // Serialize as TestAllExtensions and parse as TestAllTypes to insure wire - // compatibility of extensions. - // - // This checks serialization to a flat array by explicitly reserving space in - // the string and calling the generated message's - // SerializeWithCachedSizesToArray. - unittest::TestAllExtensions source; - unittest::TestAllTypes destination; - TestUtil::SetAllExtensions(&source); - int size = source.ByteSize(); - string data; - data.resize(size); - uint8* target = reinterpret_cast(string_as_array(&data)); - uint8* end = source.SerializeWithCachedSizesToArray(target); - EXPECT_EQ(size, end - target); - EXPECT_TRUE(destination.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(destination); -} - -TEST(ExtensionSetTest, SerializationToStream) { - // Serialize as TestAllExtensions and parse as TestAllTypes to insure wire - // compatibility of extensions. - // - // This checks serialization to an output stream by creating an array output - // stream that can only buffer 1 byte at a time - this prevents the message - // from ever jumping to the fast path, ensuring that serialization happens via - // the CodedOutputStream. - unittest::TestAllExtensions source; - unittest::TestAllTypes destination; - TestUtil::SetAllExtensions(&source); - int size = source.ByteSize(); - string data; - data.resize(size); - { - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - source.SerializeWithCachedSizes(&output_stream); - ASSERT_FALSE(output_stream.HadError()); - } - EXPECT_TRUE(destination.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(destination); -} - -TEST(ExtensionSetTest, PackedSerializationToArray) { - // Serialize as TestPackedExtensions and parse as TestPackedTypes to insure - // wire compatibility of extensions. - // - // This checks serialization to a flat array by explicitly reserving space in - // the string and calling the generated message's - // SerializeWithCachedSizesToArray. - unittest::TestPackedExtensions source; - unittest::TestPackedTypes destination; - TestUtil::SetPackedExtensions(&source); - int size = source.ByteSize(); - string data; - data.resize(size); - uint8* target = reinterpret_cast(string_as_array(&data)); - uint8* end = source.SerializeWithCachedSizesToArray(target); - EXPECT_EQ(size, end - target); - EXPECT_TRUE(destination.ParseFromString(data)); - TestUtil::ExpectPackedFieldsSet(destination); -} - -TEST(ExtensionSetTest, PackedSerializationToStream) { - // Serialize as TestPackedExtensions and parse as TestPackedTypes to insure - // wire compatibility of extensions. - // - // This checks serialization to an output stream by creating an array output - // stream that can only buffer 1 byte at a time - this prevents the message - // from ever jumping to the fast path, ensuring that serialization happens via - // the CodedOutputStream. - unittest::TestPackedExtensions source; - unittest::TestPackedTypes destination; - TestUtil::SetPackedExtensions(&source); - int size = source.ByteSize(); - string data; - data.resize(size); - { - io::ArrayOutputStream array_stream(string_as_array(&data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - source.SerializeWithCachedSizes(&output_stream); - ASSERT_FALSE(output_stream.HadError()); - } - EXPECT_TRUE(destination.ParseFromString(data)); - TestUtil::ExpectPackedFieldsSet(destination); -} - -TEST(ExtensionSetTest, Parsing) { - // Serialize as TestAllTypes and parse as TestAllExtensions. - unittest::TestAllTypes source; - unittest::TestAllExtensions destination; - string data; - - TestUtil::SetAllFields(&source); - source.SerializeToString(&data); - EXPECT_TRUE(destination.ParseFromString(data)); - TestUtil::ExpectAllExtensionsSet(destination); -} - -TEST(ExtensionSetTest, PackedParsing) { - // Serialize as TestPackedTypes and parse as TestPackedExtensions. - unittest::TestPackedTypes source; - unittest::TestPackedExtensions destination; - string data; - - TestUtil::SetPackedFields(&source); - source.SerializeToString(&data); - EXPECT_TRUE(destination.ParseFromString(data)); - TestUtil::ExpectPackedExtensionsSet(destination); -} - -TEST(ExtensionSetTest, IsInitialized) { - // Test that IsInitialized() returns false if required fields in nested - // extensions are missing. - unittest::TestAllExtensions message; - - EXPECT_TRUE(message.IsInitialized()); - - message.MutableExtension(unittest::TestRequired::single); - EXPECT_FALSE(message.IsInitialized()); - - message.MutableExtension(unittest::TestRequired::single)->set_a(1); - EXPECT_FALSE(message.IsInitialized()); - message.MutableExtension(unittest::TestRequired::single)->set_b(2); - EXPECT_FALSE(message.IsInitialized()); - message.MutableExtension(unittest::TestRequired::single)->set_c(3); - EXPECT_TRUE(message.IsInitialized()); - - message.AddExtension(unittest::TestRequired::multi); - EXPECT_FALSE(message.IsInitialized()); - - message.MutableExtension(unittest::TestRequired::multi, 0)->set_a(1); - EXPECT_FALSE(message.IsInitialized()); - message.MutableExtension(unittest::TestRequired::multi, 0)->set_b(2); - EXPECT_FALSE(message.IsInitialized()); - message.MutableExtension(unittest::TestRequired::multi, 0)->set_c(3); - EXPECT_TRUE(message.IsInitialized()); -} - -TEST(ExtensionSetTest, MutableString) { - // Test the mutable string accessors. - unittest::TestAllExtensions message; - - message.MutableExtension(unittest::optional_string_extension)->assign("foo"); - EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension)); - EXPECT_EQ("foo", message.GetExtension(unittest::optional_string_extension)); - - message.AddExtension(unittest::repeated_string_extension)->assign("bar"); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_extension)); - EXPECT_EQ("bar", - message.GetExtension(unittest::repeated_string_extension, 0)); -} - -TEST(ExtensionSetTest, SpaceUsedExcludingSelf) { - // Scalar primitive extensions should increase the extension set size by a - // minimum of the size of the primitive type. -#define TEST_SCALAR_EXTENSIONS_SPACE_USED(type, value) \ - do { \ - unittest::TestAllExtensions message; \ - const int base_size = message.SpaceUsed(); \ - message.SetExtension(unittest::optional_##type##_extension, value); \ - int min_expected_size = base_size + \ - sizeof(message.GetExtension(unittest::optional_##type##_extension)); \ - EXPECT_LE(min_expected_size, message.SpaceUsed()); \ - } while (0) - - TEST_SCALAR_EXTENSIONS_SPACE_USED(int32 , 101); - TEST_SCALAR_EXTENSIONS_SPACE_USED(int64 , 102); - TEST_SCALAR_EXTENSIONS_SPACE_USED(uint32 , 103); - TEST_SCALAR_EXTENSIONS_SPACE_USED(uint64 , 104); - TEST_SCALAR_EXTENSIONS_SPACE_USED(sint32 , 105); - TEST_SCALAR_EXTENSIONS_SPACE_USED(sint64 , 106); - TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed32 , 107); - TEST_SCALAR_EXTENSIONS_SPACE_USED(fixed64 , 108); - TEST_SCALAR_EXTENSIONS_SPACE_USED(sfixed32, 109); - TEST_SCALAR_EXTENSIONS_SPACE_USED(sfixed64, 110); - TEST_SCALAR_EXTENSIONS_SPACE_USED(float , 111); - TEST_SCALAR_EXTENSIONS_SPACE_USED(double , 112); - TEST_SCALAR_EXTENSIONS_SPACE_USED(bool , true); -#undef TEST_SCALAR_EXTENSIONS_SPACE_USED - { - unittest::TestAllExtensions message; - const int base_size = message.SpaceUsed(); - message.SetExtension(unittest::optional_nested_enum_extension, - unittest::TestAllTypes::FOO); - int min_expected_size = base_size + - sizeof(message.GetExtension(unittest::optional_nested_enum_extension)); - EXPECT_LE(min_expected_size, message.SpaceUsed()); - } - { - // Strings may cause extra allocations depending on their length; ensure - // that gets included as well. - unittest::TestAllExtensions message; - const int base_size = message.SpaceUsed(); - const string s("this is a fairly large string that will cause some " - "allocation in order to store it in the extension"); - message.SetExtension(unittest::optional_string_extension, s); - int min_expected_size = base_size + s.length(); - EXPECT_LE(min_expected_size, message.SpaceUsed()); - } - { - // Messages also have additional allocation that need to be counted. - unittest::TestAllExtensions message; - const int base_size = message.SpaceUsed(); - unittest::ForeignMessage foreign; - foreign.set_c(42); - message.MutableExtension(unittest::optional_foreign_message_extension)-> - CopyFrom(foreign); - int min_expected_size = base_size + foreign.SpaceUsed(); - EXPECT_LE(min_expected_size, message.SpaceUsed()); - } - - // Repeated primitive extensions will increase space used by at least a - // RepeatedField, and will cause additional allocations when the array - // gets too big for the initial space. - // This macro: - // - Adds a value to the repeated extension, then clears it, establishing - // the base size. - // - Adds a small number of values, testing that it doesn't increase the - // SpaceUsed() - // - Adds a large number of values (requiring allocation in the repeated - // field), and ensures that that allocation is included in SpaceUsed() -#define TEST_REPEATED_EXTENSIONS_SPACE_USED(type, cpptype, value) \ - do { \ - unittest::TestAllExtensions message; \ - const int base_size = message.SpaceUsed(); \ - int min_expected_size = sizeof(RepeatedField) + base_size; \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - message.ClearExtension(unittest::repeated_##type##_extension); \ - const int empty_repeated_field_size = message.SpaceUsed(); \ - EXPECT_LE(min_expected_size, empty_repeated_field_size) << #type; \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - EXPECT_EQ(empty_repeated_field_size, message.SpaceUsed()) << #type; \ - message.ClearExtension(unittest::repeated_##type##_extension); \ - for (int i = 0; i < 16; ++i) { \ - message.AddExtension(unittest::repeated_##type##_extension, value); \ - } \ - int expected_size = sizeof(cpptype) * 16 + empty_repeated_field_size; \ - EXPECT_EQ(expected_size, message.SpaceUsed()) << #type; \ - } while (0) - - TEST_REPEATED_EXTENSIONS_SPACE_USED(int32 , int32 , 101); - TEST_REPEATED_EXTENSIONS_SPACE_USED(int64 , int64 , 102); - TEST_REPEATED_EXTENSIONS_SPACE_USED(uint32 , uint32, 103); - TEST_REPEATED_EXTENSIONS_SPACE_USED(uint64 , uint64, 104); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sint32 , int32 , 105); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sint64 , int64 , 106); - TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed32 , uint32, 107); - TEST_REPEATED_EXTENSIONS_SPACE_USED(fixed64 , uint64, 108); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed32, int32 , 109); - TEST_REPEATED_EXTENSIONS_SPACE_USED(sfixed64, int64 , 110); - TEST_REPEATED_EXTENSIONS_SPACE_USED(float , float , 111); - TEST_REPEATED_EXTENSIONS_SPACE_USED(double , double, 112); - TEST_REPEATED_EXTENSIONS_SPACE_USED(bool , bool , true); - TEST_REPEATED_EXTENSIONS_SPACE_USED(nested_enum, int, - unittest::TestAllTypes::FOO); -#undef TEST_REPEATED_EXTENSIONS_SPACE_USED - // Repeated strings - { - unittest::TestAllExtensions message; - const int base_size = message.SpaceUsed(); - int min_expected_size = sizeof(RepeatedPtrField) + base_size; - const string value(256, 'x'); - // Once items are allocated, they may stick around even when cleared so - // without the hardcore memory management accessors there isn't a notion of - // the empty repeated field memory usage as there is with primitive types. - for (int i = 0; i < 16; ++i) { - message.AddExtension(unittest::repeated_string_extension, value); - } - min_expected_size += (sizeof(value) + value.size()) * 16; - EXPECT_LE(min_expected_size, message.SpaceUsed()); - } - // Repeated messages - { - unittest::TestAllExtensions message; - const int base_size = message.SpaceUsed(); - int min_expected_size = sizeof(RepeatedPtrField) + - base_size; - unittest::ForeignMessage prototype; - prototype.set_c(2); - for (int i = 0; i < 16; ++i) { - message.AddExtension(unittest::repeated_foreign_message_extension)-> - CopyFrom(prototype); - } - min_expected_size += 16 * prototype.SpaceUsed(); - EXPECT_LE(min_expected_size, message.SpaceUsed()); - } -} - -#ifdef GTEST_HAS_DEATH_TEST - -TEST(ExtensionSetTest, InvalidEnumDeath) { - unittest::TestAllExtensions message; - EXPECT_DEBUG_DEATH( - message.SetExtension(unittest::optional_foreign_enum_extension, - static_cast(53)), - "IsValid"); -} - -#endif // GTEST_HAS_DEATH_TEST - -TEST(ExtensionSetTest, DynamicExtensions) { - // Test adding a dynamic extension to a compiled-in message object. - - FileDescriptorProto dynamic_proto; - dynamic_proto.set_name("dynamic_extensions_test.proto"); - dynamic_proto.add_dependency( - unittest::TestAllExtensions::descriptor()->file()->name()); - dynamic_proto.set_package("dynamic_extensions"); - - // Copy the fields and nested types from TestDynamicExtensions into our new - // proto, converting the fields into extensions. - const Descriptor* template_descriptor = - unittest::TestDynamicExtensions::descriptor(); - DescriptorProto template_descriptor_proto; - template_descriptor->CopyTo(&template_descriptor_proto); - dynamic_proto.mutable_message_type()->MergeFrom( - template_descriptor_proto.nested_type()); - dynamic_proto.mutable_enum_type()->MergeFrom( - template_descriptor_proto.enum_type()); - dynamic_proto.mutable_extension()->MergeFrom( - template_descriptor_proto.field()); - - // For each extension that we added... - for (int i = 0; i < dynamic_proto.extension_size(); i++) { - // Set its extendee to TestAllExtensions. - FieldDescriptorProto* extension = dynamic_proto.mutable_extension(i); - extension->set_extendee( - unittest::TestAllExtensions::descriptor()->full_name()); - - // If the field refers to one of the types nested in TestDynamicExtensions, - // make it refer to the type in our dynamic proto instead. - string prefix = "." + template_descriptor->full_name() + "."; - if (extension->has_type_name()) { - string* type_name = extension->mutable_type_name(); - if (HasPrefixString(*type_name, prefix)) { - type_name->replace(0, prefix.size(), ".dynamic_extensions."); - } - } - } - - // Now build the file, using the generated pool as an underlay. - DescriptorPool dynamic_pool(DescriptorPool::generated_pool()); - const FileDescriptor* file = dynamic_pool.BuildFile(dynamic_proto); - ASSERT_TRUE(file != NULL); - DynamicMessageFactory dynamic_factory(&dynamic_pool); - dynamic_factory.SetDelegateToGeneratedFactory(true); - - // Construct a message that we can parse with the extensions we defined. - // Since the extensions were based off of the fields of TestDynamicExtensions, - // we can use that message to create this test message. - string data; - { - unittest::TestDynamicExtensions message; - message.set_scalar_extension(123); - message.set_enum_extension(unittest::FOREIGN_BAR); - message.set_dynamic_enum_extension( - unittest::TestDynamicExtensions::DYNAMIC_BAZ); - message.mutable_message_extension()->set_c(456); - message.mutable_dynamic_message_extension()->set_dynamic_field(789); - message.add_repeated_extension("foo"); - message.add_repeated_extension("bar"); - message.add_packed_extension(12); - message.add_packed_extension(-34); - message.add_packed_extension(56); - message.add_packed_extension(-78); - - // Also add some unknown fields. - - // An unknown enum value (for a known field). - message.mutable_unknown_fields()->AddVarint( - unittest::TestDynamicExtensions::kDynamicEnumExtensionFieldNumber, - 12345); - // A regular unknown field. - message.mutable_unknown_fields()->AddLengthDelimited(54321, "unknown"); - - message.SerializeToString(&data); - } - - // Now we can parse this using our dynamic extension definitions... - unittest::TestAllExtensions message; - { - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - input.SetExtensionRegistry(&dynamic_pool, &dynamic_factory); - ASSERT_TRUE(message.ParseFromCodedStream(&input)); - ASSERT_TRUE(input.ConsumedEntireMessage()); - } - - // Can we print it? - EXPECT_EQ( - "[dynamic_extensions.scalar_extension]: 123\n" - "[dynamic_extensions.enum_extension]: FOREIGN_BAR\n" - "[dynamic_extensions.dynamic_enum_extension]: DYNAMIC_BAZ\n" - "[dynamic_extensions.message_extension] {\n" - " c: 456\n" - "}\n" - "[dynamic_extensions.dynamic_message_extension] {\n" - " dynamic_field: 789\n" - "}\n" - "[dynamic_extensions.repeated_extension]: \"foo\"\n" - "[dynamic_extensions.repeated_extension]: \"bar\"\n" - "[dynamic_extensions.packed_extension]: 12\n" - "[dynamic_extensions.packed_extension]: -34\n" - "[dynamic_extensions.packed_extension]: 56\n" - "[dynamic_extensions.packed_extension]: -78\n" - "2002: 12345\n" - "54321: \"unknown\"\n", - message.DebugString()); - - // Can we serialize it? - // (Don't use EXPECT_EQ because we don't want to dump raw binary data to the - // terminal on failure.) - EXPECT_TRUE(message.SerializeAsString() == data); - - // What if we parse using the reflection-based parser? - { - unittest::TestAllExtensions message2; - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - input.SetExtensionRegistry(&dynamic_pool, &dynamic_factory); - ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &message2)); - ASSERT_TRUE(input.ConsumedEntireMessage()); - EXPECT_EQ(message.DebugString(), message2.DebugString()); - } - - // Are the embedded generated types actually using the generated objects? - { - const FieldDescriptor* message_extension = - file->FindExtensionByName("message_extension"); - ASSERT_TRUE(message_extension != NULL); - const Message& sub_message = - message.GetReflection()->GetMessage(message, message_extension); - const unittest::ForeignMessage* typed_sub_message = - dynamic_cast(&sub_message); - ASSERT_TRUE(typed_sub_message != NULL); - EXPECT_EQ(456, typed_sub_message->c()); - } - - // What does GetMessage() return for the embedded dynamic type if it isn't - // present? - { - const FieldDescriptor* dynamic_message_extension = - file->FindExtensionByName("dynamic_message_extension"); - ASSERT_TRUE(dynamic_message_extension != NULL); - const Message& parent = unittest::TestAllExtensions::default_instance(); - const Message& sub_message = - parent.GetReflection()->GetMessage(parent, dynamic_message_extension, - &dynamic_factory); - const Message* prototype = - dynamic_factory.GetPrototype(dynamic_message_extension->message_type()); - EXPECT_EQ(prototype, &sub_message); - } -} - -} // namespace -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/generated_message_reflection.cc b/Resources/NetHook/google/protobuf/generated_message_reflection.cc deleted file mode 100644 index 0f065ff2..00000000 --- a/Resources/NetHook/google/protobuf/generated_message_reflection.cc +++ /dev/null @@ -1,1231 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { - -namespace { const string kEmptyString; } - -int StringSpaceUsedExcludingSelf(const string& str) { - const void* start = &str; - const void* end = &str + 1; - - if (start <= str.data() && str.data() <= end) { - // The string's data is stored inside the string object itself. - return 0; - } else { - return str.capacity(); - } -} - -bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, - int* value) { - const EnumValueDescriptor* d = descriptor->FindValueByName(name); - if (d == NULL) return false; - *value = d->number(); - return true; -} - -const string& NameOfEnum(const EnumDescriptor* descriptor, int value) { - static string kEmptyString; - const EnumValueDescriptor* d = descriptor->FindValueByNumber(value); - return (d == NULL ? kEmptyString : d->name()); -} - -// =================================================================== -// Helpers for reporting usage errors (e.g. trying to use GetInt32() on -// a string field). - -namespace { - -void ReportReflectionUsageError( - const Descriptor* descriptor, const FieldDescriptor* field, - const char* method, const char* description) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::" << method << "\n" - " Message type: " << descriptor->full_name() << "\n" - " Field : " << field->full_name() << "\n" - " Problem : " << description; -} - -const char* cpptype_names_[FieldDescriptor::MAX_CPPTYPE + 1] = { - "INVALID_CPPTYPE", - "CPPTYPE_INT32", - "CPPTYPE_INT64", - "CPPTYPE_UINT32", - "CPPTYPE_UINT64", - "CPPTYPE_DOUBLE", - "CPPTYPE_FLOAT", - "CPPTYPE_BOOL", - "CPPTYPE_ENUM", - "CPPTYPE_STRING", - "CPPTYPE_MESSAGE" -}; - -static void ReportReflectionUsageTypeError( - const Descriptor* descriptor, const FieldDescriptor* field, - const char* method, - FieldDescriptor::CppType expected_type) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::" << method << "\n" - " Message type: " << descriptor->full_name() << "\n" - " Field : " << field->full_name() << "\n" - " Problem : Field is not the right type for this message:\n" - " Expected : " << cpptype_names_[expected_type] << "\n" - " Field type: " << cpptype_names_[field->cpp_type()]; -} - -static void ReportReflectionUsageEnumTypeError( - const Descriptor* descriptor, const FieldDescriptor* field, - const char* method, const EnumValueDescriptor* value) { - GOOGLE_LOG(FATAL) - << "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::" << method << "\n" - " Message type: " << descriptor->full_name() << "\n" - " Field : " << field->full_name() << "\n" - " Problem : Enum value did not match field type:\n" - " Expected : " << field->enum_type()->full_name() << "\n" - " Actual : " << value->full_name(); -} - -#define USAGE_CHECK(CONDITION, METHOD, ERROR_DESCRIPTION) \ - if (!(CONDITION)) \ - ReportReflectionUsageError(descriptor_, field, #METHOD, ERROR_DESCRIPTION) -#define USAGE_CHECK_EQ(A, B, METHOD, ERROR_DESCRIPTION) \ - USAGE_CHECK((A) == (B), METHOD, ERROR_DESCRIPTION) -#define USAGE_CHECK_NE(A, B, METHOD, ERROR_DESCRIPTION) \ - USAGE_CHECK((A) != (B), METHOD, ERROR_DESCRIPTION) - -#define USAGE_CHECK_TYPE(METHOD, CPPTYPE) \ - if (field->cpp_type() != FieldDescriptor::CPPTYPE_##CPPTYPE) \ - ReportReflectionUsageTypeError(descriptor_, field, #METHOD, \ - FieldDescriptor::CPPTYPE_##CPPTYPE) - -#define USAGE_CHECK_ENUM_VALUE(METHOD) \ - if (value->type() != field->enum_type()) \ - ReportReflectionUsageEnumTypeError(descriptor_, field, #METHOD, value) - -#define USAGE_CHECK_MESSAGE_TYPE(METHOD) \ - USAGE_CHECK_EQ(field->containing_type(), descriptor_, \ - METHOD, "Field does not match message type."); -#define USAGE_CHECK_SINGULAR(METHOD) \ - USAGE_CHECK_NE(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \ - "Field is repeated; the method requires a singular field.") -#define USAGE_CHECK_REPEATED(METHOD) \ - USAGE_CHECK_EQ(field->label(), FieldDescriptor::LABEL_REPEATED, METHOD, \ - "Field is singular; the method requires a repeated field.") - -#define USAGE_CHECK_ALL(METHOD, LABEL, CPPTYPE) \ - USAGE_CHECK_MESSAGE_TYPE(METHOD); \ - USAGE_CHECK_##LABEL(METHOD); \ - USAGE_CHECK_TYPE(METHOD, CPPTYPE) - -} // namespace - -// =================================================================== - -GeneratedMessageReflection::GeneratedMessageReflection( - const Descriptor* descriptor, - const Message* default_instance, - const int offsets[], - int has_bits_offset, - int unknown_fields_offset, - int extensions_offset, - const DescriptorPool* descriptor_pool, - MessageFactory* factory, - int object_size) - : descriptor_ (descriptor), - default_instance_ (default_instance), - offsets_ (offsets), - has_bits_offset_ (has_bits_offset), - unknown_fields_offset_(unknown_fields_offset), - extensions_offset_(extensions_offset), - object_size_ (object_size), - descriptor_pool_ ((descriptor_pool == NULL) ? - DescriptorPool::generated_pool() : - descriptor_pool), - message_factory_ (factory) { -} - -GeneratedMessageReflection::~GeneratedMessageReflection() {} - -const UnknownFieldSet& GeneratedMessageReflection::GetUnknownFields( - const Message& message) const { - const void* ptr = reinterpret_cast(&message) + - unknown_fields_offset_; - return *reinterpret_cast(ptr); -} -UnknownFieldSet* GeneratedMessageReflection::MutableUnknownFields( - Message* message) const { - void* ptr = reinterpret_cast(message) + unknown_fields_offset_; - return reinterpret_cast(ptr); -} - -int GeneratedMessageReflection::SpaceUsed(const Message& message) const { - // object_size_ already includes the in-memory representation of each field - // in the message, so we only need to account for additional memory used by - // the fields. - int total_size = object_size_; - - total_size += GetUnknownFields(message).SpaceUsedExcludingSelf(); - - if (extensions_offset_ != -1) { - total_size += GetExtensionSet(message).SpaceUsedExcludingSelf(); - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - if (field->is_repeated()) { - switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - total_size += GetRaw >(message, field) \ - .SpaceUsedExcludingSelf(); \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - total_size += GetRaw >(message, field) - .SpaceUsedExcludingSelf(); - break; - } - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: - // We don't know which subclass of RepeatedPtrFieldBase the type is, - // so we use RepeatedPtrFieldBase directly. - total_size += - GetRaw(message, field) - .SpaceUsedExcludingSelf >(); - break; - } - } else { - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32 : - case FieldDescriptor::CPPTYPE_INT64 : - case FieldDescriptor::CPPTYPE_UINT32: - case FieldDescriptor::CPPTYPE_UINT64: - case FieldDescriptor::CPPTYPE_DOUBLE: - case FieldDescriptor::CPPTYPE_FLOAT : - case FieldDescriptor::CPPTYPE_BOOL : - case FieldDescriptor::CPPTYPE_ENUM : - // Field is inline, so we've already counted it. - break; - - case FieldDescriptor::CPPTYPE_STRING: { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: { - const string* ptr = GetField(message, field); - - // Initially, the string points to the default value stored in - // the prototype. Only count the string if it has been changed - // from the default value. - const string* default_ptr = DefaultRaw(field); - - if (ptr != default_ptr) { - // string fields are represented by just a pointer, so also - // include sizeof(string) as well. - total_size += sizeof(*ptr) + StringSpaceUsedExcludingSelf(*ptr); - } - break; - } - } - break; - } - - case FieldDescriptor::CPPTYPE_MESSAGE: - if (&message == default_instance_) { - // For singular fields, the prototype just stores a pointer to the - // external type's prototype, so there is no extra memory usage. - } else { - const Message* sub_message = GetRaw(message, field); - if (sub_message != NULL) { - total_size += sub_message->SpaceUsed(); - } - } - break; - } - } - } - - return total_size; -} - -void GeneratedMessageReflection::Swap( - Message* message1, - Message* message2) const { - if (message1 == message2) return; - - // TODO(kenton): Other Reflection methods should probably check this too. - GOOGLE_CHECK_EQ(message1->GetReflection(), this) - << "First argument to Swap() (of type \"" - << message1->GetDescriptor()->full_name() - << "\") is not compatible with this reflection object (which is for type \"" - << descriptor_->full_name() - << "\"). Note that the exact same class is required; not just the same " - "descriptor."; - GOOGLE_CHECK_EQ(message2->GetReflection(), this) - << "Second argument to Swap() (of type \"" - << message1->GetDescriptor()->full_name() - << "\") is not compatible with this reflection object (which is for type \"" - << descriptor_->full_name() - << "\"). Note that the exact same class is required; not just the same " - "descriptor."; - - uint32* has_bits1 = MutableHasBits(message1); - uint32* has_bits2 = MutableHasBits(message2); - int has_bits_size = (descriptor_->field_count() + 31) / 32; - - for (int i = 0; i < has_bits_size; i++) { - std::swap(has_bits1[i], has_bits2[i]); - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->is_repeated()) { - switch (field->cpp_type()) { -#define SWAP_ARRAYS(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - MutableRaw >(message1, field)->Swap( \ - MutableRaw >(message2, field)); \ - break; - - SWAP_ARRAYS(INT32 , int32 ); - SWAP_ARRAYS(INT64 , int64 ); - SWAP_ARRAYS(UINT32, uint32); - SWAP_ARRAYS(UINT64, uint64); - SWAP_ARRAYS(FLOAT , float ); - SWAP_ARRAYS(DOUBLE, double); - SWAP_ARRAYS(BOOL , bool ); - SWAP_ARRAYS(ENUM , int ); -#undef SWAP_ARRAYS - - case FieldDescriptor::CPPTYPE_STRING: - case FieldDescriptor::CPPTYPE_MESSAGE: - MutableRaw(message1, field)->Swap( - MutableRaw(message2, field)); - break; - - default: - GOOGLE_LOG(FATAL) << "Unimplemented type: " << field->cpp_type(); - } - } else { - switch (field->cpp_type()) { -#define SWAP_VALUES(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - std::swap(*MutableRaw(message1, field), \ - *MutableRaw(message2, field)); \ - break; - - SWAP_VALUES(INT32 , int32 ); - SWAP_VALUES(INT64 , int64 ); - SWAP_VALUES(UINT32, uint32); - SWAP_VALUES(UINT64, uint64); - SWAP_VALUES(FLOAT , float ); - SWAP_VALUES(DOUBLE, double); - SWAP_VALUES(BOOL , bool ); - SWAP_VALUES(ENUM , int ); - SWAP_VALUES(MESSAGE, Message*); -#undef SWAP_VALUES - - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - std::swap(*MutableRaw(message1, field), - *MutableRaw(message2, field)); - break; - } - break; - - default: - GOOGLE_LOG(FATAL) << "Unimplemented type: " << field->cpp_type(); - } - } - } - - if (extensions_offset_ != -1) { - MutableExtensionSet(message1)->Swap(MutableExtensionSet(message2)); - } - - MutableUnknownFields(message1)->Swap(MutableUnknownFields(message2)); -} - -// ------------------------------------------------------------------- - -bool GeneratedMessageReflection::HasField(const Message& message, - const FieldDescriptor* field) const { - USAGE_CHECK_MESSAGE_TYPE(HasField); - USAGE_CHECK_SINGULAR(HasField); - - if (field->is_extension()) { - return GetExtensionSet(message).Has(field->number()); - } else { - return HasBit(message, field); - } -} - -int GeneratedMessageReflection::FieldSize(const Message& message, - const FieldDescriptor* field) const { - USAGE_CHECK_MESSAGE_TYPE(FieldSize); - USAGE_CHECK_REPEATED(FieldSize); - - if (field->is_extension()) { - return GetExtensionSet(message).ExtensionSize(field->number()); - } else { - switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - return GetRaw >(message, field).size() - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_STRING: - case FieldDescriptor::CPPTYPE_MESSAGE: - return GetRaw(message, field).size(); - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return 0; - } -} - -void GeneratedMessageReflection::ClearField( - Message* message, const FieldDescriptor* field) const { - USAGE_CHECK_MESSAGE_TYPE(ClearField); - - if (field->is_extension()) { - MutableExtensionSet(message)->ClearExtension(field->number()); - } else if (!field->is_repeated()) { - if (HasBit(*message, field)) { - ClearBit(message, field); - - // We need to set the field back to its default value. - switch (field->cpp_type()) { -#define CLEAR_TYPE(CPPTYPE, TYPE) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - *MutableRaw(message, field) = \ - field->default_value_##TYPE(); \ - break; - - CLEAR_TYPE(INT32 , int32 ); - CLEAR_TYPE(INT64 , int64 ); - CLEAR_TYPE(UINT32, uint32); - CLEAR_TYPE(UINT64, uint64); - CLEAR_TYPE(FLOAT , float ); - CLEAR_TYPE(DOUBLE, double); - CLEAR_TYPE(BOOL , bool ); -#undef CLEAR_TYPE - - case FieldDescriptor::CPPTYPE_ENUM: - *MutableRaw(message, field) = - field->default_value_enum()->number(); - break; - - case FieldDescriptor::CPPTYPE_STRING: { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - const string* default_ptr = DefaultRaw(field); - string** value = MutableRaw(message, field); - if (*value != default_ptr) { - if (field->has_default_value()) { - (*value)->assign(field->default_value_string()); - } else { - (*value)->clear(); - } - } - break; - } - break; - } - - case FieldDescriptor::CPPTYPE_MESSAGE: - (*MutableRaw(message, field))->Clear(); - break; - } - } - } else { - switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - MutableRaw >(message, field)->Clear(); \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_STRING: { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - MutableRaw >(message, field)->Clear(); - break; - } - break; - } - - case FieldDescriptor::CPPTYPE_MESSAGE: { - // We don't know which subclass of RepeatedPtrFieldBase the type is, - // so we use RepeatedPtrFieldBase directly. - MutableRaw(message, field) - ->Clear >(); - break; - } - } - } -} - -void GeneratedMessageReflection::RemoveLast( - Message* message, - const FieldDescriptor* field) const { - USAGE_CHECK_MESSAGE_TYPE(RemoveLast); - USAGE_CHECK_REPEATED(RemoveLast); - - if (field->is_extension()) { - MutableExtensionSet(message)->RemoveLast(field->number()); - } else { - switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - MutableRaw >(message, field)->RemoveLast(); \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_STRING: - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - MutableRaw >(message, field)->RemoveLast(); - break; - } - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: - MutableRaw(message, field) - ->RemoveLast >(); - break; - } - } -} - -void GeneratedMessageReflection::SwapElements( - Message* message, - const FieldDescriptor* field, - int index1, - int index2) const { - USAGE_CHECK_MESSAGE_TYPE(Swap); - USAGE_CHECK_REPEATED(Swap); - - if (field->is_extension()) { - MutableExtensionSet(message)->SwapElements(field->number(), index1, index2); - } else { - switch (field->cpp_type()) { -#define HANDLE_TYPE(UPPERCASE, LOWERCASE) \ - case FieldDescriptor::CPPTYPE_##UPPERCASE : \ - MutableRaw >(message, field) \ - ->SwapElements(index1, index2); \ - break - - HANDLE_TYPE( INT32, int32); - HANDLE_TYPE( INT64, int64); - HANDLE_TYPE(UINT32, uint32); - HANDLE_TYPE(UINT64, uint64); - HANDLE_TYPE(DOUBLE, double); - HANDLE_TYPE( FLOAT, float); - HANDLE_TYPE( BOOL, bool); - HANDLE_TYPE( ENUM, int); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_STRING: - case FieldDescriptor::CPPTYPE_MESSAGE: - MutableRaw(message, field) - ->SwapElements(index1, index2); - break; - } - } -} - -namespace { -// Comparison functor for sorting FieldDescriptors by field number. -struct FieldNumberSorter { - bool operator()(const FieldDescriptor* left, - const FieldDescriptor* right) const { - return left->number() < right->number(); - } -}; -} // namespace - -void GeneratedMessageReflection::ListFields( - const Message& message, - vector* output) const { - output->clear(); - - // Optimization: The default instance never has any fields set. - if (&message == default_instance_) return; - - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->is_repeated()) { - if (FieldSize(message, field) > 0) { - output->push_back(field); - } - } else { - if (HasBit(message, field)) { - output->push_back(field); - } - } - } - - if (extensions_offset_ != -1) { - GetExtensionSet(message).AppendToList(descriptor_, descriptor_pool_, - output); - } - - // ListFields() must sort output by field number. - sort(output->begin(), output->end(), FieldNumberSorter()); -} - -// ------------------------------------------------------------------- - -#undef DEFINE_PRIMITIVE_ACCESSORS -#define DEFINE_PRIMITIVE_ACCESSORS(TYPENAME, TYPE, PASSTYPE, CPPTYPE) \ - PASSTYPE GeneratedMessageReflection::Get##TYPENAME( \ - const Message& message, const FieldDescriptor* field) const { \ - USAGE_CHECK_ALL(Get##TYPENAME, SINGULAR, CPPTYPE); \ - if (field->is_extension()) { \ - return GetExtensionSet(message).Get##TYPENAME( \ - field->number(), field->default_value_##PASSTYPE()); \ - } else { \ - return GetField(message, field); \ - } \ - } \ - \ - void GeneratedMessageReflection::Set##TYPENAME( \ - Message* message, const FieldDescriptor* field, \ - PASSTYPE value) const { \ - USAGE_CHECK_ALL(Set##TYPENAME, SINGULAR, CPPTYPE); \ - if (field->is_extension()) { \ - return MutableExtensionSet(message)->Set##TYPENAME( \ - field->number(), field->type(), value, field); \ - } else { \ - SetField(message, field, value); \ - } \ - } \ - \ - PASSTYPE GeneratedMessageReflection::GetRepeated##TYPENAME( \ - const Message& message, \ - const FieldDescriptor* field, int index) const { \ - USAGE_CHECK_ALL(GetRepeated##TYPENAME, REPEATED, CPPTYPE); \ - if (field->is_extension()) { \ - return GetExtensionSet(message).GetRepeated##TYPENAME( \ - field->number(), index); \ - } else { \ - return GetRepeatedField(message, field, index); \ - } \ - } \ - \ - void GeneratedMessageReflection::SetRepeated##TYPENAME( \ - Message* message, const FieldDescriptor* field, \ - int index, PASSTYPE value) const { \ - USAGE_CHECK_ALL(SetRepeated##TYPENAME, REPEATED, CPPTYPE); \ - if (field->is_extension()) { \ - MutableExtensionSet(message)->SetRepeated##TYPENAME( \ - field->number(), index, value); \ - } else { \ - SetRepeatedField(message, field, index, value); \ - } \ - } \ - \ - void GeneratedMessageReflection::Add##TYPENAME( \ - Message* message, const FieldDescriptor* field, \ - PASSTYPE value) const { \ - USAGE_CHECK_ALL(Add##TYPENAME, REPEATED, CPPTYPE); \ - if (field->is_extension()) { \ - MutableExtensionSet(message)->Add##TYPENAME( \ - field->number(), field->type(), field->options().packed(), value, \ - field); \ - } else { \ - AddField(message, field, value); \ - } \ - } - -DEFINE_PRIMITIVE_ACCESSORS(Int32 , int32 , int32 , INT32 ) -DEFINE_PRIMITIVE_ACCESSORS(Int64 , int64 , int64 , INT64 ) -DEFINE_PRIMITIVE_ACCESSORS(UInt32, uint32, uint32, UINT32) -DEFINE_PRIMITIVE_ACCESSORS(UInt64, uint64, uint64, UINT64) -DEFINE_PRIMITIVE_ACCESSORS(Float , float , float , FLOAT ) -DEFINE_PRIMITIVE_ACCESSORS(Double, double, double, DOUBLE) -DEFINE_PRIMITIVE_ACCESSORS(Bool , bool , bool , BOOL ) -#undef DEFINE_PRIMITIVE_ACCESSORS - -// ------------------------------------------------------------------- - -string GeneratedMessageReflection::GetString( - const Message& message, const FieldDescriptor* field) const { - USAGE_CHECK_ALL(GetString, SINGULAR, STRING); - if (field->is_extension()) { - return GetExtensionSet(message).GetString(field->number(), - field->default_value_string()); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - return *GetField(message, field); - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return kEmptyString; // Make compiler happy. - } -} - -const string& GeneratedMessageReflection::GetStringReference( - const Message& message, - const FieldDescriptor* field, string* scratch) const { - USAGE_CHECK_ALL(GetStringReference, SINGULAR, STRING); - if (field->is_extension()) { - return GetExtensionSet(message).GetString(field->number(), - field->default_value_string()); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - return *GetField(message, field); - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return kEmptyString; // Make compiler happy. - } -} - - -void GeneratedMessageReflection::SetString( - Message* message, const FieldDescriptor* field, - const string& value) const { - USAGE_CHECK_ALL(SetString, SINGULAR, STRING); - if (field->is_extension()) { - return MutableExtensionSet(message)->SetString(field->number(), - field->type(), value, field); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: { - string** ptr = MutableField(message, field); - if (*ptr == DefaultRaw(field)) { - *ptr = new string(value); - } else { - (*ptr)->assign(value); - } - break; - } - } - } -} - - -string GeneratedMessageReflection::GetRepeatedString( - const Message& message, const FieldDescriptor* field, int index) const { - USAGE_CHECK_ALL(GetRepeatedString, REPEATED, STRING); - if (field->is_extension()) { - return GetExtensionSet(message).GetRepeatedString(field->number(), index); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - return GetRepeatedPtrField(message, field, index); - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return kEmptyString; // Make compiler happy. - } -} - -const string& GeneratedMessageReflection::GetRepeatedStringReference( - const Message& message, const FieldDescriptor* field, - int index, string* scratch) const { - USAGE_CHECK_ALL(GetRepeatedStringReference, REPEATED, STRING); - if (field->is_extension()) { - return GetExtensionSet(message).GetRepeatedString(field->number(), index); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - return GetRepeatedPtrField(message, field, index); - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return kEmptyString; // Make compiler happy. - } -} - - -void GeneratedMessageReflection::SetRepeatedString( - Message* message, const FieldDescriptor* field, - int index, const string& value) const { - USAGE_CHECK_ALL(SetRepeatedString, REPEATED, STRING); - if (field->is_extension()) { - MutableExtensionSet(message)->SetRepeatedString( - field->number(), index, value); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - *MutableRepeatedField(message, field, index) = value; - break; - } - } -} - - -void GeneratedMessageReflection::AddString( - Message* message, const FieldDescriptor* field, - const string& value) const { - USAGE_CHECK_ALL(AddString, REPEATED, STRING); - if (field->is_extension()) { - MutableExtensionSet(message)->AddString(field->number(), - field->type(), value, field); - } else { - switch (field->options().ctype()) { - default: // TODO(kenton): Support other string reps. - case FieldOptions::STRING: - *AddField(message, field) = value; - break; - } - } -} - - -// ------------------------------------------------------------------- - -const EnumValueDescriptor* GeneratedMessageReflection::GetEnum( - const Message& message, const FieldDescriptor* field) const { - USAGE_CHECK_ALL(GetEnum, SINGULAR, ENUM); - - int value; - if (field->is_extension()) { - value = GetExtensionSet(message).GetEnum( - field->number(), field->default_value_enum()->number()); - } else { - value = GetField(message, field); - } - const EnumValueDescriptor* result = - field->enum_type()->FindValueByNumber(value); - GOOGLE_CHECK(result != NULL); - return result; -} - -void GeneratedMessageReflection::SetEnum( - Message* message, const FieldDescriptor* field, - const EnumValueDescriptor* value) const { - USAGE_CHECK_ALL(SetEnum, SINGULAR, ENUM); - USAGE_CHECK_ENUM_VALUE(SetEnum); - - if (field->is_extension()) { - MutableExtensionSet(message)->SetEnum(field->number(), field->type(), - value->number(), field); - } else { - SetField(message, field, value->number()); - } -} - -const EnumValueDescriptor* GeneratedMessageReflection::GetRepeatedEnum( - const Message& message, const FieldDescriptor* field, int index) const { - USAGE_CHECK_ALL(GetRepeatedEnum, REPEATED, ENUM); - - int value; - if (field->is_extension()) { - value = GetExtensionSet(message).GetRepeatedEnum(field->number(), index); - } else { - value = GetRepeatedField(message, field, index); - } - const EnumValueDescriptor* result = - field->enum_type()->FindValueByNumber(value); - GOOGLE_CHECK(result != NULL); - return result; -} - -void GeneratedMessageReflection::SetRepeatedEnum( - Message* message, - const FieldDescriptor* field, int index, - const EnumValueDescriptor* value) const { - USAGE_CHECK_ALL(SetRepeatedEnum, REPEATED, ENUM); - USAGE_CHECK_ENUM_VALUE(SetRepeatedEnum); - - if (field->is_extension()) { - MutableExtensionSet(message)->SetRepeatedEnum( - field->number(), index, value->number()); - } else { - SetRepeatedField(message, field, index, value->number()); - } -} - -void GeneratedMessageReflection::AddEnum( - Message* message, const FieldDescriptor* field, - const EnumValueDescriptor* value) const { - USAGE_CHECK_ALL(AddEnum, REPEATED, ENUM); - USAGE_CHECK_ENUM_VALUE(AddEnum); - - if (field->is_extension()) { - MutableExtensionSet(message)->AddEnum(field->number(), field->type(), - field->options().packed(), - value->number(), field); - } else { - AddField(message, field, value->number()); - } -} - -// ------------------------------------------------------------------- - -const Message& GeneratedMessageReflection::GetMessage( - const Message& message, const FieldDescriptor* field, - MessageFactory* factory) const { - USAGE_CHECK_ALL(GetMessage, SINGULAR, MESSAGE); - - if (field->is_extension()) { - return static_cast( - GetExtensionSet(message).GetMessage( - field->number(), field->message_type(), - factory == NULL ? message_factory_ : factory)); - } else { - const Message* result = GetRaw(message, field); - if (result == NULL) { - result = DefaultRaw(field); - } - return *result; - } -} - -Message* GeneratedMessageReflection::MutableMessage( - Message* message, const FieldDescriptor* field, - MessageFactory* factory) const { - USAGE_CHECK_ALL(MutableMessage, SINGULAR, MESSAGE); - - if (field->is_extension()) { - return static_cast( - MutableExtensionSet(message)->MutableMessage(field, - factory == NULL ? message_factory_ : factory)); - } else { - Message** result = MutableField(message, field); - if (*result == NULL) { - const Message* default_message = DefaultRaw(field); - *result = default_message->New(); - } - return *result; - } -} - -const Message& GeneratedMessageReflection::GetRepeatedMessage( - const Message& message, const FieldDescriptor* field, int index) const { - USAGE_CHECK_ALL(GetRepeatedMessage, REPEATED, MESSAGE); - - if (field->is_extension()) { - return static_cast( - GetExtensionSet(message).GetRepeatedMessage(field->number(), index)); - } else { - return GetRaw(message, field) - .Get >(index); - } -} - -Message* GeneratedMessageReflection::MutableRepeatedMessage( - Message* message, const FieldDescriptor* field, int index) const { - USAGE_CHECK_ALL(MutableRepeatedMessage, REPEATED, MESSAGE); - - if (field->is_extension()) { - return static_cast( - MutableExtensionSet(message)->MutableRepeatedMessage( - field->number(), index)); - } else { - return MutableRaw(message, field) - ->Mutable >(index); - } -} - -Message* GeneratedMessageReflection::AddMessage( - Message* message, const FieldDescriptor* field, - MessageFactory* factory) const { - USAGE_CHECK_ALL(AddMessage, REPEATED, MESSAGE); - - if (factory == NULL) factory = message_factory_; - - if (field->is_extension()) { - return static_cast( - MutableExtensionSet(message)->AddMessage(field, factory)); - } else { - // We can't use AddField() because RepeatedPtrFieldBase doesn't - // know how to allocate one. - RepeatedPtrFieldBase* repeated = - MutableRaw(message, field); - Message* result = repeated->AddFromCleared >(); - if (result == NULL) { - // We must allocate a new object. - const Message* prototype; - if (repeated->size() == 0) { - prototype = factory->GetPrototype(field->message_type()); - } else { - prototype = &repeated->Get >(0); - } - result = prototype->New(); - repeated->AddAllocated >(result); - } - return result; - } -} - -// ------------------------------------------------------------------- - -const FieldDescriptor* GeneratedMessageReflection::FindKnownExtensionByName( - const string& name) const { - if (extensions_offset_ == -1) return NULL; - - const FieldDescriptor* result = descriptor_pool_->FindExtensionByName(name); - if (result != NULL && result->containing_type() == descriptor_) { - return result; - } - - if (descriptor_->options().message_set_wire_format()) { - // MessageSet extensions may be identified by type name. - const Descriptor* type = descriptor_pool_->FindMessageTypeByName(name); - if (type != NULL) { - // Look for a matching extension in the foreign type's scope. - for (int i = 0; i < type->extension_count(); i++) { - const FieldDescriptor* extension = type->extension(i); - if (extension->containing_type() == descriptor_ && - extension->type() == FieldDescriptor::TYPE_MESSAGE && - extension->is_optional() && - extension->message_type() == type) { - // Found it. - return extension; - } - } - } - } - - return NULL; -} - -const FieldDescriptor* GeneratedMessageReflection::FindKnownExtensionByNumber( - int number) const { - if (extensions_offset_ == -1) return NULL; - return descriptor_pool_->FindExtensionByNumber(descriptor_, number); -} - -// =================================================================== -// Some private helpers. - -// These simple template accessors obtain pointers (or references) to -// the given field. -template -inline const Type& GeneratedMessageReflection::GetRaw( - const Message& message, const FieldDescriptor* field) const { - const void* ptr = reinterpret_cast(&message) + - offsets_[field->index()]; - return *reinterpret_cast(ptr); -} - -template -inline Type* GeneratedMessageReflection::MutableRaw( - Message* message, const FieldDescriptor* field) const { - void* ptr = reinterpret_cast(message) + offsets_[field->index()]; - return reinterpret_cast(ptr); -} - -template -inline const Type& GeneratedMessageReflection::DefaultRaw( - const FieldDescriptor* field) const { - const void* ptr = reinterpret_cast(default_instance_) + - offsets_[field->index()]; - return *reinterpret_cast(ptr); -} - -inline const uint32* GeneratedMessageReflection::GetHasBits( - const Message& message) const { - const void* ptr = reinterpret_cast(&message) + has_bits_offset_; - return reinterpret_cast(ptr); -} -inline uint32* GeneratedMessageReflection::MutableHasBits( - Message* message) const { - void* ptr = reinterpret_cast(message) + has_bits_offset_; - return reinterpret_cast(ptr); -} - -inline const ExtensionSet& GeneratedMessageReflection::GetExtensionSet( - const Message& message) const { - GOOGLE_DCHECK_NE(extensions_offset_, -1); - const void* ptr = reinterpret_cast(&message) + - extensions_offset_; - return *reinterpret_cast(ptr); -} -inline ExtensionSet* GeneratedMessageReflection::MutableExtensionSet( - Message* message) const { - GOOGLE_DCHECK_NE(extensions_offset_, -1); - void* ptr = reinterpret_cast(message) + extensions_offset_; - return reinterpret_cast(ptr); -} - -// Simple accessors for manipulating has_bits_. -inline bool GeneratedMessageReflection::HasBit( - const Message& message, const FieldDescriptor* field) const { - return GetHasBits(message)[field->index() / 32] & - (1 << (field->index() % 32)); -} - -inline void GeneratedMessageReflection::SetBit( - Message* message, const FieldDescriptor* field) const { - MutableHasBits(message)[field->index() / 32] |= (1 << (field->index() % 32)); -} - -inline void GeneratedMessageReflection::ClearBit( - Message* message, const FieldDescriptor* field) const { - MutableHasBits(message)[field->index() / 32] &= ~(1 << (field->index() % 32)); -} - -// Template implementations of basic accessors. Inline because each -// template instance is only called from one location. These are -// used for all types except messages. -template -inline const Type& GeneratedMessageReflection::GetField( - const Message& message, const FieldDescriptor* field) const { - return GetRaw(message, field); -} - -template -inline void GeneratedMessageReflection::SetField( - Message* message, const FieldDescriptor* field, const Type& value) const { - *MutableRaw(message, field) = value; - SetBit(message, field); -} - -template -inline Type* GeneratedMessageReflection::MutableField( - Message* message, const FieldDescriptor* field) const { - SetBit(message, field); - return MutableRaw(message, field); -} - -template -inline const Type& GeneratedMessageReflection::GetRepeatedField( - const Message& message, const FieldDescriptor* field, int index) const { - return GetRaw >(message, field).Get(index); -} - -template -inline const Type& GeneratedMessageReflection::GetRepeatedPtrField( - const Message& message, const FieldDescriptor* field, int index) const { - return GetRaw >(message, field).Get(index); -} - -template -inline void GeneratedMessageReflection::SetRepeatedField( - Message* message, const FieldDescriptor* field, - int index, Type value) const { - MutableRaw >(message, field)->Set(index, value); -} - -template -inline Type* GeneratedMessageReflection::MutableRepeatedField( - Message* message, const FieldDescriptor* field, int index) const { - RepeatedPtrField* repeated = - MutableRaw >(message, field); - return repeated->Mutable(index); -} - -template -inline void GeneratedMessageReflection::AddField( - Message* message, const FieldDescriptor* field, const Type& value) const { - MutableRaw >(message, field)->Add(value); -} - -template -inline Type* GeneratedMessageReflection::AddField( - Message* message, const FieldDescriptor* field) const { - RepeatedPtrField* repeated = - MutableRaw >(message, field); - return repeated->Add(); -} - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/generated_message_reflection.h b/Resources/NetHook/google/protobuf/generated_message_reflection.h deleted file mode 100644 index b545fa1a..00000000 --- a/Resources/NetHook/google/protobuf/generated_message_reflection.h +++ /dev/null @@ -1,424 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This header is logically internal, but is made public because it is used -// from protocol-compiler-generated code, which may reside in other components. - -#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__ -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__ - -#include -#include -#include -#include - - -namespace google { -namespace protobuf { - class DescriptorPool; - // Generated code needs these to have been forward-declared. Easier to do it - // here than to print them inside every .pb.h file. - class FileDescriptor; - class EnumDescriptor; -} - -namespace protobuf { -namespace internal { - -// Defined in this file. -class GeneratedMessageReflection; - -// Defined in other files. -class ExtensionSet; // extension_set.h - -// THIS CLASS IS NOT INTENDED FOR DIRECT USE. It is intended for use -// by generated code. This class is just a big hack that reduces code -// size. -// -// A GeneratedMessageReflection is an implementation of Reflection -// which expects all fields to be backed by simple variables located in -// memory. The locations are given using a base pointer and a set of -// offsets. -// -// It is required that the user represents fields of each type in a standard -// way, so that GeneratedMessageReflection can cast the void* pointer to -// the appropriate type. For primitive fields and string fields, each field -// should be represented using the obvious C++ primitive type. Enums and -// Messages are different: -// - Singular Message fields are stored as a pointer to a Message. These -// should start out NULL, except for in the default instance where they -// should start out pointing to other default instances. -// - Enum fields are stored as an int. This int must always contain -// a valid value, such that EnumDescriptor::FindValueByNumber() would -// not return NULL. -// - Repeated fields are stored as RepeatedFields or RepeatedPtrFields -// of whatever type the individual field would be. Strings and -// Messages use RepeatedPtrFields while everything else uses -// RepeatedFields. -class LIBPROTOBUF_EXPORT GeneratedMessageReflection : public Reflection { - public: - // Constructs a GeneratedMessageReflection. - // Parameters: - // descriptor: The descriptor for the message type being implemented. - // default_instance: The default instance of the message. This is only - // used to obtain pointers to default instances of embedded - // messages, which GetMessage() will return if the particular - // sub-message has not been initialized yet. (Thus, all - // embedded message fields *must* have non-NULL pointers - // in the default instance.) - // offsets: An array of ints giving the byte offsets, relative to - // the start of the message object, of each field. These can - // be computed at compile time using the - // GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET() macro, defined - // below. - // has_bits_offset: Offset in the message of an array of uint32s of size - // descriptor->field_count()/32, rounded up. This is a - // bitfield where each bit indicates whether or not the - // corresponding field of the message has been initialized. - // The bit for field index i is obtained by the expression: - // has_bits[i / 32] & (1 << (i % 32)) - // unknown_fields_offset: Offset in the message of the UnknownFieldSet for - // the message. - // extensions_offset: Offset in the message of the ExtensionSet for the - // message, or -1 if the message type has no extension - // ranges. - // pool: DescriptorPool to search for extension definitions. Only - // used by FindKnownExtensionByName() and - // FindKnownExtensionByNumber(). - // factory: MessageFactory to use to construct extension messages. - // object_size: The size of a message object of this type, as measured - // by sizeof(). - GeneratedMessageReflection(const Descriptor* descriptor, - const Message* default_instance, - const int offsets[], - int has_bits_offset, - int unknown_fields_offset, - int extensions_offset, - const DescriptorPool* pool, - MessageFactory* factory, - int object_size); - ~GeneratedMessageReflection(); - - // implements Reflection ------------------------------------------- - - const UnknownFieldSet& GetUnknownFields(const Message& message) const; - UnknownFieldSet* MutableUnknownFields(Message* message) const; - - int SpaceUsed(const Message& message) const; - - bool HasField(const Message& message, const FieldDescriptor* field) const; - int FieldSize(const Message& message, const FieldDescriptor* field) const; - void ClearField(Message* message, const FieldDescriptor* field) const; - void RemoveLast(Message* message, const FieldDescriptor* field) const; - void Swap(Message* message1, Message* message2) const; - void SwapElements(Message* message, const FieldDescriptor* field, - int index1, int index2) const; - void ListFields(const Message& message, - vector* output) const; - - int32 GetInt32 (const Message& message, - const FieldDescriptor* field) const; - int64 GetInt64 (const Message& message, - const FieldDescriptor* field) const; - uint32 GetUInt32(const Message& message, - const FieldDescriptor* field) const; - uint64 GetUInt64(const Message& message, - const FieldDescriptor* field) const; - float GetFloat (const Message& message, - const FieldDescriptor* field) const; - double GetDouble(const Message& message, - const FieldDescriptor* field) const; - bool GetBool (const Message& message, - const FieldDescriptor* field) const; - string GetString(const Message& message, - const FieldDescriptor* field) const; - const string& GetStringReference(const Message& message, - const FieldDescriptor* field, - string* scratch) const; - const EnumValueDescriptor* GetEnum(const Message& message, - const FieldDescriptor* field) const; - const Message& GetMessage(const Message& message, - const FieldDescriptor* field, - MessageFactory* factory = NULL) const; - - void SetInt32 (Message* message, - const FieldDescriptor* field, int32 value) const; - void SetInt64 (Message* message, - const FieldDescriptor* field, int64 value) const; - void SetUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const; - void SetUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const; - void SetFloat (Message* message, - const FieldDescriptor* field, float value) const; - void SetDouble(Message* message, - const FieldDescriptor* field, double value) const; - void SetBool (Message* message, - const FieldDescriptor* field, bool value) const; - void SetString(Message* message, - const FieldDescriptor* field, - const string& value) const; - void SetEnum (Message* message, const FieldDescriptor* field, - const EnumValueDescriptor* value) const; - Message* MutableMessage(Message* message, const FieldDescriptor* field, - MessageFactory* factory = NULL) const; - - int32 GetRepeatedInt32 (const Message& message, - const FieldDescriptor* field, int index) const; - int64 GetRepeatedInt64 (const Message& message, - const FieldDescriptor* field, int index) const; - uint32 GetRepeatedUInt32(const Message& message, - const FieldDescriptor* field, int index) const; - uint64 GetRepeatedUInt64(const Message& message, - const FieldDescriptor* field, int index) const; - float GetRepeatedFloat (const Message& message, - const FieldDescriptor* field, int index) const; - double GetRepeatedDouble(const Message& message, - const FieldDescriptor* field, int index) const; - bool GetRepeatedBool (const Message& message, - const FieldDescriptor* field, int index) const; - string GetRepeatedString(const Message& message, - const FieldDescriptor* field, int index) const; - const string& GetRepeatedStringReference(const Message& message, - const FieldDescriptor* field, - int index, string* scratch) const; - const EnumValueDescriptor* GetRepeatedEnum(const Message& message, - const FieldDescriptor* field, - int index) const; - const Message& GetRepeatedMessage(const Message& message, - const FieldDescriptor* field, - int index) const; - - // Set the value of a field. - void SetRepeatedInt32 (Message* message, - const FieldDescriptor* field, int index, int32 value) const; - void SetRepeatedInt64 (Message* message, - const FieldDescriptor* field, int index, int64 value) const; - void SetRepeatedUInt32(Message* message, - const FieldDescriptor* field, int index, uint32 value) const; - void SetRepeatedUInt64(Message* message, - const FieldDescriptor* field, int index, uint64 value) const; - void SetRepeatedFloat (Message* message, - const FieldDescriptor* field, int index, float value) const; - void SetRepeatedDouble(Message* message, - const FieldDescriptor* field, int index, double value) const; - void SetRepeatedBool (Message* message, - const FieldDescriptor* field, int index, bool value) const; - void SetRepeatedString(Message* message, - const FieldDescriptor* field, int index, - const string& value) const; - void SetRepeatedEnum(Message* message, const FieldDescriptor* field, - int index, const EnumValueDescriptor* value) const; - // Get a mutable pointer to a field with a message type. - Message* MutableRepeatedMessage(Message* message, - const FieldDescriptor* field, - int index) const; - - void AddInt32 (Message* message, - const FieldDescriptor* field, int32 value) const; - void AddInt64 (Message* message, - const FieldDescriptor* field, int64 value) const; - void AddUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const; - void AddUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const; - void AddFloat (Message* message, - const FieldDescriptor* field, float value) const; - void AddDouble(Message* message, - const FieldDescriptor* field, double value) const; - void AddBool (Message* message, - const FieldDescriptor* field, bool value) const; - void AddString(Message* message, - const FieldDescriptor* field, const string& value) const; - void AddEnum(Message* message, - const FieldDescriptor* field, - const EnumValueDescriptor* value) const; - Message* AddMessage(Message* message, const FieldDescriptor* field, - MessageFactory* factory = NULL) const; - - const FieldDescriptor* FindKnownExtensionByName(const string& name) const; - const FieldDescriptor* FindKnownExtensionByNumber(int number) const; - - private: - friend class GeneratedMessage; - - const Descriptor* descriptor_; - const Message* default_instance_; - const int* offsets_; - - int has_bits_offset_; - int unknown_fields_offset_; - int extensions_offset_; - int object_size_; - - const DescriptorPool* descriptor_pool_; - MessageFactory* message_factory_; - - template - inline const Type& GetRaw(const Message& message, - const FieldDescriptor* field) const; - template - inline Type* MutableRaw(Message* message, - const FieldDescriptor* field) const; - template - inline const Type& DefaultRaw(const FieldDescriptor* field) const; - inline const Message* GetMessagePrototype(const FieldDescriptor* field) const; - - inline const uint32* GetHasBits(const Message& message) const; - inline uint32* MutableHasBits(Message* message) const; - inline const ExtensionSet& GetExtensionSet(const Message& message) const; - inline ExtensionSet* MutableExtensionSet(Message* message) const; - - inline bool HasBit(const Message& message, - const FieldDescriptor* field) const; - inline void SetBit(Message* message, - const FieldDescriptor* field) const; - inline void ClearBit(Message* message, - const FieldDescriptor* field) const; - - template - inline const Type& GetField(const Message& message, - const FieldDescriptor* field) const; - template - inline void SetField(Message* message, - const FieldDescriptor* field, const Type& value) const; - template - inline Type* MutableField(Message* message, - const FieldDescriptor* field) const; - template - inline const Type& GetRepeatedField(const Message& message, - const FieldDescriptor* field, - int index) const; - template - inline const Type& GetRepeatedPtrField(const Message& message, - const FieldDescriptor* field, - int index) const; - template - inline void SetRepeatedField(Message* message, - const FieldDescriptor* field, int index, - Type value) const; - template - inline Type* MutableRepeatedField(Message* message, - const FieldDescriptor* field, - int index) const; - template - inline void AddField(Message* message, - const FieldDescriptor* field, const Type& value) const; - template - inline Type* AddField(Message* message, - const FieldDescriptor* field) const; - - int GetExtensionNumberOrDie(const Descriptor* type) const; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GeneratedMessageReflection); -}; - -// Returns the offset of the given field within the given aggregate type. -// This is equivalent to the ANSI C offsetof() macro. However, according -// to the C++ standard, offsetof() only works on POD types, and GCC -// enforces this requirement with a warning. In practice, this rule is -// unnecessarily strict; there is probably no compiler or platform on -// which the offsets of the direct fields of a class are non-constant. -// Fields inherited from superclasses *can* have non-constant offsets, -// but that's not what this macro will be used for. -// -// Note that we calculate relative to the pointer value 16 here since if we -// just use zero, GCC complains about dereferencing a NULL pointer. We -// choose 16 rather than some other number just in case the compiler would -// be confused by an unaligned pointer. -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(TYPE, FIELD) \ - static_cast( \ - reinterpret_cast( \ - &reinterpret_cast(16)->FIELD) - \ - reinterpret_cast(16)) - -// There are some places in proto2 where dynamic_cast would be useful as an -// optimization. For example, take Message::MergeFrom(const Message& other). -// For a given generated message FooMessage, we generate these two methods: -// void MergeFrom(const FooMessage& other); -// void MergeFrom(const Message& other); -// The former method can be implemented directly in terms of FooMessage's -// inline accessors, but the latter method must work with the reflection -// interface. However, if the parameter to the latter method is actually of -// type FooMessage, then we'd like to be able to just call the other method -// as an optimization. So, we use dynamic_cast to check this. -// -// That said, dynamic_cast requires RTTI, which many people like to disable -// for performance and code size reasons. When RTTI is not available, we -// still need to produce correct results. So, in this case we have to fall -// back to using reflection, which is what we would have done anyway if the -// objects were not of the exact same class. -// -// dynamic_cast_if_available() implements this logic. If RTTI is -// enabled, it does a dynamic_cast. If RTTI is disabled, it just returns -// NULL. -// -// If you need to compile without RTTI, simply #define GOOGLE_PROTOBUF_NO_RTTI. -// On MSVC, this should be detected automatically. -template -inline To dynamic_cast_if_available(From from) { -#if defined(GOOGLE_PROTOBUF_NO_RTTI) || (defined(_MSC_VER)&&!defined(_CPPRTTI)) - return NULL; -#else - return dynamic_cast(from); -#endif -} - -// Helper for EnumType_Parse functions: try to parse the string 'name' as an -// enum name of the given type, returning true and filling in value on success, -// or returning false and leaving value unchanged on failure. -LIBPROTOBUF_EXPORT bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, - int* value); - -template -bool ParseNamedEnum(const EnumDescriptor* descriptor, - const string& name, - EnumType* value) { - int tmp; - if (!ParseNamedEnum(descriptor, name, &tmp)) return false; - *value = static_cast(tmp); - return true; -} - -// Just a wrapper around printing the name of a value. The main point of this -// function is not to be inlined, so that you can do this without including -// descriptor.h. -LIBPROTOBUF_EXPORT const string& NameOfEnum(const EnumDescriptor* descriptor, int value); - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_REFLECTION_H__ diff --git a/Resources/NetHook/google/protobuf/generated_message_reflection_unittest.cc b/Resources/NetHook/google/protobuf/generated_message_reflection_unittest.cc deleted file mode 100644 index a03bcdb7..00000000 --- a/Resources/NetHook/google/protobuf/generated_message_reflection_unittest.cc +++ /dev/null @@ -1,384 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// To test GeneratedMessageReflection, we actually let the protocol compiler -// generate a full protocol message implementation and then test its -// reflection interface. This is much easier and more maintainable than -// trying to create our own Message class for GeneratedMessageReflection -// to wrap. -// -// The tests here closely mirror some of the tests in -// compiler/cpp/unittest, except using the reflection interface -// rather than generated accessors. - -#include -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { - -namespace { - -// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. -const FieldDescriptor* F(const string& name) { - const FieldDescriptor* result = - unittest::TestAllTypes::descriptor()->FindFieldByName(name); - GOOGLE_CHECK(result != NULL); - return result; -} - -TEST(GeneratedMessageReflectionTest, Defaults) { - // Check that all default values are set correctly in the initial message. - unittest::TestAllTypes message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - - reflection_tester.ExpectClearViaReflection(message); - - const Reflection* reflection = message.GetReflection(); - - // Messages should return pointers to default instances until first use. - // (This is not checked by ExpectClear() since it is not actually true after - // the fields have been set and then cleared.) - EXPECT_EQ(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &reflection->GetMessage(message, F("optionalgroup"))); - EXPECT_EQ(&unittest::TestAllTypes::NestedMessage::default_instance(), - &reflection->GetMessage(message, F("optional_nested_message"))); - EXPECT_EQ(&unittest::ForeignMessage::default_instance(), - &reflection->GetMessage(message, F("optional_foreign_message"))); - EXPECT_EQ(&unittest_import::ImportMessage::default_instance(), - &reflection->GetMessage(message, F("optional_import_message"))); -} - -TEST(GeneratedMessageReflectionTest, Accessors) { - // Set every field to a unique value then go back and check all those - // values. - unittest::TestAllTypes message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - - reflection_tester.SetAllFieldsViaReflection(&message); - TestUtil::ExpectAllFieldsSet(message); - reflection_tester.ExpectAllFieldsSetViaReflection(message); - - reflection_tester.ModifyRepeatedFieldsViaReflection(&message); - TestUtil::ExpectRepeatedFieldsModified(message); -} - -TEST(GeneratedMessageReflectionTest, GetStringReference) { - // Test that GetStringReference() returns the underlying string when it is - // a normal string field. - unittest::TestAllTypes message; - message.set_optional_string("foo"); - message.add_repeated_string("foo"); - - const Reflection* reflection = message.GetReflection(); - string scratch; - - EXPECT_EQ(&message.optional_string(), - &reflection->GetStringReference(message, F("optional_string"), &scratch)) - << "For simple string fields, GetStringReference() should return a " - "reference to the underlying string."; - EXPECT_EQ(&message.repeated_string(0), - &reflection->GetRepeatedStringReference(message, F("repeated_string"), - 0, &scratch)) - << "For simple string fields, GetRepeatedStringReference() should return " - "a reference to the underlying string."; -} - - -TEST(GeneratedMessageReflectionTest, DefaultsAfterClear) { - // Check that after setting all fields and then clearing, getting an - // embedded message does NOT return the default instance. - unittest::TestAllTypes message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - - TestUtil::SetAllFields(&message); - message.Clear(); - - const Reflection* reflection = message.GetReflection(); - - EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &reflection->GetMessage(message, F("optionalgroup"))); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &reflection->GetMessage(message, F("optional_nested_message"))); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &reflection->GetMessage(message, F("optional_foreign_message"))); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &reflection->GetMessage(message, F("optional_import_message"))); -} - - -TEST(GeneratedMessageReflectionTest, Swap) { - unittest::TestAllTypes message1; - unittest::TestAllTypes message2; - - TestUtil::SetAllFields(&message1); - - const Reflection* reflection = message1.GetReflection(); - reflection->Swap(&message1, &message2); - - TestUtil::ExpectClear(message1); - TestUtil::ExpectAllFieldsSet(message2); -} - -TEST(GeneratedMessageReflectionTest, SwapWithBothSet) { - unittest::TestAllTypes message1; - unittest::TestAllTypes message2; - - TestUtil::SetAllFields(&message1); - TestUtil::SetAllFields(&message2); - TestUtil::ModifyRepeatedFields(&message2); - - const Reflection* reflection = message1.GetReflection(); - reflection->Swap(&message1, &message2); - - TestUtil::ExpectRepeatedFieldsModified(message1); - TestUtil::ExpectAllFieldsSet(message2); - - message1.set_optional_int32(532819); - - reflection->Swap(&message1, &message2); - - EXPECT_EQ(532819, message2.optional_int32()); -} - -TEST(GeneratedMessageReflectionTest, SwapExtensions) { - unittest::TestAllExtensions message1; - unittest::TestAllExtensions message2; - - TestUtil::SetAllExtensions(&message1); - - const Reflection* reflection = message1.GetReflection(); - reflection->Swap(&message1, &message2); - - TestUtil::ExpectExtensionsClear(message1); - TestUtil::ExpectAllExtensionsSet(message2); -} - -TEST(GeneratedMessageReflectionTest, SwapUnknown) { - unittest::TestEmptyMessage message1, message2; - - message1.mutable_unknown_fields()->AddVarint(1234, 1); - - EXPECT_EQ(1, message1.unknown_fields().field_count()); - EXPECT_EQ(0, message2.unknown_fields().field_count()); - const Reflection* reflection = message1.GetReflection(); - reflection->Swap(&message1, &message2); - EXPECT_EQ(0, message1.unknown_fields().field_count()); - EXPECT_EQ(1, message2.unknown_fields().field_count()); -} - -TEST(GeneratedMessageReflectionTest, RemoveLast) { - unittest::TestAllTypes message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - - TestUtil::SetAllFields(&message); - - reflection_tester.RemoveLastRepeatedsViaReflection(&message); - - TestUtil::ExpectLastRepeatedsRemoved(message); -} - -TEST(GeneratedMessageReflectionTest, RemoveLastExtensions) { - unittest::TestAllExtensions message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); - - TestUtil::SetAllExtensions(&message); - reflection_tester.RemoveLastRepeatedsViaReflection(&message); - - TestUtil::ExpectLastRepeatedExtensionsRemoved(message); -} - -TEST(GeneratedMessageReflectionTest, SwapRepeatedElements) { - unittest::TestAllTypes message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllTypes::descriptor()); - - TestUtil::SetAllFields(&message); - - // Swap and test that fields are all swapped. - reflection_tester.SwapRepeatedsViaReflection(&message); - TestUtil::ExpectRepeatedsSwapped(message); - - // Swap back and test that fields are all back to original values. - reflection_tester.SwapRepeatedsViaReflection(&message); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(GeneratedMessageReflectionTest, SwapRepeatedElementsExtension) { - unittest::TestAllExtensions message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); - - TestUtil::SetAllExtensions(&message); - - // Swap and test that fields are all swapped. - reflection_tester.SwapRepeatedsViaReflection(&message); - TestUtil::ExpectRepeatedExtensionsSwapped(message); - - // Swap back and test that fields are all back to original values. - reflection_tester.SwapRepeatedsViaReflection(&message); - TestUtil::ExpectAllExtensionsSet(message); -} - -TEST(GeneratedMessageReflectionTest, Extensions) { - // Set every extension to a unique value then go back and check all those - // values. - unittest::TestAllExtensions message; - TestUtil::ReflectionTester reflection_tester( - unittest::TestAllExtensions::descriptor()); - - reflection_tester.SetAllFieldsViaReflection(&message); - TestUtil::ExpectAllExtensionsSet(message); - reflection_tester.ExpectAllFieldsSetViaReflection(message); - - reflection_tester.ModifyRepeatedFieldsViaReflection(&message); - TestUtil::ExpectRepeatedExtensionsModified(message); -} - -TEST(GeneratedMessageReflectionTest, FindExtensionTypeByNumber) { - const Reflection* reflection = - unittest::TestAllExtensions::default_instance().GetReflection(); - - const FieldDescriptor* extension1 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "optional_int32_extension"); - const FieldDescriptor* extension2 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "repeated_string_extension"); - - EXPECT_EQ(extension1, - reflection->FindKnownExtensionByNumber(extension1->number())); - EXPECT_EQ(extension2, - reflection->FindKnownExtensionByNumber(extension2->number())); - - // Non-existent extension. - EXPECT_TRUE(reflection->FindKnownExtensionByNumber(62341) == NULL); - - // Extensions of TestAllExtensions should not show up as extensions of - // other types. - EXPECT_TRUE(unittest::TestAllTypes::default_instance().GetReflection()-> - FindKnownExtensionByNumber(extension1->number()) == NULL); -} - -TEST(GeneratedMessageReflectionTest, FindKnownExtensionByName) { - const Reflection* reflection = - unittest::TestAllExtensions::default_instance().GetReflection(); - - const FieldDescriptor* extension1 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "optional_int32_extension"); - const FieldDescriptor* extension2 = - unittest::TestAllExtensions::descriptor()->file()->FindExtensionByName( - "repeated_string_extension"); - - EXPECT_EQ(extension1, - reflection->FindKnownExtensionByName(extension1->full_name())); - EXPECT_EQ(extension2, - reflection->FindKnownExtensionByName(extension2->full_name())); - - // Non-existent extension. - EXPECT_TRUE(reflection->FindKnownExtensionByName("no_such_ext") == NULL); - - // Extensions of TestAllExtensions should not show up as extensions of - // other types. - EXPECT_TRUE(unittest::TestAllTypes::default_instance().GetReflection()-> - FindKnownExtensionByName(extension1->full_name()) == NULL); -} - -#ifdef GTEST_HAS_DEATH_TEST - -TEST(GeneratedMessageReflectionTest, UsageErrors) { - unittest::TestAllTypes message; - const Reflection* reflection = message.GetReflection(); - const Descriptor* descriptor = message.GetDescriptor(); - -#define f(NAME) descriptor->FindFieldByName(NAME) - - // Testing every single failure mode would be too much work. Let's just - // check a few. - EXPECT_DEATH( - reflection->GetInt32( - message, descriptor->FindFieldByName("optional_int64")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::GetInt32\n" - " Message type: protobuf_unittest\\.TestAllTypes\n" - " Field : protobuf_unittest\\.TestAllTypes\\.optional_int64\n" - " Problem : Field is not the right type for this message:\n" - " Expected : CPPTYPE_INT32\n" - " Field type: CPPTYPE_INT64"); - EXPECT_DEATH( - reflection->GetInt32( - message, descriptor->FindFieldByName("repeated_int32")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::GetInt32\n" - " Message type: protobuf_unittest.TestAllTypes\n" - " Field : protobuf_unittest.TestAllTypes.repeated_int32\n" - " Problem : Field is repeated; the method requires a singular field."); - EXPECT_DEATH( - reflection->GetInt32( - message, unittest::ForeignMessage::descriptor()->FindFieldByName("c")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::GetInt32\n" - " Message type: protobuf_unittest.TestAllTypes\n" - " Field : protobuf_unittest.ForeignMessage.c\n" - " Problem : Field does not match message type."); - EXPECT_DEATH( - reflection->HasField( - message, unittest::ForeignMessage::descriptor()->FindFieldByName("c")), - "Protocol Buffer reflection usage error:\n" - " Method : google::protobuf::Reflection::HasField\n" - " Message type: protobuf_unittest.TestAllTypes\n" - " Field : protobuf_unittest.ForeignMessage.c\n" - " Problem : Field does not match message type."); - -#undef f -} - -#endif // GTEST_HAS_DEATH_TEST - - -} // namespace -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/generated_message_util.cc b/Resources/NetHook/google/protobuf/generated_message_util.cc deleted file mode 100644 index 7ac015d0..00000000 --- a/Resources/NetHook/google/protobuf/generated_message_util.cc +++ /dev/null @@ -1,53 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include - -namespace google { -namespace protobuf { -namespace internal { - -double Infinity() { - return std::numeric_limits::infinity(); -} -double NaN() { - return std::numeric_limits::quiet_NaN(); -} - - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/generated_message_util.h b/Resources/NetHook/google/protobuf/generated_message_util.h deleted file mode 100644 index daa16f77..00000000 --- a/Resources/NetHook/google/protobuf/generated_message_util.h +++ /dev/null @@ -1,77 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains miscellaneous helper code used by generated code -- -// including lite types -- but which should not be used directly by users. - -#ifndef GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__ -#define GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__ - -#include - - -namespace google { -namespace protobuf { - namespace io { - class CodedInputStream; // coded_stream.h - } -} - -namespace protobuf { -namespace internal { - -// Annotation for the compiler to emit a deprecation message if a field marked -// with option 'deprecated=true' is used in the code, or for other things in -// generated code which are deprecated. -// -// For internal use in the pb.cc files, deprecation warnings are suppressed -// there. -#undef DEPRECATED_PROTOBUF_FIELD -#if !defined(INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION) -# define PROTOBUF_DEPRECATED GOOGLE_ATTRIBUTE_DEPRECATED -#else -# define PROTOBUF_DEPRECATED -#endif - - -// Constants for special floating point values. -LIBPROTOBUF_EXPORT double Infinity(); -LIBPROTOBUF_EXPORT double NaN(); - - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_GENERATED_MESSAGE_UTIL_H__ diff --git a/Resources/NetHook/google/protobuf/io/coded_stream.cc b/Resources/NetHook/google/protobuf/io/coded_stream.cc deleted file mode 100644 index 6a91a13d..00000000 --- a/Resources/NetHook/google/protobuf/io/coded_stream.cc +++ /dev/null @@ -1,830 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This implementation is heavily optimized to make reads and writes -// of small values (especially varints) as fast as possible. In -// particular, we optimize for the common case that a read or a write -// will not cross the end of the buffer, since we can avoid a lot -// of branching in this case. - -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace io { - -namespace { - -static const int kMaxVarintBytes = 10; -static const int kMaxVarint32Bytes = 5; - - -} // namespace - -// CodedInputStream ================================================== - - -void CodedInputStream::BackUpInputToCurrentPosition() { - int backup_bytes = BufferSize() + buffer_size_after_limit_ + overflow_bytes_; - if (backup_bytes > 0) { - input_->BackUp(backup_bytes); - - // total_bytes_read_ doesn't include overflow_bytes_. - total_bytes_read_ -= BufferSize() + buffer_size_after_limit_; - buffer_end_ = buffer_; - buffer_size_after_limit_ = 0; - overflow_bytes_ = 0; - } -} - -inline void CodedInputStream::RecomputeBufferLimits() { - buffer_end_ += buffer_size_after_limit_; - int closest_limit = min(current_limit_, total_bytes_limit_); - if (closest_limit < total_bytes_read_) { - // The limit position is in the current buffer. We must adjust - // the buffer size accordingly. - buffer_size_after_limit_ = total_bytes_read_ - closest_limit; - buffer_end_ -= buffer_size_after_limit_; - } else { - buffer_size_after_limit_ = 0; - } -} - -CodedInputStream::Limit CodedInputStream::PushLimit(int byte_limit) { - // Current position relative to the beginning of the stream. - int current_position = total_bytes_read_ - - (BufferSize() + buffer_size_after_limit_); - - Limit old_limit = current_limit_; - - // security: byte_limit is possibly evil, so check for negative values - // and overflow. - if (byte_limit >= 0 && - byte_limit <= INT_MAX - current_position) { - current_limit_ = current_position + byte_limit; - } else { - // Negative or overflow. - current_limit_ = INT_MAX; - } - - // We need to enforce all limits, not just the new one, so if the previous - // limit was before the new requested limit, we continue to enforce the - // previous limit. - current_limit_ = min(current_limit_, old_limit); - - RecomputeBufferLimits(); - return old_limit; -} - -void CodedInputStream::PopLimit(Limit limit) { - // The limit passed in is actually the *old* limit, which we returned from - // PushLimit(). - current_limit_ = limit; - RecomputeBufferLimits(); - - // We may no longer be at a legitimate message end. ReadTag() needs to be - // called again to find out. - legitimate_message_end_ = false; -} - -int CodedInputStream::BytesUntilLimit() { - if (current_limit_ == INT_MAX) return -1; - int current_position = total_bytes_read_ - - (BufferSize() + buffer_size_after_limit_); - - return current_limit_ - current_position; -} - -void CodedInputStream::SetTotalBytesLimit( - int total_bytes_limit, int warning_threshold) { - // Make sure the limit isn't already past, since this could confuse other - // code. - int current_position = total_bytes_read_ - - (BufferSize() + buffer_size_after_limit_); - total_bytes_limit_ = max(current_position, total_bytes_limit); - total_bytes_warning_threshold_ = warning_threshold; - RecomputeBufferLimits(); -} - -void CodedInputStream::PrintTotalBytesLimitError() { - GOOGLE_LOG(ERROR) << "A protocol message was rejected because it was too " - "big (more than " << total_bytes_limit_ - << " bytes). To increase the limit (or to disable these " - "warnings), see CodedInputStream::SetTotalBytesLimit() " - "in google/protobuf/io/coded_stream.h."; -} - -bool CodedInputStream::Skip(int count) { - if (count < 0) return false; // security: count is often user-supplied - - const int original_buffer_size = BufferSize(); - - if (count <= original_buffer_size) { - // Just skipping within the current buffer. Easy. - Advance(count); - return true; - } - - if (buffer_size_after_limit_ > 0) { - // We hit a limit inside this buffer. Advance to the limit and fail. - Advance(original_buffer_size); - return false; - } - - count -= original_buffer_size; - buffer_ = NULL; - buffer_end_ = buffer_; - - // Make sure this skip doesn't try to skip past the current limit. - int closest_limit = min(current_limit_, total_bytes_limit_); - int bytes_until_limit = closest_limit - total_bytes_read_; - if (bytes_until_limit < count) { - // We hit the limit. Skip up to it then fail. - if (bytes_until_limit > 0) { - total_bytes_read_ = closest_limit; - input_->Skip(bytes_until_limit); - } - return false; - } - - total_bytes_read_ += count; - return input_->Skip(count); -} - -bool CodedInputStream::GetDirectBufferPointer(const void** data, int* size) { - if (BufferSize() == 0 && !Refresh()) return false; - - *data = buffer_; - *size = BufferSize(); - return true; -} - -bool CodedInputStream::ReadRaw(void* buffer, int size) { - int current_buffer_size; - while ((current_buffer_size = BufferSize()) < size) { - // Reading past end of buffer. Copy what we have, then refresh. - memcpy(buffer, buffer_, current_buffer_size); - buffer = reinterpret_cast(buffer) + current_buffer_size; - size -= current_buffer_size; - Advance(current_buffer_size); - if (!Refresh()) return false; - } - - memcpy(buffer, buffer_, size); - Advance(size); - - return true; -} - -bool CodedInputStream::ReadString(string* buffer, int size) { - if (size < 0) return false; // security: size is often user-supplied - return InternalReadStringInline(buffer, size); -} - -bool CodedInputStream::ReadStringFallback(string* buffer, int size) { - if (!buffer->empty()) { - buffer->clear(); - } - - int current_buffer_size; - while ((current_buffer_size = BufferSize()) < size) { - // Some STL implementations "helpfully" crash on buffer->append(NULL, 0). - if (current_buffer_size != 0) { - // Note: string1.append(string2) is O(string2.size()) (as opposed to - // O(string1.size() + string2.size()), which would be bad). - buffer->append(reinterpret_cast(buffer_), - current_buffer_size); - } - size -= current_buffer_size; - Advance(current_buffer_size); - if (!Refresh()) return false; - } - - buffer->append(reinterpret_cast(buffer_), size); - Advance(size); - - return true; -} - - -bool CodedInputStream::ReadLittleEndian32Fallback(uint32* value) { - uint8 bytes[sizeof(*value)]; - - const uint8* ptr; - if (BufferSize() >= sizeof(*value)) { - // Fast path: Enough bytes in the buffer to read directly. - ptr = buffer_; - Advance(sizeof(*value)); - } else { - // Slow path: Had to read past the end of the buffer. - if (!ReadRaw(bytes, sizeof(*value))) return false; - ptr = bytes; - } - ReadLittleEndian32FromArray(ptr, value); - return true; -} - -bool CodedInputStream::ReadLittleEndian64Fallback(uint64* value) { - uint8 bytes[sizeof(*value)]; - - const uint8* ptr; - if (BufferSize() >= sizeof(*value)) { - // Fast path: Enough bytes in the buffer to read directly. - ptr = buffer_; - Advance(sizeof(*value)); - } else { - // Slow path: Had to read past the end of the buffer. - if (!ReadRaw(bytes, sizeof(*value))) return false; - ptr = bytes; - } - ReadLittleEndian64FromArray(ptr, value); - return true; -} - -namespace { - -inline const uint8* ReadVarint32FromArray( - const uint8* buffer, uint32* value) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; -inline const uint8* ReadVarint32FromArray(const uint8* buffer, uint32* value) { - // Fast path: We have enough bytes left in the buffer to guarantee that - // this read won't cross the end, so we can skip the checks. - const uint8* ptr = buffer; - uint32 b; - uint32 result; - - b = *(ptr++); result = (b & 0x7F) ; if (!(b & 0x80)) goto done; - b = *(ptr++); result |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done; - b = *(ptr++); result |= (b & 0x7F) << 14; if (!(b & 0x80)) goto done; - b = *(ptr++); result |= (b & 0x7F) << 21; if (!(b & 0x80)) goto done; - b = *(ptr++); result |= b << 28; if (!(b & 0x80)) goto done; - - // If the input is larger than 32 bits, we still need to read it all - // and discard the high-order bits. - for (int i = 0; i < kMaxVarintBytes - kMaxVarint32Bytes; i++) { - b = *(ptr++); if (!(b & 0x80)) goto done; - } - - // We have overrun the maximum size of a varint (10 bytes). Assume - // the data is corrupt. - return NULL; - - done: - *value = result; - return ptr; -} - -} // namespace - -bool CodedInputStream::ReadVarint32Slow(uint32* value) { - uint64 result; - // Directly invoke ReadVarint64Fallback, since we already tried to optimize - // for one-byte varints. - if (!ReadVarint64Fallback(&result)) return false; - *value = (uint32)result; - return true; -} - -bool CodedInputStream::ReadVarint32Fallback(uint32* value) { - if (BufferSize() >= kMaxVarintBytes || - // Optimization: If the varint ends at exactly the end of the buffer, - // we can detect that and still use the fast path. - (buffer_end_ > buffer_ && !(buffer_end_[-1] & 0x80))) { - const uint8* end = ReadVarint32FromArray(buffer_, value); - if (end == NULL) return false; - buffer_ = end; - return true; - } else { - // Really slow case: we will incur the cost of an extra function call here, - // but moving this out of line reduces the size of this function, which - // improves the common case. In micro benchmarks, this is worth about 10-15% - return ReadVarint32Slow(value); - } -} - -uint32 CodedInputStream::ReadTagSlow() { - if (buffer_ == buffer_end_) { - // Call refresh. - if (!Refresh()) { - // Refresh failed. Make sure that it failed due to EOF, not because - // we hit total_bytes_limit_, which, unlike normal limits, is not a - // valid place to end a message. - int current_position = total_bytes_read_ - buffer_size_after_limit_; - if (current_position >= total_bytes_limit_) { - // Hit total_bytes_limit_. But if we also hit the normal limit, - // we're still OK. - legitimate_message_end_ = current_limit_ == total_bytes_limit_; - } else { - legitimate_message_end_ = true; - } - return 0; - } - } - - // For the slow path, just do a 64-bit read. Try to optimize for one-byte tags - // again, since we have now refreshed the buffer. - uint64 result; - if (!ReadVarint64(&result)) return 0; - return static_cast(result); -} - -uint32 CodedInputStream::ReadTagFallback() { - if (BufferSize() >= kMaxVarintBytes || - // Optimization: If the varint ends at exactly the end of the buffer, - // we can detect that and still use the fast path. - (buffer_end_ > buffer_ && !(buffer_end_[-1] & 0x80))) { - uint32 tag; - const uint8* end = ReadVarint32FromArray(buffer_, &tag); - if (end == NULL) { - return 0; - } - buffer_ = end; - return tag; - } else { - // We are commonly at a limit when attempting to read tags. Try to quickly - // detect this case without making another function call. - if (buffer_ == buffer_end_ && buffer_size_after_limit_ > 0 && - // Make sure that the limit we hit is not total_bytes_limit_, since - // in that case we still need to call Refresh() so that it prints an - // error. - total_bytes_read_ - buffer_size_after_limit_ < total_bytes_limit_) { - // We hit a byte limit. - legitimate_message_end_ = true; - return 0; - } - return ReadTagSlow(); - } -} - -bool CodedInputStream::ReadVarint64Slow(uint64* value) { - // Slow path: This read might cross the end of the buffer, so we - // need to check and refresh the buffer if and when it does. - - uint64 result = 0; - int count = 0; - uint32 b; - - do { - if (count == kMaxVarintBytes) return false; - while (buffer_ == buffer_end_) { - if (!Refresh()) return false; - } - b = *buffer_; - result |= static_cast(b & 0x7F) << (7 * count); - Advance(1); - ++count; - } while (b & 0x80); - - *value = result; - return true; -} - -bool CodedInputStream::ReadVarint64Fallback(uint64* value) { - if (BufferSize() >= kMaxVarintBytes || - // Optimization: If the varint ends at exactly the end of the buffer, - // we can detect that and still use the fast path. - (buffer_end_ > buffer_ && !(buffer_end_[-1] & 0x80))) { - // Fast path: We have enough bytes left in the buffer to guarantee that - // this read won't cross the end, so we can skip the checks. - - const uint8* ptr = buffer_; - uint32 b; - - // Splitting into 32-bit pieces gives better performance on 32-bit - // processors. - uint32 part0 = 0, part1 = 0, part2 = 0; - - b = *(ptr++); part0 = (b & 0x7F) ; if (!(b & 0x80)) goto done; - b = *(ptr++); part0 |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done; - b = *(ptr++); part0 |= (b & 0x7F) << 14; if (!(b & 0x80)) goto done; - b = *(ptr++); part0 |= (b & 0x7F) << 21; if (!(b & 0x80)) goto done; - b = *(ptr++); part1 = (b & 0x7F) ; if (!(b & 0x80)) goto done; - b = *(ptr++); part1 |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done; - b = *(ptr++); part1 |= (b & 0x7F) << 14; if (!(b & 0x80)) goto done; - b = *(ptr++); part1 |= (b & 0x7F) << 21; if (!(b & 0x80)) goto done; - b = *(ptr++); part2 = (b & 0x7F) ; if (!(b & 0x80)) goto done; - b = *(ptr++); part2 |= (b & 0x7F) << 7; if (!(b & 0x80)) goto done; - - // We have overrun the maximum size of a varint (10 bytes). The data - // must be corrupt. - return NULL; - - done: - Advance(ptr - buffer_); - *value = (static_cast(part0) ) | - (static_cast(part1) << 28) | - (static_cast(part2) << 56); - return true; - } else { - return ReadVarint64Slow(value); - } -} - -bool CodedInputStream::Refresh() { - GOOGLE_DCHECK_EQ(0, BufferSize()); - - if (buffer_size_after_limit_ > 0 || overflow_bytes_ > 0 || - total_bytes_read_ == current_limit_) { - // We've hit a limit. Stop. - int current_position = total_bytes_read_ - buffer_size_after_limit_; - - if (current_position >= total_bytes_limit_ && - total_bytes_limit_ != current_limit_) { - // Hit total_bytes_limit_. - PrintTotalBytesLimitError(); - } - - return false; - } - - if (total_bytes_warning_threshold_ >= 0 && - total_bytes_read_ >= total_bytes_warning_threshold_) { - GOOGLE_LOG(WARNING) << "Reading dangerously large protocol message. If the " - "message turns out to be larger than " - << total_bytes_limit_ << " bytes, parsing will be halted " - "for security reasons. To increase the limit (or to " - "disable these warnings), see " - "CodedInputStream::SetTotalBytesLimit() in " - "google/protobuf/io/coded_stream.h."; - - // Don't warn again for this stream. - total_bytes_warning_threshold_ = -1; - } - - const void* void_buffer; - int buffer_size; - if (input_->Next(&void_buffer, &buffer_size)) { - buffer_ = reinterpret_cast(void_buffer); - buffer_end_ = buffer_ + buffer_size; - GOOGLE_CHECK_GE(buffer_size, 0); - - if (total_bytes_read_ <= INT_MAX - buffer_size) { - total_bytes_read_ += buffer_size; - } else { - // Overflow. Reset buffer_end_ to not include the bytes beyond INT_MAX. - // We can't get that far anyway, because total_bytes_limit_ is guaranteed - // to be less than it. We need to keep track of the number of bytes - // we discarded, though, so that we can call input_->BackUp() to back - // up over them on destruction. - - // The following line is equivalent to: - // overflow_bytes_ = total_bytes_read_ + buffer_size - INT_MAX; - // except that it avoids overflows. Signed integer overflow has - // undefined results according to the C standard. - overflow_bytes_ = total_bytes_read_ - (INT_MAX - buffer_size); - buffer_end_ -= overflow_bytes_; - total_bytes_read_ = INT_MAX; - } - - RecomputeBufferLimits(); - return true; - } else { - buffer_ = NULL; - buffer_end_ = NULL; - return false; - } -} - -// CodedOutputStream ================================================= - -CodedOutputStream::CodedOutputStream(ZeroCopyOutputStream* output) - : output_(output), - buffer_(NULL), - buffer_size_(0), - total_bytes_(0), - had_error_(false) { - // Eagerly Refresh() so buffer space is immediately available. - Refresh(); - // The Refresh() may have failed. If the client doesn't write any data, - // though, don't consider this an error. If the client does write data, then - // another Refresh() will be attempted and it will set the error once again. - had_error_ = false; -} - -CodedOutputStream::~CodedOutputStream() { - if (buffer_size_ > 0) { - output_->BackUp(buffer_size_); - } -} - -bool CodedOutputStream::Skip(int count) { - if (count < 0) return false; - - while (count > buffer_size_) { - count -= buffer_size_; - if (!Refresh()) return false; - } - - Advance(count); - return true; -} - -bool CodedOutputStream::GetDirectBufferPointer(void** data, int* size) { - if (buffer_size_ == 0 && !Refresh()) return false; - - *data = buffer_; - *size = buffer_size_; - return true; -} - -void CodedOutputStream::WriteRaw(const void* data, int size) { - while (buffer_size_ < size) { - memcpy(buffer_, data, buffer_size_); - size -= buffer_size_; - data = reinterpret_cast(data) + buffer_size_; - if (!Refresh()) return; - } - - memcpy(buffer_, data, size); - Advance(size); -} - -uint8* CodedOutputStream::WriteRawToArray( - const void* data, int size, uint8* target) { - memcpy(target, data, size); - return target + size; -} - - -void CodedOutputStream::WriteLittleEndian32(uint32 value) { - uint8 bytes[sizeof(value)]; - - bool use_fast = buffer_size_ >= sizeof(value); - uint8* ptr = use_fast ? buffer_ : bytes; - - WriteLittleEndian32ToArray(value, ptr); - - if (use_fast) { - Advance(sizeof(value)); - } else { - WriteRaw(bytes, sizeof(value)); - } -} - -void CodedOutputStream::WriteLittleEndian64(uint64 value) { - uint8 bytes[sizeof(value)]; - - bool use_fast = buffer_size_ >= sizeof(value); - uint8* ptr = use_fast ? buffer_ : bytes; - - WriteLittleEndian64ToArray(value, ptr); - - if (use_fast) { - Advance(sizeof(value)); - } else { - WriteRaw(bytes, sizeof(value)); - } -} - -inline uint8* CodedOutputStream::WriteVarint32FallbackToArrayInline( - uint32 value, uint8* target) { - target[0] = static_cast(value | 0x80); - if (value >= (1 << 7)) { - target[1] = static_cast((value >> 7) | 0x80); - if (value >= (1 << 14)) { - target[2] = static_cast((value >> 14) | 0x80); - if (value >= (1 << 21)) { - target[3] = static_cast((value >> 21) | 0x80); - if (value >= (1 << 28)) { - target[4] = static_cast(value >> 28); - return target + 5; - } else { - target[3] &= 0x7F; - return target + 4; - } - } else { - target[2] &= 0x7F; - return target + 3; - } - } else { - target[1] &= 0x7F; - return target + 2; - } - } else { - target[0] &= 0x7F; - return target + 1; - } -} - -void CodedOutputStream::WriteVarint32(uint32 value) { - if (buffer_size_ >= kMaxVarint32Bytes) { - // Fast path: We have enough bytes left in the buffer to guarantee that - // this write won't cross the end, so we can skip the checks. - uint8* target = buffer_; - uint8* end = WriteVarint32FallbackToArrayInline(value, target); - int size = end - target; - Advance(size); - } else { - // Slow path: This write might cross the end of the buffer, so we - // compose the bytes first then use WriteRaw(). - uint8 bytes[kMaxVarint32Bytes]; - int size = 0; - while (value > 0x7F) { - bytes[size++] = (static_cast(value) & 0x7F) | 0x80; - value >>= 7; - } - bytes[size++] = static_cast(value) & 0x7F; - WriteRaw(bytes, size); - } -} - -uint8* CodedOutputStream::WriteVarint32FallbackToArray( - uint32 value, uint8* target) { - return WriteVarint32FallbackToArrayInline(value, target); -} - -inline uint8* CodedOutputStream::WriteVarint64ToArrayInline( - uint64 value, uint8* target) { - // Splitting into 32-bit pieces gives better performance on 32-bit - // processors. - uint32 part0 = static_cast(value ); - uint32 part1 = static_cast(value >> 28); - uint32 part2 = static_cast(value >> 56); - - int size; - - // Here we can't really optimize for small numbers, since the value is - // split into three parts. Cheking for numbers < 128, for instance, - // would require three comparisons, since you'd have to make sure part1 - // and part2 are zero. However, if the caller is using 64-bit integers, - // it is likely that they expect the numbers to often be very large, so - // we probably don't want to optimize for small numbers anyway. Thus, - // we end up with a hardcoded binary search tree... - if (part2 == 0) { - if (part1 == 0) { - if (part0 < (1 << 14)) { - if (part0 < (1 << 7)) { - size = 1; goto size1; - } else { - size = 2; goto size2; - } - } else { - if (part0 < (1 << 21)) { - size = 3; goto size3; - } else { - size = 4; goto size4; - } - } - } else { - if (part1 < (1 << 14)) { - if (part1 < (1 << 7)) { - size = 5; goto size5; - } else { - size = 6; goto size6; - } - } else { - if (part1 < (1 << 21)) { - size = 7; goto size7; - } else { - size = 8; goto size8; - } - } - } - } else { - if (part2 < (1 << 7)) { - size = 9; goto size9; - } else { - size = 10; goto size10; - } - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - - size10: target[9] = static_cast((part2 >> 7) | 0x80); - size9 : target[8] = static_cast((part2 ) | 0x80); - size8 : target[7] = static_cast((part1 >> 21) | 0x80); - size7 : target[6] = static_cast((part1 >> 14) | 0x80); - size6 : target[5] = static_cast((part1 >> 7) | 0x80); - size5 : target[4] = static_cast((part1 ) | 0x80); - size4 : target[3] = static_cast((part0 >> 21) | 0x80); - size3 : target[2] = static_cast((part0 >> 14) | 0x80); - size2 : target[1] = static_cast((part0 >> 7) | 0x80); - size1 : target[0] = static_cast((part0 ) | 0x80); - - target[size-1] &= 0x7F; - return target + size; -} - -void CodedOutputStream::WriteVarint64(uint64 value) { - if (buffer_size_ >= kMaxVarintBytes) { - // Fast path: We have enough bytes left in the buffer to guarantee that - // this write won't cross the end, so we can skip the checks. - uint8* target = buffer_; - - uint8* end = WriteVarint64ToArrayInline(value, target); - int size = end - target; - Advance(size); - } else { - // Slow path: This write might cross the end of the buffer, so we - // compose the bytes first then use WriteRaw(). - uint8 bytes[kMaxVarintBytes]; - int size = 0; - while (value > 0x7F) { - bytes[size++] = (static_cast(value) & 0x7F) | 0x80; - value >>= 7; - } - bytes[size++] = static_cast(value) & 0x7F; - WriteRaw(bytes, size); - } -} - -uint8* CodedOutputStream::WriteVarint64ToArray( - uint64 value, uint8* target) { - return WriteVarint64ToArrayInline(value, target); -} - -bool CodedOutputStream::Refresh() { - void* void_buffer; - if (output_->Next(&void_buffer, &buffer_size_)) { - buffer_ = reinterpret_cast(void_buffer); - total_bytes_ += buffer_size_; - return true; - } else { - buffer_ = NULL; - buffer_size_ = 0; - had_error_ = true; - return false; - } -} - -int CodedOutputStream::VarintSize32Fallback(uint32 value) { - if (value < (1 << 7)) { - return 1; - } else if (value < (1 << 14)) { - return 2; - } else if (value < (1 << 21)) { - return 3; - } else if (value < (1 << 28)) { - return 4; - } else { - return 5; - } -} - -int CodedOutputStream::VarintSize64(uint64 value) { - if (value < (1ull << 35)) { - if (value < (1ull << 7)) { - return 1; - } else if (value < (1ull << 14)) { - return 2; - } else if (value < (1ull << 21)) { - return 3; - } else if (value < (1ull << 28)) { - return 4; - } else { - return 5; - } - } else { - if (value < (1ull << 42)) { - return 6; - } else if (value < (1ull << 49)) { - return 7; - } else if (value < (1ull << 56)) { - return 8; - } else if (value < (1ull << 63)) { - return 9; - } else { - return 10; - } - } -} - -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/coded_stream.h b/Resources/NetHook/google/protobuf/io/coded_stream.h deleted file mode 100644 index dcbb0d45..00000000 --- a/Resources/NetHook/google/protobuf/io/coded_stream.h +++ /dev/null @@ -1,1090 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains the CodedInputStream and CodedOutputStream classes, -// which wrap a ZeroCopyInputStream or ZeroCopyOutputStream, respectively, -// and allow you to read or write individual pieces of data in various -// formats. In particular, these implement the varint encoding for -// integers, a simple variable-length encoding in which smaller numbers -// take fewer bytes. -// -// Typically these classes will only be used internally by the protocol -// buffer library in order to encode and decode protocol buffers. Clients -// of the library only need to know about this class if they wish to write -// custom message parsing or serialization procedures. -// -// CodedOutputStream example: -// // Write some data to "myfile". First we write a 4-byte "magic number" -// // to identify the file type, then write a length-delimited string. The -// // string is composed of a varint giving the length followed by the raw -// // bytes. -// int fd = open("myfile", O_WRONLY); -// ZeroCopyOutputStream* raw_output = new FileOutputStream(fd); -// CodedOutputStream* coded_output = new CodedOutputStream(raw_output); -// -// int magic_number = 1234; -// char text[] = "Hello world!"; -// coded_output->WriteLittleEndian32(magic_number); -// coded_output->WriteVarint32(strlen(text)); -// coded_output->WriteRaw(text, strlen(text)); -// -// delete coded_output; -// delete raw_output; -// close(fd); -// -// CodedInputStream example: -// // Read a file created by the above code. -// int fd = open("myfile", O_RDONLY); -// ZeroCopyInputStream* raw_input = new FileInputStream(fd); -// CodedInputStream coded_input = new CodedInputStream(raw_input); -// -// coded_input->ReadLittleEndian32(&magic_number); -// if (magic_number != 1234) { -// cerr << "File not in expected format." << endl; -// return; -// } -// -// uint32 size; -// coded_input->ReadVarint32(&size); -// -// char* text = new char[size + 1]; -// coded_input->ReadRaw(buffer, size); -// text[size] = '\0'; -// -// delete coded_input; -// delete raw_input; -// close(fd); -// -// cout << "Text is: " << text << endl; -// delete [] text; -// -// For those who are interested, varint encoding is defined as follows: -// -// The encoding operates on unsigned integers of up to 64 bits in length. -// Each byte of the encoded value has the format: -// * bits 0-6: Seven bits of the number being encoded. -// * bit 7: Zero if this is the last byte in the encoding (in which -// case all remaining bits of the number are zero) or 1 if -// more bytes follow. -// The first byte contains the least-significant 7 bits of the number, the -// second byte (if present) contains the next-least-significant 7 bits, -// and so on. So, the binary number 1011000101011 would be encoded in two -// bytes as "10101011 00101100". -// -// In theory, varint could be used to encode integers of any length. -// However, for practicality we set a limit at 64 bits. The maximum encoded -// length of a number is thus 10 bytes. - -#ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_H__ -#define GOOGLE_PROTOBUF_IO_CODED_STREAM_H__ - -#include -#ifndef _MSC_VER -#include -#endif // !_MSC_VER -#include -#include // for GOOGLE_PREDICT_TRUE macro - -namespace google { - -namespace protobuf { - -class DescriptorPool; -class MessageFactory; - -namespace io { - -// Defined in this file. -class CodedInputStream; -class CodedOutputStream; - -// Defined in other files. -class ZeroCopyInputStream; // zero_copy_stream.h -class ZeroCopyOutputStream; // zero_copy_stream.h - -// Class which reads and decodes binary data which is composed of varint- -// encoded integers and fixed-width pieces. Wraps a ZeroCopyInputStream. -// Most users will not need to deal with CodedInputStream. -// -// Most methods of CodedInputStream that return a bool return false if an -// underlying I/O error occurs or if the data is malformed. Once such a -// failure occurs, the CodedInputStream is broken and is no longer useful. -class LIBPROTOBUF_EXPORT CodedInputStream { - public: - // Create a CodedInputStream that reads from the given ZeroCopyInputStream. - explicit CodedInputStream(ZeroCopyInputStream* input); - - // Create a CodedInputStream that reads from the given flat array. This is - // faster than using an ArrayInputStream. PushLimit(size) is implied by - // this constructor. - explicit CodedInputStream(const uint8* buffer, int size); - - // Destroy the CodedInputStream and position the underlying - // ZeroCopyInputStream at the first unread byte. If an error occurred while - // reading (causing a method to return false), then the exact position of - // the input stream may be anywhere between the last value that was read - // successfully and the stream's byte limit. - ~CodedInputStream(); - - - // Skips a number of bytes. Returns false if an underlying read error - // occurs. - bool Skip(int count); - - // Sets *data to point directly at the unread part of the CodedInputStream's - // underlying buffer, and *size to the size of that buffer, but does not - // advance the stream's current position. This will always either produce - // a non-empty buffer or return false. If the caller consumes any of - // this data, it should then call Skip() to skip over the consumed bytes. - // This may be useful for implementing external fast parsing routines for - // types of data not covered by the CodedInputStream interface. - bool GetDirectBufferPointer(const void** data, int* size); - - // Like GetDirectBufferPointer, but this method is inlined, and does not - // attempt to Refresh() if the buffer is currently empty. - inline void GetDirectBufferPointerInline(const void** data, - int* size) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - // Read raw bytes, copying them into the given buffer. - bool ReadRaw(void* buffer, int size); - - // Like ReadRaw, but reads into a string. - // - // Implementation Note: ReadString() grows the string gradually as it - // reads in the data, rather than allocating the entire requested size - // upfront. This prevents denial-of-service attacks in which a client - // could claim that a string is going to be MAX_INT bytes long in order to - // crash the server because it can't allocate this much space at once. - bool ReadString(string* buffer, int size); - // Like the above, with inlined optimizations. This should only be used - // by the protobuf implementation. - inline bool InternalReadStringInline(string* buffer, - int size) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - - // Read a 32-bit little-endian integer. - bool ReadLittleEndian32(uint32* value); - // Read a 64-bit little-endian integer. - bool ReadLittleEndian64(uint64* value); - - // These methods read from an externally provided buffer. The caller is - // responsible for ensuring that the buffer has sufficient space. - // Read a 32-bit little-endian integer. - static const uint8* ReadLittleEndian32FromArray(const uint8* buffer, - uint32* value); - // Read a 64-bit little-endian integer. - static const uint8* ReadLittleEndian64FromArray(const uint8* buffer, - uint64* value); - - // Read an unsigned integer with Varint encoding, truncating to 32 bits. - // Reading a 32-bit value is equivalent to reading a 64-bit one and casting - // it to uint32, but may be more efficient. - bool ReadVarint32(uint32* value); - // Read an unsigned integer with Varint encoding. - bool ReadVarint64(uint64* value); - - // Read a tag. This calls ReadVarint32() and returns the result, or returns - // zero (which is not a valid tag) if ReadVarint32() fails. Also, it updates - // the last tag value, which can be checked with LastTagWas(). - // Always inline because this is only called in once place per parse loop - // but it is called for every iteration of said loop, so it should be fast. - // GCC doesn't want to inline this by default. - uint32 ReadTag() GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - // Usually returns true if calling ReadVarint32() now would produce the given - // value. Will always return false if ReadVarint32() would not return the - // given value. If ExpectTag() returns true, it also advances past - // the varint. For best performance, use a compile-time constant as the - // parameter. - // Always inline because this collapses to a small number of instructions - // when given a constant parameter, but GCC doesn't want to inline by default. - bool ExpectTag(uint32 expected) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - // Like above, except this reads from the specified buffer. The caller is - // responsible for ensuring that the buffer is large enough to read a varint - // of the expected size. For best performance, use a compile-time constant as - // the expected tag parameter. - // - // Returns a pointer beyond the expected tag if it was found, or NULL if it - // was not. - static const uint8* ExpectTagFromArray( - const uint8* buffer, - uint32 expected) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - // Usually returns true if no more bytes can be read. Always returns false - // if more bytes can be read. If ExpectAtEnd() returns true, a subsequent - // call to LastTagWas() will act as if ReadTag() had been called and returned - // zero, and ConsumedEntireMessage() will return true. - bool ExpectAtEnd(); - - // If the last call to ReadTag() returned the given value, returns true. - // Otherwise, returns false; - // - // This is needed because parsers for some types of embedded messages - // (with field type TYPE_GROUP) don't actually know that they've reached the - // end of a message until they see an ENDGROUP tag, which was actually part - // of the enclosing message. The enclosing message would like to check that - // tag to make sure it had the right number, so it calls LastTagWas() on - // return from the embedded parser to check. - bool LastTagWas(uint32 expected); - - // When parsing message (but NOT a group), this method must be called - // immediately after MergeFromCodedStream() returns (if it returns true) - // to further verify that the message ended in a legitimate way. For - // example, this verifies that parsing did not end on an end-group tag. - // It also checks for some cases where, due to optimizations, - // MergeFromCodedStream() can incorrectly return true. - bool ConsumedEntireMessage(); - - // Limits ---------------------------------------------------------- - // Limits are used when parsing length-delimited embedded messages. - // After the message's length is read, PushLimit() is used to prevent - // the CodedInputStream from reading beyond that length. Once the - // embedded message has been parsed, PopLimit() is called to undo the - // limit. - - // Opaque type used with PushLimit() and PopLimit(). Do not modify - // values of this type yourself. The only reason that this isn't a - // struct with private internals is for efficiency. - typedef int Limit; - - // Places a limit on the number of bytes that the stream may read, - // starting from the current position. Once the stream hits this limit, - // it will act like the end of the input has been reached until PopLimit() - // is called. - // - // As the names imply, the stream conceptually has a stack of limits. The - // shortest limit on the stack is always enforced, even if it is not the - // top limit. - // - // The value returned by PushLimit() is opaque to the caller, and must - // be passed unchanged to the corresponding call to PopLimit(). - Limit PushLimit(int byte_limit); - - // Pops the last limit pushed by PushLimit(). The input must be the value - // returned by that call to PushLimit(). - void PopLimit(Limit limit); - - // Returns the number of bytes left until the nearest limit on the - // stack is hit, or -1 if no limits are in place. - int BytesUntilLimit(); - - // Total Bytes Limit ----------------------------------------------- - // To prevent malicious users from sending excessively large messages - // and causing integer overflows or memory exhaustion, CodedInputStream - // imposes a hard limit on the total number of bytes it will read. - - // Sets the maximum number of bytes that this CodedInputStream will read - // before refusing to continue. To prevent integer overflows in the - // protocol buffers implementation, as well as to prevent servers from - // allocating enormous amounts of memory to hold parsed messages, the - // maximum message length should be limited to the shortest length that - // will not harm usability. The theoretical shortest message that could - // cause integer overflows is 512MB. The default limit is 64MB. Apps - // should set shorter limits if possible. If warning_threshold is not -1, - // a warning will be printed to stderr after warning_threshold bytes are - // read. An error will always be printed to stderr if the limit is - // reached. - // - // This is unrelated to PushLimit()/PopLimit(). - // - // Hint: If you are reading this because your program is printing a - // warning about dangerously large protocol messages, you may be - // confused about what to do next. The best option is to change your - // design such that excessively large messages are not necessary. - // For example, try to design file formats to consist of many small - // messages rather than a single large one. If this is infeasible, - // you will need to increase the limit. Chances are, though, that - // your code never constructs a CodedInputStream on which the limit - // can be set. You probably parse messages by calling things like - // Message::ParseFromString(). In this case, you will need to change - // your code to instead construct some sort of ZeroCopyInputStream - // (e.g. an ArrayInputStream), construct a CodedInputStream around - // that, then call Message::ParseFromCodedStream() instead. Then - // you can adjust the limit. Yes, it's more work, but you're doing - // something unusual. - void SetTotalBytesLimit(int total_bytes_limit, int warning_threshold); - - // Recursion Limit ------------------------------------------------- - // To prevent corrupt or malicious messages from causing stack overflows, - // we must keep track of the depth of recursion when parsing embedded - // messages and groups. CodedInputStream keeps track of this because it - // is the only object that is passed down the stack during parsing. - - // Sets the maximum recursion depth. The default is 64. - void SetRecursionLimit(int limit); - - // Increments the current recursion depth. Returns true if the depth is - // under the limit, false if it has gone over. - bool IncrementRecursionDepth(); - - // Decrements the recursion depth. - void DecrementRecursionDepth(); - - // Extension Registry ---------------------------------------------- - // ADVANCED USAGE: 99.9% of people can ignore this section. - // - // By default, when parsing extensions, the parser looks for extension - // definitions in the pool which owns the outer message's Descriptor. - // However, you may call SetExtensionRegistry() to provide an alternative - // pool instead. This makes it possible, for example, to parse a message - // using a generated class, but represent some extensions using - // DynamicMessage. - - // Set the pool used to look up extensions. Most users do not need to call - // this as the correct pool will be chosen automatically. - // - // WARNING: It is very easy to misuse this. Carefully read the requirements - // below. Do not use this unless you are sure you need it. Almost no one - // does. - // - // Let's say you are parsing a message into message object m, and you want - // to take advantage of SetExtensionRegistry(). You must follow these - // requirements: - // - // The given DescriptorPool must contain m->GetDescriptor(). It is not - // sufficient for it to simply contain a descriptor that has the same name - // and content -- it must be the *exact object*. In other words: - // assert(pool->FindMessageTypeByName(m->GetDescriptor()->full_name()) == - // m->GetDescriptor()); - // There are two ways to satisfy this requirement: - // 1) Use m->GetDescriptor()->pool() as the pool. This is generally useless - // because this is the pool that would be used anyway if you didn't call - // SetExtensionRegistry() at all. - // 2) Use a DescriptorPool which has m->GetDescriptor()->pool() as an - // "underlay". Read the documentation for DescriptorPool for more - // information about underlays. - // - // You must also provide a MessageFactory. This factory will be used to - // construct Message objects representing extensions. The factory's - // GetPrototype() MUST return non-NULL for any Descriptor which can be found - // through the provided pool. - // - // If the provided factory might return instances of protocol-compiler- - // generated (i.e. compiled-in) types, or if the outer message object m is - // a generated type, then the given factory MUST have this property: If - // GetPrototype() is given a Descriptor which resides in - // DescriptorPool::generated_pool(), the factory MUST return the same - // prototype which MessageFactory::generated_factory() would return. That - // is, given a descriptor for a generated type, the factory must return an - // instance of the generated class (NOT DynamicMessage). However, when - // given a descriptor for a type that is NOT in generated_pool, the factory - // is free to return any implementation. - // - // The reason for this requirement is that generated sub-objects may be - // accessed via the standard (non-reflection) extension accessor methods, - // and these methods will down-cast the object to the generated class type. - // If the object is not actually of that type, the results would be undefined. - // On the other hand, if an extension is not compiled in, then there is no - // way the code could end up accessing it via the standard accessors -- the - // only way to access the extension is via reflection. When using reflection, - // DynamicMessage and generated messages are indistinguishable, so it's fine - // if these objects are represented using DynamicMessage. - // - // Using DynamicMessageFactory on which you have called - // SetDelegateToGeneratedFactory(true) should be sufficient to satisfy the - // above requirement. - // - // If either pool or factory is NULL, both must be NULL. - // - // Note that this feature is ignored when parsing "lite" messages as they do - // not have descriptors. - void SetExtensionRegistry(DescriptorPool* pool, MessageFactory* factory); - - // Get the DescriptorPool set via SetExtensionRegistry(), or NULL if no pool - // has been provided. - const DescriptorPool* GetExtensionPool(); - - // Get the MessageFactory set via SetExtensionRegistry(), or NULL if no - // factory has been provided. - MessageFactory* GetExtensionFactory(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodedInputStream); - - ZeroCopyInputStream* input_; - const uint8* buffer_; - const uint8* buffer_end_; // pointer to the end of the buffer. - int total_bytes_read_; // total bytes read from input_, including - // the current buffer - - // If total_bytes_read_ surpasses INT_MAX, we record the extra bytes here - // so that we can BackUp() on destruction. - int overflow_bytes_; - - // LastTagWas() stuff. - uint32 last_tag_; // result of last ReadTag(). - - // This is set true by ReadTag{Fallback/Slow}() if it is called when exactly - // at EOF, or by ExpectAtEnd() when it returns true. This happens when we - // reach the end of a message and attempt to read another tag. - bool legitimate_message_end_; - - // See EnableAliasing(). - bool aliasing_enabled_; - - // Limits - Limit current_limit_; // if position = -1, no limit is applied - - // For simplicity, if the current buffer crosses a limit (either a normal - // limit created by PushLimit() or the total bytes limit), buffer_size_ - // only tracks the number of bytes before that limit. This field - // contains the number of bytes after it. Note that this implies that if - // buffer_size_ == 0 and buffer_size_after_limit_ > 0, we know we've - // hit a limit. However, if both are zero, it doesn't necessarily mean - // we aren't at a limit -- the buffer may have ended exactly at the limit. - int buffer_size_after_limit_; - - // Maximum number of bytes to read, period. This is unrelated to - // current_limit_. Set using SetTotalBytesLimit(). - int total_bytes_limit_; - int total_bytes_warning_threshold_; - - // Current recursion depth, controlled by IncrementRecursionDepth() and - // DecrementRecursionDepth(). - int recursion_depth_; - // Recursion depth limit, set by SetRecursionLimit(). - int recursion_limit_; - - // See SetExtensionRegistry(). - const DescriptorPool* extension_pool_; - MessageFactory* extension_factory_; - - // Private member functions. - - // Advance the buffer by a given number of bytes. - void Advance(int amount); - - // Back up input_ to the current buffer position. - void BackUpInputToCurrentPosition(); - - // Recomputes the value of buffer_size_after_limit_. Must be called after - // current_limit_ or total_bytes_limit_ changes. - void RecomputeBufferLimits(); - - // Writes an error message saying that we hit total_bytes_limit_. - void PrintTotalBytesLimitError(); - - // Called when the buffer runs out to request more data. Implies an - // Advance(BufferSize()). - bool Refresh(); - - // When parsing varints, we optimize for the common case of small values, and - // then optimize for the case when the varint fits within the current buffer - // piece. The Fallback method is used when we can't use the one-byte - // optimization. The Slow method is yet another fallback when the buffer is - // not large enough. Making the slow path out-of-line speeds up the common - // case by 10-15%. The slow path is fairly uncommon: it only triggers when a - // message crosses multiple buffers. - bool ReadVarint32Fallback(uint32* value); - bool ReadVarint64Fallback(uint64* value); - bool ReadVarint32Slow(uint32* value); - bool ReadVarint64Slow(uint64* value); - bool ReadLittleEndian32Fallback(uint32* value); - bool ReadLittleEndian64Fallback(uint64* value); - // Fallback/slow methods for reading tags. These do not update last_tag_, - // but will set legitimate_message_end_ if we are at the end of the input - // stream. - uint32 ReadTagFallback(); - uint32 ReadTagSlow(); - bool ReadStringFallback(string* buffer, int size); - - // Return the size of the buffer. - int BufferSize() const; - - static const int kDefaultTotalBytesLimit = 64 << 20; // 64MB - - static const int kDefaultTotalBytesWarningThreshold = 32 << 20; // 32MB - static const int kDefaultRecursionLimit = 64; -}; - -// Class which encodes and writes binary data which is composed of varint- -// encoded integers and fixed-width pieces. Wraps a ZeroCopyOutputStream. -// Most users will not need to deal with CodedOutputStream. -// -// Most methods of CodedOutputStream which return a bool return false if an -// underlying I/O error occurs. Once such a failure occurs, the -// CodedOutputStream is broken and is no longer useful. The Write* methods do -// not return the stream status, but will invalidate the stream if an error -// occurs. The client can probe HadError() to determine the status. -// -// Note that every method of CodedOutputStream which writes some data has -// a corresponding static "ToArray" version. These versions write directly -// to the provided buffer, returning a pointer past the last written byte. -// They require that the buffer has sufficient capacity for the encoded data. -// This allows an optimization where we check if an output stream has enough -// space for an entire message before we start writing and, if there is, we -// call only the ToArray methods to avoid doing bound checks for each -// individual value. -// i.e., in the example above: -// -// CodedOutputStream coded_output = new CodedOutputStream(raw_output); -// int magic_number = 1234; -// char text[] = "Hello world!"; -// -// int coded_size = sizeof(magic_number) + -// CodedOutputStream::Varint32Size(strlen(text)) + -// strlen(text); -// -// uint8* buffer = -// coded_output->GetDirectBufferForNBytesAndAdvance(coded_size); -// if (buffer != NULL) { -// // The output stream has enough space in the buffer: write directly to -// // the array. -// buffer = CodedOutputStream::WriteLittleEndian32ToArray(magic_number, -// buffer); -// buffer = CodedOutputStream::WriteVarint32ToArray(strlen(text), buffer); -// buffer = CodedOutputStream::WriteRawToArray(text, strlen(text), buffer); -// } else { -// // Make bound-checked writes, which will ask the underlying stream for -// // more space as needed. -// coded_output->WriteLittleEndian32(magic_number); -// coded_output->WriteVarint32(strlen(text)); -// coded_output->WriteRaw(text, strlen(text)); -// } -// -// delete coded_output; -class LIBPROTOBUF_EXPORT CodedOutputStream { - public: - // Create an CodedOutputStream that writes to the given ZeroCopyOutputStream. - explicit CodedOutputStream(ZeroCopyOutputStream* output); - - // Destroy the CodedOutputStream and position the underlying - // ZeroCopyOutputStream immediately after the last byte written. - ~CodedOutputStream(); - - // Skips a number of bytes, leaving the bytes unmodified in the underlying - // buffer. Returns false if an underlying write error occurs. This is - // mainly useful with GetDirectBufferPointer(). - bool Skip(int count); - - // Sets *data to point directly at the unwritten part of the - // CodedOutputStream's underlying buffer, and *size to the size of that - // buffer, but does not advance the stream's current position. This will - // always either produce a non-empty buffer or return false. If the caller - // writes any data to this buffer, it should then call Skip() to skip over - // the consumed bytes. This may be useful for implementing external fast - // serialization routines for types of data not covered by the - // CodedOutputStream interface. - bool GetDirectBufferPointer(void** data, int* size); - - // If there are at least "size" bytes available in the current buffer, - // returns a pointer directly into the buffer and advances over these bytes. - // The caller may then write directly into this buffer (e.g. using the - // *ToArray static methods) rather than go through CodedOutputStream. If - // there are not enough bytes available, returns NULL. The return pointer is - // invalidated as soon as any other non-const method of CodedOutputStream - // is called. - inline uint8* GetDirectBufferForNBytesAndAdvance(int size); - - // Write raw bytes, copying them from the given buffer. - void WriteRaw(const void* buffer, int size); - // Like WriteRaw() but writing directly to the target array. - // This is _not_ inlined, as the compiler often optimizes memcpy into inline - // copy loops. Since this gets called by every field with string or bytes - // type, inlining may lead to a significant amount of code bloat, with only a - // minor performance gain. - static uint8* WriteRawToArray(const void* buffer, int size, uint8* target); - - // Equivalent to WriteRaw(str.data(), str.size()). - void WriteString(const string& str); - // Like WriteString() but writing directly to the target array. - static uint8* WriteStringToArray(const string& str, uint8* target); - - - // Write a 32-bit little-endian integer. - void WriteLittleEndian32(uint32 value); - // Like WriteLittleEndian32() but writing directly to the target array. - static uint8* WriteLittleEndian32ToArray(uint32 value, uint8* target); - // Write a 64-bit little-endian integer. - void WriteLittleEndian64(uint64 value); - // Like WriteLittleEndian64() but writing directly to the target array. - static uint8* WriteLittleEndian64ToArray(uint64 value, uint8* target); - - // Write an unsigned integer with Varint encoding. Writing a 32-bit value - // is equivalent to casting it to uint64 and writing it as a 64-bit value, - // but may be more efficient. - void WriteVarint32(uint32 value); - // Like WriteVarint32() but writing directly to the target array. - static uint8* WriteVarint32ToArray(uint32 value, uint8* target); - // Write an unsigned integer with Varint encoding. - void WriteVarint64(uint64 value); - // Like WriteVarint64() but writing directly to the target array. - static uint8* WriteVarint64ToArray(uint64 value, uint8* target); - - // Equivalent to WriteVarint32() except when the value is negative, - // in which case it must be sign-extended to a full 10 bytes. - void WriteVarint32SignExtended(int32 value); - // Like WriteVarint32SignExtended() but writing directly to the target array. - static uint8* WriteVarint32SignExtendedToArray(int32 value, uint8* target); - - // This is identical to WriteVarint32(), but optimized for writing tags. - // In particular, if the input is a compile-time constant, this method - // compiles down to a couple instructions. - // Always inline because otherwise the aformentioned optimization can't work, - // but GCC by default doesn't want to inline this. - void WriteTag(uint32 value); - // Like WriteTag() but writing directly to the target array. - static uint8* WriteTagToArray( - uint32 value, uint8* target) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - // Returns the number of bytes needed to encode the given value as a varint. - static int VarintSize32(uint32 value); - // Returns the number of bytes needed to encode the given value as a varint. - static int VarintSize64(uint64 value); - - // If negative, 10 bytes. Otheriwse, same as VarintSize32(). - static int VarintSize32SignExtended(int32 value); - - // Returns the total number of bytes written since this object was created. - inline int ByteCount() const; - - // Returns true if there was an underlying I/O error since this object was - // created. - bool HadError() const { return had_error_; } - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CodedOutputStream); - - ZeroCopyOutputStream* output_; - uint8* buffer_; - int buffer_size_; - int total_bytes_; // Sum of sizes of all buffers seen so far. - bool had_error_; // Whether an error occurred during output. - - // Advance the buffer by a given number of bytes. - void Advance(int amount); - - // Called when the buffer runs out to request more data. Implies an - // Advance(buffer_size_). - bool Refresh(); - - static uint8* WriteVarint32FallbackToArray(uint32 value, uint8* target); - - // Always-inlined versions of WriteVarint* functions so that code can be - // reused, while still controlling size. For instance, WriteVarint32ToArray() - // should not directly call this: since it is inlined itself, doing so - // would greatly increase the size of generated code. Instead, it should call - // WriteVarint32FallbackToArray. Meanwhile, WriteVarint32() is already - // out-of-line, so it should just invoke this directly to avoid any extra - // function call overhead. - static uint8* WriteVarint32FallbackToArrayInline( - uint32 value, uint8* target) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - static uint8* WriteVarint64ToArrayInline( - uint64 value, uint8* target) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - static int VarintSize32Fallback(uint32 value); -}; - -// inline methods ==================================================== -// The vast majority of varints are only one byte. These inline -// methods optimize for that case. - -inline bool CodedInputStream::ReadVarint32(uint32* value) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) { - *value = *buffer_; - Advance(1); - return true; - } else { - return ReadVarint32Fallback(value); - } -} - -inline bool CodedInputStream::ReadVarint64(uint64* value) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && *buffer_ < 0x80) { - *value = *buffer_; - Advance(1); - return true; - } else { - return ReadVarint64Fallback(value); - } -} - -// static -inline const uint8* CodedInputStream::ReadLittleEndian32FromArray( - const uint8* buffer, - uint32* value) { -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) && \ - defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN - memcpy(value, buffer, sizeof(*value)); - return buffer + sizeof(*value); -#else - *value = (static_cast(buffer[0]) ) | - (static_cast(buffer[1]) << 8) | - (static_cast(buffer[2]) << 16) | - (static_cast(buffer[3]) << 24); - return buffer + sizeof(*value); -#endif -} -// static -inline const uint8* CodedInputStream::ReadLittleEndian64FromArray( - const uint8* buffer, - uint64* value) { -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) && \ - defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN - memcpy(value, buffer, sizeof(*value)); - return buffer + sizeof(*value); -#else - uint32 part0 = (static_cast(buffer[0]) ) | - (static_cast(buffer[1]) << 8) | - (static_cast(buffer[2]) << 16) | - (static_cast(buffer[3]) << 24); - uint32 part1 = (static_cast(buffer[4]) ) | - (static_cast(buffer[5]) << 8) | - (static_cast(buffer[6]) << 16) | - (static_cast(buffer[7]) << 24); - *value = static_cast(part0) | - (static_cast(part1) << 32); - return buffer + sizeof(*value); -#endif -} - -inline bool CodedInputStream::ReadLittleEndian32(uint32* value) { -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) && \ - defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN - if (GOOGLE_PREDICT_TRUE(BufferSize() >= sizeof(*value))) { - memcpy(value, buffer_, sizeof(*value)); - Advance(sizeof(*value)); - return true; - } else { - return ReadLittleEndian32Fallback(value); - } -#else - return ReadLittleEndian32Fallback(value); -#endif -} - -inline bool CodedInputStream::ReadLittleEndian64(uint64* value) { -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) && \ - defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN - if (GOOGLE_PREDICT_TRUE(BufferSize() >= sizeof(*value))) { - memcpy(value, buffer_, sizeof(*value)); - Advance(sizeof(*value)); - return true; - } else { - return ReadLittleEndian64Fallback(value); - } -#else - return ReadLittleEndian64Fallback(value); -#endif -} - -inline uint32 CodedInputStream::ReadTag() { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] < 0x80) { - last_tag_ = buffer_[0]; - Advance(1); - return last_tag_; - } else { - last_tag_ = ReadTagFallback(); - return last_tag_; - } -} - -inline bool CodedInputStream::LastTagWas(uint32 expected) { - return last_tag_ == expected; -} - -inline bool CodedInputStream::ConsumedEntireMessage() { - return legitimate_message_end_; -} - -inline bool CodedInputStream::ExpectTag(uint32 expected) { - if (expected < (1 << 7)) { - if (GOOGLE_PREDICT_TRUE(buffer_ < buffer_end_) && buffer_[0] == expected) { - Advance(1); - return true; - } else { - return false; - } - } else if (expected < (1 << 14)) { - if (GOOGLE_PREDICT_TRUE(BufferSize() >= 2) && - buffer_[0] == static_cast(expected | 0x80) && - buffer_[1] == static_cast(expected >> 7)) { - Advance(2); - return true; - } else { - return false; - } - } else { - // Don't bother optimizing for larger values. - return false; - } -} - -inline const uint8* CodedInputStream::ExpectTagFromArray( - const uint8* buffer, uint32 expected) { - if (expected < (1 << 7)) { - if (buffer[0] == expected) { - return buffer + 1; - } - } else if (expected < (1 << 14)) { - if (buffer[0] == static_cast(expected | 0x80) && - buffer[1] == static_cast(expected >> 7)) { - return buffer + 2; - } - } - return NULL; -} - -inline void CodedInputStream::GetDirectBufferPointerInline(const void** data, - int* size) { - *data = buffer_; - *size = buffer_end_ - buffer_; -} - -inline bool CodedInputStream::ExpectAtEnd() { - // If we are at a limit we know no more bytes can be read. Otherwise, it's - // hard to say without calling Refresh(), and we'd rather not do that. - - if (buffer_ == buffer_end_ && buffer_size_after_limit_ != 0) { - last_tag_ = 0; // Pretend we called ReadTag()... - legitimate_message_end_ = true; // ... and it hit EOF. - return true; - } else { - return false; - } -} - -inline uint8* CodedOutputStream::GetDirectBufferForNBytesAndAdvance(int size) { - if (buffer_size_ < size) { - return NULL; - } else { - uint8* result = buffer_; - Advance(size); - return result; - } -} - -inline uint8* CodedOutputStream::WriteVarint32ToArray(uint32 value, - uint8* target) { - if (value < 0x80) { - *target = value; - return target + 1; - } else { - return WriteVarint32FallbackToArray(value, target); - } -} - -inline void CodedOutputStream::WriteVarint32SignExtended(int32 value) { - if (value < 0) { - WriteVarint64(static_cast(value)); - } else { - WriteVarint32(static_cast(value)); - } -} - -inline uint8* CodedOutputStream::WriteVarint32SignExtendedToArray( - int32 value, uint8* target) { - if (value < 0) { - return WriteVarint64ToArray(static_cast(value), target); - } else { - return WriteVarint32ToArray(static_cast(value), target); - } -} - -inline uint8* CodedOutputStream::WriteLittleEndian32ToArray(uint32 value, - uint8* target) { -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) && \ - defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN - memcpy(target, &value, sizeof(value)); -#else - target[0] = static_cast(value); - target[1] = static_cast(value >> 8); - target[2] = static_cast(value >> 16); - target[3] = static_cast(value >> 24); -#endif - return target + sizeof(value); -} - -inline uint8* CodedOutputStream::WriteLittleEndian64ToArray(uint64 value, - uint8* target) { -#if !defined(PROTOBUF_DISABLE_LITTLE_ENDIAN_OPT_FOR_TEST) && \ - defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN - memcpy(target, &value, sizeof(value)); -#else - uint32 part0 = static_cast(value); - uint32 part1 = static_cast(value >> 32); - - target[0] = static_cast(part0); - target[1] = static_cast(part0 >> 8); - target[2] = static_cast(part0 >> 16); - target[3] = static_cast(part0 >> 24); - target[4] = static_cast(part1); - target[5] = static_cast(part1 >> 8); - target[6] = static_cast(part1 >> 16); - target[7] = static_cast(part1 >> 24); -#endif - return target + sizeof(value); -} - -inline void CodedOutputStream::WriteTag(uint32 value) { - WriteVarint32(value); -} - -inline uint8* CodedOutputStream::WriteTagToArray( - uint32 value, uint8* target) { - if (value < (1 << 7)) { - target[0] = value; - return target + 1; - } else if (value < (1 << 14)) { - target[0] = static_cast(value | 0x80); - target[1] = static_cast(value >> 7); - return target + 2; - } else { - return WriteVarint32FallbackToArray(value, target); - } -} - -inline int CodedOutputStream::VarintSize32(uint32 value) { - if (value < (1 << 7)) { - return 1; - } else { - return VarintSize32Fallback(value); - } -} - -inline int CodedOutputStream::VarintSize32SignExtended(int32 value) { - if (value < 0) { - return 10; // TODO(kenton): Make this a symbolic constant. - } else { - return VarintSize32(static_cast(value)); - } -} - -inline void CodedOutputStream::WriteString(const string& str) { - WriteRaw(str.data(), str.size()); -} - -inline uint8* CodedOutputStream::WriteStringToArray( - const string& str, uint8* target) { - return WriteRawToArray(str.data(), str.size(), target); -} - -inline int CodedOutputStream::ByteCount() const { - return total_bytes_ - buffer_size_; -} - -inline void CodedInputStream::Advance(int amount) { - buffer_ += amount; -} - -inline void CodedOutputStream::Advance(int amount) { - buffer_ += amount; - buffer_size_ -= amount; -} - -inline void CodedInputStream::SetRecursionLimit(int limit) { - recursion_limit_ = limit; -} - -inline bool CodedInputStream::IncrementRecursionDepth() { - ++recursion_depth_; - return recursion_depth_ <= recursion_limit_; -} - -inline void CodedInputStream::DecrementRecursionDepth() { - if (recursion_depth_ > 0) --recursion_depth_; -} - -inline void CodedInputStream::SetExtensionRegistry(DescriptorPool* pool, - MessageFactory* factory) { - extension_pool_ = pool; - extension_factory_ = factory; -} - -inline const DescriptorPool* CodedInputStream::GetExtensionPool() { - return extension_pool_; -} - -inline MessageFactory* CodedInputStream::GetExtensionFactory() { - return extension_factory_; -} - -inline int CodedInputStream::BufferSize() const { - return buffer_end_ - buffer_; -} - -inline CodedInputStream::CodedInputStream(ZeroCopyInputStream* input) - : input_(input), - buffer_(NULL), - buffer_end_(NULL), - total_bytes_read_(0), - overflow_bytes_(0), - last_tag_(0), - legitimate_message_end_(false), - aliasing_enabled_(false), - current_limit_(INT_MAX), - buffer_size_after_limit_(0), - total_bytes_limit_(kDefaultTotalBytesLimit), - total_bytes_warning_threshold_(kDefaultTotalBytesWarningThreshold), - recursion_depth_(0), - recursion_limit_(kDefaultRecursionLimit), - extension_pool_(NULL), - extension_factory_(NULL) { - // Eagerly Refresh() so buffer space is immediately available. - Refresh(); -} - -inline CodedInputStream::CodedInputStream(const uint8* buffer, int size) - : input_(NULL), - buffer_(buffer), - buffer_end_(buffer + size), - total_bytes_read_(size), - overflow_bytes_(0), - last_tag_(0), - legitimate_message_end_(false), - aliasing_enabled_(false), - current_limit_(size), - buffer_size_after_limit_(0), - total_bytes_limit_(kDefaultTotalBytesLimit), - total_bytes_warning_threshold_(kDefaultTotalBytesWarningThreshold), - recursion_depth_(0), - recursion_limit_(kDefaultRecursionLimit), - extension_pool_(NULL), - extension_factory_(NULL) { - // Note that setting current_limit_ == size is important to prevent some - // code paths from trying to access input_ and segfaulting. -} - -inline CodedInputStream::~CodedInputStream() { - if (input_ != NULL) { - BackUpInputToCurrentPosition(); - } -} - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_CODED_STREAM_H__ diff --git a/Resources/NetHook/google/protobuf/io/coded_stream_inl.h b/Resources/NetHook/google/protobuf/io/coded_stream_inl.h deleted file mode 100644 index e9799d47..00000000 --- a/Resources/NetHook/google/protobuf/io/coded_stream_inl.h +++ /dev/null @@ -1,64 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: jasonh@google.com (Jason Hsueh) -// -// Implements methods of coded_stream.h that need to be inlined for performance -// reasons, but should not be defined in a public header. - -#ifndef GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__ -#define GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { - -inline bool CodedInputStream::InternalReadStringInline(string* buffer, - int size) { - if (size < 0) return false; // security: size is often user-supplied - - if (BufferSize() >= size) { - STLStringResizeUninitialized(buffer, size); - memcpy(string_as_array(buffer), buffer_, size); - Advance(size); - return true; - } - - return ReadStringFallback(buffer, size); -} - -} // namespace io -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_CODED_STREAM_INL_H__ diff --git a/Resources/NetHook/google/protobuf/io/coded_stream_unittest.cc b/Resources/NetHook/google/protobuf/io/coded_stream_unittest.cc deleted file mode 100644 index 7d298332..00000000 --- a/Resources/NetHook/google/protobuf/io/coded_stream_unittest.cc +++ /dev/null @@ -1,1103 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains tests and benchmarks. - -#include - -#include - -#include - -#include -#include -#include -#include -#include - - -// This declares an unsigned long long integer literal in a portable way. -// (The original macro is way too big and ruins my formatting.) -#undef ULL -#define ULL(x) GOOGLE_ULONGLONG(x) - -namespace google { -namespace protobuf { -namespace io { -namespace { - -// =================================================================== -// Data-Driven Test Infrastructure - -// TEST_1D and TEST_2D are macros I'd eventually like to see added to -// gTest. These macros can be used to declare tests which should be -// run multiple times, once for each item in some input array. TEST_1D -// tests all cases in a single input array. TEST_2D tests all -// combinations of cases from two arrays. The arrays must be statically -// defined such that the GOOGLE_ARRAYSIZE() macro works on them. Example: -// -// int kCases[] = {1, 2, 3, 4} -// TEST_1D(MyFixture, MyTest, kCases) { -// EXPECT_GT(kCases_case, 0); -// } -// -// This test iterates through the numbers 1, 2, 3, and 4 and tests that -// they are all grater than zero. In case of failure, the exact case -// which failed will be printed. The case type must be printable using -// ostream::operator<<. - -// TODO(kenton): gTest now supports "parameterized tests" which would be -// a better way to accomplish this. Rewrite when time permits. - -#define TEST_1D(FIXTURE, NAME, CASES) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType& CASES##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES); i++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES " case #" << i << ": " << CASES[i]); \ - DoSingleCase(CASES[i]); \ - } \ - } \ - \ - template \ - void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType& CASES##_case) - -#define TEST_2D(FIXTURE, NAME, CASES1, CASES2) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType1& CASES1##_case, \ - const CaseType2& CASES2##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES1); i++) { \ - for (int j = 0; j < GOOGLE_ARRAYSIZE(CASES2); j++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES1 " case #" << i << ": " << CASES1[i] << ", " \ - << #CASES2 " case #" << j << ": " << CASES2[j]); \ - DoSingleCase(CASES1[i], CASES2[j]); \ - } \ - } \ - } \ - \ - template \ - void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType1& CASES1##_case, \ - const CaseType2& CASES2##_case) - -// =================================================================== - -class CodedStreamTest : public testing::Test { - protected: - static const int kBufferSize = 1024 * 64; - static uint8 buffer_[kBufferSize]; -}; - -uint8 CodedStreamTest::buffer_[CodedStreamTest::kBufferSize]; - -// We test each operation over a variety of block sizes to insure that -// we test cases where reads or writes cross buffer boundaries, cases -// where they don't, and cases where there is so much buffer left that -// we can use special optimized paths that don't worry about bounds -// checks. -const int kBlockSizes[] = {1, 2, 3, 5, 7, 13, 32, 1024}; - -// ------------------------------------------------------------------- -// Varint tests. - -struct VarintCase { - uint8 bytes[10]; // Encoded bytes. - int size; // Encoded size, in bytes. - uint64 value; // Parsed value. -}; - -inline std::ostream& operator<<(std::ostream& os, const VarintCase& c) { - return os << c.value; -} - -VarintCase kVarintCases[] = { - // 32-bit values - {{0x00} , 1, 0}, - {{0x01} , 1, 1}, - {{0x7f} , 1, 127}, - {{0xa2, 0x74}, 2, (0x22 << 0) | (0x74 << 7)}, // 14882 - {{0xbe, 0xf7, 0x92, 0x84, 0x0b}, 5, // 2961488830 - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (ULL(0x0b) << 28)}, - - // 64-bit - {{0xbe, 0xf7, 0x92, 0x84, 0x1b}, 5, // 7256456126 - (0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | - (ULL(0x1b) << 28)}, - {{0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49}, 8, // 41256202580718336 - (0x00 << 0) | (0x66 << 7) | (0x6b << 14) | (0x1c << 21) | - (ULL(0x43) << 28) | (ULL(0x49) << 35) | (ULL(0x24) << 42) | - (ULL(0x49) << 49)}, - // 11964378330978735131 - {{0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01}, 10, - (0x1b << 0) | (0x28 << 7) | (0x79 << 14) | (0x42 << 21) | - (ULL(0x3b) << 28) | (ULL(0x56) << 35) | (ULL(0x00) << 42) | - (ULL(0x05) << 49) | (ULL(0x26) << 56) | (ULL(0x01) << 63)}, -}; - -TEST_2D(CodedStreamTest, ReadVarint32, kVarintCases, kBlockSizes) { - memcpy(buffer_, kVarintCases_case.bytes, kVarintCases_case.size); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - uint32 value; - EXPECT_TRUE(coded_input.ReadVarint32(&value)); - EXPECT_EQ(static_cast(kVarintCases_case.value), value); - } - - EXPECT_EQ(kVarintCases_case.size, input.ByteCount()); -} - -TEST_2D(CodedStreamTest, ReadTag, kVarintCases, kBlockSizes) { - memcpy(buffer_, kVarintCases_case.bytes, kVarintCases_case.size); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - uint32 expected_value = static_cast(kVarintCases_case.value); - EXPECT_EQ(expected_value, coded_input.ReadTag()); - - EXPECT_TRUE(coded_input.LastTagWas(expected_value)); - EXPECT_FALSE(coded_input.LastTagWas(expected_value + 1)); - } - - EXPECT_EQ(kVarintCases_case.size, input.ByteCount()); -} - -TEST_1D(CodedStreamTest, ExpectTag, kVarintCases) { - // Leave one byte at the beginning of the buffer so we can read it - // to force the first buffer to be loaded. - buffer_[0] = '\0'; - memcpy(buffer_ + 1, kVarintCases_case.bytes, kVarintCases_case.size); - ArrayInputStream input(buffer_, sizeof(buffer_)); - - { - CodedInputStream coded_input(&input); - - // Read one byte to force coded_input.Refill() to be called. Otherwise, - // ExpectTag() will return a false negative. - uint8 dummy; - coded_input.ReadRaw(&dummy, 1); - EXPECT_EQ((uint)'\0', (uint)dummy); - - uint32 expected_value = static_cast(kVarintCases_case.value); - - // ExpectTag() produces false negatives for large values. - if (kVarintCases_case.size <= 2) { - EXPECT_FALSE(coded_input.ExpectTag(expected_value + 1)); - EXPECT_TRUE(coded_input.ExpectTag(expected_value)); - } else { - EXPECT_FALSE(coded_input.ExpectTag(expected_value)); - } - } - - if (kVarintCases_case.size <= 2) { - EXPECT_EQ(kVarintCases_case.size + 1, input.ByteCount()); - } else { - EXPECT_EQ(1, input.ByteCount()); - } -} - -TEST_1D(CodedStreamTest, ExpectTagFromArray, kVarintCases) { - memcpy(buffer_, kVarintCases_case.bytes, kVarintCases_case.size); - - const uint32 expected_value = static_cast(kVarintCases_case.value); - - // If the expectation succeeds, it should return a pointer past the tag. - if (kVarintCases_case.size <= 2) { - EXPECT_TRUE(NULL == - CodedInputStream::ExpectTagFromArray(buffer_, - expected_value + 1)); - EXPECT_TRUE(buffer_ + kVarintCases_case.size == - CodedInputStream::ExpectTagFromArray(buffer_, expected_value)); - } else { - EXPECT_TRUE(NULL == - CodedInputStream::ExpectTagFromArray(buffer_, expected_value)); - } -} - -TEST_2D(CodedStreamTest, ReadVarint64, kVarintCases, kBlockSizes) { - memcpy(buffer_, kVarintCases_case.bytes, kVarintCases_case.size); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - uint64 value; - EXPECT_TRUE(coded_input.ReadVarint64(&value)); - EXPECT_EQ(kVarintCases_case.value, value); - } - - EXPECT_EQ(kVarintCases_case.size, input.ByteCount()); -} - -TEST_2D(CodedStreamTest, WriteVarint32, kVarintCases, kBlockSizes) { - if (kVarintCases_case.value > ULL(0x00000000FFFFFFFF)) { - // Skip this test for the 64-bit values. - return; - } - - ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedOutputStream coded_output(&output); - - coded_output.WriteVarint32(static_cast(kVarintCases_case.value)); - EXPECT_FALSE(coded_output.HadError()); - - EXPECT_EQ(kVarintCases_case.size, coded_output.ByteCount()); - } - - EXPECT_EQ(kVarintCases_case.size, output.ByteCount()); - EXPECT_EQ(0, - memcmp(buffer_, kVarintCases_case.bytes, kVarintCases_case.size)); -} - -TEST_2D(CodedStreamTest, WriteVarint64, kVarintCases, kBlockSizes) { - ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedOutputStream coded_output(&output); - - coded_output.WriteVarint64(kVarintCases_case.value); - EXPECT_FALSE(coded_output.HadError()); - - EXPECT_EQ(kVarintCases_case.size, coded_output.ByteCount()); - } - - EXPECT_EQ(kVarintCases_case.size, output.ByteCount()); - EXPECT_EQ(0, - memcmp(buffer_, kVarintCases_case.bytes, kVarintCases_case.size)); -} - -// This test causes gcc 3.3.5 (and earlier?) to give the cryptic error: -// "sorry, unimplemented: `method_call_expr' not supported by dump_expr" -#if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) - -int32 kSignExtendedVarintCases[] = { - 0, 1, -1, 1237894, -37895138 -}; - -TEST_2D(CodedStreamTest, WriteVarint32SignExtended, - kSignExtendedVarintCases, kBlockSizes) { - ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedOutputStream coded_output(&output); - - coded_output.WriteVarint32SignExtended(kSignExtendedVarintCases_case); - EXPECT_FALSE(coded_output.HadError()); - - if (kSignExtendedVarintCases_case < 0) { - EXPECT_EQ(10, coded_output.ByteCount()); - } else { - EXPECT_LE(coded_output.ByteCount(), 5); - } - } - - if (kSignExtendedVarintCases_case < 0) { - EXPECT_EQ(10, output.ByteCount()); - } else { - EXPECT_LE(output.ByteCount(), 5); - } - - // Read value back in as a varint64 and insure it matches. - ArrayInputStream input(buffer_, sizeof(buffer_)); - - { - CodedInputStream coded_input(&input); - - uint64 value; - EXPECT_TRUE(coded_input.ReadVarint64(&value)); - - EXPECT_EQ(kSignExtendedVarintCases_case, static_cast(value)); - } - - EXPECT_EQ(output.ByteCount(), input.ByteCount()); -} - -#endif - - -// ------------------------------------------------------------------- -// Varint failure test. - -struct VarintErrorCase { - uint8 bytes[12]; - int size; - bool can_parse; -}; - -inline std::ostream& operator<<(std::ostream& os, const VarintErrorCase& c) { - return os << "size " << c.size; -} - -const VarintErrorCase kVarintErrorCases[] = { - // Control case. (Insures that there isn't something else wrong that - // makes parsing always fail.) - {{0x00}, 1, true}, - - // No input data. - {{}, 0, false}, - - // Input ends unexpectedly. - {{0xf0, 0xab}, 2, false}, - - // Input ends unexpectedly after 32 bits. - {{0xf0, 0xab, 0xc9, 0x9a, 0xf8, 0xb2}, 6, false}, - - // Longer than 10 bytes. - {{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}, - 11, false}, -}; - -TEST_2D(CodedStreamTest, ReadVarint32Error, kVarintErrorCases, kBlockSizes) { - memcpy(buffer_, kVarintErrorCases_case.bytes, kVarintErrorCases_case.size); - ArrayInputStream input(buffer_, kVarintErrorCases_case.size, - kBlockSizes_case); - CodedInputStream coded_input(&input); - - uint32 value; - EXPECT_EQ(kVarintErrorCases_case.can_parse, coded_input.ReadVarint32(&value)); -} - -TEST_2D(CodedStreamTest, ReadVarint64Error, kVarintErrorCases, kBlockSizes) { - memcpy(buffer_, kVarintErrorCases_case.bytes, kVarintErrorCases_case.size); - ArrayInputStream input(buffer_, kVarintErrorCases_case.size, - kBlockSizes_case); - CodedInputStream coded_input(&input); - - uint64 value; - EXPECT_EQ(kVarintErrorCases_case.can_parse, coded_input.ReadVarint64(&value)); -} - -// ------------------------------------------------------------------- -// VarintSize - -struct VarintSizeCase { - uint64 value; - int size; -}; - -inline std::ostream& operator<<(std::ostream& os, const VarintSizeCase& c) { - return os << c.value; -} - -VarintSizeCase kVarintSizeCases[] = { - {0u, 1}, - {1u, 1}, - {127u, 1}, - {128u, 2}, - {758923u, 3}, - {4000000000u, 5}, - {ULL(41256202580718336), 8}, - {ULL(11964378330978735131), 10}, -}; - -TEST_1D(CodedStreamTest, VarintSize32, kVarintSizeCases) { - if (kVarintSizeCases_case.value > 0xffffffffu) { - // Skip 64-bit values. - return; - } - - EXPECT_EQ(kVarintSizeCases_case.size, - CodedOutputStream::VarintSize32( - static_cast(kVarintSizeCases_case.value))); -} - -TEST_1D(CodedStreamTest, VarintSize64, kVarintSizeCases) { - EXPECT_EQ(kVarintSizeCases_case.size, - CodedOutputStream::VarintSize64(kVarintSizeCases_case.value)); -} - -// ------------------------------------------------------------------- -// Fixed-size int tests - -struct Fixed32Case { - uint8 bytes[sizeof(uint32)]; // Encoded bytes. - uint32 value; // Parsed value. -}; - -struct Fixed64Case { - uint8 bytes[sizeof(uint64)]; // Encoded bytes. - uint64 value; // Parsed value. -}; - -inline std::ostream& operator<<(std::ostream& os, const Fixed32Case& c) { - return os << "0x" << hex << c.value << dec; -} - -inline std::ostream& operator<<(std::ostream& os, const Fixed64Case& c) { - return os << "0x" << hex << c.value << dec; -} - -Fixed32Case kFixed32Cases[] = { - {{0xef, 0xcd, 0xab, 0x90}, 0x90abcdefu}, - {{0x12, 0x34, 0x56, 0x78}, 0x78563412u}, -}; - -Fixed64Case kFixed64Cases[] = { - {{0xef, 0xcd, 0xab, 0x90, 0x12, 0x34, 0x56, 0x78}, ULL(0x7856341290abcdef)}, - {{0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88}, ULL(0x8877665544332211)}, -}; - -TEST_2D(CodedStreamTest, ReadLittleEndian32, kFixed32Cases, kBlockSizes) { - memcpy(buffer_, kFixed32Cases_case.bytes, sizeof(kFixed32Cases_case.bytes)); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - uint32 value; - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(kFixed32Cases_case.value, value); - } - - EXPECT_EQ(sizeof(uint32), input.ByteCount()); -} - -TEST_2D(CodedStreamTest, ReadLittleEndian64, kFixed64Cases, kBlockSizes) { - memcpy(buffer_, kFixed64Cases_case.bytes, sizeof(kFixed64Cases_case.bytes)); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - uint64 value; - EXPECT_TRUE(coded_input.ReadLittleEndian64(&value)); - EXPECT_EQ(kFixed64Cases_case.value, value); - } - - EXPECT_EQ(sizeof(uint64), input.ByteCount()); -} - -TEST_2D(CodedStreamTest, WriteLittleEndian32, kFixed32Cases, kBlockSizes) { - ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedOutputStream coded_output(&output); - - coded_output.WriteLittleEndian32(kFixed32Cases_case.value); - EXPECT_FALSE(coded_output.HadError()); - - EXPECT_EQ(sizeof(uint32), coded_output.ByteCount()); - } - - EXPECT_EQ(sizeof(uint32), output.ByteCount()); - EXPECT_EQ(0, memcmp(buffer_, kFixed32Cases_case.bytes, sizeof(uint32))); -} - -TEST_2D(CodedStreamTest, WriteLittleEndian64, kFixed64Cases, kBlockSizes) { - ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedOutputStream coded_output(&output); - - coded_output.WriteLittleEndian64(kFixed64Cases_case.value); - EXPECT_FALSE(coded_output.HadError()); - - EXPECT_EQ(sizeof(uint64), coded_output.ByteCount()); - } - - EXPECT_EQ(sizeof(uint64), output.ByteCount()); - EXPECT_EQ(0, memcmp(buffer_, kFixed64Cases_case.bytes, sizeof(uint64))); -} - -// Tests using the static methods to read fixed-size values from raw arrays. - -TEST_1D(CodedStreamTest, ReadLittleEndian32FromArray, kFixed32Cases) { - memcpy(buffer_, kFixed32Cases_case.bytes, sizeof(kFixed32Cases_case.bytes)); - - uint32 value; - const uint8* end = CodedInputStream::ReadLittleEndian32FromArray( - buffer_, &value); - EXPECT_EQ(kFixed32Cases_case.value, value); - EXPECT_TRUE(end == buffer_ + sizeof(value)); -} - -TEST_1D(CodedStreamTest, ReadLittleEndian64FromArray, kFixed64Cases) { - memcpy(buffer_, kFixed64Cases_case.bytes, sizeof(kFixed64Cases_case.bytes)); - - uint64 value; - const uint8* end = CodedInputStream::ReadLittleEndian64FromArray( - buffer_, &value); - EXPECT_EQ(kFixed64Cases_case.value, value); - EXPECT_TRUE(end == buffer_ + sizeof(value)); -} - -// ------------------------------------------------------------------- -// Raw reads and writes - -const char kRawBytes[] = "Some bytes which will be written and read raw."; - -TEST_1D(CodedStreamTest, ReadRaw, kBlockSizes) { - memcpy(buffer_, kRawBytes, sizeof(kRawBytes)); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - char read_buffer[sizeof(kRawBytes)]; - - { - CodedInputStream coded_input(&input); - - EXPECT_TRUE(coded_input.ReadRaw(read_buffer, sizeof(kRawBytes))); - EXPECT_EQ(0, memcmp(kRawBytes, read_buffer, sizeof(kRawBytes))); - } - - EXPECT_EQ(sizeof(kRawBytes), input.ByteCount()); -} - -TEST_1D(CodedStreamTest, WriteRaw, kBlockSizes) { - ArrayOutputStream output(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedOutputStream coded_output(&output); - - coded_output.WriteRaw(kRawBytes, sizeof(kRawBytes)); - EXPECT_FALSE(coded_output.HadError()); - - EXPECT_EQ(sizeof(kRawBytes), coded_output.ByteCount()); - } - - EXPECT_EQ(sizeof(kRawBytes), output.ByteCount()); - EXPECT_EQ(0, memcmp(buffer_, kRawBytes, sizeof(kRawBytes))); -} - -TEST_1D(CodedStreamTest, ReadString, kBlockSizes) { - memcpy(buffer_, kRawBytes, sizeof(kRawBytes)); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - string str; - EXPECT_TRUE(coded_input.ReadString(&str, strlen(kRawBytes))); - EXPECT_EQ(kRawBytes, str); - } - - EXPECT_EQ(strlen(kRawBytes), input.ByteCount()); -} - -// Check to make sure ReadString doesn't crash on impossibly large strings. -TEST_1D(CodedStreamTest, ReadStringImpossiblyLarge, kBlockSizes) { - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - string str; - // Try to read a gigabyte. - EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); - } -} - -TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnStack) { - // Same test as above, except directly use a buffer. This used to cause - // crashes while the above did not. - uint8 buffer[8]; - CodedInputStream coded_input(buffer, 8); - string str; - EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); -} - -TEST_F(CodedStreamTest, ReadStringImpossiblyLargeFromStringOnHeap) { - scoped_array buffer(new uint8[8]); - CodedInputStream coded_input(buffer.get(), 8); - string str; - EXPECT_FALSE(coded_input.ReadString(&str, 1 << 30)); -} - - -// ------------------------------------------------------------------- -// Skip - -const char kSkipTestBytes[] = - ""; -const char kSkipOutputTestBytes[] = - "---------------------------------"; - -TEST_1D(CodedStreamTest, SkipInput, kBlockSizes) { - memcpy(buffer_, kSkipTestBytes, sizeof(kSkipTestBytes)); - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - string str; - EXPECT_TRUE(coded_input.ReadString(&str, strlen(""))); - EXPECT_EQ("", str); - EXPECT_TRUE(coded_input.Skip(strlen(""))); - EXPECT_TRUE(coded_input.ReadString(&str, strlen(""))); - EXPECT_EQ("", str); - } - - EXPECT_EQ(strlen(kSkipTestBytes), input.ByteCount()); -} - -// ------------------------------------------------------------------- -// GetDirectBufferPointer - -TEST_F(CodedStreamTest, GetDirectBufferPointerInput) { - ArrayInputStream input(buffer_, sizeof(buffer_), 8); - CodedInputStream coded_input(&input); - - const void* ptr; - int size; - - EXPECT_TRUE(coded_input.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_, ptr); - EXPECT_EQ(8, size); - - // Peeking again should return the same pointer. - EXPECT_TRUE(coded_input.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_, ptr); - EXPECT_EQ(8, size); - - // Skip forward in the same buffer then peek again. - EXPECT_TRUE(coded_input.Skip(3)); - EXPECT_TRUE(coded_input.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_ + 3, ptr); - EXPECT_EQ(5, size); - - // Skip to end of buffer and peek -- should get next buffer. - EXPECT_TRUE(coded_input.Skip(5)); - EXPECT_TRUE(coded_input.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_ + 8, ptr); - EXPECT_EQ(8, size); -} - -TEST_F(CodedStreamTest, GetDirectBufferPointerInlineInput) { - ArrayInputStream input(buffer_, sizeof(buffer_), 8); - CodedInputStream coded_input(&input); - - const void* ptr; - int size; - - coded_input.GetDirectBufferPointerInline(&ptr, &size); - EXPECT_EQ(buffer_, ptr); - EXPECT_EQ(8, size); - - // Peeking again should return the same pointer. - coded_input.GetDirectBufferPointerInline(&ptr, &size); - EXPECT_EQ(buffer_, ptr); - EXPECT_EQ(8, size); - - // Skip forward in the same buffer then peek again. - EXPECT_TRUE(coded_input.Skip(3)); - coded_input.GetDirectBufferPointerInline(&ptr, &size); - EXPECT_EQ(buffer_ + 3, ptr); - EXPECT_EQ(5, size); - - // Skip to end of buffer and peek -- should return false and provide an empty - // buffer. It does not try to Refresh(). - EXPECT_TRUE(coded_input.Skip(5)); - coded_input.GetDirectBufferPointerInline(&ptr, &size); - EXPECT_EQ(buffer_ + 8, ptr); - EXPECT_EQ(0, size); -} - -TEST_F(CodedStreamTest, GetDirectBufferPointerOutput) { - ArrayOutputStream output(buffer_, sizeof(buffer_), 8); - CodedOutputStream coded_output(&output); - - void* ptr; - int size; - - EXPECT_TRUE(coded_output.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_, ptr); - EXPECT_EQ(8, size); - - // Peeking again should return the same pointer. - EXPECT_TRUE(coded_output.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_, ptr); - EXPECT_EQ(8, size); - - // Skip forward in the same buffer then peek again. - EXPECT_TRUE(coded_output.Skip(3)); - EXPECT_TRUE(coded_output.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_ + 3, ptr); - EXPECT_EQ(5, size); - - // Skip to end of buffer and peek -- should get next buffer. - EXPECT_TRUE(coded_output.Skip(5)); - EXPECT_TRUE(coded_output.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_ + 8, ptr); - EXPECT_EQ(8, size); - - // Skip over multiple buffers. - EXPECT_TRUE(coded_output.Skip(22)); - EXPECT_TRUE(coded_output.GetDirectBufferPointer(&ptr, &size)); - EXPECT_EQ(buffer_ + 30, ptr); - EXPECT_EQ(2, size); -} - -// ------------------------------------------------------------------- -// Limits - -TEST_1D(CodedStreamTest, BasicLimit, kBlockSizes) { - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - CodedInputStream::Limit limit = coded_input.PushLimit(8); - - // Read until we hit the limit. - uint32 value; - EXPECT_EQ(8, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(4, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - EXPECT_FALSE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - - coded_input.PopLimit(limit); - - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - } - - EXPECT_EQ(12, input.ByteCount()); -} - -// Test what happens when we push two limits where the second (top) one is -// shorter. -TEST_1D(CodedStreamTest, SmallLimitOnTopOfBigLimit, kBlockSizes) { - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - CodedInputStream::Limit limit1 = coded_input.PushLimit(8); - EXPECT_EQ(8, coded_input.BytesUntilLimit()); - CodedInputStream::Limit limit2 = coded_input.PushLimit(4); - - uint32 value; - - // Read until we hit limit2, the top and shortest limit. - EXPECT_EQ(4, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - EXPECT_FALSE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - - coded_input.PopLimit(limit2); - - // Read until we hit limit1. - EXPECT_EQ(4, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - EXPECT_FALSE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - - coded_input.PopLimit(limit1); - - // No more limits. - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - } - - EXPECT_EQ(12, input.ByteCount()); -} - -// Test what happens when we push two limits where the second (top) one is -// longer. In this case, the top limit is shortened to match the previous -// limit. -TEST_1D(CodedStreamTest, BigLimitOnTopOfSmallLimit, kBlockSizes) { - ArrayInputStream input(buffer_, sizeof(buffer_), kBlockSizes_case); - - { - CodedInputStream coded_input(&input); - - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - CodedInputStream::Limit limit1 = coded_input.PushLimit(4); - EXPECT_EQ(4, coded_input.BytesUntilLimit()); - CodedInputStream::Limit limit2 = coded_input.PushLimit(8); - - uint32 value; - - // Read until we hit limit2. Except, wait! limit1 is shorter, so - // we end up hitting that first, despite having 4 bytes to go on - // limit2. - EXPECT_EQ(4, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - EXPECT_FALSE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - - coded_input.PopLimit(limit2); - - // OK, popped limit2, now limit1 is on top, which we've already hit. - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - EXPECT_FALSE(coded_input.ReadLittleEndian32(&value)); - EXPECT_EQ(0, coded_input.BytesUntilLimit()); - - coded_input.PopLimit(limit1); - - // No more limits. - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - } - - EXPECT_EQ(8, input.ByteCount()); -} - -TEST_F(CodedStreamTest, ExpectAtEnd) { - // Test ExpectAtEnd(), which is based on limits. - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - - EXPECT_FALSE(coded_input.ExpectAtEnd()); - - CodedInputStream::Limit limit = coded_input.PushLimit(4); - - uint32 value; - EXPECT_TRUE(coded_input.ReadLittleEndian32(&value)); - EXPECT_TRUE(coded_input.ExpectAtEnd()); - - coded_input.PopLimit(limit); - EXPECT_FALSE(coded_input.ExpectAtEnd()); -} - -TEST_F(CodedStreamTest, NegativeLimit) { - // Check what happens when we push a negative limit. - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - - CodedInputStream::Limit limit = coded_input.PushLimit(-1234); - // BytesUntilLimit() returns -1 to mean "no limit", which actually means - // "the limit is INT_MAX relative to the beginning of the stream". - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - coded_input.PopLimit(limit); -} - -TEST_F(CodedStreamTest, NegativeLimitAfterReading) { - // Check what happens when we push a negative limit. - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - ASSERT_TRUE(coded_input.Skip(128)); - - CodedInputStream::Limit limit = coded_input.PushLimit(-64); - // BytesUntilLimit() returns -1 to mean "no limit", which actually means - // "the limit is INT_MAX relative to the beginning of the stream". - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - coded_input.PopLimit(limit); -} - -TEST_F(CodedStreamTest, OverflowLimit) { - // Check what happens when we push a limit large enough that its absolute - // position is more than 2GB into the stream. - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - ASSERT_TRUE(coded_input.Skip(128)); - - CodedInputStream::Limit limit = coded_input.PushLimit(INT_MAX); - // BytesUntilLimit() returns -1 to mean "no limit", which actually means - // "the limit is INT_MAX relative to the beginning of the stream". - EXPECT_EQ(-1, coded_input.BytesUntilLimit()); - coded_input.PopLimit(limit); -} - -TEST_F(CodedStreamTest, TotalBytesLimit) { - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - coded_input.SetTotalBytesLimit(16, -1); - - string str; - EXPECT_TRUE(coded_input.ReadString(&str, 16)); - - vector errors; - - { - ScopedMemoryLog error_log; - EXPECT_FALSE(coded_input.ReadString(&str, 1)); - errors = error_log.GetMessages(ERROR); - } - - ASSERT_EQ(1, errors.size()); - EXPECT_PRED_FORMAT2(testing::IsSubstring, - "A protocol message was rejected because it was too big", errors[0]); - - coded_input.SetTotalBytesLimit(32, -1); - EXPECT_TRUE(coded_input.ReadString(&str, 16)); -} - -TEST_F(CodedStreamTest, TotalBytesLimitNotValidMessageEnd) { - // total_bytes_limit_ is not a valid place for a message to end. - - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - - // Set both total_bytes_limit and a regular limit at 16 bytes. - coded_input.SetTotalBytesLimit(16, -1); - CodedInputStream::Limit limit = coded_input.PushLimit(16); - - // Read 16 bytes. - string str; - EXPECT_TRUE(coded_input.ReadString(&str, 16)); - - // Read a tag. Should fail, but report being a valid endpoint since it's - // a regular limit. - EXPECT_EQ(0, coded_input.ReadTag()); - EXPECT_TRUE(coded_input.ConsumedEntireMessage()); - - // Pop the limit. - coded_input.PopLimit(limit); - - // Read a tag. Should fail, and report *not* being a valid endpoint, since - // this time we're hitting the total bytes limit. - EXPECT_EQ(0, coded_input.ReadTag()); - EXPECT_FALSE(coded_input.ConsumedEntireMessage()); -} - -TEST_F(CodedStreamTest, RecursionLimit) { - ArrayInputStream input(buffer_, sizeof(buffer_)); - CodedInputStream coded_input(&input); - coded_input.SetRecursionLimit(4); - - // This is way too much testing for a counter. - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 1 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 2 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 3 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 6 - coded_input.DecrementRecursionDepth(); // 5 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 6 - coded_input.DecrementRecursionDepth(); // 5 - coded_input.DecrementRecursionDepth(); // 4 - coded_input.DecrementRecursionDepth(); // 3 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 - coded_input.DecrementRecursionDepth(); // 4 - coded_input.DecrementRecursionDepth(); // 3 - coded_input.DecrementRecursionDepth(); // 2 - coded_input.DecrementRecursionDepth(); // 1 - coded_input.DecrementRecursionDepth(); // 0 - coded_input.DecrementRecursionDepth(); // 0 - coded_input.DecrementRecursionDepth(); // 0 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 1 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 2 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 3 - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 4 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 5 - - coded_input.SetRecursionLimit(6); - EXPECT_TRUE(coded_input.IncrementRecursionDepth()); // 6 - EXPECT_FALSE(coded_input.IncrementRecursionDepth()); // 7 -} - -class ReallyBigInputStream : public ZeroCopyInputStream { - public: - ReallyBigInputStream() : backup_amount_(0), buffer_count_(0) {} - ~ReallyBigInputStream() {} - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size) { - // We only expect BackUp() to be called at the end. - EXPECT_EQ(0, backup_amount_); - - switch (buffer_count_++) { - case 0: - *data = buffer_; - *size = sizeof(buffer_); - return true; - case 1: - // Return an enormously large buffer that, when combined with the 1k - // returned already, should overflow the total_bytes_read_ counter in - // CodedInputStream. Note that we'll only read the first 1024 bytes - // of this buffer so it's OK that we have it point at buffer_. - *data = buffer_; - *size = INT_MAX; - return true; - default: - return false; - } - } - - void BackUp(int count) { - backup_amount_ = count; - } - - bool Skip(int count) { GOOGLE_LOG(FATAL) << "Not implemented."; return false; } - int64 ByteCount() const { GOOGLE_LOG(FATAL) << "Not implemented."; return 0; } - - int backup_amount_; - - private: - char buffer_[1024]; - int64 buffer_count_; -}; - -TEST_F(CodedStreamTest, InputOver2G) { - // CodedInputStream should gracefully handle input over 2G and call - // input.BackUp() with the correct number of bytes on destruction. - ReallyBigInputStream input; - - vector errors; - - { - ScopedMemoryLog error_log; - CodedInputStream coded_input(&input); - string str; - EXPECT_TRUE(coded_input.ReadString(&str, 512)); - EXPECT_TRUE(coded_input.ReadString(&str, 1024)); - errors = error_log.GetMessages(ERROR); - } - - EXPECT_EQ(INT_MAX - 512, input.backup_amount_); - EXPECT_EQ(0, errors.size()); -} - -// =================================================================== - - -} // namespace -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/gzip_stream.cc b/Resources/NetHook/google/protobuf/io/gzip_stream.cc deleted file mode 100644 index 84d277f4..00000000 --- a/Resources/NetHook/google/protobuf/io/gzip_stream.cc +++ /dev/null @@ -1,320 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: brianolson@google.com (Brian Olson) -// -// This file contains the implementation of classes GzipInputStream and -// GzipOutputStream. - -#include "config.h" - -#if HAVE_ZLIB -#include - -#include - -namespace google { -namespace protobuf { -namespace io { - -static const int kDefaultBufferSize = 65536; - -GzipInputStream::GzipInputStream( - ZeroCopyInputStream* sub_stream, Format format, int buffer_size) - : format_(format), sub_stream_(sub_stream), zerror_(Z_OK) { - zcontext_.zalloc = Z_NULL; - zcontext_.zfree = Z_NULL; - zcontext_.opaque = Z_NULL; - zcontext_.total_out = 0; - zcontext_.next_in = NULL; - zcontext_.avail_in = 0; - zcontext_.total_in = 0; - zcontext_.msg = NULL; - if (buffer_size == -1) { - output_buffer_length_ = kDefaultBufferSize; - } else { - output_buffer_length_ = buffer_size; - } - output_buffer_ = operator new(output_buffer_length_); - GOOGLE_CHECK(output_buffer_ != NULL); - zcontext_.next_out = static_cast(output_buffer_); - zcontext_.avail_out = output_buffer_length_; - output_position_ = output_buffer_; -} -GzipInputStream::~GzipInputStream() { - operator delete(output_buffer_); - zerror_ = inflateEnd(&zcontext_); -} - -int GzipInputStream::Inflate(int flush) { - if ((zerror_ == Z_OK) && (zcontext_.avail_out == 0)) { - // previous inflate filled output buffer. don't change input params yet. - } else if (zcontext_.avail_in == 0) { - const void* in; - int in_size; - bool first = zcontext_.next_in == NULL; - bool ok = sub_stream_->Next(&in, &in_size); - if (!ok) { - zcontext_.next_out = NULL; - zcontext_.avail_out = 0; - return Z_STREAM_END; - } - zcontext_.next_in = static_cast(const_cast(in)); - zcontext_.avail_in = in_size; - if (first) { - int windowBitsFormat = 0; - switch (format_) { - case GZIP: windowBitsFormat = 16; break; - case AUTO: windowBitsFormat = 32; break; - case ZLIB: windowBitsFormat = 0; break; - } - int error = inflateInit2(&zcontext_, - /* windowBits */15 | windowBitsFormat); - if (error != Z_OK) { - return error; - } - } - } - zcontext_.next_out = static_cast(output_buffer_); - zcontext_.avail_out = output_buffer_length_; - output_position_ = output_buffer_; - int error = inflate(&zcontext_, flush); - return error; -} - -void GzipInputStream::DoNextOutput(const void** data, int* size) { - *data = output_position_; - *size = ((uintptr_t)zcontext_.next_out) - ((uintptr_t)output_position_); - output_position_ = zcontext_.next_out; -} - -// implements ZeroCopyInputStream ---------------------------------- -bool GzipInputStream::Next(const void** data, int* size) { - bool ok = (zerror_ == Z_OK) || (zerror_ == Z_STREAM_END) - || (zerror_ == Z_BUF_ERROR); - if ((!ok) || (zcontext_.next_out == NULL)) { - return false; - } - if (zcontext_.next_out != output_position_) { - DoNextOutput(data, size); - return true; - } - if (zerror_ == Z_STREAM_END) { - *data = NULL; - *size = 0; - return false; - } - zerror_ = Inflate(Z_NO_FLUSH); - if ((zerror_ == Z_STREAM_END) && (zcontext_.next_out == NULL)) { - // The underlying stream's Next returned false inside Inflate. - return false; - } - ok = (zerror_ == Z_OK) || (zerror_ == Z_STREAM_END) - || (zerror_ == Z_BUF_ERROR); - if (!ok) { - return false; - } - DoNextOutput(data, size); - return true; -} -void GzipInputStream::BackUp(int count) { - output_position_ = reinterpret_cast( - reinterpret_cast(output_position_) - count); -} -bool GzipInputStream::Skip(int count) { - const void* data; - int size; - bool ok = Next(&data, &size); - while (ok && (size < count)) { - count -= size; - ok = Next(&data, &size); - } - if (size > count) { - BackUp(size - count); - } - return ok; -} -int64 GzipInputStream::ByteCount() const { - return zcontext_.total_out + - (((uintptr_t)zcontext_.next_out) - ((uintptr_t)output_position_)); -} - -// ========================================================================= - -GzipOutputStream::Options::Options() - : format(GZIP), - buffer_size(kDefaultBufferSize), - compression_level(Z_DEFAULT_COMPRESSION), - compression_strategy(Z_DEFAULT_STRATEGY) {} - -GzipOutputStream::GzipOutputStream(ZeroCopyOutputStream* sub_stream) { - Init(sub_stream, Options()); -} - -GzipOutputStream::GzipOutputStream(ZeroCopyOutputStream* sub_stream, - const Options& options) { - Init(sub_stream, options); -} - -GzipOutputStream::GzipOutputStream( - ZeroCopyOutputStream* sub_stream, Format format, int buffer_size) { - Options options; - options.format = format; - if (buffer_size != -1) { - options.buffer_size = buffer_size; - } - Init(sub_stream, options); -} - -void GzipOutputStream::Init(ZeroCopyOutputStream* sub_stream, - const Options& options) { - sub_stream_ = sub_stream; - sub_data_ = NULL; - sub_data_size_ = 0; - - input_buffer_length_ = options.buffer_size; - input_buffer_ = operator new(input_buffer_length_); - GOOGLE_CHECK(input_buffer_ != NULL); - - zcontext_.zalloc = Z_NULL; - zcontext_.zfree = Z_NULL; - zcontext_.opaque = Z_NULL; - zcontext_.next_out = NULL; - zcontext_.avail_out = 0; - zcontext_.total_out = 0; - zcontext_.next_in = NULL; - zcontext_.avail_in = 0; - zcontext_.total_in = 0; - zcontext_.msg = NULL; - // default to GZIP format - int windowBitsFormat = 16; - if (options.format == ZLIB) { - windowBitsFormat = 0; - } - zerror_ = deflateInit2( - &zcontext_, - options.compression_level, - Z_DEFLATED, - /* windowBits */15 | windowBitsFormat, - /* memLevel (default) */8, - options.compression_strategy); -} - -GzipOutputStream::~GzipOutputStream() { - Close(); - if (input_buffer_ != NULL) { - operator delete(input_buffer_); - } -} - -// private -int GzipOutputStream::Deflate(int flush) { - int error = Z_OK; - do { - if ((sub_data_ == NULL) || (zcontext_.avail_out == 0)) { - bool ok = sub_stream_->Next(&sub_data_, &sub_data_size_); - if (!ok) { - sub_data_ = NULL; - sub_data_size_ = 0; - return Z_BUF_ERROR; - } - GOOGLE_CHECK_GT(sub_data_size_, 0); - zcontext_.next_out = static_cast(sub_data_); - zcontext_.avail_out = sub_data_size_; - } - error = deflate(&zcontext_, flush); - } while (error == Z_OK && zcontext_.avail_out == 0); - if (((flush == Z_FULL_FLUSH) || (flush == Z_FINISH)) - && (zcontext_.avail_out != sub_data_size_)) { - // Notify lower layer of data. - sub_stream_->BackUp(zcontext_.avail_out); - // We don't own the buffer anymore. - sub_data_ = NULL; - sub_data_size_ = 0; - } - return error; -} - -// implements ZeroCopyOutputStream --------------------------------- -bool GzipOutputStream::Next(void** data, int* size) { - if ((zerror_ != Z_OK) && (zerror_ != Z_BUF_ERROR)) { - return false; - } - if (zcontext_.avail_in != 0) { - zerror_ = Deflate(Z_NO_FLUSH); - if (zerror_ != Z_OK) { - return false; - } - } - if (zcontext_.avail_in == 0) { - // all input was consumed. reset the buffer. - zcontext_.next_in = static_cast(input_buffer_); - zcontext_.avail_in = input_buffer_length_; - *data = input_buffer_; - *size = input_buffer_length_; - } else { - // The loop in Deflate should consume all avail_in - GOOGLE_LOG(DFATAL) << "Deflate left bytes unconsumed"; - } - return true; -} -void GzipOutputStream::BackUp(int count) { - GOOGLE_CHECK_GE(zcontext_.avail_in, count); - zcontext_.avail_in -= count; -} -int64 GzipOutputStream::ByteCount() const { - return zcontext_.total_in + zcontext_.avail_in; -} - -bool GzipOutputStream::Flush() { - do { - zerror_ = Deflate(Z_FULL_FLUSH); - } while (zerror_ == Z_OK); - return zerror_ == Z_OK; -} - -bool GzipOutputStream::Close() { - if ((zerror_ != Z_OK) && (zerror_ != Z_BUF_ERROR)) { - return false; - } - do { - zerror_ = Deflate(Z_FINISH); - } while (zerror_ == Z_OK); - zerror_ = deflateEnd(&zcontext_); - bool ok = zerror_ == Z_OK; - zerror_ = Z_STREAM_END; - return ok; -} - -} // namespace io -} // namespace protobuf -} // namespace google - -#endif // HAVE_ZLIB diff --git a/Resources/NetHook/google/protobuf/io/gzip_stream.h b/Resources/NetHook/google/protobuf/io/gzip_stream.h deleted file mode 100644 index 65dbc5b5..00000000 --- a/Resources/NetHook/google/protobuf/io/gzip_stream.h +++ /dev/null @@ -1,207 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: brianolson@google.com (Brian Olson) -// -// This file contains the definition for classes GzipInputStream and -// GzipOutputStream. -// -// GzipInputStream decompresses data from an underlying -// ZeroCopyInputStream and provides the decompressed data as a -// ZeroCopyInputStream. -// -// GzipOutputStream is an ZeroCopyOutputStream that compresses data to -// an underlying ZeroCopyOutputStream. - -#ifndef GOOGLE_PROTOBUF_IO_GZIP_STREAM_H__ -#define GOOGLE_PROTOBUF_IO_GZIP_STREAM_H__ - -#include - -#include - -namespace google { -namespace protobuf { -namespace io { - -// A ZeroCopyInputStream that reads compressed data through zlib -class LIBPROTOBUF_EXPORT GzipInputStream : public ZeroCopyInputStream { - public: - // Format key for constructor - enum Format { - // zlib will autodetect gzip header or deflate stream - AUTO = 0, - - // GZIP streams have some extra header data for file attributes. - GZIP = 1, - - // Simpler zlib stream format. - ZLIB = 2, - }; - - // buffer_size and format may be -1 for default of 64kB and GZIP format - explicit GzipInputStream( - ZeroCopyInputStream* sub_stream, - Format format = AUTO, - int buffer_size = -1); - virtual ~GzipInputStream(); - - // Return last error message or NULL if no error. - inline const char* ZlibErrorMessage() const { - return zcontext_.msg; - } - inline int ZlibErrorCode() const { - return zerror_; - } - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - private: - Format format_; - - ZeroCopyInputStream* sub_stream_; - - z_stream zcontext_; - int zerror_; - - void* output_buffer_; - void* output_position_; - size_t output_buffer_length_; - - int Inflate(int flush); - void DoNextOutput(const void** data, int* size); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GzipInputStream); -}; - - -class LIBPROTOBUF_EXPORT GzipOutputStream : public ZeroCopyOutputStream { - public: - // Format key for constructor - enum Format { - // GZIP streams have some extra header data for file attributes. - GZIP = 1, - - // Simpler zlib stream format. - ZLIB = 2, - }; - - struct Options { - // Defaults to GZIP. - Format format; - - // What size buffer to use internally. Defaults to 64kB. - int buffer_size; - - // A number between 0 and 9, where 0 is no compression and 9 is best - // compression. Defaults to Z_DEFAULT_COMPRESSION (see zlib.h). - int compression_level; - - // Defaults to Z_DEFAULT_STRATEGY. Can also be set to Z_FILTERED, - // Z_HUFFMAN_ONLY, or Z_RLE. See the documentation for deflateInit2 in - // zlib.h for definitions of these constants. - int compression_strategy; - - Options(); // Initializes with default values. - }; - - // Create a GzipOutputStream with default options. - explicit GzipOutputStream(ZeroCopyOutputStream* sub_stream); - - // Create a GzipOutputStream with the given options. - GzipOutputStream( - ZeroCopyOutputStream* sub_stream, - const Options& options); - - // DEPRECATED: Use one of the above constructors instead. - GzipOutputStream( - ZeroCopyOutputStream* sub_stream, - Format format, - int buffer_size = -1) GOOGLE_ATTRIBUTE_DEPRECATED; - - virtual ~GzipOutputStream(); - - // Return last error message or NULL if no error. - inline const char* ZlibErrorMessage() const { - return zcontext_.msg; - } - inline int ZlibErrorCode() const { - return zerror_; - } - - // Flushes data written so far to zipped data in the underlying stream. - // It is the caller's responsibility to flush the underlying stream if - // necessary. - // Compression may be less efficient stopping and starting around flushes. - // Returns true if no error. - bool Flush(); - - // Writes out all data and closes the gzip stream. - // It is the caller's responsibility to close the underlying stream if - // necessary. - // Returns true if no error. - bool Close(); - - // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - private: - ZeroCopyOutputStream* sub_stream_; - // Result from calling Next() on sub_stream_ - void* sub_data_; - int sub_data_size_; - - z_stream zcontext_; - int zerror_; - void* input_buffer_; - size_t input_buffer_length_; - - // Shared constructor code. - void Init(ZeroCopyOutputStream* sub_stream, const Options& options); - - // Do some compression. - // Takes zlib flush mode. - // Returns zlib error code. - int Deflate(int flush); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(GzipOutputStream); -}; - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_GZIP_STREAM_H__ diff --git a/Resources/NetHook/google/protobuf/io/gzip_stream_unittest.sh b/Resources/NetHook/google/protobuf/io/gzip_stream_unittest.sh deleted file mode 100644 index 6e8a0943..00000000 --- a/Resources/NetHook/google/protobuf/io/gzip_stream_unittest.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/sh -x -# -# Protocol Buffers - Google's data interchange format -# Copyright 2009 Google Inc. All rights reserved. -# http://code.google.com/p/protobuf/ -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * 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. -# * Neither the name of Google Inc. nor the names of its -# contributors may 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. -# -# Author: brianolson@google.com (Brian Olson) -# -# Test compatibility between command line gzip/gunzip binaries and -# ZeroCopyStream versions. - -TESTFILE=Makefile - -(./zcgzip < ${TESTFILE} | gunzip | cmp - ${TESTFILE}) && \ -(gzip < ${TESTFILE} | ./zcgunzip | cmp - ${TESTFILE}) - -# Result of "(cmd) && (cmd)" implicitly becomes result of this script -# and thus the test. diff --git a/Resources/NetHook/google/protobuf/io/package_info.h b/Resources/NetHook/google/protobuf/io/package_info.h deleted file mode 100644 index 7a7a4e77..00000000 --- a/Resources/NetHook/google/protobuf/io/package_info.h +++ /dev/null @@ -1,54 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file exists solely to document the google::protobuf::io namespace. -// It is not compiled into anything, but it may be read by an automated -// documentation generator. - -namespace google { - -namespace protobuf { - -// Auxiliary classes used for I/O. -// -// The Protocol Buffer library uses the classes in this package to deal with -// I/O and encoding/decoding raw bytes. Most users will not need to -// deal with this package. However, users who want to adapt the system to -// work with their own I/O abstractions -- e.g., to allow Protocol Buffers -// to be read from a different kind of input stream without the need for a -// temporary buffer -- should take a closer look. -namespace io {} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/printer.cc b/Resources/NetHook/google/protobuf/io/printer.cc deleted file mode 100644 index c7d3074d..00000000 --- a/Resources/NetHook/google/protobuf/io/printer.cc +++ /dev/null @@ -1,188 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { - -Printer::Printer(ZeroCopyOutputStream* output, char variable_delimiter) - : variable_delimiter_(variable_delimiter), - output_(output), - buffer_(NULL), - buffer_size_(0), - at_start_of_line_(true), - failed_(false) { -} - -Printer::~Printer() { - // Only BackUp() if we're sure we've successfully called Next() at least once. - if (buffer_size_ > 0) { - output_->BackUp(buffer_size_); - } -} - -void Printer::Print(const map& variables, const char* text) { - int size = strlen(text); - int pos = 0; // The number of bytes we've written so far. - - for (int i = 0; i < size; i++) { - if (text[i] == '\n') { - // Saw newline. If there is more text, we may need to insert an indent - // here. So, write what we have so far, including the '\n'. - WriteRaw(text + pos, i - pos + 1); - pos = i + 1; - - // Setting this true will cause the next WriteRaw() to insert an indent - // first. - at_start_of_line_ = true; - - } else if (text[i] == variable_delimiter_) { - // Saw the start of a variable name. - - // Write what we have so far. - WriteRaw(text + pos, i - pos); - pos = i + 1; - - // Find closing delimiter. - const char* end = strchr(text + pos, variable_delimiter_); - if (end == NULL) { - GOOGLE_LOG(DFATAL) << " Unclosed variable name."; - end = text + pos; - } - int endpos = end - text; - - string varname(text + pos, endpos - pos); - if (varname.empty()) { - // Two delimiters in a row reduce to a literal delimiter character. - WriteRaw(&variable_delimiter_, 1); - } else { - // Replace with the variable's value. - map::const_iterator iter = variables.find(varname); - if (iter == variables.end()) { - GOOGLE_LOG(DFATAL) << " Undefined variable: " << varname; - } else { - WriteRaw(iter->second.data(), iter->second.size()); - } - } - - // Advance past this variable. - i = endpos; - pos = endpos + 1; - } - } - - // Write the rest. - WriteRaw(text + pos, size - pos); -} - -void Printer::Print(const char* text) { - static map empty; - Print(empty, text); -} - -void Printer::Print(const char* text, - const char* variable, const string& value) { - map vars; - vars[variable] = value; - Print(vars, text); -} - -void Printer::Print(const char* text, - const char* variable1, const string& value1, - const char* variable2, const string& value2) { - map vars; - vars[variable1] = value1; - vars[variable2] = value2; - Print(vars, text); -} - -void Printer::Indent() { - indent_ += " "; -} - -void Printer::Outdent() { - if (indent_.empty()) { - GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent()."; - return; - } - - indent_.resize(indent_.size() - 2); -} - -void Printer::PrintRaw(const string& data) { - WriteRaw(data.data(), data.size()); -} - -void Printer::PrintRaw(const char* data) { - if (failed_) return; - WriteRaw(data, strlen(data)); -} - -void Printer::WriteRaw(const char* data, int size) { - if (failed_) return; - if (size == 0) return; - - if (at_start_of_line_) { - // Insert an indent. - at_start_of_line_ = false; - WriteRaw(indent_.data(), indent_.size()); - if (failed_) return; - } - - while (size > buffer_size_) { - // Data exceeds space in the buffer. Copy what we can and request a - // new buffer. - memcpy(buffer_, data, buffer_size_); - data += buffer_size_; - size -= buffer_size_; - void* void_buffer; - failed_ = !output_->Next(&void_buffer, &buffer_size_); - if (failed_) return; - buffer_ = reinterpret_cast(void_buffer); - } - - // Buffer is big enough to receive the data; copy it. - memcpy(buffer_, data, size); - buffer_ += size; - buffer_size_ -= size; -} - -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/printer.h b/Resources/NetHook/google/protobuf/io/printer.h deleted file mode 100644 index de085389..00000000 --- a/Resources/NetHook/google/protobuf/io/printer.h +++ /dev/null @@ -1,132 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Utility class for writing text to a ZeroCopyOutputStream. - -#ifndef GOOGLE_PROTOBUF_IO_PRINTER_H__ -#define GOOGLE_PROTOBUF_IO_PRINTER_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { - -class ZeroCopyOutputStream; // zero_copy_stream.h - -// This simple utility class assists in code generation. It basically -// allows the caller to define a set of variables and then output some -// text with variable substitutions. Example usage: -// -// Printer printer(output, '$'); -// map vars; -// vars["name"] = "Bob"; -// printer.Print(vars, "My name is $name$."); -// -// The above writes "My name is Bob." to the output stream. -// -// Printer aggressively enforces correct usage, crashing (with assert failures) -// in the case of undefined variables in debug builds. This helps greatly in -// debugging code which uses it. -class LIBPROTOBUF_EXPORT Printer { - public: - // Create a printer that writes text to the given output stream. Use the - // given character as the delimiter for variables. - Printer(ZeroCopyOutputStream* output, char variable_delimiter); - ~Printer(); - - // Print some text after applying variable substitutions. If a particular - // variable in the text is not defined, this will crash. Variables to be - // substituted are identified by their names surrounded by delimiter - // characters (as given to the constructor). The variable bindings are - // defined by the given map. - void Print(const map& variables, const char* text); - - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable, const string& value); - // Like the first Print(), except the substitutions are given as parameters. - void Print(const char* text, const char* variable1, const string& value1, - const char* variable2, const string& value2); - // TODO(kenton): Overloaded versions with more variables? Two seems - // to be enough. - - // Indent text by two spaces. After calling Indent(), two spaces will be - // inserted at the beginning of each line of text. Indent() may be called - // multiple times to produce deeper indents. - void Indent(); - - // Reduces the current indent level by two spaces, or crashes if the indent - // level is zero. - void Outdent(); - - // Write a string to the output buffer. - // This method does not look for newlines to add indentation. - void PrintRaw(const string& data); - - // Write a zero-delimited string to output buffer. - // This method does not look for newlines to add indentation. - void PrintRaw(const char* data); - - // Write some bytes to the output buffer. - // This method does not look for newlines to add indentation. - void WriteRaw(const char* data, int size); - - // True if any write to the underlying stream failed. (We don't just - // crash in this case because this is an I/O failure, not a programming - // error.) - bool failed() const { return failed_; } - - private: - const char variable_delimiter_; - - ZeroCopyOutputStream* const output_; - char* buffer_; - int buffer_size_; - - string indent_; - bool at_start_of_line_; - bool failed_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Printer); -}; - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_PRINTER_H__ diff --git a/Resources/NetHook/google/protobuf/io/printer_unittest.cc b/Resources/NetHook/google/protobuf/io/printer_unittest.cc deleted file mode 100644 index 580a53da..00000000 --- a/Resources/NetHook/google/protobuf/io/printer_unittest.cc +++ /dev/null @@ -1,261 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { -namespace { - -// Each test repeats over several block sizes in order to test both cases -// where particular writes cross a buffer boundary and cases where they do -// not. - -TEST(Printer, EmptyPrinter) { - char buffer[8192]; - const int block_size = 100; - ArrayOutputStream output(buffer, GOOGLE_ARRAYSIZE(buffer), block_size); - Printer printer(&output, '\0'); - EXPECT_TRUE(!printer.failed()); -} - -TEST(Printer, BasicPrinting) { - char buffer[8192]; - - for (int block_size = 1; block_size < 512; block_size *= 2) { - ArrayOutputStream output(buffer, sizeof(buffer), block_size); - - { - Printer printer(&output, '\0'); - - printer.Print("Hello World!"); - printer.Print(" This is the same line.\n"); - printer.Print("But this is a new one.\nAnd this is another one."); - - EXPECT_FALSE(printer.failed()); - } - - buffer[output.ByteCount()] = '\0'; - - EXPECT_STREQ("Hello World! This is the same line.\n" - "But this is a new one.\n" - "And this is another one.", - buffer); - } -} - -TEST(Printer, WriteRaw) { - char buffer[8192]; - - for (int block_size = 1; block_size < 512; block_size *= 2) { - ArrayOutputStream output(buffer, sizeof(buffer), block_size); - - { - string string_obj = "From an object\n"; - Printer printer(&output, '$'); - printer.WriteRaw("Hello World!", 12); - printer.PrintRaw(" This is the same line.\n"); - printer.PrintRaw("But this is a new one.\nAnd this is another one."); - printer.WriteRaw("\n", 1); - printer.PrintRaw(string_obj); - EXPECT_FALSE(printer.failed()); - } - - buffer[output.ByteCount()] = '\0'; - - EXPECT_STREQ("Hello World! This is the same line.\n" - "But this is a new one.\n" - "And this is another one." - "\n" - "From an object\n", - buffer); - } -} - -TEST(Printer, VariableSubstitution) { - char buffer[8192]; - - for (int block_size = 1; block_size < 512; block_size *= 2) { - ArrayOutputStream output(buffer, sizeof(buffer), block_size); - - { - Printer printer(&output, '$'); - map vars; - - vars["foo"] = "World"; - vars["bar"] = "$foo$"; - vars["abcdefg"] = "1234"; - - printer.Print(vars, "Hello $foo$!\nbar = $bar$\n"); - printer.PrintRaw("RawBit\n"); - printer.Print(vars, "$abcdefg$\nA literal dollar sign: $$"); - - vars["foo"] = "blah"; - printer.Print(vars, "\nNow foo = $foo$."); - - EXPECT_FALSE(printer.failed()); - } - - buffer[output.ByteCount()] = '\0'; - - EXPECT_STREQ("Hello World!\n" - "bar = $foo$\n" - "RawBit\n" - "1234\n" - "A literal dollar sign: $\n" - "Now foo = blah.", - buffer); - } -} - -TEST(Printer, InlineVariableSubstitution) { - char buffer[8192]; - - ArrayOutputStream output(buffer, sizeof(buffer)); - - { - Printer printer(&output, '$'); - printer.Print("Hello $foo$!\n", "foo", "World"); - printer.PrintRaw("RawBit\n"); - printer.Print("$foo$ $bar$\n", "foo", "one", "bar", "two"); - EXPECT_FALSE(printer.failed()); - } - - buffer[output.ByteCount()] = '\0'; - - EXPECT_STREQ("Hello World!\n" - "RawBit\n" - "one two\n", - buffer); -} - -TEST(Printer, Indenting) { - char buffer[8192]; - - for (int block_size = 1; block_size < 512; block_size *= 2) { - ArrayOutputStream output(buffer, sizeof(buffer), block_size); - - { - Printer printer(&output, '$'); - map vars; - - vars["newline"] = "\n"; - - printer.Print("This is not indented.\n"); - printer.Indent(); - printer.Print("This is indented\nAnd so is this\n"); - printer.Outdent(); - printer.Print("But this is not."); - printer.Indent(); - printer.Print(" And this is still the same line.\n" - "But this is indented.\n"); - printer.PrintRaw("RawBit has indent at start\n"); - printer.PrintRaw("but not after a raw newline\n"); - printer.Print(vars, "Note that a newline in a variable will break " - "indenting, as we see$newline$here.\n"); - printer.Indent(); - printer.Print("And this"); - printer.Outdent(); - printer.Outdent(); - printer.Print(" is double-indented\nBack to normal."); - - EXPECT_FALSE(printer.failed()); - } - - buffer[output.ByteCount()] = '\0'; - - EXPECT_STREQ( - "This is not indented.\n" - " This is indented\n" - " And so is this\n" - "But this is not. And this is still the same line.\n" - " But this is indented.\n" - " RawBit has indent at start\n" - "but not after a raw newline\n" - "Note that a newline in a variable will break indenting, as we see\n" - "here.\n" - " And this is double-indented\n" - "Back to normal.", - buffer); - } -} - -// Death tests do not work on Windows as of yet. -#ifdef GTEST_HAS_DEATH_TEST -TEST(Printer, Death) { - char buffer[8192]; - - ArrayOutputStream output(buffer, sizeof(buffer)); - Printer printer(&output, '$'); - - EXPECT_DEBUG_DEATH(printer.Print("$nosuchvar$"), "Undefined variable"); - EXPECT_DEBUG_DEATH(printer.Print("$unclosed"), "Unclosed variable name"); - EXPECT_DEBUG_DEATH(printer.Outdent(), "without matching Indent"); -} -#endif // GTEST_HAS_DEATH_TEST - -TEST(Printer, WriteFailure) { - char buffer[16]; - - ArrayOutputStream output(buffer, sizeof(buffer)); - Printer printer(&output, '$'); - - // Print 16 bytes to fill the buffer exactly (should not fail). - printer.Print("0123456789abcdef"); - EXPECT_FALSE(printer.failed()); - - // Try to print one more byte (should fail). - printer.Print(" "); - EXPECT_TRUE(printer.failed()); - - // Should not crash - printer.Print("blah"); - EXPECT_TRUE(printer.failed()); - - // Buffer should contain the first 16 bytes written. - EXPECT_EQ("0123456789abcdef", string(buffer, sizeof(buffer))); -} - -} // namespace -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/tokenizer.cc b/Resources/NetHook/google/protobuf/io/tokenizer.cc deleted file mode 100644 index 38fa351c..00000000 --- a/Resources/NetHook/google/protobuf/io/tokenizer.cc +++ /dev/null @@ -1,691 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Here we have a hand-written lexer. At first you might ask yourself, -// "Hand-written text processing? Is Kenton crazy?!" Well, first of all, -// yes I am crazy, but that's beside the point. There are actually reasons -// why I ended up writing this this way. -// -// The traditional approach to lexing is to use lex to generate a lexer for -// you. Unfortunately, lex's output is ridiculously ugly and difficult to -// integrate cleanly with C++ code, especially abstract code or code meant -// as a library. Better parser-generators exist but would add dependencies -// which most users won't already have, which we'd like to avoid. (GNU flex -// has a C++ output option, but it's still ridiculously ugly, non-abstract, -// and not library-friendly.) -// -// The next approach that any good software engineer should look at is to -// use regular expressions. And, indeed, I did. I have code which -// implements this same class using regular expressions. It's about 200 -// lines shorter. However: -// - Rather than error messages telling you "This string has an invalid -// escape sequence at line 5, column 45", you get error messages like -// "Parse error on line 5". Giving more precise errors requires adding -// a lot of code that ends up basically as complex as the hand-coded -// version anyway. -// - The regular expression to match a string literal looks like this: -// kString = new RE("(\"([^\"\\\\]|" // non-escaped -// "\\\\[abfnrtv?\"'\\\\0-7]|" // normal escape -// "\\\\x[0-9a-fA-F])*\"|" // hex escape -// "\'([^\'\\\\]|" // Also support single-quotes. -// "\\\\[abfnrtv?\"'\\\\0-7]|" -// "\\\\x[0-9a-fA-F])*\')"); -// Verifying the correctness of this line noise is actually harder than -// verifying the correctness of ConsumeString(), defined below. I'm not -// even confident that the above is correct, after staring at it for some -// time. -// - PCRE is fast, but there's still more overhead involved than the code -// below. -// - Sadly, regular expressions are not part of the C standard library, so -// using them would require depending on some other library. For the -// open source release, this could be really annoying. Nobody likes -// downloading one piece of software just to find that they need to -// download something else to make it work, and in all likelihood -// people downloading Protocol Buffers will already be doing so just -// to make something else work. We could include a copy of PCRE with -// our code, but that obligates us to keep it up-to-date and just seems -// like a big waste just to save 200 lines of code. -// -// On a similar but unrelated note, I'm even scared to use ctype.h. -// Apparently functions like isalpha() are locale-dependent. So, if we used -// that, then if this code is being called from some program that doesn't -// have its locale set to "C", it would behave strangely. We can't just set -// the locale to "C" ourselves since we might break the calling program that -// way, particularly if it is multi-threaded. WTF? Someone please let me -// (Kenton) know if I'm missing something here... -// -// I'd love to hear about other alternatives, though, as this code isn't -// exactly pretty. - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { -namespace { - -// As mentioned above, I don't trust ctype.h due to the presence of "locales". -// So, I have written replacement functions here. Someone please smack me if -// this is a bad idea or if there is some way around this. -// -// These "character classes" are designed to be used in template methods. -// For instance, Tokenizer::ConsumeZeroOrMore() will eat -// whitespace. - -// Note: No class is allowed to contain '\0', since this is used to mark end- -// of-input and is handled specially. - -#define CHARACTER_CLASS(NAME, EXPRESSION) \ - class NAME { \ - public: \ - static inline bool InClass(char c) { \ - return EXPRESSION; \ - } \ - } - -CHARACTER_CLASS(Whitespace, c == ' ' || c == '\n' || c == '\t' || - c == '\r' || c == '\v' || c == '\f'); - -CHARACTER_CLASS(Unprintable, c < ' ' && c > '\0'); - -CHARACTER_CLASS(Digit, '0' <= c && c <= '9'); -CHARACTER_CLASS(OctalDigit, '0' <= c && c <= '7'); -CHARACTER_CLASS(HexDigit, ('0' <= c && c <= '9') || - ('a' <= c && c <= 'f') || - ('A' <= c && c <= 'F')); - -CHARACTER_CLASS(Letter, ('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - (c == '_')); - -CHARACTER_CLASS(Alphanumeric, ('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - ('0' <= c && c <= '9') || - (c == '_')); - -CHARACTER_CLASS(Escape, c == 'a' || c == 'b' || c == 'f' || c == 'n' || - c == 'r' || c == 't' || c == 'v' || c == '\\' || - c == '?' || c == '\'' || c == '\"'); - -#undef CHARACTER_CLASS - -// Given a char, interpret it as a numeric digit and return its value. -// This supports any number base up to 36. -inline int DigitValue(char digit) { - if ('0' <= digit && digit <= '9') return digit - '0'; - if ('a' <= digit && digit <= 'z') return digit - 'a' + 10; - if ('A' <= digit && digit <= 'Z') return digit - 'A' + 10; - return -1; -} - -// Inline because it's only used in one place. -inline char TranslateEscape(char c) { - switch (c) { - case 'a': return '\a'; - case 'b': return '\b'; - case 'f': return '\f'; - case 'n': return '\n'; - case 'r': return '\r'; - case 't': return '\t'; - case 'v': return '\v'; - case '\\': return '\\'; - case '?': return '\?'; // Trigraphs = :( - case '\'': return '\''; - case '"': return '\"'; - - // We expect escape sequences to have been validated separately. - default: return '?'; - } -} - -} // anonymous namespace - -ErrorCollector::~ErrorCollector() {} - -// =================================================================== - -Tokenizer::Tokenizer(ZeroCopyInputStream* input, - ErrorCollector* error_collector) - : input_(input), - error_collector_(error_collector), - buffer_(NULL), - buffer_size_(0), - buffer_pos_(0), - read_error_(false), - line_(0), - column_(0), - token_start_(-1), - allow_f_after_float_(false), - comment_style_(CPP_COMMENT_STYLE) { - - current_.line = 0; - current_.column = 0; - current_.type = TYPE_START; - - Refresh(); -} - -Tokenizer::~Tokenizer() { - // If we had any buffer left unread, return it to the underlying stream - // so that someone else can read it. - if (buffer_size_ > buffer_pos_) { - input_->BackUp(buffer_size_ - buffer_pos_); - } -} - -// ------------------------------------------------------------------- -// Internal helpers. - -void Tokenizer::NextChar() { - // Update our line and column counters based on the character being - // consumed. - if (current_char_ == '\n') { - ++line_; - column_ = 0; - } else if (current_char_ == '\t') { - column_ += kTabWidth - column_ % kTabWidth; - } else { - ++column_; - } - - // Advance to the next character. - ++buffer_pos_; - if (buffer_pos_ < buffer_size_) { - current_char_ = buffer_[buffer_pos_]; - } else { - Refresh(); - } -} - -void Tokenizer::Refresh() { - if (read_error_) { - current_char_ = '\0'; - return; - } - - // If we're in a token, append the rest of the buffer to it. - if (token_start_ >= 0 && token_start_ < buffer_size_) { - current_.text.append(buffer_ + token_start_, buffer_size_ - token_start_); - token_start_ = 0; - } - - const void* data = NULL; - buffer_ = NULL; - buffer_pos_ = 0; - do { - if (!input_->Next(&data, &buffer_size_)) { - // end of stream (or read error) - buffer_size_ = 0; - read_error_ = true; - current_char_ = '\0'; - return; - } - } while (buffer_size_ == 0); - - buffer_ = static_cast(data); - - current_char_ = buffer_[0]; -} - -inline void Tokenizer::StartToken() { - token_start_ = buffer_pos_; - current_.type = TYPE_START; // Just for the sake of initializing it. - current_.text.clear(); - current_.line = line_; - current_.column = column_; -} - -inline void Tokenizer::EndToken() { - // Note: The if() is necessary because some STL implementations crash when - // you call string::append(NULL, 0), presumably because they are trying to - // be helpful by detecting the NULL pointer, even though there's nothing - // wrong with reading zero bytes from NULL. - if (buffer_pos_ != token_start_) { - current_.text.append(buffer_ + token_start_, buffer_pos_ - token_start_); - } - token_start_ = -1; -} - -// ------------------------------------------------------------------- -// Helper methods that consume characters. - -template -inline bool Tokenizer::LookingAt() { - return CharacterClass::InClass(current_char_); -} - -template -inline bool Tokenizer::TryConsumeOne() { - if (CharacterClass::InClass(current_char_)) { - NextChar(); - return true; - } else { - return false; - } -} - -inline bool Tokenizer::TryConsume(char c) { - if (current_char_ == c) { - NextChar(); - return true; - } else { - return false; - } -} - -template -inline void Tokenizer::ConsumeZeroOrMore() { - while (CharacterClass::InClass(current_char_)) { - NextChar(); - } -} - -template -inline void Tokenizer::ConsumeOneOrMore(const char* error) { - if (!CharacterClass::InClass(current_char_)) { - AddError(error); - } else { - do { - NextChar(); - } while (CharacterClass::InClass(current_char_)); - } -} - -// ------------------------------------------------------------------- -// Methods that read whole patterns matching certain kinds of tokens -// or comments. - -void Tokenizer::ConsumeString(char delimiter) { - while (true) { - switch (current_char_) { - case '\0': - case '\n': { - AddError("String literals cannot cross line boundaries."); - return; - } - - case '\\': { - // An escape sequence. - NextChar(); - if (TryConsumeOne()) { - // Valid escape sequence. - } else if (TryConsumeOne()) { - // Possibly followed by two more octal digits, but these will - // just be consumed by the main loop anyway so we don't need - // to do so explicitly here. - } else if (TryConsume('x') || TryConsume('X')) { - if (!TryConsumeOne()) { - AddError("Expected hex digits for escape sequence."); - } - // Possibly followed by another hex digit, but again we don't care. - } else { - AddError("Invalid escape sequence in string literal."); - } - break; - } - - default: { - if (current_char_ == delimiter) { - NextChar(); - return; - } - NextChar(); - break; - } - } - } -} - -Tokenizer::TokenType Tokenizer::ConsumeNumber(bool started_with_zero, - bool started_with_dot) { - bool is_float = false; - - if (started_with_zero && (TryConsume('x') || TryConsume('X'))) { - // A hex number (started with "0x"). - ConsumeOneOrMore("\"0x\" must be followed by hex digits."); - - } else if (started_with_zero && LookingAt()) { - // An octal number (had a leading zero). - ConsumeZeroOrMore(); - if (LookingAt()) { - AddError("Numbers starting with leading zero must be in octal."); - ConsumeZeroOrMore(); - } - - } else { - // A decimal number. - if (started_with_dot) { - is_float = true; - ConsumeZeroOrMore(); - } else { - ConsumeZeroOrMore(); - - if (TryConsume('.')) { - is_float = true; - ConsumeZeroOrMore(); - } - } - - if (TryConsume('e') || TryConsume('E')) { - is_float = true; - TryConsume('-') || TryConsume('+'); - ConsumeOneOrMore("\"e\" must be followed by exponent."); - } - - if (allow_f_after_float_ && (TryConsume('f') || TryConsume('F'))) { - is_float = true; - } - } - - if (LookingAt()) { - AddError("Need space between number and identifier."); - } else if (current_char_ == '.') { - if (is_float) { - AddError( - "Already saw decimal point or exponent; can't have another one."); - } else { - AddError("Hex and octal numbers must be integers."); - } - } - - return is_float ? TYPE_FLOAT : TYPE_INTEGER; -} - -void Tokenizer::ConsumeLineComment() { - while (current_char_ != '\0' && current_char_ != '\n') { - NextChar(); - } - TryConsume('\n'); -} - -void Tokenizer::ConsumeBlockComment() { - int start_line = line_; - int start_column = column_ - 2; - - while (true) { - while (current_char_ != '\0' && - current_char_ != '*' && - current_char_ != '/') { - NextChar(); - } - - if (TryConsume('*') && TryConsume('/')) { - // End of comment. - break; - } else if (TryConsume('/') && current_char_ == '*') { - // Note: We didn't consume the '*' because if there is a '/' after it - // we want to interpret that as the end of the comment. - AddError( - "\"/*\" inside block comment. Block comments cannot be nested."); - } else if (current_char_ == '\0') { - AddError("End-of-file inside block comment."); - error_collector_->AddError( - start_line, start_column, " Comment started here."); - break; - } - } -} - -// ------------------------------------------------------------------- - -bool Tokenizer::Next() { - TokenType last_token_type = current_.type; - - // Did we skip any characters after the last token? - bool skipped_stuff = false; - - while (!read_error_) { - if (TryConsumeOne()) { - ConsumeZeroOrMore(); - - } else if (comment_style_ == CPP_COMMENT_STYLE && TryConsume('/')) { - // Starting a comment? - if (TryConsume('/')) { - ConsumeLineComment(); - } else if (TryConsume('*')) { - ConsumeBlockComment(); - } else { - // Oops, it was just a slash. Return it. - current_.type = TYPE_SYMBOL; - current_.text = "/"; - current_.line = line_; - current_.column = column_ - 1; - return true; - } - - } else if (comment_style_ == SH_COMMENT_STYLE && TryConsume('#')) { - ConsumeLineComment(); - - } else if (LookingAt() || current_char_ == '\0') { - AddError("Invalid control characters encountered in text."); - NextChar(); - // Skip more unprintable characters, too. But, remember that '\0' is - // also what current_char_ is set to after EOF / read error. We have - // to be careful not to go into an infinite loop of trying to consume - // it, so make sure to check read_error_ explicitly before consuming - // '\0'. - while (TryConsumeOne() || - (!read_error_ && TryConsume('\0'))) { - // Ignore. - } - - } else { - // Reading some sort of token. - StartToken(); - - if (TryConsumeOne()) { - ConsumeZeroOrMore(); - current_.type = TYPE_IDENTIFIER; - } else if (TryConsume('0')) { - current_.type = ConsumeNumber(true, false); - } else if (TryConsume('.')) { - // This could be the beginning of a floating-point number, or it could - // just be a '.' symbol. - - if (TryConsumeOne()) { - // It's a floating-point number. - if (last_token_type == TYPE_IDENTIFIER && !skipped_stuff) { - // We don't accept syntax like "blah.123". - error_collector_->AddError(line_, column_ - 2, - "Need space between identifier and decimal point."); - } - current_.type = ConsumeNumber(false, true); - } else { - current_.type = TYPE_SYMBOL; - } - } else if (TryConsumeOne()) { - current_.type = ConsumeNumber(false, false); - } else if (TryConsume('\"')) { - ConsumeString('\"'); - current_.type = TYPE_STRING; - } else if (TryConsume('\'')) { - ConsumeString('\''); - current_.type = TYPE_STRING; - } else { - NextChar(); - current_.type = TYPE_SYMBOL; - } - - EndToken(); - return true; - } - - skipped_stuff = true; - } - - // EOF - current_.type = TYPE_END; - current_.text.clear(); - current_.line = line_; - current_.column = column_; - return false; -} - -// ------------------------------------------------------------------- -// Token-parsing helpers. Remember that these don't need to report -// errors since any errors should already have been reported while -// tokenizing. Also, these can assume that whatever text they -// are given is text that the tokenizer actually parsed as a token -// of the given type. - -bool Tokenizer::ParseInteger(const string& text, uint64 max_value, - uint64* output) { - // Sadly, we can't just use strtoul() since it is only 32-bit and strtoull() - // is non-standard. I hate the C standard library. :( - -// return strtoull(text.c_str(), NULL, 0); - - const char* ptr = text.c_str(); - int base = 10; - if (ptr[0] == '0') { - if (ptr[1] == 'x' || ptr[1] == 'X') { - // This is hex. - base = 16; - ptr += 2; - } else { - // This is octal. - base = 8; - } - } - - uint64 result = 0; - for (; *ptr != '\0'; ptr++) { - int digit = DigitValue(*ptr); - GOOGLE_LOG_IF(DFATAL, digit < 0 || digit >= base) - << " Tokenizer::ParseInteger() passed text that could not have been" - " tokenized as an integer: " << CEscape(text); - if (digit > max_value || result > (max_value - digit) / base) { - // Overflow. - return false; - } - result = result * base + digit; - } - - *output = result; - return true; -} - -double Tokenizer::ParseFloat(const string& text) { - const char* start = text.c_str(); - char* end; - double result = NoLocaleStrtod(start, &end); - - // "1e" is not a valid float, but if the tokenizer reads it, it will - // report an error but still return it as a valid token. We need to - // accept anything the tokenizer could possibly return, error or not. - if (*end == 'e' || *end == 'E') { - ++end; - if (*end == '-' || *end == '+') ++end; - } - - // If the Tokenizer had allow_f_after_float_ enabled, the float may be - // suffixed with the letter 'f'. - if (*end == 'f' || *end == 'F') { - ++end; - } - - GOOGLE_LOG_IF(DFATAL, end - start != text.size() || *start == '-') - << " Tokenizer::ParseFloat() passed text that could not have been" - " tokenized as a float: " << CEscape(text); - return result; -} - -void Tokenizer::ParseStringAppend(const string& text, string* output) { - // Reminder: text[0] is always the quote character. (If text is - // empty, it's invalid, so we'll just return.) - if (text.empty()) { - GOOGLE_LOG(DFATAL) - << " Tokenizer::ParseStringAppend() passed text that could not" - " have been tokenized as a string: " << CEscape(text); - return; - } - - output->reserve(output->size() + text.size()); - - // Loop through the string copying characters to "output" and - // interpreting escape sequences. Note that any invalid escape - // sequences or other errors were already reported while tokenizing. - // In this case we do not need to produce valid results. - for (const char* ptr = text.c_str() + 1; *ptr != '\0'; ptr++) { - if (*ptr == '\\' && ptr[1] != '\0') { - // An escape sequence. - ++ptr; - - if (OctalDigit::InClass(*ptr)) { - // An octal escape. May one, two, or three digits. - int code = DigitValue(*ptr); - if (OctalDigit::InClass(ptr[1])) { - ++ptr; - code = code * 8 + DigitValue(*ptr); - } - if (OctalDigit::InClass(ptr[1])) { - ++ptr; - code = code * 8 + DigitValue(*ptr); - } - output->push_back(static_cast(code)); - - } else if (*ptr == 'x') { - // A hex escape. May zero, one, or two digits. (The zero case - // will have been caught as an error earlier.) - int code = 0; - if (HexDigit::InClass(ptr[1])) { - ++ptr; - code = DigitValue(*ptr); - } - if (HexDigit::InClass(ptr[1])) { - ++ptr; - code = code * 16 + DigitValue(*ptr); - } - output->push_back(static_cast(code)); - - } else { - // Some other escape code. - output->push_back(TranslateEscape(*ptr)); - } - - } else if (*ptr == text[0]) { - // Ignore quote matching the starting quote. - } else { - output->push_back(*ptr); - } - } - - return; -} - -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/tokenizer.h b/Resources/NetHook/google/protobuf/io/tokenizer.h deleted file mode 100644 index d115161f..00000000 --- a/Resources/NetHook/google/protobuf/io/tokenizer.h +++ /dev/null @@ -1,303 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Class for parsing tokenized text from a ZeroCopyInputStream. - -#ifndef GOOGLE_PROTOBUF_IO_TOKENIZER_H__ -#define GOOGLE_PROTOBUF_IO_TOKENIZER_H__ - -#include -#include - -namespace google { -namespace protobuf { -namespace io { - -class ZeroCopyInputStream; // zero_copy_stream.h - -// Defined in this file. -class ErrorCollector; -class Tokenizer; - -// Abstract interface for an object which collects the errors that occur -// during parsing. A typical implementation might simply print the errors -// to stdout. -class LIBPROTOBUF_EXPORT ErrorCollector { - public: - inline ErrorCollector() {} - virtual ~ErrorCollector(); - - // Indicates that there was an error in the input at the given line and - // column numbers. The numbers are zero-based, so you may want to add - // 1 to each before printing them. - virtual void AddError(int line, int column, const string& message) = 0; - - // Indicates that there was a warning in the input at the given line and - // column numbers. The numbers are zero-based, so you may want to add - // 1 to each before printing them. - virtual void AddWarning(int line, int column, const string& message) { } - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ErrorCollector); -}; - -// This class converts a stream of raw text into a stream of tokens for -// the protocol definition parser to parse. The tokens recognized are -// similar to those that make up the C language; see the TokenType enum for -// precise descriptions. Whitespace and comments are skipped. By default, -// C- and C++-style comments are recognized, but other styles can be used by -// calling set_comment_style(). -class LIBPROTOBUF_EXPORT Tokenizer { - public: - // Construct a Tokenizer that reads and tokenizes text from the given - // input stream and writes errors to the given error_collector. - // The caller keeps ownership of input and error_collector. - Tokenizer(ZeroCopyInputStream* input, ErrorCollector* error_collector); - ~Tokenizer(); - - enum TokenType { - TYPE_START, // Next() has not yet been called. - TYPE_END, // End of input reached. "text" is empty. - - TYPE_IDENTIFIER, // A sequence of letters, digits, and underscores, not - // starting with a digit. It is an error for a number - // to be followed by an identifier with no space in - // between. - TYPE_INTEGER, // A sequence of digits representing an integer. Normally - // the digits are decimal, but a prefix of "0x" indicates - // a hex number and a leading zero indicates octal, just - // like with C numeric literals. A leading negative sign - // is NOT included in the token; it's up to the parser to - // interpret the unary minus operator on its own. - TYPE_FLOAT, // A floating point literal, with a fractional part and/or - // an exponent. Always in decimal. Again, never - // negative. - TYPE_STRING, // A quoted sequence of escaped characters. Either single - // or double quotes can be used, but they must match. - // A string literal cannot cross a line break. - TYPE_SYMBOL, // Any other printable character, like '!' or '+'. - // Symbols are always a single character, so "!+$%" is - // four tokens. - }; - - // Structure representing a token read from the token stream. - struct Token { - TokenType type; - string text; // The exact text of the token as it appeared in - // the input. e.g. tokens of TYPE_STRING will still - // be escaped and in quotes. - - // "line" and "column" specify the position of the first character of - // the token within the input stream. They are zero-based. - int line; - int column; - }; - - // Get the current token. This is updated when Next() is called. Before - // the first call to Next(), current() has type TYPE_START and no contents. - const Token& current(); - - // Advance to the next token. Returns false if the end of the input is - // reached. - bool Next(); - - // Parse helpers --------------------------------------------------- - - // Parses a TYPE_FLOAT token. This never fails, so long as the text actually - // comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the - // result is undefined (possibly an assert failure). - static double ParseFloat(const string& text); - - // Parses a TYPE_STRING token. This never fails, so long as the text actually - // comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the - // result is undefined (possibly an assert failure). - static void ParseString(const string& text, string* output); - - // Identical to ParseString, but appends to output. - static void ParseStringAppend(const string& text, string* output); - - // Parses a TYPE_INTEGER token. Returns false if the result would be - // greater than max_value. Otherwise, returns true and sets *output to the - // result. If the text is not from a Token of type TYPE_INTEGER originally - // parsed by a Tokenizer, the result is undefined (possibly an assert - // failure). - static bool ParseInteger(const string& text, uint64 max_value, - uint64* output); - - // Options --------------------------------------------------------- - - // Set true to allow floats to be suffixed with the letter 'f'. Tokens - // which would otherwise be integers but which have the 'f' suffix will be - // forced to be interpreted as floats. For all other purposes, the 'f' is - // ignored. - void set_allow_f_after_float(bool value) { allow_f_after_float_ = value; } - - // Valid values for set_comment_style(). - enum CommentStyle { - // Line comments begin with "//", block comments are delimited by "/*" and - // "*/". - CPP_COMMENT_STYLE, - // Line comments begin with "#". No way to write block comments. - SH_COMMENT_STYLE - }; - - // Sets the comment style. - void set_comment_style(CommentStyle style) { comment_style_ = style; } - - // ----------------------------------------------------------------- - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Tokenizer); - - Token current_; // Returned by current(). - - ZeroCopyInputStream* input_; - ErrorCollector* error_collector_; - - char current_char_; // == buffer_[buffer_pos_], updated by NextChar(). - const char* buffer_; // Current buffer returned from input_. - int buffer_size_; // Size of buffer_. - int buffer_pos_; // Current position within the buffer. - bool read_error_; // Did we previously encounter a read error? - - // Line and column number of current_char_ within the whole input stream. - int line_; - int column_; - - // Position in buffer_ where StartToken() was called. If the token - // started in the previous buffer, this is zero, and current_.text already - // contains the part of the token from the previous buffer. If not - // currently parsing a token, this is -1. - int token_start_; - - // Options. - bool allow_f_after_float_; - CommentStyle comment_style_; - - // Since we count columns we need to interpret tabs somehow. We'll take - // the standard 8-character definition for lack of any way to do better. - static const int kTabWidth = 8; - - // ----------------------------------------------------------------- - // Helper methods. - - // Consume this character and advance to the next one. - void NextChar(); - - // Read a new buffer from the input. - void Refresh(); - - // Called when the current character is the first character of a new - // token (not including whitespace or comments). - inline void StartToken(); - // Called when the current character is the first character after the - // end of the last token. After this returns, current_.text will - // contain all text consumed since StartToken() was called. - inline void EndToken(); - - // Convenience method to add an error at the current line and column. - void AddError(const string& message) { - error_collector_->AddError(line_, column_, message); - } - - // ----------------------------------------------------------------- - // The following four methods are used to consume tokens of specific - // types. They are actually used to consume all characters *after* - // the first, since the calling function consumes the first character - // in order to decide what kind of token is being read. - - // Read and consume a string, ending when the given delimiter is - // consumed. - void ConsumeString(char delimiter); - - // Read and consume a number, returning TYPE_FLOAT or TYPE_INTEGER - // depending on what was read. This needs to know if the first - // character was a zero in order to correctly recognize hex and octal - // numbers. - // It also needs to know if the first characted was a . to parse floating - // point correctly. - TokenType ConsumeNumber(bool started_with_zero, bool started_with_dot); - - // Consume the rest of a line. - void ConsumeLineComment(); - // Consume until "*/". - void ConsumeBlockComment(); - - // ----------------------------------------------------------------- - // These helper methods make the parsing code more readable. The - // "character classes" refered to are defined at the top of the .cc file. - // Basically it is a C++ class with one method: - // static bool InClass(char c); - // The method returns true if c is a member of this "class", like "Letter" - // or "Digit". - - // Returns true if the current character is of the given character - // class, but does not consume anything. - template - inline bool LookingAt(); - - // If the current character is in the given class, consume it and return - // true. Otherwise return false. - // e.g. TryConsumeOne() - template - inline bool TryConsumeOne(); - - // Like above, but try to consume the specific character indicated. - inline bool TryConsume(char c); - - // Consume zero or more of the given character class. - template - inline void ConsumeZeroOrMore(); - - // Consume one or more of the given character class or log the given - // error message. - // e.g. ConsumeOneOrMore("Expected digits."); - template - inline void ConsumeOneOrMore(const char* error); -}; - -// inline methods ==================================================== -inline const Tokenizer::Token& Tokenizer::current() { - return current_; -} - -inline void Tokenizer::ParseString(const string& text, string* output) { - output->clear(); - ParseStringAppend(text, output); -} - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_TOKENIZER_H__ diff --git a/Resources/NetHook/google/protobuf/io/tokenizer_unittest.cc b/Resources/NetHook/google/protobuf/io/tokenizer_unittest.cc deleted file mode 100644 index 358ec567..00000000 --- a/Resources/NetHook/google/protobuf/io/tokenizer_unittest.cc +++ /dev/null @@ -1,743 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { -namespace { - -// =================================================================== -// Data-Driven Test Infrastructure - -// TODO(kenton): This is copied from coded_stream_unittest. This is -// temporary until these fetaures are integrated into gTest itself. - -// TEST_1D and TEST_2D are macros I'd eventually like to see added to -// gTest. These macros can be used to declare tests which should be -// run multiple times, once for each item in some input array. TEST_1D -// tests all cases in a single input array. TEST_2D tests all -// combinations of cases from two arrays. The arrays must be statically -// defined such that the GOOGLE_ARRAYSIZE() macro works on them. Example: -// -// int kCases[] = {1, 2, 3, 4} -// TEST_1D(MyFixture, MyTest, kCases) { -// EXPECT_GT(kCases_case, 0); -// } -// -// This test iterates through the numbers 1, 2, 3, and 4 and tests that -// they are all grater than zero. In case of failure, the exact case -// which failed will be printed. The case type must be printable using -// ostream::operator<<. - -#define TEST_1D(FIXTURE, NAME, CASES) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType& CASES##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES); i++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES " case #" << i << ": " << CASES[i]); \ - DoSingleCase(CASES[i]); \ - } \ - } \ - \ - template \ - void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType& CASES##_case) - -#define TEST_2D(FIXTURE, NAME, CASES1, CASES2) \ - class FIXTURE##_##NAME##_DD : public FIXTURE { \ - protected: \ - template \ - void DoSingleCase(const CaseType1& CASES1##_case, \ - const CaseType2& CASES2##_case); \ - }; \ - \ - TEST_F(FIXTURE##_##NAME##_DD, NAME) { \ - for (int i = 0; i < GOOGLE_ARRAYSIZE(CASES1); i++) { \ - for (int j = 0; j < GOOGLE_ARRAYSIZE(CASES2); j++) { \ - SCOPED_TRACE(testing::Message() \ - << #CASES1 " case #" << i << ": " << CASES1[i] << ", " \ - << #CASES2 " case #" << j << ": " << CASES2[j]); \ - DoSingleCase(CASES1[i], CASES2[j]); \ - } \ - } \ - } \ - \ - template \ - void FIXTURE##_##NAME##_DD::DoSingleCase(const CaseType1& CASES1##_case, \ - const CaseType2& CASES2##_case) - -// ------------------------------------------------------------------- - -// An input stream that is basically like an ArrayInputStream but sometimes -// returns empty buffers, just to throw us off. -class TestInputStream : public ZeroCopyInputStream { - public: - TestInputStream(const void* data, int size, int block_size) - : array_stream_(data, size, block_size), counter_(0) {} - ~TestInputStream() {} - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size) { - // We'll return empty buffers starting with the first buffer, and every - // 3 and 5 buffers after that. - if (counter_ % 3 == 0 || counter_ % 5 == 0) { - *data = NULL; - *size = 0; - ++counter_; - return true; - } else { - ++counter_; - return array_stream_.Next(data, size); - } - } - - void BackUp(int count) { return array_stream_.BackUp(count); } - bool Skip(int count) { return array_stream_.Skip(count); } - int64 ByteCount() const { return array_stream_.ByteCount(); } - - private: - ArrayInputStream array_stream_; - int counter_; -}; - -// ------------------------------------------------------------------- - -// An error collector which simply concatenates all its errors into a big -// block of text which can be checked. -class TestErrorCollector : public ErrorCollector { - public: - TestErrorCollector() {} - ~TestErrorCollector() {} - - string text_; - - // implements ErrorCollector --------------------------------------- - void AddError(int line, int column, const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", - line, column, message); - } -}; - -// ------------------------------------------------------------------- - -// We test each operation over a variety of block sizes to insure that -// we test cases where reads cross buffer boundaries as well as cases -// where they don't. This is sort of a brute-force approach to this, -// but it's easy to write and easy to understand. -const int kBlockSizes[] = {1, 2, 3, 5, 7, 13, 32, 1024}; - -class TokenizerTest : public testing::Test { - protected: - // For easy testing. - uint64 ParseInteger(const string& text) { - uint64 result; - EXPECT_TRUE(Tokenizer::ParseInteger(text, kuint64max, &result)); - return result; - } -}; - -// =================================================================== - -// These tests causes gcc 3.3.5 (and earlier?) to give the cryptic error: -// "sorry, unimplemented: `method_call_expr' not supported by dump_expr" -#if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) - -// In each test case, the entire input text should parse as a single token -// of the given type. -struct SimpleTokenCase { - string input; - Tokenizer::TokenType type; -}; - -inline ostream& operator<<(ostream& out, - const SimpleTokenCase& test_case) { - return out << CEscape(test_case.input); -} - -SimpleTokenCase kSimpleTokenCases[] = { - // Test identifiers. - { "hello", Tokenizer::TYPE_IDENTIFIER }, - - // Test integers. - { "123", Tokenizer::TYPE_INTEGER }, - { "0xab6", Tokenizer::TYPE_INTEGER }, - { "0XAB6", Tokenizer::TYPE_INTEGER }, - { "0X1234567", Tokenizer::TYPE_INTEGER }, - { "0x89abcdef", Tokenizer::TYPE_INTEGER }, - { "0x89ABCDEF", Tokenizer::TYPE_INTEGER }, - { "01234567", Tokenizer::TYPE_INTEGER }, - - // Test floats. - { "123.45", Tokenizer::TYPE_FLOAT }, - { "1.", Tokenizer::TYPE_FLOAT }, - { "1e3", Tokenizer::TYPE_FLOAT }, - { "1E3", Tokenizer::TYPE_FLOAT }, - { "1e-3", Tokenizer::TYPE_FLOAT }, - { "1e+3", Tokenizer::TYPE_FLOAT }, - { "1.e3", Tokenizer::TYPE_FLOAT }, - { "1.2e3", Tokenizer::TYPE_FLOAT }, - { ".1", Tokenizer::TYPE_FLOAT }, - { ".1e3", Tokenizer::TYPE_FLOAT }, - { ".1e-3", Tokenizer::TYPE_FLOAT }, - { ".1e+3", Tokenizer::TYPE_FLOAT }, - - // Test strings. - { "'hello'", Tokenizer::TYPE_STRING }, - { "\"foo\"", Tokenizer::TYPE_STRING }, - { "'a\"b'", Tokenizer::TYPE_STRING }, - { "\"a'b\"", Tokenizer::TYPE_STRING }, - { "'a\\'b'", Tokenizer::TYPE_STRING }, - { "\"a\\\"b\"", Tokenizer::TYPE_STRING }, - { "'\\xf'", Tokenizer::TYPE_STRING }, - { "'\\0'", Tokenizer::TYPE_STRING }, - - // Test symbols. - { "+", Tokenizer::TYPE_SYMBOL }, - { ".", Tokenizer::TYPE_SYMBOL }, -}; - -TEST_2D(TokenizerTest, SimpleTokens, kSimpleTokenCases, kBlockSizes) { - // Set up the tokenizer. - TestInputStream input(kSimpleTokenCases_case.input.data(), - kSimpleTokenCases_case.input.size(), - kBlockSizes_case); - TestErrorCollector error_collector; - Tokenizer tokenizer(&input, &error_collector); - - // Before Next() is called, the initial token should always be TYPE_START. - EXPECT_EQ(Tokenizer::TYPE_START, tokenizer.current().type); - EXPECT_EQ("", tokenizer.current().text); - EXPECT_EQ(0, tokenizer.current().line); - EXPECT_EQ(0, tokenizer.current().column); - - // Parse the token. - ASSERT_TRUE(tokenizer.Next()); - - // Check that it has the right type. - EXPECT_EQ(kSimpleTokenCases_case.type, tokenizer.current().type); - // Check that it contains the complete input text. - EXPECT_EQ(kSimpleTokenCases_case.input, tokenizer.current().text); - // Check that it is located at the beginning of the input - EXPECT_EQ(0, tokenizer.current().line); - EXPECT_EQ(0, tokenizer.current().column); - - // There should be no more input. - EXPECT_FALSE(tokenizer.Next()); - - // After Next() returns false, the token should have type TYPE_END. - EXPECT_EQ(Tokenizer::TYPE_END, tokenizer.current().type); - EXPECT_EQ("", tokenizer.current().text); - EXPECT_EQ(0, tokenizer.current().line); - EXPECT_EQ(kSimpleTokenCases_case.input.size(), tokenizer.current().column); - - // There should be no errors. - EXPECT_TRUE(error_collector.text_.empty()); -} - -TEST_1D(TokenizerTest, FloatSuffix, kBlockSizes) { - // Test the "allow_f_after_float" option. - - // Set up the tokenizer. - const char* text = "1f 2.5f 6e3f 7F"; - TestInputStream input(text, strlen(text), kBlockSizes_case); - TestErrorCollector error_collector; - Tokenizer tokenizer(&input, &error_collector); - tokenizer.set_allow_f_after_float(true); - - // Advance through tokens and check that they are parsed as expected. - ASSERT_TRUE(tokenizer.Next()); - EXPECT_EQ(tokenizer.current().text, "1f"); - EXPECT_EQ(tokenizer.current().type, Tokenizer::TYPE_FLOAT); - ASSERT_TRUE(tokenizer.Next()); - EXPECT_EQ(tokenizer.current().text, "2.5f"); - EXPECT_EQ(tokenizer.current().type, Tokenizer::TYPE_FLOAT); - ASSERT_TRUE(tokenizer.Next()); - EXPECT_EQ(tokenizer.current().text, "6e3f"); - EXPECT_EQ(tokenizer.current().type, Tokenizer::TYPE_FLOAT); - ASSERT_TRUE(tokenizer.Next()); - EXPECT_EQ(tokenizer.current().text, "7F"); - EXPECT_EQ(tokenizer.current().type, Tokenizer::TYPE_FLOAT); - - // There should be no more input. - EXPECT_FALSE(tokenizer.Next()); - // There should be no errors. - EXPECT_TRUE(error_collector.text_.empty()); -} - -#endif - -// ------------------------------------------------------------------- - -// In each case, the input is parsed to produce a list of tokens. The -// last token in "output" must have type TYPE_END. -struct MultiTokenCase { - string input; - Tokenizer::Token output[10]; // The compiler wants a constant array - // size for initialization to work. There - // is no reason this can't be increased if - // needed. -}; - -inline ostream& operator<<(ostream& out, - const MultiTokenCase& test_case) { - return out << CEscape(test_case.input); -} - -MultiTokenCase kMultiTokenCases[] = { - // Test empty input. - { "", { - { Tokenizer::TYPE_END , "" , 0, 0 }, - }}, - - // Test all token types at the same time. - { "foo 1 1.2 + 'bar'", { - { Tokenizer::TYPE_IDENTIFIER, "foo" , 0, 0 }, - { Tokenizer::TYPE_INTEGER , "1" , 0, 4 }, - { Tokenizer::TYPE_FLOAT , "1.2" , 0, 6 }, - { Tokenizer::TYPE_SYMBOL , "+" , 0, 10 }, - { Tokenizer::TYPE_STRING , "'bar'", 0, 12 }, - { Tokenizer::TYPE_END , "" , 0, 17 }, - }}, - - // Test that consecutive symbols are parsed as separate tokens. - { "!@+%", { - { Tokenizer::TYPE_SYMBOL , "!" , 0, 0 }, - { Tokenizer::TYPE_SYMBOL , "@" , 0, 1 }, - { Tokenizer::TYPE_SYMBOL , "+" , 0, 2 }, - { Tokenizer::TYPE_SYMBOL , "%" , 0, 3 }, - { Tokenizer::TYPE_END , "" , 0, 4 }, - }}, - - // Test that newlines affect line numbers correctly. - { "foo bar\nrab oof", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 4 }, - { Tokenizer::TYPE_IDENTIFIER, "rab", 1, 0 }, - { Tokenizer::TYPE_IDENTIFIER, "oof", 1, 4 }, - { Tokenizer::TYPE_END , "" , 1, 7 }, - }}, - - // Test that tabs affect column numbers correctly. - { "foo\tbar \tbaz", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 8 }, - { Tokenizer::TYPE_IDENTIFIER, "baz", 0, 16 }, - { Tokenizer::TYPE_END , "" , 0, 19 }, - }}, - - // Test that line comments are ignored. - { "foo // This is a comment\n" - "bar // This is another comment", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 1, 0 }, - { Tokenizer::TYPE_END , "" , 1, 30 }, - }}, - - // Test that block comments are ignored. - { "foo /* This is a block comment */ bar", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 34 }, - { Tokenizer::TYPE_END , "" , 0, 37 }, - }}, - - // Test that sh-style comments are not ignored by default. - { "foo # bar\n" - "baz", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0 }, - { Tokenizer::TYPE_SYMBOL , "#" , 0, 4 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 0, 6 }, - { Tokenizer::TYPE_IDENTIFIER, "baz", 1, 0 }, - { Tokenizer::TYPE_END , "" , 1, 3 }, - }}, - - // Bytes with the high-order bit set should not be seen as control characters. - { "\300", { - { Tokenizer::TYPE_SYMBOL, "\300", 0, 0 }, - { Tokenizer::TYPE_END , "" , 0, 1 }, - }}, - - // Test all whitespace chars - { "foo\n\t\r\v\fbar", { - { Tokenizer::TYPE_IDENTIFIER, "foo", 0, 0 }, - { Tokenizer::TYPE_IDENTIFIER, "bar", 1, 11 }, - { Tokenizer::TYPE_END , "" , 1, 14 }, - }}, -}; - -TEST_2D(TokenizerTest, MultipleTokens, kMultiTokenCases, kBlockSizes) { - // Set up the tokenizer. - TestInputStream input(kMultiTokenCases_case.input.data(), - kMultiTokenCases_case.input.size(), - kBlockSizes_case); - TestErrorCollector error_collector; - Tokenizer tokenizer(&input, &error_collector); - - // Before Next() is called, the initial token should always be TYPE_START. - EXPECT_EQ(Tokenizer::TYPE_START, tokenizer.current().type); - EXPECT_EQ("", tokenizer.current().text); - EXPECT_EQ(0, tokenizer.current().line); - EXPECT_EQ(0, tokenizer.current().column); - - // Loop through all expected tokens. - int i = 0; - Tokenizer::Token token; - do { - token = kMultiTokenCases_case.output[i++]; - - SCOPED_TRACE(testing::Message() << "Token #" << i << ": " << token.text); - - // Next() should only return false when it hits the end token. - if (token.type != Tokenizer::TYPE_END) { - ASSERT_TRUE(tokenizer.Next()); - } else { - ASSERT_FALSE(tokenizer.Next()); - } - - // Check that the token matches the expected one. - EXPECT_EQ(token.type, tokenizer.current().type); - EXPECT_EQ(token.text, tokenizer.current().text); - EXPECT_EQ(token.line, tokenizer.current().line); - EXPECT_EQ(token.column, tokenizer.current().column); - - } while (token.type != Tokenizer::TYPE_END); - - // There should be no errors. - EXPECT_TRUE(error_collector.text_.empty()); -} - -// This test causes gcc 3.3.5 (and earlier?) to give the cryptic error: -// "sorry, unimplemented: `method_call_expr' not supported by dump_expr" -#if !defined(__GNUC__) || __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 3) - -TEST_1D(TokenizerTest, ShCommentStyle, kBlockSizes) { - // Test the "comment_style" option. - - const char* text = "foo # bar\n" - "baz // qux\n" - "corge /* grault */\n" - "garply"; - const char* const kTokens[] = {"foo", // "# bar" is ignored - "baz", "/", "/", "qux", - "corge", "/", "*", "grault", "*", "/", - "garply"}; - - // Set up the tokenizer. - TestInputStream input(text, strlen(text), kBlockSizes_case); - TestErrorCollector error_collector; - Tokenizer tokenizer(&input, &error_collector); - tokenizer.set_comment_style(Tokenizer::SH_COMMENT_STYLE); - - // Advance through tokens and check that they are parsed as expected. - for (int i = 0; i < GOOGLE_ARRAYSIZE(kTokens); i++) { - EXPECT_TRUE(tokenizer.Next()); - EXPECT_EQ(tokenizer.current().text, kTokens[i]); - } - - // There should be no more input. - EXPECT_FALSE(tokenizer.Next()); - // There should be no errors. - EXPECT_TRUE(error_collector.text_.empty()); -} - -#endif - -// ------------------------------------------------------------------- - -// Test parse helpers. It's not really worth setting up a full data-driven -// test here. -TEST_F(TokenizerTest, ParseInteger) { - EXPECT_EQ(0, ParseInteger("0")); - EXPECT_EQ(123, ParseInteger("123")); - EXPECT_EQ(0xabcdef12u, ParseInteger("0xabcdef12")); - EXPECT_EQ(0xabcdef12u, ParseInteger("0xABCDEF12")); - EXPECT_EQ(kuint64max, ParseInteger("0xFFFFFFFFFFFFFFFF")); - EXPECT_EQ(01234567, ParseInteger("01234567")); - EXPECT_EQ(0X123, ParseInteger("0X123")); - - // Test invalid integers that may still be tokenized as integers. - EXPECT_EQ(0, ParseInteger("0x")); - - uint64 i; -#ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet - // Test invalid integers that will never be tokenized as integers. - EXPECT_DEBUG_DEATH(Tokenizer::ParseInteger("zxy", kuint64max, &i), - "passed text that could not have been tokenized as an integer"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseInteger("1.2", kuint64max, &i), - "passed text that could not have been tokenized as an integer"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseInteger("08", kuint64max, &i), - "passed text that could not have been tokenized as an integer"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseInteger("0xg", kuint64max, &i), - "passed text that could not have been tokenized as an integer"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseInteger("-1", kuint64max, &i), - "passed text that could not have been tokenized as an integer"); -#endif // GTEST_HAS_DEATH_TEST - - // Test overflows. - EXPECT_TRUE (Tokenizer::ParseInteger("0", 0, &i)); - EXPECT_FALSE(Tokenizer::ParseInteger("1", 0, &i)); - EXPECT_TRUE (Tokenizer::ParseInteger("1", 1, &i)); - EXPECT_TRUE (Tokenizer::ParseInteger("12345", 12345, &i)); - EXPECT_FALSE(Tokenizer::ParseInteger("12346", 12345, &i)); - EXPECT_TRUE (Tokenizer::ParseInteger("0xFFFFFFFFFFFFFFFF" , kuint64max, &i)); - EXPECT_FALSE(Tokenizer::ParseInteger("0x10000000000000000", kuint64max, &i)); -} - -TEST_F(TokenizerTest, ParseFloat) { - EXPECT_DOUBLE_EQ(1 , Tokenizer::ParseFloat("1.")); - EXPECT_DOUBLE_EQ(1e3 , Tokenizer::ParseFloat("1e3")); - EXPECT_DOUBLE_EQ(1e3 , Tokenizer::ParseFloat("1E3")); - EXPECT_DOUBLE_EQ(1.5e3, Tokenizer::ParseFloat("1.5e3")); - EXPECT_DOUBLE_EQ(.1 , Tokenizer::ParseFloat(".1")); - EXPECT_DOUBLE_EQ(.25 , Tokenizer::ParseFloat(".25")); - EXPECT_DOUBLE_EQ(.1e3 , Tokenizer::ParseFloat(".1e3")); - EXPECT_DOUBLE_EQ(.25e3, Tokenizer::ParseFloat(".25e3")); - EXPECT_DOUBLE_EQ(.1e+3, Tokenizer::ParseFloat(".1e+3")); - EXPECT_DOUBLE_EQ(.1e-3, Tokenizer::ParseFloat(".1e-3")); - EXPECT_DOUBLE_EQ(5 , Tokenizer::ParseFloat("5")); - EXPECT_DOUBLE_EQ(6e-12, Tokenizer::ParseFloat("6e-12")); - EXPECT_DOUBLE_EQ(1.2 , Tokenizer::ParseFloat("1.2")); - EXPECT_DOUBLE_EQ(1.e2 , Tokenizer::ParseFloat("1.e2")); - - // Test invalid integers that may still be tokenized as integers. - EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1e")); - EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1e-")); - EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1.e")); - - // Test 'f' suffix. - EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1f")); - EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1.0f")); - EXPECT_DOUBLE_EQ(1, Tokenizer::ParseFloat("1F")); - - // These should parse successfully even though they are out of range. - // Overflows become infinity and underflows become zero. - EXPECT_EQ( 0.0, Tokenizer::ParseFloat("1e-9999999999999999999999999999")); - EXPECT_EQ(HUGE_VAL, Tokenizer::ParseFloat("1e+9999999999999999999999999999")); - -#ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet - // Test invalid integers that will never be tokenized as integers. - EXPECT_DEBUG_DEATH(Tokenizer::ParseFloat("zxy"), - "passed text that could not have been tokenized as a float"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseFloat("1-e0"), - "passed text that could not have been tokenized as a float"); - EXPECT_DEBUG_DEATH(Tokenizer::ParseFloat("-1.0"), - "passed text that could not have been tokenized as a float"); -#endif // GTEST_HAS_DEATH_TEST -} - -TEST_F(TokenizerTest, ParseString) { - string output; - Tokenizer::ParseString("'hello'", &output); - EXPECT_EQ("hello", output); - Tokenizer::ParseString("\"blah\\nblah2\"", &output); - EXPECT_EQ("blah\nblah2", output); - Tokenizer::ParseString("'\\1x\\1\\123\\739\\52\\334n\\3'", &output); - EXPECT_EQ("\1x\1\123\739\52\334n\3", output); - Tokenizer::ParseString("'\\x20\\x4'", &output); - EXPECT_EQ("\x20\x4", output); - - // Test invalid strings that may still be tokenized as strings. - Tokenizer::ParseString("\"\\a\\l\\v\\t", &output); // \l is invalid - EXPECT_EQ("\a?\v\t", output); - Tokenizer::ParseString("'", &output); - EXPECT_EQ("", output); - Tokenizer::ParseString("'\\", &output); - EXPECT_EQ("\\", output); - - // Test invalid strings that will never be tokenized as strings. -#ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet - EXPECT_DEBUG_DEATH(Tokenizer::ParseString("", &output), - "passed text that could not have been tokenized as a string"); -#endif // GTEST_HAS_DEATH_TEST -} - -TEST_F(TokenizerTest, ParseStringAppend) { - // Check that ParseString and ParseStringAppend differ. - string output("stuff+"); - Tokenizer::ParseStringAppend("'hello'", &output); - EXPECT_EQ("stuff+hello", output); - Tokenizer::ParseString("'hello'", &output); - EXPECT_EQ("hello", output); -} - -// ------------------------------------------------------------------- - -// Each case parses some input text, ignoring the tokens produced, and -// checks that the error output matches what is expected. -struct ErrorCase { - string input; - bool recoverable; // True if the tokenizer should be able to recover and - // parse more tokens after seeing this error. Cases - // for which this is true must end with "foo" as - // the last token, which the test will check for. - const char* errors; -}; - -inline ostream& operator<<(ostream& out, - const ErrorCase& test_case) { - return out << CEscape(test_case.input); -} - -ErrorCase kErrorCases[] = { - // String errors. - { "'\\l' foo", true, - "0:2: Invalid escape sequence in string literal.\n" }, - { "'\\x' foo", true, - "0:3: Expected hex digits for escape sequence.\n" }, - { "'foo", false, - "0:4: String literals cannot cross line boundaries.\n" }, - { "'bar\nfoo", true, - "0:4: String literals cannot cross line boundaries.\n" }, - - // Integer errors. - { "123foo", true, - "0:3: Need space between number and identifier.\n" }, - - // Hex/octal errors. - { "0x foo", true, - "0:2: \"0x\" must be followed by hex digits.\n" }, - { "0541823 foo", true, - "0:4: Numbers starting with leading zero must be in octal.\n" }, - { "0x123z foo", true, - "0:5: Need space between number and identifier.\n" }, - { "0x123.4 foo", true, - "0:5: Hex and octal numbers must be integers.\n" }, - { "0123.4 foo", true, - "0:4: Hex and octal numbers must be integers.\n" }, - - // Float errors. - { "1e foo", true, - "0:2: \"e\" must be followed by exponent.\n" }, - { "1e- foo", true, - "0:3: \"e\" must be followed by exponent.\n" }, - { "1.2.3 foo", true, - "0:3: Already saw decimal point or exponent; can't have another one.\n" }, - { "1e2.3 foo", true, - "0:3: Already saw decimal point or exponent; can't have another one.\n" }, - { "a.1 foo", true, - "0:1: Need space between identifier and decimal point.\n" }, - // allow_f_after_float not enabled, so this should be an error. - { "1.0f foo", true, - "0:3: Need space between number and identifier.\n" }, - - // Block comment errors. - { "/*", false, - "0:2: End-of-file inside block comment.\n" - "0:0: Comment started here.\n"}, - { "/*/*/ foo", true, - "0:3: \"/*\" inside block comment. Block comments cannot be nested.\n"}, - - // Control characters. Multiple consecutive control characters should only - // produce one error. - { "\b foo", true, - "0:0: Invalid control characters encountered in text.\n" }, - { "\b\b foo", true, - "0:0: Invalid control characters encountered in text.\n" }, - - // Check that control characters at end of input don't result in an - // infinite loop. - { "\b", false, - "0:0: Invalid control characters encountered in text.\n" }, - - // Check recovery from '\0'. We have to explicitly specify the length of - // these strings because otherwise the string constructor will just call - // strlen() which will see the first '\0' and think that is the end of the - // string. - { string("\0foo", 4), true, - "0:0: Invalid control characters encountered in text.\n" }, - { string("\0\0foo", 5), true, - "0:0: Invalid control characters encountered in text.\n" }, -}; - -TEST_2D(TokenizerTest, Errors, kErrorCases, kBlockSizes) { - // Set up the tokenizer. - TestInputStream input(kErrorCases_case.input.data(), - kErrorCases_case.input.size(), - kBlockSizes_case); - TestErrorCollector error_collector; - Tokenizer tokenizer(&input, &error_collector); - - // Ignore all input, except remember if the last token was "foo". - bool last_was_foo = false; - while (tokenizer.Next()) { - last_was_foo = tokenizer.current().text == "foo"; - } - - // Check that the errors match what was expected. - EXPECT_EQ(error_collector.text_, kErrorCases_case.errors); - - // If the error was recoverable, make sure we saw "foo" after it. - if (kErrorCases_case.recoverable) { - EXPECT_TRUE(last_was_foo); - } -} - -// ------------------------------------------------------------------- - -TEST_1D(TokenizerTest, BackUpOnDestruction, kBlockSizes) { - string text = "foo bar"; - TestInputStream input(text.data(), text.size(), kBlockSizes_case); - - // Create a tokenizer, read one token, then destroy it. - { - TestErrorCollector error_collector; - Tokenizer tokenizer(&input, &error_collector); - - tokenizer.Next(); - } - - // Only "foo" should have been read. - EXPECT_EQ(strlen("foo"), input.ByteCount()); -} - -} // namespace -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream.cc b/Resources/NetHook/google/protobuf/io/zero_copy_stream.cc deleted file mode 100644 index dad6ff14..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream.cc +++ /dev/null @@ -1,48 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - - -namespace google { -namespace protobuf { -namespace io { - -ZeroCopyInputStream::~ZeroCopyInputStream() {} -ZeroCopyOutputStream::~ZeroCopyOutputStream() {} - - -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream.h b/Resources/NetHook/google/protobuf/io/zero_copy_stream.h deleted file mode 100644 index db5326f7..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream.h +++ /dev/null @@ -1,238 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains the ZeroCopyInputStream and ZeroCopyOutputStream -// interfaces, which represent abstract I/O streams to and from which -// protocol buffers can be read and written. For a few simple -// implementations of these interfaces, see zero_copy_stream_impl.h. -// -// These interfaces are different from classic I/O streams in that they -// try to minimize the amount of data copying that needs to be done. -// To accomplish this, responsibility for allocating buffers is moved to -// the stream object, rather than being the responsibility of the caller. -// So, the stream can return a buffer which actually points directly into -// the final data structure where the bytes are to be stored, and the caller -// can interact directly with that buffer, eliminating an intermediate copy -// operation. -// -// As an example, consider the common case in which you are reading bytes -// from an array that is already in memory (or perhaps an mmap()ed file). -// With classic I/O streams, you would do something like: -// char buffer[BUFFER_SIZE]; -// input->Read(buffer, BUFFER_SIZE); -// DoSomething(buffer, BUFFER_SIZE); -// Then, the stream basically just calls memcpy() to copy the data from -// the array into your buffer. With a ZeroCopyInputStream, you would do -// this instead: -// const void* buffer; -// int size; -// input->Next(&buffer, &size); -// DoSomething(buffer, size); -// Here, no copy is performed. The input stream returns a pointer directly -// into the backing array, and the caller ends up reading directly from it. -// -// If you want to be able to read the old-fashion way, you can create -// a CodedInputStream or CodedOutputStream wrapping these objects and use -// their ReadRaw()/WriteRaw() methods. These will, of course, add a copy -// step, but Coded*Stream will handle buffering so at least it will be -// reasonably efficient. -// -// ZeroCopyInputStream example: -// // Read in a file and print its contents to stdout. -// int fd = open("myfile", O_RDONLY); -// ZeroCopyInputStream* input = new FileInputStream(fd); -// -// const void* buffer; -// int size; -// while (input->Next(&buffer, &size)) { -// cout.write(buffer, size); -// } -// -// delete input; -// close(fd); -// -// ZeroCopyOutputStream example: -// // Copy the contents of "infile" to "outfile", using plain read() for -// // "infile" but a ZeroCopyOutputStream for "outfile". -// int infd = open("infile", O_RDONLY); -// int outfd = open("outfile", O_WRONLY); -// ZeroCopyOutputStream* output = new FileOutputStream(outfd); -// -// void* buffer; -// int size; -// while (output->Next(&buffer, &size)) { -// int bytes = read(infd, buffer, size); -// if (bytes < size) { -// // Reached EOF. -// output->BackUp(size - bytes); -// break; -// } -// } -// -// delete output; -// close(infd); -// close(outfd); - -#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ -#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ - -#include -#include - -namespace google { - -namespace protobuf { -namespace io { - -// Defined in this file. -class ZeroCopyInputStream; -class ZeroCopyOutputStream; - -// Abstract interface similar to an input stream but designed to minimize -// copying. -class LIBPROTOBUF_EXPORT ZeroCopyInputStream { - public: - inline ZeroCopyInputStream() {} - virtual ~ZeroCopyInputStream(); - - // Obtains a chunk of data from the stream. - // - // Preconditions: - // * "size" and "data" are not NULL. - // - // Postconditions: - // * If the returned value is false, there is no more data to return or - // an error occurred. All errors are permanent. - // * Otherwise, "size" points to the actual number of bytes read and "data" - // points to a pointer to a buffer containing these bytes. - // * Ownership of this buffer remains with the stream, and the buffer - // remains valid only until some other method of the stream is called - // or the stream is destroyed. - // * It is legal for the returned buffer to have zero size, as long - // as repeatedly calling Next() eventually yields a buffer with non-zero - // size. - virtual bool Next(const void** data, int* size) = 0; - - // Backs up a number of bytes, so that the next call to Next() returns - // data again that was already returned by the last call to Next(). This - // is useful when writing procedures that are only supposed to read up - // to a certain point in the input, then return. If Next() returns a - // buffer that goes beyond what you wanted to read, you can use BackUp() - // to return to the point where you intended to finish. - // - // Preconditions: - // * The last method called must have been Next(). - // * count must be less than or equal to the size of the last buffer - // returned by Next(). - // - // Postconditions: - // * The last "count" bytes of the last buffer returned by Next() will be - // pushed back into the stream. Subsequent calls to Next() will return - // the same data again before producing new data. - virtual void BackUp(int count) = 0; - - // Skips a number of bytes. Returns false if the end of the stream is - // reached or some input error occurred. In the end-of-stream case, the - // stream is advanced to the end of the stream (so ByteCount() will return - // the total size of the stream). - virtual bool Skip(int count) = 0; - - // Returns the total number of bytes read since this object was created. - virtual int64 ByteCount() const = 0; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyInputStream); -}; - -// Abstract interface similar to an output stream but designed to minimize -// copying. -class LIBPROTOBUF_EXPORT ZeroCopyOutputStream { - public: - inline ZeroCopyOutputStream() {} - virtual ~ZeroCopyOutputStream(); - - // Obtains a buffer into which data can be written. Any data written - // into this buffer will eventually (maybe instantly, maybe later on) - // be written to the output. - // - // Preconditions: - // * "size" and "data" are not NULL. - // - // Postconditions: - // * If the returned value is false, an error occurred. All errors are - // permanent. - // * Otherwise, "size" points to the actual number of bytes in the buffer - // and "data" points to the buffer. - // * Ownership of this buffer remains with the stream, and the buffer - // remains valid only until some other method of the stream is called - // or the stream is destroyed. - // * Any data which the caller stores in this buffer will eventually be - // written to the output (unless BackUp() is called). - // * It is legal for the returned buffer to have zero size, as long - // as repeatedly calling Next() eventually yields a buffer with non-zero - // size. - virtual bool Next(void** data, int* size) = 0; - - // Backs up a number of bytes, so that the end of the last buffer returned - // by Next() is not actually written. This is needed when you finish - // writing all the data you want to write, but the last buffer was bigger - // than you needed. You don't want to write a bunch of garbage after the - // end of your data, so you use BackUp() to back up. - // - // Preconditions: - // * The last method called must have been Next(). - // * count must be less than or equal to the size of the last buffer - // returned by Next(). - // * The caller must not have written anything to the last "count" bytes - // of that buffer. - // - // Postconditions: - // * The last "count" bytes of the last buffer returned by Next() will be - // ignored. - virtual void BackUp(int count) = 0; - - // Returns the total number of bytes written since this object was created. - virtual int64 ByteCount() const = 0; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ZeroCopyOutputStream); -}; - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_H__ diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl.cc b/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl.cc deleted file mode 100644 index 1384c746..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl.cc +++ /dev/null @@ -1,470 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifdef _MSC_VER -#include -#else -#include -#include -#include -#include -#endif -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { - -#ifdef _WIN32 -// Win32 lseek is broken: If invoked on a non-seekable file descriptor, its -// return value is undefined. We re-define it to always produce an error. -#define lseek(fd, offset, origin) ((off_t)-1) -#endif - -namespace { - -// EINTR sucks. -int close_no_eintr(int fd) { - int result; - do { - result = close(fd); - } while (result < 0 && errno == EINTR); - return result; -} - -} // namespace - - -// =================================================================== - -FileInputStream::FileInputStream(int file_descriptor, int block_size) - : copying_input_(file_descriptor), - impl_(©ing_input_, block_size) { -} - -FileInputStream::~FileInputStream() {} - -bool FileInputStream::Close() { - return copying_input_.Close(); -} - -bool FileInputStream::Next(const void** data, int* size) { - return impl_.Next(data, size); -} - -void FileInputStream::BackUp(int count) { - impl_.BackUp(count); -} - -bool FileInputStream::Skip(int count) { - return impl_.Skip(count); -} - -int64 FileInputStream::ByteCount() const { - return impl_.ByteCount(); -} - -FileInputStream::CopyingFileInputStream::CopyingFileInputStream( - int file_descriptor) - : file_(file_descriptor), - close_on_delete_(false), - is_closed_(false), - errno_(0), - previous_seek_failed_(false) { -} - -FileInputStream::CopyingFileInputStream::~CopyingFileInputStream() { - if (close_on_delete_) { - if (!Close()) { - GOOGLE_LOG(ERROR) << "close() failed: " << strerror(errno_); - } - } -} - -bool FileInputStream::CopyingFileInputStream::Close() { - GOOGLE_CHECK(!is_closed_); - - is_closed_ = true; - if (close_no_eintr(file_) != 0) { - // The docs on close() do not specify whether a file descriptor is still - // open after close() fails with EIO. However, the glibc source code - // seems to indicate that it is not. - errno_ = errno; - return false; - } - - return true; -} - -int FileInputStream::CopyingFileInputStream::Read(void* buffer, int size) { - GOOGLE_CHECK(!is_closed_); - - int result; - do { - result = read(file_, buffer, size); - } while (result < 0 && errno == EINTR); - - if (result < 0) { - // Read error (not EOF). - errno_ = errno; - } - - return result; -} - -int FileInputStream::CopyingFileInputStream::Skip(int count) { - GOOGLE_CHECK(!is_closed_); - - if (!previous_seek_failed_ && - lseek(file_, count, SEEK_CUR) != (off_t)-1) { - // Seek succeeded. - return count; - } else { - // Failed to seek. - - // Note to self: Don't seek again. This file descriptor doesn't - // support it. - previous_seek_failed_ = true; - - // Use the default implementation. - return CopyingInputStream::Skip(count); - } -} - -// =================================================================== - -FileOutputStream::FileOutputStream(int file_descriptor, int block_size) - : copying_output_(file_descriptor), - impl_(©ing_output_, block_size) { -} - -FileOutputStream::~FileOutputStream() { - impl_.Flush(); -} - -bool FileOutputStream::Close() { - bool flush_succeeded = impl_.Flush(); - return copying_output_.Close() && flush_succeeded; -} - -bool FileOutputStream::Flush() { - return impl_.Flush(); -} - -bool FileOutputStream::Next(void** data, int* size) { - return impl_.Next(data, size); -} - -void FileOutputStream::BackUp(int count) { - impl_.BackUp(count); -} - -int64 FileOutputStream::ByteCount() const { - return impl_.ByteCount(); -} - -FileOutputStream::CopyingFileOutputStream::CopyingFileOutputStream( - int file_descriptor) - : file_(file_descriptor), - close_on_delete_(false), - is_closed_(false), - errno_(0) { -} - -FileOutputStream::CopyingFileOutputStream::~CopyingFileOutputStream() { - if (close_on_delete_) { - if (!Close()) { - GOOGLE_LOG(ERROR) << "close() failed: " << strerror(errno_); - } - } -} - -bool FileOutputStream::CopyingFileOutputStream::Close() { - GOOGLE_CHECK(!is_closed_); - - is_closed_ = true; - if (close_no_eintr(file_) != 0) { - // The docs on close() do not specify whether a file descriptor is still - // open after close() fails with EIO. However, the glibc source code - // seems to indicate that it is not. - errno_ = errno; - return false; - } - - return true; -} - -bool FileOutputStream::CopyingFileOutputStream::Write( - const void* buffer, int size) { - GOOGLE_CHECK(!is_closed_); - int total_written = 0; - - const uint8* buffer_base = reinterpret_cast(buffer); - - while (total_written < size) { - int bytes; - do { - bytes = write(file_, buffer_base + total_written, size - total_written); - } while (bytes < 0 && errno == EINTR); - - if (bytes <= 0) { - // Write error. - - // FIXME(kenton): According to the man page, if write() returns zero, - // there was no error; write() simply did not write anything. It's - // unclear under what circumstances this might happen, but presumably - // errno won't be set in this case. I am confused as to how such an - // event should be handled. For now I'm treating it as an error, since - // retrying seems like it could lead to an infinite loop. I suspect - // this never actually happens anyway. - - if (bytes < 0) { - errno_ = errno; - } - return false; - } - total_written += bytes; - } - - return true; -} - -// =================================================================== - -IstreamInputStream::IstreamInputStream(istream* input, int block_size) - : copying_input_(input), - impl_(©ing_input_, block_size) { -} - -IstreamInputStream::~IstreamInputStream() {} - -bool IstreamInputStream::Next(const void** data, int* size) { - return impl_.Next(data, size); -} - -void IstreamInputStream::BackUp(int count) { - impl_.BackUp(count); -} - -bool IstreamInputStream::Skip(int count) { - return impl_.Skip(count); -} - -int64 IstreamInputStream::ByteCount() const { - return impl_.ByteCount(); -} - -IstreamInputStream::CopyingIstreamInputStream::CopyingIstreamInputStream( - istream* input) - : input_(input) { -} - -IstreamInputStream::CopyingIstreamInputStream::~CopyingIstreamInputStream() {} - -int IstreamInputStream::CopyingIstreamInputStream::Read( - void* buffer, int size) { - input_->read(reinterpret_cast(buffer), size); - int result = input_->gcount(); - if (result == 0 && input_->fail() && !input_->eof()) { - return -1; - } - return result; -} - -// =================================================================== - -OstreamOutputStream::OstreamOutputStream(ostream* output, int block_size) - : copying_output_(output), - impl_(©ing_output_, block_size) { -} - -OstreamOutputStream::~OstreamOutputStream() { - impl_.Flush(); -} - -bool OstreamOutputStream::Next(void** data, int* size) { - return impl_.Next(data, size); -} - -void OstreamOutputStream::BackUp(int count) { - impl_.BackUp(count); -} - -int64 OstreamOutputStream::ByteCount() const { - return impl_.ByteCount(); -} - -OstreamOutputStream::CopyingOstreamOutputStream::CopyingOstreamOutputStream( - ostream* output) - : output_(output) { -} - -OstreamOutputStream::CopyingOstreamOutputStream::~CopyingOstreamOutputStream() { -} - -bool OstreamOutputStream::CopyingOstreamOutputStream::Write( - const void* buffer, int size) { - output_->write(reinterpret_cast(buffer), size); - return output_->good(); -} - -// =================================================================== - -ConcatenatingInputStream::ConcatenatingInputStream( - ZeroCopyInputStream* const streams[], int count) - : streams_(streams), stream_count_(count), bytes_retired_(0) { -} - -ConcatenatingInputStream::~ConcatenatingInputStream() { -} - -bool ConcatenatingInputStream::Next(const void** data, int* size) { - while (stream_count_ > 0) { - if (streams_[0]->Next(data, size)) return true; - - // That stream is done. Advance to the next one. - bytes_retired_ += streams_[0]->ByteCount(); - ++streams_; - --stream_count_; - } - - // No more streams. - return false; -} - -void ConcatenatingInputStream::BackUp(int count) { - if (stream_count_ > 0) { - streams_[0]->BackUp(count); - } else { - GOOGLE_LOG(DFATAL) << "Can't BackUp() after failed Next()."; - } -} - -bool ConcatenatingInputStream::Skip(int count) { - while (stream_count_ > 0) { - // Assume that ByteCount() can be used to find out how much we actually - // skipped when Skip() fails. - int64 target_byte_count = streams_[0]->ByteCount() + count; - if (streams_[0]->Skip(count)) return true; - - // Hit the end of the stream. Figure out how many more bytes we still have - // to skip. - int64 final_byte_count = streams_[0]->ByteCount(); - GOOGLE_DCHECK_LT(final_byte_count, target_byte_count); - count = target_byte_count - final_byte_count; - - // That stream is done. Advance to the next one. - bytes_retired_ += final_byte_count; - ++streams_; - --stream_count_; - } - - return false; -} - -int64 ConcatenatingInputStream::ByteCount() const { - if (stream_count_ == 0) { - return bytes_retired_; - } else { - return bytes_retired_ + streams_[0]->ByteCount(); - } -} - - -// =================================================================== - -LimitingInputStream::LimitingInputStream(ZeroCopyInputStream* input, - int64 limit) - : input_(input), limit_(limit) {} - -LimitingInputStream::~LimitingInputStream() { - // If we overshot the limit, back up. - if (limit_ < 0) input_->BackUp(-limit_); -} - -bool LimitingInputStream::Next(const void** data, int* size) { - if (limit_ <= 0) return false; - if (!input_->Next(data, size)) return false; - - limit_ -= *size; - if (limit_ < 0) { - // We overshot the limit. Reduce *size to hide the rest of the buffer. - *size += limit_; - } - return true; -} - -void LimitingInputStream::BackUp(int count) { - if (limit_ < 0) { - input_->BackUp(count - limit_); - limit_ = count; - } else { - input_->BackUp(count); - limit_ += count; - } -} - -bool LimitingInputStream::Skip(int count) { - if (count > limit_) { - if (limit_ < 0) return false; - input_->Skip(limit_); - limit_ = 0; - return false; - } else { - if (!input_->Skip(count)) return false; - limit_ -= count; - return true; - } -} - -int64 LimitingInputStream::ByteCount() const { - if (limit_ < 0) { - return input_->ByteCount() + limit_; - } else { - return input_->ByteCount(); - } -} - - -// =================================================================== - -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl.h b/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl.h deleted file mode 100644 index 9fedb005..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl.h +++ /dev/null @@ -1,357 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains common implementations of the interfaces defined in -// zero_copy_stream.h which are only included in the full (non-lite) -// protobuf library. These implementations include Unix file descriptors -// and C++ iostreams. See also: zero_copy_stream_impl_lite.h - -#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ -#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ - -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace io { - - -// =================================================================== - -// A ZeroCopyInputStream which reads from a file descriptor. -// -// FileInputStream is preferred over using an ifstream with IstreamInputStream. -// The latter will introduce an extra layer of buffering, harming performance. -// Also, it's conceivable that FileInputStream could someday be enhanced -// to use zero-copy file descriptors on OSs which support them. -class LIBPROTOBUF_EXPORT FileInputStream : public ZeroCopyInputStream { - public: - // Creates a stream that reads from the given Unix file descriptor. - // If a block_size is given, it specifies the number of bytes that - // should be read and returned with each call to Next(). Otherwise, - // a reasonable default is used. - explicit FileInputStream(int file_descriptor, int block_size = -1); - ~FileInputStream(); - - // Flushes any buffers and closes the underlying file. Returns false if - // an error occurs during the process; use GetErrno() to examine the error. - // Even if an error occurs, the file descriptor is closed when this returns. - bool Close(); - - // By default, the file descriptor is not closed when the stream is - // destroyed. Call SetCloseOnDelete(true) to change that. WARNING: - // This leaves no way for the caller to detect if close() fails. If - // detecting close() errors is important to you, you should arrange - // to close the descriptor yourself. - void SetCloseOnDelete(bool value) { copying_input_.SetCloseOnDelete(value); } - - // If an I/O error has occurred on this file descriptor, this is the - // errno from that error. Otherwise, this is zero. Once an error - // occurs, the stream is broken and all subsequent operations will - // fail. - int GetErrno() { return copying_input_.GetErrno(); } - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - private: - class LIBPROTOBUF_EXPORT CopyingFileInputStream : public CopyingInputStream { - public: - CopyingFileInputStream(int file_descriptor); - ~CopyingFileInputStream(); - - bool Close(); - void SetCloseOnDelete(bool value) { close_on_delete_ = value; } - int GetErrno() { return errno_; } - - // implements CopyingInputStream --------------------------------- - int Read(void* buffer, int size); - int Skip(int count); - - private: - // The file descriptor. - const int file_; - bool close_on_delete_; - bool is_closed_; - - // The errno of the I/O error, if one has occurred. Otherwise, zero. - int errno_; - - // Did we try to seek once and fail? If so, we assume this file descriptor - // doesn't support seeking and won't try again. - bool previous_seek_failed_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingFileInputStream); - }; - - CopyingFileInputStream copying_input_; - CopyingInputStreamAdaptor impl_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileInputStream); -}; - -// =================================================================== - -// A ZeroCopyOutputStream which writes to a file descriptor. -// -// FileOutputStream is preferred over using an ofstream with -// OstreamOutputStream. The latter will introduce an extra layer of buffering, -// harming performance. Also, it's conceivable that FileOutputStream could -// someday be enhanced to use zero-copy file descriptors on OSs which -// support them. -class LIBPROTOBUF_EXPORT FileOutputStream : public ZeroCopyOutputStream { - public: - // Creates a stream that writes to the given Unix file descriptor. - // If a block_size is given, it specifies the size of the buffers - // that should be returned by Next(). Otherwise, a reasonable default - // is used. - explicit FileOutputStream(int file_descriptor, int block_size = -1); - ~FileOutputStream(); - - // Flushes any buffers and closes the underlying file. Returns false if - // an error occurs during the process; use GetErrno() to examine the error. - // Even if an error occurs, the file descriptor is closed when this returns. - bool Close(); - - // Flushes FileOutputStream's buffers but does not close the - // underlying file. No special measures are taken to ensure that - // underlying operating system file object is synchronized to disk. - bool Flush(); - - // By default, the file descriptor is not closed when the stream is - // destroyed. Call SetCloseOnDelete(true) to change that. WARNING: - // This leaves no way for the caller to detect if close() fails. If - // detecting close() errors is important to you, you should arrange - // to close the descriptor yourself. - void SetCloseOnDelete(bool value) { copying_output_.SetCloseOnDelete(value); } - - // If an I/O error has occurred on this file descriptor, this is the - // errno from that error. Otherwise, this is zero. Once an error - // occurs, the stream is broken and all subsequent operations will - // fail. - int GetErrno() { return copying_output_.GetErrno(); } - - // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - private: - class LIBPROTOBUF_EXPORT CopyingFileOutputStream : public CopyingOutputStream { - public: - CopyingFileOutputStream(int file_descriptor); - ~CopyingFileOutputStream(); - - bool Close(); - void SetCloseOnDelete(bool value) { close_on_delete_ = value; } - int GetErrno() { return errno_; } - - // implements CopyingOutputStream -------------------------------- - bool Write(const void* buffer, int size); - - private: - // The file descriptor. - const int file_; - bool close_on_delete_; - bool is_closed_; - - // The errno of the I/O error, if one has occurred. Otherwise, zero. - int errno_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingFileOutputStream); - }; - - CopyingFileOutputStream copying_output_; - CopyingOutputStreamAdaptor impl_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileOutputStream); -}; - -// =================================================================== - -// A ZeroCopyInputStream which reads from a C++ istream. -// -// Note that for reading files (or anything represented by a file descriptor), -// FileInputStream is more efficient. -class LIBPROTOBUF_EXPORT IstreamInputStream : public ZeroCopyInputStream { - public: - // Creates a stream that reads from the given C++ istream. - // If a block_size is given, it specifies the number of bytes that - // should be read and returned with each call to Next(). Otherwise, - // a reasonable default is used. - explicit IstreamInputStream(istream* stream, int block_size = -1); - ~IstreamInputStream(); - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - private: - class LIBPROTOBUF_EXPORT CopyingIstreamInputStream : public CopyingInputStream { - public: - CopyingIstreamInputStream(istream* input); - ~CopyingIstreamInputStream(); - - // implements CopyingInputStream --------------------------------- - int Read(void* buffer, int size); - // (We use the default implementation of Skip().) - - private: - // The stream. - istream* input_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingIstreamInputStream); - }; - - CopyingIstreamInputStream copying_input_; - CopyingInputStreamAdaptor impl_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(IstreamInputStream); -}; - -// =================================================================== - -// A ZeroCopyOutputStream which writes to a C++ ostream. -// -// Note that for writing files (or anything represented by a file descriptor), -// FileOutputStream is more efficient. -class LIBPROTOBUF_EXPORT OstreamOutputStream : public ZeroCopyOutputStream { - public: - // Creates a stream that writes to the given C++ ostream. - // If a block_size is given, it specifies the size of the buffers - // that should be returned by Next(). Otherwise, a reasonable default - // is used. - explicit OstreamOutputStream(ostream* stream, int block_size = -1); - ~OstreamOutputStream(); - - // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - private: - class LIBPROTOBUF_EXPORT CopyingOstreamOutputStream : public CopyingOutputStream { - public: - CopyingOstreamOutputStream(ostream* output); - ~CopyingOstreamOutputStream(); - - // implements CopyingOutputStream -------------------------------- - bool Write(const void* buffer, int size); - - private: - // The stream. - ostream* output_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOstreamOutputStream); - }; - - CopyingOstreamOutputStream copying_output_; - CopyingOutputStreamAdaptor impl_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OstreamOutputStream); -}; - -// =================================================================== - -// A ZeroCopyInputStream which reads from several other streams in sequence. -// ConcatenatingInputStream is unable to distinguish between end-of-stream -// and read errors in the underlying streams, so it assumes any errors mean -// end-of-stream. So, if the underlying streams fail for any other reason, -// ConcatenatingInputStream may do odd things. It is suggested that you do -// not use ConcatenatingInputStream on streams that might produce read errors -// other than end-of-stream. -class LIBPROTOBUF_EXPORT ConcatenatingInputStream : public ZeroCopyInputStream { - public: - // All streams passed in as well as the array itself must remain valid - // until the ConcatenatingInputStream is destroyed. - ConcatenatingInputStream(ZeroCopyInputStream* const streams[], int count); - ~ConcatenatingInputStream(); - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - - private: - // As streams are retired, streams_ is incremented and count_ is - // decremented. - ZeroCopyInputStream* const* streams_; - int stream_count_; - int64 bytes_retired_; // Bytes read from previous streams. - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ConcatenatingInputStream); -}; - -// =================================================================== - -// A ZeroCopyInputStream which wraps some other stream and limits it to -// a particular byte count. -class LIBPROTOBUF_EXPORT LimitingInputStream : public ZeroCopyInputStream { - public: - LimitingInputStream(ZeroCopyInputStream* input, int64 limit); - ~LimitingInputStream(); - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - - private: - ZeroCopyInputStream* input_; - int64 limit_; // Decreases as we go, becomes negative if we overshoot. - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(LimitingInputStream); -}; - -// =================================================================== - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_H__ diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl_lite.cc b/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl_lite.cc deleted file mode 100644 index e8012510..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl_lite.cc +++ /dev/null @@ -1,393 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { - -namespace { - -// Default block size for Copying{In,Out}putStreamAdaptor. -static const int kDefaultBlockSize = 8192; - -} // namespace - -// =================================================================== - -ArrayInputStream::ArrayInputStream(const void* data, int size, - int block_size) - : data_(reinterpret_cast(data)), - size_(size), - block_size_(block_size > 0 ? block_size : size), - position_(0), - last_returned_size_(0) { -} - -ArrayInputStream::~ArrayInputStream() { -} - -bool ArrayInputStream::Next(const void** data, int* size) { - if (position_ < size_) { - last_returned_size_ = min(block_size_, size_ - position_); - *data = data_ + position_; - *size = last_returned_size_; - position_ += last_returned_size_; - return true; - } else { - // We're at the end of the array. - last_returned_size_ = 0; // Don't let caller back up. - return false; - } -} - -void ArrayInputStream::BackUp(int count) { - GOOGLE_CHECK_GT(last_returned_size_, 0) - << "BackUp() can only be called after a successful Next()."; - GOOGLE_CHECK_LE(count, last_returned_size_); - GOOGLE_CHECK_GE(count, 0); - position_ -= count; - last_returned_size_ = 0; // Don't let caller back up further. -} - -bool ArrayInputStream::Skip(int count) { - GOOGLE_CHECK_GE(count, 0); - last_returned_size_ = 0; // Don't let caller back up. - if (count > size_ - position_) { - position_ = size_; - return false; - } else { - position_ += count; - return true; - } -} - -int64 ArrayInputStream::ByteCount() const { - return position_; -} - - -// =================================================================== - -ArrayOutputStream::ArrayOutputStream(void* data, int size, int block_size) - : data_(reinterpret_cast(data)), - size_(size), - block_size_(block_size > 0 ? block_size : size), - position_(0), - last_returned_size_(0) { -} - -ArrayOutputStream::~ArrayOutputStream() { -} - -bool ArrayOutputStream::Next(void** data, int* size) { - if (position_ < size_) { - last_returned_size_ = min(block_size_, size_ - position_); - *data = data_ + position_; - *size = last_returned_size_; - position_ += last_returned_size_; - return true; - } else { - // We're at the end of the array. - last_returned_size_ = 0; // Don't let caller back up. - return false; - } -} - -void ArrayOutputStream::BackUp(int count) { - GOOGLE_CHECK_GT(last_returned_size_, 0) - << "BackUp() can only be called after a successful Next()."; - GOOGLE_CHECK_LE(count, last_returned_size_); - GOOGLE_CHECK_GE(count, 0); - position_ -= count; - last_returned_size_ = 0; // Don't let caller back up further. -} - -int64 ArrayOutputStream::ByteCount() const { - return position_; -} - -// =================================================================== - -StringOutputStream::StringOutputStream(string* target) - : target_(target) { -} - -StringOutputStream::~StringOutputStream() { -} - -bool StringOutputStream::Next(void** data, int* size) { - int old_size = target_->size(); - - // Grow the string. - if (old_size < target_->capacity()) { - // Resize the string to match its capacity, since we can get away - // without a memory allocation this way. - STLStringResizeUninitialized(target_, target_->capacity()); - } else { - // Size has reached capacity, so double the size. Also make sure - // that the new size is at least kMinimumSize. - STLStringResizeUninitialized( - target_, - max(old_size * 2, - kMinimumSize + 0)); // "+ 0" works around GCC4 weirdness. - } - - *data = string_as_array(target_) + old_size; - *size = target_->size() - old_size; - return true; -} - -void StringOutputStream::BackUp(int count) { - GOOGLE_CHECK_GE(count, 0); - GOOGLE_CHECK_LE(count, target_->size()); - target_->resize(target_->size() - count); -} - -int64 StringOutputStream::ByteCount() const { - return target_->size(); -} - -// =================================================================== - -CopyingInputStream::~CopyingInputStream() {} - -int CopyingInputStream::Skip(int count) { - char junk[4096]; - int skipped = 0; - while (skipped < count) { - int bytes = Read(junk, min(count - skipped, - implicit_cast(sizeof(junk)))); - if (bytes <= 0) { - // EOF or read error. - return skipped; - } - skipped += bytes; - } - return skipped; -} - -CopyingInputStreamAdaptor::CopyingInputStreamAdaptor( - CopyingInputStream* copying_stream, int block_size) - : copying_stream_(copying_stream), - owns_copying_stream_(false), - failed_(false), - position_(0), - buffer_size_(block_size > 0 ? block_size : kDefaultBlockSize), - buffer_used_(0), - backup_bytes_(0) { -} - -CopyingInputStreamAdaptor::~CopyingInputStreamAdaptor() { - if (owns_copying_stream_) { - delete copying_stream_; - } -} - -bool CopyingInputStreamAdaptor::Next(const void** data, int* size) { - if (failed_) { - // Already failed on a previous read. - return false; - } - - AllocateBufferIfNeeded(); - - if (backup_bytes_ > 0) { - // We have data left over from a previous BackUp(), so just return that. - *data = buffer_.get() + buffer_used_ - backup_bytes_; - *size = backup_bytes_; - backup_bytes_ = 0; - return true; - } - - // Read new data into the buffer. - buffer_used_ = copying_stream_->Read(buffer_.get(), buffer_size_); - if (buffer_used_ <= 0) { - // EOF or read error. We don't need the buffer anymore. - if (buffer_used_ < 0) { - // Read error (not EOF). - failed_ = true; - } - FreeBuffer(); - return false; - } - position_ += buffer_used_; - - *size = buffer_used_; - *data = buffer_.get(); - return true; -} - -void CopyingInputStreamAdaptor::BackUp(int count) { - GOOGLE_CHECK(backup_bytes_ == 0 && buffer_.get() != NULL) - << " BackUp() can only be called after Next()."; - GOOGLE_CHECK_LE(count, buffer_used_) - << " Can't back up over more bytes than were returned by the last call" - " to Next()."; - GOOGLE_CHECK_GE(count, 0) - << " Parameter to BackUp() can't be negative."; - - backup_bytes_ = count; -} - -bool CopyingInputStreamAdaptor::Skip(int count) { - GOOGLE_CHECK_GE(count, 0); - - if (failed_) { - // Already failed on a previous read. - return false; - } - - // First skip any bytes left over from a previous BackUp(). - if (backup_bytes_ >= count) { - // We have more data left over than we're trying to skip. Just chop it. - backup_bytes_ -= count; - return true; - } - - count -= backup_bytes_; - backup_bytes_ = 0; - - int skipped = copying_stream_->Skip(count); - position_ += skipped; - return skipped == count; -} - -int64 CopyingInputStreamAdaptor::ByteCount() const { - return position_ - backup_bytes_; -} - -void CopyingInputStreamAdaptor::AllocateBufferIfNeeded() { - if (buffer_.get() == NULL) { - buffer_.reset(new uint8[buffer_size_]); - } -} - -void CopyingInputStreamAdaptor::FreeBuffer() { - GOOGLE_CHECK_EQ(backup_bytes_, 0); - buffer_used_ = 0; - buffer_.reset(); -} - -// =================================================================== - -CopyingOutputStream::~CopyingOutputStream() {} - -CopyingOutputStreamAdaptor::CopyingOutputStreamAdaptor( - CopyingOutputStream* copying_stream, int block_size) - : copying_stream_(copying_stream), - owns_copying_stream_(false), - failed_(false), - position_(0), - buffer_size_(block_size > 0 ? block_size : kDefaultBlockSize), - buffer_used_(0) { -} - -CopyingOutputStreamAdaptor::~CopyingOutputStreamAdaptor() { - WriteBuffer(); - if (owns_copying_stream_) { - delete copying_stream_; - } -} - -bool CopyingOutputStreamAdaptor::Flush() { - return WriteBuffer(); -} - -bool CopyingOutputStreamAdaptor::Next(void** data, int* size) { - if (buffer_used_ == buffer_size_) { - if (!WriteBuffer()) return false; - } - - AllocateBufferIfNeeded(); - - *data = buffer_.get() + buffer_used_; - *size = buffer_size_ - buffer_used_; - buffer_used_ = buffer_size_; - return true; -} - -void CopyingOutputStreamAdaptor::BackUp(int count) { - GOOGLE_CHECK_GE(count, 0); - GOOGLE_CHECK_EQ(buffer_used_, buffer_size_) - << " BackUp() can only be called after Next()."; - GOOGLE_CHECK_LE(count, buffer_used_) - << " Can't back up over more bytes than were returned by the last call" - " to Next()."; - - buffer_used_ -= count; -} - -int64 CopyingOutputStreamAdaptor::ByteCount() const { - return position_ + buffer_used_; -} - -bool CopyingOutputStreamAdaptor::WriteBuffer() { - if (failed_) { - // Already failed on a previous write. - return false; - } - - if (buffer_used_ == 0) return true; - - if (copying_stream_->Write(buffer_.get(), buffer_used_)) { - position_ += buffer_used_; - buffer_used_ = 0; - return true; - } else { - failed_ = true; - FreeBuffer(); - return false; - } -} - -void CopyingOutputStreamAdaptor::AllocateBufferIfNeeded() { - if (buffer_ == NULL) { - buffer_.reset(new uint8[buffer_size_]); - } -} - -void CopyingOutputStreamAdaptor::FreeBuffer() { - buffer_used_ = 0; - buffer_.reset(); -} - -// =================================================================== - -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl_lite.h b/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl_lite.h deleted file mode 100644 index 153f543e..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream_impl_lite.h +++ /dev/null @@ -1,340 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains common implementations of the interfaces defined in -// zero_copy_stream.h which are included in the "lite" protobuf library. -// These implementations cover I/O on raw arrays and strings, as well as -// adaptors which make it easy to implement streams based on traditional -// streams. Of course, many users will probably want to write their own -// implementations of these interfaces specific to the particular I/O -// abstractions they prefer to use, but these should cover the most common -// cases. - -#ifndef GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ -#define GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ - -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace io { - -// =================================================================== - -// A ZeroCopyInputStream backed by an in-memory array of bytes. -class LIBPROTOBUF_EXPORT ArrayInputStream : public ZeroCopyInputStream { - public: - // Create an InputStream that returns the bytes pointed to by "data". - // "data" remains the property of the caller but must remain valid until - // the stream is destroyed. If a block_size is given, calls to Next() - // will return data blocks no larger than the given size. Otherwise, the - // first call to Next() returns the entire array. block_size is mainly - // useful for testing; in production you would probably never want to set - // it. - ArrayInputStream(const void* data, int size, int block_size = -1); - ~ArrayInputStream(); - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - - private: - const uint8* const data_; // The byte array. - const int size_; // Total size of the array. - const int block_size_; // How many bytes to return at a time. - - int position_; - int last_returned_size_; // How many bytes we returned last time Next() - // was called (used for error checking only). - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayInputStream); -}; - -// =================================================================== - -// A ZeroCopyOutputStream backed by an in-memory array of bytes. -class LIBPROTOBUF_EXPORT ArrayOutputStream : public ZeroCopyOutputStream { - public: - // Create an OutputStream that writes to the bytes pointed to by "data". - // "data" remains the property of the caller but must remain valid until - // the stream is destroyed. If a block_size is given, calls to Next() - // will return data blocks no larger than the given size. Otherwise, the - // first call to Next() returns the entire array. block_size is mainly - // useful for testing; in production you would probably never want to set - // it. - ArrayOutputStream(void* data, int size, int block_size = -1); - ~ArrayOutputStream(); - - // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - private: - uint8* const data_; // The byte array. - const int size_; // Total size of the array. - const int block_size_; // How many bytes to return at a time. - - int position_; - int last_returned_size_; // How many bytes we returned last time Next() - // was called (used for error checking only). - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ArrayOutputStream); -}; - -// =================================================================== - -// A ZeroCopyOutputStream which appends bytes to a string. -class LIBPROTOBUF_EXPORT StringOutputStream : public ZeroCopyOutputStream { - public: - // Create a StringOutputStream which appends bytes to the given string. - // The string remains property of the caller, but it MUST NOT be accessed - // in any way until the stream is destroyed. - // - // Hint: If you call target->reserve(n) before creating the stream, - // the first call to Next() will return at least n bytes of buffer - // space. - explicit StringOutputStream(string* target); - ~StringOutputStream(); - - // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - private: - static const int kMinimumSize = 16; - - string* target_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(StringOutputStream); -}; - -// Note: There is no StringInputStream. Instead, just create an -// ArrayInputStream as follows: -// ArrayInputStream input(str.data(), str.size()); - -// =================================================================== - -// A generic traditional input stream interface. -// -// Lots of traditional input streams (e.g. file descriptors, C stdio -// streams, and C++ iostreams) expose an interface where every read -// involves copying bytes into a buffer. If you want to take such an -// interface and make a ZeroCopyInputStream based on it, simply implement -// CopyingInputStream and then use CopyingInputStreamAdaptor. -// -// CopyingInputStream implementations should avoid buffering if possible. -// CopyingInputStreamAdaptor does its own buffering and will read data -// in large blocks. -class LIBPROTOBUF_EXPORT CopyingInputStream { - public: - virtual ~CopyingInputStream(); - - // Reads up to "size" bytes into the given buffer. Returns the number of - // bytes read. Read() waits until at least one byte is available, or - // returns zero if no bytes will ever become available (EOF), or -1 if a - // permanent read error occurred. - virtual int Read(void* buffer, int size) = 0; - - // Skips the next "count" bytes of input. Returns the number of bytes - // actually skipped. This will always be exactly equal to "count" unless - // EOF was reached or a permanent read error occurred. - // - // The default implementation just repeatedly calls Read() into a scratch - // buffer. - virtual int Skip(int count); -}; - -// A ZeroCopyInputStream which reads from a CopyingInputStream. This is -// useful for implementing ZeroCopyInputStreams that read from traditional -// streams. Note that this class is not really zero-copy. -// -// If you want to read from file descriptors or C++ istreams, this is -// already implemented for you: use FileInputStream or IstreamInputStream -// respectively. -class LIBPROTOBUF_EXPORT CopyingInputStreamAdaptor : public ZeroCopyInputStream { - public: - // Creates a stream that reads from the given CopyingInputStream. - // If a block_size is given, it specifies the number of bytes that - // should be read and returned with each call to Next(). Otherwise, - // a reasonable default is used. The caller retains ownership of - // copying_stream unless SetOwnsCopyingStream(true) is called. - explicit CopyingInputStreamAdaptor(CopyingInputStream* copying_stream, - int block_size = -1); - ~CopyingInputStreamAdaptor(); - - // Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to - // delete the underlying CopyingInputStream when it is destroyed. - void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; } - - // implements ZeroCopyInputStream ---------------------------------- - bool Next(const void** data, int* size); - void BackUp(int count); - bool Skip(int count); - int64 ByteCount() const; - - private: - // Insures that buffer_ is not NULL. - void AllocateBufferIfNeeded(); - // Frees the buffer and resets buffer_used_. - void FreeBuffer(); - - // The underlying copying stream. - CopyingInputStream* copying_stream_; - bool owns_copying_stream_; - - // True if we have seen a permenant error from the underlying stream. - bool failed_; - - // The current position of copying_stream_, relative to the point where - // we started reading. - int64 position_; - - // Data is read into this buffer. It may be NULL if no buffer is currently - // in use. Otherwise, it points to an array of size buffer_size_. - scoped_array buffer_; - const int buffer_size_; - - // Number of valid bytes currently in the buffer (i.e. the size last - // returned by Next()). 0 <= buffer_used_ <= buffer_size_. - int buffer_used_; - - // Number of bytes in the buffer which were backed up over by a call to - // BackUp(). These need to be returned again. - // 0 <= backup_bytes_ <= buffer_used_ - int backup_bytes_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingInputStreamAdaptor); -}; - -// =================================================================== - -// A generic traditional output stream interface. -// -// Lots of traditional output streams (e.g. file descriptors, C stdio -// streams, and C++ iostreams) expose an interface where every write -// involves copying bytes from a buffer. If you want to take such an -// interface and make a ZeroCopyOutputStream based on it, simply implement -// CopyingOutputStream and then use CopyingOutputStreamAdaptor. -// -// CopyingOutputStream implementations should avoid buffering if possible. -// CopyingOutputStreamAdaptor does its own buffering and will write data -// in large blocks. -class LIBPROTOBUF_EXPORT CopyingOutputStream { - public: - virtual ~CopyingOutputStream(); - - // Writes "size" bytes from the given buffer to the output. Returns true - // if successful, false on a write error. - virtual bool Write(const void* buffer, int size) = 0; -}; - -// A ZeroCopyOutputStream which writes to a CopyingOutputStream. This is -// useful for implementing ZeroCopyOutputStreams that write to traditional -// streams. Note that this class is not really zero-copy. -// -// If you want to write to file descriptors or C++ ostreams, this is -// already implemented for you: use FileOutputStream or OstreamOutputStream -// respectively. -class LIBPROTOBUF_EXPORT CopyingOutputStreamAdaptor : public ZeroCopyOutputStream { - public: - // Creates a stream that writes to the given Unix file descriptor. - // If a block_size is given, it specifies the size of the buffers - // that should be returned by Next(). Otherwise, a reasonable default - // is used. - explicit CopyingOutputStreamAdaptor(CopyingOutputStream* copying_stream, - int block_size = -1); - ~CopyingOutputStreamAdaptor(); - - // Writes all pending data to the underlying stream. Returns false if a - // write error occurred on the underlying stream. (The underlying - // stream itself is not necessarily flushed.) - bool Flush(); - - // Call SetOwnsCopyingStream(true) to tell the CopyingOutputStreamAdaptor to - // delete the underlying CopyingOutputStream when it is destroyed. - void SetOwnsCopyingStream(bool value) { owns_copying_stream_ = value; } - - // implements ZeroCopyOutputStream --------------------------------- - bool Next(void** data, int* size); - void BackUp(int count); - int64 ByteCount() const; - - private: - // Write the current buffer, if it is present. - bool WriteBuffer(); - // Insures that buffer_ is not NULL. - void AllocateBufferIfNeeded(); - // Frees the buffer. - void FreeBuffer(); - - // The underlying copying stream. - CopyingOutputStream* copying_stream_; - bool owns_copying_stream_; - - // True if we have seen a permenant error from the underlying stream. - bool failed_; - - // The current position of copying_stream_, relative to the point where - // we started writing. - int64 position_; - - // Data is written from this buffer. It may be NULL if no buffer is - // currently in use. Otherwise, it points to an array of size buffer_size_. - scoped_array buffer_; - const int buffer_size_; - - // Number of valid bytes currently in the buffer (i.e. the size last - // returned by Next()). When BackUp() is called, we just reduce this. - // 0 <= buffer_used_ <= buffer_size_. - int buffer_used_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(CopyingOutputStreamAdaptor); -}; - -// =================================================================== - -} // namespace io -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_IO_ZERO_COPY_STREAM_IMPL_LITE_H__ diff --git a/Resources/NetHook/google/protobuf/io/zero_copy_stream_unittest.cc b/Resources/NetHook/google/protobuf/io/zero_copy_stream_unittest.cc deleted file mode 100644 index 8229ee6d..00000000 --- a/Resources/NetHook/google/protobuf/io/zero_copy_stream_unittest.cc +++ /dev/null @@ -1,721 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Testing strategy: For each type of I/O (array, string, file, etc.) we -// create an output stream and write some data to it, then create a -// corresponding input stream to read the same data back and expect it to -// match. When the data is written, it is written in several small chunks -// of varying sizes, with a BackUp() after each chunk. It is read back -// similarly, but with chunks separated at different points. The whole -// process is run with a variety of block sizes for both the input and -// the output. -// -// TODO(kenton): Rewrite this test to bring it up to the standards of all -// the other proto2 tests. May want to wait for gTest to implement -// "parametized tests" so that one set of tests can be used on all the -// implementations. - -#include "config.h" - -#ifdef _MSC_VER -#include -#else -#include -#endif -#include -#include -#include -#include -#include -#include - -#include - -#if HAVE_ZLIB -#include -#endif - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace io { -namespace { - -#ifdef _WIN32 -#define pipe(fds) _pipe(fds, 4096, O_BINARY) -#endif - -#ifndef O_BINARY -#ifdef _O_BINARY -#define O_BINARY _O_BINARY -#else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. -#endif -#endif - -class IoTest : public testing::Test { - protected: - // Test helpers. - - // Helper to write an array of data to an output stream. - bool WriteToOutput(ZeroCopyOutputStream* output, const void* data, int size); - // Helper to read a fixed-length array of data from an input stream. - int ReadFromInput(ZeroCopyInputStream* input, void* data, int size); - // Write a string to the output stream. - void WriteString(ZeroCopyOutputStream* output, const string& str); - // Read a number of bytes equal to the size of the given string and checks - // that it matches the string. - void ReadString(ZeroCopyInputStream* input, const string& str); - // Writes some text to the output stream in a particular order. Returns - // the number of bytes written, incase the caller needs that to set up an - // input stream. - int WriteStuff(ZeroCopyOutputStream* output); - // Reads text from an input stream and expects it to match what - // WriteStuff() writes. - void ReadStuff(ZeroCopyInputStream* input); - - // Similar to WriteStuff, but performs more sophisticated testing. - int WriteStuffLarge(ZeroCopyOutputStream* output); - // Reads and tests a stream that should have been written to - // via WriteStuffLarge(). - void ReadStuffLarge(ZeroCopyInputStream* input); - -#if HAVE_ZLIB - string Compress(const string& data, const GzipOutputStream::Options& options); - string Uncompress(const string& data); -#endif - - static const int kBlockSizes[]; - static const int kBlockSizeCount; -}; - -const int IoTest::kBlockSizes[] = {-1, 1, 2, 5, 7, 10, 23, 64}; -const int IoTest::kBlockSizeCount = GOOGLE_ARRAYSIZE(IoTest::kBlockSizes); - -bool IoTest::WriteToOutput(ZeroCopyOutputStream* output, - const void* data, int size) { - const uint8* in = reinterpret_cast(data); - int in_size = size; - - void* out; - int out_size; - - while (true) { - if (!output->Next(&out, &out_size)) { - return false; - } - EXPECT_GT(out_size, 0); - - if (in_size <= out_size) { - memcpy(out, in, in_size); - output->BackUp(out_size - in_size); - return true; - } - - memcpy(out, in, out_size); - in += out_size; - in_size -= out_size; - } -} - -#define MAX_REPEATED_ZEROS 100 - -int IoTest::ReadFromInput(ZeroCopyInputStream* input, void* data, int size) { - uint8* out = reinterpret_cast(data); - int out_size = size; - - const void* in; - int in_size = 0; - - int repeated_zeros = 0; - - while (true) { - if (!input->Next(&in, &in_size)) { - return size - out_size; - } - EXPECT_GT(in_size, -1); - if (in_size == 0) { - repeated_zeros++; - } else { - repeated_zeros = 0; - } - EXPECT_LT(repeated_zeros, MAX_REPEATED_ZEROS); - - if (out_size <= in_size) { - memcpy(out, in, out_size); - if (in_size > out_size) { - input->BackUp(in_size - out_size); - } - return size; // Copied all of it. - } - - memcpy(out, in, in_size); - out += in_size; - out_size -= in_size; - } -} - -void IoTest::WriteString(ZeroCopyOutputStream* output, const string& str) { - EXPECT_TRUE(WriteToOutput(output, str.c_str(), str.size())); -} - -void IoTest::ReadString(ZeroCopyInputStream* input, const string& str) { - scoped_array buffer(new char[str.size() + 1]); - buffer[str.size()] = '\0'; - EXPECT_EQ(ReadFromInput(input, buffer.get(), str.size()), str.size()); - EXPECT_STREQ(str.c_str(), buffer.get()); -} - -int IoTest::WriteStuff(ZeroCopyOutputStream* output) { - WriteString(output, "Hello world!\n"); - WriteString(output, "Some te"); - WriteString(output, "xt. Blah blah."); - WriteString(output, "abcdefg"); - WriteString(output, "01234567890123456789"); - WriteString(output, "foobar"); - - EXPECT_EQ(output->ByteCount(), 68); - - int result = output->ByteCount(); - return result; -} - -// Reads text from an input stream and expects it to match what WriteStuff() -// writes. -void IoTest::ReadStuff(ZeroCopyInputStream* input) { - ReadString(input, "Hello world!\n"); - ReadString(input, "Some text. "); - ReadString(input, "Blah "); - ReadString(input, "blah."); - ReadString(input, "abcdefg"); - EXPECT_TRUE(input->Skip(20)); - ReadString(input, "foo"); - ReadString(input, "bar"); - - EXPECT_EQ(input->ByteCount(), 68); - - uint8 byte; - EXPECT_EQ(ReadFromInput(input, &byte, 1), 0); -} - -int IoTest::WriteStuffLarge(ZeroCopyOutputStream* output) { - WriteString(output, "Hello world!\n"); - WriteString(output, "Some te"); - WriteString(output, "xt. Blah blah."); - WriteString(output, string(100000, 'x')); // A very long string - WriteString(output, string(100000, 'y')); // A very long string - WriteString(output, "01234567890123456789"); - - EXPECT_EQ(output->ByteCount(), 200055); - - int result = output->ByteCount(); - return result; -} - -// Reads text from an input stream and expects it to match what WriteStuff() -// writes. -void IoTest::ReadStuffLarge(ZeroCopyInputStream* input) { - ReadString(input, "Hello world!\nSome text. "); - EXPECT_TRUE(input->Skip(5)); - ReadString(input, "blah."); - EXPECT_TRUE(input->Skip(100000 - 10)); - ReadString(input, string(10, 'x') + string(100000 - 20000, 'y')); - EXPECT_TRUE(input->Skip(20000 - 10)); - ReadString(input, "yyyyyyyyyy01234567890123456789"); - - EXPECT_EQ(input->ByteCount(), 200055); - - uint8 byte; - EXPECT_EQ(ReadFromInput(input, &byte, 1), 0); -} - -// =================================================================== - -TEST_F(IoTest, ArrayIo) { - const int kBufferSize = 256; - uint8 buffer[kBufferSize]; - - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - int size; - { - ArrayOutputStream output(buffer, kBufferSize, kBlockSizes[i]); - size = WriteStuff(&output); - } - { - ArrayInputStream input(buffer, size, kBlockSizes[j]); - ReadStuff(&input); - } - } - } -} - -#if HAVE_ZLIB -TEST_F(IoTest, GzipIo) { - const int kBufferSize = 2*1024; - uint8* buffer = new uint8[kBufferSize]; - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - for (int z = 0; z < kBlockSizeCount; z++) { - int gzip_buffer_size = kBlockSizes[z]; - int size; - { - ArrayOutputStream output(buffer, kBufferSize, kBlockSizes[i]); - GzipOutputStream gzout( - &output, GzipOutputStream::GZIP, gzip_buffer_size); - WriteStuff(&gzout); - gzout.Close(); - size = output.ByteCount(); - } - { - ArrayInputStream input(buffer, size, kBlockSizes[j]); - GzipInputStream gzin( - &input, GzipInputStream::GZIP, gzip_buffer_size); - ReadStuff(&gzin); - } - } - } - } - delete [] buffer; -} - -TEST_F(IoTest, ZlibIo) { - const int kBufferSize = 2*1024; - uint8* buffer = new uint8[kBufferSize]; - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - for (int z = 0; z < kBlockSizeCount; z++) { - int gzip_buffer_size = kBlockSizes[z]; - int size; - { - ArrayOutputStream output(buffer, kBufferSize, kBlockSizes[i]); - GzipOutputStream gzout( - &output, GzipOutputStream::ZLIB, gzip_buffer_size); - WriteStuff(&gzout); - gzout.Close(); - size = output.ByteCount(); - } - { - ArrayInputStream input(buffer, size, kBlockSizes[j]); - GzipInputStream gzin( - &input, GzipInputStream::ZLIB, gzip_buffer_size); - ReadStuff(&gzin); - } - } - } - } - delete [] buffer; -} - -TEST_F(IoTest, ZlibIoInputAutodetect) { - const int kBufferSize = 2*1024; - uint8* buffer = new uint8[kBufferSize]; - int size; - { - ArrayOutputStream output(buffer, kBufferSize); - GzipOutputStream gzout(&output, GzipOutputStream::ZLIB); - WriteStuff(&gzout); - gzout.Close(); - size = output.ByteCount(); - } - { - ArrayInputStream input(buffer, size); - GzipInputStream gzin(&input, GzipInputStream::AUTO); - ReadStuff(&gzin); - } - { - ArrayOutputStream output(buffer, kBufferSize); - GzipOutputStream gzout(&output, GzipOutputStream::GZIP); - WriteStuff(&gzout); - gzout.Close(); - size = output.ByteCount(); - } - { - ArrayInputStream input(buffer, size); - GzipInputStream gzin(&input, GzipInputStream::AUTO); - ReadStuff(&gzin); - } - delete [] buffer; -} - -string IoTest::Compress(const string& data, - const GzipOutputStream::Options& options) { - string result; - { - StringOutputStream output(&result); - GzipOutputStream gzout(&output, options); - WriteToOutput(&gzout, data.data(), data.size()); - } - return result; -} - -string IoTest::Uncompress(const string& data) { - string result; - { - ArrayInputStream input(data.data(), data.size()); - GzipInputStream gzin(&input); - const void* buffer; - int size; - while (gzin.Next(&buffer, &size)) { - result.append(reinterpret_cast(buffer), size); - } - } - return result; -} - -TEST_F(IoTest, CompressionOptions) { - // Some ad-hoc testing of compression options. - - string golden; - File::ReadFileToStringOrDie( - TestSourceDir() + "/google/protobuf/testdata/golden_message", - &golden); - - GzipOutputStream::Options options; - string gzip_compressed = Compress(golden, options); - - options.compression_level = 0; - string not_compressed = Compress(golden, options); - - // Try zlib compression for fun. - options = GzipOutputStream::Options(); - options.format = GzipOutputStream::ZLIB; - string zlib_compressed = Compress(golden, options); - - // Uncompressed should be bigger than the original since it should have some - // sort of header. - EXPECT_GT(not_compressed.size(), golden.size()); - - // Higher compression levels should result in smaller sizes. - EXPECT_LT(zlib_compressed.size(), not_compressed.size()); - - // ZLIB format should differ from GZIP format. - EXPECT_TRUE(zlib_compressed != gzip_compressed); - - // Everything should decompress correctly. - EXPECT_TRUE(Uncompress(not_compressed) == golden); - EXPECT_TRUE(Uncompress(gzip_compressed) == golden); - EXPECT_TRUE(Uncompress(zlib_compressed) == golden); -} -#endif - -// There is no string input, only string output. Also, it doesn't support -// explicit block sizes. So, we'll only run one test and we'll use -// ArrayInput to read back the results. -TEST_F(IoTest, StringIo) { - string str; - { - StringOutputStream output(&str); - WriteStuff(&output); - } - { - ArrayInputStream input(str.data(), str.size()); - ReadStuff(&input); - } -} - - -// To test files, we create a temporary file, write, read, truncate, repeat. -TEST_F(IoTest, FileIo) { - string filename = TestTempDir() + "/zero_copy_stream_test_file"; - - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - // Make a temporary file. - int file = - open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777); - ASSERT_GE(file, 0); - - { - FileOutputStream output(file, kBlockSizes[i]); - WriteStuff(&output); - EXPECT_EQ(0, output.GetErrno()); - } - - // Rewind. - ASSERT_NE(lseek(file, 0, SEEK_SET), (off_t)-1); - - { - FileInputStream input(file, kBlockSizes[j]); - ReadStuff(&input); - EXPECT_EQ(0, input.GetErrno()); - } - - close(file); - } - } -} - -#if HAVE_ZLIB -TEST_F(IoTest, GzipFileIo) { - string filename = TestTempDir() + "/zero_copy_stream_test_file"; - - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - // Make a temporary file. - int file = - open(filename.c_str(), O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0777); - ASSERT_GE(file, 0); - { - FileOutputStream output(file, kBlockSizes[i]); - GzipOutputStream gzout(&output); - WriteStuffLarge(&gzout); - gzout.Close(); - output.Flush(); - EXPECT_EQ(0, output.GetErrno()); - } - - // Rewind. - ASSERT_NE(lseek(file, 0, SEEK_SET), (off_t)-1); - - { - FileInputStream input(file, kBlockSizes[j]); - GzipInputStream gzin(&input); - ReadStuffLarge(&gzin); - EXPECT_EQ(0, input.GetErrno()); - } - - close(file); - } - } -} -#endif - -// MSVC raises various debugging exceptions if we try to use a file -// descriptor of -1, defeating our tests below. This class will disable -// these debug assertions while in scope. -class MsvcDebugDisabler { - public: -#if defined(_MSC_VER) && _MSC_VER >= 1400 - MsvcDebugDisabler() { - old_handler_ = _set_invalid_parameter_handler(MyHandler); - old_mode_ = _CrtSetReportMode(_CRT_ASSERT, 0); - } - ~MsvcDebugDisabler() { - old_handler_ = _set_invalid_parameter_handler(old_handler_); - old_mode_ = _CrtSetReportMode(_CRT_ASSERT, old_mode_); - } - - static void MyHandler(const wchar_t *expr, - const wchar_t *func, - const wchar_t *file, - unsigned int line, - uintptr_t pReserved) { - // do nothing - } - - _invalid_parameter_handler old_handler_; - int old_mode_; -#else - // Dummy constructor and destructor to ensure that GCC doesn't complain - // that debug_disabler is an unused variable. - MsvcDebugDisabler() {} - ~MsvcDebugDisabler() {} -#endif -}; - -// Test that FileInputStreams report errors correctly. -TEST_F(IoTest, FileReadError) { - MsvcDebugDisabler debug_disabler; - - // -1 = invalid file descriptor. - FileInputStream input(-1); - - const void* buffer; - int size; - EXPECT_FALSE(input.Next(&buffer, &size)); - EXPECT_EQ(EBADF, input.GetErrno()); -} - -// Test that FileOutputStreams report errors correctly. -TEST_F(IoTest, FileWriteError) { - MsvcDebugDisabler debug_disabler; - - // -1 = invalid file descriptor. - FileOutputStream input(-1); - - void* buffer; - int size; - - // The first call to Next() succeeds because it doesn't have anything to - // write yet. - EXPECT_TRUE(input.Next(&buffer, &size)); - - // Second call fails. - EXPECT_FALSE(input.Next(&buffer, &size)); - - EXPECT_EQ(EBADF, input.GetErrno()); -} - -// Pipes are not seekable, so File{Input,Output}Stream ends up doing some -// different things to handle them. We'll test by writing to a pipe and -// reading back from it. -TEST_F(IoTest, PipeIo) { - int files[2]; - - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - // Need to create a new pipe each time because ReadStuff() expects - // to see EOF at the end. - ASSERT_EQ(pipe(files), 0); - - { - FileOutputStream output(files[1], kBlockSizes[i]); - WriteStuff(&output); - EXPECT_EQ(0, output.GetErrno()); - } - close(files[1]); // Send EOF. - - { - FileInputStream input(files[0], kBlockSizes[j]); - ReadStuff(&input); - EXPECT_EQ(0, input.GetErrno()); - } - close(files[0]); - } - } -} - -// Test using C++ iostreams. -TEST_F(IoTest, IostreamIo) { - for (int i = 0; i < kBlockSizeCount; i++) { - for (int j = 0; j < kBlockSizeCount; j++) { - { - stringstream stream; - - { - OstreamOutputStream output(&stream, kBlockSizes[i]); - WriteStuff(&output); - EXPECT_FALSE(stream.fail()); - } - - { - IstreamInputStream input(&stream, kBlockSizes[j]); - ReadStuff(&input); - EXPECT_TRUE(stream.eof()); - } - } - - { - stringstream stream; - - { - OstreamOutputStream output(&stream, kBlockSizes[i]); - WriteStuffLarge(&output); - EXPECT_FALSE(stream.fail()); - } - - { - IstreamInputStream input(&stream, kBlockSizes[j]); - ReadStuffLarge(&input); - EXPECT_TRUE(stream.eof()); - } - } - } - } -} - -// To test ConcatenatingInputStream, we create several ArrayInputStreams -// covering a buffer and then concatenate them. -TEST_F(IoTest, ConcatenatingInputStream) { - const int kBufferSize = 256; - uint8 buffer[kBufferSize]; - - // Fill the buffer. - ArrayOutputStream output(buffer, kBufferSize); - WriteStuff(&output); - - // Now split it up into multiple streams of varying sizes. - ASSERT_EQ(68, output.ByteCount()); // Test depends on this. - ArrayInputStream input1(buffer , 12); - ArrayInputStream input2(buffer + 12, 7); - ArrayInputStream input3(buffer + 19, 6); - ArrayInputStream input4(buffer + 25, 15); - ArrayInputStream input5(buffer + 40, 0); - // Note: We want to make sure we have a stream boundary somewhere between - // bytes 42 and 62, which is the range that it Skip()ed by ReadStuff(). This - // tests that a bug that existed in the original code for Skip() is fixed. - ArrayInputStream input6(buffer + 40, 10); - ArrayInputStream input7(buffer + 50, 18); // Total = 68 bytes. - - ZeroCopyInputStream* streams[] = - {&input1, &input2, &input3, &input4, &input5, &input6, &input7}; - - // Create the concatenating stream and read. - ConcatenatingInputStream input(streams, GOOGLE_ARRAYSIZE(streams)); - ReadStuff(&input); -} - -// To test LimitingInputStream, we write our golden text to a buffer, then -// create an ArrayInputStream that contains the whole buffer (not just the -// bytes written), then use a LimitingInputStream to limit it just to the -// bytes written. -TEST_F(IoTest, LimitingInputStream) { - const int kBufferSize = 256; - uint8 buffer[kBufferSize]; - - // Fill the buffer. - ArrayOutputStream output(buffer, kBufferSize); - WriteStuff(&output); - - // Set up input. - ArrayInputStream array_input(buffer, kBufferSize); - LimitingInputStream input(&array_input, output.ByteCount()); - - ReadStuff(&input); -} - -// Check that a zero-size array doesn't confuse the code. -TEST(ZeroSizeArray, Input) { - ArrayInputStream input(NULL, 0); - const void* data; - int size; - EXPECT_FALSE(input.Next(&data, &size)); -} - -TEST(ZeroSizeArray, Output) { - ArrayOutputStream output(NULL, 0); - void* data; - int size; - EXPECT_FALSE(output.Next(&data, &size)); -} - -} // namespace -} // namespace io -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/lite_unittest.cc b/Resources/NetHook/google/protobuf/lite_unittest.cc deleted file mode 100644 index ffeec3c4..00000000 --- a/Resources/NetHook/google/protobuf/lite_unittest.cc +++ /dev/null @@ -1,112 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#include -#include - -#include -#include - -using namespace std; - -int main(int argc, char* argv[]) { - string data, packed_data; - - { - protobuf_unittest::TestAllTypesLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectClear(message); - google::protobuf::TestUtilLite::SetAllFields(&message); - message2.CopyFrom(message); - data = message.SerializeAsString(); - message3.ParseFromString(data); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message2); - google::protobuf::TestUtilLite::ExpectAllFieldsSet(message3); - google::protobuf::TestUtilLite::ModifyRepeatedFields(&message); - google::protobuf::TestUtilLite::ExpectRepeatedFieldsModified(message); - message.Clear(); - google::protobuf::TestUtilLite::ExpectClear(message); - } - - { - protobuf_unittest::TestAllExtensionsLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectExtensionsClear(message); - google::protobuf::TestUtilLite::SetAllExtensions(&message); - message2.CopyFrom(message); - string extensions_data = message.SerializeAsString(); - GOOGLE_CHECK(extensions_data == data); - message3.ParseFromString(extensions_data); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message2); - google::protobuf::TestUtilLite::ExpectAllExtensionsSet(message3); - google::protobuf::TestUtilLite::ModifyRepeatedExtensions(&message); - google::protobuf::TestUtilLite::ExpectRepeatedExtensionsModified(message); - message.Clear(); - google::protobuf::TestUtilLite::ExpectExtensionsClear(message); - } - - { - protobuf_unittest::TestPackedTypesLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectPackedClear(message); - google::protobuf::TestUtilLite::SetPackedFields(&message); - message2.CopyFrom(message); - packed_data = message.SerializeAsString(); - message3.ParseFromString(packed_data); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message2); - google::protobuf::TestUtilLite::ExpectPackedFieldsSet(message3); - google::protobuf::TestUtilLite::ModifyPackedFields(&message); - google::protobuf::TestUtilLite::ExpectPackedFieldsModified(message); - message.Clear(); - google::protobuf::TestUtilLite::ExpectPackedClear(message); - } - - { - protobuf_unittest::TestPackedExtensionsLite message, message2, message3; - google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message); - google::protobuf::TestUtilLite::SetPackedExtensions(&message); - message2.CopyFrom(message); - string packed_extensions_data = message.SerializeAsString(); - GOOGLE_CHECK(packed_extensions_data == packed_data); - message3.ParseFromString(packed_extensions_data); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message2); - google::protobuf::TestUtilLite::ExpectPackedExtensionsSet(message3); - google::protobuf::TestUtilLite::ModifyPackedExtensions(&message); - google::protobuf::TestUtilLite::ExpectPackedExtensionsModified(message); - message.Clear(); - google::protobuf::TestUtilLite::ExpectPackedExtensionsClear(message); - } - - cout << "PASS" << endl; - return 0; -} diff --git a/Resources/NetHook/google/protobuf/message.cc b/Resources/NetHook/google/protobuf/message.cc deleted file mode 100644 index 91e6878e..00000000 --- a/Resources/NetHook/google/protobuf/message.cc +++ /dev/null @@ -1,318 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -using internal::WireFormat; -using internal::ReflectionOps; - -Message::~Message() {} - -void Message::MergeFrom(const Message& from) { - const Descriptor* descriptor = GetDescriptor(); - GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor) - << ": Tried to merge from a message with a different type. " - "to: " << descriptor->full_name() << ", " - "from:" << from.GetDescriptor()->full_name(); - ReflectionOps::Merge(from, this); -} - -void Message::CheckTypeAndMergeFrom(const MessageLite& other) { - MergeFrom(*down_cast(&other)); -} - -void Message::CopyFrom(const Message& from) { - const Descriptor* descriptor = GetDescriptor(); - GOOGLE_CHECK_EQ(from.GetDescriptor(), descriptor) - << ": Tried to copy from a message with a different type." - "to: " << descriptor->full_name() << ", " - "from:" << from.GetDescriptor()->full_name(); - ReflectionOps::Copy(from, this); -} - -string Message::GetTypeName() const { - return GetDescriptor()->full_name(); -} - -void Message::Clear() { - ReflectionOps::Clear(this); -} - -bool Message::IsInitialized() const { - return ReflectionOps::IsInitialized(*this); -} - -void Message::FindInitializationErrors(vector* errors) const { - return ReflectionOps::FindInitializationErrors(*this, "", errors); -} - -string Message::InitializationErrorString() const { - vector errors; - FindInitializationErrors(&errors); - return JoinStrings(errors, ", "); -} - -void Message::CheckInitialized() const { - GOOGLE_CHECK(IsInitialized()) - << "Message of type \"" << GetDescriptor()->full_name() - << "\" is missing required fields: " << InitializationErrorString(); -} - -void Message::DiscardUnknownFields() { - return ReflectionOps::DiscardUnknownFields(this); -} - -bool Message::MergePartialFromCodedStream(io::CodedInputStream* input) { - return WireFormat::ParseAndMergePartial(input, this); -} - -bool Message::ParseFromFileDescriptor(int file_descriptor) { - io::FileInputStream input(file_descriptor); - return ParseFromZeroCopyStream(&input) && input.GetErrno() == 0; -} - -bool Message::ParsePartialFromFileDescriptor(int file_descriptor) { - io::FileInputStream input(file_descriptor); - return ParsePartialFromZeroCopyStream(&input) && input.GetErrno() == 0; -} - -bool Message::ParseFromIstream(istream* input) { - io::IstreamInputStream zero_copy_input(input); - return ParseFromZeroCopyStream(&zero_copy_input) && input->eof(); -} - -bool Message::ParsePartialFromIstream(istream* input) { - io::IstreamInputStream zero_copy_input(input); - return ParsePartialFromZeroCopyStream(&zero_copy_input) && input->eof(); -} - - -void Message::SerializeWithCachedSizes( - io::CodedOutputStream* output) const { - WireFormat::SerializeWithCachedSizes(*this, GetCachedSize(), output); -} - -int Message::ByteSize() const { - int size = WireFormat::ByteSize(*this); - SetCachedSize(size); - return size; -} - -void Message::SetCachedSize(int size) const { - GOOGLE_LOG(FATAL) << "Message class \"" << GetDescriptor()->full_name() - << "\" implements neither SetCachedSize() nor ByteSize(). " - "Must implement one or the other."; -} - -int Message::SpaceUsed() const { - return GetReflection()->SpaceUsed(*this); -} - -bool Message::SerializeToFileDescriptor(int file_descriptor) const { - io::FileOutputStream output(file_descriptor); - return SerializeToZeroCopyStream(&output); -} - -bool Message::SerializePartialToFileDescriptor(int file_descriptor) const { - io::FileOutputStream output(file_descriptor); - return SerializePartialToZeroCopyStream(&output); -} - -bool Message::SerializeToOstream(ostream* output) const { - { - io::OstreamOutputStream zero_copy_output(output); - if (!SerializeToZeroCopyStream(&zero_copy_output)) return false; - } - return output->good(); -} - -bool Message::SerializePartialToOstream(ostream* output) const { - io::OstreamOutputStream zero_copy_output(output); - return SerializePartialToZeroCopyStream(&zero_copy_output); -} - - -Reflection::~Reflection() {} - -// =================================================================== -// MessageFactory - -MessageFactory::~MessageFactory() {} - -namespace { - -class GeneratedMessageFactory : public MessageFactory { - public: - GeneratedMessageFactory(); - ~GeneratedMessageFactory(); - - static GeneratedMessageFactory* singleton(); - - typedef void RegistrationFunc(const string&); - void RegisterFile(const char* file, RegistrationFunc* registration_func); - void RegisterType(const Descriptor* descriptor, const Message* prototype); - - // implements MessageFactory --------------------------------------- - const Message* GetPrototype(const Descriptor* type); - - private: - // Only written at static init time, so does not require locking. - hash_map, streq> file_map_; - - // Initialized lazily, so requires locking. - Mutex mutex_; - hash_map type_map_; -}; - -GeneratedMessageFactory* generated_message_factory_ = NULL; -GOOGLE_PROTOBUF_DECLARE_ONCE(generated_message_factory_once_init_); - -void ShutdownGeneratedMessageFactory() { - delete generated_message_factory_; -} - -void InitGeneratedMessageFactory() { - generated_message_factory_ = new GeneratedMessageFactory; - internal::OnShutdown(&ShutdownGeneratedMessageFactory); -} - -GeneratedMessageFactory::GeneratedMessageFactory() {} -GeneratedMessageFactory::~GeneratedMessageFactory() {} - -GeneratedMessageFactory* GeneratedMessageFactory::singleton() { - ::google::protobuf::GoogleOnceInit(&generated_message_factory_once_init_, - &InitGeneratedMessageFactory); - return generated_message_factory_; -} - -void GeneratedMessageFactory::RegisterFile( - const char* file, RegistrationFunc* registration_func) { - if (!InsertIfNotPresent(&file_map_, file, registration_func)) { - GOOGLE_LOG(FATAL) << "File is already registered: " << file; - } -} - -void GeneratedMessageFactory::RegisterType(const Descriptor* descriptor, - const Message* prototype) { - GOOGLE_DCHECK_EQ(descriptor->file()->pool(), DescriptorPool::generated_pool()) - << "Tried to register a non-generated type with the generated " - "type registry."; - - // This should only be called as a result of calling a file registration - // function during GetPrototype(), in which case we already have locked - // the mutex. - mutex_.AssertHeld(); - if (!InsertIfNotPresent(&type_map_, descriptor, prototype)) { - GOOGLE_LOG(DFATAL) << "Type is already registered: " << descriptor->full_name(); - } -} - -const Message* GeneratedMessageFactory::GetPrototype(const Descriptor* type) { - { - ReaderMutexLock lock(&mutex_); - const Message* result = FindPtrOrNull(type_map_, type); - if (result != NULL) return result; - } - - // If the type is not in the generated pool, then we can't possibly handle - // it. - if (type->file()->pool() != DescriptorPool::generated_pool()) return NULL; - - // Apparently the file hasn't been registered yet. Let's do that now. - RegistrationFunc* registration_func = - FindPtrOrNull(file_map_, type->file()->name().c_str()); - if (registration_func == NULL) { - GOOGLE_LOG(DFATAL) << "File appears to be in generated pool but wasn't " - "registered: " << type->file()->name(); - return NULL; - } - - WriterMutexLock lock(&mutex_); - - // Check if another thread preempted us. - const Message* result = FindPtrOrNull(type_map_, type); - if (result == NULL) { - // Nope. OK, register everything. - registration_func(type->file()->name()); - // Should be here now. - result = FindPtrOrNull(type_map_, type); - } - - if (result == NULL) { - GOOGLE_LOG(DFATAL) << "Type appears to be in generated pool but wasn't " - << "registered: " << type->full_name(); - } - - return result; -} - -} // namespace - -MessageFactory* MessageFactory::generated_factory() { - return GeneratedMessageFactory::singleton(); -} - -void MessageFactory::InternalRegisterGeneratedFile( - const char* filename, void (*register_messages)(const string&)) { - GeneratedMessageFactory::singleton()->RegisterFile(filename, - register_messages); -} - -void MessageFactory::InternalRegisterGeneratedMessage( - const Descriptor* descriptor, const Message* prototype) { - GeneratedMessageFactory::singleton()->RegisterType(descriptor, prototype); -} - - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/message.h b/Resources/NetHook/google/protobuf/message.h deleted file mode 100644 index c0062f98..00000000 --- a/Resources/NetHook/google/protobuf/message.h +++ /dev/null @@ -1,710 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Defines Message, the abstract interface implemented by non-lite -// protocol message objects. Although it's possible to implement this -// interface manually, most users will use the protocol compiler to -// generate implementations. -// -// Example usage: -// -// Say you have a message defined as: -// -// message Foo { -// optional string text = 1; -// repeated int32 numbers = 2; -// } -// -// Then, if you used the protocol compiler to generate a class from the above -// definition, you could use it like so: -// -// string data; // Will store a serialized version of the message. -// -// { -// // Create a message and serialize it. -// Foo foo; -// foo.set_text("Hello World!"); -// foo.add_numbers(1); -// foo.add_numbers(5); -// foo.add_numbers(42); -// -// foo.SerializeToString(&data); -// } -// -// { -// // Parse the serialized message and check that it contains the -// // correct data. -// Foo foo; -// foo.ParseFromString(data); -// -// assert(foo.text() == "Hello World!"); -// assert(foo.numbers_size() == 3); -// assert(foo.numbers(0) == 1); -// assert(foo.numbers(1) == 5); -// assert(foo.numbers(2) == 42); -// } -// -// { -// // Same as the last block, but do it dynamically via the Message -// // reflection interface. -// Message* foo = new Foo; -// Descriptor* descriptor = foo->GetDescriptor(); -// -// // Get the descriptors for the fields we're interested in and verify -// // their types. -// FieldDescriptor* text_field = descriptor->FindFieldByName("text"); -// assert(text_field != NULL); -// assert(text_field->type() == FieldDescriptor::TYPE_STRING); -// assert(text_field->label() == FieldDescriptor::TYPE_OPTIONAL); -// FieldDescriptor* numbers_field = descriptor->FindFieldByName("numbers"); -// assert(numbers_field != NULL); -// assert(numbers_field->type() == FieldDescriptor::TYPE_INT32); -// assert(numbers_field->label() == FieldDescriptor::TYPE_REPEATED); -// -// // Parse the message. -// foo->ParseFromString(data); -// -// // Use the reflection interface to examine the contents. -// const Reflection* reflection = foo->GetReflection(); -// assert(reflection->GetString(foo, text_field) == "Hello World!"); -// assert(reflection->FieldSize(foo, numbers_field) == 3); -// assert(reflection->GetRepeatedInt32(foo, numbers_field, 0) == 1); -// assert(reflection->GetRepeatedInt32(foo, numbers_field, 1) == 5); -// assert(reflection->GetRepeatedInt32(foo, numbers_field, 2) == 42); -// -// delete foo; -// } - -#ifndef GOOGLE_PROTOBUF_MESSAGE_H__ -#define GOOGLE_PROTOBUF_MESSAGE_H__ - -#include -#include - -#ifdef __DECCXX -// HP C++'s iosfwd doesn't work. -#include -#else -#include -#endif - -#include - -#include - -#if defined(_WIN32) && defined(GetMessage) -// windows.h defines GetMessage() as a macro. Let's re-define it as an inline -// function. This is necessary because Reflection has a method called -// GetMessage() which we don't want overridden. The inline function should be -// equivalent for C++ users. -inline BOOL GetMessage_Win32( - LPMSG lpMsg, HWND hWnd, - UINT wMsgFilterMin, UINT wMsgFilterMax) { - return GetMessage(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax); -} -#undef GetMessage -inline BOOL GetMessage( - LPMSG lpMsg, HWND hWnd, - UINT wMsgFilterMin, UINT wMsgFilterMax) { - return GetMessage_Win32(lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax); -} -#endif - - -namespace google { -namespace protobuf { - -// Defined in this file. -class Message; -class Reflection; -class MessageFactory; - -// Defined in other files. -class Descriptor; // descriptor.h -class FieldDescriptor; // descriptor.h -class EnumDescriptor; // descriptor.h -class EnumValueDescriptor; // descriptor.h -namespace io { - class ZeroCopyInputStream; // zero_copy_stream.h - class ZeroCopyOutputStream; // zero_copy_stream.h - class CodedInputStream; // coded_stream.h - class CodedOutputStream; // coded_stream.h -} -class UnknownFieldSet; // unknown_field_set.h - -// A container to hold message metadata. -struct Metadata { - const Descriptor* descriptor; - const Reflection* reflection; -}; - -// Returns the EnumDescriptor for enum type E, which must be a -// proto-declared enum type. Code generated by the protocol compiler -// will include specializations of this template for each enum type declared. -template -const EnumDescriptor* GetEnumDescriptor(); - -// Abstract interface for protocol messages. -// -// See also MessageLite, which contains most every-day operations. Message -// adds descriptors and reflection on top of that. -// -// The methods of this class that are virtual but not pure-virtual have -// default implementations based on reflection. Message classes which are -// optimized for speed will want to override these with faster implementations, -// but classes optimized for code size may be happy with keeping them. See -// the optimize_for option in descriptor.proto. -class LIBPROTOBUF_EXPORT Message : public MessageLite { - public: - inline Message() {} - virtual ~Message(); - - // Basic Operations ------------------------------------------------ - - // Construct a new instance of the same type. Ownership is passed to the - // caller. (This is also defined in MessageLite, but is defined again here - // for return-type covariance.) - virtual Message* New() const = 0; - - // Make this message into a copy of the given message. The given message - // must have the same descriptor, but need not necessarily be the same class. - // By default this is just implemented as "Clear(); MergeFrom(from);". - virtual void CopyFrom(const Message& from); - - // Merge the fields from the given message into this message. Singular - // fields will be overwritten, except for embedded messages which will - // be merged. Repeated fields will be concatenated. The given message - // must be of the same type as this message (i.e. the exact same class). - virtual void MergeFrom(const Message& from); - - // Verifies that IsInitialized() returns true. GOOGLE_CHECK-fails otherwise, with - // a nice error message. - void CheckInitialized() const; - - // Slowly build a list of all required fields that are not set. - // This is much, much slower than IsInitialized() as it is implemented - // purely via reflection. Generally, you should not call this unless you - // have already determined that an error exists by calling IsInitialized(). - void FindInitializationErrors(vector* errors) const; - - // Like FindInitializationErrors, but joins all the strings, delimited by - // commas, and returns them. - string InitializationErrorString() const; - - // Clears all unknown fields from this message and all embedded messages. - // Normally, if unknown tag numbers are encountered when parsing a message, - // the tag and value are stored in the message's UnknownFieldSet and - // then written back out when the message is serialized. This allows servers - // which simply route messages to other servers to pass through messages - // that have new field definitions which they don't yet know about. However, - // this behavior can have security implications. To avoid it, call this - // method after parsing. - // - // See Reflection::GetUnknownFields() for more on unknown fields. - virtual void DiscardUnknownFields(); - - // Computes (an estimate of) the total number of bytes currently used for - // storing the message in memory. The default implementation calls the - // Reflection object's SpaceUsed() method. - virtual int SpaceUsed() const; - - // Debugging & Testing---------------------------------------------- - - // Generates a human readable form of this message, useful for debugging - // and other purposes. - string DebugString() const; - // Like DebugString(), but with less whitespace. - string ShortDebugString() const; - // Like DebugString(), but do not escape UTF-8 byte sequences. - string Utf8DebugString() const; - // Convenience function useful in GDB. Prints DebugString() to stdout. - void PrintDebugString() const; - - // Heavy I/O ------------------------------------------------------- - // Additional parsing and serialization methods not implemented by - // MessageLite because they are not supported by the lite library. - - // Parse a protocol buffer from a file descriptor. If successful, the entire - // input will be consumed. - bool ParseFromFileDescriptor(int file_descriptor); - // Like ParseFromFileDescriptor(), but accepts messages that are missing - // required fields. - bool ParsePartialFromFileDescriptor(int file_descriptor); - // Parse a protocol buffer from a C++ istream. If successful, the entire - // input will be consumed. - bool ParseFromIstream(istream* input); - // Like ParseFromIstream(), but accepts messages that are missing - // required fields. - bool ParsePartialFromIstream(istream* input); - - // Serialize the message and write it to the given file descriptor. All - // required fields must be set. - bool SerializeToFileDescriptor(int file_descriptor) const; - // Like SerializeToFileDescriptor(), but allows missing required fields. - bool SerializePartialToFileDescriptor(int file_descriptor) const; - // Serialize the message and write it to the given C++ ostream. All - // required fields must be set. - bool SerializeToOstream(ostream* output) const; - // Like SerializeToOstream(), but allows missing required fields. - bool SerializePartialToOstream(ostream* output) const; - - - // Reflection-based methods ---------------------------------------- - // These methods are pure-virtual in MessageLite, but Message provides - // reflection-based default implementations. - - virtual string GetTypeName() const; - virtual void Clear(); - virtual bool IsInitialized() const; - virtual void CheckTypeAndMergeFrom(const MessageLite& other); - virtual bool MergePartialFromCodedStream(io::CodedInputStream* input); - virtual int ByteSize() const; - virtual void SerializeWithCachedSizes(io::CodedOutputStream* output) const; - - private: - // This is called only by the default implementation of ByteSize(), to - // update the cached size. If you override ByteSize(), you do not need - // to override this. If you do not override ByteSize(), you MUST override - // this; the default implementation will crash. - // - // The method is private because subclasses should never call it; only - // override it. Yes, C++ lets you do that. Crazy, huh? - virtual void SetCachedSize(int size) const; - - public: - - // Introspection --------------------------------------------------- - - // Typedef for backwards-compatibility. - typedef google::protobuf::Reflection Reflection; - - // Get a Descriptor for this message's type. This describes what - // fields the message contains, the types of those fields, etc. - const Descriptor* GetDescriptor() const { return GetMetadata().descriptor; } - - // Get the Reflection interface for this Message, which can be used to - // read and modify the fields of the Message dynamically (in other words, - // without knowing the message type at compile time). This object remains - // property of the Message. - // - // This method remains virtual in case a subclass does not implement - // reflection and wants to override the default behavior. - virtual const Reflection* GetReflection() const { - return GetMetadata().reflection; - } - - protected: - // Get a struct containing the metadata for the Message. Most subclasses only - // need to implement this method, rather than the GetDescriptor() and - // GetReflection() wrappers. - virtual Metadata GetMetadata() const = 0; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Message); -}; - -// This interface contains methods that can be used to dynamically access -// and modify the fields of a protocol message. Their semantics are -// similar to the accessors the protocol compiler generates. -// -// To get the Reflection for a given Message, call Message::GetReflection(). -// -// This interface is separate from Message only for efficiency reasons; -// the vast majority of implementations of Message will share the same -// implementation of Reflection (GeneratedMessageReflection, -// defined in generated_message.h), and all Messages of a particular class -// should share the same Reflection object (though you should not rely on -// the latter fact). -// -// There are several ways that these methods can be used incorrectly. For -// example, any of the following conditions will lead to undefined -// results (probably assertion failures): -// - The FieldDescriptor is not a field of this message type. -// - The method called is not appropriate for the field's type. For -// each field type in FieldDescriptor::TYPE_*, there is only one -// Get*() method, one Set*() method, and one Add*() method that is -// valid for that type. It should be obvious which (except maybe -// for TYPE_BYTES, which are represented using strings in C++). -// - A Get*() or Set*() method for singular fields is called on a repeated -// field. -// - GetRepeated*(), SetRepeated*(), or Add*() is called on a non-repeated -// field. -// - The Message object passed to any method is not of the right type for -// this Reflection object (i.e. message.GetReflection() != reflection). -// -// You might wonder why there is not any abstract representation for a field -// of arbitrary type. E.g., why isn't there just a "GetField()" method that -// returns "const Field&", where "Field" is some class with accessors like -// "GetInt32Value()". The problem is that someone would have to deal with -// allocating these Field objects. For generated message classes, having to -// allocate space for an additional object to wrap every field would at least -// double the message's memory footprint, probably worse. Allocating the -// objects on-demand, on the other hand, would be expensive and prone to -// memory leaks. So, instead we ended up with this flat interface. -// -// TODO(kenton): Create a utility class which callers can use to read and -// write fields from a Reflection without paying attention to the type. -class LIBPROTOBUF_EXPORT Reflection { - public: - // TODO(kenton): Remove parameter. - inline Reflection() {} - virtual ~Reflection(); - - // Get the UnknownFieldSet for the message. This contains fields which - // were seen when the Message was parsed but were not recognized according - // to the Message's definition. - virtual const UnknownFieldSet& GetUnknownFields( - const Message& message) const = 0; - // Get a mutable pointer to the UnknownFieldSet for the message. This - // contains fields which were seen when the Message was parsed but were not - // recognized according to the Message's definition. - virtual UnknownFieldSet* MutableUnknownFields(Message* message) const = 0; - - // Estimate the amount of memory used by the message object. - virtual int SpaceUsed(const Message& message) const = 0; - - // Check if the given non-repeated field is set. - virtual bool HasField(const Message& message, - const FieldDescriptor* field) const = 0; - - // Get the number of elements of a repeated field. - virtual int FieldSize(const Message& message, - const FieldDescriptor* field) const = 0; - - // Clear the value of a field, so that HasField() returns false or - // FieldSize() returns zero. - virtual void ClearField(Message* message, - const FieldDescriptor* field) const = 0; - - // Remove the last element of a repeated field. - // We don't provide a way to remove any element other than the last - // because it invites inefficient use, such as O(n^2) filtering loops - // that should have been O(n). If you want to remove an element other - // than the last, the best way to do it is to re-arrange the elements - // (using Swap()) so that the one you want removed is at the end, then - // call RemoveLast(). - virtual void RemoveLast(Message* message, - const FieldDescriptor* field) const = 0; - - // Swap the complete contents of two messages. - virtual void Swap(Message* message1, Message* message2) const = 0; - - // Swap two elements of a repeated field. - virtual void SwapElements(Message* message, - const FieldDescriptor* field, - int index1, - int index2) const = 0; - - // List all fields of the message which are currently set. This includes - // extensions. Singular fields will only be listed if HasField(field) would - // return true and repeated fields will only be listed if FieldSize(field) - // would return non-zero. Fields (both normal fields and extension fields) - // will be listed ordered by field number. - virtual void ListFields(const Message& message, - vector* output) const = 0; - - // Singular field getters ------------------------------------------ - // These get the value of a non-repeated field. They return the default - // value for fields that aren't set. - - virtual int32 GetInt32 (const Message& message, - const FieldDescriptor* field) const = 0; - virtual int64 GetInt64 (const Message& message, - const FieldDescriptor* field) const = 0; - virtual uint32 GetUInt32(const Message& message, - const FieldDescriptor* field) const = 0; - virtual uint64 GetUInt64(const Message& message, - const FieldDescriptor* field) const = 0; - virtual float GetFloat (const Message& message, - const FieldDescriptor* field) const = 0; - virtual double GetDouble(const Message& message, - const FieldDescriptor* field) const = 0; - virtual bool GetBool (const Message& message, - const FieldDescriptor* field) const = 0; - virtual string GetString(const Message& message, - const FieldDescriptor* field) const = 0; - virtual const EnumValueDescriptor* GetEnum( - const Message& message, const FieldDescriptor* field) const = 0; - // See MutableMessage() for the meaning of the "factory" parameter. - virtual const Message& GetMessage(const Message& message, - const FieldDescriptor* field, - MessageFactory* factory = NULL) const = 0; - - // Get a string value without copying, if possible. - // - // GetString() necessarily returns a copy of the string. This can be - // inefficient when the string is already stored in a string object in the - // underlying message. GetStringReference() will return a reference to the - // underlying string in this case. Otherwise, it will copy the string into - // *scratch and return that. - // - // Note: It is perfectly reasonable and useful to write code like: - // str = reflection->GetStringReference(field, &str); - // This line would ensure that only one copy of the string is made - // regardless of the field's underlying representation. When initializing - // a newly-constructed string, though, it's just as fast and more readable - // to use code like: - // string str = reflection->GetString(field); - virtual const string& GetStringReference(const Message& message, - const FieldDescriptor* field, - string* scratch) const = 0; - - - // Singular field mutators ----------------------------------------- - // These mutate the value of a non-repeated field. - - virtual void SetInt32 (Message* message, - const FieldDescriptor* field, int32 value) const = 0; - virtual void SetInt64 (Message* message, - const FieldDescriptor* field, int64 value) const = 0; - virtual void SetUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const = 0; - virtual void SetUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const = 0; - virtual void SetFloat (Message* message, - const FieldDescriptor* field, float value) const = 0; - virtual void SetDouble(Message* message, - const FieldDescriptor* field, double value) const = 0; - virtual void SetBool (Message* message, - const FieldDescriptor* field, bool value) const = 0; - virtual void SetString(Message* message, - const FieldDescriptor* field, - const string& value) const = 0; - virtual void SetEnum (Message* message, - const FieldDescriptor* field, - const EnumValueDescriptor* value) const = 0; - // Get a mutable pointer to a field with a message type. If a MessageFactory - // is provided, it will be used to construct instances of the sub-message; - // otherwise, the default factory is used. If the field is an extension that - // does not live in the same pool as the containing message's descriptor (e.g. - // it lives in an overlay pool), then a MessageFactory must be provided. - // If you have no idea what that meant, then you probably don't need to worry - // about it (don't provide a MessageFactory). WARNING: If the - // FieldDescriptor is for a compiled-in extension, then - // factory->GetPrototype(field->message_type() MUST return an instance of the - // compiled-in class for this type, NOT DynamicMessage. - virtual Message* MutableMessage(Message* message, - const FieldDescriptor* field, - MessageFactory* factory = NULL) const = 0; - - - // Repeated field getters ------------------------------------------ - // These get the value of one element of a repeated field. - - virtual int32 GetRepeatedInt32 (const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual int64 GetRepeatedInt64 (const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual uint32 GetRepeatedUInt32(const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual uint64 GetRepeatedUInt64(const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual float GetRepeatedFloat (const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual double GetRepeatedDouble(const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual bool GetRepeatedBool (const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual string GetRepeatedString(const Message& message, - const FieldDescriptor* field, - int index) const = 0; - virtual const EnumValueDescriptor* GetRepeatedEnum( - const Message& message, - const FieldDescriptor* field, int index) const = 0; - virtual const Message& GetRepeatedMessage( - const Message& message, - const FieldDescriptor* field, int index) const = 0; - - // See GetStringReference(), above. - virtual const string& GetRepeatedStringReference( - const Message& message, const FieldDescriptor* field, - int index, string* scratch) const = 0; - - - // Repeated field mutators ----------------------------------------- - // These mutate the value of one element of a repeated field. - - virtual void SetRepeatedInt32 (Message* message, - const FieldDescriptor* field, - int index, int32 value) const = 0; - virtual void SetRepeatedInt64 (Message* message, - const FieldDescriptor* field, - int index, int64 value) const = 0; - virtual void SetRepeatedUInt32(Message* message, - const FieldDescriptor* field, - int index, uint32 value) const = 0; - virtual void SetRepeatedUInt64(Message* message, - const FieldDescriptor* field, - int index, uint64 value) const = 0; - virtual void SetRepeatedFloat (Message* message, - const FieldDescriptor* field, - int index, float value) const = 0; - virtual void SetRepeatedDouble(Message* message, - const FieldDescriptor* field, - int index, double value) const = 0; - virtual void SetRepeatedBool (Message* message, - const FieldDescriptor* field, - int index, bool value) const = 0; - virtual void SetRepeatedString(Message* message, - const FieldDescriptor* field, - int index, const string& value) const = 0; - virtual void SetRepeatedEnum(Message* message, - const FieldDescriptor* field, int index, - const EnumValueDescriptor* value) const = 0; - // Get a mutable pointer to an element of a repeated field with a message - // type. - virtual Message* MutableRepeatedMessage( - Message* message, const FieldDescriptor* field, int index) const = 0; - - - // Repeated field adders ------------------------------------------- - // These add an element to a repeated field. - - virtual void AddInt32 (Message* message, - const FieldDescriptor* field, int32 value) const = 0; - virtual void AddInt64 (Message* message, - const FieldDescriptor* field, int64 value) const = 0; - virtual void AddUInt32(Message* message, - const FieldDescriptor* field, uint32 value) const = 0; - virtual void AddUInt64(Message* message, - const FieldDescriptor* field, uint64 value) const = 0; - virtual void AddFloat (Message* message, - const FieldDescriptor* field, float value) const = 0; - virtual void AddDouble(Message* message, - const FieldDescriptor* field, double value) const = 0; - virtual void AddBool (Message* message, - const FieldDescriptor* field, bool value) const = 0; - virtual void AddString(Message* message, - const FieldDescriptor* field, - const string& value) const = 0; - virtual void AddEnum (Message* message, - const FieldDescriptor* field, - const EnumValueDescriptor* value) const = 0; - // See MutableMessage() for comments on the "factory" parameter. - virtual Message* AddMessage(Message* message, - const FieldDescriptor* field, - MessageFactory* factory = NULL) const = 0; - - - // Extensions ------------------------------------------------------ - - // Try to find an extension of this message type by fully-qualified field - // name. Returns NULL if no extension is known for this name or number. - virtual const FieldDescriptor* FindKnownExtensionByName( - const string& name) const = 0; - - // Try to find an extension of this message type by field number. - // Returns NULL if no extension is known for this name or number. - virtual const FieldDescriptor* FindKnownExtensionByNumber( - int number) const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Reflection); -}; - -// Abstract interface for a factory for message objects. -class LIBPROTOBUF_EXPORT MessageFactory { - public: - inline MessageFactory() {} - virtual ~MessageFactory(); - - // Given a Descriptor, gets or constructs the default (prototype) Message - // of that type. You can then call that message's New() method to construct - // a mutable message of that type. - // - // Calling this method twice with the same Descriptor returns the same - // object. The returned object remains property of the factory. Also, any - // objects created by calling the prototype's New() method share some data - // with the prototype, so these must be destoyed before the MessageFactory - // is destroyed. - // - // The given descriptor must outlive the returned message, and hence must - // outlive the MessageFactory. - // - // Some implementations do not support all types. GetPrototype() will - // return NULL if the descriptor passed in is not supported. - // - // This method may or may not be thread-safe depending on the implementation. - // Each implementation should document its own degree thread-safety. - virtual const Message* GetPrototype(const Descriptor* type) = 0; - - // Gets a MessageFactory which supports all generated, compiled-in messages. - // In other words, for any compiled-in type FooMessage, the following is true: - // MessageFactory::generated_factory()->GetPrototype( - // FooMessage::descriptor()) == FooMessage::default_instance() - // This factory supports all types which are found in - // DescriptorPool::generated_pool(). If given a descriptor from any other - // pool, GetPrototype() will return NULL. (You can also check if a - // descriptor is for a generated message by checking if - // descriptor->file()->pool() == DescriptorPool::generated_pool().) - // - // This factory is 100% thread-safe; calling GetPrototype() does not modify - // any shared data. - // - // This factory is a singleton. The caller must not delete the object. - static MessageFactory* generated_factory(); - - // For internal use only: Registers a .proto file at static initialization - // time, to be placed in generated_factory. The first time GetPrototype() - // is called with a descriptor from this file, |register_messages| will be - // called, with the file name as the parameter. It must call - // InternalRegisterGeneratedMessage() (below) to register each message type - // in the file. This strange mechanism is necessary because descriptors are - // built lazily, so we can't register types by their descriptor until we - // know that the descriptor exists. |filename| must be a permanent string. - static void InternalRegisterGeneratedFile( - const char* filename, void (*register_messages)(const string&)); - - // For internal use only: Registers a message type. Called only by the - // functions which are registered with InternalRegisterGeneratedFile(), - // above. - static void InternalRegisterGeneratedMessage(const Descriptor* descriptor, - const Message* prototype); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFactory); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_MESSAGE_H__ diff --git a/Resources/NetHook/google/protobuf/message_lite.cc b/Resources/NetHook/google/protobuf/message_lite.cc deleted file mode 100644 index 7c8f37dc..00000000 --- a/Resources/NetHook/google/protobuf/message_lite.cc +++ /dev/null @@ -1,334 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Authors: wink@google.com (Wink Saville), -// kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -MessageLite::~MessageLite() {} - -string MessageLite::InitializationErrorString() const { - return "(cannot determine missing fields for lite message)"; -} - -namespace { - -// When serializing, we first compute the byte size, then serialize the message. -// If serialization produces a different number of bytes than expected, we -// call this function, which crashes. The problem could be due to a bug in the -// protobuf implementation but is more likely caused by concurrent modification -// of the message. This function attempts to distinguish between the two and -// provide a useful error message. -void ByteSizeConsistencyError(int byte_size_before_serialization, - int byte_size_after_serialization, - int bytes_produced_by_serialization) { - GOOGLE_CHECK_EQ(byte_size_before_serialization, byte_size_after_serialization) - << "Protocol message was modified concurrently during serialization."; - GOOGLE_CHECK_EQ(bytes_produced_by_serialization, byte_size_before_serialization) - << "Byte size calculation and serialization were inconsistent. This " - "may indicate a bug in protocol buffers or it may be caused by " - "concurrent modification of the message."; - GOOGLE_LOG(FATAL) << "This shouldn't be called if all the sizes are equal."; -} - -string InitializationErrorMessage(const char* action, - const MessageLite& message) { - // Note: We want to avoid depending on strutil in the lite library, otherwise - // we'd use: - // - // return strings::Substitute( - // "Can't $0 message of type \"$1\" because it is missing required " - // "fields: $2", - // action, message.GetTypeName(), - // message.InitializationErrorString()); - - string result; - result += "Can't "; - result += action; - result += " message of type \""; - result += message.GetTypeName(); - result += "\" because it is missing required fields: "; - result += message.InitializationErrorString(); - return result; -} - -// Several of the Parse methods below just do one thing and then call another -// method. In a naive implementation, we might have ParseFromString() call -// ParseFromArray() which would call ParseFromZeroCopyStream() which would call -// ParseFromCodedStream() which would call MergeFromCodedStream() which would -// call MergePartialFromCodedStream(). However, when parsing very small -// messages, every function call introduces significant overhead. To avoid -// this without reproducing code, we use these forced-inline helpers. -// -// Note: GCC only allows GOOGLE_ATTRIBUTE_ALWAYS_INLINE on declarations, not -// definitions. -inline bool InlineMergeFromCodedStream(io::CodedInputStream* input, - MessageLite* message) - GOOGLE_ATTRIBUTE_ALWAYS_INLINE; -inline bool InlineParseFromCodedStream(io::CodedInputStream* input, - MessageLite* message) - GOOGLE_ATTRIBUTE_ALWAYS_INLINE; -inline bool InlineParsePartialFromCodedStream(io::CodedInputStream* input, - MessageLite* message) - GOOGLE_ATTRIBUTE_ALWAYS_INLINE; -inline bool InlineParseFromArray(const void* data, int size, - MessageLite* message) - GOOGLE_ATTRIBUTE_ALWAYS_INLINE; -inline bool InlineParsePartialFromArray(const void* data, int size, - MessageLite* message) - GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - -bool InlineMergeFromCodedStream(io::CodedInputStream* input, - MessageLite* message) { - if (!message->MergePartialFromCodedStream(input)) return false; - if (!message->IsInitialized()) { - GOOGLE_LOG(ERROR) << InitializationErrorMessage("parse", *message); - return false; - } - return true; -} - -bool InlineParseFromCodedStream(io::CodedInputStream* input, - MessageLite* message) { - message->Clear(); - return InlineMergeFromCodedStream(input, message); -} - -bool InlineParsePartialFromCodedStream(io::CodedInputStream* input, - MessageLite* message) { - message->Clear(); - return message->MergePartialFromCodedStream(input); -} - -bool InlineParseFromArray(const void* data, int size, MessageLite* message) { - io::CodedInputStream input(reinterpret_cast(data), size); - return InlineParseFromCodedStream(&input, message) && - input.ConsumedEntireMessage(); -} - -bool InlineParsePartialFromArray(const void* data, int size, - MessageLite* message) { - io::CodedInputStream input(reinterpret_cast(data), size); - return InlineParsePartialFromCodedStream(&input, message) && - input.ConsumedEntireMessage(); -} - -} // namespace - -bool MessageLite::MergeFromCodedStream(io::CodedInputStream* input) { - return InlineMergeFromCodedStream(input, this); -} - -bool MessageLite::ParseFromCodedStream(io::CodedInputStream* input) { - return InlineParseFromCodedStream(input, this); -} - -bool MessageLite::ParsePartialFromCodedStream(io::CodedInputStream* input) { - return InlineParsePartialFromCodedStream(input, this); -} - -bool MessageLite::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) { - io::CodedInputStream decoder(input); - return ParseFromCodedStream(&decoder) && decoder.ConsumedEntireMessage(); -} - -bool MessageLite::ParsePartialFromZeroCopyStream( - io::ZeroCopyInputStream* input) { - io::CodedInputStream decoder(input); - return ParsePartialFromCodedStream(&decoder) && - decoder.ConsumedEntireMessage(); -} - -bool MessageLite::ParseFromBoundedZeroCopyStream( - io::ZeroCopyInputStream* input, int size) { - io::CodedInputStream decoder(input); - decoder.PushLimit(size); - return ParseFromCodedStream(&decoder) && - decoder.ConsumedEntireMessage() && - decoder.BytesUntilLimit() == 0; -} - -bool MessageLite::ParsePartialFromBoundedZeroCopyStream( - io::ZeroCopyInputStream* input, int size) { - io::CodedInputStream decoder(input); - decoder.PushLimit(size); - return ParsePartialFromCodedStream(&decoder) && - decoder.ConsumedEntireMessage() && - decoder.BytesUntilLimit() == 0; -} - -bool MessageLite::ParseFromString(const string& data) { - return InlineParseFromArray(data.data(), data.size(), this); -} - -bool MessageLite::ParsePartialFromString(const string& data) { - return InlineParsePartialFromArray(data.data(), data.size(), this); -} - -bool MessageLite::ParseFromArray(const void* data, int size) { - return InlineParseFromArray(data, size, this); -} - -bool MessageLite::ParsePartialFromArray(const void* data, int size) { - return InlineParsePartialFromArray(data, size, this); -} - - -// =================================================================== - -uint8* MessageLite::SerializeWithCachedSizesToArray(uint8* target) const { - // We only optimize this when using optimize_for = SPEED. In other cases - // we just use the CodedOutputStream path. - int size = GetCachedSize(); - io::ArrayOutputStream out(target, size); - io::CodedOutputStream coded_out(&out); - SerializeWithCachedSizes(&coded_out); - GOOGLE_CHECK(!coded_out.HadError()); - return target + size; -} - -bool MessageLite::SerializeToCodedStream(io::CodedOutputStream* output) const { - GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this); - return SerializePartialToCodedStream(output); -} - -bool MessageLite::SerializePartialToCodedStream( - io::CodedOutputStream* output) const { - const int size = ByteSize(); // Force size to be cached. - uint8* buffer = output->GetDirectBufferForNBytesAndAdvance(size); - if (buffer != NULL) { - uint8* end = SerializeWithCachedSizesToArray(buffer); - if (end - buffer != size) { - ByteSizeConsistencyError(size, ByteSize(), end - buffer); - } - return true; - } else { - int original_byte_count = output->ByteCount(); - SerializeWithCachedSizes(output); - if (output->HadError()) { - return false; - } - int final_byte_count = output->ByteCount(); - - if (final_byte_count - original_byte_count != size) { - ByteSizeConsistencyError(size, ByteSize(), - final_byte_count - original_byte_count); - } - - return true; - } -} - -bool MessageLite::SerializeToZeroCopyStream( - io::ZeroCopyOutputStream* output) const { - io::CodedOutputStream encoder(output); - return SerializeToCodedStream(&encoder); -} - -bool MessageLite::SerializePartialToZeroCopyStream( - io::ZeroCopyOutputStream* output) const { - io::CodedOutputStream encoder(output); - return SerializePartialToCodedStream(&encoder); -} - -bool MessageLite::AppendToString(string* output) const { - GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this); - return AppendPartialToString(output); -} - -bool MessageLite::AppendPartialToString(string* output) const { - int old_size = output->size(); - int byte_size = ByteSize(); - STLStringResizeUninitialized(output, old_size + byte_size); - uint8* start = reinterpret_cast(string_as_array(output) + old_size); - uint8* end = SerializeWithCachedSizesToArray(start); - if (end - start != byte_size) { - ByteSizeConsistencyError(byte_size, ByteSize(), end - start); - } - return true; -} - -bool MessageLite::SerializeToString(string* output) const { - output->clear(); - return AppendToString(output); -} - -bool MessageLite::SerializePartialToString(string* output) const { - output->clear(); - return AppendPartialToString(output); -} - -bool MessageLite::SerializeToArray(void* data, int size) const { - GOOGLE_DCHECK(IsInitialized()) << InitializationErrorMessage("serialize", *this); - return SerializePartialToArray(data, size); -} - -bool MessageLite::SerializePartialToArray(void* data, int size) const { - int byte_size = ByteSize(); - if (size < byte_size) return false; - uint8* start = reinterpret_cast(data); - uint8* end = SerializeWithCachedSizesToArray(start); - if (end - start != byte_size) { - ByteSizeConsistencyError(byte_size, ByteSize(), end - start); - } - return true; -} - -string MessageLite::SerializeAsString() const { - // If the compiler implements the (Named) Return Value Optimization, - // the local variable 'result' will not actually reside on the stack - // of this function, but will be overlaid with the object that the - // caller supplied for the return value to be constructed in. - string output; - if (!AppendToString(&output)) - output.clear(); - return output; -} - -string MessageLite::SerializePartialAsString() const { - string output; - if (!AppendPartialToString(&output)) - output.clear(); - return output; -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/message_lite.h b/Resources/NetHook/google/protobuf/message_lite.h deleted file mode 100644 index ebf4ba3c..00000000 --- a/Resources/NetHook/google/protobuf/message_lite.h +++ /dev/null @@ -1,239 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Authors: wink@google.com (Wink Saville), -// kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Defines MessageLite, the abstract interface implemented by all (lite -// and non-lite) protocol message objects. - -#ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__ -#define GOOGLE_PROTOBUF_MESSAGE_LITE_H__ - -#include -#include - -namespace google { -namespace protobuf { - -// Interface to light weight protocol messages. -// -// This interface is implemented by all protocol message objects. Non-lite -// messages additionally implement the Message interface, which is a -// subclass of MessageLite. Use MessageLite instead when you only need -// the subset of features which it supports -- namely, nothing that uses -// descriptors or reflection. You can instruct the protocol compiler -// to generate classes which implement only MessageLite, not the full -// Message interface, by adding the following line to the .proto file: -// -// option optimize_for = LITE_RUNTIME; -// -// This is particularly useful on resource-constrained systems where -// the full protocol buffers runtime library is too big. -// -// Note that on non-constrained systems (e.g. servers) when you need -// to link in lots of protocol definitions, a better way to reduce -// total code footprint is to use optimize_for = CODE_SIZE. This -// will make the generated code smaller while still supporting all the -// same features (at the expense of speed). optimize_for = LITE_RUNTIME -// is best when you only have a small number of message types linked -// into your binary, in which case the size of the protocol buffers -// runtime itself is the biggest problem. -class LIBPROTOBUF_EXPORT MessageLite { - public: - inline MessageLite() {} - virtual ~MessageLite(); - - // Basic Operations ------------------------------------------------ - - // Get the name of this message type, e.g. "foo.bar.BazProto". - virtual string GetTypeName() const = 0; - - // Construct a new instance of the same type. Ownership is passed to the - // caller. - virtual MessageLite* New() const = 0; - - // Clear all fields of the message and set them to their default values. - // Clear() avoids freeing memory, assuming that any memory allocated - // to hold parts of the message will be needed again to hold the next - // message. If you actually want to free the memory used by a Message, - // you must delete it. - virtual void Clear() = 0; - - // Quickly check if all required fields have values set. - virtual bool IsInitialized() const = 0; - - // This is not implemented for Lite messages -- it just returns "(cannot - // determine missing fields for lite message)". However, it is implemented - // for full messages. See message.h. - virtual string InitializationErrorString() const; - - // If |other| is the exact same class as this, calls MergeFrom(). Otherwise, - // results are undefined (probably crash). - virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0; - - // Parsing --------------------------------------------------------- - // Methods for parsing in protocol buffer format. Most of these are - // just simple wrappers around MergeFromCodedStream(). - - // Fill the message with a protocol buffer parsed from the given input - // stream. Returns false on a read error or if the input is in the - // wrong format. - bool ParseFromCodedStream(io::CodedInputStream* input); - // Like ParseFromCodedStream(), but accepts messages that are missing - // required fields. - bool ParsePartialFromCodedStream(io::CodedInputStream* input); - // Read a protocol buffer from the given zero-copy input stream. If - // successful, the entire input will be consumed. - bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input); - // Like ParseFromZeroCopyStream(), but accepts messages that are missing - // required fields. - bool ParsePartialFromZeroCopyStream(io::ZeroCopyInputStream* input); - // Read a protocol buffer from the given zero-copy input stream, expecting - // the message to be exactly "size" bytes long. If successful, exactly - // this many bytes will have been consumed from the input. - bool ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size); - // Like ParseFromBoundedZeroCopyStream(), but accepts messages that are - // missing required fields. - bool ParsePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, - int size); - // Parse a protocol buffer contained in a string. - bool ParseFromString(const string& data); - // Like ParseFromString(), but accepts messages that are missing - // required fields. - bool ParsePartialFromString(const string& data); - // Parse a protocol buffer contained in an array of bytes. - bool ParseFromArray(const void* data, int size); - // Like ParseFromArray(), but accepts messages that are missing - // required fields. - bool ParsePartialFromArray(const void* data, int size); - - - // Reads a protocol buffer from the stream and merges it into this - // Message. Singular fields read from the input overwrite what is - // already in the Message and repeated fields are appended to those - // already present. - // - // It is the responsibility of the caller to call input->LastTagWas() - // (for groups) or input->ConsumedEntireMessage() (for non-groups) after - // this returns to verify that the message's end was delimited correctly. - // - // ParsefromCodedStream() is implemented as Clear() followed by - // MergeFromCodedStream(). - bool MergeFromCodedStream(io::CodedInputStream* input); - - // Like MergeFromCodedStream(), but succeeds even if required fields are - // missing in the input. - // - // MergeFromCodedStream() is just implemented as MergePartialFromCodedStream() - // followed by IsInitialized(). - virtual bool MergePartialFromCodedStream(io::CodedInputStream* input) = 0; - - // Serialization --------------------------------------------------- - // Methods for serializing in protocol buffer format. Most of these - // are just simple wrappers around ByteSize() and SerializeWithCachedSizes(). - - // Write a protocol buffer of this message to the given output. Returns - // false on a write error. If the message is missing required fields, - // this may GOOGLE_CHECK-fail. - bool SerializeToCodedStream(io::CodedOutputStream* output) const; - // Like SerializeToCodedStream(), but allows missing required fields. - bool SerializePartialToCodedStream(io::CodedOutputStream* output) const; - // Write the message to the given zero-copy output stream. All required - // fields must be set. - bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const; - // Like SerializeToZeroCopyStream(), but allows missing required fields. - bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const; - // Serialize the message and store it in the given string. All required - // fields must be set. - bool SerializeToString(string* output) const; - // Like SerializeToString(), but allows missing required fields. - bool SerializePartialToString(string* output) const; - // Serialize the message and store it in the given byte array. All required - // fields must be set. - bool SerializeToArray(void* data, int size) const; - // Like SerializeToArray(), but allows missing required fields. - bool SerializePartialToArray(void* data, int size) const; - - // Make a string encoding the message. Is equivalent to calling - // SerializeToString() on a string and using that. Returns the empty - // string if SerializeToString() would have returned an error. - // Note: If you intend to generate many such strings, you may - // reduce heap fragmentation by instead re-using the same string - // object with calls to SerializeToString(). - string SerializeAsString() const; - // Like SerializeAsString(), but allows missing required fields. - string SerializePartialAsString() const; - - // Like SerializeToString(), but appends to the data to the string's existing - // contents. All required fields must be set. - bool AppendToString(string* output) const; - // Like AppendToString(), but allows missing required fields. - bool AppendPartialToString(string* output) const; - - // Computes the serialized size of the message. This recursively calls - // ByteSize() on all embedded messages. If a subclass does not override - // this, it MUST override SetCachedSize(). - virtual int ByteSize() const = 0; - - // Serializes the message without recomputing the size. The message must - // not have changed since the last call to ByteSize(); if it has, the results - // are undefined. - virtual void SerializeWithCachedSizes( - io::CodedOutputStream* output) const = 0; - - // Like SerializeWithCachedSizes, but writes directly to *target, returning - // a pointer to the byte immediately after the last byte written. "target" - // must point at a byte array of at least ByteSize() bytes. - virtual uint8* SerializeWithCachedSizesToArray(uint8* target) const; - - // Returns the result of the last call to ByteSize(). An embedded message's - // size is needed both to serialize it (because embedded messages are - // length-delimited) and to compute the outer message's size. Caching - // the size avoids computing it multiple times. - // - // ByteSize() does not automatically use the cached size when available - // because this would require invalidating it every time the message was - // modified, which would be too hard and expensive. (E.g. if a deeply-nested - // sub-message is changed, all of its parents' cached sizes would need to be - // invalidated, which is too much work for an otherwise inlined setter - // method.) - virtual int GetCachedSize() const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_MESSAGE_LITE_H__ diff --git a/Resources/NetHook/google/protobuf/message_unittest.cc b/Resources/NetHook/google/protobuf/message_unittest.cc deleted file mode 100644 index 33b9e77c..00000000 --- a/Resources/NetHook/google/protobuf/message_unittest.cc +++ /dev/null @@ -1,281 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#ifdef _MSC_VER -#include -#else -#include -#endif -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace google { -namespace protobuf { - -#ifndef O_BINARY -#ifdef _O_BINARY -#define O_BINARY _O_BINARY -#else -#define O_BINARY 0 // If this isn't defined, the platform doesn't need it. -#endif -#endif - -TEST(MessageTest, SerializeHelpers) { - // TODO(kenton): Test more helpers? They're all two-liners so it seems - // like a waste of time. - - protobuf_unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - stringstream stream; - - string str1("foo"); - string str2("bar"); - - EXPECT_TRUE(message.SerializeToString(&str1)); - EXPECT_TRUE(message.AppendToString(&str2)); - EXPECT_TRUE(message.SerializeToOstream(&stream)); - - EXPECT_EQ(str1.size() + 3, str2.size()); - EXPECT_EQ("bar", str2.substr(0, 3)); - // Don't use EXPECT_EQ because we don't want to dump raw binary data to - // stdout. - EXPECT_TRUE(str2.substr(3) == str1); - - // GCC gives some sort of error if we try to just do stream.str() == str1. - string temp = stream.str(); - EXPECT_TRUE(temp == str1); - - EXPECT_TRUE(message.SerializeAsString() == str1); - -} - -TEST(MessageTest, SerializeToBrokenOstream) { - ofstream out; - protobuf_unittest::TestAllTypes message; - message.set_optional_int32(123); - - EXPECT_FALSE(message.SerializeToOstream(&out)); -} - -TEST(MessageTest, ParseFromFileDescriptor) { - string filename = TestSourceDir() + - "/google/protobuf/testdata/golden_message"; - int file = open(filename.c_str(), O_RDONLY | O_BINARY); - - unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromFileDescriptor(file)); - TestUtil::ExpectAllFieldsSet(message); - - EXPECT_GE(close(file), 0); -} - -TEST(MessageTest, ParsePackedFromFileDescriptor) { - string filename = - TestSourceDir() + - "/google/protobuf/testdata/golden_packed_fields_message"; - int file = open(filename.c_str(), O_RDONLY | O_BINARY); - - unittest::TestPackedTypes message; - EXPECT_TRUE(message.ParseFromFileDescriptor(file)); - TestUtil::ExpectPackedFieldsSet(message); - - EXPECT_GE(close(file), 0); -} - -TEST(MessageTest, ParseHelpers) { - // TODO(kenton): Test more helpers? They're all two-liners so it seems - // like a waste of time. - string data; - - { - // Set up. - protobuf_unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - message.SerializeToString(&data); - } - - { - // Test ParseFromString. - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromString(data)); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test ParseFromIstream. - protobuf_unittest::TestAllTypes message; - stringstream stream(data); - EXPECT_TRUE(message.ParseFromIstream(&stream)); - EXPECT_TRUE(stream.eof()); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test ParseFromBoundedZeroCopyStream. - string data_with_junk(data); - data_with_junk.append("some junk on the end"); - io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size()); - protobuf_unittest::TestAllTypes message; - EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size())); - TestUtil::ExpectAllFieldsSet(message); - } - - { - // Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if - // EOF is reached before the expected number of bytes. - io::ArrayInputStream stream(data.data(), data.size()); - protobuf_unittest::TestAllTypes message; - EXPECT_FALSE( - message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1)); - } -} - -TEST(MessageTest, ParseFailsIfNotInitialized) { - unittest::TestRequired message; - vector errors; - - { - ScopedMemoryLog log; - EXPECT_FALSE(message.ParseFromString("")); - errors = log.GetMessages(ERROR); - } - - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Can't parse message of type \"protobuf_unittest.TestRequired\" " - "because it is missing required fields: a, b, c", - errors[0]); -} - -TEST(MessageTest, BypassInitializationCheckOnParse) { - unittest::TestRequired message; - io::ArrayInputStream raw_input(NULL, 0); - io::CodedInputStream input(&raw_input); - EXPECT_TRUE(message.MergePartialFromCodedStream(&input)); -} - -TEST(MessageTest, InitializationErrorString) { - unittest::TestRequired message; - EXPECT_EQ("a, b, c", message.InitializationErrorString()); -} - -#ifdef GTEST_HAS_DEATH_TEST // death tests do not work on Windows yet. - -TEST(MessageTest, SerializeFailsIfNotInitialized) { - unittest::TestRequired message; - string data; - EXPECT_DEBUG_DEATH(EXPECT_TRUE(message.SerializeToString(&data)), - "Can't serialize message of type \"protobuf_unittest.TestRequired\" because " - "it is missing required fields: a, b, c"); -} - -TEST(MessageTest, CheckInitialized) { - unittest::TestRequired message; - EXPECT_DEATH(message.CheckInitialized(), - "Message of type \"protobuf_unittest.TestRequired\" is missing required " - "fields: a, b, c"); -} - -#endif // GTEST_HAS_DEATH_TEST - -TEST(MessageTest, BypassInitializationCheckOnSerialize) { - unittest::TestRequired message; - io::ArrayOutputStream raw_output(NULL, 0); - io::CodedOutputStream output(&raw_output); - EXPECT_TRUE(message.SerializePartialToCodedStream(&output)); -} - -TEST(MessageTest, FindInitializationErrors) { - unittest::TestRequired message; - vector errors; - message.FindInitializationErrors(&errors); - ASSERT_EQ(3, errors.size()); - EXPECT_EQ("a", errors[0]); - EXPECT_EQ("b", errors[1]); - EXPECT_EQ("c", errors[2]); -} - -TEST(MessageTest, ParseFailsOnInvalidMessageEnd) { - unittest::TestAllTypes message; - - // Control case. - EXPECT_TRUE(message.ParseFromArray("", 0)); - - // The byte is a valid varint, but not a valid tag (zero). - EXPECT_FALSE(message.ParseFromArray("\0", 1)); - - // The byte is a malformed varint. - EXPECT_FALSE(message.ParseFromArray("\200", 1)); - - // The byte is an endgroup tag, but we aren't parsing a group. - EXPECT_FALSE(message.ParseFromArray("\014", 1)); -} - -TEST(MessageFactoryTest, GeneratedFactoryLookup) { - EXPECT_EQ( - MessageFactory::generated_factory()->GetPrototype( - protobuf_unittest::TestAllTypes::descriptor()), - &protobuf_unittest::TestAllTypes::default_instance()); -} - -TEST(MessageFactoryTest, GeneratedFactoryUnknownType) { - // Construct a new descriptor. - DescriptorPool pool; - FileDescriptorProto file; - file.set_name("foo.proto"); - file.add_message_type()->set_name("Foo"); - const Descriptor* descriptor = pool.BuildFile(file)->message_type(0); - - // Trying to construct it should return NULL. - EXPECT_TRUE( - MessageFactory::generated_factory()->GetPrototype(descriptor) == NULL); -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/package_info.h b/Resources/NetHook/google/protobuf/package_info.h deleted file mode 100644 index 60cd3994..00000000 --- a/Resources/NetHook/google/protobuf/package_info.h +++ /dev/null @@ -1,64 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file exists solely to document the google::protobuf namespace. -// It is not compiled into anything, but it may be read by an automated -// documentation generator. - -namespace google { - -// Core components of the Protocol Buffers runtime library. -// -// The files in this package represent the core of the Protocol Buffer -// system. All of them are part of the libprotobuf library. -// -// A note on thread-safety: -// -// Thread-safety in the Protocol Buffer library follows a simple rule: -// unless explicitly noted otherwise, it is always safe to use an object -// from multiple threads simultaneously as long as the object is declared -// const in all threads (or, it is only used in ways that would be allowed -// if it were declared const). However, if an object is accessed in one -// thread in a way that would not be allowed if it were const, then it is -// not safe to access that object in any other thread simultaneously. -// -// Put simply, read-only access to an object can happen in multiple threads -// simultaneously, but write access can only happen in a single thread at -// a time. -// -// The implementation does contain some "const" methods which actually modify -// the object behind the scenes -- e.g., to cache results -- but in these cases -// mutex locking is used to make the access thread-safe. -namespace protobuf {} -} // namespace google diff --git a/Resources/NetHook/google/protobuf/reflection_ops.cc b/Resources/NetHook/google/protobuf/reflection_ops.cc deleted file mode 100644 index 897c0d7c..00000000 --- a/Resources/NetHook/google/protobuf/reflection_ops.cc +++ /dev/null @@ -1,262 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { - -void ReflectionOps::Copy(const Message& from, Message* to) { - if (&from == to) return; - Clear(to); - Merge(from, to); -} - -void ReflectionOps::Merge(const Message& from, Message* to) { - GOOGLE_CHECK_NE(&from, to); - - const Descriptor* descriptor = from.GetDescriptor(); - GOOGLE_CHECK_EQ(to->GetDescriptor(), descriptor) - << "Tried to merge messages of different types."; - - const Reflection* from_reflection = from.GetReflection(); - const Reflection* to_reflection = to->GetReflection(); - - vector fields; - from_reflection->ListFields(from, &fields); - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - - if (field->is_repeated()) { - int count = from_reflection->FieldSize(from, field); - for (int j = 0; j < count; j++) { - switch (field->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, METHOD) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - to_reflection->Add##METHOD(to, field, \ - from_reflection->GetRepeated##METHOD(from, field, j)); \ - break; - - HANDLE_TYPE(INT32 , Int32 ); - HANDLE_TYPE(INT64 , Int64 ); - HANDLE_TYPE(UINT32, UInt32); - HANDLE_TYPE(UINT64, UInt64); - HANDLE_TYPE(FLOAT , Float ); - HANDLE_TYPE(DOUBLE, Double); - HANDLE_TYPE(BOOL , Bool ); - HANDLE_TYPE(STRING, String); - HANDLE_TYPE(ENUM , Enum ); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_MESSAGE: - to_reflection->AddMessage(to, field)->MergeFrom( - from_reflection->GetRepeatedMessage(from, field, j)); - break; - } - } - } else { - switch (field->cpp_type()) { -#define HANDLE_TYPE(CPPTYPE, METHOD) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - to_reflection->Set##METHOD(to, field, \ - from_reflection->Get##METHOD(from, field)); \ - break; - - HANDLE_TYPE(INT32 , Int32 ); - HANDLE_TYPE(INT64 , Int64 ); - HANDLE_TYPE(UINT32, UInt32); - HANDLE_TYPE(UINT64, UInt64); - HANDLE_TYPE(FLOAT , Float ); - HANDLE_TYPE(DOUBLE, Double); - HANDLE_TYPE(BOOL , Bool ); - HANDLE_TYPE(STRING, String); - HANDLE_TYPE(ENUM , Enum ); -#undef HANDLE_TYPE - - case FieldDescriptor::CPPTYPE_MESSAGE: - to_reflection->MutableMessage(to, field)->MergeFrom( - from_reflection->GetMessage(from, field)); - break; - } - } - } - - to_reflection->MutableUnknownFields(to)->MergeFrom( - from_reflection->GetUnknownFields(from)); -} - -void ReflectionOps::Clear(Message* message) { - const Reflection* reflection = message->GetReflection(); - - vector fields; - reflection->ListFields(*message, &fields); - for (int i = 0; i < fields.size(); i++) { - reflection->ClearField(message, fields[i]); - } - - reflection->MutableUnknownFields(message)->Clear(); -} - -bool ReflectionOps::IsInitialized(const Message& message) { - const Descriptor* descriptor = message.GetDescriptor(); - const Reflection* reflection = message.GetReflection(); - - // Check required fields of this message. - for (int i = 0; i < descriptor->field_count(); i++) { - if (descriptor->field(i)->is_required()) { - if (!reflection->HasField(message, descriptor->field(i))) { - return false; - } - } - } - - // Check that sub-messages are initialized. - vector fields; - reflection->ListFields(message, &fields); - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (field->is_repeated()) { - int size = reflection->FieldSize(message, field); - - for (int i = 0; i < size; i++) { - if (!reflection->GetRepeatedMessage(message, field, i) - .IsInitialized()) { - return false; - } - } - } else { - if (!reflection->GetMessage(message, field).IsInitialized()) { - return false; - } - } - } - } - - return true; -} - -void ReflectionOps::DiscardUnknownFields(Message* message) { - const Reflection* reflection = message->GetReflection(); - - reflection->MutableUnknownFields(message)->Clear(); - - vector fields; - reflection->ListFields(*message, &fields); - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (field->is_repeated()) { - int size = reflection->FieldSize(*message, field); - for (int i = 0; i < size; i++) { - reflection->MutableRepeatedMessage(message, field, i) - ->DiscardUnknownFields(); - } - } else { - reflection->MutableMessage(message, field)->DiscardUnknownFields(); - } - } - } -} - -static string SubMessagePrefix(const string& prefix, - const FieldDescriptor* field, - int index) { - string result(prefix); - if (field->is_extension()) { - result.append("("); - result.append(field->full_name()); - result.append(")"); - } else { - result.append(field->name()); - } - if (index != -1) { - result.append("["); - result.append(SimpleItoa(index)); - result.append("]"); - } - result.append("."); - return result; -} - -void ReflectionOps::FindInitializationErrors( - const Message& message, - const string& prefix, - vector* errors) { - const Descriptor* descriptor = message.GetDescriptor(); - const Reflection* reflection = message.GetReflection(); - - // Check required fields of this message. - for (int i = 0; i < descriptor->field_count(); i++) { - if (descriptor->field(i)->is_required()) { - if (!reflection->HasField(message, descriptor->field(i))) { - errors->push_back(prefix + descriptor->field(i)->name()); - } - } - } - - // Check sub-messages. - vector fields; - reflection->ListFields(message, &fields); - for (int i = 0; i < fields.size(); i++) { - const FieldDescriptor* field = fields[i]; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - - if (field->is_repeated()) { - int size = reflection->FieldSize(message, field); - - for (int i = 0; i < size; i++) { - const Message& sub_message = - reflection->GetRepeatedMessage(message, field, i); - FindInitializationErrors(sub_message, - SubMessagePrefix(prefix, field, i), - errors); - } - } else { - const Message& sub_message = reflection->GetMessage(message, field); - FindInitializationErrors(sub_message, - SubMessagePrefix(prefix, field, -1), - errors); - } - } - } -} - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/reflection_ops.h b/Resources/NetHook/google/protobuf/reflection_ops.h deleted file mode 100644 index 355a0a5d..00000000 --- a/Resources/NetHook/google/protobuf/reflection_ops.h +++ /dev/null @@ -1,80 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This header is logically internal, but is made public because it is used -// from protocol-compiler-generated code, which may reside in other components. - -#ifndef GOOGLE_PROTOBUF_REFLECTION_OPS_H__ -#define GOOGLE_PROTOBUF_REFLECTION_OPS_H__ - -#include - -namespace google { -namespace protobuf { -namespace internal { - -// Basic operations that can be performed using reflection. -// These can be used as a cheap way to implement the corresponding -// methods of the Message interface, though they are likely to be -// slower than implementations tailored for the specific message type. -// -// This class should stay limited to operations needed to implement -// the Message interface. -// -// This class is really a namespace that contains only static methods. -class LIBPROTOBUF_EXPORT ReflectionOps { - public: - static void Copy(const Message& from, Message* to); - static void Merge(const Message& from, Message* to); - static void Clear(Message* message); - static bool IsInitialized(const Message& message); - static void DiscardUnknownFields(Message* message); - - // Finds all unset required fields in the message and adds their full - // paths (e.g. "foo.bar[5].baz") to *names. "prefix" will be attached to - // the front of each name. - static void FindInitializationErrors(const Message& message, - const string& prefix, - vector* errors); - - private: - // All methods are static. No need to construct. - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionOps); -}; - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_REFLECTION_OPS_H__ diff --git a/Resources/NetHook/google/protobuf/reflection_ops_unittest.cc b/Resources/NetHook/google/protobuf/reflection_ops_unittest.cc deleted file mode 100644 index 1cd56f1e..00000000 --- a/Resources/NetHook/google/protobuf/reflection_ops_unittest.cc +++ /dev/null @@ -1,405 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { -namespace { - -TEST(ReflectionOpsTest, SanityCheck) { - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(ReflectionOpsTest, Copy) { - unittest::TestAllTypes message, message2; - - TestUtil::SetAllFields(&message); - - ReflectionOps::Copy(message, &message2); - - TestUtil::ExpectAllFieldsSet(message2); - - // Copying from self should be a no-op. - ReflectionOps::Copy(message2, &message2); - TestUtil::ExpectAllFieldsSet(message2); -} - -TEST(ReflectionOpsTest, CopyExtensions) { - unittest::TestAllExtensions message, message2; - - TestUtil::SetAllExtensions(&message); - - ReflectionOps::Copy(message, &message2); - - TestUtil::ExpectAllExtensionsSet(message2); -} - -TEST(ReflectionOpsTest, Merge) { - // Note: Copy is implemented in terms of Merge() so technically the Copy - // test already tested most of this. - - unittest::TestAllTypes message, message2; - - TestUtil::SetAllFields(&message); - - // This field will test merging into an empty spot. - message2.set_optional_int32(message.optional_int32()); - message.clear_optional_int32(); - - // This tests overwriting. - message2.set_optional_string(message.optional_string()); - message.set_optional_string("something else"); - - // This tests concatenating. - message2.add_repeated_int32(message.repeated_int32(1)); - int32 i = message.repeated_int32(0); - message.clear_repeated_int32(); - message.add_repeated_int32(i); - - ReflectionOps::Merge(message2, &message); - - TestUtil::ExpectAllFieldsSet(message); -} - -TEST(ReflectionOpsTest, MergeExtensions) { - // Note: Copy is implemented in terms of Merge() so technically the Copy - // test already tested most of this. - - unittest::TestAllExtensions message, message2; - - TestUtil::SetAllExtensions(&message); - - // This field will test merging into an empty spot. - message2.SetExtension(unittest::optional_int32_extension, - message.GetExtension(unittest::optional_int32_extension)); - message.ClearExtension(unittest::optional_int32_extension); - - // This tests overwriting. - message2.SetExtension(unittest::optional_string_extension, - message.GetExtension(unittest::optional_string_extension)); - message.SetExtension(unittest::optional_string_extension, "something else"); - - // This tests concatenating. - message2.AddExtension(unittest::repeated_int32_extension, - message.GetExtension(unittest::repeated_int32_extension, 1)); - int32 i = message.GetExtension(unittest::repeated_int32_extension, 0); - message.ClearExtension(unittest::repeated_int32_extension); - message.AddExtension(unittest::repeated_int32_extension, i); - - ReflectionOps::Merge(message2, &message); - - TestUtil::ExpectAllExtensionsSet(message); -} - -TEST(ReflectionOpsTest, MergeUnknown) { - // Test that the messages' UnknownFieldSets are correctly merged. - unittest::TestEmptyMessage message1, message2; - message1.mutable_unknown_fields()->AddVarint(1234, 1); - message2.mutable_unknown_fields()->AddVarint(1234, 2); - - ReflectionOps::Merge(message2, &message1); - - ASSERT_EQ(2, message1.unknown_fields().field_count()); - ASSERT_EQ(UnknownField::TYPE_VARINT, - message1.unknown_fields().field(0).type()); - EXPECT_EQ(1, message1.unknown_fields().field(0).varint()); - ASSERT_EQ(UnknownField::TYPE_VARINT, - message1.unknown_fields().field(1).type()); - EXPECT_EQ(2, message1.unknown_fields().field(1).varint()); -} - -#ifdef GTEST_HAS_DEATH_TEST - -TEST(ReflectionOpsTest, MergeFromSelf) { - // Note: Copy is implemented in terms of Merge() so technically the Copy - // test already tested most of this. - - unittest::TestAllTypes message; - - EXPECT_DEATH( - ReflectionOps::Merge(message, &message), - "&from"); -} - -#endif // GTEST_HAS_DEATH_TEST - -TEST(ReflectionOpsTest, Clear) { - unittest::TestAllTypes message; - - TestUtil::SetAllFields(&message); - - ReflectionOps::Clear(&message); - - TestUtil::ExpectClear(message); - - // Check that getting embedded messages returns the objects created during - // SetAllFields() rather than default instances. - EXPECT_NE(&unittest::TestAllTypes::OptionalGroup::default_instance(), - &message.optionalgroup()); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.optional_nested_message()); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.optional_foreign_message()); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &message.optional_import_message()); -} - -TEST(ReflectionOpsTest, ClearExtensions) { - unittest::TestAllExtensions message; - - TestUtil::SetAllExtensions(&message); - - ReflectionOps::Clear(&message); - - TestUtil::ExpectExtensionsClear(message); - - // Check that getting embedded messages returns the objects created during - // SetAllExtensions() rather than default instances. - EXPECT_NE(&unittest::OptionalGroup_extension::default_instance(), - &message.GetExtension(unittest::optionalgroup_extension)); - EXPECT_NE(&unittest::TestAllTypes::NestedMessage::default_instance(), - &message.GetExtension(unittest::optional_nested_message_extension)); - EXPECT_NE(&unittest::ForeignMessage::default_instance(), - &message.GetExtension( - unittest::optional_foreign_message_extension)); - EXPECT_NE(&unittest_import::ImportMessage::default_instance(), - &message.GetExtension(unittest::optional_import_message_extension)); -} - -TEST(ReflectionOpsTest, ClearUnknown) { - // Test that the message's UnknownFieldSet is correctly cleared. - unittest::TestEmptyMessage message; - message.mutable_unknown_fields()->AddVarint(1234, 1); - - ReflectionOps::Clear(&message); - - EXPECT_EQ(0, message.unknown_fields().field_count()); -} - -TEST(ReflectionOpsTest, DiscardUnknownFields) { - unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - - // Set some unknown fields in message. - message.mutable_unknown_fields() - ->AddVarint(123456, 654321); - message.mutable_optional_nested_message() - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); - message.mutable_repeated_nested_message(0) - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); - - EXPECT_EQ(1, message.unknown_fields().field_count()); - EXPECT_EQ(1, message.optional_nested_message() - .unknown_fields().field_count()); - EXPECT_EQ(1, message.repeated_nested_message(0) - .unknown_fields().field_count()); - - // Discard them. - ReflectionOps::DiscardUnknownFields(&message); - TestUtil::ExpectAllFieldsSet(message); - - EXPECT_EQ(0, message.unknown_fields().field_count()); - EXPECT_EQ(0, message.optional_nested_message() - .unknown_fields().field_count()); - EXPECT_EQ(0, message.repeated_nested_message(0) - .unknown_fields().field_count()); -} - -TEST(ReflectionOpsTest, DiscardUnknownExtensions) { - unittest::TestAllExtensions message; - TestUtil::SetAllExtensions(&message); - - // Set some unknown fields. - message.mutable_unknown_fields() - ->AddVarint(123456, 654321); - message.MutableExtension(unittest::optional_nested_message_extension) - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); - message.MutableExtension(unittest::repeated_nested_message_extension, 0) - ->mutable_unknown_fields() - ->AddVarint(123456, 654321); - - EXPECT_EQ(1, message.unknown_fields().field_count()); - EXPECT_EQ(1, - message.GetExtension(unittest::optional_nested_message_extension) - .unknown_fields().field_count()); - EXPECT_EQ(1, - message.GetExtension(unittest::repeated_nested_message_extension, 0) - .unknown_fields().field_count()); - - // Discard them. - ReflectionOps::DiscardUnknownFields(&message); - TestUtil::ExpectAllExtensionsSet(message); - - EXPECT_EQ(0, message.unknown_fields().field_count()); - EXPECT_EQ(0, - message.GetExtension(unittest::optional_nested_message_extension) - .unknown_fields().field_count()); - EXPECT_EQ(0, - message.GetExtension(unittest::repeated_nested_message_extension, 0) - .unknown_fields().field_count()); -} - -TEST(ReflectionOpsTest, IsInitialized) { - unittest::TestRequired message; - - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - message.set_a(1); - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - message.set_b(2); - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - message.set_c(3); - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); -} - -TEST(ReflectionOpsTest, ForeignIsInitialized) { - unittest::TestRequiredForeign message; - - // Starts out initialized because the foreign message is itself an optional - // field. - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); - - // Once we create that field, the message is no longer initialized. - message.mutable_optional_message(); - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - - // Initialize it. Now we're initialized. - message.mutable_optional_message()->set_a(1); - message.mutable_optional_message()->set_b(2); - message.mutable_optional_message()->set_c(3); - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); - - // Add a repeated version of the message. No longer initialized. - unittest::TestRequired* sub_message = message.add_repeated_message(); - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - - // Initialize that repeated version. - sub_message->set_a(1); - sub_message->set_b(2); - sub_message->set_c(3); - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); -} - -TEST(ReflectionOpsTest, ExtensionIsInitialized) { - unittest::TestAllExtensions message; - - // Starts out initialized because the foreign message is itself an optional - // field. - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); - - // Once we create that field, the message is no longer initialized. - message.MutableExtension(unittest::TestRequired::single); - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - - // Initialize it. Now we're initialized. - message.MutableExtension(unittest::TestRequired::single)->set_a(1); - message.MutableExtension(unittest::TestRequired::single)->set_b(2); - message.MutableExtension(unittest::TestRequired::single)->set_c(3); - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); - - // Add a repeated version of the message. No longer initialized. - message.AddExtension(unittest::TestRequired::multi); - EXPECT_FALSE(ReflectionOps::IsInitialized(message)); - - // Initialize that repeated version. - message.MutableExtension(unittest::TestRequired::multi, 0)->set_a(1); - message.MutableExtension(unittest::TestRequired::multi, 0)->set_b(2); - message.MutableExtension(unittest::TestRequired::multi, 0)->set_c(3); - EXPECT_TRUE(ReflectionOps::IsInitialized(message)); -} - -static string FindInitializationErrors(const Message& message) { - vector errors; - ReflectionOps::FindInitializationErrors(message, "", &errors); - return JoinStrings(errors, ","); -} - -TEST(ReflectionOpsTest, FindInitializationErrors) { - unittest::TestRequired message; - EXPECT_EQ("a,b,c", FindInitializationErrors(message)); -} - -TEST(ReflectionOpsTest, FindForeignInitializationErrors) { - unittest::TestRequiredForeign message; - message.mutable_optional_message(); - message.add_repeated_message(); - message.add_repeated_message(); - EXPECT_EQ("optional_message.a," - "optional_message.b," - "optional_message.c," - "repeated_message[0].a," - "repeated_message[0].b," - "repeated_message[0].c," - "repeated_message[1].a," - "repeated_message[1].b," - "repeated_message[1].c", - FindInitializationErrors(message)); -} - -TEST(ReflectionOpsTest, FindExtensionInitializationErrors) { - unittest::TestAllExtensions message; - message.MutableExtension(unittest::TestRequired::single); - message.AddExtension(unittest::TestRequired::multi); - message.AddExtension(unittest::TestRequired::multi); - EXPECT_EQ("(protobuf_unittest.TestRequired.single).a," - "(protobuf_unittest.TestRequired.single).b," - "(protobuf_unittest.TestRequired.single).c," - "(protobuf_unittest.TestRequired.multi)[0].a," - "(protobuf_unittest.TestRequired.multi)[0].b," - "(protobuf_unittest.TestRequired.multi)[0].c," - "(protobuf_unittest.TestRequired.multi)[1].a," - "(protobuf_unittest.TestRequired.multi)[1].b," - "(protobuf_unittest.TestRequired.multi)[1].c", - FindInitializationErrors(message)); -} - -} // namespace -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/repeated_field.cc b/Resources/NetHook/google/protobuf/repeated_field.cc deleted file mode 100644 index f7beb110..00000000 --- a/Resources/NetHook/google/protobuf/repeated_field.cc +++ /dev/null @@ -1,95 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - -namespace google { -namespace protobuf { -namespace internal { - -void RepeatedPtrFieldBase::Reserve(int new_size) { - if (total_size_ >= new_size) return; - - void** old_elements = elements_; - total_size_ = max(total_size_ * 2, new_size); - elements_ = new void*[total_size_]; - memcpy(elements_, old_elements, allocated_size_ * sizeof(elements_[0])); - if (old_elements != initial_space_) { - delete [] old_elements; - } -} - -void RepeatedPtrFieldBase::Swap(RepeatedPtrFieldBase* other) { - void** swap_elements = elements_; - int swap_current_size = current_size_; - int swap_allocated_size = allocated_size_; - int swap_total_size = total_size_; - // We may not be using initial_space_ but it's not worth checking. Just - // copy it anyway. - void* swap_initial_space[kInitialSize]; - memcpy(swap_initial_space, initial_space_, sizeof(initial_space_)); - - elements_ = other->elements_; - current_size_ = other->current_size_; - allocated_size_ = other->allocated_size_; - total_size_ = other->total_size_; - memcpy(initial_space_, other->initial_space_, sizeof(initial_space_)); - - other->elements_ = swap_elements; - other->current_size_ = swap_current_size; - other->allocated_size_ = swap_allocated_size; - other->total_size_ = swap_total_size; - memcpy(other->initial_space_, swap_initial_space, sizeof(swap_initial_space)); - - if (elements_ == other->initial_space_) { - elements_ = initial_space_; - } - if (other->elements_ == initial_space_) { - other->elements_ = other->initial_space_; - } -} - -string* StringTypeHandlerBase::New() { - return new string; -} -void StringTypeHandlerBase::Delete(string* value) { - delete value; -} - - -} // namespace internal - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/repeated_field.h b/Resources/NetHook/google/protobuf/repeated_field.h deleted file mode 100644 index defdefe0..00000000 --- a/Resources/NetHook/google/protobuf/repeated_field.h +++ /dev/null @@ -1,1248 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// RepeatedField and RepeatedPtrField are used by generated protocol message -// classes to manipulate repeated fields. These classes are very similar to -// STL's vector, but include a number of optimizations found to be useful -// specifically in the case of Protocol Buffers. RepeatedPtrField is -// particularly different from STL vector as it manages ownership of the -// pointers that it contains. -// -// Typically, clients should not need to access RepeatedField objects directly, -// but should instead use the accessor functions generated automatically by the -// protocol compiler. - -#ifndef GOOGLE_PROTOBUF_REPEATED_FIELD_H__ -#define GOOGLE_PROTOBUF_REPEATED_FIELD_H__ - -#include -#include -#include -#include - -namespace google { - -namespace protobuf { - -class Message; - -namespace internal { - -// We need this (from generated_message_reflection.cc). -LIBPROTOBUF_EXPORT int StringSpaceUsedExcludingSelf(const string& str); - -} // namespace internal - -// RepeatedField is used to represent repeated fields of a primitive type (in -// other words, everything except strings and nested Messages). Most users will -// not ever use a RepeatedField directly; they will use the get-by-index, -// set-by-index, and add accessors that are generated for all repeated fields. -template -class RepeatedField { - public: - RepeatedField(); - ~RepeatedField(); - - int size() const; - - const Element& Get(int index) const; - Element* Mutable(int index); - void Set(int index, const Element& value); - void Add(const Element& value); - Element* Add(); - // Remove the last element in the array. - // We don't provide a way to remove any element other than the last - // because it invites inefficient use, such as O(n^2) filtering loops - // that should have been O(n). If you want to remove an element other - // than the last, the best way to do it is to re-arrange the elements - // so that the one you want removed is at the end, then call RemoveLast(). - void RemoveLast(); - void Clear(); - void MergeFrom(const RepeatedField& other); - - // Reserve space to expand the field to at least the given size. If the - // array is grown, it will always be at least doubled in size. - void Reserve(int new_size); - - // Resize the RepeatedField to a new, smaller size. This is O(1). - void Truncate(int new_size); - - void AddAlreadyReserved(const Element& value); - Element* AddAlreadyReserved(); - int Capacity() const; - - // Gets the underlying array. This pointer is possibly invalidated by - // any add or remove operation. - Element* mutable_data(); - const Element* data() const; - - // Swap entire contents with "other". - void Swap(RepeatedField* other); - - // Swap two elements. - void SwapElements(int index1, int index2); - - // STL-like iterator support - typedef Element* iterator; - typedef const Element* const_iterator; - - iterator begin(); - const_iterator begin() const; - iterator end(); - const_iterator end() const; - - // Returns the number of bytes used by the repeated field, excluding - // sizeof(*this) - int SpaceUsedExcludingSelf() const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedField); - - static const int kInitialSize = 4; - - Element* elements_; - int current_size_; - int total_size_; - - Element initial_space_[kInitialSize]; - - // Move the contents of |from| into |to|, possibly clobbering |from| in the - // process. For primitive types this is just a memcpy(), but it could be - // specialized for non-primitive types to, say, swap each element instead. - void MoveArray(Element to[], Element from[], int size); - - // Copy the elements of |from| into |to|. - void CopyArray(Element to[], const Element from[], int size); -}; - -namespace internal { -template class RepeatedPtrIterator; -template class RepeatedPtrOverPtrsIterator; -} // namespace internal - -namespace internal { - -// This is the common base class for RepeatedPtrFields. It deals only in void* -// pointers. Users should not use this interface directly. -// -// The methods of this interface correspond to the methods of RepeatedPtrField, -// but may have a template argument called TypeHandler. Its signature is: -// class TypeHandler { -// public: -// typedef MyType Type; -// static Type* New(); -// static void Delete(Type*); -// static void Clear(Type*); -// static void Merge(const Type& from, Type* to); -// -// // Only needs to be implemented if SpaceUsedExcludingSelf() is called. -// static int SpaceUsed(const Type&); -// }; -class LIBPROTOBUF_EXPORT RepeatedPtrFieldBase { - protected: - // The reflection implementation needs to call protected methods directly, - // reinterpreting pointers as being to Message instead of a specific Message - // subclass. - friend class GeneratedMessageReflection; - - // ExtensionSet stores repeated message extensions as - // RepeatedPtrField, but non-lite ExtensionSets need to - // implement SpaceUsed(), and thus need to call SpaceUsedExcludingSelf() - // reinterpreting MessageLite as Message. ExtensionSet also needs to make - // use of AddFromCleared(), which is not part of the public interface. - friend class ExtensionSet; - - RepeatedPtrFieldBase(); - - // Must be called from destructor. - template - void Destroy(); - - int size() const; - - template - const typename TypeHandler::Type& Get(int index) const; - template - typename TypeHandler::Type* Mutable(int index); - template - typename TypeHandler::Type* Add(); - template - void RemoveLast(); - template - void Clear(); - template - void MergeFrom(const RepeatedPtrFieldBase& other); - - void Reserve(int new_size); - - int Capacity() const; - - // Used for constructing iterators. - void* const* raw_data() const; - void** raw_mutable_data() const; - - template - typename TypeHandler::Type** mutable_data(); - template - const typename TypeHandler::Type* const* data() const; - - void Swap(RepeatedPtrFieldBase* other); - - void SwapElements(int index1, int index2); - - template - int SpaceUsedExcludingSelf() const; - - - // Advanced memory management -------------------------------------- - - // Like Add(), but if there are no cleared objects to use, returns NULL. - template - typename TypeHandler::Type* AddFromCleared(); - - template - void AddAllocated(typename TypeHandler::Type* value); - template - typename TypeHandler::Type* ReleaseLast(); - - int ClearedCount() const; - template - void AddCleared(typename TypeHandler::Type* value); - template - typename TypeHandler::Type* ReleaseCleared(); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPtrFieldBase); - - static const int kInitialSize = 4; - - void** elements_; - int current_size_; - int allocated_size_; - int total_size_; - - void* initial_space_[kInitialSize]; - - template - static inline typename TypeHandler::Type* cast(void* element) { - return reinterpret_cast(element); - } - template - static inline const typename TypeHandler::Type* cast(const void* element) { - return reinterpret_cast(element); - } -}; - -template -class GenericTypeHandler { - public: - typedef GenericType Type; - static GenericType* New() { return new GenericType; } - static void Delete(GenericType* value) { delete value; } - static void Clear(GenericType* value) { value->Clear(); } - static void Merge(const GenericType& from, GenericType* to) { - to->MergeFrom(from); - } - static int SpaceUsed(const GenericType& value) { return value.SpaceUsed(); } -}; - -template <> -inline void GenericTypeHandler::Merge( - const MessageLite& from, MessageLite* to) { - to->CheckTypeAndMergeFrom(from); -} - -// HACK: If a class is declared as DLL-exported in MSVC, it insists on -// generating copies of all its methods -- even inline ones -- to include -// in the DLL. But SpaceUsed() calls StringSpaceUsedExcludingSelf() which -// isn't in the lite library, therefore the lite library cannot link if -// StringTypeHandler is exported. So, we factor out StringTypeHandlerBase, -// export that, then make StringTypeHandler be a subclass which is NOT -// exported. -// TODO(kenton): There has to be a better way. -class LIBPROTOBUF_EXPORT StringTypeHandlerBase { - public: - typedef string Type; - static string* New(); - static void Delete(string* value); - static void Clear(string* value) { value->clear(); } - static void Merge(const string& from, string* to) { *to = from; } -}; - -class StringTypeHandler : public StringTypeHandlerBase { - public: - static int SpaceUsed(const string& value) { - return sizeof(value) + StringSpaceUsedExcludingSelf(value); - } -}; - - -} // namespace internal - -// RepeatedPtrField is like RepeatedField, but used for repeated strings or -// Messages. -template -class RepeatedPtrField : public internal::RepeatedPtrFieldBase { - public: - RepeatedPtrField(); - - ~RepeatedPtrField(); - - int size() const; - - const Element& Get(int index) const; - Element* Mutable(int index); - Element* Add(); - void RemoveLast(); // Remove the last element in the array. - void Clear(); - void MergeFrom(const RepeatedPtrField& other); - - // Reserve space to expand the field to at least the given size. This only - // resizes the pointer array; it doesn't allocate any objects. If the - // array is grown, it will always be at least doubled in size. - void Reserve(int new_size); - - int Capacity() const; - - // Gets the underlying array. This pointer is possibly invalidated by - // any add or remove operation. - Element** mutable_data(); - const Element* const* data() const; - - // Swap entire contents with "other". - void Swap(RepeatedPtrField* other); - - // Swap two elements. - void SwapElements(int index1, int index2); - - // STL-like iterator support - typedef internal::RepeatedPtrIterator iterator; - typedef internal::RepeatedPtrIterator const_iterator; - - iterator begin(); - const_iterator begin() const; - iterator end(); - const_iterator end() const; - - // Custom STL-like iterator that iterates over and returns the underlying - // pointers to Element rather than Element itself. - typedef internal::RepeatedPtrOverPtrsIterator pointer_iterator; - pointer_iterator pointer_begin(); - pointer_iterator pointer_end(); - - // Returns (an estimate of) the number of bytes used by the repeated field, - // excluding sizeof(*this). - int SpaceUsedExcludingSelf() const; - - // The spaced used just by the pointer array, not counting the objects pointed - // at. Returns zero if the array is inlined (i.e. initial_space_ is being - // used). - int SpaceUsedByArray() const; - - // Advanced memory management -------------------------------------- - // When hardcore memory management becomes necessary -- as it often - // does here at Google -- the following methods may be useful. - - // Add an already-allocated object, passing ownership to the - // RepeatedPtrField. - void AddAllocated(Element* value); - // Remove the last element and return it, passing ownership to the - // caller. - // Requires: size() > 0 - Element* ReleaseLast(); - - // When elements are removed by calls to RemoveLast() or Clear(), they - // are not actually freed. Instead, they are cleared and kept so that - // they can be reused later. This can save lots of CPU time when - // repeatedly reusing a protocol message for similar purposes. - // - // Really, extremely hardcore programs may actually want to manipulate - // these objects to better-optimize memory management. These methods - // allow that. - - // Get the number of cleared objects that are currently being kept - // around for reuse. - int ClearedCount() const; - // Add an element to the pool of cleared objects, passing ownership to - // the RepeatedPtrField. The element must be cleared prior to calling - // this method. - void AddCleared(Element* value); - // Remove a single element from the cleared pool and return it, passing - // ownership to the caller. The element is guaranteed to be cleared. - // Requires: ClearedCount() > 0 - Element* ReleaseCleared(); - - protected: - // Note: RepeatedPtrField SHOULD NOT be subclassed by users. We only - // subclass it in one place as a hack for compatibility with proto1. The - // subclass needs to know about TypeHandler in order to call protected - // methods on RepeatedPtrFieldBase. - class TypeHandler; - - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPtrField); -}; - -// implementation ==================================================== - -template -inline RepeatedField::RepeatedField() - : elements_(initial_space_), - current_size_(0), - total_size_(kInitialSize) { -} - -template -RepeatedField::~RepeatedField() { - if (elements_ != initial_space_) { - delete [] elements_; - } -} - -template -inline int RepeatedField::size() const { - return current_size_; -} - -template -inline int RepeatedField::Capacity() const { - return total_size_; -} - -template -inline void RepeatedField::AddAlreadyReserved(const Element& value) { - GOOGLE_DCHECK_LT(size(), Capacity()); - elements_[current_size_++] = value; -} - -template -inline Element* RepeatedField::AddAlreadyReserved() { - GOOGLE_DCHECK_LT(size(), Capacity()); - return &elements_[current_size_++]; -} - -template -inline const Element& RepeatedField::Get(int index) const { - GOOGLE_DCHECK_LT(index, size()); - return elements_[index]; -} - -template -inline Element* RepeatedField::Mutable(int index) { - GOOGLE_DCHECK_LT(index, size()); - return elements_ + index; -} - -template -inline void RepeatedField::Set(int index, const Element& value) { - GOOGLE_DCHECK_LT(index, size()); - elements_[index] = value; -} - -template -inline void RepeatedField::Add(const Element& value) { - if (current_size_ == total_size_) Reserve(total_size_ + 1); - elements_[current_size_++] = value; -} - -template -inline Element* RepeatedField::Add() { - if (current_size_ == total_size_) Reserve(total_size_ + 1); - return &elements_[current_size_++]; -} - -template -inline void RepeatedField::RemoveLast() { - GOOGLE_DCHECK_GT(current_size_, 0); - --current_size_; -} - -template -inline void RepeatedField::Clear() { - current_size_ = 0; -} - -template -inline void RepeatedField::MergeFrom(const RepeatedField& other) { - Reserve(current_size_ + other.current_size_); - CopyArray(elements_ + current_size_, other.elements_, other.current_size_); - current_size_ += other.current_size_; -} - -template -inline Element* RepeatedField::mutable_data() { - return elements_; -} - -template -inline const Element* RepeatedField::data() const { - return elements_; -} - - -template -void RepeatedField::Swap(RepeatedField* other) { - Element* swap_elements = elements_; - int swap_current_size = current_size_; - int swap_total_size = total_size_; - // We may not be using initial_space_ but it's not worth checking. Just - // copy it anyway. - Element swap_initial_space[kInitialSize]; - MoveArray(swap_initial_space, initial_space_, kInitialSize); - - elements_ = other->elements_; - current_size_ = other->current_size_; - total_size_ = other->total_size_; - MoveArray(initial_space_, other->initial_space_, kInitialSize); - - other->elements_ = swap_elements; - other->current_size_ = swap_current_size; - other->total_size_ = swap_total_size; - MoveArray(other->initial_space_, swap_initial_space, kInitialSize); - - if (elements_ == other->initial_space_) { - elements_ = initial_space_; - } - if (other->elements_ == initial_space_) { - other->elements_ = other->initial_space_; - } -} - -template -void RepeatedField::SwapElements(int index1, int index2) { - std::swap(elements_[index1], elements_[index2]); -} - -template -inline typename RepeatedField::iterator -RepeatedField::begin() { - return elements_; -} -template -inline typename RepeatedField::const_iterator -RepeatedField::begin() const { - return elements_; -} -template -inline typename RepeatedField::iterator -RepeatedField::end() { - return elements_ + current_size_; -} -template -inline typename RepeatedField::const_iterator -RepeatedField::end() const { - return elements_ + current_size_; -} - -template -inline int RepeatedField::SpaceUsedExcludingSelf() const { - return (elements_ != initial_space_) ? total_size_ * sizeof(elements_[0]) : 0; -} - -// Avoid inlining of Reserve(): new, memcpy, and delete[] lead to a significant -// amount of code bloat. -template -void RepeatedField::Reserve(int new_size) { - if (total_size_ >= new_size) return; - - Element* old_elements = elements_; - total_size_ = max(total_size_ * 2, new_size); - elements_ = new Element[total_size_]; - MoveArray(elements_, old_elements, current_size_); - if (old_elements != initial_space_) { - delete [] old_elements; - } -} - -template -inline void RepeatedField::Truncate(int new_size) { - GOOGLE_DCHECK_LE(new_size, current_size_); - current_size_ = new_size; -} - -template -inline void RepeatedField::MoveArray( - Element to[], Element from[], int size) { - memcpy(to, from, size * sizeof(Element)); -} - -template -inline void RepeatedField::CopyArray( - Element to[], const Element from[], int size) { - memcpy(to, from, size * sizeof(Element)); -} - - -// ------------------------------------------------------------------- - -namespace internal { - -inline RepeatedPtrFieldBase::RepeatedPtrFieldBase() - : elements_(initial_space_), - current_size_(0), - allocated_size_(0), - total_size_(kInitialSize) { -} - -template -void RepeatedPtrFieldBase::Destroy() { - for (int i = 0; i < allocated_size_; i++) { - TypeHandler::Delete(cast(elements_[i])); - } - if (elements_ != initial_space_) { - delete [] elements_; - } -} - -inline int RepeatedPtrFieldBase::size() const { - return current_size_; -} - - -template -inline const typename TypeHandler::Type& -RepeatedPtrFieldBase::Get(int index) const { - GOOGLE_DCHECK_LT(index, size()); - return *cast(elements_[index]); -} - -template -inline typename TypeHandler::Type* -RepeatedPtrFieldBase::Mutable(int index) { - GOOGLE_DCHECK_LT(index, size()); - return cast(elements_[index]); -} - -template -inline typename TypeHandler::Type* RepeatedPtrFieldBase::Add() { - if (current_size_ < allocated_size_) { - return cast(elements_[current_size_++]); - } - if (allocated_size_ == total_size_) Reserve(total_size_ + 1); - ++allocated_size_; - typename TypeHandler::Type* result = TypeHandler::New(); - elements_[current_size_++] = result; - return result; -} - -template -inline void RepeatedPtrFieldBase::RemoveLast() { - GOOGLE_DCHECK_GT(current_size_, 0); - TypeHandler::Clear(cast(elements_[--current_size_])); -} - -template -void RepeatedPtrFieldBase::Clear() { - for (int i = 0; i < current_size_; i++) { - TypeHandler::Clear(cast(elements_[i])); - } - current_size_ = 0; -} - -template -inline void RepeatedPtrFieldBase::MergeFrom(const RepeatedPtrFieldBase& other) { - Reserve(current_size_ + other.current_size_); - for (int i = 0; i < other.current_size_; i++) { - TypeHandler::Merge(other.Get(i), Add()); - } -} - -inline int RepeatedPtrFieldBase::Capacity() const { - return total_size_; -} - -inline void* const* RepeatedPtrFieldBase::raw_data() const { - return elements_; -} - -inline void** RepeatedPtrFieldBase::raw_mutable_data() const { - return elements_; -} - -template -inline typename TypeHandler::Type** RepeatedPtrFieldBase::mutable_data() { - // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this - // method entirely. - return reinterpret_cast(elements_); -} - -template -inline const typename TypeHandler::Type* const* -RepeatedPtrFieldBase::data() const { - // TODO(kenton): Breaks C++ aliasing rules. We should probably remove this - // method entirely. - return reinterpret_cast(elements_); -} - -inline void RepeatedPtrFieldBase::SwapElements(int index1, int index2) { - std::swap(elements_[index1], elements_[index2]); -} - -template -inline int RepeatedPtrFieldBase::SpaceUsedExcludingSelf() const { - int allocated_bytes = - (elements_ != initial_space_) ? total_size_ * sizeof(elements_[0]) : 0; - for (int i = 0; i < allocated_size_; ++i) { - allocated_bytes += TypeHandler::SpaceUsed(*cast(elements_[i])); - } - return allocated_bytes; -} - -template -inline typename TypeHandler::Type* RepeatedPtrFieldBase::AddFromCleared() { - if (current_size_ < allocated_size_) { - return cast(elements_[current_size_++]); - } else { - return NULL; - } -} - -template -void RepeatedPtrFieldBase::AddAllocated( - typename TypeHandler::Type* value) { - // Make room for the new pointer. - if (current_size_ == total_size_) { - // The array is completely full with no cleared objects, so grow it. - Reserve(total_size_ + 1); - ++allocated_size_; - } else if (allocated_size_ == total_size_) { - // There is no more space in the pointer array because it contains some - // cleared objects awaiting reuse. We don't want to grow the array in this - // case because otherwise a loop calling AddAllocated() followed by Clear() - // would leak memory. - TypeHandler::Delete(cast(elements_[current_size_])); - } else if (current_size_ < allocated_size_) { - // We have some cleared objects. We don't care about their order, so we - // can just move the first one to the end to make space. - elements_[allocated_size_] = elements_[current_size_]; - ++allocated_size_; - } else { - // There are no cleared objects. - ++allocated_size_; - } - - elements_[current_size_++] = value; -} - -template -inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseLast() { - GOOGLE_DCHECK_GT(current_size_, 0); - typename TypeHandler::Type* result = - cast(elements_[--current_size_]); - --allocated_size_; - if (current_size_ < allocated_size_) { - // There are cleared elements on the end; replace the removed element - // with the last allocated element. - elements_[current_size_] = elements_[allocated_size_]; - } - return result; -} - - -inline int RepeatedPtrFieldBase::ClearedCount() const { - return allocated_size_ - current_size_; -} - -template -inline void RepeatedPtrFieldBase::AddCleared( - typename TypeHandler::Type* value) { - if (allocated_size_ == total_size_) Reserve(total_size_ + 1); - elements_[allocated_size_++] = value; -} - -template -inline typename TypeHandler::Type* RepeatedPtrFieldBase::ReleaseCleared() { - GOOGLE_DCHECK_GT(allocated_size_, current_size_); - return cast(elements_[--allocated_size_]); -} - -} // namespace internal - -// ------------------------------------------------------------------- - -template -class RepeatedPtrField::TypeHandler - : public internal::GenericTypeHandler {}; - -template <> -class RepeatedPtrField::TypeHandler - : public internal::StringTypeHandler {}; - - -template -inline RepeatedPtrField::RepeatedPtrField() {} - -template -RepeatedPtrField::~RepeatedPtrField() { - Destroy(); -} - -template -inline int RepeatedPtrField::size() const { - return RepeatedPtrFieldBase::size(); -} - -template -inline const Element& RepeatedPtrField::Get(int index) const { - return RepeatedPtrFieldBase::Get(index); -} - -template -inline Element* RepeatedPtrField::Mutable(int index) { - return RepeatedPtrFieldBase::Mutable(index); -} - -template -inline Element* RepeatedPtrField::Add() { - return RepeatedPtrFieldBase::Add(); -} - -template -inline void RepeatedPtrField::RemoveLast() { - RepeatedPtrFieldBase::RemoveLast(); -} - -template -inline void RepeatedPtrField::Clear() { - RepeatedPtrFieldBase::Clear(); -} - -template -inline void RepeatedPtrField::MergeFrom( - const RepeatedPtrField& other) { - RepeatedPtrFieldBase::MergeFrom(other); -} - -template -inline Element** RepeatedPtrField::mutable_data() { - return RepeatedPtrFieldBase::mutable_data(); -} - -template -inline const Element* const* RepeatedPtrField::data() const { - return RepeatedPtrFieldBase::data(); -} - -template -void RepeatedPtrField::Swap(RepeatedPtrField* other) { - RepeatedPtrFieldBase::Swap(other); -} - -template -void RepeatedPtrField::SwapElements(int index1, int index2) { - RepeatedPtrFieldBase::SwapElements(index1, index2); -} - -template -inline int RepeatedPtrField::SpaceUsedExcludingSelf() const { - return RepeatedPtrFieldBase::SpaceUsedExcludingSelf(); -} - -template -inline void RepeatedPtrField::AddAllocated(Element* value) { - RepeatedPtrFieldBase::AddAllocated(value); -} - -template -inline Element* RepeatedPtrField::ReleaseLast() { - return RepeatedPtrFieldBase::ReleaseLast(); -} - - -template -inline int RepeatedPtrField::ClearedCount() const { - return RepeatedPtrFieldBase::ClearedCount(); -} - -template -inline void RepeatedPtrField::AddCleared(Element* value) { - return RepeatedPtrFieldBase::AddCleared(value); -} - -template -inline Element* RepeatedPtrField::ReleaseCleared() { - return RepeatedPtrFieldBase::ReleaseCleared(); -} - -template -inline void RepeatedPtrField::Reserve(int new_size) { - return RepeatedPtrFieldBase::Reserve(new_size); -} - -template -inline int RepeatedPtrField::Capacity() const { - return RepeatedPtrFieldBase::Capacity(); -} - -// ------------------------------------------------------------------- - -namespace internal { - -// STL-like iterator implementation for RepeatedPtrField. You should not -// refer to this class directly; use RepeatedPtrField::iterator instead. -// -// The iterator for RepeatedPtrField, RepeatedPtrIterator, is -// very similar to iterator_ptr in util/gtl/iterator_adaptors-inl.h, -// but adds random-access operators and is modified to wrap a void** base -// iterator (since RepeatedPtrField stores its array as a void* array and -// casting void** to T** would violate C++ aliasing rules). -// -// This code based on net/proto/proto-array-internal.h by Jeffrey Yasskin -// (jyasskin@google.com). -template -class RepeatedPtrIterator - : public std::iterator< - std::random_access_iterator_tag, Element> { - public: - typedef RepeatedPtrIterator iterator; - typedef std::iterator< - std::random_access_iterator_tag, Element> superclass; - - // Let the compiler know that these are type names, so we don't have to - // write "typename" in front of them everywhere. - typedef typename superclass::reference reference; - typedef typename superclass::pointer pointer; - typedef typename superclass::difference_type difference_type; - - RepeatedPtrIterator() : it_(NULL) {} - explicit RepeatedPtrIterator(void* const* it) : it_(it) {} - - // Allow "upcasting" from RepeatedPtrIterator to - // RepeatedPtrIterator. - template - RepeatedPtrIterator(const RepeatedPtrIterator& other) - : it_(other.it_) { - // Force a compiler error if the other type is not convertable to ours. - if (false) { - implicit_cast(0); - } - } - - // dereferenceable - reference operator*() const { return *reinterpret_cast(*it_); } - pointer operator->() const { return &(operator*()); } - - // {inc,dec}rementable - iterator& operator++() { ++it_; return *this; } - iterator operator++(int) { return iterator(it_++); } - iterator& operator--() { --it_; return *this; } - iterator operator--(int) { return iterator(it_--); } - - // equality_comparable - bool operator==(const iterator& x) const { return it_ == x.it_; } - bool operator!=(const iterator& x) const { return it_ != x.it_; } - - // less_than_comparable - bool operator<(const iterator& x) const { return it_ < x.it_; } - bool operator<=(const iterator& x) const { return it_ <= x.it_; } - bool operator>(const iterator& x) const { return it_ > x.it_; } - bool operator>=(const iterator& x) const { return it_ >= x.it_; } - - // addable, subtractable - iterator& operator+=(difference_type d) { - it_ += d; - return *this; - } - friend iterator operator+(iterator it, difference_type d) { - it += d; - return it; - } - friend iterator operator+(difference_type d, iterator it) { - it += d; - return it; - } - iterator& operator-=(difference_type d) { - it_ -= d; - return *this; - } - friend iterator operator-(iterator it, difference_type d) { - it -= d; - return it; - } - - // indexable - reference operator[](difference_type d) const { return *(*this + d); } - - // random access iterator - difference_type operator-(const iterator& x) const { return it_ - x.it_; } - - private: - template - friend class RepeatedPtrIterator; - - // The internal iterator. - void* const* it_; -}; - -// Provide an iterator that operates on pointers to the underlying objects -// rather than the objects themselves as RepeatedPtrIterator does. -// Consider using this when working with stl algorithms that change -// the array. -template -class RepeatedPtrOverPtrsIterator - : public std::iterator { - public: - typedef RepeatedPtrOverPtrsIterator iterator; - typedef std::iterator< - std::random_access_iterator_tag, Element*> superclass; - - // Let the compiler know that these are type names, so we don't have to - // write "typename" in front of them everywhere. - typedef typename superclass::reference reference; - typedef typename superclass::pointer pointer; - typedef typename superclass::difference_type difference_type; - - RepeatedPtrOverPtrsIterator() : it_(NULL) {} - explicit RepeatedPtrOverPtrsIterator(void** it) : it_(it) {} - - // dereferenceable - reference operator*() const { return *reinterpret_cast(it_); } - pointer operator->() const { return &(operator*()); } - - // {inc,dec}rementable - iterator& operator++() { ++it_; return *this; } - iterator operator++(int) { return iterator(it_++); } - iterator& operator--() { --it_; return *this; } - iterator operator--(int) { return iterator(it_--); } - - // equality_comparable - bool operator==(const iterator& x) const { return it_ == x.it_; } - bool operator!=(const iterator& x) const { return it_ != x.it_; } - - // less_than_comparable - bool operator<(const iterator& x) const { return it_ < x.it_; } - bool operator<=(const iterator& x) const { return it_ <= x.it_; } - bool operator>(const iterator& x) const { return it_ > x.it_; } - bool operator>=(const iterator& x) const { return it_ >= x.it_; } - - // addable, subtractable - iterator& operator+=(difference_type d) { - it_ += d; - return *this; - } - friend iterator operator+(iterator it, difference_type d) { - it += d; - return it; - } - friend iterator operator+(difference_type d, iterator it) { - it += d; - return it; - } - iterator& operator-=(difference_type d) { - it_ -= d; - return *this; - } - friend iterator operator-(iterator it, difference_type d) { - it -= d; - return it; - } - - // indexable - reference operator[](difference_type d) const { return *(*this + d); } - - // random access iterator - difference_type operator-(const iterator& x) const { return it_ - x.it_; } - - private: - template - friend class RepeatedPtrIterator; - - // The internal iterator. - void** it_; -}; - - -} // namespace internal - -template -inline typename RepeatedPtrField::iterator -RepeatedPtrField::begin() { - return iterator(raw_data()); -} -template -inline typename RepeatedPtrField::const_iterator -RepeatedPtrField::begin() const { - return iterator(raw_data()); -} -template -inline typename RepeatedPtrField::iterator -RepeatedPtrField::end() { - return iterator(raw_data() + size()); -} -template -inline typename RepeatedPtrField::const_iterator -RepeatedPtrField::end() const { - return iterator(raw_data() + size()); -} - -template -inline typename RepeatedPtrField::pointer_iterator -RepeatedPtrField::pointer_begin() { - return pointer_iterator(raw_mutable_data()); -} -template -inline typename RepeatedPtrField::pointer_iterator -RepeatedPtrField::pointer_end() { - return pointer_iterator(raw_mutable_data() + size()); -} - - -// Iterators and helper functions that follow the spirit of the STL -// std::back_insert_iterator and std::back_inserter but are tailor-made -// for RepeatedField and RepatedPtrField. Typical usage would be: -// -// std::copy(some_sequence.begin(), some_sequence.end(), -// google::protobuf::RepeatedFieldBackInserter(proto.mutable_sequence())); -// -// Ported by johannes from util/gtl/proto-array-iterators-inl.h - -namespace internal { -// A back inserter for RepeatedField objects. -template class RepeatedFieldBackInsertIterator - : public std::iterator { - public: - explicit RepeatedFieldBackInsertIterator( - RepeatedField* const mutable_field) - : field_(mutable_field) { - } - RepeatedFieldBackInsertIterator& operator=(const T& value) { - field_->Add(value); - return *this; - } - RepeatedFieldBackInsertIterator& operator*() { - return *this; - } - RepeatedFieldBackInsertIterator& operator++() { - return *this; - } - RepeatedFieldBackInsertIterator& operator++(int ignores_parameter) { - return *this; - } - - private: - RepeatedField* const field_; -}; - -// A back inserter for RepeatedPtrField objects. -template class RepeatedPtrFieldBackInsertIterator - : public std::iterator { - public: - RepeatedPtrFieldBackInsertIterator( - RepeatedPtrField* const mutable_field) - : field_(mutable_field) { - } - RepeatedPtrFieldBackInsertIterator& operator=(const T& value) { - *field_->Add() = value; - return *this; - } - RepeatedPtrFieldBackInsertIterator& operator=( - const T* const ptr_to_value) { - *field_->Add() = *ptr_to_value; - return *this; - } - RepeatedPtrFieldBackInsertIterator& operator*() { - return *this; - } - RepeatedPtrFieldBackInsertIterator& operator++() { - return *this; - } - RepeatedPtrFieldBackInsertIterator& operator++(int ignores_parameter) { - return *this; - } - - private: - RepeatedPtrField* const field_; -}; - -// A back inserter for RepeatedPtrFields that inserts by transfering ownership -// of a pointer. -template class AllocatedRepeatedPtrFieldBackInsertIterator - : public std::iterator { - public: - explicit AllocatedRepeatedPtrFieldBackInsertIterator( - RepeatedPtrField* const mutable_field) - : field_(mutable_field) { - } - AllocatedRepeatedPtrFieldBackInsertIterator& operator=( - T* const ptr_to_value) { - field_->AddAllocated(ptr_to_value); - return *this; - } - AllocatedRepeatedPtrFieldBackInsertIterator& operator*() { - return *this; - } - AllocatedRepeatedPtrFieldBackInsertIterator& operator++() { - return *this; - } - AllocatedRepeatedPtrFieldBackInsertIterator& operator++( - int ignores_parameter) { - return *this; - } - - private: - RepeatedPtrField* const field_; -}; -} // namespace internal - -// Provides a back insert iterator for RepeatedField instances, -// similar to std::back_inserter(). Note the identically named -// function for RepeatedPtrField instances. -template internal::RepeatedFieldBackInsertIterator -RepeatedFieldBackInserter(RepeatedField* const mutable_field) { - return internal::RepeatedFieldBackInsertIterator(mutable_field); -} - -// Provides a back insert iterator for RepeatedPtrField instances, -// similar to std::back_inserter(). Note the identically named -// function for RepeatedField instances. -template internal::RepeatedPtrFieldBackInsertIterator -RepeatedFieldBackInserter(RepeatedPtrField* const mutable_field) { - return internal::RepeatedPtrFieldBackInsertIterator(mutable_field); -} - -// Provides a back insert iterator for RepeatedPtrField instances -// similar to std::back_inserter() which transfers the ownership while -// copying elements. -template internal::AllocatedRepeatedPtrFieldBackInsertIterator -AllocatedRepeatedPtrFieldBackInserter( - RepeatedPtrField* const mutable_field) { - return internal::AllocatedRepeatedPtrFieldBackInsertIterator( - mutable_field); -} - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_REPEATED_FIELD_H__ diff --git a/Resources/NetHook/google/protobuf/repeated_field_unittest.cc b/Resources/NetHook/google/protobuf/repeated_field_unittest.cc deleted file mode 100644 index 7c35f604..00000000 --- a/Resources/NetHook/google/protobuf/repeated_field_unittest.cc +++ /dev/null @@ -1,986 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// TODO(kenton): Improve this unittest to bring it up to the standards of -// other proto2 unittests. - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -using protobuf_unittest::TestAllTypes; - -namespace protobuf { -namespace { - -// Test operations on a RepeatedField which is small enough that it does -// not allocate a separate array for storage. -TEST(RepeatedField, Small) { - RepeatedField field; - - EXPECT_EQ(field.size(), 0); - - field.Add(5); - - EXPECT_EQ(field.size(), 1); - EXPECT_EQ(field.Get(0), 5); - - field.Add(42); - - EXPECT_EQ(field.size(), 2); - EXPECT_EQ(field.Get(0), 5); - EXPECT_EQ(field.Get(1), 42); - - field.Set(1, 23); - - EXPECT_EQ(field.size(), 2); - EXPECT_EQ(field.Get(0), 5); - EXPECT_EQ(field.Get(1), 23); - EXPECT_EQ(field.SpaceUsedExcludingSelf(), 0); - - field.RemoveLast(); - - EXPECT_EQ(field.size(), 1); - EXPECT_EQ(field.Get(0), 5); - - field.Clear(); - - EXPECT_EQ(field.size(), 0); - EXPECT_EQ(field.SpaceUsedExcludingSelf(), 0); -} - -// Test operations on a RepeatedField which is large enough to allocate a -// separate array. -TEST(RepeatedField, Large) { - RepeatedField field; - - for (int i = 0; i < 16; i++) { - field.Add(i * i); - } - - EXPECT_EQ(field.size(), 16); - - for (int i = 0; i < 16; i++) { - EXPECT_EQ(field.Get(i), i * i); - } - - int expected_usage = 16 * sizeof(int); - EXPECT_GE(field.SpaceUsedExcludingSelf(), expected_usage); -} - -// Test swapping between various types of RepeatedFields. -TEST(RepeatedField, SwapSmallSmall) { - RepeatedField field1; - RepeatedField field2; - - field1.Add(5); - field1.Add(42); - - field1.Swap(&field2); - - EXPECT_EQ(field1.size(), 0); - EXPECT_EQ(field2.size(), 2); - EXPECT_EQ(field2.Get(0), 5); - EXPECT_EQ(field2.Get(1), 42); -} - -TEST(RepeatedField, SwapLargeSmall) { - RepeatedField field1; - RepeatedField field2; - - for (int i = 0; i < 16; i++) { - field1.Add(i * i); - } - field2.Add(5); - field2.Add(42); - field1.Swap(&field2); - - EXPECT_EQ(field1.size(), 2); - EXPECT_EQ(field1.Get(0), 5); - EXPECT_EQ(field1.Get(1), 42); - EXPECT_EQ(field2.size(), 16); - for (int i = 0; i < 16; i++) { - EXPECT_EQ(field2.Get(i), i * i); - } -} - -TEST(RepeatedField, SwapLargeLarge) { - RepeatedField field1; - RepeatedField field2; - - field1.Add(5); - field1.Add(42); - for (int i = 0; i < 16; i++) { - field1.Add(i); - field2.Add(i * i); - } - field2.Swap(&field1); - - EXPECT_EQ(field1.size(), 16); - for (int i = 0; i < 16; i++) { - EXPECT_EQ(field1.Get(i), i * i); - } - EXPECT_EQ(field2.size(), 18); - EXPECT_EQ(field2.Get(0), 5); - EXPECT_EQ(field2.Get(1), 42); - for (int i = 2; i < 18; i++) { - EXPECT_EQ(field2.Get(i), i - 2); - } -} - -// Determines how much space was reserved by the given field by adding elements -// to it until it re-allocates its space. -static int ReservedSpace(RepeatedField* field) { - const int* ptr = field->data(); - do { - field->Add(0); - } while (field->data() == ptr); - - return field->size() - 1; -} - -TEST(RepeatedField, ReserveMoreThanDouble) { - // Reserve more than double the previous space in the field and expect the - // field to reserve exactly the amount specified. - RepeatedField field; - field.Reserve(20); - - EXPECT_EQ(20, ReservedSpace(&field)); -} - -TEST(RepeatedField, ReserveLessThanDouble) { - // Reserve less than double the previous space in the field and expect the - // field to grow by double instead. - RepeatedField field; - field.Reserve(20); - field.Reserve(30); - - EXPECT_EQ(40, ReservedSpace(&field)); -} - -TEST(RepeatedField, ReserveLessThanExisting) { - // Reserve less than the previous space in the field and expect the - // field to not re-allocate at all. - RepeatedField field; - field.Reserve(20); - const int* previous_ptr = field.data(); - field.Reserve(10); - - EXPECT_EQ(previous_ptr, field.data()); - EXPECT_EQ(20, ReservedSpace(&field)); -} - -TEST(RepeatedField, MergeFrom) { - RepeatedField source, destination; - - source.Add(4); - source.Add(5); - - destination.Add(1); - destination.Add(2); - destination.Add(3); - - destination.MergeFrom(source); - - ASSERT_EQ(5, destination.size()); - - EXPECT_EQ(1, destination.Get(0)); - EXPECT_EQ(2, destination.Get(1)); - EXPECT_EQ(3, destination.Get(2)); - EXPECT_EQ(4, destination.Get(3)); - EXPECT_EQ(5, destination.Get(4)); -} - -TEST(RepeatedField, MutableDataIsMutable) { - RepeatedField field; - field.Add(1); - EXPECT_EQ(1, field.Get(0)); - // The fact that this line compiles would be enough, but we'll check the - // value anyway. - *field.mutable_data() = 2; - EXPECT_EQ(2, field.Get(0)); -} - -TEST(RepeatedField, Truncate) { - RepeatedField field; - - field.Add(12); - field.Add(34); - field.Add(56); - field.Add(78); - EXPECT_EQ(4, field.size()); - - field.Truncate(3); - EXPECT_EQ(3, field.size()); - - field.Add(90); - EXPECT_EQ(4, field.size()); - EXPECT_EQ(90, field.Get(3)); - - // Truncations that don't change the size are allowed, but growing is not - // allowed. - field.Truncate(field.size()); -#ifdef GTEST_HAS_DEATH_TEST - EXPECT_DEBUG_DEATH(field.Truncate(field.size() + 1), "new_size"); -#endif -} - - -// =================================================================== -// RepeatedPtrField tests. These pretty much just mirror the RepeatedField -// tests above. - -TEST(RepeatedPtrField, Small) { - RepeatedPtrField field; - - EXPECT_EQ(field.size(), 0); - - field.Add()->assign("foo"); - - EXPECT_EQ(field.size(), 1); - EXPECT_EQ(field.Get(0), "foo"); - - field.Add()->assign("bar"); - - EXPECT_EQ(field.size(), 2); - EXPECT_EQ(field.Get(0), "foo"); - EXPECT_EQ(field.Get(1), "bar"); - - field.Mutable(1)->assign("baz"); - - EXPECT_EQ(field.size(), 2); - EXPECT_EQ(field.Get(0), "foo"); - EXPECT_EQ(field.Get(1), "baz"); - - field.RemoveLast(); - - EXPECT_EQ(field.size(), 1); - EXPECT_EQ(field.Get(0), "foo"); - - field.Clear(); - - EXPECT_EQ(field.size(), 0); -} - -TEST(RepeatedPtrField, Large) { - RepeatedPtrField field; - - for (int i = 0; i < 16; i++) { - *field.Add() += 'a' + i; - } - - EXPECT_EQ(field.size(), 16); - - for (int i = 0; i < 16; i++) { - EXPECT_EQ(field.Get(i).size(), 1); - EXPECT_EQ(field.Get(i)[0], 'a' + i); - } - - int min_expected_usage = 16 * sizeof(string); - EXPECT_GE(field.SpaceUsedExcludingSelf(), min_expected_usage); -} - -TEST(RepeatedPtrField, SwapSmallSmall) { - RepeatedPtrField field1; - RepeatedPtrField field2; - - field1.Add()->assign("foo"); - field1.Add()->assign("bar"); - field1.Swap(&field2); - - EXPECT_EQ(field1.size(), 0); - EXPECT_EQ(field2.size(), 2); - EXPECT_EQ(field2.Get(0), "foo"); - EXPECT_EQ(field2.Get(1), "bar"); -} - -TEST(RepeatedPtrField, SwapLargeSmall) { - RepeatedPtrField field1; - RepeatedPtrField field2; - - field2.Add()->assign("foo"); - field2.Add()->assign("bar"); - for (int i = 0; i < 16; i++) { - *field1.Add() += 'a' + i; - } - field1.Swap(&field2); - - EXPECT_EQ(field1.size(), 2); - EXPECT_EQ(field1.Get(0), "foo"); - EXPECT_EQ(field1.Get(1), "bar"); - EXPECT_EQ(field2.size(), 16); - for (int i = 0; i < 16; i++) { - EXPECT_EQ(field2.Get(i).size(), 1); - EXPECT_EQ(field2.Get(i)[0], 'a' + i); - } -} - -TEST(RepeatedPtrField, SwapLargeLarge) { - RepeatedPtrField field1; - RepeatedPtrField field2; - - field1.Add()->assign("foo"); - field1.Add()->assign("bar"); - for (int i = 0; i < 16; i++) { - *field1.Add() += 'A' + i; - *field2.Add() += 'a' + i; - } - field2.Swap(&field1); - - EXPECT_EQ(field1.size(), 16); - for (int i = 0; i < 16; i++) { - EXPECT_EQ(field1.Get(i).size(), 1); - EXPECT_EQ(field1.Get(i)[0], 'a' + i); - } - EXPECT_EQ(field2.size(), 18); - EXPECT_EQ(field2.Get(0), "foo"); - EXPECT_EQ(field2.Get(1), "bar"); - for (int i = 2; i < 18; i++) { - EXPECT_EQ(field2.Get(i).size(), 1); - EXPECT_EQ(field2.Get(i)[0], 'A' + i - 2); - } -} - -static int ReservedSpace(RepeatedPtrField* field) { - const string* const* ptr = field->data(); - do { - field->Add(); - } while (field->data() == ptr); - - return field->size() - 1; -} - -TEST(RepeatedPtrField, ReserveMoreThanDouble) { - RepeatedPtrField field; - field.Reserve(20); - - EXPECT_EQ(20, ReservedSpace(&field)); -} - -TEST(RepeatedPtrField, ReserveLessThanDouble) { - RepeatedPtrField field; - field.Reserve(20); - field.Reserve(30); - - EXPECT_EQ(40, ReservedSpace(&field)); -} - -TEST(RepeatedPtrField, ReserveLessThanExisting) { - RepeatedPtrField field; - field.Reserve(20); - const string* const* previous_ptr = field.data(); - field.Reserve(10); - - EXPECT_EQ(previous_ptr, field.data()); - EXPECT_EQ(20, ReservedSpace(&field)); -} - -TEST(RepeatedPtrField, ReserveDoesntLoseAllocated) { - // Check that a bug is fixed: An earlier implementation of Reserve() - // failed to copy pointers to allocated-but-cleared objects, possibly - // leading to segfaults. - RepeatedPtrField field; - string* first = field.Add(); - field.RemoveLast(); - - field.Reserve(20); - EXPECT_EQ(first, field.Add()); -} - -// Clearing elements is tricky with RepeatedPtrFields since the memory for -// the elements is retained and reused. -TEST(RepeatedPtrField, ClearedElements) { - RepeatedPtrField field; - - string* original = field.Add(); - *original = "foo"; - - EXPECT_EQ(field.ClearedCount(), 0); - - field.RemoveLast(); - EXPECT_TRUE(original->empty()); - EXPECT_EQ(field.ClearedCount(), 1); - - EXPECT_EQ(field.Add(), original); // Should return same string for reuse. - - EXPECT_EQ(field.ReleaseLast(), original); // We take ownership. - EXPECT_EQ(field.ClearedCount(), 0); - - EXPECT_NE(field.Add(), original); // Should NOT return the same string. - EXPECT_EQ(field.ClearedCount(), 0); - - field.AddAllocated(original); // Give ownership back. - EXPECT_EQ(field.ClearedCount(), 0); - EXPECT_EQ(field.Mutable(1), original); - - field.Clear(); - EXPECT_EQ(field.ClearedCount(), 2); - EXPECT_EQ(field.ReleaseCleared(), original); // Take ownership again. - EXPECT_EQ(field.ClearedCount(), 1); - EXPECT_NE(field.Add(), original); - EXPECT_EQ(field.ClearedCount(), 0); - EXPECT_NE(field.Add(), original); - EXPECT_EQ(field.ClearedCount(), 0); - - field.AddCleared(original); // Give ownership back, but as a cleared object. - EXPECT_EQ(field.ClearedCount(), 1); - EXPECT_EQ(field.Add(), original); - EXPECT_EQ(field.ClearedCount(), 0); -} - -// Test all code paths in AddAllocated(). -TEST(RepeatedPtrField, AddAlocated) { - RepeatedPtrField field; - while (field.size() < field.Capacity()) { - field.Add()->assign("filler"); - } - - int index = field.size(); - - // First branch: Field is at capacity with no cleared objects. - string* foo = new string("foo"); - field.AddAllocated(foo); - EXPECT_EQ(index + 1, field.size()); - EXPECT_EQ(0, field.ClearedCount()); - EXPECT_EQ(foo, &field.Get(index)); - - // Last branch: Field is not at capacity and there are no cleared objects. - string* bar = new string("bar"); - field.AddAllocated(bar); - ++index; - EXPECT_EQ(index + 1, field.size()); - EXPECT_EQ(0, field.ClearedCount()); - EXPECT_EQ(bar, &field.Get(index)); - - // Third branch: Field is not at capacity and there are no cleared objects. - field.RemoveLast(); - string* baz = new string("baz"); - field.AddAllocated(baz); - EXPECT_EQ(index + 1, field.size()); - EXPECT_EQ(1, field.ClearedCount()); - EXPECT_EQ(baz, &field.Get(index)); - - // Second branch: Field is at capacity but has some cleared objects. - while (field.size() < field.Capacity()) { - field.Add()->assign("filler2"); - } - field.RemoveLast(); - index = field.size(); - string* qux = new string("qux"); - field.AddAllocated(qux); - EXPECT_EQ(index + 1, field.size()); - // We should have discarded the cleared object. - EXPECT_EQ(0, field.ClearedCount()); - EXPECT_EQ(qux, &field.Get(index)); -} - -TEST(RepeatedPtrField, MergeFrom) { - RepeatedPtrField source, destination; - - source.Add()->assign("4"); - source.Add()->assign("5"); - - destination.Add()->assign("1"); - destination.Add()->assign("2"); - destination.Add()->assign("3"); - - destination.MergeFrom(source); - - ASSERT_EQ(5, destination.size()); - - EXPECT_EQ("1", destination.Get(0)); - EXPECT_EQ("2", destination.Get(1)); - EXPECT_EQ("3", destination.Get(2)); - EXPECT_EQ("4", destination.Get(3)); - EXPECT_EQ("5", destination.Get(4)); -} - -TEST(RepeatedPtrField, MutableDataIsMutable) { - RepeatedPtrField field; - *field.Add() = "1"; - EXPECT_EQ("1", field.Get(0)); - // The fact that this line compiles would be enough, but we'll check the - // value anyway. - string** data = field.mutable_data(); - **data = "2"; - EXPECT_EQ("2", field.Get(0)); -} - -// =================================================================== - -// Iterator tests stolen from net/proto/proto-array_unittest. -class RepeatedFieldIteratorTest : public testing::Test { - protected: - virtual void SetUp() { - for (int i = 0; i < 3; ++i) { - proto_array_.Add(i); - } - } - - RepeatedField proto_array_; -}; - -TEST_F(RepeatedFieldIteratorTest, Convertible) { - RepeatedField::iterator iter = proto_array_.begin(); - RepeatedField::const_iterator c_iter = iter; - EXPECT_EQ(0, *c_iter); -} - -TEST_F(RepeatedFieldIteratorTest, MutableIteration) { - RepeatedField::iterator iter = proto_array_.begin(); - EXPECT_EQ(0, *iter); - ++iter; - EXPECT_EQ(1, *iter++); - EXPECT_EQ(2, *iter); - ++iter; - EXPECT_TRUE(proto_array_.end() == iter); - - EXPECT_EQ(2, *(proto_array_.end() - 1)); -} - -TEST_F(RepeatedFieldIteratorTest, ConstIteration) { - const RepeatedField& const_proto_array = proto_array_; - RepeatedField::const_iterator iter = const_proto_array.begin(); - EXPECT_EQ(0, *iter); - ++iter; - EXPECT_EQ(1, *iter++); - EXPECT_EQ(2, *iter); - ++iter; - EXPECT_TRUE(proto_array_.end() == iter); - EXPECT_EQ(2, *(proto_array_.end() - 1)); -} - -TEST_F(RepeatedFieldIteratorTest, Mutation) { - RepeatedField::iterator iter = proto_array_.begin(); - *iter = 7; - EXPECT_EQ(7, proto_array_.Get(0)); -} - -// ------------------------------------------------------------------- - -class RepeatedPtrFieldIteratorTest : public testing::Test { - protected: - virtual void SetUp() { - proto_array_.Add()->assign("foo"); - proto_array_.Add()->assign("bar"); - proto_array_.Add()->assign("baz"); - } - - RepeatedPtrField proto_array_; -}; - -TEST_F(RepeatedPtrFieldIteratorTest, Convertible) { - RepeatedPtrField::iterator iter = proto_array_.begin(); - RepeatedPtrField::const_iterator c_iter = iter; -} - -TEST_F(RepeatedPtrFieldIteratorTest, MutableIteration) { - RepeatedPtrField::iterator iter = proto_array_.begin(); - EXPECT_EQ("foo", *iter); - ++iter; - EXPECT_EQ("bar", *(iter++)); - EXPECT_EQ("baz", *iter); - ++iter; - EXPECT_TRUE(proto_array_.end() == iter); - EXPECT_EQ("baz", *(--proto_array_.end())); -} - -TEST_F(RepeatedPtrFieldIteratorTest, ConstIteration) { - const RepeatedPtrField& const_proto_array = proto_array_; - RepeatedPtrField::const_iterator iter = const_proto_array.begin(); - EXPECT_EQ("foo", *iter); - ++iter; - EXPECT_EQ("bar", *(iter++)); - EXPECT_EQ("baz", *iter); - ++iter; - EXPECT_TRUE(const_proto_array.end() == iter); - EXPECT_EQ("baz", *(--const_proto_array.end())); -} - -TEST_F(RepeatedPtrFieldIteratorTest, RandomAccess) { - RepeatedPtrField::iterator iter = proto_array_.begin(); - RepeatedPtrField::iterator iter2 = iter; - ++iter2; - ++iter2; - EXPECT_TRUE(iter + 2 == iter2); - EXPECT_TRUE(iter == iter2 - 2); - EXPECT_EQ("baz", iter[2]); - EXPECT_EQ("baz", *(iter + 2)); - EXPECT_EQ(3, proto_array_.end() - proto_array_.begin()); -} - -TEST_F(RepeatedPtrFieldIteratorTest, Comparable) { - RepeatedPtrField::const_iterator iter = proto_array_.begin(); - RepeatedPtrField::const_iterator iter2 = iter + 1; - EXPECT_TRUE(iter == iter); - EXPECT_TRUE(iter != iter2); - EXPECT_TRUE(iter < iter2); - EXPECT_TRUE(iter <= iter2); - EXPECT_TRUE(iter <= iter); - EXPECT_TRUE(iter2 > iter); - EXPECT_TRUE(iter2 >= iter); - EXPECT_TRUE(iter >= iter); -} - -// Uninitialized iterator does not point to any of the RepeatedPtrField. -TEST_F(RepeatedPtrFieldIteratorTest, UninitializedIterator) { - RepeatedPtrField::iterator iter; - EXPECT_TRUE(iter != proto_array_.begin()); - EXPECT_TRUE(iter != proto_array_.begin() + 1); - EXPECT_TRUE(iter != proto_array_.begin() + 2); - EXPECT_TRUE(iter != proto_array_.begin() + 3); - EXPECT_TRUE(iter != proto_array_.end()); -} - -TEST_F(RepeatedPtrFieldIteratorTest, STLAlgorithms_lower_bound) { - proto_array_.Clear(); - proto_array_.Add()->assign("a"); - proto_array_.Add()->assign("c"); - proto_array_.Add()->assign("d"); - proto_array_.Add()->assign("n"); - proto_array_.Add()->assign("p"); - proto_array_.Add()->assign("x"); - proto_array_.Add()->assign("y"); - - string v = "f"; - RepeatedPtrField::const_iterator it = - lower_bound(proto_array_.begin(), proto_array_.end(), v); - - EXPECT_EQ(*it, "n"); - EXPECT_TRUE(it == proto_array_.begin() + 3); -} - -TEST_F(RepeatedPtrFieldIteratorTest, Mutation) { - RepeatedPtrField::iterator iter = proto_array_.begin(); - *iter = "qux"; - EXPECT_EQ("qux", proto_array_.Get(0)); -} - -// ------------------------------------------------------------------- - -class RepeatedPtrFieldPtrsIteratorTest : public testing::Test { - protected: - virtual void SetUp() { - proto_array_.Add()->assign("foo"); - proto_array_.Add()->assign("bar"); - proto_array_.Add()->assign("baz"); - } - - RepeatedPtrField proto_array_; -}; - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, ConvertiblePtr) { - RepeatedPtrField::pointer_iterator iter = - proto_array_.pointer_begin(); -} - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, MutablePtrIteration) { - RepeatedPtrField::pointer_iterator iter = - proto_array_.pointer_begin(); - EXPECT_EQ("foo", **iter); - ++iter; - EXPECT_EQ("bar", **(iter++)); - EXPECT_EQ("baz", **iter); - ++iter; - EXPECT_TRUE(proto_array_.pointer_end() == iter); - EXPECT_EQ("baz", **(--proto_array_.pointer_end())); -} - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, RandomPtrAccess) { - RepeatedPtrField::pointer_iterator iter = - proto_array_.pointer_begin(); - RepeatedPtrField::pointer_iterator iter2 = iter; - ++iter2; - ++iter2; - EXPECT_TRUE(iter + 2 == iter2); - EXPECT_TRUE(iter == iter2 - 2); - EXPECT_EQ("baz", *iter[2]); - EXPECT_EQ("baz", **(iter + 2)); - EXPECT_EQ(3, proto_array_.end() - proto_array_.begin()); -} - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, ComparablePtr) { - RepeatedPtrField::pointer_iterator iter = - proto_array_.pointer_begin(); - RepeatedPtrField::pointer_iterator iter2 = iter + 1; - EXPECT_TRUE(iter == iter); - EXPECT_TRUE(iter != iter2); - EXPECT_TRUE(iter < iter2); - EXPECT_TRUE(iter <= iter2); - EXPECT_TRUE(iter <= iter); - EXPECT_TRUE(iter2 > iter); - EXPECT_TRUE(iter2 >= iter); - EXPECT_TRUE(iter >= iter); -} - -// Uninitialized iterator does not point to any of the RepeatedPtrOverPtrs. -// Dereferencing an uninitialized iterator crashes the process. -TEST_F(RepeatedPtrFieldPtrsIteratorTest, UninitializedPtrIterator) { - RepeatedPtrField::pointer_iterator iter; - EXPECT_TRUE(iter != proto_array_.pointer_begin()); - EXPECT_TRUE(iter != proto_array_.pointer_begin() + 1); - EXPECT_TRUE(iter != proto_array_.pointer_begin() + 2); - EXPECT_TRUE(iter != proto_array_.pointer_begin() + 3); - EXPECT_TRUE(iter != proto_array_.pointer_end()); -} - - -// This comparison functor is required by the tests for RepeatedPtrOverPtrs. -// They operate on strings and need to compare strings as strings in -// any stl algorithm, even though the iterator returns a pointer to a string -// - i.e. *iter has type string*. -struct StringLessThan { - bool operator()(const string* z, const string& y) { - return *z < y; - } - bool operator()(const string* z, const string* y) { - return *z < *y; - } -}; - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrSTLAlgorithms_lower_bound) { - proto_array_.Clear(); - proto_array_.Add()->assign("a"); - proto_array_.Add()->assign("c"); - proto_array_.Add()->assign("d"); - proto_array_.Add()->assign("n"); - proto_array_.Add()->assign("p"); - proto_array_.Add()->assign("x"); - proto_array_.Add()->assign("y"); - - RepeatedPtrField::pointer_iterator iter = - proto_array_.pointer_begin(); - string v = "f"; - RepeatedPtrField::pointer_iterator it = - lower_bound(proto_array_.pointer_begin(), proto_array_.pointer_end(), - &v, StringLessThan()); - - GOOGLE_CHECK(*it != NULL); - - EXPECT_EQ(**it, "n"); - EXPECT_TRUE(it == proto_array_.pointer_begin() + 3); -} - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, PtrMutation) { - RepeatedPtrField::pointer_iterator iter = - proto_array_.pointer_begin(); - **iter = "qux"; - EXPECT_EQ("qux", proto_array_.Get(0)); - - EXPECT_EQ("bar", proto_array_.Get(1)); - EXPECT_EQ("baz", proto_array_.Get(2)); - ++iter; - delete *iter; - *iter = new string("a"); - ++iter; - delete *iter; - *iter = new string("b"); - EXPECT_EQ("a", proto_array_.Get(1)); - EXPECT_EQ("b", proto_array_.Get(2)); -} - -TEST_F(RepeatedPtrFieldPtrsIteratorTest, Sort) { - proto_array_.Add()->assign("c"); - proto_array_.Add()->assign("d"); - proto_array_.Add()->assign("n"); - proto_array_.Add()->assign("p"); - proto_array_.Add()->assign("a"); - proto_array_.Add()->assign("y"); - proto_array_.Add()->assign("x"); - EXPECT_EQ("foo", proto_array_.Get(0)); - EXPECT_EQ("n", proto_array_.Get(5)); - EXPECT_EQ("x", proto_array_.Get(9)); - sort(proto_array_.pointer_begin(), - proto_array_.pointer_end(), - StringLessThan()); - EXPECT_EQ("a", proto_array_.Get(0)); - EXPECT_EQ("baz", proto_array_.Get(2)); - EXPECT_EQ("y", proto_array_.Get(9)); -} - - -// ----------------------------------------------------------------------------- -// Unit-tests for the insert iterators -// google::protobuf::RepeatedFieldBackInserter, -// google::protobuf::AllocatedRepeatedPtrFieldBackInserter -// Ported from util/gtl/proto-array-iterators_unittest. - -class RepeatedFieldInsertionIteratorsTest : public testing::Test { - protected: - std::list halves; - std::list fibonacci; - std::vector words; - typedef TestAllTypes::NestedMessage Nested; - Nested nesteds[2]; - std::vector nested_ptrs; - TestAllTypes protobuffer; - - virtual void SetUp() { - fibonacci.push_back(1); - fibonacci.push_back(1); - fibonacci.push_back(2); - fibonacci.push_back(3); - fibonacci.push_back(5); - fibonacci.push_back(8); - std::copy(fibonacci.begin(), fibonacci.end(), - RepeatedFieldBackInserter(protobuffer.mutable_repeated_int32())); - - halves.push_back(1.0); - halves.push_back(0.5); - halves.push_back(0.25); - halves.push_back(0.125); - halves.push_back(0.0625); - std::copy(halves.begin(), halves.end(), - RepeatedFieldBackInserter(protobuffer.mutable_repeated_double())); - - words.push_back("Able"); - words.push_back("was"); - words.push_back("I"); - words.push_back("ere"); - words.push_back("I"); - words.push_back("saw"); - words.push_back("Elba"); - std::copy(words.begin(), words.end(), - RepeatedFieldBackInserter(protobuffer.mutable_repeated_string())); - - nesteds[0].set_bb(17); - nesteds[1].set_bb(4711); - std::copy(&nesteds[0], &nesteds[2], - RepeatedFieldBackInserter( - protobuffer.mutable_repeated_nested_message())); - - nested_ptrs.push_back(new Nested); - nested_ptrs.back()->set_bb(170); - nested_ptrs.push_back(new Nested); - nested_ptrs.back()->set_bb(47110); - std::copy(nested_ptrs.begin(), nested_ptrs.end(), - RepeatedFieldBackInserter( - protobuffer.mutable_repeated_nested_message())); - - } - - virtual void TearDown() { - STLDeleteContainerPointers(nested_ptrs.begin(), nested_ptrs.end()); - } -}; - -TEST_F(RepeatedFieldInsertionIteratorsTest, Fibonacci) { - EXPECT_TRUE(std::equal(fibonacci.begin(), - fibonacci.end(), - protobuffer.repeated_int32().begin())); - EXPECT_TRUE(std::equal(protobuffer.repeated_int32().begin(), - protobuffer.repeated_int32().end(), - fibonacci.begin())); -} - -TEST_F(RepeatedFieldInsertionIteratorsTest, Halves) { - EXPECT_TRUE(std::equal(halves.begin(), - halves.end(), - protobuffer.repeated_double().begin())); - EXPECT_TRUE(std::equal(protobuffer.repeated_double().begin(), - protobuffer.repeated_double().end(), - halves.begin())); -} - -TEST_F(RepeatedFieldInsertionIteratorsTest, Words) { - ASSERT_EQ(words.size(), protobuffer.repeated_string_size()); - EXPECT_EQ(words.at(0), protobuffer.repeated_string(0)); - EXPECT_EQ(words.at(1), protobuffer.repeated_string(1)); - EXPECT_EQ(words.at(2), protobuffer.repeated_string(2)); - EXPECT_EQ(words.at(3), protobuffer.repeated_string(3)); - EXPECT_EQ(words.at(4), protobuffer.repeated_string(4)); - EXPECT_EQ(words.at(5), protobuffer.repeated_string(5)); - EXPECT_EQ(words.at(6), protobuffer.repeated_string(6)); -} - -TEST_F(RepeatedFieldInsertionIteratorsTest, Nesteds) { - ASSERT_EQ(protobuffer.repeated_nested_message_size(), 4); - EXPECT_EQ(protobuffer.repeated_nested_message(0).bb(), 17); - EXPECT_EQ(protobuffer.repeated_nested_message(1).bb(), 4711); - EXPECT_EQ(protobuffer.repeated_nested_message(2).bb(), 170); - EXPECT_EQ(protobuffer.repeated_nested_message(3).bb(), 47110); -} - -TEST_F(RepeatedFieldInsertionIteratorsTest, - AllocatedRepeatedPtrFieldWithStringIntData) { - vector data; - TestAllTypes goldenproto; - for (int i = 0; i < 10; ++i) { - Nested* new_data = new Nested; - new_data->set_bb(i); - data.push_back(new_data); - - new_data = goldenproto.add_repeated_nested_message(); - new_data->set_bb(i); - } - TestAllTypes testproto; - copy(data.begin(), data.end(), - AllocatedRepeatedPtrFieldBackInserter( - testproto.mutable_repeated_nested_message())); - EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString()); -} - -TEST_F(RepeatedFieldInsertionIteratorsTest, - AllocatedRepeatedPtrFieldWithString) { - vector data; - TestAllTypes goldenproto; - for (int i = 0; i < 10; ++i) { - string* new_data = new string; - *new_data = "name-" + SimpleItoa(i); - data.push_back(new_data); - - new_data = goldenproto.add_repeated_string(); - *new_data = "name-" + SimpleItoa(i); - } - TestAllTypes testproto; - copy(data.begin(), data.end(), - AllocatedRepeatedPtrFieldBackInserter( - testproto.mutable_repeated_string())); - EXPECT_EQ(testproto.DebugString(), goldenproto.DebugString()); -} - -} // namespace - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/service.cc b/Resources/NetHook/google/protobuf/service.cc deleted file mode 100644 index caf968ca..00000000 --- a/Resources/NetHook/google/protobuf/service.cc +++ /dev/null @@ -1,46 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -namespace google { -namespace protobuf { - -Service::~Service() {} -RpcChannel::~RpcChannel() {} -RpcController::~RpcController() {} - -} // namespace protobuf - -} // namespace google diff --git a/Resources/NetHook/google/protobuf/service.h b/Resources/NetHook/google/protobuf/service.h deleted file mode 100644 index a6a7d16d..00000000 --- a/Resources/NetHook/google/protobuf/service.h +++ /dev/null @@ -1,291 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// DEPRECATED: This module declares the abstract interfaces underlying proto2 -// RPC services. These are intented to be independent of any particular RPC -// implementation, so that proto2 services can be used on top of a variety -// of implementations. Starting with version 2.3.0, RPC implementations should -// not try to build on these, but should instead provide code generator plugins -// which generate code specific to the particular RPC implementation. This way -// the generated code can be more appropriate for the implementation in use -// and can avoid unnecessary layers of indirection. -// -// -// When you use the protocol compiler to compile a service definition, it -// generates two classes: An abstract interface for the service (with -// methods matching the service definition) and a "stub" implementation. -// A stub is just a type-safe wrapper around an RpcChannel which emulates a -// local implementation of the service. -// -// For example, the service definition: -// service MyService { -// rpc Foo(MyRequest) returns(MyResponse); -// } -// will generate abstract interface "MyService" and class "MyService::Stub". -// You could implement a MyService as follows: -// class MyServiceImpl : public MyService { -// public: -// MyServiceImpl() {} -// ~MyServiceImpl() {} -// -// // implements MyService --------------------------------------- -// -// void Foo(google::protobuf::RpcController* controller, -// const MyRequest* request, -// MyResponse* response, -// Closure* done) { -// // ... read request and fill in response ... -// done->Run(); -// } -// }; -// You would then register an instance of MyServiceImpl with your RPC server -// implementation. (How to do that depends on the implementation.) -// -// To call a remote MyServiceImpl, first you need an RpcChannel connected to it. -// How to construct a channel depends, again, on your RPC implementation. -// Here we use a hypothentical "MyRpcChannel" as an example: -// MyRpcChannel channel("rpc:hostname:1234/myservice"); -// MyRpcController controller; -// MyServiceImpl::Stub stub(&channel); -// FooRequest request; -// FooRespnose response; -// -// // ... fill in request ... -// -// stub.Foo(&controller, request, &response, NewCallback(HandleResponse)); -// -// On Thread-Safety: -// -// Different RPC implementations may make different guarantees about what -// threads they may run callbacks on, and what threads the application is -// allowed to use to call the RPC system. Portable software should be ready -// for callbacks to be called on any thread, but should not try to call the -// RPC system from any thread except for the ones on which it received the -// callbacks. Realistically, though, simple software will probably want to -// use a single-threaded RPC system while high-end software will want to -// use multiple threads. RPC implementations should provide multiple -// choices. - -#ifndef GOOGLE_PROTOBUF_SERVICE_H__ -#define GOOGLE_PROTOBUF_SERVICE_H__ - -#include -#include - -namespace google { -namespace protobuf { - -// Defined in this file. -class Service; -class RpcController; -class RpcChannel; - -// Defined in other files. -class Descriptor; // descriptor.h -class ServiceDescriptor; // descriptor.h -class MethodDescriptor; // descriptor.h -class Message; // message.h - -// Abstract base interface for protocol-buffer-based RPC services. Services -// themselves are abstract interfaces (implemented either by servers or as -// stubs), but they subclass this base interface. The methods of this -// interface can be used to call the methods of the Service without knowing -// its exact type at compile time (analogous to Reflection). -class LIBPROTOBUF_EXPORT Service { - public: - inline Service() {} - virtual ~Service(); - - // When constructing a stub, you may pass STUB_OWNS_CHANNEL as the second - // parameter to the constructor to tell it to delete its RpcChannel when - // destroyed. - enum ChannelOwnership { - STUB_OWNS_CHANNEL, - STUB_DOESNT_OWN_CHANNEL - }; - - // Get the ServiceDescriptor describing this service and its methods. - virtual const ServiceDescriptor* GetDescriptor() = 0; - - // Call a method of the service specified by MethodDescriptor. This is - // normally implemented as a simple switch() that calls the standard - // definitions of the service's methods. - // - // Preconditions: - // * method->service() == GetDescriptor() - // * request and response are of the exact same classes as the objects - // returned by GetRequestPrototype(method) and - // GetResponsePrototype(method). - // * After the call has started, the request must not be modified and the - // response must not be accessed at all until "done" is called. - // * "controller" is of the correct type for the RPC implementation being - // used by this Service. For stubs, the "correct type" depends on the - // RpcChannel which the stub is using. Server-side Service - // implementations are expected to accept whatever type of RpcController - // the server-side RPC implementation uses. - // - // Postconditions: - // * "done" will be called when the method is complete. This may be - // before CallMethod() returns or it may be at some point in the future. - // * If the RPC succeeded, "response" contains the response returned by - // the server. - // * If the RPC failed, "response"'s contents are undefined. The - // RpcController can be queried to determine if an error occurred and - // possibly to get more information about the error. - virtual void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) = 0; - - // CallMethod() requires that the request and response passed in are of a - // particular subclass of Message. GetRequestPrototype() and - // GetResponsePrototype() get the default instances of these required types. - // You can then call Message::New() on these instances to construct mutable - // objects which you can then pass to CallMethod(). - // - // Example: - // const MethodDescriptor* method = - // service->GetDescriptor()->FindMethodByName("Foo"); - // Message* request = stub->GetRequestPrototype (method)->New(); - // Message* response = stub->GetResponsePrototype(method)->New(); - // request->ParseFromString(input); - // service->CallMethod(method, *request, response, callback); - virtual const Message& GetRequestPrototype( - const MethodDescriptor* method) const = 0; - virtual const Message& GetResponsePrototype( - const MethodDescriptor* method) const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Service); -}; - -// An RpcController mediates a single method call. The primary purpose of -// the controller is to provide a way to manipulate settings specific to the -// RPC implementation and to find out about RPC-level errors. -// -// The methods provided by the RpcController interface are intended to be a -// "least common denominator" set of features which we expect all -// implementations to support. Specific implementations may provide more -// advanced features (e.g. deadline propagation). -class LIBPROTOBUF_EXPORT RpcController { - public: - inline RpcController() {} - virtual ~RpcController(); - - // Client-side methods --------------------------------------------- - // These calls may be made from the client side only. Their results - // are undefined on the server side (may crash). - - // Resets the RpcController to its initial state so that it may be reused in - // a new call. Must not be called while an RPC is in progress. - virtual void Reset() = 0; - - // After a call has finished, returns true if the call failed. The possible - // reasons for failure depend on the RPC implementation. Failed() must not - // be called before a call has finished. If Failed() returns true, the - // contents of the response message are undefined. - virtual bool Failed() const = 0; - - // If Failed() is true, returns a human-readable description of the error. - virtual string ErrorText() const = 0; - - // Advises the RPC system that the caller desires that the RPC call be - // canceled. The RPC system may cancel it immediately, may wait awhile and - // then cancel it, or may not even cancel the call at all. If the call is - // canceled, the "done" callback will still be called and the RpcController - // will indicate that the call failed at that time. - virtual void StartCancel() = 0; - - // Server-side methods --------------------------------------------- - // These calls may be made from the server side only. Their results - // are undefined on the client side (may crash). - - // Causes Failed() to return true on the client side. "reason" will be - // incorporated into the message returned by ErrorText(). If you find - // you need to return machine-readable information about failures, you - // should incorporate it into your response protocol buffer and should - // NOT call SetFailed(). - virtual void SetFailed(const string& reason) = 0; - - // If true, indicates that the client canceled the RPC, so the server may - // as well give up on replying to it. The server should still call the - // final "done" callback. - virtual bool IsCanceled() const = 0; - - // Asks that the given callback be called when the RPC is canceled. The - // callback will always be called exactly once. If the RPC completes without - // being canceled, the callback will be called after completion. If the RPC - // has already been canceled when NotifyOnCancel() is called, the callback - // will be called immediately. - // - // NotifyOnCancel() must be called no more than once per request. - virtual void NotifyOnCancel(Closure* callback) = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RpcController); -}; - -// Abstract interface for an RPC channel. An RpcChannel represents a -// communication line to a Service which can be used to call that Service's -// methods. The Service may be running on another machine. Normally, you -// should not call an RpcChannel directly, but instead construct a stub Service -// wrapping it. Example: -// RpcChannel* channel = new MyRpcChannel("remotehost.example.com:1234"); -// MyService* service = new MyService::Stub(channel); -// service->MyMethod(request, &response, callback); -class LIBPROTOBUF_EXPORT RpcChannel { - public: - inline RpcChannel() {} - virtual ~RpcChannel(); - - // Call the given method of the remote service. The signature of this - // procedure looks the same as Service::CallMethod(), but the requirements - // are less strict in one important way: the request and response objects - // need not be of any specific class as long as their descriptors are - // method->input_type() and method->output_type(). - virtual void CallMethod(const MethodDescriptor* method, - RpcController* controller, - const Message* request, - Message* response, - Closure* done) = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RpcChannel); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_SERVICE_H__ diff --git a/Resources/NetHook/google/protobuf/stubs/common.cc b/Resources/NetHook/google/protobuf/stubs/common.cc deleted file mode 100644 index 1e2d68d2..00000000 --- a/Resources/NetHook/google/protobuf/stubs/common.cc +++ /dev/null @@ -1,365 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#include -#include -#include -#include -#include - -#include "config.h" - -#ifdef _WIN32 -#define WIN32_LEAN_AND_MEAN // We only need minimal includes -#include -#define snprintf _snprintf // see comment in strutil.cc -#elif defined(HAVE_PTHREAD) -#include -#else -#error "No suitable threading library available." -#endif - -namespace google { -namespace protobuf { - -namespace internal { - -void VerifyVersion(int headerVersion, - int minLibraryVersion, - const char* filename) { - if (GOOGLE_PROTOBUF_VERSION < minLibraryVersion) { - // Library is too old for headers. - GOOGLE_LOG(FATAL) - << "This program requires version " << VersionString(minLibraryVersion) - << " of the Protocol Buffer runtime library, but the installed version " - "is " << VersionString(GOOGLE_PROTOBUF_VERSION) << ". Please update " - "your library. If you compiled the program yourself, make sure that " - "your headers are from the same version of Protocol Buffers as your " - "link-time library. (Version verification failed in \"" - << filename << "\".)"; - } - if (headerVersion < kMinHeaderVersionForLibrary) { - // Headers are too old for library. - GOOGLE_LOG(FATAL) - << "This program was compiled against version " - << VersionString(headerVersion) << " of the Protocol Buffer runtime " - "library, which is not compatible with the installed version (" - << VersionString(GOOGLE_PROTOBUF_VERSION) << "). Contact the program " - "author for an update. If you compiled the program yourself, make " - "sure that your headers are from the same version of Protocol Buffers " - "as your link-time library. (Version verification failed in \"" - << filename << "\".)"; - } -} - -string VersionString(int version) { - int major = version / 1000000; - int minor = (version / 1000) % 1000; - int micro = version % 1000; - - // 128 bytes should always be enough, but we use snprintf() anyway to be - // safe. - char buffer[128]; - snprintf(buffer, sizeof(buffer), "%d.%d.%d", major, minor, micro); - - // Guard against broken MSVC snprintf(). - buffer[sizeof(buffer)-1] = '\0'; - - return buffer; -} - -} // namespace internal - -// =================================================================== -// emulates google3/base/logging.cc - -namespace internal { - -void DefaultLogHandler(LogLevel level, const char* filename, int line, - const string& message) { - static const char* level_names[] = { "INFO", "WARNING", "ERROR", "FATAL" }; - - // We use fprintf() instead of cerr because we want this to work at static - // initialization time. - fprintf(stderr, "libprotobuf %s %s:%d] %s\n", - level_names[level], filename, line, message.c_str()); - fflush(stderr); // Needed on MSVC. -} - -void NullLogHandler(LogLevel level, const char* filename, int line, - const string& message) { - // Nothing. -} - -static LogHandler* log_handler_ = &DefaultLogHandler; -static int log_silencer_count_ = 0; - -static Mutex* log_silencer_count_mutex_ = NULL; -GOOGLE_PROTOBUF_DECLARE_ONCE(log_silencer_count_init_); - -void DeleteLogSilencerCount() { - delete log_silencer_count_mutex_; - log_silencer_count_mutex_ = NULL; -} -void InitLogSilencerCount() { - log_silencer_count_mutex_ = new Mutex; - OnShutdown(&DeleteLogSilencerCount); -} -void InitLogSilencerCountOnce() { - GoogleOnceInit(&log_silencer_count_init_, &InitLogSilencerCount); -} - -LogMessage& LogMessage::operator<<(const string& value) { - message_ += value; - return *this; -} - -LogMessage& LogMessage::operator<<(const char* value) { - message_ += value; - return *this; -} - -// Since this is just for logging, we don't care if the current locale changes -// the results -- in fact, we probably prefer that. So we use snprintf() -// instead of Simple*toa(). -#undef DECLARE_STREAM_OPERATOR -#define DECLARE_STREAM_OPERATOR(TYPE, FORMAT) \ - LogMessage& LogMessage::operator<<(TYPE value) { \ - /* 128 bytes should be big enough for any of the primitive */ \ - /* values which we print with this, but well use snprintf() */ \ - /* anyway to be extra safe. */ \ - char buffer[128]; \ - snprintf(buffer, sizeof(buffer), FORMAT, value); \ - /* Guard against broken MSVC snprintf(). */ \ - buffer[sizeof(buffer)-1] = '\0'; \ - message_ += buffer; \ - return *this; \ - } - -DECLARE_STREAM_OPERATOR(char , "%c" ) -DECLARE_STREAM_OPERATOR(int , "%d" ) -DECLARE_STREAM_OPERATOR(uint , "%u" ) -DECLARE_STREAM_OPERATOR(long , "%ld") -DECLARE_STREAM_OPERATOR(unsigned long, "%lu") -DECLARE_STREAM_OPERATOR(double , "%g" ) -#undef DECLARE_STREAM_OPERATOR - -LogMessage::LogMessage(LogLevel level, const char* filename, int line) - : level_(level), filename_(filename), line_(line) {} -LogMessage::~LogMessage() {} - -void LogMessage::Finish() { - bool suppress = false; - - if (level_ != LOGLEVEL_FATAL) { - InitLogSilencerCountOnce(); - MutexLock lock(log_silencer_count_mutex_); - suppress = internal::log_silencer_count_ > 0; - } - - if (!suppress) { - internal::log_handler_(level_, filename_, line_, message_); - } - - if (level_ == LOGLEVEL_FATAL) { - abort(); - } -} - -void LogFinisher::operator=(LogMessage& other) { - other.Finish(); -} - -} // namespace internal - -LogHandler* SetLogHandler(LogHandler* new_func) { - LogHandler* old = internal::log_handler_; - if (old == &internal::NullLogHandler) { - old = NULL; - } - if (new_func == NULL) { - internal::log_handler_ = &internal::NullLogHandler; - } else { - internal::log_handler_ = new_func; - } - return old; -} - -LogSilencer::LogSilencer() { - internal::InitLogSilencerCountOnce(); - MutexLock lock(internal::log_silencer_count_mutex_); - ++internal::log_silencer_count_; -}; - -LogSilencer::~LogSilencer() { - internal::InitLogSilencerCountOnce(); - MutexLock lock(internal::log_silencer_count_mutex_); - --internal::log_silencer_count_; -}; - -// =================================================================== -// emulates google3/base/callback.cc - -Closure::~Closure() {} - -namespace internal { FunctionClosure0::~FunctionClosure0() {} } - -void DoNothing() {} - -// =================================================================== -// emulates google3/base/mutex.cc - -#ifdef _WIN32 - -struct Mutex::Internal { - CRITICAL_SECTION mutex; -#ifndef NDEBUG - // Used only to implement AssertHeld(). - DWORD thread_id; -#endif -}; - -Mutex::Mutex() - : mInternal(new Internal) { - InitializeCriticalSection(&mInternal->mutex); -} - -Mutex::~Mutex() { - DeleteCriticalSection(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - EnterCriticalSection(&mInternal->mutex); -#ifndef NDEBUG - mInternal->thread_id = GetCurrentThreadId(); -#endif -} - -void Mutex::Unlock() { -#ifndef NDEBUG - mInternal->thread_id = 0; -#endif - LeaveCriticalSection(&mInternal->mutex); -} - -void Mutex::AssertHeld() { -#ifndef NDEBUG - GOOGLE_DCHECK_EQ(mInternal->thread_id, GetCurrentThreadId()); -#endif -} - -#elif defined(HAVE_PTHREAD) - -struct Mutex::Internal { - pthread_mutex_t mutex; -}; - -Mutex::Mutex() - : mInternal(new Internal) { - pthread_mutex_init(&mInternal->mutex, NULL); -} - -Mutex::~Mutex() { - pthread_mutex_destroy(&mInternal->mutex); - delete mInternal; -} - -void Mutex::Lock() { - int result = pthread_mutex_lock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_lock: " << strerror(result); - } -} - -void Mutex::Unlock() { - int result = pthread_mutex_unlock(&mInternal->mutex); - if (result != 0) { - GOOGLE_LOG(FATAL) << "pthread_mutex_unlock: " << strerror(result); - } -} - -void Mutex::AssertHeld() { - // pthreads dosn't provide a way to check which thread holds the mutex. - // TODO(kenton): Maybe keep track of locking thread ID like with WIN32? -} - -#endif - -// =================================================================== -// Shutdown support. - -namespace internal { - -typedef void OnShutdownFunc(); -vector* shutdown_functions = NULL; -Mutex* shutdown_functions_mutex = NULL; -GOOGLE_PROTOBUF_DECLARE_ONCE(shutdown_functions_init); - -void InitShutdownFunctions() { - shutdown_functions = new vector; - shutdown_functions_mutex = new Mutex; -} - -inline void InitShutdownFunctionsOnce() { - GoogleOnceInit(&shutdown_functions_init, &InitShutdownFunctions); -} - -void OnShutdown(void (*func)()) { - InitShutdownFunctionsOnce(); - MutexLock lock(shutdown_functions_mutex); - shutdown_functions->push_back(func); -} - -} // namespace internal - -void ShutdownProtobufLibrary() { - internal::InitShutdownFunctionsOnce(); - - // We don't need to lock shutdown_functions_mutex because it's up to the - // caller to make sure that no one is using the library before this is - // called. - - // Make it safe to call this multiple times. - if (internal::shutdown_functions == NULL) return; - - for (int i = 0; i < internal::shutdown_functions->size(); i++) { - internal::shutdown_functions->at(i)(); - } - delete internal::shutdown_functions; - internal::shutdown_functions = NULL; - delete internal::shutdown_functions_mutex; - internal::shutdown_functions_mutex = NULL; -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/common.h b/Resources/NetHook/google/protobuf/stubs/common.h deleted file mode 100644 index 551ee4aa..00000000 --- a/Resources/NetHook/google/protobuf/stubs/common.h +++ /dev/null @@ -1,1155 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) and others -// -// Contains basic types and utilities used by the rest of the library. - -#ifndef GOOGLE_PROTOBUF_COMMON_H__ -#define GOOGLE_PROTOBUF_COMMON_H__ - -#include -#include -#include -#include -#include -#if defined(__osf__) -// Tru64 lacks stdint.h, but has inttypes.h which defines a superset of -// what stdint.h would define. -#include -#elif !defined(_MSC_VER) -#include -#endif - -namespace std {} - -namespace google { -namespace protobuf { - -using namespace std; // Don't do this at home, kids. - -#undef GOOGLE_DISALLOW_EVIL_CONSTRUCTORS -#define GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TypeName) \ - TypeName(const TypeName&); \ - void operator=(const TypeName&) - -#if defined(_MSC_VER) && defined(PROTOBUF_USE_DLLS) - #ifdef LIBPROTOBUF_EXPORTS - #define LIBPROTOBUF_EXPORT __declspec(dllexport) - #else - #define LIBPROTOBUF_EXPORT __declspec(dllimport) - #endif - #ifdef LIBPROTOC_EXPORTS - #define LIBPROTOC_EXPORT __declspec(dllexport) - #else - #define LIBPROTOC_EXPORT __declspec(dllimport) - #endif -#else - #define LIBPROTOBUF_EXPORT - #define LIBPROTOC_EXPORT -#endif - -namespace internal { - -// Some of these constants are macros rather than const ints so that they can -// be used in #if directives. - -// The current version, represented as a single integer to make comparison -// easier: major * 10^6 + minor * 10^3 + micro -#define GOOGLE_PROTOBUF_VERSION 2003000 - -// The minimum library version which works with the current version of the -// headers. -#define GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION 2003000 - -// The minimum header version which works with the current version of -// the library. This constant should only be used by protoc's C++ code -// generator. -static const int kMinHeaderVersionForLibrary = 2003000; - -// The minimum protoc version which works with the current version of the -// headers. -#define GOOGLE_PROTOBUF_MIN_PROTOC_VERSION 2003000 - -// The minimum header version which works with the current version of -// protoc. This constant should only be used in VerifyVersion(). -static const int kMinHeaderVersionForProtoc = 2003000; - -// Verifies that the headers and libraries are compatible. Use the macro -// below to call this. -void LIBPROTOBUF_EXPORT VerifyVersion(int headerVersion, int minLibraryVersion, - const char* filename); - -// Converts a numeric version number to a string. -string LIBPROTOBUF_EXPORT VersionString(int version); - -} // namespace internal - -// Place this macro in your main() function (or somewhere before you attempt -// to use the protobuf library) to verify that the version you link against -// matches the headers you compiled against. If a version mismatch is -// detected, the process will abort. -#define GOOGLE_PROTOBUF_VERIFY_VERSION \ - ::google::protobuf::internal::VerifyVersion( \ - GOOGLE_PROTOBUF_VERSION, GOOGLE_PROTOBUF_MIN_LIBRARY_VERSION, \ - __FILE__) - -// =================================================================== -// from google3/base/port.h - -typedef unsigned int uint; - -#ifdef _MSC_VER -typedef __int8 int8; -typedef __int16 int16; -typedef __int32 int32; -typedef __int64 int64; - -typedef unsigned __int8 uint8; -typedef unsigned __int16 uint16; -typedef unsigned __int32 uint32; -typedef unsigned __int64 uint64; -#else -typedef int8_t int8; -typedef int16_t int16; -typedef int32_t int32; -typedef int64_t int64; - -typedef uint8_t uint8; -typedef uint16_t uint16; -typedef uint32_t uint32; -typedef uint64_t uint64; -#endif - -// long long macros to be used because gcc and vc++ use different suffixes, -// and different size specifiers in format strings -#undef GOOGLE_LONGLONG -#undef GOOGLE_ULONGLONG -#undef GOOGLE_LL_FORMAT - -#ifdef _MSC_VER -#define GOOGLE_LONGLONG(x) x##I64 -#define GOOGLE_ULONGLONG(x) x##UI64 -#define GOOGLE_LL_FORMAT "I64" // As in printf("%I64d", ...) -#else -#define GOOGLE_LONGLONG(x) x##LL -#define GOOGLE_ULONGLONG(x) x##ULL -#define GOOGLE_LL_FORMAT "ll" // As in "%lld". Note that "q" is poor form also. -#endif - -static const int32 kint32max = 0x7FFFFFFF; -static const int32 kint32min = -kint32max - 1; -static const int64 kint64max = GOOGLE_LONGLONG(0x7FFFFFFFFFFFFFFF); -static const int64 kint64min = -kint64max - 1; -static const uint32 kuint32max = 0xFFFFFFFFu; -static const uint64 kuint64max = GOOGLE_ULONGLONG(0xFFFFFFFFFFFFFFFF); - -// ------------------------------------------------------------------- -// Annotations: Some parts of the code have been annotated in ways that might -// be useful to some compilers or tools, but are not supported universally. -// You can #define these annotations yourself if the default implementation -// is not right for you. - -#ifndef GOOGLE_ATTRIBUTE_ALWAYS_INLINE -#if defined(__GNUC__) && (__GNUC__ > 3 ||(__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -// For functions we want to force inline. -// Introduced in gcc 3.1. -#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE __attribute__ ((always_inline)) -#else -// Other compilers will have to figure it out for themselves. -#define GOOGLE_ATTRIBUTE_ALWAYS_INLINE -#endif -#endif - -#ifndef GOOGLE_ATTRIBUTE_DEPRECATED -#ifdef __GNUC__ -// If the method/variable/type is used anywhere, produce a warning. -#define GOOGLE_ATTRIBUTE_DEPRECATED __attribute__((deprecated)) -#else -#define GOOGLE_ATTRIBUTE_DEPRECATED -#endif -#endif - -#ifndef GOOGLE_PREDICT_TRUE -#ifdef __GNUC__ -// Provided at least since GCC 3.0. -#define GOOGLE_PREDICT_TRUE(x) (__builtin_expect(!!(x), 1)) -#else -#define GOOGLE_PREDICT_TRUE -#endif -#endif - -// Delimits a block of code which may write to memory which is simultaneously -// written by other threads, but which has been determined to be thread-safe -// (e.g. because it is an idempotent write). -#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN -#define GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN() -#endif -#ifndef GOOGLE_SAFE_CONCURRENT_WRITES_END -#define GOOGLE_SAFE_CONCURRENT_WRITES_END() -#endif - -// =================================================================== -// from google3/base/basictypes.h - -// The GOOGLE_ARRAYSIZE(arr) macro returns the # of elements in an array arr. -// The expression is a compile-time constant, and therefore can be -// used in defining new arrays, for example. -// -// GOOGLE_ARRAYSIZE catches a few type errors. If you see a compiler error -// -// "warning: division by zero in ..." -// -// when using GOOGLE_ARRAYSIZE, you are (wrongfully) giving it a pointer. -// You should only use GOOGLE_ARRAYSIZE on statically allocated arrays. -// -// The following comments are on the implementation details, and can -// be ignored by the users. -// -// ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in -// the array) and sizeof(*(arr)) (the # of bytes in one array -// element). If the former is divisible by the latter, perhaps arr is -// indeed an array, in which case the division result is the # of -// elements in the array. Otherwise, arr cannot possibly be an array, -// and we generate a compiler error to prevent the code from -// compiling. -// -// Since the size of bool is implementation-defined, we need to cast -// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final -// result has type size_t. -// -// This macro is not perfect as it wrongfully accepts certain -// pointers, namely where the pointer size is divisible by the pointee -// size. Since all our code has to go through a 32-bit compiler, -// where a pointer is 4 bytes, this means all pointers to a type whose -// size is 3 or greater than 4 will be (righteously) rejected. -// -// Kudos to Jorg Brown for this simple and elegant implementation. - -#undef GOOGLE_ARRAYSIZE -#define GOOGLE_ARRAYSIZE(a) \ - ((sizeof(a) / sizeof(*(a))) / \ - static_cast(!(sizeof(a) % sizeof(*(a))))) - -namespace internal { - -// Use implicit_cast as a safe version of static_cast or const_cast -// for upcasting in the type hierarchy (i.e. casting a pointer to Foo -// to a pointer to SuperclassOfFoo or casting a pointer to Foo to -// a const pointer to Foo). -// When you use implicit_cast, the compiler checks that the cast is safe. -// Such explicit implicit_casts are necessary in surprisingly many -// situations where C++ demands an exact type match instead of an -// argument type convertable to a target type. -// -// The From type can be inferred, so the preferred syntax for using -// implicit_cast is the same as for static_cast etc.: -// -// implicit_cast(expr) -// -// implicit_cast would have been part of the C++ standard library, -// but the proposal was submitted too late. It will probably make -// its way into the language in the future. -template -inline To implicit_cast(From const &f) { - return f; -} - -// When you upcast (that is, cast a pointer from type Foo to type -// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts -// always succeed. When you downcast (that is, cast a pointer from -// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because -// how do you know the pointer is really of type SubclassOfFoo? It -// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus, -// when you downcast, you should use this macro. In debug mode, we -// use dynamic_cast<> to double-check the downcast is legal (we die -// if it's not). In normal mode, we do the efficient static_cast<> -// instead. Thus, it's important to test in debug mode to make sure -// the cast is legal! -// This is the only place in the code we should use dynamic_cast<>. -// In particular, you SHOULDN'T be using dynamic_cast<> in order to -// do RTTI (eg code like this: -// if (dynamic_cast(foo)) HandleASubclass1Object(foo); -// if (dynamic_cast(foo)) HandleASubclass2Object(foo); -// You should design the code some other way not to need this. - -template // use like this: down_cast(foo); -inline To down_cast(From* f) { // so we only accept pointers - // Ensures that To is a sub-type of From *. This test is here only - // for compile-time type checking, and has no overhead in an - // optimized build at run-time, as it will be optimized away - // completely. - if (false) { - implicit_cast(0); - } - -#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI) - assert(f == NULL || dynamic_cast(f) != NULL); // RTTI: debug mode only! -#endif - return static_cast(f); -} - -} // namespace internal - -// We made these internal so that they would show up as such in the docs, -// but we don't want to stick "internal::" in front of them everywhere. -using internal::implicit_cast; -using internal::down_cast; - -// The COMPILE_ASSERT macro can be used to verify that a compile time -// expression is true. For example, you could use it to verify the -// size of a static array: -// -// COMPILE_ASSERT(ARRAYSIZE(content_type_names) == CONTENT_NUM_TYPES, -// content_type_names_incorrect_size); -// -// or to make sure a struct is smaller than a certain size: -// -// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large); -// -// The second argument to the macro is the name of the variable. If -// the expression is false, most compilers will issue a warning/error -// containing the name of the variable. - -namespace internal { - -template -struct CompileAssert { -}; - -} // namespace internal - -#undef GOOGLE_COMPILE_ASSERT -#define GOOGLE_COMPILE_ASSERT(expr, msg) \ - typedef ::google::protobuf::internal::CompileAssert<(bool(expr))> \ - msg[bool(expr) ? 1 : -1] - -// Implementation details of COMPILE_ASSERT: -// -// - COMPILE_ASSERT works by defining an array type that has -1 -// elements (and thus is invalid) when the expression is false. -// -// - The simpler definition -// -// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1] -// -// does not work, as gcc supports variable-length arrays whose sizes -// are determined at run-time (this is gcc's extension and not part -// of the C++ standard). As a result, gcc fails to reject the -// following code with the simple definition: -// -// int foo; -// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is -// // not a compile-time constant. -// -// - By using the type CompileAssert<(bool(expr))>, we ensures that -// expr is a compile-time constant. (Template arguments must be -// determined at compile-time.) -// -// - The outter parentheses in CompileAssert<(bool(expr))> are necessary -// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written -// -// CompileAssert -// -// instead, these compilers will refuse to compile -// -// COMPILE_ASSERT(5 > 0, some_message); -// -// (They seem to think the ">" in "5 > 0" marks the end of the -// template argument list.) -// -// - The array size is (bool(expr) ? 1 : -1), instead of simply -// -// ((expr) ? 1 : -1). -// -// This is to avoid running into a bug in MS VC 7.1, which -// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1. - -// =================================================================== -// from google3/base/scoped_ptr.h - -namespace internal { - -// This is an implementation designed to match the anticipated future TR2 -// implementation of the scoped_ptr class, and its closely-related brethren, -// scoped_array, scoped_ptr_malloc, and make_scoped_ptr. - -template class scoped_ptr; -template class scoped_array; - -// A scoped_ptr is like a T*, except that the destructor of scoped_ptr -// automatically deletes the pointer it holds (if any). -// That is, scoped_ptr owns the T object that it points to. -// Like a T*, a scoped_ptr may hold either NULL or a pointer to a T object. -// -// The size of a scoped_ptr is small: -// sizeof(scoped_ptr) == sizeof(C*) -template -class scoped_ptr { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to intializing with NULL. - // There is no way to create an uninitialized scoped_ptr. - // The input parameter must be allocated with new. - explicit scoped_ptr(C* p = NULL) : ptr_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_ptr() { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != ptr_) { - enum { type_must_be_complete = sizeof(C) }; - delete ptr_; - ptr_ = p; - } - } - - // Accessors to get the owned object. - // operator* and operator-> will assert() if there is no current object. - C& operator*() const { - assert(ptr_ != NULL); - return *ptr_; - } - C* operator->() const { - assert(ptr_ != NULL); - return ptr_; - } - C* get() const { return ptr_; } - - // Comparison operators. - // These return whether two scoped_ptr refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return ptr_ == p; } - bool operator!=(C* p) const { return ptr_ != p; } - - // Swap two scoped pointers. - void swap(scoped_ptr& p2) { - C* tmp = ptr_; - ptr_ = p2.ptr_; - p2.ptr_ = tmp; - } - - // Release a pointer. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = ptr_; - ptr_ = NULL; - return retVal; - } - - private: - C* ptr_; - - // Forbid comparison of scoped_ptr types. If C2 != C, it totally doesn't - // make sense, and if C2 == C, it still doesn't make sense because you should - // never have the same object owned by two different scoped_ptrs. - template bool operator==(scoped_ptr const& p2) const; - template bool operator!=(scoped_ptr const& p2) const; - - // Disallow evil constructors - scoped_ptr(const scoped_ptr&); - void operator=(const scoped_ptr&); -}; - -// scoped_array is like scoped_ptr, except that the caller must allocate -// with new [] and the destructor deletes objects with delete []. -// -// As with scoped_ptr, a scoped_array either points to an object -// or is NULL. A scoped_array owns the object that it points to. -// -// Size: sizeof(scoped_array) == sizeof(C*) -template -class scoped_array { - public: - - // The element type - typedef C element_type; - - // Constructor. Defaults to intializing with NULL. - // There is no way to create an uninitialized scoped_array. - // The input parameter must be allocated with new []. - explicit scoped_array(C* p = NULL) : array_(p) { } - - // Destructor. If there is a C object, delete it. - // We don't need to test ptr_ == NULL because C++ does that for us. - ~scoped_array() { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - } - - // Reset. Deletes the current owned object, if any. - // Then takes ownership of a new object, if given. - // this->reset(this->get()) works. - void reset(C* p = NULL) { - if (p != array_) { - enum { type_must_be_complete = sizeof(C) }; - delete[] array_; - array_ = p; - } - } - - // Get one element of the current object. - // Will assert() if there is no current object, or index i is negative. - C& operator[](std::ptrdiff_t i) const { - assert(i >= 0); - assert(array_ != NULL); - return array_[i]; - } - - // Get a pointer to the zeroth element of the current object. - // If there is no current object, return NULL. - C* get() const { - return array_; - } - - // Comparison operators. - // These return whether two scoped_array refer to the same object, not just to - // two different but equal objects. - bool operator==(C* p) const { return array_ == p; } - bool operator!=(C* p) const { return array_ != p; } - - // Swap two scoped arrays. - void swap(scoped_array& p2) { - C* tmp = array_; - array_ = p2.array_; - p2.array_ = tmp; - } - - // Release an array. - // The return value is the current pointer held by this object. - // If this object holds a NULL pointer, the return value is NULL. - // After this operation, this object will hold a NULL pointer, - // and will not own the object any more. - C* release() { - C* retVal = array_; - array_ = NULL; - return retVal; - } - - private: - C* array_; - - // Forbid comparison of different scoped_array types. - template bool operator==(scoped_array const& p2) const; - template bool operator!=(scoped_array const& p2) const; - - // Disallow evil constructors - scoped_array(const scoped_array&); - void operator=(const scoped_array&); -}; - -} // namespace internal - -// We made these internal so that they would show up as such in the docs, -// but we don't want to stick "internal::" in front of them everywhere. -using internal::scoped_ptr; -using internal::scoped_array; - -// =================================================================== -// emulates google3/base/logging.h - -enum LogLevel { - LOGLEVEL_INFO, // Informational. This is never actually used by - // libprotobuf. - LOGLEVEL_WARNING, // Warns about issues that, although not technically a - // problem now, could cause problems in the future. For - // example, a // warning will be printed when parsing a - // message that is near the message size limit. - LOGLEVEL_ERROR, // An error occurred which should never happen during - // normal use. - LOGLEVEL_FATAL, // An error occurred from which the library cannot - // recover. This usually indicates a programming error - // in the code which calls the library, especially when - // compiled in debug mode. - -#ifdef NDEBUG - LOGLEVEL_DFATAL = LOGLEVEL_ERROR -#else - LOGLEVEL_DFATAL = LOGLEVEL_FATAL -#endif -}; - -namespace internal { - -class LogFinisher; - -class LIBPROTOBUF_EXPORT LogMessage { - public: - LogMessage(LogLevel level, const char* filename, int line); - ~LogMessage(); - - LogMessage& operator<<(const string& value); - LogMessage& operator<<(const char* value); - LogMessage& operator<<(char value); - LogMessage& operator<<(int value); - LogMessage& operator<<(uint value); - LogMessage& operator<<(long value); - LogMessage& operator<<(unsigned long value); - LogMessage& operator<<(double value); - - private: - friend class LogFinisher; - void Finish(); - - LogLevel level_; - const char* filename_; - int line_; - string message_; -}; - -// Used to make the entire "LOG(BLAH) << etc." expression have a void return -// type and print a newline after each message. -class LIBPROTOBUF_EXPORT LogFinisher { - public: - void operator=(LogMessage& other); -}; - -} // namespace internal - -// Undef everything in case we're being mixed with some other Google library -// which already defined them itself. Presumably all Google libraries will -// support the same syntax for these so it should not be a big deal if they -// end up using our definitions instead. -#undef GOOGLE_LOG -#undef GOOGLE_LOG_IF - -#undef GOOGLE_CHECK -#undef GOOGLE_CHECK_EQ -#undef GOOGLE_CHECK_NE -#undef GOOGLE_CHECK_LT -#undef GOOGLE_CHECK_LE -#undef GOOGLE_CHECK_GT -#undef GOOGLE_CHECK_GE - -#undef GOOGLE_DLOG -#undef GOOGLE_DCHECK -#undef GOOGLE_DCHECK_EQ -#undef GOOGLE_DCHECK_NE -#undef GOOGLE_DCHECK_LT -#undef GOOGLE_DCHECK_LE -#undef GOOGLE_DCHECK_GT -#undef GOOGLE_DCHECK_GE - -#define GOOGLE_LOG(LEVEL) \ - ::google::protobuf::internal::LogFinisher() = \ - ::google::protobuf::internal::LogMessage( \ - ::google::protobuf::LOGLEVEL_##LEVEL, __FILE__, __LINE__) -#define GOOGLE_LOG_IF(LEVEL, CONDITION) \ - !(CONDITION) ? (void)0 : GOOGLE_LOG(LEVEL) - -#define GOOGLE_CHECK(EXPRESSION) \ - GOOGLE_LOG_IF(FATAL, !(EXPRESSION)) << "CHECK failed: " #EXPRESSION ": " -#define GOOGLE_CHECK_EQ(A, B) GOOGLE_CHECK((A) == (B)) -#define GOOGLE_CHECK_NE(A, B) GOOGLE_CHECK((A) != (B)) -#define GOOGLE_CHECK_LT(A, B) GOOGLE_CHECK((A) < (B)) -#define GOOGLE_CHECK_LE(A, B) GOOGLE_CHECK((A) <= (B)) -#define GOOGLE_CHECK_GT(A, B) GOOGLE_CHECK((A) > (B)) -#define GOOGLE_CHECK_GE(A, B) GOOGLE_CHECK((A) >= (B)) - -#ifdef NDEBUG - -#define GOOGLE_DLOG GOOGLE_LOG_IF(INFO, false) - -#define GOOGLE_DCHECK(EXPRESSION) while(false) GOOGLE_CHECK(EXPRESSION) -#define GOOGLE_DCHECK_EQ(A, B) GOOGLE_DCHECK((A) == (B)) -#define GOOGLE_DCHECK_NE(A, B) GOOGLE_DCHECK((A) != (B)) -#define GOOGLE_DCHECK_LT(A, B) GOOGLE_DCHECK((A) < (B)) -#define GOOGLE_DCHECK_LE(A, B) GOOGLE_DCHECK((A) <= (B)) -#define GOOGLE_DCHECK_GT(A, B) GOOGLE_DCHECK((A) > (B)) -#define GOOGLE_DCHECK_GE(A, B) GOOGLE_DCHECK((A) >= (B)) - -#else // NDEBUG - -#define GOOGLE_DLOG GOOGLE_LOG - -#define GOOGLE_DCHECK GOOGLE_CHECK -#define GOOGLE_DCHECK_EQ GOOGLE_CHECK_EQ -#define GOOGLE_DCHECK_NE GOOGLE_CHECK_NE -#define GOOGLE_DCHECK_LT GOOGLE_CHECK_LT -#define GOOGLE_DCHECK_LE GOOGLE_CHECK_LE -#define GOOGLE_DCHECK_GT GOOGLE_CHECK_GT -#define GOOGLE_DCHECK_GE GOOGLE_CHECK_GE - -#endif // !NDEBUG - -typedef void LogHandler(LogLevel level, const char* filename, int line, - const string& message); - -// The protobuf library sometimes writes warning and error messages to -// stderr. These messages are primarily useful for developers, but may -// also help end users figure out a problem. If you would prefer that -// these messages be sent somewhere other than stderr, call SetLogHandler() -// to set your own handler. This returns the old handler. Set the handler -// to NULL to ignore log messages (but see also LogSilencer, below). -// -// Obviously, SetLogHandler is not thread-safe. You should only call it -// at initialization time, and probably not from library code. If you -// simply want to suppress log messages temporarily (e.g. because you -// have some code that tends to trigger them frequently and you know -// the warnings are not important to you), use the LogSilencer class -// below. -LIBPROTOBUF_EXPORT LogHandler* SetLogHandler(LogHandler* new_func); - -// Create a LogSilencer if you want to temporarily suppress all log -// messages. As long as any LogSilencer objects exist, non-fatal -// log messages will be discarded (the current LogHandler will *not* -// be called). Constructing a LogSilencer is thread-safe. You may -// accidentally suppress log messages occurring in another thread, but -// since messages are generally for debugging purposes only, this isn't -// a big deal. If you want to intercept log messages, use SetLogHandler(). -class LIBPROTOBUF_EXPORT LogSilencer { - public: - LogSilencer(); - ~LogSilencer(); -}; - -// =================================================================== -// emulates google3/base/callback.h - -// Abstract interface for a callback. When calling an RPC, you must provide -// a Closure to call when the procedure completes. See the Service interface -// in service.h. -// -// To automatically construct a Closure which calls a particular function or -// method with a particular set of parameters, use the NewCallback() function. -// Example: -// void FooDone(const FooResponse* response) { -// ... -// } -// -// void CallFoo() { -// ... -// // When done, call FooDone() and pass it a pointer to the response. -// Closure* callback = NewCallback(&FooDone, response); -// // Make the call. -// service->Foo(controller, request, response, callback); -// } -// -// Example that calls a method: -// class Handler { -// public: -// ... -// -// void FooDone(const FooResponse* response) { -// ... -// } -// -// void CallFoo() { -// ... -// // When done, call FooDone() and pass it a pointer to the response. -// Closure* callback = NewCallback(this, &Handler::FooDone, response); -// // Make the call. -// service->Foo(controller, request, response, callback); -// } -// }; -// -// Currently NewCallback() supports binding zero, one, or two arguments. -// -// Callbacks created with NewCallback() automatically delete themselves when -// executed. They should be used when a callback is to be called exactly -// once (usually the case with RPC callbacks). If a callback may be called -// a different number of times (including zero), create it with -// NewPermanentCallback() instead. You are then responsible for deleting the -// callback (using the "delete" keyword as normal). -// -// Note that NewCallback() is a bit touchy regarding argument types. Generally, -// the values you provide for the parameter bindings must exactly match the -// types accepted by the callback function. For example: -// void Foo(string s); -// NewCallback(&Foo, "foo"); // WON'T WORK: const char* != string -// NewCallback(&Foo, string("foo")); // WORKS -// Also note that the arguments cannot be references: -// void Foo(const string& s); -// string my_str; -// NewCallback(&Foo, my_str); // WON'T WORK: Can't use referecnes. -// However, correctly-typed pointers will work just fine. -class LIBPROTOBUF_EXPORT Closure { - public: - Closure() {} - virtual ~Closure(); - - virtual void Run() = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Closure); -}; - -namespace internal { - -class LIBPROTOBUF_EXPORT FunctionClosure0 : public Closure { - public: - typedef void (*FunctionType)(); - - FunctionClosure0(FunctionType function, bool self_deleting) - : function_(function), self_deleting_(self_deleting) {} - ~FunctionClosure0(); - - void Run() { - function_(); - if (self_deleting_) delete this; - } - - private: - FunctionType function_; - bool self_deleting_; -}; - -template -class MethodClosure0 : public Closure { - public: - typedef void (Class::*MethodType)(); - - MethodClosure0(Class* object, MethodType method, bool self_deleting) - : object_(object), method_(method), self_deleting_(self_deleting) {} - ~MethodClosure0() {} - - void Run() { - (object_->*method_)(); - if (self_deleting_) delete this; - } - - private: - Class* object_; - MethodType method_; - bool self_deleting_; -}; - -template -class FunctionClosure1 : public Closure { - public: - typedef void (*FunctionType)(Arg1 arg1); - - FunctionClosure1(FunctionType function, bool self_deleting, - Arg1 arg1) - : function_(function), self_deleting_(self_deleting), - arg1_(arg1) {} - ~FunctionClosure1() {} - - void Run() { - function_(arg1_); - if (self_deleting_) delete this; - } - - private: - FunctionType function_; - bool self_deleting_; - Arg1 arg1_; -}; - -template -class MethodClosure1 : public Closure { - public: - typedef void (Class::*MethodType)(Arg1 arg1); - - MethodClosure1(Class* object, MethodType method, bool self_deleting, - Arg1 arg1) - : object_(object), method_(method), self_deleting_(self_deleting), - arg1_(arg1) {} - ~MethodClosure1() {} - - void Run() { - (object_->*method_)(arg1_); - if (self_deleting_) delete this; - } - - private: - Class* object_; - MethodType method_; - bool self_deleting_; - Arg1 arg1_; -}; - -template -class FunctionClosure2 : public Closure { - public: - typedef void (*FunctionType)(Arg1 arg1, Arg2 arg2); - - FunctionClosure2(FunctionType function, bool self_deleting, - Arg1 arg1, Arg2 arg2) - : function_(function), self_deleting_(self_deleting), - arg1_(arg1), arg2_(arg2) {} - ~FunctionClosure2() {} - - void Run() { - function_(arg1_, arg2_); - if (self_deleting_) delete this; - } - - private: - FunctionType function_; - bool self_deleting_; - Arg1 arg1_; - Arg2 arg2_; -}; - -template -class MethodClosure2 : public Closure { - public: - typedef void (Class::*MethodType)(Arg1 arg1, Arg2 arg2); - - MethodClosure2(Class* object, MethodType method, bool self_deleting, - Arg1 arg1, Arg2 arg2) - : object_(object), method_(method), self_deleting_(self_deleting), - arg1_(arg1), arg2_(arg2) {} - ~MethodClosure2() {} - - void Run() { - (object_->*method_)(arg1_, arg2_); - if (self_deleting_) delete this; - } - - private: - Class* object_; - MethodType method_; - bool self_deleting_; - Arg1 arg1_; - Arg2 arg2_; -}; - -} // namespace internal - -// See Closure. -inline Closure* NewCallback(void (*function)()) { - return new internal::FunctionClosure0(function, true); -} - -// See Closure. -inline Closure* NewPermanentCallback(void (*function)()) { - return new internal::FunctionClosure0(function, false); -} - -// See Closure. -template -inline Closure* NewCallback(Class* object, void (Class::*method)()) { - return new internal::MethodClosure0(object, method, true); -} - -// See Closure. -template -inline Closure* NewPermanentCallback(Class* object, void (Class::*method)()) { - return new internal::MethodClosure0(object, method, false); -} - -// See Closure. -template -inline Closure* NewCallback(void (*function)(Arg1), - Arg1 arg1) { - return new internal::FunctionClosure1(function, true, arg1); -} - -// See Closure. -template -inline Closure* NewPermanentCallback(void (*function)(Arg1), - Arg1 arg1) { - return new internal::FunctionClosure1(function, false, arg1); -} - -// See Closure. -template -inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1), - Arg1 arg1) { - return new internal::MethodClosure1(object, method, true, arg1); -} - -// See Closure. -template -inline Closure* NewPermanentCallback(Class* object, void (Class::*method)(Arg1), - Arg1 arg1) { - return new internal::MethodClosure1(object, method, false, arg1); -} - -// See Closure. -template -inline Closure* NewCallback(void (*function)(Arg1, Arg2), - Arg1 arg1, Arg2 arg2) { - return new internal::FunctionClosure2( - function, true, arg1, arg2); -} - -// See Closure. -template -inline Closure* NewPermanentCallback(void (*function)(Arg1, Arg2), - Arg1 arg1, Arg2 arg2) { - return new internal::FunctionClosure2( - function, false, arg1, arg2); -} - -// See Closure. -template -inline Closure* NewCallback(Class* object, void (Class::*method)(Arg1, Arg2), - Arg1 arg1, Arg2 arg2) { - return new internal::MethodClosure2( - object, method, true, arg1, arg2); -} - -// See Closure. -template -inline Closure* NewPermanentCallback( - Class* object, void (Class::*method)(Arg1, Arg2), - Arg1 arg1, Arg2 arg2) { - return new internal::MethodClosure2( - object, method, false, arg1, arg2); -} - -// A function which does nothing. Useful for creating no-op callbacks, e.g.: -// Closure* nothing = NewCallback(&DoNothing); -void LIBPROTOBUF_EXPORT DoNothing(); - -// =================================================================== -// emulates google3/base/mutex.h - -namespace internal { - -// A Mutex is a non-reentrant (aka non-recursive) mutex. At most one thread T -// may hold a mutex at a given time. If T attempts to Lock() the same Mutex -// while holding it, T will deadlock. -class LIBPROTOBUF_EXPORT Mutex { - public: - // Create a Mutex that is not held by anybody. - Mutex(); - - // Destructor - ~Mutex(); - - // Block if necessary until this Mutex is free, then acquire it exclusively. - void Lock(); - - // Release this Mutex. Caller must hold it exclusively. - void Unlock(); - - // Crash if this Mutex is not held exclusively by this thread. - // May fail to crash when it should; will never crash when it should not. - void AssertHeld(); - - private: - struct Internal; - Internal* mInternal; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(Mutex); -}; - -// MutexLock(mu) acquires mu when constructed and releases it when destroyed. -class LIBPROTOBUF_EXPORT MutexLock { - public: - explicit MutexLock(Mutex *mu) : mu_(mu) { this->mu_->Lock(); } - ~MutexLock() { this->mu_->Unlock(); } - private: - Mutex *const mu_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLock); -}; - -// TODO(kenton): Implement these? Hard to implement portably. -typedef MutexLock ReaderMutexLock; -typedef MutexLock WriterMutexLock; - -// MutexLockMaybe is like MutexLock, but is a no-op when mu is NULL. -class LIBPROTOBUF_EXPORT MutexLockMaybe { - public: - explicit MutexLockMaybe(Mutex *mu) : - mu_(mu) { if (this->mu_ != NULL) { this->mu_->Lock(); } } - ~MutexLockMaybe() { if (this->mu_ != NULL) { this->mu_->Unlock(); } } - private: - Mutex *const mu_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MutexLockMaybe); -}; - -} // namespace internal - -// We made these internal so that they would show up as such in the docs, -// but we don't want to stick "internal::" in front of them everywhere. -using internal::Mutex; -using internal::MutexLock; -using internal::ReaderMutexLock; -using internal::WriterMutexLock; -using internal::MutexLockMaybe; - -// =================================================================== -// from google3/base/type_traits.h - -namespace internal { - -// Specified by TR1 [4.7.4] Pointer modifications. -template struct remove_pointer { typedef T type; }; -template struct remove_pointer { typedef T type; }; -template struct remove_pointer { typedef T type; }; -template struct remove_pointer { typedef T type; }; -template struct remove_pointer { - typedef T type; }; - -// =================================================================== - -// Checks if the buffer contains structurally-valid UTF-8. Implemented in -// structurally_valid.cc. -LIBPROTOBUF_EXPORT bool IsStructurallyValidUTF8(const char* buf, int len); - -} // namespace internal - -// =================================================================== -// Shutdown support. - -// Shut down the entire protocol buffers library, deleting all static-duration -// objects allocated by the library or by generated .pb.cc files. -// -// There are two reasons you might want to call this: -// * You use a draconian definition of "memory leak" in which you expect -// every single malloc() to have a corresponding free(), even for objects -// which live until program exit. -// * You are writing a dynamically-loaded library which needs to clean up -// after itself when the library is unloaded. -// -// It is safe to call this multiple times. However, it is not safe to use -// any other part of the protocol buffers library after -// ShutdownProtobufLibrary() has been called. -LIBPROTOBUF_EXPORT void ShutdownProtobufLibrary(); - -namespace internal { - -// Register a function to be called when ShutdownProtocolBuffers() is called. -LIBPROTOBUF_EXPORT void OnShutdown(void (*func)()); - -} // namespace internal - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMMON_H__ diff --git a/Resources/NetHook/google/protobuf/stubs/common_unittest.cc b/Resources/NetHook/google/protobuf/stubs/common_unittest.cc deleted file mode 100644 index 32c1d08e..00000000 --- a/Resources/NetHook/google/protobuf/stubs/common_unittest.cc +++ /dev/null @@ -1,345 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#include -#include -#include -#include - -#include -#include - -#include "config.h" - -namespace google { -namespace protobuf { -namespace { - -// TODO(kenton): More tests. - -#ifdef PACKAGE_VERSION // only defined when using automake, not MSVC - -TEST(VersionTest, VersionMatchesConfig) { - // Verify that the version string specified in config.h matches the one - // in common.h. The config.h version is a string which may have a suffix - // like "beta" or "rc1", so we remove that. - string version = PACKAGE_VERSION; - int pos = 0; - while (pos < version.size() && - (ascii_isdigit(version[pos]) || version[pos] == '.')) { - ++pos; - } - version.erase(pos); - - EXPECT_EQ(version, internal::VersionString(GOOGLE_PROTOBUF_VERSION)); -} - -#endif // PACKAGE_VERSION - -TEST(CommonTest, IntMinMaxConstants) { - // kint32min was declared incorrectly in the first release of protobufs. - // Ugh. - EXPECT_LT(kint32min, kint32max); - EXPECT_EQ(static_cast(kint32min), static_cast(kint32max) + 1); - EXPECT_LT(kint64min, kint64max); - EXPECT_EQ(static_cast(kint64min), static_cast(kint64max) + 1); - EXPECT_EQ(0, kuint32max + 1); - EXPECT_EQ(0, kuint64max + 1); -} - -vector captured_messages_; - -void CaptureLog(LogLevel level, const char* filename, int line, - const string& message) { - captured_messages_.push_back( - strings::Substitute("$0 $1:$2: $3", - implicit_cast(level), filename, line, message)); -} - -TEST(LoggingTest, DefaultLogging) { - CaptureTestStderr(); - int line = __LINE__; - GOOGLE_LOG(INFO ) << "A message."; - GOOGLE_LOG(WARNING) << "A warning."; - GOOGLE_LOG(ERROR ) << "An error."; - - string text = GetCapturedTestStderr(); - EXPECT_EQ( - "libprotobuf INFO "__FILE__":" + SimpleItoa(line + 1) + "] A message.\n" - "libprotobuf WARNING "__FILE__":" + SimpleItoa(line + 2) + "] A warning.\n" - "libprotobuf ERROR "__FILE__":" + SimpleItoa(line + 3) + "] An error.\n", - text); -} - -TEST(LoggingTest, NullLogging) { - LogHandler* old_handler = SetLogHandler(NULL); - - CaptureTestStderr(); - GOOGLE_LOG(INFO ) << "A message."; - GOOGLE_LOG(WARNING) << "A warning."; - GOOGLE_LOG(ERROR ) << "An error."; - - EXPECT_TRUE(SetLogHandler(old_handler) == NULL); - - string text = GetCapturedTestStderr(); - EXPECT_EQ("", text); -} - -TEST(LoggingTest, CaptureLogging) { - captured_messages_.clear(); - - LogHandler* old_handler = SetLogHandler(&CaptureLog); - - int start_line = __LINE__; - GOOGLE_LOG(ERROR) << "An error."; - GOOGLE_LOG(WARNING) << "A warning."; - - EXPECT_TRUE(SetLogHandler(old_handler) == &CaptureLog); - - ASSERT_EQ(2, captured_messages_.size()); - EXPECT_EQ( - "2 "__FILE__":" + SimpleItoa(start_line + 1) + ": An error.", - captured_messages_[0]); - EXPECT_EQ( - "1 "__FILE__":" + SimpleItoa(start_line + 2) + ": A warning.", - captured_messages_[1]); -} - -TEST(LoggingTest, SilenceLogging) { - captured_messages_.clear(); - - LogHandler* old_handler = SetLogHandler(&CaptureLog); - - int line1 = __LINE__; GOOGLE_LOG(INFO) << "Visible1"; - LogSilencer* silencer1 = new LogSilencer; - GOOGLE_LOG(INFO) << "Not visible."; - LogSilencer* silencer2 = new LogSilencer; - GOOGLE_LOG(INFO) << "Not visible."; - delete silencer1; - GOOGLE_LOG(INFO) << "Not visible."; - delete silencer2; - int line2 = __LINE__; GOOGLE_LOG(INFO) << "Visible2"; - - EXPECT_TRUE(SetLogHandler(old_handler) == &CaptureLog); - - ASSERT_EQ(2, captured_messages_.size()); - EXPECT_EQ( - "0 "__FILE__":" + SimpleItoa(line1) + ": Visible1", - captured_messages_[0]); - EXPECT_EQ( - "0 "__FILE__":" + SimpleItoa(line2) + ": Visible2", - captured_messages_[1]); -} - -class ClosureTest : public testing::Test { - public: - void SetA123Method() { a_ = 123; } - static void SetA123Function() { current_instance_->a_ = 123; } - - void SetAMethod(int a) { a_ = a; } - void SetCMethod(string c) { c_ = c; } - - static void SetAFunction(int a) { current_instance_->a_ = a; } - static void SetCFunction(string c) { current_instance_->c_ = c; } - - void SetABMethod(int a, const char* b) { a_ = a; b_ = b; } - static void SetABFunction(int a, const char* b) { - current_instance_->a_ = a; - current_instance_->b_ = b; - } - - virtual void SetUp() { - current_instance_ = this; - a_ = 0; - b_ = NULL; - c_.clear(); - } - - int a_; - const char* b_; - string c_; - - static ClosureTest* current_instance_; -}; - -ClosureTest* ClosureTest::current_instance_ = NULL; - -TEST_F(ClosureTest, TestClosureFunction0) { - Closure* closure = NewCallback(&SetA123Function); - EXPECT_NE(123, a_); - closure->Run(); - EXPECT_EQ(123, a_); -} - -TEST_F(ClosureTest, TestClosureMethod0) { - Closure* closure = NewCallback(current_instance_, - &ClosureTest::SetA123Method); - EXPECT_NE(123, a_); - closure->Run(); - EXPECT_EQ(123, a_); -} - -TEST_F(ClosureTest, TestClosureFunction1) { - Closure* closure = NewCallback(&SetAFunction, 456); - EXPECT_NE(456, a_); - closure->Run(); - EXPECT_EQ(456, a_); -} - -TEST_F(ClosureTest, TestClosureMethod1) { - Closure* closure = NewCallback(current_instance_, - &ClosureTest::SetAMethod, 456); - EXPECT_NE(456, a_); - closure->Run(); - EXPECT_EQ(456, a_); -} - -TEST_F(ClosureTest, TestClosureFunction1String) { - Closure* closure = NewCallback(&SetCFunction, string("test")); - EXPECT_NE("test", c_); - closure->Run(); - EXPECT_EQ("test", c_); -} - -TEST_F(ClosureTest, TestClosureMethod1String) { - Closure* closure = NewCallback(current_instance_, - &ClosureTest::SetCMethod, string("test")); - EXPECT_NE("test", c_); - closure->Run(); - EXPECT_EQ("test", c_); -} - -TEST_F(ClosureTest, TestClosureFunction2) { - const char* cstr = "hello"; - Closure* closure = NewCallback(&SetABFunction, 789, cstr); - EXPECT_NE(789, a_); - EXPECT_NE(cstr, b_); - closure->Run(); - EXPECT_EQ(789, a_); - EXPECT_EQ(cstr, b_); -} - -TEST_F(ClosureTest, TestClosureMethod2) { - const char* cstr = "hello"; - Closure* closure = NewCallback(current_instance_, - &ClosureTest::SetABMethod, 789, cstr); - EXPECT_NE(789, a_); - EXPECT_NE(cstr, b_); - closure->Run(); - EXPECT_EQ(789, a_); - EXPECT_EQ(cstr, b_); -} - -// Repeat all of the above with NewPermanentCallback() - -TEST_F(ClosureTest, TestPermanentClosureFunction0) { - Closure* closure = NewPermanentCallback(&SetA123Function); - EXPECT_NE(123, a_); - closure->Run(); - EXPECT_EQ(123, a_); - a_ = 0; - closure->Run(); - EXPECT_EQ(123, a_); - delete closure; -} - -TEST_F(ClosureTest, TestPermanentClosureMethod0) { - Closure* closure = NewPermanentCallback(current_instance_, - &ClosureTest::SetA123Method); - EXPECT_NE(123, a_); - closure->Run(); - EXPECT_EQ(123, a_); - a_ = 0; - closure->Run(); - EXPECT_EQ(123, a_); - delete closure; -} - -TEST_F(ClosureTest, TestPermanentClosureFunction1) { - Closure* closure = NewPermanentCallback(&SetAFunction, 456); - EXPECT_NE(456, a_); - closure->Run(); - EXPECT_EQ(456, a_); - a_ = 0; - closure->Run(); - EXPECT_EQ(456, a_); - delete closure; -} - -TEST_F(ClosureTest, TestPermanentClosureMethod1) { - Closure* closure = NewPermanentCallback(current_instance_, - &ClosureTest::SetAMethod, 456); - EXPECT_NE(456, a_); - closure->Run(); - EXPECT_EQ(456, a_); - a_ = 0; - closure->Run(); - EXPECT_EQ(456, a_); - delete closure; -} - -TEST_F(ClosureTest, TestPermanentClosureFunction2) { - const char* cstr = "hello"; - Closure* closure = NewPermanentCallback(&SetABFunction, 789, cstr); - EXPECT_NE(789, a_); - EXPECT_NE(cstr, b_); - closure->Run(); - EXPECT_EQ(789, a_); - EXPECT_EQ(cstr, b_); - a_ = 0; - b_ = NULL; - closure->Run(); - EXPECT_EQ(789, a_); - EXPECT_EQ(cstr, b_); - delete closure; -} - -TEST_F(ClosureTest, TestPermanentClosureMethod2) { - const char* cstr = "hello"; - Closure* closure = NewPermanentCallback(current_instance_, - &ClosureTest::SetABMethod, 789, cstr); - EXPECT_NE(789, a_); - EXPECT_NE(cstr, b_); - closure->Run(); - EXPECT_EQ(789, a_); - EXPECT_EQ(cstr, b_); - a_ = 0; - b_ = NULL; - closure->Run(); - EXPECT_EQ(789, a_); - EXPECT_EQ(cstr, b_); - delete closure; -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/hash.cc b/Resources/NetHook/google/protobuf/stubs/hash.cc deleted file mode 100644 index 9eaf4a1e..00000000 --- a/Resources/NetHook/google/protobuf/stubs/hash.cc +++ /dev/null @@ -1,41 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#include - -namespace google { -namespace protobuf { - -// Nothing needed here right now. - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/hash.h b/Resources/NetHook/google/protobuf/stubs/hash.h deleted file mode 100644 index 822d6050..00000000 --- a/Resources/NetHook/google/protobuf/stubs/hash.h +++ /dev/null @@ -1,220 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// -// Deals with the fact that hash_map is not defined everywhere. - -#ifndef GOOGLE_PROTOBUF_STUBS_HASH_H__ -#define GOOGLE_PROTOBUF_STUBS_HASH_H__ - -#include -#include -#include "config.h" - -#if defined(HAVE_HASH_MAP) && defined(HAVE_HASH_SET) -#include HASH_MAP_H -#include HASH_SET_H -#else -#define MISSING_HASH -#include -#include -#endif - -namespace google { -namespace protobuf { - -#ifdef MISSING_HASH - -// This system doesn't have hash_map or hash_set. Emulate them using map and -// set. - -// Make hash be the same as less. Note that everywhere where custom -// hash functions are defined in the protobuf code, they are also defined such -// that they can be used as "less" functions, which is required by MSVC anyway. -template -struct hash { - // Dummy, just to make derivative hash functions compile. - int operator()(const Key& key) { - GOOGLE_LOG(FATAL) << "Should never be called."; - return 0; - } - - inline bool operator()(const Key& a, const Key& b) const { - return a < b; - } -}; - -// Make sure char* is compared by value. -template <> -struct hash { - // Dummy, just to make derivative hash functions compile. - int operator()(const char* key) { - GOOGLE_LOG(FATAL) << "Should never be called."; - return 0; - } - - inline bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; - -template , - typename EqualKey = int > -class hash_map : public std::map { -}; - -template , - typename EqualKey = int > -class hash_set : public std::set { -}; - -#elif defined(_MSC_VER) && !defined(_STLPORT_VERSION) - -template -struct hash : public HASH_NAMESPACE::hash_compare { -}; - -// MSVC's hash_compare hashes based on the string contents but -// compares based on the string pointer. WTF? -class CstringLess { - public: - inline bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; - -template <> -struct hash - : public HASH_NAMESPACE::hash_compare { -}; - -template , - typename EqualKey = int > -class hash_map : public HASH_NAMESPACE::hash_map< - Key, Data, HashFcn> { -}; - -template , - typename EqualKey = int > -class hash_set : public HASH_NAMESPACE::hash_set< - Key, HashFcn> { -}; - -#else - -template -struct hash : public HASH_NAMESPACE::hash { -}; - -template -struct hash { - inline size_t operator()(const Key* key) const { - return reinterpret_cast(key); - } -}; - -// Unlike the old SGI version, the TR1 "hash" does not special-case char*. So, -// we go ahead and provide our own implementation. -template <> -struct hash { - inline size_t operator()(const char* str) const { - size_t result = 0; - for (; *str != '\0'; str++) { - result = 5 * result + *str; - } - return result; - } -}; - -template , - typename EqualKey = std::equal_to > -class hash_map : public HASH_NAMESPACE::HASH_MAP_CLASS< - Key, Data, HashFcn, EqualKey> { -}; - -template , - typename EqualKey = std::equal_to > -class hash_set : public HASH_NAMESPACE::HASH_SET_CLASS< - Key, HashFcn, EqualKey> { -}; - -#endif - -template <> -struct hash { - inline size_t operator()(const string& key) const { - return hash()(key.c_str()); - } - - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; - inline size_t operator()(const string& a, const string& b) const { - return a < b; - } -}; - -template -struct hash > { - inline size_t operator()(const pair& key) const { - size_t first_hash = hash()(key.first); - size_t second_hash = hash()(key.second); - - // FIXME(kenton): What is the best way to compute this hash? I have - // no idea! This seems a bit better than an XOR. - return first_hash * ((1 << 16) - 1) + second_hash; - } - - static const size_t bucket_size = 4; - static const size_t min_buckets = 8; - inline size_t operator()(const pair& a, - const pair& b) const { - return a < b; - } -}; - -// Used by GCC/SGI STL only. (Why isn't this provided by the standard -// library? :( ) -struct streq { - inline bool operator()(const char* a, const char* b) const { - return strcmp(a, b) == 0; - } -}; - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_HASH_H__ diff --git a/Resources/NetHook/google/protobuf/stubs/map-util.h b/Resources/NetHook/google/protobuf/stubs/map-util.h deleted file mode 100644 index f5c9d6b6..00000000 --- a/Resources/NetHook/google/protobuf/stubs/map-util.h +++ /dev/null @@ -1,119 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// from google3/util/gtl/map-util.h -// Author: Anton Carver - -#ifndef GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__ -#define GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__ - -#include - -namespace google { -namespace protobuf { - -// Perform a lookup in a map or hash_map. -// If the key is present in the map then the value associated with that -// key is returned, otherwise the value passed as a default is returned. -template -const typename Collection::value_type::second_type& -FindWithDefault(const Collection& collection, - const typename Collection::value_type::first_type& key, - const typename Collection::value_type::second_type& value) { - typename Collection::const_iterator it = collection.find(key); - if (it == collection.end()) { - return value; - } - return it->second; -} - -// Perform a lookup in a map or hash_map. -// If the key is present a const pointer to the associated value is returned, -// otherwise a NULL pointer is returned. -template -const typename Collection::value_type::second_type* -FindOrNull(const Collection& collection, - const typename Collection::value_type::first_type& key) { - typename Collection::const_iterator it = collection.find(key); - if (it == collection.end()) { - return 0; - } - return &it->second; -} - -// Perform a lookup in a map or hash_map whose values are pointers. -// If the key is present a const pointer to the associated value is returned, -// otherwise a NULL pointer is returned. -// This function does not distinguish between a missing key and a key mapped -// to a NULL value. -template -const typename Collection::value_type::second_type -FindPtrOrNull(const Collection& collection, - const typename Collection::value_type::first_type& key) { - typename Collection::const_iterator it = collection.find(key); - if (it == collection.end()) { - return 0; - } - return it->second; -} - -// Change the value associated with a particular key in a map or hash_map. -// If the key is not present in the map the key and value are inserted, -// otherwise the value is updated to be a copy of the value provided. -// True indicates that an insert took place, false indicates an update. -template -bool InsertOrUpdate(Collection * const collection, - const Key& key, const Value& value) { - pair ret = - collection->insert(typename Collection::value_type(key, value)); - if (!ret.second) { - // update - ret.first->second = value; - return false; - } - return true; -} - -// Insert a new key and value into a map or hash_map. -// If the key is not present in the map the key and value are -// inserted, otherwise nothing happens. True indicates that an insert -// took place, false indicates the key was already present. -template -bool InsertIfNotPresent(Collection * const collection, - const Key& key, const Value& value) { - pair ret = - collection->insert(typename Collection::value_type(key, value)); - return ret.second; -} - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_MAP_UTIL_H__ diff --git a/Resources/NetHook/google/protobuf/stubs/once.cc b/Resources/NetHook/google/protobuf/stubs/once.cc deleted file mode 100644 index 5b7af9ce..00000000 --- a/Resources/NetHook/google/protobuf/stubs/once.cc +++ /dev/null @@ -1,88 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// -// emulates google3/base/once.h -// -// This header is intended to be included only by internal .cc files and -// generated .pb.cc files. Users should not use this directly. - -#ifdef _WIN32 -#include -#endif - -#include - -namespace google { -namespace protobuf { - -#ifdef _WIN32 - -struct ProtobufOnceInternal { - ProtobufOnceInternal() { - InitializeCriticalSection(&critical_section); - } - ~ProtobufOnceInternal() { - DeleteCriticalSection(&critical_section); - } - CRITICAL_SECTION critical_section; -}; - -ProtobufOnceType::~ProtobufOnceType() -{ - delete internal_; - internal_ = NULL; -} - -ProtobufOnceType::ProtobufOnceType() { - // internal_ may be non-NULL if Init() was already called. - if (internal_ == NULL) internal_ = new ProtobufOnceInternal; -} - -void ProtobufOnceType::Init(void (*init_func)()) { - // internal_ may be NULL if we're still in dynamic initialization and the - // constructor has not been called yet. As mentioned in once.h, we assume - // that the program is still single-threaded at this time, and therefore it - // should be safe to initialize internal_ like so. - if (internal_ == NULL) internal_ = new ProtobufOnceInternal; - - EnterCriticalSection(&internal_->critical_section); - if (!initialized_) { - init_func(); - initialized_ = true; - } - LeaveCriticalSection(&internal_->critical_section); -} - -#endif - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/once.h b/Resources/NetHook/google/protobuf/stubs/once.h deleted file mode 100644 index 0dee4076..00000000 --- a/Resources/NetHook/google/protobuf/stubs/once.h +++ /dev/null @@ -1,123 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// -// emulates google3/base/once.h -// -// This header is intended to be included only by internal .cc files and -// generated .pb.cc files. Users should not use this directly. -// -// This is basically a portable version of pthread_once(). -// -// This header declares three things: -// * A type called ProtobufOnceType. -// * A macro GOOGLE_PROTOBUF_DECLARE_ONCE() which declares a variable of type -// ProtobufOnceType. This is the only legal way to declare such a variable. -// The macro may only be used at the global scope (you cannot create local -// or class member variables of this type). -// * A function GogoleOnceInit(ProtobufOnceType* once, void (*init_func)()). -// This function, when invoked multiple times given the same ProtobufOnceType -// object, will invoke init_func on the first call only, and will make sure -// none of the calls return before that first call to init_func has finished. -// -// This implements a way to perform lazy initialization. It's more efficient -// than using mutexes as no lock is needed if initialization has already -// happened. -// -// Example usage: -// void Init(); -// GOOGLE_PROTOBUF_DECLARE_ONCE(once_init); -// -// // Calls Init() exactly once. -// void InitOnce() { -// GoogleOnceInit(&once_init, &Init); -// } -// -// Note that if GoogleOnceInit() is called before main() has begun, it must -// only be called by the thread that will eventually call main() -- that is, -// the thread that performs dynamic initialization. In general this is a safe -// assumption since people don't usually construct threads before main() starts, -// but it is technically not guaranteed. Unfortunately, Win32 provides no way -// whatsoever to statically-initialize its synchronization primitives, so our -// only choice is to assume that dynamic initialization is single-threaded. - -#ifndef GOOGLE_PROTOBUF_STUBS_ONCE_H__ -#define GOOGLE_PROTOBUF_STUBS_ONCE_H__ - -#include - -#ifndef _WIN32 -#include -#endif - -namespace google { -namespace protobuf { - -#ifdef _WIN32 - -struct ProtobufOnceInternal; - -struct LIBPROTOBUF_EXPORT ProtobufOnceType { - ProtobufOnceType(); - ~ProtobufOnceType(); - void Init(void (*init_func)()); - - volatile bool initialized_; - ProtobufOnceInternal* internal_; -}; - -#define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \ - ::google::protobuf::ProtobufOnceType NAME - -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - // Note: Double-checked locking is safe on x86. - if (!once->initialized_) { - once->Init(init_func); - } -} - -#else - -typedef pthread_once_t ProtobufOnceType; - -#define GOOGLE_PROTOBUF_DECLARE_ONCE(NAME) \ - pthread_once_t NAME = PTHREAD_ONCE_INIT - -inline void GoogleOnceInit(ProtobufOnceType* once, void (*init_func)()) { - pthread_once(once, init_func); -} - -#endif - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_ONCE_H__ diff --git a/Resources/NetHook/google/protobuf/stubs/once_unittest.cc b/Resources/NetHook/google/protobuf/stubs/once_unittest.cc deleted file mode 100644 index b8f86a0f..00000000 --- a/Resources/NetHook/google/protobuf/stubs/once_unittest.cc +++ /dev/null @@ -1,253 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#ifdef _WIN32 -#include -#else -#include -#include -#endif - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace { - -class OnceInitTest : public testing::Test { - protected: - void SetUp() { - state_ = INIT_NOT_STARTED; - current_test_ = this; - } - - // Since ProtobufOnceType is only allowed to be allocated in static storage, - // each test must use a different pair of ProtobufOnceType objects which it - // must declare itself. - void SetOnces(ProtobufOnceType* once, ProtobufOnceType* recursive_once) { - once_ = once; - recursive_once_ = recursive_once; - } - - void InitOnce() { - GoogleOnceInit(once_, &InitStatic); - } - void InitRecursiveOnce() { - GoogleOnceInit(recursive_once_, &InitRecursiveStatic); - } - - void BlockInit() { init_blocker_.Lock(); } - void UnblockInit() { init_blocker_.Unlock(); } - - class TestThread { - public: - TestThread(Closure* callback) - : done_(false), joined_(false), callback_(callback) { -#ifdef _WIN32 - thread_ = CreateThread(NULL, 0, &Start, this, 0, NULL); -#else - pthread_create(&thread_, NULL, &Start, this); -#endif - } - ~TestThread() { - if (!joined_) Join(); - } - - bool IsDone() { - MutexLock lock(&done_mutex_); - return done_; - } - void Join() { - joined_ = true; -#ifdef _WIN32 - WaitForSingleObject(thread_, INFINITE); - CloseHandle(thread_); -#else - pthread_join(thread_, NULL); -#endif - } - - private: -#ifdef _WIN32 - HANDLE thread_; -#else - pthread_t thread_; -#endif - - Mutex done_mutex_; - bool done_; - bool joined_; - Closure* callback_; - -#ifdef _WIN32 - static DWORD WINAPI Start(LPVOID arg) { -#else - static void* Start(void* arg) { -#endif - reinterpret_cast(arg)->Run(); - return 0; - } - - void Run() { - callback_->Run(); - MutexLock lock(&done_mutex_); - done_ = true; - } - }; - - TestThread* RunInitOnceInNewThread() { - return new TestThread(NewCallback(this, &OnceInitTest::InitOnce)); - } - TestThread* RunInitRecursiveOnceInNewThread() { - return new TestThread(NewCallback(this, &OnceInitTest::InitRecursiveOnce)); - } - - enum State { - INIT_NOT_STARTED, - INIT_STARTED, - INIT_DONE - }; - State CurrentState() { - MutexLock lock(&mutex_); - return state_; - } - - void WaitABit() { -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } - - private: - Mutex mutex_; - Mutex init_blocker_; - State state_; - ProtobufOnceType* once_; - ProtobufOnceType* recursive_once_; - - void Init() { - MutexLock lock(&mutex_); - EXPECT_EQ(INIT_NOT_STARTED, state_); - state_ = INIT_STARTED; - mutex_.Unlock(); - init_blocker_.Lock(); - init_blocker_.Unlock(); - mutex_.Lock(); - state_ = INIT_DONE; - } - - static OnceInitTest* current_test_; - static void InitStatic() { current_test_->Init(); } - static void InitRecursiveStatic() { current_test_->InitOnce(); } -}; - -OnceInitTest* OnceInitTest::current_test_ = NULL; - -GOOGLE_PROTOBUF_DECLARE_ONCE(simple_once); - -TEST_F(OnceInitTest, Simple) { - SetOnces(&simple_once, NULL); - - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - InitOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); - - // Calling again has no effect. - InitOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once1); -GOOGLE_PROTOBUF_DECLARE_ONCE(recursive_once2); - -TEST_F(OnceInitTest, Recursive) { - SetOnces(&recursive_once1, &recursive_once2); - - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - InitRecursiveOnce(); - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_once); - -TEST_F(OnceInitTest, MultipleThreads) { - SetOnces(&multiple_threads_once, NULL); - - scoped_ptr threads[4]; - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - for (int i = 0; i < 4; i++) { - threads[i].reset(RunInitOnceInNewThread()); - } - for (int i = 0; i < 4; i++) { - threads[i]->Join(); - } - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once1); -GOOGLE_PROTOBUF_DECLARE_ONCE(multiple_threads_blocked_once2); - -TEST_F(OnceInitTest, MultipleThreadsBlocked) { - SetOnces(&multiple_threads_blocked_once1, &multiple_threads_blocked_once2); - - scoped_ptr threads[8]; - EXPECT_EQ(INIT_NOT_STARTED, CurrentState()); - - BlockInit(); - for (int i = 0; i < 4; i++) { - threads[i].reset(RunInitOnceInNewThread()); - } - for (int i = 4; i < 8; i++) { - threads[i].reset(RunInitRecursiveOnceInNewThread()); - } - - WaitABit(); - - // We should now have one thread blocked inside Init(), four blocked waiting - // for Init() to complete, and three blocked waiting for InitRecursive() to - // complete. - EXPECT_EQ(INIT_STARTED, CurrentState()); - UnblockInit(); - - for (int i = 0; i < 8; i++) { - threads[i]->Join(); - } - EXPECT_EQ(INIT_DONE, CurrentState()); -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/stl_util-inl.h b/Resources/NetHook/google/protobuf/stubs/stl_util-inl.h deleted file mode 100644 index a2e671bb..00000000 --- a/Resources/NetHook/google/protobuf/stubs/stl_util-inl.h +++ /dev/null @@ -1,121 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// from google3/util/gtl/stl_util-inl.h - -#ifndef GOOGLE_PROTOBUF_STUBS_STL_UTIL_INL_H__ -#define GOOGLE_PROTOBUF_STUBS_STL_UTIL_INL_H__ - -#include - -namespace google { -namespace protobuf { - -// STLDeleteContainerPointers() -// For a range within a container of pointers, calls delete -// (non-array version) on these pointers. -// NOTE: for these three functions, we could just implement a DeleteObject -// functor and then call for_each() on the range and functor, but this -// requires us to pull in all of algorithm.h, which seems expensive. -// For hash_[multi]set, it is important that this deletes behind the iterator -// because the hash_set may call the hash function on the iterator when it is -// advanced, which could result in the hash function trying to deference a -// stale pointer. -template -void STLDeleteContainerPointers(ForwardIterator begin, - ForwardIterator end) { - while (begin != end) { - ForwardIterator temp = begin; - ++begin; - delete *temp; - } -} - -// Inside Google, this function implements a horrible, disgusting hack in which -// we reach into the string's private implementation and resize it without -// initializing the new bytes. In some cases doing this can significantly -// improve performance. However, since it's totally non-portable it has no -// place in open source code. Feel free to fill this function in with your -// own disgusting hack if you want the perf boost. -inline void STLStringResizeUninitialized(string* s, size_t new_size) { - s->resize(new_size); -} - -// Return a mutable char* pointing to a string's internal buffer, -// which may not be null-terminated. Writing through this pointer will -// modify the string. -// -// string_as_array(&str)[i] is valid for 0 <= i < str.size() until the -// next call to a string method that invalidates iterators. -// -// As of 2006-04, there is no standard-blessed way of getting a -// mutable reference to a string's internal buffer. However, issue 530 -// (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530) -// proposes this as the method. According to Matt Austern, this should -// already work on all current implementations. -inline char* string_as_array(string* str) { - // DO NOT USE const_cast(str->data())! See the unittest for why. - return str->empty() ? NULL : &*str->begin(); -} - -// STLDeleteElements() deletes all the elements in an STL container and clears -// the container. This function is suitable for use with a vector, set, -// hash_set, or any other STL container which defines sensible begin(), end(), -// and clear() methods. -// -// If container is NULL, this function is a no-op. -// -// As an alternative to calling STLDeleteElements() directly, consider -// ElementDeleter (defined below), which ensures that your container's elements -// are deleted when the ElementDeleter goes out of scope. -template -void STLDeleteElements(T *container) { - if (!container) return; - STLDeleteContainerPointers(container->begin(), container->end()); - container->clear(); -} - -// Given an STL container consisting of (key, value) pairs, STLDeleteValues -// deletes all the "value" components and clears the container. Does nothing -// in the case it's given a NULL pointer. - -template -void STLDeleteValues(T *v) { - if (!v) return; - for (typename T::iterator i = v->begin(); i != v->end(); ++i) { - delete i->second; - } - v->clear(); -} - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_STL_UTIL_INL_H__ diff --git a/Resources/NetHook/google/protobuf/stubs/structurally_valid.cc b/Resources/NetHook/google/protobuf/stubs/structurally_valid.cc deleted file mode 100644 index 0f6afe6d..00000000 --- a/Resources/NetHook/google/protobuf/stubs/structurally_valid.cc +++ /dev/null @@ -1,536 +0,0 @@ -// Copyright 2005-2008 Google Inc. All Rights Reserved. -// Author: jrm@google.com (Jim Meehan) - -#include - -namespace google { -namespace protobuf { -namespace internal { - -// These four-byte entries compactly encode how many bytes 0..255 to delete -// in making a string replacement, how many bytes to add 0..255, and the offset -// 0..64k-1 of the replacement string in remap_string. -struct RemapEntry { - uint8 delete_bytes; - uint8 add_bytes; - uint16 bytes_offset; -}; - -// Exit type codes for state tables. All but the first get stuffed into -// signed one-byte entries. The first is only generated by executable code. -// To distinguish from next-state entries, these must be contiguous and -// all <= kExitNone -typedef enum { - kExitDstSpaceFull = 239, - kExitIllegalStructure, // 240 - kExitOK, // 241 - kExitReject, // ... - kExitReplace1, - kExitReplace2, - kExitReplace3, - kExitReplace21, - kExitReplace31, - kExitReplace32, - kExitReplaceOffset1, - kExitReplaceOffset2, - kExitReplace1S0, - kExitSpecial, - kExitDoAgain, - kExitRejectAlt, - kExitNone // 255 -} ExitReason; - - -// This struct represents one entire state table. The three initialized byte -// areas are state_table, remap_base, and remap_string. state0 and state0_size -// give the byte offset and length within state_table of the initial state -- -// table lookups are expected to start and end in this state, but for -// truncated UTF-8 strings, may end in a different state. These allow a quick -// test for that condition. entry_shift is 8 for tables subscripted by a full -// byte value and 6 for space-optimized tables subscripted by only six -// significant bits in UTF-8 continuation bytes. -typedef struct { - const uint32 state0; - const uint32 state0_size; - const uint32 total_size; - const int max_expand; - const int entry_shift; - const int bytes_per_entry; - const uint32 losub; - const uint32 hiadd; - const uint8* state_table; - const RemapEntry* remap_base; - const uint8* remap_string; - const uint8* fast_state; -} UTF8StateMachineObj; - -typedef UTF8StateMachineObj UTF8ScanObj; - -#define X__ (kExitIllegalStructure) -#define RJ_ (kExitReject) -#define S1_ (kExitReplace1) -#define S2_ (kExitReplace2) -#define S3_ (kExitReplace3) -#define S21 (kExitReplace21) -#define S31 (kExitReplace31) -#define S32 (kExitReplace32) -#define T1_ (kExitReplaceOffset1) -#define T2_ (kExitReplaceOffset2) -#define S11 (kExitReplace1S0) -#define SP_ (kExitSpecial) -#define D__ (kExitDoAgain) -#define RJA (kExitRejectAlt) - -// Entire table has 9 state blocks of 256 entries each -static const unsigned int utf8acceptnonsurrogates_STATE0 = 0; // state[0] -static const unsigned int utf8acceptnonsurrogates_STATE0_SIZE = 256; // =[1] -static const unsigned int utf8acceptnonsurrogates_TOTAL_SIZE = 2304; -static const unsigned int utf8acceptnonsurrogates_MAX_EXPAND_X4 = 0; -static const unsigned int utf8acceptnonsurrogates_SHIFT = 8; -static const unsigned int utf8acceptnonsurrogates_BYTES = 1; -static const unsigned int utf8acceptnonsurrogates_LOSUB = 0x20202020; -static const unsigned int utf8acceptnonsurrogates_HIADD = 0x00000000; - -static const uint8 utf8acceptnonsurrogates[] = { -// state[0] 0x000000 Byte 1 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 3, - 4, 5, 5, 5, 6, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[1] 0x000080 Byte 2 of 2 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[2] 0x000000 Byte 2 of 3 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[3] 0x001000 Byte 2 of 3 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[4] 0x000000 Byte 2 of 4 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[5] 0x040000 Byte 2 of 4 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[6] 0x100000 Byte 2 of 4 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[7] 0x00d000 Byte 2 of 3 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -// state[8] 0x00d800 Byte 3 of 3 -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, - -RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, -RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, -RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, -RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, RJ_, - -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, X__, -}; - -// Remap base[0] = (del, add, string_offset) -static const RemapEntry utf8acceptnonsurrogates_remap_base[] = { -{0, 0, 0} }; - -// Remap string[0] -static const unsigned char utf8acceptnonsurrogates_remap_string[] = { -0 }; - -static const unsigned char utf8acceptnonsurrogates_fast[256] = { -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -}; - -static const UTF8ScanObj utf8acceptnonsurrogates_obj = { - utf8acceptnonsurrogates_STATE0, - utf8acceptnonsurrogates_STATE0_SIZE, - utf8acceptnonsurrogates_TOTAL_SIZE, - utf8acceptnonsurrogates_MAX_EXPAND_X4, - utf8acceptnonsurrogates_SHIFT, - utf8acceptnonsurrogates_BYTES, - utf8acceptnonsurrogates_LOSUB, - utf8acceptnonsurrogates_HIADD, - utf8acceptnonsurrogates, - utf8acceptnonsurrogates_remap_base, - utf8acceptnonsurrogates_remap_string, - utf8acceptnonsurrogates_fast -}; - - -#undef X__ -#undef RJ_ -#undef S1_ -#undef S2_ -#undef S3_ -#undef S21 -#undef S31 -#undef S32 -#undef T1_ -#undef T2_ -#undef S11 -#undef SP_ -#undef D__ -#undef RJA - -// Return true if current Tbl pointer is within state0 range -// Note that unsigned compare checks both ends of range simultaneously -static inline bool InStateZero(const UTF8ScanObj* st, const uint8* Tbl) { - const uint8* Tbl0 = &st->state_table[st->state0]; - return (static_cast(Tbl - Tbl0) < st->state0_size); -} - -// Scan a UTF-8 string based on state table. -// Always scan complete UTF-8 characters -// Set number of bytes scanned. Return reason for exiting -int UTF8GenericScan(const UTF8ScanObj* st, - const char * str, - int str_length, - int* bytes_consumed) { - *bytes_consumed = 0; - if (str_length == 0) return kExitOK; - - int eshift = st->entry_shift; - const uint8* isrc = reinterpret_cast(str); - const uint8* src = isrc; - const uint8* srclimit = isrc + str_length; - const uint8* srclimit8 = srclimit - 7; - const uint8* Tbl_0 = &st->state_table[st->state0]; - - DoAgain: - // Do state-table scan - int e = 0; - uint8 c; - const uint8* Tbl2 = &st->fast_state[0]; - const uint32 losub = st->losub; - const uint32 hiadd = st->hiadd; - // Check initial few bytes one at a time until 8-byte aligned - //---------------------------- - while ((((uintptr_t)src & 0x07) != 0) && - (src < srclimit) && - Tbl2[src[0]] == 0) { - src++; - } - if (((uintptr_t)src & 0x07) == 0) { - // Do fast for groups of 8 identity bytes. - // This covers a lot of 7-bit ASCII ~8x faster then the 1-byte loop, - // including slowing slightly on cr/lf/ht - //---------------------------- - while (src < srclimit8) { - uint32 s0123 = (reinterpret_cast(src))[0]; - uint32 s4567 = (reinterpret_cast(src))[1]; - src += 8; - // This is a fast range check for all bytes in [lowsub..0x80-hiadd) - uint32 temp = (s0123 - losub) | (s0123 + hiadd) | - (s4567 - losub) | (s4567 + hiadd); - if ((temp & 0x80808080) != 0) { - // We typically end up here on cr/lf/ht; src was incremented - int e0123 = (Tbl2[src[-8]] | Tbl2[src[-7]]) | - (Tbl2[src[-6]] | Tbl2[src[-5]]); - if (e0123 != 0) { - src -= 8; - break; - } // Exit on Non-interchange - e0123 = (Tbl2[src[-4]] | Tbl2[src[-3]]) | - (Tbl2[src[-2]] | Tbl2[src[-1]]); - if (e0123 != 0) { - src -= 4; - break; - } // Exit on Non-interchange - // Else OK, go around again - } - } - } - //---------------------------- - - // Byte-at-a-time scan - //---------------------------- - const uint8* Tbl = Tbl_0; - while (src < srclimit) { - c = *src; - e = Tbl[c]; - src++; - if (e >= kExitIllegalStructure) {break;} - Tbl = &Tbl_0[e << eshift]; - } - //---------------------------- - - - // Exit posibilities: - // Some exit code, !state0, back up over last char - // Some exit code, state0, back up one byte exactly - // source consumed, !state0, back up over partial char - // source consumed, state0, exit OK - // For illegal byte in state0, avoid backup up over PREVIOUS char - // For truncated last char, back up to beginning of it - - if (e >= kExitIllegalStructure) { - // Back up over exactly one byte of rejected/illegal UTF-8 character - src--; - // Back up more if needed - if (!InStateZero(st, Tbl)) { - do { - src--; - } while ((src > isrc) && ((src[0] & 0xc0) == 0x80)); - } - } else if (!InStateZero(st, Tbl)) { - // Back up over truncated UTF-8 character - e = kExitIllegalStructure; - do { - src--; - } while ((src > isrc) && ((src[0] & 0xc0) == 0x80)); - } else { - // Normal termination, source fully consumed - e = kExitOK; - } - - if (e == kExitDoAgain) { - // Loop back up to the fast scan - goto DoAgain; - } - - *bytes_consumed = src - isrc; - return e; -} - -int UTF8GenericScanFastAscii(const UTF8ScanObj* st, - const char * str, - int str_length, - int* bytes_consumed) { - *bytes_consumed = 0; - if (str_length == 0) return kExitOK; - - const uint8* isrc = reinterpret_cast(str); - const uint8* src = isrc; - const uint8* srclimit = isrc + str_length; - const uint8* srclimit8 = srclimit - 7; - int n; - int rest_consumed; - int exit_reason; - do { - // Check initial few bytes one at a time until 8-byte aligned - while ((((uintptr_t)src & 0x07) != 0) && - (src < srclimit) && (src[0] < 0x80)) { - src++; - } - if (((uintptr_t)src & 0x07) == 0) { - while ((src < srclimit8) && - (((reinterpret_cast(src)[0] | - reinterpret_cast(src)[1]) & 0x80808080) == 0)) { - src += 8; - } - } - while ((src < srclimit) && (src[0] < 0x80)) { - src++; - } - // Run state table on the rest - n = src - isrc; - exit_reason = UTF8GenericScan(st, str + n, str_length - n, &rest_consumed); - src += rest_consumed; - } while ( exit_reason == kExitDoAgain ); - - *bytes_consumed = src - isrc; - return exit_reason; -} - -// Hack: On some compilers the static tables are initialized at startup. -// We can't use them until they are initialized. However, some Protocol -// Buffer parsing happens at static init time and may try to validate -// UTF-8 strings. Since UTF-8 validation is only used for debugging -// anyway, we simply always return success if initialization hasn't -// occurred yet. -namespace { - -bool module_initialized_ = false; - -struct InitDetector { - InitDetector() { - module_initialized_ = true; - } -}; -InitDetector init_detector; - -} // namespace - -bool IsStructurallyValidUTF8(const char* buf, int len) { - if (!module_initialized_) return true; - - int bytes_consumed = 0; - UTF8GenericScanFastAscii(&utf8acceptnonsurrogates_obj, - buf, len, &bytes_consumed); - return (bytes_consumed == len); -} - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/structurally_valid_unittest.cc b/Resources/NetHook/google/protobuf/stubs/structurally_valid_unittest.cc deleted file mode 100644 index 90888885..00000000 --- a/Resources/NetHook/google/protobuf/stubs/structurally_valid_unittest.cc +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright 2008 Google Inc. All Rights Reserved. -// Author: xpeng@google.com (Peter Peng) - -#include -#include - -namespace google { -namespace protobuf { -namespace internal { -namespace { - -TEST(StructurallyValidTest, ValidUTF8String) { - // On GCC, this string can be written as: - // "abcd 1234 - \u2014\u2013\u2212" - // MSVC seems to interpret \u differently. - string valid_str("abcd 1234 - \342\200\224\342\200\223\342\210\222 - xyz789"); - EXPECT_TRUE(IsStructurallyValidUTF8(valid_str.data(), - valid_str.size())); - // Additional check for pointer alignment - for (int i = 1; i < 8; ++i) { - EXPECT_TRUE(IsStructurallyValidUTF8(valid_str.data() + i, - valid_str.size() - i)); - } -} - -TEST(StructurallyValidTest, InvalidUTF8String) { - const string invalid_str("abcd\xA0\xB0\xA0\xB0\xA0\xB0 - xyz789"); - EXPECT_FALSE(IsStructurallyValidUTF8(invalid_str.data(), - invalid_str.size())); - // Additional check for pointer alignment - for (int i = 1; i < 8; ++i) { - EXPECT_FALSE(IsStructurallyValidUTF8(invalid_str.data() + i, - invalid_str.size() - i)); - } -} - -} // namespace -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/strutil.cc b/Resources/NetHook/google/protobuf/stubs/strutil.cc deleted file mode 100644 index bb658ba8..00000000 --- a/Resources/NetHook/google/protobuf/stubs/strutil.cc +++ /dev/null @@ -1,1166 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// from google3/strings/strutil.cc - -#include -#include -#include // FLT_DIG and DBL_DIG -#include -#include -#include -#include - -#ifdef _WIN32 -// MSVC has only _snprintf, not snprintf. -// -// MinGW has both snprintf and _snprintf, but they appear to be different -// functions. The former is buggy. When invoked like so: -// char buffer[32]; -// snprintf(buffer, 32, "%.*g\n", FLT_DIG, 1.23e10f); -// it prints "1.23000e+10". This is plainly wrong: %g should never print -// trailing zeros after the decimal point. For some reason this bug only -// occurs with some input values, not all. In any case, _snprintf does the -// right thing, so we use it. -#define snprintf _snprintf -#endif - -namespace google { -namespace protobuf { - -inline bool IsNaN(double value) { - // NaN is never equal to anything, even itself. - return value != value; -} - -// These are defined as macros on some platforms. #undef them so that we can -// redefine them. -#undef isxdigit -#undef isprint - -// The definitions of these in ctype.h change based on locale. Since our -// string manipulation is all in relation to the protocol buffer and C++ -// languages, we always want to use the C locale. So, we re-define these -// exactly as we want them. -inline bool isxdigit(char c) { - return ('0' <= c && c <= '9') || - ('a' <= c && c <= 'f') || - ('A' <= c && c <= 'F'); -} - -inline bool isprint(char c) { - return c >= 0x20 && c <= 0x7E; -} - -// ---------------------------------------------------------------------- -// StripString -// Replaces any occurrence of the character 'remove' (or the characters -// in 'remove') with the character 'replacewith'. -// ---------------------------------------------------------------------- -void StripString(string* s, const char* remove, char replacewith) { - const char * str_start = s->c_str(); - const char * str = str_start; - for (str = strpbrk(str, remove); - str != NULL; - str = strpbrk(str + 1, remove)) { - (*s)[str - str_start] = replacewith; - } -} - -// ---------------------------------------------------------------------- -// StringReplace() -// Replace the "old" pattern with the "new" pattern in a string, -// and append the result to "res". If replace_all is false, -// it only replaces the first instance of "old." -// ---------------------------------------------------------------------- - -void StringReplace(const string& s, const string& oldsub, - const string& newsub, bool replace_all, - string* res) { - if (oldsub.empty()) { - res->append(s); // if empty, append the given string. - return; - } - - string::size_type start_pos = 0; - string::size_type pos; - do { - pos = s.find(oldsub, start_pos); - if (pos == string::npos) { - break; - } - res->append(s, start_pos, pos - start_pos); - res->append(newsub); - start_pos = pos + oldsub.size(); // start searching again after the "old" - } while (replace_all); - res->append(s, start_pos, s.length() - start_pos); -} - -// ---------------------------------------------------------------------- -// StringReplace() -// Give me a string and two patterns "old" and "new", and I replace -// the first instance of "old" in the string with "new", if it -// exists. If "global" is true; call this repeatedly until it -// fails. RETURN a new string, regardless of whether the replacement -// happened or not. -// ---------------------------------------------------------------------- - -string StringReplace(const string& s, const string& oldsub, - const string& newsub, bool replace_all) { - string ret; - StringReplace(s, oldsub, newsub, replace_all, &ret); - return ret; -} - -// ---------------------------------------------------------------------- -// SplitStringUsing() -// Split a string using a character delimiter. Append the components -// to 'result'. -// -// Note: For multi-character delimiters, this routine will split on *ANY* of -// the characters in the string, not the entire string as a single delimiter. -// ---------------------------------------------------------------------- -template -static inline -void SplitStringToIteratorUsing(const string& full, - const char* delim, - ITR& result) { - // Optimize the common case where delim is a single character. - if (delim[0] != '\0' && delim[1] == '\0') { - char c = delim[0]; - const char* p = full.data(); - const char* end = p + full.size(); - while (p != end) { - if (*p == c) { - ++p; - } else { - const char* start = p; - while (++p != end && *p != c); - *result++ = string(start, p - start); - } - } - return; - } - - string::size_type begin_index, end_index; - begin_index = full.find_first_not_of(delim); - while (begin_index != string::npos) { - end_index = full.find_first_of(delim, begin_index); - if (end_index == string::npos) { - *result++ = full.substr(begin_index); - return; - } - *result++ = full.substr(begin_index, (end_index - begin_index)); - begin_index = full.find_first_not_of(delim, end_index); - } -} - -void SplitStringUsing(const string& full, - const char* delim, - vector* result) { - back_insert_iterator< vector > it(*result); - SplitStringToIteratorUsing(full, delim, it); -} - -// ---------------------------------------------------------------------- -// JoinStrings() -// This merges a vector of string components with delim inserted -// as separaters between components. -// -// ---------------------------------------------------------------------- -template -static void JoinStringsIterator(const ITERATOR& start, - const ITERATOR& end, - const char* delim, - string* result) { - GOOGLE_CHECK(result != NULL); - result->clear(); - int delim_length = strlen(delim); - - // Precompute resulting length so we can reserve() memory in one shot. - int length = 0; - for (ITERATOR iter = start; iter != end; ++iter) { - if (iter != start) { - length += delim_length; - } - length += iter->size(); - } - result->reserve(length); - - // Now combine everything. - for (ITERATOR iter = start; iter != end; ++iter) { - if (iter != start) { - result->append(delim, delim_length); - } - result->append(iter->data(), iter->size()); - } -} - -void JoinStrings(const vector& components, - const char* delim, - string * result) { - JoinStringsIterator(components.begin(), components.end(), delim, result); -} - -// ---------------------------------------------------------------------- -// UnescapeCEscapeSequences() -// This does all the unescaping that C does: \ooo, \r, \n, etc -// Returns length of resulting string. -// The implementation of \x parses any positive number of hex digits, -// but it is an error if the value requires more than 8 bits, and the -// result is truncated to 8 bits. -// -// The second call stores its errors in a supplied string vector. -// If the string vector pointer is NULL, it reports the errors with LOG(). -// ---------------------------------------------------------------------- - -#define IS_OCTAL_DIGIT(c) (((c) >= '0') && ((c) <= '7')) - -inline int hex_digit_to_int(char c) { - /* Assume ASCII. */ - assert('0' == 0x30 && 'A' == 0x41 && 'a' == 0x61); - assert(isxdigit(c)); - int x = static_cast(c); - if (x > '9') { - x += 9; - } - return x & 0xf; -} - -// Protocol buffers doesn't ever care about errors, but I don't want to remove -// the code. -#define LOG_STRING(LEVEL, VECTOR) GOOGLE_LOG_IF(LEVEL, false) - -int UnescapeCEscapeSequences(const char* source, char* dest) { - return UnescapeCEscapeSequences(source, dest, NULL); -} - -int UnescapeCEscapeSequences(const char* source, char* dest, - vector *errors) { - GOOGLE_DCHECK(errors == NULL) << "Error reporting not implemented."; - - char* d = dest; - const char* p = source; - - // Small optimization for case where source = dest and there's no escaping - while ( p == d && *p != '\0' && *p != '\\' ) - p++, d++; - - while (*p != '\0') { - if (*p != '\\') { - *d++ = *p++; - } else { - switch ( *++p ) { // skip past the '\\' - case '\0': - LOG_STRING(ERROR, errors) << "String cannot end with \\"; - *d = '\0'; - return d - dest; // we're done with p - case 'a': *d++ = '\a'; break; - case 'b': *d++ = '\b'; break; - case 'f': *d++ = '\f'; break; - case 'n': *d++ = '\n'; break; - case 'r': *d++ = '\r'; break; - case 't': *d++ = '\t'; break; - case 'v': *d++ = '\v'; break; - case '\\': *d++ = '\\'; break; - case '?': *d++ = '\?'; break; // \? Who knew? - case '\'': *d++ = '\''; break; - case '"': *d++ = '\"'; break; - case '0': case '1': case '2': case '3': // octal digit: 1 to 3 digits - case '4': case '5': case '6': case '7': { - char ch = *p - '0'; - if ( IS_OCTAL_DIGIT(p[1]) ) - ch = ch * 8 + *++p - '0'; - if ( IS_OCTAL_DIGIT(p[1]) ) // safe (and easy) to do this twice - ch = ch * 8 + *++p - '0'; // now points at last digit - *d++ = ch; - break; - } - case 'x': case 'X': { - if (!isxdigit(p[1])) { - if (p[1] == '\0') { - LOG_STRING(ERROR, errors) << "String cannot end with \\x"; - } else { - LOG_STRING(ERROR, errors) << - "\\x cannot be followed by non-hex digit: \\" << *p << p[1]; - } - break; - } - unsigned int ch = 0; - const char *hex_start = p; - while (isxdigit(p[1])) // arbitrarily many hex digits - ch = (ch << 4) + hex_digit_to_int(*++p); - if (ch > 0xFF) - LOG_STRING(ERROR, errors) << "Value of " << - "\\" << string(hex_start, p+1-hex_start) << " exceeds 8 bits"; - *d++ = ch; - break; - } -#if 0 // TODO(kenton): Support \u and \U? Requires runetochar(). - case 'u': { - // \uhhhh => convert 4 hex digits to UTF-8 - char32 rune = 0; - const char *hex_start = p; - for (int i = 0; i < 4; ++i) { - if (isxdigit(p[1])) { // Look one char ahead. - rune = (rune << 4) + hex_digit_to_int(*++p); // Advance p. - } else { - LOG_STRING(ERROR, errors) - << "\\u must be followed by 4 hex digits: \\" - << string(hex_start, p+1-hex_start); - break; - } - } - d += runetochar(d, &rune); - break; - } - case 'U': { - // \Uhhhhhhhh => convert 8 hex digits to UTF-8 - char32 rune = 0; - const char *hex_start = p; - for (int i = 0; i < 8; ++i) { - if (isxdigit(p[1])) { // Look one char ahead. - // Don't change rune until we're sure this - // is within the Unicode limit, but do advance p. - char32 newrune = (rune << 4) + hex_digit_to_int(*++p); - if (newrune > 0x10FFFF) { - LOG_STRING(ERROR, errors) - << "Value of \\" - << string(hex_start, p + 1 - hex_start) - << " exceeds Unicode limit (0x10FFFF)"; - break; - } else { - rune = newrune; - } - } else { - LOG_STRING(ERROR, errors) - << "\\U must be followed by 8 hex digits: \\" - << string(hex_start, p+1-hex_start); - break; - } - } - d += runetochar(d, &rune); - break; - } -#endif - default: - LOG_STRING(ERROR, errors) << "Unknown escape sequence: \\" << *p; - } - p++; // read past letter we escaped - } - } - *d = '\0'; - return d - dest; -} - -// ---------------------------------------------------------------------- -// UnescapeCEscapeString() -// This does the same thing as UnescapeCEscapeSequences, but creates -// a new string. The caller does not need to worry about allocating -// a dest buffer. This should be used for non performance critical -// tasks such as printing debug messages. It is safe for src and dest -// to be the same. -// -// The second call stores its errors in a supplied string vector. -// If the string vector pointer is NULL, it reports the errors with LOG(). -// -// In the first and second calls, the length of dest is returned. In the -// the third call, the new string is returned. -// ---------------------------------------------------------------------- -int UnescapeCEscapeString(const string& src, string* dest) { - return UnescapeCEscapeString(src, dest, NULL); -} - -int UnescapeCEscapeString(const string& src, string* dest, - vector *errors) { - scoped_array unescaped(new char[src.size() + 1]); - int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), errors); - GOOGLE_CHECK(dest); - dest->assign(unescaped.get(), len); - return len; -} - -string UnescapeCEscapeString(const string& src) { - scoped_array unescaped(new char[src.size() + 1]); - int len = UnescapeCEscapeSequences(src.c_str(), unescaped.get(), NULL); - return string(unescaped.get(), len); -} - -// ---------------------------------------------------------------------- -// CEscapeString() -// CHexEscapeString() -// Copies 'src' to 'dest', escaping dangerous characters using -// C-style escape sequences. This is very useful for preparing query -// flags. 'src' and 'dest' should not overlap. The 'Hex' version uses -// hexadecimal rather than octal sequences. -// Returns the number of bytes written to 'dest' (not including the \0) -// or -1 if there was insufficient space. -// -// Currently only \n, \r, \t, ", ', \ and !isprint() chars are escaped. -// ---------------------------------------------------------------------- -int CEscapeInternal(const char* src, int src_len, char* dest, - int dest_len, bool use_hex, bool utf8_safe) { - const char* src_end = src + src_len; - int used = 0; - bool last_hex_escape = false; // true if last output char was \xNN - - for (; src < src_end; src++) { - if (dest_len - used < 2) // Need space for two letter escape - return -1; - - bool is_hex_escape = false; - switch (*src) { - case '\n': dest[used++] = '\\'; dest[used++] = 'n'; break; - case '\r': dest[used++] = '\\'; dest[used++] = 'r'; break; - case '\t': dest[used++] = '\\'; dest[used++] = 't'; break; - case '\"': dest[used++] = '\\'; dest[used++] = '\"'; break; - case '\'': dest[used++] = '\\'; dest[used++] = '\''; break; - case '\\': dest[used++] = '\\'; dest[used++] = '\\'; break; - default: - // Note that if we emit \xNN and the src character after that is a hex - // digit then that digit must be escaped too to prevent it being - // interpreted as part of the character code by C. - if ((!utf8_safe || static_cast(*src) < 0x80) && - (!isprint(*src) || - (last_hex_escape && isxdigit(*src)))) { - if (dest_len - used < 4) // need space for 4 letter escape - return -1; - sprintf(dest + used, (use_hex ? "\\x%02x" : "\\%03o"), - static_cast(*src)); - is_hex_escape = use_hex; - used += 4; - } else { - dest[used++] = *src; break; - } - } - last_hex_escape = is_hex_escape; - } - - if (dest_len - used < 1) // make sure that there is room for \0 - return -1; - - dest[used] = '\0'; // doesn't count towards return value though - return used; -} - -int CEscapeString(const char* src, int src_len, char* dest, int dest_len) { - return CEscapeInternal(src, src_len, dest, dest_len, false, false); -} - -// ---------------------------------------------------------------------- -// CEscape() -// CHexEscape() -// Copies 'src' to result, escaping dangerous characters using -// C-style escape sequences. This is very useful for preparing query -// flags. 'src' and 'dest' should not overlap. The 'Hex' version -// hexadecimal rather than octal sequences. -// -// Currently only \n, \r, \t, ", ', \ and !isprint() chars are escaped. -// ---------------------------------------------------------------------- -string CEscape(const string& src) { - const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array dest(new char[dest_length]); - const int len = CEscapeInternal(src.data(), src.size(), - dest.get(), dest_length, false, false); - GOOGLE_DCHECK_GE(len, 0); - return string(dest.get(), len); -} - -namespace strings { - -string Utf8SafeCEscape(const string& src) { - const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array dest(new char[dest_length]); - const int len = CEscapeInternal(src.data(), src.size(), - dest.get(), dest_length, false, true); - GOOGLE_DCHECK_GE(len, 0); - return string(dest.get(), len); -} - -string CHexEscape(const string& src) { - const int dest_length = src.size() * 4 + 1; // Maximum possible expansion - scoped_array dest(new char[dest_length]); - const int len = CEscapeInternal(src.data(), src.size(), - dest.get(), dest_length, true, false); - GOOGLE_DCHECK_GE(len, 0); - return string(dest.get(), len); -} - -} // namespace strings - -// ---------------------------------------------------------------------- -// strto32_adaptor() -// strtou32_adaptor() -// Implementation of strto[u]l replacements that have identical -// overflow and underflow characteristics for both ILP-32 and LP-64 -// platforms, including errno preservation in error-free calls. -// ---------------------------------------------------------------------- - -int32 strto32_adaptor(const char *nptr, char **endptr, int base) { - const int saved_errno = errno; - errno = 0; - const long result = strtol(nptr, endptr, base); - if (errno == ERANGE && result == LONG_MIN) { - return kint32min; - } else if (errno == ERANGE && result == LONG_MAX) { - return kint32max; - } else if (errno == 0 && result < kint32min) { - errno = ERANGE; - return kint32min; - } else if (errno == 0 && result > kint32max) { - errno = ERANGE; - return kint32max; - } - if (errno == 0) - errno = saved_errno; - return static_cast(result); -} - -uint32 strtou32_adaptor(const char *nptr, char **endptr, int base) { - const int saved_errno = errno; - errno = 0; - const unsigned long result = strtoul(nptr, endptr, base); - if (errno == ERANGE && result == ULONG_MAX) { - return kuint32max; - } else if (errno == 0 && result > kuint32max) { - errno = ERANGE; - return kuint32max; - } - if (errno == 0) - errno = saved_errno; - return static_cast(result); -} - -// ---------------------------------------------------------------------- -// FastIntToBuffer() -// FastInt64ToBuffer() -// FastHexToBuffer() -// FastHex64ToBuffer() -// FastHex32ToBuffer() -// ---------------------------------------------------------------------- - -// Offset into buffer where FastInt64ToBuffer places the end of string -// null character. Also used by FastInt64ToBufferLeft. -static const int kFastInt64ToBufferOffset = 21; - -char *FastInt64ToBuffer(int64 i, char* buffer) { - // We could collapse the positive and negative sections, but that - // would be slightly slower for positive numbers... - // 22 bytes is enough to store -2**64, -18446744073709551616. - char* p = buffer + kFastInt64ToBufferOffset; - *p-- = '\0'; - if (i >= 0) { - do { - *p-- = '0' + i % 10; - i /= 10; - } while (i > 0); - return p + 1; - } else { - // On different platforms, % and / have different behaviors for - // negative numbers, so we need to jump through hoops to make sure - // we don't divide negative numbers. - if (i > -10) { - i = -i; - *p-- = '0' + i; - *p = '-'; - return p; - } else { - // Make sure we aren't at MIN_INT, in which case we can't say i = -i - i = i + 10; - i = -i; - *p-- = '0' + i % 10; - // Undo what we did a moment ago - i = i / 10 + 1; - do { - *p-- = '0' + i % 10; - i /= 10; - } while (i > 0); - *p = '-'; - return p; - } - } -} - -// Offset into buffer where FastInt32ToBuffer places the end of string -// null character. Also used by FastInt32ToBufferLeft -static const int kFastInt32ToBufferOffset = 11; - -// Yes, this is a duplicate of FastInt64ToBuffer. But, we need this for the -// compiler to generate 32 bit arithmetic instructions. It's much faster, at -// least with 32 bit binaries. -char *FastInt32ToBuffer(int32 i, char* buffer) { - // We could collapse the positive and negative sections, but that - // would be slightly slower for positive numbers... - // 12 bytes is enough to store -2**32, -4294967296. - char* p = buffer + kFastInt32ToBufferOffset; - *p-- = '\0'; - if (i >= 0) { - do { - *p-- = '0' + i % 10; - i /= 10; - } while (i > 0); - return p + 1; - } else { - // On different platforms, % and / have different behaviors for - // negative numbers, so we need to jump through hoops to make sure - // we don't divide negative numbers. - if (i > -10) { - i = -i; - *p-- = '0' + i; - *p = '-'; - return p; - } else { - // Make sure we aren't at MIN_INT, in which case we can't say i = -i - i = i + 10; - i = -i; - *p-- = '0' + i % 10; - // Undo what we did a moment ago - i = i / 10 + 1; - do { - *p-- = '0' + i % 10; - i /= 10; - } while (i > 0); - *p = '-'; - return p; - } - } -} - -char *FastHexToBuffer(int i, char* buffer) { - GOOGLE_CHECK(i >= 0) << "FastHexToBuffer() wants non-negative integers, not " << i; - - static const char *hexdigits = "0123456789abcdef"; - char *p = buffer + 21; - *p-- = '\0'; - do { - *p-- = hexdigits[i & 15]; // mod by 16 - i >>= 4; // divide by 16 - } while (i > 0); - return p + 1; -} - -char *InternalFastHexToBuffer(uint64 value, char* buffer, int num_byte) { - static const char *hexdigits = "0123456789abcdef"; - buffer[num_byte] = '\0'; - for (int i = num_byte - 1; i >= 0; i--) { - buffer[i] = hexdigits[uint32(value) & 0xf]; - value >>= 4; - } - return buffer; -} - -char *FastHex64ToBuffer(uint64 value, char* buffer) { - return InternalFastHexToBuffer(value, buffer, 16); -} - -char *FastHex32ToBuffer(uint32 value, char* buffer) { - return InternalFastHexToBuffer(value, buffer, 8); -} - -static inline char* PlaceNum(char* p, int num, char prev_sep) { - *p-- = '0' + num % 10; - *p-- = '0' + num / 10; - *p-- = prev_sep; - return p; -} - -// ---------------------------------------------------------------------- -// FastInt32ToBufferLeft() -// FastUInt32ToBufferLeft() -// FastInt64ToBufferLeft() -// FastUInt64ToBufferLeft() -// -// Like the Fast*ToBuffer() functions above, these are intended for speed. -// Unlike the Fast*ToBuffer() functions, however, these functions write -// their output to the beginning of the buffer (hence the name, as the -// output is left-aligned). The caller is responsible for ensuring that -// the buffer has enough space to hold the output. -// -// Returns a pointer to the end of the string (i.e. the null character -// terminating the string). -// ---------------------------------------------------------------------- - -static const char two_ASCII_digits[100][2] = { - {'0','0'}, {'0','1'}, {'0','2'}, {'0','3'}, {'0','4'}, - {'0','5'}, {'0','6'}, {'0','7'}, {'0','8'}, {'0','9'}, - {'1','0'}, {'1','1'}, {'1','2'}, {'1','3'}, {'1','4'}, - {'1','5'}, {'1','6'}, {'1','7'}, {'1','8'}, {'1','9'}, - {'2','0'}, {'2','1'}, {'2','2'}, {'2','3'}, {'2','4'}, - {'2','5'}, {'2','6'}, {'2','7'}, {'2','8'}, {'2','9'}, - {'3','0'}, {'3','1'}, {'3','2'}, {'3','3'}, {'3','4'}, - {'3','5'}, {'3','6'}, {'3','7'}, {'3','8'}, {'3','9'}, - {'4','0'}, {'4','1'}, {'4','2'}, {'4','3'}, {'4','4'}, - {'4','5'}, {'4','6'}, {'4','7'}, {'4','8'}, {'4','9'}, - {'5','0'}, {'5','1'}, {'5','2'}, {'5','3'}, {'5','4'}, - {'5','5'}, {'5','6'}, {'5','7'}, {'5','8'}, {'5','9'}, - {'6','0'}, {'6','1'}, {'6','2'}, {'6','3'}, {'6','4'}, - {'6','5'}, {'6','6'}, {'6','7'}, {'6','8'}, {'6','9'}, - {'7','0'}, {'7','1'}, {'7','2'}, {'7','3'}, {'7','4'}, - {'7','5'}, {'7','6'}, {'7','7'}, {'7','8'}, {'7','9'}, - {'8','0'}, {'8','1'}, {'8','2'}, {'8','3'}, {'8','4'}, - {'8','5'}, {'8','6'}, {'8','7'}, {'8','8'}, {'8','9'}, - {'9','0'}, {'9','1'}, {'9','2'}, {'9','3'}, {'9','4'}, - {'9','5'}, {'9','6'}, {'9','7'}, {'9','8'}, {'9','9'} -}; - -char* FastUInt32ToBufferLeft(uint32 u, char* buffer) { - int digits; - const char *ASCII_digits = NULL; - // The idea of this implementation is to trim the number of divides to as few - // as possible by using multiplication and subtraction rather than mod (%), - // and by outputting two digits at a time rather than one. - // The huge-number case is first, in the hopes that the compiler will output - // that case in one branch-free block of code, and only output conditional - // branches into it from below. - if (u >= 1000000000) { // >= 1,000,000,000 - digits = u / 100000000; // 100,000,000 - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; -sublt100_000_000: - u -= digits * 100000000; // 100,000,000 -lt100_000_000: - digits = u / 1000000; // 1,000,000 - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; -sublt1_000_000: - u -= digits * 1000000; // 1,000,000 -lt1_000_000: - digits = u / 10000; // 10,000 - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; -sublt10_000: - u -= digits * 10000; // 10,000 -lt10_000: - digits = u / 100; - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; -sublt100: - u -= digits * 100; -lt100: - digits = u; - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; -done: - *buffer = 0; - return buffer; - } - - if (u < 100) { - digits = u; - if (u >= 10) goto lt100; - *buffer++ = '0' + digits; - goto done; - } - if (u < 10000) { // 10,000 - if (u >= 1000) goto lt10_000; - digits = u / 100; - *buffer++ = '0' + digits; - goto sublt100; - } - if (u < 1000000) { // 1,000,000 - if (u >= 100000) goto lt1_000_000; - digits = u / 10000; // 10,000 - *buffer++ = '0' + digits; - goto sublt10_000; - } - if (u < 100000000) { // 100,000,000 - if (u >= 10000000) goto lt100_000_000; - digits = u / 1000000; // 1,000,000 - *buffer++ = '0' + digits; - goto sublt1_000_000; - } - // we already know that u < 1,000,000,000 - digits = u / 100000000; // 100,000,000 - *buffer++ = '0' + digits; - goto sublt100_000_000; -} - -char* FastInt32ToBufferLeft(int32 i, char* buffer) { - uint32 u = i; - if (i < 0) { - *buffer++ = '-'; - u = -i; - } - return FastUInt32ToBufferLeft(u, buffer); -} - -char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) { - int digits; - const char *ASCII_digits = NULL; - - uint32 u = static_cast(u64); - if (u == u64) return FastUInt32ToBufferLeft(u, buffer); - - uint64 top_11_digits = u64 / 1000000000; - buffer = FastUInt64ToBufferLeft(top_11_digits, buffer); - u = u64 - (top_11_digits * 1000000000); - - digits = u / 10000000; // 10,000,000 - GOOGLE_DCHECK_LT(digits, 100); - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; - u -= digits * 10000000; // 10,000,000 - digits = u / 100000; // 100,000 - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; - u -= digits * 100000; // 100,000 - digits = u / 1000; // 1,000 - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; - u -= digits * 1000; // 1,000 - digits = u / 10; - ASCII_digits = two_ASCII_digits[digits]; - buffer[0] = ASCII_digits[0]; - buffer[1] = ASCII_digits[1]; - buffer += 2; - u -= digits * 10; - digits = u; - *buffer++ = '0' + digits; - *buffer = 0; - return buffer; -} - -char* FastInt64ToBufferLeft(int64 i, char* buffer) { - uint64 u = i; - if (i < 0) { - *buffer++ = '-'; - u = -i; - } - return FastUInt64ToBufferLeft(u, buffer); -} - -// ---------------------------------------------------------------------- -// SimpleItoa() -// Description: converts an integer to a string. -// -// Return value: string -// ---------------------------------------------------------------------- - -string SimpleItoa(int i) { - char buffer[kFastToBufferSize]; - return (sizeof(i) == 4) ? - FastInt32ToBuffer(i, buffer) : - FastInt64ToBuffer(i, buffer); -} - -string SimpleItoa(unsigned int i) { - char buffer[kFastToBufferSize]; - return string(buffer, (sizeof(i) == 4) ? - FastUInt32ToBufferLeft(i, buffer) : - FastUInt64ToBufferLeft(i, buffer)); -} - -string SimpleItoa(long i) { - char buffer[kFastToBufferSize]; - return (sizeof(i) == 4) ? - FastInt32ToBuffer(i, buffer) : - FastInt64ToBuffer(i, buffer); -} - -string SimpleItoa(unsigned long i) { - char buffer[kFastToBufferSize]; - return string(buffer, (sizeof(i) == 4) ? - FastUInt32ToBufferLeft(i, buffer) : - FastUInt64ToBufferLeft(i, buffer)); -} - -string SimpleItoa(long long i) { - char buffer[kFastToBufferSize]; - return (sizeof(i) == 4) ? - FastInt32ToBuffer(i, buffer) : - FastInt64ToBuffer(i, buffer); -} - -string SimpleItoa(unsigned long long i) { - char buffer[kFastToBufferSize]; - return string(buffer, (sizeof(i) == 4) ? - FastUInt32ToBufferLeft(i, buffer) : - FastUInt64ToBufferLeft(i, buffer)); -} - -// ---------------------------------------------------------------------- -// SimpleDtoa() -// SimpleFtoa() -// DoubleToBuffer() -// FloatToBuffer() -// We want to print the value without losing precision, but we also do -// not want to print more digits than necessary. This turns out to be -// trickier than it sounds. Numbers like 0.2 cannot be represented -// exactly in binary. If we print 0.2 with a very large precision, -// e.g. "%.50g", we get "0.2000000000000000111022302462515654042363167". -// On the other hand, if we set the precision too low, we lose -// significant digits when printing numbers that actually need them. -// It turns out there is no precision value that does the right thing -// for all numbers. -// -// Our strategy is to first try printing with a precision that is never -// over-precise, then parse the result with strtod() to see if it -// matches. If not, we print again with a precision that will always -// give a precise result, but may use more digits than necessary. -// -// An arguably better strategy would be to use the algorithm described -// in "How to Print Floating-Point Numbers Accurately" by Steele & -// White, e.g. as implemented by David M. Gay's dtoa(). It turns out, -// however, that the following implementation is about as fast as -// DMG's code. Furthermore, DMG's code locks mutexes, which means it -// will not scale well on multi-core machines. DMG's code is slightly -// more accurate (in that it will never use more digits than -// necessary), but this is probably irrelevant for most users. -// -// Rob Pike and Ken Thompson also have an implementation of dtoa() in -// third_party/fmt/fltfmt.cc. Their implementation is similar to this -// one in that it makes guesses and then uses strtod() to check them. -// Their implementation is faster because they use their own code to -// generate the digits in the first place rather than use snprintf(), -// thus avoiding format string parsing overhead. However, this makes -// it considerably more complicated than the following implementation, -// and it is embedded in a larger library. If speed turns out to be -// an issue, we could re-implement this in terms of their -// implementation. -// ---------------------------------------------------------------------- - -string SimpleDtoa(double value) { - char buffer[kDoubleToBufferSize]; - return DoubleToBuffer(value, buffer); -} - -string SimpleFtoa(float value) { - char buffer[kFloatToBufferSize]; - return FloatToBuffer(value, buffer); -} - -static inline bool IsValidFloatChar(char c) { - return ('0' <= c && c <= '9') || - c == 'e' || c == 'E' || - c == '+' || c == '-'; -} - -void DelocalizeRadix(char* buffer) { - // Fast check: if the buffer has a normal decimal point, assume no - // translation is needed. - if (strchr(buffer, '.') != NULL) return; - - // Find the first unknown character. - while (IsValidFloatChar(*buffer)) ++buffer; - - if (*buffer == '\0') { - // No radix character found. - return; - } - - // We are now pointing at the locale-specific radix character. Replace it - // with '.'. - *buffer = '.'; - ++buffer; - - if (!IsValidFloatChar(*buffer) && *buffer != '\0') { - // It appears the radix was a multi-byte character. We need to remove the - // extra bytes. - char* target = buffer; - do { ++buffer; } while (!IsValidFloatChar(*buffer) && *buffer != '\0'); - memmove(target, buffer, strlen(buffer) + 1); - } -} - -char* DoubleToBuffer(double value, char* buffer) { - // DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all - // platforms these days. Just in case some system exists where DBL_DIG - // is significantly larger -- and risks overflowing our buffer -- we have - // this assert. - GOOGLE_COMPILE_ASSERT(DBL_DIG < 20, DBL_DIG_is_too_big); - - if (value == numeric_limits::infinity()) { - strcpy(buffer, "inf"); - return buffer; - } else if (value == -numeric_limits::infinity()) { - strcpy(buffer, "-inf"); - return buffer; - } else if (IsNaN(value)) { - strcpy(buffer, "nan"); - return buffer; - } - - int snprintf_result = - snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG, value); - - // The snprintf should never overflow because the buffer is significantly - // larger than the precision we asked for. - GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize); - - // We need to make parsed_value volatile in order to force the compiler to - // write it out to the stack. Otherwise, it may keep the value in a - // register, and if it does that, it may keep it as a long double instead - // of a double. This long double may have extra bits that make it compare - // unequal to "value" even though it would be exactly equal if it were - // truncated to a double. - volatile double parsed_value = strtod(buffer, NULL); - if (parsed_value != value) { - int snprintf_result = - snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value); - - // Should never overflow; see above. - GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize); - } - - DelocalizeRadix(buffer); - return buffer; -} - -bool safe_strtof(const char* str, float* value) { - char* endptr; - errno = 0; // errno only gets set on errors -#if defined(_WIN32) || defined (__hpux) // has no strtof() - *value = strtod(str, &endptr); -#else - *value = strtof(str, &endptr); -#endif - return *str != 0 && *endptr == 0 && errno == 0; -} - -char* FloatToBuffer(float value, char* buffer) { - // FLT_DIG is 6 for IEEE-754 floats, which are used on almost all - // platforms these days. Just in case some system exists where FLT_DIG - // is significantly larger -- and risks overflowing our buffer -- we have - // this assert. - GOOGLE_COMPILE_ASSERT(FLT_DIG < 10, FLT_DIG_is_too_big); - - if (value == numeric_limits::infinity()) { - strcpy(buffer, "inf"); - return buffer; - } else if (value == -numeric_limits::infinity()) { - strcpy(buffer, "-inf"); - return buffer; - } else if (IsNaN(value)) { - strcpy(buffer, "nan"); - return buffer; - } - - int snprintf_result = - snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG, value); - - // The snprintf should never overflow because the buffer is significantly - // larger than the precision we asked for. - GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize); - - float parsed_value; - if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) { - int snprintf_result = - snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value); - - // Should never overflow; see above. - GOOGLE_DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize); - } - - DelocalizeRadix(buffer); - return buffer; -} - -// ---------------------------------------------------------------------- -// NoLocaleStrtod() -// This code will make you cry. -// ---------------------------------------------------------------------- - -// Returns a string identical to *input except that the character pointed to -// by radix_pos (which should be '.') is replaced with the locale-specific -// radix character. -string LocalizeRadix(const char* input, const char* radix_pos) { - // Determine the locale-specific radix character by calling sprintf() to - // print the number 1.5, then stripping off the digits. As far as I can - // tell, this is the only portable, thread-safe way to get the C library - // to divuldge the locale's radix character. No, localeconv() is NOT - // thread-safe. - char temp[16]; - int size = sprintf(temp, "%.1f", 1.5); - GOOGLE_CHECK_EQ(temp[0], '1'); - GOOGLE_CHECK_EQ(temp[size-1], '5'); - GOOGLE_CHECK_LE(size, 6); - - // Now replace the '.' in the input with it. - string result; - result.reserve(strlen(input) + size - 3); - result.append(input, radix_pos); - result.append(temp + 1, size - 2); - result.append(radix_pos + 1); - return result; -} - -double NoLocaleStrtod(const char* text, char** original_endptr) { - // We cannot simply set the locale to "C" temporarily with setlocale() - // as this is not thread-safe. Instead, we try to parse in the current - // locale first. If parsing stops at a '.' character, then this is a - // pretty good hint that we're actually in some other locale in which - // '.' is not the radix character. - - char* temp_endptr; - double result = strtod(text, &temp_endptr); - if (original_endptr != NULL) *original_endptr = temp_endptr; - if (*temp_endptr != '.') return result; - - // Parsing halted on a '.'. Perhaps we're in a different locale? Let's - // try to replace the '.' with a locale-specific radix character and - // try again. - string localized = LocalizeRadix(text, temp_endptr); - const char* localized_cstr = localized.c_str(); - char* localized_endptr; - result = strtod(localized_cstr, &localized_endptr); - if ((localized_endptr - localized_cstr) > - (temp_endptr - text)) { - // This attempt got further, so replacing the decimal must have helped. - // Update original_endptr to point at the right location. - if (original_endptr != NULL) { - // size_diff is non-zero if the localized radix has multiple bytes. - int size_diff = localized.size() - strlen(text); - // const_cast is necessary to match the strtod() interface. - *original_endptr = const_cast( - text + (localized_endptr - localized_cstr - size_diff)); - } - } - - return result; -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/strutil.h b/Resources/NetHook/google/protobuf/stubs/strutil.h deleted file mode 100644 index 777694b7..00000000 --- a/Resources/NetHook/google/protobuf/stubs/strutil.h +++ /dev/null @@ -1,459 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// from google3/strings/strutil.h - -#ifndef GOOGLE_PROTOBUF_STUBS_STRUTIL_H__ -#define GOOGLE_PROTOBUF_STUBS_STRUTIL_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - -#ifdef _MSC_VER -#define strtoll _strtoi64 -#define strtoull _strtoui64 -#elif defined(__DECCXX) && defined(__osf__) -// HP C++ on Tru64 does not have strtoll, but strtol is already 64-bit. -#define strtoll strtol -#define strtoull strtoul -#endif - -// ---------------------------------------------------------------------- -// ascii_isalnum() -// Check if an ASCII character is alphanumeric. We can't use ctype's -// isalnum() because it is affected by locale. This function is applied -// to identifiers in the protocol buffer language, not to natural-language -// strings, so locale should not be taken into account. -// ascii_isdigit() -// Like above, but only accepts digits. -// ---------------------------------------------------------------------- - -inline bool ascii_isalnum(char c) { - return ('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - ('0' <= c && c <= '9'); -} - -inline bool ascii_isdigit(char c) { - return ('0' <= c && c <= '9'); -} - -// ---------------------------------------------------------------------- -// HasPrefixString() -// Check if a string begins with a given prefix. -// StripPrefixString() -// Given a string and a putative prefix, returns the string minus the -// prefix string if the prefix matches, otherwise the original -// string. -// ---------------------------------------------------------------------- -inline bool HasPrefixString(const string& str, - const string& prefix) { - return str.size() >= prefix.size() && - str.compare(0, prefix.size(), prefix) == 0; -} - -inline string StripPrefixString(const string& str, const string& prefix) { - if (HasPrefixString(str, prefix)) { - return str.substr(prefix.size()); - } else { - return str; - } -} - -// ---------------------------------------------------------------------- -// HasSuffixString() -// Return true if str ends in suffix. -// StripSuffixString() -// Given a string and a putative suffix, returns the string minus the -// suffix string if the suffix matches, otherwise the original -// string. -// ---------------------------------------------------------------------- -inline bool HasSuffixString(const string& str, - const string& suffix) { - return str.size() >= suffix.size() && - str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; -} - -inline string StripSuffixString(const string& str, const string& suffix) { - if (HasSuffixString(str, suffix)) { - return str.substr(0, str.size() - suffix.size()); - } else { - return str; - } -} - -// ---------------------------------------------------------------------- -// StripString -// Replaces any occurrence of the character 'remove' (or the characters -// in 'remove') with the character 'replacewith'. -// Good for keeping html characters or protocol characters (\t) out -// of places where they might cause a problem. -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void StripString(string* s, const char* remove, - char replacewith); - -// ---------------------------------------------------------------------- -// LowerString() -// UpperString() -// Convert the characters in "s" to lowercase or uppercase. ASCII-only: -// these functions intentionally ignore locale because they are applied to -// identifiers used in the Protocol Buffer language, not to natural-language -// strings. -// ---------------------------------------------------------------------- - -inline void LowerString(string * s) { - string::iterator end = s->end(); - for (string::iterator i = s->begin(); i != end; ++i) { - // tolower() changes based on locale. We don't want this! - if ('A' <= *i && *i <= 'Z') *i += 'a' - 'A'; - } -} - -inline void UpperString(string * s) { - string::iterator end = s->end(); - for (string::iterator i = s->begin(); i != end; ++i) { - // toupper() changes based on locale. We don't want this! - if ('a' <= *i && *i <= 'z') *i += 'A' - 'a'; - } -} - -// ---------------------------------------------------------------------- -// StringReplace() -// Give me a string and two patterns "old" and "new", and I replace -// the first instance of "old" in the string with "new", if it -// exists. RETURN a new string, regardless of whether the replacement -// happened or not. -// ---------------------------------------------------------------------- - -LIBPROTOBUF_EXPORT string StringReplace(const string& s, const string& oldsub, - const string& newsub, bool replace_all); - -// ---------------------------------------------------------------------- -// SplitStringUsing() -// Split a string using a character delimiter. Append the components -// to 'result'. If there are consecutive delimiters, this function skips -// over all of them. -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void SplitStringUsing(const string& full, const char* delim, - vector* res); - -// ---------------------------------------------------------------------- -// JoinStrings() -// These methods concatenate a vector of strings into a C++ string, using -// the C-string "delim" as a separator between components. There are two -// flavors of the function, one flavor returns the concatenated string, -// another takes a pointer to the target string. In the latter case the -// target string is cleared and overwritten. -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT void JoinStrings(const vector& components, - const char* delim, string* result); - -inline string JoinStrings(const vector& components, - const char* delim) { - string result; - JoinStrings(components, delim, &result); - return result; -} - -// ---------------------------------------------------------------------- -// UnescapeCEscapeSequences() -// Copies "source" to "dest", rewriting C-style escape sequences -// -- '\n', '\r', '\\', '\ooo', etc -- to their ASCII -// equivalents. "dest" must be sufficiently large to hold all -// the characters in the rewritten string (i.e. at least as large -// as strlen(source) + 1 should be safe, since the replacements -// are always shorter than the original escaped sequences). It's -// safe for source and dest to be the same. RETURNS the length -// of dest. -// -// It allows hex sequences \xhh, or generally \xhhhhh with an -// arbitrary number of hex digits, but all of them together must -// specify a value of a single byte (e.g. \x0045 is equivalent -// to \x45, and \x1234 is erroneous). -// -// It also allows escape sequences of the form \uhhhh (exactly four -// hex digits, upper or lower case) or \Uhhhhhhhh (exactly eight -// hex digits, upper or lower case) to specify a Unicode code -// point. The dest array will contain the UTF8-encoded version of -// that code-point (e.g., if source contains \u2019, then dest will -// contain the three bytes 0xE2, 0x80, and 0x99). For the inverse -// transformation, use UniLib::UTF8EscapeString -// (util/utf8/unilib.h), not CEscapeString. -// -// Errors: In the first form of the call, errors are reported with -// LOG(ERROR). The same is true for the second form of the call if -// the pointer to the string vector is NULL; otherwise, error -// messages are stored in the vector. In either case, the effect on -// the dest array is not defined, but rest of the source will be -// processed. -// ---------------------------------------------------------------------- - -LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest); -LIBPROTOBUF_EXPORT int UnescapeCEscapeSequences(const char* source, char* dest, - vector *errors); - -// ---------------------------------------------------------------------- -// UnescapeCEscapeString() -// This does the same thing as UnescapeCEscapeSequences, but creates -// a new string. The caller does not need to worry about allocating -// a dest buffer. This should be used for non performance critical -// tasks such as printing debug messages. It is safe for src and dest -// to be the same. -// -// The second call stores its errors in a supplied string vector. -// If the string vector pointer is NULL, it reports the errors with LOG(). -// -// In the first and second calls, the length of dest is returned. In the -// the third call, the new string is returned. -// ---------------------------------------------------------------------- - -LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest); -LIBPROTOBUF_EXPORT int UnescapeCEscapeString(const string& src, string* dest, - vector *errors); -LIBPROTOBUF_EXPORT string UnescapeCEscapeString(const string& src); - -// ---------------------------------------------------------------------- -// CEscapeString() -// Copies 'src' to 'dest', escaping dangerous characters using -// C-style escape sequences. This is very useful for preparing query -// flags. 'src' and 'dest' should not overlap. -// Returns the number of bytes written to 'dest' (not including the \0) -// or -1 if there was insufficient space. -// -// Currently only \n, \r, \t, ", ', \ and !isprint() chars are escaped. -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int CEscapeString(const char* src, int src_len, - char* dest, int dest_len); - -// ---------------------------------------------------------------------- -// CEscape() -// More convenient form of CEscapeString: returns result as a "string". -// This version is slower than CEscapeString() because it does more -// allocation. However, it is much more convenient to use in -// non-speed-critical code like logging messages etc. -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string CEscape(const string& src); - -namespace strings { -// Like CEscape() but does not escape bytes with the upper bit set. -LIBPROTOBUF_EXPORT string Utf8SafeCEscape(const string& src); - -// Like CEscape() but uses hex (\x) escapes instead of octals. -LIBPROTOBUF_EXPORT string CHexEscape(const string& src); -} // namespace strings - -// ---------------------------------------------------------------------- -// strto32() -// strtou32() -// strto64() -// strtou64() -// Architecture-neutral plug compatible replacements for strtol() and -// strtoul(). Long's have different lengths on ILP-32 and LP-64 -// platforms, so using these is safer, from the point of view of -// overflow behavior, than using the standard libc functions. -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT int32 strto32_adaptor(const char *nptr, char **endptr, - int base); -LIBPROTOBUF_EXPORT uint32 strtou32_adaptor(const char *nptr, char **endptr, - int base); - -inline int32 strto32(const char *nptr, char **endptr, int base) { - if (sizeof(int32) == sizeof(long)) - return strtol(nptr, endptr, base); - else - return strto32_adaptor(nptr, endptr, base); -} - -inline uint32 strtou32(const char *nptr, char **endptr, int base) { - if (sizeof(uint32) == sizeof(unsigned long)) - return strtoul(nptr, endptr, base); - else - return strtou32_adaptor(nptr, endptr, base); -} - -// For now, long long is 64-bit on all the platforms we care about, so these -// functions can simply pass the call to strto[u]ll. -inline int64 strto64(const char *nptr, char **endptr, int base) { - GOOGLE_COMPILE_ASSERT(sizeof(int64) == sizeof(long long), - sizeof_int64_is_not_sizeof_long_long); - return strtoll(nptr, endptr, base); -} - -inline uint64 strtou64(const char *nptr, char **endptr, int base) { - GOOGLE_COMPILE_ASSERT(sizeof(uint64) == sizeof(unsigned long long), - sizeof_uint64_is_not_sizeof_long_long); - return strtoull(nptr, endptr, base); -} - -// ---------------------------------------------------------------------- -// FastIntToBuffer() -// FastHexToBuffer() -// FastHex64ToBuffer() -// FastHex32ToBuffer() -// FastTimeToBuffer() -// These are intended for speed. FastIntToBuffer() assumes the -// integer is non-negative. FastHexToBuffer() puts output in -// hex rather than decimal. FastTimeToBuffer() puts the output -// into RFC822 format. -// -// FastHex64ToBuffer() puts a 64-bit unsigned value in hex-format, -// padded to exactly 16 bytes (plus one byte for '\0') -// -// FastHex32ToBuffer() puts a 32-bit unsigned value in hex-format, -// padded to exactly 8 bytes (plus one byte for '\0') -// -// All functions take the output buffer as an arg. -// They all return a pointer to the beginning of the output, -// which may not be the beginning of the input buffer. -// ---------------------------------------------------------------------- - -// Suggested buffer size for FastToBuffer functions. Also works with -// DoubleToBuffer() and FloatToBuffer(). -static const int kFastToBufferSize = 32; - -LIBPROTOBUF_EXPORT char* FastInt32ToBuffer(int32 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastInt64ToBuffer(int64 i, char* buffer); -char* FastUInt32ToBuffer(uint32 i, char* buffer); // inline below -char* FastUInt64ToBuffer(uint64 i, char* buffer); // inline below -LIBPROTOBUF_EXPORT char* FastHexToBuffer(int i, char* buffer); -LIBPROTOBUF_EXPORT char* FastHex64ToBuffer(uint64 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastHex32ToBuffer(uint32 i, char* buffer); - -// at least 22 bytes long -inline char* FastIntToBuffer(int i, char* buffer) { - return (sizeof(i) == 4 ? - FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer)); -} -inline char* FastUIntToBuffer(unsigned int i, char* buffer) { - return (sizeof(i) == 4 ? - FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer)); -} -inline char* FastLongToBuffer(long i, char* buffer) { - return (sizeof(i) == 4 ? - FastInt32ToBuffer(i, buffer) : FastInt64ToBuffer(i, buffer)); -} -inline char* FastULongToBuffer(unsigned long i, char* buffer) { - return (sizeof(i) == 4 ? - FastUInt32ToBuffer(i, buffer) : FastUInt64ToBuffer(i, buffer)); -} - -// ---------------------------------------------------------------------- -// FastInt32ToBufferLeft() -// FastUInt32ToBufferLeft() -// FastInt64ToBufferLeft() -// FastUInt64ToBufferLeft() -// -// Like the Fast*ToBuffer() functions above, these are intended for speed. -// Unlike the Fast*ToBuffer() functions, however, these functions write -// their output to the beginning of the buffer (hence the name, as the -// output is left-aligned). The caller is responsible for ensuring that -// the buffer has enough space to hold the output. -// -// Returns a pointer to the end of the string (i.e. the null character -// terminating the string). -// ---------------------------------------------------------------------- - -LIBPROTOBUF_EXPORT char* FastInt32ToBufferLeft(int32 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastUInt32ToBufferLeft(uint32 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastInt64ToBufferLeft(int64 i, char* buffer); -LIBPROTOBUF_EXPORT char* FastUInt64ToBufferLeft(uint64 i, char* buffer); - -// Just define these in terms of the above. -inline char* FastUInt32ToBuffer(uint32 i, char* buffer) { - FastUInt32ToBufferLeft(i, buffer); - return buffer; -} -inline char* FastUInt64ToBuffer(uint64 i, char* buffer) { - FastUInt64ToBufferLeft(i, buffer); - return buffer; -} - -// ---------------------------------------------------------------------- -// SimpleItoa() -// Description: converts an integer to a string. -// -// Return value: string -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string SimpleItoa(int i); -LIBPROTOBUF_EXPORT string SimpleItoa(unsigned int i); -LIBPROTOBUF_EXPORT string SimpleItoa(long i); -LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long i); -LIBPROTOBUF_EXPORT string SimpleItoa(long long i); -LIBPROTOBUF_EXPORT string SimpleItoa(unsigned long long i); - -// ---------------------------------------------------------------------- -// SimpleDtoa() -// SimpleFtoa() -// DoubleToBuffer() -// FloatToBuffer() -// Description: converts a double or float to a string which, if -// passed to NoLocaleStrtod(), will produce the exact same original double -// (except in case of NaN; all NaNs are considered the same value). -// We try to keep the string short but it's not guaranteed to be as -// short as possible. -// -// DoubleToBuffer() and FloatToBuffer() write the text to the given -// buffer and return it. The buffer must be at least -// kDoubleToBufferSize bytes for doubles and kFloatToBufferSize -// bytes for floats. kFastToBufferSize is also guaranteed to be large -// enough to hold either. -// -// Return value: string -// ---------------------------------------------------------------------- -LIBPROTOBUF_EXPORT string SimpleDtoa(double value); -LIBPROTOBUF_EXPORT string SimpleFtoa(float value); - -LIBPROTOBUF_EXPORT char* DoubleToBuffer(double i, char* buffer); -LIBPROTOBUF_EXPORT char* FloatToBuffer(float i, char* buffer); - -// In practice, doubles should never need more than 24 bytes and floats -// should never need more than 14 (including null terminators), but we -// overestimate to be safe. -static const int kDoubleToBufferSize = 32; -static const int kFloatToBufferSize = 24; - -// ---------------------------------------------------------------------- -// NoLocaleStrtod() -// Exactly like strtod(), except it always behaves as if in the "C" -// locale (i.e. decimal points must be '.'s). -// ---------------------------------------------------------------------- - -LIBPROTOBUF_EXPORT double NoLocaleStrtod(const char* text, char** endptr); - -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_STRUTIL_H__ - - diff --git a/Resources/NetHook/google/protobuf/stubs/strutil_unittest.cc b/Resources/NetHook/google/protobuf/stubs/strutil_unittest.cc deleted file mode 100644 index b9c9253b..00000000 --- a/Resources/NetHook/google/protobuf/stubs/strutil_unittest.cc +++ /dev/null @@ -1,83 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#include - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace { - -// TODO(kenton): Copy strutil tests from google3? - -TEST(StringUtilityTest, ImmuneToLocales) { - // Remember the old locale. - char* old_locale_cstr = setlocale(LC_NUMERIC, NULL); - ASSERT_TRUE(old_locale_cstr != NULL); - string old_locale = old_locale_cstr; - - // Set the locale to "C". - ASSERT_TRUE(setlocale(LC_NUMERIC, "C") != NULL); - - EXPECT_EQ(1.5, NoLocaleStrtod("1.5", NULL)); - EXPECT_EQ("1.5", SimpleDtoa(1.5)); - EXPECT_EQ("1.5", SimpleFtoa(1.5)); - - // Verify that the endptr is set correctly even if not all text was parsed. - const char* text = "1.5f"; - char* endptr; - EXPECT_EQ(1.5, NoLocaleStrtod(text, &endptr)); - EXPECT_EQ(3, endptr - text); - - if (setlocale(LC_NUMERIC, "es_ES") == NULL && - setlocale(LC_NUMERIC, "es_ES.utf8") == NULL) { - // Some systems may not have the desired locale available. - GOOGLE_LOG(WARNING) - << "Couldn't set locale to es_ES. Skipping this test."; - } else { - EXPECT_EQ(1.5, NoLocaleStrtod("1.5", NULL)); - EXPECT_EQ("1.5", SimpleDtoa(1.5)); - EXPECT_EQ("1.5", SimpleFtoa(1.5)); - EXPECT_EQ(1.5, NoLocaleStrtod(text, &endptr)); - EXPECT_EQ(3, endptr - text); - } - - // Return to original locale. - setlocale(LC_NUMERIC, old_locale.c_str()); -} - -} // anonymous namespace -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/substitute.cc b/Resources/NetHook/google/protobuf/stubs/substitute.cc deleted file mode 100644 index b542aaa4..00000000 --- a/Resources/NetHook/google/protobuf/stubs/substitute.cc +++ /dev/null @@ -1,134 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -#include -#include -#include - -namespace google { -namespace protobuf { -namespace strings { - -using internal::SubstituteArg; - -// Returns the number of args in arg_array which were passed explicitly -// to Substitute(). -static int CountSubstituteArgs(const SubstituteArg* const* args_array) { - int count = 0; - while (args_array[count] != NULL && args_array[count]->size() != -1) { - ++count; - } - return count; -} - -string Substitute( - const char* format, - const SubstituteArg& arg0, const SubstituteArg& arg1, - const SubstituteArg& arg2, const SubstituteArg& arg3, - const SubstituteArg& arg4, const SubstituteArg& arg5, - const SubstituteArg& arg6, const SubstituteArg& arg7, - const SubstituteArg& arg8, const SubstituteArg& arg9) { - string result; - SubstituteAndAppend(&result, format, arg0, arg1, arg2, arg3, arg4, - arg5, arg6, arg7, arg8, arg9); - return result; -} - -void SubstituteAndAppend( - string* output, const char* format, - const SubstituteArg& arg0, const SubstituteArg& arg1, - const SubstituteArg& arg2, const SubstituteArg& arg3, - const SubstituteArg& arg4, const SubstituteArg& arg5, - const SubstituteArg& arg6, const SubstituteArg& arg7, - const SubstituteArg& arg8, const SubstituteArg& arg9) { - const SubstituteArg* const args_array[] = { - &arg0, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8, &arg9, NULL - }; - - // Determine total size needed. - int size = 0; - for (int i = 0; format[i] != '\0'; i++) { - if (format[i] == '$') { - if (ascii_isdigit(format[i+1])) { - int index = format[i+1] - '0'; - if (args_array[index]->size() == -1) { - GOOGLE_LOG(DFATAL) - << "strings::Substitute format string invalid: asked for \"$" - << index << "\", but only " << CountSubstituteArgs(args_array) - << " args were given. Full format string was: \"" - << CEscape(format) << "\"."; - return; - } - size += args_array[index]->size(); - ++i; // Skip next char. - } else if (format[i+1] == '$') { - ++size; - ++i; // Skip next char. - } else { - GOOGLE_LOG(DFATAL) - << "Invalid strings::Substitute() format string: \"" - << CEscape(format) << "\"."; - return; - } - } else { - ++size; - } - } - - if (size == 0) return; - - // Build the string. - int original_size = output->size(); - STLStringResizeUninitialized(output, original_size + size); - char* target = string_as_array(output) + original_size; - for (int i = 0; format[i] != '\0'; i++) { - if (format[i] == '$') { - if (ascii_isdigit(format[i+1])) { - const SubstituteArg* src = args_array[format[i+1] - '0']; - memcpy(target, src->data(), src->size()); - target += src->size(); - ++i; // Skip next char. - } else if (format[i+1] == '$') { - *target++ = '$'; - ++i; // Skip next char. - } - } else { - *target++ = format[i]; - } - } - - GOOGLE_DCHECK_EQ(target - output->data(), output->size()); -} - -} // namespace strings -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/stubs/substitute.h b/Resources/NetHook/google/protobuf/stubs/substitute.h deleted file mode 100644 index 2581793b..00000000 --- a/Resources/NetHook/google/protobuf/stubs/substitute.h +++ /dev/null @@ -1,170 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// from google3/strings/substitute.h - -#include -#include -#include - -#ifndef GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_ -#define GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_ - -namespace google { -namespace protobuf { -namespace strings { - -// ---------------------------------------------------------------------- -// strings::Substitute() -// strings::SubstituteAndAppend() -// Kind of like StringPrintf, but different. -// -// Example: -// string GetMessage(string first_name, string last_name, int age) { -// return strings::Substitute("My name is $0 $1 and I am $2 years old.", -// first_name, last_name, age); -// } -// -// Differences from StringPrintf: -// * The format string does not identify the types of arguments. -// Instead, the magic of C++ deals with this for us. See below -// for a list of accepted types. -// * Substitutions in the format string are identified by a '$' -// followed by a digit. So, you can use arguments out-of-order and -// use the same argument multiple times. -// * It's much faster than StringPrintf. -// -// Supported types: -// * Strings (const char*, const string&) -// * Note that this means you do not have to add .c_str() to all of -// your strings. In fact, you shouldn't; it will be slower. -// * int32, int64, uint32, uint64: Formatted using SimpleItoa(). -// * float, double: Formatted using SimpleFtoa() and SimpleDtoa(). -// * bool: Printed as "true" or "false". -// -// SubstituteAndAppend() is like Substitute() but appends the result to -// *output. Example: -// -// string str; -// strings::SubstituteAndAppend(&str, -// "My name is $0 $1 and I am $2 years old.", -// first_name, last_name, age); -// -// Substitute() is significantly faster than StringPrintf(). For very -// large strings, it may be orders of magnitude faster. -// ---------------------------------------------------------------------- - -namespace internal { // Implementation details. - -class SubstituteArg { - public: - inline SubstituteArg(const char* value) - : text_(value), size_(strlen(text_)) {} - inline SubstituteArg(const string& value) - : text_(value.data()), size_(value.size()) {} - - // Indicates that no argument was given. - inline explicit SubstituteArg() - : text_(NULL), size_(-1) {} - - // Primitives - // We don't overload for signed and unsigned char because if people are - // explicitly declaring their chars as signed or unsigned then they are - // probably actually using them as 8-bit integers and would probably - // prefer an integer representation. But, we don't really know. So, we - // make the caller decide what to do. - inline SubstituteArg(char value) - : text_(scratch_), size_(1) { scratch_[0] = value; } - inline SubstituteArg(short value) - : text_(FastInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(unsigned short value) - : text_(FastUInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(int value) - : text_(FastInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(unsigned int value) - : text_(FastUInt32ToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(long value) - : text_(FastLongToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(unsigned long value) - : text_(FastULongToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(long long value) - : text_(FastInt64ToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(unsigned long long value) - : text_(FastUInt64ToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(float value) - : text_(FloatToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(double value) - : text_(DoubleToBuffer(value, scratch_)), size_(strlen(text_)) {} - inline SubstituteArg(bool value) - : text_(value ? "true" : "false"), size_(strlen(text_)) {} - - inline const char* data() const { return text_; } - inline int size() const { return size_; } - - private: - const char* text_; - int size_; - char scratch_[kFastToBufferSize]; -}; - -} // namespace internal - -LIBPROTOBUF_EXPORT string Substitute( - const char* format, - const internal::SubstituteArg& arg0 = internal::SubstituteArg(), - const internal::SubstituteArg& arg1 = internal::SubstituteArg(), - const internal::SubstituteArg& arg2 = internal::SubstituteArg(), - const internal::SubstituteArg& arg3 = internal::SubstituteArg(), - const internal::SubstituteArg& arg4 = internal::SubstituteArg(), - const internal::SubstituteArg& arg5 = internal::SubstituteArg(), - const internal::SubstituteArg& arg6 = internal::SubstituteArg(), - const internal::SubstituteArg& arg7 = internal::SubstituteArg(), - const internal::SubstituteArg& arg8 = internal::SubstituteArg(), - const internal::SubstituteArg& arg9 = internal::SubstituteArg()); - -LIBPROTOBUF_EXPORT void SubstituteAndAppend( - string* output, const char* format, - const internal::SubstituteArg& arg0 = internal::SubstituteArg(), - const internal::SubstituteArg& arg1 = internal::SubstituteArg(), - const internal::SubstituteArg& arg2 = internal::SubstituteArg(), - const internal::SubstituteArg& arg3 = internal::SubstituteArg(), - const internal::SubstituteArg& arg4 = internal::SubstituteArg(), - const internal::SubstituteArg& arg5 = internal::SubstituteArg(), - const internal::SubstituteArg& arg6 = internal::SubstituteArg(), - const internal::SubstituteArg& arg7 = internal::SubstituteArg(), - const internal::SubstituteArg& arg8 = internal::SubstituteArg(), - const internal::SubstituteArg& arg9 = internal::SubstituteArg()); - -} // namespace strings -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_STUBS_SUBSTITUTE_H_ diff --git a/Resources/NetHook/google/protobuf/test_util.cc b/Resources/NetHook/google/protobuf/test_util.cc deleted file mode 100644 index af8b3909..00000000 --- a/Resources/NetHook/google/protobuf/test_util.cc +++ /dev/null @@ -1,2854 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifdef _WIN32 -// Verify that #including windows.h does not break anything (e.g. because -// windows.h #defines GetMessage() as a macro). -#include -#endif - -#include -#include -#include - -#include -#include -#include - -namespace google { -namespace protobuf { - -void TestUtil::SetAllFields(unittest::TestAllTypes* message) { - message->set_optional_int32 (101); - message->set_optional_int64 (102); - message->set_optional_uint32 (103); - message->set_optional_uint64 (104); - message->set_optional_sint32 (105); - message->set_optional_sint64 (106); - message->set_optional_fixed32 (107); - message->set_optional_fixed64 (108); - message->set_optional_sfixed32(109); - message->set_optional_sfixed64(110); - message->set_optional_float (111); - message->set_optional_double (112); - message->set_optional_bool (true); - message->set_optional_string ("115"); - message->set_optional_bytes ("116"); - - message->mutable_optionalgroup ()->set_a(117); - message->mutable_optional_nested_message ()->set_bb(118); - message->mutable_optional_foreign_message()->set_c(119); - message->mutable_optional_import_message ()->set_d(120); - - message->set_optional_nested_enum (unittest::TestAllTypes::BAZ); - message->set_optional_foreign_enum(unittest::FOREIGN_BAZ ); - message->set_optional_import_enum (unittest_import::IMPORT_BAZ); - - // StringPiece and Cord fields are only accessible via reflection in the - // open source release; see comments in compiler/cpp/string_field.cc. -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("optional_string_piece"), - "124"); - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("optional_cord"), - "125"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - - // ----------------------------------------------------------------- - - message->add_repeated_int32 (201); - message->add_repeated_int64 (202); - message->add_repeated_uint32 (203); - message->add_repeated_uint64 (204); - message->add_repeated_sint32 (205); - message->add_repeated_sint64 (206); - message->add_repeated_fixed32 (207); - message->add_repeated_fixed64 (208); - message->add_repeated_sfixed32(209); - message->add_repeated_sfixed64(210); - message->add_repeated_float (211); - message->add_repeated_double (212); - message->add_repeated_bool (true); - message->add_repeated_string ("215"); - message->add_repeated_bytes ("216"); - - message->add_repeatedgroup ()->set_a(217); - message->add_repeated_nested_message ()->set_bb(218); - message->add_repeated_foreign_message()->set_c(219); - message->add_repeated_import_message ()->set_d(220); - - message->add_repeated_nested_enum (unittest::TestAllTypes::BAR); - message->add_repeated_foreign_enum(unittest::FOREIGN_BAR ); - message->add_repeated_import_enum (unittest_import::IMPORT_BAR); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - "224"); - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - "225"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - - // Add a second one of each field. - message->add_repeated_int32 (301); - message->add_repeated_int64 (302); - message->add_repeated_uint32 (303); - message->add_repeated_uint64 (304); - message->add_repeated_sint32 (305); - message->add_repeated_sint64 (306); - message->add_repeated_fixed32 (307); - message->add_repeated_fixed64 (308); - message->add_repeated_sfixed32(309); - message->add_repeated_sfixed64(310); - message->add_repeated_float (311); - message->add_repeated_double (312); - message->add_repeated_bool (false); - message->add_repeated_string ("315"); - message->add_repeated_bytes ("316"); - - message->add_repeatedgroup ()->set_a(317); - message->add_repeated_nested_message ()->set_bb(318); - message->add_repeated_foreign_message()->set_c(319); - message->add_repeated_import_message ()->set_d(320); - - message->add_repeated_nested_enum (unittest::TestAllTypes::BAZ); - message->add_repeated_foreign_enum(unittest::FOREIGN_BAZ ); - message->add_repeated_import_enum (unittest_import::IMPORT_BAZ); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - "324"); - message->GetReflection()->AddString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - "325"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS - - // ----------------------------------------------------------------- - - message->set_default_int32 (401); - message->set_default_int64 (402); - message->set_default_uint32 (403); - message->set_default_uint64 (404); - message->set_default_sint32 (405); - message->set_default_sint64 (406); - message->set_default_fixed32 (407); - message->set_default_fixed64 (408); - message->set_default_sfixed32(409); - message->set_default_sfixed64(410); - message->set_default_float (411); - message->set_default_double (412); - message->set_default_bool (false); - message->set_default_string ("415"); - message->set_default_bytes ("416"); - - message->set_default_nested_enum (unittest::TestAllTypes::FOO); - message->set_default_foreign_enum(unittest::FOREIGN_FOO ); - message->set_default_import_enum (unittest_import::IMPORT_FOO); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("default_string_piece"), - "424"); - message->GetReflection()->SetString( - message, - message->GetDescriptor()->FindFieldByName("default_cord"), - "425"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyRepeatedFields(unittest::TestAllTypes* message) { - message->set_repeated_int32 (1, 501); - message->set_repeated_int64 (1, 502); - message->set_repeated_uint32 (1, 503); - message->set_repeated_uint64 (1, 504); - message->set_repeated_sint32 (1, 505); - message->set_repeated_sint64 (1, 506); - message->set_repeated_fixed32 (1, 507); - message->set_repeated_fixed64 (1, 508); - message->set_repeated_sfixed32(1, 509); - message->set_repeated_sfixed64(1, 510); - message->set_repeated_float (1, 511); - message->set_repeated_double (1, 512); - message->set_repeated_bool (1, true); - message->set_repeated_string (1, "515"); - message->set_repeated_bytes (1, "516"); - - message->mutable_repeatedgroup (1)->set_a(517); - message->mutable_repeated_nested_message (1)->set_bb(518); - message->mutable_repeated_foreign_message(1)->set_c(519); - message->mutable_repeated_import_message (1)->set_d(520); - - message->set_repeated_nested_enum (1, unittest::TestAllTypes::FOO); - message->set_repeated_foreign_enum(1, unittest::FOREIGN_FOO ); - message->set_repeated_import_enum (1, unittest_import::IMPORT_FOO); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - message->GetReflection()->SetRepeatedString( - message, - message->GetDescriptor()->FindFieldByName("repeated_string_piece"), - 1, "524"); - message->GetReflection()->SetRepeatedString( - message, - message->GetDescriptor()->FindFieldByName("repeated_cord"), - 1, "525"); -#endif // !PROTOBUF_TEST_NO_DESCRIPTORS -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllFieldsSet(const unittest::TestAllTypes& message) { - EXPECT_TRUE(message.has_optional_int32 ()); - EXPECT_TRUE(message.has_optional_int64 ()); - EXPECT_TRUE(message.has_optional_uint32 ()); - EXPECT_TRUE(message.has_optional_uint64 ()); - EXPECT_TRUE(message.has_optional_sint32 ()); - EXPECT_TRUE(message.has_optional_sint64 ()); - EXPECT_TRUE(message.has_optional_fixed32 ()); - EXPECT_TRUE(message.has_optional_fixed64 ()); - EXPECT_TRUE(message.has_optional_sfixed32()); - EXPECT_TRUE(message.has_optional_sfixed64()); - EXPECT_TRUE(message.has_optional_float ()); - EXPECT_TRUE(message.has_optional_double ()); - EXPECT_TRUE(message.has_optional_bool ()); - EXPECT_TRUE(message.has_optional_string ()); - EXPECT_TRUE(message.has_optional_bytes ()); - - EXPECT_TRUE(message.has_optionalgroup ()); - EXPECT_TRUE(message.has_optional_nested_message ()); - EXPECT_TRUE(message.has_optional_foreign_message()); - EXPECT_TRUE(message.has_optional_import_message ()); - - EXPECT_TRUE(message.optionalgroup ().has_a()); - EXPECT_TRUE(message.optional_nested_message ().has_bb()); - EXPECT_TRUE(message.optional_foreign_message().has_c()); - EXPECT_TRUE(message.optional_import_message ().has_d()); - - EXPECT_TRUE(message.has_optional_nested_enum ()); - EXPECT_TRUE(message.has_optional_foreign_enum()); - EXPECT_TRUE(message.has_optional_import_enum ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - EXPECT_TRUE(message.has_optional_string_piece()); - EXPECT_TRUE(message.has_optional_cord()); -#endif - - EXPECT_EQ(101 , message.optional_int32 ()); - EXPECT_EQ(102 , message.optional_int64 ()); - EXPECT_EQ(103 , message.optional_uint32 ()); - EXPECT_EQ(104 , message.optional_uint64 ()); - EXPECT_EQ(105 , message.optional_sint32 ()); - EXPECT_EQ(106 , message.optional_sint64 ()); - EXPECT_EQ(107 , message.optional_fixed32 ()); - EXPECT_EQ(108 , message.optional_fixed64 ()); - EXPECT_EQ(109 , message.optional_sfixed32()); - EXPECT_EQ(110 , message.optional_sfixed64()); - EXPECT_EQ(111 , message.optional_float ()); - EXPECT_EQ(112 , message.optional_double ()); - EXPECT_EQ(true , message.optional_bool ()); - EXPECT_EQ("115", message.optional_string ()); - EXPECT_EQ("116", message.optional_bytes ()); - - EXPECT_EQ(117, message.optionalgroup ().a()); - EXPECT_EQ(118, message.optional_nested_message ().bb()); - EXPECT_EQ(119, message.optional_foreign_message().c()); - EXPECT_EQ(120, message.optional_import_message ().d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.optional_import_enum ()); - - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); - - EXPECT_EQ(301 , message.repeated_int32 (1)); - EXPECT_EQ(302 , message.repeated_int64 (1)); - EXPECT_EQ(303 , message.repeated_uint32 (1)); - EXPECT_EQ(304 , message.repeated_uint64 (1)); - EXPECT_EQ(305 , message.repeated_sint32 (1)); - EXPECT_EQ(306 , message.repeated_sint64 (1)); - EXPECT_EQ(307 , message.repeated_fixed32 (1)); - EXPECT_EQ(308 , message.repeated_fixed64 (1)); - EXPECT_EQ(309 , message.repeated_sfixed32(1)); - EXPECT_EQ(310 , message.repeated_sfixed64(1)); - EXPECT_EQ(311 , message.repeated_float (1)); - EXPECT_EQ(312 , message.repeated_double (1)); - EXPECT_EQ(false, message.repeated_bool (1)); - EXPECT_EQ("315", message.repeated_string (1)); - EXPECT_EQ("316", message.repeated_bytes (1)); - - EXPECT_EQ(317, message.repeatedgroup (1).a()); - EXPECT_EQ(318, message.repeated_nested_message (1).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(1).c()); - EXPECT_EQ(320, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (1)); - - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.has_default_int32 ()); - EXPECT_TRUE(message.has_default_int64 ()); - EXPECT_TRUE(message.has_default_uint32 ()); - EXPECT_TRUE(message.has_default_uint64 ()); - EXPECT_TRUE(message.has_default_sint32 ()); - EXPECT_TRUE(message.has_default_sint64 ()); - EXPECT_TRUE(message.has_default_fixed32 ()); - EXPECT_TRUE(message.has_default_fixed64 ()); - EXPECT_TRUE(message.has_default_sfixed32()); - EXPECT_TRUE(message.has_default_sfixed64()); - EXPECT_TRUE(message.has_default_float ()); - EXPECT_TRUE(message.has_default_double ()); - EXPECT_TRUE(message.has_default_bool ()); - EXPECT_TRUE(message.has_default_string ()); - EXPECT_TRUE(message.has_default_bytes ()); - - EXPECT_TRUE(message.has_default_nested_enum ()); - EXPECT_TRUE(message.has_default_foreign_enum()); - EXPECT_TRUE(message.has_default_import_enum ()); - - - EXPECT_EQ(401 , message.default_int32 ()); - EXPECT_EQ(402 , message.default_int64 ()); - EXPECT_EQ(403 , message.default_uint32 ()); - EXPECT_EQ(404 , message.default_uint64 ()); - EXPECT_EQ(405 , message.default_sint32 ()); - EXPECT_EQ(406 , message.default_sint64 ()); - EXPECT_EQ(407 , message.default_fixed32 ()); - EXPECT_EQ(408 , message.default_fixed64 ()); - EXPECT_EQ(409 , message.default_sfixed32()); - EXPECT_EQ(410 , message.default_sfixed64()); - EXPECT_EQ(411 , message.default_float ()); - EXPECT_EQ(412 , message.default_double ()); - EXPECT_EQ(false, message.default_bool ()); - EXPECT_EQ("415", message.default_string ()); - EXPECT_EQ("416", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_FOO , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.default_import_enum ()); - -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectClear(const unittest::TestAllTypes& message) { - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.has_optional_int32 ()); - EXPECT_FALSE(message.has_optional_int64 ()); - EXPECT_FALSE(message.has_optional_uint32 ()); - EXPECT_FALSE(message.has_optional_uint64 ()); - EXPECT_FALSE(message.has_optional_sint32 ()); - EXPECT_FALSE(message.has_optional_sint64 ()); - EXPECT_FALSE(message.has_optional_fixed32 ()); - EXPECT_FALSE(message.has_optional_fixed64 ()); - EXPECT_FALSE(message.has_optional_sfixed32()); - EXPECT_FALSE(message.has_optional_sfixed64()); - EXPECT_FALSE(message.has_optional_float ()); - EXPECT_FALSE(message.has_optional_double ()); - EXPECT_FALSE(message.has_optional_bool ()); - EXPECT_FALSE(message.has_optional_string ()); - EXPECT_FALSE(message.has_optional_bytes ()); - - EXPECT_FALSE(message.has_optionalgroup ()); - EXPECT_FALSE(message.has_optional_nested_message ()); - EXPECT_FALSE(message.has_optional_foreign_message()); - EXPECT_FALSE(message.has_optional_import_message ()); - - EXPECT_FALSE(message.has_optional_nested_enum ()); - EXPECT_FALSE(message.has_optional_foreign_enum()); - EXPECT_FALSE(message.has_optional_import_enum ()); - - EXPECT_FALSE(message.has_optional_string_piece()); - EXPECT_FALSE(message.has_optional_cord()); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.optional_int32 ()); - EXPECT_EQ(0 , message.optional_int64 ()); - EXPECT_EQ(0 , message.optional_uint32 ()); - EXPECT_EQ(0 , message.optional_uint64 ()); - EXPECT_EQ(0 , message.optional_sint32 ()); - EXPECT_EQ(0 , message.optional_sint64 ()); - EXPECT_EQ(0 , message.optional_fixed32 ()); - EXPECT_EQ(0 , message.optional_fixed64 ()); - EXPECT_EQ(0 , message.optional_sfixed32()); - EXPECT_EQ(0 , message.optional_sfixed64()); - EXPECT_EQ(0 , message.optional_float ()); - EXPECT_EQ(0 , message.optional_double ()); - EXPECT_EQ(false, message.optional_bool ()); - EXPECT_EQ("" , message.optional_string ()); - EXPECT_EQ("" , message.optional_bytes ()); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.optionalgroup ().has_a()); - EXPECT_FALSE(message.optional_nested_message ().has_bb()); - EXPECT_FALSE(message.optional_foreign_message().has_c()); - EXPECT_FALSE(message.optional_import_message ().has_d()); - - EXPECT_EQ(0, message.optionalgroup ().a()); - EXPECT_EQ(0, message.optional_nested_message ().bb()); - EXPECT_EQ(0, message.optional_foreign_message().c()); - EXPECT_EQ(0, message.optional_import_message ().d()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypes::FOO, message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_FOO , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.optional_import_enum ()); - - - // Repeated fields are empty. - EXPECT_EQ(0, message.repeated_int32_size ()); - EXPECT_EQ(0, message.repeated_int64_size ()); - EXPECT_EQ(0, message.repeated_uint32_size ()); - EXPECT_EQ(0, message.repeated_uint64_size ()); - EXPECT_EQ(0, message.repeated_sint32_size ()); - EXPECT_EQ(0, message.repeated_sint64_size ()); - EXPECT_EQ(0, message.repeated_fixed32_size ()); - EXPECT_EQ(0, message.repeated_fixed64_size ()); - EXPECT_EQ(0, message.repeated_sfixed32_size()); - EXPECT_EQ(0, message.repeated_sfixed64_size()); - EXPECT_EQ(0, message.repeated_float_size ()); - EXPECT_EQ(0, message.repeated_double_size ()); - EXPECT_EQ(0, message.repeated_bool_size ()); - EXPECT_EQ(0, message.repeated_string_size ()); - EXPECT_EQ(0, message.repeated_bytes_size ()); - - EXPECT_EQ(0, message.repeatedgroup_size ()); - EXPECT_EQ(0, message.repeated_nested_message_size ()); - EXPECT_EQ(0, message.repeated_foreign_message_size()); - EXPECT_EQ(0, message.repeated_import_message_size ()); - EXPECT_EQ(0, message.repeated_nested_enum_size ()); - EXPECT_EQ(0, message.repeated_foreign_enum_size ()); - EXPECT_EQ(0, message.repeated_import_enum_size ()); - - EXPECT_EQ(0, message.repeated_string_piece_size()); - EXPECT_EQ(0, message.repeated_cord_size()); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.has_default_int32 ()); - EXPECT_FALSE(message.has_default_int64 ()); - EXPECT_FALSE(message.has_default_uint32 ()); - EXPECT_FALSE(message.has_default_uint64 ()); - EXPECT_FALSE(message.has_default_sint32 ()); - EXPECT_FALSE(message.has_default_sint64 ()); - EXPECT_FALSE(message.has_default_fixed32 ()); - EXPECT_FALSE(message.has_default_fixed64 ()); - EXPECT_FALSE(message.has_default_sfixed32()); - EXPECT_FALSE(message.has_default_sfixed64()); - EXPECT_FALSE(message.has_default_float ()); - EXPECT_FALSE(message.has_default_double ()); - EXPECT_FALSE(message.has_default_bool ()); - EXPECT_FALSE(message.has_default_string ()); - EXPECT_FALSE(message.has_default_bytes ()); - - EXPECT_FALSE(message.has_default_nested_enum ()); - EXPECT_FALSE(message.has_default_foreign_enum()); - EXPECT_FALSE(message.has_default_import_enum ()); - - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.default_int32 ()); - EXPECT_EQ( 42 , message.default_int64 ()); - EXPECT_EQ( 43 , message.default_uint32 ()); - EXPECT_EQ( 44 , message.default_uint64 ()); - EXPECT_EQ(-45 , message.default_sint32 ()); - EXPECT_EQ( 46 , message.default_sint64 ()); - EXPECT_EQ( 47 , message.default_fixed32 ()); - EXPECT_EQ( 48 , message.default_fixed64 ()); - EXPECT_EQ( 49 , message.default_sfixed32()); - EXPECT_EQ(-50 , message.default_sfixed64()); - EXPECT_EQ( 51.5 , message.default_float ()); - EXPECT_EQ( 52e3 , message.default_double ()); - EXPECT_EQ(true , message.default_bool ()); - EXPECT_EQ("hello", message.default_string ()); - EXPECT_EQ("world", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_BAR , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.default_import_enum ()); - -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectRepeatedFieldsModified( - const unittest::TestAllTypes& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); - - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.repeated_int32 (1)); - EXPECT_EQ(502 , message.repeated_int64 (1)); - EXPECT_EQ(503 , message.repeated_uint32 (1)); - EXPECT_EQ(504 , message.repeated_uint64 (1)); - EXPECT_EQ(505 , message.repeated_sint32 (1)); - EXPECT_EQ(506 , message.repeated_sint64 (1)); - EXPECT_EQ(507 , message.repeated_fixed32 (1)); - EXPECT_EQ(508 , message.repeated_fixed64 (1)); - EXPECT_EQ(509 , message.repeated_sfixed32(1)); - EXPECT_EQ(510 , message.repeated_sfixed64(1)); - EXPECT_EQ(511 , message.repeated_float (1)); - EXPECT_EQ(512 , message.repeated_double (1)); - EXPECT_EQ(true , message.repeated_bool (1)); - EXPECT_EQ("515", message.repeated_string (1)); - EXPECT_EQ("516", message.repeated_bytes (1)); - - EXPECT_EQ(517, message.repeatedgroup (1).a()); - EXPECT_EQ(518, message.repeated_nested_message (1).bb()); - EXPECT_EQ(519, message.repeated_foreign_message(1).c()); - EXPECT_EQ(520, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_FOO , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.repeated_import_enum (1)); - -} - -// ------------------------------------------------------------------- - -void TestUtil::SetPackedFields(unittest::TestPackedTypes* message) { - message->add_packed_int32 (601); - message->add_packed_int64 (602); - message->add_packed_uint32 (603); - message->add_packed_uint64 (604); - message->add_packed_sint32 (605); - message->add_packed_sint64 (606); - message->add_packed_fixed32 (607); - message->add_packed_fixed64 (608); - message->add_packed_sfixed32(609); - message->add_packed_sfixed64(610); - message->add_packed_float (611); - message->add_packed_double (612); - message->add_packed_bool (true); - message->add_packed_enum (unittest::FOREIGN_BAR); - // add a second one of each field - message->add_packed_int32 (701); - message->add_packed_int64 (702); - message->add_packed_uint32 (703); - message->add_packed_uint64 (704); - message->add_packed_sint32 (705); - message->add_packed_sint64 (706); - message->add_packed_fixed32 (707); - message->add_packed_fixed64 (708); - message->add_packed_sfixed32(709); - message->add_packed_sfixed64(710); - message->add_packed_float (711); - message->add_packed_double (712); - message->add_packed_bool (false); - message->add_packed_enum (unittest::FOREIGN_BAZ); -} - -void TestUtil::SetUnpackedFields(unittest::TestUnpackedTypes* message) { - // The values applied here must match those of SetPackedFields. - - message->add_unpacked_int32 (601); - message->add_unpacked_int64 (602); - message->add_unpacked_uint32 (603); - message->add_unpacked_uint64 (604); - message->add_unpacked_sint32 (605); - message->add_unpacked_sint64 (606); - message->add_unpacked_fixed32 (607); - message->add_unpacked_fixed64 (608); - message->add_unpacked_sfixed32(609); - message->add_unpacked_sfixed64(610); - message->add_unpacked_float (611); - message->add_unpacked_double (612); - message->add_unpacked_bool (true); - message->add_unpacked_enum (unittest::FOREIGN_BAR); - // add a second one of each field - message->add_unpacked_int32 (701); - message->add_unpacked_int64 (702); - message->add_unpacked_uint32 (703); - message->add_unpacked_uint64 (704); - message->add_unpacked_sint32 (705); - message->add_unpacked_sint64 (706); - message->add_unpacked_fixed32 (707); - message->add_unpacked_fixed64 (708); - message->add_unpacked_sfixed32(709); - message->add_unpacked_sfixed64(710); - message->add_unpacked_float (711); - message->add_unpacked_double (712); - message->add_unpacked_bool (false); - message->add_unpacked_enum (unittest::FOREIGN_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyPackedFields(unittest::TestPackedTypes* message) { - message->set_packed_int32 (1, 801); - message->set_packed_int64 (1, 802); - message->set_packed_uint32 (1, 803); - message->set_packed_uint64 (1, 804); - message->set_packed_sint32 (1, 805); - message->set_packed_sint64 (1, 806); - message->set_packed_fixed32 (1, 807); - message->set_packed_fixed64 (1, 808); - message->set_packed_sfixed32(1, 809); - message->set_packed_sfixed64(1, 810); - message->set_packed_float (1, 811); - message->set_packed_double (1, 812); - message->set_packed_bool (1, true); - message->set_packed_enum (1, unittest::FOREIGN_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedFieldsSet(const unittest::TestPackedTypes& message) { - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_EQ(true , message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0)); - - EXPECT_EQ(701 , message.packed_int32 (1)); - EXPECT_EQ(702 , message.packed_int64 (1)); - EXPECT_EQ(703 , message.packed_uint32 (1)); - EXPECT_EQ(704 , message.packed_uint64 (1)); - EXPECT_EQ(705 , message.packed_sint32 (1)); - EXPECT_EQ(706 , message.packed_sint64 (1)); - EXPECT_EQ(707 , message.packed_fixed32 (1)); - EXPECT_EQ(708 , message.packed_fixed64 (1)); - EXPECT_EQ(709 , message.packed_sfixed32(1)); - EXPECT_EQ(710 , message.packed_sfixed64(1)); - EXPECT_EQ(711 , message.packed_float (1)); - EXPECT_EQ(712 , message.packed_double (1)); - EXPECT_EQ(false, message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, message.packed_enum(1)); -} - -void TestUtil::ExpectUnpackedFieldsSet( - const unittest::TestUnpackedTypes& message) { - // The values expected here must match those of ExpectPackedFieldsSet. - - ASSERT_EQ(2, message.unpacked_int32_size ()); - ASSERT_EQ(2, message.unpacked_int64_size ()); - ASSERT_EQ(2, message.unpacked_uint32_size ()); - ASSERT_EQ(2, message.unpacked_uint64_size ()); - ASSERT_EQ(2, message.unpacked_sint32_size ()); - ASSERT_EQ(2, message.unpacked_sint64_size ()); - ASSERT_EQ(2, message.unpacked_fixed32_size ()); - ASSERT_EQ(2, message.unpacked_fixed64_size ()); - ASSERT_EQ(2, message.unpacked_sfixed32_size()); - ASSERT_EQ(2, message.unpacked_sfixed64_size()); - ASSERT_EQ(2, message.unpacked_float_size ()); - ASSERT_EQ(2, message.unpacked_double_size ()); - ASSERT_EQ(2, message.unpacked_bool_size ()); - ASSERT_EQ(2, message.unpacked_enum_size ()); - - EXPECT_EQ(601 , message.unpacked_int32 (0)); - EXPECT_EQ(602 , message.unpacked_int64 (0)); - EXPECT_EQ(603 , message.unpacked_uint32 (0)); - EXPECT_EQ(604 , message.unpacked_uint64 (0)); - EXPECT_EQ(605 , message.unpacked_sint32 (0)); - EXPECT_EQ(606 , message.unpacked_sint64 (0)); - EXPECT_EQ(607 , message.unpacked_fixed32 (0)); - EXPECT_EQ(608 , message.unpacked_fixed64 (0)); - EXPECT_EQ(609 , message.unpacked_sfixed32(0)); - EXPECT_EQ(610 , message.unpacked_sfixed64(0)); - EXPECT_EQ(611 , message.unpacked_float (0)); - EXPECT_EQ(612 , message.unpacked_double (0)); - EXPECT_EQ(true , message.unpacked_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.unpacked_enum(0)); - - EXPECT_EQ(701 , message.unpacked_int32 (1)); - EXPECT_EQ(702 , message.unpacked_int64 (1)); - EXPECT_EQ(703 , message.unpacked_uint32 (1)); - EXPECT_EQ(704 , message.unpacked_uint64 (1)); - EXPECT_EQ(705 , message.unpacked_sint32 (1)); - EXPECT_EQ(706 , message.unpacked_sint64 (1)); - EXPECT_EQ(707 , message.unpacked_fixed32 (1)); - EXPECT_EQ(708 , message.unpacked_fixed64 (1)); - EXPECT_EQ(709 , message.unpacked_sfixed32(1)); - EXPECT_EQ(710 , message.unpacked_sfixed64(1)); - EXPECT_EQ(711 , message.unpacked_float (1)); - EXPECT_EQ(712 , message.unpacked_double (1)); - EXPECT_EQ(false, message.unpacked_bool (1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, message.unpacked_enum(1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedClear( - const unittest::TestPackedTypes& message) { - // Packed repeated fields are empty. - EXPECT_EQ(0, message.packed_int32_size ()); - EXPECT_EQ(0, message.packed_int64_size ()); - EXPECT_EQ(0, message.packed_uint32_size ()); - EXPECT_EQ(0, message.packed_uint64_size ()); - EXPECT_EQ(0, message.packed_sint32_size ()); - EXPECT_EQ(0, message.packed_sint64_size ()); - EXPECT_EQ(0, message.packed_fixed32_size ()); - EXPECT_EQ(0, message.packed_fixed64_size ()); - EXPECT_EQ(0, message.packed_sfixed32_size()); - EXPECT_EQ(0, message.packed_sfixed64_size()); - EXPECT_EQ(0, message.packed_float_size ()); - EXPECT_EQ(0, message.packed_double_size ()); - EXPECT_EQ(0, message.packed_bool_size ()); - EXPECT_EQ(0, message.packed_enum_size ()); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedFieldsModified( - const unittest::TestPackedTypes& message) { - // Do the same for packed repeated fields. - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_EQ(true , message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_BAR, message.packed_enum(0)); - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.packed_int32 (1)); - EXPECT_EQ(802 , message.packed_int64 (1)); - EXPECT_EQ(803 , message.packed_uint32 (1)); - EXPECT_EQ(804 , message.packed_uint64 (1)); - EXPECT_EQ(805 , message.packed_sint32 (1)); - EXPECT_EQ(806 , message.packed_sint64 (1)); - EXPECT_EQ(807 , message.packed_fixed32 (1)); - EXPECT_EQ(808 , message.packed_fixed64 (1)); - EXPECT_EQ(809 , message.packed_sfixed32(1)); - EXPECT_EQ(810 , message.packed_sfixed64(1)); - EXPECT_EQ(811 , message.packed_float (1)); - EXPECT_EQ(812 , message.packed_double (1)); - EXPECT_EQ(true , message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_FOO, message.packed_enum(1)); -} - -// =================================================================== -// Extensions -// -// All this code is exactly equivalent to the above code except that it's -// manipulating extension fields instead of normal ones. -// -// I gave up on the 80-char limit here. Sorry. - -void TestUtil::SetAllExtensions(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::optional_int32_extension , 101); - message->SetExtension(unittest::optional_int64_extension , 102); - message->SetExtension(unittest::optional_uint32_extension , 103); - message->SetExtension(unittest::optional_uint64_extension , 104); - message->SetExtension(unittest::optional_sint32_extension , 105); - message->SetExtension(unittest::optional_sint64_extension , 106); - message->SetExtension(unittest::optional_fixed32_extension , 107); - message->SetExtension(unittest::optional_fixed64_extension , 108); - message->SetExtension(unittest::optional_sfixed32_extension, 109); - message->SetExtension(unittest::optional_sfixed64_extension, 110); - message->SetExtension(unittest::optional_float_extension , 111); - message->SetExtension(unittest::optional_double_extension , 112); - message->SetExtension(unittest::optional_bool_extension , true); - message->SetExtension(unittest::optional_string_extension , "115"); - message->SetExtension(unittest::optional_bytes_extension , "116"); - - message->MutableExtension(unittest::optionalgroup_extension )->set_a(117); - message->MutableExtension(unittest::optional_nested_message_extension )->set_bb(118); - message->MutableExtension(unittest::optional_foreign_message_extension)->set_c(119); - message->MutableExtension(unittest::optional_import_message_extension )->set_d(120); - - message->SetExtension(unittest::optional_nested_enum_extension , unittest::TestAllTypes::BAZ); - message->SetExtension(unittest::optional_foreign_enum_extension, unittest::FOREIGN_BAZ ); - message->SetExtension(unittest::optional_import_enum_extension , unittest_import::IMPORT_BAZ); - - message->SetExtension(unittest::optional_string_piece_extension, "124"); - message->SetExtension(unittest::optional_cord_extension, "125"); - - // ----------------------------------------------------------------- - - message->AddExtension(unittest::repeated_int32_extension , 201); - message->AddExtension(unittest::repeated_int64_extension , 202); - message->AddExtension(unittest::repeated_uint32_extension , 203); - message->AddExtension(unittest::repeated_uint64_extension , 204); - message->AddExtension(unittest::repeated_sint32_extension , 205); - message->AddExtension(unittest::repeated_sint64_extension , 206); - message->AddExtension(unittest::repeated_fixed32_extension , 207); - message->AddExtension(unittest::repeated_fixed64_extension , 208); - message->AddExtension(unittest::repeated_sfixed32_extension, 209); - message->AddExtension(unittest::repeated_sfixed64_extension, 210); - message->AddExtension(unittest::repeated_float_extension , 211); - message->AddExtension(unittest::repeated_double_extension , 212); - message->AddExtension(unittest::repeated_bool_extension , true); - message->AddExtension(unittest::repeated_string_extension , "215"); - message->AddExtension(unittest::repeated_bytes_extension , "216"); - - message->AddExtension(unittest::repeatedgroup_extension )->set_a(217); - message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(218); - message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(219); - message->AddExtension(unittest::repeated_import_message_extension )->set_d(220); - - message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAR); - message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAR ); - message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAR); - - message->AddExtension(unittest::repeated_string_piece_extension, "224"); - message->AddExtension(unittest::repeated_cord_extension, "225"); - - // Add a second one of each field. - message->AddExtension(unittest::repeated_int32_extension , 301); - message->AddExtension(unittest::repeated_int64_extension , 302); - message->AddExtension(unittest::repeated_uint32_extension , 303); - message->AddExtension(unittest::repeated_uint64_extension , 304); - message->AddExtension(unittest::repeated_sint32_extension , 305); - message->AddExtension(unittest::repeated_sint64_extension , 306); - message->AddExtension(unittest::repeated_fixed32_extension , 307); - message->AddExtension(unittest::repeated_fixed64_extension , 308); - message->AddExtension(unittest::repeated_sfixed32_extension, 309); - message->AddExtension(unittest::repeated_sfixed64_extension, 310); - message->AddExtension(unittest::repeated_float_extension , 311); - message->AddExtension(unittest::repeated_double_extension , 312); - message->AddExtension(unittest::repeated_bool_extension , false); - message->AddExtension(unittest::repeated_string_extension , "315"); - message->AddExtension(unittest::repeated_bytes_extension , "316"); - - message->AddExtension(unittest::repeatedgroup_extension )->set_a(317); - message->AddExtension(unittest::repeated_nested_message_extension )->set_bb(318); - message->AddExtension(unittest::repeated_foreign_message_extension)->set_c(319); - message->AddExtension(unittest::repeated_import_message_extension )->set_d(320); - - message->AddExtension(unittest::repeated_nested_enum_extension , unittest::TestAllTypes::BAZ); - message->AddExtension(unittest::repeated_foreign_enum_extension, unittest::FOREIGN_BAZ ); - message->AddExtension(unittest::repeated_import_enum_extension , unittest_import::IMPORT_BAZ); - - message->AddExtension(unittest::repeated_string_piece_extension, "324"); - message->AddExtension(unittest::repeated_cord_extension, "325"); - - // ----------------------------------------------------------------- - - message->SetExtension(unittest::default_int32_extension , 401); - message->SetExtension(unittest::default_int64_extension , 402); - message->SetExtension(unittest::default_uint32_extension , 403); - message->SetExtension(unittest::default_uint64_extension , 404); - message->SetExtension(unittest::default_sint32_extension , 405); - message->SetExtension(unittest::default_sint64_extension , 406); - message->SetExtension(unittest::default_fixed32_extension , 407); - message->SetExtension(unittest::default_fixed64_extension , 408); - message->SetExtension(unittest::default_sfixed32_extension, 409); - message->SetExtension(unittest::default_sfixed64_extension, 410); - message->SetExtension(unittest::default_float_extension , 411); - message->SetExtension(unittest::default_double_extension , 412); - message->SetExtension(unittest::default_bool_extension , false); - message->SetExtension(unittest::default_string_extension , "415"); - message->SetExtension(unittest::default_bytes_extension , "416"); - - message->SetExtension(unittest::default_nested_enum_extension , unittest::TestAllTypes::FOO); - message->SetExtension(unittest::default_foreign_enum_extension, unittest::FOREIGN_FOO ); - message->SetExtension(unittest::default_import_enum_extension , unittest_import::IMPORT_FOO); - - message->SetExtension(unittest::default_string_piece_extension, "424"); - message->SetExtension(unittest::default_cord_extension, "425"); -} - -// ------------------------------------------------------------------- - -void TestUtil::SetAllFieldsAndExtensions( - unittest::TestFieldOrderings* message) { - GOOGLE_CHECK(message); - message->set_my_int(1); - message->set_my_string("foo"); - message->set_my_float(1.0); - message->SetExtension(unittest::my_extension_int, 23); - message->SetExtension(unittest::my_extension_string, "bar"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyRepeatedExtensions(unittest::TestAllExtensions* message) { - message->SetExtension(unittest::repeated_int32_extension , 1, 501); - message->SetExtension(unittest::repeated_int64_extension , 1, 502); - message->SetExtension(unittest::repeated_uint32_extension , 1, 503); - message->SetExtension(unittest::repeated_uint64_extension , 1, 504); - message->SetExtension(unittest::repeated_sint32_extension , 1, 505); - message->SetExtension(unittest::repeated_sint64_extension , 1, 506); - message->SetExtension(unittest::repeated_fixed32_extension , 1, 507); - message->SetExtension(unittest::repeated_fixed64_extension , 1, 508); - message->SetExtension(unittest::repeated_sfixed32_extension, 1, 509); - message->SetExtension(unittest::repeated_sfixed64_extension, 1, 510); - message->SetExtension(unittest::repeated_float_extension , 1, 511); - message->SetExtension(unittest::repeated_double_extension , 1, 512); - message->SetExtension(unittest::repeated_bool_extension , 1, true); - message->SetExtension(unittest::repeated_string_extension , 1, "515"); - message->SetExtension(unittest::repeated_bytes_extension , 1, "516"); - - message->MutableExtension(unittest::repeatedgroup_extension , 1)->set_a(517); - message->MutableExtension(unittest::repeated_nested_message_extension , 1)->set_bb(518); - message->MutableExtension(unittest::repeated_foreign_message_extension, 1)->set_c(519); - message->MutableExtension(unittest::repeated_import_message_extension , 1)->set_d(520); - - message->SetExtension(unittest::repeated_nested_enum_extension , 1, unittest::TestAllTypes::FOO); - message->SetExtension(unittest::repeated_foreign_enum_extension, 1, unittest::FOREIGN_FOO ); - message->SetExtension(unittest::repeated_import_enum_extension , 1, unittest_import::IMPORT_FOO); - - message->SetExtension(unittest::repeated_string_piece_extension, 1, "524"); - message->SetExtension(unittest::repeated_cord_extension, 1, "525"); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllExtensionsSet( - const unittest::TestAllExtensions& message) { - EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed64_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_message_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_message_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_message_extension )); - - EXPECT_TRUE(message.GetExtension(unittest::optionalgroup_extension ).has_a()); - EXPECT_TRUE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb()); - EXPECT_TRUE(message.GetExtension(unittest::optional_foreign_message_extension).has_c()); - EXPECT_TRUE(message.GetExtension(unittest::optional_import_message_extension ).has_d()); - - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_enum_extension )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_enum_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_enum_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::optional_string_piece_extension)); - EXPECT_TRUE(message.HasExtension(unittest::optional_cord_extension)); - - EXPECT_EQ(101 , message.GetExtension(unittest::optional_int32_extension )); - EXPECT_EQ(102 , message.GetExtension(unittest::optional_int64_extension )); - EXPECT_EQ(103 , message.GetExtension(unittest::optional_uint32_extension )); - EXPECT_EQ(104 , message.GetExtension(unittest::optional_uint64_extension )); - EXPECT_EQ(105 , message.GetExtension(unittest::optional_sint32_extension )); - EXPECT_EQ(106 , message.GetExtension(unittest::optional_sint64_extension )); - EXPECT_EQ(107 , message.GetExtension(unittest::optional_fixed32_extension )); - EXPECT_EQ(108 , message.GetExtension(unittest::optional_fixed64_extension )); - EXPECT_EQ(109 , message.GetExtension(unittest::optional_sfixed32_extension)); - EXPECT_EQ(110 , message.GetExtension(unittest::optional_sfixed64_extension)); - EXPECT_EQ(111 , message.GetExtension(unittest::optional_float_extension )); - EXPECT_EQ(112 , message.GetExtension(unittest::optional_double_extension )); - EXPECT_EQ(true , message.GetExtension(unittest::optional_bool_extension )); - EXPECT_EQ("115", message.GetExtension(unittest::optional_string_extension )); - EXPECT_EQ("116", message.GetExtension(unittest::optional_bytes_extension )); - - EXPECT_EQ(117, message.GetExtension(unittest::optionalgroup_extension ).a()); - EXPECT_EQ(118, message.GetExtension(unittest::optional_nested_message_extension ).bb()); - EXPECT_EQ(119, message.GetExtension(unittest::optional_foreign_message_extension).c()); - EXPECT_EQ(120, message.GetExtension(unittest::optional_import_message_extension ).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::optional_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::optional_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::optional_import_enum_extension )); - - EXPECT_EQ("124", message.GetExtension(unittest::optional_string_piece_extension)); - EXPECT_EQ("125", message.GetExtension(unittest::optional_cord_extension)); - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 1)); - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed32_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed64_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_float_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_double_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_string_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::default_nested_enum_extension )); - EXPECT_TRUE(message.HasExtension(unittest::default_foreign_enum_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_import_enum_extension )); - - EXPECT_TRUE(message.HasExtension(unittest::default_string_piece_extension)); - EXPECT_TRUE(message.HasExtension(unittest::default_cord_extension)); - - EXPECT_EQ(401 , message.GetExtension(unittest::default_int32_extension )); - EXPECT_EQ(402 , message.GetExtension(unittest::default_int64_extension )); - EXPECT_EQ(403 , message.GetExtension(unittest::default_uint32_extension )); - EXPECT_EQ(404 , message.GetExtension(unittest::default_uint64_extension )); - EXPECT_EQ(405 , message.GetExtension(unittest::default_sint32_extension )); - EXPECT_EQ(406 , message.GetExtension(unittest::default_sint64_extension )); - EXPECT_EQ(407 , message.GetExtension(unittest::default_fixed32_extension )); - EXPECT_EQ(408 , message.GetExtension(unittest::default_fixed64_extension )); - EXPECT_EQ(409 , message.GetExtension(unittest::default_sfixed32_extension)); - EXPECT_EQ(410 , message.GetExtension(unittest::default_sfixed64_extension)); - EXPECT_EQ(411 , message.GetExtension(unittest::default_float_extension )); - EXPECT_EQ(412 , message.GetExtension(unittest::default_double_extension )); - EXPECT_EQ(false, message.GetExtension(unittest::default_bool_extension )); - EXPECT_EQ("415", message.GetExtension(unittest::default_string_extension )); - EXPECT_EQ("416", message.GetExtension(unittest::default_bytes_extension )); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::default_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::default_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::default_import_enum_extension )); - - EXPECT_EQ("424", message.GetExtension(unittest::default_string_piece_extension)); - EXPECT_EQ("425", message.GetExtension(unittest::default_cord_extension)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectExtensionsClear( - const unittest::TestAllExtensions& message) { - string serialized; - ASSERT_TRUE(message.SerializeToString(&serialized)); - EXPECT_EQ("", serialized); - EXPECT_EQ(0, message.ByteSize()); - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed32_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed64_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_message_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_message_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_message_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_enum_extension )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_enum_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_enum_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_string_piece_extension)); - EXPECT_FALSE(message.HasExtension(unittest::optional_cord_extension)); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed32_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed64_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed32_extension)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed64_extension)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_float_extension )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_double_extension )); - EXPECT_EQ(false, message.GetExtension(unittest::optional_bool_extension )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_string_extension )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_bytes_extension )); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.GetExtension(unittest::optionalgroup_extension ).has_a()); - EXPECT_FALSE(message.GetExtension(unittest::optional_nested_message_extension ).has_bb()); - EXPECT_FALSE(message.GetExtension(unittest::optional_foreign_message_extension).has_c()); - EXPECT_FALSE(message.GetExtension(unittest::optional_import_message_extension ).has_d()); - - EXPECT_EQ(0, message.GetExtension(unittest::optionalgroup_extension ).a()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension ).bb()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_foreign_message_extension).c()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_import_message_extension ).d()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::optional_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::optional_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::optional_import_enum_extension )); - - EXPECT_EQ("", message.GetExtension(unittest::optional_string_piece_extension)); - EXPECT_EQ("", message.GetExtension(unittest::optional_cord_extension)); - - // Repeated fields are empty. - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_message_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_piece_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_cord_extension)); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed32_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed64_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_float_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_double_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_string_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::default_nested_enum_extension )); - EXPECT_FALSE(message.HasExtension(unittest::default_foreign_enum_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_import_enum_extension )); - - EXPECT_FALSE(message.HasExtension(unittest::default_string_piece_extension)); - EXPECT_FALSE(message.HasExtension(unittest::default_cord_extension)); - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.GetExtension(unittest::default_int32_extension )); - EXPECT_EQ( 42 , message.GetExtension(unittest::default_int64_extension )); - EXPECT_EQ( 43 , message.GetExtension(unittest::default_uint32_extension )); - EXPECT_EQ( 44 , message.GetExtension(unittest::default_uint64_extension )); - EXPECT_EQ(-45 , message.GetExtension(unittest::default_sint32_extension )); - EXPECT_EQ( 46 , message.GetExtension(unittest::default_sint64_extension )); - EXPECT_EQ( 47 , message.GetExtension(unittest::default_fixed32_extension )); - EXPECT_EQ( 48 , message.GetExtension(unittest::default_fixed64_extension )); - EXPECT_EQ( 49 , message.GetExtension(unittest::default_sfixed32_extension)); - EXPECT_EQ(-50 , message.GetExtension(unittest::default_sfixed64_extension)); - EXPECT_EQ( 51.5 , message.GetExtension(unittest::default_float_extension )); - EXPECT_EQ( 52e3 , message.GetExtension(unittest::default_double_extension )); - EXPECT_EQ(true , message.GetExtension(unittest::default_bool_extension )); - EXPECT_EQ("hello", message.GetExtension(unittest::default_string_extension )); - EXPECT_EQ("world", message.GetExtension(unittest::default_bytes_extension )); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::default_nested_enum_extension )); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::default_foreign_enum_extension)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::default_import_enum_extension )); - - EXPECT_EQ("abc", message.GetExtension(unittest::default_string_piece_extension)); - EXPECT_EQ("123", message.GetExtension(unittest::default_cord_extension)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensions& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(502 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(503 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(504 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(505 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(506 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(507 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(508 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(509 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(510 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(511 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(512 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("515", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("516", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(517, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(518, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(519, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(520, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - - EXPECT_EQ(unittest::TestAllTypes::FOO, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_FOO , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_FOO, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("524", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("525", message.GetExtension(unittest::repeated_cord_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::SetPackedExtensions(unittest::TestPackedExtensions* message) { - message->AddExtension(unittest::packed_int32_extension , 601); - message->AddExtension(unittest::packed_int64_extension , 602); - message->AddExtension(unittest::packed_uint32_extension , 603); - message->AddExtension(unittest::packed_uint64_extension , 604); - message->AddExtension(unittest::packed_sint32_extension , 605); - message->AddExtension(unittest::packed_sint64_extension , 606); - message->AddExtension(unittest::packed_fixed32_extension , 607); - message->AddExtension(unittest::packed_fixed64_extension , 608); - message->AddExtension(unittest::packed_sfixed32_extension, 609); - message->AddExtension(unittest::packed_sfixed64_extension, 610); - message->AddExtension(unittest::packed_float_extension , 611); - message->AddExtension(unittest::packed_double_extension , 612); - message->AddExtension(unittest::packed_bool_extension , true); - message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAR); - // add a second one of each field - message->AddExtension(unittest::packed_int32_extension , 701); - message->AddExtension(unittest::packed_int64_extension , 702); - message->AddExtension(unittest::packed_uint32_extension , 703); - message->AddExtension(unittest::packed_uint64_extension , 704); - message->AddExtension(unittest::packed_sint32_extension , 705); - message->AddExtension(unittest::packed_sint64_extension , 706); - message->AddExtension(unittest::packed_fixed32_extension , 707); - message->AddExtension(unittest::packed_fixed64_extension , 708); - message->AddExtension(unittest::packed_sfixed32_extension, 709); - message->AddExtension(unittest::packed_sfixed64_extension, 710); - message->AddExtension(unittest::packed_float_extension , 711); - message->AddExtension(unittest::packed_double_extension , 712); - message->AddExtension(unittest::packed_bool_extension , false); - message->AddExtension(unittest::packed_enum_extension, unittest::FOREIGN_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtil::ModifyPackedExtensions(unittest::TestPackedExtensions* message) { - message->SetExtension(unittest::packed_int32_extension , 1, 801); - message->SetExtension(unittest::packed_int64_extension , 1, 802); - message->SetExtension(unittest::packed_uint32_extension , 1, 803); - message->SetExtension(unittest::packed_uint64_extension , 1, 804); - message->SetExtension(unittest::packed_sint32_extension , 1, 805); - message->SetExtension(unittest::packed_sint64_extension , 1, 806); - message->SetExtension(unittest::packed_fixed32_extension , 1, 807); - message->SetExtension(unittest::packed_fixed64_extension , 1, 808); - message->SetExtension(unittest::packed_sfixed32_extension, 1, 809); - message->SetExtension(unittest::packed_sfixed64_extension, 1, 810); - message->SetExtension(unittest::packed_float_extension , 1, 811); - message->SetExtension(unittest::packed_double_extension , 1, 812); - message->SetExtension(unittest::packed_bool_extension , 1, true); - message->SetExtension(unittest::packed_enum_extension , 1, - unittest::FOREIGN_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsSet( - const unittest::TestPackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension )); - - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::packed_enum_extension, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::packed_int32_extension , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::packed_int64_extension , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::packed_uint32_extension , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::packed_uint64_extension , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::packed_sint32_extension , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::packed_sint64_extension , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::packed_fixed32_extension , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::packed_fixed64_extension , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::packed_sfixed32_extension, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::packed_sfixed64_extension, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::packed_float_extension , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::packed_double_extension , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::packed_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAZ, - message.GetExtension(unittest::packed_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsClear( - const unittest::TestPackedExtensions& message) { - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed32_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed64_extension)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension )); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectPackedExtensionsModified( - const unittest::TestPackedExtensions& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension )); - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR, - message.GetExtension(unittest::packed_enum_extension, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.GetExtension(unittest::packed_int32_extension , 1)); - EXPECT_EQ(802 , message.GetExtension(unittest::packed_int64_extension , 1)); - EXPECT_EQ(803 , message.GetExtension(unittest::packed_uint32_extension , 1)); - EXPECT_EQ(804 , message.GetExtension(unittest::packed_uint64_extension , 1)); - EXPECT_EQ(805 , message.GetExtension(unittest::packed_sint32_extension , 1)); - EXPECT_EQ(806 , message.GetExtension(unittest::packed_sint64_extension , 1)); - EXPECT_EQ(807 , message.GetExtension(unittest::packed_fixed32_extension , 1)); - EXPECT_EQ(808 , message.GetExtension(unittest::packed_fixed64_extension , 1)); - EXPECT_EQ(809 , message.GetExtension(unittest::packed_sfixed32_extension, 1)); - EXPECT_EQ(810 , message.GetExtension(unittest::packed_sfixed64_extension, 1)); - EXPECT_EQ(811 , message.GetExtension(unittest::packed_float_extension , 1)); - EXPECT_EQ(812 , message.GetExtension(unittest::packed_double_extension , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_FOO, - message.GetExtension(unittest::packed_enum_extension, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ExpectAllFieldsAndExtensionsInOrder(const string& serialized) { - // We set each field individually, serialize separately, and concatenate all - // the strings in canonical order to determine the expected serialization. - string expected; - unittest::TestFieldOrderings message; - message.set_my_int(1); // Field 1. - message.AppendToString(&expected); - message.Clear(); - message.SetExtension(unittest::my_extension_int, 23); // Field 5. - message.AppendToString(&expected); - message.Clear(); - message.set_my_string("foo"); // Field 11. - message.AppendToString(&expected); - message.Clear(); - message.SetExtension(unittest::my_extension_string, "bar"); // Field 50. - message.AppendToString(&expected); - message.Clear(); - message.set_my_float(1.0); // Field 101. - message.AppendToString(&expected); - message.Clear(); - - // We don't EXPECT_EQ() since we don't want to print raw bytes to stdout. - EXPECT_TRUE(serialized == expected); -} - -void TestUtil::ExpectLastRepeatedsRemoved( - const unittest::TestAllTypes& message) { - ASSERT_EQ(1, message.repeated_int32_size ()); - ASSERT_EQ(1, message.repeated_int64_size ()); - ASSERT_EQ(1, message.repeated_uint32_size ()); - ASSERT_EQ(1, message.repeated_uint64_size ()); - ASSERT_EQ(1, message.repeated_sint32_size ()); - ASSERT_EQ(1, message.repeated_sint64_size ()); - ASSERT_EQ(1, message.repeated_fixed32_size ()); - ASSERT_EQ(1, message.repeated_fixed64_size ()); - ASSERT_EQ(1, message.repeated_sfixed32_size()); - ASSERT_EQ(1, message.repeated_sfixed64_size()); - ASSERT_EQ(1, message.repeated_float_size ()); - ASSERT_EQ(1, message.repeated_double_size ()); - ASSERT_EQ(1, message.repeated_bool_size ()); - ASSERT_EQ(1, message.repeated_string_size ()); - ASSERT_EQ(1, message.repeated_bytes_size ()); - - ASSERT_EQ(1, message.repeatedgroup_size ()); - ASSERT_EQ(1, message.repeated_nested_message_size ()); - ASSERT_EQ(1, message.repeated_foreign_message_size()); - ASSERT_EQ(1, message.repeated_import_message_size ()); - ASSERT_EQ(1, message.repeated_nested_enum_size ()); - ASSERT_EQ(1, message.repeated_foreign_enum_size ()); - ASSERT_EQ(1, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(1, message.repeated_string_piece_size()); - ASSERT_EQ(1, message.repeated_cord_size()); -#endif - - // Test that the remaining element is the correct one. - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (0)); -} - -void TestUtil::ExpectLastRepeatedExtensionsRemoved( - const unittest::TestAllExtensions& message) { - - // Test that one element was removed. - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(1, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(1, message.ExtensionSize(unittest::repeated_cord_extension)); - - // Test that the remaining element is the correct one. - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 0)); -} - -void TestUtil::ExpectRepeatedsSwapped( - const unittest::TestAllTypes& message) { - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - -#ifndef PROTOBUF_TEST_NO_DESCRIPTORS - ASSERT_EQ(2, message.repeated_string_piece_size()); - ASSERT_EQ(2, message.repeated_cord_size()); -#endif - - // Test that the first element and second element are flipped. - EXPECT_EQ(201 , message.repeated_int32 (1)); - EXPECT_EQ(202 , message.repeated_int64 (1)); - EXPECT_EQ(203 , message.repeated_uint32 (1)); - EXPECT_EQ(204 , message.repeated_uint64 (1)); - EXPECT_EQ(205 , message.repeated_sint32 (1)); - EXPECT_EQ(206 , message.repeated_sint64 (1)); - EXPECT_EQ(207 , message.repeated_fixed32 (1)); - EXPECT_EQ(208 , message.repeated_fixed64 (1)); - EXPECT_EQ(209 , message.repeated_sfixed32(1)); - EXPECT_EQ(210 , message.repeated_sfixed64(1)); - EXPECT_EQ(211 , message.repeated_float (1)); - EXPECT_EQ(212 , message.repeated_double (1)); - EXPECT_EQ(true , message.repeated_bool (1)); - EXPECT_EQ("215", message.repeated_string (1)); - EXPECT_EQ("216", message.repeated_bytes (1)); - - EXPECT_EQ(217, message.repeatedgroup (1).a()); - EXPECT_EQ(218, message.repeated_nested_message (1).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(1).c()); - EXPECT_EQ(220, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.repeated_import_enum (1)); - - EXPECT_EQ(301 , message.repeated_int32 (0)); - EXPECT_EQ(302 , message.repeated_int64 (0)); - EXPECT_EQ(303 , message.repeated_uint32 (0)); - EXPECT_EQ(304 , message.repeated_uint64 (0)); - EXPECT_EQ(305 , message.repeated_sint32 (0)); - EXPECT_EQ(306 , message.repeated_sint64 (0)); - EXPECT_EQ(307 , message.repeated_fixed32 (0)); - EXPECT_EQ(308 , message.repeated_fixed64 (0)); - EXPECT_EQ(309 , message.repeated_sfixed32(0)); - EXPECT_EQ(310 , message.repeated_sfixed64(0)); - EXPECT_EQ(311 , message.repeated_float (0)); - EXPECT_EQ(312 , message.repeated_double (0)); - EXPECT_EQ(false, message.repeated_bool (0)); - EXPECT_EQ("315", message.repeated_string (0)); - EXPECT_EQ("316", message.repeated_bytes (0)); - - EXPECT_EQ(317, message.repeatedgroup (0).a()); - EXPECT_EQ(318, message.repeated_nested_message (0).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(0).c()); - EXPECT_EQ(320, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.repeated_import_enum (0)); -} - -void TestUtil::ExpectRepeatedExtensionsSwapped( - const unittest::TestAllExtensions& message) { - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_piece_extension)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_cord_extension)); - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension , 1)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension , 1)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension , 1)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension , 1)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension , 1)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension , 1)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension , 1)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension , 1)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension, 1)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension, 1)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension , 1)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension , 1)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension , 1)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension , 1)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension , 1).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension , 1).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension, 1).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension , 1).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAR, message.GetExtension(unittest::repeated_nested_enum_extension , 1)); - EXPECT_EQ(unittest::FOREIGN_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension, 1)); - EXPECT_EQ(unittest_import::IMPORT_BAR, message.GetExtension(unittest::repeated_import_enum_extension , 1)); - - EXPECT_EQ("224", message.GetExtension(unittest::repeated_string_piece_extension, 1)); - EXPECT_EQ("225", message.GetExtension(unittest::repeated_cord_extension, 1)); - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension , 0)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension , 0)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension , 0)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension , 0)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension , 0)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension , 0)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension , 0)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension , 0)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension, 0)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension, 0)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension , 0)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension , 0)); - EXPECT_EQ(false, message.GetExtension(unittest::repeated_bool_extension , 0)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension , 0)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension , 0)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension , 0).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension , 0).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension, 0).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension , 0).d()); - - EXPECT_EQ(unittest::TestAllTypes::BAZ, message.GetExtension(unittest::repeated_nested_enum_extension , 0)); - EXPECT_EQ(unittest::FOREIGN_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension, 0)); - EXPECT_EQ(unittest_import::IMPORT_BAZ, message.GetExtension(unittest::repeated_import_enum_extension , 0)); - - EXPECT_EQ("324", message.GetExtension(unittest::repeated_string_piece_extension, 0)); - EXPECT_EQ("325", message.GetExtension(unittest::repeated_cord_extension, 0)); -} - -// =================================================================== - -TestUtil::ReflectionTester::ReflectionTester( - const Descriptor* base_descriptor) - : base_descriptor_(base_descriptor) { - - const DescriptorPool* pool = base_descriptor->file()->pool(); - - nested_b_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.NestedMessage.bb"); - foreign_c_ = - pool->FindFieldByName("protobuf_unittest.ForeignMessage.c"); - import_d_ = - pool->FindFieldByName("protobuf_unittest_import.ImportMessage.d"); - nested_foo_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.FOO"); - nested_bar_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAR"); - nested_baz_ = - pool->FindEnumValueByName("protobuf_unittest.TestAllTypes.BAZ"); - foreign_foo_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_FOO"); - foreign_bar_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAR"); - foreign_baz_ = - pool->FindEnumValueByName("protobuf_unittest.FOREIGN_BAZ"); - import_foo_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_FOO"); - import_bar_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAR"); - import_baz_ = - pool->FindEnumValueByName("protobuf_unittest_import.IMPORT_BAZ"); - - if (base_descriptor_->name() == "TestAllExtensions") { - group_a_ = - pool->FindFieldByName("protobuf_unittest.OptionalGroup_extension.a"); - repeated_group_a_ = - pool->FindFieldByName("protobuf_unittest.RepeatedGroup_extension.a"); - } else { - group_a_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.OptionalGroup.a"); - repeated_group_a_ = - pool->FindFieldByName("protobuf_unittest.TestAllTypes.RepeatedGroup.a"); - } - - EXPECT_TRUE(group_a_ != NULL); - EXPECT_TRUE(repeated_group_a_ != NULL); - EXPECT_TRUE(nested_b_ != NULL); - EXPECT_TRUE(foreign_c_ != NULL); - EXPECT_TRUE(import_d_ != NULL); - EXPECT_TRUE(nested_foo_ != NULL); - EXPECT_TRUE(nested_bar_ != NULL); - EXPECT_TRUE(nested_baz_ != NULL); - EXPECT_TRUE(foreign_foo_ != NULL); - EXPECT_TRUE(foreign_bar_ != NULL); - EXPECT_TRUE(foreign_baz_ != NULL); - EXPECT_TRUE(import_foo_ != NULL); - EXPECT_TRUE(import_bar_ != NULL); - EXPECT_TRUE(import_baz_ != NULL); -} - -// Shorthand to get a FieldDescriptor for a field of unittest::TestAllTypes. -const FieldDescriptor* TestUtil::ReflectionTester::F(const string& name) { - const FieldDescriptor* result = NULL; - if (base_descriptor_->name() == "TestAllExtensions" || - base_descriptor_->name() == "TestPackedExtensions") { - result = base_descriptor_->file()->FindExtensionByName(name + "_extension"); - } else { - result = base_descriptor_->FindFieldByName(name); - } - GOOGLE_CHECK(result != NULL); - return result; -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::SetAllFieldsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - Message* sub_message; - - reflection->SetInt32 (message, F("optional_int32" ), 101); - reflection->SetInt64 (message, F("optional_int64" ), 102); - reflection->SetUInt32(message, F("optional_uint32" ), 103); - reflection->SetUInt64(message, F("optional_uint64" ), 104); - reflection->SetInt32 (message, F("optional_sint32" ), 105); - reflection->SetInt64 (message, F("optional_sint64" ), 106); - reflection->SetUInt32(message, F("optional_fixed32" ), 107); - reflection->SetUInt64(message, F("optional_fixed64" ), 108); - reflection->SetInt32 (message, F("optional_sfixed32"), 109); - reflection->SetInt64 (message, F("optional_sfixed64"), 110); - reflection->SetFloat (message, F("optional_float" ), 111); - reflection->SetDouble(message, F("optional_double" ), 112); - reflection->SetBool (message, F("optional_bool" ), true); - reflection->SetString(message, F("optional_string" ), "115"); - reflection->SetString(message, F("optional_bytes" ), "116"); - - sub_message = reflection->MutableMessage(message, F("optionalgroup")); - sub_message->GetReflection()->SetInt32(sub_message, group_a_, 117); - sub_message = reflection->MutableMessage(message, F("optional_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 118); - sub_message = reflection->MutableMessage(message, F("optional_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 119); - sub_message = reflection->MutableMessage(message, F("optional_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 120); - - reflection->SetEnum(message, F("optional_nested_enum" ), nested_baz_); - reflection->SetEnum(message, F("optional_foreign_enum"), foreign_baz_); - reflection->SetEnum(message, F("optional_import_enum" ), import_baz_); - - reflection->SetString(message, F("optional_string_piece"), "124"); - reflection->SetString(message, F("optional_cord"), "125"); - - // ----------------------------------------------------------------- - - reflection->AddInt32 (message, F("repeated_int32" ), 201); - reflection->AddInt64 (message, F("repeated_int64" ), 202); - reflection->AddUInt32(message, F("repeated_uint32" ), 203); - reflection->AddUInt64(message, F("repeated_uint64" ), 204); - reflection->AddInt32 (message, F("repeated_sint32" ), 205); - reflection->AddInt64 (message, F("repeated_sint64" ), 206); - reflection->AddUInt32(message, F("repeated_fixed32" ), 207); - reflection->AddUInt64(message, F("repeated_fixed64" ), 208); - reflection->AddInt32 (message, F("repeated_sfixed32"), 209); - reflection->AddInt64 (message, F("repeated_sfixed64"), 210); - reflection->AddFloat (message, F("repeated_float" ), 211); - reflection->AddDouble(message, F("repeated_double" ), 212); - reflection->AddBool (message, F("repeated_bool" ), true); - reflection->AddString(message, F("repeated_string" ), "215"); - reflection->AddString(message, F("repeated_bytes" ), "216"); - - sub_message = reflection->AddMessage(message, F("repeatedgroup")); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 217); - sub_message = reflection->AddMessage(message, F("repeated_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 218); - sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 219); - sub_message = reflection->AddMessage(message, F("repeated_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 220); - - reflection->AddEnum(message, F("repeated_nested_enum" ), nested_bar_); - reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_bar_); - reflection->AddEnum(message, F("repeated_import_enum" ), import_bar_); - - reflection->AddString(message, F("repeated_string_piece"), "224"); - reflection->AddString(message, F("repeated_cord"), "225"); - - // Add a second one of each field. - reflection->AddInt32 (message, F("repeated_int32" ), 301); - reflection->AddInt64 (message, F("repeated_int64" ), 302); - reflection->AddUInt32(message, F("repeated_uint32" ), 303); - reflection->AddUInt64(message, F("repeated_uint64" ), 304); - reflection->AddInt32 (message, F("repeated_sint32" ), 305); - reflection->AddInt64 (message, F("repeated_sint64" ), 306); - reflection->AddUInt32(message, F("repeated_fixed32" ), 307); - reflection->AddUInt64(message, F("repeated_fixed64" ), 308); - reflection->AddInt32 (message, F("repeated_sfixed32"), 309); - reflection->AddInt64 (message, F("repeated_sfixed64"), 310); - reflection->AddFloat (message, F("repeated_float" ), 311); - reflection->AddDouble(message, F("repeated_double" ), 312); - reflection->AddBool (message, F("repeated_bool" ), false); - reflection->AddString(message, F("repeated_string" ), "315"); - reflection->AddString(message, F("repeated_bytes" ), "316"); - - sub_message = reflection->AddMessage(message, F("repeatedgroup")); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 317); - sub_message = reflection->AddMessage(message, F("repeated_nested_message")); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 318); - sub_message = reflection->AddMessage(message, F("repeated_foreign_message")); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 319); - sub_message = reflection->AddMessage(message, F("repeated_import_message")); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 320); - - reflection->AddEnum(message, F("repeated_nested_enum" ), nested_baz_); - reflection->AddEnum(message, F("repeated_foreign_enum"), foreign_baz_); - reflection->AddEnum(message, F("repeated_import_enum" ), import_baz_); - - reflection->AddString(message, F("repeated_string_piece"), "324"); - reflection->AddString(message, F("repeated_cord"), "325"); - - // ----------------------------------------------------------------- - - reflection->SetInt32 (message, F("default_int32" ), 401); - reflection->SetInt64 (message, F("default_int64" ), 402); - reflection->SetUInt32(message, F("default_uint32" ), 403); - reflection->SetUInt64(message, F("default_uint64" ), 404); - reflection->SetInt32 (message, F("default_sint32" ), 405); - reflection->SetInt64 (message, F("default_sint64" ), 406); - reflection->SetUInt32(message, F("default_fixed32" ), 407); - reflection->SetUInt64(message, F("default_fixed64" ), 408); - reflection->SetInt32 (message, F("default_sfixed32"), 409); - reflection->SetInt64 (message, F("default_sfixed64"), 410); - reflection->SetFloat (message, F("default_float" ), 411); - reflection->SetDouble(message, F("default_double" ), 412); - reflection->SetBool (message, F("default_bool" ), false); - reflection->SetString(message, F("default_string" ), "415"); - reflection->SetString(message, F("default_bytes" ), "416"); - - reflection->SetEnum(message, F("default_nested_enum" ), nested_foo_); - reflection->SetEnum(message, F("default_foreign_enum"), foreign_foo_); - reflection->SetEnum(message, F("default_import_enum" ), import_foo_); - - reflection->SetString(message, F("default_string_piece"), "424"); - reflection->SetString(message, F("default_cord"), "425"); -} - -void TestUtil::ReflectionTester::SetPackedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - reflection->AddInt32 (message, F("packed_int32" ), 601); - reflection->AddInt64 (message, F("packed_int64" ), 602); - reflection->AddUInt32(message, F("packed_uint32" ), 603); - reflection->AddUInt64(message, F("packed_uint64" ), 604); - reflection->AddInt32 (message, F("packed_sint32" ), 605); - reflection->AddInt64 (message, F("packed_sint64" ), 606); - reflection->AddUInt32(message, F("packed_fixed32" ), 607); - reflection->AddUInt64(message, F("packed_fixed64" ), 608); - reflection->AddInt32 (message, F("packed_sfixed32"), 609); - reflection->AddInt64 (message, F("packed_sfixed64"), 610); - reflection->AddFloat (message, F("packed_float" ), 611); - reflection->AddDouble(message, F("packed_double" ), 612); - reflection->AddBool (message, F("packed_bool" ), true); - reflection->AddEnum (message, F("packed_enum" ), foreign_bar_); - - reflection->AddInt32 (message, F("packed_int32" ), 701); - reflection->AddInt64 (message, F("packed_int64" ), 702); - reflection->AddUInt32(message, F("packed_uint32" ), 703); - reflection->AddUInt64(message, F("packed_uint64" ), 704); - reflection->AddInt32 (message, F("packed_sint32" ), 705); - reflection->AddInt64 (message, F("packed_sint64" ), 706); - reflection->AddUInt32(message, F("packed_fixed32" ), 707); - reflection->AddUInt64(message, F("packed_fixed64" ), 708); - reflection->AddInt32 (message, F("packed_sfixed32"), 709); - reflection->AddInt64 (message, F("packed_sfixed64"), 710); - reflection->AddFloat (message, F("packed_float" ), 711); - reflection->AddDouble(message, F("packed_double" ), 712); - reflection->AddBool (message, F("packed_bool" ), false); - reflection->AddEnum (message, F("packed_enum" ), foreign_baz_); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection( - const Message& message) { - // We have to split this into three function otherwise it creates a stack - // frame so large that it triggers a warning. - ExpectAllFieldsSetViaReflection1(message); - ExpectAllFieldsSetViaReflection2(message); - ExpectAllFieldsSetViaReflection3(message); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection1( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - EXPECT_TRUE(reflection->HasField(message, F("optional_int32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_int64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_uint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_uint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_fixed32" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_fixed64" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed32"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_sfixed64"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_float" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_double" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_bool" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_string" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_bytes" ))); - - EXPECT_TRUE(reflection->HasField(message, F("optionalgroup" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_nested_message" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_message"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_import_message" ))); - - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_TRUE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); - - EXPECT_TRUE(reflection->HasField(message, F("optional_nested_enum" ))); - EXPECT_TRUE(reflection->HasField(message, F("optional_foreign_enum"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_import_enum" ))); - - EXPECT_TRUE(reflection->HasField(message, F("optional_string_piece"))); - EXPECT_TRUE(reflection->HasField(message, F("optional_cord"))); - - EXPECT_EQ(101 , reflection->GetInt32 (message, F("optional_int32" ))); - EXPECT_EQ(102 , reflection->GetInt64 (message, F("optional_int64" ))); - EXPECT_EQ(103 , reflection->GetUInt32(message, F("optional_uint32" ))); - EXPECT_EQ(104 , reflection->GetUInt64(message, F("optional_uint64" ))); - EXPECT_EQ(105 , reflection->GetInt32 (message, F("optional_sint32" ))); - EXPECT_EQ(106 , reflection->GetInt64 (message, F("optional_sint64" ))); - EXPECT_EQ(107 , reflection->GetUInt32(message, F("optional_fixed32" ))); - EXPECT_EQ(108 , reflection->GetUInt64(message, F("optional_fixed64" ))); - EXPECT_EQ(109 , reflection->GetInt32 (message, F("optional_sfixed32"))); - EXPECT_EQ(110 , reflection->GetInt64 (message, F("optional_sfixed64"))); - EXPECT_EQ(111 , reflection->GetFloat (message, F("optional_float" ))); - EXPECT_EQ(112 , reflection->GetDouble(message, F("optional_double" ))); - EXPECT_EQ(true , reflection->GetBool (message, F("optional_bool" ))); - EXPECT_EQ("115", reflection->GetString(message, F("optional_string" ))); - EXPECT_EQ("116", reflection->GetString(message, F("optional_bytes" ))); - - EXPECT_EQ("115", reflection->GetStringReference(message, F("optional_string"), &scratch)); - EXPECT_EQ("116", reflection->GetStringReference(message, F("optional_bytes" ), &scratch)); - - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_EQ(117, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_EQ(118, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_EQ(119, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_EQ(120, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - - EXPECT_EQ( nested_baz_, reflection->GetEnum(message, F("optional_nested_enum" ))); - EXPECT_EQ(foreign_baz_, reflection->GetEnum(message, F("optional_foreign_enum"))); - EXPECT_EQ( import_baz_, reflection->GetEnum(message, F("optional_import_enum" ))); - - EXPECT_EQ("124", reflection->GetString(message, F("optional_string_piece"))); - EXPECT_EQ("124", reflection->GetStringReference(message, F("optional_string_piece"), &scratch)); - - EXPECT_EQ("125", reflection->GetString(message, F("optional_cord"))); - EXPECT_EQ("125", reflection->GetStringReference(message, F("optional_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection2( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_int64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_uint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_fixed64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed32"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_sfixed64"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_float" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_double" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bool" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_bytes" ))); - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeatedgroup" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_message"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_message" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_nested_enum" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_foreign_enum" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_import_enum" ))); - - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_string_piece"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("repeated_cord"))); - - EXPECT_EQ(201 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 0)); - EXPECT_EQ(202 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 0)); - EXPECT_EQ(203 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 0)); - EXPECT_EQ(204 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 0)); - EXPECT_EQ(205 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 0)); - EXPECT_EQ(206 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 0)); - EXPECT_EQ(207 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 0)); - EXPECT_EQ(208 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 0)); - EXPECT_EQ(209 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 0)); - EXPECT_EQ(210 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 0)); - EXPECT_EQ(211 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 0)); - EXPECT_EQ(212 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 0)); - EXPECT_EQ(true , reflection->GetRepeatedBool (message, F("repeated_bool" ), 0)); - EXPECT_EQ("215", reflection->GetRepeatedString(message, F("repeated_string" ), 0)); - EXPECT_EQ("216", reflection->GetRepeatedString(message, F("repeated_bytes" ), 0)); - - EXPECT_EQ("215", reflection->GetRepeatedStringReference(message, F("repeated_string"), 0, &scratch)); - EXPECT_EQ("216", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), 0, &scratch)); - - sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 0); - EXPECT_EQ(217, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 0); - EXPECT_EQ(218, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 0); - EXPECT_EQ(219, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 0); - EXPECT_EQ(220, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - - EXPECT_EQ( nested_bar_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),0)); - EXPECT_EQ(foreign_bar_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),0)); - EXPECT_EQ( import_bar_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),0)); - - EXPECT_EQ("224", reflection->GetRepeatedString(message, F("repeated_string_piece"), 0)); - EXPECT_EQ("224", reflection->GetRepeatedStringReference( - message, F("repeated_string_piece"), 0, &scratch)); - - EXPECT_EQ("225", reflection->GetRepeatedString(message, F("repeated_cord"), 0)); - EXPECT_EQ("225", reflection->GetRepeatedStringReference( - message, F("repeated_cord"), 0, &scratch)); - - EXPECT_EQ(301 , reflection->GetRepeatedInt32 (message, F("repeated_int32" ), 1)); - EXPECT_EQ(302 , reflection->GetRepeatedInt64 (message, F("repeated_int64" ), 1)); - EXPECT_EQ(303 , reflection->GetRepeatedUInt32(message, F("repeated_uint32" ), 1)); - EXPECT_EQ(304 , reflection->GetRepeatedUInt64(message, F("repeated_uint64" ), 1)); - EXPECT_EQ(305 , reflection->GetRepeatedInt32 (message, F("repeated_sint32" ), 1)); - EXPECT_EQ(306 , reflection->GetRepeatedInt64 (message, F("repeated_sint64" ), 1)); - EXPECT_EQ(307 , reflection->GetRepeatedUInt32(message, F("repeated_fixed32" ), 1)); - EXPECT_EQ(308 , reflection->GetRepeatedUInt64(message, F("repeated_fixed64" ), 1)); - EXPECT_EQ(309 , reflection->GetRepeatedInt32 (message, F("repeated_sfixed32"), 1)); - EXPECT_EQ(310 , reflection->GetRepeatedInt64 (message, F("repeated_sfixed64"), 1)); - EXPECT_EQ(311 , reflection->GetRepeatedFloat (message, F("repeated_float" ), 1)); - EXPECT_EQ(312 , reflection->GetRepeatedDouble(message, F("repeated_double" ), 1)); - EXPECT_EQ(false, reflection->GetRepeatedBool (message, F("repeated_bool" ), 1)); - EXPECT_EQ("315", reflection->GetRepeatedString(message, F("repeated_string" ), 1)); - EXPECT_EQ("316", reflection->GetRepeatedString(message, F("repeated_bytes" ), 1)); - - EXPECT_EQ("315", reflection->GetRepeatedStringReference(message, F("repeated_string"), - 1, &scratch)); - EXPECT_EQ("316", reflection->GetRepeatedStringReference(message, F("repeated_bytes"), - 1, &scratch)); - - sub_message = &reflection->GetRepeatedMessage(message, F("repeatedgroup"), 1); - EXPECT_EQ(317, sub_message->GetReflection()->GetInt32(*sub_message, repeated_group_a_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_nested_message"), 1); - EXPECT_EQ(318, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_foreign_message"), 1); - EXPECT_EQ(319, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetRepeatedMessage(message, F("repeated_import_message"), 1); - EXPECT_EQ(320, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - - EXPECT_EQ( nested_baz_, reflection->GetRepeatedEnum(message, F("repeated_nested_enum" ),1)); - EXPECT_EQ(foreign_baz_, reflection->GetRepeatedEnum(message, F("repeated_foreign_enum"),1)); - EXPECT_EQ( import_baz_, reflection->GetRepeatedEnum(message, F("repeated_import_enum" ),1)); - - EXPECT_EQ("324", reflection->GetRepeatedString(message, F("repeated_string_piece"), 1)); - EXPECT_EQ("324", reflection->GetRepeatedStringReference( - message, F("repeated_string_piece"), 1, &scratch)); - - EXPECT_EQ("325", reflection->GetRepeatedString(message, F("repeated_cord"), 1)); - EXPECT_EQ("325", reflection->GetRepeatedStringReference( - message, F("repeated_cord"), 1, &scratch)); -} - -void TestUtil::ReflectionTester::ExpectAllFieldsSetViaReflection3( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - - // ----------------------------------------------------------------- - - EXPECT_TRUE(reflection->HasField(message, F("default_int32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_int64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_uint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_uint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sint32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sint64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_fixed32" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_fixed64" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_sfixed32"))); - EXPECT_TRUE(reflection->HasField(message, F("default_sfixed64"))); - EXPECT_TRUE(reflection->HasField(message, F("default_float" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_double" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_bool" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_string" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_bytes" ))); - - EXPECT_TRUE(reflection->HasField(message, F("default_nested_enum" ))); - EXPECT_TRUE(reflection->HasField(message, F("default_foreign_enum"))); - EXPECT_TRUE(reflection->HasField(message, F("default_import_enum" ))); - - EXPECT_TRUE(reflection->HasField(message, F("default_string_piece"))); - EXPECT_TRUE(reflection->HasField(message, F("default_cord"))); - - EXPECT_EQ(401 , reflection->GetInt32 (message, F("default_int32" ))); - EXPECT_EQ(402 , reflection->GetInt64 (message, F("default_int64" ))); - EXPECT_EQ(403 , reflection->GetUInt32(message, F("default_uint32" ))); - EXPECT_EQ(404 , reflection->GetUInt64(message, F("default_uint64" ))); - EXPECT_EQ(405 , reflection->GetInt32 (message, F("default_sint32" ))); - EXPECT_EQ(406 , reflection->GetInt64 (message, F("default_sint64" ))); - EXPECT_EQ(407 , reflection->GetUInt32(message, F("default_fixed32" ))); - EXPECT_EQ(408 , reflection->GetUInt64(message, F("default_fixed64" ))); - EXPECT_EQ(409 , reflection->GetInt32 (message, F("default_sfixed32"))); - EXPECT_EQ(410 , reflection->GetInt64 (message, F("default_sfixed64"))); - EXPECT_EQ(411 , reflection->GetFloat (message, F("default_float" ))); - EXPECT_EQ(412 , reflection->GetDouble(message, F("default_double" ))); - EXPECT_EQ(false, reflection->GetBool (message, F("default_bool" ))); - EXPECT_EQ("415", reflection->GetString(message, F("default_string" ))); - EXPECT_EQ("416", reflection->GetString(message, F("default_bytes" ))); - - EXPECT_EQ("415", reflection->GetStringReference(message, F("default_string"), &scratch)); - EXPECT_EQ("416", reflection->GetStringReference(message, F("default_bytes" ), &scratch)); - - EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("default_nested_enum" ))); - EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("default_foreign_enum"))); - EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("default_import_enum" ))); - - EXPECT_EQ("424", reflection->GetString(message, F("default_string_piece"))); - EXPECT_EQ("424", reflection->GetStringReference(message, F("default_string_piece"), - &scratch)); - - EXPECT_EQ("425", reflection->GetString(message, F("default_cord"))); - EXPECT_EQ("425", reflection->GetStringReference(message, F("default_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectPackedFieldsSetViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_int64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_uint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sint64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed32" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_fixed64" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed32"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_sfixed64"))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_float" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_double" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_bool" ))); - ASSERT_EQ(2, reflection->FieldSize(message, F("packed_enum" ))); - - EXPECT_EQ(601 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 0)); - EXPECT_EQ(602 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 0)); - EXPECT_EQ(603 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 0)); - EXPECT_EQ(604 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 0)); - EXPECT_EQ(605 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 0)); - EXPECT_EQ(606 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 0)); - EXPECT_EQ(607 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 0)); - EXPECT_EQ(608 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 0)); - EXPECT_EQ(609 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 0)); - EXPECT_EQ(610 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 0)); - EXPECT_EQ(611 , reflection->GetRepeatedFloat (message, F("packed_float" ), 0)); - EXPECT_EQ(612 , reflection->GetRepeatedDouble(message, F("packed_double" ), 0)); - EXPECT_EQ(true , reflection->GetRepeatedBool (message, F("packed_bool" ), 0)); - EXPECT_EQ(foreign_bar_, - reflection->GetRepeatedEnum(message, F("packed_enum"), 0)); - - EXPECT_EQ(701 , reflection->GetRepeatedInt32 (message, F("packed_int32" ), 1)); - EXPECT_EQ(702 , reflection->GetRepeatedInt64 (message, F("packed_int64" ), 1)); - EXPECT_EQ(703 , reflection->GetRepeatedUInt32(message, F("packed_uint32" ), 1)); - EXPECT_EQ(704 , reflection->GetRepeatedUInt64(message, F("packed_uint64" ), 1)); - EXPECT_EQ(705 , reflection->GetRepeatedInt32 (message, F("packed_sint32" ), 1)); - EXPECT_EQ(706 , reflection->GetRepeatedInt64 (message, F("packed_sint64" ), 1)); - EXPECT_EQ(707 , reflection->GetRepeatedUInt32(message, F("packed_fixed32" ), 1)); - EXPECT_EQ(708 , reflection->GetRepeatedUInt64(message, F("packed_fixed64" ), 1)); - EXPECT_EQ(709 , reflection->GetRepeatedInt32 (message, F("packed_sfixed32"), 1)); - EXPECT_EQ(710 , reflection->GetRepeatedInt64 (message, F("packed_sfixed64"), 1)); - EXPECT_EQ(711 , reflection->GetRepeatedFloat (message, F("packed_float" ), 1)); - EXPECT_EQ(712 , reflection->GetRepeatedDouble(message, F("packed_double" ), 1)); - EXPECT_EQ(false, reflection->GetRepeatedBool (message, F("packed_bool" ), 1)); - EXPECT_EQ(foreign_baz_, - reflection->GetRepeatedEnum(message, F("packed_enum"), 1)); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ExpectClearViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - string scratch; - const Message* sub_message; - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(reflection->HasField(message, F("optional_int32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_int64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_uint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_uint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_fixed32" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_fixed64" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed32"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_sfixed64"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_float" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_double" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_bool" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_string" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_bytes" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optionalgroup" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_nested_message" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_message"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_import_message" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optional_nested_enum" ))); - EXPECT_FALSE(reflection->HasField(message, F("optional_foreign_enum"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_import_enum" ))); - - EXPECT_FALSE(reflection->HasField(message, F("optional_string_piece"))); - EXPECT_FALSE(reflection->HasField(message, F("optional_cord"))); - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_int32" ))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_int64" ))); - EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_uint32" ))); - EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_uint64" ))); - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sint32" ))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sint64" ))); - EXPECT_EQ(0 , reflection->GetUInt32(message, F("optional_fixed32" ))); - EXPECT_EQ(0 , reflection->GetUInt64(message, F("optional_fixed64" ))); - EXPECT_EQ(0 , reflection->GetInt32 (message, F("optional_sfixed32"))); - EXPECT_EQ(0 , reflection->GetInt64 (message, F("optional_sfixed64"))); - EXPECT_EQ(0 , reflection->GetFloat (message, F("optional_float" ))); - EXPECT_EQ(0 , reflection->GetDouble(message, F("optional_double" ))); - EXPECT_EQ(false, reflection->GetBool (message, F("optional_bool" ))); - EXPECT_EQ("" , reflection->GetString(message, F("optional_string" ))); - EXPECT_EQ("" , reflection->GetString(message, F("optional_bytes" ))); - - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string"), &scratch)); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_bytes" ), &scratch)); - - // Embedded messages should also be clear. - sub_message = &reflection->GetMessage(message, F("optionalgroup")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, group_a_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, group_a_)); - sub_message = &reflection->GetMessage(message, F("optional_nested_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, nested_b_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, nested_b_)); - sub_message = &reflection->GetMessage(message, F("optional_foreign_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, foreign_c_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, foreign_c_)); - sub_message = &reflection->GetMessage(message, F("optional_import_message")); - EXPECT_FALSE(sub_message->GetReflection()->HasField(*sub_message, import_d_)); - EXPECT_EQ(0, sub_message->GetReflection()->GetInt32(*sub_message, import_d_)); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ( nested_foo_, reflection->GetEnum(message, F("optional_nested_enum" ))); - EXPECT_EQ(foreign_foo_, reflection->GetEnum(message, F("optional_foreign_enum"))); - EXPECT_EQ( import_foo_, reflection->GetEnum(message, F("optional_import_enum" ))); - - EXPECT_EQ("", reflection->GetString(message, F("optional_string_piece"))); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_string_piece"), &scratch)); - - EXPECT_EQ("", reflection->GetString(message, F("optional_cord"))); - EXPECT_EQ("", reflection->GetStringReference(message, F("optional_cord"), &scratch)); - - // Repeated fields are empty. - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_int64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_uint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_fixed64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed32"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_sfixed64"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_float" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_double" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bool" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_bytes" ))); - - EXPECT_EQ(0, reflection->FieldSize(message, F("repeatedgroup" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_message"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_message" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_nested_enum" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_foreign_enum" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_import_enum" ))); - - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_string_piece"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("repeated_cord"))); - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(reflection->HasField(message, F("default_int32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_int64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_uint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_uint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sint32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sint64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_fixed32" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_fixed64" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_sfixed32"))); - EXPECT_FALSE(reflection->HasField(message, F("default_sfixed64"))); - EXPECT_FALSE(reflection->HasField(message, F("default_float" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_double" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_bool" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_string" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_bytes" ))); - - EXPECT_FALSE(reflection->HasField(message, F("default_nested_enum" ))); - EXPECT_FALSE(reflection->HasField(message, F("default_foreign_enum"))); - EXPECT_FALSE(reflection->HasField(message, F("default_import_enum" ))); - - EXPECT_FALSE(reflection->HasField(message, F("default_string_piece"))); - EXPECT_FALSE(reflection->HasField(message, F("default_cord"))); - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , reflection->GetInt32 (message, F("default_int32" ))); - EXPECT_EQ( 42 , reflection->GetInt64 (message, F("default_int64" ))); - EXPECT_EQ( 43 , reflection->GetUInt32(message, F("default_uint32" ))); - EXPECT_EQ( 44 , reflection->GetUInt64(message, F("default_uint64" ))); - EXPECT_EQ(-45 , reflection->GetInt32 (message, F("default_sint32" ))); - EXPECT_EQ( 46 , reflection->GetInt64 (message, F("default_sint64" ))); - EXPECT_EQ( 47 , reflection->GetUInt32(message, F("default_fixed32" ))); - EXPECT_EQ( 48 , reflection->GetUInt64(message, F("default_fixed64" ))); - EXPECT_EQ( 49 , reflection->GetInt32 (message, F("default_sfixed32"))); - EXPECT_EQ(-50 , reflection->GetInt64 (message, F("default_sfixed64"))); - EXPECT_EQ( 51.5 , reflection->GetFloat (message, F("default_float" ))); - EXPECT_EQ( 52e3 , reflection->GetDouble(message, F("default_double" ))); - EXPECT_EQ(true , reflection->GetBool (message, F("default_bool" ))); - EXPECT_EQ("hello", reflection->GetString(message, F("default_string" ))); - EXPECT_EQ("world", reflection->GetString(message, F("default_bytes" ))); - - EXPECT_EQ("hello", reflection->GetStringReference(message, F("default_string"), &scratch)); - EXPECT_EQ("world", reflection->GetStringReference(message, F("default_bytes" ), &scratch)); - - EXPECT_EQ( nested_bar_, reflection->GetEnum(message, F("default_nested_enum" ))); - EXPECT_EQ(foreign_bar_, reflection->GetEnum(message, F("default_foreign_enum"))); - EXPECT_EQ( import_bar_, reflection->GetEnum(message, F("default_import_enum" ))); - - EXPECT_EQ("abc", reflection->GetString(message, F("default_string_piece"))); - EXPECT_EQ("abc", reflection->GetStringReference(message, F("default_string_piece"), &scratch)); - - EXPECT_EQ("123", reflection->GetString(message, F("default_cord"))); - EXPECT_EQ("123", reflection->GetStringReference(message, F("default_cord"), &scratch)); -} - -void TestUtil::ReflectionTester::ExpectPackedClearViaReflection( - const Message& message) { - const Reflection* reflection = message.GetReflection(); - - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_int64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_uint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sint64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed32" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_fixed64" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed32"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_sfixed64"))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_float" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_double" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_bool" ))); - EXPECT_EQ(0, reflection->FieldSize(message, F("packed_enum" ))); -} - -// ------------------------------------------------------------------- - -void TestUtil::ReflectionTester::ModifyRepeatedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - Message* sub_message; - - reflection->SetRepeatedInt32 (message, F("repeated_int32" ), 1, 501); - reflection->SetRepeatedInt64 (message, F("repeated_int64" ), 1, 502); - reflection->SetRepeatedUInt32(message, F("repeated_uint32" ), 1, 503); - reflection->SetRepeatedUInt64(message, F("repeated_uint64" ), 1, 504); - reflection->SetRepeatedInt32 (message, F("repeated_sint32" ), 1, 505); - reflection->SetRepeatedInt64 (message, F("repeated_sint64" ), 1, 506); - reflection->SetRepeatedUInt32(message, F("repeated_fixed32" ), 1, 507); - reflection->SetRepeatedUInt64(message, F("repeated_fixed64" ), 1, 508); - reflection->SetRepeatedInt32 (message, F("repeated_sfixed32"), 1, 509); - reflection->SetRepeatedInt64 (message, F("repeated_sfixed64"), 1, 510); - reflection->SetRepeatedFloat (message, F("repeated_float" ), 1, 511); - reflection->SetRepeatedDouble(message, F("repeated_double" ), 1, 512); - reflection->SetRepeatedBool (message, F("repeated_bool" ), 1, true); - reflection->SetRepeatedString(message, F("repeated_string" ), 1, "515"); - reflection->SetRepeatedString(message, F("repeated_bytes" ), 1, "516"); - - sub_message = reflection->MutableRepeatedMessage(message, F("repeatedgroup"), 1); - sub_message->GetReflection()->SetInt32(sub_message, repeated_group_a_, 517); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_nested_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, nested_b_, 518); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_foreign_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, foreign_c_, 519); - sub_message = reflection->MutableRepeatedMessage(message, F("repeated_import_message"), 1); - sub_message->GetReflection()->SetInt32(sub_message, import_d_, 520); - - reflection->SetRepeatedEnum(message, F("repeated_nested_enum" ), 1, nested_foo_); - reflection->SetRepeatedEnum(message, F("repeated_foreign_enum"), 1, foreign_foo_); - reflection->SetRepeatedEnum(message, F("repeated_import_enum" ), 1, import_foo_); - - reflection->SetRepeatedString(message, F("repeated_string_piece"), 1, "524"); - reflection->SetRepeatedString(message, F("repeated_cord"), 1, "525"); -} - -void TestUtil::ReflectionTester::ModifyPackedFieldsViaReflection( - Message* message) { - const Reflection* reflection = message->GetReflection(); - reflection->SetRepeatedInt32 (message, F("packed_int32" ), 1, 801); - reflection->SetRepeatedInt64 (message, F("packed_int64" ), 1, 802); - reflection->SetRepeatedUInt32(message, F("packed_uint32" ), 1, 803); - reflection->SetRepeatedUInt64(message, F("packed_uint64" ), 1, 804); - reflection->SetRepeatedInt32 (message, F("packed_sint32" ), 1, 805); - reflection->SetRepeatedInt64 (message, F("packed_sint64" ), 1, 806); - reflection->SetRepeatedUInt32(message, F("packed_fixed32" ), 1, 807); - reflection->SetRepeatedUInt64(message, F("packed_fixed64" ), 1, 808); - reflection->SetRepeatedInt32 (message, F("packed_sfixed32"), 1, 809); - reflection->SetRepeatedInt64 (message, F("packed_sfixed64"), 1, 810); - reflection->SetRepeatedFloat (message, F("packed_float" ), 1, 811); - reflection->SetRepeatedDouble(message, F("packed_double" ), 1, 812); - reflection->SetRepeatedBool (message, F("packed_bool" ), 1, true); - reflection->SetRepeatedEnum (message, F("packed_enum" ), 1, foreign_foo_); -} - -void TestUtil::ReflectionTester::RemoveLastRepeatedsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - - vector output; - reflection->ListFields(*message, &output); - for (int i=0; iis_repeated()) continue; - - reflection->RemoveLast(message, field); - } -} - -void TestUtil::ReflectionTester::SwapRepeatedsViaReflection(Message* message) { - const Reflection* reflection = message->GetReflection(); - - vector output; - reflection->ListFields(*message, &output); - for (int i=0; iis_repeated()) continue; - - reflection->SwapElements(message, field, 0, 1); - } -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/test_util.h b/Resources/NetHook/google/protobuf/test_util.h deleted file mode 100644 index 25165f3a..00000000 --- a/Resources/NetHook/google/protobuf/test_util.h +++ /dev/null @@ -1,174 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_TEST_UTIL_H__ -#define GOOGLE_PROTOBUF_TEST_UTIL_H__ - -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -namespace unittest = protobuf_unittest; -namespace unittest_import = protobuf_unittest_import; - -class TestUtil { - public: - // Set every field in the message to a unique value. - static void SetAllFields(unittest::TestAllTypes* message); - static void SetAllExtensions(unittest::TestAllExtensions* message); - static void SetAllFieldsAndExtensions(unittest::TestFieldOrderings* message); - static void SetPackedFields(unittest::TestPackedTypes* message); - static void SetPackedExtensions(unittest::TestPackedExtensions* message); - static void SetUnpackedFields(unittest::TestUnpackedTypes* message); - - // Use the repeated versions of the set_*() accessors to modify all the - // repeated fields of the messsage (which should already have been - // initialized with Set*Fields()). Set*Fields() itself only tests - // the add_*() accessors. - static void ModifyRepeatedFields(unittest::TestAllTypes* message); - static void ModifyRepeatedExtensions(unittest::TestAllExtensions* message); - static void ModifyPackedFields(unittest::TestPackedTypes* message); - static void ModifyPackedExtensions(unittest::TestPackedExtensions* message); - - // Check that all fields have the values that they should have after - // Set*Fields() is called. - static void ExpectAllFieldsSet(const unittest::TestAllTypes& message); - static void ExpectAllExtensionsSet( - const unittest::TestAllExtensions& message); - static void ExpectPackedFieldsSet(const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsSet( - const unittest::TestPackedExtensions& message); - static void ExpectUnpackedFieldsSet( - const unittest::TestUnpackedTypes& message); - - // Expect that the message is modified as would be expected from - // Modify*Fields(). - static void ExpectRepeatedFieldsModified( - const unittest::TestAllTypes& message); - static void ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensions& message); - static void ExpectPackedFieldsModified( - const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsModified( - const unittest::TestPackedExtensions& message); - - // Check that all fields have their default values. - static void ExpectClear(const unittest::TestAllTypes& message); - static void ExpectExtensionsClear(const unittest::TestAllExtensions& message); - static void ExpectPackedClear(const unittest::TestPackedTypes& message); - static void ExpectPackedExtensionsClear( - const unittest::TestPackedExtensions& message); - - // Check that the passed-in serialization is the canonical serialization we - // expect for a TestFieldOrderings message filled in by - // SetAllFieldsAndExtensions(). - static void ExpectAllFieldsAndExtensionsInOrder(const string& serialized); - - // Check that all repeated fields have had their last elements removed. - static void ExpectLastRepeatedsRemoved( - const unittest::TestAllTypes& message); - static void ExpectLastRepeatedExtensionsRemoved( - const unittest::TestAllExtensions& message); - - // Check that all repeated fields have had their first and last elements - // swapped. - static void ExpectRepeatedsSwapped(const unittest::TestAllTypes& message); - static void ExpectRepeatedExtensionsSwapped( - const unittest::TestAllExtensions& message); - - // Like above, but use the reflection interface. - class ReflectionTester { - public: - // base_descriptor must be a descriptor for TestAllTypes or - // TestAllExtensions. In the former case, ReflectionTester fetches from - // it the FieldDescriptors needed to use the reflection interface. In - // the latter case, ReflectionTester searches for extension fields in - // its file. - explicit ReflectionTester(const Descriptor* base_descriptor); - - void SetAllFieldsViaReflection(Message* message); - void ModifyRepeatedFieldsViaReflection(Message* message); - void ExpectAllFieldsSetViaReflection(const Message& message); - void ExpectClearViaReflection(const Message& message); - - void SetPackedFieldsViaReflection(Message* message); - void ModifyPackedFieldsViaReflection(Message* message); - void ExpectPackedFieldsSetViaReflection(const Message& message); - void ExpectPackedClearViaReflection(const Message& message); - - void RemoveLastRepeatedsViaReflection(Message* message); - void SwapRepeatedsViaReflection(Message* message); - - private: - const FieldDescriptor* F(const string& name); - - const Descriptor* base_descriptor_; - - const FieldDescriptor* group_a_; - const FieldDescriptor* repeated_group_a_; - const FieldDescriptor* nested_b_; - const FieldDescriptor* foreign_c_; - const FieldDescriptor* import_d_; - - const EnumValueDescriptor* nested_foo_; - const EnumValueDescriptor* nested_bar_; - const EnumValueDescriptor* nested_baz_; - const EnumValueDescriptor* foreign_foo_; - const EnumValueDescriptor* foreign_bar_; - const EnumValueDescriptor* foreign_baz_; - const EnumValueDescriptor* import_foo_; - const EnumValueDescriptor* import_bar_; - const EnumValueDescriptor* import_baz_; - - // We have to split this into three function otherwise it creates a stack - // frame so large that it triggers a warning. - void ExpectAllFieldsSetViaReflection1(const Message& message); - void ExpectAllFieldsSetViaReflection2(const Message& message); - void ExpectAllFieldsSetViaReflection3(const Message& message); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ReflectionTester); - }; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TestUtil); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_TEST_UTIL_H__ diff --git a/Resources/NetHook/google/protobuf/test_util_lite.cc b/Resources/NetHook/google/protobuf/test_util_lite.cc deleted file mode 100644 index d7140e0c..00000000 --- a/Resources/NetHook/google/protobuf/test_util_lite.cc +++ /dev/null @@ -1,1502 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include - - -#define EXPECT_TRUE GOOGLE_CHECK -#define ASSERT_TRUE GOOGLE_CHECK -#define EXPECT_FALSE(COND) GOOGLE_CHECK(!(COND)) -#define EXPECT_EQ GOOGLE_CHECK_EQ -#define ASSERT_EQ GOOGLE_CHECK_EQ - -namespace google { -namespace protobuf { - -void TestUtilLite::SetAllFields(unittest::TestAllTypesLite* message) { - message->set_optional_int32 (101); - message->set_optional_int64 (102); - message->set_optional_uint32 (103); - message->set_optional_uint64 (104); - message->set_optional_sint32 (105); - message->set_optional_sint64 (106); - message->set_optional_fixed32 (107); - message->set_optional_fixed64 (108); - message->set_optional_sfixed32(109); - message->set_optional_sfixed64(110); - message->set_optional_float (111); - message->set_optional_double (112); - message->set_optional_bool (true); - message->set_optional_string ("115"); - message->set_optional_bytes ("116"); - - message->mutable_optionalgroup ()->set_a(117); - message->mutable_optional_nested_message ()->set_bb(118); - message->mutable_optional_foreign_message()->set_c(119); - message->mutable_optional_import_message ()->set_d(120); - - message->set_optional_nested_enum (unittest::TestAllTypesLite::BAZ ); - message->set_optional_foreign_enum(unittest::FOREIGN_LITE_BAZ ); - message->set_optional_import_enum (unittest_import::IMPORT_LITE_BAZ); - - - // ----------------------------------------------------------------- - - message->add_repeated_int32 (201); - message->add_repeated_int64 (202); - message->add_repeated_uint32 (203); - message->add_repeated_uint64 (204); - message->add_repeated_sint32 (205); - message->add_repeated_sint64 (206); - message->add_repeated_fixed32 (207); - message->add_repeated_fixed64 (208); - message->add_repeated_sfixed32(209); - message->add_repeated_sfixed64(210); - message->add_repeated_float (211); - message->add_repeated_double (212); - message->add_repeated_bool (true); - message->add_repeated_string ("215"); - message->add_repeated_bytes ("216"); - - message->add_repeatedgroup ()->set_a(217); - message->add_repeated_nested_message ()->set_bb(218); - message->add_repeated_foreign_message()->set_c(219); - message->add_repeated_import_message ()->set_d(220); - - message->add_repeated_nested_enum (unittest::TestAllTypesLite::BAR ); - message->add_repeated_foreign_enum(unittest::FOREIGN_LITE_BAR ); - message->add_repeated_import_enum (unittest_import::IMPORT_LITE_BAR); - - - // Add a second one of each field. - message->add_repeated_int32 (301); - message->add_repeated_int64 (302); - message->add_repeated_uint32 (303); - message->add_repeated_uint64 (304); - message->add_repeated_sint32 (305); - message->add_repeated_sint64 (306); - message->add_repeated_fixed32 (307); - message->add_repeated_fixed64 (308); - message->add_repeated_sfixed32(309); - message->add_repeated_sfixed64(310); - message->add_repeated_float (311); - message->add_repeated_double (312); - message->add_repeated_bool (false); - message->add_repeated_string ("315"); - message->add_repeated_bytes ("316"); - - message->add_repeatedgroup ()->set_a(317); - message->add_repeated_nested_message ()->set_bb(318); - message->add_repeated_foreign_message()->set_c(319); - message->add_repeated_import_message ()->set_d(320); - - message->add_repeated_nested_enum (unittest::TestAllTypesLite::BAZ ); - message->add_repeated_foreign_enum(unittest::FOREIGN_LITE_BAZ ); - message->add_repeated_import_enum (unittest_import::IMPORT_LITE_BAZ); - - - // ----------------------------------------------------------------- - - message->set_default_int32 (401); - message->set_default_int64 (402); - message->set_default_uint32 (403); - message->set_default_uint64 (404); - message->set_default_sint32 (405); - message->set_default_sint64 (406); - message->set_default_fixed32 (407); - message->set_default_fixed64 (408); - message->set_default_sfixed32(409); - message->set_default_sfixed64(410); - message->set_default_float (411); - message->set_default_double (412); - message->set_default_bool (false); - message->set_default_string ("415"); - message->set_default_bytes ("416"); - - message->set_default_nested_enum (unittest::TestAllTypesLite::FOO ); - message->set_default_foreign_enum(unittest::FOREIGN_LITE_FOO ); - message->set_default_import_enum (unittest_import::IMPORT_LITE_FOO); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ModifyRepeatedFields(unittest::TestAllTypesLite* message) { - message->set_repeated_int32 (1, 501); - message->set_repeated_int64 (1, 502); - message->set_repeated_uint32 (1, 503); - message->set_repeated_uint64 (1, 504); - message->set_repeated_sint32 (1, 505); - message->set_repeated_sint64 (1, 506); - message->set_repeated_fixed32 (1, 507); - message->set_repeated_fixed64 (1, 508); - message->set_repeated_sfixed32(1, 509); - message->set_repeated_sfixed64(1, 510); - message->set_repeated_float (1, 511); - message->set_repeated_double (1, 512); - message->set_repeated_bool (1, true); - message->set_repeated_string (1, "515"); - message->set_repeated_bytes (1, "516"); - - message->mutable_repeatedgroup (1)->set_a(517); - message->mutable_repeated_nested_message (1)->set_bb(518); - message->mutable_repeated_foreign_message(1)->set_c(519); - message->mutable_repeated_import_message (1)->set_d(520); - - message->set_repeated_nested_enum (1, unittest::TestAllTypesLite::FOO ); - message->set_repeated_foreign_enum(1, unittest::FOREIGN_LITE_FOO ); - message->set_repeated_import_enum (1, unittest_import::IMPORT_LITE_FOO); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectAllFieldsSet( - const unittest::TestAllTypesLite& message) { - EXPECT_TRUE(message.has_optional_int32 ()); - EXPECT_TRUE(message.has_optional_int64 ()); - EXPECT_TRUE(message.has_optional_uint32 ()); - EXPECT_TRUE(message.has_optional_uint64 ()); - EXPECT_TRUE(message.has_optional_sint32 ()); - EXPECT_TRUE(message.has_optional_sint64 ()); - EXPECT_TRUE(message.has_optional_fixed32 ()); - EXPECT_TRUE(message.has_optional_fixed64 ()); - EXPECT_TRUE(message.has_optional_sfixed32()); - EXPECT_TRUE(message.has_optional_sfixed64()); - EXPECT_TRUE(message.has_optional_float ()); - EXPECT_TRUE(message.has_optional_double ()); - EXPECT_TRUE(message.has_optional_bool ()); - EXPECT_TRUE(message.has_optional_string ()); - EXPECT_TRUE(message.has_optional_bytes ()); - - EXPECT_TRUE(message.has_optionalgroup ()); - EXPECT_TRUE(message.has_optional_nested_message ()); - EXPECT_TRUE(message.has_optional_foreign_message()); - EXPECT_TRUE(message.has_optional_import_message ()); - - EXPECT_TRUE(message.optionalgroup ().has_a()); - EXPECT_TRUE(message.optional_nested_message ().has_bb()); - EXPECT_TRUE(message.optional_foreign_message().has_c()); - EXPECT_TRUE(message.optional_import_message ().has_d()); - - EXPECT_TRUE(message.has_optional_nested_enum ()); - EXPECT_TRUE(message.has_optional_foreign_enum()); - EXPECT_TRUE(message.has_optional_import_enum ()); - - - EXPECT_EQ(101 , message.optional_int32 ()); - EXPECT_EQ(102 , message.optional_int64 ()); - EXPECT_EQ(103 , message.optional_uint32 ()); - EXPECT_EQ(104 , message.optional_uint64 ()); - EXPECT_EQ(105 , message.optional_sint32 ()); - EXPECT_EQ(106 , message.optional_sint64 ()); - EXPECT_EQ(107 , message.optional_fixed32 ()); - EXPECT_EQ(108 , message.optional_fixed64 ()); - EXPECT_EQ(109 , message.optional_sfixed32()); - EXPECT_EQ(110 , message.optional_sfixed64()); - EXPECT_EQ(111 , message.optional_float ()); - EXPECT_EQ(112 , message.optional_double ()); - EXPECT_EQ(true , message.optional_bool ()); - EXPECT_EQ("115", message.optional_string ()); - EXPECT_EQ("116", message.optional_bytes ()); - - EXPECT_EQ(117, message.optionalgroup ().a()); - EXPECT_EQ(118, message.optional_nested_message ().bb()); - EXPECT_EQ(119, message.optional_foreign_message().c()); - EXPECT_EQ(120, message.optional_import_message ().d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.optional_import_enum ()); - - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.repeated_import_enum (0)); - - EXPECT_EQ(301 , message.repeated_int32 (1)); - EXPECT_EQ(302 , message.repeated_int64 (1)); - EXPECT_EQ(303 , message.repeated_uint32 (1)); - EXPECT_EQ(304 , message.repeated_uint64 (1)); - EXPECT_EQ(305 , message.repeated_sint32 (1)); - EXPECT_EQ(306 , message.repeated_sint64 (1)); - EXPECT_EQ(307 , message.repeated_fixed32 (1)); - EXPECT_EQ(308 , message.repeated_fixed64 (1)); - EXPECT_EQ(309 , message.repeated_sfixed32(1)); - EXPECT_EQ(310 , message.repeated_sfixed64(1)); - EXPECT_EQ(311 , message.repeated_float (1)); - EXPECT_EQ(312 , message.repeated_double (1)); - EXPECT_EQ(false, message.repeated_bool (1)); - EXPECT_EQ("315", message.repeated_string (1)); - EXPECT_EQ("316", message.repeated_bytes (1)); - - EXPECT_EQ(317, message.repeatedgroup (1).a()); - EXPECT_EQ(318, message.repeated_nested_message (1).bb()); - EXPECT_EQ(319, message.repeated_foreign_message(1).c()); - EXPECT_EQ(320, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.repeated_import_enum (1)); - - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.has_default_int32 ()); - EXPECT_TRUE(message.has_default_int64 ()); - EXPECT_TRUE(message.has_default_uint32 ()); - EXPECT_TRUE(message.has_default_uint64 ()); - EXPECT_TRUE(message.has_default_sint32 ()); - EXPECT_TRUE(message.has_default_sint64 ()); - EXPECT_TRUE(message.has_default_fixed32 ()); - EXPECT_TRUE(message.has_default_fixed64 ()); - EXPECT_TRUE(message.has_default_sfixed32()); - EXPECT_TRUE(message.has_default_sfixed64()); - EXPECT_TRUE(message.has_default_float ()); - EXPECT_TRUE(message.has_default_double ()); - EXPECT_TRUE(message.has_default_bool ()); - EXPECT_TRUE(message.has_default_string ()); - EXPECT_TRUE(message.has_default_bytes ()); - - EXPECT_TRUE(message.has_default_nested_enum ()); - EXPECT_TRUE(message.has_default_foreign_enum()); - EXPECT_TRUE(message.has_default_import_enum ()); - - - EXPECT_EQ(401 , message.default_int32 ()); - EXPECT_EQ(402 , message.default_int64 ()); - EXPECT_EQ(403 , message.default_uint32 ()); - EXPECT_EQ(404 , message.default_uint64 ()); - EXPECT_EQ(405 , message.default_sint32 ()); - EXPECT_EQ(406 , message.default_sint64 ()); - EXPECT_EQ(407 , message.default_fixed32 ()); - EXPECT_EQ(408 , message.default_fixed64 ()); - EXPECT_EQ(409 , message.default_sfixed32()); - EXPECT_EQ(410 , message.default_sfixed64()); - EXPECT_EQ(411 , message.default_float ()); - EXPECT_EQ(412 , message.default_double ()); - EXPECT_EQ(false, message.default_bool ()); - EXPECT_EQ("415", message.default_string ()); - EXPECT_EQ("416", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.default_import_enum ()); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectClear(const unittest::TestAllTypesLite& message) { - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.has_optional_int32 ()); - EXPECT_FALSE(message.has_optional_int64 ()); - EXPECT_FALSE(message.has_optional_uint32 ()); - EXPECT_FALSE(message.has_optional_uint64 ()); - EXPECT_FALSE(message.has_optional_sint32 ()); - EXPECT_FALSE(message.has_optional_sint64 ()); - EXPECT_FALSE(message.has_optional_fixed32 ()); - EXPECT_FALSE(message.has_optional_fixed64 ()); - EXPECT_FALSE(message.has_optional_sfixed32()); - EXPECT_FALSE(message.has_optional_sfixed64()); - EXPECT_FALSE(message.has_optional_float ()); - EXPECT_FALSE(message.has_optional_double ()); - EXPECT_FALSE(message.has_optional_bool ()); - EXPECT_FALSE(message.has_optional_string ()); - EXPECT_FALSE(message.has_optional_bytes ()); - - EXPECT_FALSE(message.has_optionalgroup ()); - EXPECT_FALSE(message.has_optional_nested_message ()); - EXPECT_FALSE(message.has_optional_foreign_message()); - EXPECT_FALSE(message.has_optional_import_message ()); - - EXPECT_FALSE(message.has_optional_nested_enum ()); - EXPECT_FALSE(message.has_optional_foreign_enum()); - EXPECT_FALSE(message.has_optional_import_enum ()); - - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.optional_int32 ()); - EXPECT_EQ(0 , message.optional_int64 ()); - EXPECT_EQ(0 , message.optional_uint32 ()); - EXPECT_EQ(0 , message.optional_uint64 ()); - EXPECT_EQ(0 , message.optional_sint32 ()); - EXPECT_EQ(0 , message.optional_sint64 ()); - EXPECT_EQ(0 , message.optional_fixed32 ()); - EXPECT_EQ(0 , message.optional_fixed64 ()); - EXPECT_EQ(0 , message.optional_sfixed32()); - EXPECT_EQ(0 , message.optional_sfixed64()); - EXPECT_EQ(0 , message.optional_float ()); - EXPECT_EQ(0 , message.optional_double ()); - EXPECT_EQ(false, message.optional_bool ()); - EXPECT_EQ("" , message.optional_string ()); - EXPECT_EQ("" , message.optional_bytes ()); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.optionalgroup ().has_a()); - EXPECT_FALSE(message.optional_nested_message ().has_bb()); - EXPECT_FALSE(message.optional_foreign_message().has_c()); - EXPECT_FALSE(message.optional_import_message ().has_d()); - - EXPECT_EQ(0, message.optionalgroup ().a()); - EXPECT_EQ(0, message.optional_nested_message ().bb()); - EXPECT_EQ(0, message.optional_foreign_message().c()); - EXPECT_EQ(0, message.optional_import_message ().d()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.optional_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.optional_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.optional_import_enum ()); - - - // Repeated fields are empty. - EXPECT_EQ(0, message.repeated_int32_size ()); - EXPECT_EQ(0, message.repeated_int64_size ()); - EXPECT_EQ(0, message.repeated_uint32_size ()); - EXPECT_EQ(0, message.repeated_uint64_size ()); - EXPECT_EQ(0, message.repeated_sint32_size ()); - EXPECT_EQ(0, message.repeated_sint64_size ()); - EXPECT_EQ(0, message.repeated_fixed32_size ()); - EXPECT_EQ(0, message.repeated_fixed64_size ()); - EXPECT_EQ(0, message.repeated_sfixed32_size()); - EXPECT_EQ(0, message.repeated_sfixed64_size()); - EXPECT_EQ(0, message.repeated_float_size ()); - EXPECT_EQ(0, message.repeated_double_size ()); - EXPECT_EQ(0, message.repeated_bool_size ()); - EXPECT_EQ(0, message.repeated_string_size ()); - EXPECT_EQ(0, message.repeated_bytes_size ()); - - EXPECT_EQ(0, message.repeatedgroup_size ()); - EXPECT_EQ(0, message.repeated_nested_message_size ()); - EXPECT_EQ(0, message.repeated_foreign_message_size()); - EXPECT_EQ(0, message.repeated_import_message_size ()); - EXPECT_EQ(0, message.repeated_nested_enum_size ()); - EXPECT_EQ(0, message.repeated_foreign_enum_size ()); - EXPECT_EQ(0, message.repeated_import_enum_size ()); - - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.has_default_int32 ()); - EXPECT_FALSE(message.has_default_int64 ()); - EXPECT_FALSE(message.has_default_uint32 ()); - EXPECT_FALSE(message.has_default_uint64 ()); - EXPECT_FALSE(message.has_default_sint32 ()); - EXPECT_FALSE(message.has_default_sint64 ()); - EXPECT_FALSE(message.has_default_fixed32 ()); - EXPECT_FALSE(message.has_default_fixed64 ()); - EXPECT_FALSE(message.has_default_sfixed32()); - EXPECT_FALSE(message.has_default_sfixed64()); - EXPECT_FALSE(message.has_default_float ()); - EXPECT_FALSE(message.has_default_double ()); - EXPECT_FALSE(message.has_default_bool ()); - EXPECT_FALSE(message.has_default_string ()); - EXPECT_FALSE(message.has_default_bytes ()); - - EXPECT_FALSE(message.has_default_nested_enum ()); - EXPECT_FALSE(message.has_default_foreign_enum()); - EXPECT_FALSE(message.has_default_import_enum ()); - - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.default_int32 ()); - EXPECT_EQ( 42 , message.default_int64 ()); - EXPECT_EQ( 43 , message.default_uint32 ()); - EXPECT_EQ( 44 , message.default_uint64 ()); - EXPECT_EQ(-45 , message.default_sint32 ()); - EXPECT_EQ( 46 , message.default_sint64 ()); - EXPECT_EQ( 47 , message.default_fixed32 ()); - EXPECT_EQ( 48 , message.default_fixed64 ()); - EXPECT_EQ( 49 , message.default_sfixed32()); - EXPECT_EQ(-50 , message.default_sfixed64()); - EXPECT_EQ( 51.5 , message.default_float ()); - EXPECT_EQ( 52e3 , message.default_double ()); - EXPECT_EQ(true , message.default_bool ()); - EXPECT_EQ("hello", message.default_string ()); - EXPECT_EQ("world", message.default_bytes ()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.default_nested_enum ()); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.default_foreign_enum()); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.default_import_enum ()); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectRepeatedFieldsModified( - const unittest::TestAllTypesLite& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.repeated_int32_size ()); - ASSERT_EQ(2, message.repeated_int64_size ()); - ASSERT_EQ(2, message.repeated_uint32_size ()); - ASSERT_EQ(2, message.repeated_uint64_size ()); - ASSERT_EQ(2, message.repeated_sint32_size ()); - ASSERT_EQ(2, message.repeated_sint64_size ()); - ASSERT_EQ(2, message.repeated_fixed32_size ()); - ASSERT_EQ(2, message.repeated_fixed64_size ()); - ASSERT_EQ(2, message.repeated_sfixed32_size()); - ASSERT_EQ(2, message.repeated_sfixed64_size()); - ASSERT_EQ(2, message.repeated_float_size ()); - ASSERT_EQ(2, message.repeated_double_size ()); - ASSERT_EQ(2, message.repeated_bool_size ()); - ASSERT_EQ(2, message.repeated_string_size ()); - ASSERT_EQ(2, message.repeated_bytes_size ()); - - ASSERT_EQ(2, message.repeatedgroup_size ()); - ASSERT_EQ(2, message.repeated_nested_message_size ()); - ASSERT_EQ(2, message.repeated_foreign_message_size()); - ASSERT_EQ(2, message.repeated_import_message_size ()); - ASSERT_EQ(2, message.repeated_nested_enum_size ()); - ASSERT_EQ(2, message.repeated_foreign_enum_size ()); - ASSERT_EQ(2, message.repeated_import_enum_size ()); - - - EXPECT_EQ(201 , message.repeated_int32 (0)); - EXPECT_EQ(202 , message.repeated_int64 (0)); - EXPECT_EQ(203 , message.repeated_uint32 (0)); - EXPECT_EQ(204 , message.repeated_uint64 (0)); - EXPECT_EQ(205 , message.repeated_sint32 (0)); - EXPECT_EQ(206 , message.repeated_sint64 (0)); - EXPECT_EQ(207 , message.repeated_fixed32 (0)); - EXPECT_EQ(208 , message.repeated_fixed64 (0)); - EXPECT_EQ(209 , message.repeated_sfixed32(0)); - EXPECT_EQ(210 , message.repeated_sfixed64(0)); - EXPECT_EQ(211 , message.repeated_float (0)); - EXPECT_EQ(212 , message.repeated_double (0)); - EXPECT_EQ(true , message.repeated_bool (0)); - EXPECT_EQ("215", message.repeated_string (0)); - EXPECT_EQ("216", message.repeated_bytes (0)); - - EXPECT_EQ(217, message.repeatedgroup (0).a()); - EXPECT_EQ(218, message.repeated_nested_message (0).bb()); - EXPECT_EQ(219, message.repeated_foreign_message(0).c()); - EXPECT_EQ(220, message.repeated_import_message (0).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.repeated_nested_enum (0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.repeated_foreign_enum(0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.repeated_import_enum (0)); - - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.repeated_int32 (1)); - EXPECT_EQ(502 , message.repeated_int64 (1)); - EXPECT_EQ(503 , message.repeated_uint32 (1)); - EXPECT_EQ(504 , message.repeated_uint64 (1)); - EXPECT_EQ(505 , message.repeated_sint32 (1)); - EXPECT_EQ(506 , message.repeated_sint64 (1)); - EXPECT_EQ(507 , message.repeated_fixed32 (1)); - EXPECT_EQ(508 , message.repeated_fixed64 (1)); - EXPECT_EQ(509 , message.repeated_sfixed32(1)); - EXPECT_EQ(510 , message.repeated_sfixed64(1)); - EXPECT_EQ(511 , message.repeated_float (1)); - EXPECT_EQ(512 , message.repeated_double (1)); - EXPECT_EQ(true , message.repeated_bool (1)); - EXPECT_EQ("515", message.repeated_string (1)); - EXPECT_EQ("516", message.repeated_bytes (1)); - - EXPECT_EQ(517, message.repeatedgroup (1).a()); - EXPECT_EQ(518, message.repeated_nested_message (1).bb()); - EXPECT_EQ(519, message.repeated_foreign_message(1).c()); - EXPECT_EQ(520, message.repeated_import_message (1).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.repeated_nested_enum (1)); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.repeated_foreign_enum(1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.repeated_import_enum (1)); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::SetPackedFields(unittest::TestPackedTypesLite* message) { - message->add_packed_int32 (601); - message->add_packed_int64 (602); - message->add_packed_uint32 (603); - message->add_packed_uint64 (604); - message->add_packed_sint32 (605); - message->add_packed_sint64 (606); - message->add_packed_fixed32 (607); - message->add_packed_fixed64 (608); - message->add_packed_sfixed32(609); - message->add_packed_sfixed64(610); - message->add_packed_float (611); - message->add_packed_double (612); - message->add_packed_bool (true); - message->add_packed_enum (unittest::FOREIGN_LITE_BAR); - // add a second one of each field - message->add_packed_int32 (701); - message->add_packed_int64 (702); - message->add_packed_uint32 (703); - message->add_packed_uint64 (704); - message->add_packed_sint32 (705); - message->add_packed_sint64 (706); - message->add_packed_fixed32 (707); - message->add_packed_fixed64 (708); - message->add_packed_sfixed32(709); - message->add_packed_sfixed64(710); - message->add_packed_float (711); - message->add_packed_double (712); - message->add_packed_bool (false); - message->add_packed_enum (unittest::FOREIGN_LITE_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ModifyPackedFields(unittest::TestPackedTypesLite* message) { - message->set_packed_int32 (1, 801); - message->set_packed_int64 (1, 802); - message->set_packed_uint32 (1, 803); - message->set_packed_uint64 (1, 804); - message->set_packed_sint32 (1, 805); - message->set_packed_sint64 (1, 806); - message->set_packed_fixed32 (1, 807); - message->set_packed_fixed64 (1, 808); - message->set_packed_sfixed32(1, 809); - message->set_packed_sfixed64(1, 810); - message->set_packed_float (1, 811); - message->set_packed_double (1, 812); - message->set_packed_bool (1, true); - message->set_packed_enum (1, unittest::FOREIGN_LITE_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectPackedFieldsSet( - const unittest::TestPackedTypesLite& message) { - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_EQ(true , message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.packed_enum(0)); - - EXPECT_EQ(701 , message.packed_int32 (1)); - EXPECT_EQ(702 , message.packed_int64 (1)); - EXPECT_EQ(703 , message.packed_uint32 (1)); - EXPECT_EQ(704 , message.packed_uint64 (1)); - EXPECT_EQ(705 , message.packed_sint32 (1)); - EXPECT_EQ(706 , message.packed_sint64 (1)); - EXPECT_EQ(707 , message.packed_fixed32 (1)); - EXPECT_EQ(708 , message.packed_fixed64 (1)); - EXPECT_EQ(709 , message.packed_sfixed32(1)); - EXPECT_EQ(710 , message.packed_sfixed64(1)); - EXPECT_EQ(711 , message.packed_float (1)); - EXPECT_EQ(712 , message.packed_double (1)); - EXPECT_EQ(false, message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, message.packed_enum(1)); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectPackedClear( - const unittest::TestPackedTypesLite& message) { - // Packed repeated fields are empty. - EXPECT_EQ(0, message.packed_int32_size ()); - EXPECT_EQ(0, message.packed_int64_size ()); - EXPECT_EQ(0, message.packed_uint32_size ()); - EXPECT_EQ(0, message.packed_uint64_size ()); - EXPECT_EQ(0, message.packed_sint32_size ()); - EXPECT_EQ(0, message.packed_sint64_size ()); - EXPECT_EQ(0, message.packed_fixed32_size ()); - EXPECT_EQ(0, message.packed_fixed64_size ()); - EXPECT_EQ(0, message.packed_sfixed32_size()); - EXPECT_EQ(0, message.packed_sfixed64_size()); - EXPECT_EQ(0, message.packed_float_size ()); - EXPECT_EQ(0, message.packed_double_size ()); - EXPECT_EQ(0, message.packed_bool_size ()); - EXPECT_EQ(0, message.packed_enum_size ()); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectPackedFieldsModified( - const unittest::TestPackedTypesLite& message) { - // Do the same for packed repeated fields. - ASSERT_EQ(2, message.packed_int32_size ()); - ASSERT_EQ(2, message.packed_int64_size ()); - ASSERT_EQ(2, message.packed_uint32_size ()); - ASSERT_EQ(2, message.packed_uint64_size ()); - ASSERT_EQ(2, message.packed_sint32_size ()); - ASSERT_EQ(2, message.packed_sint64_size ()); - ASSERT_EQ(2, message.packed_fixed32_size ()); - ASSERT_EQ(2, message.packed_fixed64_size ()); - ASSERT_EQ(2, message.packed_sfixed32_size()); - ASSERT_EQ(2, message.packed_sfixed64_size()); - ASSERT_EQ(2, message.packed_float_size ()); - ASSERT_EQ(2, message.packed_double_size ()); - ASSERT_EQ(2, message.packed_bool_size ()); - ASSERT_EQ(2, message.packed_enum_size ()); - - EXPECT_EQ(601 , message.packed_int32 (0)); - EXPECT_EQ(602 , message.packed_int64 (0)); - EXPECT_EQ(603 , message.packed_uint32 (0)); - EXPECT_EQ(604 , message.packed_uint64 (0)); - EXPECT_EQ(605 , message.packed_sint32 (0)); - EXPECT_EQ(606 , message.packed_sint64 (0)); - EXPECT_EQ(607 , message.packed_fixed32 (0)); - EXPECT_EQ(608 , message.packed_fixed64 (0)); - EXPECT_EQ(609 , message.packed_sfixed32(0)); - EXPECT_EQ(610 , message.packed_sfixed64(0)); - EXPECT_EQ(611 , message.packed_float (0)); - EXPECT_EQ(612 , message.packed_double (0)); - EXPECT_EQ(true , message.packed_bool (0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR, message.packed_enum(0)); - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.packed_int32 (1)); - EXPECT_EQ(802 , message.packed_int64 (1)); - EXPECT_EQ(803 , message.packed_uint32 (1)); - EXPECT_EQ(804 , message.packed_uint64 (1)); - EXPECT_EQ(805 , message.packed_sint32 (1)); - EXPECT_EQ(806 , message.packed_sint64 (1)); - EXPECT_EQ(807 , message.packed_fixed32 (1)); - EXPECT_EQ(808 , message.packed_fixed64 (1)); - EXPECT_EQ(809 , message.packed_sfixed32(1)); - EXPECT_EQ(810 , message.packed_sfixed64(1)); - EXPECT_EQ(811 , message.packed_float (1)); - EXPECT_EQ(812 , message.packed_double (1)); - EXPECT_EQ(true , message.packed_bool (1)); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO, message.packed_enum(1)); -} - -// =================================================================== -// Extensions -// -// All this code is exactly equivalent to the above code except that it's -// manipulating extension fields instead of normal ones. -// -// I gave up on the 80-char limit here. Sorry. - -void TestUtilLite::SetAllExtensions(unittest::TestAllExtensionsLite* message) { - message->SetExtension(unittest::optional_int32_extension_lite , 101); - message->SetExtension(unittest::optional_int64_extension_lite , 102); - message->SetExtension(unittest::optional_uint32_extension_lite , 103); - message->SetExtension(unittest::optional_uint64_extension_lite , 104); - message->SetExtension(unittest::optional_sint32_extension_lite , 105); - message->SetExtension(unittest::optional_sint64_extension_lite , 106); - message->SetExtension(unittest::optional_fixed32_extension_lite , 107); - message->SetExtension(unittest::optional_fixed64_extension_lite , 108); - message->SetExtension(unittest::optional_sfixed32_extension_lite, 109); - message->SetExtension(unittest::optional_sfixed64_extension_lite, 110); - message->SetExtension(unittest::optional_float_extension_lite , 111); - message->SetExtension(unittest::optional_double_extension_lite , 112); - message->SetExtension(unittest::optional_bool_extension_lite , true); - message->SetExtension(unittest::optional_string_extension_lite , "115"); - message->SetExtension(unittest::optional_bytes_extension_lite , "116"); - - message->MutableExtension(unittest::optionalgroup_extension_lite )->set_a(117); - message->MutableExtension(unittest::optional_nested_message_extension_lite )->set_bb(118); - message->MutableExtension(unittest::optional_foreign_message_extension_lite)->set_c(119); - message->MutableExtension(unittest::optional_import_message_extension_lite )->set_d(120); - - message->SetExtension(unittest::optional_nested_enum_extension_lite , unittest::TestAllTypesLite::BAZ ); - message->SetExtension(unittest::optional_foreign_enum_extension_lite, unittest::FOREIGN_LITE_BAZ ); - message->SetExtension(unittest::optional_import_enum_extension_lite , unittest_import::IMPORT_LITE_BAZ); - - - // ----------------------------------------------------------------- - - message->AddExtension(unittest::repeated_int32_extension_lite , 201); - message->AddExtension(unittest::repeated_int64_extension_lite , 202); - message->AddExtension(unittest::repeated_uint32_extension_lite , 203); - message->AddExtension(unittest::repeated_uint64_extension_lite , 204); - message->AddExtension(unittest::repeated_sint32_extension_lite , 205); - message->AddExtension(unittest::repeated_sint64_extension_lite , 206); - message->AddExtension(unittest::repeated_fixed32_extension_lite , 207); - message->AddExtension(unittest::repeated_fixed64_extension_lite , 208); - message->AddExtension(unittest::repeated_sfixed32_extension_lite, 209); - message->AddExtension(unittest::repeated_sfixed64_extension_lite, 210); - message->AddExtension(unittest::repeated_float_extension_lite , 211); - message->AddExtension(unittest::repeated_double_extension_lite , 212); - message->AddExtension(unittest::repeated_bool_extension_lite , true); - message->AddExtension(unittest::repeated_string_extension_lite , "215"); - message->AddExtension(unittest::repeated_bytes_extension_lite , "216"); - - message->AddExtension(unittest::repeatedgroup_extension_lite )->set_a(217); - message->AddExtension(unittest::repeated_nested_message_extension_lite )->set_bb(218); - message->AddExtension(unittest::repeated_foreign_message_extension_lite)->set_c(219); - message->AddExtension(unittest::repeated_import_message_extension_lite )->set_d(220); - - message->AddExtension(unittest::repeated_nested_enum_extension_lite , unittest::TestAllTypesLite::BAR ); - message->AddExtension(unittest::repeated_foreign_enum_extension_lite, unittest::FOREIGN_LITE_BAR ); - message->AddExtension(unittest::repeated_import_enum_extension_lite , unittest_import::IMPORT_LITE_BAR); - - - // Add a second one of each field. - message->AddExtension(unittest::repeated_int32_extension_lite , 301); - message->AddExtension(unittest::repeated_int64_extension_lite , 302); - message->AddExtension(unittest::repeated_uint32_extension_lite , 303); - message->AddExtension(unittest::repeated_uint64_extension_lite , 304); - message->AddExtension(unittest::repeated_sint32_extension_lite , 305); - message->AddExtension(unittest::repeated_sint64_extension_lite , 306); - message->AddExtension(unittest::repeated_fixed32_extension_lite , 307); - message->AddExtension(unittest::repeated_fixed64_extension_lite , 308); - message->AddExtension(unittest::repeated_sfixed32_extension_lite, 309); - message->AddExtension(unittest::repeated_sfixed64_extension_lite, 310); - message->AddExtension(unittest::repeated_float_extension_lite , 311); - message->AddExtension(unittest::repeated_double_extension_lite , 312); - message->AddExtension(unittest::repeated_bool_extension_lite , false); - message->AddExtension(unittest::repeated_string_extension_lite , "315"); - message->AddExtension(unittest::repeated_bytes_extension_lite , "316"); - - message->AddExtension(unittest::repeatedgroup_extension_lite )->set_a(317); - message->AddExtension(unittest::repeated_nested_message_extension_lite )->set_bb(318); - message->AddExtension(unittest::repeated_foreign_message_extension_lite)->set_c(319); - message->AddExtension(unittest::repeated_import_message_extension_lite )->set_d(320); - - message->AddExtension(unittest::repeated_nested_enum_extension_lite , unittest::TestAllTypesLite::BAZ ); - message->AddExtension(unittest::repeated_foreign_enum_extension_lite, unittest::FOREIGN_LITE_BAZ ); - message->AddExtension(unittest::repeated_import_enum_extension_lite , unittest_import::IMPORT_LITE_BAZ); - - - // ----------------------------------------------------------------- - - message->SetExtension(unittest::default_int32_extension_lite , 401); - message->SetExtension(unittest::default_int64_extension_lite , 402); - message->SetExtension(unittest::default_uint32_extension_lite , 403); - message->SetExtension(unittest::default_uint64_extension_lite , 404); - message->SetExtension(unittest::default_sint32_extension_lite , 405); - message->SetExtension(unittest::default_sint64_extension_lite , 406); - message->SetExtension(unittest::default_fixed32_extension_lite , 407); - message->SetExtension(unittest::default_fixed64_extension_lite , 408); - message->SetExtension(unittest::default_sfixed32_extension_lite, 409); - message->SetExtension(unittest::default_sfixed64_extension_lite, 410); - message->SetExtension(unittest::default_float_extension_lite , 411); - message->SetExtension(unittest::default_double_extension_lite , 412); - message->SetExtension(unittest::default_bool_extension_lite , false); - message->SetExtension(unittest::default_string_extension_lite , "415"); - message->SetExtension(unittest::default_bytes_extension_lite , "416"); - - message->SetExtension(unittest::default_nested_enum_extension_lite , unittest::TestAllTypesLite::FOO ); - message->SetExtension(unittest::default_foreign_enum_extension_lite, unittest::FOREIGN_LITE_FOO ); - message->SetExtension(unittest::default_import_enum_extension_lite , unittest_import::IMPORT_LITE_FOO); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ModifyRepeatedExtensions( - unittest::TestAllExtensionsLite* message) { - message->SetExtension(unittest::repeated_int32_extension_lite , 1, 501); - message->SetExtension(unittest::repeated_int64_extension_lite , 1, 502); - message->SetExtension(unittest::repeated_uint32_extension_lite , 1, 503); - message->SetExtension(unittest::repeated_uint64_extension_lite , 1, 504); - message->SetExtension(unittest::repeated_sint32_extension_lite , 1, 505); - message->SetExtension(unittest::repeated_sint64_extension_lite , 1, 506); - message->SetExtension(unittest::repeated_fixed32_extension_lite , 1, 507); - message->SetExtension(unittest::repeated_fixed64_extension_lite , 1, 508); - message->SetExtension(unittest::repeated_sfixed32_extension_lite, 1, 509); - message->SetExtension(unittest::repeated_sfixed64_extension_lite, 1, 510); - message->SetExtension(unittest::repeated_float_extension_lite , 1, 511); - message->SetExtension(unittest::repeated_double_extension_lite , 1, 512); - message->SetExtension(unittest::repeated_bool_extension_lite , 1, true); - message->SetExtension(unittest::repeated_string_extension_lite , 1, "515"); - message->SetExtension(unittest::repeated_bytes_extension_lite , 1, "516"); - - message->MutableExtension(unittest::repeatedgroup_extension_lite , 1)->set_a(517); - message->MutableExtension(unittest::repeated_nested_message_extension_lite , 1)->set_bb(518); - message->MutableExtension(unittest::repeated_foreign_message_extension_lite, 1)->set_c(519); - message->MutableExtension(unittest::repeated_import_message_extension_lite , 1)->set_d(520); - - message->SetExtension(unittest::repeated_nested_enum_extension_lite , 1, unittest::TestAllTypesLite::FOO ); - message->SetExtension(unittest::repeated_foreign_enum_extension_lite, 1, unittest::FOREIGN_LITE_FOO ); - message->SetExtension(unittest::repeated_import_enum_extension_lite , 1, unittest_import::IMPORT_LITE_FOO); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectAllExtensionsSet( - const unittest::TestAllExtensionsLite& message) { - EXPECT_TRUE(message.HasExtension(unittest::optional_int32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_int64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_uint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_float_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_double_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bool_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_string_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_bytes_extension_lite )); - - EXPECT_TRUE(message.HasExtension(unittest::optionalgroup_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_message_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_message_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_message_extension_lite )); - - EXPECT_TRUE(message.GetExtension(unittest::optionalgroup_extension_lite ).has_a()); - EXPECT_TRUE(message.GetExtension(unittest::optional_nested_message_extension_lite ).has_bb()); - EXPECT_TRUE(message.GetExtension(unittest::optional_foreign_message_extension_lite).has_c()); - EXPECT_TRUE(message.GetExtension(unittest::optional_import_message_extension_lite ).has_d()); - - EXPECT_TRUE(message.HasExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::optional_import_enum_extension_lite )); - - - EXPECT_EQ(101 , message.GetExtension(unittest::optional_int32_extension_lite )); - EXPECT_EQ(102 , message.GetExtension(unittest::optional_int64_extension_lite )); - EXPECT_EQ(103 , message.GetExtension(unittest::optional_uint32_extension_lite )); - EXPECT_EQ(104 , message.GetExtension(unittest::optional_uint64_extension_lite )); - EXPECT_EQ(105 , message.GetExtension(unittest::optional_sint32_extension_lite )); - EXPECT_EQ(106 , message.GetExtension(unittest::optional_sint64_extension_lite )); - EXPECT_EQ(107 , message.GetExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_EQ(108 , message.GetExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_EQ(109 , message.GetExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_EQ(110 , message.GetExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_EQ(111 , message.GetExtension(unittest::optional_float_extension_lite )); - EXPECT_EQ(112 , message.GetExtension(unittest::optional_double_extension_lite )); - EXPECT_EQ(true , message.GetExtension(unittest::optional_bool_extension_lite )); - EXPECT_EQ("115", message.GetExtension(unittest::optional_string_extension_lite )); - EXPECT_EQ("116", message.GetExtension(unittest::optional_bytes_extension_lite )); - - EXPECT_EQ(117, message.GetExtension(unittest::optionalgroup_extension_lite ).a()); - EXPECT_EQ(118, message.GetExtension(unittest::optional_nested_message_extension_lite ).bb()); - EXPECT_EQ(119, message.GetExtension(unittest::optional_foreign_message_extension_lite).c()); - EXPECT_EQ(120, message.GetExtension(unittest::optional_import_message_extension_lite ).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.GetExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.GetExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.GetExtension(unittest::optional_import_enum_extension_lite )); - - - // ----------------------------------------------------------------- - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension_lite )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension_lite )); - - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension_lite , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension_lite , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension_lite , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension_lite , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension_lite , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension_lite , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension_lite , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension_lite , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension_lite , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension_lite , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension_lite , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension_lite , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension_lite , 0).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.GetExtension(unittest::repeated_import_enum_extension_lite , 0)); - - - EXPECT_EQ(301 , message.GetExtension(unittest::repeated_int32_extension_lite , 1)); - EXPECT_EQ(302 , message.GetExtension(unittest::repeated_int64_extension_lite , 1)); - EXPECT_EQ(303 , message.GetExtension(unittest::repeated_uint32_extension_lite , 1)); - EXPECT_EQ(304 , message.GetExtension(unittest::repeated_uint64_extension_lite , 1)); - EXPECT_EQ(305 , message.GetExtension(unittest::repeated_sint32_extension_lite , 1)); - EXPECT_EQ(306 , message.GetExtension(unittest::repeated_sint64_extension_lite , 1)); - EXPECT_EQ(307 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 1)); - EXPECT_EQ(308 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 1)); - EXPECT_EQ(309 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 1)); - EXPECT_EQ(310 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 1)); - EXPECT_EQ(311 , message.GetExtension(unittest::repeated_float_extension_lite , 1)); - EXPECT_EQ(312 , message.GetExtension(unittest::repeated_double_extension_lite , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::repeated_bool_extension_lite , 1)); - EXPECT_EQ("315", message.GetExtension(unittest::repeated_string_extension_lite , 1)); - EXPECT_EQ("316", message.GetExtension(unittest::repeated_bytes_extension_lite , 1)); - - EXPECT_EQ(317, message.GetExtension(unittest::repeatedgroup_extension_lite , 1).a()); - EXPECT_EQ(318, message.GetExtension(unittest::repeated_nested_message_extension_lite , 1).bb()); - EXPECT_EQ(319, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 1).c()); - EXPECT_EQ(320, message.GetExtension(unittest::repeated_import_message_extension_lite , 1).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAZ , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 1)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAZ, message.GetExtension(unittest::repeated_import_enum_extension_lite , 1)); - - - // ----------------------------------------------------------------- - - EXPECT_TRUE(message.HasExtension(unittest::default_int32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_int64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_uint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_sint64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed32_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_fixed64_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed32_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::default_float_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_double_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_bool_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_string_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_bytes_extension_lite )); - - EXPECT_TRUE(message.HasExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_TRUE(message.HasExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_TRUE(message.HasExtension(unittest::default_import_enum_extension_lite )); - - - EXPECT_EQ(401 , message.GetExtension(unittest::default_int32_extension_lite )); - EXPECT_EQ(402 , message.GetExtension(unittest::default_int64_extension_lite )); - EXPECT_EQ(403 , message.GetExtension(unittest::default_uint32_extension_lite )); - EXPECT_EQ(404 , message.GetExtension(unittest::default_uint64_extension_lite )); - EXPECT_EQ(405 , message.GetExtension(unittest::default_sint32_extension_lite )); - EXPECT_EQ(406 , message.GetExtension(unittest::default_sint64_extension_lite )); - EXPECT_EQ(407 , message.GetExtension(unittest::default_fixed32_extension_lite )); - EXPECT_EQ(408 , message.GetExtension(unittest::default_fixed64_extension_lite )); - EXPECT_EQ(409 , message.GetExtension(unittest::default_sfixed32_extension_lite)); - EXPECT_EQ(410 , message.GetExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_EQ(411 , message.GetExtension(unittest::default_float_extension_lite )); - EXPECT_EQ(412 , message.GetExtension(unittest::default_double_extension_lite )); - EXPECT_EQ(false, message.GetExtension(unittest::default_bool_extension_lite )); - EXPECT_EQ("415", message.GetExtension(unittest::default_string_extension_lite )); - EXPECT_EQ("416", message.GetExtension(unittest::default_bytes_extension_lite )); - - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.GetExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.GetExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.GetExtension(unittest::default_import_enum_extension_lite )); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectExtensionsClear( - const unittest::TestAllExtensionsLite& message) { - string serialized; - ASSERT_TRUE(message.SerializeToString(&serialized)); - EXPECT_EQ("", serialized); - EXPECT_EQ(0, message.ByteSize()); - - // has_blah() should initially be false for all optional fields. - EXPECT_FALSE(message.HasExtension(unittest::optional_int32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_int64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_uint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_float_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_double_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bool_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_string_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_bytes_extension_lite )); - - EXPECT_FALSE(message.HasExtension(unittest::optionalgroup_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_message_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_message_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_message_extension_lite )); - - EXPECT_FALSE(message.HasExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::optional_import_enum_extension_lite )); - - - // Optional fields without defaults are set to zero or something like it. - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_int64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_uint64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sint64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed32_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_fixed64_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed32_extension_lite)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_sfixed64_extension_lite)); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_float_extension_lite )); - EXPECT_EQ(0 , message.GetExtension(unittest::optional_double_extension_lite )); - EXPECT_EQ(false, message.GetExtension(unittest::optional_bool_extension_lite )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_string_extension_lite )); - EXPECT_EQ("" , message.GetExtension(unittest::optional_bytes_extension_lite )); - - // Embedded messages should also be clear. - EXPECT_FALSE(message.GetExtension(unittest::optionalgroup_extension_lite ).has_a()); - EXPECT_FALSE(message.GetExtension(unittest::optional_nested_message_extension_lite ).has_bb()); - EXPECT_FALSE(message.GetExtension(unittest::optional_foreign_message_extension_lite).has_c()); - EXPECT_FALSE(message.GetExtension(unittest::optional_import_message_extension_lite ).has_d()); - - EXPECT_EQ(0, message.GetExtension(unittest::optionalgroup_extension_lite ).a()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_nested_message_extension_lite ).bb()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_foreign_message_extension_lite).c()); - EXPECT_EQ(0, message.GetExtension(unittest::optional_import_message_extension_lite ).d()); - - // Enums without defaults are set to the first value in the enum. - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.GetExtension(unittest::optional_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.GetExtension(unittest::optional_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.GetExtension(unittest::optional_import_enum_extension_lite )); - - - // Repeated fields are empty. - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_int64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_uint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_fixed64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_float_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_double_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bool_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_string_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_bytes_extension_lite )); - - EXPECT_EQ(0, message.ExtensionSize(unittest::repeatedgroup_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_message_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_message_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_message_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::repeated_import_enum_extension_lite )); - - - // has_blah() should also be false for all default fields. - EXPECT_FALSE(message.HasExtension(unittest::default_int32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_int64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_uint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_sint64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed32_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_fixed64_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed32_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::default_float_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_double_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_bool_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_string_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_bytes_extension_lite )); - - EXPECT_FALSE(message.HasExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_FALSE(message.HasExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_FALSE(message.HasExtension(unittest::default_import_enum_extension_lite )); - - - // Fields with defaults have their default values (duh). - EXPECT_EQ( 41 , message.GetExtension(unittest::default_int32_extension_lite )); - EXPECT_EQ( 42 , message.GetExtension(unittest::default_int64_extension_lite )); - EXPECT_EQ( 43 , message.GetExtension(unittest::default_uint32_extension_lite )); - EXPECT_EQ( 44 , message.GetExtension(unittest::default_uint64_extension_lite )); - EXPECT_EQ(-45 , message.GetExtension(unittest::default_sint32_extension_lite )); - EXPECT_EQ( 46 , message.GetExtension(unittest::default_sint64_extension_lite )); - EXPECT_EQ( 47 , message.GetExtension(unittest::default_fixed32_extension_lite )); - EXPECT_EQ( 48 , message.GetExtension(unittest::default_fixed64_extension_lite )); - EXPECT_EQ( 49 , message.GetExtension(unittest::default_sfixed32_extension_lite)); - EXPECT_EQ(-50 , message.GetExtension(unittest::default_sfixed64_extension_lite)); - EXPECT_EQ( 51.5 , message.GetExtension(unittest::default_float_extension_lite )); - EXPECT_EQ( 52e3 , message.GetExtension(unittest::default_double_extension_lite )); - EXPECT_EQ(true , message.GetExtension(unittest::default_bool_extension_lite )); - EXPECT_EQ("hello", message.GetExtension(unittest::default_string_extension_lite )); - EXPECT_EQ("world", message.GetExtension(unittest::default_bytes_extension_lite )); - - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.GetExtension(unittest::default_nested_enum_extension_lite )); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.GetExtension(unittest::default_foreign_enum_extension_lite)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.GetExtension(unittest::default_import_enum_extension_lite )); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensionsLite& message) { - // ModifyRepeatedFields only sets the second repeated element of each - // field. In addition to verifying this, we also verify that the first - // element and size were *not* modified. - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_fixed64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed32_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_string_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_bytes_extension_lite )); - - ASSERT_EQ(2, message.ExtensionSize(unittest::repeatedgroup_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_message_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_message_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_nested_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_foreign_enum_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::repeated_import_enum_extension_lite )); - - - EXPECT_EQ(201 , message.GetExtension(unittest::repeated_int32_extension_lite , 0)); - EXPECT_EQ(202 , message.GetExtension(unittest::repeated_int64_extension_lite , 0)); - EXPECT_EQ(203 , message.GetExtension(unittest::repeated_uint32_extension_lite , 0)); - EXPECT_EQ(204 , message.GetExtension(unittest::repeated_uint64_extension_lite , 0)); - EXPECT_EQ(205 , message.GetExtension(unittest::repeated_sint32_extension_lite , 0)); - EXPECT_EQ(206 , message.GetExtension(unittest::repeated_sint64_extension_lite , 0)); - EXPECT_EQ(207 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 0)); - EXPECT_EQ(208 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 0)); - EXPECT_EQ(209 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 0)); - EXPECT_EQ(210 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 0)); - EXPECT_EQ(211 , message.GetExtension(unittest::repeated_float_extension_lite , 0)); - EXPECT_EQ(212 , message.GetExtension(unittest::repeated_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension_lite , 0)); - EXPECT_EQ("215", message.GetExtension(unittest::repeated_string_extension_lite , 0)); - EXPECT_EQ("216", message.GetExtension(unittest::repeated_bytes_extension_lite , 0)); - - EXPECT_EQ(217, message.GetExtension(unittest::repeatedgroup_extension_lite , 0).a()); - EXPECT_EQ(218, message.GetExtension(unittest::repeated_nested_message_extension_lite , 0).bb()); - EXPECT_EQ(219, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 0).c()); - EXPECT_EQ(220, message.GetExtension(unittest::repeated_import_message_extension_lite , 0).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::BAR , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 0)); - EXPECT_EQ(unittest_import::IMPORT_LITE_BAR, message.GetExtension(unittest::repeated_import_enum_extension_lite , 0)); - - - // Actually verify the second (modified) elements now. - EXPECT_EQ(501 , message.GetExtension(unittest::repeated_int32_extension_lite , 1)); - EXPECT_EQ(502 , message.GetExtension(unittest::repeated_int64_extension_lite , 1)); - EXPECT_EQ(503 , message.GetExtension(unittest::repeated_uint32_extension_lite , 1)); - EXPECT_EQ(504 , message.GetExtension(unittest::repeated_uint64_extension_lite , 1)); - EXPECT_EQ(505 , message.GetExtension(unittest::repeated_sint32_extension_lite , 1)); - EXPECT_EQ(506 , message.GetExtension(unittest::repeated_sint64_extension_lite , 1)); - EXPECT_EQ(507 , message.GetExtension(unittest::repeated_fixed32_extension_lite , 1)); - EXPECT_EQ(508 , message.GetExtension(unittest::repeated_fixed64_extension_lite , 1)); - EXPECT_EQ(509 , message.GetExtension(unittest::repeated_sfixed32_extension_lite, 1)); - EXPECT_EQ(510 , message.GetExtension(unittest::repeated_sfixed64_extension_lite, 1)); - EXPECT_EQ(511 , message.GetExtension(unittest::repeated_float_extension_lite , 1)); - EXPECT_EQ(512 , message.GetExtension(unittest::repeated_double_extension_lite , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::repeated_bool_extension_lite , 1)); - EXPECT_EQ("515", message.GetExtension(unittest::repeated_string_extension_lite , 1)); - EXPECT_EQ("516", message.GetExtension(unittest::repeated_bytes_extension_lite , 1)); - - EXPECT_EQ(517, message.GetExtension(unittest::repeatedgroup_extension_lite , 1).a()); - EXPECT_EQ(518, message.GetExtension(unittest::repeated_nested_message_extension_lite , 1).bb()); - EXPECT_EQ(519, message.GetExtension(unittest::repeated_foreign_message_extension_lite, 1).c()); - EXPECT_EQ(520, message.GetExtension(unittest::repeated_import_message_extension_lite , 1).d()); - - EXPECT_EQ(unittest::TestAllTypesLite::FOO , message.GetExtension(unittest::repeated_nested_enum_extension_lite , 1)); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO , message.GetExtension(unittest::repeated_foreign_enum_extension_lite, 1)); - EXPECT_EQ(unittest_import::IMPORT_LITE_FOO, message.GetExtension(unittest::repeated_import_enum_extension_lite , 1)); - -} - -// ------------------------------------------------------------------- - -void TestUtilLite::SetPackedExtensions( - unittest::TestPackedExtensionsLite* message) { - message->AddExtension(unittest::packed_int32_extension_lite , 601); - message->AddExtension(unittest::packed_int64_extension_lite , 602); - message->AddExtension(unittest::packed_uint32_extension_lite , 603); - message->AddExtension(unittest::packed_uint64_extension_lite , 604); - message->AddExtension(unittest::packed_sint32_extension_lite , 605); - message->AddExtension(unittest::packed_sint64_extension_lite , 606); - message->AddExtension(unittest::packed_fixed32_extension_lite , 607); - message->AddExtension(unittest::packed_fixed64_extension_lite , 608); - message->AddExtension(unittest::packed_sfixed32_extension_lite, 609); - message->AddExtension(unittest::packed_sfixed64_extension_lite, 610); - message->AddExtension(unittest::packed_float_extension_lite , 611); - message->AddExtension(unittest::packed_double_extension_lite , 612); - message->AddExtension(unittest::packed_bool_extension_lite , true); - message->AddExtension(unittest::packed_enum_extension_lite, unittest::FOREIGN_LITE_BAR); - // add a second one of each field - message->AddExtension(unittest::packed_int32_extension_lite , 701); - message->AddExtension(unittest::packed_int64_extension_lite , 702); - message->AddExtension(unittest::packed_uint32_extension_lite , 703); - message->AddExtension(unittest::packed_uint64_extension_lite , 704); - message->AddExtension(unittest::packed_sint32_extension_lite , 705); - message->AddExtension(unittest::packed_sint64_extension_lite , 706); - message->AddExtension(unittest::packed_fixed32_extension_lite , 707); - message->AddExtension(unittest::packed_fixed64_extension_lite , 708); - message->AddExtension(unittest::packed_sfixed32_extension_lite, 709); - message->AddExtension(unittest::packed_sfixed64_extension_lite, 710); - message->AddExtension(unittest::packed_float_extension_lite , 711); - message->AddExtension(unittest::packed_double_extension_lite , 712); - message->AddExtension(unittest::packed_bool_extension_lite , false); - message->AddExtension(unittest::packed_enum_extension_lite, unittest::FOREIGN_LITE_BAZ); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ModifyPackedExtensions( - unittest::TestPackedExtensionsLite* message) { - message->SetExtension(unittest::packed_int32_extension_lite , 1, 801); - message->SetExtension(unittest::packed_int64_extension_lite , 1, 802); - message->SetExtension(unittest::packed_uint32_extension_lite , 1, 803); - message->SetExtension(unittest::packed_uint64_extension_lite , 1, 804); - message->SetExtension(unittest::packed_sint32_extension_lite , 1, 805); - message->SetExtension(unittest::packed_sint64_extension_lite , 1, 806); - message->SetExtension(unittest::packed_fixed32_extension_lite , 1, 807); - message->SetExtension(unittest::packed_fixed64_extension_lite , 1, 808); - message->SetExtension(unittest::packed_sfixed32_extension_lite, 1, 809); - message->SetExtension(unittest::packed_sfixed64_extension_lite, 1, 810); - message->SetExtension(unittest::packed_float_extension_lite , 1, 811); - message->SetExtension(unittest::packed_double_extension_lite , 1, 812); - message->SetExtension(unittest::packed_bool_extension_lite , 1, true); - message->SetExtension(unittest::packed_enum_extension_lite , 1, - unittest::FOREIGN_LITE_FOO); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectPackedExtensionsSet( - const unittest::TestPackedExtensionsLite& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension_lite )); - - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension_lite , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension_lite , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension_lite , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension_lite , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension_lite , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension_lite , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension_lite , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension_lite , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension_lite , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension_lite , 0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR, - message.GetExtension(unittest::packed_enum_extension_lite, 0)); - EXPECT_EQ(701 , message.GetExtension(unittest::packed_int32_extension_lite , 1)); - EXPECT_EQ(702 , message.GetExtension(unittest::packed_int64_extension_lite , 1)); - EXPECT_EQ(703 , message.GetExtension(unittest::packed_uint32_extension_lite , 1)); - EXPECT_EQ(704 , message.GetExtension(unittest::packed_uint64_extension_lite , 1)); - EXPECT_EQ(705 , message.GetExtension(unittest::packed_sint32_extension_lite , 1)); - EXPECT_EQ(706 , message.GetExtension(unittest::packed_sint64_extension_lite , 1)); - EXPECT_EQ(707 , message.GetExtension(unittest::packed_fixed32_extension_lite , 1)); - EXPECT_EQ(708 , message.GetExtension(unittest::packed_fixed64_extension_lite , 1)); - EXPECT_EQ(709 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 1)); - EXPECT_EQ(710 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 1)); - EXPECT_EQ(711 , message.GetExtension(unittest::packed_float_extension_lite , 1)); - EXPECT_EQ(712 , message.GetExtension(unittest::packed_double_extension_lite , 1)); - EXPECT_EQ(false, message.GetExtension(unittest::packed_bool_extension_lite , 1)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAZ, - message.GetExtension(unittest::packed_enum_extension_lite, 1)); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectPackedExtensionsClear( - const unittest::TestPackedExtensionsLite& message) { - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_int64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_uint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sint64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed32_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_fixed64_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed32_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_sfixed64_extension_lite)); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_float_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_double_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_bool_extension_lite )); - EXPECT_EQ(0, message.ExtensionSize(unittest::packed_enum_extension_lite )); -} - -// ------------------------------------------------------------------- - -void TestUtilLite::ExpectPackedExtensionsModified( - const unittest::TestPackedExtensionsLite& message) { - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_int64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_uint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sint64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed32_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_fixed64_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed32_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_sfixed64_extension_lite)); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_float_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_double_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_bool_extension_lite )); - ASSERT_EQ(2, message.ExtensionSize(unittest::packed_enum_extension_lite )); - EXPECT_EQ(601 , message.GetExtension(unittest::packed_int32_extension_lite , 0)); - EXPECT_EQ(602 , message.GetExtension(unittest::packed_int64_extension_lite , 0)); - EXPECT_EQ(603 , message.GetExtension(unittest::packed_uint32_extension_lite , 0)); - EXPECT_EQ(604 , message.GetExtension(unittest::packed_uint64_extension_lite , 0)); - EXPECT_EQ(605 , message.GetExtension(unittest::packed_sint32_extension_lite , 0)); - EXPECT_EQ(606 , message.GetExtension(unittest::packed_sint64_extension_lite , 0)); - EXPECT_EQ(607 , message.GetExtension(unittest::packed_fixed32_extension_lite , 0)); - EXPECT_EQ(608 , message.GetExtension(unittest::packed_fixed64_extension_lite , 0)); - EXPECT_EQ(609 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 0)); - EXPECT_EQ(610 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 0)); - EXPECT_EQ(611 , message.GetExtension(unittest::packed_float_extension_lite , 0)); - EXPECT_EQ(612 , message.GetExtension(unittest::packed_double_extension_lite , 0)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension_lite , 0)); - EXPECT_EQ(unittest::FOREIGN_LITE_BAR, - message.GetExtension(unittest::packed_enum_extension_lite, 0)); - - // Actually verify the second (modified) elements now. - EXPECT_EQ(801 , message.GetExtension(unittest::packed_int32_extension_lite , 1)); - EXPECT_EQ(802 , message.GetExtension(unittest::packed_int64_extension_lite , 1)); - EXPECT_EQ(803 , message.GetExtension(unittest::packed_uint32_extension_lite , 1)); - EXPECT_EQ(804 , message.GetExtension(unittest::packed_uint64_extension_lite , 1)); - EXPECT_EQ(805 , message.GetExtension(unittest::packed_sint32_extension_lite , 1)); - EXPECT_EQ(806 , message.GetExtension(unittest::packed_sint64_extension_lite , 1)); - EXPECT_EQ(807 , message.GetExtension(unittest::packed_fixed32_extension_lite , 1)); - EXPECT_EQ(808 , message.GetExtension(unittest::packed_fixed64_extension_lite , 1)); - EXPECT_EQ(809 , message.GetExtension(unittest::packed_sfixed32_extension_lite, 1)); - EXPECT_EQ(810 , message.GetExtension(unittest::packed_sfixed64_extension_lite, 1)); - EXPECT_EQ(811 , message.GetExtension(unittest::packed_float_extension_lite , 1)); - EXPECT_EQ(812 , message.GetExtension(unittest::packed_double_extension_lite , 1)); - EXPECT_EQ(true , message.GetExtension(unittest::packed_bool_extension_lite , 1)); - EXPECT_EQ(unittest::FOREIGN_LITE_FOO, - message.GetExtension(unittest::packed_enum_extension_lite, 1)); -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/test_util_lite.h b/Resources/NetHook/google/protobuf/test_util_lite.h deleted file mode 100644 index ca35aaa4..00000000 --- a/Resources/NetHook/google/protobuf/test_util_lite.h +++ /dev/null @@ -1,101 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__ -#define GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__ - -#include - -namespace google { -namespace protobuf { - -namespace unittest = protobuf_unittest; -namespace unittest_import = protobuf_unittest_import; - -class TestUtilLite { - public: - // Set every field in the message to a unique value. - static void SetAllFields(unittest::TestAllTypesLite* message); - static void SetAllExtensions(unittest::TestAllExtensionsLite* message); - static void SetPackedFields(unittest::TestPackedTypesLite* message); - static void SetPackedExtensions(unittest::TestPackedExtensionsLite* message); - - // Use the repeated versions of the set_*() accessors to modify all the - // repeated fields of the messsage (which should already have been - // initialized with Set*Fields()). Set*Fields() itself only tests - // the add_*() accessors. - static void ModifyRepeatedFields(unittest::TestAllTypesLite* message); - static void ModifyRepeatedExtensions( - unittest::TestAllExtensionsLite* message); - static void ModifyPackedFields(unittest::TestPackedTypesLite* message); - static void ModifyPackedExtensions( - unittest::TestPackedExtensionsLite* message); - - // Check that all fields have the values that they should have after - // Set*Fields() is called. - static void ExpectAllFieldsSet(const unittest::TestAllTypesLite& message); - static void ExpectAllExtensionsSet( - const unittest::TestAllExtensionsLite& message); - static void ExpectPackedFieldsSet( - const unittest::TestPackedTypesLite& message); - static void ExpectPackedExtensionsSet( - const unittest::TestPackedExtensionsLite& message); - - // Expect that the message is modified as would be expected from - // Modify*Fields(). - static void ExpectRepeatedFieldsModified( - const unittest::TestAllTypesLite& message); - static void ExpectRepeatedExtensionsModified( - const unittest::TestAllExtensionsLite& message); - static void ExpectPackedFieldsModified( - const unittest::TestPackedTypesLite& message); - static void ExpectPackedExtensionsModified( - const unittest::TestPackedExtensionsLite& message); - - // Check that all fields have their default values. - static void ExpectClear(const unittest::TestAllTypesLite& message); - static void ExpectExtensionsClear( - const unittest::TestAllExtensionsLite& message); - static void ExpectPackedClear(const unittest::TestPackedTypesLite& message); - static void ExpectPackedExtensionsClear( - const unittest::TestPackedExtensionsLite& message); - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TestUtilLite); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_TEST_UTIL_LITE_H__ diff --git a/Resources/NetHook/google/protobuf/text_format.cc b/Resources/NetHook/google/protobuf/text_format.cc deleted file mode 100644 index 137cbcee..00000000 --- a/Resources/NetHook/google/protobuf/text_format.cc +++ /dev/null @@ -1,1241 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: jschorr@google.com (Joseph Schorr) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -string Message::DebugString() const { - string debug_string; - - TextFormat::PrintToString(*this, &debug_string); - - return debug_string; -} - -string Message::ShortDebugString() const { - string debug_string; - - TextFormat::Printer printer; - printer.SetSingleLineMode(true); - - printer.PrintToString(*this, &debug_string); - // Single line mode currently might have an extra space at the end. - if (debug_string.size() > 0 && - debug_string[debug_string.size() - 1] == ' ') { - debug_string.resize(debug_string.size() - 1); - } - - return debug_string; -} - -string Message::Utf8DebugString() const { - string debug_string; - - TextFormat::Printer printer; - printer.SetUseUtf8StringEscaping(true); - - printer.PrintToString(*this, &debug_string); - - return debug_string; -} - -void Message::PrintDebugString() const { - printf("%s", DebugString().c_str()); -} - - -// =========================================================================== -// Internal class for parsing an ASCII representation of a Protocol Message. -// This class makes use of the Protocol Message compiler's tokenizer found -// in //google/protobuf/io/tokenizer.h. Note that class's Parse -// method is *not* thread-safe and should only be used in a single thread at -// a time. - -// Makes code slightly more readable. The meaning of "DO(foo)" is -// "Execute foo and fail if it fails.", where failure is indicated by -// returning false. Borrowed from parser.cc (Thanks Kenton!). -#define DO(STATEMENT) if (STATEMENT) {} else return false - -class TextFormat::Parser::ParserImpl { - public: - - // Determines if repeated values for a non-repeated field are - // permitted, e.g., the string "foo: 1 foo: 2" for a - // required/optional field named "foo". - enum SingularOverwritePolicy { - ALLOW_SINGULAR_OVERWRITES = 0, // the last value is retained - FORBID_SINGULAR_OVERWRITES = 1, // an error is issued - }; - - ParserImpl(const Descriptor* root_message_type, - io::ZeroCopyInputStream* input_stream, - io::ErrorCollector* error_collector, - SingularOverwritePolicy singular_overwrite_policy) - : error_collector_(error_collector), - tokenizer_error_collector_(this), - tokenizer_(input_stream, &tokenizer_error_collector_), - root_message_type_(root_message_type), - singular_overwrite_policy_(singular_overwrite_policy), - had_errors_(false) { - // For backwards-compatibility with proto1, we need to allow the 'f' suffix - // for floats. - tokenizer_.set_allow_f_after_float(true); - - // '#' starts a comment. - tokenizer_.set_comment_style(io::Tokenizer::SH_COMMENT_STYLE); - - // Consume the starting token. - tokenizer_.Next(); - } - ~ParserImpl() { } - - // Parses the ASCII representation specified in input and saves the - // information into the output pointer (a Message). Returns - // false if an error occurs (an error will also be logged to - // GOOGLE_LOG(ERROR)). - bool Parse(Message* output) { - // Consume fields until we cannot do so anymore. - while(true) { - if (LookingAtType(io::Tokenizer::TYPE_END)) { - return !had_errors_; - } - - DO(ConsumeField(output)); - } - } - - bool ParseField(const FieldDescriptor* field, Message* output) { - bool suc; - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - suc = ConsumeFieldMessage(output, output->GetReflection(), field); - } else { - suc = ConsumeFieldValue(output, output->GetReflection(), field); - } - return suc && LookingAtType(io::Tokenizer::TYPE_END); - } - - void ReportError(int line, int col, const string& message) { - had_errors_ = true; - if (error_collector_ == NULL) { - if (line >= 0) { - GOOGLE_LOG(ERROR) << "Error parsing text-format " - << root_message_type_->full_name() - << ": " << (line + 1) << ":" - << (col + 1) << ": " << message; - } else { - GOOGLE_LOG(ERROR) << "Error parsing text-format " - << root_message_type_->full_name() - << ": " << message; - } - } else { - error_collector_->AddError(line, col, message); - } - } - - void ReportWarning(int line, int col, const string& message) { - if (error_collector_ == NULL) { - if (line >= 0) { - GOOGLE_LOG(WARNING) << "Warning parsing text-format " - << root_message_type_->full_name() - << ": " << (line + 1) << ":" - << (col + 1) << ": " << message; - } else { - GOOGLE_LOG(WARNING) << "Warning parsing text-format " - << root_message_type_->full_name() - << ": " << message; - } - } else { - error_collector_->AddWarning(line, col, message); - } - } - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserImpl); - - // Reports an error with the given message with information indicating - // the position (as derived from the current token). - void ReportError(const string& message) { - ReportError(tokenizer_.current().line, tokenizer_.current().column, - message); - } - - // Reports a warning with the given message with information indicating - // the position (as derived from the current token). - void ReportWarning(const string& message) { - ReportWarning(tokenizer_.current().line, tokenizer_.current().column, - message); - } - - // Consumes the specified message with the given starting delimeter. - // This method checks to see that the end delimeter at the conclusion of - // the consumption matches the starting delimeter passed in here. - bool ConsumeMessage(Message* message, const string delimeter) { - while (!LookingAt(">") && !LookingAt("}")) { - DO(ConsumeField(message)); - } - - // Confirm that we have a valid ending delimeter. - DO(Consume(delimeter)); - - return true; - } - - // Consumes the current field (as returned by the tokenizer) on the - // passed in message. - bool ConsumeField(Message* message) { - const Reflection* reflection = message->GetReflection(); - const Descriptor* descriptor = message->GetDescriptor(); - - string field_name; - - const FieldDescriptor* field = NULL; - - if (TryConsume("[")) { - // Extension. - DO(ConsumeIdentifier(&field_name)); - while (TryConsume(".")) { - string part; - DO(ConsumeIdentifier(&part)); - field_name += "."; - field_name += part; - } - DO(Consume("]")); - - field = reflection->FindKnownExtensionByName(field_name); - - if (field == NULL) { - ReportError("Extension \"" + field_name + "\" is not defined or " - "is not an extension of \"" + - descriptor->full_name() + "\"."); - return false; - } - } else { - DO(ConsumeIdentifier(&field_name)); - - field = descriptor->FindFieldByName(field_name); - // Group names are expected to be capitalized as they appear in the - // .proto file, which actually matches their type names, not their field - // names. - if (field == NULL) { - string lower_field_name = field_name; - LowerString(&lower_field_name); - field = descriptor->FindFieldByName(lower_field_name); - // If the case-insensitive match worked but the field is NOT a group, - if (field != NULL && field->type() != FieldDescriptor::TYPE_GROUP) { - field = NULL; - } - } - // Again, special-case group names as described above. - if (field != NULL && field->type() == FieldDescriptor::TYPE_GROUP - && field->message_type()->name() != field_name) { - field = NULL; - } - - if (field == NULL) { - ReportError("Message type \"" + descriptor->full_name() + - "\" has no field named \"" + field_name + "\"."); - return false; - } - } - - // Fail if the field is not repeated and it has already been specified. - if ((singular_overwrite_policy_ == FORBID_SINGULAR_OVERWRITES) && - !field->is_repeated() && reflection->HasField(*message, field)) { - ReportError("Non-repeated field \"" + field_name + - "\" is specified multiple times."); - return false; - } - - // Perform special handling for embedded message types. - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - // ':' is optional here. - TryConsume(":"); - DO(ConsumeFieldMessage(message, reflection, field)); - } else { - DO(Consume(":")); - DO(ConsumeFieldValue(message, reflection, field)); - } - - if (field->options().deprecated()) { - ReportWarning("text format contains deprecated field \"" - + field_name + "\""); - } - - return true; - } - - bool ConsumeFieldMessage(Message* message, - const Reflection* reflection, - const FieldDescriptor* field) { - string delimeter; - if (TryConsume("<")) { - delimeter = ">"; - } else { - DO(Consume("{")); - delimeter = "}"; - } - - if (field->is_repeated()) { - DO(ConsumeMessage(reflection->AddMessage(message, field), delimeter)); - } else { - DO(ConsumeMessage(reflection->MutableMessage(message, field), - delimeter)); - } - return true; - } - - bool ConsumeFieldValue(Message* message, - const Reflection* reflection, - const FieldDescriptor* field) { - -// Define an easy to use macro for setting fields. This macro checks -// to see if the field is repeated (in which case we need to use the Add -// methods or not (in which case we need to use the Set methods). -#define SET_FIELD(CPPTYPE, VALUE) \ - if (field->is_repeated()) { \ - reflection->Add##CPPTYPE(message, field, VALUE); \ - } else { \ - reflection->Set##CPPTYPE(message, field, VALUE); \ - } \ - - switch(field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: { - int64 value; - DO(ConsumeSignedInteger(&value, kint32max)); - SET_FIELD(Int32, static_cast(value)); - break; - } - - case FieldDescriptor::CPPTYPE_UINT32: { - uint64 value; - DO(ConsumeUnsignedInteger(&value, kuint32max)); - SET_FIELD(UInt32, static_cast(value)); - break; - } - - case FieldDescriptor::CPPTYPE_INT64: { - int64 value; - DO(ConsumeSignedInteger(&value, kint64max)); - SET_FIELD(Int64, value); - break; - } - - case FieldDescriptor::CPPTYPE_UINT64: { - uint64 value; - DO(ConsumeUnsignedInteger(&value, kuint64max)); - SET_FIELD(UInt64, value); - break; - } - - case FieldDescriptor::CPPTYPE_FLOAT: { - double value; - DO(ConsumeDouble(&value)); - SET_FIELD(Float, static_cast(value)); - break; - } - - case FieldDescriptor::CPPTYPE_DOUBLE: { - double value; - DO(ConsumeDouble(&value)); - SET_FIELD(Double, value); - break; - } - - case FieldDescriptor::CPPTYPE_STRING: { - string value; - DO(ConsumeString(&value)); - SET_FIELD(String, value); - break; - } - - case FieldDescriptor::CPPTYPE_BOOL: { - string value; - DO(ConsumeIdentifier(&value)); - - if (value == "true") { - SET_FIELD(Bool, true); - } else if (value == "false") { - SET_FIELD(Bool, false); - } else { - ReportError("Invalid value for boolean field \"" + field->name() - + "\". Value: \"" + value + "\"."); - return false; - } - break; - } - - case FieldDescriptor::CPPTYPE_ENUM: { - string value; - DO(ConsumeIdentifier(&value)); - - // Find the enumeration value. - const EnumDescriptor* enum_type = field->enum_type(); - const EnumValueDescriptor* enum_value - = enum_type->FindValueByName(value); - - if (enum_value == NULL) { - ReportError("Unknown enumeration value of \"" + value + "\" for " - "field \"" + field->name() + "\"."); - return false; - } - - SET_FIELD(Enum, enum_value); - break; - } - - case FieldDescriptor::CPPTYPE_MESSAGE: { - // We should never get here. Put here instead of a default - // so that if new types are added, we get a nice compiler warning. - GOOGLE_LOG(FATAL) << "Reached an unintended state: CPPTYPE_MESSAGE"; - break; - } - } -#undef SET_FIELD - return true; - } - - // Returns true if the current token's text is equal to that specified. - bool LookingAt(const string& text) { - return tokenizer_.current().text == text; - } - - // Returns true if the current token's type is equal to that specified. - bool LookingAtType(io::Tokenizer::TokenType token_type) { - return tokenizer_.current().type == token_type; - } - - // Consumes an identifier and saves its value in the identifier parameter. - // Returns false if the token is not of type IDENTFIER. - bool ConsumeIdentifier(string* identifier) { - if (!LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { - ReportError("Expected identifier."); - return false; - } - - *identifier = tokenizer_.current().text; - - tokenizer_.Next(); - return true; - } - - // Consumes a string and saves its value in the text parameter. - // Returns false if the token is not of type STRING. - bool ConsumeString(string* text) { - if (!LookingAtType(io::Tokenizer::TYPE_STRING)) { - ReportError("Expected string."); - return false; - } - - text->clear(); - while (LookingAtType(io::Tokenizer::TYPE_STRING)) { - io::Tokenizer::ParseStringAppend(tokenizer_.current().text, text); - - tokenizer_.Next(); - } - - return true; - } - - // Consumes a uint64 and saves its value in the value parameter. - // Returns false if the token is not of type INTEGER. - bool ConsumeUnsignedInteger(uint64* value, uint64 max_value) { - if (!LookingAtType(io::Tokenizer::TYPE_INTEGER)) { - ReportError("Expected integer."); - return false; - } - - if (!io::Tokenizer::ParseInteger(tokenizer_.current().text, - max_value, value)) { - ReportError("Integer out of range."); - return false; - } - - tokenizer_.Next(); - return true; - } - - // Consumes an int64 and saves its value in the value parameter. - // Note that since the tokenizer does not support negative numbers, - // we actually may consume an additional token (for the minus sign) in this - // method. Returns false if the token is not an integer - // (signed or otherwise). - bool ConsumeSignedInteger(int64* value, uint64 max_value) { - bool negative = false; - - if (TryConsume("-")) { - negative = true; - // Two's complement always allows one more negative integer than - // positive. - ++max_value; - } - - uint64 unsigned_value; - - DO(ConsumeUnsignedInteger(&unsigned_value, max_value)); - - *value = static_cast(unsigned_value); - - if (negative) { - *value = -*value; - } - - return true; - } - - // Consumes a double and saves its value in the value parameter. - // Note that since the tokenizer does not support negative numbers, - // we actually may consume an additional token (for the minus sign) in this - // method. Returns false if the token is not a double - // (signed or otherwise). - bool ConsumeDouble(double* value) { - bool negative = false; - - if (TryConsume("-")) { - negative = true; - } - - // A double can actually be an integer, according to the tokenizer. - // Therefore, we must check both cases here. - if (LookingAtType(io::Tokenizer::TYPE_INTEGER)) { - // We have found an integer value for the double. - uint64 integer_value; - DO(ConsumeUnsignedInteger(&integer_value, kuint64max)); - - *value = static_cast(integer_value); - } else if (LookingAtType(io::Tokenizer::TYPE_FLOAT)) { - // We have found a float value for the double. - *value = io::Tokenizer::ParseFloat(tokenizer_.current().text); - - // Mark the current token as consumed. - tokenizer_.Next(); - } else if (LookingAtType(io::Tokenizer::TYPE_IDENTIFIER)) { - string text = tokenizer_.current().text; - LowerString(&text); - if (text == "inf" || text == "infinity") { - *value = std::numeric_limits::infinity(); - tokenizer_.Next(); - } else if (text == "nan") { - *value = std::numeric_limits::quiet_NaN(); - tokenizer_.Next(); - } else { - ReportError("Expected double."); - return false; - } - } else { - ReportError("Expected double."); - return false; - } - - if (negative) { - *value = -*value; - } - - return true; - } - - // Consumes a token and confirms that it matches that specified in the - // value parameter. Returns false if the token found does not match that - // which was specified. - bool Consume(const string& value) { - const string& current_value = tokenizer_.current().text; - - if (current_value != value) { - ReportError("Expected \"" + value + "\", found \"" + current_value - + "\"."); - return false; - } - - tokenizer_.Next(); - - return true; - } - - // Attempts to consume the supplied value. Returns false if a the - // token found does not match the value specified. - bool TryConsume(const string& value) { - if (tokenizer_.current().text == value) { - tokenizer_.Next(); - return true; - } else { - return false; - } - } - - // An internal instance of the Tokenizer's error collector, used to - // collect any base-level parse errors and feed them to the ParserImpl. - class ParserErrorCollector : public io::ErrorCollector { - public: - explicit ParserErrorCollector(TextFormat::Parser::ParserImpl* parser) : - parser_(parser) { } - - virtual ~ParserErrorCollector() { }; - - virtual void AddError(int line, int column, const string& message) { - parser_->ReportError(line, column, message); - } - - virtual void AddWarning(int line, int column, const string& message) { - parser_->ReportWarning(line, column, message); - } - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ParserErrorCollector); - TextFormat::Parser::ParserImpl* parser_; - }; - - io::ErrorCollector* error_collector_; - ParserErrorCollector tokenizer_error_collector_; - io::Tokenizer tokenizer_; - const Descriptor* root_message_type_; - SingularOverwritePolicy singular_overwrite_policy_; - bool had_errors_; -}; - -#undef DO - -// =========================================================================== -// Internal class for writing text to the io::ZeroCopyOutputStream. Adapted -// from the Printer found in //google/protobuf/io/printer.h -class TextFormat::Printer::TextGenerator { - public: - explicit TextGenerator(io::ZeroCopyOutputStream* output, - int initial_indent_level) - : output_(output), - buffer_(NULL), - buffer_size_(0), - at_start_of_line_(true), - failed_(false), - indent_(""), - initial_indent_level_(initial_indent_level) { - indent_.resize(initial_indent_level_ * 2, ' '); - } - - ~TextGenerator() { - // Only BackUp() if we're sure we've successfully called Next() at least - // once. - if (buffer_size_ > 0) { - output_->BackUp(buffer_size_); - } - } - - // Indent text by two spaces. After calling Indent(), two spaces will be - // inserted at the beginning of each line of text. Indent() may be called - // multiple times to produce deeper indents. - void Indent() { - indent_ += " "; - } - - // Reduces the current indent level by two spaces, or crashes if the indent - // level is zero. - void Outdent() { - if (indent_.empty() || - indent_.size() < initial_indent_level_ * 2) { - GOOGLE_LOG(DFATAL) << " Outdent() without matching Indent()."; - return; - } - - indent_.resize(indent_.size() - 2); - } - - // Print text to the output stream. - void Print(const string& str) { - Print(str.data(), str.size()); - } - - // Print text to the output stream. - void Print(const char* text) { - Print(text, strlen(text)); - } - - // Print text to the output stream. - void Print(const char* text, int size) { - int pos = 0; // The number of bytes we've written so far. - - for (int i = 0; i < size; i++) { - if (text[i] == '\n') { - // Saw newline. If there is more text, we may need to insert an indent - // here. So, write what we have so far, including the '\n'. - Write(text + pos, i - pos + 1); - pos = i + 1; - - // Setting this true will cause the next Write() to insert an indent - // first. - at_start_of_line_ = true; - } - } - - // Write the rest. - Write(text + pos, size - pos); - } - - // True if any write to the underlying stream failed. (We don't just - // crash in this case because this is an I/O failure, not a programming - // error.) - bool failed() const { return failed_; } - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextGenerator); - - void Write(const char* data, int size) { - if (failed_) return; - if (size == 0) return; - - if (at_start_of_line_) { - // Insert an indent. - at_start_of_line_ = false; - Write(indent_.data(), indent_.size()); - if (failed_) return; - } - - while (size > buffer_size_) { - // Data exceeds space in the buffer. Copy what we can and request a - // new buffer. - memcpy(buffer_, data, buffer_size_); - data += buffer_size_; - size -= buffer_size_; - void* void_buffer; - failed_ = !output_->Next(&void_buffer, &buffer_size_); - if (failed_) return; - buffer_ = reinterpret_cast(void_buffer); - } - - // Buffer is big enough to receive the data; copy it. - memcpy(buffer_, data, size); - buffer_ += size; - buffer_size_ -= size; - } - - io::ZeroCopyOutputStream* const output_; - char* buffer_; - int buffer_size_; - bool at_start_of_line_; - bool failed_; - - string indent_; - int initial_indent_level_; -}; - -// =========================================================================== - -TextFormat::Parser::Parser() - : error_collector_(NULL), - allow_partial_(false) {} - -TextFormat::Parser::~Parser() {} - -bool TextFormat::Parser::Parse(io::ZeroCopyInputStream* input, - Message* output) { - output->Clear(); - ParserImpl parser(output->GetDescriptor(), input, error_collector_, - ParserImpl::FORBID_SINGULAR_OVERWRITES); - return MergeUsingImpl(input, output, &parser); -} - -bool TextFormat::Parser::ParseFromString(const string& input, - Message* output) { - io::ArrayInputStream input_stream(input.data(), input.size()); - return Parse(&input_stream, output); -} - -bool TextFormat::Parser::Merge(io::ZeroCopyInputStream* input, - Message* output) { - ParserImpl parser(output->GetDescriptor(), input, error_collector_, - ParserImpl::ALLOW_SINGULAR_OVERWRITES); - return MergeUsingImpl(input, output, &parser); -} - -bool TextFormat::Parser::MergeFromString(const string& input, - Message* output) { - io::ArrayInputStream input_stream(input.data(), input.size()); - return Merge(&input_stream, output); -} - -bool TextFormat::Parser::MergeUsingImpl(io::ZeroCopyInputStream* input, - Message* output, - ParserImpl* parser_impl) { - if (!parser_impl->Parse(output)) return false; - if (!allow_partial_ && !output->IsInitialized()) { - vector missing_fields; - output->FindInitializationErrors(&missing_fields); - parser_impl->ReportError(-1, 0, "Message missing required fields: " + - JoinStrings(missing_fields, ", ")); - return false; - } - return true; -} - -bool TextFormat::Parser::ParseFieldValueFromString( - const string& input, - const FieldDescriptor* field, - Message* output) { - io::ArrayInputStream input_stream(input.data(), input.size()); - ParserImpl parser(output->GetDescriptor(), &input_stream, error_collector_, - ParserImpl::ALLOW_SINGULAR_OVERWRITES); - return parser.ParseField(field, output); -} - -/* static */ bool TextFormat::Parse(io::ZeroCopyInputStream* input, - Message* output) { - return Parser().Parse(input, output); -} - -/* static */ bool TextFormat::Merge(io::ZeroCopyInputStream* input, - Message* output) { - return Parser().Merge(input, output); -} - -/* static */ bool TextFormat::ParseFromString(const string& input, - Message* output) { - return Parser().ParseFromString(input, output); -} - -/* static */ bool TextFormat::MergeFromString(const string& input, - Message* output) { - return Parser().MergeFromString(input, output); -} - -// =========================================================================== - -TextFormat::Printer::Printer() - : initial_indent_level_(0), - single_line_mode_(false), - use_short_repeated_primitives_(false), - utf8_string_escaping_(false) {} - -TextFormat::Printer::~Printer() {} - -bool TextFormat::Printer::PrintToString(const Message& message, - string* output) { - GOOGLE_DCHECK(output) << "output specified is NULL"; - - output->clear(); - io::StringOutputStream output_stream(output); - - bool result = Print(message, &output_stream); - - return result; -} - -bool TextFormat::Printer::PrintUnknownFieldsToString( - const UnknownFieldSet& unknown_fields, - string* output) { - GOOGLE_DCHECK(output) << "output specified is NULL"; - - output->clear(); - io::StringOutputStream output_stream(output); - return PrintUnknownFields(unknown_fields, &output_stream); -} - -bool TextFormat::Printer::Print(const Message& message, - io::ZeroCopyOutputStream* output) { - TextGenerator generator(output, initial_indent_level_); - - Print(message, generator); - - // Output false if the generator failed internally. - return !generator.failed(); -} - -bool TextFormat::Printer::PrintUnknownFields( - const UnknownFieldSet& unknown_fields, - io::ZeroCopyOutputStream* output) { - TextGenerator generator(output, initial_indent_level_); - - PrintUnknownFields(unknown_fields, generator); - - // Output false if the generator failed internally. - return !generator.failed(); -} - -void TextFormat::Printer::Print(const Message& message, - TextGenerator& generator) { - const Reflection* reflection = message.GetReflection(); - vector fields; - reflection->ListFields(message, &fields); - for (int i = 0; i < fields.size(); i++) { - PrintField(message, reflection, fields[i], generator); - } - PrintUnknownFields(reflection->GetUnknownFields(message), generator); -} - -void TextFormat::Printer::PrintFieldValueToString( - const Message& message, - const FieldDescriptor* field, - int index, - string* output) { - - GOOGLE_DCHECK(output) << "output specified is NULL"; - - output->clear(); - io::StringOutputStream output_stream(output); - TextGenerator generator(&output_stream, initial_indent_level_); - - PrintFieldValue(message, message.GetReflection(), field, index, generator); -} - -void TextFormat::Printer::PrintField(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - TextGenerator& generator) { - if (use_short_repeated_primitives_ && - field->is_repeated() && - field->cpp_type() != FieldDescriptor::CPPTYPE_STRING && - field->cpp_type() != FieldDescriptor::CPPTYPE_MESSAGE) { - PrintShortRepeatedField(message, reflection, field, generator); - return; - } - - int count = 0; - - if (field->is_repeated()) { - count = reflection->FieldSize(message, field); - } else if (reflection->HasField(message, field)) { - count = 1; - } - - for (int j = 0; j < count; ++j) { - PrintFieldName(message, reflection, field, generator); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (single_line_mode_) { - generator.Print(" { "); - } else { - generator.Print(" {\n"); - generator.Indent(); - } - } else { - generator.Print(": "); - } - - // Write the field value. - int field_index = j; - if (!field->is_repeated()) { - field_index = -1; - } - - PrintFieldValue(message, reflection, field, field_index, generator); - - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (single_line_mode_) { - generator.Print("} "); - } else { - generator.Outdent(); - generator.Print("}\n"); - } - } else { - if (single_line_mode_) { - generator.Print(" "); - } else { - generator.Print("\n"); - } - } - } -} - -void TextFormat::Printer::PrintShortRepeatedField(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - TextGenerator& generator) { - // Print primitive repeated field in short form. - PrintFieldName(message, reflection, field, generator); - - int size = reflection->FieldSize(message, field); - generator.Print(": ["); - for (int i = 0; i < size; i++) { - if (i > 0) generator.Print(", "); - PrintFieldValue(message, reflection, field, i, generator); - } - if (single_line_mode_) { - generator.Print("] "); - } else { - generator.Print("]\n"); - } -} - -void TextFormat::Printer::PrintFieldName(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - TextGenerator& generator) { - if (field->is_extension()) { - generator.Print("["); - // We special-case MessageSet elements for compatibility with proto1. - if (field->containing_type()->options().message_set_wire_format() - && field->type() == FieldDescriptor::TYPE_MESSAGE - && field->is_optional() - && field->extension_scope() == field->message_type()) { - generator.Print(field->message_type()->full_name()); - } else { - generator.Print(field->full_name()); - } - generator.Print("]"); - } else { - if (field->type() == FieldDescriptor::TYPE_GROUP) { - // Groups must be serialized with their original capitalization. - generator.Print(field->message_type()->name()); - } else { - generator.Print(field->name()); - } - } -} - -void TextFormat::Printer::PrintFieldValue( - const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - int index, - TextGenerator& generator) { - GOOGLE_DCHECK(field->is_repeated() || (index == -1)) - << "Index must be -1 for non-repeated fields"; - - switch (field->cpp_type()) { -#define OUTPUT_FIELD(CPPTYPE, METHOD, TO_STRING) \ - case FieldDescriptor::CPPTYPE_##CPPTYPE: \ - generator.Print(TO_STRING(field->is_repeated() ? \ - reflection->GetRepeated##METHOD(message, field, index) : \ - reflection->Get##METHOD(message, field))); \ - break; \ - - OUTPUT_FIELD( INT32, Int32, SimpleItoa); - OUTPUT_FIELD( INT64, Int64, SimpleItoa); - OUTPUT_FIELD(UINT32, UInt32, SimpleItoa); - OUTPUT_FIELD(UINT64, UInt64, SimpleItoa); - OUTPUT_FIELD( FLOAT, Float, SimpleFtoa); - OUTPUT_FIELD(DOUBLE, Double, SimpleDtoa); -#undef OUTPUT_FIELD - - case FieldDescriptor::CPPTYPE_STRING: { - string scratch; - const string& value = field->is_repeated() ? - reflection->GetRepeatedStringReference( - message, field, index, &scratch) : - reflection->GetStringReference(message, field, &scratch); - - generator.Print("\""); - if (utf8_string_escaping_) { - generator.Print(strings::Utf8SafeCEscape(value)); - } else { - generator.Print(CEscape(value)); - } - generator.Print("\""); - - break; - } - - case FieldDescriptor::CPPTYPE_BOOL: - if (field->is_repeated()) { - generator.Print(reflection->GetRepeatedBool(message, field, index) - ? "true" : "false"); - } else { - generator.Print(reflection->GetBool(message, field) - ? "true" : "false"); - } - break; - - case FieldDescriptor::CPPTYPE_ENUM: - generator.Print(field->is_repeated() ? - reflection->GetRepeatedEnum(message, field, index)->name() : - reflection->GetEnum(message, field)->name()); - break; - - case FieldDescriptor::CPPTYPE_MESSAGE: - Print(field->is_repeated() ? - reflection->GetRepeatedMessage(message, field, index) : - reflection->GetMessage(message, field), - generator); - break; - } -} - -/* static */ bool TextFormat::Print(const Message& message, - io::ZeroCopyOutputStream* output) { - return Printer().Print(message, output); -} - -/* static */ bool TextFormat::PrintUnknownFields( - const UnknownFieldSet& unknown_fields, - io::ZeroCopyOutputStream* output) { - return Printer().PrintUnknownFields(unknown_fields, output); -} - -/* static */ bool TextFormat::PrintToString( - const Message& message, string* output) { - return Printer().PrintToString(message, output); -} - -/* static */ bool TextFormat::PrintUnknownFieldsToString( - const UnknownFieldSet& unknown_fields, string* output) { - return Printer().PrintUnknownFieldsToString(unknown_fields, output); -} - -/* static */ void TextFormat::PrintFieldValueToString( - const Message& message, - const FieldDescriptor* field, - int index, - string* output) { - return Printer().PrintFieldValueToString(message, field, index, output); -} - -/* static */ bool TextFormat::ParseFieldValueFromString( - const string& input, - const FieldDescriptor* field, - Message* message) { - return Parser().ParseFieldValueFromString(input, field, message); -} - -// Prints an integer as hex with a fixed number of digits dependent on the -// integer type. -template -static string PaddedHex(IntType value) { - string result; - result.reserve(sizeof(value) * 2); - for (int i = sizeof(value) * 2 - 1; i >= 0; i--) { - result.push_back(int_to_hex_digit(value >> (i*4) & 0x0F)); - } - return result; -} - -void TextFormat::Printer::PrintUnknownFields( - const UnknownFieldSet& unknown_fields, TextGenerator& generator) { - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - string field_number = SimpleItoa(field.number()); - - switch (field.type()) { - case UnknownField::TYPE_VARINT: - generator.Print(field_number); - generator.Print(": "); - generator.Print(SimpleItoa(field.varint())); - if (single_line_mode_) { - generator.Print(" "); - } else { - generator.Print("\n"); - } - break; - case UnknownField::TYPE_FIXED32: { - generator.Print(field_number); - generator.Print(": 0x"); - char buffer[kFastToBufferSize]; - generator.Print(FastHex32ToBuffer(field.fixed32(), buffer)); - if (single_line_mode_) { - generator.Print(" "); - } else { - generator.Print("\n"); - } - break; - } - case UnknownField::TYPE_FIXED64: { - generator.Print(field_number); - generator.Print(": 0x"); - char buffer[kFastToBufferSize]; - generator.Print(FastHex64ToBuffer(field.fixed64(), buffer)); - if (single_line_mode_) { - generator.Print(" "); - } else { - generator.Print("\n"); - } - break; - } - case UnknownField::TYPE_LENGTH_DELIMITED: { - generator.Print(field_number); - const string& value = field.length_delimited(); - UnknownFieldSet embedded_unknown_fields; - if (!value.empty() && embedded_unknown_fields.ParseFromString(value)) { - // This field is parseable as a Message. - // So it is probably an embedded message. - if (single_line_mode_) { - generator.Print(" { "); - } else { - generator.Print(" {\n"); - generator.Indent(); - } - PrintUnknownFields(embedded_unknown_fields, generator); - if (single_line_mode_) { - generator.Print("} "); - } else { - generator.Outdent(); - generator.Print("}\n"); - } - } else { - // This field is not parseable as a Message. - // So it is probably just a plain string. - generator.Print(": \""); - generator.Print(CEscape(value)); - generator.Print("\""); - if (single_line_mode_) { - generator.Print(" "); - } else { - generator.Print("\n"); - } - } - break; - } - case UnknownField::TYPE_GROUP: - generator.Print(field_number); - if (single_line_mode_) { - generator.Print(" { "); - } else { - generator.Print(" {\n"); - generator.Indent(); - } - PrintUnknownFields(field.group(), generator); - if (single_line_mode_) { - generator.Print("} "); - } else { - generator.Outdent(); - generator.Print("}\n"); - } - break; - } - } -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/text_format.h b/Resources/NetHook/google/protobuf/text_format.h deleted file mode 100644 index e78e1042..00000000 --- a/Resources/NetHook/google/protobuf/text_format.h +++ /dev/null @@ -1,264 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: jschorr@google.com (Joseph Schorr) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Utilities for printing and parsing protocol messages in a human-readable, -// text-based format. - -#ifndef GOOGLE_PROTOBUF_TEXT_FORMAT_H__ -#define GOOGLE_PROTOBUF_TEXT_FORMAT_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - -namespace io { - class ErrorCollector; // tokenizer.h -} - -// This class implements protocol buffer text format. Printing and parsing -// protocol messages in text format is useful for debugging and human editing -// of messages. -// -// This class is really a namespace that contains only static methods. -class LIBPROTOBUF_EXPORT TextFormat { - public: - // Outputs a textual representation of the given message to the given - // output stream. - static bool Print(const Message& message, io::ZeroCopyOutputStream* output); - - // Print the fields in an UnknownFieldSet. They are printed by tag number - // only. Embedded messages are heuristically identified by attempting to - // parse them. - static bool PrintUnknownFields(const UnknownFieldSet& unknown_fields, - io::ZeroCopyOutputStream* output); - - // Like Print(), but outputs directly to a string. - static bool PrintToString(const Message& message, string* output); - - // Like PrintUnknownFields(), but outputs directly to a string. - static bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields, - string* output); - - // Outputs a textual representation of the value of the field supplied on - // the message supplied. For non-repeated fields, an index of -1 must - // be supplied. Note that this method will print the default value for a - // field if it is not set. - static void PrintFieldValueToString(const Message& message, - const FieldDescriptor* field, - int index, - string* output); - - // Class for those users which require more fine-grained control over how - // a protobuffer message is printed out. - class LIBPROTOBUF_EXPORT Printer { - public: - Printer(); - ~Printer(); - - // Like TextFormat::Print - bool Print(const Message& message, io::ZeroCopyOutputStream* output); - // Like TextFormat::PrintUnknownFields - bool PrintUnknownFields(const UnknownFieldSet& unknown_fields, - io::ZeroCopyOutputStream* output); - // Like TextFormat::PrintToString - bool PrintToString(const Message& message, string* output); - // Like TextFormat::PrintUnknownFieldsToString - bool PrintUnknownFieldsToString(const UnknownFieldSet& unknown_fields, - string* output); - // Like TextFormat::PrintFieldValueToString - void PrintFieldValueToString(const Message& message, - const FieldDescriptor* field, - int index, - string* output); - - // Adjust the initial indent level of all output. Each indent level is - // equal to two spaces. - void SetInitialIndentLevel(int indent_level) { - initial_indent_level_ = indent_level; - } - - // If printing in single line mode, then the entire message will be output - // on a single line with no line breaks. - void SetSingleLineMode(bool single_line_mode) { - single_line_mode_ = single_line_mode; - } - - // Set true to print repeated primitives in a format like: - // field_name: [1, 2, 3, 4] - // instead of printing each value on its own line. Short format applies - // only to primitive values -- i.e. everything except strings and - // sub-messages/groups. Note that at present this format is not recognized - // by the parser. - void SetUseShortRepeatedPrimitives(bool use_short_repeated_primitives) { - use_short_repeated_primitives_ = use_short_repeated_primitives; - } - - // Set true to output UTF-8 instead of ASCII. The only difference - // is that bytes >= 0x80 in string fields will not be escaped, - // because they are assumed to be part of UTF-8 multi-byte - // sequences. - void SetUseUtf8StringEscaping(bool as_utf8) { - utf8_string_escaping_ = as_utf8; - } - - private: - // Forward declaration of an internal class used to print the text - // output to the OutputStream (see text_format.cc for implementation). - class TextGenerator; - - // Internal Print method, used for writing to the OutputStream via - // the TextGenerator class. - void Print(const Message& message, - TextGenerator& generator); - - // Print a single field. - void PrintField(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - TextGenerator& generator); - - // Print a repeated primitive field in short form. - void PrintShortRepeatedField(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - TextGenerator& generator); - - // Print the name of a field -- i.e. everything that comes before the - // ':' for a single name/value pair. - void PrintFieldName(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - TextGenerator& generator); - - // Outputs a textual representation of the value of the field supplied on - // the message supplied or the default value if not set. - void PrintFieldValue(const Message& message, - const Reflection* reflection, - const FieldDescriptor* field, - int index, - TextGenerator& generator); - - // Print the fields in an UnknownFieldSet. They are printed by tag number - // only. Embedded messages are heuristically identified by attempting to - // parse them. - void PrintUnknownFields(const UnknownFieldSet& unknown_fields, - TextGenerator& generator); - - int initial_indent_level_; - - bool single_line_mode_; - - bool use_short_repeated_primitives_; - - bool utf8_string_escaping_; - }; - - // Parses a text-format protocol message from the given input stream to - // the given message object. This function parses the format written - // by Print(). - static bool Parse(io::ZeroCopyInputStream* input, Message* output); - // Like Parse(), but reads directly from a string. - static bool ParseFromString(const string& input, Message* output); - - // Like Parse(), but the data is merged into the given message, as if - // using Message::MergeFrom(). - static bool Merge(io::ZeroCopyInputStream* input, Message* output); - // Like Merge(), but reads directly from a string. - static bool MergeFromString(const string& input, Message* output); - - // Parse the given text as a single field value and store it into the - // given field of the given message. If the field is a repeated field, - // the new value will be added to the end - static bool ParseFieldValueFromString(const string& input, - const FieldDescriptor* field, - Message* message); - - // For more control over parsing, use this class. - class LIBPROTOBUF_EXPORT Parser { - public: - Parser(); - ~Parser(); - - // Like TextFormat::Parse(). - bool Parse(io::ZeroCopyInputStream* input, Message* output); - // Like TextFormat::ParseFromString(). - bool ParseFromString(const string& input, Message* output); - // Like TextFormat::Merge(). - bool Merge(io::ZeroCopyInputStream* input, Message* output); - // Like TextFormat::MergeFromString(). - bool MergeFromString(const string& input, Message* output); - - // Set where to report parse errors. If NULL (the default), errors will - // be printed to stderr. - void RecordErrorsTo(io::ErrorCollector* error_collector) { - error_collector_ = error_collector; - } - - // Normally parsing fails if, after parsing, output->IsInitialized() - // returns false. Call AllowPartialMessage(true) to skip this check. - void AllowPartialMessage(bool allow) { - allow_partial_ = allow; - } - - // Like TextFormat::ParseFieldValueFromString - bool ParseFieldValueFromString(const string& input, - const FieldDescriptor* field, - Message* output); - - private: - // Forward declaration of an internal class used to parse text - // representations (see text_format.cc for implementation). - class ParserImpl; - - // Like TextFormat::Merge(). The provided implementation is used - // to do the parsing. - bool MergeUsingImpl(io::ZeroCopyInputStream* input, - Message* output, - ParserImpl* parser_impl); - - io::ErrorCollector* error_collector_; - bool allow_partial_; - }; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(TextFormat); -}; - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_TEXT_FORMAT_H__ diff --git a/Resources/NetHook/google/protobuf/text_format_unittest.cc b/Resources/NetHook/google/protobuf/text_format_unittest.cc deleted file mode 100644 index ddf8ff7f..00000000 --- a/Resources/NetHook/google/protobuf/text_format_unittest.cc +++ /dev/null @@ -1,1074 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: jschorr@google.com (Joseph Schorr) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -// Can't use an anonymous namespace here due to brokenness of Tru64 compiler. -namespace text_format_unittest { - -inline bool IsNaN(double value) { - // NaN is never equal to anything, even itself. - return value != value; -} - -// A basic string with different escapable characters for testing. -const string kEscapeTestString = - "\"A string with ' characters \n and \r newlines and \t tabs and \001 " - "slashes \\ and multiple spaces"; - -// A representation of the above string with all the characters escaped. -const string kEscapeTestStringEscaped = - "\"\\\"A string with \\' characters \\n and \\r newlines " - "and \\t tabs and \\001 slashes \\\\ and multiple spaces\""; - -class TextFormatTest : public testing::Test { - public: - static void SetUpTestCase() { - File::ReadFileToStringOrDie( - TestSourceDir() - + "/google/protobuf/testdata/text_format_unittest_data.txt", - &static_proto_debug_string_); - } - - TextFormatTest() : proto_debug_string_(static_proto_debug_string_) {} - - protected: - // Debug string read from text_format_unittest_data.txt. - const string proto_debug_string_; - unittest::TestAllTypes proto_; - - private: - static string static_proto_debug_string_; -}; -string TextFormatTest::static_proto_debug_string_; - -class TextFormatExtensionsTest : public testing::Test { - public: - static void SetUpTestCase() { - File::ReadFileToStringOrDie( - TestSourceDir() - + "/google/protobuf/testdata/" - "text_format_unittest_extensions_data.txt", - &static_proto_debug_string_); - } - - TextFormatExtensionsTest() - : proto_debug_string_(static_proto_debug_string_) {} - - protected: - // Debug string read from text_format_unittest_data.txt. - const string proto_debug_string_; - unittest::TestAllExtensions proto_; - - private: - static string static_proto_debug_string_; -}; -string TextFormatExtensionsTest::static_proto_debug_string_; - - -TEST_F(TextFormatTest, Basic) { - TestUtil::SetAllFields(&proto_); - EXPECT_EQ(proto_debug_string_, proto_.DebugString()); -} - -TEST_F(TextFormatExtensionsTest, Extensions) { - TestUtil::SetAllExtensions(&proto_); - EXPECT_EQ(proto_debug_string_, proto_.DebugString()); -} - -TEST_F(TextFormatTest, ShortDebugString) { - proto_.set_optional_int32(1); - proto_.set_optional_string("hello"); - proto_.mutable_optional_nested_message()->set_bb(2); - proto_.mutable_optional_foreign_message(); - - EXPECT_EQ("optional_int32: 1 optional_string: \"hello\" " - "optional_nested_message { bb: 2 } " - "optional_foreign_message { }", - proto_.ShortDebugString()); -} - -TEST_F(TextFormatTest, ShortPrimitiveRepeateds) { - proto_.set_optional_int32(123); - proto_.add_repeated_int32(456); - proto_.add_repeated_int32(789); - proto_.add_repeated_string("foo"); - proto_.add_repeated_string("bar"); - proto_.add_repeated_nested_message()->set_bb(2); - proto_.add_repeated_nested_message()->set_bb(3); - proto_.add_repeated_nested_enum(unittest::TestAllTypes::FOO); - proto_.add_repeated_nested_enum(unittest::TestAllTypes::BAR); - - TextFormat::Printer printer; - printer.SetUseShortRepeatedPrimitives(true); - string text; - printer.PrintToString(proto_, &text); - - EXPECT_EQ("optional_int32: 123\n" - "repeated_int32: [456, 789]\n" - "repeated_string: \"foo\"\n" - "repeated_string: \"bar\"\n" - "repeated_nested_message {\n bb: 2\n}\n" - "repeated_nested_message {\n bb: 3\n}\n" - "repeated_nested_enum: [FOO, BAR]\n", - text); - - // Try in single-line mode. - printer.SetSingleLineMode(true); - printer.PrintToString(proto_, &text); - - EXPECT_EQ("optional_int32: 123 " - "repeated_int32: [456, 789] " - "repeated_string: \"foo\" " - "repeated_string: \"bar\" " - "repeated_nested_message { bb: 2 } " - "repeated_nested_message { bb: 3 } " - "repeated_nested_enum: [FOO, BAR] ", - text); -} - - -TEST_F(TextFormatTest, StringEscape) { - // Set the string value to test. - proto_.set_optional_string(kEscapeTestString); - - // Get the DebugString from the proto. - string debug_string = proto_.DebugString(); - string utf8_debug_string = proto_.Utf8DebugString(); - - // Hardcode a correct value to test against. - string correct_string = "optional_string: " - + kEscapeTestStringEscaped - + "\n"; - - // Compare. - EXPECT_EQ(correct_string, debug_string); - // UTF-8 string is the same as non-UTF-8 because - // the protocol buffer contains no UTF-8 text. - EXPECT_EQ(correct_string, utf8_debug_string); - - string expected_short_debug_string = "optional_string: " - + kEscapeTestStringEscaped; - EXPECT_EQ(expected_short_debug_string, proto_.ShortDebugString()); -} - -TEST_F(TextFormatTest, Utf8DebugString) { - // Set the string value to test. - proto_.set_optional_string("\350\260\267\346\255\214"); - - // Get the DebugString from the proto. - string debug_string = proto_.DebugString(); - string utf8_debug_string = proto_.Utf8DebugString(); - - // Hardcode a correct value to test against. - string correct_utf8_string = "optional_string: " - "\"\350\260\267\346\255\214\"" - "\n"; - string correct_string = "optional_string: " - "\"\\350\\260\\267\\346\\255\\214\"" - "\n"; - - // Compare. - EXPECT_EQ(correct_utf8_string, utf8_debug_string); - EXPECT_EQ(correct_string, debug_string); -} - -TEST_F(TextFormatTest, PrintUnknownFields) { - // Test printing of unknown fields in a message. - - unittest::TestEmptyMessage message; - UnknownFieldSet* unknown_fields = message.mutable_unknown_fields(); - - unknown_fields->AddVarint(5, 1); - unknown_fields->AddFixed32(5, 2); - unknown_fields->AddFixed64(5, 3); - unknown_fields->AddLengthDelimited(5, "4"); - unknown_fields->AddGroup(5)->AddVarint(10, 5); - - unknown_fields->AddVarint(8, 1); - unknown_fields->AddVarint(8, 2); - unknown_fields->AddVarint(8, 3); - - EXPECT_EQ( - "5: 1\n" - "5: 0x00000002\n" - "5: 0x0000000000000003\n" - "5: \"4\"\n" - "5 {\n" - " 10: 5\n" - "}\n" - "8: 1\n" - "8: 2\n" - "8: 3\n", - message.DebugString()); -} - -TEST_F(TextFormatTest, PrintUnknownMessage) { - // Test heuristic printing of messages in an UnknownFieldSet. - - protobuf_unittest::TestAllTypes message; - - // Cases which should not be interpreted as sub-messages. - - // 'a' is a valid FIXED64 tag, so for the string to be parseable as a message - // it should be followed by 8 bytes. Since this string only has two - // subsequent bytes, it should be treated as a string. - message.add_repeated_string("abc"); - - // 'd' happens to be a valid ENDGROUP tag. So, - // UnknownFieldSet::MergeFromCodedStream() will successfully parse "def", but - // the ConsumedEntireMessage() check should fail. - message.add_repeated_string("def"); - - // A zero-length string should never be interpreted as a message even though - // it is technically valid as one. - message.add_repeated_string(""); - - // Case which should be interpreted as a sub-message. - - // An actual nested message with content should always be interpreted as a - // nested message. - message.add_repeated_nested_message()->set_bb(123); - - string data; - message.SerializeToString(&data); - - string text; - UnknownFieldSet unknown_fields; - EXPECT_TRUE(unknown_fields.ParseFromString(data)); - EXPECT_TRUE(TextFormat::PrintUnknownFieldsToString(unknown_fields, &text)); - EXPECT_EQ( - "44: \"abc\"\n" - "44: \"def\"\n" - "44: \"\"\n" - "48 {\n" - " 1: 123\n" - "}\n", - text); -} - -TEST_F(TextFormatTest, PrintMessageWithIndent) { - // Test adding an initial indent to printing. - - protobuf_unittest::TestAllTypes message; - - message.add_repeated_string("abc"); - message.add_repeated_string("def"); - message.add_repeated_nested_message()->set_bb(123); - - string text; - TextFormat::Printer printer; - printer.SetInitialIndentLevel(1); - EXPECT_TRUE(printer.PrintToString(message, &text)); - EXPECT_EQ( - " repeated_string: \"abc\"\n" - " repeated_string: \"def\"\n" - " repeated_nested_message {\n" - " bb: 123\n" - " }\n", - text); -} - -TEST_F(TextFormatTest, PrintMessageSingleLine) { - // Test printing a message on a single line. - - protobuf_unittest::TestAllTypes message; - - message.add_repeated_string("abc"); - message.add_repeated_string("def"); - message.add_repeated_nested_message()->set_bb(123); - - string text; - TextFormat::Printer printer; - printer.SetInitialIndentLevel(1); - printer.SetSingleLineMode(true); - EXPECT_TRUE(printer.PrintToString(message, &text)); - EXPECT_EQ( - " repeated_string: \"abc\" repeated_string: \"def\" " - "repeated_nested_message { bb: 123 } ", - text); -} - -TEST_F(TextFormatTest, ParseBasic) { - io::ArrayInputStream input_stream(proto_debug_string_.data(), - proto_debug_string_.size()); - TextFormat::Parse(&input_stream, &proto_); - TestUtil::ExpectAllFieldsSet(proto_); -} - -TEST_F(TextFormatExtensionsTest, ParseExtensions) { - io::ArrayInputStream input_stream(proto_debug_string_.data(), - proto_debug_string_.size()); - TextFormat::Parse(&input_stream, &proto_); - TestUtil::ExpectAllExtensionsSet(proto_); -} - -TEST_F(TextFormatTest, ParseStringEscape) { - // Create a parse string with escpaed characters in it. - string parse_string = "optional_string: " - + kEscapeTestStringEscaped - + "\n"; - - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); - TextFormat::Parse(&input_stream, &proto_); - - // Compare. - EXPECT_EQ(kEscapeTestString, proto_.optional_string()); -} - -TEST_F(TextFormatTest, ParseConcatenatedString) { - // Create a parse string with multiple parts on one line. - string parse_string = "optional_string: \"foo\" \"bar\"\n"; - - io::ArrayInputStream input_stream1(parse_string.data(), - parse_string.size()); - TextFormat::Parse(&input_stream1, &proto_); - - // Compare. - EXPECT_EQ("foobar", proto_.optional_string()); - - // Create a parse string with multiple parts on seperate lines. - parse_string = "optional_string: \"foo\"\n" - "\"bar\"\n"; - - io::ArrayInputStream input_stream2(parse_string.data(), - parse_string.size()); - TextFormat::Parse(&input_stream2, &proto_); - - // Compare. - EXPECT_EQ("foobar", proto_.optional_string()); -} - -TEST_F(TextFormatTest, ParseFloatWithSuffix) { - // Test that we can parse a floating-point value with 'f' appended to the - // end. This is needed for backwards-compatibility with proto1. - - // Have it parse a float with the 'f' suffix. - string parse_string = "optional_float: 1.0f\n"; - - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); - - TextFormat::Parse(&input_stream, &proto_); - - // Compare. - EXPECT_EQ(1.0, proto_.optional_float()); -} - -TEST_F(TextFormatTest, Comments) { - // Test that comments are ignored. - - string parse_string = "optional_int32: 1 # a comment\n" - "optional_int64: 2 # another comment"; - - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); - - TextFormat::Parse(&input_stream, &proto_); - - // Compare. - EXPECT_EQ(1, proto_.optional_int32()); - EXPECT_EQ(2, proto_.optional_int64()); -} - -TEST_F(TextFormatTest, OptionalColon) { - // Test that we can place a ':' after the field name of a nested message, - // even though we don't have to. - - string parse_string = "optional_nested_message: { bb: 1}\n"; - - io::ArrayInputStream input_stream(parse_string.data(), - parse_string.size()); - - TextFormat::Parse(&input_stream, &proto_); - - // Compare. - EXPECT_TRUE(proto_.has_optional_nested_message()); - EXPECT_EQ(1, proto_.optional_nested_message().bb()); -} - -// Some platforms (e.g. Windows) insist on padding the exponent to three -// digits when one or two would be just fine. -static string RemoveRedundantZeros(string text) { - text = StringReplace(text, "e+0", "e+", true); - text = StringReplace(text, "e-0", "e-", true); - return text; -} - -TEST_F(TextFormatTest, PrintExotic) { - unittest::TestAllTypes message; - - // Note: In C, a negative integer literal is actually the unary negation - // operator being applied to a positive integer literal, and - // 9223372036854775808 is outside the range of int64. However, it is not - // outside the range of uint64. Confusingly, this means that everything - // works if we make the literal unsigned, even though we are negating it. - message.add_repeated_int64(-GOOGLE_ULONGLONG(9223372036854775808)); - message.add_repeated_uint64(GOOGLE_ULONGLONG(18446744073709551615)); - message.add_repeated_double(123.456); - message.add_repeated_double(1.23e21); - message.add_repeated_double(1.23e-18); - message.add_repeated_double(std::numeric_limits::infinity()); - message.add_repeated_double(-std::numeric_limits::infinity()); - message.add_repeated_double(std::numeric_limits::quiet_NaN()); - message.add_repeated_string(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12)); - - // Fun story: We used to use 1.23e22 instead of 1.23e21 above, but this - // seemed to trigger an odd case on MinGW/GCC 3.4.5 where GCC's parsing of - // the value differed from strtod()'s parsing. That is to say, the - // following assertion fails on MinGW: - // assert(1.23e22 == strtod("1.23e22", NULL)); - // As a result, SimpleDtoa() would print the value as - // "1.2300000000000001e+22" to make sure strtod() produce the exact same - // result. Our goal is to test runtime parsing, not compile-time parsing, - // so this wasn't our problem. It was found that using 1.23e21 did not - // have this problem, so we switched to that instead. - - EXPECT_EQ( - "repeated_int64: -9223372036854775808\n" - "repeated_uint64: 18446744073709551615\n" - "repeated_double: 123.456\n" - "repeated_double: 1.23e+21\n" - "repeated_double: 1.23e-18\n" - "repeated_double: inf\n" - "repeated_double: -inf\n" - "repeated_double: nan\n" - "repeated_string: \"\\000\\001\\007\\010\\014\\n\\r\\t\\013\\\\\\'\\\"\"\n", - RemoveRedundantZeros(message.DebugString())); -} - -TEST_F(TextFormatTest, PrintFloatPrecision) { - unittest::TestAllTypes message; - - message.add_repeated_float(1.2); - message.add_repeated_float(1.23); - message.add_repeated_float(1.234); - message.add_repeated_float(1.2345); - message.add_repeated_float(1.23456); - message.add_repeated_float(1.2e10); - message.add_repeated_float(1.23e10); - message.add_repeated_float(1.234e10); - message.add_repeated_float(1.2345e10); - message.add_repeated_float(1.23456e10); - message.add_repeated_double(1.2); - message.add_repeated_double(1.23); - message.add_repeated_double(1.234); - message.add_repeated_double(1.2345); - message.add_repeated_double(1.23456); - message.add_repeated_double(1.234567); - message.add_repeated_double(1.2345678); - message.add_repeated_double(1.23456789); - message.add_repeated_double(1.234567898); - message.add_repeated_double(1.2345678987); - message.add_repeated_double(1.23456789876); - message.add_repeated_double(1.234567898765); - message.add_repeated_double(1.2345678987654); - message.add_repeated_double(1.23456789876543); - message.add_repeated_double(1.2e100); - message.add_repeated_double(1.23e100); - message.add_repeated_double(1.234e100); - message.add_repeated_double(1.2345e100); - message.add_repeated_double(1.23456e100); - message.add_repeated_double(1.234567e100); - message.add_repeated_double(1.2345678e100); - message.add_repeated_double(1.23456789e100); - message.add_repeated_double(1.234567898e100); - message.add_repeated_double(1.2345678987e100); - message.add_repeated_double(1.23456789876e100); - message.add_repeated_double(1.234567898765e100); - message.add_repeated_double(1.2345678987654e100); - message.add_repeated_double(1.23456789876543e100); - - EXPECT_EQ( - "repeated_float: 1.2\n" - "repeated_float: 1.23\n" - "repeated_float: 1.234\n" - "repeated_float: 1.2345\n" - "repeated_float: 1.23456\n" - "repeated_float: 1.2e+10\n" - "repeated_float: 1.23e+10\n" - "repeated_float: 1.234e+10\n" - "repeated_float: 1.2345e+10\n" - "repeated_float: 1.23456e+10\n" - "repeated_double: 1.2\n" - "repeated_double: 1.23\n" - "repeated_double: 1.234\n" - "repeated_double: 1.2345\n" - "repeated_double: 1.23456\n" - "repeated_double: 1.234567\n" - "repeated_double: 1.2345678\n" - "repeated_double: 1.23456789\n" - "repeated_double: 1.234567898\n" - "repeated_double: 1.2345678987\n" - "repeated_double: 1.23456789876\n" - "repeated_double: 1.234567898765\n" - "repeated_double: 1.2345678987654\n" - "repeated_double: 1.23456789876543\n" - "repeated_double: 1.2e+100\n" - "repeated_double: 1.23e+100\n" - "repeated_double: 1.234e+100\n" - "repeated_double: 1.2345e+100\n" - "repeated_double: 1.23456e+100\n" - "repeated_double: 1.234567e+100\n" - "repeated_double: 1.2345678e+100\n" - "repeated_double: 1.23456789e+100\n" - "repeated_double: 1.234567898e+100\n" - "repeated_double: 1.2345678987e+100\n" - "repeated_double: 1.23456789876e+100\n" - "repeated_double: 1.234567898765e+100\n" - "repeated_double: 1.2345678987654e+100\n" - "repeated_double: 1.23456789876543e+100\n", - RemoveRedundantZeros(message.DebugString())); -} - - -TEST_F(TextFormatTest, AllowPartial) { - unittest::TestRequired message; - TextFormat::Parser parser; - parser.AllowPartialMessage(true); - EXPECT_TRUE(parser.ParseFromString("a: 1", &message)); - EXPECT_EQ(1, message.a()); - EXPECT_FALSE(message.has_b()); - EXPECT_FALSE(message.has_c()); -} - -TEST_F(TextFormatTest, ParseExotic) { - unittest::TestAllTypes message; - ASSERT_TRUE(TextFormat::ParseFromString( - "repeated_int32: -1\n" - "repeated_int32: -2147483648\n" - "repeated_int64: -1\n" - "repeated_int64: -9223372036854775808\n" - "repeated_uint32: 4294967295\n" - "repeated_uint32: 2147483648\n" - "repeated_uint64: 18446744073709551615\n" - "repeated_uint64: 9223372036854775808\n" - "repeated_double: 123.0\n" - "repeated_double: 123.5\n" - "repeated_double: 0.125\n" - "repeated_double: 1.23E17\n" - "repeated_double: 1.235E+22\n" - "repeated_double: 1.235e-18\n" - "repeated_double: 123.456789\n" - "repeated_double: inf\n" - "repeated_double: Infinity\n" - "repeated_double: -inf\n" - "repeated_double: -Infinity\n" - "repeated_double: nan\n" - "repeated_double: NaN\n" - "repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\"\n", - &message)); - - ASSERT_EQ(2, message.repeated_int32_size()); - EXPECT_EQ(-1, message.repeated_int32(0)); - // Note: In C, a negative integer literal is actually the unary negation - // operator being applied to a positive integer literal, and 2147483648 is - // outside the range of int32. However, it is not outside the range of - // uint32. Confusingly, this means that everything works if we make the - // literal unsigned, even though we are negating it. - EXPECT_EQ(-2147483648u, message.repeated_int32(1)); - - ASSERT_EQ(2, message.repeated_int64_size()); - EXPECT_EQ(-1, message.repeated_int64(0)); - // Note: In C, a negative integer literal is actually the unary negation - // operator being applied to a positive integer literal, and - // 9223372036854775808 is outside the range of int64. However, it is not - // outside the range of uint64. Confusingly, this means that everything - // works if we make the literal unsigned, even though we are negating it. - EXPECT_EQ(-GOOGLE_ULONGLONG(9223372036854775808), message.repeated_int64(1)); - - ASSERT_EQ(2, message.repeated_uint32_size()); - EXPECT_EQ(4294967295u, message.repeated_uint32(0)); - EXPECT_EQ(2147483648u, message.repeated_uint32(1)); - - ASSERT_EQ(2, message.repeated_uint64_size()); - EXPECT_EQ(GOOGLE_ULONGLONG(18446744073709551615), message.repeated_uint64(0)); - EXPECT_EQ(GOOGLE_ULONGLONG(9223372036854775808), message.repeated_uint64(1)); - - ASSERT_EQ(13, message.repeated_double_size()); - EXPECT_EQ(123.0 , message.repeated_double(0)); - EXPECT_EQ(123.5 , message.repeated_double(1)); - EXPECT_EQ(0.125 , message.repeated_double(2)); - EXPECT_EQ(1.23E17 , message.repeated_double(3)); - EXPECT_EQ(1.235E22 , message.repeated_double(4)); - EXPECT_EQ(1.235E-18 , message.repeated_double(5)); - EXPECT_EQ(123.456789, message.repeated_double(6)); - EXPECT_EQ(message.repeated_double(7), numeric_limits::infinity()); - EXPECT_EQ(message.repeated_double(8), numeric_limits::infinity()); - EXPECT_EQ(message.repeated_double(9), -numeric_limits::infinity()); - EXPECT_EQ(message.repeated_double(10), -numeric_limits::infinity()); - EXPECT_TRUE(IsNaN(message.repeated_double(11))); - EXPECT_TRUE(IsNaN(message.repeated_double(12))); - - // Note: Since these string literals have \0's in them, we must explicitly - // pass their sizes to string's constructor. - ASSERT_EQ(1, message.repeated_string_size()); - EXPECT_EQ(string("\000\001\a\b\f\n\r\t\v\\\'\"", 12), - message.repeated_string(0)); -} - -class TextFormatParserTest : public testing::Test { - protected: - void ExpectFailure(const string& input, const string& message, int line, - int col) { - scoped_ptr proto(new unittest::TestAllTypes); - ExpectFailure(input, message, line, col, proto.get()); - } - - void ExpectFailure(const string& input, const string& message, int line, - int col, Message* proto) { - ExpectMessage(input, message, line, col, proto, false); - } - - void ExpectMessage(const string& input, const string& message, int line, - int col, Message* proto, bool expected_result) { - TextFormat::Parser parser; - MockErrorCollector error_collector; - parser.RecordErrorsTo(&error_collector); - EXPECT_EQ(parser.ParseFromString(input, proto), expected_result); - EXPECT_EQ(SimpleItoa(line) + ":" + SimpleItoa(col) + ": " + message + "\n", - error_collector.text_); - } - - // An error collector which simply concatenates all its errors into a big - // block of text which can be checked. - class MockErrorCollector : public io::ErrorCollector { - public: - MockErrorCollector() {} - ~MockErrorCollector() {} - - string text_; - - // implements ErrorCollector ------------------------------------- - void AddError(int line, int column, const string& message) { - strings::SubstituteAndAppend(&text_, "$0:$1: $2\n", - line + 1, column + 1, message); - } - - void AddWarning(int line, int column, const string& message) { - AddError(line, column, "WARNING:" + message); - } - }; -}; - -TEST_F(TextFormatParserTest, ParseFieldValueFromString) { - scoped_ptr message(new unittest::TestAllTypes); - const Descriptor* d = message->GetDescriptor(); - -#define EXPECT_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_EQ(value, message->optional_##name()); \ - EXPECT_TRUE(message->has_optional_##name()); - -#define EXPECT_FLOAT_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_FLOAT_EQ(value, message->optional_##name()); \ - EXPECT_TRUE(message->has_optional_##name()); - -#define EXPECT_DOUBLE_FIELD(name, value, valuestring) \ - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); \ - EXPECT_DOUBLE_EQ(value, message->optional_##name()); \ - EXPECT_TRUE(message->has_optional_##name()); - -#define EXPECT_INVALID(name, valuestring) \ - EXPECT_FALSE(TextFormat::ParseFieldValueFromString( \ - valuestring, d->FindFieldByName("optional_" #name), message.get())); - - // int32 - EXPECT_FIELD(int32, 1, "1"); - EXPECT_FIELD(int32, -1, "-1"); - EXPECT_FIELD(int32, 0x1234, "0x1234"); - EXPECT_INVALID(int32, "a"); - EXPECT_INVALID(int32, "999999999999999999999999999999999999"); - EXPECT_INVALID(int32, "1,2"); - - // int64 - EXPECT_FIELD(int64, 1, "1"); - EXPECT_FIELD(int64, -1, "-1"); - EXPECT_FIELD(int64, 0x1234567812345678LL, "0x1234567812345678"); - EXPECT_INVALID(int64, "a"); - EXPECT_INVALID(int64, "999999999999999999999999999999999999"); - EXPECT_INVALID(int64, "1,2"); - - // uint64 - EXPECT_FIELD(uint64, 1, "1"); - EXPECT_FIELD(uint64, 0xf234567812345678ULL, "0xf234567812345678"); - EXPECT_INVALID(uint64, "-1"); - EXPECT_INVALID(uint64, "a"); - EXPECT_INVALID(uint64, "999999999999999999999999999999999999"); - EXPECT_INVALID(uint64, "1,2"); - - // fixed32 - EXPECT_FIELD(fixed32, 1, "1"); - EXPECT_FIELD(fixed32, 0x12345678, "0x12345678"); - EXPECT_INVALID(fixed32, "-1"); - EXPECT_INVALID(fixed32, "a"); - EXPECT_INVALID(fixed32, "999999999999999999999999999999999999"); - EXPECT_INVALID(fixed32, "1,2"); - - // fixed64 - EXPECT_FIELD(fixed64, 1, "1"); - EXPECT_FIELD(fixed64, 0x1234567812345678ULL, "0x1234567812345678"); - EXPECT_INVALID(fixed64, "-1"); - EXPECT_INVALID(fixed64, "a"); - EXPECT_INVALID(fixed64, "999999999999999999999999999999999999"); - EXPECT_INVALID(fixed64, "1,2"); - - // bool - EXPECT_FIELD(bool, true, "true"); - EXPECT_FIELD(bool, false, "false"); - EXPECT_INVALID(bool, "1"); - EXPECT_INVALID(bool, "on"); - EXPECT_INVALID(bool, "a"); - EXPECT_INVALID(bool, "True"); - - // float - EXPECT_FIELD(float, 1, "1"); - EXPECT_FLOAT_FIELD(float, 1.5, "1.5"); - EXPECT_FLOAT_FIELD(float, 1.5e3, "1.5e3"); - EXPECT_FLOAT_FIELD(float, -4.55, "-4.55"); - EXPECT_INVALID(float, "a"); - EXPECT_INVALID(float, "1,2"); - - // double - EXPECT_FIELD(double, 1, "1"); - EXPECT_FIELD(double, -1, "-1"); - EXPECT_DOUBLE_FIELD(double, 2.3, "2.3"); - EXPECT_DOUBLE_FIELD(double, 3e5, "3e5"); - EXPECT_INVALID(double, "a"); - EXPECT_INVALID(double, "1,2"); - - // string - EXPECT_FIELD(string, "hello", "\"hello\""); - EXPECT_FIELD(string, "-1.87", "'-1.87'"); - EXPECT_INVALID(string, "hello"); // without quote for value - - // enum - EXPECT_FIELD(nested_enum, unittest::TestAllTypes::BAR, "BAR"); - EXPECT_INVALID(nested_enum, "1"); // number not supported - EXPECT_INVALID(nested_enum, "FOOBAR"); - - // message - EXPECT_TRUE(TextFormat::ParseFieldValueFromString( - "", d->FindFieldByName("optional_nested_message"), message.get())); - EXPECT_EQ(12, message->optional_nested_message().bb()); \ - EXPECT_TRUE(message->has_optional_nested_message()); - EXPECT_INVALID(nested_message, "any"); - -#undef EXPECT_FIELD -#undef EXPECT_FLOAT_FIELD -#undef EXPECT_DOUBLE_FIELD -#undef EXPECT_INVALID -} - - -TEST_F(TextFormatParserTest, InvalidToken) { - ExpectFailure("optional_bool: true\n-5\n", "Expected identifier.", - 2, 1); - - ExpectFailure("optional_bool: true;\n", "Expected identifier.", 1, 20); - ExpectFailure("\"some string\"", "Expected identifier.", 1, 1); -} - -TEST_F(TextFormatParserTest, InvalidFieldName) { - ExpectFailure( - "invalid_field: somevalue\n", - "Message type \"protobuf_unittest.TestAllTypes\" has no field named " - "\"invalid_field\".", - 1, 14); -} - -TEST_F(TextFormatParserTest, InvalidCapitalization) { - // We require that group names be exactly as they appear in the .proto. - ExpectFailure( - "optionalgroup {\na: 15\n}\n", - "Message type \"protobuf_unittest.TestAllTypes\" has no field named " - "\"optionalgroup\".", - 1, 15); - ExpectFailure( - "OPTIONALgroup {\na: 15\n}\n", - "Message type \"protobuf_unittest.TestAllTypes\" has no field named " - "\"OPTIONALgroup\".", - 1, 15); - ExpectFailure( - "Optional_Double: 10.0\n", - "Message type \"protobuf_unittest.TestAllTypes\" has no field named " - "\"Optional_Double\".", - 1, 16); -} - -TEST_F(TextFormatParserTest, InvalidFieldValues) { - // Invalid values for a double/float field. - ExpectFailure("optional_double: \"hello\"\n", "Expected double.", 1, 18); - ExpectFailure("optional_double: true\n", "Expected double.", 1, 18); - ExpectFailure("optional_double: !\n", "Expected double.", 1, 18); - ExpectFailure("optional_double {\n \n}\n", "Expected \":\", found \"{\".", - 1, 17); - - // Invalid values for a signed integer field. - ExpectFailure("optional_int32: \"hello\"\n", "Expected integer.", 1, 17); - ExpectFailure("optional_int32: true\n", "Expected integer.", 1, 17); - ExpectFailure("optional_int32: 4.5\n", "Expected integer.", 1, 17); - ExpectFailure("optional_int32: !\n", "Expected integer.", 1, 17); - ExpectFailure("optional_int32 {\n \n}\n", "Expected \":\", found \"{\".", - 1, 16); - ExpectFailure("optional_int32: 0x80000000\n", - "Integer out of range.", 1, 17); - ExpectFailure("optional_int32: -0x80000001\n", - "Integer out of range.", 1, 18); - ExpectFailure("optional_int64: 0x8000000000000000\n", - "Integer out of range.", 1, 17); - ExpectFailure("optional_int64: -0x8000000000000001\n", - "Integer out of range.", 1, 18); - - // Invalid values for an unsigned integer field. - ExpectFailure("optional_uint64: \"hello\"\n", "Expected integer.", 1, 18); - ExpectFailure("optional_uint64: true\n", "Expected integer.", 1, 18); - ExpectFailure("optional_uint64: 4.5\n", "Expected integer.", 1, 18); - ExpectFailure("optional_uint64: -5\n", "Expected integer.", 1, 18); - ExpectFailure("optional_uint64: !\n", "Expected integer.", 1, 18); - ExpectFailure("optional_uint64 {\n \n}\n", "Expected \":\", found \"{\".", - 1, 17); - ExpectFailure("optional_uint32: 0x100000000\n", - "Integer out of range.", 1, 18); - ExpectFailure("optional_uint64: 0x10000000000000000\n", - "Integer out of range.", 1, 18); - - // Invalid values for a boolean field. - ExpectFailure("optional_bool: \"hello\"\n", "Expected identifier.", 1, 16); - ExpectFailure("optional_bool: 5\n", "Expected identifier.", 1, 16); - ExpectFailure("optional_bool: -7.5\n", "Expected identifier.", 1, 16); - ExpectFailure("optional_bool: !\n", "Expected identifier.", 1, 16); - - ExpectFailure( - "optional_bool: meh\n", - "Invalid value for boolean field \"optional_bool\". Value: \"meh\".", - 2, 1); - - ExpectFailure("optional_bool {\n \n}\n", "Expected \":\", found \"{\".", - 1, 15); - - // Invalid values for a string field. - ExpectFailure("optional_string: true\n", "Expected string.", 1, 18); - ExpectFailure("optional_string: 5\n", "Expected string.", 1, 18); - ExpectFailure("optional_string: -7.5\n", "Expected string.", 1, 18); - ExpectFailure("optional_string: !\n", "Expected string.", 1, 18); - ExpectFailure("optional_string {\n \n}\n", "Expected \":\", found \"{\".", - 1, 17); - - // Invalid values for an enumeration field. - ExpectFailure("optional_nested_enum: \"hello\"\n", "Expected identifier.", - 1, 23); - - ExpectFailure("optional_nested_enum: 5\n", "Expected identifier.", 1, 23); - ExpectFailure("optional_nested_enum: -7.5\n", "Expected identifier.", 1, 23); - ExpectFailure("optional_nested_enum: !\n", "Expected identifier.", 1, 23); - - ExpectFailure( - "optional_nested_enum: grah\n", - "Unknown enumeration value of \"grah\" for field " - "\"optional_nested_enum\".", 2, 1); - - ExpectFailure( - "optional_nested_enum {\n \n}\n", - "Expected \":\", found \"{\".", 1, 22); -} - -TEST_F(TextFormatParserTest, MessageDelimeters) { - // Non-matching delimeters. - ExpectFailure("OptionalGroup <\n \n}\n", "Expected \">\", found \"}\".", - 3, 1); - - // Invalid delimeters. - ExpectFailure("OptionalGroup [\n \n]\n", "Expected \"{\", found \"[\".", - 1, 15); - - // Unending message. - ExpectFailure("optional_nested_message {\n \nbb: 118\n", - "Expected identifier.", - 4, 1); -} - -TEST_F(TextFormatParserTest, UnknownExtension) { - // Non-matching delimeters. - ExpectFailure("[blahblah]: 123", - "Extension \"blahblah\" is not defined or is not an " - "extension of \"protobuf_unittest.TestAllTypes\".", - 1, 11); -} - -TEST_F(TextFormatParserTest, MissingRequired) { - unittest::TestRequired message; - ExpectFailure("a: 1", - "Message missing required fields: b, c", - 0, 1, &message); -} - -TEST_F(TextFormatParserTest, ParseDuplicateRequired) { - unittest::TestRequired message; - ExpectFailure("a: 1 b: 2 c: 3 a: 1", - "Non-repeated field \"a\" is specified multiple times.", - 1, 17, &message); -} - -TEST_F(TextFormatParserTest, ParseDuplicateOptional) { - unittest::ForeignMessage message; - ExpectFailure("c: 1 c: 2", - "Non-repeated field \"c\" is specified multiple times.", - 1, 7, &message); -} - -TEST_F(TextFormatParserTest, MergeDuplicateRequired) { - unittest::TestRequired message; - TextFormat::Parser parser; - EXPECT_TRUE(parser.MergeFromString("a: 1 b: 2 c: 3 a: 4", &message)); - EXPECT_EQ(4, message.a()); -} - -TEST_F(TextFormatParserTest, MergeDuplicateOptional) { - unittest::ForeignMessage message; - TextFormat::Parser parser; - EXPECT_TRUE(parser.MergeFromString("c: 1 c: 2", &message)); - EXPECT_EQ(2, message.c()); -} - -TEST_F(TextFormatParserTest, PrintErrorsToStderr) { - vector errors; - - { - ScopedMemoryLog log; - unittest::TestAllTypes proto; - EXPECT_FALSE(TextFormat::ParseFromString("no_such_field: 1", &proto)); - errors = log.GetMessages(ERROR); - } - - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: " - "1:14: Message type \"protobuf_unittest.TestAllTypes\" has no field " - "named \"no_such_field\".", - errors[0]); -} - -TEST_F(TextFormatParserTest, FailsOnTokenizationError) { - vector errors; - - { - ScopedMemoryLog log; - unittest::TestAllTypes proto; - EXPECT_FALSE(TextFormat::ParseFromString("\020", &proto)); - errors = log.GetMessages(ERROR); - } - - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Error parsing text-format protobuf_unittest.TestAllTypes: " - "1:1: Invalid control characters encountered in text.", - errors[0]); -} - -TEST_F(TextFormatParserTest, ParseDeprecatedField) { - unittest::TestDeprecatedFields message; - ExpectMessage("deprecated_int32: 42", - "WARNING:text format contains deprecated field " - "\"deprecated_int32\"", 1, 21, &message, true); -} - -class TextFormatMessageSetTest : public testing::Test { - protected: - static const char proto_debug_string_[]; -}; -const char TextFormatMessageSetTest::proto_debug_string_[] = -"message_set {\n" -" [protobuf_unittest.TestMessageSetExtension1] {\n" -" i: 23\n" -" }\n" -" [protobuf_unittest.TestMessageSetExtension2] {\n" -" str: \"foo\"\n" -" }\n" -"}\n"; - - -TEST_F(TextFormatMessageSetTest, Serialize) { - protobuf_unittest::TestMessageSetContainer proto; - protobuf_unittest::TestMessageSetExtension1* item_a = - proto.mutable_message_set()->MutableExtension( - protobuf_unittest::TestMessageSetExtension1::message_set_extension); - item_a->set_i(23); - protobuf_unittest::TestMessageSetExtension2* item_b = - proto.mutable_message_set()->MutableExtension( - protobuf_unittest::TestMessageSetExtension2::message_set_extension); - item_b->set_str("foo"); - EXPECT_EQ(proto_debug_string_, proto.DebugString()); -} - -TEST_F(TextFormatMessageSetTest, Deserialize) { - protobuf_unittest::TestMessageSetContainer proto; - ASSERT_TRUE(TextFormat::ParseFromString(proto_debug_string_, &proto)); - EXPECT_EQ(23, proto.message_set().GetExtension( - protobuf_unittest::TestMessageSetExtension1::message_set_extension).i()); - EXPECT_EQ("foo", proto.message_set().GetExtension( - protobuf_unittest::TestMessageSetExtension2::message_set_extension).str()); - - // Ensure that these are the only entries present. - vector descriptors; - proto.message_set().GetReflection()->ListFields( - proto.message_set(), &descriptors); - EXPECT_EQ(2, descriptors.size()); -} - -} // namespace text_format_unittest -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/unittest.proto b/Resources/NetHook/google/protobuf/unittest.proto deleted file mode 100644 index d51fa1e7..00000000 --- a/Resources/NetHook/google/protobuf/unittest.proto +++ /dev/null @@ -1,612 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// A proto file we will use for unit testing. - - -import "google/protobuf/unittest_import.proto"; - -// We don't put this in a package within proto2 because we need to make sure -// that the generated code doesn't depend on being in the proto2 namespace. -// In test_util.h we do "using namespace unittest = protobuf_unittest". -package protobuf_unittest; - -// Protos optimized for SPEED use a strict superset of the generated code -// of equivalent ones optimized for CODE_SIZE, so we should optimize all our -// tests for speed unless explicitly testing code size optimization. -option optimize_for = SPEED; - -option java_outer_classname = "UnittestProto"; - -// This proto includes every type of field in both singular and repeated -// forms. -message TestAllTypes { - message NestedMessage { - // The field name "b" fails to compile in proto1 because it conflicts with - // a local variable named "b" in one of the generated methods. Doh. - // This file needs to compile in proto1 to test backwards-compatibility. - optional int32 bb = 1; - } - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - // Singular - optional int32 optional_int32 = 1; - optional int64 optional_int64 = 2; - optional uint32 optional_uint32 = 3; - optional uint64 optional_uint64 = 4; - optional sint32 optional_sint32 = 5; - optional sint64 optional_sint64 = 6; - optional fixed32 optional_fixed32 = 7; - optional fixed64 optional_fixed64 = 8; - optional sfixed32 optional_sfixed32 = 9; - optional sfixed64 optional_sfixed64 = 10; - optional float optional_float = 11; - optional double optional_double = 12; - optional bool optional_bool = 13; - optional string optional_string = 14; - optional bytes optional_bytes = 15; - - optional group OptionalGroup = 16 { - optional int32 a = 17; - } - - optional NestedMessage optional_nested_message = 18; - optional ForeignMessage optional_foreign_message = 19; - optional protobuf_unittest_import.ImportMessage optional_import_message = 20; - - optional NestedEnum optional_nested_enum = 21; - optional ForeignEnum optional_foreign_enum = 22; - optional protobuf_unittest_import.ImportEnum optional_import_enum = 23; - - optional string optional_string_piece = 24 [ctype=STRING_PIECE]; - optional string optional_cord = 25 [ctype=CORD]; - - // Repeated - repeated int32 repeated_int32 = 31; - repeated int64 repeated_int64 = 32; - repeated uint32 repeated_uint32 = 33; - repeated uint64 repeated_uint64 = 34; - repeated sint32 repeated_sint32 = 35; - repeated sint64 repeated_sint64 = 36; - repeated fixed32 repeated_fixed32 = 37; - repeated fixed64 repeated_fixed64 = 38; - repeated sfixed32 repeated_sfixed32 = 39; - repeated sfixed64 repeated_sfixed64 = 40; - repeated float repeated_float = 41; - repeated double repeated_double = 42; - repeated bool repeated_bool = 43; - repeated string repeated_string = 44; - repeated bytes repeated_bytes = 45; - - repeated group RepeatedGroup = 46 { - optional int32 a = 47; - } - - repeated NestedMessage repeated_nested_message = 48; - repeated ForeignMessage repeated_foreign_message = 49; - repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50; - - repeated NestedEnum repeated_nested_enum = 51; - repeated ForeignEnum repeated_foreign_enum = 52; - repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53; - - repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; - repeated string repeated_cord = 55 [ctype=CORD]; - - // Singular with defaults - optional int32 default_int32 = 61 [default = 41 ]; - optional int64 default_int64 = 62 [default = 42 ]; - optional uint32 default_uint32 = 63 [default = 43 ]; - optional uint64 default_uint64 = 64 [default = 44 ]; - optional sint32 default_sint32 = 65 [default = -45 ]; - optional sint64 default_sint64 = 66 [default = 46 ]; - optional fixed32 default_fixed32 = 67 [default = 47 ]; - optional fixed64 default_fixed64 = 68 [default = 48 ]; - optional sfixed32 default_sfixed32 = 69 [default = 49 ]; - optional sfixed64 default_sfixed64 = 70 [default = -50 ]; - optional float default_float = 71 [default = 51.5 ]; - optional double default_double = 72 [default = 52e3 ]; - optional bool default_bool = 73 [default = true ]; - optional string default_string = 74 [default = "hello"]; - optional bytes default_bytes = 75 [default = "world"]; - - optional NestedEnum default_nested_enum = 81 [default = BAR ]; - optional ForeignEnum default_foreign_enum = 82 [default = FOREIGN_BAR]; - optional protobuf_unittest_import.ImportEnum - default_import_enum = 83 [default = IMPORT_BAR]; - - optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"]; - optional string default_cord = 85 [ctype=CORD,default="123"]; -} - -message TestDeprecatedFields { - optional int32 deprecated_int32 = 1 [deprecated=true]; -} - -// Define these after TestAllTypes to make sure the compiler can handle -// that. -message ForeignMessage { - optional int32 c = 1; -} - -enum ForeignEnum { - FOREIGN_FOO = 4; - FOREIGN_BAR = 5; - FOREIGN_BAZ = 6; -} - -message TestAllExtensions { - extensions 1 to max; -} - -extend TestAllExtensions { - // Singular - optional int32 optional_int32_extension = 1; - optional int64 optional_int64_extension = 2; - optional uint32 optional_uint32_extension = 3; - optional uint64 optional_uint64_extension = 4; - optional sint32 optional_sint32_extension = 5; - optional sint64 optional_sint64_extension = 6; - optional fixed32 optional_fixed32_extension = 7; - optional fixed64 optional_fixed64_extension = 8; - optional sfixed32 optional_sfixed32_extension = 9; - optional sfixed64 optional_sfixed64_extension = 10; - optional float optional_float_extension = 11; - optional double optional_double_extension = 12; - optional bool optional_bool_extension = 13; - optional string optional_string_extension = 14; - optional bytes optional_bytes_extension = 15; - - optional group OptionalGroup_extension = 16 { - optional int32 a = 17; - } - - optional TestAllTypes.NestedMessage optional_nested_message_extension = 18; - optional ForeignMessage optional_foreign_message_extension = 19; - optional protobuf_unittest_import.ImportMessage - optional_import_message_extension = 20; - - optional TestAllTypes.NestedEnum optional_nested_enum_extension = 21; - optional ForeignEnum optional_foreign_enum_extension = 22; - optional protobuf_unittest_import.ImportEnum - optional_import_enum_extension = 23; - - optional string optional_string_piece_extension = 24 [ctype=STRING_PIECE]; - optional string optional_cord_extension = 25 [ctype=CORD]; - - // Repeated - repeated int32 repeated_int32_extension = 31; - repeated int64 repeated_int64_extension = 32; - repeated uint32 repeated_uint32_extension = 33; - repeated uint64 repeated_uint64_extension = 34; - repeated sint32 repeated_sint32_extension = 35; - repeated sint64 repeated_sint64_extension = 36; - repeated fixed32 repeated_fixed32_extension = 37; - repeated fixed64 repeated_fixed64_extension = 38; - repeated sfixed32 repeated_sfixed32_extension = 39; - repeated sfixed64 repeated_sfixed64_extension = 40; - repeated float repeated_float_extension = 41; - repeated double repeated_double_extension = 42; - repeated bool repeated_bool_extension = 43; - repeated string repeated_string_extension = 44; - repeated bytes repeated_bytes_extension = 45; - - repeated group RepeatedGroup_extension = 46 { - optional int32 a = 47; - } - - repeated TestAllTypes.NestedMessage repeated_nested_message_extension = 48; - repeated ForeignMessage repeated_foreign_message_extension = 49; - repeated protobuf_unittest_import.ImportMessage - repeated_import_message_extension = 50; - - repeated TestAllTypes.NestedEnum repeated_nested_enum_extension = 51; - repeated ForeignEnum repeated_foreign_enum_extension = 52; - repeated protobuf_unittest_import.ImportEnum - repeated_import_enum_extension = 53; - - repeated string repeated_string_piece_extension = 54 [ctype=STRING_PIECE]; - repeated string repeated_cord_extension = 55 [ctype=CORD]; - - // Singular with defaults - optional int32 default_int32_extension = 61 [default = 41 ]; - optional int64 default_int64_extension = 62 [default = 42 ]; - optional uint32 default_uint32_extension = 63 [default = 43 ]; - optional uint64 default_uint64_extension = 64 [default = 44 ]; - optional sint32 default_sint32_extension = 65 [default = -45 ]; - optional sint64 default_sint64_extension = 66 [default = 46 ]; - optional fixed32 default_fixed32_extension = 67 [default = 47 ]; - optional fixed64 default_fixed64_extension = 68 [default = 48 ]; - optional sfixed32 default_sfixed32_extension = 69 [default = 49 ]; - optional sfixed64 default_sfixed64_extension = 70 [default = -50 ]; - optional float default_float_extension = 71 [default = 51.5 ]; - optional double default_double_extension = 72 [default = 52e3 ]; - optional bool default_bool_extension = 73 [default = true ]; - optional string default_string_extension = 74 [default = "hello"]; - optional bytes default_bytes_extension = 75 [default = "world"]; - - optional TestAllTypes.NestedEnum - default_nested_enum_extension = 81 [default = BAR]; - optional ForeignEnum - default_foreign_enum_extension = 82 [default = FOREIGN_BAR]; - optional protobuf_unittest_import.ImportEnum - default_import_enum_extension = 83 [default = IMPORT_BAR]; - - optional string default_string_piece_extension = 84 [ctype=STRING_PIECE, - default="abc"]; - optional string default_cord_extension = 85 [ctype=CORD, default="123"]; -} - -message TestNestedExtension { - extend TestAllExtensions { - // Check for bug where string extensions declared in tested scope did not - // compile. - optional string test = 1002 [default="test"]; - } -} - -// We have separate messages for testing required fields because it's -// annoying to have to fill in required fields in TestProto in order to -// do anything with it. Note that we don't need to test every type of -// required filed because the code output is basically identical to -// optional fields for all types. -message TestRequired { - required int32 a = 1; - optional int32 dummy2 = 2; - required int32 b = 3; - - extend TestAllExtensions { - optional TestRequired single = 1000; - repeated TestRequired multi = 1001; - } - - // Pad the field count to 32 so that we can test that IsInitialized() - // properly checks multiple elements of has_bits_. - optional int32 dummy4 = 4; - optional int32 dummy5 = 5; - optional int32 dummy6 = 6; - optional int32 dummy7 = 7; - optional int32 dummy8 = 8; - optional int32 dummy9 = 9; - optional int32 dummy10 = 10; - optional int32 dummy11 = 11; - optional int32 dummy12 = 12; - optional int32 dummy13 = 13; - optional int32 dummy14 = 14; - optional int32 dummy15 = 15; - optional int32 dummy16 = 16; - optional int32 dummy17 = 17; - optional int32 dummy18 = 18; - optional int32 dummy19 = 19; - optional int32 dummy20 = 20; - optional int32 dummy21 = 21; - optional int32 dummy22 = 22; - optional int32 dummy23 = 23; - optional int32 dummy24 = 24; - optional int32 dummy25 = 25; - optional int32 dummy26 = 26; - optional int32 dummy27 = 27; - optional int32 dummy28 = 28; - optional int32 dummy29 = 29; - optional int32 dummy30 = 30; - optional int32 dummy31 = 31; - optional int32 dummy32 = 32; - - required int32 c = 33; -} - -message TestRequiredForeign { - optional TestRequired optional_message = 1; - repeated TestRequired repeated_message = 2; - optional int32 dummy = 3; -} - -// Test that we can use NestedMessage from outside TestAllTypes. -message TestForeignNested { - optional TestAllTypes.NestedMessage foreign_nested = 1; -} - -// TestEmptyMessage is used to test unknown field support. -message TestEmptyMessage { -} - -// Like above, but declare all field numbers as potential extensions. No -// actual extensions should ever be defined for this type. -message TestEmptyMessageWithExtensions { - extensions 1 to max; -} - -message TestMultipleExtensionRanges { - extensions 42; - extensions 4143 to 4243; - extensions 65536 to max; -} - -// Test that really large tag numbers don't break anything. -message TestReallyLargeTagNumber { - // The largest possible tag number is 2^28 - 1, since the wire format uses - // three bits to communicate wire type. - optional int32 a = 1; - optional int32 bb = 268435455; -} - -message TestRecursiveMessage { - optional TestRecursiveMessage a = 1; - optional int32 i = 2; -} - -// Test that mutual recursion works. -message TestMutualRecursionA { - optional TestMutualRecursionB bb = 1; -} - -message TestMutualRecursionB { - optional TestMutualRecursionA a = 1; - optional int32 optional_int32 = 2; -} - -// Test that groups have disjoint field numbers from their siblings and -// parents. This is NOT possible in proto1; only proto2. When attempting -// to compile with proto1, this will emit an error; so we only include it -// in protobuf_unittest_proto. -message TestDupFieldNumber { // NO_PROTO1 - optional int32 a = 1; // NO_PROTO1 - optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1 - optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1 -} // NO_PROTO1 - - -// Needed for a Python test. -message TestNestedMessageHasBits { - message NestedMessage { - repeated int32 nestedmessage_repeated_int32 = 1; - repeated ForeignMessage nestedmessage_repeated_foreignmessage = 2; - } - optional NestedMessage optional_nested_message = 1; -} - - -// Test an enum that has multiple values with the same number. -enum TestEnumWithDupValue { - FOO1 = 1; - BAR1 = 2; - BAZ = 3; - FOO2 = 1; - BAR2 = 2; -} - -// Test an enum with large, unordered values. -enum TestSparseEnum { - SPARSE_A = 123; - SPARSE_B = 62374; - SPARSE_C = 12589234; - SPARSE_D = -15; - SPARSE_E = -53452; - SPARSE_F = 0; - SPARSE_G = 2; -} - -// Test message with CamelCase field names. This violates Protocol Buffer -// standard style. -message TestCamelCaseFieldNames { - optional int32 PrimitiveField = 1; - optional string StringField = 2; - optional ForeignEnum EnumField = 3; - optional ForeignMessage MessageField = 4; - optional string StringPieceField = 5 [ctype=STRING_PIECE]; - optional string CordField = 6 [ctype=CORD]; - - repeated int32 RepeatedPrimitiveField = 7; - repeated string RepeatedStringField = 8; - repeated ForeignEnum RepeatedEnumField = 9; - repeated ForeignMessage RepeatedMessageField = 10; - repeated string RepeatedStringPieceField = 11 [ctype=STRING_PIECE]; - repeated string RepeatedCordField = 12 [ctype=CORD]; -} - - -// We list fields out of order, to ensure that we're using field number and not -// field index to determine serialization order. -message TestFieldOrderings { - optional string my_string = 11; - extensions 2 to 10; - optional int64 my_int = 1; - extensions 12 to 100; - optional float my_float = 101; -} - - -extend TestFieldOrderings { - optional string my_extension_string = 50; - optional int32 my_extension_int = 5; -} - - -message TestExtremeDefaultValues { - optional bytes escaped_bytes = 1 [default = "\0\001\a\b\f\n\r\t\v\\\'\"\xfe"]; - optional uint32 large_uint32 = 2 [default = 0xFFFFFFFF]; - optional uint64 large_uint64 = 3 [default = 0xFFFFFFFFFFFFFFFF]; - optional int32 small_int32 = 4 [default = -0x7FFFFFFF]; - optional int64 small_int64 = 5 [default = -0x7FFFFFFFFFFFFFFF]; - - // The default value here is UTF-8 for "\u1234". (We could also just type - // the UTF-8 text directly into this text file rather than escape it, but - // lots of people use editors that would be confused by this.) - optional string utf8_string = 6 [default = "\341\210\264"]; - - // Tests for single-precision floating-point values. - optional float zero_float = 7 [default = 0]; - optional float one_float = 8 [default = 1]; - optional float small_float = 9 [default = 1.5]; - optional float negative_one_float = 10 [default = -1]; - optional float negative_float = 11 [default = -1.5]; - // Using exponents - optional float large_float = 12 [default = 2E8]; - optional float small_negative_float = 13 [default = -8e-28]; - - // Text for nonfinite floating-point values. - optional double inf_double = 14 [default = inf]; - optional double neg_inf_double = 15 [default = -inf]; - optional double nan_double = 16 [default = nan]; - optional float inf_float = 17 [default = inf]; - optional float neg_inf_float = 18 [default = -inf]; - optional float nan_float = 19 [default = nan]; -} - -// Test String and Bytes: string is for valid UTF-8 strings -message OneString { - optional string data = 1; -} - -message OneBytes { - optional bytes data = 1; -} - -// Test messages for packed fields - -message TestPackedTypes { - repeated int32 packed_int32 = 90 [packed = true]; - repeated int64 packed_int64 = 91 [packed = true]; - repeated uint32 packed_uint32 = 92 [packed = true]; - repeated uint64 packed_uint64 = 93 [packed = true]; - repeated sint32 packed_sint32 = 94 [packed = true]; - repeated sint64 packed_sint64 = 95 [packed = true]; - repeated fixed32 packed_fixed32 = 96 [packed = true]; - repeated fixed64 packed_fixed64 = 97 [packed = true]; - repeated sfixed32 packed_sfixed32 = 98 [packed = true]; - repeated sfixed64 packed_sfixed64 = 99 [packed = true]; - repeated float packed_float = 100 [packed = true]; - repeated double packed_double = 101 [packed = true]; - repeated bool packed_bool = 102 [packed = true]; - repeated ForeignEnum packed_enum = 103 [packed = true]; -} - -// A message with the same fields as TestPackedTypes, but without packing. Used -// to test packed <-> unpacked wire compatibility. -message TestUnpackedTypes { - repeated int32 unpacked_int32 = 90 [packed = false]; - repeated int64 unpacked_int64 = 91 [packed = false]; - repeated uint32 unpacked_uint32 = 92 [packed = false]; - repeated uint64 unpacked_uint64 = 93 [packed = false]; - repeated sint32 unpacked_sint32 = 94 [packed = false]; - repeated sint64 unpacked_sint64 = 95 [packed = false]; - repeated fixed32 unpacked_fixed32 = 96 [packed = false]; - repeated fixed64 unpacked_fixed64 = 97 [packed = false]; - repeated sfixed32 unpacked_sfixed32 = 98 [packed = false]; - repeated sfixed64 unpacked_sfixed64 = 99 [packed = false]; - repeated float unpacked_float = 100 [packed = false]; - repeated double unpacked_double = 101 [packed = false]; - repeated bool unpacked_bool = 102 [packed = false]; - repeated ForeignEnum unpacked_enum = 103 [packed = false]; -} - -message TestPackedExtensions { - extensions 1 to max; -} - -extend TestPackedExtensions { - repeated int32 packed_int32_extension = 90 [packed = true]; - repeated int64 packed_int64_extension = 91 [packed = true]; - repeated uint32 packed_uint32_extension = 92 [packed = true]; - repeated uint64 packed_uint64_extension = 93 [packed = true]; - repeated sint32 packed_sint32_extension = 94 [packed = true]; - repeated sint64 packed_sint64_extension = 95 [packed = true]; - repeated fixed32 packed_fixed32_extension = 96 [packed = true]; - repeated fixed64 packed_fixed64_extension = 97 [packed = true]; - repeated sfixed32 packed_sfixed32_extension = 98 [packed = true]; - repeated sfixed64 packed_sfixed64_extension = 99 [packed = true]; - repeated float packed_float_extension = 100 [packed = true]; - repeated double packed_double_extension = 101 [packed = true]; - repeated bool packed_bool_extension = 102 [packed = true]; - repeated ForeignEnum packed_enum_extension = 103 [packed = true]; -} - -// Used by ExtensionSetTest/DynamicExtensions. The test actually builds -// a set of extensions to TestAllExtensions dynamically, based on the fields -// of this message type. -message TestDynamicExtensions { - enum DynamicEnumType { - DYNAMIC_FOO = 2200; - DYNAMIC_BAR = 2201; - DYNAMIC_BAZ = 2202; - } - message DynamicMessageType { - optional int32 dynamic_field = 2100; - } - - optional fixed32 scalar_extension = 2000; - optional ForeignEnum enum_extension = 2001; - optional DynamicEnumType dynamic_enum_extension = 2002; - - optional ForeignMessage message_extension = 2003; - optional DynamicMessageType dynamic_message_extension = 2004; - - repeated string repeated_extension = 2005; - repeated sint32 packed_extension = 2006 [packed = true]; -} - -message TestRepeatedScalarDifferentTagSizes { - // Parsing repeated fixed size values used to fail. This message needs to be - // used in order to get a tag of the right size; all of the repeated fields - // in TestAllTypes didn't trigger the check. - repeated fixed32 repeated_fixed32 = 12; - // Check for a varint type, just for good measure. - repeated int32 repeated_int32 = 13; - - // These have two-byte tags. - repeated fixed64 repeated_fixed64 = 2046; - repeated int64 repeated_int64 = 2047; - - // Three byte tags. - repeated float repeated_float = 262142; - repeated uint64 repeated_uint64 = 262143; -} - -// Test that RPC services work. -message FooRequest {} -message FooResponse {} - -service TestService { - rpc Foo(FooRequest) returns (FooResponse); - rpc Bar(BarRequest) returns (BarResponse); -} - - -message BarRequest {} -message BarResponse {} diff --git a/Resources/NetHook/google/protobuf/unittest_custom_options.proto b/Resources/NetHook/google/protobuf/unittest_custom_options.proto deleted file mode 100644 index b6ee03da..00000000 --- a/Resources/NetHook/google/protobuf/unittest_custom_options.proto +++ /dev/null @@ -1,275 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: benjy@google.com (Benjy Weinberger) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// A proto file used to test the "custom options" feature of proto2. - - -// A custom file option (defined below). -option (file_opt1) = 9876543210; - -import "google/protobuf/descriptor.proto"; - -// We don't put this in a package within proto2 because we need to make sure -// that the generated code doesn't depend on being in the proto2 namespace. -package protobuf_unittest; - - -// Some simple test custom options of various types. - -extend google.protobuf.FileOptions { - optional uint64 file_opt1 = 7736974; -} - -extend google.protobuf.MessageOptions { - optional int32 message_opt1 = 7739036; -} - -extend google.protobuf.FieldOptions { - optional fixed64 field_opt1 = 7740936; - // This is useful for testing that we correctly register default values for - // extension options. - optional int32 field_opt2 = 7753913 [default=42]; -} - -extend google.protobuf.EnumOptions { - optional sfixed32 enum_opt1 = 7753576; -} - -extend google.protobuf.EnumValueOptions { - optional int32 enum_value_opt1 = 1560678; -} - -extend google.protobuf.ServiceOptions { - optional sint64 service_opt1 = 7887650; -} - -enum MethodOpt1 { - METHODOPT1_VAL1 = 1; - METHODOPT1_VAL2 = 2; -} - -extend google.protobuf.MethodOptions { - optional MethodOpt1 method_opt1 = 7890860; -} - -// A test message with custom options at all possible locations (and also some -// regular options, to make sure they interact nicely). -message TestMessageWithCustomOptions { - option message_set_wire_format = false; - - option (message_opt1) = -56; - - optional string field1 = 1 [ctype=CORD, - (field_opt1)=8765432109]; - - enum AnEnum { - option (enum_opt1) = -789; - - ANENUM_VAL1 = 1; - ANENUM_VAL2 = 2 [(enum_value_opt1) = 123]; - } -} - - -// A test RPC service with custom options at all possible locations (and also -// some regular options, to make sure they interact nicely). -message CustomOptionFooRequest { -} - -message CustomOptionFooResponse { -} - -service TestServiceWithCustomOptions { - option (service_opt1) = -9876543210; - - rpc Foo(CustomOptionFooRequest) returns (CustomOptionFooResponse) { - option (method_opt1) = METHODOPT1_VAL2; - } -} - - - -// Options of every possible field type, so we can test them all exhaustively. - -message DummyMessageContainingEnum { - enum TestEnumType { - TEST_OPTION_ENUM_TYPE1 = 22; - TEST_OPTION_ENUM_TYPE2 = -23; - } -} - -message DummyMessageInvalidAsOptionType { -} - -extend google.protobuf.MessageOptions { - optional bool bool_opt = 7706090; - optional int32 int32_opt = 7705709; - optional int64 int64_opt = 7705542; - optional uint32 uint32_opt = 7704880; - optional uint64 uint64_opt = 7702367; - optional sint32 sint32_opt = 7701568; - optional sint64 sint64_opt = 7700863; - optional fixed32 fixed32_opt = 7700307; - optional fixed64 fixed64_opt = 7700194; - optional sfixed32 sfixed32_opt = 7698645; - optional sfixed64 sfixed64_opt = 7685475; - optional float float_opt = 7675390; - optional double double_opt = 7673293; - optional string string_opt = 7673285; - optional bytes bytes_opt = 7673238; - optional DummyMessageContainingEnum.TestEnumType enum_opt = 7673233; - optional DummyMessageInvalidAsOptionType message_type_opt = 7665967; -} - -message CustomOptionMinIntegerValues { - option (bool_opt) = false; - option (int32_opt) = -0x80000000; - option (int64_opt) = -0x8000000000000000; - option (uint32_opt) = 0; - option (uint64_opt) = 0; - option (sint32_opt) = -0x80000000; - option (sint64_opt) = -0x8000000000000000; - option (fixed32_opt) = 0; - option (fixed64_opt) = 0; - option (sfixed32_opt) = -0x80000000; - option (sfixed64_opt) = -0x8000000000000000; -} - -message CustomOptionMaxIntegerValues { - option (bool_opt) = true; - option (int32_opt) = 0x7FFFFFFF; - option (int64_opt) = 0x7FFFFFFFFFFFFFFF; - option (uint32_opt) = 0xFFFFFFFF; - option (uint64_opt) = 0xFFFFFFFFFFFFFFFF; - option (sint32_opt) = 0x7FFFFFFF; - option (sint64_opt) = 0x7FFFFFFFFFFFFFFF; - option (fixed32_opt) = 0xFFFFFFFF; - option (fixed64_opt) = 0xFFFFFFFFFFFFFFFF; - option (sfixed32_opt) = 0x7FFFFFFF; - option (sfixed64_opt) = 0x7FFFFFFFFFFFFFFF; -} - -message CustomOptionOtherValues { - option (int32_opt) = -100; // To test sign-extension. - option (float_opt) = 12.3456789; - option (double_opt) = 1.234567890123456789; - option (string_opt) = "Hello, \"World\""; - option (bytes_opt) = "Hello\0World"; - option (enum_opt) = TEST_OPTION_ENUM_TYPE2; -} - -message SettingRealsFromPositiveInts { - option (float_opt) = 12; - option (double_opt) = 154; -} - -message SettingRealsFromNegativeInts { - option (float_opt) = -12; - option (double_opt) = -154; -} - -// Options of complex message types, themselves combined and extended in -// various ways. - -message ComplexOptionType1 { - optional int32 foo = 1; - optional int32 foo2 = 2; - optional int32 foo3 = 3; - - extensions 100 to max; -} - -message ComplexOptionType2 { - optional ComplexOptionType1 bar = 1; - optional int32 baz = 2; - - message ComplexOptionType4 { - optional int32 waldo = 1; - - extend google.protobuf.MessageOptions { - optional ComplexOptionType4 complex_opt4 = 7633546; - } - } - - optional ComplexOptionType4 fred = 3; - - extensions 100 to max; -} - -message ComplexOptionType3 { - optional int32 qux = 1; - - optional group ComplexOptionType5 = 2 { - optional int32 plugh = 3; - } -} - -extend ComplexOptionType1 { - optional int32 quux = 7663707; - optional ComplexOptionType3 corge = 7663442; -} - -extend ComplexOptionType2 { - optional int32 grault = 7650927; - optional ComplexOptionType1 garply = 7649992; -} - -extend google.protobuf.MessageOptions { - optional protobuf_unittest.ComplexOptionType1 complex_opt1 = 7646756; - optional ComplexOptionType2 complex_opt2 = 7636949; - optional ComplexOptionType3 complex_opt3 = 7636463; - optional group ComplexOpt6 = 7595468 { - optional int32 xyzzy = 7593951; - } -} - -// Note that we try various different ways of naming the same extension. -message VariousComplexOptions { - option (.protobuf_unittest.complex_opt1).foo = 42; - option (protobuf_unittest.complex_opt1).(.protobuf_unittest.quux) = 324; - option (.protobuf_unittest.complex_opt1).(protobuf_unittest.corge).qux = 876; - option (complex_opt2).baz = 987; - option (complex_opt2).(grault) = 654; - option (complex_opt2).bar.foo = 743; - option (complex_opt2).bar.(quux) = 1999; - option (complex_opt2).bar.(protobuf_unittest.corge).qux = 2008; - option (complex_opt2).(garply).foo = 741; - option (complex_opt2).(garply).(.protobuf_unittest.quux) = 1998; - option (complex_opt2).(protobuf_unittest.garply).(corge).qux = 2121; - option (ComplexOptionType2.ComplexOptionType4.complex_opt4).waldo = 1971; - option (complex_opt2).fred.waldo = 321; - option (protobuf_unittest.complex_opt3).qux = 9; - option (complex_opt3).complexoptiontype5.plugh = 22; - option (complexopt6).xyzzy = 24; -} diff --git a/Resources/NetHook/google/protobuf/unittest_embed_optimize_for.proto b/Resources/NetHook/google/protobuf/unittest_embed_optimize_for.proto deleted file mode 100644 index fa176259..00000000 --- a/Resources/NetHook/google/protobuf/unittest_embed_optimize_for.proto +++ /dev/null @@ -1,50 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// A proto file which imports a proto file that uses optimize_for = CODE_SIZE. - -import "google/protobuf/unittest_optimize_for.proto"; - -package protobuf_unittest; - -// We optimize for speed here, but we are importing a proto that is optimized -// for code size. -option optimize_for = SPEED; - -message TestEmbedOptimizedForSize { - // Test that embedding a message which has optimize_for = CODE_SIZE into - // one optimized for speed works. - optional TestOptimizedForSize optional_message = 1; - repeated TestOptimizedForSize repeated_message = 2; -} diff --git a/Resources/NetHook/google/protobuf/unittest_empty.proto b/Resources/NetHook/google/protobuf/unittest_empty.proto deleted file mode 100644 index ab12d1fb..00000000 --- a/Resources/NetHook/google/protobuf/unittest_empty.proto +++ /dev/null @@ -1,37 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file intentionally left blank. (At one point this wouldn't compile -// correctly.) - diff --git a/Resources/NetHook/google/protobuf/unittest_enormous_descriptor.proto b/Resources/NetHook/google/protobuf/unittest_enormous_descriptor.proto deleted file mode 100644 index bc0b7c16..00000000 --- a/Resources/NetHook/google/protobuf/unittest_enormous_descriptor.proto +++ /dev/null @@ -1,1046 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// A proto file that has an extremely large descriptor. Used to test that -// descriptors over 64k don't break the string literal length limit in Java. - - -package google.protobuf; -option java_package = "com.google.protobuf"; - -// Avoid generating insanely long methods. -option optimize_for = CODE_SIZE; - -message TestEnormousDescriptor { - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1 = 1 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_2 = 2 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_3 = 3 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_4 = 4 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_5 = 5 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_6 = 6 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_7 = 7 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_8 = 8 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_9 = 9 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_10 = 10 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_11 = 11 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_12 = 12 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_13 = 13 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_14 = 14 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_15 = 15 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_16 = 16 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_17 = 17 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_18 = 18 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_19 = 19 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_20 = 20 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_21 = 21 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_22 = 22 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_23 = 23 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_24 = 24 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_25 = 25 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_26 = 26 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_27 = 27 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_28 = 28 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_29 = 29 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_30 = 30 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_31 = 31 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_32 = 32 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_33 = 33 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_34 = 34 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_35 = 35 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_36 = 36 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_37 = 37 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_38 = 38 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_39 = 39 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_40 = 40 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_41 = 41 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_42 = 42 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_43 = 43 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_44 = 44 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_45 = 45 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_46 = 46 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_47 = 47 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_48 = 48 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_49 = 49 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_50 = 50 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_51 = 51 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_52 = 52 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_53 = 53 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_54 = 54 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_55 = 55 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_56 = 56 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_57 = 57 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_58 = 58 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_59 = 59 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_60 = 60 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_61 = 61 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_62 = 62 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_63 = 63 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_64 = 64 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_65 = 65 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_66 = 66 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_67 = 67 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_68 = 68 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_69 = 69 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_70 = 70 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_71 = 71 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_72 = 72 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_73 = 73 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_74 = 74 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_75 = 75 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_76 = 76 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_77 = 77 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_78 = 78 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_79 = 79 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_80 = 80 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_81 = 81 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_82 = 82 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_83 = 83 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_84 = 84 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_85 = 85 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_86 = 86 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_87 = 87 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_88 = 88 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_89 = 89 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_90 = 90 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_91 = 91 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_92 = 92 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_93 = 93 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_94 = 94 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_95 = 95 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_96 = 96 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_97 = 97 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_98 = 98 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_99 = 99 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_100 = 100 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_101 = 101 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_102 = 102 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_103 = 103 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_104 = 104 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_105 = 105 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_106 = 106 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_107 = 107 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_108 = 108 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_109 = 109 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_110 = 110 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_111 = 111 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_112 = 112 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_113 = 113 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_114 = 114 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_115 = 115 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_116 = 116 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_117 = 117 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_118 = 118 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_119 = 119 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_120 = 120 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_121 = 121 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_122 = 122 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_123 = 123 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_124 = 124 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_125 = 125 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_126 = 126 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_127 = 127 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_128 = 128 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_129 = 129 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_130 = 130 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_131 = 131 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_132 = 132 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_133 = 133 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_134 = 134 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_135 = 135 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_136 = 136 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_137 = 137 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_138 = 138 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_139 = 139 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_140 = 140 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_141 = 141 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_142 = 142 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_143 = 143 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_144 = 144 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_145 = 145 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_146 = 146 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_147 = 147 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_148 = 148 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_149 = 149 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_150 = 150 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_151 = 151 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_152 = 152 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_153 = 153 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_154 = 154 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_155 = 155 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_156 = 156 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_157 = 157 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_158 = 158 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_159 = 159 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_160 = 160 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_161 = 161 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_162 = 162 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_163 = 163 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_164 = 164 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_165 = 165 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_166 = 166 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_167 = 167 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_168 = 168 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_169 = 169 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_170 = 170 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_171 = 171 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_172 = 172 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_173 = 173 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_174 = 174 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_175 = 175 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_176 = 176 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_177 = 177 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_178 = 178 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_179 = 179 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_180 = 180 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_181 = 181 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_182 = 182 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_183 = 183 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_184 = 184 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_185 = 185 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_186 = 186 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_187 = 187 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_188 = 188 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_189 = 189 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_190 = 190 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_191 = 191 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_192 = 192 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_193 = 193 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_194 = 194 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_195 = 195 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_196 = 196 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_197 = 197 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_198 = 198 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_199 = 199 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_200 = 200 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_201 = 201 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_202 = 202 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_203 = 203 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_204 = 204 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_205 = 205 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_206 = 206 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_207 = 207 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_208 = 208 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_209 = 209 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_210 = 210 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_211 = 211 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_212 = 212 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_213 = 213 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_214 = 214 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_215 = 215 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_216 = 216 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_217 = 217 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_218 = 218 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_219 = 219 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_220 = 220 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_221 = 221 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_222 = 222 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_223 = 223 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_224 = 224 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_225 = 225 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_226 = 226 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_227 = 227 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_228 = 228 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_229 = 229 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_230 = 230 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_231 = 231 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_232 = 232 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_233 = 233 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_234 = 234 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_235 = 235 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_236 = 236 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_237 = 237 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_238 = 238 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_239 = 239 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_240 = 240 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_241 = 241 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_242 = 242 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_243 = 243 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_244 = 244 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_245 = 245 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_246 = 246 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_247 = 247 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_248 = 248 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_249 = 249 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_250 = 250 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_251 = 251 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_252 = 252 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_253 = 253 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_254 = 254 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_255 = 255 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_256 = 256 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_257 = 257 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_258 = 258 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_259 = 259 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_260 = 260 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_261 = 261 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_262 = 262 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_263 = 263 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_264 = 264 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_265 = 265 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_266 = 266 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_267 = 267 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_268 = 268 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_269 = 269 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_270 = 270 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_271 = 271 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_272 = 272 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_273 = 273 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_274 = 274 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_275 = 275 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_276 = 276 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_277 = 277 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_278 = 278 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_279 = 279 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_280 = 280 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_281 = 281 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_282 = 282 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_283 = 283 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_284 = 284 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_285 = 285 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_286 = 286 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_287 = 287 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_288 = 288 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_289 = 289 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_290 = 290 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_291 = 291 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_292 = 292 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_293 = 293 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_294 = 294 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_295 = 295 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_296 = 296 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_297 = 297 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_298 = 298 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_299 = 299 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_300 = 300 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_301 = 301 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_302 = 302 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_303 = 303 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_304 = 304 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_305 = 305 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_306 = 306 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_307 = 307 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_308 = 308 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_309 = 309 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_310 = 310 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_311 = 311 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_312 = 312 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_313 = 313 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_314 = 314 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_315 = 315 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_316 = 316 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_317 = 317 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_318 = 318 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_319 = 319 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_320 = 320 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_321 = 321 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_322 = 322 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_323 = 323 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_324 = 324 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_325 = 325 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_326 = 326 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_327 = 327 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_328 = 328 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_329 = 329 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_330 = 330 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_331 = 331 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_332 = 332 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_333 = 333 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_334 = 334 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_335 = 335 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_336 = 336 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_337 = 337 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_338 = 338 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_339 = 339 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_340 = 340 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_341 = 341 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_342 = 342 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_343 = 343 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_344 = 344 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_345 = 345 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_346 = 346 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_347 = 347 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_348 = 348 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_349 = 349 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_350 = 350 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_351 = 351 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_352 = 352 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_353 = 353 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_354 = 354 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_355 = 355 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_356 = 356 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_357 = 357 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_358 = 358 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_359 = 359 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_360 = 360 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_361 = 361 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_362 = 362 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_363 = 363 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_364 = 364 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_365 = 365 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_366 = 366 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_367 = 367 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_368 = 368 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_369 = 369 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_370 = 370 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_371 = 371 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_372 = 372 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_373 = 373 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_374 = 374 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_375 = 375 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_376 = 376 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_377 = 377 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_378 = 378 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_379 = 379 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_380 = 380 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_381 = 381 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_382 = 382 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_383 = 383 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_384 = 384 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_385 = 385 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_386 = 386 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_387 = 387 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_388 = 388 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_389 = 389 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_390 = 390 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_391 = 391 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_392 = 392 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_393 = 393 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_394 = 394 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_395 = 395 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_396 = 396 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_397 = 397 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_398 = 398 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_399 = 399 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_400 = 400 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_401 = 401 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_402 = 402 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_403 = 403 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_404 = 404 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_405 = 405 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_406 = 406 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_407 = 407 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_408 = 408 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_409 = 409 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_410 = 410 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_411 = 411 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_412 = 412 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_413 = 413 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_414 = 414 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_415 = 415 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_416 = 416 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_417 = 417 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_418 = 418 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_419 = 419 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_420 = 420 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_421 = 421 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_422 = 422 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_423 = 423 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_424 = 424 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_425 = 425 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_426 = 426 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_427 = 427 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_428 = 428 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_429 = 429 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_430 = 430 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_431 = 431 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_432 = 432 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_433 = 433 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_434 = 434 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_435 = 435 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_436 = 436 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_437 = 437 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_438 = 438 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_439 = 439 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_440 = 440 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_441 = 441 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_442 = 442 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_443 = 443 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_444 = 444 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_445 = 445 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_446 = 446 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_447 = 447 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_448 = 448 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_449 = 449 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_450 = 450 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_451 = 451 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_452 = 452 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_453 = 453 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_454 = 454 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_455 = 455 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_456 = 456 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_457 = 457 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_458 = 458 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_459 = 459 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_460 = 460 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_461 = 461 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_462 = 462 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_463 = 463 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_464 = 464 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_465 = 465 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_466 = 466 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_467 = 467 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_468 = 468 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_469 = 469 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_470 = 470 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_471 = 471 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_472 = 472 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_473 = 473 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_474 = 474 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_475 = 475 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_476 = 476 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_477 = 477 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_478 = 478 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_479 = 479 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_480 = 480 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_481 = 481 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_482 = 482 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_483 = 483 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_484 = 484 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_485 = 485 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_486 = 486 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_487 = 487 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_488 = 488 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_489 = 489 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_490 = 490 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_491 = 491 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_492 = 492 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_493 = 493 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_494 = 494 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_495 = 495 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_496 = 496 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_497 = 497 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_498 = 498 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_499 = 499 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_500 = 500 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_501 = 501 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_502 = 502 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_503 = 503 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_504 = 504 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_505 = 505 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_506 = 506 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_507 = 507 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_508 = 508 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_509 = 509 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_510 = 510 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_511 = 511 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_512 = 512 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_513 = 513 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_514 = 514 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_515 = 515 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_516 = 516 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_517 = 517 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_518 = 518 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_519 = 519 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_520 = 520 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_521 = 521 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_522 = 522 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_523 = 523 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_524 = 524 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_525 = 525 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_526 = 526 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_527 = 527 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_528 = 528 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_529 = 529 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_530 = 530 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_531 = 531 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_532 = 532 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_533 = 533 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_534 = 534 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_535 = 535 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_536 = 536 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_537 = 537 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_538 = 538 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_539 = 539 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_540 = 540 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_541 = 541 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_542 = 542 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_543 = 543 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_544 = 544 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_545 = 545 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_546 = 546 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_547 = 547 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_548 = 548 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_549 = 549 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_550 = 550 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_551 = 551 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_552 = 552 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_553 = 553 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_554 = 554 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_555 = 555 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_556 = 556 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_557 = 557 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_558 = 558 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_559 = 559 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_560 = 560 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_561 = 561 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_562 = 562 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_563 = 563 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_564 = 564 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_565 = 565 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_566 = 566 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_567 = 567 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_568 = 568 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_569 = 569 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_570 = 570 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_571 = 571 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_572 = 572 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_573 = 573 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_574 = 574 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_575 = 575 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_576 = 576 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_577 = 577 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_578 = 578 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_579 = 579 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_580 = 580 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_581 = 581 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_582 = 582 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_583 = 583 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_584 = 584 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_585 = 585 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_586 = 586 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_587 = 587 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_588 = 588 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_589 = 589 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_590 = 590 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_591 = 591 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_592 = 592 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_593 = 593 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_594 = 594 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_595 = 595 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_596 = 596 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_597 = 597 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_598 = 598 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_599 = 599 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_600 = 600 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_601 = 601 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_602 = 602 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_603 = 603 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_604 = 604 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_605 = 605 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_606 = 606 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_607 = 607 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_608 = 608 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_609 = 609 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_610 = 610 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_611 = 611 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_612 = 612 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_613 = 613 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_614 = 614 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_615 = 615 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_616 = 616 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_617 = 617 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_618 = 618 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_619 = 619 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_620 = 620 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_621 = 621 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_622 = 622 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_623 = 623 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_624 = 624 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_625 = 625 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_626 = 626 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_627 = 627 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_628 = 628 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_629 = 629 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_630 = 630 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_631 = 631 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_632 = 632 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_633 = 633 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_634 = 634 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_635 = 635 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_636 = 636 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_637 = 637 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_638 = 638 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_639 = 639 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_640 = 640 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_641 = 641 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_642 = 642 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_643 = 643 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_644 = 644 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_645 = 645 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_646 = 646 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_647 = 647 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_648 = 648 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_649 = 649 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_650 = 650 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_651 = 651 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_652 = 652 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_653 = 653 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_654 = 654 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_655 = 655 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_656 = 656 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_657 = 657 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_658 = 658 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_659 = 659 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_660 = 660 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_661 = 661 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_662 = 662 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_663 = 663 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_664 = 664 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_665 = 665 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_666 = 666 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_667 = 667 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_668 = 668 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_669 = 669 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_670 = 670 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_671 = 671 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_672 = 672 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_673 = 673 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_674 = 674 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_675 = 675 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_676 = 676 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_677 = 677 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_678 = 678 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_679 = 679 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_680 = 680 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_681 = 681 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_682 = 682 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_683 = 683 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_684 = 684 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_685 = 685 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_686 = 686 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_687 = 687 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_688 = 688 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_689 = 689 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_690 = 690 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_691 = 691 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_692 = 692 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_693 = 693 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_694 = 694 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_695 = 695 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_696 = 696 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_697 = 697 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_698 = 698 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_699 = 699 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_700 = 700 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_701 = 701 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_702 = 702 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_703 = 703 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_704 = 704 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_705 = 705 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_706 = 706 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_707 = 707 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_708 = 708 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_709 = 709 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_710 = 710 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_711 = 711 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_712 = 712 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_713 = 713 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_714 = 714 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_715 = 715 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_716 = 716 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_717 = 717 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_718 = 718 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_719 = 719 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_720 = 720 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_721 = 721 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_722 = 722 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_723 = 723 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_724 = 724 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_725 = 725 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_726 = 726 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_727 = 727 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_728 = 728 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_729 = 729 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_730 = 730 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_731 = 731 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_732 = 732 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_733 = 733 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_734 = 734 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_735 = 735 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_736 = 736 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_737 = 737 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_738 = 738 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_739 = 739 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_740 = 740 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_741 = 741 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_742 = 742 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_743 = 743 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_744 = 744 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_745 = 745 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_746 = 746 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_747 = 747 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_748 = 748 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_749 = 749 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_750 = 750 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_751 = 751 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_752 = 752 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_753 = 753 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_754 = 754 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_755 = 755 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_756 = 756 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_757 = 757 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_758 = 758 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_759 = 759 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_760 = 760 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_761 = 761 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_762 = 762 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_763 = 763 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_764 = 764 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_765 = 765 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_766 = 766 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_767 = 767 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_768 = 768 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_769 = 769 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_770 = 770 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_771 = 771 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_772 = 772 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_773 = 773 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_774 = 774 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_775 = 775 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_776 = 776 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_777 = 777 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_778 = 778 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_779 = 779 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_780 = 780 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_781 = 781 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_782 = 782 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_783 = 783 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_784 = 784 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_785 = 785 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_786 = 786 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_787 = 787 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_788 = 788 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_789 = 789 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_790 = 790 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_791 = 791 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_792 = 792 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_793 = 793 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_794 = 794 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_795 = 795 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_796 = 796 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_797 = 797 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_798 = 798 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_799 = 799 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_800 = 800 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_801 = 801 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_802 = 802 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_803 = 803 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_804 = 804 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_805 = 805 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_806 = 806 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_807 = 807 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_808 = 808 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_809 = 809 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_810 = 810 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_811 = 811 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_812 = 812 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_813 = 813 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_814 = 814 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_815 = 815 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_816 = 816 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_817 = 817 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_818 = 818 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_819 = 819 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_820 = 820 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_821 = 821 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_822 = 822 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_823 = 823 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_824 = 824 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_825 = 825 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_826 = 826 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_827 = 827 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_828 = 828 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_829 = 829 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_830 = 830 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_831 = 831 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_832 = 832 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_833 = 833 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_834 = 834 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_835 = 835 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_836 = 836 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_837 = 837 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_838 = 838 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_839 = 839 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_840 = 840 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_841 = 841 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_842 = 842 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_843 = 843 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_844 = 844 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_845 = 845 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_846 = 846 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_847 = 847 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_848 = 848 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_849 = 849 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_850 = 850 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_851 = 851 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_852 = 852 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_853 = 853 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_854 = 854 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_855 = 855 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_856 = 856 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_857 = 857 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_858 = 858 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_859 = 859 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_860 = 860 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_861 = 861 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_862 = 862 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_863 = 863 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_864 = 864 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_865 = 865 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_866 = 866 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_867 = 867 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_868 = 868 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_869 = 869 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_870 = 870 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_871 = 871 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_872 = 872 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_873 = 873 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_874 = 874 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_875 = 875 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_876 = 876 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_877 = 877 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_878 = 878 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_879 = 879 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_880 = 880 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_881 = 881 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_882 = 882 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_883 = 883 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_884 = 884 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_885 = 885 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_886 = 886 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_887 = 887 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_888 = 888 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_889 = 889 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_890 = 890 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_891 = 891 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_892 = 892 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_893 = 893 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_894 = 894 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_895 = 895 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_896 = 896 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_897 = 897 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_898 = 898 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_899 = 899 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_900 = 900 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_901 = 901 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_902 = 902 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_903 = 903 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_904 = 904 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_905 = 905 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_906 = 906 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_907 = 907 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_908 = 908 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_909 = 909 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_910 = 910 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_911 = 911 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_912 = 912 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_913 = 913 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_914 = 914 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_915 = 915 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_916 = 916 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_917 = 917 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_918 = 918 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_919 = 919 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_920 = 920 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_921 = 921 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_922 = 922 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_923 = 923 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_924 = 924 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_925 = 925 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_926 = 926 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_927 = 927 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_928 = 928 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_929 = 929 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_930 = 930 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_931 = 931 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_932 = 932 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_933 = 933 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_934 = 934 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_935 = 935 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_936 = 936 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_937 = 937 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_938 = 938 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_939 = 939 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_940 = 940 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_941 = 941 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_942 = 942 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_943 = 943 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_944 = 944 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_945 = 945 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_946 = 946 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_947 = 947 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_948 = 948 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_949 = 949 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_950 = 950 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_951 = 951 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_952 = 952 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_953 = 953 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_954 = 954 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_955 = 955 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_956 = 956 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_957 = 957 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_958 = 958 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_959 = 959 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_960 = 960 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_961 = 961 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_962 = 962 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_963 = 963 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_964 = 964 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_965 = 965 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_966 = 966 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_967 = 967 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_968 = 968 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_969 = 969 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_970 = 970 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_971 = 971 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_972 = 972 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_973 = 973 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_974 = 974 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_975 = 975 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_976 = 976 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_977 = 977 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_978 = 978 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_979 = 979 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_980 = 980 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_981 = 981 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_982 = 982 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_983 = 983 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_984 = 984 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_985 = 985 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_986 = 986 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_987 = 987 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_988 = 988 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_989 = 989 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_990 = 990 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_991 = 991 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_992 = 992 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_993 = 993 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_994 = 994 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_995 = 995 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_996 = 996 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_997 = 997 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_998 = 998 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_999 = 999 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; - optional string long_field_name_is_looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong_1000 = 1000 [default="long default value is also loooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong"]; -} diff --git a/Resources/NetHook/google/protobuf/unittest_import.proto b/Resources/NetHook/google/protobuf/unittest_import.proto deleted file mode 100644 index cd533ecd..00000000 --- a/Resources/NetHook/google/protobuf/unittest_import.proto +++ /dev/null @@ -1,61 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// A proto file which is imported by unittest.proto to test importing. - - -// We don't put this in a package within proto2 because we need to make sure -// that the generated code doesn't depend on being in the proto2 namespace. -// In test_util.h we do -// "using namespace unittest_import = protobuf_unittest_import". -package protobuf_unittest_import; - -option optimize_for = SPEED; - -// Excercise the java_package option. -option java_package = "com.google.protobuf.test"; - -// Do not set a java_outer_classname here to verify that Proto2 works without -// one. - -message ImportMessage { - optional int32 d = 1; -} - -enum ImportEnum { - IMPORT_FOO = 7; - IMPORT_BAR = 8; - IMPORT_BAZ = 9; -} - diff --git a/Resources/NetHook/google/protobuf/unittest_import_lite.proto b/Resources/NetHook/google/protobuf/unittest_import_lite.proto deleted file mode 100644 index ebaab5c0..00000000 --- a/Resources/NetHook/google/protobuf/unittest_import_lite.proto +++ /dev/null @@ -1,49 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// -// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME. - -package protobuf_unittest_import; - -option optimize_for = LITE_RUNTIME; - -option java_package = "com.google.protobuf"; - -message ImportMessageLite { - optional int32 d = 1; -} - -enum ImportEnumLite { - IMPORT_LITE_FOO = 7; - IMPORT_LITE_BAR = 8; - IMPORT_LITE_BAZ = 9; -} diff --git a/Resources/NetHook/google/protobuf/unittest_lite.proto b/Resources/NetHook/google/protobuf/unittest_lite.proto deleted file mode 100644 index cca6b497..00000000 --- a/Resources/NetHook/google/protobuf/unittest_lite.proto +++ /dev/null @@ -1,312 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// -// This is like unittest.proto but with optimize_for = LITE_RUNTIME. - -package protobuf_unittest; - -import "google/protobuf/unittest_import_lite.proto"; - -option optimize_for = LITE_RUNTIME; - -option java_package = "com.google.protobuf"; - -// Same as TestAllTypes but with the lite runtime. -message TestAllTypesLite { - message NestedMessage { - optional int32 bb = 1; - } - - enum NestedEnum { - FOO = 1; - BAR = 2; - BAZ = 3; - } - - // Singular - optional int32 optional_int32 = 1; - optional int64 optional_int64 = 2; - optional uint32 optional_uint32 = 3; - optional uint64 optional_uint64 = 4; - optional sint32 optional_sint32 = 5; - optional sint64 optional_sint64 = 6; - optional fixed32 optional_fixed32 = 7; - optional fixed64 optional_fixed64 = 8; - optional sfixed32 optional_sfixed32 = 9; - optional sfixed64 optional_sfixed64 = 10; - optional float optional_float = 11; - optional double optional_double = 12; - optional bool optional_bool = 13; - optional string optional_string = 14; - optional bytes optional_bytes = 15; - - optional group OptionalGroup = 16 { - optional int32 a = 17; - } - - optional NestedMessage optional_nested_message = 18; - optional ForeignMessageLite optional_foreign_message = 19; - optional protobuf_unittest_import.ImportMessageLite - optional_import_message = 20; - - optional NestedEnum optional_nested_enum = 21; - optional ForeignEnumLite optional_foreign_enum = 22; - optional protobuf_unittest_import.ImportEnumLite optional_import_enum = 23; - - optional string optional_string_piece = 24 [ctype=STRING_PIECE]; - optional string optional_cord = 25 [ctype=CORD]; - - // Repeated - repeated int32 repeated_int32 = 31; - repeated int64 repeated_int64 = 32; - repeated uint32 repeated_uint32 = 33; - repeated uint64 repeated_uint64 = 34; - repeated sint32 repeated_sint32 = 35; - repeated sint64 repeated_sint64 = 36; - repeated fixed32 repeated_fixed32 = 37; - repeated fixed64 repeated_fixed64 = 38; - repeated sfixed32 repeated_sfixed32 = 39; - repeated sfixed64 repeated_sfixed64 = 40; - repeated float repeated_float = 41; - repeated double repeated_double = 42; - repeated bool repeated_bool = 43; - repeated string repeated_string = 44; - repeated bytes repeated_bytes = 45; - - repeated group RepeatedGroup = 46 { - optional int32 a = 47; - } - - repeated NestedMessage repeated_nested_message = 48; - repeated ForeignMessageLite repeated_foreign_message = 49; - repeated protobuf_unittest_import.ImportMessageLite - repeated_import_message = 50; - - repeated NestedEnum repeated_nested_enum = 51; - repeated ForeignEnumLite repeated_foreign_enum = 52; - repeated protobuf_unittest_import.ImportEnumLite repeated_import_enum = 53; - - repeated string repeated_string_piece = 54 [ctype=STRING_PIECE]; - repeated string repeated_cord = 55 [ctype=CORD]; - - // Singular with defaults - optional int32 default_int32 = 61 [default = 41 ]; - optional int64 default_int64 = 62 [default = 42 ]; - optional uint32 default_uint32 = 63 [default = 43 ]; - optional uint64 default_uint64 = 64 [default = 44 ]; - optional sint32 default_sint32 = 65 [default = -45 ]; - optional sint64 default_sint64 = 66 [default = 46 ]; - optional fixed32 default_fixed32 = 67 [default = 47 ]; - optional fixed64 default_fixed64 = 68 [default = 48 ]; - optional sfixed32 default_sfixed32 = 69 [default = 49 ]; - optional sfixed64 default_sfixed64 = 70 [default = -50 ]; - optional float default_float = 71 [default = 51.5 ]; - optional double default_double = 72 [default = 52e3 ]; - optional bool default_bool = 73 [default = true ]; - optional string default_string = 74 [default = "hello"]; - optional bytes default_bytes = 75 [default = "world"]; - - optional NestedEnum default_nested_enum = 81 [default = BAR]; - optional ForeignEnumLite default_foreign_enum = 82 - [default = FOREIGN_LITE_BAR]; - optional protobuf_unittest_import.ImportEnumLite - default_import_enum = 83 [default = IMPORT_LITE_BAR]; - - optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"]; - optional string default_cord = 85 [ctype=CORD,default="123"]; -} - -message ForeignMessageLite { - optional int32 c = 1; -} - -enum ForeignEnumLite { - FOREIGN_LITE_FOO = 4; - FOREIGN_LITE_BAR = 5; - FOREIGN_LITE_BAZ = 6; -} - -message TestPackedTypesLite { - repeated int32 packed_int32 = 90 [packed = true]; - repeated int64 packed_int64 = 91 [packed = true]; - repeated uint32 packed_uint32 = 92 [packed = true]; - repeated uint64 packed_uint64 = 93 [packed = true]; - repeated sint32 packed_sint32 = 94 [packed = true]; - repeated sint64 packed_sint64 = 95 [packed = true]; - repeated fixed32 packed_fixed32 = 96 [packed = true]; - repeated fixed64 packed_fixed64 = 97 [packed = true]; - repeated sfixed32 packed_sfixed32 = 98 [packed = true]; - repeated sfixed64 packed_sfixed64 = 99 [packed = true]; - repeated float packed_float = 100 [packed = true]; - repeated double packed_double = 101 [packed = true]; - repeated bool packed_bool = 102 [packed = true]; - repeated ForeignEnumLite packed_enum = 103 [packed = true]; -} - -message TestAllExtensionsLite { - extensions 1 to max; -} - -extend TestAllExtensionsLite { - // Singular - optional int32 optional_int32_extension_lite = 1; - optional int64 optional_int64_extension_lite = 2; - optional uint32 optional_uint32_extension_lite = 3; - optional uint64 optional_uint64_extension_lite = 4; - optional sint32 optional_sint32_extension_lite = 5; - optional sint64 optional_sint64_extension_lite = 6; - optional fixed32 optional_fixed32_extension_lite = 7; - optional fixed64 optional_fixed64_extension_lite = 8; - optional sfixed32 optional_sfixed32_extension_lite = 9; - optional sfixed64 optional_sfixed64_extension_lite = 10; - optional float optional_float_extension_lite = 11; - optional double optional_double_extension_lite = 12; - optional bool optional_bool_extension_lite = 13; - optional string optional_string_extension_lite = 14; - optional bytes optional_bytes_extension_lite = 15; - - optional group OptionalGroup_extension_lite = 16 { - optional int32 a = 17; - } - - optional TestAllTypesLite.NestedMessage optional_nested_message_extension_lite - = 18; - optional ForeignMessageLite optional_foreign_message_extension_lite = 19; - optional protobuf_unittest_import.ImportMessageLite - optional_import_message_extension_lite = 20; - - optional TestAllTypesLite.NestedEnum optional_nested_enum_extension_lite = 21; - optional ForeignEnumLite optional_foreign_enum_extension_lite = 22; - optional protobuf_unittest_import.ImportEnumLite - optional_import_enum_extension_lite = 23; - - optional string optional_string_piece_extension_lite = 24 - [ctype=STRING_PIECE]; - optional string optional_cord_extension_lite = 25 [ctype=CORD]; - - // Repeated - repeated int32 repeated_int32_extension_lite = 31; - repeated int64 repeated_int64_extension_lite = 32; - repeated uint32 repeated_uint32_extension_lite = 33; - repeated uint64 repeated_uint64_extension_lite = 34; - repeated sint32 repeated_sint32_extension_lite = 35; - repeated sint64 repeated_sint64_extension_lite = 36; - repeated fixed32 repeated_fixed32_extension_lite = 37; - repeated fixed64 repeated_fixed64_extension_lite = 38; - repeated sfixed32 repeated_sfixed32_extension_lite = 39; - repeated sfixed64 repeated_sfixed64_extension_lite = 40; - repeated float repeated_float_extension_lite = 41; - repeated double repeated_double_extension_lite = 42; - repeated bool repeated_bool_extension_lite = 43; - repeated string repeated_string_extension_lite = 44; - repeated bytes repeated_bytes_extension_lite = 45; - - repeated group RepeatedGroup_extension_lite = 46 { - optional int32 a = 47; - } - - repeated TestAllTypesLite.NestedMessage repeated_nested_message_extension_lite - = 48; - repeated ForeignMessageLite repeated_foreign_message_extension_lite = 49; - repeated protobuf_unittest_import.ImportMessageLite - repeated_import_message_extension_lite = 50; - - repeated TestAllTypesLite.NestedEnum repeated_nested_enum_extension_lite = 51; - repeated ForeignEnumLite repeated_foreign_enum_extension_lite = 52; - repeated protobuf_unittest_import.ImportEnumLite - repeated_import_enum_extension_lite = 53; - - repeated string repeated_string_piece_extension_lite = 54 - [ctype=STRING_PIECE]; - repeated string repeated_cord_extension_lite = 55 [ctype=CORD]; - - // Singular with defaults - optional int32 default_int32_extension_lite = 61 [default = 41 ]; - optional int64 default_int64_extension_lite = 62 [default = 42 ]; - optional uint32 default_uint32_extension_lite = 63 [default = 43 ]; - optional uint64 default_uint64_extension_lite = 64 [default = 44 ]; - optional sint32 default_sint32_extension_lite = 65 [default = -45 ]; - optional sint64 default_sint64_extension_lite = 66 [default = 46 ]; - optional fixed32 default_fixed32_extension_lite = 67 [default = 47 ]; - optional fixed64 default_fixed64_extension_lite = 68 [default = 48 ]; - optional sfixed32 default_sfixed32_extension_lite = 69 [default = 49 ]; - optional sfixed64 default_sfixed64_extension_lite = 70 [default = -50 ]; - optional float default_float_extension_lite = 71 [default = 51.5 ]; - optional double default_double_extension_lite = 72 [default = 52e3 ]; - optional bool default_bool_extension_lite = 73 [default = true ]; - optional string default_string_extension_lite = 74 [default = "hello"]; - optional bytes default_bytes_extension_lite = 75 [default = "world"]; - - optional TestAllTypesLite.NestedEnum - default_nested_enum_extension_lite = 81 [default = BAR]; - optional ForeignEnumLite - default_foreign_enum_extension_lite = 82 [default = FOREIGN_LITE_BAR]; - optional protobuf_unittest_import.ImportEnumLite - default_import_enum_extension_lite = 83 [default = IMPORT_LITE_BAR]; - - optional string default_string_piece_extension_lite = 84 [ctype=STRING_PIECE, - default="abc"]; - optional string default_cord_extension_lite = 85 [ctype=CORD, default="123"]; -} - -message TestPackedExtensionsLite { - extensions 1 to max; -} - -extend TestPackedExtensionsLite { - repeated int32 packed_int32_extension_lite = 90 [packed = true]; - repeated int64 packed_int64_extension_lite = 91 [packed = true]; - repeated uint32 packed_uint32_extension_lite = 92 [packed = true]; - repeated uint64 packed_uint64_extension_lite = 93 [packed = true]; - repeated sint32 packed_sint32_extension_lite = 94 [packed = true]; - repeated sint64 packed_sint64_extension_lite = 95 [packed = true]; - repeated fixed32 packed_fixed32_extension_lite = 96 [packed = true]; - repeated fixed64 packed_fixed64_extension_lite = 97 [packed = true]; - repeated sfixed32 packed_sfixed32_extension_lite = 98 [packed = true]; - repeated sfixed64 packed_sfixed64_extension_lite = 99 [packed = true]; - repeated float packed_float_extension_lite = 100 [packed = true]; - repeated double packed_double_extension_lite = 101 [packed = true]; - repeated bool packed_bool_extension_lite = 102 [packed = true]; - repeated ForeignEnumLite packed_enum_extension_lite = 103 [packed = true]; -} - -message TestNestedExtensionLite { - extend TestAllExtensionsLite { - optional int32 nested_extension = 12345; - } -} - -// Test that deprecated fields work. We only verify that they compile (at one -// point this failed). -message TestDeprecatedLite { - optional int32 deprecated_field = 1 [deprecated = true]; -} diff --git a/Resources/NetHook/google/protobuf/unittest_lite_imports_nonlite.proto b/Resources/NetHook/google/protobuf/unittest_lite_imports_nonlite.proto deleted file mode 100644 index d52cb8cc..00000000 --- a/Resources/NetHook/google/protobuf/unittest_lite_imports_nonlite.proto +++ /dev/null @@ -1,43 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// -// Tests that a "lite" message can import a regular message. - -package protobuf_unittest; - -import "google/protobuf/unittest.proto"; - -option optimize_for = LITE_RUNTIME; - -message TestLiteImportsNonlite { - optional TestAllTypes message = 1; -} diff --git a/Resources/NetHook/google/protobuf/unittest_mset.proto b/Resources/NetHook/google/protobuf/unittest_mset.proto deleted file mode 100644 index 3497f09f..00000000 --- a/Resources/NetHook/google/protobuf/unittest_mset.proto +++ /dev/null @@ -1,72 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This file contains messages for testing message_set_wire_format. - -package protobuf_unittest; - -option optimize_for = SPEED; - -// A message with message_set_wire_format. -message TestMessageSet { - option message_set_wire_format = true; - extensions 4 to max; -} - -message TestMessageSetContainer { - optional TestMessageSet message_set = 1; -} - -message TestMessageSetExtension1 { - extend TestMessageSet { - optional TestMessageSetExtension1 message_set_extension = 1545008; - } - optional int32 i = 15; -} - -message TestMessageSetExtension2 { - extend TestMessageSet { - optional TestMessageSetExtension2 message_set_extension = 1547769; - } - optional string str = 25; -} - -// MessageSet wire format is equivalent to this. -message RawMessageSet { - repeated group Item = 1 { - required int32 type_id = 2; - required bytes message = 3; - } -} - diff --git a/Resources/NetHook/google/protobuf/unittest_no_generic_services.proto b/Resources/NetHook/google/protobuf/unittest_no_generic_services.proto deleted file mode 100644 index fcae4214..00000000 --- a/Resources/NetHook/google/protobuf/unittest_no_generic_services.proto +++ /dev/null @@ -1,54 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) - -package google.protobuf.no_generic_services_test; - -option cc_generic_services = false; -option java_generic_services = false; -option py_generic_services = false; - -message TestMessage { - optional int32 a = 1; - extensions 1000 to max; -} - -enum TestEnum { - FOO = 1; -} - -extend TestMessage { - optional int32 test_extension = 1000; -} - -service TestService { - rpc Foo(TestMessage) returns(TestMessage); -} diff --git a/Resources/NetHook/google/protobuf/unittest_optimize_for.proto b/Resources/NetHook/google/protobuf/unittest_optimize_for.proto deleted file mode 100644 index feecbef8..00000000 --- a/Resources/NetHook/google/protobuf/unittest_optimize_for.proto +++ /dev/null @@ -1,61 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// A proto file which uses optimize_for = CODE_SIZE. - -import "google/protobuf/unittest.proto"; - -package protobuf_unittest; - -option optimize_for = CODE_SIZE; - -message TestOptimizedForSize { - optional int32 i = 1; - optional ForeignMessage msg = 19; - - extensions 1000 to max; - - extend TestOptimizedForSize { - optional int32 test_extension = 1234; - optional TestRequiredOptimizedForSize test_extension2 = 1235; - } -} - -message TestRequiredOptimizedForSize { - required int32 x = 1; -} - -message TestOptionalOptimizedForSize { - optional TestRequiredOptimizedForSize o = 1; -} diff --git a/Resources/NetHook/google/protobuf/unknown_field_set.cc b/Resources/NetHook/google/protobuf/unknown_field_set.cc deleted file mode 100644 index e1f8b838..00000000 --- a/Resources/NetHook/google/protobuf/unknown_field_set.cc +++ /dev/null @@ -1,204 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -UnknownFieldSet::UnknownFieldSet() - : fields_(NULL) {} - -UnknownFieldSet::~UnknownFieldSet() { - Clear(); - delete fields_; -} - -void UnknownFieldSet::ClearFallback() { - GOOGLE_DCHECK(fields_ != NULL); - for (int i = 0; i < fields_->size(); i++) { - (*fields_)[i].Delete(); - } - fields_->clear(); -} - -void UnknownFieldSet::MergeFrom(const UnknownFieldSet& other) { - for (int i = 0; i < other.field_count(); i++) { - AddField(other.field(i)); - } -} - -int UnknownFieldSet::SpaceUsedExcludingSelf() const { - if (fields_ == NULL) return 0; - - int total_size = sizeof(*fields_) + sizeof(UnknownField) * fields_->size(); - for (int i = 0; i < fields_->size(); i++) { - const UnknownField& field = (*fields_)[i]; - switch (field.type()) { - case UnknownField::TYPE_LENGTH_DELIMITED: - total_size += sizeof(*field.length_delimited_) + - internal::StringSpaceUsedExcludingSelf(*field.length_delimited_); - break; - case UnknownField::TYPE_GROUP: - total_size += field.group_->SpaceUsed(); - break; - default: - break; - } - } - return total_size; -} - -int UnknownFieldSet::SpaceUsed() const { - return sizeof(*this) + SpaceUsedExcludingSelf(); -} - -void UnknownFieldSet::AddVarint(int number, uint64 value) { - if (fields_ == NULL) fields_ = new vector; - UnknownField field; - field.number_ = number; - field.type_ = UnknownField::TYPE_VARINT; - field.varint_ = value; - fields_->push_back(field); -} - -void UnknownFieldSet::AddFixed32(int number, uint32 value) { - if (fields_ == NULL) fields_ = new vector; - UnknownField field; - field.number_ = number; - field.type_ = UnknownField::TYPE_FIXED32; - field.fixed32_ = value; - fields_->push_back(field); -} - -void UnknownFieldSet::AddFixed64(int number, uint64 value) { - if (fields_ == NULL) fields_ = new vector; - UnknownField field; - field.number_ = number; - field.type_ = UnknownField::TYPE_FIXED64; - field.fixed64_ = value; - fields_->push_back(field); -} - -string* UnknownFieldSet::AddLengthDelimited(int number) { - if (fields_ == NULL) fields_ = new vector; - UnknownField field; - field.number_ = number; - field.type_ = UnknownField::TYPE_LENGTH_DELIMITED; - field.length_delimited_ = new string; - fields_->push_back(field); - return field.length_delimited_; -} - -UnknownFieldSet* UnknownFieldSet::AddGroup(int number) { - if (fields_ == NULL) fields_ = new vector; - UnknownField field; - field.number_ = number; - field.type_ = UnknownField::TYPE_GROUP; - field.group_ = new UnknownFieldSet; - fields_->push_back(field); - return field.group_; -} - -void UnknownFieldSet::AddField(const UnknownField& field) { - if (fields_ == NULL) fields_ = new vector; - fields_->push_back(field); - fields_->back().DeepCopy(); -} - -bool UnknownFieldSet::MergeFromCodedStream(io::CodedInputStream* input) { - - UnknownFieldSet other; - if (internal::WireFormat::SkipMessage(input, &other) && - input->ConsumedEntireMessage()) { - MergeFrom(other); - return true; - } else { - return false; - } -} - -bool UnknownFieldSet::ParseFromCodedStream(io::CodedInputStream* input) { - Clear(); - return MergeFromCodedStream(input); -} - -bool UnknownFieldSet::ParseFromZeroCopyStream(io::ZeroCopyInputStream* input) { - io::CodedInputStream coded_input(input); - return ParseFromCodedStream(&coded_input) && - coded_input.ConsumedEntireMessage(); -} - -bool UnknownFieldSet::ParseFromArray(const void* data, int size) { - io::ArrayInputStream input(data, size); - return ParseFromZeroCopyStream(&input); -} - -void UnknownField::Delete() { - switch (type()) { - case UnknownField::TYPE_LENGTH_DELIMITED: - delete length_delimited_; - break; - case UnknownField::TYPE_GROUP: - delete group_; - break; - default: - break; - } -} - -void UnknownField::DeepCopy() { - switch (type()) { - case UnknownField::TYPE_LENGTH_DELIMITED: - length_delimited_ = new string(*length_delimited_); - break; - case UnknownField::TYPE_GROUP: { - UnknownFieldSet* group = new UnknownFieldSet; - group->MergeFrom(*group_); - group_ = group; - break; - } - default: - break; - } -} - -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/unknown_field_set.h b/Resources/NetHook/google/protobuf/unknown_field_set.h deleted file mode 100644 index 84c2e2b6..00000000 --- a/Resources/NetHook/google/protobuf/unknown_field_set.h +++ /dev/null @@ -1,268 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// Contains classes used to keep track of unrecognized fields seen while -// parsing a protocol message. - -#ifndef GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__ -#define GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__ - -#include -#include -#include - -namespace google { -namespace protobuf { - -class Message; // message.h -class UnknownField; // below - -// An UnknownFieldSet contains fields that were encountered while parsing a -// message but were not defined by its type. Keeping track of these can be -// useful, especially in that they may be written if the message is serialized -// again without being cleared in between. This means that software which -// simply receives messages and forwards them to other servers does not need -// to be updated every time a new field is added to the message definition. -// -// To get the UnknownFieldSet attached to any message, call -// Reflection::GetUnknownFields(). -// -// This class is necessarily tied to the protocol buffer wire format, unlike -// the Reflection interface which is independent of any serialization scheme. -class LIBPROTOBUF_EXPORT UnknownFieldSet { - public: - UnknownFieldSet(); - ~UnknownFieldSet(); - - // Remove all fields. - inline void Clear(); - - // Is this set empty? - inline bool empty() const; - - // Merge the contents of some other UnknownFieldSet with this one. - void MergeFrom(const UnknownFieldSet& other); - - // Swaps the contents of some other UnknownFieldSet with this one. - inline void Swap(UnknownFieldSet* x); - - // Computes (an estimate of) the total number of bytes currently used for - // storing the unknown fields in memory. Does NOT include - // sizeof(*this) in the calculation. - int SpaceUsedExcludingSelf() const; - - // Version of SpaceUsed() including sizeof(*this). - int SpaceUsed() const; - - // Returns the number of fields present in the UnknownFieldSet. - inline int field_count() const; - // Get a field in the set, where 0 <= index < field_count(). The fields - // appear in the order in which they were added. - inline const UnknownField& field(int index) const; - // Get a mutable pointer to a field in the set, where - // 0 <= index < field_count(). The fields appear in the order in which - // they were added. - inline UnknownField* mutable_field(int index); - - // Adding fields --------------------------------------------------- - - void AddVarint(int number, uint64 value); - void AddFixed32(int number, uint32 value); - void AddFixed64(int number, uint64 value); - void AddLengthDelimited(int number, const string& value); - string* AddLengthDelimited(int number); - UnknownFieldSet* AddGroup(int number); - - // Adds an unknown field from another set. - void AddField(const UnknownField& field); - - // Parsing helpers ------------------------------------------------- - // These work exactly like the similarly-named methods of Message. - - bool MergeFromCodedStream(io::CodedInputStream* input); - bool ParseFromCodedStream(io::CodedInputStream* input); - bool ParseFromZeroCopyStream(io::ZeroCopyInputStream* input); - bool ParseFromArray(const void* data, int size); - inline bool ParseFromString(const string& data) { - return ParseFromArray(data.data(), data.size()); - } - - private: - void ClearFallback(); - - vector* fields_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UnknownFieldSet); -}; - -// Represents one field in an UnknownFieldSet. -class LIBPROTOBUF_EXPORT UnknownField { - public: - enum Type { - TYPE_VARINT, - TYPE_FIXED32, - TYPE_FIXED64, - TYPE_LENGTH_DELIMITED, - TYPE_GROUP - }; - - // The field's tag number, as seen on the wire. - inline int number() const; - - // The field type. - inline Type type() const; - - // Accessors ------------------------------------------------------- - // Each method works only for UnknownFields of the corresponding type. - - inline uint64 varint() const; - inline uint32 fixed32() const; - inline uint64 fixed64() const; - inline const string& length_delimited() const; - inline const UnknownFieldSet& group() const; - - inline void set_varint(uint64 value); - inline void set_fixed32(uint32 value); - inline void set_fixed64(uint64 value); - inline void set_length_delimited(const string& value); - inline string* mutable_length_delimited(); - inline UnknownFieldSet* mutable_group(); - - private: - friend class UnknownFieldSet; - - // If this UnknownField contains a pointer, delete it. - void Delete(); - - // Make a deep copy of any pointers in this UnknownField. - void DeepCopy(); - - unsigned int number_ : 29; - unsigned int type_ : 3; - union { - uint64 varint_; - uint32 fixed32_; - uint64 fixed64_; - string* length_delimited_; - UnknownFieldSet* group_; - }; -}; - -// =================================================================== -// inline implementations - -inline void UnknownFieldSet::Clear() { - if (fields_ != NULL) { - ClearFallback(); - } -} - -inline bool UnknownFieldSet::empty() const { - return fields_ == NULL || fields_->empty(); -} - -inline void UnknownFieldSet::Swap(UnknownFieldSet* x) { - std::swap(fields_, x->fields_); -} - -inline int UnknownFieldSet::field_count() const { - return (fields_ == NULL) ? 0 : fields_->size(); -} -inline const UnknownField& UnknownFieldSet::field(int index) const { - return (*fields_)[index]; -} -inline UnknownField* UnknownFieldSet::mutable_field(int index) { - return &(*fields_)[index]; -} - -inline void UnknownFieldSet::AddLengthDelimited( - int number, const string& value) { - AddLengthDelimited(number)->assign(value); -} - -inline int UnknownField::number() const { return number_; } -inline UnknownField::Type UnknownField::type() const { - return static_cast(type_); -} - -inline uint64 UnknownField::varint () const { - GOOGLE_DCHECK_EQ(type_, TYPE_VARINT); - return varint_; -} -inline uint32 UnknownField::fixed32() const { - GOOGLE_DCHECK_EQ(type_, TYPE_FIXED32); - return fixed32_; -} -inline uint64 UnknownField::fixed64() const { - GOOGLE_DCHECK_EQ(type_, TYPE_FIXED64); - return fixed64_; -} -inline const string& UnknownField::length_delimited() const { - GOOGLE_DCHECK_EQ(type_, TYPE_LENGTH_DELIMITED); - return *length_delimited_; -} -inline const UnknownFieldSet& UnknownField::group() const { - GOOGLE_DCHECK_EQ(type_, TYPE_GROUP); - return *group_; -} - -inline void UnknownField::set_varint(uint64 value) { - GOOGLE_DCHECK_EQ(type_, TYPE_VARINT); - varint_ = value; -} -inline void UnknownField::set_fixed32(uint32 value) { - GOOGLE_DCHECK_EQ(type_, TYPE_FIXED32); - fixed32_ = value; -} -inline void UnknownField::set_fixed64(uint64 value) { - GOOGLE_DCHECK_EQ(type_, TYPE_FIXED64); - fixed64_ = value; -} -inline void UnknownField::set_length_delimited(const string& value) { - GOOGLE_DCHECK_EQ(type_, TYPE_LENGTH_DELIMITED); - length_delimited_->assign(value); -} -inline string* UnknownField::mutable_length_delimited() { - GOOGLE_DCHECK_EQ(type_, TYPE_LENGTH_DELIMITED); - return length_delimited_; -} -inline UnknownFieldSet* UnknownField::mutable_group() { - GOOGLE_DCHECK_EQ(type_, TYPE_GROUP); - return group_; -} - -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_UNKNOWN_FIELD_SET_H__ diff --git a/Resources/NetHook/google/protobuf/unknown_field_set_unittest.cc b/Resources/NetHook/google/protobuf/unknown_field_set_unittest.cc deleted file mode 100644 index 1235c9ee..00000000 --- a/Resources/NetHook/google/protobuf/unknown_field_set_unittest.cc +++ /dev/null @@ -1,512 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This test is testing a lot more than just the UnknownFieldSet class. It -// tests handling of unknown fields throughout the system. - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { - -using internal::WireFormat; - -namespace { - -class UnknownFieldSetTest : public testing::Test { - protected: - virtual void SetUp() { - descriptor_ = unittest::TestAllTypes::descriptor(); - TestUtil::SetAllFields(&all_fields_); - all_fields_.SerializeToString(&all_fields_data_); - ASSERT_TRUE(empty_message_.ParseFromString(all_fields_data_)); - unknown_fields_ = empty_message_.mutable_unknown_fields(); - } - - const UnknownField* GetField(const string& name) { - const FieldDescriptor* field = descriptor_->FindFieldByName(name); - if (field == NULL) return NULL; - for (int i = 0; i < unknown_fields_->field_count(); i++) { - if (unknown_fields_->field(i).number() == field->number()) { - return &unknown_fields_->field(i); - } - } - return NULL; - } - - // Constructs a protocol buffer which contains fields with all the same - // numbers as all_fields_data_ except that each field is some other wire - // type. - string GetBizarroData() { - unittest::TestEmptyMessage bizarro_message; - UnknownFieldSet* bizarro_unknown_fields = - bizarro_message.mutable_unknown_fields(); - for (int i = 0; i < unknown_fields_->field_count(); i++) { - const UnknownField& unknown_field = unknown_fields_->field(i); - if (unknown_field.type() == UnknownField::TYPE_VARINT) { - bizarro_unknown_fields->AddFixed32(unknown_field.number(), 1); - } else { - bizarro_unknown_fields->AddVarint(unknown_field.number(), 1); - } - } - - string data; - EXPECT_TRUE(bizarro_message.SerializeToString(&data)); - return data; - } - - const Descriptor* descriptor_; - unittest::TestAllTypes all_fields_; - string all_fields_data_; - - // An empty message that has been parsed from all_fields_data_. So, it has - // unknown fields of every type. - unittest::TestEmptyMessage empty_message_; - UnknownFieldSet* unknown_fields_; -}; - -TEST_F(UnknownFieldSetTest, AllFieldsPresent) { - // All fields of TestAllTypes should be present, in numeric order (because - // that's the order we parsed them in). Fields that are not valid field - // numbers of TestAllTypes should NOT be present. - - int pos = 0; - - for (int i = 0; i < 1000; i++) { - const FieldDescriptor* field = descriptor_->FindFieldByNumber(i); - if (field != NULL) { - ASSERT_LT(pos, unknown_fields_->field_count()); - EXPECT_EQ(i, unknown_fields_->field(pos++).number()); - if (field->is_repeated()) { - // Should have a second instance. - ASSERT_LT(pos, unknown_fields_->field_count()); - EXPECT_EQ(i, unknown_fields_->field(pos++).number()); - } - } - } - EXPECT_EQ(unknown_fields_->field_count(), pos); -} - -TEST_F(UnknownFieldSetTest, Varint) { - const UnknownField* field = GetField("optional_int32"); - ASSERT_TRUE(field != NULL); - - ASSERT_EQ(UnknownField::TYPE_VARINT, field->type()); - EXPECT_EQ(all_fields_.optional_int32(), field->varint()); -} - -TEST_F(UnknownFieldSetTest, Fixed32) { - const UnknownField* field = GetField("optional_fixed32"); - ASSERT_TRUE(field != NULL); - - ASSERT_EQ(UnknownField::TYPE_FIXED32, field->type()); - EXPECT_EQ(all_fields_.optional_fixed32(), field->fixed32()); -} - -TEST_F(UnknownFieldSetTest, Fixed64) { - const UnknownField* field = GetField("optional_fixed64"); - ASSERT_TRUE(field != NULL); - - ASSERT_EQ(UnknownField::TYPE_FIXED64, field->type()); - EXPECT_EQ(all_fields_.optional_fixed64(), field->fixed64()); -} - -TEST_F(UnknownFieldSetTest, LengthDelimited) { - const UnknownField* field = GetField("optional_string"); - ASSERT_TRUE(field != NULL); - - ASSERT_EQ(UnknownField::TYPE_LENGTH_DELIMITED, field->type()); - EXPECT_EQ(all_fields_.optional_string(), field->length_delimited()); -} - -TEST_F(UnknownFieldSetTest, Group) { - const UnknownField* field = GetField("optionalgroup"); - ASSERT_TRUE(field != NULL); - - ASSERT_EQ(UnknownField::TYPE_GROUP, field->type()); - ASSERT_EQ(1, field->group().field_count()); - - const UnknownField& nested_field = field->group().field(0); - const FieldDescriptor* nested_field_descriptor = - unittest::TestAllTypes::OptionalGroup::descriptor()->FindFieldByName("a"); - ASSERT_TRUE(nested_field_descriptor != NULL); - - EXPECT_EQ(nested_field_descriptor->number(), nested_field.number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, nested_field.type()); - EXPECT_EQ(all_fields_.optionalgroup().a(), nested_field.varint()); -} - -TEST_F(UnknownFieldSetTest, SerializeFastAndSlowAreEquivalent) { - int size = WireFormat::ComputeUnknownFieldsSize( - empty_message_.unknown_fields()); - string slow_buffer; - string fast_buffer; - slow_buffer.resize(size); - fast_buffer.resize(size); - - uint8* target = reinterpret_cast(string_as_array(&fast_buffer)); - uint8* result = WireFormat::SerializeUnknownFieldsToArray( - empty_message_.unknown_fields(), target); - EXPECT_EQ(size, result - target); - - { - io::ArrayOutputStream raw_stream(string_as_array(&slow_buffer), size, 1); - io::CodedOutputStream output_stream(&raw_stream); - WireFormat::SerializeUnknownFields(empty_message_.unknown_fields(), - &output_stream); - ASSERT_FALSE(output_stream.HadError()); - } - EXPECT_TRUE(fast_buffer == slow_buffer); -} - -TEST_F(UnknownFieldSetTest, Serialize) { - // Check that serializing the UnknownFieldSet produces the original data - // again. - - string data; - empty_message_.SerializeToString(&data); - - // Don't use EXPECT_EQ because we don't want to dump raw binary data to - // stdout. - EXPECT_TRUE(data == all_fields_data_); -} - -TEST_F(UnknownFieldSetTest, ParseViaReflection) { - // Make sure fields are properly parsed to the UnknownFieldSet when parsing - // via reflection. - - unittest::TestEmptyMessage message; - io::ArrayInputStream raw_input(all_fields_data_.data(), - all_fields_data_.size()); - io::CodedInputStream input(&raw_input); - ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &message)); - - EXPECT_EQ(message.DebugString(), empty_message_.DebugString()); -} - -TEST_F(UnknownFieldSetTest, SerializeViaReflection) { - // Make sure fields are properly written from the UnknownFieldSet when - // serializing via reflection. - - string data; - - { - io::StringOutputStream raw_output(&data); - io::CodedOutputStream output(&raw_output); - int size = WireFormat::ByteSize(empty_message_); - WireFormat::SerializeWithCachedSizes(empty_message_, size, &output); - ASSERT_FALSE(output.HadError()); - } - - // Don't use EXPECT_EQ because we don't want to dump raw binary data to - // stdout. - EXPECT_TRUE(data == all_fields_data_); -} - -TEST_F(UnknownFieldSetTest, CopyFrom) { - unittest::TestEmptyMessage message; - - message.CopyFrom(empty_message_); - - EXPECT_EQ(empty_message_.DebugString(), message.DebugString()); -} - -TEST_F(UnknownFieldSetTest, Swap) { - unittest::TestEmptyMessage other_message; - ASSERT_TRUE(other_message.ParseFromString(GetBizarroData())); - - EXPECT_GT(empty_message_.unknown_fields().field_count(), 0); - EXPECT_GT(other_message.unknown_fields().field_count(), 0); - const string debug_string = empty_message_.DebugString(); - const string other_debug_string = other_message.DebugString(); - EXPECT_NE(debug_string, other_debug_string); - - empty_message_.Swap(&other_message); - EXPECT_EQ(debug_string, other_message.DebugString()); - EXPECT_EQ(other_debug_string, empty_message_.DebugString()); -} - -TEST_F(UnknownFieldSetTest, SwapWithSelf) { - const string debug_string = empty_message_.DebugString(); - EXPECT_GT(empty_message_.unknown_fields().field_count(), 0); - - empty_message_.Swap(&empty_message_); - EXPECT_GT(empty_message_.unknown_fields().field_count(), 0); - EXPECT_EQ(debug_string, empty_message_.DebugString()); -} - -TEST_F(UnknownFieldSetTest, MergeFrom) { - unittest::TestEmptyMessage source, destination; - - destination.mutable_unknown_fields()->AddVarint(1, 1); - destination.mutable_unknown_fields()->AddVarint(3, 2); - source.mutable_unknown_fields()->AddVarint(2, 3); - source.mutable_unknown_fields()->AddVarint(3, 4); - - destination.MergeFrom(source); - - EXPECT_EQ( - // Note: The ordering of fields here depends on the ordering of adds - // and merging, above. - "1: 1\n" - "3: 2\n" - "2: 3\n" - "3: 4\n", - destination.DebugString()); -} - -TEST_F(UnknownFieldSetTest, Clear) { - // Clear the set. - empty_message_.Clear(); - EXPECT_EQ(0, unknown_fields_->field_count()); -} - -TEST_F(UnknownFieldSetTest, ParseKnownAndUnknown) { - // Test mixing known and unknown fields when parsing. - - unittest::TestEmptyMessage source; - source.mutable_unknown_fields()->AddVarint(123456, 654321); - string data; - ASSERT_TRUE(source.SerializeToString(&data)); - - unittest::TestAllTypes destination; - ASSERT_TRUE(destination.ParseFromString(all_fields_data_ + data)); - - TestUtil::ExpectAllFieldsSet(destination); - ASSERT_EQ(1, destination.unknown_fields().field_count()); - ASSERT_EQ(UnknownField::TYPE_VARINT, - destination.unknown_fields().field(0).type()); - EXPECT_EQ(654321, destination.unknown_fields().field(0).varint()); -} - -TEST_F(UnknownFieldSetTest, WrongTypeTreatedAsUnknown) { - // Test that fields of the wrong wire type are treated like unknown fields - // when parsing. - - unittest::TestAllTypes all_types_message; - unittest::TestEmptyMessage empty_message; - string bizarro_data = GetBizarroData(); - ASSERT_TRUE(all_types_message.ParseFromString(bizarro_data)); - ASSERT_TRUE(empty_message.ParseFromString(bizarro_data)); - - // All fields should have been interpreted as unknown, so the debug strings - // should be the same. - EXPECT_EQ(empty_message.DebugString(), all_types_message.DebugString()); -} - -TEST_F(UnknownFieldSetTest, WrongTypeTreatedAsUnknownViaReflection) { - // Same as WrongTypeTreatedAsUnknown but via the reflection interface. - - unittest::TestAllTypes all_types_message; - unittest::TestEmptyMessage empty_message; - string bizarro_data = GetBizarroData(); - io::ArrayInputStream raw_input(bizarro_data.data(), bizarro_data.size()); - io::CodedInputStream input(&raw_input); - ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &all_types_message)); - ASSERT_TRUE(empty_message.ParseFromString(bizarro_data)); - - EXPECT_EQ(empty_message.DebugString(), all_types_message.DebugString()); -} - -TEST_F(UnknownFieldSetTest, UnknownExtensions) { - // Make sure fields are properly parsed to the UnknownFieldSet even when - // they are declared as extension numbers. - - unittest::TestEmptyMessageWithExtensions message; - ASSERT_TRUE(message.ParseFromString(all_fields_data_)); - - EXPECT_EQ(message.DebugString(), empty_message_.DebugString()); -} - -TEST_F(UnknownFieldSetTest, UnknownExtensionsReflection) { - // Same as UnknownExtensions except parsing via reflection. - - unittest::TestEmptyMessageWithExtensions message; - io::ArrayInputStream raw_input(all_fields_data_.data(), - all_fields_data_.size()); - io::CodedInputStream input(&raw_input); - ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &message)); - - EXPECT_EQ(message.DebugString(), empty_message_.DebugString()); -} - -TEST_F(UnknownFieldSetTest, WrongExtensionTypeTreatedAsUnknown) { - // Test that fields of the wrong wire type are treated like unknown fields - // when parsing extensions. - - unittest::TestAllExtensions all_extensions_message; - unittest::TestEmptyMessage empty_message; - string bizarro_data = GetBizarroData(); - ASSERT_TRUE(all_extensions_message.ParseFromString(bizarro_data)); - ASSERT_TRUE(empty_message.ParseFromString(bizarro_data)); - - // All fields should have been interpreted as unknown, so the debug strings - // should be the same. - EXPECT_EQ(empty_message.DebugString(), all_extensions_message.DebugString()); -} - -TEST_F(UnknownFieldSetTest, UnknownEnumValue) { - using unittest::TestAllTypes; - using unittest::TestAllExtensions; - using unittest::TestEmptyMessage; - - const FieldDescriptor* singular_field = - TestAllTypes::descriptor()->FindFieldByName("optional_nested_enum"); - const FieldDescriptor* repeated_field = - TestAllTypes::descriptor()->FindFieldByName("repeated_nested_enum"); - ASSERT_TRUE(singular_field != NULL); - ASSERT_TRUE(repeated_field != NULL); - - string data; - - { - TestEmptyMessage empty_message; - UnknownFieldSet* unknown_fields = empty_message.mutable_unknown_fields(); - unknown_fields->AddVarint(singular_field->number(), TestAllTypes::BAR); - unknown_fields->AddVarint(singular_field->number(), 5); // not valid - unknown_fields->AddVarint(repeated_field->number(), TestAllTypes::FOO); - unknown_fields->AddVarint(repeated_field->number(), 4); // not valid - unknown_fields->AddVarint(repeated_field->number(), TestAllTypes::BAZ); - unknown_fields->AddVarint(repeated_field->number(), 6); // not valid - empty_message.SerializeToString(&data); - } - - { - TestAllTypes message; - ASSERT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(TestAllTypes::BAR, message.optional_nested_enum()); - ASSERT_EQ(2, message.repeated_nested_enum_size()); - EXPECT_EQ(TestAllTypes::FOO, message.repeated_nested_enum(0)); - EXPECT_EQ(TestAllTypes::BAZ, message.repeated_nested_enum(1)); - - const UnknownFieldSet& unknown_fields = message.unknown_fields(); - ASSERT_EQ(3, unknown_fields.field_count()); - - EXPECT_EQ(singular_field->number(), unknown_fields.field(0).number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, unknown_fields.field(0).type()); - EXPECT_EQ(5, unknown_fields.field(0).varint()); - - EXPECT_EQ(repeated_field->number(), unknown_fields.field(1).number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, unknown_fields.field(1).type()); - EXPECT_EQ(4, unknown_fields.field(1).varint()); - - EXPECT_EQ(repeated_field->number(), unknown_fields.field(2).number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, unknown_fields.field(2).type()); - EXPECT_EQ(6, unknown_fields.field(2).varint()); - } - - { - using unittest::optional_nested_enum_extension; - using unittest::repeated_nested_enum_extension; - - TestAllExtensions message; - ASSERT_TRUE(message.ParseFromString(data)); - EXPECT_EQ(TestAllTypes::BAR, - message.GetExtension(optional_nested_enum_extension)); - ASSERT_EQ(2, message.ExtensionSize(repeated_nested_enum_extension)); - EXPECT_EQ(TestAllTypes::FOO, - message.GetExtension(repeated_nested_enum_extension, 0)); - EXPECT_EQ(TestAllTypes::BAZ, - message.GetExtension(repeated_nested_enum_extension, 1)); - - const UnknownFieldSet& unknown_fields = message.unknown_fields(); - ASSERT_EQ(3, unknown_fields.field_count()); - - EXPECT_EQ(singular_field->number(), unknown_fields.field(0).number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, unknown_fields.field(0).type()); - EXPECT_EQ(5, unknown_fields.field(0).varint()); - - EXPECT_EQ(repeated_field->number(), unknown_fields.field(1).number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, unknown_fields.field(1).type()); - EXPECT_EQ(4, unknown_fields.field(1).varint()); - - EXPECT_EQ(repeated_field->number(), unknown_fields.field(2).number()); - ASSERT_EQ(UnknownField::TYPE_VARINT, unknown_fields.field(2).type()); - EXPECT_EQ(6, unknown_fields.field(2).varint()); - } -} - -TEST_F(UnknownFieldSetTest, SpaceUsed) { - unittest::TestEmptyMessage empty_message; - - // Make sure an unknown field set has zero space used until a field is - // actually added. - int base_size = empty_message.SpaceUsed(); - UnknownFieldSet* unknown_fields = empty_message.mutable_unknown_fields(); - EXPECT_EQ(base_size, empty_message.SpaceUsed()); - - // Make sure each thing we add to the set increases the SpaceUsed(). - unknown_fields->AddVarint(1, 0); - EXPECT_LT(base_size, empty_message.SpaceUsed()); - base_size = empty_message.SpaceUsed(); - - string* str = unknown_fields->AddLengthDelimited(1); - EXPECT_LT(base_size, empty_message.SpaceUsed()); - base_size = empty_message.SpaceUsed(); - - str->assign(sizeof(string) + 1, 'x'); - EXPECT_LT(base_size, empty_message.SpaceUsed()); - base_size = empty_message.SpaceUsed(); - - UnknownFieldSet* group = unknown_fields->AddGroup(1); - EXPECT_LT(base_size, empty_message.SpaceUsed()); - base_size = empty_message.SpaceUsed(); - - group->AddVarint(1, 0); - EXPECT_LT(base_size, empty_message.SpaceUsed()); -} - -TEST_F(UnknownFieldSetTest, Empty) { - UnknownFieldSet unknown_fields; - EXPECT_TRUE(unknown_fields.empty()); - unknown_fields.AddVarint(6, 123); - EXPECT_FALSE(unknown_fields.empty()); - unknown_fields.Clear(); - EXPECT_TRUE(unknown_fields.empty()); -} - -} // namespace -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/wire_format.cc b/Resources/NetHook/google/protobuf/wire_format.cc deleted file mode 100644 index 831a5794..00000000 --- a/Resources/NetHook/google/protobuf/wire_format.cc +++ /dev/null @@ -1,1069 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace internal { - -using internal::WireFormatLite; - -namespace { - -// This function turns out to be convenient when using some macros later. -inline int GetEnumNumber(const EnumValueDescriptor* descriptor) { - return descriptor->number(); -} - -} // anonymous namespace - -// =================================================================== - -bool UnknownFieldSetFieldSkipper::SkipField( - io::CodedInputStream* input, uint32 tag) { - return WireFormat::SkipField(input, tag, unknown_fields_); -} - -bool UnknownFieldSetFieldSkipper::SkipMessage(io::CodedInputStream* input) { - return WireFormat::SkipMessage(input, unknown_fields_); -} - -void UnknownFieldSetFieldSkipper::SkipUnknownEnum( - int field_number, int value) { - unknown_fields_->AddVarint(field_number, value); -} - -bool WireFormat::SkipField(io::CodedInputStream* input, uint32 tag, - UnknownFieldSet* unknown_fields) { - int number = WireFormatLite::GetTagFieldNumber(tag); - - switch (WireFormatLite::GetTagWireType(tag)) { - case WireFormatLite::WIRETYPE_VARINT: { - uint64 value; - if (!input->ReadVarint64(&value)) return false; - if (unknown_fields != NULL) unknown_fields->AddVarint(number, value); - return true; - } - case WireFormatLite::WIRETYPE_FIXED64: { - uint64 value; - if (!input->ReadLittleEndian64(&value)) return false; - if (unknown_fields != NULL) unknown_fields->AddFixed64(number, value); - return true; - } - case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (unknown_fields == NULL) { - if (!input->Skip(length)) return false; - } else { - if (!input->ReadString(unknown_fields->AddLengthDelimited(number), - length)) { - return false; - } - } - return true; - } - case WireFormatLite::WIRETYPE_START_GROUP: { - if (!input->IncrementRecursionDepth()) return false; - if (!SkipMessage(input, (unknown_fields == NULL) ? - NULL : unknown_fields->AddGroup(number))) { - return false; - } - input->DecrementRecursionDepth(); - // Check that the ending tag matched the starting tag. - if (!input->LastTagWas(WireFormatLite::MakeTag( - WireFormatLite::GetTagFieldNumber(tag), - WireFormatLite::WIRETYPE_END_GROUP))) { - return false; - } - return true; - } - case WireFormatLite::WIRETYPE_END_GROUP: { - return false; - } - case WireFormatLite::WIRETYPE_FIXED32: { - uint32 value; - if (!input->ReadLittleEndian32(&value)) return false; - if (unknown_fields != NULL) unknown_fields->AddFixed32(number, value); - return true; - } - default: { - return false; - } - } -} - -bool WireFormat::SkipMessage(io::CodedInputStream* input, - UnknownFieldSet* unknown_fields) { - while(true) { - uint32 tag = input->ReadTag(); - if (tag == 0) { - // End of input. This is a valid place to end, so return true. - return true; - } - - WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); - - if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) { - // Must be the end of the message. - return true; - } - - if (!SkipField(input, tag, unknown_fields)) return false; - } -} - -void WireFormat::SerializeUnknownFields(const UnknownFieldSet& unknown_fields, - io::CodedOutputStream* output) { - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - switch (field.type()) { - case UnknownField::TYPE_VARINT: - output->WriteVarint32(WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_VARINT)); - output->WriteVarint64(field.varint()); - break; - case UnknownField::TYPE_FIXED32: - output->WriteVarint32(WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_FIXED32)); - output->WriteLittleEndian32(field.fixed32()); - break; - case UnknownField::TYPE_FIXED64: - output->WriteVarint32(WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_FIXED64)); - output->WriteLittleEndian64(field.fixed64()); - break; - case UnknownField::TYPE_LENGTH_DELIMITED: - output->WriteVarint32(WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); - output->WriteVarint32(field.length_delimited().size()); - output->WriteString(field.length_delimited()); - break; - case UnknownField::TYPE_GROUP: - output->WriteVarint32(WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_START_GROUP)); - SerializeUnknownFields(field.group(), output); - output->WriteVarint32(WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_END_GROUP)); - break; - } - } -} - -uint8* WireFormat::SerializeUnknownFieldsToArray( - const UnknownFieldSet& unknown_fields, - uint8* target) { - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - - switch (field.type()) { - case UnknownField::TYPE_VARINT: - target = WireFormatLite::WriteInt64ToArray( - field.number(), field.varint(), target); - break; - case UnknownField::TYPE_FIXED32: - target = WireFormatLite::WriteFixed32ToArray( - field.number(), field.fixed32(), target); - break; - case UnknownField::TYPE_FIXED64: - target = WireFormatLite::WriteFixed64ToArray( - field.number(), field.fixed64(), target); - break; - case UnknownField::TYPE_LENGTH_DELIMITED: - target = WireFormatLite::WriteBytesToArray( - field.number(), field.length_delimited(), target); - break; - case UnknownField::TYPE_GROUP: - target = WireFormatLite::WriteTagToArray( - field.number(), WireFormatLite::WIRETYPE_START_GROUP, target); - target = SerializeUnknownFieldsToArray(field.group(), target); - target = WireFormatLite::WriteTagToArray( - field.number(), WireFormatLite::WIRETYPE_END_GROUP, target); - break; - } - } - return target; -} - -void WireFormat::SerializeUnknownMessageSetItems( - const UnknownFieldSet& unknown_fields, - io::CodedOutputStream* output) { - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - // The only unknown fields that are allowed to exist in a MessageSet are - // messages, which are length-delimited. - if (field.type() == UnknownField::TYPE_LENGTH_DELIMITED) { - const string& data = field.length_delimited(); - - // Start group. - output->WriteVarint32(WireFormatLite::kMessageSetItemStartTag); - - // Write type ID. - output->WriteVarint32(WireFormatLite::kMessageSetTypeIdTag); - output->WriteVarint32(field.number()); - - // Write message. - output->WriteVarint32(WireFormatLite::kMessageSetMessageTag); - output->WriteVarint32(data.size()); - output->WriteString(data); - - // End group. - output->WriteVarint32(WireFormatLite::kMessageSetItemEndTag); - } - } -} - -uint8* WireFormat::SerializeUnknownMessageSetItemsToArray( - const UnknownFieldSet& unknown_fields, - uint8* target) { - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - - // The only unknown fields that are allowed to exist in a MessageSet are - // messages, which are length-delimited. - if (field.type() == UnknownField::TYPE_LENGTH_DELIMITED) { - const string& data = field.length_delimited(); - - // Start group. - target = io::CodedOutputStream::WriteTagToArray( - WireFormatLite::kMessageSetItemStartTag, target); - - // Write type ID. - target = io::CodedOutputStream::WriteTagToArray( - WireFormatLite::kMessageSetTypeIdTag, target); - target = io::CodedOutputStream::WriteVarint32ToArray( - field.number(), target); - - // Write message. - target = io::CodedOutputStream::WriteTagToArray( - WireFormatLite::kMessageSetMessageTag, target); - target = io::CodedOutputStream::WriteVarint32ToArray(data.size(), target); - target = io::CodedOutputStream::WriteStringToArray(data, target); - - // End group. - target = io::CodedOutputStream::WriteTagToArray( - WireFormatLite::kMessageSetItemEndTag, target); - } - } - - return target; -} - -int WireFormat::ComputeUnknownFieldsSize( - const UnknownFieldSet& unknown_fields) { - int size = 0; - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - - switch (field.type()) { - case UnknownField::TYPE_VARINT: - size += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_VARINT)); - size += io::CodedOutputStream::VarintSize64(field.varint()); - break; - case UnknownField::TYPE_FIXED32: - size += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_FIXED32)); - size += sizeof(int32); - break; - case UnknownField::TYPE_FIXED64: - size += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_FIXED64)); - size += sizeof(int64); - break; - case UnknownField::TYPE_LENGTH_DELIMITED: - size += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED)); - size += io::CodedOutputStream::VarintSize32( - field.length_delimited().size()); - size += field.length_delimited().size(); - break; - case UnknownField::TYPE_GROUP: - size += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_START_GROUP)); - size += ComputeUnknownFieldsSize(field.group()); - size += io::CodedOutputStream::VarintSize32( - WireFormatLite::MakeTag(field.number(), - WireFormatLite::WIRETYPE_END_GROUP)); - break; - } - } - - return size; -} - -int WireFormat::ComputeUnknownMessageSetItemsSize( - const UnknownFieldSet& unknown_fields) { - int size = 0; - for (int i = 0; i < unknown_fields.field_count(); i++) { - const UnknownField& field = unknown_fields.field(i); - - // The only unknown fields that are allowed to exist in a MessageSet are - // messages, which are length-delimited. - if (field.type() == UnknownField::TYPE_LENGTH_DELIMITED) { - size += WireFormatLite::kMessageSetItemTagsSize; - size += io::CodedOutputStream::VarintSize32(field.number()); - size += io::CodedOutputStream::VarintSize32( - field.length_delimited().size()); - size += field.length_delimited().size(); - } - } - - return size; -} - -// =================================================================== - -bool WireFormat::ParseAndMergePartial(io::CodedInputStream* input, - Message* message) { - const Descriptor* descriptor = message->GetDescriptor(); - const Reflection* message_reflection = message->GetReflection(); - - while(true) { - uint32 tag = input->ReadTag(); - if (tag == 0) { - // End of input. This is a valid place to end, so return true. - return true; - } - - if (WireFormatLite::GetTagWireType(tag) == - WireFormatLite::WIRETYPE_END_GROUP) { - // Must be the end of the message. - return true; - } - - const FieldDescriptor* field = NULL; - - if (descriptor != NULL) { - int field_number = WireFormatLite::GetTagFieldNumber(tag); - field = descriptor->FindFieldByNumber(field_number); - - // If that failed, check if the field is an extension. - if (field == NULL && descriptor->IsExtensionNumber(field_number)) { - if (input->GetExtensionPool() == NULL) { - field = message_reflection->FindKnownExtensionByNumber(field_number); - } else { - field = input->GetExtensionPool() - ->FindExtensionByNumber(descriptor, field_number); - } - } - - // If that failed, but we're a MessageSet, and this is the tag for a - // MessageSet item, then parse that. - if (field == NULL && - descriptor->options().message_set_wire_format() && - tag == WireFormatLite::kMessageSetItemStartTag) { - if (!ParseAndMergeMessageSetItem(input, message)) { - return false; - } - continue; // Skip ParseAndMergeField(); already taken care of. - } - } - - if (!ParseAndMergeField(tag, field, message, input)) { - return false; - } - } -} - -bool WireFormat::ParseAndMergeField( - uint32 tag, - const FieldDescriptor* field, // May be NULL for unknown - Message* message, - io::CodedInputStream* input) { - const Reflection* message_reflection = message->GetReflection(); - - enum { UNKNOWN, NORMAL_FORMAT, PACKED_FORMAT } value_format; - - if (field == NULL) { - value_format = UNKNOWN; - } else if (WireFormatLite::GetTagWireType(tag) == - WireTypeForFieldType(field->type())) { - value_format = NORMAL_FORMAT; - } else if (field->is_packable() && - WireFormatLite::GetTagWireType(tag) == - WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - value_format = PACKED_FORMAT; - } else { - // We don't recognize this field. Either the field number is unknown - // or the wire type doesn't match. Put it in our unknown field set. - value_format = UNKNOWN; - } - - if (value_format == UNKNOWN) { - return SkipField(input, tag, - message_reflection->MutableUnknownFields(message)); - } else if (value_format == PACKED_FORMAT) { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - io::CodedInputStream::Limit limit = input->PushLimit(length); - - switch (field->type()) { -#define HANDLE_PACKED_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \ - case FieldDescriptor::TYPE_##TYPE: { \ - while (input->BytesUntilLimit() > 0) { \ - CPPTYPE value; \ - if (!WireFormatLite::ReadPrimitive< \ - CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)) \ - return false; \ - message_reflection->Add##CPPTYPE_METHOD(message, field, value); \ - } \ - break; \ - } - - HANDLE_PACKED_TYPE( INT32, int32, Int32) - HANDLE_PACKED_TYPE( INT64, int64, Int64) - HANDLE_PACKED_TYPE(SINT32, int32, Int32) - HANDLE_PACKED_TYPE(SINT64, int64, Int64) - HANDLE_PACKED_TYPE(UINT32, uint32, UInt32) - HANDLE_PACKED_TYPE(UINT64, uint64, UInt64) - - HANDLE_PACKED_TYPE( FIXED32, uint32, UInt32) - HANDLE_PACKED_TYPE( FIXED64, uint64, UInt64) - HANDLE_PACKED_TYPE(SFIXED32, int32, Int32) - HANDLE_PACKED_TYPE(SFIXED64, int64, Int64) - - HANDLE_PACKED_TYPE(FLOAT , float , Float ) - HANDLE_PACKED_TYPE(DOUBLE, double, Double) - - HANDLE_PACKED_TYPE(BOOL, bool, Bool) -#undef HANDLE_PACKED_TYPE - - case FieldDescriptor::TYPE_ENUM: { - while (input->BytesUntilLimit() > 0) { - int value; - if (!WireFormatLite::ReadPrimitive( - input, &value)) return false; - const EnumValueDescriptor* enum_value = - field->enum_type()->FindValueByNumber(value); - if (enum_value != NULL) { - message_reflection->AddEnum(message, field, enum_value); - } - } - - break; - } - - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: - case FieldDescriptor::TYPE_BYTES: - // Can't have packed fields of these types: these should be caught by - // the protocol compiler. - return false; - break; - } - - input->PopLimit(limit); - } else { - // Non-packed value (value_format == NORMAL_FORMAT) - switch (field->type()) { -#define HANDLE_TYPE(TYPE, CPPTYPE, CPPTYPE_METHOD) \ - case FieldDescriptor::TYPE_##TYPE: { \ - CPPTYPE value; \ - if (!WireFormatLite::ReadPrimitive< \ - CPPTYPE, WireFormatLite::TYPE_##TYPE>(input, &value)) \ - return false; \ - if (field->is_repeated()) { \ - message_reflection->Add##CPPTYPE_METHOD(message, field, value); \ - } else { \ - message_reflection->Set##CPPTYPE_METHOD(message, field, value); \ - } \ - break; \ - } - - HANDLE_TYPE( INT32, int32, Int32) - HANDLE_TYPE( INT64, int64, Int64) - HANDLE_TYPE(SINT32, int32, Int32) - HANDLE_TYPE(SINT64, int64, Int64) - HANDLE_TYPE(UINT32, uint32, UInt32) - HANDLE_TYPE(UINT64, uint64, UInt64) - - HANDLE_TYPE( FIXED32, uint32, UInt32) - HANDLE_TYPE( FIXED64, uint64, UInt64) - HANDLE_TYPE(SFIXED32, int32, Int32) - HANDLE_TYPE(SFIXED64, int64, Int64) - - HANDLE_TYPE(FLOAT , float , Float ) - HANDLE_TYPE(DOUBLE, double, Double) - - HANDLE_TYPE(BOOL, bool, Bool) -#undef HANDLE_TYPE - - case FieldDescriptor::TYPE_ENUM: { - int value; - if (!WireFormatLite::ReadPrimitive( - input, &value)) return false; - const EnumValueDescriptor* enum_value = - field->enum_type()->FindValueByNumber(value); - if (enum_value != NULL) { - if (field->is_repeated()) { - message_reflection->AddEnum(message, field, enum_value); - } else { - message_reflection->SetEnum(message, field, enum_value); - } - } else { - // The enum value is not one of the known values. Add it to the - // UnknownFieldSet. - int64 sign_extended_value = static_cast(value); - message_reflection->MutableUnknownFields(message) - ->AddVarint(WireFormatLite::GetTagFieldNumber(tag), - sign_extended_value); - } - break; - } - - // Handle strings separately so that we can optimize the ctype=CORD case. - case FieldDescriptor::TYPE_STRING: { - string value; - if (!WireFormatLite::ReadString(input, &value)) return false; - VerifyUTF8String(value.data(), value.length(), PARSE); - if (field->is_repeated()) { - message_reflection->AddString(message, field, value); - } else { - message_reflection->SetString(message, field, value); - } - break; - } - - case FieldDescriptor::TYPE_BYTES: { - string value; - if (!WireFormatLite::ReadBytes(input, &value)) return false; - if (field->is_repeated()) { - message_reflection->AddString(message, field, value); - } else { - message_reflection->SetString(message, field, value); - } - break; - } - - case FieldDescriptor::TYPE_GROUP: { - Message* sub_message; - if (field->is_repeated()) { - sub_message = message_reflection->AddMessage( - message, field, input->GetExtensionFactory()); - } else { - sub_message = message_reflection->MutableMessage( - message, field, input->GetExtensionFactory()); - } - - if (!WireFormatLite::ReadGroup(WireFormatLite::GetTagFieldNumber(tag), - input, sub_message)) - return false; - break; - } - - case FieldDescriptor::TYPE_MESSAGE: { - Message* sub_message; - if (field->is_repeated()) { - sub_message = message_reflection->AddMessage( - message, field, input->GetExtensionFactory()); - } else { - sub_message = message_reflection->MutableMessage( - message, field, input->GetExtensionFactory()); - } - - if (!WireFormatLite::ReadMessage(input, sub_message)) return false; - break; - } - } - } - - return true; -} - -bool WireFormat::ParseAndMergeMessageSetItem( - io::CodedInputStream* input, - Message* message) { - const Reflection* message_reflection = message->GetReflection(); - - // This method parses a group which should contain two fields: - // required int32 type_id = 2; - // required data message = 3; - - // Once we see a type_id, we'll construct a fake tag for this extension - // which is the tag it would have had under the proto2 extensions wire - // format. - uint32 fake_tag = 0; - - // Once we see a type_id, we'll look up the FieldDescriptor for the - // extension. - const FieldDescriptor* field = NULL; - - // If we see message data before the type_id, we'll append it to this so - // we can parse it later. This will probably never happen in practice, - // as no MessageSet encoder I know of writes the message before the type ID. - // But, it's technically valid so we should allow it. - // TODO(kenton): Use a Cord instead? Do I care? - string message_data; - - while (true) { - uint32 tag = input->ReadTag(); - if (tag == 0) return false; - - switch (tag) { - case WireFormatLite::kMessageSetTypeIdTag: { - uint32 type_id; - if (!input->ReadVarint32(&type_id)) return false; - fake_tag = WireFormatLite::MakeTag( - type_id, WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - field = message_reflection->FindKnownExtensionByNumber(type_id); - - if (!message_data.empty()) { - // We saw some message data before the type_id. Have to parse it - // now. - io::ArrayInputStream raw_input(message_data.data(), - message_data.size()); - io::CodedInputStream sub_input(&raw_input); - if (!ParseAndMergeField(fake_tag, field, message, - &sub_input)) { - return false; - } - message_data.clear(); - } - - break; - } - - case WireFormatLite::kMessageSetMessageTag: { - if (fake_tag == 0) { - // We haven't seen a type_id yet. Append this data to message_data. - string temp; - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->ReadString(&temp, length)) return false; - message_data.append(temp); - } else { - // Already saw type_id, so we can parse this directly. - if (!ParseAndMergeField(fake_tag, field, message, input)) { - return false; - } - } - - break; - } - - case WireFormatLite::kMessageSetItemEndTag: { - return true; - } - - default: { - if (!SkipField(input, tag, NULL)) return false; - } - } - } -} - -// =================================================================== - -void WireFormat::SerializeWithCachedSizes( - const Message& message, - int size, io::CodedOutputStream* output) { - const Descriptor* descriptor = message.GetDescriptor(); - const Reflection* message_reflection = message.GetReflection(); - int expected_endpoint = output->ByteCount() + size; - - vector fields; - message_reflection->ListFields(message, &fields); - for (int i = 0; i < fields.size(); i++) { - SerializeFieldWithCachedSizes(fields[i], message, output); - } - - if (descriptor->options().message_set_wire_format()) { - SerializeUnknownMessageSetItems( - message_reflection->GetUnknownFields(message), output); - } else { - SerializeUnknownFields( - message_reflection->GetUnknownFields(message), output); - } - - GOOGLE_CHECK_EQ(output->ByteCount(), expected_endpoint) - << ": Protocol message serialized to a size different from what was " - "originally expected. Perhaps it was modified by another thread " - "during serialization?"; -} - -void WireFormat::SerializeFieldWithCachedSizes( - const FieldDescriptor* field, - const Message& message, - io::CodedOutputStream* output) { - const Reflection* message_reflection = message.GetReflection(); - - if (field->is_extension() && - field->containing_type()->options().message_set_wire_format() && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !field->is_repeated()) { - SerializeMessageSetItemWithCachedSizes(field, message, output); - return; - } - - int count = 0; - - if (field->is_repeated()) { - count = message_reflection->FieldSize(message, field); - } else if (message_reflection->HasField(message, field)) { - count = 1; - } - - const bool is_packed = field->options().packed(); - if (is_packed && count > 0) { - WireFormatLite::WriteTag(field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); - const int data_size = FieldDataOnlyByteSize(field, message); - output->WriteVarint32(data_size); - } - - for (int j = 0; j < count; j++) { - switch (field->type()) { -#define HANDLE_PRIMITIVE_TYPE(TYPE, CPPTYPE, TYPE_METHOD, CPPTYPE_METHOD) \ - case FieldDescriptor::TYPE_##TYPE: { \ - const CPPTYPE value = field->is_repeated() ? \ - message_reflection->GetRepeated##CPPTYPE_METHOD( \ - message, field, j) : \ - message_reflection->Get##CPPTYPE_METHOD( \ - message, field); \ - if (is_packed) { \ - WireFormatLite::Write##TYPE_METHOD##NoTag(value, output); \ - } else { \ - WireFormatLite::Write##TYPE_METHOD(field->number(), value, output); \ - } \ - break; \ - } - - HANDLE_PRIMITIVE_TYPE( INT32, int32, Int32, Int32) - HANDLE_PRIMITIVE_TYPE( INT64, int64, Int64, Int64) - HANDLE_PRIMITIVE_TYPE(SINT32, int32, SInt32, Int32) - HANDLE_PRIMITIVE_TYPE(SINT64, int64, SInt64, Int64) - HANDLE_PRIMITIVE_TYPE(UINT32, uint32, UInt32, UInt32) - HANDLE_PRIMITIVE_TYPE(UINT64, uint64, UInt64, UInt64) - - HANDLE_PRIMITIVE_TYPE( FIXED32, uint32, Fixed32, UInt32) - HANDLE_PRIMITIVE_TYPE( FIXED64, uint64, Fixed64, UInt64) - HANDLE_PRIMITIVE_TYPE(SFIXED32, int32, SFixed32, Int32) - HANDLE_PRIMITIVE_TYPE(SFIXED64, int64, SFixed64, Int64) - - HANDLE_PRIMITIVE_TYPE(FLOAT , float , Float , Float ) - HANDLE_PRIMITIVE_TYPE(DOUBLE, double, Double, Double) - - HANDLE_PRIMITIVE_TYPE(BOOL, bool, Bool, Bool) -#undef HANDLE_PRIMITIVE_TYPE - -#define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \ - case FieldDescriptor::TYPE_##TYPE: \ - WireFormatLite::Write##TYPE_METHOD( \ - field->number(), \ - field->is_repeated() ? \ - message_reflection->GetRepeated##CPPTYPE_METHOD( \ - message, field, j) : \ - message_reflection->Get##CPPTYPE_METHOD(message, field), \ - output); \ - break; - - HANDLE_TYPE(GROUP , Group , Message) - HANDLE_TYPE(MESSAGE, Message, Message) -#undef HANDLE_TYPE - - case FieldDescriptor::TYPE_ENUM: { - const EnumValueDescriptor* value = field->is_repeated() ? - message_reflection->GetRepeatedEnum(message, field, j) : - message_reflection->GetEnum(message, field); - if (is_packed) { - WireFormatLite::WriteEnumNoTag(value->number(), output); - } else { - WireFormatLite::WriteEnum(field->number(), value->number(), output); - } - break; - } - - // Handle strings separately so that we can get string references - // instead of copying. - case FieldDescriptor::TYPE_STRING: { - string scratch; - const string& value = field->is_repeated() ? - message_reflection->GetRepeatedStringReference( - message, field, j, &scratch) : - message_reflection->GetStringReference(message, field, &scratch); - VerifyUTF8String(value.data(), value.length(), SERIALIZE); - WireFormatLite::WriteString(field->number(), value, output); - break; - } - - case FieldDescriptor::TYPE_BYTES: { - string scratch; - const string& value = field->is_repeated() ? - message_reflection->GetRepeatedStringReference( - message, field, j, &scratch) : - message_reflection->GetStringReference(message, field, &scratch); - WireFormatLite::WriteBytes(field->number(), value, output); - break; - } - } - } -} - -void WireFormat::SerializeMessageSetItemWithCachedSizes( - const FieldDescriptor* field, - const Message& message, - io::CodedOutputStream* output) { - const Reflection* message_reflection = message.GetReflection(); - - // Start group. - output->WriteVarint32(WireFormatLite::kMessageSetItemStartTag); - - // Write type ID. - output->WriteVarint32(WireFormatLite::kMessageSetTypeIdTag); - output->WriteVarint32(field->number()); - - // Write message. - output->WriteVarint32(WireFormatLite::kMessageSetMessageTag); - - const Message& sub_message = message_reflection->GetMessage(message, field); - output->WriteVarint32(sub_message.GetCachedSize()); - sub_message.SerializeWithCachedSizes(output); - - // End group. - output->WriteVarint32(WireFormatLite::kMessageSetItemEndTag); -} - -// =================================================================== - -int WireFormat::ByteSize(const Message& message) { - const Descriptor* descriptor = message.GetDescriptor(); - const Reflection* message_reflection = message.GetReflection(); - - int our_size = 0; - - vector fields; - message_reflection->ListFields(message, &fields); - for (int i = 0; i < fields.size(); i++) { - our_size += FieldByteSize(fields[i], message); - } - - if (descriptor->options().message_set_wire_format()) { - our_size += ComputeUnknownMessageSetItemsSize( - message_reflection->GetUnknownFields(message)); - } else { - our_size += ComputeUnknownFieldsSize( - message_reflection->GetUnknownFields(message)); - } - - return our_size; -} - -int WireFormat::FieldByteSize( - const FieldDescriptor* field, - const Message& message) { - const Reflection* message_reflection = message.GetReflection(); - - if (field->is_extension() && - field->containing_type()->options().message_set_wire_format() && - field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - !field->is_repeated()) { - return MessageSetItemByteSize(field, message); - } - - int count = 0; - if (field->is_repeated()) { - count = message_reflection->FieldSize(message, field); - } else if (message_reflection->HasField(message, field)) { - count = 1; - } - - const int data_size = FieldDataOnlyByteSize(field, message); - int our_size = data_size; - if (field->options().packed()) { - if (data_size > 0) { - // Packed fields get serialized like a string, not their native type. - // Technically this doesn't really matter; the size only changes if it's - // a GROUP - our_size += TagSize(field->number(), FieldDescriptor::TYPE_STRING); - our_size += io::CodedOutputStream::VarintSize32(data_size); - } - } else { - our_size += count * TagSize(field->number(), field->type()); - } - return our_size; -} - -int WireFormat::FieldDataOnlyByteSize( - const FieldDescriptor* field, - const Message& message) { - const Reflection* message_reflection = message.GetReflection(); - - int count = 0; - if (field->is_repeated()) { - count = message_reflection->FieldSize(message, field); - } else if (message_reflection->HasField(message, field)) { - count = 1; - } - - int data_size = 0; - switch (field->type()) { -#define HANDLE_TYPE(TYPE, TYPE_METHOD, CPPTYPE_METHOD) \ - case FieldDescriptor::TYPE_##TYPE: \ - if (field->is_repeated()) { \ - for (int j = 0; j < count; j++) { \ - data_size += WireFormatLite::TYPE_METHOD##Size( \ - message_reflection->GetRepeated##CPPTYPE_METHOD( \ - message, field, j)); \ - } \ - } else { \ - data_size += WireFormatLite::TYPE_METHOD##Size( \ - message_reflection->Get##CPPTYPE_METHOD(message, field)); \ - } \ - break; - -#define HANDLE_FIXED_TYPE(TYPE, TYPE_METHOD) \ - case FieldDescriptor::TYPE_##TYPE: \ - data_size += count * WireFormatLite::k##TYPE_METHOD##Size; \ - break; - - HANDLE_TYPE( INT32, Int32, Int32) - HANDLE_TYPE( INT64, Int64, Int64) - HANDLE_TYPE(SINT32, SInt32, Int32) - HANDLE_TYPE(SINT64, SInt64, Int64) - HANDLE_TYPE(UINT32, UInt32, UInt32) - HANDLE_TYPE(UINT64, UInt64, UInt64) - - HANDLE_FIXED_TYPE( FIXED32, Fixed32) - HANDLE_FIXED_TYPE( FIXED64, Fixed64) - HANDLE_FIXED_TYPE(SFIXED32, SFixed32) - HANDLE_FIXED_TYPE(SFIXED64, SFixed64) - - HANDLE_FIXED_TYPE(FLOAT , Float ) - HANDLE_FIXED_TYPE(DOUBLE, Double) - - HANDLE_FIXED_TYPE(BOOL, Bool) - - HANDLE_TYPE(GROUP , Group , Message) - HANDLE_TYPE(MESSAGE, Message, Message) -#undef HANDLE_TYPE -#undef HANDLE_FIXED_TYPE - - case FieldDescriptor::TYPE_ENUM: { - if (field->is_repeated()) { - for (int j = 0; j < count; j++) { - data_size += WireFormatLite::EnumSize( - message_reflection->GetRepeatedEnum(message, field, j)->number()); - } - } else { - data_size += WireFormatLite::EnumSize( - message_reflection->GetEnum(message, field)->number()); - } - break; - } - - // Handle strings separately so that we can get string references - // instead of copying. - case FieldDescriptor::TYPE_STRING: - case FieldDescriptor::TYPE_BYTES: { - for (int j = 0; j < count; j++) { - string scratch; - const string& value = field->is_repeated() ? - message_reflection->GetRepeatedStringReference( - message, field, j, &scratch) : - message_reflection->GetStringReference(message, field, &scratch); - data_size += WireFormatLite::StringSize(value); - } - break; - } - } - return data_size; -} - -int WireFormat::MessageSetItemByteSize( - const FieldDescriptor* field, - const Message& message) { - const Reflection* message_reflection = message.GetReflection(); - - int our_size = WireFormatLite::kMessageSetItemTagsSize; - - // type_id - our_size += io::CodedOutputStream::VarintSize32(field->number()); - - // message - const Message& sub_message = message_reflection->GetMessage(message, field); - int message_size = sub_message.ByteSize(); - - our_size += io::CodedOutputStream::VarintSize32(message_size); - our_size += message_size; - - return our_size; -} - -void WireFormat::VerifyUTF8StringFallback(const char* data, - int size, - Operation op) { - if (!IsStructurallyValidUTF8(data, size)) { - const char* operation_str = NULL; - switch (op) { - case PARSE: - operation_str = "parsing"; - break; - case SERIALIZE: - operation_str = "serializing"; - break; - // no default case: have the compiler warn if a case is not covered. - } - GOOGLE_LOG(ERROR) << "Encountered string containing invalid UTF-8 data while " - << operation_str - << " protocol buffer. Strings must contain only UTF-8; " - "use the 'bytes' type for raw bytes."; - } -} - - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/wire_format.h b/Resources/NetHook/google/protobuf/wire_format.h deleted file mode 100644 index c7539250..00000000 --- a/Resources/NetHook/google/protobuf/wire_format.h +++ /dev/null @@ -1,304 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// atenasio@google.com (Chris Atenasio) (ZigZag transform) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This header is logically internal, but is made public because it is used -// from protocol-compiler-generated code, which may reside in other components. - -#ifndef GOOGLE_PROTOBUF_WIRE_FORMAT_H__ -#define GOOGLE_PROTOBUF_WIRE_FORMAT_H__ - -#include -#include -#include -#include -#include - -// Do UTF-8 validation on string type in Debug build only -#ifndef NDEBUG -#define GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED -#endif - -namespace google { -namespace protobuf { - namespace io { - class CodedInputStream; // coded_stream.h - class CodedOutputStream; // coded_stream.h - } - class UnknownFieldSet; // unknown_field_set.h -} - -namespace protobuf { -namespace internal { - -// This class is for internal use by the protocol buffer library and by -// protocol-complier-generated message classes. It must not be called -// directly by clients. -// -// This class contains code for implementing the binary protocol buffer -// wire format via reflection. The WireFormatLite class implements the -// non-reflection based routines. -// -// This class is really a namespace that contains only static methods -class LIBPROTOBUF_EXPORT WireFormat { - public: - - // Given a field return its WireType - static inline WireFormatLite::WireType WireTypeForField( - const FieldDescriptor* field); - - // Given a FieldSescriptor::Type return its WireType - static inline WireFormatLite::WireType WireTypeForFieldType( - FieldDescriptor::Type type); - - // Compute the byte size of a tag. For groups, this includes both the start - // and end tags. - static inline int TagSize(int field_number, FieldDescriptor::Type type); - - // These procedures can be used to implement the methods of Message which - // handle parsing and serialization of the protocol buffer wire format - // using only the Reflection interface. When you ask the protocol - // compiler to optimize for code size rather than speed, it will implement - // those methods in terms of these procedures. Of course, these are much - // slower than the specialized implementations which the protocol compiler - // generates when told to optimize for speed. - - // Read a message in protocol buffer wire format. - // - // This procedure reads either to the end of the input stream or through - // a WIRETYPE_END_GROUP tag ending the message, whichever comes first. - // It returns false if the input is invalid. - // - // Required fields are NOT checked by this method. You must call - // IsInitialized() on the resulting message yourself. - static bool ParseAndMergePartial(io::CodedInputStream* input, - Message* message); - - // Serialize a message in protocol buffer wire format. - // - // Any embedded messages within the message must have their correct sizes - // cached. However, the top-level message need not; its size is passed as - // a parameter to this procedure. - // - // These return false iff the underlying stream returns a write error. - static void SerializeWithCachedSizes( - const Message& message, - int size, io::CodedOutputStream* output); - - // Implements Message::ByteSize() via reflection. WARNING: The result - // of this method is *not* cached anywhere. However, all embedded messages - // will have their ByteSize() methods called, so their sizes will be cached. - // Therefore, calling this method is sufficient to allow you to call - // WireFormat::SerializeWithCachedSizes() on the same object. - static int ByteSize(const Message& message); - - // ----------------------------------------------------------------- - // Helpers for dealing with unknown fields - - // Skips a field value of the given WireType. The input should start - // positioned immediately after the tag. If unknown_fields is non-NULL, - // the contents of the field will be added to it. - static bool SkipField(io::CodedInputStream* input, uint32 tag, - UnknownFieldSet* unknown_fields); - - // Reads and ignores a message from the input. If unknown_fields is non-NULL, - // the contents will be added to it. - static bool SkipMessage(io::CodedInputStream* input, - UnknownFieldSet* unknown_fields); - - // Write the contents of an UnknownFieldSet to the output. - static void SerializeUnknownFields(const UnknownFieldSet& unknown_fields, - io::CodedOutputStream* output); - // Same as above, except writing directly to the provided buffer. - // Requires that the buffer have sufficient capacity for - // ComputeUnknownFieldsSize(unknown_fields). - // - // Returns a pointer past the last written byte. - static uint8* SerializeUnknownFieldsToArray( - const UnknownFieldSet& unknown_fields, - uint8* target); - - // Same thing except for messages that have the message_set_wire_format - // option. - static void SerializeUnknownMessageSetItems( - const UnknownFieldSet& unknown_fields, - io::CodedOutputStream* output); - // Same as above, except writing directly to the provided buffer. - // Requires that the buffer have sufficient capacity for - // ComputeUnknownMessageSetItemsSize(unknown_fields). - // - // Returns a pointer past the last written byte. - static uint8* SerializeUnknownMessageSetItemsToArray( - const UnknownFieldSet& unknown_fields, - uint8* target); - - // Compute the size of the UnknownFieldSet on the wire. - static int ComputeUnknownFieldsSize(const UnknownFieldSet& unknown_fields); - - // Same thing except for messages that have the message_set_wire_format - // option. - static int ComputeUnknownMessageSetItemsSize( - const UnknownFieldSet& unknown_fields); - - - // Helper functions for encoding and decoding tags. (Inlined below and in - // _inl.h) - // - // This is different from MakeTag(field->number(), field->type()) in the case - // of packed repeated fields. - static uint32 MakeTag(const FieldDescriptor* field); - - // Parse a single field. The input should start out positioned immidately - // after the tag. - static bool ParseAndMergeField( - uint32 tag, - const FieldDescriptor* field, // May be NULL for unknown - Message* message, - io::CodedInputStream* input); - - // Serialize a single field. - static void SerializeFieldWithCachedSizes( - const FieldDescriptor* field, // Cannot be NULL - const Message& message, - io::CodedOutputStream* output); - - // Compute size of a single field. If the field is a message type, this - // will call ByteSize() for the embedded message, insuring that it caches - // its size. - static int FieldByteSize( - const FieldDescriptor* field, // Cannot be NULL - const Message& message); - - // Parse/serialize a MessageSet::Item group. Used with messages that use - // opion message_set_wire_format = true. - static bool ParseAndMergeMessageSetItem( - io::CodedInputStream* input, - Message* message); - static void SerializeMessageSetItemWithCachedSizes( - const FieldDescriptor* field, - const Message& message, - io::CodedOutputStream* output); - static int MessageSetItemByteSize( - const FieldDescriptor* field, - const Message& message); - - // Computes the byte size of a field, excluding tags. For packed fields, it - // only includes the size of the raw data, and not the size of the total - // length, but for other length-delimited types, the size of the length is - // included. - static int FieldDataOnlyByteSize( - const FieldDescriptor* field, // Cannot be NULL - const Message& message); - - enum Operation { - PARSE, - SERIALIZE, - }; - - // Verifies that a string field is valid UTF8, logging an error if not. - static void VerifyUTF8String(const char* data, int size, Operation op); - - private: - // Verifies that a string field is valid UTF8, logging an error if not. - static void VerifyUTF8StringFallback( - const char* data, - int size, - Operation op); - - - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WireFormat); -}; - -// Subclass of FieldSkipper which saves skipped fields to an UnknownFieldSet. -class LIBPROTOBUF_EXPORT UnknownFieldSetFieldSkipper : public FieldSkipper { - public: - UnknownFieldSetFieldSkipper(UnknownFieldSet* unknown_fields) - : unknown_fields_(unknown_fields) {} - virtual ~UnknownFieldSetFieldSkipper() {} - - // implements FieldSkipper ----------------------------------------- - virtual bool SkipField(io::CodedInputStream* input, uint32 tag); - virtual bool SkipMessage(io::CodedInputStream* input); - virtual void SkipUnknownEnum(int field_number, int value); - - private: - UnknownFieldSet* unknown_fields_; -}; - -// inline methods ==================================================== - -inline WireFormatLite::WireType WireFormat::WireTypeForField( - const FieldDescriptor* field) { - if (field->options().packed()) { - return WireFormatLite::WIRETYPE_LENGTH_DELIMITED; - } else { - return WireTypeForFieldType(field->type()); - } -} - -inline WireFormatLite::WireType WireFormat::WireTypeForFieldType( - FieldDescriptor::Type type) { - // Some compilers don't like enum -> enum casts, so we implicit_cast to - // int first. - return WireFormatLite::WireTypeForFieldType( - static_cast( - implicit_cast(type))); -} - -inline uint32 WireFormat::MakeTag(const FieldDescriptor* field) { - return WireFormatLite::MakeTag(field->number(), WireTypeForField(field)); -} - -inline int WireFormat::TagSize(int field_number, FieldDescriptor::Type type) { - // Some compilers don't like enum -> enum casts, so we implicit_cast to - // int first. - return WireFormatLite::TagSize(field_number, - static_cast( - implicit_cast(type))); -} - -inline void WireFormat::VerifyUTF8String(const char* data, int size, - WireFormat::Operation op) { -#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - WireFormat::VerifyUTF8StringFallback(data, size, op); -#endif -} - - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_WIRE_FORMAT_H__ diff --git a/Resources/NetHook/google/protobuf/wire_format_lite.cc b/Resources/NetHook/google/protobuf/wire_format_lite.cc deleted file mode 100644 index d347d116..00000000 --- a/Resources/NetHook/google/protobuf/wire_format_lite.cc +++ /dev/null @@ -1,359 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { - -#ifndef _MSC_VER // MSVC doesn't like definitions of inline constants, GCC - // requires them. -const int WireFormatLite::kMessageSetItemStartTag; -const int WireFormatLite::kMessageSetItemEndTag; -const int WireFormatLite::kMessageSetTypeIdTag; -const int WireFormatLite::kMessageSetMessageTag; - -#endif - -const int WireFormatLite::kMessageSetItemTagsSize = - io::CodedOutputStream::VarintSize32(kMessageSetItemStartTag) + - io::CodedOutputStream::VarintSize32(kMessageSetItemEndTag) + - io::CodedOutputStream::VarintSize32(kMessageSetTypeIdTag) + - io::CodedOutputStream::VarintSize32(kMessageSetMessageTag); - -const WireFormatLite::CppType -WireFormatLite::kFieldTypeToCppTypeMap[MAX_FIELD_TYPE + 1] = { - static_cast(0), // 0 is reserved for errors - - CPPTYPE_DOUBLE, // TYPE_DOUBLE - CPPTYPE_FLOAT, // TYPE_FLOAT - CPPTYPE_INT64, // TYPE_INT64 - CPPTYPE_UINT64, // TYPE_UINT64 - CPPTYPE_INT32, // TYPE_INT32 - CPPTYPE_UINT64, // TYPE_FIXED64 - CPPTYPE_UINT32, // TYPE_FIXED32 - CPPTYPE_BOOL, // TYPE_BOOL - CPPTYPE_STRING, // TYPE_STRING - CPPTYPE_MESSAGE, // TYPE_GROUP - CPPTYPE_MESSAGE, // TYPE_MESSAGE - CPPTYPE_STRING, // TYPE_BYTES - CPPTYPE_UINT32, // TYPE_UINT32 - CPPTYPE_ENUM, // TYPE_ENUM - CPPTYPE_INT32, // TYPE_SFIXED32 - CPPTYPE_INT64, // TYPE_SFIXED64 - CPPTYPE_INT32, // TYPE_SINT32 - CPPTYPE_INT64, // TYPE_SINT64 -}; - -const WireFormatLite::WireType -WireFormatLite::kWireTypeForFieldType[MAX_FIELD_TYPE + 1] = { - static_cast(-1), // invalid - WireFormatLite::WIRETYPE_FIXED64, // TYPE_DOUBLE - WireFormatLite::WIRETYPE_FIXED32, // TYPE_FLOAT - WireFormatLite::WIRETYPE_VARINT, // TYPE_INT64 - WireFormatLite::WIRETYPE_VARINT, // TYPE_UINT64 - WireFormatLite::WIRETYPE_VARINT, // TYPE_INT32 - WireFormatLite::WIRETYPE_FIXED64, // TYPE_FIXED64 - WireFormatLite::WIRETYPE_FIXED32, // TYPE_FIXED32 - WireFormatLite::WIRETYPE_VARINT, // TYPE_BOOL - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, // TYPE_STRING - WireFormatLite::WIRETYPE_START_GROUP, // TYPE_GROUP - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, // TYPE_MESSAGE - WireFormatLite::WIRETYPE_LENGTH_DELIMITED, // TYPE_BYTES - WireFormatLite::WIRETYPE_VARINT, // TYPE_UINT32 - WireFormatLite::WIRETYPE_VARINT, // TYPE_ENUM - WireFormatLite::WIRETYPE_FIXED32, // TYPE_SFIXED32 - WireFormatLite::WIRETYPE_FIXED64, // TYPE_SFIXED64 - WireFormatLite::WIRETYPE_VARINT, // TYPE_SINT32 - WireFormatLite::WIRETYPE_VARINT, // TYPE_SINT64 -}; - -bool WireFormatLite::SkipField( - io::CodedInputStream* input, uint32 tag) { - switch (WireFormatLite::GetTagWireType(tag)) { - case WireFormatLite::WIRETYPE_VARINT: { - uint64 value; - if (!input->ReadVarint64(&value)) return false; - return true; - } - case WireFormatLite::WIRETYPE_FIXED64: { - uint64 value; - if (!input->ReadLittleEndian64(&value)) return false; - return true; - } - case WireFormatLite::WIRETYPE_LENGTH_DELIMITED: { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->Skip(length)) return false; - return true; - } - case WireFormatLite::WIRETYPE_START_GROUP: { - if (!input->IncrementRecursionDepth()) return false; - if (!SkipMessage(input)) return false; - input->DecrementRecursionDepth(); - // Check that the ending tag matched the starting tag. - if (!input->LastTagWas(WireFormatLite::MakeTag( - WireFormatLite::GetTagFieldNumber(tag), - WireFormatLite::WIRETYPE_END_GROUP))) { - return false; - } - return true; - } - case WireFormatLite::WIRETYPE_END_GROUP: { - return false; - } - case WireFormatLite::WIRETYPE_FIXED32: { - uint32 value; - if (!input->ReadLittleEndian32(&value)) return false; - return true; - } - default: { - return false; - } - } -} - -bool WireFormatLite::SkipMessage(io::CodedInputStream* input) { - while(true) { - uint32 tag = input->ReadTag(); - if (tag == 0) { - // End of input. This is a valid place to end, so return true. - return true; - } - - WireFormatLite::WireType wire_type = WireFormatLite::GetTagWireType(tag); - - if (wire_type == WireFormatLite::WIRETYPE_END_GROUP) { - // Must be the end of the message. - return true; - } - - if (!SkipField(input, tag)) return false; - } -} - -bool FieldSkipper::SkipField( - io::CodedInputStream* input, uint32 tag) { - return WireFormatLite::SkipField(input, tag); -} - -bool FieldSkipper::SkipMessage(io::CodedInputStream* input) { - return WireFormatLite::SkipMessage(input); -} - -void FieldSkipper::SkipUnknownEnum( - int field_number, int value) { - // Nothing. -} - -bool WireFormatLite::ReadPackedEnumNoInline(io::CodedInputStream* input, - bool (*is_valid)(int), - RepeatedField* values) { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - io::CodedInputStream::Limit limit = input->PushLimit(length); - while (input->BytesUntilLimit() > 0) { - int value; - if (!google::protobuf::internal::WireFormatLite::ReadPrimitive< - int, WireFormatLite::TYPE_ENUM>(input, &value)) { - return false; - } - if (is_valid(value)) { - values->Add(value); - } - } - input->PopLimit(limit); - return true; -} - -void WireFormatLite::WriteInt32(int field_number, int32 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteInt32NoTag(value, output); -} -void WireFormatLite::WriteInt64(int field_number, int64 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteInt64NoTag(value, output); -} -void WireFormatLite::WriteUInt32(int field_number, uint32 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteUInt32NoTag(value, output); -} -void WireFormatLite::WriteUInt64(int field_number, uint64 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteUInt64NoTag(value, output); -} -void WireFormatLite::WriteSInt32(int field_number, int32 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteSInt32NoTag(value, output); -} -void WireFormatLite::WriteSInt64(int field_number, int64 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteSInt64NoTag(value, output); -} -void WireFormatLite::WriteFixed32(int field_number, uint32 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_FIXED32, output); - WriteFixed32NoTag(value, output); -} -void WireFormatLite::WriteFixed64(int field_number, uint64 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_FIXED64, output); - WriteFixed64NoTag(value, output); -} -void WireFormatLite::WriteSFixed32(int field_number, int32 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_FIXED32, output); - WriteSFixed32NoTag(value, output); -} -void WireFormatLite::WriteSFixed64(int field_number, int64 value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_FIXED64, output); - WriteSFixed64NoTag(value, output); -} -void WireFormatLite::WriteFloat(int field_number, float value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_FIXED32, output); - WriteFloatNoTag(value, output); -} -void WireFormatLite::WriteDouble(int field_number, double value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_FIXED64, output); - WriteDoubleNoTag(value, output); -} -void WireFormatLite::WriteBool(int field_number, bool value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteBoolNoTag(value, output); -} -void WireFormatLite::WriteEnum(int field_number, int value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_VARINT, output); - WriteEnumNoTag(value, output); -} - -void WireFormatLite::WriteString(int field_number, const string& value, - io::CodedOutputStream* output) { - // String is for UTF-8 text only - WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(value.size()); - output->WriteString(value); -} -void WireFormatLite::WriteBytes(int field_number, const string& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(value.size()); - output->WriteString(value); -} - - -void WireFormatLite::WriteGroup(int field_number, - const MessageLite& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_START_GROUP, output); - value.SerializeWithCachedSizes(output); - WriteTag(field_number, WIRETYPE_END_GROUP, output); -} - -void WireFormatLite::WriteMessage(int field_number, - const MessageLite& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - const int size = value.GetCachedSize(); - output->WriteVarint32(size); - value.SerializeWithCachedSizes(output); -} - -void WireFormatLite::WriteGroupMaybeToArray(int field_number, - const MessageLite& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_START_GROUP, output); - const int size = value.GetCachedSize(); - uint8* target = output->GetDirectBufferForNBytesAndAdvance(size); - if (target != NULL) { - uint8* end = value.SerializeWithCachedSizesToArray(target); - GOOGLE_DCHECK_EQ(end - target, size); - } else { - value.SerializeWithCachedSizes(output); - } - WriteTag(field_number, WIRETYPE_END_GROUP, output); -} - -void WireFormatLite::WriteMessageMaybeToArray(int field_number, - const MessageLite& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - const int size = value.GetCachedSize(); - output->WriteVarint32(size); - uint8* target = output->GetDirectBufferForNBytesAndAdvance(size); - if (target != NULL) { - uint8* end = value.SerializeWithCachedSizesToArray(target); - GOOGLE_DCHECK_EQ(end - target, size); - } else { - value.SerializeWithCachedSizes(output); - } -} - -bool WireFormatLite::ReadString(io::CodedInputStream* input, - string* value) { - // String is for UTF-8 text only - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->InternalReadStringInline(value, length)) return false; - return true; -} -bool WireFormatLite::ReadBytes(io::CodedInputStream* input, - string* value) { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - return input->InternalReadStringInline(value, length); -} - -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/google/protobuf/wire_format_lite.h b/Resources/NetHook/google/protobuf/wire_format_lite.h deleted file mode 100644 index e3d5b2d8..00000000 --- a/Resources/NetHook/google/protobuf/wire_format_lite.h +++ /dev/null @@ -1,620 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// atenasio@google.com (Chris Atenasio) (ZigZag transform) -// wink@google.com (Wink Saville) (refactored from wire_format.h) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. -// -// This header is logically internal, but is made public because it is used -// from protocol-compiler-generated code, which may reside in other components. - -#ifndef GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_H__ -#define GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_H__ - -#include -#include - -namespace google { - -namespace protobuf { - template class RepeatedField; // repeated_field.h - namespace io { - class CodedInputStream; // coded_stream.h - class CodedOutputStream; // coded_stream.h - } -} - -namespace protobuf { -namespace internal { - -class StringPieceField; - -// This class is for internal use by the protocol buffer library and by -// protocol-complier-generated message classes. It must not be called -// directly by clients. -// -// This class contains helpers for implementing the binary protocol buffer -// wire format without the need for reflection. Use WireFormat when using -// reflection. -// -// This class is really a namespace that contains only static methods. -class LIBPROTOBUF_EXPORT WireFormatLite { - public: - - // ----------------------------------------------------------------- - // Helper constants and functions related to the format. These are - // mostly meant for internal and generated code to use. - - // The wire format is composed of a sequence of tag/value pairs, each - // of which contains the value of one field (or one element of a repeated - // field). Each tag is encoded as a varint. The lower bits of the tag - // identify its wire type, which specifies the format of the data to follow. - // The rest of the bits contain the field number. Each type of field (as - // declared by FieldDescriptor::Type, in descriptor.h) maps to one of - // these wire types. Immediately following each tag is the field's value, - // encoded in the format specified by the wire type. Because the tag - // identifies the encoding of this data, it is possible to skip - // unrecognized fields for forwards compatibility. - - enum WireType { - WIRETYPE_VARINT = 0, - WIRETYPE_FIXED64 = 1, - WIRETYPE_LENGTH_DELIMITED = 2, - WIRETYPE_START_GROUP = 3, - WIRETYPE_END_GROUP = 4, - WIRETYPE_FIXED32 = 5, - }; - - // Lite alternative to FieldDescriptor::Type. Must be kept in sync. - enum FieldType { - TYPE_DOUBLE = 1, - TYPE_FLOAT = 2, - TYPE_INT64 = 3, - TYPE_UINT64 = 4, - TYPE_INT32 = 5, - TYPE_FIXED64 = 6, - TYPE_FIXED32 = 7, - TYPE_BOOL = 8, - TYPE_STRING = 9, - TYPE_GROUP = 10, - TYPE_MESSAGE = 11, - TYPE_BYTES = 12, - TYPE_UINT32 = 13, - TYPE_ENUM = 14, - TYPE_SFIXED32 = 15, - TYPE_SFIXED64 = 16, - TYPE_SINT32 = 17, - TYPE_SINT64 = 18, - MAX_FIELD_TYPE = 18, - }; - - // Lite alternative to FieldDescriptor::CppType. Must be kept in sync. - enum CppType { - CPPTYPE_INT32 = 1, - CPPTYPE_INT64 = 2, - CPPTYPE_UINT32 = 3, - CPPTYPE_UINT64 = 4, - CPPTYPE_DOUBLE = 5, - CPPTYPE_FLOAT = 6, - CPPTYPE_BOOL = 7, - CPPTYPE_ENUM = 8, - CPPTYPE_STRING = 9, - CPPTYPE_MESSAGE = 10, - MAX_CPPTYPE = 10, - }; - - // Helper method to get the CppType for a particular Type. - static CppType FieldTypeToCppType(FieldType type); - - // Given a FieldSescriptor::Type return its WireType - static inline WireFormatLite::WireType WireTypeForFieldType( - WireFormatLite::FieldType type) { - return kWireTypeForFieldType[type]; - } - - // Number of bits in a tag which identify the wire type. - static const int kTagTypeBits = 3; - // Mask for those bits. - static const uint32 kTagTypeMask = (1 << kTagTypeBits) - 1; - - // Helper functions for encoding and decoding tags. (Inlined below and in - // _inl.h) - // - // This is different from MakeTag(field->number(), field->type()) in the case - // of packed repeated fields. - static uint32 MakeTag(int field_number, WireType type); - static WireType GetTagWireType(uint32 tag); - static int GetTagFieldNumber(uint32 tag); - - // Compute the byte size of a tag. For groups, this includes both the start - // and end tags. - static inline int TagSize(int field_number, WireFormatLite::FieldType type); - - // Skips a field value with the given tag. The input should start - // positioned immediately after the tag. Skipped values are simply discarded, - // not recorded anywhere. See WireFormat::SkipField() for a version that - // records to an UnknownFieldSet. - static bool SkipField(io::CodedInputStream* input, uint32 tag); - - // Reads and ignores a message from the input. Skipped values are simply - // discarded, not recorded anywhere. See WireFormat::SkipMessage() for a - // version that records to an UnknownFieldSet. - static bool SkipMessage(io::CodedInputStream* input); - -// This macro does the same thing as WireFormatLite::MakeTag(), but the -// result is usable as a compile-time constant, which makes it usable -// as a switch case or a template input. WireFormatLite::MakeTag() is more -// type-safe, though, so prefer it if possible. -#define GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(FIELD_NUMBER, TYPE) \ - static_cast( \ - ((FIELD_NUMBER) << ::google::protobuf::internal::WireFormatLite::kTagTypeBits) \ - | (TYPE)) - - // These are the tags for the old MessageSet format, which was defined as: - // message MessageSet { - // repeated group Item = 1 { - // required int32 type_id = 2; - // required string message = 3; - // } - // } - static const int kMessageSetItemNumber = 1; - static const int kMessageSetTypeIdNumber = 2; - static const int kMessageSetMessageNumber = 3; - static const int kMessageSetItemStartTag = - GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetItemNumber, - WireFormatLite::WIRETYPE_START_GROUP); - static const int kMessageSetItemEndTag = - GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetItemNumber, - WireFormatLite::WIRETYPE_END_GROUP); - static const int kMessageSetTypeIdTag = - GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetTypeIdNumber, - WireFormatLite::WIRETYPE_VARINT); - static const int kMessageSetMessageTag = - GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(kMessageSetMessageNumber, - WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - - // Byte size of all tags of a MessageSet::Item combined. - static const int kMessageSetItemTagsSize; - - // Helper functions for converting between floats/doubles and IEEE-754 - // uint32s/uint64s so that they can be written. (Assumes your platform - // uses IEEE-754 floats.) - static uint32 EncodeFloat(float value); - static float DecodeFloat(uint32 value); - static uint64 EncodeDouble(double value); - static double DecodeDouble(uint64 value); - - // Helper functions for mapping signed integers to unsigned integers in - // such a way that numbers with small magnitudes will encode to smaller - // varints. If you simply static_cast a negative number to an unsigned - // number and varint-encode it, it will always take 10 bytes, defeating - // the purpose of varint. So, for the "sint32" and "sint64" field types, - // we ZigZag-encode the values. - static uint32 ZigZagEncode32(int32 n); - static int32 ZigZagDecode32(uint32 n); - static uint64 ZigZagEncode64(int64 n); - static int64 ZigZagDecode64(uint64 n); - - // ================================================================= - // Methods for reading/writing individual field. The implementations - // of these methods are defined in wire_format_lite_inl.h; you must #include - // that file to use these. - -// Avoid ugly line wrapping -#define input io::CodedInputStream* input -#define output io::CodedOutputStream* output -#define field_number int field_number -#define INL GOOGLE_ATTRIBUTE_ALWAYS_INLINE - - // Read fields, not including tags. The assumption is that you already - // read the tag to determine what field to read. - - // For primitive fields, we just use a templatized routine parameterized by - // the represented type and the FieldType. These are specialized with the - // appropriate definition for each declared type. - template - static inline bool ReadPrimitive(input, CType* value) INL; - - // Reads repeated primitive values, with optimizations for repeats. - // tag_size and tag should both be compile-time constants provided by the - // protocol compiler. - template - static inline bool ReadRepeatedPrimitive(int tag_size, - uint32 tag, - input, - RepeatedField* value) INL; - - // Identical to ReadRepeatedPrimitive, except will not inline the - // implementation. - template - static bool ReadRepeatedPrimitiveNoInline(int tag_size, - uint32 tag, - input, - RepeatedField* value); - - // Reads a primitive value directly from the provided buffer. It returns a - // pointer past the segment of data that was read. - // - // This is only implemented for the types with fixed wire size, e.g. - // float, double, and the (s)fixed* types. - template - static inline const uint8* ReadPrimitiveFromArray(const uint8* buffer, - CType* value) INL; - - // Reads a primitive packed field. - // - // This is only implemented for packable types. - template - static inline bool ReadPackedPrimitive(input, - RepeatedField* value) INL; - - // Identical to ReadPackedPrimitive, except will not inline the - // implementation. - template - static bool ReadPackedPrimitiveNoInline(input, RepeatedField* value); - - // Read a packed enum field. Values for which is_valid() returns false are - // dropped. - static bool ReadPackedEnumNoInline(input, - bool (*is_valid)(int), - RepeatedField* value); - - static bool ReadString(input, string* value); - static bool ReadBytes (input, string* value); - - static inline bool ReadGroup (field_number, input, MessageLite* value); - static inline bool ReadMessage(input, MessageLite* value); - - // Like above, but de-virtualize the call to MergePartialFromCodedStream(). - // The pointer must point at an instance of MessageType, *not* a subclass (or - // the subclass must not override MergePartialFromCodedStream()). - template - static inline bool ReadGroupNoVirtual(field_number, input, - MessageType* value); - template - static inline bool ReadMessageNoVirtual(input, MessageType* value); - - // Write a tag. The Write*() functions typically include the tag, so - // normally there's no need to call this unless using the Write*NoTag() - // variants. - static inline void WriteTag(field_number, WireType type, output) INL; - - // Write fields, without tags. - static inline void WriteInt32NoTag (int32 value, output) INL; - static inline void WriteInt64NoTag (int64 value, output) INL; - static inline void WriteUInt32NoTag (uint32 value, output) INL; - static inline void WriteUInt64NoTag (uint64 value, output) INL; - static inline void WriteSInt32NoTag (int32 value, output) INL; - static inline void WriteSInt64NoTag (int64 value, output) INL; - static inline void WriteFixed32NoTag (uint32 value, output) INL; - static inline void WriteFixed64NoTag (uint64 value, output) INL; - static inline void WriteSFixed32NoTag(int32 value, output) INL; - static inline void WriteSFixed64NoTag(int64 value, output) INL; - static inline void WriteFloatNoTag (float value, output) INL; - static inline void WriteDoubleNoTag (double value, output) INL; - static inline void WriteBoolNoTag (bool value, output) INL; - static inline void WriteEnumNoTag (int value, output) INL; - - // Write fields, including tags. - static void WriteInt32 (field_number, int32 value, output); - static void WriteInt64 (field_number, int64 value, output); - static void WriteUInt32 (field_number, uint32 value, output); - static void WriteUInt64 (field_number, uint64 value, output); - static void WriteSInt32 (field_number, int32 value, output); - static void WriteSInt64 (field_number, int64 value, output); - static void WriteFixed32 (field_number, uint32 value, output); - static void WriteFixed64 (field_number, uint64 value, output); - static void WriteSFixed32(field_number, int32 value, output); - static void WriteSFixed64(field_number, int64 value, output); - static void WriteFloat (field_number, float value, output); - static void WriteDouble (field_number, double value, output); - static void WriteBool (field_number, bool value, output); - static void WriteEnum (field_number, int value, output); - - static void WriteString(field_number, const string& value, output); - static void WriteBytes (field_number, const string& value, output); - - static void WriteGroup( - field_number, const MessageLite& value, output); - static void WriteMessage( - field_number, const MessageLite& value, output); - // Like above, but these will check if the output stream has enough - // space to write directly to a flat array. - static void WriteGroupMaybeToArray( - field_number, const MessageLite& value, output); - static void WriteMessageMaybeToArray( - field_number, const MessageLite& value, output); - - // Like above, but de-virtualize the call to SerializeWithCachedSizes(). The - // pointer must point at an instance of MessageType, *not* a subclass (or - // the subclass must not override SerializeWithCachedSizes()). - template - static inline void WriteGroupNoVirtual( - field_number, const MessageType& value, output); - template - static inline void WriteMessageNoVirtual( - field_number, const MessageType& value, output); - -#undef output -#define output uint8* target - - // Like above, but use only *ToArray methods of CodedOutputStream. - static inline uint8* WriteTagToArray(field_number, WireType type, output) INL; - - // Write fields, without tags. - static inline uint8* WriteInt32NoTagToArray (int32 value, output) INL; - static inline uint8* WriteInt64NoTagToArray (int64 value, output) INL; - static inline uint8* WriteUInt32NoTagToArray (uint32 value, output) INL; - static inline uint8* WriteUInt64NoTagToArray (uint64 value, output) INL; - static inline uint8* WriteSInt32NoTagToArray (int32 value, output) INL; - static inline uint8* WriteSInt64NoTagToArray (int64 value, output) INL; - static inline uint8* WriteFixed32NoTagToArray (uint32 value, output) INL; - static inline uint8* WriteFixed64NoTagToArray (uint64 value, output) INL; - static inline uint8* WriteSFixed32NoTagToArray(int32 value, output) INL; - static inline uint8* WriteSFixed64NoTagToArray(int64 value, output) INL; - static inline uint8* WriteFloatNoTagToArray (float value, output) INL; - static inline uint8* WriteDoubleNoTagToArray (double value, output) INL; - static inline uint8* WriteBoolNoTagToArray (bool value, output) INL; - static inline uint8* WriteEnumNoTagToArray (int value, output) INL; - - // Write fields, including tags. - static inline uint8* WriteInt32ToArray( - field_number, int32 value, output) INL; - static inline uint8* WriteInt64ToArray( - field_number, int64 value, output) INL; - static inline uint8* WriteUInt32ToArray( - field_number, uint32 value, output) INL; - static inline uint8* WriteUInt64ToArray( - field_number, uint64 value, output) INL; - static inline uint8* WriteSInt32ToArray( - field_number, int32 value, output) INL; - static inline uint8* WriteSInt64ToArray( - field_number, int64 value, output) INL; - static inline uint8* WriteFixed32ToArray( - field_number, uint32 value, output) INL; - static inline uint8* WriteFixed64ToArray( - field_number, uint64 value, output) INL; - static inline uint8* WriteSFixed32ToArray( - field_number, int32 value, output) INL; - static inline uint8* WriteSFixed64ToArray( - field_number, int64 value, output) INL; - static inline uint8* WriteFloatToArray( - field_number, float value, output) INL; - static inline uint8* WriteDoubleToArray( - field_number, double value, output) INL; - static inline uint8* WriteBoolToArray( - field_number, bool value, output) INL; - static inline uint8* WriteEnumToArray( - field_number, int value, output) INL; - - static inline uint8* WriteStringToArray( - field_number, const string& value, output) INL; - static inline uint8* WriteBytesToArray( - field_number, const string& value, output) INL; - - static inline uint8* WriteGroupToArray( - field_number, const MessageLite& value, output) INL; - static inline uint8* WriteMessageToArray( - field_number, const MessageLite& value, output) INL; - - // Like above, but de-virtualize the call to SerializeWithCachedSizes(). The - // pointer must point at an instance of MessageType, *not* a subclass (or - // the subclass must not override SerializeWithCachedSizes()). - template - static inline uint8* WriteGroupNoVirtualToArray( - field_number, const MessageType& value, output) INL; - template - static inline uint8* WriteMessageNoVirtualToArray( - field_number, const MessageType& value, output) INL; - -#undef output -#undef input -#undef INL - -#undef field_number - - // Compute the byte size of a field. The XxSize() functions do NOT include - // the tag, so you must also call TagSize(). (This is because, for repeated - // fields, you should only call TagSize() once and multiply it by the element - // count, but you may have to call XxSize() for each individual element.) - static inline int Int32Size ( int32 value); - static inline int Int64Size ( int64 value); - static inline int UInt32Size (uint32 value); - static inline int UInt64Size (uint64 value); - static inline int SInt32Size ( int32 value); - static inline int SInt64Size ( int64 value); - static inline int EnumSize ( int value); - - // These types always have the same size. - static const int kFixed32Size = 4; - static const int kFixed64Size = 8; - static const int kSFixed32Size = 4; - static const int kSFixed64Size = 8; - static const int kFloatSize = 4; - static const int kDoubleSize = 8; - static const int kBoolSize = 1; - - static inline int StringSize(const string& value); - static inline int BytesSize (const string& value); - - static inline int GroupSize (const MessageLite& value); - static inline int MessageSize(const MessageLite& value); - - // Like above, but de-virtualize the call to ByteSize(). The - // pointer must point at an instance of MessageType, *not* a subclass (or - // the subclass must not override ByteSize()). - template - static inline int GroupSizeNoVirtual (const MessageType& value); - template - static inline int MessageSizeNoVirtual(const MessageType& value); - - private: - // A helper method for the repeated primitive reader. This method has - // optimizations for primitive types that have fixed size on the wire, and - // can be read using potentially faster paths. - template - static inline bool ReadRepeatedFixedSizePrimitive( - int tag_size, - uint32 tag, - google::protobuf::io::CodedInputStream* input, - RepeatedField* value) GOOGLE_ATTRIBUTE_ALWAYS_INLINE; - - static const CppType kFieldTypeToCppTypeMap[]; - static const WireFormatLite::WireType kWireTypeForFieldType[]; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(WireFormatLite); -}; - -// A class which deals with unknown values. The default implementation just -// discards them. WireFormat defines a subclass which writes to an -// UnknownFieldSet. This class is used by ExtensionSet::ParseField(), since -// ExtensionSet is part of the lite library but UnknownFieldSet is not. -class LIBPROTOBUF_EXPORT FieldSkipper { - public: - FieldSkipper() {} - virtual ~FieldSkipper() {} - - // Skip a field whose tag has already been consumed. - virtual bool SkipField(io::CodedInputStream* input, uint32 tag); - - // Skip an entire message or group, up to an end-group tag (which is consumed) - // or end-of-stream. - virtual bool SkipMessage(io::CodedInputStream* input); - - // Deal with an already-parsed unrecognized enum value. The default - // implementation does nothing, but the UnknownFieldSet-based implementation - // saves it as an unknown varint. - virtual void SkipUnknownEnum(int field_number, int value); -}; - -// inline methods ==================================================== - -inline WireFormatLite::CppType -WireFormatLite::FieldTypeToCppType(FieldType type) { - return kFieldTypeToCppTypeMap[type]; -} - -inline uint32 WireFormatLite::MakeTag(int field_number, WireType type) { - return GOOGLE_PROTOBUF_WIRE_FORMAT_MAKE_TAG(field_number, type); -} - -inline WireFormatLite::WireType WireFormatLite::GetTagWireType(uint32 tag) { - return static_cast(tag & kTagTypeMask); -} - -inline int WireFormatLite::GetTagFieldNumber(uint32 tag) { - return static_cast(tag >> kTagTypeBits); -} - -inline int WireFormatLite::TagSize(int field_number, - WireFormatLite::FieldType type) { - int result = io::CodedOutputStream::VarintSize32( - field_number << kTagTypeBits); - if (type == TYPE_GROUP) { - // Groups have both a start and an end tag. - return result * 2; - } else { - return result; - } -} - -inline uint32 WireFormatLite::EncodeFloat(float value) { - union {float f; uint32 i;}; - f = value; - return i; -} - -inline float WireFormatLite::DecodeFloat(uint32 value) { - union {float f; uint32 i;}; - i = value; - return f; -} - -inline uint64 WireFormatLite::EncodeDouble(double value) { - union {double f; uint64 i;}; - f = value; - return i; -} - -inline double WireFormatLite::DecodeDouble(uint64 value) { - union {double f; uint64 i;}; - i = value; - return f; -} - -// ZigZag Transform: Encodes signed integers so that they can be -// effectively used with varint encoding. -// -// varint operates on unsigned integers, encoding smaller numbers into -// fewer bytes. If you try to use it on a signed integer, it will treat -// this number as a very large unsigned integer, which means that even -// small signed numbers like -1 will take the maximum number of bytes -// (10) to encode. ZigZagEncode() maps signed integers to unsigned -// in such a way that those with a small absolute value will have smaller -// encoded values, making them appropriate for encoding using varint. -// -// int32 -> uint32 -// ------------------------- -// 0 -> 0 -// -1 -> 1 -// 1 -> 2 -// -2 -> 3 -// ... -> ... -// 2147483647 -> 4294967294 -// -2147483648 -> 4294967295 -// -// >> encode >> -// << decode << - -inline uint32 WireFormatLite::ZigZagEncode32(int32 n) { - // Note: the right-shift must be arithmetic - return (n << 1) ^ (n >> 31); -} - -inline int32 WireFormatLite::ZigZagDecode32(uint32 n) { - return (n >> 1) ^ -static_cast(n & 1); -} - -inline uint64 WireFormatLite::ZigZagEncode64(int64 n) { - // Note: the right-shift must be arithmetic - return (n << 1) ^ (n >> 63); -} - -inline int64 WireFormatLite::ZigZagDecode64(uint64 n) { - return (n >> 1) ^ -static_cast(n & 1); -} - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_H__ diff --git a/Resources/NetHook/google/protobuf/wire_format_lite_inl.h b/Resources/NetHook/google/protobuf/wire_format_lite_inl.h deleted file mode 100644 index d7b2c302..00000000 --- a/Resources/NetHook/google/protobuf/wire_format_lite_inl.h +++ /dev/null @@ -1,747 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// wink@google.com (Wink Saville) (refactored from wire_format.h) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#ifndef GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_INL_H__ -#define GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_INL_H__ - -#include -#include -#include -#include -#include -#include -#include - - -namespace google { -namespace protobuf { -namespace internal { - -// Implementation details of ReadPrimitive. - -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int32* value) { - uint32 temp; - if (!input->ReadVarint32(&temp)) return false; - *value = static_cast(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int64* value) { - uint64 temp; - if (!input->ReadVarint64(&temp)) return false; - *value = static_cast(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - uint32* value) { - return input->ReadVarint32(value); -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - uint64* value) { - return input->ReadVarint64(value); -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int32* value) { - uint32 temp; - if (!input->ReadVarint32(&temp)) return false; - *value = ZigZagDecode32(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int64* value) { - uint64 temp; - if (!input->ReadVarint64(&temp)) return false; - *value = ZigZagDecode64(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - uint32* value) { - return input->ReadLittleEndian32(value); -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - uint64* value) { - return input->ReadLittleEndian64(value); -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int32* value) { - uint32 temp; - if (!input->ReadLittleEndian32(&temp)) return false; - *value = static_cast(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int64* value) { - uint64 temp; - if (!input->ReadLittleEndian64(&temp)) return false; - *value = static_cast(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - float* value) { - uint32 temp; - if (!input->ReadLittleEndian32(&temp)) return false; - *value = DecodeFloat(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - double* value) { - uint64 temp; - if (!input->ReadLittleEndian64(&temp)) return false; - *value = DecodeDouble(temp); - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - bool* value) { - uint32 temp; - if (!input->ReadVarint32(&temp)) return false; - *value = temp != 0; - return true; -} -template <> -inline bool WireFormatLite::ReadPrimitive( - io::CodedInputStream* input, - int* value) { - uint32 temp; - if (!input->ReadVarint32(&temp)) return false; - *value = static_cast(temp); - return true; -} - -template <> -inline const uint8* WireFormatLite::ReadPrimitiveFromArray< - uint32, WireFormatLite::TYPE_FIXED32>( - const uint8* buffer, - uint32* value) { - return io::CodedInputStream::ReadLittleEndian32FromArray(buffer, value); -} -template <> -inline const uint8* WireFormatLite::ReadPrimitiveFromArray< - uint64, WireFormatLite::TYPE_FIXED64>( - const uint8* buffer, - uint64* value) { - return io::CodedInputStream::ReadLittleEndian64FromArray(buffer, value); -} -template <> -inline const uint8* WireFormatLite::ReadPrimitiveFromArray< - int32, WireFormatLite::TYPE_SFIXED32>( - const uint8* buffer, - int32* value) { - uint32 temp; - buffer = io::CodedInputStream::ReadLittleEndian32FromArray(buffer, &temp); - *value = static_cast(temp); - return buffer; -} -template <> -inline const uint8* WireFormatLite::ReadPrimitiveFromArray< - int64, WireFormatLite::TYPE_SFIXED64>( - const uint8* buffer, - int64* value) { - uint64 temp; - buffer = io::CodedInputStream::ReadLittleEndian64FromArray(buffer, &temp); - *value = static_cast(temp); - return buffer; -} -template <> -inline const uint8* WireFormatLite::ReadPrimitiveFromArray< - float, WireFormatLite::TYPE_FLOAT>( - const uint8* buffer, - float* value) { - uint32 temp; - buffer = io::CodedInputStream::ReadLittleEndian32FromArray(buffer, &temp); - *value = DecodeFloat(temp); - return buffer; -} -template <> -inline const uint8* WireFormatLite::ReadPrimitiveFromArray< - double, WireFormatLite::TYPE_DOUBLE>( - const uint8* buffer, - double* value) { - uint64 temp; - buffer = io::CodedInputStream::ReadLittleEndian64FromArray(buffer, &temp); - *value = DecodeDouble(temp); - return buffer; -} - -template -inline bool WireFormatLite::ReadRepeatedPrimitive(int tag_size, - uint32 tag, - io::CodedInputStream* input, - RepeatedField* values) { - CType value; - if (!ReadPrimitive(input, &value)) return false; - values->Add(value); - int elements_already_reserved = values->Capacity() - values->size(); - while (elements_already_reserved > 0 && input->ExpectTag(tag)) { - if (!ReadPrimitive(input, &value)) return false; - values->AddAlreadyReserved(value); - elements_already_reserved--; - } - return true; -} - -template -inline bool WireFormatLite::ReadRepeatedFixedSizePrimitive( - int tag_size, - uint32 tag, - io::CodedInputStream* input, - RepeatedField* values) { - GOOGLE_DCHECK_EQ(UInt32Size(tag), tag_size); - CType value; - if (!ReadPrimitive(input, &value)) - return false; - values->Add(value); - - // For fixed size values, repeated values can be read more quickly by - // reading directly from a raw array. - // - // We can get a tight loop by only reading as many elements as can be - // added to the RepeatedField without having to do any resizing. Additionally, - // we only try to read as many elements as are available from the current - // buffer space. Doing so avoids having to perform boundary checks when - // reading the value: the maximum number of elements that can be read is - // known outside of the loop. - const void* void_pointer; - int size; - input->GetDirectBufferPointerInline(&void_pointer, &size); - if (size > 0) { - const uint8* buffer = reinterpret_cast(void_pointer); - // The number of bytes each type occupies on the wire. - const int per_value_size = tag_size + sizeof(value); - - int elements_available = min(values->Capacity() - values->size(), - size / per_value_size); - int num_read = 0; - while (num_read < elements_available && - (buffer = io::CodedInputStream::ExpectTagFromArray( - buffer, tag)) != NULL) { - buffer = ReadPrimitiveFromArray(buffer, &value); - values->AddAlreadyReserved(value); - ++num_read; - } - const int read_bytes = num_read * per_value_size; - if (read_bytes > 0) { - input->Skip(read_bytes); - } - } - return true; -} - -// Specializations of ReadRepeatedPrimitive for the fixed size types, which use -// the optimized code path. -#define READ_REPEATED_FIXED_SIZE_PRIMITIVE(CPPTYPE, DECLARED_TYPE) \ -template <> \ -inline bool WireFormatLite::ReadRepeatedPrimitive< \ - CPPTYPE, WireFormatLite::DECLARED_TYPE>( \ - int tag_size, \ - uint32 tag, \ - io::CodedInputStream* input, \ - RepeatedField* values) { \ - return ReadRepeatedFixedSizePrimitive< \ - CPPTYPE, WireFormatLite::DECLARED_TYPE>( \ - tag_size, tag, input, values); \ -} - -READ_REPEATED_FIXED_SIZE_PRIMITIVE(uint32, TYPE_FIXED32); -READ_REPEATED_FIXED_SIZE_PRIMITIVE(uint64, TYPE_FIXED64); -READ_REPEATED_FIXED_SIZE_PRIMITIVE(int32, TYPE_SFIXED32); -READ_REPEATED_FIXED_SIZE_PRIMITIVE(int64, TYPE_SFIXED64); -READ_REPEATED_FIXED_SIZE_PRIMITIVE(float, TYPE_FLOAT); -READ_REPEATED_FIXED_SIZE_PRIMITIVE(double, TYPE_DOUBLE); - -#undef READ_REPEATED_FIXED_SIZE_PRIMITIVE - -template -bool WireFormatLite::ReadRepeatedPrimitiveNoInline( - int tag_size, - uint32 tag, - io::CodedInputStream* input, - RepeatedField* value) { - return ReadRepeatedPrimitive( - tag_size, tag, input, value); -} - -template -inline bool WireFormatLite::ReadPackedPrimitive(io::CodedInputStream* input, - RepeatedField* values) { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - io::CodedInputStream::Limit limit = input->PushLimit(length); - while (input->BytesUntilLimit() > 0) { - CType value; - if (!ReadPrimitive(input, &value)) return false; - values->Add(value); - } - input->PopLimit(limit); - return true; -} - -template -bool WireFormatLite::ReadPackedPrimitiveNoInline(io::CodedInputStream* input, - RepeatedField* values) { - return ReadPackedPrimitive(input, values); -} - - -inline bool WireFormatLite::ReadGroup(int field_number, - io::CodedInputStream* input, - MessageLite* value) { - if (!input->IncrementRecursionDepth()) return false; - if (!value->MergePartialFromCodedStream(input)) return false; - input->DecrementRecursionDepth(); - // Make sure the last thing read was an end tag for this group. - if (!input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP))) { - return false; - } - return true; -} -inline bool WireFormatLite::ReadMessage(io::CodedInputStream* input, - MessageLite* value) { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->IncrementRecursionDepth()) return false; - io::CodedInputStream::Limit limit = input->PushLimit(length); - if (!value->MergePartialFromCodedStream(input)) return false; - // Make sure that parsing stopped when the limit was hit, not at an endgroup - // tag. - if (!input->ConsumedEntireMessage()) return false; - input->PopLimit(limit); - input->DecrementRecursionDepth(); - return true; -} - -template -inline bool WireFormatLite::ReadGroupNoVirtual(int field_number, - io::CodedInputStream* input, - MessageType* value) { - if (!input->IncrementRecursionDepth()) return false; - if (!value->MessageType::MergePartialFromCodedStream(input)) return false; - input->DecrementRecursionDepth(); - // Make sure the last thing read was an end tag for this group. - if (!input->LastTagWas(MakeTag(field_number, WIRETYPE_END_GROUP))) { - return false; - } - return true; -} -template -inline bool WireFormatLite::ReadMessageNoVirtual(io::CodedInputStream* input, - MessageType* value) { - uint32 length; - if (!input->ReadVarint32(&length)) return false; - if (!input->IncrementRecursionDepth()) return false; - io::CodedInputStream::Limit limit = input->PushLimit(length); - if (!value->MessageType::MergePartialFromCodedStream(input)) return false; - // Make sure that parsing stopped when the limit was hit, not at an endgroup - // tag. - if (!input->ConsumedEntireMessage()) return false; - input->PopLimit(limit); - input->DecrementRecursionDepth(); - return true; -} - -// =================================================================== - -inline void WireFormatLite::WriteTag(int field_number, WireType type, - io::CodedOutputStream* output) { - output->WriteTag(MakeTag(field_number, type)); -} - -inline void WireFormatLite::WriteInt32NoTag(int32 value, - io::CodedOutputStream* output) { - output->WriteVarint32SignExtended(value); -} -inline void WireFormatLite::WriteInt64NoTag(int64 value, - io::CodedOutputStream* output) { - output->WriteVarint64(static_cast(value)); -} -inline void WireFormatLite::WriteUInt32NoTag(uint32 value, - io::CodedOutputStream* output) { - output->WriteVarint32(value); -} -inline void WireFormatLite::WriteUInt64NoTag(uint64 value, - io::CodedOutputStream* output) { - output->WriteVarint64(value); -} -inline void WireFormatLite::WriteSInt32NoTag(int32 value, - io::CodedOutputStream* output) { - output->WriteVarint32(ZigZagEncode32(value)); -} -inline void WireFormatLite::WriteSInt64NoTag(int64 value, - io::CodedOutputStream* output) { - output->WriteVarint64(ZigZagEncode64(value)); -} -inline void WireFormatLite::WriteFixed32NoTag(uint32 value, - io::CodedOutputStream* output) { - output->WriteLittleEndian32(value); -} -inline void WireFormatLite::WriteFixed64NoTag(uint64 value, - io::CodedOutputStream* output) { - output->WriteLittleEndian64(value); -} -inline void WireFormatLite::WriteSFixed32NoTag(int32 value, - io::CodedOutputStream* output) { - output->WriteLittleEndian32(static_cast(value)); -} -inline void WireFormatLite::WriteSFixed64NoTag(int64 value, - io::CodedOutputStream* output) { - output->WriteLittleEndian64(static_cast(value)); -} -inline void WireFormatLite::WriteFloatNoTag(float value, - io::CodedOutputStream* output) { - output->WriteLittleEndian32(EncodeFloat(value)); -} -inline void WireFormatLite::WriteDoubleNoTag(double value, - io::CodedOutputStream* output) { - output->WriteLittleEndian64(EncodeDouble(value)); -} -inline void WireFormatLite::WriteBoolNoTag(bool value, - io::CodedOutputStream* output) { - output->WriteVarint32(value ? 1 : 0); -} -inline void WireFormatLite::WriteEnumNoTag(int value, - io::CodedOutputStream* output) { - output->WriteVarint32SignExtended(value); -} - -template -inline void WireFormatLite::WriteGroupNoVirtual(int field_number, - const MessageType& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_START_GROUP, output); - value.MessageType::SerializeWithCachedSizes(output); - WriteTag(field_number, WIRETYPE_END_GROUP, output); -} -template -inline void WireFormatLite::WriteMessageNoVirtual(int field_number, - const MessageType& value, - io::CodedOutputStream* output) { - WriteTag(field_number, WIRETYPE_LENGTH_DELIMITED, output); - output->WriteVarint32(value.MessageType::GetCachedSize()); - value.MessageType::SerializeWithCachedSizes(output); -} - -// =================================================================== - -inline uint8* WireFormatLite::WriteTagToArray(int field_number, - WireType type, - uint8* target) { - return io::CodedOutputStream::WriteTagToArray(MakeTag(field_number, type), - target); -} - -inline uint8* WireFormatLite::WriteInt32NoTagToArray(int32 value, - uint8* target) { - return io::CodedOutputStream::WriteVarint32SignExtendedToArray(value, target); -} -inline uint8* WireFormatLite::WriteInt64NoTagToArray(int64 value, - uint8* target) { - return io::CodedOutputStream::WriteVarint64ToArray( - static_cast(value), target); -} -inline uint8* WireFormatLite::WriteUInt32NoTagToArray(uint32 value, - uint8* target) { - return io::CodedOutputStream::WriteVarint32ToArray(value, target); -} -inline uint8* WireFormatLite::WriteUInt64NoTagToArray(uint64 value, - uint8* target) { - return io::CodedOutputStream::WriteVarint64ToArray(value, target); -} -inline uint8* WireFormatLite::WriteSInt32NoTagToArray(int32 value, - uint8* target) { - return io::CodedOutputStream::WriteVarint32ToArray(ZigZagEncode32(value), - target); -} -inline uint8* WireFormatLite::WriteSInt64NoTagToArray(int64 value, - uint8* target) { - return io::CodedOutputStream::WriteVarint64ToArray(ZigZagEncode64(value), - target); -} -inline uint8* WireFormatLite::WriteFixed32NoTagToArray(uint32 value, - uint8* target) { - return io::CodedOutputStream::WriteLittleEndian32ToArray(value, target); -} -inline uint8* WireFormatLite::WriteFixed64NoTagToArray(uint64 value, - uint8* target) { - return io::CodedOutputStream::WriteLittleEndian64ToArray(value, target); -} -inline uint8* WireFormatLite::WriteSFixed32NoTagToArray(int32 value, - uint8* target) { - return io::CodedOutputStream::WriteLittleEndian32ToArray( - static_cast(value), target); -} -inline uint8* WireFormatLite::WriteSFixed64NoTagToArray(int64 value, - uint8* target) { - return io::CodedOutputStream::WriteLittleEndian64ToArray( - static_cast(value), target); -} -inline uint8* WireFormatLite::WriteFloatNoTagToArray(float value, - uint8* target) { - return io::CodedOutputStream::WriteLittleEndian32ToArray(EncodeFloat(value), - target); -} -inline uint8* WireFormatLite::WriteDoubleNoTagToArray(double value, - uint8* target) { - return io::CodedOutputStream::WriteLittleEndian64ToArray(EncodeDouble(value), - target); -} -inline uint8* WireFormatLite::WriteBoolNoTagToArray(bool value, - uint8* target) { - return io::CodedOutputStream::WriteVarint32ToArray(value ? 1 : 0, target); -} -inline uint8* WireFormatLite::WriteEnumNoTagToArray(int value, - uint8* target) { - return io::CodedOutputStream::WriteVarint32SignExtendedToArray(value, target); -} - -inline uint8* WireFormatLite::WriteInt32ToArray(int field_number, - int32 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteInt32NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteInt64ToArray(int field_number, - int64 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteInt64NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteUInt32ToArray(int field_number, - uint32 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteUInt32NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteUInt64ToArray(int field_number, - uint64 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteUInt64NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteSInt32ToArray(int field_number, - int32 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteSInt32NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteSInt64ToArray(int field_number, - int64 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteSInt64NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteFixed32ToArray(int field_number, - uint32 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_FIXED32, target); - return WriteFixed32NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteFixed64ToArray(int field_number, - uint64 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_FIXED64, target); - return WriteFixed64NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteSFixed32ToArray(int field_number, - int32 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_FIXED32, target); - return WriteSFixed32NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteSFixed64ToArray(int field_number, - int64 value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_FIXED64, target); - return WriteSFixed64NoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteFloatToArray(int field_number, - float value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_FIXED32, target); - return WriteFloatNoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteDoubleToArray(int field_number, - double value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_FIXED64, target); - return WriteDoubleNoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteBoolToArray(int field_number, - bool value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteBoolNoTagToArray(value, target); -} -inline uint8* WireFormatLite::WriteEnumToArray(int field_number, - int value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_VARINT, target); - return WriteEnumNoTagToArray(value, target); -} - -inline uint8* WireFormatLite::WriteStringToArray(int field_number, - const string& value, - uint8* target) { - // String is for UTF-8 text only - // WARNING: In wire_format.cc, both strings and bytes are handled by - // WriteString() to avoid code duplication. If the implementations become - // different, you will need to update that usage. - target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target); - target = io::CodedOutputStream::WriteVarint32ToArray(value.size(), target); - return io::CodedOutputStream::WriteStringToArray(value, target); -} -inline uint8* WireFormatLite::WriteBytesToArray(int field_number, - const string& value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target); - target = io::CodedOutputStream::WriteVarint32ToArray(value.size(), target); - return io::CodedOutputStream::WriteStringToArray(value, target); -} - - -inline uint8* WireFormatLite::WriteGroupToArray(int field_number, - const MessageLite& value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_START_GROUP, target); - target = value.SerializeWithCachedSizesToArray(target); - return WriteTagToArray(field_number, WIRETYPE_END_GROUP, target); -} -inline uint8* WireFormatLite::WriteMessageToArray(int field_number, - const MessageLite& value, - uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target); - target = io::CodedOutputStream::WriteVarint32ToArray( - value.GetCachedSize(), target); - return value.SerializeWithCachedSizesToArray(target); -} - -template -inline uint8* WireFormatLite::WriteGroupNoVirtualToArray( - int field_number, const MessageType& value, uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_START_GROUP, target); - target = value.MessageType::SerializeWithCachedSizesToArray(target); - return WriteTagToArray(field_number, WIRETYPE_END_GROUP, target); -} -template -inline uint8* WireFormatLite::WriteMessageNoVirtualToArray( - int field_number, const MessageType& value, uint8* target) { - target = WriteTagToArray(field_number, WIRETYPE_LENGTH_DELIMITED, target); - target = io::CodedOutputStream::WriteVarint32ToArray( - value.MessageType::GetCachedSize(), target); - return value.MessageType::SerializeWithCachedSizesToArray(target); -} - -// =================================================================== - -inline int WireFormatLite::Int32Size(int32 value) { - return io::CodedOutputStream::VarintSize32SignExtended(value); -} -inline int WireFormatLite::Int64Size(int64 value) { - return io::CodedOutputStream::VarintSize64(static_cast(value)); -} -inline int WireFormatLite::UInt32Size(uint32 value) { - return io::CodedOutputStream::VarintSize32(value); -} -inline int WireFormatLite::UInt64Size(uint64 value) { - return io::CodedOutputStream::VarintSize64(value); -} -inline int WireFormatLite::SInt32Size(int32 value) { - return io::CodedOutputStream::VarintSize32(ZigZagEncode32(value)); -} -inline int WireFormatLite::SInt64Size(int64 value) { - return io::CodedOutputStream::VarintSize64(ZigZagEncode64(value)); -} -inline int WireFormatLite::EnumSize(int value) { - return io::CodedOutputStream::VarintSize32SignExtended(value); -} - -inline int WireFormatLite::StringSize(const string& value) { - return io::CodedOutputStream::VarintSize32(value.size()) + - value.size(); -} -inline int WireFormatLite::BytesSize(const string& value) { - return io::CodedOutputStream::VarintSize32(value.size()) + - value.size(); -} - - -inline int WireFormatLite::GroupSize(const MessageLite& value) { - return value.ByteSize(); -} -inline int WireFormatLite::MessageSize(const MessageLite& value) { - int size = value.ByteSize(); - return io::CodedOutputStream::VarintSize32(size) + size; -} - -template -inline int WireFormatLite::GroupSizeNoVirtual(const MessageType& value) { - return value.MessageType::ByteSize(); -} -template -inline int WireFormatLite::MessageSizeNoVirtual(const MessageType& value) { - int size = value.MessageType::ByteSize(); - return io::CodedOutputStream::VarintSize32(size) + size; -} - -} // namespace internal -} // namespace protobuf - -} // namespace google -#endif // GOOGLE_PROTOBUF_WIRE_FORMAT_LITE_INL_H__ diff --git a/Resources/NetHook/google/protobuf/wire_format_unittest.cc b/Resources/NetHook/google/protobuf/wire_format_unittest.cc deleted file mode 100644 index 867970c4..00000000 --- a/Resources/NetHook/google/protobuf/wire_format_unittest.cc +++ /dev/null @@ -1,905 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * 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. -// * Neither the name of Google Inc. nor the names of its -// contributors may 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. - -// Author: kenton@google.com (Kenton Varda) -// Based on original Protocol Buffers design by -// Sanjay Ghemawat, Jeff Dean, and others. - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace internal { -namespace { - -TEST(WireFormatTest, EnumsInSync) { - // Verify that WireFormatLite::FieldType and WireFormatLite::CppType match - // FieldDescriptor::Type and FieldDescriptor::CppType. - - EXPECT_EQ(implicit_cast(FieldDescriptor::MAX_TYPE), - implicit_cast(WireFormatLite::MAX_FIELD_TYPE)); - EXPECT_EQ(implicit_cast(FieldDescriptor::MAX_CPPTYPE), - implicit_cast(WireFormatLite::MAX_CPPTYPE)); - - for (int i = 1; i <= WireFormatLite::MAX_FIELD_TYPE; i++) { - EXPECT_EQ( - implicit_cast(FieldDescriptor::TypeToCppType( - static_cast(i))), - implicit_cast(WireFormatLite::FieldTypeToCppType( - static_cast(i)))); - } -} - -TEST(WireFormatTest, MaxFieldNumber) { - // Make sure the max field number constant is accurate. - EXPECT_EQ((1 << (32 - WireFormatLite::kTagTypeBits)) - 1, - FieldDescriptor::kMaxNumber); -} - -TEST(WireFormatTest, Parse) { - unittest::TestAllTypes source, dest; - string data; - - // Serialize using the generated code. - TestUtil::SetAllFields(&source); - source.SerializeToString(&data); - - // Parse using WireFormat. - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - WireFormat::ParseAndMergePartial(&input, &dest); - - // Check. - TestUtil::ExpectAllFieldsSet(dest); -} - -TEST(WireFormatTest, ParseExtensions) { - unittest::TestAllExtensions source, dest; - string data; - - // Serialize using the generated code. - TestUtil::SetAllExtensions(&source); - source.SerializeToString(&data); - - // Parse using WireFormat. - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - WireFormat::ParseAndMergePartial(&input, &dest); - - // Check. - TestUtil::ExpectAllExtensionsSet(dest); -} - -TEST(WireFormatTest, ParsePacked) { - unittest::TestPackedTypes source, dest; - string data; - - // Serialize using the generated code. - TestUtil::SetPackedFields(&source); - source.SerializeToString(&data); - - // Parse using WireFormat. - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - WireFormat::ParseAndMergePartial(&input, &dest); - - // Check. - TestUtil::ExpectPackedFieldsSet(dest); -} - -TEST(WireFormatTest, ParsePackedFromUnpacked) { - // Serialize using the generated code. - unittest::TestUnpackedTypes source; - TestUtil::SetUnpackedFields(&source); - string data = source.SerializeAsString(); - - // Parse using WireFormat. - unittest::TestPackedTypes dest; - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - WireFormat::ParseAndMergePartial(&input, &dest); - - // Check. - TestUtil::ExpectPackedFieldsSet(dest); -} - -TEST(WireFormatTest, ParseUnpackedFromPacked) { - // Serialize using the generated code. - unittest::TestPackedTypes source; - TestUtil::SetPackedFields(&source); - string data = source.SerializeAsString(); - - // Parse using WireFormat. - unittest::TestUnpackedTypes dest; - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - WireFormat::ParseAndMergePartial(&input, &dest); - - // Check. - TestUtil::ExpectUnpackedFieldsSet(dest); -} - -TEST(WireFormatTest, ParsePackedExtensions) { - unittest::TestPackedExtensions source, dest; - string data; - - // Serialize using the generated code. - TestUtil::SetPackedExtensions(&source); - source.SerializeToString(&data); - - // Parse using WireFormat. - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - WireFormat::ParseAndMergePartial(&input, &dest); - - // Check. - TestUtil::ExpectPackedExtensionsSet(dest); -} - -TEST(WireFormatTest, ByteSize) { - unittest::TestAllTypes message; - TestUtil::SetAllFields(&message); - - EXPECT_EQ(message.ByteSize(), WireFormat::ByteSize(message)); - message.Clear(); - EXPECT_EQ(0, message.ByteSize()); - EXPECT_EQ(0, WireFormat::ByteSize(message)); -} - -TEST(WireFormatTest, ByteSizeExtensions) { - unittest::TestAllExtensions message; - TestUtil::SetAllExtensions(&message); - - EXPECT_EQ(message.ByteSize(), - WireFormat::ByteSize(message)); - message.Clear(); - EXPECT_EQ(0, message.ByteSize()); - EXPECT_EQ(0, WireFormat::ByteSize(message)); -} - -TEST(WireFormatTest, ByteSizePacked) { - unittest::TestPackedTypes message; - TestUtil::SetPackedFields(&message); - - EXPECT_EQ(message.ByteSize(), WireFormat::ByteSize(message)); - message.Clear(); - EXPECT_EQ(0, message.ByteSize()); - EXPECT_EQ(0, WireFormat::ByteSize(message)); -} - -TEST(WireFormatTest, ByteSizePackedExtensions) { - unittest::TestPackedExtensions message; - TestUtil::SetPackedExtensions(&message); - - EXPECT_EQ(message.ByteSize(), - WireFormat::ByteSize(message)); - message.Clear(); - EXPECT_EQ(0, message.ByteSize()); - EXPECT_EQ(0, WireFormat::ByteSize(message)); -} - -TEST(WireFormatTest, Serialize) { - unittest::TestAllTypes message; - string generated_data; - string dynamic_data; - - TestUtil::SetAllFields(&message); - int size = message.ByteSize(); - - // Serialize using the generated code. - { - io::StringOutputStream raw_output(&generated_data); - io::CodedOutputStream output(&raw_output); - message.SerializeWithCachedSizes(&output); - ASSERT_FALSE(output.HadError()); - } - - // Serialize using WireFormat. - { - io::StringOutputStream raw_output(&dynamic_data); - io::CodedOutputStream output(&raw_output); - WireFormat::SerializeWithCachedSizes(message, size, &output); - ASSERT_FALSE(output.HadError()); - } - - // Should be the same. - // Don't use EXPECT_EQ here because we're comparing raw binary data and - // we really don't want it dumped to stdout on failure. - EXPECT_TRUE(dynamic_data == generated_data); -} - -TEST(WireFormatTest, SerializeExtensions) { - unittest::TestAllExtensions message; - string generated_data; - string dynamic_data; - - TestUtil::SetAllExtensions(&message); - int size = message.ByteSize(); - - // Serialize using the generated code. - { - io::StringOutputStream raw_output(&generated_data); - io::CodedOutputStream output(&raw_output); - message.SerializeWithCachedSizes(&output); - ASSERT_FALSE(output.HadError()); - } - - // Serialize using WireFormat. - { - io::StringOutputStream raw_output(&dynamic_data); - io::CodedOutputStream output(&raw_output); - WireFormat::SerializeWithCachedSizes(message, size, &output); - ASSERT_FALSE(output.HadError()); - } - - // Should be the same. - // Don't use EXPECT_EQ here because we're comparing raw binary data and - // we really don't want it dumped to stdout on failure. - EXPECT_TRUE(dynamic_data == generated_data); -} - -TEST(WireFormatTest, SerializeFieldsAndExtensions) { - unittest::TestFieldOrderings message; - string generated_data; - string dynamic_data; - - TestUtil::SetAllFieldsAndExtensions(&message); - int size = message.ByteSize(); - - // Serialize using the generated code. - { - io::StringOutputStream raw_output(&generated_data); - io::CodedOutputStream output(&raw_output); - message.SerializeWithCachedSizes(&output); - ASSERT_FALSE(output.HadError()); - } - - // Serialize using WireFormat. - { - io::StringOutputStream raw_output(&dynamic_data); - io::CodedOutputStream output(&raw_output); - WireFormat::SerializeWithCachedSizes(message, size, &output); - ASSERT_FALSE(output.HadError()); - } - - // Should be the same. - // Don't use EXPECT_EQ here because we're comparing raw binary data and - // we really don't want it dumped to stdout on failure. - EXPECT_TRUE(dynamic_data == generated_data); - - // Should output in canonical order. - TestUtil::ExpectAllFieldsAndExtensionsInOrder(dynamic_data); - TestUtil::ExpectAllFieldsAndExtensionsInOrder(generated_data); -} - -TEST(WireFormatTest, ParseMultipleExtensionRanges) { - // Make sure we can parse a message that contains multiple extensions ranges. - unittest::TestFieldOrderings source; - string data; - - TestUtil::SetAllFieldsAndExtensions(&source); - source.SerializeToString(&data); - - { - unittest::TestFieldOrderings dest; - EXPECT_TRUE(dest.ParseFromString(data)); - EXPECT_EQ(source.DebugString(), dest.DebugString()); - } - - // Also test using reflection-based parsing. - { - unittest::TestFieldOrderings dest; - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream coded_input(&raw_input); - EXPECT_TRUE(WireFormat::ParseAndMergePartial(&coded_input, &dest)); - EXPECT_EQ(source.DebugString(), dest.DebugString()); - } -} - -const int kUnknownTypeId = 1550055; - -TEST(WireFormatTest, SerializeMessageSet) { - // Set up a TestMessageSet with two known messages and an unknown one. - unittest::TestMessageSet message_set; - message_set.MutableExtension( - unittest::TestMessageSetExtension1::message_set_extension)->set_i(123); - message_set.MutableExtension( - unittest::TestMessageSetExtension2::message_set_extension)->set_str("foo"); - message_set.mutable_unknown_fields()->AddLengthDelimited( - kUnknownTypeId, "bar"); - - string data; - ASSERT_TRUE(message_set.SerializeToString(&data)); - - // Parse back using RawMessageSet and check the contents. - unittest::RawMessageSet raw; - ASSERT_TRUE(raw.ParseFromString(data)); - - EXPECT_EQ(0, raw.unknown_fields().field_count()); - - ASSERT_EQ(3, raw.item_size()); - EXPECT_EQ( - unittest::TestMessageSetExtension1::descriptor()->extension(0)->number(), - raw.item(0).type_id()); - EXPECT_EQ( - unittest::TestMessageSetExtension2::descriptor()->extension(0)->number(), - raw.item(1).type_id()); - EXPECT_EQ(kUnknownTypeId, raw.item(2).type_id()); - - unittest::TestMessageSetExtension1 message1; - EXPECT_TRUE(message1.ParseFromString(raw.item(0).message())); - EXPECT_EQ(123, message1.i()); - - unittest::TestMessageSetExtension2 message2; - EXPECT_TRUE(message2.ParseFromString(raw.item(1).message())); - EXPECT_EQ("foo", message2.str()); - - EXPECT_EQ("bar", raw.item(2).message()); -} - -TEST(WireFormatTest, SerializeMessageSetVariousWaysAreEqual) { - // Serialize a MessageSet to a stream and to a flat array using generated - // code, and also using WireFormat, and check that the results are equal. - // Set up a TestMessageSet with two known messages and an unknown one, as - // above. - - unittest::TestMessageSet message_set; - message_set.MutableExtension( - unittest::TestMessageSetExtension1::message_set_extension)->set_i(123); - message_set.MutableExtension( - unittest::TestMessageSetExtension2::message_set_extension)->set_str("foo"); - message_set.mutable_unknown_fields()->AddLengthDelimited( - kUnknownTypeId, "bar"); - - int size = message_set.ByteSize(); - EXPECT_EQ(size, message_set.GetCachedSize()); - ASSERT_EQ(size, WireFormat::ByteSize(message_set)); - - string flat_data; - string stream_data; - string dynamic_data; - flat_data.resize(size); - stream_data.resize(size); - - // Serialize to flat array - { - uint8* target = reinterpret_cast(string_as_array(&flat_data)); - uint8* end = message_set.SerializeWithCachedSizesToArray(target); - EXPECT_EQ(size, end - target); - } - - // Serialize to buffer - { - io::ArrayOutputStream array_stream(string_as_array(&stream_data), size, 1); - io::CodedOutputStream output_stream(&array_stream); - message_set.SerializeWithCachedSizes(&output_stream); - ASSERT_FALSE(output_stream.HadError()); - } - - // Serialize to buffer with WireFormat. - { - io::StringOutputStream string_stream(&dynamic_data); - io::CodedOutputStream output_stream(&string_stream); - WireFormat::SerializeWithCachedSizes(message_set, size, &output_stream); - ASSERT_FALSE(output_stream.HadError()); - } - - EXPECT_TRUE(flat_data == stream_data); - EXPECT_TRUE(flat_data == dynamic_data); -} - -TEST(WireFormatTest, ParseMessageSet) { - // Set up a RawMessageSet with two known messages and an unknown one. - unittest::RawMessageSet raw; - - { - unittest::RawMessageSet::Item* item = raw.add_item(); - item->set_type_id( - unittest::TestMessageSetExtension1::descriptor()->extension(0)->number()); - unittest::TestMessageSetExtension1 message; - message.set_i(123); - message.SerializeToString(item->mutable_message()); - } - - { - unittest::RawMessageSet::Item* item = raw.add_item(); - item->set_type_id( - unittest::TestMessageSetExtension2::descriptor()->extension(0)->number()); - unittest::TestMessageSetExtension2 message; - message.set_str("foo"); - message.SerializeToString(item->mutable_message()); - } - - { - unittest::RawMessageSet::Item* item = raw.add_item(); - item->set_type_id(kUnknownTypeId); - item->set_message("bar"); - } - - string data; - ASSERT_TRUE(raw.SerializeToString(&data)); - - // Parse as a TestMessageSet and check the contents. - unittest::TestMessageSet message_set; - ASSERT_TRUE(message_set.ParseFromString(data)); - - EXPECT_EQ(123, message_set.GetExtension( - unittest::TestMessageSetExtension1::message_set_extension).i()); - EXPECT_EQ("foo", message_set.GetExtension( - unittest::TestMessageSetExtension2::message_set_extension).str()); - - ASSERT_EQ(1, message_set.unknown_fields().field_count()); - ASSERT_EQ(UnknownField::TYPE_LENGTH_DELIMITED, - message_set.unknown_fields().field(0).type()); - EXPECT_EQ("bar", message_set.unknown_fields().field(0).length_delimited()); - - // Also parse using WireFormat. - unittest::TestMessageSet dynamic_message_set; - io::CodedInputStream input(reinterpret_cast(data.data()), - data.size()); - ASSERT_TRUE(WireFormat::ParseAndMergePartial(&input, &dynamic_message_set)); - EXPECT_EQ(message_set.DebugString(), dynamic_message_set.DebugString()); -} - -TEST(WireFormatTest, RecursionLimit) { - unittest::TestRecursiveMessage message; - message.mutable_a()->mutable_a()->mutable_a()->mutable_a()->set_i(1); - string data; - message.SerializeToString(&data); - - { - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - input.SetRecursionLimit(4); - unittest::TestRecursiveMessage message2; - EXPECT_TRUE(message2.ParseFromCodedStream(&input)); - } - - { - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - input.SetRecursionLimit(3); - unittest::TestRecursiveMessage message2; - EXPECT_FALSE(message2.ParseFromCodedStream(&input)); - } -} - -TEST(WireFormatTest, UnknownFieldRecursionLimit) { - unittest::TestEmptyMessage message; - message.mutable_unknown_fields() - ->AddGroup(1234) - ->AddGroup(1234) - ->AddGroup(1234) - ->AddGroup(1234) - ->AddVarint(1234, 123); - string data; - message.SerializeToString(&data); - - { - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - input.SetRecursionLimit(4); - unittest::TestEmptyMessage message2; - EXPECT_TRUE(message2.ParseFromCodedStream(&input)); - } - - { - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream input(&raw_input); - input.SetRecursionLimit(3); - unittest::TestEmptyMessage message2; - EXPECT_FALSE(message2.ParseFromCodedStream(&input)); - } -} - -TEST(WireFormatTest, ZigZag) { -// avoid line-wrapping -#define LL(x) GOOGLE_LONGLONG(x) -#define ULL(x) GOOGLE_ULONGLONG(x) -#define ZigZagEncode32(x) WireFormatLite::ZigZagEncode32(x) -#define ZigZagDecode32(x) WireFormatLite::ZigZagDecode32(x) -#define ZigZagEncode64(x) WireFormatLite::ZigZagEncode64(x) -#define ZigZagDecode64(x) WireFormatLite::ZigZagDecode64(x) - - EXPECT_EQ(0u, ZigZagEncode32( 0)); - EXPECT_EQ(1u, ZigZagEncode32(-1)); - EXPECT_EQ(2u, ZigZagEncode32( 1)); - EXPECT_EQ(3u, ZigZagEncode32(-2)); - EXPECT_EQ(0x7FFFFFFEu, ZigZagEncode32(0x3FFFFFFF)); - EXPECT_EQ(0x7FFFFFFFu, ZigZagEncode32(0xC0000000)); - EXPECT_EQ(0xFFFFFFFEu, ZigZagEncode32(0x7FFFFFFF)); - EXPECT_EQ(0xFFFFFFFFu, ZigZagEncode32(0x80000000)); - - EXPECT_EQ( 0, ZigZagDecode32(0u)); - EXPECT_EQ(-1, ZigZagDecode32(1u)); - EXPECT_EQ( 1, ZigZagDecode32(2u)); - EXPECT_EQ(-2, ZigZagDecode32(3u)); - EXPECT_EQ(0x3FFFFFFF, ZigZagDecode32(0x7FFFFFFEu)); - EXPECT_EQ(0xC0000000, ZigZagDecode32(0x7FFFFFFFu)); - EXPECT_EQ(0x7FFFFFFF, ZigZagDecode32(0xFFFFFFFEu)); - EXPECT_EQ(0x80000000, ZigZagDecode32(0xFFFFFFFFu)); - - EXPECT_EQ(0u, ZigZagEncode64( 0)); - EXPECT_EQ(1u, ZigZagEncode64(-1)); - EXPECT_EQ(2u, ZigZagEncode64( 1)); - EXPECT_EQ(3u, ZigZagEncode64(-2)); - EXPECT_EQ(ULL(0x000000007FFFFFFE), ZigZagEncode64(LL(0x000000003FFFFFFF))); - EXPECT_EQ(ULL(0x000000007FFFFFFF), ZigZagEncode64(LL(0xFFFFFFFFC0000000))); - EXPECT_EQ(ULL(0x00000000FFFFFFFE), ZigZagEncode64(LL(0x000000007FFFFFFF))); - EXPECT_EQ(ULL(0x00000000FFFFFFFF), ZigZagEncode64(LL(0xFFFFFFFF80000000))); - EXPECT_EQ(ULL(0xFFFFFFFFFFFFFFFE), ZigZagEncode64(LL(0x7FFFFFFFFFFFFFFF))); - EXPECT_EQ(ULL(0xFFFFFFFFFFFFFFFF), ZigZagEncode64(LL(0x8000000000000000))); - - EXPECT_EQ( 0, ZigZagDecode64(0u)); - EXPECT_EQ(-1, ZigZagDecode64(1u)); - EXPECT_EQ( 1, ZigZagDecode64(2u)); - EXPECT_EQ(-2, ZigZagDecode64(3u)); - EXPECT_EQ(LL(0x000000003FFFFFFF), ZigZagDecode64(ULL(0x000000007FFFFFFE))); - EXPECT_EQ(LL(0xFFFFFFFFC0000000), ZigZagDecode64(ULL(0x000000007FFFFFFF))); - EXPECT_EQ(LL(0x000000007FFFFFFF), ZigZagDecode64(ULL(0x00000000FFFFFFFE))); - EXPECT_EQ(LL(0xFFFFFFFF80000000), ZigZagDecode64(ULL(0x00000000FFFFFFFF))); - EXPECT_EQ(LL(0x7FFFFFFFFFFFFFFF), ZigZagDecode64(ULL(0xFFFFFFFFFFFFFFFE))); - EXPECT_EQ(LL(0x8000000000000000), ZigZagDecode64(ULL(0xFFFFFFFFFFFFFFFF))); - - // Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1) - // were chosen semi-randomly via keyboard bashing. - EXPECT_EQ( 0, ZigZagDecode32(ZigZagEncode32( 0))); - EXPECT_EQ( 1, ZigZagDecode32(ZigZagEncode32( 1))); - EXPECT_EQ( -1, ZigZagDecode32(ZigZagEncode32( -1))); - EXPECT_EQ(14927, ZigZagDecode32(ZigZagEncode32(14927))); - EXPECT_EQ(-3612, ZigZagDecode32(ZigZagEncode32(-3612))); - - EXPECT_EQ( 0, ZigZagDecode64(ZigZagEncode64( 0))); - EXPECT_EQ( 1, ZigZagDecode64(ZigZagEncode64( 1))); - EXPECT_EQ( -1, ZigZagDecode64(ZigZagEncode64( -1))); - EXPECT_EQ(14927, ZigZagDecode64(ZigZagEncode64(14927))); - EXPECT_EQ(-3612, ZigZagDecode64(ZigZagEncode64(-3612))); - - EXPECT_EQ(LL(856912304801416), ZigZagDecode64(ZigZagEncode64( - LL(856912304801416)))); - EXPECT_EQ(LL(-75123905439571256), ZigZagDecode64(ZigZagEncode64( - LL(-75123905439571256)))); -} - -TEST(WireFormatTest, RepeatedScalarsDifferentTagSizes) { - // At one point checks would trigger when parsing repeated fixed scalar - // fields. - protobuf_unittest::TestRepeatedScalarDifferentTagSizes msg1, msg2; - for (int i = 0; i < 100; ++i) { - msg1.add_repeated_fixed32(i); - msg1.add_repeated_int32(i); - msg1.add_repeated_fixed64(i); - msg1.add_repeated_int64(i); - msg1.add_repeated_float(i); - msg1.add_repeated_uint64(i); - } - - // Make sure that we have a variety of tag sizes. - const google::protobuf::Descriptor* desc = msg1.GetDescriptor(); - const google::protobuf::FieldDescriptor* field; - field = desc->FindFieldByName("repeated_fixed32"); - ASSERT_TRUE(field != NULL); - ASSERT_EQ(1, WireFormat::TagSize(field->number(), field->type())); - field = desc->FindFieldByName("repeated_int32"); - ASSERT_TRUE(field != NULL); - ASSERT_EQ(1, WireFormat::TagSize(field->number(), field->type())); - field = desc->FindFieldByName("repeated_fixed64"); - ASSERT_TRUE(field != NULL); - ASSERT_EQ(2, WireFormat::TagSize(field->number(), field->type())); - field = desc->FindFieldByName("repeated_int64"); - ASSERT_TRUE(field != NULL); - ASSERT_EQ(2, WireFormat::TagSize(field->number(), field->type())); - field = desc->FindFieldByName("repeated_float"); - ASSERT_TRUE(field != NULL); - ASSERT_EQ(3, WireFormat::TagSize(field->number(), field->type())); - field = desc->FindFieldByName("repeated_uint64"); - ASSERT_TRUE(field != NULL); - ASSERT_EQ(3, WireFormat::TagSize(field->number(), field->type())); - - EXPECT_TRUE(msg2.ParseFromString(msg1.SerializeAsString())); - EXPECT_EQ(msg1.DebugString(), msg2.DebugString()); -} - -class WireFormatInvalidInputTest : public testing::Test { - protected: - // Make a serialized TestAllTypes in which the field optional_nested_message - // contains exactly the given bytes, which may be invalid. - string MakeInvalidEmbeddedMessage(const char* bytes, int size) { - const FieldDescriptor* field = - unittest::TestAllTypes::descriptor()->FindFieldByName( - "optional_nested_message"); - GOOGLE_CHECK(field != NULL); - - string result; - - { - io::StringOutputStream raw_output(&result); - io::CodedOutputStream output(&raw_output); - - WireFormatLite::WriteBytes(field->number(), string(bytes, size), &output); - } - - return result; - } - - // Make a serialized TestAllTypes in which the field optionalgroup - // contains exactly the given bytes -- which may be invalid -- and - // possibly no end tag. - string MakeInvalidGroup(const char* bytes, int size, bool include_end_tag) { - const FieldDescriptor* field = - unittest::TestAllTypes::descriptor()->FindFieldByName( - "optionalgroup"); - GOOGLE_CHECK(field != NULL); - - string result; - - { - io::StringOutputStream raw_output(&result); - io::CodedOutputStream output(&raw_output); - - output.WriteVarint32(WireFormat::MakeTag(field)); - output.WriteString(string(bytes, size)); - if (include_end_tag) { - output.WriteVarint32(WireFormatLite::MakeTag( - field->number(), WireFormatLite::WIRETYPE_END_GROUP)); - } - } - - return result; - } -}; - -TEST_F(WireFormatInvalidInputTest, InvalidSubMessage) { - unittest::TestAllTypes message; - - // Control case. - EXPECT_TRUE(message.ParseFromString(MakeInvalidEmbeddedMessage("", 0))); - - // The byte is a valid varint, but not a valid tag (zero). - EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\0", 1))); - - // The byte is a malformed varint. - EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\200", 1))); - - // The byte is an endgroup tag, but we aren't parsing a group. - EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\014", 1))); - - // The byte is a valid varint but not a valid tag (bad wire type). - EXPECT_FALSE(message.ParseFromString(MakeInvalidEmbeddedMessage("\017", 1))); -} - -TEST_F(WireFormatInvalidInputTest, InvalidGroup) { - unittest::TestAllTypes message; - - // Control case. - EXPECT_TRUE(message.ParseFromString(MakeInvalidGroup("", 0, true))); - - // Missing end tag. Groups cannot end at EOF. - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("", 0, false))); - - // The byte is a valid varint, but not a valid tag (zero). - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\0", 1, false))); - - // The byte is a malformed varint. - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\200", 1, false))); - - // The byte is an endgroup tag, but not the right one for this group. - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\014", 1, false))); - - // The byte is a valid varint but not a valid tag (bad wire type). - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\017", 1, true))); -} - -TEST_F(WireFormatInvalidInputTest, InvalidUnknownGroup) { - // Use TestEmptyMessage so that the group made by MakeInvalidGroup will not - // be a known tag number. - unittest::TestEmptyMessage message; - - // Control case. - EXPECT_TRUE(message.ParseFromString(MakeInvalidGroup("", 0, true))); - - // Missing end tag. Groups cannot end at EOF. - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("", 0, false))); - - // The byte is a valid varint, but not a valid tag (zero). - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\0", 1, false))); - - // The byte is a malformed varint. - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\200", 1, false))); - - // The byte is an endgroup tag, but not the right one for this group. - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\014", 1, false))); - - // The byte is a valid varint but not a valid tag (bad wire type). - EXPECT_FALSE(message.ParseFromString(MakeInvalidGroup("\017", 1, true))); -} - -TEST_F(WireFormatInvalidInputTest, InvalidStringInUnknownGroup) { - // Test a bug fix: SkipMessage should fail if the message contains a string - // whose length would extend beyond the message end. - - unittest::TestAllTypes message; - message.set_optional_string("foo foo foo foo"); - string data; - message.SerializeToString(&data); - - // Chop some bytes off the end. - data.resize(data.size() - 4); - - // Try to skip it. Note that the bug was only present when parsing to an - // UnknownFieldSet. - io::ArrayInputStream raw_input(data.data(), data.size()); - io::CodedInputStream coded_input(&raw_input); - UnknownFieldSet unknown_fields; - EXPECT_FALSE(WireFormat::SkipMessage(&coded_input, &unknown_fields)); -} - -// Test differences between string and bytes. -// Value of a string type must be valid UTF-8 string. When UTF-8 -// validation is enabled (GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED): -// WriteInvalidUTF8String: see error message. -// ReadInvalidUTF8String: see error message. -// WriteValidUTF8String: fine. -// ReadValidUTF8String: fine. -// WriteAnyBytes: fine. -// ReadAnyBytes: fine. -const char * kInvalidUTF8String = "Invalid UTF-8: \xA0\xB0\xC0\xD0"; -// This used to be "Valid UTF-8: \x01\x02\u8C37\u6B4C", but MSVC seems to -// interpret \u differently from GCC. -const char * kValidUTF8String = "Valid UTF-8: \x01\x02\350\260\267\346\255\214"; - -template -bool WriteMessage(const char *value, T *message, string *wire_buffer) { - message->set_data(value); - wire_buffer->clear(); - message->AppendToString(wire_buffer); - return (wire_buffer->size() > 0); -} - -template -bool ReadMessage(const string &wire_buffer, T *message) { - return message->ParseFromArray(wire_buffer.data(), wire_buffer.size()); -} - -TEST(Utf8ValidationTest, WriteInvalidUTF8String) { - string wire_buffer; - protobuf_unittest::OneString input; - vector errors; - { - ScopedMemoryLog log; - WriteMessage(kInvalidUTF8String, &input, &wire_buffer); - errors = log.GetMessages(ERROR); - } -#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Encountered string containing invalid UTF-8 data while " - "serializing protocol buffer. Strings must contain only UTF-8; " - "use the 'bytes' type for raw bytes.", - errors[0]); - -#else - ASSERT_EQ(0, errors.size()); -#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED -} - -TEST(Utf8ValidationTest, ReadInvalidUTF8String) { - string wire_buffer; - protobuf_unittest::OneString input; - WriteMessage(kInvalidUTF8String, &input, &wire_buffer); - protobuf_unittest::OneString output; - vector errors; - { - ScopedMemoryLog log; - ReadMessage(wire_buffer, &output); - errors = log.GetMessages(ERROR); - } -#ifdef GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED - ASSERT_EQ(1, errors.size()); - EXPECT_EQ("Encountered string containing invalid UTF-8 data while " - "parsing protocol buffer. Strings must contain only UTF-8; " - "use the 'bytes' type for raw bytes.", - errors[0]); - -#else - ASSERT_EQ(0, errors.size()); -#endif // GOOGLE_PROTOBUF_UTF8_VALIDATION_ENABLED -} - -TEST(Utf8ValidationTest, WriteValidUTF8String) { - string wire_buffer; - protobuf_unittest::OneString input; - vector errors; - { - ScopedMemoryLog log; - WriteMessage(kValidUTF8String, &input, &wire_buffer); - errors = log.GetMessages(ERROR); - } - ASSERT_EQ(0, errors.size()); -} - -TEST(Utf8ValidationTest, ReadValidUTF8String) { - string wire_buffer; - protobuf_unittest::OneString input; - WriteMessage(kValidUTF8String, &input, &wire_buffer); - protobuf_unittest::OneString output; - vector errors; - { - ScopedMemoryLog log; - ReadMessage(wire_buffer, &output); - errors = log.GetMessages(ERROR); - } - ASSERT_EQ(0, errors.size()); - EXPECT_EQ(input.data(), output.data()); -} - -// Bytes: anything can pass as bytes, use invalid UTF-8 string to test -TEST(Utf8ValidationTest, WriteArbitraryBytes) { - string wire_buffer; - protobuf_unittest::OneBytes input; - vector errors; - { - ScopedMemoryLog log; - WriteMessage(kInvalidUTF8String, &input, &wire_buffer); - errors = log.GetMessages(ERROR); - } - ASSERT_EQ(0, errors.size()); -} - -TEST(Utf8ValidationTest, ReadArbitraryBytes) { - string wire_buffer; - protobuf_unittest::OneBytes input; - WriteMessage(kInvalidUTF8String, &input, &wire_buffer); - protobuf_unittest::OneBytes output; - vector errors; - { - ScopedMemoryLog log; - ReadMessage(wire_buffer, &output); - errors = log.GetMessages(ERROR); - } - ASSERT_EQ(0, errors.size()); - EXPECT_EQ(input.data(), output.data()); -} - -} // namespace -} // namespace internal -} // namespace protobuf -} // namespace google diff --git a/Resources/NetHook/libprotobuf.lib b/Resources/NetHook/libprotobuf.lib deleted file mode 100644 index 6c097464..00000000 Binary files a/Resources/NetHook/libprotobuf.lib and /dev/null differ diff --git a/Resources/NetHook/logger.cpp b/Resources/NetHook/logger.cpp deleted file mode 100644 index 6e2d6c4a..00000000 --- a/Resources/NetHook/logger.cpp +++ /dev/null @@ -1,106 +0,0 @@ -#include - -#include "logger.h" -#include "utils.h" - -CLogger* g_Logger; - -CLogger::CLogger( const char *szBaseDir ) -{ - memset( m_szDir, 0, sizeof( m_szDir ) ); - - const char *szLastSlash = strrchr( szBaseDir, '\\' ); - - memcpy( m_szDir, szBaseDir, szLastSlash - szBaseDir ); - - sprintf_s( m_szDir, MAX_PATH, "%s\\netlogs\\", m_szDir ); // build the netlogs dir - - CreateDirectoryA( m_szDir, NULL ); -} - - -void CLogger::LogConsole( const char *szFmt, ... ) -{ - va_list args; - va_start( args, szFmt ); - - int buffSize = _vscprintf( szFmt, args ) + 1; - - if ( buffSize == 0 ) - return; - - char *szBuff = new char[ buffSize ]; - memset( szBuff, 0, buffSize ); - - int len = vsprintf_s( szBuff, buffSize, szFmt, args ); - - szBuff[ buffSize - 1 ] = 0; - - HANDLE hOutput = GetStdHandle( STD_OUTPUT_HANDLE ); - - DWORD numWritten = 0; - WriteFile( hOutput, szBuff, len, &numWritten, NULL ); - - delete [] szBuff; -} - - -void CLogger::AppendFile( const char *szFileName, const char *szString, ... ) -{ - va_list args; - va_start( args, szString ); - - int buffSize = _vscprintf( szString, args ) + 1; - - if ( buffSize == 0 ) - return; - - char *szBuff = new char[ buffSize ]; - memset( szBuff, 0, buffSize ); - - int len = vsprintf_s( szBuff, buffSize, szString, args ); - - szBuff[ buffSize - 1 ] = 0; - - this->LogFileData( szFileName, (uint8 *)szBuff, len, true ); - - delete [] szBuff; -} - -void CLogger::LogFileData( const char *szFileName, const uint8 *pData, uint32 cubData, bool bAppend ) -{ - DWORD fileFlags = CREATE_ALWAYS; - - if ( bAppend ) - fileFlags = OPEN_ALWAYS; - - HANDLE hFile = CreateFileA( GetFileDir(szFileName), GENERIC_WRITE, FILE_SHARE_READ, NULL, fileFlags, FILE_ATTRIBUTE_NORMAL, NULL ); - - if ( bAppend ) - SetFilePointer( hFile, 0, NULL, FILE_END ); - - DWORD lNumBytes = 0; - WriteFile( hFile, pData, cubData, &lNumBytes, NULL ); - - CloseHandle( hFile ); -} - -void CLogger::CreateDir(const char *szDir) -{ - const char* szCreatePath = this->GetFileDir(szDir); - - DWORD dwAttribs = GetFileAttributes(szCreatePath); - - if ( dwAttribs == INVALID_FILE_ATTRIBUTES ) - CreateDirectory(szCreatePath, NULL); -} - -const char *CLogger::GetFileDir( const char *szFile ) -{ - static char szFilePath[ MAX_PATH ]; - memset( szFilePath, 0, sizeof( szFilePath ) ); - - sprintf_s( szFilePath, sizeof( szFilePath ), "%s\\%s", m_szDir, szFile ); - - return szFilePath; -} \ No newline at end of file diff --git a/Resources/NetHook/logger.h b/Resources/NetHook/logger.h deleted file mode 100644 index 44b230d4..00000000 --- a/Resources/NetHook/logger.h +++ /dev/null @@ -1,42 +0,0 @@ - -#ifndef LOGGER_H_ -#define LOGGER_H_ -#ifdef _WIN32 -#pragma once -#endif - - -#include "steam/steamtypes.h" - -#define _WINSOCKAPI_ -#include - - - -class CLogger -{ - -public: - CLogger( const char *szBaseDir ); - - - void LogConsole( const char *szString, ... ); - - void AppendFile( const char *szFileName, const char *szString, ... ); - - void LogFileData( const char *szFileName, const uint8 *pData, uint32 cubData, bool bAppend = false ); - - void CreateDir( const char* szDir ); - - -private: - const char *GetFileDir( const char *szFile ); - -private: - char m_szDir[ MAX_PATH ]; - -}; - -extern CLogger* g_Logger; - -#endif // !LOGGER_H_ diff --git a/Resources/NetHook/mathlib/IceKey.H b/Resources/NetHook/mathlib/IceKey.H deleted file mode 100644 index 635482ab..00000000 --- a/Resources/NetHook/mathlib/IceKey.H +++ /dev/null @@ -1,62 +0,0 @@ -// Purpose: Header file for the C++ ICE encryption class. -// Taken from public domain code, as written by Matthew Kwan - July 1996 -// http://www.darkside.com.au/ice/ - -#ifndef _IceKey_H -#define _IceKey_H - -/* -The IceKey class is used for encrypting and decrypting 64-bit blocks of data -with the ICE (Information Concealment Engine) encryption algorithm. - -The constructor creates a new IceKey object that can be used to encrypt and decrypt data. -The level of encryption determines the size of the key, and hence its speed. -Level 0 uses the Thin-ICE variant, which is an 8-round cipher taking an 8-byte key. -This is the fastest option, and is generally considered to be at least as secure as DES, -although it is not yet certain whether it is as secure as its key size. - -For levels n greater than zero, a 16n-round cipher is used, taking 8n-byte keys. -Although not as fast as level 0, these are very very secure. - -Before an IceKey can be used to encrypt data, its key schedule must be set with the set() member function. -The length of the key required is determined by the level, as described above. - -The member functions encrypt() and decrypt() encrypt and decrypt respectively data -in blocks of eight chracters, using the specified key. - -Two functions keySize() and blockSize() are provided -which return the key and block size respectively, measured in bytes. -The key size is determined by the level, while the block size is always 8. - -The destructor zeroes out and frees up all memory associated with the key. -*/ - -class IceSubkey; - -class IceKey { - public: - IceKey (int n); - ~IceKey (); - - void set (const unsigned char *key); - - void encrypt (const unsigned char *plaintext, - unsigned char *ciphertext) const; - - void decrypt (const unsigned char *ciphertext, - unsigned char *plaintext) const; - - int keySize () const; - - int blockSize () const; - - private: - void scheduleBuild (unsigned short *k, int n, - const int *keyrot); - - int _size; - int _rounds; - IceSubkey *_keysched; -}; - -#endif diff --git a/Resources/NetHook/mathlib/amd3dx.h b/Resources/NetHook/mathlib/amd3dx.h deleted file mode 100644 index 1cff7e8e..00000000 --- a/Resources/NetHook/mathlib/amd3dx.h +++ /dev/null @@ -1,1187 +0,0 @@ -/****************************************************************************** - - Copyright (c) 1999 Advanced Micro Devices, Inc. - - LIMITATION OF LIABILITY: THE MATERIALS ARE PROVIDED *AS IS* WITHOUT ANY - EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, - NONINFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY, OR FITNESS FOR ANY - PARTICULAR PURPOSE. IN NO EVENT SHALL AMD OR ITS SUPPLIERS BE LIABLE FOR ANY - DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, - BUSINESS INTERRUPTION, LOSS OF INFORMATION) ARISING OUT OF THE USE OF OR - INABILITY TO USE THE MATERIALS, EVEN IF AMD HAS BEEN ADVISED OF THE POSSIBILITY - OF SUCH DAMAGES. BECAUSE SOME JURISDICTIONS PROHIBIT THE EXCLUSION OR LIMITATION - OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY - NOT APPLY TO YOU. - - AMD does not assume any responsibility for any errors which may appear in the - Materials nor any responsibility to support or update the Materials. AMD retains - the right to make changes to its test specifications at any time, without notice. - - NO SUPPORT OBLIGATION: AMD is not obligated to furnish, support, or make any - further information, software, technical information, know-how, or show-how - available to you. - - So that all may benefit from your experience, please report any problems - or suggestions about this software to 3dsdk.support@amd.com - - AMD Developer Technologies, M/S 585 - Advanced Micro Devices, Inc. - 5900 E. Ben White Blvd. - Austin, TX 78741 - 3dsdk.support@amd.com - -******************************************************************************* - - AMD3DX.H - - MACRO FORMAT - ============ - This file contains inline assembly macros that - generate AMD-3D instructions in binary format. - Therefore, C or C++ programmer can use AMD-3D instructions - without any penalty in their C or C++ source code. - - The macro's name and format conventions are as follow: - - - 1. First argument of macro is a destination and - second argument is a source operand. - ex) _asm PFCMPEQ (mm3, mm4) - | | - dst src - - 2. The destination operand can be m0 to m7 only. - The source operand can be any one of the register - m0 to m7 or _eax, _ecx, _edx, _ebx, _esi, or _edi - that contains effective address. - ex) _asm PFRCP (MM7, MM6) - ex) _asm PFRCPIT2 (mm0, mm4) - ex) _asm PFMUL (mm3, _edi) - - 3. The prefetch(w) takes one src operand _eax, ecx, _edx, - _ebx, _esi, or _edi that contains effective address. - ex) _asm PREFETCH (_edi) - - For WATCOM C/C++ users, when using #pragma aux instead if - _asm, all macro names should be prefixed by a p_ or P_. - Macros should not be enclosed in quotes. - ex) p_pfrcp (MM7,MM6) - - NOTE: Not all instruction macros, nor all possible - combinations of operands have been explicitely - tested. If any errors are found, please report - them. - - EXAMPLE - ======= - Following program doesn't do anything but it shows you - how to use inline assembly AMD-3D instructions in C. - Note that this will only work in flat memory model which - segment registers cs, ds, ss and es point to the same - linear address space total less than 4GB. - - Used Microsoft VC++ 5.0 - - #include - #include "amd3d.h" - - void main () - { - float x = (float)1.25; - float y = (float)1.25; - float z, zz; - - _asm { - movd mm1, x - movd mm2, y - pfmul (mm1, mm2) - movd z, mm1 - femms - } - - printf ("value of z = %f\n", z); - - // - // Demonstration of using the memory instead of - // multimedia register - // - _asm { - movd mm3, x - lea esi, y // load effective address of y - pfmul (mm3, _esi) - movd zz, mm3 - femms - } - - printf ("value of zz = %f\n", zz); - } - - #pragma aux EXAMPLE with WATCOM C/C++ v11.x - =========================================== - - extern void Add(float *__Dest, float *__A, float *__B); - #pragma aux Add = \ - p_femms \ - "movd mm6,[esi]" \ - p_pfadd(mm6,_edi) \ - "movd [ebx],mm6" \ - p_femms \ - parm [ebx] [esi] [edi]; - -*******************************************************************************/ - -#ifndef _K3DMACROSINCLUDED_ -#define _K3DMACROSINCLUDED_ - -#if defined (__WATCOMC__) - -// The WATCOM C/C++ version of the 3DNow! macros. -// -// The older, compbined register style for WATCOM C/C++ macros is not -// supported. - -/* Operand defines for instructions two operands */ -#define _k3d_mm0_mm0 0xc0 -#define _k3d_mm0_mm1 0xc1 -#define _k3d_mm0_mm2 0xc2 -#define _k3d_mm0_mm3 0xc3 -#define _k3d_mm0_mm4 0xc4 -#define _k3d_mm0_mm5 0xc5 -#define _k3d_mm0_mm6 0xc6 -#define _k3d_mm0_mm7 0xc7 -#define _k3d_mm0_eax 0x00 -#define _k3d_mm0_ecx 0x01 -#define _k3d_mm0_edx 0x02 -#define _k3d_mm0_ebx 0x03 -#define _k3d_mm0_esi 0x06 -#define _k3d_mm0_edi 0x07 -#define _k3d_mm1_mm0 0xc8 -#define _k3d_mm1_mm1 0xc9 -#define _k3d_mm1_mm2 0xca -#define _k3d_mm1_mm3 0xcb -#define _k3d_mm1_mm4 0xcc -#define _k3d_mm1_mm5 0xcd -#define _k3d_mm1_mm6 0xce -#define _k3d_mm1_mm7 0xcf -#define _k3d_mm1_eax 0x08 -#define _k3d_mm1_ecx 0x09 -#define _k3d_mm1_edx 0x0a -#define _k3d_mm1_ebx 0x0b -#define _k3d_mm1_esi 0x0e -#define _k3d_mm1_edi 0x0f -#define _k3d_mm2_mm0 0xd0 -#define _k3d_mm2_mm1 0xd1 -#define _k3d_mm2_mm2 0xd2 -#define _k3d_mm2_mm3 0xd3 -#define _k3d_mm2_mm4 0xd4 -#define _k3d_mm2_mm5 0xd5 -#define _k3d_mm2_mm6 0xd6 -#define _k3d_mm2_mm7 0xd7 -#define _k3d_mm2_eax 0x10 -#define _k3d_mm2_ecx 0x11 -#define _k3d_mm2_edx 0x12 -#define _k3d_mm2_ebx 0x13 -#define _k3d_mm2_esi 0x16 -#define _k3d_mm2_edi 0x17 -#define _k3d_mm3_mm0 0xd8 -#define _k3d_mm3_mm1 0xd9 -#define _k3d_mm3_mm2 0xda -#define _k3d_mm3_mm3 0xdb -#define _k3d_mm3_mm4 0xdc -#define _k3d_mm3_mm5 0xdd -#define _k3d_mm3_mm6 0xde -#define _k3d_mm3_mm7 0xdf -#define _k3d_mm3_eax 0x18 -#define _k3d_mm3_ecx 0x19 -#define _k3d_mm3_edx 0x1a -#define _k3d_mm3_ebx 0x1b -#define _k3d_mm3_esi 0x1e -#define _k3d_mm3_edi 0x1f -#define _k3d_mm4_mm0 0xe0 -#define _k3d_mm4_mm1 0xe1 -#define _k3d_mm4_mm2 0xe2 -#define _k3d_mm4_mm3 0xe3 -#define _k3d_mm4_mm4 0xe4 -#define _k3d_mm4_mm5 0xe5 -#define _k3d_mm4_mm6 0xe6 -#define _k3d_mm4_mm7 0xe7 -#define _k3d_mm4_eax 0x20 -#define _k3d_mm4_ecx 0x21 -#define _k3d_mm4_edx 0x22 -#define _k3d_mm4_ebx 0x23 -#define _k3d_mm4_esi 0x26 -#define _k3d_mm4_edi 0x27 -#define _k3d_mm5_mm0 0xe8 -#define _k3d_mm5_mm1 0xe9 -#define _k3d_mm5_mm2 0xea -#define _k3d_mm5_mm3 0xeb -#define _k3d_mm5_mm4 0xec -#define _k3d_mm5_mm5 0xed -#define _k3d_mm5_mm6 0xee -#define _k3d_mm5_mm7 0xef -#define _k3d_mm5_eax 0x28 -#define _k3d_mm5_ecx 0x29 -#define _k3d_mm5_edx 0x2a -#define _k3d_mm5_ebx 0x2b -#define _k3d_mm5_esi 0x2e -#define _k3d_mm5_edi 0x2f -#define _k3d_mm6_mm0 0xf0 -#define _k3d_mm6_mm1 0xf1 -#define _k3d_mm6_mm2 0xf2 -#define _k3d_mm6_mm3 0xf3 -#define _k3d_mm6_mm4 0xf4 -#define _k3d_mm6_mm5 0xf5 -#define _k3d_mm6_mm6 0xf6 -#define _k3d_mm6_mm7 0xf7 -#define _k3d_mm6_eax 0x30 -#define _k3d_mm6_ecx 0x31 -#define _k3d_mm6_edx 0x32 -#define _k3d_mm6_ebx 0x33 -#define _k3d_mm6_esi 0x36 -#define _k3d_mm6_edi 0x37 -#define _k3d_mm7_mm0 0xf8 -#define _k3d_mm7_mm1 0xf9 -#define _k3d_mm7_mm2 0xfa -#define _k3d_mm7_mm3 0xfb -#define _k3d_mm7_mm4 0xfc -#define _k3d_mm7_mm5 0xfd -#define _k3d_mm7_mm6 0xfe -#define _k3d_mm7_mm7 0xff -#define _k3d_mm7_eax 0x38 -#define _k3d_mm7_ecx 0x39 -#define _k3d_mm7_edx 0x3a -#define _k3d_mm7_ebx 0x3b -#define _k3d_mm7_esi 0x3e -#define _k3d_mm7_edi 0x3f - -#define _k3d_name_xlat_m0 _mm0 -#define _k3d_name_xlat_m1 _mm1 -#define _k3d_name_xlat_m2 _mm2 -#define _k3d_name_xlat_m3 _mm3 -#define _k3d_name_xlat_m4 _mm4 -#define _k3d_name_xlat_m5 _mm5 -#define _k3d_name_xlat_m6 _mm6 -#define _k3d_name_xlat_m7 _mm7 -#define _k3d_name_xlat_M0 _mm0 -#define _k3d_name_xlat_M1 _mm1 -#define _k3d_name_xlat_M2 _mm2 -#define _k3d_name_xlat_M3 _mm3 -#define _k3d_name_xlat_M4 _mm4 -#define _k3d_name_xlat_M5 _mm5 -#define _k3d_name_xlat_M6 _mm6 -#define _k3d_name_xlat_M7 _mm7 -#define _k3d_name_xlat_mm0 _mm0 -#define _k3d_name_xlat_mm1 _mm1 -#define _k3d_name_xlat_mm2 _mm2 -#define _k3d_name_xlat_mm3 _mm3 -#define _k3d_name_xlat_mm4 _mm4 -#define _k3d_name_xlat_mm5 _mm5 -#define _k3d_name_xlat_mm6 _mm6 -#define _k3d_name_xlat_mm7 _mm7 -#define _k3d_name_xlat_MM0 _mm0 -#define _k3d_name_xlat_MM1 _mm1 -#define _k3d_name_xlat_MM2 _mm2 -#define _k3d_name_xlat_MM3 _mm3 -#define _k3d_name_xlat_MM4 _mm4 -#define _k3d_name_xlat_MM5 _mm5 -#define _k3d_name_xlat_MM6 _mm6 -#define _k3d_name_xlat_MM7 _mm7 -#define _k3d_name_xlat_eax _eax -#define _k3d_name_xlat_ebx _ebx -#define _k3d_name_xlat_ecx _ecx -#define _k3d_name_xlat_edx _edx -#define _k3d_name_xlat_esi _esi -#define _k3d_name_xlat_edi _edi -#define _k3d_name_xlat_ebp _ebp -#define _k3d_name_xlat_EAX _eax -#define _k3d_name_xlat_EBX _ebx -#define _k3d_name_xlat_ECX _ecx -#define _k3d_name_xlat_EDX _edx -#define _k3d_name_xlat_ESI _esi -#define _k3d_name_xlat_EDI _edi -#define _k3d_name_xlat_EBP _ebp -#define _k3d_name_xlat__eax _eax -#define _k3d_name_xlat__ebx _ebx -#define _k3d_name_xlat__ecx _ecx -#define _k3d_name_xlat__edx _edx -#define _k3d_name_xlat__esi _esi -#define _k3d_name_xlat__edi _edi -#define _k3d_name_xlat__ebp _ebp -#define _k3d_name_xlat__EAX _eax -#define _k3d_name_xlat__EBX _ebx -#define _k3d_name_xlat__ECX _ecx -#define _k3d_name_xlat__EDX _edx -#define _k3d_name_xlat__ESI _esi -#define _k3d_name_xlat__EDI _edi -#define _k3d_name_xlat__EBP _ebp - -#define _k3d_xglue3(a,b,c) a##b##c -#define _k3d_glue3(a,b,c) _k3d_xglue3(a,b,c) -#define _k3d_MODRM(dst, src) _k3d_glue3(_k3d,_k3d_name_xlat_##dst,_k3d_name_xlat_##src) - -/* Operand defines for prefetch and prefetchw */ - -#define _k3d_pref_eax 0x00 -#define _k3d_pref_ecx 0x01 -#define _k3d_pref_edx 0x02 -#define _k3d_pref_ebx 0x03 -#define _k3d_pref_esi 0x06 -#define _k3d_pref_edi 0x07 -#define _k3d_pref_EAX 0x00 -#define _k3d_pref_ECX 0x01 -#define _k3d_pref_EDX 0x02 -#define _k3d_pref_EBX 0x03 -#define _k3d_pref_ESI 0x06 -#define _k3d_pref_EDI 0x07 -#define _k3d_prefw_eax 0x08 -#define _k3d_prefw_ecx 0x09 -#define _k3d_prefw_edx 0x0A -#define _k3d_prefw_ebx 0x0B -#define _k3d_prefw_esi 0x0E -#define _k3d_prefw_edi 0x0F -#define _k3d_prefw_EAX 0x08 -#define _k3d_prefw_ECX 0x09 -#define _k3d_prefw_EDX 0x0A -#define _k3d_prefw_EBX 0x0B -#define _k3d_prefw_ESI 0x0E -#define _k3d_prefw_EDI 0x0F - -/* Defines for 3DNow! instructions */ -#define PF2ID(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x1d -#define PFACC(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xae -#define PFADD(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x9e -#define PFCMPEQ(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xb0 -#define PFCMPGE(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x90 -#define PFCMPGT(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xa0 -#define PFMAX(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xa4 -#define PFMIN(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x94 -#define PFMUL(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xb4 -#define PFRCP(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x96 -#define PFRCPIT1(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xa6 -#define PFRCPIT2(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xb6 -#define PFRSQRT(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x97 -#define PFRSQIT1(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xa7 -#define PFSUB(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x9a -#define PFSUBR(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xaa -#define PI2FD(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0x0d -#define FEMMS db 0x0f, 0x0e -#define PAVGUSB(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xbf -#define PMULHRW(dst, src) db 0x0f, 0x0f, _k3d_MODRM(dst, src), 0xb7 -#define PREFETCH(src) db 0x0f, 0x0d, _k3d_pref_##src -#define PREFETCHW(src) db 0x0f, 0x0d, _k3d_prefw_##src -#define CPUID db 0x0f, 0xa2 - -/* Defines for new, K7 opcodes */ -#define PFNACC(dst,src) db 0x0f, 0x0f, _k3d_MODRM(dst,src), 0x8a -#define FPPNACC(dst,src) db 0x0f, 0x0f, _k3d_MODRM(dst,src), 0x8e -#define PSWAPD(dst,src) db 0x0f, 0x0f, _k3d_MODRM(dst,src), 0xbb -#define PMINUB(dst,src) db 0x0f, 0xda, _k3d_MODRM(dst,src) -#define PMAXUB(dst,src) db 0x0f, 0xde, _k3d_MODRM(dst,src) -#define PMINSW(dst,src) db 0x0f, 0xea, _k3d_MODRM(dst,src) -#define PMAXSW(dst,src) db 0x0f, 0xee, _k3d_MODRM(dst,src) -#define PMULHUW(dst,src) db 0x0f, 0xe4, _k3d_MODRM(dst,src) -#define PAVGB(dst,src) db 0x0f, 0xe0, _k3d_MODRM(dst,src) -#define PAVGW(dst,src) db 0x0f, 0xe3, _k3d_MODRM(dst,src) -#define PSADBW(dst,src) db 0x0f, 0xf6, _k3d_MODRM(dst,src) -#define PMOVMSKB(dst,src) db 0x0f, 0xd7, _k3d_MODRM(dst,src) -#define PMASKMOVQ(dst,src) db 0x0f, 0xf7, _k3d_MODRM(dst,src) -#define PINSRW(dst,src,msk) db 0x0f, 0xc4, _k3d_MODRM(dst,src), msk -#define PEXTRW(dst,src,msk) db 0x0f, 0xc5, _k3d_MODRM(dst,src), msk -#define PSHUFW(dst,src,msk) db 0x0f, 0x70, _k3d_MODRM(dst,src), msk -#define MOVNTQ(dst,src) db 0x0f, 0xe7, _k3d_MODRM(src,dst) -#define SFENCE db 0x0f, 0xae, 0xf8 - -/* Memory/offset versions of the opcodes */ -#define PF2IDM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x1d -#define PFACCM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xae -#define PFADDM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x9e -#define PFCMPEQM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xb0 -#define PFCMPGEM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x90 -#define PFCMPGTM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xa0 -#define PFMAXM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xa4 -#define PFMINM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x94 -#define PFMULM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xb4 -#define PFRCPM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x96 -#define PFRCPIT1M(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xa6 -#define PFRCPIT2M(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xb6 -#define PFRSQRTM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x97 -#define PFRSQIT1M(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xa7 -#define PFSUBM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x9a -#define PFSUBRM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xaa -#define PI2FDM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x0d -#define PAVGUSBM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xbf -#define PMULHRWM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xb7 - - -/* Memory/offset versions of the new, K7 opcodes */ -#define PFNACCM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x8a -#define FPPNACCM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0x8e -#define PSWAPDM(dst,src,off) db 0x0f, 0x0f, _k3d_MODRM(dst,src) | 0x40, off, 0xbb -#define PMINUBM(dst,src,off) db 0x0f, 0xda, _k3d_MODRM(dst,src) | 0x40, off -#define PMAXUBM(dst,src,off) db 0x0f, 0xde, _k3d_MODRM(dst,src) | 0x40, off -#define PMINSWM(dst,src,off) db 0x0f, 0xea, _k3d_MODRM(dst,src) | 0x40, off -#define PMAXSWM(dst,src,off) db 0x0f, 0xee, _k3d_MODRM(dst,src) | 0x40, off -#define PMULHUWM(dst,src,off) db 0x0f, 0xe4, _k3d_MODRM(dst,src) | 0x40, off -#define PAVGBM(dst,src,off) db 0x0f, 0xe0, _k3d_MODRM(dst,src) | 0x40, off -#define PAVGWM(dst,src,off) db 0x0f, 0xe3, _k3d_MODRM(dst,src) | 0x40, off -#define PSADBWM(dst,src,off) db 0x0f, 0xf6, _k3d_MODRM(dst,src) | 0x40, off -#define PMOVMSKBM(dst,src,off) db 0x0f, 0xd7, _k3d_MODRM(dst,src) | 0x40, off -#define PMASKMOVQM(dst,src,off) db 0x0f, 0xf7, _k3d_MODRM(dst,src) | 0x40, off -#define MOVNTQM(dst,src,off) db 0x0f, 0xe7, _k3d_MODRM(src,dst) | 0x40, off -#define PINSRWM(dst,src,off,msk) db 0x0f, 0xc4, _k3d_MODRM(dst,src) | 0x40, off, msk -#define PSHUFWM(dst,src,off,msk) db 0x0f, 0x70, _k3d_MODRM(dst,src) | 0x40, off, msk - - -/* Defines for 3DNow! instructions for use in pragmas */ -#define p_pf2id(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x1d -#define p_pfacc(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xae -#define p_pfadd(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x9e -#define p_pfcmpeq(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xb0 -#define p_pfcmpge(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x90 -#define p_pfcmpgt(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xa0 -#define p_pfmax(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xa4 -#define p_pfmin(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x94 -#define p_pfmul(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xb4 -#define p_pfrcp(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x96 -#define p_pfrcpit1(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xa6 -#define p_pfrcpit2(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xb6 -#define p_pfrsqrt(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x97 -#define p_pfrsqit1(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xa7 -#define p_pfsub(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x9a -#define p_pfsubr(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xaa -#define p_pi2fd(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0x0d -#define p_femms 0x0f 0x0e -#define p_pavgusb(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xbf -#define p_pmulhrw(dst,src) 0x0f 0x0f _k3d_MODRM(dst,src) 0xb7 -#define p_prefetch(src) 0x0f 0x0d _k3d_pref_##src -#define p_prefetchw(src) 0x0f 0x0d _k3d_prefw_##src -#define P_PFNACC(dst,src) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x8a -#define P_FPPNACC(dst,src) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x8e -#define P_PSWAPD(dst,src) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xbb -#define P_PMINUB(dst,src) 0x0f 0xda (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMAXUB(dst,src) 0x0f 0xde (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMINSW(dst,src) 0x0f 0xea (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMAXSW(dst,src) 0x0f 0xee (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMULHUW(dst,src) 0x0f 0xe4 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PAVGB(dst,src) 0x0f 0xe0 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PAVGW(dst,src) 0x0f 0xe3 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PSADBW(dst,src) 0x0f 0xf6 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMOVMSKB(dst,src) 0x0f 0xd7 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMASKMOVQ(dst,src) 0x0f 0xf7 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PINSRW(dst,src,msk) 0x0f 0xc4 (_k3d_MODRM(dst,src) | 0x40) off msk -#define P_PEXTRW(dst,src,msk) 0x0f 0xc5 (_k3d_MODRM(dst,src) | 0x40) off msk -#define P_PSHUFW(dst,src,msk) 0x0f 0x70 (_k3d_MODRM(dst,src) | 0x40) off msk -#define P_MOVNTQ(dst,src) 0x0f 0xe7 (_k3d_MODRM(src,dst) | 0x40) off - -#define P_PF2IDM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x1d -#define P_PFACCM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xae -#define P_PFADDM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x9e -#define P_PFCMPEQM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xb0 -#define P_PFCMPGEM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x90 -#define P_PFCMPGTM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xa0 -#define P_PFMAXM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xa4 -#define P_PFMINM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x94 -#define P_PFMULM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xb4 -#define P_PFRCPM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x96 -#define P_PFRCPIT1M(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xa6 -#define P_PFRCPIT2M(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xb6 -#define P_PFRSQRTM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x97 -#define P_PFRSQIT1M(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xa7 -#define P_PFSUBM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x9a -#define P_PFSUBRM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xaa -#define P_PI2FDM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x0d -#define P_PAVGUSBM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xbf -#define P_PMULHRWM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xb7 -#define P_PFNACCM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x8a -#define P_FPPNACCM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0x8e -#define P_PSWAPDM(dst,src,off) 0x0f 0x0f (_k3d_MODRM(dst,src) | 0x40) off 0xbb -#define P_PMINUBM(dst,src,off) 0x0f 0xda (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMAXUBM(dst,src,off) 0x0f 0xde (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMINSWM(dst,src,off) 0x0f 0xea (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMAXSWM(dst,src,off) 0x0f 0xee (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMULHUWM(dst,src,off) 0x0f 0xe4 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PAVGBM(dst,src,off) 0x0f 0xe0 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PAVGWM(dst,src,off) 0x0f 0xe3 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PSADBWM(dst,src,off) 0x0f 0xf6 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PMOVMSKBM(dst,src,off) 0x0f 0xd7 (_k3d_MODRM(dst,src) | 0x40) off -#define P_MOVNTQM(dst,src,off) 0x0f 0xe7 (_k3d_MODRM(src,dst) | 0x40) off -#define P_PMASKMOVQM(dst,src,off) 0x0f 0xf7 (_k3d_MODRM(dst,src) | 0x40) off -#define P_PINSRWM(dst,src,off,msk) 0x0f 0xc4 (_k3d_MODRM(dst,src) | 0x40) off msk -#define P_PSHUFWM(dst,src,off,msk) 0x0f 0x70 (_k3d_MODRM(dst,src) | 0x40) off msk - - -#define P_PF2ID(dst,src) p_pf2id(dst,src) -#define P_PFACC(dst,src) p_pfacc(dst,src) -#define P_PFADD(dst,src) p_pfadd(dst,src) -#define P_PFCMPEQ(dst,src) p_pfcmpeq(dst,src) -#define P_PFCMPGE(dst,src) p_pfcmpge(dst,src) -#define P_PFCMPGT(dst,src) p_pfcmpgt(dst,src) -#define P_PFMAX(dst,src) p_pfmax(dst,src) -#define P_PFMIN(dst,src) p_pfmin(dst,src) -#define P_PFMUL(dst,src) p_pfmul(dst,src) -#define P_PFRCP(dst,src) p_pfrcp(dst,src) -#define P_PFRCPIT1(dst,src) p_pfrcpit1(dst,src) -#define P_PFRCPIT2(dst,src) p_pfrcpit2(dst,src) -#define P_PFRSQRT(dst,src) p_pfrsqrt(dst,src) -#define P_PFRSQIT1(dst,src) p_pfrsqit1(dst,src) -#define P_PFSUB(dst,src) p_pfsub(dst,src) -#define P_PFSUBR(dst,src) p_pfsubr(dst,src) -#define P_PI2FD(dst,src) p_pi2fd(dst,src) -#define P_FEMMS p_femms -#define P_PAVGUSB(dst,src) p_pavgusb(dst,src) -#define P_PMULHRW(dst,src) p_pmulhrw(dst,src) -#define P_PREFETCH(src) p_prefetch(src) -#define P_PREFETCHW(src) p_prefetchw(src) -#define p_CPUID 0x0f 0xa2 -#define p_pf2idm(dst,src,off) P_PF2IDM(dst,src,off) -#define p_pfaccm(dst,src,off) P_PFACCM(dst,src,off) -#define p_pfaddm(dst,src,off) P_PFADDM(dst,src,off) -#define p_pfcmpeqm(dst,src,off) P_PFCMPEQM(dst,src,off) -#define p_pfcmpgem(dst,src,off) P_PFCMPGEM(dst,src,off) -#define p_pfcmpgtm(dst,src,off) P_PFCMPGTM(dst,src,off) -#define p_pfmaxm(dst,src,off) P_PFMAXM(dst,src,off) -#define p_pfminm(dst,src,off) P_PFMINM(dst,src,off) -#define p_pfmulm(dst,src,off) P_PFMULM(dst,src,off) -#define p_pfrcpm(dst,src,off) P_PFRCPM(dst,src,off) -#define p_pfrcpit1m(dst,src,off) P_PFRCPIT1M(dst,src,off) -#define p_pfrcpit2m(dst,src,off) P_PFRCPIT2M(dst,src,off) -#define p_pfrsqrtm(dst,src,off) P_PFRSQRTM(dst,src,off) -#define p_pfrsqit1m(dst,src,off) P_PFRSQIT1M(dst,src,off) -#define p_pfsubm(dst,src,off) P_PFSUBM(dst,src,off) -#define p_pfsubrm(dst,src,off) P_PFSUBRM(dst,src,off) -#define p_pi2fdm(dst,src,off) P_PI2FDM(dst,src,off) -#define p_pavgusbm(dst,src,off) P_PAVGUSBM(dst,src,off) -#define p_pmulhrwm(dst,src,off) P_PMULHRWM(dst,src,off) - -#define P_PFNACC(dst,src) p_pfnacc(dst,src) -#define P_FPPNACC(dst,src) p_pfpnacc(dst,src) -#define P_PSWAPD(dst,src) p_pswapd(dst,src) -#define P_PMINUB(dst,src) p_pminub(dst,src) -#define P_PMAXUB(dst,src) p_pmaxub(dst,src) -#define P_PMINSW(dst,src) p_pminsw(dst,src) -#define P_PMAXSW(dst,src) p_pmaxsw(dst,src) -#define P_PMULHUW(dst,src) p_pmulhuw(dst,src) -#define P_PAVGB(dst,src) p_pavgb(dst,src) -#define P_PAVGW(dst,src) p_avgw(dst,src) -#define P_PSADBW(dst,src) p_psadbw(dst,src) -#define P_PMOVMSKB(dst,src) p_pmovmskb(dst,src) -#define P_PMASKMOVQ(dst,src) p_pmaskmovq(dst,src) -#define P_PINSRW(dst,src,msk) p_pinsrw(dst,src) -#define P_PEXTRW(dst,src,msk) p_pextrw(dst,src) -#define P_PSHUFW(dst,src,msk) p_pshufw(dst,src) -#define P_MOVNTQ(dst,src) p_movntq(dst,src) - -#define P_PFNACCM(dst,src,off) p_pfnaccm(dst,src,off) -#define P_FPPNACCM(dst,src,off) p_pfpnaccm(dst,src,off) -#define P_PSWAPDM(dst,src,off) p_pswapdm(dst,src,off) -#define P_PMINUBM(dst,src,off) p_pminubm(dst,src,off) -#define P_PMAXUBM(dst,src,off) p_pmaxubm(dst,src,off) -#define P_PMINSWM(dst,src,off) p_pminswm(dst,src,off) -#define P_PMAXSWM(dst,src,off) p_pmaxswm(dst,src,off) -#define P_PMULHUWM(dst,src,off) p_pmulhuwm(dst,src,off) -#define P_PAVGBM(dst,src,off) p_pavgbm(dst,src,off) -#define P_PAVGWM(dst,src,off) p_avgwm(dst,src,off) -#define P_PSADBWM(dst,src,off) p_psadbwm(dst,src,off) -#define P_PMOVMSKBM(dst,src,off) p_pmovmskbm(dst,src,off) -#define P_PMASKMOVQM(dst,src,off) p_pmaskmovqm(dst,src,off) -#define P_PINSRWM(dst,src,off,msk) p_pinsrwm(dst,src,off,msk) -#define P_PSHUFWM(dst,src,off,msk) p_pshufwm(dst,src,off,msk) -#define P_MOVNTQM(dst,src,off) p_movntqm(dst,src,off) - -#elif defined (_MSC_VER) && !defined (__MWERKS__) -// The Microsoft Visual C++ version of the 3DNow! macros. - -// Stop the "no EMMS" warning, since it doesn't detect FEMMS properly -#pragma warning(disable:4799) - -// Defines for operands. -#define _K3D_MM0 0xc0 -#define _K3D_MM1 0xc1 -#define _K3D_MM2 0xc2 -#define _K3D_MM3 0xc3 -#define _K3D_MM4 0xc4 -#define _K3D_MM5 0xc5 -#define _K3D_MM6 0xc6 -#define _K3D_MM7 0xc7 -#define _K3D_mm0 0xc0 -#define _K3D_mm1 0xc1 -#define _K3D_mm2 0xc2 -#define _K3D_mm3 0xc3 -#define _K3D_mm4 0xc4 -#define _K3D_mm5 0xc5 -#define _K3D_mm6 0xc6 -#define _K3D_mm7 0xc7 -#define _K3D_EAX 0x00 -#define _K3D_ECX 0x01 -#define _K3D_EDX 0x02 -#define _K3D_EBX 0x03 -#define _K3D_ESI 0x06 -#define _K3D_EDI 0x07 -#define _K3D_eax 0x00 -#define _K3D_ecx 0x01 -#define _K3D_edx 0x02 -#define _K3D_ebx 0x03 -#define _K3D_esi 0x06 -#define _K3D_edi 0x07 - -// These defines are for compatibility with the previous version of the header file. -#define _K3D_M0 0xc0 -#define _K3D_M1 0xc1 -#define _K3D_M2 0xc2 -#define _K3D_M3 0xc3 -#define _K3D_M4 0xc4 -#define _K3D_M5 0xc5 -#define _K3D_M6 0xc6 -#define _K3D_M7 0xc7 -#define _K3D_m0 0xc0 -#define _K3D_m1 0xc1 -#define _K3D_m2 0xc2 -#define _K3D_m3 0xc3 -#define _K3D_m4 0xc4 -#define _K3D_m5 0xc5 -#define _K3D_m6 0xc6 -#define _K3D_m7 0xc7 -#define _K3D__EAX 0x00 -#define _K3D__ECX 0x01 -#define _K3D__EDX 0x02 -#define _K3D__EBX 0x03 -#define _K3D__ESI 0x06 -#define _K3D__EDI 0x07 -#define _K3D__eax 0x00 -#define _K3D__ecx 0x01 -#define _K3D__edx 0x02 -#define _K3D__ebx 0x03 -#define _K3D__esi 0x06 -#define _K3D__edi 0x07 - -// General 3DNow! instruction format that is supported by -// these macros. Note that only the most basic form of memory -// operands are supported by these macros. - -#define InjK3DOps(dst,src,inst) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0f \ - _asm _emit ((_K3D_##dst & 0x3f) << 3) | _K3D_##src \ - _asm _emit _3DNowOpcode##inst \ -} - -#define InjK3DMOps(dst,src,off,inst) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0f \ - _asm _emit (((_K3D_##dst & 0x3f) << 3) | _K3D_##src | 0x40) \ - _asm _emit off \ - _asm _emit _3DNowOpcode##inst \ -} - -#define InjMMXOps(dst,src,inst) \ -{ \ - _asm _emit 0x0f \ - _asm _emit _3DNowOpcode##inst \ - _asm _emit ((_K3D_##dst & 0x3f) << 3) | _K3D_##src \ -} - -#define InjMMXMOps(dst,src,off,inst) \ -{ \ - _asm _emit 0x0f \ - _asm _emit _3DNowOpcode##inst \ - _asm _emit (((_K3D_##dst & 0x3f) << 3) | _K3D_##src | 0x40) \ - _asm _emit off \ -} - -#define _3DNowOpcodePF2ID 0x1d -#define _3DNowOpcodePFACC 0xae -#define _3DNowOpcodePFADD 0x9e -#define _3DNowOpcodePFCMPEQ 0xb0 -#define _3DNowOpcodePFCMPGE 0x90 -#define _3DNowOpcodePFCMPGT 0xa0 -#define _3DNowOpcodePFMAX 0xa4 -#define _3DNowOpcodePFMIN 0x94 -#define _3DNowOpcodePFMUL 0xb4 -#define _3DNowOpcodePFRCP 0x96 -#define _3DNowOpcodePFRCPIT1 0xa6 -#define _3DNowOpcodePFRCPIT2 0xb6 -#define _3DNowOpcodePFRSQRT 0x97 -#define _3DNowOpcodePFRSQIT1 0xa7 -#define _3DNowOpcodePFSUB 0x9a -#define _3DNowOpcodePFSUBR 0xaa -#define _3DNowOpcodePI2FD 0x0d -#define _3DNowOpcodePAVGUSB 0xbf -#define _3DNowOpcodePMULHRW 0xb7 -#define _3DNowOpcodePFNACC 0x8a -#define _3DNowOpcodeFPPNACC 0x8e -#define _3DNowOpcodePSWAPD 0xbb -#define _3DNowOpcodePMINUB 0xda -#define _3DNowOpcodePMAXUB 0xde -#define _3DNowOpcodePMINSW 0xea -#define _3DNowOpcodePMAXSW 0xee -#define _3DNowOpcodePMULHUW 0xe4 -#define _3DNowOpcodePAVGB 0xe0 -#define _3DNowOpcodePAVGW 0xe3 -#define _3DNowOpcodePSADBW 0xf6 -#define _3DNowOpcodePMOVMSKB 0xd7 -#define _3DNowOpcodePMASKMOVQ 0xf7 -#define _3DNowOpcodePINSRW 0xc4 -#define _3DNowOpcodePEXTRW 0xc5 -#define _3DNowOpcodePSHUFW 0x70 -#define _3DNowOpcodeMOVNTQ 0xe7 -#define _3DNowOpcodePREFETCHT 0x18 - - -#define PF2ID(dst,src) InjK3DOps(dst, src, PF2ID) -#define PFACC(dst,src) InjK3DOps(dst, src, PFACC) -#define PFADD(dst,src) InjK3DOps(dst, src, PFADD) -#define PFCMPEQ(dst,src) InjK3DOps(dst, src, PFCMPEQ) -#define PFCMPGE(dst,src) InjK3DOps(dst, src, PFCMPGE) -#define PFCMPGT(dst,src) InjK3DOps(dst, src, PFCMPGT) -#define PFMAX(dst,src) InjK3DOps(dst, src, PFMAX) -#define PFMIN(dst,src) InjK3DOps(dst, src, PFMIN) -#define PFMUL(dst,src) InjK3DOps(dst, src, PFMUL) -#define PFRCP(dst,src) InjK3DOps(dst, src, PFRCP) -#define PFRCPIT1(dst,src) InjK3DOps(dst, src, PFRCPIT1) -#define PFRCPIT2(dst,src) InjK3DOps(dst, src, PFRCPIT2) -#define PFRSQRT(dst,src) InjK3DOps(dst, src, PFRSQRT) -#define PFRSQIT1(dst,src) InjK3DOps(dst, src, PFRSQIT1) -#define PFSUB(dst,src) InjK3DOps(dst, src, PFSUB) -#define PFSUBR(dst,src) InjK3DOps(dst, src, PFSUBR) -#define PI2FD(dst,src) InjK3DOps(dst, src, PI2FD) -#define PAVGUSB(dst,src) InjK3DOps(dst, src, PAVGUSB) -#define PMULHRW(dst,src) InjK3DOps(dst, src, PMULHRW) - -#define FEMMS \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0e \ -} - -#define PREFETCH(src) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0d \ - _asm _emit (_K3D_##src & 0x07) \ -} - -/* Prefetch with a short offset, < 127 or > -127 - Carefull! Doesn't check for your offset being - in range. */ - -#define PREFETCHM(src,off) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0d \ - _asm _emit (0x40 | (_K3D_##src & 0x07)) \ - _asm _emit off \ -} - -/* Prefetch with a long offset */ - -#define PREFETCHMLONG(src,off) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0d \ - _asm _emit (0x80 | (_K3D_##src & 0x07)) \ - _asm _emit (off & 0x000000ff) \ - _asm _emit (off & 0x0000ff00) >> 8 \ - _asm _emit (off & 0x00ff0000) >> 16 \ - _asm _emit (off & 0xff000000) >> 24 \ -} - -#define PREFETCHW(src) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0d \ - _asm _emit (0x08 | (_K3D_##src & 0x07)) \ -} - -#define PREFETCHWM(src,off) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0d \ - _asm _emit 0x48 | (_K3D_##src & 0x07) \ - _asm _emit off \ -} - -#define PREFETCHWMLONG(src,off) \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0x0d \ - _asm _emit 0x88 | (_K3D_##src & 0x07) \ - _asm _emit (off & 0x000000ff) \ - _asm _emit (off & 0x0000ff00) >> 8 \ - _asm _emit (off & 0x00ff0000) >> 16 \ - _asm _emit (off & 0xff000000) >> 24 \ -} - -#define CPUID \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0xa2 \ -} - - -/* Defines for new, K7 opcodes */ -#define SFENCE \ -{ \ - _asm _emit 0x0f \ - _asm _emit 0xae \ - _asm _emit 0xf8 \ -} - -#define PFNACC(dst,src) InjK3DOps(dst,src,PFNACC) -#define PFPNACC(dst,src) InjK3DOps(dst,src,PFPNACC) -#define PSWAPD(dst,src) InjK3DOps(dst,src,PSWAPD) -#define PMINUB(dst,src) InjMMXOps(dst,src,PMINUB) -#define PMAXUB(dst,src) InjMMXOps(dst,src,PMAXUB) -#define PMINSW(dst,src) InjMMXOps(dst,src,PMINSW) -#define PMAXSW(dst,src) InjMMXOps(dst,src,PMAXSW) -#define PMULHUW(dst,src) InjMMXOps(dst,src,PMULHUW) -#define PAVGB(dst,src) InjMMXOps(dst,src,PAVGB) -#define PAVGW(dst,src) InjMMXOps(dst,src,PAVGW) -#define PSADBW(dst,src) InjMMXOps(dst,src,PSADBW) -#define PMOVMSKB(dst,src) InjMMXOps(dst,src,PMOVMSKB) -#define PMASKMOVQ(dst,src) InjMMXOps(dst,src,PMASKMOVQ) -#define PINSRW(dst,src,msk) InjMMXOps(dst,src,PINSRW) _asm _emit msk -#define PEXTRW(dst,src,msk) InjMMXOps(dst,src,PEXTRW) _asm _emit msk -#define PSHUFW(dst,src,msk) InjMMXOps(dst,src,PSHUFW) _asm _emit msk -#define MOVNTQ(dst,src) InjMMXOps(src,dst,MOVNTQ) -#define PREFETCHNTA(mem) InjMMXOps(mm0,mem,PREFETCHT) -#define PREFETCHT0(mem) InjMMXOps(mm1,mem,PREFETCHT) -#define PREFETCHT1(mem) InjMMXOps(mm2,mem,PREFETCHT) -#define PREFETCHT2(mem) InjMMXOps(mm3,mem,PREFETCHT) - - -/* Memory/offset versions of the opcodes */ -#define PAVGUSBM(dst,src,off) InjK3DMOps(dst,src,off,PAVGUSB) -#define PF2IDM(dst,src,off) InjK3DMOps(dst,src,off,PF2ID) -#define PFACCM(dst,src,off) InjK3DMOps(dst,src,off,PFACC) -#define PFADDM(dst,src,off) InjK3DMOps(dst,src,off,PFADD) -#define PFCMPEQM(dst,src,off) InjK3DMOps(dst,src,off,PFCMPEQ) -#define PFCMPGEM(dst,src,off) InjK3DMOps(dst,src,off,PFCMPGE) -#define PFCMPGTM(dst,src,off) InjK3DMOps(dst,src,off,PFCMPGT) -#define PFMAXM(dst,src,off) InjK3DMOps(dst,src,off,PFMAX) -#define PFMINM(dst,src,off) InjK3DMOps(dst,src,off,PFMIN) -#define PFMULM(dst,src,off) InjK3DMOps(dst,src,off,PFMUL) -#define PFRCPM(dst,src,off) InjK3DMOps(dst,src,off,PFRCP) -#define PFRCPIT1M(dst,src,off) InjK3DMOps(dst,src,off,PFRCPIT1) -#define PFRCPIT2M(dst,src,off) InjK3DMOps(dst,src,off,PFRCPIT2) -#define PFRSQRTM(dst,src,off) InjK3DMOps(dst,src,off,PFRSQRT) -#define PFRSQIT1M(dst,src,off) InjK3DMOps(dst,src,off,PFRSQIT1) -#define PFSUBM(dst,src,off) InjK3DMOps(dst,src,off,PFSUB) -#define PFSUBRM(dst,src,off) InjK3DMOps(dst,src,off,PFSUBR) -#define PI2FDM(dst,src,off) InjK3DMOps(dst,src,off,PI2FD) -#define PMULHRWM(dst,src,off) InjK3DMOps(dst,src,off,PMULHRW) - - -/* Memory/offset versions of the K7 opcodes */ -#define PFNACCM(dst,src,off) InjK3DMOps(dst,src,off,PFNACC) -#define PFPNACCM(dst,src,off) InjK3DMOps(dst,src,off,PFPNACC) -#define PSWAPDM(dst,src,off) InjK3DMOps(dst,src,off,PSWAPD) -#define PMINUBM(dst,src,off) InjMMXMOps(dst,src,off,PMINUB) -#define PMAXUBM(dst,src,off) InjMMXMOps(dst,src,off,PMAXUB) -#define PMINSWM(dst,src,off) InjMMXMOps(dst,src,off,PMINSW) -#define PMAXSWM(dst,src,off) InjMMXMOps(dst,src,off,PMAXSW) -#define PMULHUWM(dst,src,off) InjMMXMOps(dst,src,off,PMULHUW) -#define PAVGBM(dst,src,off) InjMMXMOps(dst,src,off,PAVGB) -#define PAVGWM(dst,src,off) InjMMXMOps(dst,src,off,PAVGW) -#define PSADBWM(dst,src,off) InjMMXMOps(dst,src,off,PSADBW) -#define PMOVMSKBM(dst,src,off) InjMMXMOps(dst,src,off,PMOVMSKB) -#define PMASKMOVQM(dst,src,off) InjMMXMOps(dst,src,off,PMASKMOVQ) -#define PINSRWM(dst,src,off,msk) InjMMXMOps(dst,src,off,PINSRW) _asm _emit msk -#define PSHUFWM(dst,src,off,msk) InjMMXMOps(dst,src,off,PSHUFW) _asm _emit msk -#define MOVNTQM(dst,src,off) InjMMXMOps(src,dst,off,MOVNTQ) -#define PREFETCHNTAM(mem,off) InjMMXMOps(mm0,mem,off,PREFETCHT) -#define PREFETCHT0M(mem,off) InjMMXMOps(mm1,mem,off,PREFETCHT) -#define PREFETCHT1M(mem,off) InjMMXMOps(mm2,mem,off,PREFETCHT) -#define PREFETCHT2M(mem,off) InjMMXMOps(mm3,mem,off,PREFETCHT) - - -#else - -/* Assume built-in support for 3DNow! opcodes, replace macros with opcodes */ -#define PAVGUSB(dst,src) pavgusb dst,src -#define PF2ID(dst,src) pf2id dst,src -#define PFACC(dst,src) pfacc dst,src -#define PFADD(dst,src) pfadd dst,src -#define PFCMPEQ(dst,src) pfcmpeq dst,src -#define PFCMPGE(dst,src) pfcmpge dst,src -#define PFCMPGT(dst,src) pfcmpgt dst,src -#define PFMAX(dst,src) pfmax dst,src -#define PFMIN(dst,src) pfmin dst,src -#define PFMUL(dst,src) pfmul dst,src -#define PFRCP(dst,src) pfrcp dst,src -#define PFRCPIT1(dst,src) pfrcpit1 dst,src -#define PFRCPIT2(dst,src) pfrcpit2 dst,src -#define PFRSQRT(dst,src) pfrsqrt dst,src -#define PFRSQIT1(dst,src) pfrsqit1 dst,src -#define PFSUB(dst,src) pfsub dst,src -#define PFSUBR(dst,src) pfsubr dst,src -#define PI2FD(dst,src) pi2fd dst,src -#define PMULHRW(dst,src) pmulhrw dst,src -#define PREFETCH(src) prefetch src -#define PREFETCHW(src) prefetchw src - -#define PAVGUSBM(dst,src,off) pavgusb dst,[src+off] -#define PF2IDM(dst,src,off) PF2ID dst,[src+off] -#define PFACCM(dst,src,off) PFACC dst,[src+off] -#define PFADDM(dst,src,off) PFADD dst,[src+off] -#define PFCMPEQM(dst,src,off) PFCMPEQ dst,[src+off] -#define PFCMPGEM(dst,src,off) PFCMPGE dst,[src+off] -#define PFCMPGTM(dst,src,off) PFCMPGT dst,[src+off] -#define PFMAXM(dst,src,off) PFMAX dst,[src+off] -#define PFMINM(dst,src,off) PFMIN dst,[src+off] -#define PFMULM(dst,src,off) PFMUL dst,[src+off] -#define PFRCPM(dst,src,off) PFRCP dst,[src+off] -#define PFRCPIT1M(dst,src,off) PFRCPIT1 dst,[src+off] -#define PFRCPIT2M(dst,src,off) PFRCPIT2 dst,[src+off] -#define PFRSQRTM(dst,src,off) PFRSQRT dst,[src+off] -#define PFRSQIT1M(dst,src,off) PFRSQIT1 dst,[src+off] -#define PFSUBM(dst,src,off) PFSUB dst,[src+off] -#define PFSUBRM(dst,src,off) PFSUBR dst,[src+off] -#define PI2FDM(dst,src,off) PI2FD dst,[src+off] -#define PMULHRWM(dst,src,off) PMULHRW dst,[src+off] - - -#if defined (__MWERKS__) -// At the moment, CodeWarrior does not support these opcodes, so hand-assemble them - -// Defines for operands. -#define _K3D_MM0 0xc0 -#define _K3D_MM1 0xc1 -#define _K3D_MM2 0xc2 -#define _K3D_MM3 0xc3 -#define _K3D_MM4 0xc4 -#define _K3D_MM5 0xc5 -#define _K3D_MM6 0xc6 -#define _K3D_MM7 0xc7 -#define _K3D_mm0 0xc0 -#define _K3D_mm1 0xc1 -#define _K3D_mm2 0xc2 -#define _K3D_mm3 0xc3 -#define _K3D_mm4 0xc4 -#define _K3D_mm5 0xc5 -#define _K3D_mm6 0xc6 -#define _K3D_mm7 0xc7 -#define _K3D_EAX 0x00 -#define _K3D_ECX 0x01 -#define _K3D_EDX 0x02 -#define _K3D_EBX 0x03 -#define _K3D_ESI 0x06 -#define _K3D_EDI 0x07 -#define _K3D_eax 0x00 -#define _K3D_ecx 0x01 -#define _K3D_edx 0x02 -#define _K3D_ebx 0x03 -#define _K3D_esi 0x06 -#define _K3D_edi 0x07 -#define _K3D_EAX 0x00 -#define _K3D_ECX 0x01 -#define _K3D_EDX 0x02 -#define _K3D_EBX 0x03 -#define _K3D_ESI 0x06 -#define _K3D_EDI 0x07 -#define _K3D_eax 0x00 -#define _K3D_ecx 0x01 -#define _K3D_edx 0x02 -#define _K3D_ebx 0x03 -#define _K3D_esi 0x06 -#define _K3D_edi 0x07 - -#define InjK3DOps(dst,src,inst) \ - db 0x0f, 0x0f, (((_K3D_##dst & 0x3f) << 3) | _K3D_##src), _3DNowOpcode##inst - -#define InjK3DMOps(dst,src,off,inst) \ - db 0x0f, 0x0f, (((_K3D_##dst & 0x3f) << 3) | _K3D_##src | 0x40), off, _3DNowOpcode##inst - -#define InjMMXOps(dst,src,inst) \ - db 0x0f, _3DNowOpcode##inst, (((_K3D_##dst & 0x3f) << 3) | _K3D_##src) - -#define InjMMXMOps(dst,src,off,inst) \ - db 0x0f, _3DNowOpcode##inst, (((_K3D_##dst & 0x3f) << 3) | _K3D_##src | 0x40), off - -#define PFNACC(dst,src) InjK3DOps(dst,src,PFNACC) -#define PFPNACC(dst,src) InjK3DOps(dst,src,PFPNACC) -#define PSWAPD(dst,src) InjK3DOps(dst,src,PSWAPD) -#define PMINUB(dst,src) InjMMXOps(dst,src,PMINUB) -#define PMAXUB(dst,src) InjMMXOps(dst,src,PMAXUB) -#define PMINSW(dst,src) InjMMXOps(dst,src,PMINSW) -#define PMAXSW(dst,src) InjMMXOps(dst,src,PMAXSW) -#define PMULHUW(dst,src) InjMMXOps(dst,src,PMULHUW) -#define PAVGB(dst,src) InjMMXOps(dst,src,PAVGB) -#define PAVGW(dst,src) InjMMXOps(dst,src,PAVGW) -#define PSADBW(dst,src) InjMMXOps(dst,src,PSADBW) -#define PMOVMSKB(dst,src) InjMMXOps(dst,src,PMOVMSKB) -#define PMASKMOVQ(dst,src) InjMMXOps(dst,src,PMASKMOVQ) -#define PINSRW(dst,src,msk) InjMMXOps(dst,src,PINSRW) db msk -#define PEXTRW(dst,src,msk) InjMMXOps(dst,src,PEXTRW) db msk -#define PSHUFW(dst,src,msk) InjMMXOps(dst,src,PSHUFW) db msk -#define MOVNTQ(dst,src) InjMMXOps(src,dst,MOVNTQ) -#define PREFETCHNTA(mem) InjMMXOps(mm0,mem,PREFETCHT) -#define PREFETCHT0(mem) InjMMXOps(mm1,mem,PREFETCHT) -#define PREFETCHT1(mem) InjMMXOps(mm2,mem,PREFETCHT) -#define PREFETCHT2(mem) InjMMXOps(mm3,mem,PREFETCHT) - - -/* Memory/offset versions of the K7 opcodes */ -#define PFNACCM(dst,src,off) InjK3DMOps(dst,src,off,PFNACC) -#define PFPNACCM(dst,src,off) InjK3DMOps(dst,src,off,PFPNACC) -#define PSWAPDM(dst,src,off) InjK3DMOps(dst,src,off,PSWAPD) -#define PMINUBM(dst,src,off) InjMMXMOps(dst,src,off,PMINUB) -#define PMAXUBM(dst,src,off) InjMMXMOps(dst,src,off,PMAXUB) -#define PMINSWM(dst,src,off) InjMMXMOps(dst,src,off,PMINSW) -#define PMAXSWM(dst,src,off) InjMMXMOps(dst,src,off,PMAXSW) -#define PMULHUWM(dst,src,off) InjMMXMOps(dst,src,off,PMULHUW) -#define PAVGBM(dst,src,off) InjMMXMOps(dst,src,off,PAVGB) -#define PAVGWM(dst,src,off) InjMMXMOps(dst,src,off,PAVGW) -#define PSADBWM(dst,src,off) InjMMXMOps(dst,src,off,PSADBW) -#define PMOVMSKBM(dst,src,off) InjMMXMOps(dst,src,off,PMOVMSKB) -#define PMASKMOVQM(dst,src,off) InjMMXMOps(dst,src,off,PMASKMOVQ) -#define PINSRWM(dst,src,off,msk) InjMMXMOps(dst,src,off,PINSRW), msk -#define PEXTRWM(dst,src,off,msk) InjMMXMOps(dst,src,off,PEXTRW), msk -#define PSHUFWM(dst,src,off,msk) InjMMXMOps(dst,src,off,PSHUFW), msk -#define MOVNTQM(dst,src,off) InjMMXMOps(src,dst,off,MOVNTQ) -#define PREFETCHNTAM(mem,off) InjMMXMOps(mm0,mem,off,PREFETCHT) -#define PREFETCHT0M(mem,off) InjMMXMOps(mm1,mem,off,PREFETCHT) -#define PREFETCHT1M(mem,off) InjMMXMOps(mm2,mem,off,PREFETCHT) -#define PREFETCHT2M(mem,off) InjMMXMOps(mm3,mem,off,PREFETCHT) - - -#else - -#define PFNACC(dst,src) PFNACC dst,src -#define PFPNACC(dst,src) PFPNACC dst,src -#define PSWAPD(dst,src) PSWAPD dst,src -#define PMINUB(dst,src) PMINUB dst,src -#define PMAXUB(dst,src) PMAXUB dst,src -#define PMINSW(dst,src) PMINSW dst,src -#define PMAXSW(dst,src) PMAXSW dst,src -#define PMULHUW(dst,src) PMULHUW dst,src -#define PAVGB(dst,src) PAVGB dst,src -#define PAVGW(dst,src) PAVGW dst,src -#define PSADBW(dst,src) PSADBW dst,src -#define PMOVMSKB(dst,src) PMOVMSKB dst,src -#define PMASKMOVQ(dst,src) PMASKMOVQ dst,src -#define PINSRW(dst,src,msk) PINSRW dst,src,msk -#define PEXTRW(dst,src,msk) PEXTRW dst,src,msk -#define PSHUFW(dst,src,msk) PSHUFW dst,src,msk -#define MOVNTQ(dst,src) MOVNTQ dst,src - -#define PFNACCM(dst,src,off) PFNACC dst,[src+off] -#define PFPNACCM(dst,src,off) PFPNACC dst,[src+off] -#define PSWAPDM(dst,src,off) PSWAPD dst,[src+off] -#define PMINUBM(dst,src,off) PMINUB dst,[src+off] -#define PMAXUBM(dst,src,off) PMAXUB dst,[src+off] -#define PMINSWM(dst,src,off) PMINSW dst,[src+off] -#define PMAXSWM(dst,src,off) PMAXSW dst,[src+off] -#define PMULHUWM(dst,src,off) PMULHUW dst,[src+off] -#define PAVGBM(dst,src,off) PAVGB dst,[src+off] -#define PAVGWM(dst,src,off) PAVGW dst,[src+off] -#define PSADBWM(dst,src,off) PSADBW dst,[src+off] -#define PMOVMSKBM(dst,src,off) PMOVMSKB dst,[src+off] -#define PMASKMOVQM(dst,src,off) PMASKMOVQ dst,[src+off] -#define PINSRWM(dst,src,off,msk) PINSRW dst,[src+off],msk -#define PEXTRWM(dst,src,off,msk) PEXTRW dst,[src+off],msk -#define PSHUFWM(dst,src,off,msk) PSHUFW dst,[src+off],msk -#define MOVNTQM(dst,src,off) MOVNTQ dst,[src+off] - -#endif - -#endif - -/* Just to deal with lower case. */ -#define pf2id(dst,src) PF2ID(dst,src) -#define pfacc(dst,src) PFACC(dst,src) -#define pfadd(dst,src) PFADD(dst,src) -#define pfcmpeq(dst,src) PFCMPEQ(dst,src) -#define pfcmpge(dst,src) PFCMPGE(dst,src) -#define pfcmpgt(dst,src) PFCMPGT(dst,src) -#define pfmax(dst,src) PFMAX(dst,src) -#define pfmin(dst,src) PFMIN(dst,src) -#define pfmul(dst,src) PFMUL(dst,src) -#define pfrcp(dst,src) PFRCP(dst,src) -#define pfrcpit1(dst,src) PFRCPIT1(dst,src) -#define pfrcpit2(dst,src) PFRCPIT2(dst,src) -#define pfrsqrt(dst,src) PFRSQRT(dst,src) -#define pfrsqit1(dst,src) PFRSQIT1(dst,src) -#define pfsub(dst,src) PFSUB(dst,src) -#define pfsubr(dst,src) PFSUBR(dst,src) -#define pi2fd(dst,src) PI2FD(dst,src) -#define femms FEMMS -#define pavgusb(dst,src) PAVGUSB(dst,src) -#define pmulhrw(dst,src) PMULHRW(dst,src) -#define prefetch(src) PREFETCH(src) -#define prefetchw(src) PREFETCHW(src) - -#define prefetchm(src,off) PREFETCHM(src,off) -#define prefetchmlong(src,off) PREFETCHMLONG(src,off) -#define prefetchwm(src,off) PREFETCHWM(src,off) -#define prefetchwmlong(src,off) PREFETCHWMLONG(src,off) - -#define pfnacc(dst,src) PFNACC(dst,src) -#define pfpnacc(dst,src) PFPNACC(dst,src) -#define pswapd(dst,src) PSWAPD(dst,src) -#define pminub(dst,src) PMINUB(dst,src) -#define pmaxub(dst,src) PMAXUB(dst,src) -#define pminsw(dst,src) PMINSW(dst,src) -#define pmaxsw(dst,src) PMAXSW(dst,src) -#define pmulhuw(dst,src) PMULHUW(dst,src) -#define pavgb(dst,src) PAVGB(dst,src) -#define pavgw(dst,src) PAVGW(dst,src) -#define psadbw(dst,src) PSADBW(dst,src) -#define pmovmskb(dst,src) PMOVMSKB(dst,src) -#define pmaskmovq(dst,src) PMASKMOVQ(dst,src) -#define pinsrw(dst,src,msk) PINSRW(dst,src,msk) -#define pextrw(dst,src,msk) PEXTRW(dst,src,msk) -#define pshufw(dst,src,msk) PSHUFW(dst,src,msk) -#define movntq(dst,src) MOVNTQ(dst,src) -#define prefetchnta(mem) PREFETCHNTA(mem) -#define prefetcht0(mem) PREFETCHT0(mem) -#define prefetcht1(mem) PREFETCHT1(mem) -#define prefetcht2(mem) PREFETCHT2(mem) - - -#define pavgusbm(dst,src,off) PAVGUSBM(dst,src,off) -#define pf2idm(dst,src,off) PF2IDM(dst,src,off) -#define pfaccm(dst,src,off) PFACCM(dst,src,off) -#define pfaddm(dst,src,off) PFADDM(dst,src,off) -#define pfcmpeqm(dst,src,off) PFCMPEQM(dst,src,off) -#define pfcmpgem(dst,src,off) PFCMPGEM(dst,src,off) -#define pfcmpgtm(dst,src,off) PFCMPGTM(dst,src,off) -#define pfmaxm(dst,src,off) PFMAXM(dst,src,off) -#define pfminm(dst,src,off) PFMINM(dst,src,off) -#define pfmulm(dst,src,off) PFMULM(dst,src,off) -#define pfrcpm(dst,src,off) PFRCPM(dst,src,off) -#define pfrcpit1m(dst,src,off) PFRCPIT1M(dst,src,off) -#define pfrcpit2m(dst,src,off) PFRCPIT2M(dst,src,off) -#define pfrsqrtm(dst,src,off) PFRSQRTM(dst,src,off) -#define pfrsqit1m(dst,src,off) PFRSQIT1M(dst,src,off) -#define pfsubm(dst,src,off) PFSUBM(dst,src,off) -#define pfsubrm(dst,src,off) PFSUBRM(dst,src,off) -#define pi2fdm(dst,src,off) PI2FDM(dst,src,off) -#define pmulhrwm(dst,src,off) PMULHRWM(dst,src,off) -#define cpuid CPUID -#define sfence SFENCE - -#define pfnaccm(dst,src,off) PFNACCM(dst,src,off) -#define pfpnaccm(dst,src,off) PFPNACCM(dst,src,off) -#define pswapdm(dst,src,off) PSWAPDM(dst,src,off) -#define pminubm(dst,src,off) PMINUBM(dst,src,off) -#define pmaxubm(dst,src,off) PMAXUBM(dst,src,off) -#define pminswm(dst,src,off) PMINSWM(dst,src,off) -#define pmaxswm(dst,src,off) PMAXSWM(dst,src,off) -#define pmulhuwm(dst,src,off) PMULHUWM(dst,src,off) -#define pavgbm(dst,src,off) PAVGBM(dst,src,off) -#define pavgwm(dst,src,off) PAVGWM(dst,src,off) -#define psadbwm(dst,src,off) PSADBWM(dst,src,off) -#define pmovmskbm(dst,src,off) PMOVMSKBM(dst,src,off) -#define pmaskmovqm(dst,src,off) PMASKMOVQM(dst,src,off) -#define pinsrwm(dst,src,off,msk) PINSRWM(dst,src,off,msk) -#define pextrwm(dst,src,off,msk) PEXTRWM(dst,src,off,msk) -#define pshufwm(dst,src,off,msk) PSHUFWM(dst,src,off,msk) -#define movntqm(dst,src,off) MOVNTQM(dst,src,off) -#define prefetchntam(mem,off) PREFETCHNTA(mem,off) -#define prefetcht0m(mem,off) PREFETCHT0(mem,off) -#define prefetcht1m(mem,off) PREFETCHT1(mem,off) -#define prefetcht2m(mem,off) PREFETCHT2(mem,off) - -#endif diff --git a/Resources/NetHook/mathlib/anorms.h b/Resources/NetHook/mathlib/anorms.h deleted file mode 100644 index 873b5db6..00000000 --- a/Resources/NetHook/mathlib/anorms.h +++ /dev/null @@ -1,25 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#ifndef ANORMS_H -#define ANORMS_H -#ifdef _WIN32 -#pragma once -#endif - - -#include "mathlib/vector.h" - - -#define NUMVERTEXNORMALS 162 - -// the angle between consecutive g_anorms[] vectors is ~14.55 degrees -#define VERTEXNORMAL_CONE_INNER_ANGLE DEG2RAD(7.275) - -extern Vector g_anorms[NUMVERTEXNORMALS]; - - -#endif // ANORMS_H diff --git a/Resources/NetHook/mathlib/bumpvects.h b/Resources/NetHook/mathlib/bumpvects.h deleted file mode 100644 index 8eb6f030..00000000 --- a/Resources/NetHook/mathlib/bumpvects.h +++ /dev/null @@ -1,37 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef BUMPVECTS_H -#define BUMPVECTS_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "mathlib/mathlib.h" - -#define OO_SQRT_2 0.70710676908493042f -#define OO_SQRT_3 0.57735025882720947f -#define OO_SQRT_6 0.40824821591377258f -// sqrt( 2 / 3 ) -#define OO_SQRT_2_OVER_3 0.81649661064147949f - -#define NUM_BUMP_VECTS 3 - -const TableVector g_localBumpBasis[NUM_BUMP_VECTS] = -{ - { OO_SQRT_2_OVER_3, 0.0f, OO_SQRT_3 }, - { -OO_SQRT_6, OO_SQRT_2, OO_SQRT_3 }, - { -OO_SQRT_6, -OO_SQRT_2, OO_SQRT_3 } -}; - -void GetBumpNormals( const Vector& sVect, const Vector& tVect, const Vector& flatNormal, - const Vector& phongNormal, Vector bumpNormals[NUM_BUMP_VECTS] ); - -#endif // BUMPVECTS_H diff --git a/Resources/NetHook/mathlib/compressed_3d_unitvec.h b/Resources/NetHook/mathlib/compressed_3d_unitvec.h deleted file mode 100644 index f118ae17..00000000 --- a/Resources/NetHook/mathlib/compressed_3d_unitvec.h +++ /dev/null @@ -1,284 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef _3D_UNITVEC_H -#define _3D_UNITVEC_H - - -#define UNITVEC_DECLARE_STATICS \ - float cUnitVector::mUVAdjustment[0x2000]; \ - Vector cUnitVector::mTmpVec; - -// upper 3 bits -#define SIGN_MASK 0xe000 -#define XSIGN_MASK 0x8000 -#define YSIGN_MASK 0x4000 -#define ZSIGN_MASK 0x2000 - -// middle 6 bits - xbits -#define TOP_MASK 0x1f80 - -// lower 7 bits - ybits -#define BOTTOM_MASK 0x007f - -// unitcomp.cpp : A Unit Vector to 16-bit word conversion -// algorithm based on work of Rafael Baptista (rafael@oroboro.com) -// Accuracy improved by O.D. (punkfloyd@rocketmail.com) -// Used with Permission. - -// a compressed unit vector. reasonable fidelty for unit -// vectors in a 16 bit package. Good enough for surface normals -// we hope. -class cUnitVector // : public c3dMathObject -{ -public: - cUnitVector() { mVec = 0; } - cUnitVector( const Vector& vec ) - { - packVector( vec ); - } - cUnitVector( unsigned short val ) { mVec = val; } - - cUnitVector& operator=( const Vector& vec ) - { packVector( vec ); return *this; } - - operator Vector() - { - unpackVector( mTmpVec ); - return mTmpVec; - } - - void packVector( const Vector& vec ) - { - // convert from Vector to cUnitVector - - Assert( vec.IsValid()); - Vector tmp = vec; - - // input vector does not have to be unit length - // Assert( tmp.length() <= 1.001f ); - - mVec = 0; - if ( tmp.x < 0 ) { mVec |= XSIGN_MASK; tmp.x = -tmp.x; } - if ( tmp.y < 0 ) { mVec |= YSIGN_MASK; tmp.y = -tmp.y; } - if ( tmp.z < 0 ) { mVec |= ZSIGN_MASK; tmp.z = -tmp.z; } - - // project the normal onto the plane that goes through - // X0=(1,0,0),Y0=(0,1,0),Z0=(0,0,1). - // on that plane we choose an (projective!) coordinate system - // such that X0->(0,0), Y0->(126,0), Z0->(0,126),(0,0,0)->Infinity - - // a little slower... old pack was 4 multiplies and 2 adds. - // This is 2 multiplies, 2 adds, and a divide.... - float w = 126.0f / ( tmp.x + tmp.y + tmp.z ); - long xbits = (long)( tmp.x * w ); - long ybits = (long)( tmp.y * w ); - - Assert( xbits < 127 ); - Assert( xbits >= 0 ); - Assert( ybits < 127 ); - Assert( ybits >= 0 ); - - // Now we can be sure that 0<=xp<=126, 0<=yp<=126, 0<=xp+yp<=126 - // however for the sampling we want to transform this triangle - // into a rectangle. - if ( xbits >= 64 ) - { - xbits = 127 - xbits; - ybits = 127 - ybits; - } - - // now we that have xp in the range (0,127) and yp in - // the range (0,63), we can pack all the bits together - mVec |= ( xbits << 7 ); - mVec |= ybits; - } - - void unpackVector( Vector& vec ) - { - // if we do a straightforward backward transform - // we will get points on the plane X0,Y0,Z0 - // however we need points on a sphere that goes through - // these points. Therefore we need to adjust x,y,z so - // that x^2+y^2+z^2=1 by normalizing the vector. We have - // already precalculated the amount by which we need to - // scale, so all we do is a table lookup and a - // multiplication - - // get the x and y bits - long xbits = (( mVec & TOP_MASK ) >> 7 ); - long ybits = ( mVec & BOTTOM_MASK ); - - // map the numbers back to the triangle (0,0)-(0,126)-(126,0) - if (( xbits + ybits ) >= 127 ) - { - xbits = 127 - xbits; - ybits = 127 - ybits; - } - - // do the inverse transform and normalization - // costs 3 extra multiplies and 2 subtracts. No big deal. - float uvadj = mUVAdjustment[mVec & ~SIGN_MASK]; - vec.x = uvadj * (float) xbits; - vec.y = uvadj * (float) ybits; - vec.z = uvadj * (float)( 126 - xbits - ybits ); - - // set all the sign bits - if ( mVec & XSIGN_MASK ) vec.x = -vec.x; - if ( mVec & YSIGN_MASK ) vec.y = -vec.y; - if ( mVec & ZSIGN_MASK ) vec.z = -vec.z; - - Assert( vec.IsValid()); - } - - static void initializeStatics() - { - for ( int idx = 0; idx < 0x2000; idx++ ) - { - long xbits = idx >> 7; - long ybits = idx & BOTTOM_MASK; - - // map the numbers back to the triangle (0,0)-(0,127)-(127,0) - if (( xbits + ybits ) >= 127 ) - { - xbits = 127 - xbits; - ybits = 127 - ybits; - } - - // convert to 3D vectors - float x = (float)xbits; - float y = (float)ybits; - float z = (float)( 126 - xbits - ybits ); - - // calculate the amount of normalization required - mUVAdjustment[idx] = 1.0f / sqrtf( y*y + z*z + x*x ); - Assert( _finite( mUVAdjustment[idx])); - - //cerr << mUVAdjustment[idx] << "\t"; - //if ( xbits == 0 ) cerr << "\n"; - } - } - -#if 0 - void test() - { - #define TEST_RANGE 4 - #define TEST_RANDOM 100 - #define TEST_ANGERROR 1.0 - - float maxError = 0; - float avgError = 0; - int numVecs = 0; - - {for ( int x = -TEST_RANGE; x < TEST_RANGE; x++ ) - { - for ( int y = -TEST_RANGE; y < TEST_RANGE; y++ ) - { - for ( int z = -TEST_RANGE; z < TEST_RANGE; z++ ) - { - if (( x + y + z ) == 0 ) continue; - - Vector vec( (float)x, (float)y, (float)z ); - Vector vec2; - - vec.normalize(); - packVector( vec ); - unpackVector( vec2 ); - - float ang = vec.dot( vec2 ); - ang = (( fabs( ang ) > 0.99999f ) ? 0 : (float)acos(ang)); - - if (( ang > TEST_ANGERROR ) | ( !_finite( ang ))) - { - cerr << "error: " << ang << endl; - cerr << "orig vec: " << vec.x << ",\t" - << vec.y << ",\t" << vec.z << "\tmVec: " - << mVec << endl; - cerr << "quantized vec2: " << vec2.x - << ",\t" << vec2.y << ",\t" - << vec2.z << endl << endl; - } - avgError += ang; - numVecs++; - if ( maxError < ang ) maxError = ang; - } - } - }} - - for ( int w = 0; w < TEST_RANDOM; w++ ) - { - Vector vec( genRandom(), genRandom(), genRandom()); - Vector vec2; - vec.normalize(); - - packVector( vec ); - unpackVector( vec2 ); - - float ang =vec.dot( vec2 ); - ang = (( ang > 0.999f ) ? 0 : (float)acos(ang)); - - if (( ang > TEST_ANGERROR ) | ( !_finite( ang ))) - { - cerr << "error: " << ang << endl; - cerr << "orig vec: " << vec.x << ",\t" - << vec.y << ",\t" << vec.z << "\tmVec: " - << mVec << endl; - cerr << "quantized vec2: " << vec2.x << ",\t" - << vec2.y << ",\t" - << vec2.z << endl << endl; - } - avgError += ang; - numVecs++; - if ( maxError < ang ) maxError = ang; - } - - { for ( int x = 0; x < 50; x++ ) - { - Vector vec( (float)x, 25.0f, 0.0f ); - Vector vec2; - - vec.normalize(); - packVector( vec ); - unpackVector( vec2 ); - - float ang = vec.dot( vec2 ); - ang = (( fabs( ang ) > 0.999f ) ? 0 : (float)acos(ang)); - - if (( ang > TEST_ANGERROR ) | ( !_finite( ang ))) - { - cerr << "error: " << ang << endl; - cerr << "orig vec: " << vec.x << ",\t" - << vec.y << ",\t" << vec.z << "\tmVec: " - << mVec << endl; - cerr << " quantized vec2: " << vec2.x << ",\t" - << vec2.y << ",\t" << vec2.z << endl << endl; - } - - avgError += ang; - numVecs++; - if ( maxError < ang ) maxError = ang; - }} - - cerr << "max angle error: " << maxError - << ", average error: " << avgError / numVecs - << ", num tested vecs: " << numVecs << endl; - } - - friend ostream& operator<< ( ostream& os, const cUnitVector& vec ) - { os << vec.mVec; return os; } -#endif - -//protected: // !!!! - - unsigned short mVec; - static float mUVAdjustment[0x2000]; - static Vector mTmpVec; -}; - -#endif // _3D_VECTOR_H - - diff --git a/Resources/NetHook/mathlib/compressed_light_cube.h b/Resources/NetHook/mathlib/compressed_light_cube.h deleted file mode 100644 index 81a638e0..00000000 --- a/Resources/NetHook/mathlib/compressed_light_cube.h +++ /dev/null @@ -1,24 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#ifndef COMPRESSED_LIGHT_CUBE_H -#define COMPRESSED_LIGHT_CUBE_H -#ifdef _WIN32 -#pragma once -#endif - - -#include "mathlib/mathlib.h" - - -struct CompressedLightCube -{ - DECLARE_BYTESWAP_DATADESC(); - ColorRGBExp32 m_Color[6]; -}; - - -#endif // COMPRESSED_LIGHT_CUBE_H diff --git a/Resources/NetHook/mathlib/compressed_vector.h b/Resources/NetHook/mathlib/compressed_vector.h deleted file mode 100644 index 4dfb0f90..00000000 --- a/Resources/NetHook/mathlib/compressed_vector.h +++ /dev/null @@ -1,608 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef COMPRESSED_VECTOR_H -#define COMPRESSED_VECTOR_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include - -// For vec_t, put this somewhere else? -#include "basetypes.h" - -// For rand(). We really need a library! -#include - -#include "tier0/dbg.h" -#include "mathlib/vector.h" - -#include "mathlib/mathlib.h" - -#if defined( _X360 ) -#pragma bitfield_order( push, lsb_to_msb ) -#endif -//========================================================= -// fit a 3D vector into 32 bits -//========================================================= - -class Vector32 -{ -public: - // Construction/destruction: - Vector32(void); - Vector32(vec_t X, vec_t Y, vec_t Z); - - // assignment - Vector32& operator=(const Vector &vOther); - operator Vector (); - -private: - unsigned short x:10; - unsigned short y:10; - unsigned short z:10; - unsigned short exp:2; -}; - -inline Vector32& Vector32::operator=(const Vector &vOther) -{ - CHECK_VALID(vOther); - - static float expScale[4] = { 4.0f, 16.0f, 32.f, 64.f }; - - float fmax = max( fabs( vOther.x ), fabs( vOther.y ) ); - fmax = max( fmax, fabs( vOther.z ) ); - - for (exp = 0; exp < 3; exp++) - { - if (fmax < expScale[exp]) - break; - } - Assert( fmax < expScale[exp] ); - - float fexp = 512.0f / expScale[exp]; - - x = clamp( (int)(vOther.x * fexp) + 512, 0, 1023 ); - y = clamp( (int)(vOther.y * fexp) + 512, 0, 1023 ); - z = clamp( (int)(vOther.z * fexp) + 512, 0, 1023 ); - return *this; -} - - -inline Vector32::operator Vector () -{ - Vector tmp; - - static float expScale[4] = { 4.0f, 16.0f, 32.f, 64.f }; - - float fexp = expScale[exp] / 512.0f; - - tmp.x = (((int)x) - 512) * fexp; - tmp.y = (((int)y) - 512) * fexp; - tmp.z = (((int)z) - 512) * fexp; - return tmp; -} - - -//========================================================= -// Fit a unit vector into 32 bits -//========================================================= - -class Normal32 -{ -public: - // Construction/destruction: - Normal32(void); - Normal32(vec_t X, vec_t Y, vec_t Z); - - // assignment - Normal32& operator=(const Vector &vOther); - operator Vector (); - -private: - unsigned short x:15; - unsigned short y:15; - unsigned short zneg:1; -}; - - -inline Normal32& Normal32::operator=(const Vector &vOther) -{ - CHECK_VALID(vOther); - - x = clamp( (int)(vOther.x * 16384) + 16384, 0, 32767 ); - y = clamp( (int)(vOther.y * 16384) + 16384, 0, 32767 ); - zneg = (vOther.z < 0); - //x = vOther.x; - //y = vOther.y; - //z = vOther.z; - return *this; -} - - -inline Normal32::operator Vector () -{ - Vector tmp; - - tmp.x = ((int)x - 16384) * (1 / 16384.0); - tmp.y = ((int)y - 16384) * (1 / 16384.0); - tmp.z = sqrt( 1 - tmp.x * tmp.x - tmp.y * tmp.y ); - if (zneg) - tmp.z = -tmp.z; - return tmp; -} - - -//========================================================= -// 64 bit Quaternion -//========================================================= - -class Quaternion64 -{ -public: - // Construction/destruction: - Quaternion64(void); - Quaternion64(vec_t X, vec_t Y, vec_t Z); - - // assignment - // Quaternion& operator=(const Quaternion64 &vOther); - Quaternion64& operator=(const Quaternion &vOther); - operator Quaternion (); -private: - uint64 x:21; - uint64 y:21; - uint64 z:21; - uint64 wneg:1; -}; - - -inline Quaternion64::operator Quaternion () -{ - Quaternion tmp; - - // shift to -1048576, + 1048575, then round down slightly to -1.0 < x < 1.0 - tmp.x = ((int)x - 1048576) * (1 / 1048576.5f); - tmp.y = ((int)y - 1048576) * (1 / 1048576.5f); - tmp.z = ((int)z - 1048576) * (1 / 1048576.5f); - tmp.w = sqrt( 1 - tmp.x * tmp.x - tmp.y * tmp.y - tmp.z * tmp.z ); - if (wneg) - tmp.w = -tmp.w; - return tmp; -} - -inline Quaternion64& Quaternion64::operator=(const Quaternion &vOther) -{ - CHECK_VALID(vOther); - - x = clamp( (int)(vOther.x * 1048576) + 1048576, 0, 2097151 ); - y = clamp( (int)(vOther.y * 1048576) + 1048576, 0, 2097151 ); - z = clamp( (int)(vOther.z * 1048576) + 1048576, 0, 2097151 ); - wneg = (vOther.w < 0); - return *this; -} - -//========================================================= -// 48 bit Quaternion -//========================================================= - -class Quaternion48 -{ -public: - // Construction/destruction: - Quaternion48(void); - Quaternion48(vec_t X, vec_t Y, vec_t Z); - - // assignment - // Quaternion& operator=(const Quaternion48 &vOther); - Quaternion48& operator=(const Quaternion &vOther); - operator Quaternion (); -private: - unsigned short x:16; - unsigned short y:16; - unsigned short z:15; - unsigned short wneg:1; -}; - - -inline Quaternion48::operator Quaternion () -{ - Quaternion tmp; - - tmp.x = ((int)x - 32768) * (1 / 32768.0); - tmp.y = ((int)y - 32768) * (1 / 32768.0); - tmp.z = ((int)z - 16384) * (1 / 16384.0); - tmp.w = sqrt( 1 - tmp.x * tmp.x - tmp.y * tmp.y - tmp.z * tmp.z ); - if (wneg) - tmp.w = -tmp.w; - return tmp; -} - -inline Quaternion48& Quaternion48::operator=(const Quaternion &vOther) -{ - CHECK_VALID(vOther); - - x = clamp( (int)(vOther.x * 32768) + 32768, 0, 65535 ); - y = clamp( (int)(vOther.y * 32768) + 32768, 0, 65535 ); - z = clamp( (int)(vOther.z * 16384) + 16384, 0, 32767 ); - wneg = (vOther.w < 0); - return *this; -} - -//========================================================= -// 32 bit Quaternion -//========================================================= - -class Quaternion32 -{ -public: - // Construction/destruction: - Quaternion32(void); - Quaternion32(vec_t X, vec_t Y, vec_t Z); - - // assignment - // Quaternion& operator=(const Quaternion48 &vOther); - Quaternion32& operator=(const Quaternion &vOther); - operator Quaternion (); -private: - unsigned int x:11; - unsigned int y:10; - unsigned int z:10; - unsigned int wneg:1; -}; - - -inline Quaternion32::operator Quaternion () -{ - Quaternion tmp; - - tmp.x = ((int)x - 1024) * (1 / 1024.0); - tmp.y = ((int)y - 512) * (1 / 512.0); - tmp.z = ((int)z - 512) * (1 / 512.0); - tmp.w = sqrt( 1 - tmp.x * tmp.x - tmp.y * tmp.y - tmp.z * tmp.z ); - if (wneg) - tmp.w = -tmp.w; - return tmp; -} - -inline Quaternion32& Quaternion32::operator=(const Quaternion &vOther) -{ - CHECK_VALID(vOther); - - x = clamp( (int)(vOther.x * 1024) + 1024, 0, 2047 ); - y = clamp( (int)(vOther.y * 512) + 512, 0, 1023 ); - z = clamp( (int)(vOther.z * 512) + 512, 0, 1023 ); - wneg = (vOther.w < 0); - return *this; -} - -//========================================================= -// 16 bit float -//========================================================= - - -const int float32bias = 127; -const int float16bias = 15; - -const float maxfloat16bits = 65504.0f; - -class float16 -{ -public: - //float16() {} - //float16( float f ) { m_storage.rawWord = ConvertFloatTo16bits(f); } - - void Init() { m_storage.rawWord = 0; } -// float16& operator=(const float16 &other) { m_storage.rawWord = other.m_storage.rawWord; return *this; } -// float16& operator=(const float &other) { m_storage.rawWord = ConvertFloatTo16bits(other); return *this; } -// operator unsigned short () { return m_storage.rawWord; } -// operator float () { return Convert16bitFloatTo32bits( m_storage.rawWord ); } - unsigned short GetBits() const - { - return m_storage.rawWord; - } - float GetFloat() const - { - return Convert16bitFloatTo32bits( m_storage.rawWord ); - } - void SetFloat( float in ) - { - m_storage.rawWord = ConvertFloatTo16bits( in ); - } - - bool IsInfinity() const - { - return m_storage.bits.biased_exponent == 31 && m_storage.bits.mantissa == 0; - } - bool IsNaN() const - { - return m_storage.bits.biased_exponent == 31 && m_storage.bits.mantissa != 0; - } - - bool operator==(const float16 other) const { return m_storage.rawWord == other.m_storage.rawWord; } - bool operator!=(const float16 other) const { return m_storage.rawWord != other.m_storage.rawWord; } - -// bool operator< (const float other) const { return GetFloat() < other; } -// bool operator> (const float other) const { return GetFloat() > other; } - -protected: - union float32bits - { - float rawFloat; - struct - { - unsigned int mantissa : 23; - unsigned int biased_exponent : 8; - unsigned int sign : 1; - } bits; - }; - - union float16bits - { - unsigned short rawWord; - struct - { - unsigned short mantissa : 10; - unsigned short biased_exponent : 5; - unsigned short sign : 1; - } bits; - }; - - static bool IsNaN( float16bits in ) - { - return in.bits.biased_exponent == 31 && in.bits.mantissa != 0; - } - static bool IsInfinity( float16bits in ) - { - return in.bits.biased_exponent == 31 && in.bits.mantissa == 0; - } - - // 0x0001 - 0x03ff - static unsigned short ConvertFloatTo16bits( float input ) - { - if ( input > maxfloat16bits ) - input = maxfloat16bits; - else if ( input < -maxfloat16bits ) - input = -maxfloat16bits; - - float16bits output; - float32bits inFloat; - - inFloat.rawFloat = input; - - output.bits.sign = inFloat.bits.sign; - - if ( (inFloat.bits.biased_exponent==0) && (inFloat.bits.mantissa==0) ) - { - // zero - output.bits.mantissa = 0; - output.bits.biased_exponent = 0; - } - else if ( (inFloat.bits.biased_exponent==0) && (inFloat.bits.mantissa!=0) ) - { - // denorm -- denorm float maps to 0 half - output.bits.mantissa = 0; - output.bits.biased_exponent = 0; - } - else if ( (inFloat.bits.biased_exponent==0xff) && (inFloat.bits.mantissa==0) ) - { -#if 0 - // infinity - output.bits.mantissa = 0; - output.bits.biased_exponent = 31; -#else - // infinity maps to maxfloat - output.bits.mantissa = 0x3ff; - output.bits.biased_exponent = 0x1e; -#endif - } - else if ( (inFloat.bits.biased_exponent==0xff) && (inFloat.bits.mantissa!=0) ) - { -#if 0 - // NaN - output.bits.mantissa = 1; - output.bits.biased_exponent = 31; -#else - // NaN maps to zero - output.bits.mantissa = 0; - output.bits.biased_exponent = 0; -#endif - } - else - { - // regular number - int new_exp = inFloat.bits.biased_exponent-127; - - if (new_exp<-24) - { - // this maps to 0 - output.bits.mantissa = 0; - output.bits.biased_exponent = 0; - } - - if (new_exp<-14) - { - // this maps to a denorm - output.bits.biased_exponent = 0; - unsigned int exp_val = ( unsigned int )( -14 - ( inFloat.bits.biased_exponent - float32bias ) ); - if( exp_val > 0 && exp_val < 11 ) - { - output.bits.mantissa = ( 1 << ( 10 - exp_val ) ) + ( inFloat.bits.mantissa >> ( 13 + exp_val ) ); - } - } - else if (new_exp>15) - { -#if 0 - // map this value to infinity - output.bits.mantissa = 0; - output.bits.biased_exponent = 31; -#else - // to big. . . maps to maxfloat - output.bits.mantissa = 0x3ff; - output.bits.biased_exponent = 0x1e; -#endif - } - else - { - output.bits.biased_exponent = new_exp+15; - output.bits.mantissa = (inFloat.bits.mantissa >> 13); - } - } - return output.rawWord; - } - - static float Convert16bitFloatTo32bits( unsigned short input ) - { - float32bits output; - const float16bits &inFloat = *((float16bits *)&input); - - if( IsInfinity( inFloat ) ) - { - return maxfloat16bits * ( ( inFloat.bits.sign == 1 ) ? -1.0f : 1.0f ); - } - if( IsNaN( inFloat ) ) - { - return 0.0; - } - if( inFloat.bits.biased_exponent == 0 && inFloat.bits.mantissa != 0 ) - { - // denorm - const float half_denorm = (1.0f/16384.0f); // 2^-14 - float mantissa = ((float)(inFloat.bits.mantissa)) / 1024.0f; - float sgn = (inFloat.bits.sign)? -1.0f :1.0f; - output.rawFloat = sgn*mantissa*half_denorm; - } - else - { - // regular number - unsigned mantissa = inFloat.bits.mantissa; - unsigned biased_exponent = inFloat.bits.biased_exponent; - unsigned sign = ((unsigned)inFloat.bits.sign) << 31; - biased_exponent = ( (biased_exponent - float16bias + float32bias) * (biased_exponent != 0) ) << 23; - mantissa <<= (23-10); - - *((unsigned *)&output) = ( mantissa | biased_exponent | sign ); - } - - return output.rawFloat; - } - - - float16bits m_storage; -}; - -class float16_with_assign : public float16 -{ -public: - float16_with_assign() {} - float16_with_assign( float f ) { m_storage.rawWord = ConvertFloatTo16bits(f); } - - float16& operator=(const float16 &other) { m_storage.rawWord = ((float16_with_assign &)other).m_storage.rawWord; return *this; } - float16& operator=(const float &other) { m_storage.rawWord = ConvertFloatTo16bits(other); return *this; } -// operator unsigned short () const { return m_storage.rawWord; } - operator float () const { return Convert16bitFloatTo32bits( m_storage.rawWord ); } -}; - -//========================================================= -// Fit a 3D vector in 48 bits -//========================================================= - -class Vector48 -{ -public: - // Construction/destruction: - Vector48(void) {} - Vector48(vec_t X, vec_t Y, vec_t Z) { x.SetFloat( X ); y.SetFloat( Y ); z.SetFloat( Z ); } - - // assignment - Vector48& operator=(const Vector &vOther); - operator Vector (); - - const float operator[]( int i ) const { return (((float16 *)this)[i]).GetFloat(); } - - float16 x; - float16 y; - float16 z; -}; - -inline Vector48& Vector48::operator=(const Vector &vOther) -{ - CHECK_VALID(vOther); - - x.SetFloat( vOther.x ); - y.SetFloat( vOther.y ); - z.SetFloat( vOther.z ); - return *this; -} - - -inline Vector48::operator Vector () -{ - Vector tmp; - - tmp.x = x.GetFloat(); - tmp.y = y.GetFloat(); - tmp.z = z.GetFloat(); - - return tmp; -} - -//========================================================= -// Fit a 2D vector in 32 bits -//========================================================= - -class Vector2d32 -{ -public: - // Construction/destruction: - Vector2d32(void) {} - Vector2d32(vec_t X, vec_t Y) { x.SetFloat( X ); y.SetFloat( Y ); } - - // assignment - Vector2d32& operator=(const Vector &vOther); - Vector2d32& operator=(const Vector2D &vOther); - - operator Vector2D (); - - void Init( vec_t ix = 0.f, vec_t iy = 0.f); - - float16_with_assign x; - float16_with_assign y; -}; - -inline Vector2d32& Vector2d32::operator=(const Vector2D &vOther) -{ - x.SetFloat( vOther.x ); - y.SetFloat( vOther.y ); - return *this; -} - -inline Vector2d32::operator Vector2D () -{ - Vector2D tmp; - - tmp.x = x.GetFloat(); - tmp.y = y.GetFloat(); - - return tmp; -} - -inline void Vector2d32::Init( vec_t ix, vec_t iy ) -{ - x.SetFloat(ix); - y.SetFloat(iy); -} - -#if defined( _X360 ) -#pragma bitfield_order( pop ) -#endif - -#endif - diff --git a/Resources/NetHook/mathlib/halton.h b/Resources/NetHook/mathlib/halton.h deleted file mode 100644 index 47c2fab1..00000000 --- a/Resources/NetHook/mathlib/halton.h +++ /dev/null @@ -1,70 +0,0 @@ -// $Id$ - -// halton.h - classes, etc for generating numbers using the Halton pseudo-random sequence. See -// http://halton-sequences.wikiverse.org/. -// -// what this function is useful for is any sort of sampling/integration problem where -// you want to solve it by random sampling. Each call the NextValue() generates -// a random number between 0 and 1, in an unclumped manner, so that the space can be more -// or less evenly sampled with a minimum number of samples. -// -// It is NOT useful for generating random numbers dynamically, since the outputs aren't -// particularly random. -// -// To generate multidimensional sample values (points in a plane, etc), use two -// HaltonSequenceGenerator_t's, with different (primes) bases. - -#ifndef HALTON_H -#define HALTON_H - -#include -#include - -class HaltonSequenceGenerator_t -{ - int seed; - int base; - float fbase; //< base as a float - -public: - HaltonSequenceGenerator_t(int base); //< base MUST be prime, >=2 - - float GetElement(int element); - - inline float NextValue(void) - { - return GetElement(seed++); - } - -}; - - -class DirectionalSampler_t //< pseudo-random sphere sampling -{ - HaltonSequenceGenerator_t zdot; - HaltonSequenceGenerator_t vrot; -public: - DirectionalSampler_t(void) - : zdot(2),vrot(3) - { - } - - Vector NextValue(void) - { - float zvalue=zdot.NextValue(); - zvalue=2*zvalue-1.0; // map from 0..1 to -1..1 - float phi=acos(zvalue); - // now, generate a random rotation angle for x/y - float theta=2.0*M_PI*vrot.NextValue(); - float sin_p=sin(phi); - return Vector(cos(theta)*sin_p, - sin(theta)*sin_p, - zvalue); - - } -}; - - - - -#endif // halton_h diff --git a/Resources/NetHook/mathlib/lightdesc.h b/Resources/NetHook/mathlib/lightdesc.h deleted file mode 100644 index 4ac74a43..00000000 --- a/Resources/NetHook/mathlib/lightdesc.h +++ /dev/null @@ -1,167 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -// light structure definitions. -#ifndef LIGHTDESC_H -#define LIGHTDESC_H - -#include -#include - -//----------------------------------------------------------------------------- -// Light structure -//----------------------------------------------------------------------------- - -enum LightType_t -{ - MATERIAL_LIGHT_DISABLE = 0, - MATERIAL_LIGHT_POINT, - MATERIAL_LIGHT_DIRECTIONAL, - MATERIAL_LIGHT_SPOT, -}; - -enum LightType_OptimizationFlags_t -{ - LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0 = 1, - LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1 = 2, - LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2 = 4, -}; - -struct LightDesc_t -{ - LightType_t m_Type; //< MATERIAL_LIGHT_xxx - Vector m_Color; //< color+intensity - Vector m_Position; //< light source center position - Vector m_Direction; //< for SPOT, direction it is pointing - float m_Range; //< distance range for light.0=infinite - float m_Falloff; //< angular falloff exponent for spot lights - float m_Attenuation0; //< constant distance falloff term - float m_Attenuation1; //< linear term of falloff - float m_Attenuation2; //< quadatic term of falloff - float m_Theta; //< inner cone angle. no angular falloff - //< within this cone - float m_Phi; //< outer cone angle - - // the values below are derived from the above settings for optimizations - // These aren't used by DX8. . used for software lighting. - float m_ThetaDot; - float m_PhiDot; - unsigned int m_Flags; -protected: - float OneOver_ThetaDot_Minus_PhiDot; - float m_RangeSquared; -public: - - void RecalculateDerivedValues(void); // calculate m_xxDot, m_Type for changed parms - - LightDesc_t(void) - { - } - - // constructors for various useful subtypes - - // a point light with infinite range - LightDesc_t( const Vector &pos, const Vector &color ) - { - InitPoint( pos, color ); - } - - /// a simple light. cone boundaries in radians. you pass a look_at point and the - /// direciton is derived from that. - LightDesc_t( const Vector &pos, const Vector &color, const Vector &point_at, - float inner_cone_boundary, float outer_cone_boundary ) - { - InitSpot( pos, color, point_at, inner_cone_boundary, outer_cone_boundary ); - } - - void InitPoint( const Vector &pos, const Vector &color ); - void InitDirectional( const Vector &dir, const Vector &color ); - void InitSpot(const Vector &pos, const Vector &color, const Vector &point_at, - float inner_cone_boundary, float outer_cone_boundary ); - - /// Given 4 points and 4 normals, ADD lighting from this light into "color". - void ComputeLightAtPoints( const FourVectors &pos, const FourVectors &normal, - FourVectors &color, bool DoHalfLambert=false ) const; - void ComputeNonincidenceLightAtPoints( const FourVectors &pos, FourVectors &color ) const; - void ComputeLightAtPointsForDirectional( const FourVectors &pos, - const FourVectors &normal, - FourVectors &color, bool DoHalfLambert=false ) const; - - // warning - modifies color!!! set color first!! - void SetupOldStyleAttenuation( float fQuadatricAttn, float fLinearAttn, float fConstantAttn ); - - void SetupNewStyleAttenuation( float fFiftyPercentDistance, float fZeroPercentDistance ); - - -/// given a direction relative to the light source position, is this ray within the - /// light cone (for spotlights..non spots consider all rays to be within their cone) - bool IsDirectionWithinLightCone(const Vector &rdir) const - { - return ((m_Type!=MATERIAL_LIGHT_SPOT) || (rdir.Dot(m_Direction)>=m_PhiDot)); - } -}; - - -//----------------------------------------------------------------------------- -// a point light with infinite range -//----------------------------------------------------------------------------- -inline void LightDesc_t::InitPoint( const Vector &pos, const Vector &color ) -{ - m_Type=MATERIAL_LIGHT_POINT; - m_Color=color; - m_Position=pos; - m_Range=0.0; // infinite - m_Attenuation0=1.0; - m_Attenuation1=0; - m_Attenuation2=0; - RecalculateDerivedValues(); -} - - -//----------------------------------------------------------------------------- -// a directional light with infinite range -//----------------------------------------------------------------------------- -inline void LightDesc_t::InitDirectional( const Vector &dir, const Vector &color ) -{ - m_Type=MATERIAL_LIGHT_DIRECTIONAL; - m_Color=color; - m_Direction=dir; - m_Range=0.0; // infinite - m_Attenuation0=1.0; - m_Attenuation1=0; - m_Attenuation2=0; - RecalculateDerivedValues(); -} - - -//----------------------------------------------------------------------------- -// a simple light. cone boundaries in radians. you pass a look_at point and the -// direciton is derived from that. -//----------------------------------------------------------------------------- -inline void LightDesc_t::InitSpot(const Vector &pos, const Vector &color, const Vector &point_at, - float inner_cone_boundary, float outer_cone_boundary) -{ - m_Type=MATERIAL_LIGHT_SPOT; - m_Color=color; - m_Position=pos; - m_Direction=point_at; - m_Direction-=pos; - VectorNormalizeFast(m_Direction); - m_Falloff=5.0; // linear angle falloff - m_Theta=inner_cone_boundary; - m_Phi=outer_cone_boundary; - - m_Range=0.0; // infinite - - m_Attenuation0=1.0; - m_Attenuation1=0; - m_Attenuation2=0; - RecalculateDerivedValues(); -} - - -#endif - diff --git a/Resources/NetHook/mathlib/math_pfns.h b/Resources/NetHook/mathlib/math_pfns.h deleted file mode 100644 index 2fa0abfb..00000000 --- a/Resources/NetHook/mathlib/math_pfns.h +++ /dev/null @@ -1,72 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=====================================================================================// - -#ifndef _MATH_PFNS_H_ -#define _MATH_PFNS_H_ - -#if defined( _X360 ) -#include -#endif - -#if !defined( _X360 ) - -// These globals are initialized by mathlib and redirected based on available fpu features -extern float (*pfSqrt)(float x); -extern float (*pfRSqrt)(float x); -extern float (*pfRSqrtFast)(float x); -extern void (*pfFastSinCos)(float x, float *s, float *c); -extern float (*pfFastCos)(float x); - -// The following are not declared as macros because they are often used in limiting situations, -// and sometimes the compiler simply refuses to inline them for some reason -#define FastSqrt(x) (*pfSqrt)(x) -#define FastRSqrt(x) (*pfRSqrt)(x) -#define FastRSqrtFast(x) (*pfRSqrtFast)(x) -#define FastSinCos(x,s,c) (*pfFastSinCos)(x,s,c) -#define FastCos(x) (*pfFastCos)(x) - -#endif // !_X360 - -#if defined( _X360 ) - -FORCEINLINE float _VMX_Sqrt( float x ) -{ - return __fsqrts( x ); -} - -FORCEINLINE float _VMX_RSqrt( float x ) -{ - float rroot = __frsqrte( x ); - - // Single iteration NewtonRaphson on reciprocal square root estimate - return (0.5f * rroot) * (3.0f - (x * rroot) * rroot); -} - -FORCEINLINE float _VMX_RSqrtFast( float x ) -{ - return __frsqrte( x ); -} - -FORCEINLINE void _VMX_SinCos( float a, float *pS, float *pC ) -{ - XMScalarSinCos( pS, pC, a ); -} - -FORCEINLINE float _VMX_Cos( float a ) -{ - return XMScalarCos( a ); -} - -// the 360 has fixed hw and calls directly -#define FastSqrt(x) _VMX_Sqrt(x) -#define FastRSqrt(x) _VMX_RSqrt(x) -#define FastRSqrtFast(x) _VMX_RSqrtFast(x) -#define FastSinCos(x,s,c) _VMX_SinCos(x,s,c) -#define FastCos(x) _VMX_Cos(x) - -#endif // _X360 - -#endif // _MATH_PFNS_H_ diff --git a/Resources/NetHook/mathlib/mathlib.h b/Resources/NetHook/mathlib/mathlib.h deleted file mode 100644 index 5b0f8fd8..00000000 --- a/Resources/NetHook/mathlib/mathlib.h +++ /dev/null @@ -1,2073 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -#ifndef MATH_LIB_H -#define MATH_LIB_H - -#include -#include "tier0/basetypes.h" -#include "mathlib/vector.h" -#include "mathlib/vector2d.h" -#include "tier0/dbg.h" - -#include "mathlib/math_pfns.h" - -// plane_t structure -// !!! if this is changed, it must be changed in asm code too !!! -// FIXME: does the asm code even exist anymore? -// FIXME: this should move to a different file -struct cplane_t -{ - Vector normal; - float dist; - byte type; // for fast side tests - byte signbits; // signx + (signy<<1) + (signz<<1) - byte pad[2]; - -#ifdef VECTOR_NO_SLOW_OPERATIONS - cplane_t() {} - -private: - // No copy constructors allowed if we're in optimal mode - cplane_t(const cplane_t& vOther); -#endif -}; - -// structure offset for asm code -#define CPLANE_NORMAL_X 0 -#define CPLANE_NORMAL_Y 4 -#define CPLANE_NORMAL_Z 8 -#define CPLANE_DIST 12 -#define CPLANE_TYPE 16 -#define CPLANE_SIGNBITS 17 -#define CPLANE_PAD0 18 -#define CPLANE_PAD1 19 - -// 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 - -// 3-5 are non-axial planes snapped to the nearest -#define PLANE_ANYX 3 -#define PLANE_ANYY 4 -#define PLANE_ANYZ 5 - - -//----------------------------------------------------------------------------- -// Frustum plane indices. -// WARNING: there is code that depends on these values -//----------------------------------------------------------------------------- - -enum -{ - FRUSTUM_RIGHT = 0, - FRUSTUM_LEFT = 1, - FRUSTUM_TOP = 2, - FRUSTUM_BOTTOM = 3, - FRUSTUM_NEARZ = 4, - FRUSTUM_FARZ = 5, - FRUSTUM_NUMPLANES = 6 -}; - -extern int SignbitsForPlane( cplane_t *out ); - -class Frustum_t -{ -public: - void SetPlane( int i, int nType, const Vector &vecNormal, float dist ) - { - m_Plane[i].normal = vecNormal; - m_Plane[i].dist = dist; - m_Plane[i].type = nType; - m_Plane[i].signbits = SignbitsForPlane( &m_Plane[i] ); - m_AbsNormal[i].Init( fabs(vecNormal.x), fabs(vecNormal.y), fabs(vecNormal.z) ); - } - - inline const cplane_t *GetPlane( int i ) const { return &m_Plane[i]; } - inline const Vector &GetAbsNormal( int i ) const { return m_AbsNormal[i]; } - -private: - cplane_t m_Plane[FRUSTUM_NUMPLANES]; - Vector m_AbsNormal[FRUSTUM_NUMPLANES]; -}; - -// Computes Y fov from an X fov and a screen aspect ratio + X from Y -float CalcFovY( float flFovX, float flScreenAspect ); -float CalcFovX( float flFovY, float flScreenAspect ); - -// Generate a frustum based on perspective view parameters -// NOTE: FOV is specified in degrees, as the *full* view angle (not half-angle) -void GeneratePerspectiveFrustum( const Vector& origin, const QAngle &angles, float flZNear, float flZFar, float flFovX, float flAspectRatio, Frustum_t &frustum ); -void GeneratePerspectiveFrustum( const Vector& origin, const Vector &forward, const Vector &right, const Vector &up, float flZNear, float flZFar, float flFovX, float flFovY, Frustum_t &frustum ); - -// Cull the world-space bounding box to the specified frustum. -bool R_CullBox( const Vector& mins, const Vector& maxs, const Frustum_t &frustum ); -bool R_CullBoxSkipNear( const Vector& mins, const Vector& maxs, const Frustum_t &frustum ); - -struct matrix3x4_t -{ - matrix3x4_t() {} - matrix3x4_t( - float m00, float m01, float m02, float m03, - float m10, float m11, float m12, float m13, - float m20, float m21, float m22, float m23 ) - { - m_flMatVal[0][0] = m00; m_flMatVal[0][1] = m01; m_flMatVal[0][2] = m02; m_flMatVal[0][3] = m03; - m_flMatVal[1][0] = m10; m_flMatVal[1][1] = m11; m_flMatVal[1][2] = m12; m_flMatVal[1][3] = m13; - m_flMatVal[2][0] = m20; m_flMatVal[2][1] = m21; m_flMatVal[2][2] = m22; m_flMatVal[2][3] = m23; - } - - //----------------------------------------------------------------------------- - // Creates a matrix where the X axis = forward - // the Y axis = left, and the Z axis = up - //----------------------------------------------------------------------------- - void Init( const Vector& xAxis, const Vector& yAxis, const Vector& zAxis, const Vector &vecOrigin ) - { - m_flMatVal[0][0] = xAxis.x; m_flMatVal[0][1] = yAxis.x; m_flMatVal[0][2] = zAxis.x; m_flMatVal[0][3] = vecOrigin.x; - m_flMatVal[1][0] = xAxis.y; m_flMatVal[1][1] = yAxis.y; m_flMatVal[1][2] = zAxis.y; m_flMatVal[1][3] = vecOrigin.y; - m_flMatVal[2][0] = xAxis.z; m_flMatVal[2][1] = yAxis.z; m_flMatVal[2][2] = zAxis.z; m_flMatVal[2][3] = vecOrigin.z; - } - - //----------------------------------------------------------------------------- - // Creates a matrix where the X axis = forward - // the Y axis = left, and the Z axis = up - //----------------------------------------------------------------------------- - matrix3x4_t( const Vector& xAxis, const Vector& yAxis, const Vector& zAxis, const Vector &vecOrigin ) - { - Init( xAxis, yAxis, zAxis, vecOrigin ); - } - - inline void Invalidate( void ) - { - for (int i = 0; i < 3; i++) - { - for (int j = 0; j < 4; j++) - { - m_flMatVal[i][j] = VEC_T_NAN; - } - } - } - - float *operator[]( int i ) { Assert(( i >= 0 ) && ( i < 3 )); return m_flMatVal[i]; } - const float *operator[]( int i ) const { Assert(( i >= 0 ) && ( i < 3 )); return m_flMatVal[i]; } - float *Base() { return &m_flMatVal[0][0]; } - const float *Base() const { return &m_flMatVal[0][0]; } - - float m_flMatVal[3][4]; -}; - - -#ifndef M_PI - #define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h -#endif - -#define M_PI_F ((float)(M_PI)) // Shouldn't collide with anything. - -// NJS: Inlined to prevent floats from being autopromoted to doubles, as with the old system. -#ifndef RAD2DEG - #define RAD2DEG( x ) ( (float)(x) * (float)(180.f / M_PI_F) ) -#endif - -#ifndef DEG2RAD - #define DEG2RAD( x ) ( (float)(x) * (float)(M_PI_F / 180.f) ) -#endif - -// Used to represent sides of things like planes. -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 -#define SIDE_CROSS -2 // necessary for polylib.c - -#define ON_VIS_EPSILON 0.01 // necessary for vvis (flow.c) -- again look into moving later! -#define EQUAL_EPSILON 0.001 // necessary for vbsp (faces.c) -- should look into moving it there? - -extern bool s_bMathlibInitialized; - -extern const Vector vec3_origin; -extern const QAngle vec3_angle; -extern const Quaternion quat_identity; -extern const Vector vec3_invalid; -extern const int nanmask; - -#define IS_NAN(x) (((*(int *)&x)&nanmask)==nanmask) - -FORCEINLINE vec_t DotProduct(const vec_t *v1, const vec_t *v2) -{ - return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; -} -FORCEINLINE void VectorSubtract(const vec_t *a, const vec_t *b, vec_t *c) -{ - c[0]=a[0]-b[0]; - c[1]=a[1]-b[1]; - c[2]=a[2]-b[2]; -} -FORCEINLINE void VectorAdd(const vec_t *a, const vec_t *b, vec_t *c) -{ - c[0]=a[0]+b[0]; - c[1]=a[1]+b[1]; - c[2]=a[2]+b[2]; -} -FORCEINLINE void VectorCopy(const vec_t *a, vec_t *b) -{ - b[0]=a[0]; - b[1]=a[1]; - b[2]=a[2]; -} -FORCEINLINE void VectorClear(vec_t *a) -{ - a[0]=a[1]=a[2]=0; -} - -FORCEINLINE float VectorMaximum(const vec_t *v) -{ - return max( v[0], max( v[1], v[2] ) ); -} - -FORCEINLINE float VectorMaximum(const Vector& v) -{ - return max( v.x, max( v.y, v.z ) ); -} - -FORCEINLINE void VectorScale (const float* in, vec_t scale, float* out) -{ - out[0] = in[0]*scale; - out[1] = in[1]*scale; - out[2] = in[2]*scale; -} - - -// Cannot be forceinline as they have overloads: -inline void VectorFill(vec_t *a, float b) -{ - a[0]=a[1]=a[2]=b; -} - -inline void VectorNegate(vec_t *a) -{ - a[0]=-a[0]; - a[1]=-a[1]; - a[2]=-a[2]; -} - - -//#define VectorMaximum(a) ( max( (a)[0], max( (a)[1], (a)[2] ) ) ) -#define Vector2Clear(x) {(x)[0]=(x)[1]=0;} -#define Vector2Negate(x) {(x)[0]=-((x)[0]);(x)[1]=-((x)[1]);} -#define Vector2Copy(a,b) {(b)[0]=(a)[0];(b)[1]=(a)[1];} -#define Vector2Subtract(a,b,c) {(c)[0]=(a)[0]-(b)[0];(c)[1]=(a)[1]-(b)[1];} -#define Vector2Add(a,b,c) {(c)[0]=(a)[0]+(b)[0];(c)[1]=(a)[1]+(b)[1];} -#define Vector2Scale(a,b,c) {(c)[0]=(b)*(a)[0];(c)[1]=(b)*(a)[1];} - -// NJS: Some functions in VBSP still need to use these for dealing with mixing vec4's and shorts with vec_t's. -// remove when no longer needed. -#define VECTOR_COPY( A, B ) do { (B)[0] = (A)[0]; (B)[1] = (A)[1]; (B)[2]=(A)[2]; } while(0) -#define DOT_PRODUCT( A, B ) ( (A)[0]*(B)[0] + (A)[1]*(B)[1] + (A)[2]*(B)[2] ) - -FORCEINLINE void VectorMAInline( const float* start, float scale, const float* direction, float* dest ) -{ - dest[0]=start[0]+direction[0]*scale; - dest[1]=start[1]+direction[1]*scale; - dest[2]=start[2]+direction[2]*scale; -} - -FORCEINLINE void VectorMAInline( const Vector& start, float scale, const Vector& direction, Vector& dest ) -{ - dest.x=start.x+direction.x*scale; - dest.y=start.y+direction.y*scale; - dest.z=start.z+direction.z*scale; -} - -FORCEINLINE void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest ) -{ - VectorMAInline(start, scale, direction, dest); -} - -FORCEINLINE void VectorMA( const float * start, float scale, const float *direction, float *dest ) -{ - VectorMAInline(start, scale, direction, dest); -} - - -int VectorCompare (const float *v1, const float *v2); - -inline float VectorLength(const float *v) -{ - return FastSqrt( v[0]*v[0] + v[1]*v[1] + v[2]*v[2] + FLT_EPSILON ); -} - -void CrossProduct (const float *v1, const float *v2, float *cross); - -qboolean VectorsEqual( const float *v1, const float *v2 ); - -inline vec_t RoundInt (vec_t in) -{ - return floor(in + 0.5f); -} - -int Q_log2(int val); - -// Math routines done in optimized assembly math package routines -void inline SinCos( float radians, float *sine, float *cosine ) -{ -#if defined( _X360 ) - XMScalarSinCos( sine, cosine, radians ); -#elif defined( _WIN32 ) - _asm - { - fld DWORD PTR [radians] - fsincos - - mov edx, DWORD PTR [cosine] - mov eax, DWORD PTR [sine] - - fstp DWORD PTR [edx] - fstp DWORD PTR [eax] - } -#elif defined( _LINUX ) - register double __cosr, __sinr; - __asm __volatile__ - ("fsincos" - : "=t" (__cosr), "=u" (__sinr) : "0" (radians)); - - *sine = __sinr; - *cosine = __cosr; -#endif -} - -#define SIN_TABLE_SIZE 256 -#define FTOIBIAS 12582912.f -extern float SinCosTable[SIN_TABLE_SIZE]; - -inline float TableCos( float theta ) -{ - union - { - int i; - float f; - } ftmp; - - // ideally, the following should compile down to: theta * constant + constant, changing any of these constants from defines sometimes fubars this. - ftmp.f = theta * ( float )( SIN_TABLE_SIZE / ( 2.0f * M_PI ) ) + ( FTOIBIAS + ( SIN_TABLE_SIZE / 4 ) ); - return SinCosTable[ ftmp.i & ( SIN_TABLE_SIZE - 1 ) ]; -} - -inline float TableSin( float theta ) -{ - union - { - int i; - float f; - } ftmp; - - // ideally, the following should compile down to: theta * constant + constant - ftmp.f = theta * ( float )( SIN_TABLE_SIZE / ( 2.0f * M_PI ) ) + FTOIBIAS; - return SinCosTable[ ftmp.i & ( SIN_TABLE_SIZE - 1 ) ]; -} - -template -FORCEINLINE T Square( T const &a ) -{ - return a * a; -} - - -FORCEINLINE bool IsPowerOfTwo( uint x ) -{ - return ( x & ( x - 1 ) ) == 0; -} - -// return the smallest power of two >= x. -// returns 0 if x == 0 or x > 0x80000000 (ie numbers that would be negative if x was signed) -// NOTE: the old code took an int, and if you pass in an int of 0x80000000 casted to a uint, -// you'll get 0x80000000, which is correct for uints, instead of 0, which was correct for ints -FORCEINLINE uint SmallestPowerOfTwoGreaterOrEqual( uint x ) -{ - x -= 1; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - return x + 1; -} - -// return the largest power of two <= x. Will return 0 if passed 0 -FORCEINLINE uint LargestPowerOfTwoLessThanOrEqual( uint x ) -{ - if ( x >= 0x80000000 ) - return 0x80000000; - - return SmallestPowerOfTwoGreaterOrEqual( x + 1 ) >> 1; -} - - -// Math routines for optimizing division -void FloorDivMod (double numer, double denom, int *quotient, int *rem); -int GreatestCommonDivisor (int i1, int i2); - -// Test for FPU denormal mode -bool IsDenormal( const float &val ); - -// MOVEMENT INFO -enum -{ - PITCH = 0, // up / down - YAW, // left / right - ROLL // fall over -}; - -void MatrixAngles( const matrix3x4_t & matrix, float *angles ); // !!!! -void MatrixVectors( const matrix3x4_t &matrix, Vector* pForward, Vector *pRight, Vector *pUp ); -void VectorTransform (const float *in1, const matrix3x4_t & in2, float *out); -void VectorITransform (const float *in1, const matrix3x4_t & in2, float *out); -void VectorRotate( const float *in1, const matrix3x4_t & in2, float *out); -void VectorRotate( const Vector &in1, const QAngle &in2, Vector &out ); -void VectorRotate( const Vector &in1, const Quaternion &in2, Vector &out ); -void VectorIRotate( const float *in1, const matrix3x4_t & in2, float *out); - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -QAngle TransformAnglesToLocalSpace( const QAngle &angles, const matrix3x4_t &parentMatrix ); -QAngle TransformAnglesToWorldSpace( const QAngle &angles, const matrix3x4_t &parentMatrix ); - -#endif - -void MatrixInitialize( matrix3x4_t &mat, const Vector &vecOrigin, const Vector &vecXAxis, const Vector &vecYAxis, const Vector &vecZAxis ); -void MatrixCopy( const matrix3x4_t &in, matrix3x4_t &out ); -void MatrixInvert( const matrix3x4_t &in, matrix3x4_t &out ); - -// Matrix equality test -bool MatricesAreEqual( const matrix3x4_t &src1, const matrix3x4_t &src2, float flTolerance = 1e-5 ); - -void MatrixGetColumn( const matrix3x4_t &in, int column, Vector &out ); -void MatrixSetColumn( const Vector &in, int column, matrix3x4_t &out ); - -//void DecomposeRotation( const matrix3x4_t &mat, float *out ); -void ConcatRotations (const matrix3x4_t &in1, const matrix3x4_t &in2, matrix3x4_t &out); -void ConcatTransforms (const matrix3x4_t &in1, const matrix3x4_t &in2, matrix3x4_t &out); - -// For identical interface w/ VMatrix -inline void MatrixMultiply ( const matrix3x4_t &in1, const matrix3x4_t &in2, matrix3x4_t &out ) -{ - ConcatTransforms( in1, in2, out ); -} - -void QuaternionSlerp( const Quaternion &p, const Quaternion &q, float t, Quaternion &qt ); -void QuaternionSlerpNoAlign( const Quaternion &p, const Quaternion &q, float t, Quaternion &qt ); -void QuaternionBlend( const Quaternion &p, const Quaternion &q, float t, Quaternion &qt ); -void QuaternionBlendNoAlign( const Quaternion &p, const Quaternion &q, float t, Quaternion &qt ); -void QuaternionIdentityBlend( const Quaternion &p, float t, Quaternion &qt ); -float QuaternionAngleDiff( const Quaternion &p, const Quaternion &q ); -void QuaternionScale( const Quaternion &p, float t, Quaternion &q ); -void QuaternionAlign( const Quaternion &p, const Quaternion &q, Quaternion &qt ); -float QuaternionDotProduct( const Quaternion &p, const Quaternion &q ); -void QuaternionConjugate( const Quaternion &p, Quaternion &q ); -void QuaternionInvert( const Quaternion &p, Quaternion &q ); -float QuaternionNormalize( Quaternion &q ); -void QuaternionAdd( const Quaternion &p, const Quaternion &q, Quaternion &qt ); -void QuaternionMult( const Quaternion &p, const Quaternion &q, Quaternion &qt ); -void QuaternionMatrix( const Quaternion &q, matrix3x4_t &matrix ); -void QuaternionMatrix( const Quaternion &q, const Vector &pos, matrix3x4_t &matrix ); -void QuaternionAngles( const Quaternion &q, QAngle &angles ); -void AngleQuaternion( const QAngle& angles, Quaternion &qt ); -void QuaternionAngles( const Quaternion &q, RadianEuler &angles ); -void AngleQuaternion( RadianEuler const &angles, Quaternion &qt ); -void QuaternionAxisAngle( const Quaternion &q, Vector &axis, float &angle ); -void AxisAngleQuaternion( const Vector &axis, float angle, Quaternion &q ); -void BasisToQuaternion( const Vector &vecForward, const Vector &vecRight, const Vector &vecUp, Quaternion &q ); -void MatrixQuaternion( const matrix3x4_t &mat, Quaternion &q ); - -// A couple methods to find the dot product of a vector with a matrix row or column... -inline float MatrixRowDotProduct( const matrix3x4_t &in1, int row, const Vector& in2 ) -{ - Assert( (row >= 0) && (row < 3) ); - return DotProduct( in1[row], in2.Base() ); -} - -inline float MatrixColumnDotProduct( const matrix3x4_t &in1, int col, const Vector& in2 ) -{ - Assert( (col >= 0) && (col < 4) ); - return in1[0][col] * in2[0] + in1[1][col] * in2[1] + in1[2][col] * in2[2]; -} - -int __cdecl BoxOnPlaneSide (const float *emins, const float *emaxs, const cplane_t *plane); - -inline float anglemod(float a) -{ - a = (360.f/65536) * ((int)(a*(65536.f/360.0f)) & 65535); - return a; -} - -// Remap a value in the range [A,B] to [C,D]. -inline float RemapVal( float val, float A, float B, float C, float D) -{ - if ( A == B ) - return val >= B ? D : C; - return C + (D - C) * (val - A) / (B - A); -} - -inline float RemapValClamped( float val, float A, float B, float C, float D) -{ - if ( A == B ) - return val >= B ? D : C; - float cVal = (val - A) / (B - A); - cVal = clamp( cVal, 0.0f, 1.0f ); - - return C + (D - C) * cVal; -} - -// Returns A + (B-A)*flPercent. -// float Lerp( float flPercent, float A, float B ); -template -FORCEINLINE T Lerp( float flPercent, T const &A, T const &B ) -{ - return A + (B - A) * flPercent; -} - -FORCEINLINE float Sqr( float f ) -{ - return f*f; -} - -// 5-argument floating point linear interpolation. -// FLerp(f1,f2,i1,i2,x)= -// f1 at x=i1 -// f2 at x=i2 -// smooth lerp between f1 and f2 at x>i1 and xi2 -// -// If you know a function f(x)'s value (f1) at position i1, and its value (f2) at position i2, -// the function can be linearly interpolated with FLerp(f1,f2,i1,i2,x) -// i2=i1 will cause a divide by zero. -static inline float FLerp(float f1, float f2, float i1, float i2, float x) -{ - return f1+(f2-f1)*(x-i1)/(i2-i1); -} - - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -// YWB: Specialization for interpolating euler angles via quaternions... -template<> FORCEINLINE QAngle Lerp( float flPercent, const QAngle& q1, const QAngle& q2 ) -{ - // Avoid precision errors - if ( q1 == q2 ) - return q1; - - Quaternion src, dest; - - // Convert to quaternions - AngleQuaternion( q1, src ); - AngleQuaternion( q2, dest ); - - Quaternion result; - - // Slerp - QuaternionSlerp( src, dest, flPercent, result ); - - // Convert to euler - QAngle output; - QuaternionAngles( result, output ); - return output; -} - -#else - -#pragma error - -// NOTE NOTE: I haven't tested this!! It may not work! Check out interpolatedvar.cpp in the client dll to try it -template<> FORCEINLINE QAngleByValue Lerp( float flPercent, const QAngleByValue& q1, const QAngleByValue& q2 ) -{ - // Avoid precision errors - if ( q1 == q2 ) - return q1; - - Quaternion src, dest; - - // Convert to quaternions - AngleQuaternion( q1, src ); - AngleQuaternion( q2, dest ); - - Quaternion result; - - // Slerp - QuaternionSlerp( src, dest, flPercent, result ); - - // Convert to euler - QAngleByValue output; - QuaternionAngles( result, output ); - return output; -} - -#endif // VECTOR_NO_SLOW_OPERATIONS - - -// Swap two of anything. -template -FORCEINLINE void swap( T& x, T& y ) -{ - T temp = x; - x = y; - y = temp; -} - -template FORCEINLINE T AVG(T a, T b) -{ - return (a+b)/2; -} - -// number of elements in an array of static size -#define NELEMS(x) ((sizeof(x))/sizeof(x[0])) - -// XYZ macro, for printf type functions - ex printf("%f %f %f",XYZ(myvector)); -#define XYZ(v) (v).x,(v).y,(v).z - -// -// Returns a clamped value in the range [min, max]. -// -#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) - -inline float Sign( float x ) -{ - return (x <0.0f) ? -1.0f : 1.0f; -} - -// -// Clamps the input integer to the given array bounds. -// Equivalent to the following, but without using any branches: -// -// if( n < 0 ) return 0; -// else if ( n > maxindex ) return maxindex; -// else return n; -// -// This is not always a clear performance win, but when you have situations where a clamped -// value is thrashing against a boundary this is a big win. (ie, valid, invalid, valid, invalid, ...) -// -// Note: This code has been run against all possible integers. -// -inline int ClampArrayBounds( int n, unsigned maxindex ) -{ - // mask is 0 if less than 4096, 0xFFFFFFFF if greater than - unsigned int inrangemask = 0xFFFFFFFF + (((unsigned) n) > maxindex ); - unsigned int lessthan0mask = 0xFFFFFFFF + ( n >= 0 ); - - // If the result was valid, set the result, (otherwise sets zero) - int result = (inrangemask & n); - - // if the result was out of range or zero. - result |= ((~inrangemask) & (~lessthan0mask)) & maxindex; - - return result; -} - - -#define BOX_ON_PLANE_SIDE(emins, emaxs, p) \ - (((p)->type < 3)? \ - ( \ - ((p)->dist <= (emins)[(p)->type])? \ - 1 \ - : \ - ( \ - ((p)->dist >= (emaxs)[(p)->type])?\ - 2 \ - : \ - 3 \ - ) \ - ) \ - : \ - BoxOnPlaneSide( (emins), (emaxs), (p))) - -//----------------------------------------------------------------------------- -// FIXME: Vector versions.... the float versions will go away hopefully soon! -//----------------------------------------------------------------------------- - -void AngleVectors (const QAngle& angles, Vector *forward); -void AngleVectors (const QAngle& angles, Vector *forward, Vector *right, Vector *up); -void AngleVectorsTranspose (const QAngle& angles, Vector *forward, Vector *right, Vector *up); -void AngleMatrix (const QAngle &angles, matrix3x4_t &mat ); -void AngleMatrix( const QAngle &angles, const Vector &position, matrix3x4_t &mat ); -void AngleMatrix (const RadianEuler &angles, matrix3x4_t &mat ); -void AngleMatrix( RadianEuler const &angles, const Vector &position, matrix3x4_t &mat ); -void AngleIMatrix (const QAngle &angles, matrix3x4_t &mat ); -void AngleIMatrix (const QAngle &angles, const Vector &position, matrix3x4_t &mat ); -void AngleIMatrix (const RadianEuler &angles, matrix3x4_t &mat ); -void VectorAngles( const Vector &forward, QAngle &angles ); -void VectorAngles( const Vector &forward, const Vector &pseudoup, QAngle &angles ); -void VectorMatrix( const Vector &forward, matrix3x4_t &mat ); -void VectorVectors( const Vector &forward, Vector &right, Vector &up ); -void SetIdentityMatrix( matrix3x4_t &mat ); -void SetScaleMatrix( float x, float y, float z, matrix3x4_t &dst ); -void MatrixBuildRotationAboutAxis( const Vector &vAxisOfRot, float angleDegrees, matrix3x4_t &dst ); - -inline void SetScaleMatrix( float flScale, matrix3x4_t &dst ) -{ - SetScaleMatrix( flScale, flScale, flScale, dst ); -} - -inline void SetScaleMatrix( const Vector& scale, matrix3x4_t &dst ) -{ - SetScaleMatrix( scale.x, scale.y, scale.z, dst ); -} - -// Computes the inverse transpose -void MatrixTranspose( matrix3x4_t& mat ); -void MatrixTranspose( const matrix3x4_t& src, matrix3x4_t& dst ); -void MatrixInverseTranspose( const matrix3x4_t& src, matrix3x4_t& dst ); - -inline void PositionMatrix( const Vector &position, matrix3x4_t &mat ) -{ - MatrixSetColumn( position, 3, mat ); -} - -inline void MatrixPosition( const matrix3x4_t &matrix, Vector &position ) -{ - MatrixGetColumn( matrix, 3, position ); -} - -inline void VectorRotate( const Vector& in1, const matrix3x4_t &in2, Vector &out) -{ - VectorRotate( &in1.x, in2, &out.x ); -} - -inline void VectorIRotate( const Vector& in1, const matrix3x4_t &in2, Vector &out) -{ - VectorIRotate( &in1.x, in2, &out.x ); -} - -inline void MatrixAngles( const matrix3x4_t &matrix, QAngle &angles ) -{ - MatrixAngles( matrix, &angles.x ); -} - -inline void MatrixAngles( const matrix3x4_t &matrix, QAngle &angles, Vector &position ) -{ - MatrixAngles( matrix, angles ); - MatrixPosition( matrix, position ); -} - -inline void MatrixAngles( const matrix3x4_t &matrix, RadianEuler &angles ) -{ - MatrixAngles( matrix, &angles.x ); - - angles.Init( DEG2RAD( angles.z ), DEG2RAD( angles.x ), DEG2RAD( angles.y ) ); -} - -void MatrixAngles( const matrix3x4_t &mat, RadianEuler &angles, Vector &position ); - -void MatrixAngles( const matrix3x4_t &mat, Quaternion &q, Vector &position ); - -inline int VectorCompare (const Vector& v1, const Vector& v2) -{ - return v1 == v2; -} - -inline void VectorTransform (const Vector& in1, const matrix3x4_t &in2, Vector &out) -{ - VectorTransform( &in1.x, in2, &out.x ); -} - -inline void VectorITransform (const Vector& in1, const matrix3x4_t &in2, Vector &out) -{ - VectorITransform( &in1.x, in2, &out.x ); -} - -/* -inline void DecomposeRotation( const matrix3x4_t &mat, Vector &out ) -{ - DecomposeRotation( mat, &out.x ); -} -*/ - -inline int BoxOnPlaneSide (const Vector& emins, const Vector& emaxs, const cplane_t *plane ) -{ - return BoxOnPlaneSide( &emins.x, &emaxs.x, plane ); -} - -inline void VectorFill(Vector& a, float b) -{ - a[0]=a[1]=a[2]=b; -} - -inline void VectorNegate(Vector& a) -{ - a[0] = -a[0]; - a[1] = -a[1]; - a[2] = -a[2]; -} - -inline vec_t VectorAvg(Vector& a) -{ - return ( a[0] + a[1] + a[2] ) / 3; -} - -//----------------------------------------------------------------------------- -// Box/plane test (slow version) -//----------------------------------------------------------------------------- -inline int FASTCALL BoxOnPlaneSide2 (const Vector& emins, const Vector& emaxs, const cplane_t *p, float tolerance = 0.f ) -{ - Vector corners[2]; - - if (p->normal[0] < 0) - { - corners[0][0] = emins[0]; - corners[1][0] = emaxs[0]; - } - else - { - corners[1][0] = emins[0]; - corners[0][0] = emaxs[0]; - } - - if (p->normal[1] < 0) - { - corners[0][1] = emins[1]; - corners[1][1] = emaxs[1]; - } - else - { - corners[1][1] = emins[1]; - corners[0][1] = emaxs[1]; - } - - if (p->normal[2] < 0) - { - corners[0][2] = emins[2]; - corners[1][2] = emaxs[2]; - } - else - { - corners[1][2] = emins[2]; - corners[0][2] = emaxs[2]; - } - - int sides = 0; - - float dist1 = DotProduct (p->normal, corners[0]) - p->dist; - if (dist1 >= tolerance) - sides = 1; - - float dist2 = DotProduct (p->normal, corners[1]) - p->dist; - if (dist2 < -tolerance) - sides |= 2; - - return sides; -} - -//----------------------------------------------------------------------------- -// Helpers for bounding box construction -//----------------------------------------------------------------------------- - -void ClearBounds (Vector& mins, Vector& maxs); -void AddPointToBounds (const Vector& v, Vector& mins, Vector& maxs); - -// -// COLORSPACE/GAMMA CONVERSION STUFF -// -void BuildGammaTable( float gamma, float texGamma, float brightness, int overbright ); - -// convert texture to linear 0..1 value -inline float TexLightToLinear( int c, int exponent ) -{ - extern float power2_n[256]; - Assert( exponent >= -128 && exponent <= 127 ); - return ( float )c * power2_n[exponent+128]; -} - - -// convert texture to linear 0..1 value -int LinearToTexture( float f ); -// converts 0..1 linear value to screen gamma (0..255) -int LinearToScreenGamma( float f ); -float TextureToLinear( int c ); - -// compressed color format -struct ColorRGBExp32 -{ - byte r, g, b; - signed char exponent; -}; - -void ColorRGBExp32ToVector( const ColorRGBExp32& in, Vector& out ); -void VectorToColorRGBExp32( const Vector& v, ColorRGBExp32 &c ); - -// solve for "x" where "a x^2 + b x + c = 0", return true if solution exists -bool SolveQuadratic( float a, float b, float c, float &root1, float &root2 ); - -// solves for "a, b, c" where "a x^2 + b x + c = y", return true if solution exists -bool SolveInverseQuadratic( float x1, float y1, float x2, float y2, float x3, float y3, float &a, float &b, float &c ); - -// solves for a,b,c specified as above, except that it always creates a monotonically increasing or -// decreasing curve if the data is monotonically increasing or decreasing. In order to enforce the -// monoticity condition, it is possible that the resulting quadratic will only approximate the data -// instead of interpolating it. This code is not especially fast. -bool SolveInverseQuadraticMonotonic( float x1, float y1, float x2, float y2, - float x3, float y3, float &a, float &b, float &c ); - - - - -// solves for "a, b, c" where "1/(a x^2 + b x + c ) = y", return true if solution exists -bool SolveInverseReciprocalQuadratic( float x1, float y1, float x2, float y2, float x3, float y3, float &a, float &b, float &c ); - -// rotate a vector around the Z axis (YAW) -void VectorYawRotate( const Vector& in, float flYaw, Vector &out); - - -// Bias takes an X value between 0 and 1 and returns another value between 0 and 1 -// The curve is biased towards 0 or 1 based on biasAmt, which is between 0 and 1. -// Lower values of biasAmt bias the curve towards 0 and higher values bias it towards 1. -// -// For example, with biasAmt = 0.2, the curve looks like this: -// -// 1 -// | * -// | * -// | * -// | ** -// | ** -// | **** -// |********* -// |___________________ -// 0 1 -// -// -// With biasAmt = 0.8, the curve looks like this: -// -// 1 -// | ************** -// | ** -// | * -// | * -// |* -// |* -// |* -// |___________________ -// 0 1 -// -// With a biasAmt of 0.5, Bias returns X. -float Bias( float x, float biasAmt ); - - -// Gain is similar to Bias, but biasAmt biases towards or away from 0.5. -// Lower bias values bias towards 0.5 and higher bias values bias away from it. -// -// For example, with biasAmt = 0.2, the curve looks like this: -// -// 1 -// | * -// | * -// | ** -// | *************** -// | ** -// | * -// |* -// |___________________ -// 0 1 -// -// -// With biasAmt = 0.8, the curve looks like this: -// -// 1 -// | ***** -// | *** -// | * -// | * -// | * -// | *** -// |***** -// |___________________ -// 0 1 -float Gain( float x, float biasAmt ); - - -// SmoothCurve maps a 0-1 value into another 0-1 value based on a cosine wave -// where the derivatives of the function at 0 and 1 (and 0.5) are 0. This is useful for -// any fadein/fadeout effect where it should start and end smoothly. -// -// The curve looks like this: -// -// 1 -// | ** -// | * * -// | * * -// | * * -// | * * -// | ** ** -// |*** *** -// |___________________ -// 0 1 -// -float SmoothCurve( float x ); - - -// This works like SmoothCurve, with two changes: -// -// 1. Instead of the curve peaking at 0.5, it will peak at flPeakPos. -// (So if you specify flPeakPos=0.2, then the peak will slide to the left). -// -// 2. flPeakSharpness is a 0-1 value controlling the sharpness of the peak. -// Low values blunt the peak and high values sharpen the peak. -float SmoothCurve_Tweak( float x, float flPeakPos=0.5, float flPeakSharpness=0.5 ); - - -//float ExponentialDecay( float halflife, float dt ); -//float ExponentialDecay( float decayTo, float decayTime, float dt ); - -// halflife is time for value to reach 50% -inline float ExponentialDecay( float halflife, float dt ) -{ - // log(0.5) == -0.69314718055994530941723212145818 - return expf( -0.69314718f / halflife * dt); -} - -// decayTo is factor the value should decay to in decayTime -inline float ExponentialDecay( float decayTo, float decayTime, float dt ) -{ - return expf( logf( decayTo ) / decayTime * dt); -} - -// Get the integrated distanced traveled -// decayTo is factor the value should decay to in decayTime -// dt is the time relative to the last velocity update -inline float ExponentialDecayIntegral( float decayTo, float decayTime, float dt ) -{ - return (powf( decayTo, dt / decayTime) * decayTime - decayTime) / logf( decayTo ); -} - -// hermite basis function for smooth interpolation -// Similar to Gain() above, but very cheap to call -// value should be between 0 & 1 inclusive -inline float SimpleSpline( float value ) -{ - float valueSquared = value * value; - - // Nice little ease-in, ease-out spline-like curve - return (3 * valueSquared - 2 * valueSquared * value); -} - -// remaps a value in [startInterval, startInterval+rangeInterval] from linear to -// spline using SimpleSpline -inline float SimpleSplineRemapVal( float val, float A, float B, float C, float D) -{ - if ( A == B ) - return val >= B ? D : C; - float cVal = (val - A) / (B - A); - return C + (D - C) * SimpleSpline( cVal ); -} - -// remaps a value in [startInterval, startInterval+rangeInterval] from linear to -// spline using SimpleSpline -inline float SimpleSplineRemapValClamped( float val, float A, float B, float C, float D ) -{ - if ( A == B ) - return val >= B ? D : C; - float cVal = (val - A) / (B - A); - cVal = clamp( cVal, 0.0f, 1.0f ); - return C + (D - C) * SimpleSpline( cVal ); -} - -FORCEINLINE int RoundFloatToInt(float f) -{ -#if defined( _X360 ) -#ifdef Assert - Assert( IsFPUControlWordSet() ); -#endif - union - { - double flResult; - int pResult[2]; - }; - flResult = __fctiw( f ); - return pResult[1]; -#else // !X360 - int nResult; -#if defined( _WIN32 ) - __asm - { - fld f - fistp nResult - } -#elif _LINUX - __asm __volatile__ ( - "fistpl %0;": "=m" (nResult): "t" (f) : "st" - ); -#endif - return nResult; -#endif -} - -FORCEINLINE unsigned char RoundFloatToByte(float f) -{ -#if defined( _X360 ) -#ifdef Assert - Assert( IsFPUControlWordSet() ); -#endif - union - { - double flResult; - int pIntResult[2]; - unsigned char pResult[8]; - }; - flResult = __fctiw( f ); -#ifdef Assert - Assert( pIntResult[1] >= 0 && pIntResult[1] <= 255 ); -#endif - return pResult[8]; - -#else // !X360 - - int nResult; - -#if defined( _WIN32 ) - __asm - { - fld f - fistp nResult - } -#elif _LINUX - __asm __volatile__ ( - "fistpl %0;": "=m" (nResult): "t" (f) : "st" - ); -#endif - -#ifdef Assert - Assert( nResult >= 0 && nResult <= 255 ); -#endif - return nResult; - -#endif -} - -FORCEINLINE unsigned long RoundFloatToUnsignedLong(float f) -{ -#if defined( _X360 ) -#ifdef Assert - Assert( IsFPUControlWordSet() ); -#endif - union - { - double flResult; - int pIntResult[2]; - unsigned long pResult[2]; - }; - flResult = __fctiw( f ); - Assert( pIntResult[1] >= 0 ); - return pResult[1]; -#else // !X360 - - unsigned char nResult[8]; - -#if defined( _WIN32 ) - __asm - { - fld f - fistp qword ptr nResult - } -#elif _LINUX - __asm __volatile__ ( - "fistpl %0;": "=m" (nResult): "t" (f) : "st" - ); -#endif - - return *((unsigned long*)nResult); -#endif -} - -FORCEINLINE bool IsIntegralValue( float flValue, float flTolerance = 0.001f ) -{ - return fabs( RoundFloatToInt( flValue ) - flValue ) < flTolerance; -} - -// Fast, accurate ftol: -FORCEINLINE int Float2Int( float a ) -{ -#if defined( _X360 ) - union - { - double flResult; - int pResult[2]; - }; - flResult = __fctiwz( a ); - return pResult[1]; -#else // !X360 - - int RetVal; - -#if defined( _WIN32 ) - int CtrlwdHolder; - int CtrlwdSetter; - __asm - { - fld a // push 'a' onto the FP stack - fnstcw CtrlwdHolder // store FPU control word - movzx eax, CtrlwdHolder // move and zero extend word into eax - and eax, 0xFFFFF3FF // set all bits except rounding bits to 1 - or eax, 0x00000C00 // set rounding mode bits to round towards zero - mov CtrlwdSetter, eax // Prepare to set the rounding mode -- prepare to enter plaid! - fldcw CtrlwdSetter // Entering plaid! - fistp RetVal // Store and converted (to int) result - fldcw CtrlwdHolder // Restore control word - } -#elif _LINUX - RetVal = static_cast( a ); -#endif - - return RetVal; -#endif -} - -// Over 15x faster than: (int)floor(value) -inline int Floor2Int( float a ) -{ - int RetVal; - -#if defined( _X360 ) - RetVal = (int)floor( a ); -#elif defined( _WIN32 ) - int CtrlwdHolder; - int CtrlwdSetter; - __asm - { - fld a // push 'a' onto the FP stack - fnstcw CtrlwdHolder // store FPU control word - movzx eax, CtrlwdHolder // move and zero extend word into eax - and eax, 0xFFFFF3FF // set all bits except rounding bits to 1 - or eax, 0x00000400 // set rounding mode bits to round down - mov CtrlwdSetter, eax // Prepare to set the rounding mode -- prepare to enter plaid! - fldcw CtrlwdSetter // Entering plaid! - fistp RetVal // Store floored and converted (to int) result - fldcw CtrlwdHolder // Restore control word - } -#elif _LINUX - RetVal = static_cast( floor(a) ); -#endif - - return RetVal; -} - -//----------------------------------------------------------------------------- -// Fast color conversion from float to unsigned char -//----------------------------------------------------------------------------- -FORCEINLINE unsigned char FastFToC( float c ) -{ - volatile float dc; - - // ieee trick - dc = c * 255.0f + (float)(1 << 23); - - // return the lsb -#if defined( _X360 ) - return ((unsigned char*)&dc)[3]; -#else - return *(unsigned char*)&dc; -#endif -} - -//----------------------------------------------------------------------------- -// Purpose: Bound input float to .001 (millisecond) boundary -// Input : in - -// Output : inline float -//----------------------------------------------------------------------------- -inline float ClampToMsec( float in ) -{ - int msec = Floor2Int( in * 1000.0f + 0.5f ); - return msec / 1000.0f; -} - -// Over 15x faster than: (int)ceil(value) -inline int Ceil2Int( float a ) -{ - int RetVal; - -#if defined( _X360 ) - RetVal = (int)ceil( a ); -#elif defined( _WIN32 ) - int CtrlwdHolder; - int CtrlwdSetter; - __asm - { - fld a // push 'a' onto the FP stack - fnstcw CtrlwdHolder // store FPU control word - movzx eax, CtrlwdHolder // move and zero extend word into eax - and eax, 0xFFFFF3FF // set all bits except rounding bits to 1 - or eax, 0x00000800 // set rounding mode bits to round down - mov CtrlwdSetter, eax // Prepare to set the rounding mode -- prepare to enter plaid! - fldcw CtrlwdSetter // Entering plaid! - fistp RetVal // Store floored and converted (to int) result - fldcw CtrlwdHolder // Restore control word - } -#elif _LINUX - RetVal = static_cast( ceil(a) ); -#endif - - return RetVal; -} - - -// Regular signed area of triangle -#define TriArea2D( A, B, C ) \ - ( 0.5f * ( ( B.x - A.x ) * ( C.y - A.y ) - ( B.y - A.y ) * ( C.x - A.x ) ) ) - -// This version doesn't premultiply by 0.5f, so it's the area of the rectangle instead -#define TriArea2DTimesTwo( A, B, C ) \ - ( ( ( B.x - A.x ) * ( C.y - A.y ) - ( B.y - A.y ) * ( C.x - A.x ) ) ) - - -// Get the barycentric coordinates of "pt" in triangle [A,B,C]. -inline void GetBarycentricCoords2D( - Vector2D const &A, - Vector2D const &B, - Vector2D const &C, - Vector2D const &pt, - float bcCoords[3] ) -{ - // Note, because to top and bottom are both x2, the issue washes out in the composite - float invTriArea = 1.0f / TriArea2DTimesTwo( A, B, C ); - - // NOTE: We assume here that the lightmap coordinate vertices go counterclockwise. - // If not, TriArea2D() is negated so this works out right. - bcCoords[0] = TriArea2DTimesTwo( B, C, pt ) * invTriArea; - bcCoords[1] = TriArea2DTimesTwo( C, A, pt ) * invTriArea; - bcCoords[2] = TriArea2DTimesTwo( A, B, pt ) * invTriArea; -} - - -// Return true of the sphere might touch the box (the sphere is actually treated -// like a box itself, so this may return true if the sphere's bounding box touches -// a corner of the box but the sphere itself doesn't). -inline bool QuickBoxSphereTest( - const Vector& vOrigin, - float flRadius, - const Vector& bbMin, - const Vector& bbMax ) -{ - return vOrigin.x - flRadius < bbMax.x && vOrigin.x + flRadius > bbMin.x && - vOrigin.y - flRadius < bbMax.y && vOrigin.y + flRadius > bbMin.y && - vOrigin.z - flRadius < bbMax.z && vOrigin.z + flRadius > bbMin.z; -} - - -// Return true of the boxes intersect (but not if they just touch). -inline bool QuickBoxIntersectTest( - const Vector& vBox1Min, - const Vector& vBox1Max, - const Vector& vBox2Min, - const Vector& vBox2Max ) -{ - return - vBox1Min.x < vBox2Max.x && vBox1Max.x > vBox2Min.x && - vBox1Min.y < vBox2Max.y && vBox1Max.y > vBox2Min.y && - vBox1Min.z < vBox2Max.z && vBox1Max.z > vBox2Min.z; -} - - -extern float GammaToLinearFullRange( float gamma ); -extern float LinearToGammaFullRange( float linear ); -extern float GammaToLinear( float gamma ); -extern float LinearToGamma( float linear ); - -extern float SrgbGammaToLinear( float flSrgbGammaValue ); -extern float SrgbLinearToGamma( float flLinearValue ); -extern float X360GammaToLinear( float fl360GammaValue ); -extern float X360LinearToGamma( float flLinearValue ); -extern float SrgbGammaTo360Gamma( float flSrgbGammaValue ); - -// linear (0..4) to screen corrected vertex space (0..1?) -FORCEINLINE float LinearToVertexLight( float f ) -{ - extern float lineartovertex[4096]; - - // Gotta clamp before the multiply; could overflow... - // assume 0..4 range - int i = RoundFloatToInt( f * 1024.f ); - - // Presumably the comman case will be not to clamp, so check that first: - if( (unsigned)i > 4095 ) - { - if ( i < 0 ) - i = 0; // Compare to zero instead of 4095 to save 4 bytes in the instruction stream - else - i = 4095; - } - - return lineartovertex[i]; -} - - -FORCEINLINE unsigned char LinearToLightmap( float f ) -{ - extern unsigned char lineartolightmap[4096]; - - // Gotta clamp before the multiply; could overflow... - int i = RoundFloatToInt( f * 1024.f ); // assume 0..4 range - - // Presumably the comman case will be not to clamp, so check that first: - if ( (unsigned)i > 4095 ) - { - if ( i < 0 ) - i = 0; // Compare to zero instead of 4095 to save 4 bytes in the instruction stream - else - i = 4095; - } - - return lineartolightmap[i]; -} - -FORCEINLINE void ColorClamp( Vector& color ) -{ - float maxc = max( color.x, max( color.y, color.z ) ); - if ( maxc > 1.0f ) - { - float ooMax = 1.0f / maxc; - color.x *= ooMax; - color.y *= ooMax; - color.z *= ooMax; - } - - if ( color[0] < 0.f ) color[0] = 0.f; - if ( color[1] < 0.f ) color[1] = 0.f; - if ( color[2] < 0.f ) color[2] = 0.f; -} - -inline void ColorClampTruncate( Vector& color ) -{ - if (color[0] > 1.0f) color[0] = 1.0f; else if (color[0] < 0.0f) color[0] = 0.0f; - if (color[1] > 1.0f) color[1] = 1.0f; else if (color[1] < 0.0f) color[1] = 0.0f; - if (color[2] > 1.0f) color[2] = 1.0f; else if (color[2] < 0.0f) color[2] = 0.0f; -} - -// Interpolate a Catmull-Rom spline. -// t is a [0,1] value and interpolates a curve between p2 and p3. -void Catmull_Rom_Spline( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector &output ); - -// Interpolate a Catmull-Rom spline. -// Returns the tangent of the point at t of the spline -void Catmull_Rom_Spline_Tangent( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector &output ); - -// area under the curve [0..t] -void Catmull_Rom_Spline_Integral( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// area under the curve [0..1] -void Catmull_Rom_Spline_Integral( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - Vector& output ); - -// Interpolate a Catmull-Rom spline. -// Normalize p2->p1 and p3->p4 to be the same length as p2->p3 -void Catmull_Rom_Spline_Normalize( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector &output ); - -// area under the curve [0..t] -// Normalize p2->p1 and p3->p4 to be the same length as p2->p3 -void Catmull_Rom_Spline_Integral_Normalize( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// Interpolate a Catmull-Rom spline. -// Normalize p2.x->p1.x and p3.x->p4.x to be the same length as p2.x->p3.x -void Catmull_Rom_Spline_NormalizeX( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector &output ); - -// area under the curve [0..t] -void Catmull_Rom_Spline_NormalizeX( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// Interpolate a Hermite spline. -// t is a [0,1] value and interpolates a curve between p1 and p2 with the deltas d1 and d2. -void Hermite_Spline( - const Vector &p1, - const Vector &p2, - const Vector &d1, - const Vector &d2, - float t, - Vector& output ); - -float Hermite_Spline( - float p1, - float p2, - float d1, - float d2, - float t ); - -// t is a [0,1] value and interpolates a curve between p1 and p2 with the slopes p0->p1 and p1->p2 -void Hermite_Spline( - const Vector &p0, - const Vector &p1, - const Vector &p2, - float t, - Vector& output ); - -float Hermite_Spline( - float p0, - float p1, - float p2, - float t ); - - -void Hermite_SplineBasis( float t, float basis[] ); - -void Hermite_Spline( - const Quaternion &q0, - const Quaternion &q1, - const Quaternion &q2, - float t, - Quaternion &output ); - - -// See http://en.wikipedia.org/wiki/Kochanek-Bartels_curves -// -// Tension: -1 = Round -> 1 = Tight -// Bias: -1 = Pre-shoot (bias left) -> 1 = Post-shoot (bias right) -// Continuity: -1 = Box corners -> 1 = Inverted corners -// -// If T=B=C=0 it's the same matrix as Catmull-Rom. -// If T=1 & B=C=0 it's the same as Cubic. -// If T=B=0 & C=-1 it's just linear interpolation -// -// See http://news.povray.org/povray.binaries.tutorials/attachment/%3CXns91B880592482seed7@povray.org%3E/Splines.bas.txt -// for example code and descriptions of various spline types... -// -void Kochanek_Bartels_Spline( - float tension, - float bias, - float continuity, - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -void Kochanek_Bartels_Spline_NormalizeX( - float tension, - float bias, - float continuity, - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// See link at Kochanek_Bartels_Spline for info on the basis matrix used -void Cubic_Spline( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -void Cubic_Spline_NormalizeX( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// See link at Kochanek_Bartels_Spline for info on the basis matrix used -void BSpline( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -void BSpline_NormalizeX( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// See link at Kochanek_Bartels_Spline for info on the basis matrix used -void Parabolic_Spline( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -void Parabolic_Spline_NormalizeX( - const Vector &p1, - const Vector &p2, - const Vector &p3, - const Vector &p4, - float t, - Vector& output ); - -// quintic interpolating polynomial from Perlin. -// 0->0, 1->1, smooth-in between with smooth tangents -FORCEINLINE float QuinticInterpolatingPolynomial(float t) -{ - // 6t^5-15t^4+10t^3 - return t * t * t *( t * ( t* 6.0 - 15.0 ) + 10.0 ); -} - -// given a table of sorted tabulated positions, return the two indices and blendfactor to linear -// interpolate. Does a search. Can be used to find the blend value to interpolate between -// keyframes. -void GetInterpolationData( float const *pKnotPositions, - float const *pKnotValues, - int nNumValuesinList, - int nInterpolationRange, - float flPositionToInterpolateAt, - bool bWrap, - float *pValueA, - float *pValueB, - float *pInterpolationValue); - -float RangeCompressor( float flValue, float flMin, float flMax, float flBase ); - -// Get the minimum distance from vOrigin to the bounding box defined by [mins,maxs] -// using voronoi regions. -// 0 is returned if the origin is inside the box. -float CalcSqrDistanceToAABB( const Vector &mins, const Vector &maxs, const Vector &point ); -void CalcClosestPointOnAABB( const Vector &mins, const Vector &maxs, const Vector &point, Vector &closestOut ); -void CalcSqrDistAndClosestPointOnAABB( const Vector &mins, const Vector &maxs, const Vector &point, Vector &closestOut, float &distSqrOut ); - -inline float CalcDistanceToAABB( const Vector &mins, const Vector &maxs, const Vector &point ) -{ - float flDistSqr = CalcSqrDistanceToAABB( mins, maxs, point ); - return sqrt(flDistSqr); -} - -// Get the closest point from P to the (infinite) line through vLineA and vLineB and -// calculate the shortest distance from P to the line. -// If you pass in a value for t, it will tell you the t for (A + (B-A)t) to get the closest point. -// If the closest point lies on the segment between A and B, then 0 <= t <= 1. -void CalcClosestPointOnLine( const Vector &P, const Vector &vLineA, const Vector &vLineB, Vector &vClosest, float *t=0 ); -float CalcDistanceToLine( const Vector &P, const Vector &vLineA, const Vector &vLineB, float *t=0 ); -float CalcDistanceSqrToLine( const Vector &P, const Vector &vLineA, const Vector &vLineB, float *t=0 ); - -// The same three functions as above, except now the line is closed between A and B. -void CalcClosestPointOnLineSegment( const Vector &P, const Vector &vLineA, const Vector &vLineB, Vector &vClosest, float *t=0 ); -float CalcDistanceToLineSegment( const Vector &P, const Vector &vLineA, const Vector &vLineB, float *t=0 ); -float CalcDistanceSqrToLineSegment( const Vector &P, const Vector &vLineA, const Vector &vLineB, float *t=0 ); - -// A function to compute the closes line segment connnection two lines (or false if the lines are parallel, etc.) -bool CalcLineToLineIntersectionSegment( - const Vector& p1,const Vector& p2,const Vector& p3,const Vector& p4,Vector *s1,Vector *s2, - float *t1, float *t2 ); - -// The above functions in 2D -void CalcClosestPointOnLine2D( Vector2D const &P, Vector2D const &vLineA, Vector2D const &vLineB, Vector2D &vClosest, float *t=0 ); -float CalcDistanceToLine2D( Vector2D const &P, Vector2D const &vLineA, Vector2D const &vLineB, float *t=0 ); -float CalcDistanceSqrToLine2D( Vector2D const &P, Vector2D const &vLineA, Vector2D const &vLineB, float *t=0 ); -void CalcClosestPointOnLineSegment2D( Vector2D const &P, Vector2D const &vLineA, Vector2D const &vLineB, Vector2D &vClosest, float *t=0 ); -float CalcDistanceToLineSegment2D( Vector2D const &P, Vector2D const &vLineA, Vector2D const &vLineB, float *t=0 ); -float CalcDistanceSqrToLineSegment2D( Vector2D const &P, Vector2D const &vLineA, Vector2D const &vLineB, float *t=0 ); - -// Init the mathlib -void MathLib_Init( float gamma = 2.2f, float texGamma = 2.2f, float brightness = 0.0f, int overbright = 2.0f, bool bAllow3DNow = true, bool bAllowSSE = true, bool bAllowSSE2 = true, bool bAllowMMX = true ); -bool MathLib_3DNowEnabled( void ); -bool MathLib_MMXEnabled( void ); -bool MathLib_SSEEnabled( void ); -bool MathLib_SSE2Enabled( void ); - -float Approach( float target, float value, float speed ); -float ApproachAngle( float target, float value, float speed ); -float AngleDiff( float destAngle, float srcAngle ); -float AngleDistance( float next, float cur ); -float AngleNormalize( float angle ); - -// ensure that 0 <= angle <= 360 -float AngleNormalizePositive( float angle ); - -bool AnglesAreEqual( float a, float b, float tolerance = 0.0f ); - - -void RotationDeltaAxisAngle( const QAngle &srcAngles, const QAngle &destAngles, Vector &deltaAxis, float &deltaAngle ); -void RotationDelta( const QAngle &srcAngles, const QAngle &destAngles, QAngle *out ); - -void ComputeTrianglePlane( const Vector& v1, const Vector& v2, const Vector& v3, Vector& normal, float& intercept ); -int PolyFromPlane( Vector *outVerts, const Vector& normal, float dist, float fHalfScale = 9000.0f ); -int ClipPolyToPlane( Vector *inVerts, int vertCount, Vector *outVerts, const Vector& normal, float dist, float fOnPlaneEpsilon = 0.1f ); -int ClipPolyToPlane_Precise( double *inVerts, int vertCount, double *outVerts, const double *normal, double dist, double fOnPlaneEpsilon = 0.1 ); - -//----------------------------------------------------------------------------- -// Computes a reasonable tangent space for a triangle -//----------------------------------------------------------------------------- -void CalcTriangleTangentSpace( const Vector &p0, const Vector &p1, const Vector &p2, - const Vector2D &t0, const Vector2D &t1, const Vector2D& t2, - Vector &sVect, Vector &tVect ); - -//----------------------------------------------------------------------------- -// Transforms a AABB into another space; which will inherently grow the box. -//----------------------------------------------------------------------------- -void TransformAABB( const matrix3x4_t &in1, const Vector &vecMinsIn, const Vector &vecMaxsIn, Vector &vecMinsOut, Vector &vecMaxsOut ); - -//----------------------------------------------------------------------------- -// Uses the inverse transform of in1 -//----------------------------------------------------------------------------- -void ITransformAABB( const matrix3x4_t &in1, const Vector &vecMinsIn, const Vector &vecMaxsIn, Vector &vecMinsOut, Vector &vecMaxsOut ); - -//----------------------------------------------------------------------------- -// Rotates a AABB into another space; which will inherently grow the box. -// (same as TransformAABB, but doesn't take the translation into account) -//----------------------------------------------------------------------------- -void RotateAABB( const matrix3x4_t &in1, const Vector &vecMinsIn, const Vector &vecMaxsIn, Vector &vecMinsOut, Vector &vecMaxsOut ); - -//----------------------------------------------------------------------------- -// Uses the inverse transform of in1 -//----------------------------------------------------------------------------- -void IRotateAABB( const matrix3x4_t &in1, const Vector &vecMinsIn, const Vector &vecMaxsIn, Vector &vecMinsOut, Vector &vecMaxsOut ); - -//----------------------------------------------------------------------------- -// Transform a plane -//----------------------------------------------------------------------------- -inline void MatrixTransformPlane( const matrix3x4_t &src, const cplane_t &inPlane, cplane_t &outPlane ) -{ - // What we want to do is the following: - // 1) transform the normal into the new space. - // 2) Determine a point on the old plane given by plane dist * plane normal - // 3) Transform that point into the new space - // 4) Plane dist = DotProduct( new normal, new point ) - - // An optimized version, which works if the plane is orthogonal. - // 1) Transform the normal into the new space - // 2) Realize that transforming the old plane point into the new space - // is given by [ d * n'x + Tx, d * n'y + Ty, d * n'z + Tz ] - // where d = old plane dist, n' = transformed normal, Tn = translational component of transform - // 3) Compute the new plane dist using the dot product of the normal result of #2 - - // For a correct result, this should be an inverse-transpose matrix - // but that only matters if there are nonuniform scale or skew factors in this matrix. - VectorRotate( inPlane.normal, src, outPlane.normal ); - outPlane.dist = inPlane.dist * DotProduct( outPlane.normal, outPlane.normal ); - outPlane.dist += outPlane.normal.x * src[0][3] + outPlane.normal.y * src[1][3] + outPlane.normal.z * src[2][3]; -} - -inline void MatrixITransformPlane( const matrix3x4_t &src, const cplane_t &inPlane, cplane_t &outPlane ) -{ - // The trick here is that Tn = translational component of transform, - // but for an inverse transform, Tn = - R^-1 * T - Vector vecTranslation; - MatrixGetColumn( src, 3, vecTranslation ); - - Vector vecInvTranslation; - VectorIRotate( vecTranslation, src, vecInvTranslation ); - - VectorIRotate( inPlane.normal, src, outPlane.normal ); - outPlane.dist = inPlane.dist * DotProduct( outPlane.normal, outPlane.normal ); - outPlane.dist -= outPlane.normal.x * vecInvTranslation[0] + outPlane.normal.y * vecInvTranslation[1] + outPlane.normal.z * vecInvTranslation[2]; -} - -int CeilPow2( int in ); -int FloorPow2( int in ); - -FORCEINLINE float * UnpackNormal_HEND3N( const unsigned int *pPackedNormal, float *pNormal ) -{ - int temp[3]; - temp[0] = ((*pPackedNormal >> 0L) & 0x7ff); - if ( temp[0] & 0x400 ) - { - temp[0] = 2048 - temp[0]; - } - temp[1] = ((*pPackedNormal >> 11L) & 0x7ff); - if ( temp[1] & 0x400 ) - { - temp[1] = 2048 - temp[1]; - } - temp[2] = ((*pPackedNormal >> 22L) & 0x3ff); - if ( temp[2] & 0x200 ) - { - temp[2] = 1024 - temp[2]; - } - pNormal[0] = (float)temp[0] * 1.0f/1023.0f; - pNormal[1] = (float)temp[1] * 1.0f/1023.0f; - pNormal[2] = (float)temp[2] * 1.0f/511.0f; - return pNormal; -} - -FORCEINLINE unsigned int * PackNormal_HEND3N( const float *pNormal, unsigned int *pPackedNormal ) -{ - int temp[3]; - - temp[0] = Float2Int( pNormal[0] * 1023.0f ); - temp[1] = Float2Int( pNormal[1] * 1023.0f ); - temp[2] = Float2Int( pNormal[2] * 511.0f ); - - // the normal is out of bounds, determine the source and fix - // clamping would be even more of a slowdown here - Assert( temp[0] >= -1023 && temp[0] <= 1023 ); - Assert( temp[1] >= -1023 && temp[1] <= 1023 ); - Assert( temp[2] >= -511 && temp[2] <= 511 ); - - *pPackedNormal = ( ( temp[2] & 0x3ff ) << 22L ) | - ( ( temp[1] & 0x7ff ) << 11L ) | - ( ( temp[0] & 0x7ff ) << 0L ); - return pPackedNormal; -} - -FORCEINLINE unsigned int * PackNormal_HEND3N( float nx, float ny, float nz, unsigned int *pPackedNormal ) -{ - int temp[3]; - - temp[0] = Float2Int( nx * 1023.0f ); - temp[1] = Float2Int( ny * 1023.0f ); - temp[2] = Float2Int( nz * 511.0f ); - - // the normal is out of bounds, determine the source and fix - // clamping would be even more of a slowdown here - Assert( temp[0] >= -1023 && temp[0] <= 1023 ); - Assert( temp[1] >= -1023 && temp[1] <= 1023 ); - Assert( temp[2] >= -511 && temp[2] <= 511 ); - - *pPackedNormal = ( ( temp[2] & 0x3ff ) << 22L ) | - ( ( temp[1] & 0x7ff ) << 11L ) | - ( ( temp[0] & 0x7ff ) << 0L ); - return pPackedNormal; -} - -FORCEINLINE float * UnpackNormal_SHORT2( const unsigned int *pPackedNormal, float *pNormal, bool bIsTangent = FALSE ) -{ - // Unpacks from Jason's 2-short format (fills in a 4th binormal-sign (+1/-1) value, if this is a tangent vector) - - // FIXME: short math is slow on 360 - use ints here instead (bit-twiddle to deal w/ the sign bits) - short iX = (*pPackedNormal & 0x0000FFFF); - short iY = (*pPackedNormal & 0xFFFF0000) >> 16; - - float zSign = +1; - if ( iX < 0 ) - { - zSign = -1; - iX = -iX; - } - float tSign = +1; - if ( iY < 0 ) - { - tSign = -1; - iY = -iY; - } - - pNormal[0] = ( iX - 16384.0f ) / 16384.0f; - pNormal[1] = ( iY - 16384.0f ) / 16384.0f; - pNormal[2] = zSign*sqrtf( 1.0f - ( pNormal[0]*pNormal[0] + pNormal[1]*pNormal[1] ) ); - if ( bIsTangent ) - { - pNormal[3] = tSign; - } - - return pNormal; -} - -FORCEINLINE unsigned int * PackNormal_SHORT2( float nx, float ny, float nz, unsigned int *pPackedNormal, float binormalSign = +1.0f ) -{ - // Pack a vector (ASSUMED TO BE NORMALIZED) into Jason's 4-byte (SHORT2) format. - // This simply reconstructs Z from X & Y. It uses the sign bits of the X & Y coords - // to reconstruct the sign of Z and, if this is a tangent vector, the sign of the - // binormal (this is needed because tangent/binormal vectors are supposed to follow - // UV gradients, but shaders reconstruct the binormal from the tangent and normal - // assuming that they form a right-handed basis). - - nx += 1; // [-1,+1] -> [0,2] - ny += 1; - nx *= 16384.0f; // [ 0, 2] -> [0,32768] - ny *= 16384.0f; - - // '0' and '32768' values are invalid encodings - nx = max( nx, 1.0f ); // Make sure there are no zero values - ny = max( ny, 1.0f ); - nx = min( nx, 32767.0f ); // Make sure there are no 32768 values - ny = min( ny, 32767.0f ); - - if ( nz < 0.0f ) - nx = -nx; // Set the sign bit for z - - ny *= binormalSign; // Set the sign bit for the binormal (use when encoding a tangent vector) - - // FIXME: short math is slow on 360 - use ints here instead (bit-twiddle to deal w/ the sign bits), also use Float2Int() - short sX = (short)nx; // signed short [1,32767] - short sY = (short)ny; - - *pPackedNormal = ( sX & 0x0000FFFF ) | ( sY << 16 ); // NOTE: The mask is necessary (if sX is negative and cast to an int...) - - return pPackedNormal; -} - -FORCEINLINE unsigned int * PackNormal_SHORT2( const float *pNormal, unsigned int *pPackedNormal, float binormalSign = +1.0f ) -{ - return PackNormal_SHORT2( pNormal[0], pNormal[1], pNormal[2], pPackedNormal, binormalSign ); -} - -// Unpacks a UBYTE4 normal (for a tangent, the result's fourth component receives the binormal 'sign') -FORCEINLINE float * UnpackNormal_UBYTE4( const unsigned int *pPackedNormal, float *pNormal, bool bIsTangent = FALSE ) -{ - unsigned char cX, cY; - if ( bIsTangent ) - { - cX = *pPackedNormal >> 16; // Unpack Z - cY = *pPackedNormal >> 24; // Unpack W - } - else - { - cX = *pPackedNormal >> 0; // Unpack X - cY = *pPackedNormal >> 8; // Unpack Y - } - - float x = cX - 128.0f; - float y = cY - 128.0f; - float z; - - float zSignBit = x < 0 ? 1.0f : 0.0f; // z and t negative bits (like slt asm instruction) - float tSignBit = y < 0 ? 1.0f : 0.0f; - float zSign = -( 2*zSignBit - 1 ); // z and t signs - float tSign = -( 2*tSignBit - 1 ); - - x = x*zSign - zSignBit; // 0..127 - y = y*tSign - tSignBit; - x = x - 64; // -64..63 - y = y - 64; - - float xSignBit = x < 0 ? 1.0f : 0.0f; // x and y negative bits (like slt asm instruction) - float ySignBit = y < 0 ? 1.0f : 0.0f; - float xSign = -( 2*xSignBit - 1 ); // x and y signs - float ySign = -( 2*ySignBit - 1 ); - - x = ( x*xSign - xSignBit ) / 63.0f; // 0..1 range - y = ( y*ySign - ySignBit ) / 63.0f; - z = 1.0f - x - y; - - float oolen = 1.0f / sqrt( x*x + y*y + z*z ); // Normalize and - x *= oolen * xSign; // Recover signs - y *= oolen * ySign; - z *= oolen * zSign; - - pNormal[0] = x; - pNormal[1] = y; - pNormal[2] = z; - if ( bIsTangent ) - { - pNormal[3] = tSign; - } - - return pNormal; -} - -////////////////////////////////////////////////////////////////////////////// -// See: http://www.oroboro.com/rafael/docserv.php/index/programming/article/unitv2 -// -// UBYTE4 encoding, using per-octant projection onto x+y+z=1 -// Assume input vector is already unit length -// -// binormalSign specifies 'sign' of binormal, stored in t sign bit of tangent -// (lets the shader know whether norm/tan/bin form a right-handed basis) -// -// bIsTangent is used to specify which WORD of the output to store the data -// The expected usage is to call once with the normal and once with -// the tangent and binormal sign flag, bitwise OR'ing the returned DWORDs -FORCEINLINE unsigned int * PackNormal_UBYTE4( float nx, float ny, float nz, unsigned int *pPackedNormal, bool bIsTangent = false, float binormalSign = +1.0f ) -{ - float xSign = nx < 0.0f ? -1.0f : 1.0f; // -1 or 1 sign - float ySign = ny < 0.0f ? -1.0f : 1.0f; - float zSign = nz < 0.0f ? -1.0f : 1.0f; - float tSign = binormalSign; - Assert( ( binormalSign == +1.0f ) || ( binormalSign == -1.0f ) ); - - float xSignBit = 0.5f*( 1 - xSign ); // [-1,+1] -> [1,0] - float ySignBit = 0.5f*( 1 - ySign ); // 1 is negative bit (like slt instruction) - float zSignBit = 0.5f*( 1 - zSign ); - float tSignBit = 0.5f*( 1 - binormalSign ); - - float absX = xSign*nx; // 0..1 range (abs) - float absY = ySign*ny; - float absZ = zSign*nz; - - float xbits = absX / ( absX + absY + absZ ); // Project onto x+y+z=1 plane - float ybits = absY / ( absX + absY + absZ ); - - xbits *= 63; // 0..63 - ybits *= 63; - - xbits = xbits * xSign - xSignBit; // -64..63 range - ybits = ybits * ySign - ySignBit; - xbits += 64.0f; // 0..127 range - ybits += 64.0f; - - xbits = xbits * zSign - zSignBit; // Negate based on z and t - ybits = ybits * tSign - tSignBit; // -128..127 range - - xbits += 128.0f; // 0..255 range - ybits += 128.0f; - - unsigned char cX = (unsigned char) xbits; - unsigned char cY = (unsigned char) ybits; - - if ( !bIsTangent ) - *pPackedNormal = (cX << 0) | (cY << 8); // xy for normal - else - *pPackedNormal = (cX << 16) | (cY << 24); // zw for tangent - - return pPackedNormal; -} - -FORCEINLINE unsigned int * PackNormal_UBYTE4( const float *pNormal, unsigned int *pPackedNormal, bool bIsTangent = false, float binormalSign = +1.0f ) -{ - return PackNormal_UBYTE4( pNormal[0], pNormal[1], pNormal[2], pPackedNormal, bIsTangent, binormalSign ); -} - - -//----------------------------------------------------------------------------- -// Convert RGB to HSV -//----------------------------------------------------------------------------- -void RGBtoHSV( const Vector &rgb, Vector &hsv ); - - -//----------------------------------------------------------------------------- -// Convert HSV to RGB -//----------------------------------------------------------------------------- -void HSVtoRGB( const Vector &hsv, Vector &rgb ); - - - -#endif // MATH_BASE_H - diff --git a/Resources/NetHook/mathlib/noise.h b/Resources/NetHook/mathlib/noise.h deleted file mode 100644 index 4acb75a5..00000000 --- a/Resources/NetHook/mathlib/noise.h +++ /dev/null @@ -1,35 +0,0 @@ -//========= Copyright © 1996-2006, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=====================================================================================// - -#ifndef NOISE_H -#define NOISE_H - -#include -#include "basetypes.h" -#include "mathlib/vector.h" -#include "tier0/dbg.h" - - -// The following code is the c-ification of Ken Perlin's new noise algorithm -// "JAVA REFERENCE IMPLEMENTATION OF IMPROVED NOISE - COPYRIGHT 2002 KEN PERLIN" -// as available here: http://mrl.nyu.edu/~perlin/noise/ -// it generates a single octave of noise in the -1..1 range -// this should at some point probably replace SparseConvolutionNoise - jd -float ImprovedPerlinNoise( Vector const &pnt ); - -// get the noise value at a point. Output range is 0..1. -float SparseConvolutionNoise( Vector const &pnt ); - -// get the noise value at a point, passing a custom noise shaping function. The noise shaping -// function should map the domain 0..1 to 0..1. -float SparseConvolutionNoise(Vector const &pnt, float (*pNoiseShapeFunction)(float) ); - -// returns a 1/f noise. more octaves take longer -float FractalNoise( Vector const &pnt, int n_octaves ); - -// returns a abs(f)*1/f noise i.e. turbulence -float Turbulence( Vector const &pnt, int n_octaves ); -#endif // NOISE_H diff --git a/Resources/NetHook/mathlib/polyhedron.h b/Resources/NetHook/mathlib/polyhedron.h deleted file mode 100644 index 81687cdd..00000000 --- a/Resources/NetHook/mathlib/polyhedron.h +++ /dev/null @@ -1,73 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef POLYHEDRON_H_ -#define POLYHEDRON_H_ - -#ifdef _WIN32 -#pragma once -#endif - -#include "mathlib/mathlib.h" - - - -struct Polyhedron_IndexedLine_t -{ - unsigned short iPointIndices[2]; -}; - -struct Polyhedron_IndexedLineReference_t -{ - unsigned short iLineIndex; - unsigned char iEndPointIndex; //since two polygons reference any one line, one needs to traverse the line backwards, this flags that behavior -}; - -struct Polyhedron_IndexedPolygon_t -{ - unsigned short iFirstIndex; - unsigned short iIndexCount; - Vector polyNormal; -}; - -class CPolyhedron //made into a class because it's going virtual to support distinctions between temp and permanent versions -{ -public: - Vector *pVertices; - Polyhedron_IndexedLine_t *pLines; - Polyhedron_IndexedLineReference_t *pIndices; - Polyhedron_IndexedPolygon_t *pPolygons; - - unsigned short iVertexCount; - unsigned short iLineCount; - unsigned short iIndexCount; - unsigned short iPolygonCount; - - virtual ~CPolyhedron( void ) {}; - virtual void Release( void ) = 0; - Vector Center( void ); -}; - -class CPolyhedron_AllocByNew : public CPolyhedron -{ -public: - virtual void Release( void ); - static CPolyhedron_AllocByNew *Allocate( unsigned short iVertices, unsigned short iLines, unsigned short iIndices, unsigned short iPolygons ); //creates the polyhedron along with enough memory to hold all it's data in a single allocation - -private: - CPolyhedron_AllocByNew( void ) { }; //CPolyhedron_AllocByNew::Allocate() is the only way to create one of these. -}; - -CPolyhedron *GeneratePolyhedronFromPlanes( const float *pOutwardFacingPlanes, int iPlaneCount, float fOnPlaneEpsilon, bool bUseTemporaryMemory = false ); //be sure to polyhedron->Release() -CPolyhedron *ClipPolyhedron( const CPolyhedron *pExistingPolyhedron, const float *pOutwardFacingPlanes, int iPlaneCount, float fOnPlaneEpsilon, bool bUseTemporaryMemory = false ); //this does NOT modify/delete the existing polyhedron - -CPolyhedron *GetTempPolyhedron( unsigned short iVertices, unsigned short iLines, unsigned short iIndices, unsigned short iPolygons ); //grab the temporary polyhedron. Avoids new/delete for quick work. Can only be in use by one chunk of code at a time - - -#endif //#ifndef POLYHEDRON_H_ - diff --git a/Resources/NetHook/mathlib/quantize.h b/Resources/NetHook/mathlib/quantize.h deleted file mode 100644 index 11c08b2b..00000000 --- a/Resources/NetHook/mathlib/quantize.h +++ /dev/null @@ -1,141 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef QUANTIZE_H -#define QUANTIZE_H - -#ifndef STRING_H -#include -#endif - -#define MAXDIMS 768 -#define MAXQUANT 16000 - - -#include - -struct Sample; - -struct QuantizedValue { - double MinError; // minimum possible error. used - // for neighbor searches. - struct QuantizedValue *Children[2]; // splits - int32 value; // only exists for leaf nodes - struct Sample *Samples; // every sample quantized into this - // entry - int32 NSamples; // how many were quantized to this. - int32 TotSamples; - double *ErrorMeasure; // variance measure for each dimension - double TotalError; // sum of errors - uint8 *Mean; // average value of each dimension - uint8 *Mins; // min box for children and this - uint8 *Maxs; // max box for children and this - int NQuant; // the number of samples which were - // quantzied to this node since the - // last time OptimizeQuantizer() - // was called. - int *Sums; // sum used by OptimizeQuantizer - int sortdim; // dimension currently sorted along. -}; - -struct Sample { - int32 ID; // identifier of this sample. can - // be used for any purpose. - int32 Count; // number of samples this sample - // represents - int32 QNum; // what value this sample ended up quantized - // to. - struct QuantizedValue *qptr; // ptr to what this was quantized to. - uint8 Value[1]; // array of values for multi-dimensional - // variables. -}; - -void FreeQuantization(struct QuantizedValue *t); - -struct QuantizedValue *Quantize(struct Sample *s, int nsamples, int ndims, - int nvalues, uint8 *weights, int value0=0); - -int CompressSamples(struct Sample *s, int nsamples, int ndims); - -struct QuantizedValue *FindMatch(uint8 const *sample, - int ndims,uint8 *weights, - struct QuantizedValue *QTable); -void PrintSamples(struct Sample const *s, int nsamples, int ndims); - -struct QuantizedValue *FindQNode(struct QuantizedValue const *q, int32 code); - -inline struct Sample *NthSample(struct Sample *s, int i, int nd) -{ - uint8 *r=(uint8 *) s; - r+=i*(sizeof(*s)+(nd-1)); - return (struct Sample *) r; -} - -inline struct Sample *AllocSamples(int ns, int nd) -{ - size_t size5=(sizeof(struct Sample)+(nd-1))*ns; - void *ret=new uint8[size5]; - memset(ret,0,size5); - for(int i=0;iCount=1; - return (struct Sample *) ret; -} - - -// MinimumError: what is the min error which will occur if quantizing -// a sample to the given qnode? This is just the error if the qnode -// is a leaf. -double MinimumError(struct QuantizedValue const *q, uint8 const *sample, - int ndims, uint8 const *weights); -double MaximumError(struct QuantizedValue const *q, uint8 const *sample, - int ndims, uint8 const *weights); - -void PrintQTree(struct QuantizedValue const *p,int idlevel=0); -void OptimizeQuantizer(struct QuantizedValue *q, int ndims); - -// RecalculateVelues: update the means in a sample tree, based upon -// the samples. can be used to reoptimize when samples are deleted, -// for instance. - -void RecalculateValues(struct QuantizedValue *q, int ndims); - -extern double SquaredError; // may be reset and examined. updated by - // FindMatch() - - - - -// the routines below can be used for uniform quantization via dart-throwing. -typedef void (*GENERATOR)(void *); // generate a random sample -typedef double (*COMPARER)(void const *a, void const *b); - -void *DartThrow(int NResults, int NTries, size_t itemsize, GENERATOR gen, - COMPARER cmp); -void *FindClosestDart(void *items,int NResults, size_t itemsize, - COMPARER cmp, void *lookfor, int *idx); - - - - -// color quantization of 24 bit images -#define QUANTFLAGS_NODITHER 1 // don't do Floyd-steinberg dither - -extern void ColorQuantize( -uint8 const *pImage, // 4 byte pixels ARGB -int nWidth, -int nHeight, -int nFlags, // QUANTFLAGS_xxx -int nColors, // # of colors to fill in in palette -uint8 *pOutPixels, // where to store resulting 8 bit pixels -uint8 *pOutPalette, // where to store resulting 768-byte palette -int nFirstColor); // first color to use in mapping - - - - - -#endif diff --git a/Resources/NetHook/mathlib/simdvectormatrix.h b/Resources/NetHook/mathlib/simdvectormatrix.h deleted file mode 100644 index e8a3667c..00000000 --- a/Resources/NetHook/mathlib/simdvectormatrix.h +++ /dev/null @@ -1,142 +0,0 @@ -//====== Copyright © 1996-2006, Valve Corporation, All rights reserved. =======// -// -// Purpose: Provide a class (SSE/SIMD only) holding a 2d matrix of class FourVectors, -// for high speed processing in tools. -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef SIMDVECTORMATRIX_H -#define SIMDVECTORMATRIX_H - -#ifdef _WIN32 -#pragma once -#endif - - -#include -#include "tier0/platform.h" -#include "tier0/dbg.h" -#include "tier1/utlsoacontainer.h" -#include "mathlib/ssemath.h" - -class CSIMDVectorMatrix -{ -public: - int m_nWidth; // in actual vectors - int m_nHeight; - - int m_nPaddedWidth; // # of 4x wide elements - - FourVectors *m_pData; - -protected: - void Init( void ) - { - m_pData = NULL; - m_nWidth = 0; - m_nHeight = 0; - m_nPaddedWidth = 0; - } - - int NVectors( void ) const - { - return m_nHeight * m_nPaddedWidth; - } - -public: - // constructors and destructors - CSIMDVectorMatrix( void ) - { - Init(); - } - - ~CSIMDVectorMatrix( void ) - { - if ( m_pData ) - delete[] m_pData; - } - - // set up storage and fields for m x n matrix. destroys old data - void SetSize( int width, int height ) - { - if ( ( ! m_pData ) || ( width != m_nWidth ) || ( height != m_nHeight ) ) - { - if ( m_pData ) - delete[] m_pData; - - m_nWidth = width; - m_nHeight = height; - - m_nPaddedWidth = ( m_nWidth + 3) >> 2; - m_pData = NULL; - if ( width && height ) - m_pData = new FourVectors[ m_nPaddedWidth * m_nHeight ]; - } - } - - CSIMDVectorMatrix( int width, int height ) - { - Init(); - SetSize( width, height ); - } - - CSIMDVectorMatrix &operator=( CSIMDVectorMatrix const &src ) - { - SetSize( src.m_nWidth, src.m_nHeight ); - if ( m_pData ) - memcpy( m_pData, src.m_pData, m_nHeight*m_nPaddedWidth*sizeof(m_pData[0]) ); - return *this; - } - - CSIMDVectorMatrix &operator+=( CSIMDVectorMatrix const &src ); - - CSIMDVectorMatrix &operator*=( Vector const &src ); - - // create from an RGBA float bitmap. alpha ignored. - void CreateFromRGBA_FloatImageData(int srcwidth, int srcheight, float const *srcdata ); - - // create from 3 fields in a csoa - void CreateFromCSOAAttributes( CSOAContainer const *pSrc, - int nAttrIdx0, int nAttrIdx1, int nAttrIdx2 ); - - // Element access. If you are calling this a lot, you don't want to use this class, because - // you're not getting the sse advantage - Vector Element(int x, int y) const - { - Assert( m_pData ); - Assert( x < m_nWidth ); - Assert( y < m_nHeight ); - Vector ret; - FourVectors const *pData=m_pData+y*m_nPaddedWidth+(x >> 2); - - int xo=(x & 3); - ret.x=pData->X( xo ); - ret.y=pData->Y( xo ); - ret.z=pData->Z( xo ); - return ret; - } - - //addressing the individual fourvectors elements - FourVectors &CompoundElement(int x, int y) - { - Assert( m_pData ); - Assert( y < m_nHeight ); - Assert( x < m_nPaddedWidth ); - return m_pData[x + m_nPaddedWidth*y ]; - } - - // math operations on the whole image - void Clear( void ) - { - Assert( m_pData ); - memset( m_pData, 0, m_nHeight*m_nPaddedWidth*sizeof(m_pData[0]) ); - } - - void RaiseToPower( float power ); -}; - - - -#endif diff --git a/Resources/NetHook/mathlib/spherical_geometry.h b/Resources/NetHook/mathlib/spherical_geometry.h deleted file mode 100644 index f8c5862e..00000000 --- a/Resources/NetHook/mathlib/spherical_geometry.h +++ /dev/null @@ -1,73 +0,0 @@ -//====== Copyright © 2007-2007, Valve Corporation, All rights reserved. =======// -// -// Purpose: Functions for spherical geometry. -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef SPHERICAL_GEOMETRY_H -#define SPHERICAL_GEOMETRY_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include - -// see http://mathworld.wolfram.com/SphericalTrigonometry.html - -// return the spherical distance, in radians, between 2 points on the unit sphere. -FORCEINLINE float UnitSphereLineSegmentLength( Vector const &a, Vector const &b ) -{ - // check unit length - Assert( fabs( VectorLength( a ) - 1.0 ) < 1.0e-3 ); - Assert( fabs( VectorLength( b ) - 1.0 ) < 1.0e-3 ); - return acos( DotProduct( a, b ) ); -} - - -// given 3 points on the unit sphere, return the spherical area (in radians) of the triangle they form. -// valid for "small" triangles. -FORCEINLINE float UnitSphereTriangleArea( Vector const &a, Vector const &b , Vector const &c ) -{ - float flLengthA = UnitSphereLineSegmentLength( b, c ); - float flLengthB = UnitSphereLineSegmentLength( c, a ); - float flLengthC = UnitSphereLineSegmentLength( a, b ); - - if ( ( flLengthA == 0. ) || ( flLengthB == 0. ) || ( flLengthC == 0. ) ) - return 0.; // zero area triangle - - // now, find the 3 incribed angles for the triangle - float flHalfSumLens = 0.5 * ( flLengthA + flLengthB + flLengthC ); - float flSinSums = sin( flHalfSumLens ); - float flSinSMinusA= sin( flHalfSumLens - flLengthA ); - float flSinSMinusB= sin( flHalfSumLens - flLengthB ); - float flSinSMinusC= sin( flHalfSumLens - flLengthC ); - - float flTanAOver2 = sqrt ( ( flSinSMinusB * flSinSMinusC ) / ( flSinSums * flSinSMinusA ) ); - float flTanBOver2 = sqrt ( ( flSinSMinusA * flSinSMinusC ) / ( flSinSums * flSinSMinusB ) ); - float flTanCOver2 = sqrt ( ( flSinSMinusA * flSinSMinusB ) / ( flSinSums * flSinSMinusC ) ); - - // Girards formula : area = sum of angles - pi. - return 2.0 * ( atan( flTanAOver2 ) + atan( flTanBOver2 ) + atan( flTanCOver2 ) ) - M_PI; -} - -// spherical harmonics-related functions. Best explanation at http://www.research.scea.com/gdc2003/spherical-harmonic-lighting.pdf - -// Evaluate associated legendre polynomial P( l, m ) at flX, using recurrence relation -float AssociatedLegendrePolynomial( int nL, int nM, float flX ); - -// Evaluate order N spherical harmonic with spherical coordinates -// nL = band, 0..N -// nM = -nL .. nL -// theta = 0..M_PI -// phi = 0.. 2 * M_PHI -float SphericalHarmonic( int nL, int nM, float flTheta, float flPhi ); - -// evaluate spherical harmonic with normalized vector direction -float SphericalHarmonic( int nL, int nM, Vector const &vecDirection ); - - -#endif // SPHERICAL_GEOMETRY_H diff --git a/Resources/NetHook/mathlib/ssemath.h b/Resources/NetHook/mathlib/ssemath.h deleted file mode 100644 index a6d15820..00000000 --- a/Resources/NetHook/mathlib/ssemath.h +++ /dev/null @@ -1,3098 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: - defines SIMD "structure of arrays" classes and functions. -// -//===========================================================================// -#ifndef SSEMATH_H -#define SSEMATH_H - -#if defined( _X360 ) -#include -#else -#include -#endif - -#include -#include - -#if defined(_LINUX) -#define USE_STDC_FOR_SIMD 0 -#else -#define USE_STDC_FOR_SIMD 0 -#endif - -#if (!defined(_X360) && (USE_STDC_FOR_SIMD == 0)) -#define _SSE1 1 -#endif - -// I thought about defining a class/union for the SIMD packed floats instead of using fltx4, -// but decided against it because (a) the nature of SIMD code which includes comparisons is to blur -// the relationship between packed floats and packed integer types and (b) not sure that the -// compiler would handle generating good code for the intrinsics. - -#if USE_STDC_FOR_SIMD - -typedef union -{ - float m128_f32[4]; - uint32 m128_u32[4]; -} fltx4; - -typedef fltx4 i32x4; -typedef fltx4 u32x4; - -#elif ( defined( _X360 ) ) - -typedef union -{ - // This union allows float/int access (which generally shouldn't be done in inner loops) - __vector4 vmx; - float m128_f32[4]; - uint32 m128_u32[4]; -} fltx4_union; - -typedef __vector4 fltx4; -typedef __vector4 i32x4; // a VMX register; just a way of making it explicit that we're doing integer ops. -typedef __vector4 u32x4; // a VMX register; just a way of making it explicit that we're doing unsigned integer ops. - -#else - -typedef __m128 fltx4; -typedef __m128 i32x4; -typedef __m128 u32x4; - -#endif - -// The FLTX4 type is a fltx4 used as a parameter to a function. -// On the 360, the best way to do this is pass-by-copy on the registers. -// On the PC, the best way is to pass by const reference. -// The compiler will sometimes, but not always, replace a pass-by-const-ref -// with a pass-in-reg on the 360; to avoid this confusion, you can -// explicitly use a FLTX4 as the parameter type. -#ifdef _X360 -typedef __vector4 FLTX4; -#else -typedef const fltx4 & FLTX4; -#endif - -// A 16-byte aligned int32 datastructure -// (for use when writing out fltx4's as SIGNED -// ints). -struct ALIGN16 intx4 -{ - int32 m_i32[4]; - - inline int & operator[](int which) - { - return m_i32[which]; - } - - inline const int & operator[](int which) const - { - return m_i32[which]; - } - - inline int32 *Base() { - return m_i32; - } - - inline const int32 *Base() const - { - return m_i32; - } - - inline const bool operator==(const intx4 &other) const - { - return m_i32[0] == other.m_i32[0] && - m_i32[1] == other.m_i32[1] && - m_i32[2] == other.m_i32[2] && - m_i32[3] == other.m_i32[3] ; - } -}; - - -#if defined( _DEBUG ) && defined( _X360 ) -FORCEINLINE void TestVPUFlags() -{ - // Check that the VPU is in the appropriate (Java-compliant) mode (see 3.2.1 in altivec_pem.pdf on xds.xbox.com) - __vector4 a; - __asm - { - mfvscr a; - } - unsigned int * flags = (unsigned int *)&a; - unsigned int controlWord = flags[3]; - Assert(controlWord == 0); -} -#else // _DEBUG -FORCEINLINE void TestVPUFlags() {} -#endif // _DEBUG - - -// useful constants in SIMD packed float format: -// (note: some of these aren't stored on the 360, -// but are manufactured directly in one or two -// instructions, saving a load and possible L2 -// miss.) -#ifndef _X360 -extern const fltx4 Four_Zeros; // 0 0 0 0 -extern const fltx4 Four_Ones; // 1 1 1 1 -extern const fltx4 Four_Twos; // 2 2 2 2 -extern const fltx4 Four_Threes; // 3 3 3 3 -extern const fltx4 Four_Fours; // guess. -extern const fltx4 Four_Point225s; // .225 .225 .225 .225 -extern const fltx4 Four_PointFives; // .5 .5 .5 .5 -extern const fltx4 Four_Epsilons; // FLT_EPSILON FLT_EPSILON FLT_EPSILON FLT_EPSILON -extern const fltx4 Four_2ToThe21s; // (1<<21).. -extern const fltx4 Four_2ToThe22s; // (1<<22).. -extern const fltx4 Four_2ToThe23s; // (1<<23).. -extern const fltx4 Four_2ToThe24s; // (1<<24).. -extern const fltx4 Four_Origin; // 0 0 0 1 (origin point, like vr0 on the PS2) -extern const fltx4 Four_NegativeOnes; // -1 -1 -1 -1 -#else -#define Four_Zeros XMVectorZero() // 0 0 0 0 -#define Four_Ones XMVectorSplatOne() // 1 1 1 1 -extern const fltx4 Four_Twos; // 2 2 2 2 -extern const fltx4 Four_Threes; // 3 3 3 3 -extern const fltx4 Four_Fours; // guess. -extern const fltx4 Four_Point225s; // .225 .225 .225 .225 -extern const fltx4 Four_PointFives; // .5 .5 .5 .5 -extern const fltx4 Four_Epsilons; // FLT_EPSILON FLT_EPSILON FLT_EPSILON FLT_EPSILON -extern const fltx4 Four_2ToThe21s; // (1<<21).. -extern const fltx4 Four_2ToThe22s; // (1<<22).. -extern const fltx4 Four_2ToThe23s; // (1<<23).. -extern const fltx4 Four_2ToThe24s; // (1<<24).. -extern const fltx4 Four_Origin; // 0 0 0 1 (origin point, like vr0 on the PS2) -extern const fltx4 Four_NegativeOnes; // -1 -1 -1 -1 -#endif -extern const fltx4 Four_FLT_MAX; // FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX -extern const fltx4 Four_Negative_FLT_MAX; // -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX -extern const fltx4 g_SIMD_0123; // 0 1 2 3 as float - -// external aligned integer constants -extern const ALIGN16 int32 g_SIMD_clear_signmask[]; // 0x7fffffff x 4 -extern const ALIGN16 int32 g_SIMD_signmask[]; // 0x80000000 x 4 -extern const ALIGN16 int32 g_SIMD_lsbmask[]; // 0xfffffffe x 4 -extern const ALIGN16 int32 g_SIMD_clear_wmask[]; // -1 -1 -1 0 -extern const ALIGN16 int32 g_SIMD_ComponentMask[4][4]; // [0xFFFFFFFF 0 0 0], [0 0xFFFFFFFF 0 0], [0 0 0xFFFFFFFF 0], [0 0 0 0xFFFFFFFF] -extern const ALIGN16 int32 g_SIMD_AllOnesMask[]; // ~0,~0,~0,~0 -extern const ALIGN16 int32 g_SIMD_Low16BitsMask[]; // 0xffff x 4 - -// this mask is used for skipping the tail of things. If you have N elements in an array, and wish -// to mask out the tail, g_SIMD_SkipTailMask[N & 3] what you want to use for the last iteration. -extern const int32 ALIGN16 g_SIMD_SkipTailMask[4][4]; - -// Define prefetch macros. -// The characteristics of cache and prefetch are completely -// different between the different platforms, so you DO NOT -// want to just define one macro that maps to every platform -// intrinsic under the hood -- you need to prefetch at different -// intervals between x86 and PPC, for example, and that is -// a higher level code change. -// On the other hand, I'm tired of typing #ifdef _X360 -// all over the place, so this is just a nop on Intel, PS3. -#ifdef _X360 -#define PREFETCH360(address, offset) __dcbt(offset,address) -#else -#define PREFETCH360(x,y) // nothing -#endif - -#if USE_STDC_FOR_SIMD - -//--------------------------------------------------------------------- -// Standard C (fallback/Linux) implementation (only there for compat - slow) -//--------------------------------------------------------------------- - -FORCEINLINE float SubFloat( const fltx4 & a, int idx ) -{ - return a.m128_f32[ idx ]; -} - -FORCEINLINE float & SubFloat( fltx4 & a, int idx ) -{ - return a.m128_f32[idx]; -} - -FORCEINLINE uint32 SubInt( const fltx4 & a, int idx ) -{ - return a.m128_u32[idx]; -} - -FORCEINLINE uint32 & SubInt( fltx4 & a, int idx ) -{ - return a.m128_u32[idx]; -} - -// Return one in the fastest way -- on the x360, faster even than loading. -FORCEINLINE fltx4 LoadZeroSIMD( void ) -{ - return Four_Zeros; -} - -// Return one in the fastest way -- on the x360, faster even than loading. -FORCEINLINE fltx4 LoadOneSIMD( void ) -{ - return Four_Ones; -} - -FORCEINLINE fltx4 SplatXSIMD( const fltx4 & a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = SubFloat( a, 0 ); - SubFloat( retVal, 1 ) = SubFloat( a, 0 ); - SubFloat( retVal, 2 ) = SubFloat( a, 0 ); - SubFloat( retVal, 3 ) = SubFloat( a, 0 ); - return retVal; -} - -FORCEINLINE fltx4 SplatYSIMD( fltx4 a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = SubFloat( a, 1 ); - SubFloat( retVal, 1 ) = SubFloat( a, 1 ); - SubFloat( retVal, 2 ) = SubFloat( a, 1 ); - SubFloat( retVal, 3 ) = SubFloat( a, 1 ); - return retVal; -} - -FORCEINLINE fltx4 SplatZSIMD( fltx4 a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = SubFloat( a, 2 ); - SubFloat( retVal, 1 ) = SubFloat( a, 2 ); - SubFloat( retVal, 2 ) = SubFloat( a, 2 ); - SubFloat( retVal, 3 ) = SubFloat( a, 2 ); - return retVal; -} - -FORCEINLINE fltx4 SplatWSIMD( fltx4 a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = SubFloat( a, 3 ); - SubFloat( retVal, 1 ) = SubFloat( a, 3 ); - SubFloat( retVal, 2 ) = SubFloat( a, 3 ); - SubFloat( retVal, 3 ) = SubFloat( a, 3 ); - return retVal; -} - -FORCEINLINE fltx4 SetXSIMD( const fltx4& a, const fltx4& x ) -{ - fltx4 result = a; - SubFloat( result, 0 ) = SubFloat( x, 0 ); - return result; -} - -FORCEINLINE fltx4 SetYSIMD( const fltx4& a, const fltx4& y ) -{ - fltx4 result = a; - SubFloat( result, 1 ) = SubFloat( y, 1 ); - return result; -} - -FORCEINLINE fltx4 SetZSIMD( const fltx4& a, const fltx4& z ) -{ - fltx4 result = a; - SubFloat( result, 2 ) = SubFloat( z, 2 ); - return result; -} - -FORCEINLINE fltx4 SetWSIMD( const fltx4& a, const fltx4& w ) -{ - fltx4 result = a; - SubFloat( result, 3 ) = SubFloat( w, 3 ); - return result; -} - -FORCEINLINE fltx4 SetComponentSIMD( const fltx4& a, int nComponent, float flValue ) -{ - fltx4 result = a; - SubFloat( result, nComponent ) = flValue; - return result; -} - -// a b c d -> b c d a -FORCEINLINE fltx4 RotateLeft( const fltx4 & a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = SubFloat( a, 1 ); - SubFloat( retVal, 1 ) = SubFloat( a, 2 ); - SubFloat( retVal, 2 ) = SubFloat( a, 3 ); - SubFloat( retVal, 3 ) = SubFloat( a, 0 ); - return retVal; -} - -// a b c d -> c d a b -FORCEINLINE fltx4 RotateLeft2( const fltx4 & a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = SubFloat( a, 2 ); - SubFloat( retVal, 1 ) = SubFloat( a, 3 ); - SubFloat( retVal, 2 ) = SubFloat( a, 0 ); - SubFloat( retVal, 3 ) = SubFloat( a, 1 ); - return retVal; -} - -#define BINOP(op) \ - fltx4 retVal; \ - SubFloat( retVal, 0 ) = ( SubFloat( a, 0 ) op SubFloat( b, 0 ) ); \ - SubFloat( retVal, 1 ) = ( SubFloat( a, 1 ) op SubFloat( b, 1 ) ); \ - SubFloat( retVal, 2 ) = ( SubFloat( a, 2 ) op SubFloat( b, 2 ) ); \ - SubFloat( retVal, 3 ) = ( SubFloat( a, 3 ) op SubFloat( b, 3 ) ); \ - return retVal; - -#define IBINOP(op) \ - fltx4 retVal; \ - SubInt( retVal, 0 ) = ( SubInt( a, 0 ) op SubInt ( b, 0 ) ); \ - SubInt( retVal, 1 ) = ( SubInt( a, 1 ) op SubInt ( b, 1 ) ); \ - SubInt( retVal, 2 ) = ( SubInt( a, 2 ) op SubInt ( b, 2 ) ); \ - SubInt( retVal, 3 ) = ( SubInt( a, 3 ) op SubInt ( b, 3 ) ); \ - return retVal; - -FORCEINLINE fltx4 AddSIMD( const fltx4 & a, const fltx4 & b ) -{ - BINOP(+); -} - -FORCEINLINE fltx4 SubSIMD( const fltx4 & a, const fltx4 & b ) // a-b -{ - BINOP(-); -}; - -FORCEINLINE fltx4 MulSIMD( const fltx4 & a, const fltx4 & b ) // a*b -{ - BINOP(*); -} - -FORCEINLINE fltx4 DivSIMD( const fltx4 & a, const fltx4 & b ) // a/b -{ - BINOP(/); -} - - -FORCEINLINE fltx4 MaddSIMD( const fltx4 & a, const fltx4 & b, const fltx4 & c ) // a*b + c -{ - return AddSIMD( MulSIMD(a,b), c ); -} - -FORCEINLINE fltx4 MsubSIMD( const fltx4 & a, const fltx4 & b, const fltx4 & c ) // c - a*b -{ - return SubSIMD( c, MulSIMD(a,b) ); -}; - - -FORCEINLINE fltx4 SinSIMD( const fltx4 &radians ) -{ - fltx4 result; - SubFloat( result, 0 ) = sin( SubFloat( radians, 0 ) ); - SubFloat( result, 1 ) = sin( SubFloat( radians, 1 ) ); - SubFloat( result, 2 ) = sin( SubFloat( radians, 2 ) ); - SubFloat( result, 3 ) = sin( SubFloat( radians, 3 ) ); - return result; -} - -FORCEINLINE void SinCos3SIMD( fltx4 &sine, fltx4 &cosine, const fltx4 &radians ) -{ - SinCos( SubFloat( radians, 0 ), &SubFloat( sine, 0 ), &SubFloat( cosine, 0 ) ); - SinCos( SubFloat( radians, 1 ), &SubFloat( sine, 1 ), &SubFloat( cosine, 1 ) ); - SinCos( SubFloat( radians, 2 ), &SubFloat( sine, 2 ), &SubFloat( cosine, 2 ) ); -} - -FORCEINLINE void SinCosSIMD( fltx4 &sine, fltx4 &cosine, const fltx4 &radians ) -{ - SinCos( SubFloat( radians, 0 ), &SubFloat( sine, 0 ), &SubFloat( cosine, 0 ) ); - SinCos( SubFloat( radians, 1 ), &SubFloat( sine, 1 ), &SubFloat( cosine, 1 ) ); - SinCos( SubFloat( radians, 2 ), &SubFloat( sine, 2 ), &SubFloat( cosine, 2 ) ); - SinCos( SubFloat( radians, 3 ), &SubFloat( sine, 3 ), &SubFloat( cosine, 3 ) ); -} - -FORCEINLINE fltx4 ArcSinSIMD( const fltx4 &sine ) -{ - fltx4 result; - SubFloat( result, 0 ) = asin( SubFloat( sine, 0 ) ); - SubFloat( result, 1 ) = asin( SubFloat( sine, 1 ) ); - SubFloat( result, 2 ) = asin( SubFloat( sine, 2 ) ); - SubFloat( result, 3 ) = asin( SubFloat( sine, 3 ) ); - return result; -} - -FORCEINLINE fltx4 ArcCosSIMD( const fltx4 &cs ) -{ - fltx4 result; - SubFloat( result, 0 ) = acos( SubFloat( cs, 0 ) ); - SubFloat( result, 1 ) = acos( SubFloat( cs, 1 ) ); - SubFloat( result, 2 ) = acos( SubFloat( cs, 2 ) ); - SubFloat( result, 3 ) = acos( SubFloat( cs, 3 ) ); - return result; -} - -// tan^1(a/b) .. ie, pass sin in as a and cos in as b -FORCEINLINE fltx4 ArcTan2SIMD( const fltx4 &a, const fltx4 &b ) -{ - fltx4 result; - SubFloat( result, 0 ) = atan2( SubFloat( a, 0 ), SubFloat( b, 0 ) ); - SubFloat( result, 1 ) = atan2( SubFloat( a, 1 ), SubFloat( b, 1 ) ); - SubFloat( result, 2 ) = atan2( SubFloat( a, 2 ), SubFloat( b, 2 ) ); - SubFloat( result, 3 ) = atan2( SubFloat( a, 3 ), SubFloat( b, 3 ) ); - return result; -} - -FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // max(a,b) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = max( SubFloat( a, 0 ), SubFloat( b, 0 ) ); - SubFloat( retVal, 1 ) = max( SubFloat( a, 1 ), SubFloat( b, 1 ) ); - SubFloat( retVal, 2 ) = max( SubFloat( a, 2 ), SubFloat( b, 2 ) ); - SubFloat( retVal, 3 ) = max( SubFloat( a, 3 ), SubFloat( b, 3 ) ); - return retVal; -} - -FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // min(a,b) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = min( SubFloat( a, 0 ), SubFloat( b, 0 ) ); - SubFloat( retVal, 1 ) = min( SubFloat( a, 1 ), SubFloat( b, 1 ) ); - SubFloat( retVal, 2 ) = min( SubFloat( a, 2 ), SubFloat( b, 2 ) ); - SubFloat( retVal, 3 ) = min( SubFloat( a, 3 ), SubFloat( b, 3 ) ); - return retVal; -} - -FORCEINLINE fltx4 AndSIMD( const fltx4 & a, const fltx4 & b ) // a & b -{ - IBINOP(&); -} - -FORCEINLINE fltx4 AndNotSIMD( const fltx4 & a, const fltx4 & b ) // ~a & b -{ - fltx4 retVal; - SubInt( retVal, 0 ) = ~SubInt( a, 0 ) & SubInt( b, 0 ); - SubInt( retVal, 1 ) = ~SubInt( a, 1 ) & SubInt( b, 1 ); - SubInt( retVal, 2 ) = ~SubInt( a, 2 ) & SubInt( b, 2 ); - SubInt( retVal, 3 ) = ~SubInt( a, 3 ) & SubInt( b, 3 ); - return retVal; -} - -FORCEINLINE fltx4 XorSIMD( const fltx4 & a, const fltx4 & b ) // a ^ b -{ - IBINOP(^); -} - -FORCEINLINE fltx4 OrSIMD( const fltx4 & a, const fltx4 & b ) // a | b -{ - IBINOP(|); -} - -FORCEINLINE fltx4 NegSIMD(const fltx4 &a) // negate: -a -{ - fltx4 retval; - SubFloat( retval, 0 ) = -SubFloat( a, 0 ); - SubFloat( retval, 1 ) = -SubFloat( a, 1 ); - SubFloat( retval, 2 ) = -SubFloat( a, 2 ); - SubFloat( retval, 3 ) = -SubFloat( a, 3 ); - - return retval; -} - -FORCEINLINE bool IsAllZeros( const fltx4 & a ) // all floats of a zero? -{ - return ( SubFloat( a, 0 ) == 0.0 ) && - ( SubFloat( a, 1 ) == 0.0 ) && - ( SubFloat( a, 2 ) == 0.0 ) && - ( SubFloat( a, 3 ) == 0.0 ) ; -} - - -// for branching when a.xyzw > b.xyzw -FORCEINLINE bool IsAllGreaterThan( const fltx4 &a, const fltx4 &b ) -{ - return SubFloat(a,0) > SubFloat(b,0) && - SubFloat(a,1) > SubFloat(b,1) && - SubFloat(a,2) > SubFloat(b,2) && - SubFloat(a,3) > SubFloat(b,3); -} - -// for branching when a.xyzw >= b.xyzw -FORCEINLINE bool IsAllGreaterThanOrEq( const fltx4 &a, const fltx4 &b ) -{ - return SubFloat(a,0) >= SubFloat(b,0) && - SubFloat(a,1) >= SubFloat(b,1) && - SubFloat(a,2) >= SubFloat(b,2) && - SubFloat(a,3) >= SubFloat(b,3); -} - -// For branching if all a.xyzw == b.xyzw -FORCEINLINE bool IsAllEqual( const fltx4 & a, const fltx4 & b ) -{ - return SubFloat(a,0) == SubFloat(b,0) && - SubFloat(a,1) == SubFloat(b,1) && - SubFloat(a,2) == SubFloat(b,2) && - SubFloat(a,3) == SubFloat(b,3); -} - -FORCEINLINE int TestSignSIMD( const fltx4 & a ) // mask of which floats have the high bit set -{ - int nRet = 0; - - nRet |= ( SubInt( a, 0 ) & 0x80000000 ) >> 31; // sign(x) -> bit 0 - nRet |= ( SubInt( a, 1 ) & 0x80000000 ) >> 30; // sign(y) -> bit 1 - nRet |= ( SubInt( a, 2 ) & 0x80000000 ) >> 29; // sign(z) -> bit 2 - nRet |= ( SubInt( a, 3 ) & 0x80000000 ) >> 28; // sign(w) -> bit 3 - - return nRet; -} - -FORCEINLINE bool IsAnyNegative( const fltx4 & a ) // (a.x < 0) || (a.y < 0) || (a.z < 0) || (a.w < 0) -{ - return (0 != TestSignSIMD( a )); -} - -FORCEINLINE fltx4 CmpEqSIMD( const fltx4 & a, const fltx4 & b ) // (a==b) ? ~0:0 -{ - fltx4 retVal; - SubInt( retVal, 0 ) = ( SubFloat( a, 0 ) == SubFloat( b, 0 )) ? ~0 : 0; - SubInt( retVal, 1 ) = ( SubFloat( a, 1 ) == SubFloat( b, 1 )) ? ~0 : 0; - SubInt( retVal, 2 ) = ( SubFloat( a, 2 ) == SubFloat( b, 2 )) ? ~0 : 0; - SubInt( retVal, 3 ) = ( SubFloat( a, 3 ) == SubFloat( b, 3 )) ? ~0 : 0; - return retVal; -} - -FORCEINLINE fltx4 CmpGtSIMD( const fltx4 & a, const fltx4 & b ) // (a>b) ? ~0:0 -{ - fltx4 retVal; - SubInt( retVal, 0 ) = ( SubFloat( a, 0 ) > SubFloat( b, 0 )) ? ~0 : 0; - SubInt( retVal, 1 ) = ( SubFloat( a, 1 ) > SubFloat( b, 1 )) ? ~0 : 0; - SubInt( retVal, 2 ) = ( SubFloat( a, 2 ) > SubFloat( b, 2 )) ? ~0 : 0; - SubInt( retVal, 3 ) = ( SubFloat( a, 3 ) > SubFloat( b, 3 )) ? ~0 : 0; - return retVal; -} - -FORCEINLINE fltx4 CmpGeSIMD( const fltx4 & a, const fltx4 & b ) // (a>=b) ? ~0:0 -{ - fltx4 retVal; - SubInt( retVal, 0 ) = ( SubFloat( a, 0 ) >= SubFloat( b, 0 )) ? ~0 : 0; - SubInt( retVal, 1 ) = ( SubFloat( a, 1 ) >= SubFloat( b, 1 )) ? ~0 : 0; - SubInt( retVal, 2 ) = ( SubFloat( a, 2 ) >= SubFloat( b, 2 )) ? ~0 : 0; - SubInt( retVal, 3 ) = ( SubFloat( a, 3 ) >= SubFloat( b, 3 )) ? ~0 : 0; - return retVal; -} - -FORCEINLINE fltx4 CmpLtSIMD( const fltx4 & a, const fltx4 & b ) // (a= -b) ? ~0 : 0 -{ - fltx4 retVal; - SubInt( retVal, 0 ) = ( SubFloat( a, 0 ) <= SubFloat( b, 0 ) && SubFloat( a, 0 ) >= -SubFloat( b, 0 ) ) ? ~0 : 0; - SubInt( retVal, 1 ) = ( SubFloat( a, 1 ) <= SubFloat( b, 1 ) && SubFloat( a, 1 ) >= -SubFloat( b, 1 ) ) ? ~0 : 0; - SubInt( retVal, 2 ) = ( SubFloat( a, 2 ) <= SubFloat( b, 2 ) && SubFloat( a, 2 ) >= -SubFloat( b, 2 ) ) ? ~0 : 0; - SubInt( retVal, 3 ) = ( SubFloat( a, 3 ) <= SubFloat( b, 3 ) && SubFloat( a, 3 ) >= -SubFloat( b, 3 ) ) ? ~0 : 0; - return retVal; -} - - -FORCEINLINE fltx4 MaskedAssign( const fltx4 & ReplacementMask, const fltx4 & NewValue, const fltx4 & OldValue ) -{ - return OrSIMD( - AndSIMD( ReplacementMask, NewValue ), - AndNotSIMD( ReplacementMask, OldValue ) ); -} - -FORCEINLINE fltx4 ReplicateX4( float flValue ) // a,a,a,a -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = flValue; - SubFloat( retVal, 1 ) = flValue; - SubFloat( retVal, 2 ) = flValue; - SubFloat( retVal, 3 ) = flValue; - return retVal; -} - -/// replicate a single 32 bit integer value to all 4 components of an m128 -FORCEINLINE fltx4 ReplicateIX4( int nValue ) -{ - fltx4 retVal; - SubInt( retVal, 0 ) = nValue; - SubInt( retVal, 1 ) = nValue; - SubInt( retVal, 2 ) = nValue; - SubInt( retVal, 3 ) = nValue; - return retVal; - -} - -// Round towards positive infinity -FORCEINLINE fltx4 CeilSIMD( const fltx4 &a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = ceil( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = ceil( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = ceil( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = ceil( SubFloat( a, 3 ) ); - return retVal; - -} - -// Round towards negative infinity -FORCEINLINE fltx4 FloorSIMD( const fltx4 &a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = floor( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = floor( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = floor( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = floor( SubFloat( a, 3 ) ); - return retVal; - -} - -FORCEINLINE fltx4 SqrtEstSIMD( const fltx4 & a ) // sqrt(a), more or less -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = sqrt( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = sqrt( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = sqrt( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = sqrt( SubFloat( a, 3 ) ); - return retVal; -} - -FORCEINLINE fltx4 SqrtSIMD( const fltx4 & a ) // sqrt(a) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = sqrt( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = sqrt( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = sqrt( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = sqrt( SubFloat( a, 3 ) ); - return retVal; -} - -FORCEINLINE fltx4 ReciprocalSqrtEstSIMD( const fltx4 & a ) // 1/sqrt(a), more or less -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / sqrt( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = 1.0 / sqrt( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = 1.0 / sqrt( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = 1.0 / sqrt( SubFloat( a, 3 ) ); - return retVal; -} - -FORCEINLINE fltx4 ReciprocalSqrtEstSaturateSIMD( const fltx4 & a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / sqrt( SubFloat( a, 0 ) != 0.0f ? SubFloat( a, 0 ) : FLT_EPSILON ); - SubFloat( retVal, 1 ) = 1.0 / sqrt( SubFloat( a, 1 ) != 0.0f ? SubFloat( a, 1 ) : FLT_EPSILON ); - SubFloat( retVal, 2 ) = 1.0 / sqrt( SubFloat( a, 2 ) != 0.0f ? SubFloat( a, 2 ) : FLT_EPSILON ); - SubFloat( retVal, 3 ) = 1.0 / sqrt( SubFloat( a, 3 ) != 0.0f ? SubFloat( a, 3 ) : FLT_EPSILON ); - return retVal; -} - -FORCEINLINE fltx4 ReciprocalSqrtSIMD( const fltx4 & a ) // 1/sqrt(a) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / sqrt( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = 1.0 / sqrt( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = 1.0 / sqrt( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = 1.0 / sqrt( SubFloat( a, 3 ) ); - return retVal; -} - -FORCEINLINE fltx4 ReciprocalEstSIMD( const fltx4 & a ) // 1/a, more or less -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / SubFloat( a, 0 ); - SubFloat( retVal, 1 ) = 1.0 / SubFloat( a, 1 ); - SubFloat( retVal, 2 ) = 1.0 / SubFloat( a, 2 ); - SubFloat( retVal, 3 ) = 1.0 / SubFloat( a, 3 ); - return retVal; -} - -FORCEINLINE fltx4 ReciprocalSIMD( const fltx4 & a ) // 1/a -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / SubFloat( a, 0 ); - SubFloat( retVal, 1 ) = 1.0 / SubFloat( a, 1 ); - SubFloat( retVal, 2 ) = 1.0 / SubFloat( a, 2 ); - SubFloat( retVal, 3 ) = 1.0 / SubFloat( a, 3 ); - return retVal; -} - -/// 1/x for all 4 values. -/// 1/0 will result in a big but NOT infinite result -FORCEINLINE fltx4 ReciprocalEstSaturateSIMD( const fltx4 & a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / (SubFloat( a, 0 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 0 )); - SubFloat( retVal, 1 ) = 1.0 / (SubFloat( a, 1 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 1 )); - SubFloat( retVal, 2 ) = 1.0 / (SubFloat( a, 2 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 2 )); - SubFloat( retVal, 3 ) = 1.0 / (SubFloat( a, 3 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 3 )); - return retVal; -} - -FORCEINLINE fltx4 ReciprocalSaturateSIMD( const fltx4 & a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = 1.0 / (SubFloat( a, 0 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 0 )); - SubFloat( retVal, 1 ) = 1.0 / (SubFloat( a, 1 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 1 )); - SubFloat( retVal, 2 ) = 1.0 / (SubFloat( a, 2 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 2 )); - SubFloat( retVal, 3 ) = 1.0 / (SubFloat( a, 3 ) == 0.0f ? FLT_EPSILON : SubFloat( a, 3 )); - return retVal; -} - -// 2^x for all values (the antilog) -FORCEINLINE fltx4 ExpSIMD( const fltx4 &toPower ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = powf( 2, SubFloat(toPower, 0) ); - SubFloat( retVal, 1 ) = powf( 2, SubFloat(toPower, 1) ); - SubFloat( retVal, 2 ) = powf( 2, SubFloat(toPower, 2) ); - SubFloat( retVal, 3 ) = powf( 2, SubFloat(toPower, 3) ); - - return retVal; -} - -FORCEINLINE fltx4 Dot3SIMD( const fltx4 &a, const fltx4 &b ) -{ - float flDot = SubFloat( a, 0 ) * SubFloat( b, 0 ) + - SubFloat( a, 1 ) * SubFloat( b, 1 ) + - SubFloat( a, 2 ) * SubFloat( b, 2 ); - return ReplicateX4( flDot ); -} - -FORCEINLINE fltx4 Dot4SIMD( const fltx4 &a, const fltx4 &b ) -{ - float flDot = SubFloat( a, 0 ) * SubFloat( b, 0 ) + - SubFloat( a, 1 ) * SubFloat( b, 1 ) + - SubFloat( a, 2 ) * SubFloat( b, 2 ) + - SubFloat( a, 3 ) * SubFloat( b, 3 ); - return ReplicateX4( flDot ); -} - -// Clamps the components of a vector to a specified minimum and maximum range. -FORCEINLINE fltx4 ClampVectorSIMD( FLTX4 in, FLTX4 min, FLTX4 max) -{ - return MaxSIMD( min, MinSIMD( max, in ) ); -} - -// Squelch the w component of a vector to +0.0. -// Most efficient when you say a = SetWToZeroSIMD(a) (avoids a copy) -FORCEINLINE fltx4 SetWToZeroSIMD( const fltx4 & a ) -{ - fltx4 retval; - retval = a; - SubFloat( retval, 0 ) = 0; - return retval; -} - -FORCEINLINE fltx4 LoadUnalignedSIMD( const void *pSIMD ) -{ - return *( reinterpret_cast< const fltx4 *> ( pSIMD ) ); -} - -FORCEINLINE fltx4 LoadUnaligned3SIMD( const void *pSIMD ) -{ - return *( reinterpret_cast< const fltx4 *> ( pSIMD ) ); -} - -FORCEINLINE fltx4 LoadAlignedSIMD( const void *pSIMD ) -{ - return *( reinterpret_cast< const fltx4 *> ( pSIMD ) ); -} - -// for the transitional class -- load a 3-by VectorAligned and squash its w component -FORCEINLINE fltx4 LoadAlignedSIMD( const VectorAligned & pSIMD ) -{ - fltx4 retval = LoadAlignedSIMD(pSIMD.Base()); - // squelch w - SubInt( retval, 3 ) = 0; - return retval; -} - -FORCEINLINE void StoreAlignedSIMD( float *pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< fltx4 *> ( pSIMD ) ) = a; -} - -FORCEINLINE void StoreUnalignedSIMD( float *pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< fltx4 *> ( pSIMD ) ) = a; -} - -FORCEINLINE void StoreUnaligned3SIMD( float *pSIMD, const fltx4 & a ) -{ - *pSIMD = SubFloat(a, 0); - *(pSIMD+1) = SubFloat(a, 1); - *(pSIMD+2) = SubFloat(a, 2); -} - -// strongly typed -- syntactic castor oil used for typechecking as we transition to SIMD -FORCEINLINE void StoreAligned3SIMD( VectorAligned * RESTRICT pSIMD, const fltx4 & a ) -{ - StoreAlignedSIMD(pSIMD->Base(),a); -} - -FORCEINLINE void TransposeSIMD( fltx4 & x, fltx4 & y, fltx4 & z, fltx4 & w ) -{ -#define SWAP_FLOATS( _a_, _ia_, _b_, _ib_ ) { float tmp = SubFloat( _a_, _ia_ ); SubFloat( _a_, _ia_ ) = SubFloat( _b_, _ib_ ); SubFloat( _b_, _ib_ ) = tmp; } - SWAP_FLOATS( x, 1, y, 0 ); - SWAP_FLOATS( x, 2, z, 0 ); - SWAP_FLOATS( x, 3, w, 0 ); - SWAP_FLOATS( y, 2, z, 1 ); - SWAP_FLOATS( y, 3, w, 1 ); - SWAP_FLOATS( z, 3, w, 2 ); -} - -// find the lowest component of a.x, a.y, a.z, -// and replicate it to the whole return value. -FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 & a ) -{ - float lowest = min( min( SubFloat(a, 0), SubFloat(a, 1) ), SubFloat(a, 2)); - return ReplicateX4(lowest); -} - -// find the highest component of a.x, a.y, a.z, -// and replicate it to the whole return value. -FORCEINLINE fltx4 FindHighestSIMD3( const fltx4 & a ) -{ - float highest = max( max( SubFloat(a, 0), SubFloat(a, 1) ), SubFloat(a, 2)); - return ReplicateX4(highest); -} - -// Fixed-point conversion and save as SIGNED INTS. -// pDest->x = Int (vSrc.x) -// note: some architectures have means of doing -// fixed point conversion when the fix depth is -// specified as an immediate.. but there is no way -// to guarantee an immediate as a parameter to function -// like this. -FORCEINLINE void ConvertStoreAsIntsSIMD(intx4 * RESTRICT pDest, const fltx4 &vSrc) -{ - (*pDest)[0] = SubFloat(vSrc, 0); - (*pDest)[1] = SubFloat(vSrc, 1); - (*pDest)[2] = SubFloat(vSrc, 2); - (*pDest)[3] = SubFloat(vSrc, 3); -} - -// ------------------------------------ -// INTEGER SIMD OPERATIONS. -// ------------------------------------ -// splat all components of a vector to a signed immediate int number. -FORCEINLINE fltx4 IntSetImmediateSIMD( int nValue ) -{ - fltx4 retval; - SubInt( retval, 0 ) = SubInt( retval, 1 ) = SubInt( retval, 2 ) = SubInt( retval, 3) = nValue; - return retval; -} - -// Load 4 aligned words into a SIMD register -FORCEINLINE i32x4 LoadAlignedIntSIMD(const void * RESTRICT pSIMD) -{ - return *( reinterpret_cast< const i32x4 *> ( pSIMD ) ); -} - -// Load 4 unaligned words into a SIMD register -FORCEINLINE i32x4 LoadUnalignedIntSIMD( const void * RESTRICT pSIMD) -{ - return *( reinterpret_cast< const i32x4 *> ( pSIMD ) ); -} - -// save into four words, 16-byte aligned -FORCEINLINE void StoreAlignedIntSIMD( int32 *pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< i32x4 *> ( pSIMD ) ) = a; -} - -FORCEINLINE void StoreAlignedIntSIMD( intx4 &pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< i32x4 *> ( pSIMD.Base() ) ) = a; -} - -FORCEINLINE void StoreUnalignedIntSIMD( int32 *pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< i32x4 *> ( pSIMD ) ) = a; -} - -// Take a fltx4 containing fixed-point uints and -// return them as single precision floats. No -// fixed point conversion is done. -FORCEINLINE fltx4 UnsignedIntConvertToFltSIMD( const u32x4 &vSrcA ) -{ - Assert(0); /* pc has no such operation */ - fltx4 retval; - SubFloat( retval, 0 ) = ( (float) SubInt( retval, 0 ) ); - SubFloat( retval, 1 ) = ( (float) SubInt( retval, 1 ) ); - SubFloat( retval, 2 ) = ( (float) SubInt( retval, 2 ) ); - SubFloat( retval, 3 ) = ( (float) SubInt( retval, 3 ) ); - return retval; -} - - -#if 0 /* pc has no such op */ -// Take a fltx4 containing fixed-point sints and -// return them as single precision floats. No -// fixed point conversion is done. -FORCEINLINE fltx4 SignedIntConvertToFltSIMD( const i32x4 &vSrcA ) -{ - fltx4 retval; - SubFloat( retval, 0 ) = ( (float) (reinterpret_cast(&vSrcA.m128_s32[0])) ); - SubFloat( retval, 1 ) = ( (float) (reinterpret_cast(&vSrcA.m128_s32[1])) ); - SubFloat( retval, 2 ) = ( (float) (reinterpret_cast(&vSrcA.m128_s32[2])) ); - SubFloat( retval, 3 ) = ( (float) (reinterpret_cast(&vSrcA.m128_s32[3])) ); - return retval; -} - - -/* - works on fltx4's as if they are four uints. - the first parameter contains the words to be shifted, - the second contains the amount to shift by AS INTS - - for i = 0 to 3 - shift = vSrcB_i*32:(i*32)+4 - vReturned_i*32:(i*32)+31 = vSrcA_i*32:(i*32)+31 << shift -*/ -FORCEINLINE i32x4 IntShiftLeftWordSIMD(const i32x4 &vSrcA, const i32x4 &vSrcB) -{ - i32x4 retval; - SubInt(retval, 0) = SubInt(vSrcA, 0) << SubInt(vSrcB, 0); - SubInt(retval, 1) = SubInt(vSrcA, 1) << SubInt(vSrcB, 1); - SubInt(retval, 2) = SubInt(vSrcA, 2) << SubInt(vSrcB, 2); - SubInt(retval, 3) = SubInt(vSrcA, 3) << SubInt(vSrcB, 3); - - - return retval; -} -#endif - -#elif ( defined( _X360 ) ) - -//--------------------------------------------------------------------- -// X360 implementation -//--------------------------------------------------------------------- - -FORCEINLINE float & FloatSIMD( fltx4 & a, int idx ) -{ - fltx4_union & a_union = (fltx4_union &)a; - return a_union.m128_f32[idx]; -} - -FORCEINLINE unsigned int & UIntSIMD( fltx4 & a, int idx ) -{ - fltx4_union & a_union = (fltx4_union &)a; - return a_union.m128_u32[idx]; -} - -FORCEINLINE fltx4 AddSIMD( const fltx4 & a, const fltx4 & b ) -{ - return __vaddfp( a, b ); -} - -FORCEINLINE fltx4 SubSIMD( const fltx4 & a, const fltx4 & b ) // a-b -{ - return __vsubfp( a, b ); -} - -FORCEINLINE fltx4 MulSIMD( const fltx4 & a, const fltx4 & b ) // a*b -{ - return __vmulfp( a, b ); -} - -FORCEINLINE fltx4 MaddSIMD( const fltx4 & a, const fltx4 & b, const fltx4 & c ) // a*b + c -{ - return __vmaddfp( a, b, c ); -} - -FORCEINLINE fltx4 MsubSIMD( const fltx4 & a, const fltx4 & b, const fltx4 & c ) // c - a*b -{ - return __vnmsubfp( a, b, c ); -}; - -FORCEINLINE fltx4 Dot3SIMD( const fltx4 &a, const fltx4 &b ) -{ - return __vmsum3fp( a, b ); -} - -FORCEINLINE fltx4 Dot4SIMD( const fltx4 &a, const fltx4 &b ) -{ - return __vmsum4fp( a, b ); -} - -FORCEINLINE fltx4 SinSIMD( const fltx4 &radians ) -{ - return XMVectorSin( radians ); -} - -FORCEINLINE void SinCos3SIMD( fltx4 &sine, fltx4 &cosine, const fltx4 &radians ) -{ - XMVectorSinCos( &sine, &cosine, radians ); -} - -FORCEINLINE void SinCosSIMD( fltx4 &sine, fltx4 &cosine, const fltx4 &radians ) -{ - XMVectorSinCos( &sine, &cosine, radians ); -} - -FORCEINLINE void CosSIMD( fltx4 &cosine, const fltx4 &radians ) -{ - cosine = XMVectorCos( radians ); -} - -FORCEINLINE fltx4 ArcSinSIMD( const fltx4 &sine ) -{ - return XMVectorASin( sine ); -} - -FORCEINLINE fltx4 ArcCosSIMD( const fltx4 &cs ) -{ - return XMVectorACos( cs ); -} - -// tan^1(a/b) .. ie, pass sin in as a and cos in as b -FORCEINLINE fltx4 ArcTan2SIMD( const fltx4 &a, const fltx4 &b ) -{ - return XMVectorATan2( a, b ); -} - -// DivSIMD defined further down, since it uses ReciprocalSIMD - -FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // max(a,b) -{ - return __vmaxfp( a, b ); -} - -FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // min(a,b) -{ - return __vminfp( a, b ); -} - -FORCEINLINE fltx4 AndSIMD( const fltx4 & a, const fltx4 & b ) // a & b -{ - return __vand( a, b ); -} - -FORCEINLINE fltx4 AndNotSIMD( const fltx4 & a, const fltx4 & b ) // ~a & b -{ - // NOTE: a and b are swapped in the call: SSE complements the first argument, VMX the second - return __vandc( b, a ); -} - -FORCEINLINE fltx4 XorSIMD( const fltx4 & a, const fltx4 & b ) // a ^ b -{ - return __vxor( a, b ); -} - -FORCEINLINE fltx4 OrSIMD( const fltx4 & a, const fltx4 & b ) // a | b -{ - return __vor( a, b ); -} - -FORCEINLINE fltx4 NegSIMD(const fltx4 &a) // negate: -a -{ - return XMVectorNegate(a); -} - -FORCEINLINE bool IsAllZeros( const fltx4 & a ) // all floats of a zero? -{ - unsigned int equalFlags = 0; - __vcmpeqfpR( a, Four_Zeros, &equalFlags ); - return XMComparisonAllTrue( equalFlags ); -} - -FORCEINLINE bool IsAnyZeros( const fltx4 & a ) // any floats are zero? -{ - unsigned int conditionregister; - XMVectorEqualR(&conditionregister, a, XMVectorZero()); - return XMComparisonAnyTrue(conditionregister); -} - -FORCEINLINE bool IsAnyXYZZero( const fltx4 &a ) // are any of x,y,z zero? -{ - // copy a's x component into w, in case w was zero. - fltx4 temp = __vrlimi(a, a, 1, 1); - unsigned int conditionregister; - XMVectorEqualR(&conditionregister, temp, XMVectorZero()); - return XMComparisonAnyTrue(conditionregister); -} - -// for branching when a.xyzw > b.xyzw -FORCEINLINE bool IsAllGreaterThan( const fltx4 &a, const fltx4 &b ) -{ - unsigned int cr; - XMVectorGreaterR(&cr,a,b); - return XMComparisonAllTrue(cr); -} - -// for branching when a.xyzw >= b.xyzw -FORCEINLINE bool IsAllGreaterThanOrEq( const fltx4 &a, const fltx4 &b ) -{ - unsigned int cr; - XMVectorGreaterOrEqualR(&cr,a,b); - return XMComparisonAllTrue(cr); -} - -// For branching if all a.xyzw == b.xyzw -FORCEINLINE bool IsAllEqual( const fltx4 & a, const fltx4 & b ) -{ - unsigned int cr; - XMVectorEqualR(&cr,a,b); - return XMComparisonAllTrue(cr); -} - - -FORCEINLINE int TestSignSIMD( const fltx4 & a ) // mask of which floats have the high bit set -{ - // NOTE: this maps to SSE way better than it does to VMX (most code uses IsAnyNegative(), though) - int nRet = 0; - - const fltx4_union & a_union = (const fltx4_union &)a; - nRet |= ( a_union.m128_u32[0] & 0x80000000 ) >> 31; // sign(x) -> bit 0 - nRet |= ( a_union.m128_u32[1] & 0x80000000 ) >> 30; // sign(y) -> bit 1 - nRet |= ( a_union.m128_u32[2] & 0x80000000 ) >> 29; // sign(z) -> bit 2 - nRet |= ( a_union.m128_u32[3] & 0x80000000 ) >> 28; // sign(w) -> bit 3 - - return nRet; -} - -// Squelch the w component of a vector to +0.0. -// Most efficient when you say a = SetWToZeroSIMD(a) (avoids a copy) -FORCEINLINE fltx4 SetWToZeroSIMD( const fltx4 & a ) -{ - return __vrlimi( a, __vzero(), 1, 0 ); -} - -FORCEINLINE bool IsAnyNegative( const fltx4 & a ) // (a.x < 0) || (a.y < 0) || (a.z < 0) || (a.w < 0) -{ - // NOTE: this tests the top bits of each vector element using integer math - // (so it ignores NaNs - it will return true for "-NaN") - unsigned int equalFlags = 0; - fltx4 signMask = __vspltisw( -1 ); // 0xFFFFFFFF 0xFFFFFFFF 0xFFFFFFFF 0xFFFFFFFF (low order 5 bits of each element = 31) - signMask = __vslw( signMask, signMask ); // 0x80000000 0x80000000 0x80000000 0x80000000 - __vcmpequwR( Four_Zeros, __vand( signMask, a ), &equalFlags ); - return !XMComparisonAllTrue( equalFlags ); -} - -FORCEINLINE fltx4 CmpEqSIMD( const fltx4 & a, const fltx4 & b ) // (a==b) ? ~0:0 -{ - return __vcmpeqfp( a, b ); -} - - -FORCEINLINE fltx4 CmpGtSIMD( const fltx4 & a, const fltx4 & b ) // (a>b) ? ~0:0 -{ - return __vcmpgtfp( a, b ); -} - -FORCEINLINE fltx4 CmpGeSIMD( const fltx4 & a, const fltx4 & b ) // (a>=b) ? ~0:0 -{ - return __vcmpgefp( a, b ); -} - -FORCEINLINE fltx4 CmpLtSIMD( const fltx4 & a, const fltx4 & b ) // (a= -b) ? ~0 : 0 -{ - return XMVectorInBounds( a, b ); -} - -// returned[i] = ReplacementMask[i] == 0 ? OldValue : NewValue -FORCEINLINE fltx4 MaskedAssign( const fltx4 & ReplacementMask, const fltx4 & NewValue, const fltx4 & OldValue ) -{ - return __vsel( OldValue, NewValue, ReplacementMask ); -} - -// AKA "Broadcast", "Splat" -FORCEINLINE fltx4 ReplicateX4( float flValue ) // a,a,a,a -{ - // NOTE: if flValue comes from a register, this causes a Load-Hit-Store stall (don't mix fpu/vpu math!) - float * pValue = &flValue; - Assert( pValue ); - Assert( ((unsigned int)pValue & 3) == 0); - return __vspltw( __lvlx( pValue, 0 ), 0 ); -} - -FORCEINLINE fltx4 ReplicateX4( const float *pValue ) // a,a,a,a -{ - Assert( pValue ); - return __vspltw( __lvlx( pValue, 0 ), 0 ); -} - -/// replicate a single 32 bit integer value to all 4 components of an m128 -FORCEINLINE fltx4 ReplicateIX4( int nValue ) -{ - // NOTE: if nValue comes from a register, this causes a Load-Hit-Store stall (should not mix ints with fltx4s!) - int * pValue = &nValue; - Assert( pValue ); - Assert( ((unsigned int)pValue & 3) == 0); - return __vspltw( __lvlx( pValue, 0 ), 0 ); -} - -// Round towards positive infinity -FORCEINLINE fltx4 CeilSIMD( const fltx4 &a ) -{ - return __vrfip(a); -} - -// Round towards nearest integer -FORCEINLINE fltx4 RoundSIMD( const fltx4 &a ) -{ - return __vrfin(a); -} - -// Round towards negative infinity -FORCEINLINE fltx4 FloorSIMD( const fltx4 &a ) -{ - return __vrfim(a); -} - -FORCEINLINE fltx4 SqrtEstSIMD( const fltx4 & a ) // sqrt(a), more or less -{ - // This is emulated from rsqrt - return XMVectorSqrtEst( a ); -} - -FORCEINLINE fltx4 SqrtSIMD( const fltx4 & a ) // sqrt(a) -{ - // This is emulated from rsqrt - return XMVectorSqrt( a ); -} - -FORCEINLINE fltx4 ReciprocalSqrtEstSIMD( const fltx4 & a ) // 1/sqrt(a), more or less -{ - return __vrsqrtefp( a ); -} - -FORCEINLINE fltx4 ReciprocalSqrtEstSaturateSIMD( const fltx4 & a ) -{ - // Convert zeros to epsilons - fltx4 zero_mask = CmpEqSIMD( a, Four_Zeros ); - fltx4 a_safe = OrSIMD( a, AndSIMD( Four_Epsilons, zero_mask ) ); - return ReciprocalSqrtEstSIMD( a_safe ); -} - -FORCEINLINE fltx4 ReciprocalSqrtSIMD( const fltx4 & a ) // 1/sqrt(a) -{ - // This uses Newton-Raphson to improve the HW result - return XMVectorReciprocalSqrt( a ); -} - -FORCEINLINE fltx4 ReciprocalEstSIMD( const fltx4 & a ) // 1/a, more or less -{ - return __vrefp( a ); -} - -/// 1/x for all 4 values. uses reciprocal approximation instruction plus newton iteration. -/// No error checking! -FORCEINLINE fltx4 ReciprocalSIMD( const fltx4 & a ) // 1/a -{ - // This uses Newton-Raphson to improve the HW result - return XMVectorReciprocal( a ); -} - -// FIXME: on 360, this is very slow, since it uses ReciprocalSIMD (do we need DivEstSIMD?) -FORCEINLINE fltx4 DivSIMD( const fltx4 & a, const fltx4 & b ) // a/b -{ - return MulSIMD( ReciprocalSIMD( b ), a ); -} - -/// 1/x for all 4 values. -/// 1/0 will result in a big but NOT infinite result -FORCEINLINE fltx4 ReciprocalEstSaturateSIMD( const fltx4 & a ) -{ - // Convert zeros to epsilons - fltx4 zero_mask = CmpEqSIMD( a, Four_Zeros ); - fltx4 a_safe = OrSIMD( a, AndSIMD( Four_Epsilons, zero_mask ) ); - return ReciprocalEstSIMD( a_safe ); -} - -FORCEINLINE fltx4 ReciprocalSaturateSIMD( const fltx4 & a ) -{ - // Convert zeros to epsilons - fltx4 zero_mask = CmpEqSIMD( a, Four_Zeros ); - fltx4 a_safe = OrSIMD( a, AndSIMD( Four_Epsilons, zero_mask ) ); - return ReciprocalSIMD( a_safe ); - - // FIXME: This could be faster (BUT: it doesn't preserve the sign of -0.0, whereas the above does) - // fltx4 zeroMask = CmpEqSIMD( Four_Zeros, a ); - // fltx4 a_safe = XMVectorSelect( a, Four_Epsilons, zeroMask ); - // return ReciprocalSIMD( a_safe ); -} - -// CHRISG: is it worth doing integer bitfiddling for this? -// 2^x for all values (the antilog) -FORCEINLINE fltx4 ExpSIMD( const fltx4 &toPower ) -{ - return XMVectorExp(toPower); -} - -// Clamps the components of a vector to a specified minimum and maximum range. -FORCEINLINE fltx4 ClampVectorSIMD( FLTX4 in, FLTX4 min, FLTX4 max) -{ - return XMVectorClamp(in, min, max); -} - -FORCEINLINE fltx4 LoadUnalignedSIMD( const void *pSIMD ) -{ - return XMLoadVector4( pSIMD ); -} - -// load a 3-vector (as opposed to LoadUnalignedSIMD, which loads a 4-vec). -FORCEINLINE fltx4 LoadUnaligned3SIMD( const void *pSIMD ) -{ - return XMLoadVector3( pSIMD ); -} - -FORCEINLINE fltx4 LoadAlignedSIMD( const void *pSIMD ) -{ - return *( reinterpret_cast< const fltx4 *> ( pSIMD ) ); -} - -// for the transitional class -- load a 3-by VectorAligned and squash its w component -FORCEINLINE fltx4 LoadAlignedSIMD( const VectorAligned & pSIMD ) -{ - fltx4 out = XMLoadVector3A(pSIMD.Base()); - // squelch w - return __vrlimi( out, __vzero(), 1, 0 ); -} - -// for the transitional class -- load a 3-by VectorAligned and squash its w component -FORCEINLINE fltx4 LoadAlignedSIMD( const VectorAligned * RESTRICT pSIMD ) -{ - fltx4 out = XMLoadVector3A(pSIMD); - // squelch w - return __vrlimi( out, __vzero(), 1, 0 ); -} - -FORCEINLINE void StoreAlignedSIMD( float *pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< fltx4 *> ( pSIMD ) ) = a; -} - -FORCEINLINE void StoreUnalignedSIMD( float *pSIMD, const fltx4 & a ) -{ - XMStoreVector4( pSIMD, a ); -} - -FORCEINLINE void StoreUnaligned3SIMD( float *pSIMD, const fltx4 & a ) -{ - XMStoreVector3( pSIMD, a ); -} - - -// strongly typed -- for typechecking as we transition to SIMD -FORCEINLINE void StoreAligned3SIMD( VectorAligned * RESTRICT pSIMD, const fltx4 & a ) -{ - XMStoreVector3A(pSIMD->Base(),a); -} - - -// Fixed-point conversion and save as SIGNED INTS. -// pDest->x = Int (vSrc.x) -// note: some architectures have means of doing -// fixed point conversion when the fix depth is -// specified as an immediate.. but there is no way -// to guarantee an immediate as a parameter to function -// like this. -FORCEINLINE void ConvertStoreAsIntsSIMD(intx4 * RESTRICT pDest, const fltx4 &vSrc) -{ - fltx4 asInt = __vctsxs( vSrc, 0 ); - XMStoreVector4A(pDest->Base(), asInt); -} - -FORCEINLINE void TransposeSIMD( fltx4 & x, fltx4 & y, fltx4 & z, fltx4 & w ) -{ - XMMATRIX xyzwMatrix = _XMMATRIX( x, y, z, w ); - xyzwMatrix = XMMatrixTranspose( xyzwMatrix ); - x = xyzwMatrix.r[0]; - y = xyzwMatrix.r[1]; - z = xyzwMatrix.r[2]; - w = xyzwMatrix.r[3]; -} - -// Return one in the fastest way -- faster even than loading. -FORCEINLINE fltx4 LoadZeroSIMD( void ) -{ - return XMVectorZero(); -} - -// Return one in the fastest way -- faster even than loading. -FORCEINLINE fltx4 LoadOneSIMD( void ) -{ - return XMVectorSplatOne(); -} - -FORCEINLINE fltx4 SplatXSIMD( fltx4 a ) -{ - return XMVectorSplatX( a ); -} - -FORCEINLINE fltx4 SplatYSIMD( fltx4 a ) -{ - return XMVectorSplatY( a ); -} - -FORCEINLINE fltx4 SplatZSIMD( fltx4 a ) -{ - return XMVectorSplatZ( a ); -} - -FORCEINLINE fltx4 SplatWSIMD( fltx4 a ) -{ - return XMVectorSplatW( a ); -} - -FORCEINLINE fltx4 SetXSIMD( const fltx4& a, const fltx4& x ) -{ - fltx4 result = __vrlimi(a, x, 8, 0); - return result; -} - -FORCEINLINE fltx4 SetYSIMD( const fltx4& a, const fltx4& y ) -{ - fltx4 result = __vrlimi(a, y, 4, 0); - return result; -} - -FORCEINLINE fltx4 SetZSIMD( const fltx4& a, const fltx4& z ) -{ - fltx4 result = __vrlimi(a, z, 2, 0); - return result; -} - -FORCEINLINE fltx4 SetWSIMD( const fltx4& a, const fltx4& w ) -{ - fltx4 result = __vrlimi(a, w, 1, 0); - return result; -} - -FORCEINLINE fltx4 SetComponentSIMD( const fltx4& a, int nComponent, float flValue ) -{ - static int s_nVrlimiMask[4] = { 8, 4, 2, 1 }; - fltx4 val = ReplicateX4( flValue ); - fltx4 result = __vrlimi(a, val, s_nVrlimiMask[nComponent], 0); - return result; -} - -FORCEINLINE fltx4 RotateLeft( const fltx4 & a ) -{ - fltx4 compareOne = a; - return __vrlimi( compareOne, a, 8 | 4 | 2 | 1, 1 ); -} - -FORCEINLINE fltx4 RotateLeft2( const fltx4 & a ) -{ - fltx4 compareOne = a; - return __vrlimi( compareOne, a, 8 | 4 | 2 | 1, 2 ); -} - - - -// find the lowest component of a.x, a.y, a.z, -// and replicate it to the whole return value. -// ignores a.w. -// Though this is only five instructions long, -// they are all dependent, making this stall city. -// Forcing this inline should hopefully help with scheduling. -FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 & a ) -{ - // a is [x,y,z,G] (where G is garbage) - // rotate left by one - fltx4 compareOne = a ; - compareOne = __vrlimi( compareOne, a, 8 | 4 , 1 ); - // compareOne is [y,z,G,G] - fltx4 retval = MinSIMD( a, compareOne ); - // retVal is [min(x,y), min(y,z), G, G] - compareOne = __vrlimi( compareOne, a, 8 , 2); - // compareOne is [z, G, G, G] - retval = MinSIMD( retval, compareOne ); - // retVal = [ min(min(x,y),z), G, G, G ] - - // splat the x component out to the whole vector and return - return SplatXSIMD( retval ); -} - -// find the highest component of a.x, a.y, a.z, -// and replicate it to the whole return value. -// ignores a.w. -// Though this is only five instructions long, -// they are all dependent, making this stall city. -// Forcing this inline should hopefully help with scheduling. -FORCEINLINE fltx4 FindHighestSIMD3( const fltx4 & a ) -{ - // a is [x,y,z,G] (where G is garbage) - // rotate left by one - fltx4 compareOne = a ; - compareOne = __vrlimi( compareOne, a, 8 | 4 , 1 ); - // compareOne is [y,z,G,G] - fltx4 retval = MaxSIMD( a, compareOne ); - // retVal is [max(x,y), max(y,z), G, G] - compareOne = __vrlimi( compareOne, a, 8 , 2); - // compareOne is [z, G, G, G] - retval = MaxSIMD( retval, compareOne ); - // retVal = [ max(max(x,y),z), G, G, G ] - - // splat the x component out to the whole vector and return - return SplatXSIMD( retval ); -} - - -// Transform many (horizontal) points in-place by a 3x4 matrix, -// here already loaded onto three fltx4 registers. -// The points must be stored as 16-byte aligned. They are points -// and not vectors because we assume the w-component to be 1. -// To spare yourself the annoyance of loading the matrix yourself, -// use one of the overloads below. -void TransformManyPointsBy(VectorAligned * RESTRICT pVectors, unsigned int numVectors, FLTX4 mRow1, FLTX4 mRow2, FLTX4 mRow3); - -// Transform many (horizontal) points in-place by a 3x4 matrix. -// The points must be stored as 16-byte aligned. They are points -// and not vectors because we assume the w-component to be 1. -// In this function, the matrix need not be aligned. -FORCEINLINE void TransformManyPointsBy(VectorAligned * RESTRICT pVectors, unsigned int numVectors, const matrix3x4_t &pMatrix) -{ - return TransformManyPointsBy(pVectors, numVectors, - LoadUnalignedSIMD( pMatrix[0] ), LoadUnalignedSIMD( pMatrix[1] ), LoadUnalignedSIMD( pMatrix[2] ) ); -} - -// Transform many (horizontal) points in-place by a 3x4 matrix. -// The points must be stored as 16-byte aligned. They are points -// and not vectors because we assume the w-component to be 1. -// In this function, the matrix must itself be aligned on a 16-byte -// boundary. -FORCEINLINE void TransformManyPointsByA(VectorAligned * RESTRICT pVectors, unsigned int numVectors, const matrix3x4_t &pMatrix) -{ - return TransformManyPointsBy(pVectors, numVectors, - LoadAlignedSIMD( pMatrix[0] ), LoadAlignedSIMD( pMatrix[1] ), LoadAlignedSIMD( pMatrix[2] ) ); -} - -// ------------------------------------ -// INTEGER SIMD OPERATIONS. -// ------------------------------------ - -// Load 4 aligned words into a SIMD register -FORCEINLINE i32x4 LoadAlignedIntSIMD( const void * RESTRICT pSIMD) -{ - return XMLoadVector4A(pSIMD); -} - -// Load 4 unaligned words into a SIMD register -FORCEINLINE i32x4 LoadUnalignedIntSIMD(const void * RESTRICT pSIMD) -{ - return XMLoadVector4( pSIMD ); -} - -// save into four words, 16-byte aligned -FORCEINLINE void StoreAlignedIntSIMD( int32 *pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< i32x4 *> ( pSIMD ) ) = a; -} - -FORCEINLINE void StoreAlignedIntSIMD( intx4 &pSIMD, const fltx4 & a ) -{ - *( reinterpret_cast< i32x4 *> ( pSIMD.Base() ) ) = a; -} - -FORCEINLINE void StoreUnalignedIntSIMD( int32 *pSIMD, const fltx4 & a ) -{ - XMStoreVector4(pSIMD, a); -} - - -// Take a fltx4 containing fixed-point uints and -// return them as single precision floats. No -// fixed point conversion is done. -FORCEINLINE fltx4 UnsignedIntConvertToFltSIMD( const i32x4 &vSrcA ) -{ - return __vcfux( vSrcA, 0 ); -} - - -// Take a fltx4 containing fixed-point sints and -// return them as single precision floats. No -// fixed point conversion is done. -FORCEINLINE fltx4 SignedIntConvertToFltSIMD( const i32x4 &vSrcA ) -{ - return __vcfsx( vSrcA, 0 ); -} - -// Take a fltx4 containing fixed-point uints and -// return them as single precision floats. Each uint -// will be divided by 2^immed after conversion -// (eg, this is fixed point math). -/* as if: - FORCEINLINE fltx4 UnsignedIntConvertToFltSIMD( const i32x4 &vSrcA, unsigned int uImmed ) - { - return __vcfux( vSrcA, uImmed ); - } -*/ -#define UnsignedFixedIntConvertToFltSIMD(vSrcA, uImmed) (__vcfux( (vSrcA), (uImmed) )) - -// Take a fltx4 containing fixed-point sints and -// return them as single precision floats. Each int -// will be divided by 2^immed (eg, this is fixed point -// math). -/* as if: - FORCEINLINE fltx4 SignedIntConvertToFltSIMD( const i32x4 &vSrcA, unsigned int uImmed ) - { - return __vcfsx( vSrcA, uImmed ); - } -*/ -#define SignedFixedIntConvertToFltSIMD(vSrcA, uImmed) (__vcfsx( (vSrcA), (uImmed) )) - -// set all components of a vector to a signed immediate int number. -/* as if: - FORCEINLINE fltx4 IntSetImmediateSIMD(int toImmediate) - { - return __vspltisw( toImmediate ); - } -*/ -#define IntSetImmediateSIMD(x) (__vspltisw(x)) - -/* - works on fltx4's as if they are four uints. - the first parameter contains the words to be shifted, - the second contains the amount to shift by AS INTS - - for i = 0 to 3 - shift = vSrcB_i*32:(i*32)+4 - vReturned_i*32:(i*32)+31 = vSrcA_i*32:(i*32)+31 << shift -*/ -FORCEINLINE fltx4 IntShiftLeftWordSIMD(fltx4 vSrcA, fltx4 vSrcB) -{ - return __vslw(vSrcA, vSrcB); -} - -FORCEINLINE float SubFloat( const fltx4 & a, int idx ) -{ - // NOTE: if the output goes into a register, this causes a Load-Hit-Store stall (don't mix fpu/vpu math!) - const fltx4_union & a_union = (const fltx4_union &)a; - return a_union.m128_f32[ idx ]; -} - -FORCEINLINE float & SubFloat( fltx4 & a, int idx ) -{ - fltx4_union & a_union = (fltx4_union &)a; - return a_union.m128_f32[idx]; -} - -FORCEINLINE uint32 SubFloatConvertToInt( const fltx4 & a, int idx ) -{ - fltx4 t = __vctuxs( a, 0 ); - const fltx4_union & a_union = (const fltx4_union &)t; - return a_union.m128_u32[idx]; -} - - -FORCEINLINE uint32 SubInt( const fltx4 & a, int idx ) -{ - const fltx4_union & a_union = (const fltx4_union &)a; - return a_union.m128_u32[idx]; -} - -FORCEINLINE uint32 & SubInt( fltx4 & a, int idx ) -{ - fltx4_union & a_union = (fltx4_union &)a; - return a_union.m128_u32[idx]; -} - -#else - -//--------------------------------------------------------------------- -// Intel/SSE implementation -//--------------------------------------------------------------------- - -FORCEINLINE void StoreAlignedSIMD( float * RESTRICT pSIMD, const fltx4 & a ) -{ - _mm_store_ps( pSIMD, a ); -} - -FORCEINLINE void StoreUnalignedSIMD( float * RESTRICT pSIMD, const fltx4 & a ) -{ - _mm_storeu_ps( pSIMD, a ); -} - - -FORCEINLINE fltx4 RotateLeft( const fltx4 & a ); -FORCEINLINE fltx4 RotateLeft2( const fltx4 & a ); - -FORCEINLINE void StoreUnaligned3SIMD( float *pSIMD, const fltx4 & a ) -{ - _mm_store_ss(pSIMD, a); - _mm_store_ss(pSIMD+1, RotateLeft(a)); - _mm_store_ss(pSIMD+2, RotateLeft2(a)); -} - -// strongly typed -- syntactic castor oil used for typechecking as we transition to SIMD -FORCEINLINE void StoreAligned3SIMD( VectorAligned * RESTRICT pSIMD, const fltx4 & a ) -{ - StoreAlignedSIMD( pSIMD->Base(),a ); -} - -FORCEINLINE fltx4 LoadAlignedSIMD( const void *pSIMD ) -{ - return _mm_load_ps( reinterpret_cast< const float *> ( pSIMD ) ); -} - -FORCEINLINE fltx4 AndSIMD( const fltx4 & a, const fltx4 & b ) // a & b -{ - return _mm_and_ps( a, b ); -} - -FORCEINLINE fltx4 AndNotSIMD( const fltx4 & a, const fltx4 & b ) // a & ~b -{ - return _mm_andnot_ps( a, b ); -} - -FORCEINLINE fltx4 XorSIMD( const fltx4 & a, const fltx4 & b ) // a ^ b -{ - return _mm_xor_ps( a, b ); -} - -FORCEINLINE fltx4 OrSIMD( const fltx4 & a, const fltx4 & b ) // a | b -{ - return _mm_or_ps( a, b ); -} - -// Squelch the w component of a vector to +0.0. -// Most efficient when you say a = SetWToZeroSIMD(a) (avoids a copy) -FORCEINLINE fltx4 SetWToZeroSIMD( const fltx4 & a ) -{ - return AndSIMD( a, LoadAlignedSIMD( g_SIMD_clear_wmask ) ); -} - -// for the transitional class -- load a 3-by VectorAligned and squash its w component -FORCEINLINE fltx4 LoadAlignedSIMD( const VectorAligned & pSIMD ) -{ - return SetWToZeroSIMD( LoadAlignedSIMD(pSIMD.Base()) ); -} - -FORCEINLINE fltx4 LoadUnalignedSIMD( const void *pSIMD ) -{ - return _mm_loadu_ps( reinterpret_cast( pSIMD ) ); -} - -FORCEINLINE fltx4 LoadUnaligned3SIMD( const void *pSIMD ) -{ - return _mm_loadu_ps( reinterpret_cast( pSIMD ) ); -} - -/// replicate a single 32 bit integer value to all 4 components of an m128 -FORCEINLINE fltx4 ReplicateIX4( int i ) -{ - fltx4 value = _mm_set_ss( * ( ( float *) &i ) );; - return _mm_shuffle_ps( value, value, 0); -} - - -FORCEINLINE fltx4 ReplicateX4( float flValue ) -{ - __m128 value = _mm_set_ss( flValue ); - return _mm_shuffle_ps( value, value, 0 ); -} - - -FORCEINLINE float SubFloat( const fltx4 & a, int idx ) -{ - // NOTE: if the output goes into a register, this causes a Load-Hit-Store stall (don't mix fpu/vpu math!) -#ifndef _LINUX - return a.m128_f32[ idx ]; -#else - return (reinterpret_cast(&a))[idx]; -#endif -} - -FORCEINLINE float & SubFloat( fltx4 & a, int idx ) -{ -#ifndef _LINUX - return a.m128_f32[ idx ]; -#else - return (reinterpret_cast(&a))[idx]; -#endif -} - -FORCEINLINE uint32 SubFloatConvertToInt( const fltx4 & a, int idx ) -{ - return (uint32)SubFloat(a,idx); -} - -FORCEINLINE uint32 SubInt( const fltx4 & a, int idx ) -{ -#ifndef _LINUX - return a.m128_u32[idx]; -#else - return (reinterpret_cast(&a))[idx]; -#endif -} - -FORCEINLINE uint32 & SubInt( fltx4 & a, int idx ) -{ -#ifndef _LINUX - return a.m128_u32[idx]; -#else - return (reinterpret_cast(&a))[idx]; -#endif -} - -// Return one in the fastest way -- on the x360, faster even than loading. -FORCEINLINE fltx4 LoadZeroSIMD( void ) -{ - return Four_Zeros; -} - -// Return one in the fastest way -- on the x360, faster even than loading. -FORCEINLINE fltx4 LoadOneSIMD( void ) -{ - return Four_Ones; -} - -FORCEINLINE fltx4 MaskedAssign( const fltx4 & ReplacementMask, const fltx4 & NewValue, const fltx4 & OldValue ) -{ - return OrSIMD( - AndSIMD( ReplacementMask, NewValue ), - AndNotSIMD( ReplacementMask, OldValue ) ); -} - -// remember, the SSE numbers its words 3 2 1 0 -// The way we want to specify shuffles is backwards from the default -// MM_SHUFFLE_REV is in array index order (default is reversed) -#define MM_SHUFFLE_REV(a,b,c,d) _MM_SHUFFLE(d,c,b,a) - -FORCEINLINE fltx4 SplatXSIMD( fltx4 const & a ) -{ - return _mm_shuffle_ps( a, a, MM_SHUFFLE_REV( 0, 0, 0, 0 ) ); -} - -FORCEINLINE fltx4 SplatYSIMD( fltx4 const &a ) -{ - return _mm_shuffle_ps( a, a, MM_SHUFFLE_REV( 1, 1, 1, 1 ) ); -} - -FORCEINLINE fltx4 SplatZSIMD( fltx4 const &a ) -{ - return _mm_shuffle_ps( a, a, MM_SHUFFLE_REV( 2, 2, 2, 2 ) ); -} - -FORCEINLINE fltx4 SplatWSIMD( fltx4 const &a ) -{ - return _mm_shuffle_ps( a, a, _MM_SHUFFLE( 3, 3, 3, 3 ) ); -} - -FORCEINLINE fltx4 SetXSIMD( const fltx4& a, const fltx4& x ) -{ - fltx4 result = MaskedAssign( LoadAlignedSIMD( g_SIMD_ComponentMask[0] ), x, a ); - return result; -} - -FORCEINLINE fltx4 SetYSIMD( const fltx4& a, const fltx4& y ) -{ - fltx4 result = MaskedAssign( LoadAlignedSIMD( g_SIMD_ComponentMask[1] ), y, a ); - return result; -} - -FORCEINLINE fltx4 SetZSIMD( const fltx4& a, const fltx4& z ) -{ - fltx4 result = MaskedAssign( LoadAlignedSIMD( g_SIMD_ComponentMask[2] ), z, a ); - return result; -} - -FORCEINLINE fltx4 SetWSIMD( const fltx4& a, const fltx4& w ) -{ - fltx4 result = MaskedAssign( LoadAlignedSIMD( g_SIMD_ComponentMask[3] ), w, a ); - return result; -} - -FORCEINLINE fltx4 SetComponentSIMD( const fltx4& a, int nComponent, float flValue ) -{ - fltx4 val = ReplicateX4( flValue ); - fltx4 result = MaskedAssign( LoadAlignedSIMD( g_SIMD_ComponentMask[nComponent] ), val, a ); - return result; -} - -// a b c d -> b c d a -FORCEINLINE fltx4 RotateLeft( const fltx4 & a ) -{ - return _mm_shuffle_ps( a, a, MM_SHUFFLE_REV( 1, 2, 3, 0 ) ); -} - -// a b c d -> c d a b -FORCEINLINE fltx4 RotateLeft2( const fltx4 & a ) -{ - return _mm_shuffle_ps( a, a, MM_SHUFFLE_REV( 2, 3, 0, 1 ) ); -} - -// a b c d -> d a b c -FORCEINLINE fltx4 RotateRight( const fltx4 & a ) -{ - return _mm_shuffle_ps( a, a, _MM_SHUFFLE( 0, 3, 2, 1) ); -} - -// a b c d -> c d a b -FORCEINLINE fltx4 RotateRight2( const fltx4 & a ) -{ - return _mm_shuffle_ps( a, a, _MM_SHUFFLE( 1, 0, 3, 2 ) ); -} - - -FORCEINLINE fltx4 AddSIMD( const fltx4 & a, const fltx4 & b ) // a+b -{ - return _mm_add_ps( a, b ); -}; - -FORCEINLINE fltx4 SubSIMD( const fltx4 & a, const fltx4 & b ) // a-b -{ - return _mm_sub_ps( a, b ); -}; - -FORCEINLINE fltx4 MulSIMD( const fltx4 & a, const fltx4 & b ) // a*b -{ - return _mm_mul_ps( a, b ); -}; - -FORCEINLINE fltx4 DivSIMD( const fltx4 & a, const fltx4 & b ) // a/b -{ - return _mm_div_ps( a, b ); -}; - -FORCEINLINE fltx4 MaddSIMD( const fltx4 & a, const fltx4 & b, const fltx4 & c ) // a*b + c -{ - return AddSIMD( MulSIMD(a,b), c ); -} - -FORCEINLINE fltx4 MsubSIMD( const fltx4 & a, const fltx4 & b, const fltx4 & c ) // c - a*b -{ - return SubSIMD( c, MulSIMD(a,b) ); -}; - -FORCEINLINE fltx4 Dot3SIMD( const fltx4 &a, const fltx4 &b ) -{ - fltx4 m = MulSIMD( a, b ); - float flDot = SubFloat( m, 0 ) + SubFloat( m, 1 ) + SubFloat( m, 2 ); - return ReplicateX4( flDot ); -} - -FORCEINLINE fltx4 Dot4SIMD( const fltx4 &a, const fltx4 &b ) -{ - fltx4 m = MulSIMD( a, b ); - float flDot = SubFloat( m, 0 ) + SubFloat( m, 1 ) + SubFloat( m, 2 ) + SubFloat( m, 3 ); - return ReplicateX4( flDot ); -} - -//TODO: implement as four-way Taylor series (see xbox implementation) -FORCEINLINE fltx4 SinSIMD( const fltx4 &radians ) -{ - fltx4 result; - SubFloat( result, 0 ) = sin( SubFloat( radians, 0 ) ); - SubFloat( result, 1 ) = sin( SubFloat( radians, 1 ) ); - SubFloat( result, 2 ) = sin( SubFloat( radians, 2 ) ); - SubFloat( result, 3 ) = sin( SubFloat( radians, 3 ) ); - return result; -} - -FORCEINLINE void SinCos3SIMD( fltx4 &sine, fltx4 &cosine, const fltx4 &radians ) -{ - // FIXME: Make a fast SSE version - SinCos( SubFloat( radians, 0 ), &SubFloat( sine, 0 ), &SubFloat( cosine, 0 ) ); - SinCos( SubFloat( radians, 1 ), &SubFloat( sine, 1 ), &SubFloat( cosine, 1 ) ); - SinCos( SubFloat( radians, 2 ), &SubFloat( sine, 2 ), &SubFloat( cosine, 2 ) ); -} - -FORCEINLINE void SinCosSIMD( fltx4 &sine, fltx4 &cosine, const fltx4 &radians ) // a*b + c -{ - // FIXME: Make a fast SSE version - SinCos( SubFloat( radians, 0 ), &SubFloat( sine, 0 ), &SubFloat( cosine, 0 ) ); - SinCos( SubFloat( radians, 1 ), &SubFloat( sine, 1 ), &SubFloat( cosine, 1 ) ); - SinCos( SubFloat( radians, 2 ), &SubFloat( sine, 2 ), &SubFloat( cosine, 2 ) ); - SinCos( SubFloat( radians, 3 ), &SubFloat( sine, 3 ), &SubFloat( cosine, 3 ) ); -} - -//TODO: implement as four-way Taylor series (see xbox implementation) -FORCEINLINE fltx4 ArcSinSIMD( const fltx4 &sine ) -{ - // FIXME: Make a fast SSE version - fltx4 result; - SubFloat( result, 0 ) = asin( SubFloat( sine, 0 ) ); - SubFloat( result, 1 ) = asin( SubFloat( sine, 1 ) ); - SubFloat( result, 2 ) = asin( SubFloat( sine, 2 ) ); - SubFloat( result, 3 ) = asin( SubFloat( sine, 3 ) ); - return result; -} - -FORCEINLINE fltx4 ArcCosSIMD( const fltx4 &cs ) -{ - fltx4 result; - SubFloat( result, 0 ) = acos( SubFloat( cs, 0 ) ); - SubFloat( result, 1 ) = acos( SubFloat( cs, 1 ) ); - SubFloat( result, 2 ) = acos( SubFloat( cs, 2 ) ); - SubFloat( result, 3 ) = acos( SubFloat( cs, 3 ) ); - return result; -} - -// tan^1(a/b) .. ie, pass sin in as a and cos in as b -FORCEINLINE fltx4 ArcTan2SIMD( const fltx4 &a, const fltx4 &b ) -{ - fltx4 result; - SubFloat( result, 0 ) = atan2( SubFloat( a, 0 ), SubFloat( b, 0 ) ); - SubFloat( result, 1 ) = atan2( SubFloat( a, 1 ), SubFloat( b, 1 ) ); - SubFloat( result, 2 ) = atan2( SubFloat( a, 2 ), SubFloat( b, 2 ) ); - SubFloat( result, 3 ) = atan2( SubFloat( a, 3 ), SubFloat( b, 3 ) ); - return result; -} - -FORCEINLINE fltx4 NegSIMD(const fltx4 &a) // negate: -a -{ - return SubSIMD(LoadZeroSIMD(),a); -} - -FORCEINLINE int TestSignSIMD( const fltx4 & a ) // mask of which floats have the high bit set -{ - return _mm_movemask_ps( a ); -} - -FORCEINLINE bool IsAnyNegative( const fltx4 & a ) // (a.x < 0) || (a.y < 0) || (a.z < 0) || (a.w < 0) -{ - return (0 != TestSignSIMD( a )); -} - -FORCEINLINE fltx4 CmpEqSIMD( const fltx4 & a, const fltx4 & b ) // (a==b) ? ~0:0 -{ - return _mm_cmpeq_ps( a, b ); -} - -FORCEINLINE fltx4 CmpGtSIMD( const fltx4 & a, const fltx4 & b ) // (a>b) ? ~0:0 -{ - return _mm_cmpgt_ps( a, b ); -} - -FORCEINLINE fltx4 CmpGeSIMD( const fltx4 & a, const fltx4 & b ) // (a>=b) ? ~0:0 -{ - return _mm_cmpge_ps( a, b ); -} - -FORCEINLINE fltx4 CmpLtSIMD( const fltx4 & a, const fltx4 & b ) // (a b.xyzw -FORCEINLINE bool IsAllGreaterThan( const fltx4 &a, const fltx4 &b ) -{ - return TestSignSIMD( CmpLeSIMD( a, b ) ) == 0; -} - -// for branching when a.xyzw >= b.xyzw -FORCEINLINE bool IsAllGreaterThanOrEq( const fltx4 &a, const fltx4 &b ) -{ - return TestSignSIMD( CmpLtSIMD( a, b ) ) == 0; -} - -// For branching if all a.xyzw == b.xyzw -FORCEINLINE bool IsAllEqual( const fltx4 & a, const fltx4 & b ) -{ - return TestSignSIMD( CmpEqSIMD( a, b ) ) == 0xf; -} - -FORCEINLINE fltx4 CmpInBoundsSIMD( const fltx4 & a, const fltx4 & b ) // (a <= b && a >= -b) ? ~0 : 0 -{ - return AndSIMD( CmpLeSIMD(a,b), CmpGeSIMD(a, NegSIMD(b)) ); -} - -FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // min(a,b) -{ - return _mm_min_ps( a, b ); -} - -FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // max(a,b) -{ - return _mm_max_ps( a, b ); -} - - - -// SSE lacks rounding operations. -// Really. -// You can emulate them by setting the rounding mode for the -// whole processor and then converting to int, and then back again. -// But every time you set the rounding mode, you clear out the -// entire pipeline. So, I can't do them per operation. You -// have to do it once, before the loop that would call these. -// Round towards positive infinity -FORCEINLINE fltx4 CeilSIMD( const fltx4 &a ) -{ - fltx4 retVal; - SubFloat( retVal, 0 ) = ceil( SubFloat( a, 0 ) ); - SubFloat( retVal, 1 ) = ceil( SubFloat( a, 1 ) ); - SubFloat( retVal, 2 ) = ceil( SubFloat( a, 2 ) ); - SubFloat( retVal, 3 ) = ceil( SubFloat( a, 3 ) ); - return retVal; - -} - -fltx4 fabs( const fltx4 & x ); -// Round towards negative infinity -// This is the implementation that was here before; it assumes -// you are in round-to-floor mode, which I guess is usually the -// case for us vis-a-vis SSE. It's totally unnecessary on -// VMX, which has a native floor op. -FORCEINLINE fltx4 FloorSIMD( const fltx4 &val ) -{ - fltx4 fl4Abs = fabs( val ); - fltx4 ival = SubSIMD( AddSIMD( fl4Abs, Four_2ToThe23s ), Four_2ToThe23s ); - ival = MaskedAssign( CmpGtSIMD( ival, fl4Abs ), SubSIMD( ival, Four_Ones ), ival ); - return XorSIMD( ival, XorSIMD( val, fl4Abs ) ); // restore sign bits -} - - - -inline bool IsAllZeros( const fltx4 & var ) -{ - return TestSignSIMD( CmpEqSIMD( var, Four_Zeros ) ) == 0xF; -} - -FORCEINLINE fltx4 SqrtEstSIMD( const fltx4 & a ) // sqrt(a), more or less -{ - return _mm_sqrt_ps( a ); -} - -FORCEINLINE fltx4 SqrtSIMD( const fltx4 & a ) // sqrt(a) -{ - return _mm_sqrt_ps( a ); -} - -FORCEINLINE fltx4 ReciprocalSqrtEstSIMD( const fltx4 & a ) // 1/sqrt(a), more or less -{ - return _mm_rsqrt_ps( a ); -} - -FORCEINLINE fltx4 ReciprocalSqrtEstSaturateSIMD( const fltx4 & a ) -{ - fltx4 zero_mask = CmpEqSIMD( a, Four_Zeros ); - fltx4 ret = OrSIMD( a, AndSIMD( Four_Epsilons, zero_mask ) ); - ret = ReciprocalSqrtEstSIMD( ret ); - return ret; -} - -/// uses newton iteration for higher precision results than ReciprocalSqrtEstSIMD -FORCEINLINE fltx4 ReciprocalSqrtSIMD( const fltx4 & a ) // 1/sqrt(a) -{ - fltx4 guess = ReciprocalSqrtEstSIMD( a ); - // newton iteration for 1/sqrt(a) : y(n+1) = 1/2 (y(n)*(3-a*y(n)^2)); - guess = MulSIMD( guess, SubSIMD( Four_Threes, MulSIMD( a, MulSIMD( guess, guess )))); - guess = MulSIMD( Four_PointFives, guess); - return guess; -} - -FORCEINLINE fltx4 ReciprocalEstSIMD( const fltx4 & a ) // 1/a, more or less -{ - return _mm_rcp_ps( a ); -} - -/// 1/x for all 4 values, more or less -/// 1/0 will result in a big but NOT infinite result -FORCEINLINE fltx4 ReciprocalEstSaturateSIMD( const fltx4 & a ) -{ - fltx4 zero_mask = CmpEqSIMD( a, Four_Zeros ); - fltx4 ret = OrSIMD( a, AndSIMD( Four_Epsilons, zero_mask ) ); - ret = ReciprocalEstSIMD( ret ); - return ret; -} - -/// 1/x for all 4 values. uses reciprocal approximation instruction plus newton iteration. -/// No error checking! -FORCEINLINE fltx4 ReciprocalSIMD( const fltx4 & a ) // 1/a -{ - fltx4 ret = ReciprocalEstSIMD( a ); - // newton iteration is: Y(n+1) = 2*Y(n)-a*Y(n)^2 - ret = SubSIMD( AddSIMD( ret, ret ), MulSIMD( a, MulSIMD( ret, ret ) ) ); - return ret; -} - -/// 1/x for all 4 values. -/// 1/0 will result in a big but NOT infinite result -FORCEINLINE fltx4 ReciprocalSaturateSIMD( const fltx4 & a ) -{ - fltx4 zero_mask = CmpEqSIMD( a, Four_Zeros ); - fltx4 ret = OrSIMD( a, AndSIMD( Four_Epsilons, zero_mask ) ); - ret = ReciprocalSIMD( ret ); - return ret; -} - -// CHRISG: is it worth doing integer bitfiddling for this? -// 2^x for all values (the antilog) -FORCEINLINE fltx4 ExpSIMD( const fltx4 &toPower ) -{ - fltx4 retval; - SubFloat( retval, 0 ) = powf( 2, SubFloat(toPower, 0) ); - SubFloat( retval, 1 ) = powf( 2, SubFloat(toPower, 1) ); - SubFloat( retval, 2 ) = powf( 2, SubFloat(toPower, 2) ); - SubFloat( retval, 3 ) = powf( 2, SubFloat(toPower, 3) ); - - return retval; -} - -// Clamps the components of a vector to a specified minimum and maximum range. -FORCEINLINE fltx4 ClampVectorSIMD( FLTX4 in, FLTX4 min, FLTX4 max) -{ - return MaxSIMD( min, MinSIMD( max, in ) ); -} - -FORCEINLINE void TransposeSIMD( fltx4 & x, fltx4 & y, fltx4 & z, fltx4 & w) -{ - _MM_TRANSPOSE4_PS( x, y, z, w ); -} - -FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 &a ) -{ - // a is [x,y,z,G] (where G is garbage) - // rotate left by one - fltx4 compareOne = RotateLeft( a ); - // compareOne is [y,z,G,x] - fltx4 retval = MinSIMD( a, compareOne ); - // retVal is [min(x,y), ... ] - compareOne = RotateLeft2( a ); - // compareOne is [z, G, x, y] - retval = MinSIMD( retval, compareOne ); - // retVal = [ min(min(x,y),z)..] - // splat the x component out to the whole vector and return - return SplatXSIMD( retval ); - -} - -FORCEINLINE fltx4 FindHighestSIMD3( const fltx4 &a ) -{ - // a is [x,y,z,G] (where G is garbage) - // rotate left by one - fltx4 compareOne = RotateLeft( a ); - // compareOne is [y,z,G,x] - fltx4 retval = MaxSIMD( a, compareOne ); - // retVal is [max(x,y), ... ] - compareOne = RotateLeft2( a ); - // compareOne is [z, G, x, y] - retval = MaxSIMD( retval, compareOne ); - // retVal = [ max(max(x,y),z)..] - // splat the x component out to the whole vector and return - return SplatXSIMD( retval ); - -} - -// ------------------------------------ -// INTEGER SIMD OPERATIONS. -// ------------------------------------ - - -#if 0 /* pc does not have these ops */ -// splat all components of a vector to a signed immediate int number. -FORCEINLINE fltx4 IntSetImmediateSIMD(int to) -{ - //CHRISG: SSE2 has this, but not SSE1. What to do? - fltx4 retval; - SubInt( retval, 0 ) = to; - SubInt( retval, 1 ) = to; - SubInt( retval, 2 ) = to; - SubInt( retval, 3 ) = to; - return retval; -} -#endif - -// Load 4 aligned words into a SIMD register -FORCEINLINE i32x4 LoadAlignedIntSIMD( const void * RESTRICT pSIMD) -{ - return _mm_load_ps( reinterpret_cast(pSIMD) ); -} - -// Load 4 unaligned words into a SIMD register -FORCEINLINE i32x4 LoadUnalignedIntSIMD( const void * RESTRICT pSIMD) -{ - return _mm_loadu_ps( reinterpret_cast(pSIMD) ); -} - -// save into four words, 16-byte aligned -FORCEINLINE void StoreAlignedIntSIMD( int32 * RESTRICT pSIMD, const fltx4 & a ) -{ - _mm_store_ps( reinterpret_cast(pSIMD), a ); -} - -FORCEINLINE void StoreAlignedIntSIMD( intx4 &pSIMD, const fltx4 & a ) -{ - _mm_store_ps( reinterpret_cast(pSIMD.Base()), a ); -} - -FORCEINLINE void StoreUnalignedIntSIMD( int32 * RESTRICT pSIMD, const fltx4 & a ) -{ - _mm_storeu_ps( reinterpret_cast(pSIMD), a ); -} - - -// CHRISG: the conversion functions all seem to operate on m64's only... -// how do we make them work here? - -// Take a fltx4 containing fixed-point uints and -// return them as single precision floats. No -// fixed point conversion is done. -FORCEINLINE fltx4 UnsignedIntConvertToFltSIMD( const u32x4 &vSrcA ) -{ - fltx4 retval; - SubFloat( retval, 0 ) = ( (float) SubInt( retval, 0 ) ); - SubFloat( retval, 1 ) = ( (float) SubInt( retval, 1 ) ); - SubFloat( retval, 2 ) = ( (float) SubInt( retval, 2 ) ); - SubFloat( retval, 3 ) = ( (float) SubInt( retval, 3 ) ); - return retval; -} - - -// Take a fltx4 containing fixed-point sints and -// return them as single precision floats. No -// fixed point conversion is done. -FORCEINLINE fltx4 SignedIntConvertToFltSIMD( const i32x4 &vSrcA ) -{ - fltx4 retval; - SubFloat( retval, 0 ) = ( (float) (reinterpret_cast(&vSrcA)[0])); - SubFloat( retval, 1 ) = ( (float) (reinterpret_cast(&vSrcA)[1])); - SubFloat( retval, 2 ) = ( (float) (reinterpret_cast(&vSrcA)[2])); - SubFloat( retval, 3 ) = ( (float) (reinterpret_cast(&vSrcA)[3])); - return retval; -} - -/* - works on fltx4's as if they are four uints. - the first parameter contains the words to be shifted, - the second contains the amount to shift by AS INTS - - for i = 0 to 3 - shift = vSrcB_i*32:(i*32)+4 - vReturned_i*32:(i*32)+31 = vSrcA_i*32:(i*32)+31 << shift -*/ -FORCEINLINE i32x4 IntShiftLeftWordSIMD(const i32x4 &vSrcA, const i32x4 &vSrcB) -{ - i32x4 retval; - SubInt(retval, 0) = SubInt(vSrcA, 0) << SubInt(vSrcB, 0); - SubInt(retval, 1) = SubInt(vSrcA, 1) << SubInt(vSrcB, 1); - SubInt(retval, 2) = SubInt(vSrcA, 2) << SubInt(vSrcB, 2); - SubInt(retval, 3) = SubInt(vSrcA, 3) << SubInt(vSrcB, 3); - - - return retval; -} - - -// Fixed-point conversion and save as SIGNED INTS. -// pDest->x = Int (vSrc.x) -// note: some architectures have means of doing -// fixed point conversion when the fix depth is -// specified as an immediate.. but there is no way -// to guarantee an immediate as a parameter to function -// like this. -FORCEINLINE void ConvertStoreAsIntsSIMD(intx4 * RESTRICT pDest, const fltx4 &vSrc) -{ - __m64 bottom = _mm_cvttps_pi32( vSrc ); - __m64 top = _mm_cvttps_pi32( _mm_movehl_ps(vSrc,vSrc) ); - - *reinterpret_cast<__m64 *>(&(*pDest)[0]) = bottom; - *reinterpret_cast<__m64 *>(&(*pDest)[2]) = top; - - _mm_empty(); -} - - - -#endif - - - -/// class FourVectors stores 4 independent vectors for use in SIMD processing. These vectors are -/// stored in the format x x x x y y y y z z z z so that they can be efficiently SIMD-accelerated. -class ALIGN16 FourVectors -{ -public: - fltx4 x, y, z; - - FORCEINLINE void DuplicateVector(Vector const &v) //< set all 4 vectors to the same vector value - { - x=ReplicateX4(v.x); - y=ReplicateX4(v.y); - z=ReplicateX4(v.z); - } - - FORCEINLINE fltx4 const & operator[](int idx) const - { - return *((&x)+idx); - } - - FORCEINLINE fltx4 & operator[](int idx) - { - return *((&x)+idx); - } - - FORCEINLINE void operator+=(FourVectors const &b) //< add 4 vectors to another 4 vectors - { - x=AddSIMD(x,b.x); - y=AddSIMD(y,b.y); - z=AddSIMD(z,b.z); - } - - FORCEINLINE void operator-=(FourVectors const &b) //< subtract 4 vectors from another 4 - { - x=SubSIMD(x,b.x); - y=SubSIMD(y,b.y); - z=SubSIMD(z,b.z); - } - - FORCEINLINE void operator*=(FourVectors const &b) //< scale all four vectors per component scale - { - x=MulSIMD(x,b.x); - y=MulSIMD(y,b.y); - z=MulSIMD(z,b.z); - } - - FORCEINLINE void operator*=(const fltx4 & scale) //< scale - { - x=MulSIMD(x,scale); - y=MulSIMD(y,scale); - z=MulSIMD(z,scale); - } - - FORCEINLINE void operator*=(float scale) //< uniformly scale all 4 vectors - { - fltx4 scalepacked = ReplicateX4(scale); - *this *= scalepacked; - } - - FORCEINLINE fltx4 operator*(FourVectors const &b) const //< 4 dot products - { - fltx4 dot=MulSIMD(x,b.x); - dot=MaddSIMD(y,b.y,dot); - dot=MaddSIMD(z,b.z,dot); - return dot; - } - - FORCEINLINE fltx4 operator*(Vector const &b) const //< dot product all 4 vectors with 1 vector - { - fltx4 dot=MulSIMD(x,ReplicateX4(b.x)); - dot=MaddSIMD(y,ReplicateX4(b.y), dot); - dot=MaddSIMD(z,ReplicateX4(b.z), dot); - return dot; - } - - FORCEINLINE void VProduct(FourVectors const &b) //< component by component mul - { - x=MulSIMD(x,b.x); - y=MulSIMD(y,b.y); - z=MulSIMD(z,b.z); - } - FORCEINLINE void MakeReciprocal(void) //< (x,y,z)=(1/x,1/y,1/z) - { - x=ReciprocalSIMD(x); - y=ReciprocalSIMD(y); - z=ReciprocalSIMD(z); - } - - FORCEINLINE void MakeReciprocalSaturate(void) //< (x,y,z)=(1/x,1/y,1/z), 1/0=1.0e23 - { - x=ReciprocalSaturateSIMD(x); - y=ReciprocalSaturateSIMD(y); - z=ReciprocalSaturateSIMD(z); - } - - // Assume the given matrix is a rotation, and rotate these vectors by it. - // If you have a long list of FourVectors structures that you all want - // to rotate by the same matrix, use FourVectors::RotateManyBy() instead. - inline void RotateBy(const matrix3x4_t& matrix); - - /// You can use this to rotate a long array of FourVectors all by the same - /// matrix. The first parameter is the head of the array. The second is the - /// number of vectors to rotate. The third is the matrix. - static void RotateManyBy(FourVectors * RESTRICT pVectors, unsigned int numVectors, const matrix3x4_t& rotationMatrix ); - - /// Assume the vectors are points, and transform them in place by the matrix. - inline void TransformBy(const matrix3x4_t& matrix); - - /// You can use this to Transform a long array of FourVectors all by the same - /// matrix. The first parameter is the head of the array. The second is the - /// number of vectors to rotate. The third is the matrix. The fourth is the - /// output buffer, which must not overlap the pVectors buffer. This is not - /// an in-place transformation. - static void TransformManyBy(FourVectors * RESTRICT pVectors, unsigned int numVectors, const matrix3x4_t& rotationMatrix, FourVectors * RESTRICT pOut ); - - /// You can use this to Transform a long array of FourVectors all by the same - /// matrix. The first parameter is the head of the array. The second is the - /// number of vectors to rotate. The third is the matrix. The fourth is the - /// output buffer, which must not overlap the pVectors buffer. - /// This is an in-place transformation. - static void TransformManyBy(FourVectors * RESTRICT pVectors, unsigned int numVectors, const matrix3x4_t& rotationMatrix ); - - // X(),Y(),Z() - get at the desired component of the i'th (0..3) vector. - FORCEINLINE const float & X(int idx) const - { - // NOTE: if the output goes into a register, this causes a Load-Hit-Store stall (don't mix fpu/vpu math!) - return SubFloat( (fltx4 &)x, idx ); - } - - FORCEINLINE const float & Y(int idx) const - { - return SubFloat( (fltx4 &)y, idx ); - } - - FORCEINLINE const float & Z(int idx) const - { - return SubFloat( (fltx4 &)z, idx ); - } - - FORCEINLINE float & X(int idx) - { - return SubFloat( x, idx ); - } - - FORCEINLINE float & Y(int idx) - { - return SubFloat( y, idx ); - } - - FORCEINLINE float & Z(int idx) - { - return SubFloat( z, idx ); - } - - FORCEINLINE Vector Vec(int idx) const //< unpack one of the vectors - { - return Vector( X(idx), Y(idx), Z(idx) ); - } - - FourVectors(void) - { - } - - FourVectors( FourVectors const &src ) - { - x=src.x; - y=src.y; - z=src.z; - } - - FORCEINLINE void operator=( FourVectors const &src ) - { - x=src.x; - y=src.y; - z=src.z; - } - - /// LoadAndSwizzle - load 4 Vectors into a FourVectors, performing transpose op - FORCEINLINE void LoadAndSwizzle(Vector const &a, Vector const &b, Vector const &c, Vector const &d) - { - // TransposeSIMD has large sub-expressions that the compiler can't eliminate on x360 - // use an unfolded implementation here -#if _X360 - fltx4 tx = LoadUnalignedSIMD( &a.x ); - fltx4 ty = LoadUnalignedSIMD( &b.x ); - fltx4 tz = LoadUnalignedSIMD( &c.x ); - fltx4 tw = LoadUnalignedSIMD( &d.x ); - fltx4 r0 = __vmrghw(tx, tz); - fltx4 r1 = __vmrghw(ty, tw); - fltx4 r2 = __vmrglw(tx, tz); - fltx4 r3 = __vmrglw(ty, tw); - - x = __vmrghw(r0, r1); - y = __vmrglw(r0, r1); - z = __vmrghw(r2, r3); -#else - x = LoadUnalignedSIMD( &( a.x )); - y = LoadUnalignedSIMD( &( b.x )); - z = LoadUnalignedSIMD( &( c.x )); - fltx4 w = LoadUnalignedSIMD( &( d.x )); - // now, matrix is: - // x y z ? - // x y z ? - // x y z ? - // x y z ? - TransposeSIMD(x, y, z, w); -#endif - } - - /// LoadAndSwizzleAligned - load 4 Vectors into a FourVectors, performing transpose op. - /// all 4 vectors must be 128 bit boundary - FORCEINLINE void LoadAndSwizzleAligned(const float *RESTRICT a, const float *RESTRICT b, const float *RESTRICT c, const float *RESTRICT d) - { -#if _X360 - fltx4 tx = LoadAlignedSIMD(a); - fltx4 ty = LoadAlignedSIMD(b); - fltx4 tz = LoadAlignedSIMD(c); - fltx4 tw = LoadAlignedSIMD(d); - fltx4 r0 = __vmrghw(tx, tz); - fltx4 r1 = __vmrghw(ty, tw); - fltx4 r2 = __vmrglw(tx, tz); - fltx4 r3 = __vmrglw(ty, tw); - - x = __vmrghw(r0, r1); - y = __vmrglw(r0, r1); - z = __vmrghw(r2, r3); -#else - x = LoadAlignedSIMD( a ); - y = LoadAlignedSIMD( b ); - z = LoadAlignedSIMD( c ); - fltx4 w = LoadAlignedSIMD( d ); - // now, matrix is: - // x y z ? - // x y z ? - // x y z ? - // x y z ? - TransposeSIMD( x, y, z, w ); -#endif - } - - FORCEINLINE void LoadAndSwizzleAligned(Vector const &a, Vector const &b, Vector const &c, Vector const &d) - { - LoadAndSwizzleAligned( &a.x, &b.x, &c.x, &d.x ); - } - - /// return the squared length of all 4 vectors - FORCEINLINE fltx4 length2(void) const - { - return (*this)*(*this); - } - - /// return the approximate length of all 4 vectors. uses the sqrt approximation instruction - FORCEINLINE fltx4 length(void) const - { - return SqrtEstSIMD(length2()); - } - - /// normalize all 4 vectors in place. not mega-accurate (uses reciprocal approximation instruction) - FORCEINLINE void VectorNormalizeFast(void) - { - fltx4 mag_sq=(*this)*(*this); // length^2 - (*this) *= ReciprocalSqrtEstSIMD(mag_sq); // *(1.0/sqrt(length^2)) - } - - /// normalize all 4 vectors in place. - FORCEINLINE void VectorNormalize(void) - { - fltx4 mag_sq=(*this)*(*this); // length^2 - (*this) *= ReciprocalSqrtSIMD(mag_sq); // *(1.0/sqrt(length^2)) - } - - /// construct a FourVectors from 4 separate Vectors - FORCEINLINE FourVectors(Vector const &a, Vector const &b, Vector const &c, Vector const &d) - { - LoadAndSwizzle(a,b,c,d); - } - - /// construct a FourVectors from 4 separate Vectors - FORCEINLINE FourVectors(VectorAligned const &a, VectorAligned const &b, VectorAligned const &c, VectorAligned const &d) - { - LoadAndSwizzleAligned(a,b,c,d); - } - - FORCEINLINE fltx4 DistToSqr( FourVectors const &pnt ) - { - fltx4 fl4dX = SubSIMD( pnt.x, x ); - fltx4 fl4dY = SubSIMD( pnt.y, y ); - fltx4 fl4dZ = SubSIMD( pnt.z, z ); - return AddSIMD( MulSIMD( fl4dX, fl4dX), AddSIMD( MulSIMD( fl4dY, fl4dY ), MulSIMD( fl4dZ, fl4dZ ) ) ); - - } - - FORCEINLINE fltx4 TValueOfClosestPointOnLine( FourVectors const &p0, FourVectors const &p1 ) const - { - FourVectors lineDelta = p1; - lineDelta -= p0; - fltx4 OOlineDirDotlineDir = ReciprocalSIMD( p1 * p1 ); - FourVectors v4OurPnt = *this; - v4OurPnt -= p0; - return MulSIMD( OOlineDirDotlineDir, v4OurPnt * lineDelta ); - } - - FORCEINLINE fltx4 DistSqrToLineSegment( FourVectors const &p0, FourVectors const &p1 ) const - { - FourVectors lineDelta = p1; - FourVectors v4OurPnt = *this; - v4OurPnt -= p0; - lineDelta -= p0; - - fltx4 OOlineDirDotlineDir = ReciprocalSIMD( lineDelta * lineDelta ); - - fltx4 fl4T = MulSIMD( OOlineDirDotlineDir, v4OurPnt * lineDelta ); - - fl4T = MinSIMD( fl4T, Four_Ones ); - fl4T = MaxSIMD( fl4T, Four_Zeros ); - lineDelta *= fl4T; - return v4OurPnt.DistToSqr( lineDelta ); - } - -}; - -/// form 4 cross products -inline FourVectors operator ^(const FourVectors &a, const FourVectors &b) -{ - FourVectors ret; - ret.x=SubSIMD(MulSIMD(a.y,b.z),MulSIMD(a.z,b.y)); - ret.y=SubSIMD(MulSIMD(a.z,b.x),MulSIMD(a.x,b.z)); - ret.z=SubSIMD(MulSIMD(a.x,b.y),MulSIMD(a.y,b.x)); - return ret; -} - -/// component-by-componentwise MAX operator -inline FourVectors maximum(const FourVectors &a, const FourVectors &b) -{ - FourVectors ret; - ret.x=MaxSIMD(a.x,b.x); - ret.y=MaxSIMD(a.y,b.y); - ret.z=MaxSIMD(a.z,b.z); - return ret; -} - -/// component-by-componentwise MIN operator -inline FourVectors minimum(const FourVectors &a, const FourVectors &b) -{ - FourVectors ret; - ret.x=MinSIMD(a.x,b.x); - ret.y=MinSIMD(a.y,b.y); - ret.z=MinSIMD(a.z,b.z); - return ret; -} - -/// calculate reflection vector. incident and normal dir assumed normalized -FORCEINLINE FourVectors VectorReflect( const FourVectors &incident, const FourVectors &normal ) -{ - FourVectors ret = incident; - fltx4 iDotNx2 = incident * normal; - iDotNx2 = AddSIMD( iDotNx2, iDotNx2 ); - FourVectors nPart = normal; - nPart *= iDotNx2; - ret -= nPart; // i-2(n*i)n - return ret; -} - -/// calculate slide vector. removes all components of a vector which are perpendicular to a normal vector. -FORCEINLINE FourVectors VectorSlide( const FourVectors &incident, const FourVectors &normal ) -{ - FourVectors ret = incident; - fltx4 iDotN = incident * normal; - FourVectors nPart = normal; - nPart *= iDotN; - ret -= nPart; // i-(n*i)n - return ret; -} - - -// Assume the given matrix is a rotation, and rotate these vectors by it. -// If you have a long list of FourVectors structures that you all want -// to rotate by the same matrix, use FourVectors::RotateManyBy() instead. -void FourVectors::RotateBy(const matrix3x4_t& matrix) -{ - // Splat out each of the entries in the matrix to a fltx4. Do this - // in the order that we will need them, to hide latency. I'm - // avoiding making an array of them, so that they'll remain in - // registers. - fltx4 matSplat00, matSplat01, matSplat02, - matSplat10, matSplat11, matSplat12, - matSplat20, matSplat21, matSplat22; - - { - // Load the matrix into local vectors. Sadly, matrix3x4_ts are - // often unaligned. The w components will be the tranpose row of - // the matrix, but we don't really care about that. - fltx4 matCol0 = LoadUnalignedSIMD( matrix[0] ); - fltx4 matCol1 = LoadUnalignedSIMD( matrix[1] ); - fltx4 matCol2 = LoadUnalignedSIMD( matrix[2] ); - - matSplat00 = SplatXSIMD( matCol0 ); - matSplat01 = SplatYSIMD( matCol0 ); - matSplat02 = SplatZSIMD( matCol0 ); - - matSplat10 = SplatXSIMD( matCol1 ); - matSplat11 = SplatYSIMD( matCol1 ); - matSplat12 = SplatZSIMD( matCol1 ); - - matSplat20 = SplatXSIMD( matCol2 ); - matSplat21 = SplatYSIMD( matCol2 ); - matSplat22 = SplatZSIMD( matCol2 ); - } - - // Trust in the compiler to schedule these operations correctly: - fltx4 outX, outY, outZ; - outX = AddSIMD( AddSIMD( MulSIMD( x, matSplat00 ), MulSIMD( y, matSplat01 ) ), MulSIMD( z, matSplat02 ) ); - outY = AddSIMD( AddSIMD( MulSIMD( x, matSplat10 ), MulSIMD( y, matSplat11 ) ), MulSIMD( z, matSplat12 ) ); - outZ = AddSIMD( AddSIMD( MulSIMD( x, matSplat20 ), MulSIMD( y, matSplat21 ) ), MulSIMD( z, matSplat22 ) ); - - x = outX; - y = outY; - z = outZ; -} - -// Assume the given matrix is a rotation, and rotate these vectors by it. -// If you have a long list of FourVectors structures that you all want -// to rotate by the same matrix, use FourVectors::RotateManyBy() instead. -void FourVectors::TransformBy(const matrix3x4_t& matrix) -{ - // Splat out each of the entries in the matrix to a fltx4. Do this - // in the order that we will need them, to hide latency. I'm - // avoiding making an array of them, so that they'll remain in - // registers. - fltx4 matSplat00, matSplat01, matSplat02, - matSplat10, matSplat11, matSplat12, - matSplat20, matSplat21, matSplat22; - - { - // Load the matrix into local vectors. Sadly, matrix3x4_ts are - // often unaligned. The w components will be the tranpose row of - // the matrix, but we don't really care about that. - fltx4 matCol0 = LoadUnalignedSIMD( matrix[0] ); - fltx4 matCol1 = LoadUnalignedSIMD( matrix[1] ); - fltx4 matCol2 = LoadUnalignedSIMD( matrix[2] ); - - matSplat00 = SplatXSIMD( matCol0 ); - matSplat01 = SplatYSIMD( matCol0 ); - matSplat02 = SplatZSIMD( matCol0 ); - - matSplat10 = SplatXSIMD( matCol1 ); - matSplat11 = SplatYSIMD( matCol1 ); - matSplat12 = SplatZSIMD( matCol1 ); - - matSplat20 = SplatXSIMD( matCol2 ); - matSplat21 = SplatYSIMD( matCol2 ); - matSplat22 = SplatZSIMD( matCol2 ); - } - - // Trust in the compiler to schedule these operations correctly: - fltx4 outX, outY, outZ; - - outX = MaddSIMD( z, matSplat02, AddSIMD( MulSIMD( x, matSplat00 ), MulSIMD( y, matSplat01 ) ) ); - outY = MaddSIMD( z, matSplat12, AddSIMD( MulSIMD( x, matSplat10 ), MulSIMD( y, matSplat11 ) ) ); - outZ = MaddSIMD( z, matSplat22, AddSIMD( MulSIMD( x, matSplat20 ), MulSIMD( y, matSplat21 ) ) ); - - x = AddSIMD( outX, ReplicateX4( matrix[0][3] )); - y = AddSIMD( outY, ReplicateX4( matrix[1][3] )); - z = AddSIMD( outZ, ReplicateX4( matrix[2][3] )); -} - - - -/// quick, low quality perlin-style noise() function suitable for real time use. -/// return value is -1..1. Only reliable around +/- 1 million or so. -fltx4 NoiseSIMD( const fltx4 & x, const fltx4 & y, const fltx4 & z ); -fltx4 NoiseSIMD( FourVectors const &v ); - -// vector valued noise direction -FourVectors DNoiseSIMD( FourVectors const &v ); - -// vector value "curl" noise function. see http://hyperphysics.phy-astr.gsu.edu/hbase/curl.html -FourVectors CurlNoiseSIMD( FourVectors const &v ); - - -/// calculate the absolute value of a packed single -inline fltx4 fabs( const fltx4 & x ) -{ - return AndSIMD( x, LoadAlignedSIMD( g_SIMD_clear_signmask ) ); -} - -/// negate all four components of a SIMD packed single -inline fltx4 fnegate( const fltx4 & x ) -{ - return XorSIMD( x, LoadAlignedSIMD( g_SIMD_signmask ) ); -} - - -fltx4 Pow_FixedPoint_Exponent_SIMD( const fltx4 & x, int exponent); - -// PowSIMD - raise a SIMD register to a power. This is analogous to the C pow() function, with some -// restictions: fractional exponents are only handled with 2 bits of precision. Basically, -// fractions of 0,.25,.5, and .75 are handled. PowSIMD(x,.30) will be the same as PowSIMD(x,.25). -// negative and fractional powers are handled by the SIMD reciprocal and square root approximation -// instructions and so are not especially accurate ----Note that this routine does not raise -// numeric exceptions because it uses SIMD--- This routine is O(log2(exponent)). -inline fltx4 PowSIMD( const fltx4 & x, float exponent ) -{ - return Pow_FixedPoint_Exponent_SIMD(x,(int) (4.0*exponent)); -} - - - -// random number generation - generate 4 random numbers quickly. - -void SeedRandSIMD(uint32 seed); // seed the random # generator -fltx4 RandSIMD( int nContext = 0 ); // return 4 numbers in the 0..1 range - -// for multithreaded, you need to use these and use the argument form of RandSIMD: -int GetSIMDRandContext( void ); -void ReleaseSIMDRandContext( int nContext ); - -FORCEINLINE fltx4 RandSignedSIMD( void ) // -1..1 -{ - return SubSIMD( MulSIMD( Four_Twos, RandSIMD() ), Four_Ones ); -} - - -// SIMD versions of mathlib simplespline functions -// hermite basis function for smooth interpolation -// Similar to Gain() above, but very cheap to call -// value should be between 0 & 1 inclusive -inline fltx4 SimpleSpline( const fltx4 & value ) -{ - // Arranged to avoid a data dependency between these two MULs: - fltx4 valueDoubled = MulSIMD( value, Four_Twos ); - fltx4 valueSquared = MulSIMD( value, value ); - - // Nice little ease-in, ease-out spline-like curve - return SubSIMD( - MulSIMD( Four_Threes, valueSquared ), - MulSIMD( valueDoubled, valueSquared ) ); -} - -// remaps a value in [startInterval, startInterval+rangeInterval] from linear to -// spline using SimpleSpline -inline fltx4 SimpleSplineRemapValWithDeltas( const fltx4 & val, - const fltx4 & A, const fltx4 & BMinusA, - const fltx4 & OneOverBMinusA, const fltx4 & C, - const fltx4 & DMinusC ) -{ -// if ( A == B ) -// return val >= B ? D : C; - fltx4 cVal = MulSIMD( SubSIMD( val, A), OneOverBMinusA ); - return AddSIMD( C, MulSIMD( DMinusC, SimpleSpline( cVal ) ) ); -} - -inline fltx4 SimpleSplineRemapValWithDeltasClamped( const fltx4 & val, - const fltx4 & A, const fltx4 & BMinusA, - const fltx4 & OneOverBMinusA, const fltx4 & C, - const fltx4 & DMinusC ) -{ -// if ( A == B ) -// return val >= B ? D : C; - fltx4 cVal = MulSIMD( SubSIMD( val, A), OneOverBMinusA ); - cVal = MinSIMD( Four_Ones, MaxSIMD( Four_Zeros, cVal ) ); - return AddSIMD( C, MulSIMD( DMinusC, SimpleSpline( cVal ) ) ); -} - -FORCEINLINE fltx4 FracSIMD( const fltx4 &val ) -{ - fltx4 fl4Abs = fabs( val ); - fltx4 ival = SubSIMD( AddSIMD( fl4Abs, Four_2ToThe23s ), Four_2ToThe23s ); - ival = MaskedAssign( CmpGtSIMD( ival, fl4Abs ), SubSIMD( ival, Four_Ones ), ival ); - return XorSIMD( SubSIMD( fl4Abs, ival ), XorSIMD( val, fl4Abs ) ); // restore sign bits -} - -FORCEINLINE fltx4 Mod2SIMD( const fltx4 &val ) -{ - fltx4 fl4Abs = fabs( val ); - fltx4 ival = SubSIMD( AndSIMD( LoadAlignedSIMD( (float *) g_SIMD_lsbmask ), AddSIMD( fl4Abs, Four_2ToThe23s ) ), Four_2ToThe23s ); - ival = MaskedAssign( CmpGtSIMD( ival, fl4Abs ), SubSIMD( ival, Four_Twos ), ival ); - return XorSIMD( SubSIMD( fl4Abs, ival ), XorSIMD( val, fl4Abs ) ); // restore sign bits -} - -FORCEINLINE fltx4 Mod2SIMDPositiveInput( const fltx4 &val ) -{ - fltx4 ival = SubSIMD( AndSIMD( LoadAlignedSIMD( g_SIMD_lsbmask ), AddSIMD( val, Four_2ToThe23s ) ), Four_2ToThe23s ); - ival = MaskedAssign( CmpGtSIMD( ival, val ), SubSIMD( ival, Four_Twos ), ival ); - return SubSIMD( val, ival ); -} - - -// approximate sin of an angle, with -1..1 representing the whole sin wave period instead of -pi..pi. -// no range reduction is done - for values outside of 0..1 you won't like the results -FORCEINLINE fltx4 _SinEst01SIMD( const fltx4 &val ) -{ - // really rough approximation - x*(4-x*4) - a parabola. s(0) = 0, s(.5) = 1, s(1)=0, smooth in-between. - // sufficient for simple oscillation. - return MulSIMD( val, SubSIMD( Four_Fours, MulSIMD( val, Four_Fours ) ) ); -} - -FORCEINLINE fltx4 _Sin01SIMD( const fltx4 &val ) -{ - // not a bad approximation : parabola always over-estimates. Squared parabola always - // underestimates. So lets blend between them: goodsin = badsin + .225*( badsin^2-badsin) - fltx4 fl4BadEst = MulSIMD( val, SubSIMD( Four_Fours, MulSIMD( val, Four_Fours ) ) ); - return AddSIMD( MulSIMD( Four_Point225s, SubSIMD( MulSIMD( fl4BadEst, fl4BadEst ), fl4BadEst ) ), fl4BadEst ); -} - -// full range useable implementations -FORCEINLINE fltx4 SinEst01SIMD( const fltx4 &val ) -{ - fltx4 fl4Abs = fabs( val ); - fltx4 fl4Reduced2 = Mod2SIMDPositiveInput( fl4Abs ); - fltx4 fl4OddMask = CmpGeSIMD( fl4Reduced2, Four_Ones ); - fltx4 fl4val = SubSIMD( fl4Reduced2, AndSIMD( Four_Ones, fl4OddMask ) ); - fltx4 fl4Sin = _SinEst01SIMD( fl4val ); - fl4Sin = XorSIMD( fl4Sin, AndSIMD( LoadAlignedSIMD( g_SIMD_signmask ), XorSIMD( val, fl4OddMask ) ) ); - return fl4Sin; - -} - -FORCEINLINE fltx4 Sin01SIMD( const fltx4 &val ) -{ - fltx4 fl4Abs = fabs( val ); - fltx4 fl4Reduced2 = Mod2SIMDPositiveInput( fl4Abs ); - fltx4 fl4OddMask = CmpGeSIMD( fl4Reduced2, Four_Ones ); - fltx4 fl4val = SubSIMD( fl4Reduced2, AndSIMD( Four_Ones, fl4OddMask ) ); - fltx4 fl4Sin = _Sin01SIMD( fl4val ); - fl4Sin = XorSIMD( fl4Sin, AndSIMD( LoadAlignedSIMD( g_SIMD_signmask ), XorSIMD( val, fl4OddMask ) ) ); - return fl4Sin; - -} - -// Schlick style Bias approximation see graphics gems 4 : bias(t,a)= t/( (1/a-2)*(1-t)+1) - -FORCEINLINE fltx4 PreCalcBiasParameter( const fltx4 &bias_parameter ) -{ - // convert perlin-style-bias parameter to the value right for the approximation - return SubSIMD( ReciprocalSIMD( bias_parameter ), Four_Twos ); -} - -FORCEINLINE fltx4 BiasSIMD( const fltx4 &val, const fltx4 &precalc_param ) -{ - // similar to bias function except pass precalced bias value from calling PreCalcBiasParameter. - - //!!speed!! use reciprocal est? - //!!speed!! could save one op by precalcing _2_ values - return DivSIMD( val, AddSIMD( MulSIMD( precalc_param, SubSIMD( Four_Ones, val ) ), Four_Ones ) ); -} - -//----------------------------------------------------------------------------- -// Box/plane test -// NOTE: The w component of emins + emaxs must be 1 for this to work -//----------------------------------------------------------------------------- -FORCEINLINE int BoxOnPlaneSideSIMD( const fltx4& emins, const fltx4& emaxs, const cplane_t *p, float tolerance = 0.f ) -{ - fltx4 corners[2]; - fltx4 normal = LoadUnalignedSIMD( p->normal.Base() ); - fltx4 dist = ReplicateX4( -p->dist ); - normal = SetWSIMD( normal, dist ); - fltx4 t4 = ReplicateX4( tolerance ); - fltx4 negt4 = ReplicateX4( -tolerance ); - fltx4 cmp = CmpGeSIMD( normal, Four_Zeros ); - corners[0] = MaskedAssign( cmp, emaxs, emins ); - corners[1] = MaskedAssign( cmp, emins, emaxs ); - fltx4 dot1 = Dot4SIMD( normal, corners[0] ); - fltx4 dot2 = Dot4SIMD( normal, corners[1] ); - cmp = CmpGeSIMD( dot1, t4 ); - fltx4 cmp2 = CmpGtSIMD( negt4, dot2 ); - fltx4 result = MaskedAssign( cmp, Four_Ones, Four_Zeros ); - fltx4 result2 = MaskedAssign( cmp2, Four_Twos, Four_Zeros ); - result = AddSIMD( result, result2 ); - intx4 sides; - ConvertStoreAsIntsSIMD( &sides, result ); - return sides[0]; -} - -#endif // _ssemath_h diff --git a/Resources/NetHook/mathlib/ssequaternion.h b/Resources/NetHook/mathlib/ssequaternion.h deleted file mode 100644 index d38c3c09..00000000 --- a/Resources/NetHook/mathlib/ssequaternion.h +++ /dev/null @@ -1,367 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: - defines SIMD "structure of arrays" classes and functions. -// -//===========================================================================// -#ifndef SSEQUATMATH_H -#define SSEQUATMATH_H - -#ifdef _WIN32 -#pragma once -#endif - - -#include "mathlib/ssemath.h" - -// Use this #define to allow SSE versions of Quaternion math -// to exist on PC. -// On PC, certain horizontal vector operations are not supported. -// This causes the SSE implementation of quaternion math to mix the -// vector and scalar floating point units, which is extremely -// performance negative if you don't compile to native SSE2 (which -// we don't as of Sept 1, 2007). So, it's best not to allow these -// functions to exist at all. It's not good enough to simply replace -// the contents of the functions with scalar math, because each call -// to LoadAligned and StoreAligned will result in an unnecssary copy -// of the quaternion, and several moves to and from the XMM registers. -// -// Basically, the problem you run into is that for efficient SIMD code, -// you need to load the quaternions and vectors into SIMD registers and -// keep them there as long as possible while doing only SIMD math, -// whereas for efficient scalar code, each time you copy onto or ever -// use a fltx4, it hoses your pipeline. So the difference has to be -// in the management of temporary variables in the calling function, -// not inside the math functions. -// -// If you compile assuming the presence of SSE2, the MSVC will abandon -// the traditional x87 FPU operations altogether and make everything use -// the SSE2 registers, which lessens this problem a little. - -// permitted only on 360, as we've done careful tuning on its Altivec math: -#ifdef _X360 -#define ALLOW_SIMD_QUATERNION_MATH 1 // not on PC! -#endif - - - -//--------------------------------------------------------------------- -// Load/store quaternions -//--------------------------------------------------------------------- -#ifndef _X360 -#if ALLOW_SIMD_QUATERNION_MATH -// Using STDC or SSE -FORCEINLINE fltx4 LoadAlignedSIMD( const QuaternionAligned & pSIMD ) -{ - fltx4 retval = LoadAlignedSIMD( pSIMD.Base() ); - return retval; -} - -FORCEINLINE fltx4 LoadAlignedSIMD( const QuaternionAligned * RESTRICT pSIMD ) -{ - fltx4 retval = LoadAlignedSIMD( pSIMD ); - return retval; -} - -FORCEINLINE void StoreAlignedSIMD( QuaternionAligned * RESTRICT pSIMD, const fltx4 & a ) -{ - StoreAlignedSIMD( pSIMD->Base(), a ); -} -#endif -#else - -// for the transitional class -- load a QuaternionAligned -FORCEINLINE fltx4 LoadAlignedSIMD( const QuaternionAligned & pSIMD ) -{ - fltx4 retval = XMLoadVector4A( pSIMD.Base() ); - return retval; -} - -FORCEINLINE fltx4 LoadAlignedSIMD( const QuaternionAligned * RESTRICT pSIMD ) -{ - fltx4 retval = XMLoadVector4A( pSIMD ); - return retval; -} - -FORCEINLINE void StoreAlignedSIMD( QuaternionAligned * RESTRICT pSIMD, const fltx4 & a ) -{ - XMStoreVector4A( pSIMD->Base(), a ); -} - -#endif - - -#if ALLOW_SIMD_QUATERNION_MATH -//--------------------------------------------------------------------- -// Make sure quaternions are within 180 degrees of one another, if not, reverse q -//--------------------------------------------------------------------- -FORCEINLINE fltx4 QuaternionAlignSIMD( const fltx4 &p, const fltx4 &q ) -{ - // decide if one of the quaternions is backwards - fltx4 a = SubSIMD( p, q ); - fltx4 b = AddSIMD( p, q ); - a = Dot4SIMD( a, a ); - b = Dot4SIMD( b, b ); - fltx4 cmp = CmpGtSIMD( a, b ); - fltx4 result = MaskedAssign( cmp, NegSIMD(q), q ); - return result; -} - -//--------------------------------------------------------------------- -// Normalize Quaternion -//--------------------------------------------------------------------- -#if USE_STDC_FOR_SIMD - -FORCEINLINE fltx4 QuaternionNormalizeSIMD( const fltx4 &q ) -{ - fltx4 radius, result; - radius = Dot4SIMD( q, q ); - - if ( SubFloat( radius, 0 ) ) // > FLT_EPSILON && ((radius < 1.0f - 4*FLT_EPSILON) || (radius > 1.0f + 4*FLT_EPSILON)) - { - float iradius = 1.0f / sqrt( SubFloat( radius, 0 ) ); - result = ReplicateX4( iradius ); - result = MulSIMD( result, q ); - return result; - } - return q; -} - -#else - -// SSE + X360 implementation -FORCEINLINE fltx4 QuaternionNormalizeSIMD( const fltx4 &q ) -{ - fltx4 radius, result, mask; - radius = Dot4SIMD( q, q ); - mask = CmpEqSIMD( radius, Four_Zeros ); // all ones iff radius = 0 - result = ReciprocalSqrtSIMD( radius ); - result = MulSIMD( result, q ); - return MaskedAssign( mask, q, result ); // if radius was 0, just return q -} - -#endif - - -//--------------------------------------------------------------------- -// 0.0 returns p, 1.0 return q. -//--------------------------------------------------------------------- -FORCEINLINE fltx4 QuaternionBlendNoAlignSIMD( const fltx4 &p, const fltx4 &q, float t ) -{ - fltx4 sclp, sclq, result; - sclq = ReplicateX4( t ); - sclp = SubSIMD( Four_Ones, sclq ); - result = MulSIMD( sclp, p ); - result = MaddSIMD( sclq, q, result ); - return QuaternionNormalizeSIMD( result ); -} - - -//--------------------------------------------------------------------- -// Blend Quaternions -//--------------------------------------------------------------------- -FORCEINLINE fltx4 QuaternionBlendSIMD( const fltx4 &p, const fltx4 &q, float t ) -{ - // decide if one of the quaternions is backwards - fltx4 q2, result; - q2 = QuaternionAlignSIMD( p, q ); - result = QuaternionBlendNoAlignSIMD( p, q2, t ); - return result; -} - - -//--------------------------------------------------------------------- -// Multiply Quaternions -//--------------------------------------------------------------------- -#ifndef _X360 - -// SSE and STDC -FORCEINLINE fltx4 QuaternionMultSIMD( const fltx4 &p, const fltx4 &q ) -{ - // decide if one of the quaternions is backwards - fltx4 q2, result; - q2 = QuaternionAlignSIMD( p, q ); - SubFloat( result, 0 ) = SubFloat( p, 0 ) * SubFloat( q2, 3 ) + SubFloat( p, 1 ) * SubFloat( q2, 2 ) - SubFloat( p, 2 ) * SubFloat( q2, 1 ) + SubFloat( p, 3 ) * SubFloat( q2, 0 ); - SubFloat( result, 1 ) = -SubFloat( p, 0 ) * SubFloat( q2, 2 ) + SubFloat( p, 1 ) * SubFloat( q2, 3 ) + SubFloat( p, 2 ) * SubFloat( q2, 0 ) + SubFloat( p, 3 ) * SubFloat( q2, 1 ); - SubFloat( result, 2 ) = SubFloat( p, 0 ) * SubFloat( q2, 1 ) - SubFloat( p, 1 ) * SubFloat( q2, 0 ) + SubFloat( p, 2 ) * SubFloat( q2, 3 ) + SubFloat( p, 3 ) * SubFloat( q2, 2 ); - SubFloat( result, 3 ) = -SubFloat( p, 0 ) * SubFloat( q2, 0 ) - SubFloat( p, 1 ) * SubFloat( q2, 1 ) - SubFloat( p, 2 ) * SubFloat( q2, 2 ) + SubFloat( p, 3 ) * SubFloat( q2, 3 ); - return result; -} - -#else - -// X360 -extern const fltx4 g_QuatMultRowSign[4]; -FORCEINLINE fltx4 QuaternionMultSIMD( const fltx4 &p, const fltx4 &q ) -{ - fltx4 q2, row, result; - q2 = QuaternionAlignSIMD( p, q ); - - row = XMVectorSwizzle( q2, 3, 2, 1, 0 ); - row = MulSIMD( row, g_QuatMultRowSign[0] ); - result = Dot4SIMD( row, p ); - - row = XMVectorSwizzle( q2, 2, 3, 0, 1 ); - row = MulSIMD( row, g_QuatMultRowSign[1] ); - row = Dot4SIMD( row, p ); - result = __vrlimi( result, row, 4, 0 ); - - row = XMVectorSwizzle( q2, 1, 0, 3, 2 ); - row = MulSIMD( row, g_QuatMultRowSign[2] ); - row = Dot4SIMD( row, p ); - result = __vrlimi( result, row, 2, 0 ); - - row = MulSIMD( q2, g_QuatMultRowSign[3] ); - row = Dot4SIMD( row, p ); - result = __vrlimi( result, row, 1, 0 ); - return result; -} - -#endif - - -//--------------------------------------------------------------------- -// Quaternion scale -//--------------------------------------------------------------------- -#ifndef _X360 - -// SSE and STDC -FORCEINLINE fltx4 QuaternionScaleSIMD( const fltx4 &p, float t ) -{ - float r; - fltx4 q; - - // FIXME: nick, this isn't overly sensitive to accuracy, and it may be faster to - // use the cos part (w) of the quaternion (sin(omega)*N,cos(omega)) to figure the new scale. - float sinom = sqrt( SubFloat( p, 0 ) * SubFloat( p, 0 ) + SubFloat( p, 1 ) * SubFloat( p, 1 ) + SubFloat( p, 2 ) * SubFloat( p, 2 ) ); - sinom = min( sinom, 1.f ); - - float sinsom = sin( asin( sinom ) * t ); - - t = sinsom / (sinom + FLT_EPSILON); - SubFloat( q, 0 ) = t * SubFloat( p, 0 ); - SubFloat( q, 1 ) = t * SubFloat( p, 1 ); - SubFloat( q, 2 ) = t * SubFloat( p, 2 ); - - // rescale rotation - r = 1.0f - sinsom * sinsom; - - // Assert( r >= 0 ); - if (r < 0.0f) - r = 0.0f; - r = sqrt( r ); - - // keep sign of rotation - SubFloat( q, 3 ) = fsel( SubFloat( p, 3 ), r, -r ); - return q; -} - -#else - -// X360 -FORCEINLINE fltx4 QuaternionScaleSIMD( const fltx4 &p, float t ) -{ - fltx4 sinom = Dot3SIMD( p, p ); - sinom = SqrtSIMD( sinom ); - sinom = MinSIMD( sinom, Four_Ones ); - fltx4 sinsom = ArcSinSIMD( sinom ); - fltx4 t4 = ReplicateX4( t ); - sinsom = MulSIMD( sinsom, t4 ); - sinsom = SinSIMD( sinsom ); - sinom = AddSIMD( sinom, Four_Epsilons ); - sinom = ReciprocalSIMD( sinom ); - t4 = MulSIMD( sinsom, sinom ); - fltx4 result = MulSIMD( p, t4 ); - - // rescale rotation - sinsom = MulSIMD( sinsom, sinsom ); - fltx4 r = SubSIMD( Four_Ones, sinsom ); - r = MaxSIMD( r, Four_Zeros ); - r = SqrtSIMD( r ); - - // keep sign of rotation - fltx4 cmp = CmpGeSIMD( p, Four_Zeros ); - r = MaskedAssign( cmp, r, NegSIMD( r ) ); - - result = __vrlimi(result, r, 1, 0); - return result; -} - -#endif - - -//----------------------------------------------------------------------------- -// Quaternion sphereical linear interpolation -//----------------------------------------------------------------------------- -#ifndef _X360 - -// SSE and STDC -FORCEINLINE fltx4 QuaternionSlerpNoAlignSIMD( const fltx4 &p, const fltx4 &q, float t ) -{ - float omega, cosom, sinom, sclp, sclq; - - fltx4 result; - - // 0.0 returns p, 1.0 return q. - cosom = SubFloat( p, 0 ) * SubFloat( q, 0 ) + SubFloat( p, 1 ) * SubFloat( q, 1 ) + - SubFloat( p, 2 ) * SubFloat( q, 2 ) + SubFloat( p, 3 ) * SubFloat( q, 3 ); - - if ( (1.0f + cosom ) > 0.000001f ) - { - if ( (1.0f - cosom ) > 0.000001f ) - { - omega = acos( cosom ); - sinom = sin( omega ); - sclp = sin( (1.0f - t)*omega) / sinom; - sclq = sin( t*omega ) / sinom; - } - else - { - // TODO: add short circuit for cosom == 1.0f? - sclp = 1.0f - t; - sclq = t; - } - SubFloat( result, 0 ) = sclp * SubFloat( p, 0 ) + sclq * SubFloat( q, 0 ); - SubFloat( result, 1 ) = sclp * SubFloat( p, 1 ) + sclq * SubFloat( q, 1 ); - SubFloat( result, 2 ) = sclp * SubFloat( p, 2 ) + sclq * SubFloat( q, 2 ); - SubFloat( result, 3 ) = sclp * SubFloat( p, 3 ) + sclq * SubFloat( q, 3 ); - } - else - { - SubFloat( result, 0 ) = -SubFloat( q, 1 ); - SubFloat( result, 1 ) = SubFloat( q, 0 ); - SubFloat( result, 2 ) = -SubFloat( q, 3 ); - SubFloat( result, 3 ) = SubFloat( q, 2 ); - sclp = sin( (1.0f - t) * (0.5f * M_PI)); - sclq = sin( t * (0.5f * M_PI)); - SubFloat( result, 0 ) = sclp * SubFloat( p, 0 ) + sclq * SubFloat( result, 0 ); - SubFloat( result, 1 ) = sclp * SubFloat( p, 1 ) + sclq * SubFloat( result, 1 ); - SubFloat( result, 2 ) = sclp * SubFloat( p, 2 ) + sclq * SubFloat( result, 2 ); - } - - return result; -} - -#else - -// X360 -FORCEINLINE fltx4 QuaternionSlerpNoAlignSIMD( const fltx4 &p, const fltx4 &q, float t ) -{ - return XMQuaternionSlerp( p, q, t ); -} - -#endif - - -FORCEINLINE fltx4 QuaternionSlerpSIMD( const fltx4 &p, const fltx4 &q, float t ) -{ - fltx4 q2, result; - q2 = QuaternionAlignSIMD( p, q ); - result = QuaternionSlerpNoAlignSIMD( p, q2, t ); - return result; -} - - -#endif // ALLOW_SIMD_QUATERNION_MATH - -#endif // SSEQUATMATH_H - diff --git a/Resources/NetHook/mathlib/vector.h b/Resources/NetHook/mathlib/vector.h deleted file mode 100644 index 01d079e6..00000000 --- a/Resources/NetHook/mathlib/vector.h +++ /dev/null @@ -1,2226 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef VECTOR_H -#define VECTOR_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include - -// For vec_t, put this somewhere else? -#include "tier0/basetypes.h" - -// For rand(). We really need a library! -#include - -#ifndef _X360 -// For MMX intrinsics -#include -#endif - -#include "tier0/dbg.h" -#include "tier0/threadtools.h" -#include "mathlib/vector2d.h" -#include "mathlib/math_pfns.h" -#include "minmax.h" - -// Uncomment this to add extra Asserts to check for NANs, uninitialized vecs, etc. -//#define VECTOR_PARANOIA 1 - -// Uncomment this to make sure we don't do anything slow with our vectors -//#define VECTOR_NO_SLOW_OPERATIONS 1 - - -// Used to make certain code easier to read. -#define X_INDEX 0 -#define Y_INDEX 1 -#define Z_INDEX 2 - - -#ifdef VECTOR_PARANOIA -#define CHECK_VALID( _v) Assert( (_v).IsValid() ) -#else -#define CHECK_VALID( _v) 0 -#endif - -#define VecToString(v) (static_cast(CFmtStr("(%f, %f, %f)", (v).x, (v).y, (v).z))) // ** Note: this generates a temporary, don't hold reference! - -class VectorByValue; - -//========================================================= -// 3D Vector -//========================================================= -class Vector -{ -public: - // Members - vec_t x, y, z; - - // Construction/destruction: - Vector(void); - Vector(vec_t X, vec_t Y, vec_t Z); - Vector(vec_t XYZ); // TODO (Ilya): is this potentially a bad idea? - - // Initialization - void Init(vec_t ix=0.0f, vec_t iy=0.0f, vec_t iz=0.0f); - // TODO (Ilya): Should there be an init that takes a single float for consistency? - - // Got any nasty NAN's? - bool IsValid() const; - void Invalidate(); - - // array access... - vec_t operator[](int i) const; - vec_t& operator[](int i); - - // Base address... - vec_t* Base(); - vec_t const* Base() const; - - // Cast to Vector2D... - Vector2D& AsVector2D(); - const Vector2D& AsVector2D() const; - - // Initialization methods - void Random( vec_t minVal, vec_t maxVal ); - inline void Zero(); ///< zero out a vector - - // equality - bool operator==(const Vector& v) const; - bool operator!=(const Vector& v) const; - - // arithmetic operations - FORCEINLINE Vector& operator+=(const Vector &v); - FORCEINLINE Vector& operator-=(const Vector &v); - FORCEINLINE Vector& operator*=(const Vector &v); - FORCEINLINE Vector& operator*=(float s); - FORCEINLINE Vector& operator/=(const Vector &v); - FORCEINLINE Vector& operator/=(float s); - FORCEINLINE Vector& operator+=(float fl) ; ///< broadcast add - FORCEINLINE Vector& operator-=(float fl) ; ///< broadcast sub - -// negate the vector components - void Negate(); - - // Get the vector's magnitude. - inline vec_t Length() const; - - // Get the vector's magnitude squared. - FORCEINLINE vec_t LengthSqr(void) const - { - CHECK_VALID(*this); - return (x*x + y*y + z*z); - } - - // return true if this vector is (0,0,0) within tolerance - bool IsZero( float tolerance = 0.01f ) const - { - return (x > -tolerance && x < tolerance && - y > -tolerance && y < tolerance && - z > -tolerance && z < tolerance); - } - - vec_t NormalizeInPlace(); - bool IsLengthGreaterThan( float val ) const; - bool IsLengthLessThan( float val ) const; - - // check if a vector is within the box defined by two other vectors - FORCEINLINE bool WithinAABox( Vector const &boxmin, Vector const &boxmax); - - // Get the distance from this vector to the other one. - vec_t DistTo(const Vector &vOther) const; - - // Get the distance from this vector to the other one squared. - // NJS: note, VC wasn't inlining it correctly in several deeply nested inlines due to being an 'out of line' inline. - // may be able to tidy this up after switching to VC7 - FORCEINLINE vec_t DistToSqr(const Vector &vOther) const - { - Vector delta; - - delta.x = x - vOther.x; - delta.y = y - vOther.y; - delta.z = z - vOther.z; - - return delta.LengthSqr(); - } - - // Copy - void CopyToArray(float* rgfl) const; - - // Multiply, add, and assign to this (ie: *this = a + b * scalar). This - // is about 12% faster than the actual vector equation (because it's done per-component - // rather than per-vector). - void MulAdd(const Vector& a, const Vector& b, float scalar); - - // Dot product. - vec_t Dot(const Vector& vOther) const; - - // assignment - Vector& operator=(const Vector &vOther); - - // 2d - vec_t Length2D(void) const; - vec_t Length2DSqr(void) const; - - operator VectorByValue &() { return *((VectorByValue *)(this)); } - operator const VectorByValue &() const { return *((const VectorByValue *)(this)); } - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // copy constructors -// Vector(const Vector &vOther); - - // arithmetic operations - Vector operator-(void) const; - - Vector operator+(const Vector& v) const; - Vector operator-(const Vector& v) const; - Vector operator*(const Vector& v) const; - Vector operator/(const Vector& v) const; - Vector operator*(float fl) const; - Vector operator/(float fl) const; - - // Cross product between two vectors. - Vector Cross(const Vector &vOther) const; - - // Returns a vector with the min or max in X, Y, and Z. - Vector Min(const Vector &vOther) const; - Vector Max(const Vector &vOther) const; - -#else - -private: - // No copy constructors allowed if we're in optimal mode - Vector(const Vector& vOther); -#endif -}; - - - -#define USE_M64S ( ( !defined( _X360 ) ) && ( ! defined( _LINUX) ) ) - - - -//========================================================= -// 4D Short Vector (aligned on 8-byte boundary) -//========================================================= -class ALIGN8 ShortVector -{ -public: - - short x, y, z, w; - - // Initialization - void Init(short ix = 0, short iy = 0, short iz = 0, short iw = 0 ); - - -#if USE_M64S - __m64 &AsM64() { return *(__m64*)&x; } - const __m64 &AsM64() const { return *(const __m64*)&x; } -#endif - - // Setter - void Set( const ShortVector& vOther ); - void Set( const short ix, const short iy, const short iz, const short iw ); - - // array access... - short operator[](int i) const; - short& operator[](int i); - - // Base address... - short* Base(); - short const* Base() const; - - // equality - bool operator==(const ShortVector& v) const; - bool operator!=(const ShortVector& v) const; - - // Arithmetic operations - FORCEINLINE ShortVector& operator+=(const ShortVector &v); - FORCEINLINE ShortVector& operator-=(const ShortVector &v); - FORCEINLINE ShortVector& operator*=(const ShortVector &v); - FORCEINLINE ShortVector& operator*=(float s); - FORCEINLINE ShortVector& operator/=(const ShortVector &v); - FORCEINLINE ShortVector& operator/=(float s); - FORCEINLINE ShortVector operator*(float fl) const; - -private: - - // No copy constructors allowed if we're in optimal mode -// ShortVector(ShortVector const& vOther); - - // No assignment operators either... -// ShortVector& operator=( ShortVector const& src ); - -}; - - - - - - -//========================================================= -// 4D Integer Vector -//========================================================= -class IntVector4D -{ -public: - - int x, y, z, w; - - // Initialization - void Init(int ix = 0, int iy = 0, int iz = 0, int iw = 0 ); - -#if USE_M64S - __m64 &AsM64() { return *(__m64*)&x; } - const __m64 &AsM64() const { return *(const __m64*)&x; } -#endif - - // Setter - void Set( const IntVector4D& vOther ); - void Set( const int ix, const int iy, const int iz, const int iw ); - - // array access... - int operator[](int i) const; - int& operator[](int i); - - // Base address... - int* Base(); - int const* Base() const; - - // equality - bool operator==(const IntVector4D& v) const; - bool operator!=(const IntVector4D& v) const; - - // Arithmetic operations - FORCEINLINE IntVector4D& operator+=(const IntVector4D &v); - FORCEINLINE IntVector4D& operator-=(const IntVector4D &v); - FORCEINLINE IntVector4D& operator*=(const IntVector4D &v); - FORCEINLINE IntVector4D& operator*=(float s); - FORCEINLINE IntVector4D& operator/=(const IntVector4D &v); - FORCEINLINE IntVector4D& operator/=(float s); - FORCEINLINE IntVector4D operator*(float fl) const; - -private: - - // No copy constructors allowed if we're in optimal mode - // IntVector4D(IntVector4D const& vOther); - - // No assignment operators either... - // IntVector4D& operator=( IntVector4D const& src ); - -}; - - - -//----------------------------------------------------------------------------- -// Allows us to specifically pass the vector by value when we need to -//----------------------------------------------------------------------------- -class VectorByValue : public Vector -{ -public: - // Construction/destruction: - VectorByValue(void) : Vector() {} - VectorByValue(vec_t X, vec_t Y, vec_t Z) : Vector( X, Y, Z ) {} - VectorByValue(const VectorByValue& vOther) { *this = vOther; } -}; - - -//----------------------------------------------------------------------------- -// Utility to simplify table construction. No constructor means can use -// traditional C-style initialization -//----------------------------------------------------------------------------- -class TableVector -{ -public: - vec_t x, y, z; - - operator Vector &() { return *((Vector *)(this)); } - operator const Vector &() const { return *((const Vector *)(this)); } - - // array access... - inline vec_t& operator[](int i) - { - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; - } - - inline vec_t operator[](int i) const - { - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; - } -}; - - -//----------------------------------------------------------------------------- -// Here's where we add all those lovely SSE optimized routines -//----------------------------------------------------------------------------- - -class ALIGN16 VectorAligned : public Vector -{ -public: - inline VectorAligned(void) {}; - inline VectorAligned(vec_t X, vec_t Y, vec_t Z) - { - Init(X,Y,Z); - } - -#ifdef VECTOR_NO_SLOW_OPERATIONS - -private: - // No copy constructors allowed if we're in optimal mode - VectorAligned(const VectorAligned& vOther); - VectorAligned(const Vector &vOther); - -#else -public: - explicit VectorAligned(const Vector &vOther) - { - Init(vOther.x, vOther.y, vOther.z); - } - - VectorAligned& operator=(const Vector &vOther) - { - Init(vOther.x, vOther.y, vOther.z); - return *this; - } - -#endif - float w; // this space is used anyway -}; - -//----------------------------------------------------------------------------- -// Vector related operations -//----------------------------------------------------------------------------- - -// Vector clear -FORCEINLINE void VectorClear( Vector& a ); - -// Copy -FORCEINLINE void VectorCopy( const Vector& src, Vector& dst ); - -// Vector arithmetic -FORCEINLINE void VectorAdd( const Vector& a, const Vector& b, Vector& result ); -FORCEINLINE void VectorSubtract( const Vector& a, const Vector& b, Vector& result ); -FORCEINLINE void VectorMultiply( const Vector& a, vec_t b, Vector& result ); -FORCEINLINE void VectorMultiply( const Vector& a, const Vector& b, Vector& result ); -FORCEINLINE void VectorDivide( const Vector& a, vec_t b, Vector& result ); -FORCEINLINE void VectorDivide( const Vector& a, const Vector& b, Vector& result ); -inline void VectorScale ( const Vector& in, vec_t scale, Vector& result ); -inline void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest ); - -// Vector equality with tolerance -bool VectorsAreEqual( const Vector& src1, const Vector& src2, float tolerance = 0.0f ); - -#define VectorExpand(v) (v).x, (v).y, (v).z - - -// Normalization -// FIXME: Can't use quite yet -//vec_t VectorNormalize( Vector& v ); - -// Length -inline vec_t VectorLength( const Vector& v ); - -// Dot Product -FORCEINLINE vec_t DotProduct(const Vector& a, const Vector& b); - -// Cross product -void CrossProduct(const Vector& a, const Vector& b, Vector& result ); - -// Store the min or max of each of x, y, and z into the result. -void VectorMin( const Vector &a, const Vector &b, Vector &result ); -void VectorMax( const Vector &a, const Vector &b, Vector &result ); - -// Linearly interpolate between two vectors -void VectorLerp(const Vector& src1, const Vector& src2, vec_t t, Vector& dest ); - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -// Cross product -Vector CrossProduct( const Vector& a, const Vector& b ); - -// Random vector creation -Vector RandomVector( vec_t minVal, vec_t maxVal ); - -#endif - -//----------------------------------------------------------------------------- -// -// Inlined Vector methods -// -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// constructors -//----------------------------------------------------------------------------- -inline Vector::Vector(void) -{ -#ifdef _DEBUG -#ifdef VECTOR_PARANOIA - // Initialize to NAN to catch errors - x = y = z = VEC_T_NAN; -#endif -#endif -} - -inline Vector::Vector(vec_t X, vec_t Y, vec_t Z) -{ - x = X; y = Y; z = Z; - CHECK_VALID(*this); -} - -inline Vector::Vector(vec_t XYZ) -{ - x = y = z = XYZ; - CHECK_VALID(*this); -} - -//inline Vector::Vector(const float *pFloat) -//{ -// Assert( pFloat ); -// x = pFloat[0]; y = pFloat[1]; z = pFloat[2]; -// CHECK_VALID(*this); -//} - -#if 0 -//----------------------------------------------------------------------------- -// copy constructor -//----------------------------------------------------------------------------- - -inline Vector::Vector(const Vector &vOther) -{ - CHECK_VALID(vOther); - x = vOther.x; y = vOther.y; z = vOther.z; -} -#endif - -//----------------------------------------------------------------------------- -// initialization -//----------------------------------------------------------------------------- - -inline void Vector::Init( vec_t ix, vec_t iy, vec_t iz ) -{ - x = ix; y = iy; z = iz; - CHECK_VALID(*this); -} - -inline void Vector::Random( vec_t minVal, vec_t maxVal ) -{ - x = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - y = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - z = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - CHECK_VALID(*this); -} - -// This should really be a single opcode on the PowerPC (move r0 onto the vec reg) -inline void Vector::Zero() -{ - x = y = z = 0.0f; -} - -inline void VectorClear( Vector& a ) -{ - a.x = a.y = a.z = 0.0f; -} - -//----------------------------------------------------------------------------- -// assignment -//----------------------------------------------------------------------------- - -inline Vector& Vector::operator=(const Vector &vOther) -{ - CHECK_VALID(vOther); - x=vOther.x; y=vOther.y; z=vOther.z; - return *this; -} - - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- -inline vec_t& Vector::operator[](int i) -{ - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; -} - -inline vec_t Vector::operator[](int i) const -{ - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; -} - - -//----------------------------------------------------------------------------- -// Base address... -//----------------------------------------------------------------------------- -inline vec_t* Vector::Base() -{ - return (vec_t*)this; -} - -inline vec_t const* Vector::Base() const -{ - return (vec_t const*)this; -} - -//----------------------------------------------------------------------------- -// Cast to Vector2D... -//----------------------------------------------------------------------------- - -inline Vector2D& Vector::AsVector2D() -{ - return *(Vector2D*)this; -} - -inline const Vector2D& Vector::AsVector2D() const -{ - return *(const Vector2D*)this; -} - -//----------------------------------------------------------------------------- -// IsValid? -//----------------------------------------------------------------------------- - -inline bool Vector::IsValid() const -{ - return IsFinite(x) && IsFinite(y) && IsFinite(z); -} - -//----------------------------------------------------------------------------- -// Invalidate -//----------------------------------------------------------------------------- - -inline void Vector::Invalidate() -{ -//#ifdef _DEBUG -//#ifdef VECTOR_PARANOIA - x = y = z = VEC_T_NAN; -//#endif -//#endif -} - -//----------------------------------------------------------------------------- -// comparison -//----------------------------------------------------------------------------- - -inline bool Vector::operator==( const Vector& src ) const -{ - CHECK_VALID(src); - CHECK_VALID(*this); - return (src.x == x) && (src.y == y) && (src.z == z); -} - -inline bool Vector::operator!=( const Vector& src ) const -{ - CHECK_VALID(src); - CHECK_VALID(*this); - return (src.x != x) || (src.y != y) || (src.z != z); -} - - -//----------------------------------------------------------------------------- -// Copy -//----------------------------------------------------------------------------- - -FORCEINLINE void VectorCopy( const Vector& src, Vector& dst ) -{ - CHECK_VALID(src); - dst.x = src.x; - dst.y = src.y; - dst.z = src.z; -} - -inline void Vector::CopyToArray(float* rgfl) const -{ - Assert( rgfl ); - CHECK_VALID(*this); - rgfl[0] = x, rgfl[1] = y, rgfl[2] = z; -} - -//----------------------------------------------------------------------------- -// standard math operations -//----------------------------------------------------------------------------- -// #pragma message("TODO: these should be SSE") - -inline void Vector::Negate() -{ - CHECK_VALID(*this); - x = -x; y = -y; z = -z; -} - -FORCEINLINE Vector& Vector::operator+=(const Vector& v) -{ - CHECK_VALID(*this); - CHECK_VALID(v); - x+=v.x; y+=v.y; z += v.z; - return *this; -} - -FORCEINLINE Vector& Vector::operator-=(const Vector& v) -{ - CHECK_VALID(*this); - CHECK_VALID(v); - x-=v.x; y-=v.y; z -= v.z; - return *this; -} - -FORCEINLINE Vector& Vector::operator*=(float fl) -{ - x *= fl; - y *= fl; - z *= fl; - CHECK_VALID(*this); - return *this; -} - -FORCEINLINE Vector& Vector::operator*=(const Vector& v) -{ - CHECK_VALID(v); - x *= v.x; - y *= v.y; - z *= v.z; - CHECK_VALID(*this); - return *this; -} - -// this ought to be an opcode. -FORCEINLINE Vector& Vector::operator+=(float fl) -{ - x += fl; - y += fl; - z += fl; - CHECK_VALID(*this); - return *this; -} - -FORCEINLINE Vector& Vector::operator-=(float fl) -{ - x -= fl; - y -= fl; - z -= fl; - CHECK_VALID(*this); - return *this; -} - - - -FORCEINLINE Vector& Vector::operator/=(float fl) -{ - Assert( fl != 0.0f ); - float oofl = 1.0f / fl; - x *= oofl; - y *= oofl; - z *= oofl; - CHECK_VALID(*this); - return *this; -} - -FORCEINLINE Vector& Vector::operator/=(const Vector& v) -{ - CHECK_VALID(v); - Assert( v.x != 0.0f && v.y != 0.0f && v.z != 0.0f ); - x /= v.x; - y /= v.y; - z /= v.z; - CHECK_VALID(*this); - return *this; -} - - - -//----------------------------------------------------------------------------- -// -// Inlined Short Vector methods -// -//----------------------------------------------------------------------------- - - -inline void ShortVector::Init( short ix, short iy, short iz, short iw ) -{ - x = ix; y = iy; z = iz; w = iw; -} - -FORCEINLINE void ShortVector::Set( const ShortVector& vOther ) -{ - x = vOther.x; - y = vOther.y; - z = vOther.z; - w = vOther.w; -} - -FORCEINLINE void ShortVector::Set( const short ix, const short iy, const short iz, const short iw ) -{ - x = ix; - y = iy; - z = iz; - w = iw; -} - - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- -inline short ShortVector::operator[](int i) const -{ - Assert( (i >= 0) && (i < 4) ); - return ((short*)this)[i]; -} - -inline short& ShortVector::operator[](int i) -{ - Assert( (i >= 0) && (i < 4) ); - return ((short*)this)[i]; -} - -//----------------------------------------------------------------------------- -// Base address... -//----------------------------------------------------------------------------- -inline short* ShortVector::Base() -{ - return (short*)this; -} - -inline short const* ShortVector::Base() const -{ - return (short const*)this; -} - - -//----------------------------------------------------------------------------- -// comparison -//----------------------------------------------------------------------------- - -inline bool ShortVector::operator==( const ShortVector& src ) const -{ - return (src.x == x) && (src.y == y) && (src.z == z) && (src.w == w); -} - -inline bool ShortVector::operator!=( const ShortVector& src ) const -{ - return (src.x != x) || (src.y != y) || (src.z != z) || (src.w != w); -} - - - -//----------------------------------------------------------------------------- -// standard math operations -//----------------------------------------------------------------------------- - -FORCEINLINE ShortVector& ShortVector::operator+=(const ShortVector& v) -{ - x+=v.x; y+=v.y; z += v.z; w += v.w; - return *this; -} - -FORCEINLINE ShortVector& ShortVector::operator-=(const ShortVector& v) -{ - x-=v.x; y-=v.y; z -= v.z; w -= v.w; - return *this; -} - -FORCEINLINE ShortVector& ShortVector::operator*=(float fl) -{ - x *= fl; - y *= fl; - z *= fl; - w *= fl; - return *this; -} - -FORCEINLINE ShortVector& ShortVector::operator*=(const ShortVector& v) -{ - x *= v.x; - y *= v.y; - z *= v.z; - w *= v.w; - return *this; -} - -FORCEINLINE ShortVector& ShortVector::operator/=(float fl) -{ - Assert( fl != 0.0f ); - float oofl = 1.0f / fl; - x *= oofl; - y *= oofl; - z *= oofl; - w *= oofl; - return *this; -} - -FORCEINLINE ShortVector& ShortVector::operator/=(const ShortVector& v) -{ - Assert( v.x != 0 && v.y != 0 && v.z != 0 && v.w != 0 ); - x /= v.x; - y /= v.y; - z /= v.z; - w /= v.w; - return *this; -} - -FORCEINLINE void ShortVectorMultiply( const ShortVector& src, float fl, ShortVector& res ) -{ - Assert( IsFinite(fl) ); - res.x = src.x * fl; - res.y = src.y * fl; - res.z = src.z * fl; - res.w = src.w * fl; -} - -FORCEINLINE ShortVector ShortVector::operator*(float fl) const -{ - ShortVector res; - ShortVectorMultiply( *this, fl, res ); - return res; -} - - - - - - -//----------------------------------------------------------------------------- -// -// Inlined Integer Vector methods -// -//----------------------------------------------------------------------------- - - -inline void IntVector4D::Init( int ix, int iy, int iz, int iw ) -{ - x = ix; y = iy; z = iz; w = iw; -} - -FORCEINLINE void IntVector4D::Set( const IntVector4D& vOther ) -{ - x = vOther.x; - y = vOther.y; - z = vOther.z; - w = vOther.w; -} - -FORCEINLINE void IntVector4D::Set( const int ix, const int iy, const int iz, const int iw ) -{ - x = ix; - y = iy; - z = iz; - w = iw; -} - - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- -inline int IntVector4D::operator[](int i) const -{ - Assert( (i >= 0) && (i < 4) ); - return ((int*)this)[i]; -} - -inline int& IntVector4D::operator[](int i) -{ - Assert( (i >= 0) && (i < 4) ); - return ((int*)this)[i]; -} - -//----------------------------------------------------------------------------- -// Base address... -//----------------------------------------------------------------------------- -inline int* IntVector4D::Base() -{ - return (int*)this; -} - -inline int const* IntVector4D::Base() const -{ - return (int const*)this; -} - - -//----------------------------------------------------------------------------- -// comparison -//----------------------------------------------------------------------------- - -inline bool IntVector4D::operator==( const IntVector4D& src ) const -{ - return (src.x == x) && (src.y == y) && (src.z == z) && (src.w == w); -} - -inline bool IntVector4D::operator!=( const IntVector4D& src ) const -{ - return (src.x != x) || (src.y != y) || (src.z != z) || (src.w != w); -} - - - -//----------------------------------------------------------------------------- -// standard math operations -//----------------------------------------------------------------------------- - -FORCEINLINE IntVector4D& IntVector4D::operator+=(const IntVector4D& v) -{ - x+=v.x; y+=v.y; z += v.z; w += v.w; - return *this; -} - -FORCEINLINE IntVector4D& IntVector4D::operator-=(const IntVector4D& v) -{ - x-=v.x; y-=v.y; z -= v.z; w -= v.w; - return *this; -} - -FORCEINLINE IntVector4D& IntVector4D::operator*=(float fl) -{ - x *= fl; - y *= fl; - z *= fl; - w *= fl; - return *this; -} - -FORCEINLINE IntVector4D& IntVector4D::operator*=(const IntVector4D& v) -{ - x *= v.x; - y *= v.y; - z *= v.z; - w *= v.w; - return *this; -} - -FORCEINLINE IntVector4D& IntVector4D::operator/=(float fl) -{ - Assert( fl != 0.0f ); - float oofl = 1.0f / fl; - x *= oofl; - y *= oofl; - z *= oofl; - w *= oofl; - return *this; -} - -FORCEINLINE IntVector4D& IntVector4D::operator/=(const IntVector4D& v) -{ - Assert( v.x != 0 && v.y != 0 && v.z != 0 && v.w != 0 ); - x /= v.x; - y /= v.y; - z /= v.z; - w /= v.w; - return *this; -} - -FORCEINLINE void IntVector4DMultiply( const IntVector4D& src, float fl, IntVector4D& res ) -{ - Assert( IsFinite(fl) ); - res.x = src.x * fl; - res.y = src.y * fl; - res.z = src.z * fl; - res.w = src.w * fl; -} - -FORCEINLINE IntVector4D IntVector4D::operator*(float fl) const -{ - IntVector4D res; - IntVector4DMultiply( *this, fl, res ); - return res; -} - - - -// ======================= - - -FORCEINLINE void VectorAdd( const Vector& a, const Vector& b, Vector& c ) -{ - CHECK_VALID(a); - CHECK_VALID(b); - c.x = a.x + b.x; - c.y = a.y + b.y; - c.z = a.z + b.z; -} - -FORCEINLINE void VectorSubtract( const Vector& a, const Vector& b, Vector& c ) -{ - CHECK_VALID(a); - CHECK_VALID(b); - c.x = a.x - b.x; - c.y = a.y - b.y; - c.z = a.z - b.z; -} - -FORCEINLINE void VectorMultiply( const Vector& a, vec_t b, Vector& c ) -{ - CHECK_VALID(a); - Assert( IsFinite(b) ); - c.x = a.x * b; - c.y = a.y * b; - c.z = a.z * b; -} - -FORCEINLINE void VectorMultiply( const Vector& a, const Vector& b, Vector& c ) -{ - CHECK_VALID(a); - CHECK_VALID(b); - c.x = a.x * b.x; - c.y = a.y * b.y; - c.z = a.z * b.z; -} - -// for backwards compatability -inline void VectorScale ( const Vector& in, vec_t scale, Vector& result ) -{ - VectorMultiply( in, scale, result ); -} - - -FORCEINLINE void VectorDivide( const Vector& a, vec_t b, Vector& c ) -{ - CHECK_VALID(a); - Assert( b != 0.0f ); - vec_t oob = 1.0f / b; - c.x = a.x * oob; - c.y = a.y * oob; - c.z = a.z * oob; -} - -FORCEINLINE void VectorDivide( const Vector& a, const Vector& b, Vector& c ) -{ - CHECK_VALID(a); - CHECK_VALID(b); - Assert( (b.x != 0.0f) && (b.y != 0.0f) && (b.z != 0.0f) ); - c.x = a.x / b.x; - c.y = a.y / b.y; - c.z = a.z / b.z; -} - -// FIXME: Remove -// For backwards compatability -inline void Vector::MulAdd(const Vector& a, const Vector& b, float scalar) -{ - CHECK_VALID(a); - CHECK_VALID(b); - x = a.x + b.x * scalar; - y = a.y + b.y * scalar; - z = a.z + b.z * scalar; -} - -inline void VectorLerp(const Vector& src1, const Vector& src2, vec_t t, Vector& dest ) -{ - CHECK_VALID(src1); - CHECK_VALID(src2); - dest.x = src1.x + (src2.x - src1.x) * t; - dest.y = src1.y + (src2.y - src1.y) * t; - dest.z = src1.z + (src2.z - src1.z) * t; -} - - -//----------------------------------------------------------------------------- -// Temporary storage for vector results so const Vector& results can be returned -//----------------------------------------------------------------------------- -inline Vector &AllocTempVector() -{ - static Vector s_vecTemp[128]; - static CInterlockedInt s_nIndex; - - int nIndex; - for (;;) - { - int nOldIndex = s_nIndex; - nIndex = ( (nOldIndex + 0x10001) & 0x7F ); - - if ( s_nIndex.AssignIf( nOldIndex, nIndex ) ) - { - break; - } - ThreadPause(); - } - return s_vecTemp[nIndex & 0xffff]; -} - - - -//----------------------------------------------------------------------------- -// dot, cross -//----------------------------------------------------------------------------- -FORCEINLINE vec_t DotProduct(const Vector& a, const Vector& b) -{ - CHECK_VALID(a); - CHECK_VALID(b); - return( a.x*b.x + a.y*b.y + a.z*b.z ); -} - -// for backwards compatability -inline vec_t Vector::Dot( const Vector& vOther ) const -{ - CHECK_VALID(vOther); - return DotProduct( *this, vOther ); -} - -inline void CrossProduct(const Vector& a, const Vector& b, Vector& result ) -{ - CHECK_VALID(a); - CHECK_VALID(b); - Assert( &a != &result ); - Assert( &b != &result ); - result.x = a.y*b.z - a.z*b.y; - result.y = a.z*b.x - a.x*b.z; - result.z = a.x*b.y - a.y*b.x; -} - -inline vec_t DotProductAbs( const Vector &v0, const Vector &v1 ) -{ - CHECK_VALID(v0); - CHECK_VALID(v1); - return FloatMakePositive(v0.x*v1.x) + FloatMakePositive(v0.y*v1.y) + FloatMakePositive(v0.z*v1.z); -} - -inline vec_t DotProductAbs( const Vector &v0, const float *v1 ) -{ - return FloatMakePositive(v0.x * v1[0]) + FloatMakePositive(v0.y * v1[1]) + FloatMakePositive(v0.z * v1[2]); -} - -//----------------------------------------------------------------------------- -// length -//----------------------------------------------------------------------------- - -inline vec_t VectorLength( const Vector& v ) -{ - CHECK_VALID(v); - return (vec_t)FastSqrt(v.x*v.x + v.y*v.y + v.z*v.z); -} - - -inline vec_t Vector::Length(void) const -{ - CHECK_VALID(*this); - return VectorLength( *this ); -} - - -//----------------------------------------------------------------------------- -// Normalization -//----------------------------------------------------------------------------- - -/* -// FIXME: Can't use until we're un-macroed in mathlib.h -inline vec_t VectorNormalize( Vector& v ) -{ - Assert( v.IsValid() ); - vec_t l = v.Length(); - if (l != 0.0f) - { - v /= l; - } - else - { - // FIXME: - // Just copying the existing implemenation; shouldn't res.z == 0? - v.x = v.y = 0.0f; v.z = 1.0f; - } - return l; -} -*/ - - -// check a point against a box -bool Vector::WithinAABox( Vector const &boxmin, Vector const &boxmax) -{ - return ( - ( x >= boxmin.x ) && ( x <= boxmax.x) && - ( y >= boxmin.y ) && ( y <= boxmax.y) && - ( z >= boxmin.z ) && ( z <= boxmax.z) - ); -} - -//----------------------------------------------------------------------------- -// Get the distance from this vector to the other one -//----------------------------------------------------------------------------- -inline vec_t Vector::DistTo(const Vector &vOther) const -{ - Vector delta; - VectorSubtract( *this, vOther, delta ); - return delta.Length(); -} - - -//----------------------------------------------------------------------------- -// Vector equality with tolerance -//----------------------------------------------------------------------------- -inline bool VectorsAreEqual( const Vector& src1, const Vector& src2, float tolerance ) -{ - if (FloatMakePositive(src1.x - src2.x) > tolerance) - return false; - if (FloatMakePositive(src1.y - src2.y) > tolerance) - return false; - return (FloatMakePositive(src1.z - src2.z) <= tolerance); -} - - -//----------------------------------------------------------------------------- -// Computes the closest point to vecTarget no farther than flMaxDist from vecStart -//----------------------------------------------------------------------------- -inline void ComputeClosestPoint( const Vector& vecStart, float flMaxDist, const Vector& vecTarget, Vector *pResult ) -{ - Vector vecDelta; - VectorSubtract( vecTarget, vecStart, vecDelta ); - float flDistSqr = vecDelta.LengthSqr(); - if ( flDistSqr <= flMaxDist * flMaxDist ) - { - *pResult = vecTarget; - } - else - { - vecDelta /= FastSqrt( flDistSqr ); - VectorMA( vecStart, flMaxDist, vecDelta, *pResult ); - } -} - - -//----------------------------------------------------------------------------- -// Takes the absolute value of a vector -//----------------------------------------------------------------------------- -inline void VectorAbs( const Vector& src, Vector& dst ) -{ - dst.x = FloatMakePositive(src.x); - dst.y = FloatMakePositive(src.y); - dst.z = FloatMakePositive(src.z); -} - - -//----------------------------------------------------------------------------- -// -// Slow methods -// -//----------------------------------------------------------------------------- - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -//----------------------------------------------------------------------------- -// Returns a vector with the min or max in X, Y, and Z. -//----------------------------------------------------------------------------- -inline Vector Vector::Min(const Vector &vOther) const -{ - return Vector(x < vOther.x ? x : vOther.x, - y < vOther.y ? y : vOther.y, - z < vOther.z ? z : vOther.z); -} - -inline Vector Vector::Max(const Vector &vOther) const -{ - return Vector(x > vOther.x ? x : vOther.x, - y > vOther.y ? y : vOther.y, - z > vOther.z ? z : vOther.z); -} - - -//----------------------------------------------------------------------------- -// arithmetic operations -//----------------------------------------------------------------------------- - -inline Vector Vector::operator-(void) const -{ - return Vector(-x,-y,-z); -} - -inline Vector Vector::operator+(const Vector& v) const -{ - Vector res; - VectorAdd( *this, v, res ); - return res; -} - -inline Vector Vector::operator-(const Vector& v) const -{ - Vector res; - VectorSubtract( *this, v, res ); - return res; -} - -inline Vector Vector::operator*(float fl) const -{ - Vector res; - VectorMultiply( *this, fl, res ); - return res; -} - -inline Vector Vector::operator*(const Vector& v) const -{ - Vector res; - VectorMultiply( *this, v, res ); - return res; -} - -inline Vector Vector::operator/(float fl) const -{ - Vector res; - VectorDivide( *this, fl, res ); - return res; -} - -inline Vector Vector::operator/(const Vector& v) const -{ - Vector res; - VectorDivide( *this, v, res ); - return res; -} - -inline Vector operator*(float fl, const Vector& v) -{ - return v * fl; -} - -//----------------------------------------------------------------------------- -// cross product -//----------------------------------------------------------------------------- - -inline Vector Vector::Cross(const Vector& vOther) const -{ - Vector res; - CrossProduct( *this, vOther, res ); - return res; -} - -//----------------------------------------------------------------------------- -// 2D -//----------------------------------------------------------------------------- - -inline vec_t Vector::Length2D(void) const -{ - return (vec_t)FastSqrt(x*x + y*y); -} - -inline vec_t Vector::Length2DSqr(void) const -{ - return (x*x + y*y); -} - -inline Vector CrossProduct(const Vector& a, const Vector& b) -{ - return Vector( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x ); -} - -inline void VectorMin( const Vector &a, const Vector &b, Vector &result ) -{ - result.x = fpmin(a.x, b.x); - result.y = fpmin(a.y, b.y); - result.z = fpmin(a.z, b.z); -} - -inline void VectorMax( const Vector &a, const Vector &b, Vector &result ) -{ - result.x = fpmax(a.x, b.x); - result.y = fpmax(a.y, b.y); - result.z = fpmax(a.z, b.z); -} - -// Get a random vector. -inline Vector RandomVector( float minVal, float maxVal ) -{ - Vector random; - random.Random( minVal, maxVal ); - return random; -} - -#endif //slow - -//----------------------------------------------------------------------------- -// Helper debugging stuff.... -//----------------------------------------------------------------------------- - -inline bool operator==( float const* f, const Vector& v ) -{ - // AIIIEEEE!!!! - Assert(0); - return false; -} - -inline bool operator==( const Vector& v, float const* f ) -{ - // AIIIEEEE!!!! - Assert(0); - return false; -} - -inline bool operator!=( float const* f, const Vector& v ) -{ - // AIIIEEEE!!!! - Assert(0); - return false; -} - -inline bool operator!=( const Vector& v, float const* f ) -{ - // AIIIEEEE!!!! - Assert(0); - return false; -} - - -//----------------------------------------------------------------------------- -// AngularImpulse -//----------------------------------------------------------------------------- -// AngularImpulse are exponetial maps (an axis scaled by a "twist" angle in degrees) -typedef Vector AngularImpulse; - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline AngularImpulse RandomAngularImpulse( float minVal, float maxVal ) -{ - AngularImpulse angImp; - angImp.Random( minVal, maxVal ); - return angImp; -} - -#endif - - -//----------------------------------------------------------------------------- -// Quaternion -//----------------------------------------------------------------------------- - -class RadianEuler; - -class Quaternion // same data-layout as engine's vec4_t, -{ // which is a vec_t[4] -public: - inline Quaternion(void) { - - // Initialize to NAN to catch errors -#ifdef _DEBUG -#ifdef VECTOR_PARANOIA - x = y = z = w = VEC_T_NAN; -#endif -#endif - } - inline Quaternion(vec_t ix, vec_t iy, vec_t iz, vec_t iw) : x(ix), y(iy), z(iz), w(iw) { } - inline Quaternion(RadianEuler const &angle); // evil auto type promotion!!! - - inline void Init(vec_t ix=0.0f, vec_t iy=0.0f, vec_t iz=0.0f, vec_t iw=0.0f) { x = ix; y = iy; z = iz; w = iw; } - - bool IsValid() const; - void Invalidate(); - - bool operator==( const Quaternion &src ) const; - bool operator!=( const Quaternion &src ) const; - - vec_t* Base() { return (vec_t*)this; } - const vec_t* Base() const { return (vec_t*)this; } - - // array access... - vec_t operator[](int i) const; - vec_t& operator[](int i); - - vec_t x, y, z, w; -}; - - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- -inline vec_t& Quaternion::operator[](int i) -{ - Assert( (i >= 0) && (i < 4) ); - return ((vec_t*)this)[i]; -} - -inline vec_t Quaternion::operator[](int i) const -{ - Assert( (i >= 0) && (i < 4) ); - return ((vec_t*)this)[i]; -} - - -//----------------------------------------------------------------------------- -// Equality test -//----------------------------------------------------------------------------- -inline bool Quaternion::operator==( const Quaternion &src ) const -{ - return ( x == src.x ) && ( y == src.y ) && ( z == src.z ) && ( w == src.w ); -} - -inline bool Quaternion::operator!=( const Quaternion &src ) const -{ - return !operator==( src ); -} - - -//----------------------------------------------------------------------------- -// Quaternion equality with tolerance -//----------------------------------------------------------------------------- -inline bool QuaternionsAreEqual( const Quaternion& src1, const Quaternion& src2, float tolerance ) -{ - if (FloatMakePositive(src1.x - src2.x) > tolerance) - return false; - if (FloatMakePositive(src1.y - src2.y) > tolerance) - return false; - if (FloatMakePositive(src1.z - src2.z) > tolerance) - return false; - return (FloatMakePositive(src1.w - src2.w) <= tolerance); -} - - -//----------------------------------------------------------------------------- -// Here's where we add all those lovely SSE optimized routines -//----------------------------------------------------------------------------- -class ALIGN16 QuaternionAligned : public Quaternion -{ -public: - inline QuaternionAligned(void) {}; - inline QuaternionAligned(vec_t X, vec_t Y, vec_t Z, vec_t W) - { - Init(X,Y,Z,W); - } - -#ifdef VECTOR_NO_SLOW_OPERATIONS - -private: - // No copy constructors allowed if we're in optimal mode - QuaternionAligned(const QuaternionAligned& vOther); - QuaternionAligned(const Quaternion &vOther); - -#else -public: - explicit QuaternionAligned(const Quaternion &vOther) - { - Init(vOther.x, vOther.y, vOther.z, vOther.w); - } - - QuaternionAligned& operator=(const Quaternion &vOther) - { - Init(vOther.x, vOther.y, vOther.z, vOther.w); - return *this; - } - -#endif -}; - - -//----------------------------------------------------------------------------- -// Radian Euler angle aligned to axis (NOT ROLL/PITCH/YAW) -//----------------------------------------------------------------------------- -class QAngle; -class RadianEuler -{ -public: - inline RadianEuler(void) { } - inline RadianEuler(vec_t X, vec_t Y, vec_t Z) { x = X; y = Y; z = Z; } - inline RadianEuler(Quaternion const &q); // evil auto type promotion!!! - inline RadianEuler(QAngle const &angles); // evil auto type promotion!!! - - // Initialization - inline void Init(vec_t ix=0.0f, vec_t iy=0.0f, vec_t iz=0.0f) { x = ix; y = iy; z = iz; } - - // conversion to qangle - QAngle ToQAngle( void ) const; - bool IsValid() const; - void Invalidate(); - - // array access... - vec_t operator[](int i) const; - vec_t& operator[](int i); - - vec_t x, y, z; -}; - - -extern void AngleQuaternion( RadianEuler const &angles, Quaternion &qt ); -extern void QuaternionAngles( Quaternion const &q, RadianEuler &angles ); -inline Quaternion::Quaternion(RadianEuler const &angle) -{ - AngleQuaternion( angle, *this ); -} - -inline bool Quaternion::IsValid() const -{ - return IsFinite(x) && IsFinite(y) && IsFinite(z) && IsFinite(w); -} - -inline void Quaternion::Invalidate() -{ -//#ifdef _DEBUG -//#ifdef VECTOR_PARANOIA - x = y = z = w = VEC_T_NAN; -//#endif -//#endif -} - -inline RadianEuler::RadianEuler(Quaternion const &q) -{ - QuaternionAngles( q, *this ); -} - -inline void VectorCopy( RadianEuler const& src, RadianEuler &dst ) -{ - CHECK_VALID(src); - dst.x = src.x; - dst.y = src.y; - dst.z = src.z; -} - -inline void VectorScale( RadianEuler const& src, float b, RadianEuler &dst ) -{ - CHECK_VALID(src); - Assert( IsFinite(b) ); - dst.x = src.x * b; - dst.y = src.y * b; - dst.z = src.z * b; -} - -inline bool RadianEuler::IsValid() const -{ - return IsFinite(x) && IsFinite(y) && IsFinite(z); -} - -inline void RadianEuler::Invalidate() -{ -//#ifdef _DEBUG -//#ifdef VECTOR_PARANOIA - x = y = z = VEC_T_NAN; -//#endif -//#endif -} - - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- -inline vec_t& RadianEuler::operator[](int i) -{ - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; -} - -inline vec_t RadianEuler::operator[](int i) const -{ - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; -} - - -//----------------------------------------------------------------------------- -// Degree Euler QAngle pitch, yaw, roll -//----------------------------------------------------------------------------- -class QAngleByValue; - -class QAngle -{ -public: - // Members - vec_t x, y, z; - - // Construction/destruction - QAngle(void); - QAngle(vec_t X, vec_t Y, vec_t Z); -// QAngle(RadianEuler const &angles); // evil auto type promotion!!! - - // Allow pass-by-value - operator QAngleByValue &() { return *((QAngleByValue *)(this)); } - operator const QAngleByValue &() const { return *((const QAngleByValue *)(this)); } - - // Initialization - void Init(vec_t ix=0.0f, vec_t iy=0.0f, vec_t iz=0.0f); - void Random( vec_t minVal, vec_t maxVal ); - - // Got any nasty NAN's? - bool IsValid() const; - void Invalidate(); - - // array access... - vec_t operator[](int i) const; - vec_t& operator[](int i); - - // Base address... - vec_t* Base(); - vec_t const* Base() const; - - // equality - bool operator==(const QAngle& v) const; - bool operator!=(const QAngle& v) const; - - // arithmetic operations - QAngle& operator+=(const QAngle &v); - QAngle& operator-=(const QAngle &v); - QAngle& operator*=(float s); - QAngle& operator/=(float s); - - // Get the vector's magnitude. - vec_t Length() const; - vec_t LengthSqr() const; - - // negate the QAngle components - //void Negate(); - - // No assignment operators either... - QAngle& operator=( const QAngle& src ); - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // copy constructors - - // arithmetic operations - QAngle operator-(void) const; - - QAngle operator+(const QAngle& v) const; - QAngle operator-(const QAngle& v) const; - QAngle operator*(float fl) const; - QAngle operator/(float fl) const; -#else - -private: - // No copy constructors allowed if we're in optimal mode - QAngle(const QAngle& vOther); - -#endif -}; - -//----------------------------------------------------------------------------- -// Allows us to specifically pass the vector by value when we need to -//----------------------------------------------------------------------------- -class QAngleByValue : public QAngle -{ -public: - // Construction/destruction: - QAngleByValue(void) : QAngle() {} - QAngleByValue(vec_t X, vec_t Y, vec_t Z) : QAngle( X, Y, Z ) {} - QAngleByValue(const QAngleByValue& vOther) { *this = vOther; } -}; - - -inline void VectorAdd( const QAngle& a, const QAngle& b, QAngle& result ) -{ - CHECK_VALID(a); - CHECK_VALID(b); - result.x = a.x + b.x; - result.y = a.y + b.y; - result.z = a.z + b.z; -} - -inline void VectorMA( const QAngle &start, float scale, const QAngle &direction, QAngle &dest ) -{ - CHECK_VALID(start); - CHECK_VALID(direction); - dest.x = start.x + scale * direction.x; - dest.y = start.y + scale * direction.y; - dest.z = start.z + scale * direction.z; -} - - -//----------------------------------------------------------------------------- -// constructors -//----------------------------------------------------------------------------- -inline QAngle::QAngle(void) -{ -#ifdef _DEBUG -#ifdef VECTOR_PARANOIA - // Initialize to NAN to catch errors - x = y = z = VEC_T_NAN; -#endif -#endif -} - -inline QAngle::QAngle(vec_t X, vec_t Y, vec_t Z) -{ - x = X; y = Y; z = Z; - CHECK_VALID(*this); -} - - -//----------------------------------------------------------------------------- -// initialization -//----------------------------------------------------------------------------- -inline void QAngle::Init( vec_t ix, vec_t iy, vec_t iz ) -{ - x = ix; y = iy; z = iz; - CHECK_VALID(*this); -} - -inline void QAngle::Random( vec_t minVal, vec_t maxVal ) -{ - x = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - y = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - z = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - CHECK_VALID(*this); -} - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline QAngle RandomAngle( float minVal, float maxVal ) -{ - Vector random; - random.Random( minVal, maxVal ); - QAngle ret( random.x, random.y, random.z ); - return ret; -} - -#endif - - -inline RadianEuler::RadianEuler(QAngle const &angles) -{ - Init( - angles.z * 3.14159265358979323846f / 180.f, - angles.x * 3.14159265358979323846f / 180.f, - angles.y * 3.14159265358979323846f / 180.f ); -} - - - - -inline QAngle RadianEuler::ToQAngle( void) const -{ - return QAngle( - y * 180.f / 3.14159265358979323846f, - z * 180.f / 3.14159265358979323846f, - x * 180.f / 3.14159265358979323846f ); -} - - -//----------------------------------------------------------------------------- -// assignment -//----------------------------------------------------------------------------- -inline QAngle& QAngle::operator=(const QAngle &vOther) -{ - CHECK_VALID(vOther); - x=vOther.x; y=vOther.y; z=vOther.z; - return *this; -} - - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- -inline vec_t& QAngle::operator[](int i) -{ - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; -} - -inline vec_t QAngle::operator[](int i) const -{ - Assert( (i >= 0) && (i < 3) ); - return ((vec_t*)this)[i]; -} - - -//----------------------------------------------------------------------------- -// Base address... -//----------------------------------------------------------------------------- -inline vec_t* QAngle::Base() -{ - return (vec_t*)this; -} - -inline vec_t const* QAngle::Base() const -{ - return (vec_t const*)this; -} - - -//----------------------------------------------------------------------------- -// IsValid? -//----------------------------------------------------------------------------- -inline bool QAngle::IsValid() const -{ - return IsFinite(x) && IsFinite(y) && IsFinite(z); -} - -//----------------------------------------------------------------------------- -// Invalidate -//----------------------------------------------------------------------------- - -inline void QAngle::Invalidate() -{ -//#ifdef _DEBUG -//#ifdef VECTOR_PARANOIA - x = y = z = VEC_T_NAN; -//#endif -//#endif -} - -//----------------------------------------------------------------------------- -// comparison -//----------------------------------------------------------------------------- -inline bool QAngle::operator==( const QAngle& src ) const -{ - CHECK_VALID(src); - CHECK_VALID(*this); - return (src.x == x) && (src.y == y) && (src.z == z); -} - -inline bool QAngle::operator!=( const QAngle& src ) const -{ - CHECK_VALID(src); - CHECK_VALID(*this); - return (src.x != x) || (src.y != y) || (src.z != z); -} - - -//----------------------------------------------------------------------------- -// Copy -//----------------------------------------------------------------------------- -inline void VectorCopy( const QAngle& src, QAngle& dst ) -{ - CHECK_VALID(src); - dst.x = src.x; - dst.y = src.y; - dst.z = src.z; -} - - -//----------------------------------------------------------------------------- -// standard math operations -//----------------------------------------------------------------------------- -inline QAngle& QAngle::operator+=(const QAngle& v) -{ - CHECK_VALID(*this); - CHECK_VALID(v); - x+=v.x; y+=v.y; z += v.z; - return *this; -} - -inline QAngle& QAngle::operator-=(const QAngle& v) -{ - CHECK_VALID(*this); - CHECK_VALID(v); - x-=v.x; y-=v.y; z -= v.z; - return *this; -} - -inline QAngle& QAngle::operator*=(float fl) -{ - x *= fl; - y *= fl; - z *= fl; - CHECK_VALID(*this); - return *this; -} - -inline QAngle& QAngle::operator/=(float fl) -{ - Assert( fl != 0.0f ); - float oofl = 1.0f / fl; - x *= oofl; - y *= oofl; - z *= oofl; - CHECK_VALID(*this); - return *this; -} - - -//----------------------------------------------------------------------------- -// length -//----------------------------------------------------------------------------- -inline vec_t QAngle::Length( ) const -{ - CHECK_VALID(*this); - return (vec_t)FastSqrt( LengthSqr( ) ); -} - - -inline vec_t QAngle::LengthSqr( ) const -{ - CHECK_VALID(*this); - return x * x + y * y + z * z; -} - - -//----------------------------------------------------------------------------- -// Vector equality with tolerance -//----------------------------------------------------------------------------- -inline bool QAnglesAreEqual( const QAngle& src1, const QAngle& src2, float tolerance = 0.0f ) -{ - if (FloatMakePositive(src1.x - src2.x) > tolerance) - return false; - if (FloatMakePositive(src1.y - src2.y) > tolerance) - return false; - return (FloatMakePositive(src1.z - src2.z) <= tolerance); -} - - -//----------------------------------------------------------------------------- -// arithmetic operations (SLOW!!) -//----------------------------------------------------------------------------- -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline QAngle QAngle::operator-(void) const -{ - QAngle ret(-x,-y,-z); - return ret; -} - -inline QAngle QAngle::operator+(const QAngle& v) const -{ - QAngle res; - res.x = x + v.x; - res.y = y + v.y; - res.z = z + v.z; - return res; -} - -inline QAngle QAngle::operator-(const QAngle& v) const -{ - QAngle res; - res.x = x - v.x; - res.y = y - v.y; - res.z = z - v.z; - return res; -} - -inline QAngle QAngle::operator*(float fl) const -{ - QAngle res; - res.x = x * fl; - res.y = y * fl; - res.z = z * fl; - return res; -} - -inline QAngle QAngle::operator/(float fl) const -{ - QAngle res; - res.x = x / fl; - res.y = y / fl; - res.z = z / fl; - return res; -} - -inline QAngle operator*(float fl, const QAngle& v) -{ - QAngle ret( v * fl ); - return ret; -} - -#endif // VECTOR_NO_SLOW_OPERATIONS - - -//----------------------------------------------------------------------------- -// NOTE: These are not completely correct. The representations are not equivalent -// unless the QAngle represents a rotational impulse along a coordinate axis (x,y,z) -inline void QAngleToAngularImpulse( const QAngle &angles, AngularImpulse &impulse ) -{ - impulse.x = angles.z; - impulse.y = angles.x; - impulse.z = angles.y; -} - -inline void AngularImpulseToQAngle( const AngularImpulse &impulse, QAngle &angles ) -{ - angles.x = impulse.y; - angles.y = impulse.z; - angles.z = impulse.x; -} - -#if !defined( _X360 ) -extern float (*pfInvRSquared)( const float *v ); - -FORCEINLINE vec_t InvRSquared( float const *v ) -{ - return (*pfInvRSquared)(v); -} - -FORCEINLINE vec_t InvRSquared( const Vector &v ) -{ - return InvRSquared(&v.x); -} - -#else - -// call directly -FORCEINLINE float _VMX_InvRSquared( const Vector &v ) -{ - XMVECTOR xmV = XMVector3ReciprocalLength( XMLoadVector3( v.Base() ) ); - xmV = XMVector3Dot( xmV, xmV ); - return xmV.x; -} - -#define InvRSquared(x) _VMX_InvRSquared(x) - -#endif // _X360 - -#if !defined( _X360 ) -extern float (FASTCALL *pfVectorNormalize)(Vector& v); - -// FIXME: Change this back to a #define once we get rid of the vec_t version -FORCEINLINE float VectorNormalize( Vector& v ) -{ - return (*pfVectorNormalize)(v); -} -// FIXME: Obsolete version of VectorNormalize, once we remove all the friggin float*s -FORCEINLINE float VectorNormalize( float * v ) -{ - return VectorNormalize(*(reinterpret_cast(v))); -} - -#else - -// call directly -FORCEINLINE float _VMX_VectorNormalize( Vector &vec ) -{ - float mag = XMVector3Length( XMLoadVector3( vec.Base() ) ).x; - float den = 1.f / (mag + FLT_EPSILON ); - vec.x *= den; - vec.y *= den; - vec.z *= den; - return mag; -} -// FIXME: Change this back to a #define once we get rid of the vec_t version -FORCEINLINE float VectorNormalize( Vector& v ) -{ - return _VMX_VectorNormalize( v ); -} -// FIXME: Obsolete version of VectorNormalize, once we remove all the friggin float*s -FORCEINLINE float VectorNormalize( float *pV ) -{ - return _VMX_VectorNormalize(*(reinterpret_cast(pV))); -} - -#endif // _X360 - -#if !defined( _X360 ) -extern void (FASTCALL *pfVectorNormalizeFast)(Vector& v); - -FORCEINLINE void VectorNormalizeFast( Vector& v ) -{ - (*pfVectorNormalizeFast)(v); -} - -#else - -// call directly -FORCEINLINE void VectorNormalizeFast( Vector &vec ) -{ - XMVECTOR xmV = XMVector3LengthEst( XMLoadVector3( vec.Base() ) ); - float den = 1.f / (xmV.x + FLT_EPSILON); - vec.x *= den; - vec.y *= den; - vec.z *= den; -} - -#endif // _X360 - -inline vec_t Vector::NormalizeInPlace() -{ - return VectorNormalize( *this ); -} - -inline bool Vector::IsLengthGreaterThan( float val ) const -{ - return LengthSqr() > val*val; -} - -inline bool Vector::IsLengthLessThan( float val ) const -{ - return LengthSqr() < val*val; -} - -#endif - diff --git a/Resources/NetHook/mathlib/vector2d.h b/Resources/NetHook/mathlib/vector2d.h deleted file mode 100644 index 35ed31e6..00000000 --- a/Resources/NetHook/mathlib/vector2d.h +++ /dev/null @@ -1,670 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef VECTOR2D_H -#define VECTOR2D_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include - -// For vec_t, put this somewhere else? -#include "tier0/basetypes.h" - -// For rand(). We really need a library! -#include - -#include "tier0/dbg.h" -#include "mathlib/math_pfns.h" - -//========================================================= -// 2D Vector2D -//========================================================= - -class Vector2D -{ -public: - // Members - vec_t x, y; - - // Construction/destruction - Vector2D(void); - Vector2D(vec_t X, vec_t Y); - Vector2D(const float *pFloat); - - // Initialization - void Init(vec_t ix=0.0f, vec_t iy=0.0f); - - // Got any nasty NAN's? - bool IsValid() const; - - // array access... - vec_t operator[](int i) const; - vec_t& operator[](int i); - - // Base address... - vec_t* Base(); - vec_t const* Base() const; - - // Initialization methods - void Random( float minVal, float maxVal ); - - // equality - bool operator==(const Vector2D& v) const; - bool operator!=(const Vector2D& v) const; - - // arithmetic operations - Vector2D& operator+=(const Vector2D &v); - Vector2D& operator-=(const Vector2D &v); - Vector2D& operator*=(const Vector2D &v); - Vector2D& operator*=(float s); - Vector2D& operator/=(const Vector2D &v); - Vector2D& operator/=(float s); - - // negate the Vector2D components - void Negate(); - - // Get the Vector2D's magnitude. - vec_t Length() const; - - // Get the Vector2D's magnitude squared. - vec_t LengthSqr(void) const; - - // return true if this vector is (0,0) within tolerance - bool IsZero( float tolerance = 0.01f ) const - { - return (x > -tolerance && x < tolerance && - y > -tolerance && y < tolerance); - } - - // Normalize in place and return the old length. - vec_t NormalizeInPlace(); - - // Compare length. - bool IsLengthGreaterThan( float val ) const; - bool IsLengthLessThan( float val ) const; - - // Get the distance from this Vector2D to the other one. - vec_t DistTo(const Vector2D &vOther) const; - - // Get the distance from this Vector2D to the other one squared. - vec_t DistToSqr(const Vector2D &vOther) const; - - // Copy - void CopyToArray(float* rgfl) const; - - // Multiply, add, and assign to this (ie: *this = a + b * scalar). This - // is about 12% faster than the actual Vector2D equation (because it's done per-component - // rather than per-Vector2D). - void MulAdd(const Vector2D& a, const Vector2D& b, float scalar); - - // Dot product. - vec_t Dot(const Vector2D& vOther) const; - - // assignment - Vector2D& operator=(const Vector2D &vOther); - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // copy constructors - Vector2D(const Vector2D &vOther); - - // arithmetic operations - Vector2D operator-(void) const; - - Vector2D operator+(const Vector2D& v) const; - Vector2D operator-(const Vector2D& v) const; - Vector2D operator*(const Vector2D& v) const; - Vector2D operator/(const Vector2D& v) const; - Vector2D operator*(float fl) const; - Vector2D operator/(float fl) const; - - // Cross product between two vectors. - Vector2D Cross(const Vector2D &vOther) const; - - // Returns a Vector2D with the min or max in X, Y, and Z. - Vector2D Min(const Vector2D &vOther) const; - Vector2D Max(const Vector2D &vOther) const; - -#else - -private: - // No copy constructors allowed if we're in optimal mode - Vector2D(const Vector2D& vOther); -#endif -}; - -//----------------------------------------------------------------------------- - -const Vector2D vec2_origin(0,0); -const Vector2D vec2_invalid( FLT_MAX, FLT_MAX ); - -//----------------------------------------------------------------------------- -// Vector2D related operations -//----------------------------------------------------------------------------- - -// Vector2D clear -void Vector2DClear( Vector2D& a ); - -// Copy -void Vector2DCopy( const Vector2D& src, Vector2D& dst ); - -// Vector2D arithmetic -void Vector2DAdd( const Vector2D& a, const Vector2D& b, Vector2D& result ); -void Vector2DSubtract( const Vector2D& a, const Vector2D& b, Vector2D& result ); -void Vector2DMultiply( const Vector2D& a, vec_t b, Vector2D& result ); -void Vector2DMultiply( const Vector2D& a, const Vector2D& b, Vector2D& result ); -void Vector2DDivide( const Vector2D& a, vec_t b, Vector2D& result ); -void Vector2DDivide( const Vector2D& a, const Vector2D& b, Vector2D& result ); -void Vector2DMA( const Vector2D& start, float s, const Vector2D& dir, Vector2D& result ); - -// Store the min or max of each of x, y, and z into the result. -void Vector2DMin( const Vector2D &a, const Vector2D &b, Vector2D &result ); -void Vector2DMax( const Vector2D &a, const Vector2D &b, Vector2D &result ); - -#define Vector2DExpand( v ) (v).x, (v).y - -// Normalization -vec_t Vector2DNormalize( Vector2D& v ); - -// Length -vec_t Vector2DLength( const Vector2D& v ); - -// Dot Product -vec_t DotProduct2D(const Vector2D& a, const Vector2D& b); - -// Linearly interpolate between two vectors -void Vector2DLerp(const Vector2D& src1, const Vector2D& src2, vec_t t, Vector2D& dest ); - - -//----------------------------------------------------------------------------- -// -// Inlined Vector2D methods -// -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// constructors -//----------------------------------------------------------------------------- - -inline Vector2D::Vector2D(void) -{ -#ifdef _DEBUG - // Initialize to NAN to catch errors - x = y = VEC_T_NAN; -#endif -} - -inline Vector2D::Vector2D(vec_t X, vec_t Y) -{ - x = X; y = Y; - Assert( IsValid() ); -} - -inline Vector2D::Vector2D(const float *pFloat) -{ - Assert( pFloat ); - x = pFloat[0]; y = pFloat[1]; - Assert( IsValid() ); -} - - -//----------------------------------------------------------------------------- -// copy constructor -//----------------------------------------------------------------------------- - -inline Vector2D::Vector2D(const Vector2D &vOther) -{ - Assert( vOther.IsValid() ); - x = vOther.x; y = vOther.y; -} - -//----------------------------------------------------------------------------- -// initialization -//----------------------------------------------------------------------------- - -inline void Vector2D::Init( vec_t ix, vec_t iy ) -{ - x = ix; y = iy; - Assert( IsValid() ); -} - -inline void Vector2D::Random( float minVal, float maxVal ) -{ - x = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); - y = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal); -} - -inline void Vector2DClear( Vector2D& a ) -{ - a.x = a.y = 0.0f; -} - -//----------------------------------------------------------------------------- -// assignment -//----------------------------------------------------------------------------- - -inline Vector2D& Vector2D::operator=(const Vector2D &vOther) -{ - Assert( vOther.IsValid() ); - x=vOther.x; y=vOther.y; - return *this; -} - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- - -inline vec_t& Vector2D::operator[](int i) -{ - Assert( (i >= 0) && (i < 2) ); - return ((vec_t*)this)[i]; -} - -inline vec_t Vector2D::operator[](int i) const -{ - Assert( (i >= 0) && (i < 2) ); - return ((vec_t*)this)[i]; -} - -//----------------------------------------------------------------------------- -// Base address... -//----------------------------------------------------------------------------- - -inline vec_t* Vector2D::Base() -{ - return (vec_t*)this; -} - -inline vec_t const* Vector2D::Base() const -{ - return (vec_t const*)this; -} - -//----------------------------------------------------------------------------- -// IsValid? -//----------------------------------------------------------------------------- - -inline bool Vector2D::IsValid() const -{ - return IsFinite(x) && IsFinite(y); -} - -//----------------------------------------------------------------------------- -// comparison -//----------------------------------------------------------------------------- - -inline bool Vector2D::operator==( const Vector2D& src ) const -{ - Assert( src.IsValid() && IsValid() ); - return (src.x == x) && (src.y == y); -} - -inline bool Vector2D::operator!=( const Vector2D& src ) const -{ - Assert( src.IsValid() && IsValid() ); - return (src.x != x) || (src.y != y); -} - - -//----------------------------------------------------------------------------- -// Copy -//----------------------------------------------------------------------------- - -inline void Vector2DCopy( const Vector2D& src, Vector2D& dst ) -{ - Assert( src.IsValid() ); - dst.x = src.x; - dst.y = src.y; -} - -inline void Vector2D::CopyToArray(float* rgfl) const -{ - Assert( IsValid() ); - Assert( rgfl ); - rgfl[0] = x; rgfl[1] = y; -} - -//----------------------------------------------------------------------------- -// standard math operations -//----------------------------------------------------------------------------- - -inline void Vector2D::Negate() -{ - Assert( IsValid() ); - x = -x; y = -y; -} - -inline Vector2D& Vector2D::operator+=(const Vector2D& v) -{ - Assert( IsValid() && v.IsValid() ); - x+=v.x; y+=v.y; - return *this; -} - -inline Vector2D& Vector2D::operator-=(const Vector2D& v) -{ - Assert( IsValid() && v.IsValid() ); - x-=v.x; y-=v.y; - return *this; -} - -inline Vector2D& Vector2D::operator*=(float fl) -{ - x *= fl; - y *= fl; - Assert( IsValid() ); - return *this; -} - -inline Vector2D& Vector2D::operator*=(const Vector2D& v) -{ - x *= v.x; - y *= v.y; - Assert( IsValid() ); - return *this; -} - -inline Vector2D& Vector2D::operator/=(float fl) -{ - Assert( fl != 0.0f ); - float oofl = 1.0f / fl; - x *= oofl; - y *= oofl; - Assert( IsValid() ); - return *this; -} - -inline Vector2D& Vector2D::operator/=(const Vector2D& v) -{ - Assert( v.x != 0.0f && v.y != 0.0f ); - x /= v.x; - y /= v.y; - Assert( IsValid() ); - return *this; -} - -inline void Vector2DAdd( const Vector2D& a, const Vector2D& b, Vector2D& c ) -{ - Assert( a.IsValid() && b.IsValid() ); - c.x = a.x + b.x; - c.y = a.y + b.y; -} - -inline void Vector2DSubtract( const Vector2D& a, const Vector2D& b, Vector2D& c ) -{ - Assert( a.IsValid() && b.IsValid() ); - c.x = a.x - b.x; - c.y = a.y - b.y; -} - -inline void Vector2DMultiply( const Vector2D& a, vec_t b, Vector2D& c ) -{ - Assert( a.IsValid() && IsFinite(b) ); - c.x = a.x * b; - c.y = a.y * b; -} - -inline void Vector2DMultiply( const Vector2D& a, const Vector2D& b, Vector2D& c ) -{ - Assert( a.IsValid() && b.IsValid() ); - c.x = a.x * b.x; - c.y = a.y * b.y; -} - - -inline void Vector2DDivide( const Vector2D& a, vec_t b, Vector2D& c ) -{ - Assert( a.IsValid() ); - Assert( b != 0.0f ); - vec_t oob = 1.0f / b; - c.x = a.x * oob; - c.y = a.y * oob; -} - -inline void Vector2DDivide( const Vector2D& a, const Vector2D& b, Vector2D& c ) -{ - Assert( a.IsValid() ); - Assert( (b.x != 0.0f) && (b.y != 0.0f) ); - c.x = a.x / b.x; - c.y = a.y / b.y; -} - -inline void Vector2DMA( const Vector2D& start, float s, const Vector2D& dir, Vector2D& result ) -{ - Assert( start.IsValid() && IsFinite(s) && dir.IsValid() ); - result.x = start.x + s*dir.x; - result.y = start.y + s*dir.y; -} - -// FIXME: Remove -// For backwards compatability -inline void Vector2D::MulAdd(const Vector2D& a, const Vector2D& b, float scalar) -{ - x = a.x + b.x * scalar; - y = a.y + b.y * scalar; -} - -inline void Vector2DLerp(const Vector2D& src1, const Vector2D& src2, vec_t t, Vector2D& dest ) -{ - dest[0] = src1[0] + (src2[0] - src1[0]) * t; - dest[1] = src1[1] + (src2[1] - src1[1]) * t; -} - -//----------------------------------------------------------------------------- -// dot, cross -//----------------------------------------------------------------------------- -inline vec_t DotProduct2D(const Vector2D& a, const Vector2D& b) -{ - Assert( a.IsValid() && b.IsValid() ); - return( a.x*b.x + a.y*b.y ); -} - -// for backwards compatability -inline vec_t Vector2D::Dot( const Vector2D& vOther ) const -{ - return DotProduct2D( *this, vOther ); -} - - -//----------------------------------------------------------------------------- -// length -//----------------------------------------------------------------------------- -inline vec_t Vector2DLength( const Vector2D& v ) -{ - Assert( v.IsValid() ); - return (vec_t)FastSqrt(v.x*v.x + v.y*v.y); -} - -inline vec_t Vector2D::LengthSqr(void) const -{ - Assert( IsValid() ); - return (x*x + y*y); -} - -inline vec_t Vector2D::NormalizeInPlace() -{ - return Vector2DNormalize( *this ); -} - -inline bool Vector2D::IsLengthGreaterThan( float val ) const -{ - return LengthSqr() > val*val; -} - -inline bool Vector2D::IsLengthLessThan( float val ) const -{ - return LengthSqr() < val*val; -} - -inline vec_t Vector2D::Length(void) const -{ - return Vector2DLength( *this ); -} - - -inline void Vector2DMin( const Vector2D &a, const Vector2D &b, Vector2D &result ) -{ - result.x = (a.x < b.x) ? a.x : b.x; - result.y = (a.y < b.y) ? a.y : b.y; -} - - -inline void Vector2DMax( const Vector2D &a, const Vector2D &b, Vector2D &result ) -{ - result.x = (a.x > b.x) ? a.x : b.x; - result.y = (a.y > b.y) ? a.y : b.y; -} - - -//----------------------------------------------------------------------------- -// Normalization -//----------------------------------------------------------------------------- -inline vec_t Vector2DNormalize( Vector2D& v ) -{ - Assert( v.IsValid() ); - vec_t l = v.Length(); - if (l != 0.0f) - { - v /= l; - } - else - { - v.x = v.y = 0.0f; - } - return l; -} - - -//----------------------------------------------------------------------------- -// Get the distance from this Vector2D to the other one -//----------------------------------------------------------------------------- -inline vec_t Vector2D::DistTo(const Vector2D &vOther) const -{ - Vector2D delta; - Vector2DSubtract( *this, vOther, delta ); - return delta.Length(); -} - -inline vec_t Vector2D::DistToSqr(const Vector2D &vOther) const -{ - Vector2D delta; - Vector2DSubtract( *this, vOther, delta ); - return delta.LengthSqr(); -} - - -//----------------------------------------------------------------------------- -// Computes the closest point to vecTarget no farther than flMaxDist from vecStart -//----------------------------------------------------------------------------- -inline void ComputeClosestPoint2D( const Vector2D& vecStart, float flMaxDist, const Vector2D& vecTarget, Vector2D *pResult ) -{ - Vector2D vecDelta; - Vector2DSubtract( vecTarget, vecStart, vecDelta ); - float flDistSqr = vecDelta.LengthSqr(); - if ( flDistSqr <= flMaxDist * flMaxDist ) - { - *pResult = vecTarget; - } - else - { - vecDelta /= FastSqrt( flDistSqr ); - Vector2DMA( vecStart, flMaxDist, vecDelta, *pResult ); - } -} - - - -//----------------------------------------------------------------------------- -// -// Slow methods -// -//----------------------------------------------------------------------------- - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -//----------------------------------------------------------------------------- -// Returns a Vector2D with the min or max in X, Y, and Z. -//----------------------------------------------------------------------------- - -inline Vector2D Vector2D::Min(const Vector2D &vOther) const -{ - return Vector2D(x < vOther.x ? x : vOther.x, - y < vOther.y ? y : vOther.y); -} - -inline Vector2D Vector2D::Max(const Vector2D &vOther) const -{ - return Vector2D(x > vOther.x ? x : vOther.x, - y > vOther.y ? y : vOther.y); -} - - -//----------------------------------------------------------------------------- -// arithmetic operations -//----------------------------------------------------------------------------- - -inline Vector2D Vector2D::operator-(void) const -{ - return Vector2D(-x,-y); -} - -inline Vector2D Vector2D::operator+(const Vector2D& v) const -{ - Vector2D res; - Vector2DAdd( *this, v, res ); - return res; -} - -inline Vector2D Vector2D::operator-(const Vector2D& v) const -{ - Vector2D res; - Vector2DSubtract( *this, v, res ); - return res; -} - -inline Vector2D Vector2D::operator*(float fl) const -{ - Vector2D res; - Vector2DMultiply( *this, fl, res ); - return res; -} - -inline Vector2D Vector2D::operator*(const Vector2D& v) const -{ - Vector2D res; - Vector2DMultiply( *this, v, res ); - return res; -} - -inline Vector2D Vector2D::operator/(float fl) const -{ - Vector2D res; - Vector2DDivide( *this, fl, res ); - return res; -} - -inline Vector2D Vector2D::operator/(const Vector2D& v) const -{ - Vector2D res; - Vector2DDivide( *this, v, res ); - return res; -} - -inline Vector2D operator*(float fl, const Vector2D& v) -{ - return v * fl; -} - -#endif //slow - -#endif // VECTOR2D_H - diff --git a/Resources/NetHook/mathlib/vector4d.h b/Resources/NetHook/mathlib/vector4d.h deleted file mode 100644 index a74fb3a6..00000000 --- a/Resources/NetHook/mathlib/vector4d.h +++ /dev/null @@ -1,690 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef VECTOR4D_H -#define VECTOR4D_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include // For rand(). We really need a library! -#include -#if !defined( _X360 ) -#include // For SSE -#endif -#include "basetypes.h" // For vec_t, put this somewhere else? -#include "tier0/dbg.h" -#include "mathlib/math_pfns.h" - -// forward declarations -class Vector; -class Vector2D; - -//========================================================= -// 4D Vector4D -//========================================================= - -class Vector4D -{ -public: - // Members - vec_t x, y, z, w; - - // Construction/destruction - Vector4D(void); - Vector4D(vec_t X, vec_t Y, vec_t Z, vec_t W); - Vector4D(const float *pFloat); - - // Initialization - void Init(vec_t ix=0.0f, vec_t iy=0.0f, vec_t iz=0.0f, vec_t iw=0.0f); - - // Got any nasty NAN's? - bool IsValid() const; - - // array access... - vec_t operator[](int i) const; - vec_t& operator[](int i); - - // Base address... - inline vec_t* Base(); - inline vec_t const* Base() const; - - // Cast to Vector and Vector2D... - Vector& AsVector3D(); - Vector const& AsVector3D() const; - - Vector2D& AsVector2D(); - Vector2D const& AsVector2D() const; - - // Initialization methods - void Random( vec_t minVal, vec_t maxVal ); - - // equality - bool operator==(const Vector4D& v) const; - bool operator!=(const Vector4D& v) const; - - // arithmetic operations - Vector4D& operator+=(const Vector4D &v); - Vector4D& operator-=(const Vector4D &v); - Vector4D& operator*=(const Vector4D &v); - Vector4D& operator*=(float s); - Vector4D& operator/=(const Vector4D &v); - Vector4D& operator/=(float s); - - // negate the Vector4D components - void Negate(); - - // Get the Vector4D's magnitude. - vec_t Length() const; - - // Get the Vector4D's magnitude squared. - vec_t LengthSqr(void) const; - - // return true if this vector is (0,0,0,0) within tolerance - bool IsZero( float tolerance = 0.01f ) const - { - return (x > -tolerance && x < tolerance && - y > -tolerance && y < tolerance && - z > -tolerance && z < tolerance && - w > -tolerance && w < tolerance); - } - - // Get the distance from this Vector4D to the other one. - vec_t DistTo(const Vector4D &vOther) const; - - // Get the distance from this Vector4D to the other one squared. - vec_t DistToSqr(const Vector4D &vOther) const; - - // Copy - void CopyToArray(float* rgfl) const; - - // Multiply, add, and assign to this (ie: *this = a + b * scalar). This - // is about 12% faster than the actual Vector4D equation (because it's done per-component - // rather than per-Vector4D). - void MulAdd(Vector4D const& a, Vector4D const& b, float scalar); - - // Dot product. - vec_t Dot(Vector4D const& vOther) const; - - // No copy constructors allowed if we're in optimal mode -#ifdef VECTOR_NO_SLOW_OPERATIONS -private: -#else -public: -#endif - Vector4D(Vector4D const& vOther); - - // No assignment operators either... - Vector4D& operator=( Vector4D const& src ); -}; - -const Vector4D vec4_origin( 0.0f, 0.0f, 0.0f, 0.0f ); -const Vector4D vec4_invalid( FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX ); - -//----------------------------------------------------------------------------- -// SSE optimized routines -//----------------------------------------------------------------------------- - -#ifdef _WIN32 -class __declspec(align(16)) Vector4DAligned : public Vector4D -#elif _LINUX -class __attribute__((aligned(16))) Vector4DAligned : public Vector4D -#endif -{ -public: - Vector4DAligned(void) {} - Vector4DAligned( vec_t X, vec_t Y, vec_t Z, vec_t W ); - - inline void Set( vec_t X, vec_t Y, vec_t Z, vec_t W ); - inline void InitZero( void ); - - inline __m128 &AsM128() { return *(__m128*)&x; } - inline const __m128 &AsM128() const { return *(const __m128*)&x; } - -private: - // No copy constructors allowed if we're in optimal mode - Vector4DAligned( Vector4DAligned const& vOther ); - - // No assignment operators either... - Vector4DAligned& operator=( Vector4DAligned const& src ); -}; - -//----------------------------------------------------------------------------- -// Vector4D related operations -//----------------------------------------------------------------------------- - -// Vector4D clear -void Vector4DClear( Vector4D& a ); - -// Copy -void Vector4DCopy( Vector4D const& src, Vector4D& dst ); - -// Vector4D arithmetic -void Vector4DAdd( Vector4D const& a, Vector4D const& b, Vector4D& result ); -void Vector4DSubtract( Vector4D const& a, Vector4D const& b, Vector4D& result ); -void Vector4DMultiply( Vector4D const& a, vec_t b, Vector4D& result ); -void Vector4DMultiply( Vector4D const& a, Vector4D const& b, Vector4D& result ); -void Vector4DDivide( Vector4D const& a, vec_t b, Vector4D& result ); -void Vector4DDivide( Vector4D const& a, Vector4D const& b, Vector4D& result ); -void Vector4DMA( Vector4D const& start, float s, Vector4D const& dir, Vector4D& result ); - -// Vector4DAligned arithmetic -void Vector4DMultiplyAligned( Vector4DAligned const& a, vec_t b, Vector4DAligned& result ); - - -#define Vector4DExpand( v ) (v).x, (v).y, (v).z, (v).w - -// Normalization -vec_t Vector4DNormalize( Vector4D& v ); - -// Length -vec_t Vector4DLength( Vector4D const& v ); - -// Dot Product -vec_t DotProduct4D(Vector4D const& a, Vector4D const& b); - -// Linearly interpolate between two vectors -void Vector4DLerp(Vector4D const& src1, Vector4D const& src2, vec_t t, Vector4D& dest ); - - -//----------------------------------------------------------------------------- -// -// Inlined Vector4D methods -// -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// constructors -//----------------------------------------------------------------------------- - -inline Vector4D::Vector4D(void) -{ -#ifdef _DEBUG - // Initialize to NAN to catch errors - x = y = z = w = VEC_T_NAN; -#endif -} - -inline Vector4D::Vector4D(vec_t X, vec_t Y, vec_t Z, vec_t W ) -{ - x = X; y = Y; z = Z; w = W; - Assert( IsValid() ); -} - -inline Vector4D::Vector4D(const float *pFloat) -{ - Assert( pFloat ); - x = pFloat[0]; y = pFloat[1]; z = pFloat[2]; w = pFloat[3]; - Assert( IsValid() ); -} - - -//----------------------------------------------------------------------------- -// copy constructor -//----------------------------------------------------------------------------- - -inline Vector4D::Vector4D(const Vector4D &vOther) -{ - Assert( vOther.IsValid() ); - x = vOther.x; y = vOther.y; z = vOther.z; w = vOther.w; -} - -//----------------------------------------------------------------------------- -// initialization -//----------------------------------------------------------------------------- - -inline void Vector4D::Init( vec_t ix, vec_t iy, vec_t iz, vec_t iw ) -{ - x = ix; y = iy; z = iz; w = iw; - Assert( IsValid() ); -} - -inline void Vector4D::Random( vec_t minVal, vec_t maxVal ) -{ - x = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal); - y = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal); - z = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal); - w = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal); -} - -inline void Vector4DClear( Vector4D& a ) -{ - a.x = a.y = a.z = a.w = 0.0f; -} - -//----------------------------------------------------------------------------- -// assignment -//----------------------------------------------------------------------------- - -inline Vector4D& Vector4D::operator=(const Vector4D &vOther) -{ - Assert( vOther.IsValid() ); - x=vOther.x; y=vOther.y; z=vOther.z; w=vOther.w; - return *this; -} - -//----------------------------------------------------------------------------- -// Array access -//----------------------------------------------------------------------------- - -inline vec_t& Vector4D::operator[](int i) -{ - Assert( (i >= 0) && (i < 4) ); - return ((vec_t*)this)[i]; -} - -inline vec_t Vector4D::operator[](int i) const -{ - Assert( (i >= 0) && (i < 4) ); - return ((vec_t*)this)[i]; -} - -//----------------------------------------------------------------------------- -// Cast to Vector and Vector2D... -//----------------------------------------------------------------------------- - -inline Vector& Vector4D::AsVector3D() -{ - return *(Vector*)this; -} - -inline Vector const& Vector4D::AsVector3D() const -{ - return *(Vector const*)this; -} - -inline Vector2D& Vector4D::AsVector2D() -{ - return *(Vector2D*)this; -} - -inline Vector2D const& Vector4D::AsVector2D() const -{ - return *(Vector2D const*)this; -} - -//----------------------------------------------------------------------------- -// Base address... -//----------------------------------------------------------------------------- - -inline vec_t* Vector4D::Base() -{ - return (vec_t*)this; -} - -inline vec_t const* Vector4D::Base() const -{ - return (vec_t const*)this; -} - -//----------------------------------------------------------------------------- -// IsValid? -//----------------------------------------------------------------------------- - -inline bool Vector4D::IsValid() const -{ - return IsFinite(x) && IsFinite(y) && IsFinite(z) && IsFinite(w); -} - -//----------------------------------------------------------------------------- -// comparison -//----------------------------------------------------------------------------- - -inline bool Vector4D::operator==( Vector4D const& src ) const -{ - Assert( src.IsValid() && IsValid() ); - return (src.x == x) && (src.y == y) && (src.z == z) && (src.w == w); -} - -inline bool Vector4D::operator!=( Vector4D const& src ) const -{ - Assert( src.IsValid() && IsValid() ); - return (src.x != x) || (src.y != y) || (src.z != z) || (src.w != w); -} - - -//----------------------------------------------------------------------------- -// Copy -//----------------------------------------------------------------------------- - -inline void Vector4DCopy( Vector4D const& src, Vector4D& dst ) -{ - Assert( src.IsValid() ); - dst.x = src.x; - dst.y = src.y; - dst.z = src.z; - dst.w = src.w; -} - -inline void Vector4D::CopyToArray(float* rgfl) const -{ - Assert( IsValid() ); - Assert( rgfl ); - rgfl[0] = x; rgfl[1] = y; rgfl[2] = z; rgfl[3] = w; -} - -//----------------------------------------------------------------------------- -// standard math operations -//----------------------------------------------------------------------------- - -inline void Vector4D::Negate() -{ - Assert( IsValid() ); - x = -x; y = -y; z = -z; w = -w; -} - -inline Vector4D& Vector4D::operator+=(const Vector4D& v) -{ - Assert( IsValid() && v.IsValid() ); - x+=v.x; y+=v.y; z += v.z; w += v.w; - return *this; -} - -inline Vector4D& Vector4D::operator-=(const Vector4D& v) -{ - Assert( IsValid() && v.IsValid() ); - x-=v.x; y-=v.y; z -= v.z; w -= v.w; - return *this; -} - -inline Vector4D& Vector4D::operator*=(float fl) -{ - x *= fl; - y *= fl; - z *= fl; - w *= fl; - Assert( IsValid() ); - return *this; -} - -inline Vector4D& Vector4D::operator*=(Vector4D const& v) -{ - x *= v.x; - y *= v.y; - z *= v.z; - w *= v.w; - Assert( IsValid() ); - return *this; -} - -inline Vector4D& Vector4D::operator/=(float fl) -{ - Assert( fl != 0.0f ); - float oofl = 1.0f / fl; - x *= oofl; - y *= oofl; - z *= oofl; - w *= oofl; - Assert( IsValid() ); - return *this; -} - -inline Vector4D& Vector4D::operator/=(Vector4D const& v) -{ - Assert( v.x != 0.0f && v.y != 0.0f && v.z != 0.0f && v.w != 0.0f ); - x /= v.x; - y /= v.y; - z /= v.z; - w /= v.w; - Assert( IsValid() ); - return *this; -} - -inline void Vector4DAdd( Vector4D const& a, Vector4D const& b, Vector4D& c ) -{ - Assert( a.IsValid() && b.IsValid() ); - c.x = a.x + b.x; - c.y = a.y + b.y; - c.z = a.z + b.z; - c.w = a.w + b.w; -} - -inline void Vector4DSubtract( Vector4D const& a, Vector4D const& b, Vector4D& c ) -{ - Assert( a.IsValid() && b.IsValid() ); - c.x = a.x - b.x; - c.y = a.y - b.y; - c.z = a.z - b.z; - c.w = a.w - b.w; -} - -inline void Vector4DMultiply( Vector4D const& a, vec_t b, Vector4D& c ) -{ - Assert( a.IsValid() && IsFinite(b) ); - c.x = a.x * b; - c.y = a.y * b; - c.z = a.z * b; - c.w = a.w * b; -} - -inline void Vector4DMultiply( Vector4D const& a, Vector4D const& b, Vector4D& c ) -{ - Assert( a.IsValid() && b.IsValid() ); - c.x = a.x * b.x; - c.y = a.y * b.y; - c.z = a.z * b.z; - c.w = a.w * b.w; -} - -inline void Vector4DDivide( Vector4D const& a, vec_t b, Vector4D& c ) -{ - Assert( a.IsValid() ); - Assert( b != 0.0f ); - vec_t oob = 1.0f / b; - c.x = a.x * oob; - c.y = a.y * oob; - c.z = a.z * oob; - c.w = a.w * oob; -} - -inline void Vector4DDivide( Vector4D const& a, Vector4D const& b, Vector4D& c ) -{ - Assert( a.IsValid() ); - Assert( (b.x != 0.0f) && (b.y != 0.0f) && (b.z != 0.0f) && (b.w != 0.0f) ); - c.x = a.x / b.x; - c.y = a.y / b.y; - c.z = a.z / b.z; - c.w = a.w / b.w; -} - -inline void Vector4DMA( Vector4D const& start, float s, Vector4D const& dir, Vector4D& result ) -{ - Assert( start.IsValid() && IsFinite(s) && dir.IsValid() ); - result.x = start.x + s*dir.x; - result.y = start.y + s*dir.y; - result.z = start.z + s*dir.z; - result.w = start.w + s*dir.w; -} - -// FIXME: Remove -// For backwards compatability -inline void Vector4D::MulAdd(Vector4D const& a, Vector4D const& b, float scalar) -{ - x = a.x + b.x * scalar; - y = a.y + b.y * scalar; - z = a.z + b.z * scalar; - w = a.w + b.w * scalar; -} - -inline void Vector4DLerp(const Vector4D& src1, const Vector4D& src2, vec_t t, Vector4D& dest ) -{ - dest[0] = src1[0] + (src2[0] - src1[0]) * t; - dest[1] = src1[1] + (src2[1] - src1[1]) * t; - dest[2] = src1[2] + (src2[2] - src1[2]) * t; - dest[3] = src1[3] + (src2[3] - src1[3]) * t; -} - -//----------------------------------------------------------------------------- -// dot, cross -//----------------------------------------------------------------------------- - -inline vec_t DotProduct4D(const Vector4D& a, const Vector4D& b) -{ - Assert( a.IsValid() && b.IsValid() ); - return( a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w ); -} - -// for backwards compatability -inline vec_t Vector4D::Dot( Vector4D const& vOther ) const -{ - return DotProduct4D( *this, vOther ); -} - - -//----------------------------------------------------------------------------- -// length -//----------------------------------------------------------------------------- - -inline vec_t Vector4DLength( Vector4D const& v ) -{ - Assert( v.IsValid() ); - return (vec_t)FastSqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); -} - -inline vec_t Vector4D::LengthSqr(void) const -{ - Assert( IsValid() ); - return (x*x + y*y + z*z + w*w); -} - -inline vec_t Vector4D::Length(void) const -{ - return Vector4DLength( *this ); -} - - -//----------------------------------------------------------------------------- -// Normalization -//----------------------------------------------------------------------------- - -// FIXME: Can't use until we're un-macroed in mathlib.h -inline vec_t Vector4DNormalize( Vector4D& v ) -{ - Assert( v.IsValid() ); - vec_t l = v.Length(); - if (l != 0.0f) - { - v /= l; - } - else - { - v.x = v.y = v.z = v.w = 0.0f; - } - return l; -} - -//----------------------------------------------------------------------------- -// Get the distance from this Vector4D to the other one -//----------------------------------------------------------------------------- - -inline vec_t Vector4D::DistTo(const Vector4D &vOther) const -{ - Vector4D delta; - Vector4DSubtract( *this, vOther, delta ); - return delta.Length(); -} - -inline vec_t Vector4D::DistToSqr(const Vector4D &vOther) const -{ - Vector4D delta; - Vector4DSubtract( *this, vOther, delta ); - return delta.LengthSqr(); -} - - -//----------------------------------------------------------------------------- -// Vector4DAligned routines -//----------------------------------------------------------------------------- - -inline Vector4DAligned::Vector4DAligned( vec_t X, vec_t Y, vec_t Z, vec_t W ) -{ - x = X; y = Y; z = Z; w = W; - Assert( IsValid() ); -} - -inline void Vector4DAligned::Set( vec_t X, vec_t Y, vec_t Z, vec_t W ) -{ - x = X; y = Y; z = Z; w = W; - Assert( IsValid() ); -} - -inline void Vector4DAligned::InitZero( void ) -{ -#if !defined( _X360 ) - this->AsM128() = _mm_set1_ps( 0.0f ); -#else - this->AsM128() = __vspltisw( 0 ); -#endif - Assert( IsValid() ); -} - -inline void Vector4DMultiplyAligned( Vector4DAligned const& a, Vector4DAligned const& b, Vector4DAligned& c ) -{ - Assert( a.IsValid() && b.IsValid() ); -#if !defined( _X360 ) - c.x = a.x * b.x; - c.y = a.y * b.y; - c.z = a.z * b.z; - c.w = a.w * b.w; -#else - c.AsM128() = __vmulfp( a.AsM128(), b.AsM128() ); -#endif -} - -inline void Vector4DWeightMAD( vec_t w, Vector4DAligned const& vInA, Vector4DAligned& vOutA, Vector4DAligned const& vInB, Vector4DAligned& vOutB ) -{ - Assert( vInA.IsValid() && vInB.IsValid() && IsFinite(w) ); - -#if !defined( _X360 ) - vOutA.x += vInA.x * w; - vOutA.y += vInA.y * w; - vOutA.z += vInA.z * w; - vOutA.w += vInA.w * w; - - vOutB.x += vInB.x * w; - vOutB.y += vInB.y * w; - vOutB.z += vInB.z * w; - vOutB.w += vInB.w * w; -#else - __vector4 temp; - - temp = __lvlx( &w, 0 ); - temp = __vspltw( temp, 0 ); - - vOutA.AsM128() = __vmaddfp( vInA.AsM128(), temp, vOutA.AsM128() ); - vOutB.AsM128() = __vmaddfp( vInB.AsM128(), temp, vOutB.AsM128() ); -#endif -} - -inline void Vector4DWeightMADSSE( vec_t w, Vector4DAligned const& vInA, Vector4DAligned& vOutA, Vector4DAligned const& vInB, Vector4DAligned& vOutB ) -{ - Assert( vInA.IsValid() && vInB.IsValid() && IsFinite(w) ); - -#if !defined( _X360 ) - // Replicate scalar float out to 4 components - __m128 packed = _mm_set1_ps( w ); - - // 4D SSE Vector MAD - vOutA.AsM128() = _mm_add_ps( vOutA.AsM128(), _mm_mul_ps( vInA.AsM128(), packed ) ); - vOutB.AsM128() = _mm_add_ps( vOutB.AsM128(), _mm_mul_ps( vInB.AsM128(), packed ) ); -#else - __vector4 temp; - - temp = __lvlx( &w, 0 ); - temp = __vspltw( temp, 0 ); - - vOutA.AsM128() = __vmaddfp( vInA.AsM128(), temp, vOutA.AsM128() ); - vOutB.AsM128() = __vmaddfp( vInB.AsM128(), temp, vOutB.AsM128() ); -#endif -} - -#endif // VECTOR4D_H - diff --git a/Resources/NetHook/mathlib/vmatrix.h b/Resources/NetHook/mathlib/vmatrix.h deleted file mode 100644 index 6915e81d..00000000 --- a/Resources/NetHook/mathlib/vmatrix.h +++ /dev/null @@ -1,938 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -// -// VMatrix always postmultiply vectors as in Ax = b. -// Given a set of basis vectors ((F)orward, (L)eft, (U)p), and a (T)ranslation, -// a matrix to transform a vector into that space looks like this: -// Fx Lx Ux Tx -// Fy Ly Uy Ty -// Fz Lz Uz Tz -// 0 0 0 1 - -// Note that concatenating matrices needs to multiply them in reverse order. -// ie: if I want to apply matrix A, B, then C, the equation needs to look like this: -// C * B * A * v -// ie: -// v = A * v; -// v = B * v; -// v = C * v; -//============================================================================= - -#ifndef VMATRIX_H -#define VMATRIX_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include "mathlib/vector.h" -#include "mathlib/vplane.h" -#include "mathlib/vector4d.h" -#include "mathlib/mathlib.h" - -struct cplane_t; - - -class VMatrix -{ -public: - - VMatrix(); - VMatrix( - vec_t m00, vec_t m01, vec_t m02, vec_t m03, - vec_t m10, vec_t m11, vec_t m12, vec_t m13, - vec_t m20, vec_t m21, vec_t m22, vec_t m23, - vec_t m30, vec_t m31, vec_t m32, vec_t m33 - ); - - // Creates a matrix where the X axis = forward - // the Y axis = left, and the Z axis = up - VMatrix( const Vector& forward, const Vector& left, const Vector& up ); - - // Construct from a 3x4 matrix - VMatrix( const matrix3x4_t& matrix3x4 ); - - // Set the values in the matrix. - void Init( - vec_t m00, vec_t m01, vec_t m02, vec_t m03, - vec_t m10, vec_t m11, vec_t m12, vec_t m13, - vec_t m20, vec_t m21, vec_t m22, vec_t m23, - vec_t m30, vec_t m31, vec_t m32, vec_t m33 - ); - - - // Initialize from a 3x4 - void Init( const matrix3x4_t& matrix3x4 ); - - // array access - inline float* operator[](int i) - { - return m[i]; - } - - inline const float* operator[](int i) const - { - return m[i]; - } - - // Get a pointer to m[0][0] - inline float *Base() - { - return &m[0][0]; - } - - inline const float *Base() const - { - return &m[0][0]; - } - - void SetLeft(const Vector &vLeft); - void SetUp(const Vector &vUp); - void SetForward(const Vector &vForward); - - void GetBasisVectors(Vector &vForward, Vector &vLeft, Vector &vUp) const; - void SetBasisVectors(const Vector &vForward, const Vector &vLeft, const Vector &vUp); - - // Get/set the translation. - Vector & GetTranslation( Vector &vTrans ) const; - void SetTranslation(const Vector &vTrans); - - void PreTranslate(const Vector &vTrans); - void PostTranslate(const Vector &vTrans); - - matrix3x4_t& As3x4(); - const matrix3x4_t& As3x4() const; - void CopyFrom3x4( const matrix3x4_t &m3x4 ); - void Set3x4( matrix3x4_t& matrix3x4 ) const; - - bool operator==( const VMatrix& src ) const; - bool operator!=( const VMatrix& src ) const { return !( *this == src ); } - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // Access the basis vectors. - Vector GetLeft() const; - Vector GetUp() const; - Vector GetForward() const; - Vector GetTranslation() const; -#endif - - -// Matrix->vector operations. -public: - // Multiply by a 3D vector (same as operator*). - void V3Mul(const Vector &vIn, Vector &vOut) const; - - // Multiply by a 4D vector. - void V4Mul(const Vector4D &vIn, Vector4D &vOut) const; - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // Applies the rotation (ignores translation in the matrix). (This just calls VMul3x3). - Vector ApplyRotation(const Vector &vVec) const; - - // Multiply by a vector (divides by w, assumes input w is 1). - Vector operator*(const Vector &vVec) const; - - // Multiply by the upper 3x3 part of the matrix (ie: only apply rotation). - Vector VMul3x3(const Vector &vVec) const; - - // Apply the inverse (transposed) rotation (only works on pure rotation matrix) - Vector VMul3x3Transpose(const Vector &vVec) const; - - // Multiply by the upper 3 rows. - Vector VMul4x3(const Vector &vVec) const; - - // Apply the inverse (transposed) transformation (only works on pure rotation/translation) - Vector VMul4x3Transpose(const Vector &vVec) const; -#endif - - -// Matrix->plane operations. -public: - // Transform the plane. The matrix can only contain translation and rotation. - void TransformPlane( const VPlane &inPlane, VPlane &outPlane ) const; - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // Just calls TransformPlane and returns the result. - VPlane operator*(const VPlane &thePlane) const; -#endif - -// Matrix->matrix operations. -public: - - VMatrix& operator=(const VMatrix &mOther); - - // Multiply two matrices (out = this * vm). - void MatrixMul( const VMatrix &vm, VMatrix &out ) const; - - // Add two matrices. - const VMatrix& operator+=(const VMatrix &other); - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // Just calls MatrixMul and returns the result. - VMatrix operator*(const VMatrix &mOther) const; - - // Add/Subtract two matrices. - VMatrix operator+(const VMatrix &other) const; - VMatrix operator-(const VMatrix &other) const; - - // Negation. - VMatrix operator-() const; - - // Return inverse matrix. Be careful because the results are undefined - // if the matrix doesn't have an inverse (ie: InverseGeneral returns false). - VMatrix operator~() const; -#endif - -// Matrix operations. -public: - // Set to identity. - void Identity(); - - bool IsIdentity() const; - - // Setup a matrix for origin and angles. - void SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles ); - - // General inverse. This may fail so check the return! - bool InverseGeneral(VMatrix &vInverse) const; - - // Does a fast inverse, assuming the matrix only contains translation and rotation. - void InverseTR( VMatrix &mRet ) const; - - // Usually used for debug checks. Returns true if the upper 3x3 contains - // unit vectors and they are all orthogonal. - bool IsRotationMatrix() const; - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // This calls the other InverseTR and returns the result. - VMatrix InverseTR() const; - - // Get the scale of the matrix's basis vectors. - Vector GetScale() const; - - // (Fast) multiply by a scaling matrix setup from vScale. - VMatrix Scale(const Vector &vScale); - - // Normalize the basis vectors. - VMatrix NormalizeBasisVectors() const; - - // Transpose. - VMatrix Transpose() const; - - // Transpose upper-left 3x3. - VMatrix Transpose3x3() const; -#endif - -public: - // The matrix. - vec_t m[4][4]; -}; - - - -//----------------------------------------------------------------------------- -// Helper functions. -//----------------------------------------------------------------------------- - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -// Setup an identity matrix. -VMatrix SetupMatrixIdentity(); - -// Setup as a scaling matrix. -VMatrix SetupMatrixScale(const Vector &vScale); - -// Setup a translation matrix. -VMatrix SetupMatrixTranslation(const Vector &vTranslation); - -// Setup a matrix to reflect around the plane. -VMatrix SetupMatrixReflection(const VPlane &thePlane); - -// Setup a matrix to project from vOrigin onto thePlane. -VMatrix SetupMatrixProjection(const Vector &vOrigin, const VPlane &thePlane); - -// Setup a matrix to rotate the specified amount around the specified axis. -VMatrix SetupMatrixAxisRot(const Vector &vAxis, vec_t fDegrees); - -// Setup a matrix from euler angles. Just sets identity and calls MatrixAngles. -VMatrix SetupMatrixAngles(const QAngle &vAngles); - -// Setup a matrix for origin and angles. -VMatrix SetupMatrixOrgAngles(const Vector &origin, const QAngle &vAngles); - -#endif - -#define VMatToString(mat) (static_cast(CFmtStr("[ (%f, %f, %f), (%f, %f, %f), (%f, %f, %f), (%f, %f, %f) ]", mat.m[0][0], mat.m[0][1], mat.m[0][2], mat.m[0][3], mat.m[1][0], mat.m[1][1], mat.m[1][2], mat.m[1][3], mat.m[2][0], mat.m[2][1], mat.m[2][2], mat.m[2][3], mat.m[3][0], mat.m[3][1], mat.m[3][2], mat.m[3][3] ))) // ** Note: this generates a temporary, don't hold reference! - -//----------------------------------------------------------------------------- -// Returns the point at the intersection on the 3 planes. -// Returns false if it can't be solved (2 or more planes are parallel). -//----------------------------------------------------------------------------- -bool PlaneIntersection( const VPlane &vp1, const VPlane &vp2, const VPlane &vp3, Vector &vOut ); - - -//----------------------------------------------------------------------------- -// These methods are faster. Use them if you want faster code -//----------------------------------------------------------------------------- -void MatrixSetIdentity( VMatrix &dst ); -void MatrixTranspose( const VMatrix& src, VMatrix& dst ); -void MatrixCopy( const VMatrix& src, VMatrix& dst ); -void MatrixMultiply( const VMatrix& src1, const VMatrix& src2, VMatrix& dst ); - -// Accessors -void MatrixGetColumn( const VMatrix &src, int nCol, Vector *pColumn ); -void MatrixSetColumn( VMatrix &src, int nCol, const Vector &column ); -void MatrixGetRow( const VMatrix &src, int nCol, Vector *pColumn ); -void MatrixSetRow( VMatrix &src, int nCol, const Vector &column ); - -// Vector3DMultiply treats src2 as if it's a direction vector -void Vector3DMultiply( const VMatrix& src1, const Vector& src2, Vector& dst ); - -// Vector3DMultiplyPosition treats src2 as if it's a point (adds the translation) -inline void Vector3DMultiplyPosition( const VMatrix& src1, const VectorByValue src2, Vector& dst ); - -// Vector3DMultiplyPositionProjective treats src2 as if it's a point -// and does the perspective divide at the end -void Vector3DMultiplyPositionProjective( const VMatrix& src1, const Vector &src2, Vector& dst ); - -// Vector3DMultiplyPosition treats src2 as if it's a direction -// and does the perspective divide at the end -// NOTE: src1 had better be an inverse transpose to use this correctly -void Vector3DMultiplyProjective( const VMatrix& src1, const Vector &src2, Vector& dst ); - -void Vector4DMultiply( const VMatrix& src1, const Vector4D& src2, Vector4D& dst ); - -// Same as Vector4DMultiply except that src2 has an implicit W of 1 -void Vector4DMultiplyPosition( const VMatrix& src1, const Vector &src2, Vector4D& dst ); - -// Multiplies the vector by the transpose of the matrix -void Vector3DMultiplyTranspose( const VMatrix& src1, const Vector& src2, Vector& dst ); -void Vector4DMultiplyTranspose( const VMatrix& src1, const Vector4D& src2, Vector4D& dst ); - -// Transform a plane -void MatrixTransformPlane( const VMatrix &src, const cplane_t &inPlane, cplane_t &outPlane ); - -// Transform a plane that has an axis-aligned normal -void MatrixTransformAxisAlignedPlane( const VMatrix &src, int nDim, float flSign, float flDist, cplane_t &outPlane ); - -void MatrixBuildTranslation( VMatrix& dst, float x, float y, float z ); -void MatrixBuildTranslation( VMatrix& dst, const Vector &translation ); - -inline void MatrixTranslate( VMatrix& dst, const Vector &translation ) -{ - VMatrix matTranslation, temp; - MatrixBuildTranslation( matTranslation, translation ); - MatrixMultiply( dst, matTranslation, temp ); - dst = temp; -} - - -void MatrixBuildRotationAboutAxis( VMatrix& dst, const Vector& vAxisOfRot, float angleDegrees ); -void MatrixBuildRotateZ( VMatrix& dst, float angleDegrees ); - -inline void MatrixRotate( VMatrix& dst, const Vector& vAxisOfRot, float angleDegrees ) -{ - VMatrix rotation, temp; - MatrixBuildRotationAboutAxis( rotation, vAxisOfRot, angleDegrees ); - MatrixMultiply( dst, rotation, temp ); - dst = temp; -} - -// Builds a rotation matrix that rotates one direction vector into another -void MatrixBuildRotation( VMatrix &dst, const Vector& initialDirection, const Vector& finalDirection ); - -// Builds a scale matrix -void MatrixBuildScale( VMatrix &dst, float x, float y, float z ); -void MatrixBuildScale( VMatrix &dst, const Vector& scale ); - -// Build a perspective matrix. -// zNear and zFar are assumed to be positive. -// You end up looking down positive Z, X is to the right, Y is up. -// X range: [0..1] -// Y range: [0..1] -// Z range: [0..1] -void MatrixBuildPerspective( VMatrix &dst, float fovX, float fovY, float zNear, float zFar ); - -//----------------------------------------------------------------------------- -// Given a projection matrix, take the extremes of the space in transformed into world space and -// get a bounding box. -//----------------------------------------------------------------------------- -void CalculateAABBFromProjectionMatrix( const VMatrix &worldToVolume, Vector *pMins, Vector *pMaxs ); - -//----------------------------------------------------------------------------- -// Given a projection matrix, take the extremes of the space in transformed into world space and -// get a bounding sphere. -//----------------------------------------------------------------------------- -void CalculateSphereFromProjectionMatrix( const VMatrix &worldToVolume, Vector *pCenter, float *pflRadius ); - -//----------------------------------------------------------------------------- -// Given an inverse projection matrix, take the extremes of the space in transformed into world space and -// get a bounding box. -//----------------------------------------------------------------------------- -void CalculateAABBFromProjectionMatrixInverse( const VMatrix &volumeToWorld, Vector *pMins, Vector *pMaxs ); - -//----------------------------------------------------------------------------- -// Given an inverse projection matrix, take the extremes of the space in transformed into world space and -// get a bounding sphere. -//----------------------------------------------------------------------------- -void CalculateSphereFromProjectionMatrixInverse( const VMatrix &volumeToWorld, Vector *pCenter, float *pflRadius ); - -//----------------------------------------------------------------------------- -// Calculate frustum planes given a clip->world space transform. -//----------------------------------------------------------------------------- -void FrustumPlanesFromMatrix( const VMatrix &clipToWorld, Frustum_t &frustum ); - -//----------------------------------------------------------------------------- -// Setup a matrix from euler angles. -//----------------------------------------------------------------------------- -void MatrixFromAngles( const QAngle& vAngles, VMatrix& dst ); - -//----------------------------------------------------------------------------- -// Creates euler angles from a matrix -//----------------------------------------------------------------------------- -void MatrixToAngles( const VMatrix& src, QAngle& vAngles ); - -//----------------------------------------------------------------------------- -// Does a fast inverse, assuming the matrix only contains translation and rotation. -//----------------------------------------------------------------------------- -void MatrixInverseTR( const VMatrix& src, VMatrix &dst ); - -//----------------------------------------------------------------------------- -// Inverts any matrix at all -//----------------------------------------------------------------------------- -bool MatrixInverseGeneral(const VMatrix& src, VMatrix& dst); - -//----------------------------------------------------------------------------- -// Computes the inverse transpose -//----------------------------------------------------------------------------- -void MatrixInverseTranspose( const VMatrix& src, VMatrix& dst ); - - - -//----------------------------------------------------------------------------- -// VMatrix inlines. -//----------------------------------------------------------------------------- -inline VMatrix::VMatrix() -{ -} - -inline VMatrix::VMatrix( - vec_t m00, vec_t m01, vec_t m02, vec_t m03, - vec_t m10, vec_t m11, vec_t m12, vec_t m13, - vec_t m20, vec_t m21, vec_t m22, vec_t m23, - vec_t m30, vec_t m31, vec_t m32, vec_t m33) -{ - Init( - m00, m01, m02, m03, - m10, m11, m12, m13, - m20, m21, m22, m23, - m30, m31, m32, m33 - ); -} - - -inline VMatrix::VMatrix( const matrix3x4_t& matrix3x4 ) -{ - Init( matrix3x4 ); -} - - -//----------------------------------------------------------------------------- -// Creates a matrix where the X axis = forward -// the Y axis = left, and the Z axis = up -//----------------------------------------------------------------------------- -inline VMatrix::VMatrix( const Vector& xAxis, const Vector& yAxis, const Vector& zAxis ) -{ - Init( - xAxis.x, yAxis.x, zAxis.x, 0.0f, - xAxis.y, yAxis.y, zAxis.y, 0.0f, - xAxis.z, yAxis.z, zAxis.z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - ); -} - - -inline void VMatrix::Init( - vec_t m00, vec_t m01, vec_t m02, vec_t m03, - vec_t m10, vec_t m11, vec_t m12, vec_t m13, - vec_t m20, vec_t m21, vec_t m22, vec_t m23, - vec_t m30, vec_t m31, vec_t m32, vec_t m33 - ) -{ - m[0][0] = m00; - m[0][1] = m01; - m[0][2] = m02; - m[0][3] = m03; - - m[1][0] = m10; - m[1][1] = m11; - m[1][2] = m12; - m[1][3] = m13; - - m[2][0] = m20; - m[2][1] = m21; - m[2][2] = m22; - m[2][3] = m23; - - m[3][0] = m30; - m[3][1] = m31; - m[3][2] = m32; - m[3][3] = m33; -} - - -//----------------------------------------------------------------------------- -// Initialize from a 3x4 -//----------------------------------------------------------------------------- -inline void VMatrix::Init( const matrix3x4_t& matrix3x4 ) -{ - memcpy(m, matrix3x4.Base(), sizeof( matrix3x4_t ) ); - - m[3][0] = 0.0f; - m[3][1] = 0.0f; - m[3][2] = 0.0f; - m[3][3] = 1.0f; -} - - -//----------------------------------------------------------------------------- -// Methods related to the basis vectors of the matrix -//----------------------------------------------------------------------------- - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline Vector VMatrix::GetForward() const -{ - return Vector(m[0][0], m[1][0], m[2][0]); -} - -inline Vector VMatrix::GetLeft() const -{ - return Vector(m[0][1], m[1][1], m[2][1]); -} - -inline Vector VMatrix::GetUp() const -{ - return Vector(m[0][2], m[1][2], m[2][2]); -} - -#endif - -inline void VMatrix::SetForward(const Vector &vForward) -{ - m[0][0] = vForward.x; - m[1][0] = vForward.y; - m[2][0] = vForward.z; -} - -inline void VMatrix::SetLeft(const Vector &vLeft) -{ - m[0][1] = vLeft.x; - m[1][1] = vLeft.y; - m[2][1] = vLeft.z; -} - -inline void VMatrix::SetUp(const Vector &vUp) -{ - m[0][2] = vUp.x; - m[1][2] = vUp.y; - m[2][2] = vUp.z; -} - -inline void VMatrix::GetBasisVectors(Vector &vForward, Vector &vLeft, Vector &vUp) const -{ - vForward.Init( m[0][0], m[1][0], m[2][0] ); - vLeft.Init( m[0][1], m[1][1], m[2][1] ); - vUp.Init( m[0][2], m[1][2], m[2][2] ); -} - -inline void VMatrix::SetBasisVectors(const Vector &vForward, const Vector &vLeft, const Vector &vUp) -{ - SetForward(vForward); - SetLeft(vLeft); - SetUp(vUp); -} - - -//----------------------------------------------------------------------------- -// Methods related to the translation component of the matrix -//----------------------------------------------------------------------------- -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline Vector VMatrix::GetTranslation() const -{ - return Vector(m[0][3], m[1][3], m[2][3]); -} - -#endif - -inline Vector& VMatrix::GetTranslation( Vector &vTrans ) const -{ - vTrans.x = m[0][3]; - vTrans.y = m[1][3]; - vTrans.z = m[2][3]; - return vTrans; -} - -inline void VMatrix::SetTranslation(const Vector &vTrans) -{ - m[0][3] = vTrans.x; - m[1][3] = vTrans.y; - m[2][3] = vTrans.z; -} - - -//----------------------------------------------------------------------------- -// appply translation to this matrix in the input space -//----------------------------------------------------------------------------- -inline void VMatrix::PreTranslate(const Vector &vTrans) -{ - Vector tmp; - Vector3DMultiplyPosition( *this, vTrans, tmp ); - m[0][3] = tmp.x; - m[1][3] = tmp.y; - m[2][3] = tmp.z; -} - - -//----------------------------------------------------------------------------- -// appply translation to this matrix in the output space -//----------------------------------------------------------------------------- -inline void VMatrix::PostTranslate(const Vector &vTrans) -{ - m[0][3] += vTrans.x; - m[1][3] += vTrans.y; - m[2][3] += vTrans.z; -} - -inline const matrix3x4_t& VMatrix::As3x4() const -{ - return *((const matrix3x4_t*)this); -} - -inline matrix3x4_t& VMatrix::As3x4() -{ - return *((matrix3x4_t*)this); -} - -inline void VMatrix::CopyFrom3x4( const matrix3x4_t &m3x4 ) -{ - memcpy( m, m3x4.Base(), sizeof( matrix3x4_t ) ); - m[3][0] = m[3][1] = m[3][2] = 0; - m[3][3] = 1; -} - -inline void VMatrix::Set3x4( matrix3x4_t& matrix3x4 ) const -{ - memcpy(matrix3x4.Base(), m, sizeof( matrix3x4_t ) ); -} - - -//----------------------------------------------------------------------------- -// Matrix math operations -//----------------------------------------------------------------------------- -inline const VMatrix& VMatrix::operator+=(const VMatrix &other) -{ - for(int i=0; i < 4; i++) - { - for(int j=0; j < 4; j++) - { - m[i][j] += other.m[i][j]; - } - } - - return *this; -} - - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline VMatrix VMatrix::operator+(const VMatrix &other) const -{ - VMatrix ret; - for(int i=0; i < 16; i++) - { - ((float*)ret.m)[i] = ((float*)m)[i] + ((float*)other.m)[i]; - } - return ret; -} - -inline VMatrix VMatrix::operator-(const VMatrix &other) const -{ - VMatrix ret; - - for(int i=0; i < 4; i++) - { - for(int j=0; j < 4; j++) - { - ret.m[i][j] = m[i][j] - other.m[i][j]; - } - } - - return ret; -} - -inline VMatrix VMatrix::operator-() const -{ - VMatrix ret; - for( int i=0; i < 16; i++ ) - { - ((float*)ret.m)[i] = ((float*)m)[i]; - } - return ret; -} - -#endif // VECTOR_NO_SLOW_OPERATIONS - - -//----------------------------------------------------------------------------- -// Vector transformation -//----------------------------------------------------------------------------- - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline Vector VMatrix::operator*(const Vector &vVec) const -{ - Vector vRet; - vRet.x = m[0][0]*vVec.x + m[0][1]*vVec.y + m[0][2]*vVec.z + m[0][3]; - vRet.y = m[1][0]*vVec.x + m[1][1]*vVec.y + m[1][2]*vVec.z + m[1][3]; - vRet.z = m[2][0]*vVec.x + m[2][1]*vVec.y + m[2][2]*vVec.z + m[2][3]; - - return vRet; -} - -inline Vector VMatrix::VMul4x3(const Vector &vVec) const -{ - Vector vResult; - Vector3DMultiplyPosition( *this, vVec, vResult ); - return vResult; -} - - -inline Vector VMatrix::VMul4x3Transpose(const Vector &vVec) const -{ - Vector tmp = vVec; - tmp.x -= m[0][3]; - tmp.y -= m[1][3]; - tmp.z -= m[2][3]; - - return Vector( - m[0][0]*tmp.x + m[1][0]*tmp.y + m[2][0]*tmp.z, - m[0][1]*tmp.x + m[1][1]*tmp.y + m[2][1]*tmp.z, - m[0][2]*tmp.x + m[1][2]*tmp.y + m[2][2]*tmp.z - ); -} - -inline Vector VMatrix::VMul3x3(const Vector &vVec) const -{ - return Vector( - m[0][0]*vVec.x + m[0][1]*vVec.y + m[0][2]*vVec.z, - m[1][0]*vVec.x + m[1][1]*vVec.y + m[1][2]*vVec.z, - m[2][0]*vVec.x + m[2][1]*vVec.y + m[2][2]*vVec.z - ); -} - -inline Vector VMatrix::VMul3x3Transpose(const Vector &vVec) const -{ - return Vector( - m[0][0]*vVec.x + m[1][0]*vVec.y + m[2][0]*vVec.z, - m[0][1]*vVec.x + m[1][1]*vVec.y + m[2][1]*vVec.z, - m[0][2]*vVec.x + m[1][2]*vVec.y + m[2][2]*vVec.z - ); -} - -#endif // VECTOR_NO_SLOW_OPERATIONS - - -inline void VMatrix::V3Mul(const Vector &vIn, Vector &vOut) const -{ - vec_t rw; - - rw = 1.0f / (m[3][0]*vIn.x + m[3][1]*vIn.y + m[3][2]*vIn.z + m[3][3]); - vOut.x = (m[0][0]*vIn.x + m[0][1]*vIn.y + m[0][2]*vIn.z + m[0][3]) * rw; - vOut.y = (m[1][0]*vIn.x + m[1][1]*vIn.y + m[1][2]*vIn.z + m[1][3]) * rw; - vOut.z = (m[2][0]*vIn.x + m[2][1]*vIn.y + m[2][2]*vIn.z + m[2][3]) * rw; -} - -inline void VMatrix::V4Mul(const Vector4D &vIn, Vector4D &vOut) const -{ - vOut[0] = m[0][0]*vIn[0] + m[0][1]*vIn[1] + m[0][2]*vIn[2] + m[0][3]*vIn[3]; - vOut[1] = m[1][0]*vIn[0] + m[1][1]*vIn[1] + m[1][2]*vIn[2] + m[1][3]*vIn[3]; - vOut[2] = m[2][0]*vIn[0] + m[2][1]*vIn[1] + m[2][2]*vIn[2] + m[2][3]*vIn[3]; - vOut[3] = m[3][0]*vIn[0] + m[3][1]*vIn[1] + m[3][2]*vIn[2] + m[3][3]*vIn[3]; -} - - -//----------------------------------------------------------------------------- -// Plane transformation -//----------------------------------------------------------------------------- -inline void VMatrix::TransformPlane( const VPlane &inPlane, VPlane &outPlane ) const -{ - Vector vTrans; - Vector3DMultiply( *this, inPlane.m_Normal, outPlane.m_Normal ); - outPlane.m_Dist = inPlane.m_Dist * DotProduct( outPlane.m_Normal, outPlane.m_Normal ); - outPlane.m_Dist += DotProduct( outPlane.m_Normal, GetTranslation( vTrans ) ); -} - - -//----------------------------------------------------------------------------- -// Other random stuff -//----------------------------------------------------------------------------- -inline void VMatrix::Identity() -{ - MatrixSetIdentity( *this ); -} - - -inline bool VMatrix::IsIdentity() const -{ - return - m[0][0] == 1.0f && m[0][1] == 0.0f && m[0][2] == 0.0f && m[0][3] == 0.0f && - m[1][0] == 0.0f && m[1][1] == 1.0f && m[1][2] == 0.0f && m[1][3] == 0.0f && - m[2][0] == 0.0f && m[2][1] == 0.0f && m[2][2] == 1.0f && m[2][3] == 0.0f && - m[3][0] == 0.0f && m[3][1] == 0.0f && m[3][2] == 0.0f && m[3][3] == 1.0f; -} - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline Vector VMatrix::ApplyRotation(const Vector &vVec) const -{ - return VMul3x3(vVec); -} - -inline VMatrix VMatrix::operator~() const -{ - VMatrix mRet; - InverseGeneral(mRet); - return mRet; -} - -#endif - - -//----------------------------------------------------------------------------- -// Accessors -//----------------------------------------------------------------------------- -inline void MatrixGetColumn( const VMatrix &src, int nCol, Vector *pColumn ) -{ - Assert( (nCol >= 0) && (nCol <= 3) ); - - pColumn->x = src[0][nCol]; - pColumn->y = src[1][nCol]; - pColumn->z = src[2][nCol]; -} - -inline void MatrixSetColumn( VMatrix &src, int nCol, const Vector &column ) -{ - Assert( (nCol >= 0) && (nCol <= 3) ); - - src.m[0][nCol] = column.x; - src.m[1][nCol] = column.y; - src.m[2][nCol] = column.z; -} - -inline void MatrixGetRow( const VMatrix &src, int nRow, Vector *pRow ) -{ - Assert( (nRow >= 0) && (nRow <= 3) ); - *pRow = *(Vector*)src[nRow]; -} - -inline void MatrixSetRow( VMatrix &dst, int nRow, const Vector &row ) -{ - Assert( (nRow >= 0) && (nRow <= 3) ); - *(Vector*)dst[nRow] = row; -} - - -//----------------------------------------------------------------------------- -// Vector3DMultiplyPosition treats src2 as if it's a point (adds the translation) -//----------------------------------------------------------------------------- -// NJS: src2 is passed in as a full vector rather than a reference to prevent the need -// for 2 branches and a potential copy in the body. (ie, handling the case when the src2 -// reference is the same as the dst reference ). -inline void Vector3DMultiplyPosition( const VMatrix& src1, const VectorByValue src2, Vector& dst ) -{ - dst[0] = src1[0][0] * src2.x + src1[0][1] * src2.y + src1[0][2] * src2.z + src1[0][3]; - dst[1] = src1[1][0] * src2.x + src1[1][1] * src2.y + src1[1][2] * src2.z + src1[1][3]; - dst[2] = src1[2][0] * src2.x + src1[2][1] * src2.y + src1[2][2] * src2.z + src1[2][3]; -} - - -//----------------------------------------------------------------------------- -// Transform a plane that has an axis-aligned normal -//----------------------------------------------------------------------------- -inline void MatrixTransformAxisAlignedPlane( const VMatrix &src, int nDim, float flSign, float flDist, cplane_t &outPlane ) -{ - // See MatrixTransformPlane in the .cpp file for an explanation of the algorithm. - MatrixGetColumn( src, nDim, &outPlane.normal ); - outPlane.normal *= flSign; - outPlane.dist = flDist * DotProduct( outPlane.normal, outPlane.normal ); - - // NOTE: Writing this out by hand because it doesn't inline (inline depth isn't large enough) - // This should read outPlane.dist += DotProduct( outPlane.normal, src.GetTranslation ); - outPlane.dist += outPlane.normal.x * src.m[0][3] + outPlane.normal.y * src.m[1][3] + outPlane.normal.z * src.m[2][3]; -} - - -//----------------------------------------------------------------------------- -// Matrix equality test -//----------------------------------------------------------------------------- -inline bool MatricesAreEqual( const VMatrix &src1, const VMatrix &src2, float flTolerance ) -{ - for ( int i = 0; i < 3; ++i ) - { - for ( int j = 0; j < 3; ++j ) - { - if ( fabs( src1[i][j] - src2[i][j] ) > flTolerance ) - return false; - } - } - return true; -} - -//----------------------------------------------------------------------------- -// -//----------------------------------------------------------------------------- -void MatrixBuildOrtho( VMatrix& dst, double left, double top, double right, double bottom, double zNear, double zFar ); -void MatrixBuildPerspectiveX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar ); -void MatrixBuildPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar, double bottom, double top, double left, double right ); - -inline void MatrixOrtho( VMatrix& dst, double left, double top, double right, double bottom, double zNear, double zFar ) -{ - VMatrix mat; - MatrixBuildOrtho( mat, left, top, right, bottom, zNear, zFar ); - - VMatrix temp; - MatrixMultiply( dst, mat, temp ); - dst = temp; -} - -inline void MatrixPerspectiveX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar ) -{ - VMatrix mat; - MatrixBuildPerspectiveX( mat, flFovX, flAspect, flZNear, flZFar ); - - VMatrix temp; - MatrixMultiply( dst, mat, temp ); - dst = temp; -} - -inline void MatrixPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar, double bottom, double top, double left, double right ) -{ - VMatrix mat; - MatrixBuildPerspectiveOffCenterX( mat, flFovX, flAspect, flZNear, flZFar, bottom, top, left, right ); - - VMatrix temp; - MatrixMultiply( dst, mat, temp ); - dst = temp; -} - -#endif - - diff --git a/Resources/NetHook/mathlib/vplane.h b/Resources/NetHook/mathlib/vplane.h deleted file mode 100644 index 0e280ab2..00000000 --- a/Resources/NetHook/mathlib/vplane.h +++ /dev/null @@ -1,182 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef VPLANE_H -#define VPLANE_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "mathlib/vector.h" - -typedef int SideType; - -// Used to represent sides of things like planes. -#define SIDE_FRONT 0 -#define SIDE_BACK 1 -#define SIDE_ON 2 - -#define VP_EPSILON 0.01f - - -class VPlane -{ -public: - VPlane(); - VPlane(const Vector &vNormal, vec_t dist); - - void Init(const Vector &vNormal, vec_t dist); - - // Return the distance from the point to the plane. - vec_t DistTo(const Vector &vVec) const; - - // Copy. - VPlane& operator=(const VPlane &thePlane); - - // Returns SIDE_ON, SIDE_FRONT, or SIDE_BACK. - // The epsilon for SIDE_ON can be passed in. - SideType GetPointSide(const Vector &vPoint, vec_t sideEpsilon=VP_EPSILON) const; - - // Returns SIDE_FRONT or SIDE_BACK. - SideType GetPointSideExact(const Vector &vPoint) const; - - // Classify the box with respect to the plane. - // Returns SIDE_ON, SIDE_FRONT, or SIDE_BACK - SideType BoxOnPlaneSide(const Vector &vMin, const Vector &vMax) const; - -#ifndef VECTOR_NO_SLOW_OPERATIONS - // Flip the plane. - VPlane Flip(); - - // Get a point on the plane (normal*dist). - Vector GetPointOnPlane() const; - - // Snap the specified point to the plane (along the plane's normal). - Vector SnapPointToPlane(const Vector &vPoint) const; -#endif - -public: - Vector m_Normal; - vec_t m_Dist; - -#ifdef VECTOR_NO_SLOW_OPERATIONS -private: - // No copy constructors allowed if we're in optimal mode - VPlane(const VPlane& vOther); -#endif -}; - - -//----------------------------------------------------------------------------- -// Inlines. -//----------------------------------------------------------------------------- -inline VPlane::VPlane() -{ -} - -inline VPlane::VPlane(const Vector &vNormal, vec_t dist) -{ - m_Normal = vNormal; - m_Dist = dist; -} - -inline void VPlane::Init(const Vector &vNormal, vec_t dist) -{ - m_Normal = vNormal; - m_Dist = dist; -} - -inline vec_t VPlane::DistTo(const Vector &vVec) const -{ - return vVec.Dot(m_Normal) - m_Dist; -} - -inline VPlane& VPlane::operator=(const VPlane &thePlane) -{ - m_Normal = thePlane.m_Normal; - m_Dist = thePlane.m_Dist; - return *this; -} - -#ifndef VECTOR_NO_SLOW_OPERATIONS - -inline VPlane VPlane::Flip() -{ - return VPlane(-m_Normal, -m_Dist); -} - -inline Vector VPlane::GetPointOnPlane() const -{ - return m_Normal * m_Dist; -} - -inline Vector VPlane::SnapPointToPlane(const Vector &vPoint) const -{ - return vPoint - m_Normal * DistTo(vPoint); -} - -#endif - -inline SideType VPlane::GetPointSide(const Vector &vPoint, vec_t sideEpsilon) const -{ - vec_t fDist; - - fDist = DistTo(vPoint); - if(fDist >= sideEpsilon) - return SIDE_FRONT; - else if(fDist <= -sideEpsilon) - return SIDE_BACK; - else - return SIDE_ON; -} - -inline SideType VPlane::GetPointSideExact(const Vector &vPoint) const -{ - return DistTo(vPoint) > 0.0f ? SIDE_FRONT : SIDE_BACK; -} - - -// BUGBUG: This should either simply use the implementation in mathlib or cease to exist. -// mathlib implementation is much more efficient. Check to see that VPlane isn't used in -// performance critical code. -inline SideType VPlane::BoxOnPlaneSide(const Vector &vMin, const Vector &vMax) const -{ - int i, firstSide, side; - TableVector vPoints[8] = - { - { vMin.x, vMin.y, vMin.z }, - { vMin.x, vMin.y, vMax.z }, - { vMin.x, vMax.y, vMax.z }, - { vMin.x, vMax.y, vMin.z }, - - { vMax.x, vMin.y, vMin.z }, - { vMax.x, vMin.y, vMax.z }, - { vMax.x, vMax.y, vMax.z }, - { vMax.x, vMax.y, vMin.z }, - }; - - firstSide = GetPointSideExact(vPoints[0]); - for(i=1; i < 8; i++) - { - side = GetPointSideExact(vPoints[i]); - - // Does the box cross the plane? - if(side != firstSide) - return SIDE_ON; - } - - // Ok, they're all on the same side, return that. - return firstSide; -} - - - - -#endif // VPLANE_H diff --git a/Resources/NetHook/public/bitvec.h b/Resources/NetHook/public/bitvec.h deleted file mode 100644 index 65d7e660..00000000 --- a/Resources/NetHook/public/bitvec.h +++ /dev/null @@ -1,1417 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -#ifndef BITVEC_H -#define BITVEC_H -#ifdef _WIN32 -#pragma once -#endif - -#include -#include "tier0/dbg.h" -#include "tier0/basetypes.h" - - -class CBitVecAccessor -{ -public: - CBitVecAccessor(uint32 *pDWords, int iBit); - - void operator=(int val); - operator uint32(); - -private: - uint32 *m_pDWords; - int m_iBit; -}; - - -//----------------------------------------------------------------------------- -// Support functions -//----------------------------------------------------------------------------- - -#define LOG2_BITS_PER_INT 5 -#define BITS_PER_INT 32 - -#if _WIN32 && !defined(_X360) -#include -#pragma intrinsic(_BitScanForward) -#endif - -inline int FirstBitInWord( unsigned int elem, int offset ) -{ -#if _WIN32 - if ( !elem ) - return -1; -#if _X360 - // this implements CountTrailingZeros() / BitScanForward() - unsigned int mask = elem-1; - unsigned int comp = ~elem; - elem = mask & comp; - return (32 - _CountLeadingZeros(elem)) + offset; -#else - unsigned long out; - _BitScanForward(&out, elem); - return out + offset; -#endif - -#else - static unsigned firstBitLUT[256] = - { - 0,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0, - 3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0, - 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0, - 3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0, - 5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0, - 3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0, - 4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0 - }; - unsigned elemByte; - - elemByte = (elem & 0xFF); - if ( elemByte ) - return offset + firstBitLUT[elemByte]; - - elem >>= 8; - offset += 8; - elemByte = (elem & 0xFF); - if ( elemByte ) - return offset + firstBitLUT[elemByte]; - - elem >>= 8; - offset += 8; - elemByte = (elem & 0xFF); - if ( elemByte ) - return offset + firstBitLUT[elemByte]; - - elem >>= 8; - offset += 8; - elemByte = (elem & 0xFF); - if ( elemByte ) - return offset + firstBitLUT[elemByte]; - - return -1; -#endif -} - -//------------------------------------- - -inline unsigned GetEndMask( int numBits ) -{ - static unsigned bitStringEndMasks[] = - { - 0xffffffff, - 0x00000001, - 0x00000003, - 0x00000007, - 0x0000000f, - 0x0000001f, - 0x0000003f, - 0x0000007f, - 0x000000ff, - 0x000001ff, - 0x000003ff, - 0x000007ff, - 0x00000fff, - 0x00001fff, - 0x00003fff, - 0x00007fff, - 0x0000ffff, - 0x0001ffff, - 0x0003ffff, - 0x0007ffff, - 0x000fffff, - 0x001fffff, - 0x003fffff, - 0x007fffff, - 0x00ffffff, - 0x01ffffff, - 0x03ffffff, - 0x07ffffff, - 0x0fffffff, - 0x1fffffff, - 0x3fffffff, - 0x7fffffff, - }; - - return bitStringEndMasks[numBits % BITS_PER_INT]; -} - - -inline int GetBitForBitnum( int bitNum ) -{ - static int bitsForBitnum[] = - { - ( 1 << 0 ), - ( 1 << 1 ), - ( 1 << 2 ), - ( 1 << 3 ), - ( 1 << 4 ), - ( 1 << 5 ), - ( 1 << 6 ), - ( 1 << 7 ), - ( 1 << 8 ), - ( 1 << 9 ), - ( 1 << 10 ), - ( 1 << 11 ), - ( 1 << 12 ), - ( 1 << 13 ), - ( 1 << 14 ), - ( 1 << 15 ), - ( 1 << 16 ), - ( 1 << 17 ), - ( 1 << 18 ), - ( 1 << 19 ), - ( 1 << 20 ), - ( 1 << 21 ), - ( 1 << 22 ), - ( 1 << 23 ), - ( 1 << 24 ), - ( 1 << 25 ), - ( 1 << 26 ), - ( 1 << 27 ), - ( 1 << 28 ), - ( 1 << 29 ), - ( 1 << 30 ), - ( 1 << 31 ), - }; - - return bitsForBitnum[ (bitNum) & (BITS_PER_INT-1) ]; -} - -inline int GetBitForBitnumByte( int bitNum ) -{ - static int bitsForBitnum[] = - { - ( 1 << 0 ), - ( 1 << 1 ), - ( 1 << 2 ), - ( 1 << 3 ), - ( 1 << 4 ), - ( 1 << 5 ), - ( 1 << 6 ), - ( 1 << 7 ), - }; - - return bitsForBitnum[ bitNum & 7 ]; -} - -inline int CalcNumIntsForBits( int numBits ) { return (numBits + (BITS_PER_INT-1)) / BITS_PER_INT; } - -#ifdef _X360 -#define BitVec_Bit( bitNum ) GetBitForBitnum( bitNum ) -#define BitVec_BitInByte( bitNum ) GetBitForBitnumByte( bitNum ) -#else -#define BitVec_Bit( bitNum ) ( 1 << ( (bitNum) & (BITS_PER_INT-1) ) ) -#define BitVec_BitInByte( bitNum ) ( 1 << ( (bitNum) & 7 ) ) -#endif -#define BitVec_Int( bitNum ) ( (bitNum) >> LOG2_BITS_PER_INT ) - - -//----------------------------------------------------------------------------- -// template CBitVecT -// -// Defines the operations relevant to any bit array. Simply requires a base -// class that implements GetNumBits(), Base(), GetNumDWords() & ValidateOperand() -// -// CVarBitVec and CBitVec are the actual classes generally used -// by clients -// - -template -class CBitVecT : public BASE_OPS -{ -public: - CBitVecT(); - CBitVecT(int numBits); // Must be initialized with the number of bits - - void Init(int val = 0); - - // Access the bits like an array. - CBitVecAccessor operator[](int i); - - // Do NOT override bitwise operators (see note in header) - void And(const CBitVecT &andStr, CBitVecT *out) const; - void Or(const CBitVecT &orStr, CBitVecT *out) const; - void Xor(const CBitVecT &orStr, CBitVecT *out) const; - - void Not(CBitVecT *out) const; - - void CopyTo(CBitVecT *out) const; - void Copy( const CBitVecT &other, int nBits=-1 ); - bool Compare( const CBitVecT &other, int nBits=-1 ) const; - - bool IsAllClear(void) const; // Are all bits zero? - bool IsAllSet(void) const; // Are all bits one? - - uint32 Get( uint32 bitNum ) const; - bool IsBitSet( int bitNum ) const; - void Set( int bitNum ); - void Set( int bitNum, bool bNewVal ); - void Clear(int bitNum); - - bool TestAndSet(int bitNum); - - void Set( uint32 offset, uint32 mask ); - void Clear( uint32 offset, uint32 mask ); - uint32 Get( uint32 offset, uint32 mask ); - - void SetAll(void); // Sets all bits - void ClearAll(void); // Clears all bits - - uint32 GetDWord(int i) const; - void SetDWord(int i, uint32 val); - - CBitVecT& operator=(const CBitVecT &other) { other.CopyTo( this ); return *this; } - bool operator==(const CBitVecT &other) { return Compare( other ); } - bool operator!=(const CBitVecT &other) { return !operator==( other ); } - - static void GetOffsetMaskForBit( uint32 bitNum, uint32 *pOffset, uint32 *pMask ) { *pOffset = BitVec_Int( bitNum ); *pMask = BitVec_Bit( bitNum ); } -}; - -//----------------------------------------------------------------------------- -// class CVarBitVecBase -// -// Defines the operations necessary for a variable sized bit array - -class CVarBitVecBase -{ -public: - bool IsFixedSize() const { return false; } - int GetNumBits(void) const { return m_numBits; } - void Resize( int numBits, bool bClearAll = false ); // resizes bit array - - int GetNumDWords() const { return m_numInts; } - uint32 *Base() { return m_pInt; } - const uint32 *Base() const { return m_pInt; } - - void Attach( uint32 *pBits, int numBits ); - bool Detach( uint32 **ppBits, int *pNumBits ); - - int FindNextSetBit(int iStartBit) const; // returns -1 if no set bit was found - -protected: - CVarBitVecBase(); - CVarBitVecBase(int numBits); - CVarBitVecBase( const CVarBitVecBase &from ); - CVarBitVecBase &operator=( const CVarBitVecBase &from ); - ~CVarBitVecBase(void); - - void ValidateOperand( const CVarBitVecBase &operand ) const { Assert(GetNumBits() == operand.GetNumBits()); } - - unsigned GetEndMask() const { return ::GetEndMask( GetNumBits() ); } - -private: - - unsigned short m_numBits; // Number of bits in the bitstring - unsigned short m_numInts; // Number of ints to needed to store bitstring - uint32 m_iBitStringStorage; // If the bit string fits in one int, it goes here - uint32 * m_pInt; // Array of ints containing the bitstring - - void AllocInts( int numInts ); // Free the allocated bits - void ReallocInts( int numInts ); - void FreeInts( void ); // Free the allocated bits -}; - -//----------------------------------------------------------------------------- -// class CFixedBitVecBase -// -// Defines the operations necessary for a fixed sized bit array. -// - -template struct BitCountToEndMask_t { }; -template <> struct BitCountToEndMask_t< 0> { enum { MASK = 0xffffffff }; }; -template <> struct BitCountToEndMask_t< 1> { enum { MASK = 0x00000001 }; }; -template <> struct BitCountToEndMask_t< 2> { enum { MASK = 0x00000003 }; }; -template <> struct BitCountToEndMask_t< 3> { enum { MASK = 0x00000007 }; }; -template <> struct BitCountToEndMask_t< 4> { enum { MASK = 0x0000000f }; }; -template <> struct BitCountToEndMask_t< 5> { enum { MASK = 0x0000001f }; }; -template <> struct BitCountToEndMask_t< 6> { enum { MASK = 0x0000003f }; }; -template <> struct BitCountToEndMask_t< 7> { enum { MASK = 0x0000007f }; }; -template <> struct BitCountToEndMask_t< 8> { enum { MASK = 0x000000ff }; }; -template <> struct BitCountToEndMask_t< 9> { enum { MASK = 0x000001ff }; }; -template <> struct BitCountToEndMask_t<10> { enum { MASK = 0x000003ff }; }; -template <> struct BitCountToEndMask_t<11> { enum { MASK = 0x000007ff }; }; -template <> struct BitCountToEndMask_t<12> { enum { MASK = 0x00000fff }; }; -template <> struct BitCountToEndMask_t<13> { enum { MASK = 0x00001fff }; }; -template <> struct BitCountToEndMask_t<14> { enum { MASK = 0x00003fff }; }; -template <> struct BitCountToEndMask_t<15> { enum { MASK = 0x00007fff }; }; -template <> struct BitCountToEndMask_t<16> { enum { MASK = 0x0000ffff }; }; -template <> struct BitCountToEndMask_t<17> { enum { MASK = 0x0001ffff }; }; -template <> struct BitCountToEndMask_t<18> { enum { MASK = 0x0003ffff }; }; -template <> struct BitCountToEndMask_t<19> { enum { MASK = 0x0007ffff }; }; -template <> struct BitCountToEndMask_t<20> { enum { MASK = 0x000fffff }; }; -template <> struct BitCountToEndMask_t<21> { enum { MASK = 0x001fffff }; }; -template <> struct BitCountToEndMask_t<22> { enum { MASK = 0x003fffff }; }; -template <> struct BitCountToEndMask_t<23> { enum { MASK = 0x007fffff }; }; -template <> struct BitCountToEndMask_t<24> { enum { MASK = 0x00ffffff }; }; -template <> struct BitCountToEndMask_t<25> { enum { MASK = 0x01ffffff }; }; -template <> struct BitCountToEndMask_t<26> { enum { MASK = 0x03ffffff }; }; -template <> struct BitCountToEndMask_t<27> { enum { MASK = 0x07ffffff }; }; -template <> struct BitCountToEndMask_t<28> { enum { MASK = 0x0fffffff }; }; -template <> struct BitCountToEndMask_t<29> { enum { MASK = 0x1fffffff }; }; -template <> struct BitCountToEndMask_t<30> { enum { MASK = 0x3fffffff }; }; -template <> struct BitCountToEndMask_t<31> { enum { MASK = 0x7fffffff }; }; - -//------------------------------------- - -template -class CFixedBitVecBase -{ -public: - bool IsFixedSize() const { return true; } - int GetNumBits(void) const { return NUM_BITS; } - void Resize( int numBits, bool bClearAll = false ) { Assert(numBits == NUM_BITS); if ( bClearAll ) memset( m_Ints, 0, NUM_INTS * sizeof(uint32) ); }// for syntatic consistency (for when using templates) - - int GetNumDWords() const { return NUM_INTS; } - uint32 * Base() { return m_Ints; } - const uint32 * Base() const { return m_Ints; } - - int FindNextSetBit(int iStartBit) const; // returns -1 if no set bit was found - -protected: - CFixedBitVecBase() {} - CFixedBitVecBase(int numBits) { Assert( numBits == NUM_BITS ); } // doesn't make sense, really. Supported to simplify templates & allow easy replacement of variable - - void ValidateOperand( const CFixedBitVecBase &operand ) const { } // no need, compiler does so statically - -public: // for test code - unsigned GetEndMask() const { return static_cast( BitCountToEndMask_t::MASK ); } - -private: - enum - { - NUM_INTS = (NUM_BITS + (BITS_PER_INT-1)) / BITS_PER_INT - }; - - uint32 m_Ints[(NUM_BITS + (BITS_PER_INT-1)) / BITS_PER_INT]; -}; - -//----------------------------------------------------------------------------- -// -// The actual classes used -// - -// inheritance instead of typedef to allow forward declarations -class CVarBitVec : public CBitVecT -{ -public: - CVarBitVec() - { - } - - CVarBitVec(int numBits) - : CBitVecT(numBits) - { - } -}; - -//----------------------------------------------------------------------------- - -template < int NUM_BITS > -class CBitVec : public CBitVecT< CFixedBitVecBase > -{ -public: - CBitVec() - { - } - - CBitVec(int numBits) - : CBitVecT< CFixedBitVecBase >(numBits) - { - } -}; - - -//----------------------------------------------------------------------------- - -typedef CBitVec<32> CDWordBitVec; - -//----------------------------------------------------------------------------- - -inline CVarBitVecBase::CVarBitVecBase() -{ - memset( this, 0, sizeof( *this ) ); -} - -//----------------------------------------------------------------------------- - -inline CVarBitVecBase::CVarBitVecBase(int numBits) -{ - Assert( numBits ); - m_numBits = numBits; - - // Figure out how many ints are needed - m_numInts = CalcNumIntsForBits( numBits ); - m_pInt = NULL; - AllocInts( m_numInts ); -} - -//----------------------------------------------------------------------------- - -inline CVarBitVecBase::CVarBitVecBase( const CVarBitVecBase &from ) -{ - if ( from.m_numInts ) - { - m_numBits = from.m_numBits; - m_numInts = from.m_numInts; - m_pInt = NULL; - AllocInts( m_numInts ); - memcpy( m_pInt, from.m_pInt, m_numInts * sizeof(int) ); - } - else - memset( this, 0, sizeof( *this ) ); -} - -//----------------------------------------------------------------------------- - -inline CVarBitVecBase &CVarBitVecBase::operator=( const CVarBitVecBase &from ) -{ - Resize( from.GetNumBits() ); - if ( m_pInt ) - memcpy( m_pInt, from.m_pInt, m_numInts * sizeof(int) ); - return (*this); -} - -//----------------------------------------------------------------------------- -// Purpose: Destructor -// Input : -// Output : -//----------------------------------------------------------------------------- - -inline CVarBitVecBase::~CVarBitVecBase(void) -{ - FreeInts(); -} - -//----------------------------------------------------------------------------- - -inline void CVarBitVecBase::Attach( uint32 *pBits, int numBits ) -{ - FreeInts(); - m_numBits = numBits; - m_numInts = CalcNumIntsForBits( numBits ); - if ( m_numInts > 1 ) - { - m_pInt = pBits; - } - else - { - m_iBitStringStorage = *pBits; - m_pInt = &m_iBitStringStorage; - free( pBits ); - } -} - -//----------------------------------------------------------------------------- - -inline bool CVarBitVecBase::Detach( uint32 **ppBits, int *pNumBits ) -{ - if ( !m_numBits ) - { - return false; - } - - *pNumBits = m_numBits; - if ( m_numInts > 1 ) - { - *ppBits = m_pInt; - } - else - { - *ppBits = (uint32 *)malloc( sizeof(uint32) ); - **ppBits = m_iBitStringStorage; - free( m_pInt ); - } - - memset( this, 0, sizeof( *this ) ); - return true; -} - -//----------------------------------------------------------------------------- - -template -inline CBitVecT::CBitVecT() -{ - // undef this is ints are not 4 bytes - // generate a compile error if sizeof(int) is not 4 (HACK: can't use the preprocessor so use the compiler) - - COMPILE_TIME_ASSERT( sizeof(int)==4 ); - - // Initialize bitstring by clearing all bits - ClearAll(); -} - -//----------------------------------------------------------------------------- -template -inline CBitVecT::CBitVecT(int numBits) - : BASE_OPS( numBits ) -{ - // undef this is ints are not 4 bytes - // generate a compile error if sizeof(int) is not 4 (HACK: can't use the preprocessor so use the compiler) - - COMPILE_TIME_ASSERT( sizeof(int)==4 ); - - // Initialize bitstring by clearing all bits - ClearAll(); -} - -//----------------------------------------------------------------------------- - -template -inline CBitVecAccessor CBitVecT::operator[](int i) -{ - Assert(i >= 0 && i < GetNumBits()); - return CBitVecAccessor(Base(), i); -} - - -//----------------------------------------------------------------------------- - -template -inline void CBitVecT::Init( int val ) -{ - if ( Base() ) - memset( Base(), ( val ) ? 0xff : 0, GetNumDWords() * sizeof(int) ); -} - -//----------------------------------------------------------------------------- - -template -inline uint32 CBitVecT::Get( uint32 bitNum ) const -{ - Assert( bitNum < (uint32)GetNumBits() ); - const uint32 *pInt = Base() + BitVec_Int( bitNum ); - return ( *pInt & BitVec_Bit( bitNum ) ); -} - -//----------------------------------------------------------------------------- - -template -inline bool CBitVecT::IsBitSet( int bitNum ) const -{ - Assert( bitNum >= 0 && bitNum < GetNumBits() ); - const uint32 *pInt = Base() + BitVec_Int( bitNum ); - return ( ( *pInt & BitVec_Bit( bitNum ) ) != 0 ); -} - -//----------------------------------------------------------------------------- - -template -inline void CBitVecT::Set( int bitNum ) -{ - Assert( bitNum >= 0 && bitNum < GetNumBits() ); - uint32 *pInt = Base() + BitVec_Int( bitNum ); - *pInt |= BitVec_Bit( bitNum ); -} - -//----------------------------------------------------------------------------- - -template -inline bool CBitVecT::TestAndSet(int bitNum) -{ - Assert( bitNum >= 0 && bitNum < GetNumBits() ); - uint32 bitVecBit = BitVec_Bit( bitNum ); - uint32 *pInt = Base() + BitVec_Int( bitNum ); - bool bResult = ( ( *pInt & bitVecBit) != 0 ); - *pInt |= bitVecBit; - return bResult; -} - -//----------------------------------------------------------------------------- - -template -inline void CBitVecT::Clear(int bitNum) -{ - Assert( bitNum >= 0 && bitNum < GetNumBits() ); - uint32 *pInt = Base() + BitVec_Int( bitNum ); - *pInt &= ~BitVec_Bit( bitNum ); -} - -//----------------------------------------------------------------------------- - -template -inline void CBitVecT::Set( int bitNum, bool bNewVal ) -{ - uint32 *pInt = Base() + BitVec_Int( bitNum ); - uint32 bitMask = BitVec_Bit( bitNum ); - if ( bNewVal ) - { - *pInt |= bitMask; - } - else - { - *pInt &= ~bitMask; - } -} - -//----------------------------------------------------------------------------- - -template -inline void CBitVecT::Set( uint32 offset, uint32 mask ) -{ - uint32 *pInt = Base() + offset; - *pInt |= mask; -} - -//----------------------------------------------------------------------------- - -template -inline void CBitVecT::Clear( uint32 offset, uint32 mask ) -{ - uint32 *pInt = Base() + offset; - *pInt &= ~mask; -} - -//----------------------------------------------------------------------------- - -template -inline uint32 CBitVecT::Get( uint32 offset, uint32 mask ) -{ - uint32 *pInt = Base() + offset; - return ( *pInt & mask ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::And(const CBitVecT &addStr, CBitVecT *out) const -{ - ValidateOperand( addStr ); - ValidateOperand( *out ); - - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = addStr.Base(); - - for (int i = GetNumDWords() - 1; i >= 0 ; --i) - { - pDest[i] = pOperand1[i] & pOperand2[i]; - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::Or(const CBitVecT &orStr, CBitVecT *out) const -{ - ValidateOperand( orStr ); - ValidateOperand( *out ); - - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = orStr.Base(); - - for (int i = GetNumDWords() - 1; i >= 0; --i) - { - pDest[i] = pOperand1[i] | pOperand2[i]; - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::Xor(const CBitVecT &xorStr, CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = xorStr.Base(); - - for (int i = GetNumDWords() - 1; i >= 0; --i) - { - pDest[i] = pOperand1[i] ^ pOperand2[i]; - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::Not(CBitVecT *out) const -{ - ValidateOperand( *out ); - - uint32 * pDest = out->Base(); - const uint32 *pOperand = Base(); - - for (int i = GetNumDWords() - 1; i >= 0; --i) - { - pDest[i] = ~(pOperand[i]); - } -} - -//----------------------------------------------------------------------------- -// Purpose: Copy a bit string -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::CopyTo(CBitVecT *out) const -{ - out->Resize( GetNumBits() ); - - ValidateOperand( *out ); - Assert( out != this ); - - memcpy( out->Base(), Base(), GetNumDWords() * sizeof( int ) ); -} - -//----------------------------------------------------------------------------- -// Purpose: Are all bits zero? -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline bool CBitVecT::IsAllClear(void) const -{ - // Number of available bits may be more than the number - // actually used, so make sure to mask out unused bits - // before testing for zero - (const_cast(this))->Base()[GetNumDWords()-1] &= CBitVecT::GetEndMask(); // external semantics of const retained - - for (int i = GetNumDWords() - 1; i >= 0; --i) - { - if ( Base()[i] !=0 ) - { - return false; - } - } - return true; -} - -//----------------------------------------------------------------------------- -// Purpose: Are all bits set? -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline bool CBitVecT::IsAllSet(void) const -{ - // Number of available bits may be more than the number - // actually used, so make sure to mask out unused bits - // before testing for set bits - (const_cast(this))->Base()[GetNumDWords()-1] |= ~CBitVecT::GetEndMask(); // external semantics of const retained - - for (int i = GetNumDWords() - 1; i >= 0; --i) - { - if ( Base()[i] != ~0 ) - { - return false; - } - } - return true; -} - -//----------------------------------------------------------------------------- -// Purpose: Sets all bits -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::SetAll(void) -{ - if ( Base() ) - memset( Base(), 0xff, GetNumDWords() * sizeof(int) ); -} - -//----------------------------------------------------------------------------- -// Purpose: Clears all bits -// Input : -// Output : -//----------------------------------------------------------------------------- -template -inline void CBitVecT::ClearAll(void) -{ - if ( Base() ) - memset( Base(), 0, GetNumDWords() * sizeof(int) ); -} - -//----------------------------------------------------------------------------- -template -inline void CBitVecT::Copy( const CBitVecT &other, int nBits=-1 ) -{ - if ( nBits == - 1 ) - { - nBits = other.GetNumBits(); - } - - Resize( nBits ); - - ValidateOperand( other ); - Assert( &other != this ); - - memcpy( Base(), other.Base(), GetNumDWords() * sizeof( uint32 ) ); -} - -//----------------------------------------------------------------------------- -template -inline bool CBitVecT::Compare( const CBitVecT &other, int nBits=-1 ) const -{ - if ( nBits == - 1 ) - { - if ( other.GetNumBits() != GetNumBits() ) - { - return false; - } - - nBits = other.GetNumBits(); - } - - if ( nBits > other.GetNumBits() || nBits > GetNumBits() ) - { - return false; - } - - (const_cast(this))->Base()[GetNumDWords()-1] &= CBitVecT::GetEndMask(); // external semantics of const retained - (const_cast(&other))->Base()[GetNumDWords()-1] &= other.CBitVecT::GetEndMask(); // external semantics of const retained - - int nBytes = PAD_NUMBER( nBits, 8 ) >> 3; - - return ( memcmp( Base(), other.Base(), nBytes ) == 0 ); -} - -//----------------------------------------------------------------------------- -template -inline uint32 CBitVecT::GetDWord(int i) const -{ - Assert(i >= 0 && i < GetNumDWords()); - return Base()[i]; -} - -//----------------------------------------------------------------------------- -template -inline void CBitVecT::SetDWord(int i, uint32 val) -{ - Assert(i >= 0 && i < GetNumDWords()); - Base()[i] = val; -} - -//----------------------------------------------------------------------------- - -inline unsigned GetStartBitMask( int startBit ) -{ - static unsigned int g_StartMask[32] = - { - 0xffffffff, - 0xfffffffe, - 0xfffffffc, - 0xfffffff8, - 0xfffffff0, - 0xffffffe0, - 0xffffffc0, - 0xffffff80, - 0xffffff00, - 0xfffffe00, - 0xfffffc00, - 0xfffff800, - 0xfffff000, - 0xffffe000, - 0xffffc000, - 0xffff8000, - 0xffff0000, - 0xfffe0000, - 0xfffc0000, - 0xfff80000, - 0xfff00000, - 0xffe00000, - 0xffc00000, - 0xff800000, - 0xff000000, - 0xfe000000, - 0xfc000000, - 0xf8000000, - 0xf0000000, - 0xe0000000, - 0xc0000000, - 0x80000000, - }; - - return g_StartMask[ startBit & 31 ]; -} - -inline int CVarBitVecBase::FindNextSetBit( int startBit ) const -{ - if ( startBit < GetNumBits() ) - { - int wordIndex = BitVec_Int(startBit); - unsigned int startMask = GetStartBitMask( startBit ); - int lastWord = GetNumDWords()-1; - - // handle non dword lengths - if ( (GetNumBits() % BITS_PER_INT) != 0 ) - { - unsigned int elem = Base()[wordIndex]; - elem &= startMask; - if ( wordIndex == lastWord) - { - elem &= (GetEndMask()); - // there's a bit remaining in this word - if ( elem ) - return FirstBitInWord(elem, wordIndex << 5); - } - else - { - // there's a bit remaining in this word - if ( elem ) - return FirstBitInWord(elem, wordIndex << 5); - - // iterate the words - for ( int i = wordIndex+1; i < lastWord; i++ ) - { - elem = Base()[i]; - if ( elem ) - return FirstBitInWord(elem, i << 5); - } - elem = Base()[lastWord] & GetEndMask(); - if ( elem ) - return FirstBitInWord(elem, lastWord << 5); - } - } - else - { - const uint32 * RESTRICT pCurElem = Base() + wordIndex; - unsigned int elem = *pCurElem; - elem &= startMask; - do - { - if ( elem ) - return FirstBitInWord(elem, wordIndex << 5); - ++pCurElem; - elem = *pCurElem; - ++wordIndex; - } while( wordIndex <= lastWord ); - } - - } - - return -1; -} - -template -inline int CFixedBitVecBase::FindNextSetBit( int startBit ) const -{ - if ( startBit < NUM_BITS ) - { - int wordIndex = BitVec_Int(startBit); - unsigned int startMask = GetStartBitMask( startBit ); - - // handle non dword lengths - if ( (NUM_BITS % BITS_PER_INT) != 0 ) - { - unsigned int elem = Base()[wordIndex]; - elem &= startMask; - if ( wordIndex == NUM_INTS-1) - { - elem &= (GetEndMask()); - // there's a bit remaining in this word - if ( elem ) - return FirstBitInWord(elem, wordIndex << 5); - } - else - { - // there's a bit remaining in this word - if ( elem ) - return FirstBitInWord(elem, wordIndex << 5); - - // iterate the words - for ( int i = wordIndex+1; i < NUM_INTS-1; i++ ) - { - elem = Base()[i]; - if ( elem ) - return FirstBitInWord(elem, i << 5); - } - elem = Base()[NUM_INTS-1] & GetEndMask(); - if ( elem ) - return FirstBitInWord(elem, (NUM_INTS-1) << 5); - } - } - else - { - const uint32 * RESTRICT pCurElem = Base() + wordIndex; - unsigned int elem = *pCurElem; - elem &= startMask; - do - { - if ( elem ) - return FirstBitInWord(elem, wordIndex << 5); - ++pCurElem; - elem = *pCurElem; - ++wordIndex; - } while( wordIndex <= NUM_INTS-1); - } - - } - - return -1; -} - -//----------------------------------------------------------------------------- -// Unrolled loops for some common sizes - -template<> -FORCEINLINE_TEMPLATE void CBitVecT< CFixedBitVecBase<256> >::And(const CBitVecT &addStr, CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = addStr.Base(); - - pDest[0] = pOperand1[0] & pOperand2[0]; - pDest[1] = pOperand1[1] & pOperand2[1]; - pDest[2] = pOperand1[2] & pOperand2[2]; - pDest[3] = pOperand1[3] & pOperand2[3]; - pDest[4] = pOperand1[4] & pOperand2[4]; - pDest[5] = pOperand1[5] & pOperand2[5]; - pDest[6] = pOperand1[6] & pOperand2[6]; - pDest[7] = pOperand1[7] & pOperand2[7]; -} - -template<> -FORCEINLINE_TEMPLATE bool CBitVecT< CFixedBitVecBase<256> >::IsAllClear(void) const -{ - const uint32 *pInts = Base(); - return ( pInts[0] == 0 && pInts[1] == 0 && pInts[2] == 0 && pInts[3] == 0 && pInts[4] == 0 && pInts[5] == 0 && pInts[6] == 0 && pInts[7] == 0 ); -} - -template<> -FORCEINLINE_TEMPLATE void CBitVecT< CFixedBitVecBase<256> >::CopyTo(CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pInts = Base(); - - pDest[0] = pInts[0]; - pDest[1] = pInts[1]; - pDest[2] = pInts[2]; - pDest[3] = pInts[3]; - pDest[4] = pInts[4]; - pDest[5] = pInts[5]; - pDest[6] = pInts[6]; - pDest[7] = pInts[7]; -} - -template<> -FORCEINLINE_TEMPLATE void CBitVecT< CFixedBitVecBase<128> >::And(const CBitVecT &addStr, CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = addStr.Base(); - - pDest[0] = pOperand1[0] & pOperand2[0]; - pDest[1] = pOperand1[1] & pOperand2[1]; - pDest[2] = pOperand1[2] & pOperand2[2]; - pDest[3] = pOperand1[3] & pOperand2[3]; -} - -template<> -FORCEINLINE_TEMPLATE bool CBitVecT< CFixedBitVecBase<128> >::IsAllClear(void) const -{ - const uint32 *pInts = Base(); - return ( pInts[0] == 0 && pInts[1] == 0 && pInts[2] == 0 && pInts[3] == 0 ); -} - -template<> -FORCEINLINE_TEMPLATE void CBitVecT< CFixedBitVecBase<128> >::CopyTo(CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pInts = Base(); - - pDest[0] = pInts[0]; - pDest[1] = pInts[1]; - pDest[2] = pInts[2]; - pDest[3] = pInts[3]; -} - -template<> -inline void CBitVecT< CFixedBitVecBase<96> >::And(const CBitVecT &addStr, CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = addStr.Base(); - - pDest[0] = pOperand1[0] & pOperand2[0]; - pDest[1] = pOperand1[1] & pOperand2[1]; - pDest[2] = pOperand1[2] & pOperand2[2]; -} - -template<> -inline bool CBitVecT< CFixedBitVecBase<96> >::IsAllClear(void) const -{ - const uint32 *pInts = Base(); - return ( pInts[0] == 0 && pInts[1] == 0 && pInts[2] == 0 ); -} - -template<> -inline void CBitVecT< CFixedBitVecBase<96> >::CopyTo(CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pInts = Base(); - - pDest[0] = pInts[0]; - pDest[1] = pInts[1]; - pDest[2] = pInts[2]; -} - -template<> -inline void CBitVecT< CFixedBitVecBase<64> >::And(const CBitVecT &addStr, CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = addStr.Base(); - - pDest[0] = pOperand1[0] & pOperand2[0]; - pDest[1] = pOperand1[1] & pOperand2[1]; -} - -template<> -inline bool CBitVecT< CFixedBitVecBase<64> >::IsAllClear(void) const -{ - const uint32 *pInts = Base(); - return ( pInts[0] == 0 && pInts[1] == 0 ); -} - -template<> -inline void CBitVecT< CFixedBitVecBase<64> >::CopyTo(CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pInts = Base(); - - pDest[0] = pInts[0]; - pDest[1] = pInts[1]; -} - -template<> -inline void CBitVecT< CFixedBitVecBase<32> >::And(const CBitVecT &addStr, CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pOperand1 = Base(); - const uint32 *pOperand2 = addStr.Base(); - - pDest[0] = pOperand1[0] & pOperand2[0]; -} - -template<> -inline bool CBitVecT< CFixedBitVecBase<32> >::IsAllClear(void) const -{ - const uint32 *pInts = Base(); - - return ( pInts[0] == 0 ); -} - -template<> -inline void CBitVecT< CFixedBitVecBase<32> >::CopyTo(CBitVecT *out) const -{ - uint32 * pDest = out->Base(); - const uint32 *pInts = Base(); - - pDest[0] = pInts[0]; -} - -//----------------------------------------------------------------------------- - -template <> -inline uint32 CBitVecT< CFixedBitVecBase<32> >::Get( uint32 bitNum ) const -{ - return ( *Base() & BitVec_Bit( bitNum ) ); -} - -//----------------------------------------------------------------------------- - -template <> -inline bool CBitVecT< CFixedBitVecBase<32> >::IsBitSet( int bitNum ) const -{ - return ( ( *Base() & BitVec_Bit( bitNum ) ) != 0 ); -} - -//----------------------------------------------------------------------------- - -template <> -inline void CBitVecT< CFixedBitVecBase<32> >::Set( int bitNum ) -{ - *Base() |= BitVec_Bit( bitNum ); -} - -//----------------------------------------------------------------------------- - -template <> -inline void CBitVecT< CFixedBitVecBase<32> >::Clear(int bitNum) -{ - *Base() &= ~BitVec_Bit( bitNum ); -} - -//----------------------------------------------------------------------------- - -template <> -inline void CBitVecT< CFixedBitVecBase<32> >::Set( int bitNum, bool bNewVal ) -{ - uint32 bitMask = BitVec_Bit( bitNum ); - if ( bNewVal ) - { - *Base() |= bitMask; - } - else - { - *Base() &= ~bitMask; - } -} - - -//----------------------------------------------------------------------------- - -#include "tier0/memdbgon.h" - -//----------------------------------------------------------------------------- -// Purpose: Resizes the bit string to a new number of bits -// Input : resizeNumBits - -//----------------------------------------------------------------------------- -inline void CVarBitVecBase::Resize( int resizeNumBits, bool bClearAll ) -{ - Assert( resizeNumBits >= 0 && resizeNumBits <= USHRT_MAX ); - - int newIntCount = CalcNumIntsForBits( resizeNumBits ); - if ( newIntCount != GetNumDWords() ) - { - if ( Base() ) - { - ReallocInts( newIntCount ); - if ( !bClearAll && resizeNumBits >= GetNumBits() ) - { - Base()[GetNumDWords() - 1] &= GetEndMask(); - memset( Base() + GetNumDWords(), 0, (newIntCount - GetNumDWords()) * sizeof(int) ); - } - } - else - { - // Figure out how many ints are needed - AllocInts( newIntCount ); - // Initialize bitstring by clearing all bits - bClearAll = true; - } - - m_numInts = newIntCount; - } - else if ( !bClearAll && resizeNumBits >= GetNumBits() && Base() ) - { - Base()[GetNumDWords() - 1] &= GetEndMask(); - } - - if ( bClearAll && Base() ) - { - memset( Base(), 0, newIntCount * sizeof(int) ); - } - - // store the new size and end mask - m_numBits = resizeNumBits; -} - -//----------------------------------------------------------------------------- -// Purpose: Allocate the storage for the ints -// Input : numInts - -//----------------------------------------------------------------------------- -inline void CVarBitVecBase::AllocInts( int numInts ) -{ - Assert( !m_pInt ); - - if ( numInts == 0 ) - return; - - if ( numInts == 1 ) - { - m_pInt = &m_iBitStringStorage; - return; - } - - m_pInt = (uint32 *)malloc( numInts * sizeof(int) ); -} - - -//----------------------------------------------------------------------------- -// Purpose: Reallocate the storage for the ints -// Input : numInts - -//----------------------------------------------------------------------------- -inline void CVarBitVecBase::ReallocInts( int numInts ) -{ - Assert( Base() ); - if ( numInts == 0) - { - FreeInts(); - return; - } - - if ( m_pInt == &m_iBitStringStorage ) - { - if ( numInts != 1 ) - { - m_pInt = ((uint32 *)malloc( numInts * sizeof(int) )); - *m_pInt = m_iBitStringStorage; - } - - return; - } - - if ( numInts == 1 ) - { - m_iBitStringStorage = *m_pInt; - free( m_pInt ); - m_pInt = &m_iBitStringStorage; - return; - } - - m_pInt = (uint32 *)realloc( m_pInt, numInts * sizeof(int) ); -} - - -//----------------------------------------------------------------------------- -// Purpose: Free storage allocated with AllocInts -//----------------------------------------------------------------------------- -inline void CVarBitVecBase::FreeInts( void ) -{ - if ( m_numInts > 1 ) - { - free( m_pInt ); - } - m_pInt = NULL; -} - -#include "tier0/memdbgoff.h" - -// ------------------------------------------------------------------------ // -// CBitVecAccessor inlines. -// ------------------------------------------------------------------------ // - -inline CBitVecAccessor::CBitVecAccessor(uint32 *pDWords, int iBit) -{ - m_pDWords = pDWords; - m_iBit = iBit; -} - - -inline void CBitVecAccessor::operator=(int val) -{ - if(val) - m_pDWords[m_iBit >> 5] |= (1 << (m_iBit & 31)); - else - m_pDWords[m_iBit >> 5] &= ~(unsigned long)(1 << (m_iBit & 31)); -} - -inline CBitVecAccessor::operator uint32() -{ - return m_pDWords[m_iBit >> 5] & (1 << (m_iBit & 31)); -} - - -//============================================================================= - -#endif // BITVEC_H diff --git a/Resources/NetHook/public/coordsize.h b/Resources/NetHook/public/coordsize.h deleted file mode 100644 index 95e02a29..00000000 --- a/Resources/NetHook/public/coordsize.h +++ /dev/null @@ -1,98 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef COORDSIZE_H -#define COORDSIZE_H -#pragma once - -#include "worldsize.h" - -// OVERALL Coordinate Size Limits used in COMMON.C MSG_*BitCoord() Routines (and someday the HUD) -#define COORD_INTEGER_BITS 14 -#define COORD_FRACTIONAL_BITS 5 -#define COORD_DENOMINATOR (1<<(COORD_FRACTIONAL_BITS)) -#define COORD_RESOLUTION (1.0/(COORD_DENOMINATOR)) - -// Special threshold for networking multiplayer origins -#define COORD_INTEGER_BITS_MP 11 -#define COORD_FRACTIONAL_BITS_MP_LOWPRECISION 3 -#define COORD_DENOMINATOR_LOWPRECISION (1<<(COORD_FRACTIONAL_BITS_MP_LOWPRECISION)) -#define COORD_RESOLUTION_LOWPRECISION (1.0/(COORD_DENOMINATOR_LOWPRECISION)) - -#define NORMAL_FRACTIONAL_BITS 11 -#define NORMAL_DENOMINATOR ( (1<<(NORMAL_FRACTIONAL_BITS)) - 1 ) -#define NORMAL_RESOLUTION (1.0/(NORMAL_DENOMINATOR)) - -// this is limited by the network fractional bits used for coords -// because net coords will be only be accurate to 5 bits fractional -// Standard collision test epsilon -// 1/32nd inch collision epsilon -#define DIST_EPSILON (0.03125) - -// Verify that coordsize.h and worldsize.h are consistently defined -#if (MAX_COORD_INTEGER != (1<=MIN_COORD_INTEGER*2) && (v.x<=MAX_COORD_INTEGER*2) && \ - (v.y>=MIN_COORD_INTEGER*2) && (v.y<=MAX_COORD_INTEGER*2) && \ - (v.z>=MIN_COORD_INTEGER*2) && (v.z<=MAX_COORD_INTEGER*2) ); \ - - -#endif // WORLDSIZE_H \ No newline at end of file diff --git a/Resources/NetHook/sigscan.cpp b/Resources/NetHook/sigscan.cpp deleted file mode 100644 index d574b02b..00000000 --- a/Resources/NetHook/sigscan.cpp +++ /dev/null @@ -1,124 +0,0 @@ - -#include "sigscan.h" - -/* There is no ANSI ustrncpy */ -unsigned char* ustrncpy(unsigned char *dest, const unsigned char *src, int len) { - while(len--) - dest[len] = src[len]; - - return dest; -} - -/* ////////////////////////////////////// - CSigScan Class - ////////////////////////////////////// */ -unsigned char* CSigScan::base_addr; -size_t CSigScan::base_len; -void *(*CSigScan::sigscan_dllfunc)(const char *pName, int *pReturnCode); - -/* Initialize the Signature Object */ -int CSigScan::Init(unsigned char *sig, char *mask, size_t len) { - is_set = 0; - - sig_len = len; - - if ( sig_str ) - delete[] sig_str; - - sig_str = new unsigned char[sig_len]; - ustrncpy(sig_str, sig, sig_len); - - if ( sig_mask ) - delete[] sig_mask; - - sig_mask = new char[sig_len/*+1*/]; - strncpy(sig_mask, mask, sig_len); - //sig_mask[sig_len+1] = 0; - - if(!base_addr) - return 2; // GetDllMemInfo() Failed - - if((sig_addr = FindSignature()) == NULL) - return 1; // FindSignature() Failed - - is_set = 1; - // SigScan Successful! - - return 0; -} - -/* Destructor frees sig-string allocated memory */ -CSigScan::~CSigScan(void) { - delete[] sig_str; - delete[] sig_mask; -} - -/* Get base address of the server module (base_addr) and get its ending offset (base_len) */ -bool CSigScan::GetDllMemInfo(void) { - void *pAddr = (void*)sigscan_dllfunc; - base_addr = 0; - base_len = 0; - - #ifdef WIN32 - MEMORY_BASIC_INFORMATION mem; - - if(!pAddr) - return false; // GetDllMemInfo failed!pAddr - - if(!VirtualQuery(pAddr, &mem, sizeof(mem))) - return false; - - base_addr = (unsigned char*)mem.AllocationBase; - - IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER*)mem.AllocationBase; - IMAGE_NT_HEADERS *pe = (IMAGE_NT_HEADERS*)((unsigned long)dos+(unsigned long)dos->e_lfanew); - - if(pe->Signature != IMAGE_NT_SIGNATURE) { - base_addr = 0; - return false; // GetDllMemInfo failedpe points to a bad location - } - - base_len = (size_t)pe->OptionalHeader.SizeOfImage; - - #else - - Dl_info info; - struct stat buf; - - if(!dladdr(pAddr, &info)) - return false; - - if(!info.dli_fbase || !info.dli_fname) - return false; - - if(stat(info.dli_fname, &buf) != 0) - return false; - - base_addr = (unsigned char*)info.dli_fbase; - base_len = buf.st_size; - #endif - - return true; -} - -/* Scan for the signature in memory then return the starting position's address */ -void* CSigScan::FindSignature(void) { - unsigned char *pBasePtr = base_addr; - unsigned char *pEndPtr = base_addr+base_len; - size_t i; - - while(pBasePtr < pEndPtr) { - for(i = 0;i < sig_len;i++) { - if((sig_mask[i] != '?') && (sig_str[i] != pBasePtr[i])) - break; - } - - // If 'i' reached the end, we know we have a match! - if(i == sig_len) - return (void*)pBasePtr; - - pBasePtr++; - } - - return NULL; -} \ No newline at end of file diff --git a/Resources/NetHook/sigscan.h b/Resources/NetHook/sigscan.h deleted file mode 100644 index b05e7197..00000000 --- a/Resources/NetHook/sigscan.h +++ /dev/null @@ -1,66 +0,0 @@ -#ifndef SIGSCAN_H -#define SIGSCAN_H - -#include "interface.h" - -#include - -#ifdef _WIN32 - #define WIN32_LEAN_AND_MEAN - #include -#else - #include - #include - #include -#endif - -class CSigScan { -private: - /* Private Variables */ - /* Base Address of the server module in memory */ - static unsigned char *base_addr; - /* The length to the module's ending address */ - static size_t base_len; - - /* The signature to scan for */ - unsigned char *sig_str; - /* A mask to ignore certain bytes in the signature such as addresses - The mask should be as long as all the bytes in the signature string - Use '?' to ignore a byte and 'x' to check it - Example: "xxx????xx" - The first 3 bytes are checked, then the next 4 are - ignored, then the last 2 are checked */ - char *sig_mask; - /* The length of sig_str and sig_mask (not including a terminating null for sig_mask) */ - size_t sig_len; - - /* Private Functions */ - void* FindSignature(void); - -public: - /* Public Variables */ - - /* sigscan_dllfunc is a pointer of something that resides inside the gamedll so we can get - the base address of it. From a SourceMM plugin, just set this to ismm->serverFactory(0) - in Load(). From a Valve Server Plugin, you must set this to an actual factory returned - from gameServerFactory and hope that a SourceMM plugin did not override it. */ - static void *(*sigscan_dllfunc)(const char *pName, int *pReturnCode); - - /* If the scan was successful or not */ - char is_set; - /* Starting address of the found function */ - void *sig_addr; - - CSigScan(void): sig_str(NULL), sig_mask(NULL), sig_len(0), sig_addr(NULL) {} - ~CSigScan(void); - - static bool GetDllMemInfo(void); - int Init(unsigned char *sig, char *mask, size_t len); -}; - -/* Sigscanned member functions are casted to member function pointers of this class - and called with member function pointer syntax */ -class EmptyClass { }; - -void InitSigs(void); - -#endif \ No newline at end of file diff --git a/Resources/NetHook/steam/clientmsgs.h b/Resources/NetHook/steam/clientmsgs.h deleted file mode 100644 index 11876d18..00000000 --- a/Resources/NetHook/steam/clientmsgs.h +++ /dev/null @@ -1,90 +0,0 @@ - -#ifndef CLIENTMSGS_H_ -#define CLIENTMSGS_H_ -#ifdef _WIN32 -#pragma once -#endif - - -#include "steam/steamtypes.h" -#include "steam/csteamid.h" - - - -#pragma pack( push, 1 ) - -struct MsgChannelEncryptRequest_t -{ - uint32 m_unProtocolVer; - int32 m_EUniverse; // EUniverse -}; - -struct MsgChannelEncryptResponse_t -{ - uint32 m_unProtocolVer; - uint32 m_cubEncryptedKey; -}; - -struct MsgChannelEncryptResult_t -{ - int32 m_EResult; -}; - -struct MsgMulti_t -{ - uint32 m_cubUnzipped; -}; - -struct MsgClientAnonLogOn_t -{ - uint32 m_unProtocolVer; - - uint32 m_unIPPrivateObfuscated; - uint32 m_unIPPublic; - -}; - -struct MsgClientLogOnResponse_t -{ - int m_EResult; - - int m_nOutOfGameHeartbeatRateSec; - int m_nInGameHeartbeatRateSec; - - CSteamID m_ulClientSuppliedSteamId; - - uint32 m_unIPPublic; - - RTime32 m_RTime32ServerRealTime; -}; - - -struct MsgClientLogOnWithCredentials_t -{ - uint32 m_unProtocolVer; - - uint32 m_unIPPrivateObfuscated; - uint32 m_unIPPublic; - - uint64 m_ulClientSuppliedSteamId; - - uint32 m_unTicketLength; - - char m_rgchAccountName[ 64 ]; - char m_rgchPassword[ 20 ]; - - uint32 m_qosLevel; // ENetQOSLevel -}; - -struct MsgClientRegisterAuthTicketWithCM_t -{ - uint32 m_unProtocolVer; - uint32 m_unTicketLengthWithSignature; //B0 00 00 00 -}; - - - -#pragma pack( pop ) - - -#endif // !CLIENTMSGS_H_ diff --git a/Resources/NetHook/steam/csteamid.h b/Resources/NetHook/steam/csteamid.h deleted file mode 100644 index 79951696..00000000 --- a/Resources/NetHook/steam/csteamid.h +++ /dev/null @@ -1,515 +0,0 @@ - -#ifndef CSTEAMID_H -#define CSTEAMID_H -#ifdef _WIN32 -#pragma once -#endif - -#include "steamtypes.h" - -#pragma pack( push, 1 ) - -// Steam universes. Each universe is a self-contained Steam instance. -enum EUniverse -{ - k_EUniverseInvalid = 0, - k_EUniversePublic = 1, - k_EUniverseBeta = 2, - k_EUniverseInternal = 3, - k_EUniverseDev = 4, - k_EUniverseRC = 5, - - k_EUniverseMax -}; - - -// Steam account types -enum EAccountType -{ - k_EAccountTypeInvalid = 0, - k_EAccountTypeIndividual = 1, // single user account - k_EAccountTypeMultiseat = 2, // multiseat (e.g. cybercafe) account - k_EAccountTypeGameServer = 3, // game server account - k_EAccountTypeAnonGameServer = 4, // anonymous game server account - k_EAccountTypePending = 5, // pending - k_EAccountTypeContentServer = 6, // content server - k_EAccountTypeClan = 7, - k_EAccountTypeChat = 8, - k_EAccountTypeP2PSuperSeeder = 9, // a fake steamid used by superpeers to seed content to users of Steam P2P stuff - k_EAccountTypeAnonUser = 10, - - // Max of 16 items in this field - k_EAccountTypeMax -}; - -const int k_unSteamAccountIDMask = 0xFFFFFFFF; -const int k_unSteamAccountInstanceMask = 0x000FFFFF; - -// Special flags for Chat accounts - they go in the top 8 bits -// of the steam ID's "instance", leaving 12 for the actual instances -enum EChatSteamIDInstanceFlags -{ - k_EChatAccountInstanceMask = 0x00000FFF, // top 8 bits are flags - - k_EChatInstanceFlagClan = ( k_unSteamAccountInstanceMask + 1 ) >> 1, // top bit - k_EChatInstanceFlagLobby = ( k_unSteamAccountInstanceMask + 1 ) >> 2, // next one down, etc - k_EChatInstanceFlagMMSLobby = ( k_unSteamAccountInstanceMask + 1 ) >> 3, // next one down, etc - - // Max of 8 flags -}; - -// Steam ID structure (64 bits total) -class CSteamID -{ -public: - - //----------------------------------------------------------------------------- - // Purpose: Constructor - //----------------------------------------------------------------------------- - CSteamID() - { - m_steamid.m_comp.m_unAccountID = 0; - m_steamid.m_comp.m_EAccountType = k_EAccountTypeInvalid; - m_steamid.m_comp.m_EUniverse = k_EUniverseInvalid; - m_steamid.m_comp.m_unAccountInstance = 0; - } - - - //----------------------------------------------------------------------------- - // Purpose: Constructor - // Input : unAccountID - 32-bit account ID - // eUniverse - Universe this account belongs to - // eAccountType - Type of account - //----------------------------------------------------------------------------- - CSteamID( uint32 unAccountID, EUniverse eUniverse, EAccountType eAccountType ) - { - Set( unAccountID, eUniverse, eAccountType ); - } - - - //----------------------------------------------------------------------------- - // Purpose: Constructor - // Input : unAccountID - 32-bit account ID - // unAccountInstance - instance - // eUniverse - Universe this account belongs to - // eAccountType - Type of account - //----------------------------------------------------------------------------- - CSteamID( uint32 unAccountID, unsigned int unAccountInstance, EUniverse eUniverse, EAccountType eAccountType ) - { -#if defined(_SERVER) && defined(Assert) - Assert( ! ( ( k_EAccountTypeIndividual == eAccountType ) && ( 1 != unAccountInstance ) ) ); // enforce that for individual accounts, instance is always 1 -#endif // _SERVER - InstancedSet( unAccountID, unAccountInstance, eUniverse, eAccountType ); - } - - - //----------------------------------------------------------------------------- - // Purpose: Constructor - // Input : ulSteamID - 64-bit representation of a Steam ID - // Note: Will not accept a uint32 or int32 as input, as that is a probable mistake. - // See the stubbed out overloads in the private: section for more info. - //----------------------------------------------------------------------------- - CSteamID( uint64 ulSteamID ) - { - SetFromUint64( ulSteamID ); - } - - - //----------------------------------------------------------------------------- - // Purpose: Sets parameters for steam ID - // Input : unAccountID - 32-bit account ID - // eUniverse - Universe this account belongs to - // eAccountType - Type of account - //----------------------------------------------------------------------------- - void Set( uint32 unAccountID, EUniverse eUniverse, EAccountType eAccountType ) - { - m_steamid.m_comp.m_unAccountID = unAccountID; - m_steamid.m_comp.m_EUniverse = eUniverse; - m_steamid.m_comp.m_EAccountType = eAccountType; - - if ( eAccountType == k_EAccountTypeClan ) - { - m_steamid.m_comp.m_unAccountInstance = 0; - } - else - { - m_steamid.m_comp.m_unAccountInstance = 1; - } - } - - - //----------------------------------------------------------------------------- - // Purpose: Sets parameters for steam ID - // Input : unAccountID - 32-bit account ID - // eUniverse - Universe this account belongs to - // eAccountType - Type of account - //----------------------------------------------------------------------------- - void InstancedSet( uint32 unAccountID, uint32 unInstance, EUniverse eUniverse, EAccountType eAccountType ) - { - m_steamid.m_comp.m_unAccountID = unAccountID; - m_steamid.m_comp.m_EUniverse = eUniverse; - m_steamid.m_comp.m_EAccountType = eAccountType; - m_steamid.m_comp.m_unAccountInstance = unInstance; - } - - - //----------------------------------------------------------------------------- - // Purpose: Initializes a steam ID from its 52 bit parts and universe/type - // Input : ulIdentifier - 52 bits of goodness - //----------------------------------------------------------------------------- - void FullSet( uint64 ulIdentifier, EUniverse eUniverse, EAccountType eAccountType ) - { - m_steamid.m_comp.m_unAccountID = ( ulIdentifier & 0xFFFFFFFF ); // account ID is low 32 bits - m_steamid.m_comp.m_unAccountInstance = ( ( ulIdentifier >> 32 ) & 0xFFFFF ); // account instance is next 20 bits - m_steamid.m_comp.m_EUniverse = eUniverse; - m_steamid.m_comp.m_EAccountType = eAccountType; - } - - - //----------------------------------------------------------------------------- - // Purpose: Initializes a steam ID from its 64-bit representation - // Input : ulSteamID - 64-bit representation of a Steam ID - //----------------------------------------------------------------------------- - void SetFromUint64( uint64 ulSteamID ) - { - m_steamid.m_unAll64Bits = ulSteamID; - } - - //----------------------------------------------------------------------------- - // Purpose: Initializes a steam ID from a Steam2 ID structure - // Input: pTSteamGlobalUserID - Steam2 ID to convert - // eUniverse - universe this ID belongs to - //----------------------------------------------------------------------------- - void SetFromSteam2( TSteamGlobalUserID *pTSteamGlobalUserID, EUniverse eUniverse ) - { - m_steamid.m_comp.m_unAccountID = pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits * 2 + - pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits; - m_steamid.m_comp.m_EUniverse = eUniverse; // set the universe - m_steamid.m_comp.m_EAccountType = k_EAccountTypeIndividual; // Steam 2 accounts always map to account type of individual - m_steamid.m_comp.m_unAccountInstance = 1; // individual accounts always have an account instance ID of 1 - } - - //----------------------------------------------------------------------------- - // Purpose: Fills out a Steam2 ID structure - // Input: pTSteamGlobalUserID - Steam2 ID to write to - //----------------------------------------------------------------------------- - void ConvertToSteam2( TSteamGlobalUserID *pTSteamGlobalUserID ) const - { - // only individual accounts have any meaning in Steam 2, only they can be mapped - // Assert( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ); - - pTSteamGlobalUserID->m_SteamInstanceID = 0; - pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits = m_steamid.m_comp.m_unAccountID % 2; - pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits = m_steamid.m_comp.m_unAccountID / 2; - } - - //----------------------------------------------------------------------------- - // Purpose: Converts steam ID to its 64-bit representation - // Output : 64-bit representation of a Steam ID - //----------------------------------------------------------------------------- - uint64 ConvertToUint64() const - { - return m_steamid.m_unAll64Bits; - } - - - //----------------------------------------------------------------------------- - // Purpose: Converts the static parts of a steam ID to a 64-bit representation. - // For multiseat accounts, all instances of that account will have the - // same static account key, so they can be grouped together by the static - // account key. - // Output : 64-bit static account key - //----------------------------------------------------------------------------- - uint64 GetStaticAccountKey() const - { - // note we do NOT include the account instance (which is a dynamic property) in the static account key - return (uint64) ( ( ( (uint64) m_steamid.m_comp.m_EUniverse ) << 56 ) + ((uint64) m_steamid.m_comp.m_EAccountType << 52 ) + m_steamid.m_comp.m_unAccountID ); - } - - - //----------------------------------------------------------------------------- - // Purpose: create an anonymous game server login to be filled in by the AM - //----------------------------------------------------------------------------- - void CreateBlankAnonLogon( EUniverse eUniverse ) - { - m_steamid.m_comp.m_unAccountID = 0; - m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonGameServer; - m_steamid.m_comp.m_EUniverse = eUniverse; - m_steamid.m_comp.m_unAccountInstance = 0; - } - - - //----------------------------------------------------------------------------- - // Purpose: create an anonymous game server login to be filled in by the AM - //----------------------------------------------------------------------------- - void CreateBlankAnonUserLogon( EUniverse eUniverse ) - { - m_steamid.m_comp.m_unAccountID = 0; - m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonUser; - m_steamid.m_comp.m_EUniverse = eUniverse; - m_steamid.m_comp.m_unAccountInstance = 0; - } - - //----------------------------------------------------------------------------- - // Purpose: Is this an anonymous game server login that will be filled in? - //----------------------------------------------------------------------------- - bool BBlankAnonAccount() const - { - return m_steamid.m_comp.m_unAccountID == 0 && BAnonAccount() && m_steamid.m_comp.m_unAccountInstance == 0; - } - - //----------------------------------------------------------------------------- - // Purpose: Is this a game server account id? - //----------------------------------------------------------------------------- - bool BGameServerAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; - } - - //----------------------------------------------------------------------------- - // Purpose: Is this a content server account id? - //----------------------------------------------------------------------------- - bool BContentServerAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeContentServer; - } - - - //----------------------------------------------------------------------------- - // Purpose: Is this a clan account id? - //----------------------------------------------------------------------------- - bool BClanAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan; - } - - - //----------------------------------------------------------------------------- - // Purpose: Is this a chat account id? - //----------------------------------------------------------------------------- - bool BChatAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat; - } - - //----------------------------------------------------------------------------- - // Purpose: Is this a chat account id? - //----------------------------------------------------------------------------- - bool IsLobby() const - { - return ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat ) - && ( m_steamid.m_comp.m_unAccountInstance & k_EChatInstanceFlagLobby ); - } - - - //----------------------------------------------------------------------------- - // Purpose: Is this an individual user account id? - //----------------------------------------------------------------------------- - bool BIndividualAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual; - } - - - //----------------------------------------------------------------------------- - // Purpose: Is this an anonymous account? - //----------------------------------------------------------------------------- - bool BAnonAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; - } - - //----------------------------------------------------------------------------- - // Purpose: Is this an anonymous user account? ( used to create an account or reset a password ) - //----------------------------------------------------------------------------- - bool BAnonUserAccount() const - { - return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser; - } - - - // simple accessors - void SetAccountID( uint32 unAccountID ) { m_steamid.m_comp.m_unAccountID = unAccountID; } - uint32 GetAccountID() const { return m_steamid.m_comp.m_unAccountID; } - uint32 GetUnAccountInstance() const { return m_steamid.m_comp.m_unAccountInstance; } - EAccountType GetEAccountType() const { return ( EAccountType ) m_steamid.m_comp.m_EAccountType; } - EUniverse GetEUniverse() const { return m_steamid.m_comp.m_EUniverse; } - void SetEUniverse( EUniverse eUniverse ) { m_steamid.m_comp.m_EUniverse = eUniverse; } - bool IsValid() const; - - // this set of functions is hidden, will be moved out of class - explicit CSteamID( const char *pchSteamID, EUniverse eDefaultUniverse = k_EUniverseInvalid ); - const char * Render() const // renders this steam ID to string - { - static char szSteamID[64]; - switch(m_steamid.m_comp.m_EAccountType) - { - case k_EAccountTypeInvalid: - case k_EAccountTypeIndividual: - sprintf_s(szSteamID, sizeof(szSteamID), "STEAM_0:%u:%u", (m_steamid.m_comp.m_unAccountID % 2) ? 1 : 0, (int32)m_steamid.m_comp.m_unAccountID/2); - break; - default: - sprintf_s(szSteamID, sizeof(szSteamID), "%llu", ConvertToUint64()); - } - return szSteamID; - } - static const char * Render( uint64 ulSteamID ) // static method to render a uint64 representation of a steam ID to a string - { - return CSteamID(ulSteamID).Render(); - } - - const char *SteamRender() const // renders this steam ID to string using the new rendering style - { - const int k_cBufLen = 37; - const int k_cBufs = 4; - char* pchBuf; - - static char rgchBuf[k_cBufs][k_cBufLen]; - static int nBuf = 0; - - pchBuf = rgchBuf[nBuf++]; - nBuf %= k_cBufs; - - switch (m_steamid.m_comp.m_EAccountType) - { - case k_EAccountTypeAnonGameServer: - sprintf_s(pchBuf, k_cBufLen, "[A:%u:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID, m_steamid.m_comp.m_unAccountInstance); - break; - case k_EAccountTypeGameServer: - sprintf_s(pchBuf, k_cBufLen, "[G:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - case k_EAccountTypeMultiseat: - sprintf_s(pchBuf, k_cBufLen, "[M:%u:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID, m_steamid.m_comp.m_unAccountInstance); - break; - case k_EAccountTypePending: - sprintf_s(pchBuf, k_cBufLen, "[P:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - case k_EAccountTypeContentServer: - sprintf_s(pchBuf, k_cBufLen, "[C:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - case k_EAccountTypeClan: - sprintf_s(pchBuf, k_cBufLen, "[g:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - case k_EAccountTypeChat: - switch (m_steamid.m_comp.m_unAccountInstance & ~k_EChatAccountInstanceMask) - { - case k_EChatInstanceFlagClan: - sprintf_s(pchBuf, k_cBufLen, "[c:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - case k_EChatInstanceFlagLobby: - sprintf_s(pchBuf, k_cBufLen, "[L:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - default: - sprintf_s(pchBuf, k_cBufLen, "[T:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - } - break; - case k_EAccountTypeInvalid: - sprintf_s(pchBuf, k_cBufLen, "[I:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - case k_EAccountTypeIndividual: - sprintf_s(pchBuf, k_cBufLen, "[U:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - default: - sprintf_s(pchBuf, k_cBufLen, "[i:%u:%u]", m_steamid.m_comp.m_EUniverse, m_steamid.m_comp.m_unAccountID); - break; - } - - return pchBuf; - } - - static const char *SteamRender( uint64 ulSteamID ) // static method to render a uint64 representation of a steam ID to a string - { - return CSteamID(ulSteamID).SteamRender(); - } - - void SetFromString( const char *pchSteamID, EUniverse eDefaultUniverse ); - bool SetFromSteam2String( const char *pchSteam2ID, EUniverse eUniverse ); - - inline bool operator==( const CSteamID &val ) const { return m_steamid.m_unAll64Bits == val.m_steamid.m_unAll64Bits; } - inline bool operator!=( const CSteamID &val ) const { return !operator==( val ); } - inline bool operator<( const CSteamID &val ) const { return m_steamid.m_unAll64Bits < val.m_steamid.m_unAll64Bits; } - inline bool operator>( const CSteamID &val ) const { return m_steamid.m_unAll64Bits > val.m_steamid.m_unAll64Bits; } - - // DEBUG function - bool BValidExternalSteamID() const; - -private: - // These are defined here to prevent accidental implicit conversion of a u32AccountID to a CSteamID. - // If you get a compiler error about an ambiguous constructor/function then it may be because you're - // passing a 32-bit int to a function that takes a CSteamID. You should explicitly create the SteamID - // using the correct Universe and account Type/Instance values. - CSteamID( uint32 ); - CSteamID( int32 ); - - // 64 bits total - union SteamID_t - { - struct SteamIDComponent_t - { - uint32 m_unAccountID : 32; // unique account identifier - unsigned int m_unAccountInstance : 20; // dynamic instance ID (used for multiseat type accounts only) - unsigned int m_EAccountType : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference - EUniverse m_EUniverse : 8; // universe this account belongs to - } m_comp; - - uint64 m_unAll64Bits; - } m_steamid; -}; - - -inline bool CSteamID::IsValid() const -{ - if ( m_steamid.m_comp.m_EAccountType <= k_EAccountTypeInvalid || m_steamid.m_comp.m_EAccountType >= k_EAccountTypeMax ) - return false; - - if ( m_steamid.m_comp.m_EUniverse <= k_EUniverseInvalid || m_steamid.m_comp.m_EUniverse >= k_EUniverseMax ) - return false; - - if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ) - { - if ( m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance != 1 ) - return false; - } - - if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan ) - { - if ( m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance != 0 ) - return false; - } - return true; -} - -// generic invalid CSteamID -const CSteamID k_steamIDNil; - -// This steamID comes from a user game connection to an out of date GS that hasnt implemented the protocol -// to provide its steamID -const CSteamID k_steamIDOutofDateGS( 0, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ); -// This steamID comes from a user game connection to an sv_lan GS -const CSteamID k_steamIDLanModeGS( 0, 0, k_EUniversePublic, k_EAccountTypeInvalid ); -// This steamID can come from a user game connection to a GS that has just booted but hasnt yet even initialized -// its steam3 component and started logging on. -const CSteamID k_steamIDNotInitYetGS( 1, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ); -// This steamID can come from a user game connection to a GS that isn't using the steam authentication system but still -// wants to support the "Join Game" option in the friends list -const CSteamID k_steamIDNonSteamGS( 2, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ); - - -#ifdef STEAM -// Returns the matching chat steamID, with the default instance of 0 -// If the steamID passed in is already of type k_EAccountTypeChat it will be returned with the same instance -CSteamID ChatIDFromSteamID( const CSteamID &steamID ); -// Returns the matching clan steamID, with the default instance of 0 -// If the steamID passed in is already of type k_EAccountTypeClan it will be returned with the same instance -CSteamID ClanIDFromSteamID( const CSteamID &steamID ); -// Asserts steamID type before conversion -CSteamID ChatIDFromClanID( const CSteamID &steamIDClan ); -// Asserts steamID type before conversion -CSteamID ClanIDFromChatID( const CSteamID &steamIDChat ); - -#endif // _STEAM - -#pragma pack( pop ) - -#endif // CSTEAMID_H diff --git a/Resources/NetHook/steam/emsg.h b/Resources/NetHook/steam/emsg.h deleted file mode 100644 index 9d3305c9..00000000 --- a/Resources/NetHook/steam/emsg.h +++ /dev/null @@ -1,348 +0,0 @@ - -#ifndef EMSG_H_ -#define EMSG_H_ -#ifdef _WIN32 -#pragma once -#endif - -enum EMsg -{ - k_EMsgInvalid = 0, - - k_EMsgMulti = 1, - - k_EMsgRemoteSysID = 128, - k_EMsgClientChatAction = 597, - k_EMsgCSUserContentRequest = 652, - k_EMsgClientLogOn_Deprecated = 701, - k_EMsgClientAnonLogOn_Deprecated = 702, - k_EMsgClientHeartBeat = 703, - k_EMsgClientVACResponse = 704, - k_EMsgClientLogOff = 706, - k_EMsgClientNoUDPConnectivity = 707, - k_EMsgClientInformOfCreateAccount = 708, - k_EMsgClientAckVACBan = 709, - k_EMsgClientConnectionStats = 710, - k_EMsgClientInitPurchase = 711, - k_EMsgClientPingResponse = 712, - k_EMsgClientAddFriend = 713, - k_EMsgClientRemoveFriend = 714, - k_EMsgClientGamesPlayedNoDataBlob = 715, - k_EMsgClientChangeStatus = 716, - k_EMsgClientVacStatusResponse = 717, - k_EMsgClientFriendMsg = 718, - k_EMsgClientGetFinalPrice = 722, - k_EMsgClientSystemIM = 726, - k_EMsgClientSystemIMAck = 727, - k_EMsgClientGetLicenses = 728, - k_EMsgClientCancelLicense = 729, - k_EMsgClientGetLegacyGameKey = 730, - k_EMsgClientContentServerLogOn_Deprecated = 731, - k_EMsgClientAckVACBan2 = 732, - k_EMsgClientCompletePurchase = 733, - k_EMsgClientCancelPurchase = 734, - k_EMsgClientAckMessageByGID = 735, - k_EMsgClientGetPurchaseReceipts = 736, - k_EMsgClientAckPurchaseReceipt = 737, - k_EMsgClientSendGuestPass = 739, - k_EMsgClientAckGuestPass = 740, - k_EMsgClientRedeemGuestPass = 741, - k_EMsgClientGamesPlayed = 742, - k_EMsgClientRegisterKey = 743, - k_EMsgClientInviteUserToClan = 744, - k_EMsgClientAcknowledgeClanInvite = 745, - k_EMsgClientPurchaseWithMachineID = 746, - k_EMsgClientAppUsageEvent = 747, - k_EMsgClientGetGiftTargetList = 748, - k_EMsgClientGetGiftTargetListResponse = 749, - k_EMsgClientLogOnResponse = 751, - k_EMsgClientVACChallenge = 753, - k_EMsgClientSetHeartbeatRate = 755, - k_EMsgClientNotLoggedOnDeprecated = 756, - k_EMsgClientLoggedOff = 757, - k_EMsgGSApprove = 758, - k_EMsgGSDeny = 759, - k_EMsgGSKick = 760, - k_EMsgClientCreateAcctResponse = 761, - k_EMsgClientPurchaseResponse = 763, - k_EMsgClientPing = 764, - k_EMsgClientNOP = 765, - k_EMsgClientPersonaState = 766, - k_EMsgClientFriendsList = 767, - k_EMsgClientAccountInfo = 768, - k_EMsgClientAddFriendResponse = 769, - k_EMsgClientVacStatusQuery = 770, - k_EMsgClientNewsUpdate = 771, - k_EMsgClientGameConnectDeny = 773, - k_EMsgGSStatusReply = 774, - k_EMsgClientGetFinalPriceResponse = 775, - k_EMsgClientGameConnectTokens = 779, - k_EMsgClientLicenseList = 780, - k_EMsgClientCancelLicenseResponse = 781, - k_EMsgClientVACBanStatus = 782, - k_EMsgClientCMList = 783, - k_EMsgClientEncryptPct = 784, - k_EMsgClientGetLegacyGameKeyResponse = 785, - k_EMsgCSUserContentApprove = 787, - k_EMsgCSUserContentDeny = 788, - k_EMsgClientInitPurchaseResponse = 789, - k_EMsgClientAddFriend2 = 791, - k_EMsgClientAddFriendResponse2 = 792, - k_EMsgClientInviteFriend = 793, - k_EMsgClientInviteFriendResponse = 794, - k_EMsgClientSendGuestPassResponse = 795, - k_EMsgClientAckGuestPassResponse = 796, - k_EMsgClientRedeemGuestPassResponse = 797, - k_EMsgClientUpdateGuestPassesList = 798, - k_EMsgClientChatMsg = 799, - k_EMsgClientChatInvite = 800, - k_EMsgClientJoinChat = 801, - k_EMsgClientChatMemberInfo = 802, - k_EMsgClientLogOnWithCredentials_Deprecated = 803, - k_EMsgClientPasswordChange = 804, - k_EMsgClientPasswordChangeResponse = 805, - k_EMsgClientChatEnter = 807, - k_EMsgClientFriendRemovedFromSource = 808, - k_EMsgClientCreateChat = 809, - k_EMsgClientCreateChatResponse = 810, - k_EMsgClientUpdateChatMetadata = 811, - k_EMsgClientP2PIntroducerMessage = 813, - k_EMsgClientChatActionResult = 814, - k_EMsgClientRequestFriendData = 815, - k_EMsgClientOneTimeWGAuthPassword = 816, - k_EMsgClientGetUserStats = 818, - k_EMsgClientGetUserStatsResponse = 819, - k_EMsgClientStoreUserStats = 820, - k_EMsgClientStoreUserStatsResponse = 821, - k_EMsgClientClanState = 822, - k_EMsgClientServiceModule = 830, - k_EMsgClientServiceCall = 831, - k_EMsgClientServiceCallResponse = 832, - k_EMsgClientNatTraversalStatEvent = 839, - k_EMsgClientAppInfoRequest = 840, - k_EMsgClientAppInfoResponse = 841, - k_EMsgClientSteamUsageEvent = 842, - k_EMsgClientEmailChange = 843, - k_EMsgClientPersonalQAChange = 844, - k_EMsgClientCheckPassword = 845, - k_EMsgClientResetPassword = 846, - k_EMsgClientCheckPasswordResponse = 848, - k_EMsgClientResetPasswordResponse = 849, - k_EMsgClientSessionToken = 850, - k_EMsgClientDRMProblemReport = 851, - k_EMsgClientSetIgnoreFriend = 855, - k_EMsgClientSetIgnoreFriendResponse = 856, - k_EMsgClientGetAppOwnershipTicket = 857, - k_EMsgClientGetAppOwnershipTicketResponse = 858, - k_EMsgClientGetLobbyListResponse = 860, - k_EMsgClientGetLobbyMetadata = 861, - k_EMsgClientGetLobbyMetadataResponse = 862, - k_EMsgClientVTTCert = 863, - k_EMsgClientAppInfoUpdate = 866, - k_EMsgClientAppInfoChanges = 867, - k_EMsgClientServerList = 880, - k_EMsgClientGetFriendsLobbies = 888, - k_EMsgClientGetFriendsLobbiesResponse = 889, - k_EMsgClientGetLobbyList = 890, - k_EMsgClientEmailChangeResponse = 891, - k_EMsgClientSecretQAChangeResponse = 892, - k_EMsgClientPasswordChange2 = 893, - k_EMsgClientEmailChange2 = 894, - k_EMsgClientPersonalQAChange2 = 895, - k_EMsgClientDRMBlobRequest = 896, - k_EMsgClientDRMBlobResponse = 897, - k_EMsgClientLookupKey = 898, - k_EMsgClientLookupKeyResponse = 899, - k_EMsgGSDisconnectNotice = 901, - k_EMsgGSStatus = 903, - k_EMsgGSUserPlaying = 905, - k_EMsgGSStatus2 = 906, - k_EMsgGSStatusUpdate_Unused = 907, - k_EMsgGSServerType = 908, - k_EMsgGSPlayerList = 909, - k_EMsgGSGetUserAchievementStatus = 910, - k_EMsgGSGetUserAchievementStatusResponse = 911, - k_EMsgGSGetPlayStats = 918, - k_EMsgGSGetPlayStatsResponse = 919, - k_EMsgGSGetUserGroupStatus = 920, - k_EMsgGSGetUserGroupStatusResponse = 923, - k_EMsgGSGetReputation = 936, - k_EMsgGSGetReputationResponse = 937, - k_EMsgChannelEncryptRequest = 1303, - k_EMsgChannelEncryptResponse = 1304, - k_EMsgClientChatRoomInfo = 4026, - k_EMsgClientUFSUploadFileRequest = 5202, - k_EMsgClientUFSUploadFileResponse = 5203, - k_EMsgClientUFSUploadFileChunk = 5204, - k_EMsgClientUFSUploadFileFinished = 5205, - k_EMsgClientUFSGetFileListForApp = 5206, - k_EMsgClientUFSGetFileListForAppResponse = 5207, - k_EMsgClientUFSDownloadRequest = 5210, - k_EMsgClientUFSDownloadResponse = 5211, - k_EMsgClientUFSDownloadChunk = 5212, - k_EMsgClientUFSLoginRequest = 5213, - k_EMsgClientUFSLoginResponse = 5214, - k_EMsgClientUFSTransferHeartbeat = 5216, - k_EMsgClientUFSDeleteFileRequest = 5219, - k_EMsgClientUFSDeleteFileResponse = 5220, - k_EMsgClientUFSGetUGCDetails = 5226, - k_EMsgClientUFSGetUGCDetailsResponse = 5227, - k_EMsgClientUFSGetSingleFileInfo = 5230, - k_EMsgClientUFSGetSingleFileInfoResponse = 5231, - k_EMsgClientUFSShareFile = 5232, - k_EMsgClientUFSShareFileResponse = 5233, - k_EMsgClientRequestForgottenPasswordEmail = 5401, - k_EMsgClientRequestForgottenPasswordEmailResponse = 5402, - k_EMsgClientCreateAccountResponse = 5403, - k_EMsgClientResetForgottenPassword = 5404, - k_EMsgClientResetForgottenPasswordResponse = 5405, - k_EMsgClientCreateAccount2 = 5406, - k_EMsgClientInformOfResetForgottenPassword = 5407, - k_EMsgClientInformOfResetForgottenPasswordResponse = 5408, - k_EMsgClientAnonUserLogOn_Deprecated = 5409, - k_EMsgClientGamesPlayedWithDataBlob = 5410, - k_EMsgClientUpdateUserGameInfo = 5411, - k_EMsgClientFileToDownload = 5412, - k_EMsgClientFileToDownloadResponse = 5413, - k_EMsgClientLBSSetScore = 5414, - k_EMsgClientLBSSetScoreResponse = 5415, - k_EMsgClientLBSFindOrCreateLB = 5416, - k_EMsgClientLBSFindOrCreateLBResponse = 5417, - k_EMsgClientLBSGetLBEntries = 5418, - k_EMsgClientLBSGetLBEntriesResponse = 5419, - k_EMsgClientMarketingMessageUpdate = 5420, - k_EMsgClientChatDeclined = 5426, - k_EMsgClientFriendMsgIncoming = 5427, - k_EMsgClientAuthList_Deprecated = 5428, - k_EMsgClientTicketAuthComplete = 5429, - k_EMsgClientIsLimitedAccount = 5430, - k_EMsgClientAuthList = 5432, - k_EMsgClientStat = 5433, - k_EMsgClientP2PConnectionInfo = 5434, - k_EMsgClientP2PConnectionFailInfo = 5435, - k_EMsgClientGetNumberOfCurrentPlayers = 5436, - k_EMsgClientGetNumberOfCurrentPlayersResponse = 5437, - k_EMsgClientGetDepotDecryptionKey = 5438, - k_EMsgClientGetDepotDecryptionKeyResponse = 5439, - k_EMsgGSPerformHardwareSurvey = 5440, - k_EMsgClientEnableTestLicense = 5443, - k_EMsgClientEnableTestLicenseResponse = 5444, - k_EMsgClientDisableTestLicense = 5445, - k_EMsgClientDisableTestLicenseResponse = 5446, - k_EMsgClientRequestValidationMail = 5448, - k_EMsgClientRequestValidationMailResponse = 5449, - k_EMsgClientToGC = 5452, - k_EMsgClientFromGC = 5453, - k_EMsgClientRequestChangeMail = 5454, - k_EMsgClientRequestChangeMailResponse = 5455, - k_EMsgClientEmailAddrInfo = 5456, - k_EMsgClientPasswordChange3 = 5457, - k_EMsgClientEmailChange3 = 5458, - k_EMsgClientPersonalQAChange3 = 5459, - k_EMsgClientResetForgottenPassword3 = 5460, - k_EMsgClientRequestForgottenPasswordEmail3 = 5461, - k_EMsgClientCreateAccount3 = 5462, - k_EMsgClientNewLoginKey = 5463, - k_EMsgClientNewLoginKeyAccepted = 5464, - k_EMsgClientLogOnWithHash_Deprecated = 5465, - k_EMsgClientStoreUserStats2 = 5466, - k_EMsgClientStatsUpdated = 5467, - k_EMsgClientActivateOEMLicense = 5468, - k_EMsgClientRequestedClientStats = 5480, - k_EMsgClientStat2Int32 = 5481, - k_EMsgClientStat2 = 5482, - k_EMsgClientVerifyPassword = 5483, - k_EMsgClientVerifyPasswordResponse = 5484, - k_EMsgClientDRMDownloadRequest = 5485, - k_EMsgClientDRMDownloadResponse = 5486, - k_EMsgClientDRMFinalResult = 5487, - k_EMsgClientGetFriendsWhoPlayGame = 5488, - k_EMsgClientGetFriendsWhoPlayGameResponse = 5489, - k_EMsgClientOGSBeginSession = 5490, - k_EMsgClientOGSBeginSessionResponse = 5491, - k_EMsgClientOGSEndSession = 5492, - k_EMsgClientOGSEndSessionResponse = 5493, - k_EMsgClientOGSWriteRow = 5494, - k_EMsgClientDRMTest = 5495, - k_EMsgClientDRMTestResult = 5496, - k_EMsgClientServerUnavailable = 5500, - k_EMsgClientServersAvailable = 5501, - k_EMsgClientRegisterAuthTicketWithCM = 5502, - k_EMsgClientGCMsgFailed = 5503, - k_EMsgClientMicroTxnAuthRequest = 5504, - k_EMsgClientMicroTxnAuthorize = 5505, - k_EMsgClientMicroTxnAuthorizeResponse = 5506, - k_EMsgClientAppMinutesPlayedData = 5507, - k_EMsgClientGetMicroTxnInfo = 5508, - k_EMsgClientGetMicroTxnInfoResponse = 5509, - k_EMsgClientMarketingMessageUpdate2 = 5510, - k_EMsgClientDeregisterWithServer = 5511, - k_EMsgClientSubscribeToPersonaFeed = 5512, - k_EMsgClientLogon = 5514, - k_EMsgClientGetClientDetails = 5515, - k_EMsgClientGetClientDetailsResponse = 5516, - k_EMsgClientReportOverlayDetourFailure = 5517, - k_EMsgClientGetClientAppList = 5518, - k_EMsgClientGetClientAppListResponse = 5519, - k_EMsgClientInstallClientApp = 5520, - k_EMsgClientInstallClientAppResponse = 5521, - k_EMsgClientUninstallClientApp = 5522, - k_EMsgClientUninstallClientAppResponse = 5523, - k_EMsgClientSetClientAppUpdateState = 5524, - k_EMsgClientSetClientAppUpdateStateResponse = 5525, - k_EMsgClientRequestEncryptedAppTicket = 5526, - k_EMsgClientRequestEncryptedAppTicketResponse = 5527, - k_EMsgClientWalletInfoUpdate = 5528, - k_EMsgClientLBSSetUGC = 5529, - k_EMsgClientLBSSetUGCResponse = 5530, - k_EMsgClientAMGetClanOfficers = 5531, - k_EMsgClientAMGetClanOfficersResponse = 5532, - k_EMsgClientDFSAuthenticateRequest = 5605, - k_EMsgClientDFSAuthenticateResponse = 5606, - k_EMsgClientDFSEndSession = 5607, - k_EMsgClientDFSDownloadStatus = 5617, - k_EMsgClientMDSLoginRequest = 5801, - k_EMsgClientMDSLoginResponse = 5802, - k_EMsgClientMDSUploadManifestRequest = 5803, - k_EMsgClientMDSUploadManifestResponse = 5804, - k_EMsgClientMDSTransmitManifestDataChunk = 5805, - k_EMsgClientMDSHeartbeat = 5806, - k_EMsgClientMDSUploadDepotChunks = 5807, - k_EMsgClientMDSUploadDepotChunksResponse = 5808, - k_EMsgClientMDSInitDepotBuildRequest = 5809, - k_EMsgClientMDSInitDepotBuildResponse = 5810, - k_EMsgClientMDSGetDepotManifest = 5818, - k_EMsgClientMDSGetDepotManifestResponse = 5819, - k_EMsgClientMDSGetDepotManifestChunk = 5820, - k_EMsgClientMDSDownloadDepotChunksRequest = 5823, - k_EMsgClientMDSDownloadDepotChunksAsync = 5824, - k_EMsgClientMDSDownloadDepotChunksAck = 5825, - k_EMsgClientMMSCreateLobby = 6601, - k_EMsgClientMMSCreateLobbyResponse = 6602, - k_EMsgClientMMSJoinLobby = 6603, - k_EMsgClientMMSJoinLobbyResponse = 6604, - k_EMsgClientMMSLeaveLobby = 6605, - k_EMsgClientMMSLeaveLobbyResponse = 6606, - k_EMsgClientMMSGetLobbyList = 6607, - k_EMsgClientMMSGetLobbyListResponse = 6608, - k_EMsgClientMMSSetLobbyData = 6609, - k_EMsgClientMMSSetLobbyDataResponse = 6610, - k_EMsgClientMMSGetLobbyData = 6611, - k_EMsgClientMMSLobbyData = 6612, - k_EMsgClientMMSSendLobbyChatMsg = 6613, - k_EMsgClientMMSLobbyChatMsg = 6614, - k_EMsgClientMMSSetLobbyOwner = 6615, - k_EMsgClientMMSSetLobbyOwnerResponse = 6616, - k_EMsgClientMMSSetLobbyGameServer = 6617, - k_EMsgClientMMSLobbyGameServerSet = 6618, - k_EMsgClientMMSUserJoinedLobby = 6619, - k_EMsgClientMMSUserLeftLobby = 6620, - k_EMsgClientMMSInviteToLobby = 6621, - k_EMsgClientUDSP2PSessionStarted = 7001, - k_EMsgClientUDSP2PSessionEnded = 7002, - -}; - - - -#endif // !EMSG_H_ diff --git a/Resources/NetHook/steam/steamtypes.h b/Resources/NetHook/steam/steamtypes.h deleted file mode 100644 index 45e1fb0b..00000000 --- a/Resources/NetHook/steam/steamtypes.h +++ /dev/null @@ -1,306 +0,0 @@ - -#ifndef STEAMTYPES_H_ -#define STEAMTYPES_H_ -#ifdef _WIN32 -#pragma once -#endif - -#include - -#ifdef _WIN32 - #if defined( STEAM_API_EXPORTS ) - #define S_API extern "C" __declspec( dllexport ) - #else - #define S_API extern "C" __declspec( dllimport ) - #endif -#else - #define S_API extern "C" - - #ifndef __cdecl - #define __cdecl __attribute__((__cdecl__)) - #endif -#endif - -#if defined( __x86_64__ ) || defined( _WIN64 ) - #define X64BITS -#endif - - -#define STEAM_CALL __cdecl - - -// Steam-specific types. Defined here so this header file can be included in other code bases. -#ifndef WCHARTYPES_H - typedef unsigned char uint8; -#endif - -#if defined( _WIN32 ) - - typedef __int16 int16; - typedef unsigned __int16 uint16; - typedef __int32 int32; - typedef unsigned __int32 uint32; - typedef __int64 int64; - typedef unsigned __int64 uint64; - - #ifdef X64BITS - typedef __int64 intp; // intp is an integer that can accomodate a pointer - typedef unsigned __int64 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) - #else - typedef __int32 intp; - typedef unsigned __int32 uintp; - #endif - -#else // !_WIN32 - - typedef short int16; - typedef unsigned short uint16; - typedef int int32; - typedef unsigned int uint32; - typedef long long int64; - typedef unsigned long long uint64; - - #ifdef X64BITS - typedef long long intp; - typedef unsigned long long uintp; - #else - typedef int intp; - typedef unsigned int uintp; - #endif - -#endif // else _WIN32 - - -typedef uint64 SteamUnsigned64_t; - - -typedef void (*SteamAPIWarningMessageHook_t)(int hpipe, const char *message); - - -//----------------------------------------------------------------------------- -// GID (GlobalID) stuff -// This is a globally unique identifier. It's guaranteed to be unique across all -// racks and servers for as long as a given universe persists. -//----------------------------------------------------------------------------- -// NOTE: for GID parsing/rendering and other utils, see gid.h -typedef uint64 GID_t; - -const GID_t k_GIDNil = 0xffffffffffffffffull; - -// For convenience, we define a number of types that are just new names for GIDs -typedef GID_t JobID_t; // Each Job has a unique ID -typedef GID_t TxnID_t; // Each financial transaction has a unique ID - -const GID_t k_TxnIDNil = k_GIDNil; -const GID_t k_TxnIDUnknown = 0; - -// this is baked into client messages and interfaces as an int, -// make sure we never break this. AppIds and DepotIDs also presently -// share the same namespace, but since we'd like to change that in the future -// I've defined it seperately here. -typedef uint32 AppId_t; -typedef uint32 PackageId_t; -typedef uint32 DepotId_t; - -const AppId_t k_uAppIdInvalid = 0x0; - -const PackageId_t k_uPackageIdFreeSub = 0x0; -const PackageId_t k_uPackageIdInvalid = 0xFFFFFFFF; -const PackageId_t k_uPackageIdWallet = -2; -const PackageId_t k_uPackageIdMicroTxn = -3; - -const DepotId_t k_uDepotIdInvalid = 0x0; - - -typedef uint32 CellID_t; -const CellID_t k_uCellIDInvalid = 0xFFFFFFFF; - -// handle to a Steam API call -typedef uint64 SteamAPICall_t; -const SteamAPICall_t k_uAPICallInvalid = 0x0; - - -// handle to a communication pipe to the Steam client -typedef int32 HSteamPipe; -// handle to single instance of a steam user -typedef int32 HSteamUser; -// reference to a steam call, to filter results by -typedef int32 HSteamCall; - -// return type of GetAuthSessionTicket -typedef uint32 HAuthTicket; -const HAuthTicket k_HAuthTicketInvalid = 0; - -typedef int HVoiceCall; - - -const int k_cchSystemIMTextMax = 4096; - - - -// RTime32 -// We use this 32 bit time representing real world time. -// It offers 1 second resolution beginning on January 1, 1970 (Unix time) -typedef uint32 RTime32; -const RTime32 k_RTime32Nil = 0; -const RTime32 k_RTime32MinValid = 10; -const RTime32 k_RTime32Infinite = 0x7FFFFFFF; - - - -const uint32 k_nMagic = 0x31305356; // "VS01" -const uint32 k_nMagic_Old1 = 0x4D545356; // "VSTM" - -const uint32 k_cchTruncatedPassword = 20; -const uint32 k_cchAccountName = 64; - -const uint32 k_nChallengeMask = 0xA426DF2B; -const uint32 k_nObfuscationMask = 0xBAADF00D; - - -// General result codes -enum EResult -{ - k_EResultOK = 1, // success - k_EResultFail = 2, // generic failure - k_EResultNoConnection = 3, // no/failed network connection - // k_EResultNoConnectionRetry = 4, // OBSOLETE - removed - k_EResultInvalidPassword = 5, // password/ticket is invalid - k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere - k_EResultInvalidProtocolVer = 7, // protocol version is incorrect - k_EResultInvalidParam = 8, // a parameter is incorrect - k_EResultFileNotFound = 9, // file was not found - k_EResultBusy = 10, // called method busy - action not taken - k_EResultInvalidState = 11, // called object was in an invalid state - k_EResultInvalidName = 12, // name is invalid - k_EResultInvalidEmail = 13, // email is invalid - k_EResultDuplicateName = 14, // name is not unique - k_EResultAccessDenied = 15, // access is denied - k_EResultTimeout = 16, // operation timed out - k_EResultBanned = 17, // VAC2 banned - k_EResultAccountNotFound = 18, // account not found - k_EResultInvalidSteamID = 19, // steamID is invalid - k_EResultServiceUnavailable = 20, // The requested service is currently unavailable - k_EResultNotLoggedOn = 21, // The user is not logged on - k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party) - k_EResultEncryptionFailure = 23, // Encryption or Decryption failed - k_EResultInsufficientPrivilege = 24, // Insufficient privilege - k_EResultLimitExceeded = 25, // Too much of a good thing - k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes) - k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired - k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again - k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time - k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user - k_EResultIPNotFound = 31, // IP address not found - k_EResultPersistFailed = 32, // failed to write change to the data store - k_EResultLockingFailed = 33, // failed to acquire access lock for this operation - k_EResultLogonSessionReplaced = 34, - k_EResultConnectFailed = 35, - k_EResultHandshakeFailed = 36, - k_EResultIOFailure = 37, - k_EResultRemoteDisconnect = 38, - k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested - k_EResultBlocked = 40, // a user didn't allow it - k_EResultIgnored = 41, // target is ignoring sender - k_EResultNoMatch = 42, // nothing matching the request found - k_EResultAccountDisabled = 43, - k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now - k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available - k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin - k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol. - k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another. - k_EResultPasswordRequiredToKickSession = 49, // You are already logged in elsewhere, this cached credential login has failed. - k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait - k_EResultSuspended = 51, - k_EResultCancelled = 52, - k_EResultDataCorruption = 53, - k_EResultDiskFull = 54, - k_EResultRemoteCallFailed = 55, - -}; - - -//----------------------------------------------------------------------------- -// Purpose: Base values for callback identifiers, each callback must -// have a unique ID. -//----------------------------------------------------------------------------- -enum ECallbackType -{ - k_iSteamUserCallbacks = 100, - k_iSteamGameServerCallbacks = 200, - k_iSteamFriendsCallbacks = 300, - k_iSteamBillingCallbacks = 400, - k_iSteamMatchmakingCallbacks = 500, - k_iSteamContentServerCallbacks = 600, - k_iSteamUtilsCallbacks = 700, - k_iClientFriendsCallbacks = 800, - k_iClientUserCallbacks = 900, - k_iSteamAppsCallbacks = 1000, - k_iSteamUserStatsCallbacks = 1100, - k_iSteamNetworkingCallbacks = 1200, - k_iClientRemoteStorageCallbacks = 1300, - k_iSteamUserItemsCallbacks = 1400, - k_iSteamGameServerItemsCallbacks = 1500, - k_iClientUtilsCallbacks = 1600, - k_iSteamGameCoordinatorCallbacks = 1700, - k_iSteamGameServerStatsCallbacks = 1800, - k_iSteam2AsyncCallbacks = 1900, - k_iSteamGameStatsCallbacks = 2000, - k_iClientHTTPCallbacks = 2100 -}; - -// Each Steam instance (licensed Steam Service Provider) has a unique SteamInstanceID_t. -// -// Each Steam instance as its own DB of users. -// Each user in the DB has a unique SteamLocalUserID_t (a serial number, with possible -// rare gaps in the sequence). - -typedef unsigned short SteamInstanceID_t; // MUST be 16 bits - -#if defined (WIN32) - typedef unsigned __int64 SteamLocalUserID_t; // MUST be 64 bits -#else - typedef unsigned long long SteamLocalUserID_t; // MUST be 64 bits -#endif - - - - - - -// Applications need to be able to authenticate Steam users from ANY instance. -// So a SteamIDTicket contains SteamGlobalUserID, which is a unique combination of -// instance and user id. - -// SteamLocalUserID is an unsigned 64-bit integer. -// For platforms without 64-bit int support, we provide access via a union that splits it into -// high and low unsigned 32-bit ints. Such platforms will only need to compare LocalUserIDs -// for equivalence anyway - not perform arithmetic with them. -struct TSteamSplitLocalUserID -{ - unsigned int Low32bits; - unsigned int High32bits; -}; - -struct TSteamGlobalUserID -{ - SteamInstanceID_t m_SteamInstanceID; - - union m_SteamLocalUserID - { - SteamLocalUserID_t As64bits; - TSteamSplitLocalUserID Split; - } m_SteamLocalUserID; - -}; - -// structure that contains client callback data -struct CallbackMsg_t -{ - HSteamUser m_hSteamUser; - int m_iCallback; - uint8 *m_pubParam; - int m_cubParam; -}; - -#endif // !STEAMTYPES_H_ diff --git a/Resources/NetHook/steam/udppkt.h b/Resources/NetHook/steam/udppkt.h deleted file mode 100644 index 551f9486..00000000 --- a/Resources/NetHook/steam/udppkt.h +++ /dev/null @@ -1,121 +0,0 @@ - -#ifndef UDPPKT_H_ -#define UDPPKT_H_ -#ifdef _WIN32 -#pragma once -#endif - -#include "steamtypes.h" - -#include "csteamid.h" -#include "emsg.h" - -const uint32 k_uNetFlagNoIOCP = 1; -const uint32 k_uNetFlagFindAvailPort = 2; -const uint32 k_uNetFlagUseAuthentication = 4; -const uint32 k_uNetFlagUseEncryption = 8; -const uint32 k_uNetFlagRawStream = 16; -const uint32 k_uNetFlagRawStreamSend = 32; -const uint32 k_uNetFlagUnboundSocket = 64; -const uint32 k_uNetFlagRawIORecv = 128; - -const uint32 k_uNetFlagsKeyCallbackRequired = k_uNetFlagUseAuthentication | k_uNetFlagUseEncryption; // 12 - -enum EUDPPktType -{ - // This is the first packet type sent to Steam servers by the client. - // The client iterates through approximately 20 servers in an attempt to find the "best" one. - // Only the UDPPktType, local connection ID and outgoing sequence need to be given an appropriate value to request a challenge. - k_EUDPPktTypeChallengeReq = 1, - - // Steam servers respond to k_EUDPPktTypeChallengeReq with this packet type value and 8 bytes of information. - // The data is not encrypted. - // The first 4 bytes are the 'base' challenge which is used in k_EUDPPktTypeConnect after going through some changes. - // The next 4 bytes are unconfirmed, but they may be involved in the process of generating the actual challenge value used by the client. - k_EUDPPktTypeChallenge = 2, - - // The client sends this packet type after choosing the "best" Steam server available. - // A challenge is attached which is derived from the challenge in k_EUDPPktTypeChallenge. - // The instruction "XOR EDI, A426DF2B" is executed, EDI being the challenge, however this is not always the correct value and can be offset by small amounts. - // The Steam client uses the flag 4 when sending this, so assume it is necessary. - // UDPPktHdr should be filled in as normal but without encryption on the data. - k_EUDPPktTypeConnect = 3, - - // If the k_EUDPPktTypeConnect packet is received by the destination server and acknowledged as valid then it responds with this packet type. - // No data is attached, however a destination connection ID is generated and should be stored for use in later traffic. - // The Steam client uses the flag 4 when sending this, so assume it is necessary. - k_EUDPPktTypeAccept = 4, - - // Unknown, most likely sent to signify process termination. - k_EUDPPktTypeDisconnect = 5, - - // This packet type is used for the majority of VS01 traffic, incoming and outgoing. - // The flag is usually 4, however this is not confirmed as necessary or constant. - // The packet should include valid destination and source connection IDs. - // Not all data sent through this type is encrypted and it's currently unclear what indicates when it is and when it isn't. - k_EUDPPktTypeData = 6, - - // The datagram message type appears to be used for a packet resend. - // Sometimes the sequence number isn't included, but message size is. - // Sometimes the sequence number is included, but message size isn't. - // Sequence number may be replaced by size in the case of the seq value being incremented between initial send time and retry time. - k_EUDPPktTypeDatagram = 7, - - // Max enum value. - k_EUDPPktTypeMax = 8, -}; - -#pragma pack( push, 1 ) - -struct UDPPktHdr_t -{ - uint32 m_nMagic; // "VS01" or "VT01" - - uint16 m_cbPkt; - - uint8 m_EUDPPktType; // EUDPPktType - - uint8 m_nFlags; // NetFlags - - uint32 m_nSrcConnectionID; - uint32 m_nDstConnectionID; - - uint32 m_nSeqThis; - uint32 m_nSeqAcked; - - uint32 m_nPktsInMsg; - uint32 m_nMsgStartSeq; - - uint32 m_cbMsgData; -}; - -struct MsgHdr_t -{ - int32 m_EMsg; // EMsg - - JobID_t m_JobIDTarget; - JobID_t m_JobIDSource; -}; - -struct ExtendedClientMsgHdr_t -{ - int32 m_EMsg; // EMsg - - uint8 m_nCubHdr; - - uint16 m_nHdrVersion; - - JobID_t m_JobIDTarget; - JobID_t m_JobIDSource; - - uint8 m_nHdrCanary; - - CSteamID m_ulSteamID; - - int32 m_nSessionID; -}; - -#pragma pack( pop ) - - -#endif // !UDPPKT_H_ diff --git a/Resources/NetHook/steammessages_base.pb.cc b/Resources/NetHook/steammessages_base.pb.cc deleted file mode 100644 index e054793e..00000000 --- a/Resources/NetHook/steammessages_base.pb.cc +++ /dev/null @@ -1,1289 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! - -#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION -#include "steammessages_base.pb.h" -#include -#include -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -namespace { - -const ::google::protobuf::Descriptor* CMsgProtoBufHeader_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - CMsgProtoBufHeader_reflection_ = NULL; -const ::google::protobuf::Descriptor* CMsgMulti_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - CMsgMulti_reflection_ = NULL; -const ::google::protobuf::Descriptor* CMsgAuthTicket_descriptor_ = NULL; -const ::google::protobuf::internal::GeneratedMessageReflection* - CMsgAuthTicket_reflection_ = NULL; - -} // namespace - - -void protobuf_AssignDesc_steammessages_5fbase_2eproto() { - protobuf_AddDesc_steammessages_5fbase_2eproto(); - const ::google::protobuf::FileDescriptor* file = - ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( - "steammessages_base.proto"); - GOOGLE_CHECK(file != NULL); - CMsgProtoBufHeader_descriptor_ = file->message_type(0); - static const int CMsgProtoBufHeader_offsets_[6] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, client_steam_id_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, client_session_id_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, routing_appid_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, job_id_source_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, job_id_target_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, target_job_name_), - }; - CMsgProtoBufHeader_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - CMsgProtoBufHeader_descriptor_, - CMsgProtoBufHeader::default_instance_, - CMsgProtoBufHeader_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgProtoBufHeader, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(CMsgProtoBufHeader)); - CMsgMulti_descriptor_ = file->message_type(1); - static const int CMsgMulti_offsets_[2] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgMulti, size_unzipped_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgMulti, message_body_), - }; - CMsgMulti_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - CMsgMulti_descriptor_, - CMsgMulti::default_instance_, - CMsgMulti_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgMulti, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgMulti, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(CMsgMulti)); - CMsgAuthTicket_descriptor_ = file->message_type(2); - static const int CMsgAuthTicket_offsets_[7] = { - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, estate_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, eresult_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, steam_id_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, game_id_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, h_steam_pipe_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, ticket_crc_), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, ticket_), - }; - CMsgAuthTicket_reflection_ = - new ::google::protobuf::internal::GeneratedMessageReflection( - CMsgAuthTicket_descriptor_, - CMsgAuthTicket::default_instance_, - CMsgAuthTicket_offsets_, - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, _has_bits_[0]), - GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(CMsgAuthTicket, _unknown_fields_), - -1, - ::google::protobuf::DescriptorPool::generated_pool(), - ::google::protobuf::MessageFactory::generated_factory(), - sizeof(CMsgAuthTicket)); -} - -namespace { - -GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); -inline void protobuf_AssignDescriptorsOnce() { - ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, - &protobuf_AssignDesc_steammessages_5fbase_2eproto); -} - -void protobuf_RegisterTypes(const ::std::string&) { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - CMsgProtoBufHeader_descriptor_, &CMsgProtoBufHeader::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - CMsgMulti_descriptor_, &CMsgMulti::default_instance()); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( - CMsgAuthTicket_descriptor_, &CMsgAuthTicket::default_instance()); -} - -} // namespace - -void protobuf_ShutdownFile_steammessages_5fbase_2eproto() { - delete CMsgProtoBufHeader::default_instance_; - delete CMsgProtoBufHeader_reflection_; - delete CMsgMulti::default_instance_; - delete CMsgMulti_reflection_; - delete CMsgAuthTicket::default_instance_; - delete CMsgAuthTicket_reflection_; -} - -void protobuf_AddDesc_steammessages_5fbase_2eproto() { - static bool already_here = false; - if (already_here) return; - already_here = true; - GOOGLE_PROTOBUF_VERIFY_VERSION; - - ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( - "\n\030steammessages_base.proto\"\322\001\n\022CMsgProto" - "BufHeader\022\027\n\017client_steam_id\030\001 \001(\006\022\031\n\021cl" - "ient_session_id\030\002 \001(\005\022\025\n\rrouting_appid\030\003" - " \001(\r\022+\n\rjob_id_source\030\n \001(\006:\02418446744073" - "709551615\022+\n\rjob_id_target\030\013 \001(\006:\024184467" - "44073709551615\022\027\n\017target_job_name\030\014 \001(\t\"" - "8\n\tCMsgMulti\022\025\n\rsize_unzipped\030\001 \001(\r\022\024\n\014m" - "essage_body\030\002 \001(\014\"\221\001\n\016CMsgAuthTicket\022\016\n\006" - "estate\030\001 \001(\r\022\022\n\007eresult\030\002 \001(\r:\0012\022\020\n\010stea" - "m_id\030\003 \001(\006\022\017\n\007game_id\030\004 \001(\006\022\024\n\014h_steam_p" - "ipe\030\005 \001(\r\022\022\n\nticket_crc\030\006 \001(\r\022\016\n\006ticket\030" - "\007 \001(\014", 445); - ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( - "steammessages_base.proto", &protobuf_RegisterTypes); - CMsgProtoBufHeader::default_instance_ = new CMsgProtoBufHeader(); - CMsgMulti::default_instance_ = new CMsgMulti(); - CMsgAuthTicket::default_instance_ = new CMsgAuthTicket(); - CMsgProtoBufHeader::default_instance_->InitAsDefaultInstance(); - CMsgMulti::default_instance_->InitAsDefaultInstance(); - CMsgAuthTicket::default_instance_->InitAsDefaultInstance(); - ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_steammessages_5fbase_2eproto); -} - -// Force AddDescriptors() to be called at static initialization time. -struct StaticDescriptorInitializer_steammessages_5fbase_2eproto { - StaticDescriptorInitializer_steammessages_5fbase_2eproto() { - protobuf_AddDesc_steammessages_5fbase_2eproto(); - } -} static_descriptor_initializer_steammessages_5fbase_2eproto_; - - -// =================================================================== - -const ::std::string CMsgProtoBufHeader::_default_target_job_name_; -#ifndef _MSC_VER -const int CMsgProtoBufHeader::kClientSteamIdFieldNumber; -const int CMsgProtoBufHeader::kClientSessionIdFieldNumber; -const int CMsgProtoBufHeader::kRoutingAppidFieldNumber; -const int CMsgProtoBufHeader::kJobIdSourceFieldNumber; -const int CMsgProtoBufHeader::kJobIdTargetFieldNumber; -const int CMsgProtoBufHeader::kTargetJobNameFieldNumber; -#endif // !_MSC_VER - -CMsgProtoBufHeader::CMsgProtoBufHeader() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void CMsgProtoBufHeader::InitAsDefaultInstance() { -} - -CMsgProtoBufHeader::CMsgProtoBufHeader(const CMsgProtoBufHeader& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void CMsgProtoBufHeader::SharedCtor() { - _cached_size_ = 0; - client_steam_id_ = GOOGLE_ULONGLONG(0); - client_session_id_ = 0; - routing_appid_ = 0u; - job_id_source_ = GOOGLE_ULONGLONG(18446744073709551615); - job_id_target_ = GOOGLE_ULONGLONG(18446744073709551615); - target_job_name_ = const_cast< ::std::string*>(&_default_target_job_name_); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -CMsgProtoBufHeader::~CMsgProtoBufHeader() { - SharedDtor(); -} - -void CMsgProtoBufHeader::SharedDtor() { - if (target_job_name_ != &_default_target_job_name_) { - delete target_job_name_; - } - if (this != default_instance_) { - } -} - -void CMsgProtoBufHeader::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* CMsgProtoBufHeader::descriptor() { - protobuf_AssignDescriptorsOnce(); - return CMsgProtoBufHeader_descriptor_; -} - -const CMsgProtoBufHeader& CMsgProtoBufHeader::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_steammessages_5fbase_2eproto(); return *default_instance_; -} - -CMsgProtoBufHeader* CMsgProtoBufHeader::default_instance_ = NULL; - -CMsgProtoBufHeader* CMsgProtoBufHeader::New() const { - return new CMsgProtoBufHeader; -} - -void CMsgProtoBufHeader::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - client_steam_id_ = GOOGLE_ULONGLONG(0); - client_session_id_ = 0; - routing_appid_ = 0u; - job_id_source_ = GOOGLE_ULONGLONG(18446744073709551615); - job_id_target_ = GOOGLE_ULONGLONG(18446744073709551615); - if (_has_bit(5)) { - if (target_job_name_ != &_default_target_job_name_) { - target_job_name_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool CMsgProtoBufHeader::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional fixed64 client_steam_id = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>( - input, &client_steam_id_))); - _set_bit(0); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_client_session_id; - break; - } - - // optional int32 client_session_id = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_client_session_id: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( - input, &client_session_id_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(24)) goto parse_routing_appid; - break; - } - - // optional uint32 routing_appid = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_routing_appid: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &routing_appid_))); - _set_bit(2); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(81)) goto parse_job_id_source; - break; - } - - // optional fixed64 job_id_source = 10 [default = 18446744073709551615]; - case 10: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) { - parse_job_id_source: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>( - input, &job_id_source_))); - _set_bit(3); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(89)) goto parse_job_id_target; - break; - } - - // optional fixed64 job_id_target = 11 [default = 18446744073709551615]; - case 11: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) { - parse_job_id_target: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>( - input, &job_id_target_))); - _set_bit(4); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(98)) goto parse_target_job_name; - break; - } - - // optional string target_job_name = 12; - case 12: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_target_job_name: - DO_(::google::protobuf::internal::WireFormatLite::ReadString( - input, this->mutable_target_job_name())); - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->target_job_name().data(), this->target_job_name().length(), - ::google::protobuf::internal::WireFormat::PARSE); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void CMsgProtoBufHeader::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional fixed64 client_steam_id = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormatLite::WriteFixed64(1, this->client_steam_id(), output); - } - - // optional int32 client_session_id = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->client_session_id(), output); - } - - // optional uint32 routing_appid = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->routing_appid(), output); - } - - // optional fixed64 job_id_source = 10 [default = 18446744073709551615]; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormatLite::WriteFixed64(10, this->job_id_source(), output); - } - - // optional fixed64 job_id_target = 11 [default = 18446744073709551615]; - if (_has_bit(4)) { - ::google::protobuf::internal::WireFormatLite::WriteFixed64(11, this->job_id_target(), output); - } - - // optional string target_job_name = 12; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->target_job_name().data(), this->target_job_name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - ::google::protobuf::internal::WireFormatLite::WriteString( - 12, this->target_job_name(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* CMsgProtoBufHeader::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional fixed64 client_steam_id = 1; - if (_has_bit(0)) { - target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(1, this->client_steam_id(), target); - } - - // optional int32 client_session_id = 2; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->client_session_id(), target); - } - - // optional uint32 routing_appid = 3; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->routing_appid(), target); - } - - // optional fixed64 job_id_source = 10 [default = 18446744073709551615]; - if (_has_bit(3)) { - target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(10, this->job_id_source(), target); - } - - // optional fixed64 job_id_target = 11 [default = 18446744073709551615]; - if (_has_bit(4)) { - target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(11, this->job_id_target(), target); - } - - // optional string target_job_name = 12; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormat::VerifyUTF8String( - this->target_job_name().data(), this->target_job_name().length(), - ::google::protobuf::internal::WireFormat::SERIALIZE); - target = - ::google::protobuf::internal::WireFormatLite::WriteStringToArray( - 12, this->target_job_name(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int CMsgProtoBufHeader::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional fixed64 client_steam_id = 1; - if (has_client_steam_id()) { - total_size += 1 + 8; - } - - // optional int32 client_session_id = 2; - if (has_client_session_id()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::Int32Size( - this->client_session_id()); - } - - // optional uint32 routing_appid = 3; - if (has_routing_appid()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->routing_appid()); - } - - // optional fixed64 job_id_source = 10 [default = 18446744073709551615]; - if (has_job_id_source()) { - total_size += 1 + 8; - } - - // optional fixed64 job_id_target = 11 [default = 18446744073709551615]; - if (has_job_id_target()) { - total_size += 1 + 8; - } - - // optional string target_job_name = 12; - if (has_target_job_name()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::StringSize( - this->target_job_name()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void CMsgProtoBufHeader::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const CMsgProtoBufHeader* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void CMsgProtoBufHeader::MergeFrom(const CMsgProtoBufHeader& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_client_steam_id(from.client_steam_id()); - } - if (from._has_bit(1)) { - set_client_session_id(from.client_session_id()); - } - if (from._has_bit(2)) { - set_routing_appid(from.routing_appid()); - } - if (from._has_bit(3)) { - set_job_id_source(from.job_id_source()); - } - if (from._has_bit(4)) { - set_job_id_target(from.job_id_target()); - } - if (from._has_bit(5)) { - set_target_job_name(from.target_job_name()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void CMsgProtoBufHeader::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void CMsgProtoBufHeader::CopyFrom(const CMsgProtoBufHeader& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CMsgProtoBufHeader::IsInitialized() const { - - return true; -} - -void CMsgProtoBufHeader::Swap(CMsgProtoBufHeader* other) { - if (other != this) { - std::swap(client_steam_id_, other->client_steam_id_); - std::swap(client_session_id_, other->client_session_id_); - std::swap(routing_appid_, other->routing_appid_); - std::swap(job_id_source_, other->job_id_source_); - std::swap(job_id_target_, other->job_id_target_); - std::swap(target_job_name_, other->target_job_name_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata CMsgProtoBufHeader::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = CMsgProtoBufHeader_descriptor_; - metadata.reflection = CMsgProtoBufHeader_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string CMsgMulti::_default_message_body_; -#ifndef _MSC_VER -const int CMsgMulti::kSizeUnzippedFieldNumber; -const int CMsgMulti::kMessageBodyFieldNumber; -#endif // !_MSC_VER - -CMsgMulti::CMsgMulti() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void CMsgMulti::InitAsDefaultInstance() { -} - -CMsgMulti::CMsgMulti(const CMsgMulti& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void CMsgMulti::SharedCtor() { - _cached_size_ = 0; - size_unzipped_ = 0u; - message_body_ = const_cast< ::std::string*>(&_default_message_body_); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -CMsgMulti::~CMsgMulti() { - SharedDtor(); -} - -void CMsgMulti::SharedDtor() { - if (message_body_ != &_default_message_body_) { - delete message_body_; - } - if (this != default_instance_) { - } -} - -void CMsgMulti::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* CMsgMulti::descriptor() { - protobuf_AssignDescriptorsOnce(); - return CMsgMulti_descriptor_; -} - -const CMsgMulti& CMsgMulti::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_steammessages_5fbase_2eproto(); return *default_instance_; -} - -CMsgMulti* CMsgMulti::default_instance_ = NULL; - -CMsgMulti* CMsgMulti::New() const { - return new CMsgMulti; -} - -void CMsgMulti::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - size_unzipped_ = 0u; - if (_has_bit(1)) { - if (message_body_ != &_default_message_body_) { - message_body_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool CMsgMulti::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional uint32 size_unzipped = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &size_unzipped_))); - _set_bit(0); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(18)) goto parse_message_body; - break; - } - - // optional bytes message_body = 2; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_message_body: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_message_body())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void CMsgMulti::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional uint32 size_unzipped = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->size_unzipped(), output); - } - - // optional bytes message_body = 2; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteBytes( - 2, this->message_body(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* CMsgMulti::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional uint32 size_unzipped = 1; - if (_has_bit(0)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->size_unzipped(), target); - } - - // optional bytes message_body = 2; - if (_has_bit(1)) { - target = - ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( - 2, this->message_body(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int CMsgMulti::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional uint32 size_unzipped = 1; - if (has_size_unzipped()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->size_unzipped()); - } - - // optional bytes message_body = 2; - if (has_message_body()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->message_body()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void CMsgMulti::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const CMsgMulti* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void CMsgMulti::MergeFrom(const CMsgMulti& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_size_unzipped(from.size_unzipped()); - } - if (from._has_bit(1)) { - set_message_body(from.message_body()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void CMsgMulti::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void CMsgMulti::CopyFrom(const CMsgMulti& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CMsgMulti::IsInitialized() const { - - return true; -} - -void CMsgMulti::Swap(CMsgMulti* other) { - if (other != this) { - std::swap(size_unzipped_, other->size_unzipped_); - std::swap(message_body_, other->message_body_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata CMsgMulti::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = CMsgMulti_descriptor_; - metadata.reflection = CMsgMulti_reflection_; - return metadata; -} - - -// =================================================================== - -const ::std::string CMsgAuthTicket::_default_ticket_; -#ifndef _MSC_VER -const int CMsgAuthTicket::kEstateFieldNumber; -const int CMsgAuthTicket::kEresultFieldNumber; -const int CMsgAuthTicket::kSteamIdFieldNumber; -const int CMsgAuthTicket::kGameIdFieldNumber; -const int CMsgAuthTicket::kHSteamPipeFieldNumber; -const int CMsgAuthTicket::kTicketCrcFieldNumber; -const int CMsgAuthTicket::kTicketFieldNumber; -#endif // !_MSC_VER - -CMsgAuthTicket::CMsgAuthTicket() - : ::google::protobuf::Message() { - SharedCtor(); -} - -void CMsgAuthTicket::InitAsDefaultInstance() { -} - -CMsgAuthTicket::CMsgAuthTicket(const CMsgAuthTicket& from) - : ::google::protobuf::Message() { - SharedCtor(); - MergeFrom(from); -} - -void CMsgAuthTicket::SharedCtor() { - _cached_size_ = 0; - estate_ = 0u; - eresult_ = 2u; - steam_id_ = GOOGLE_ULONGLONG(0); - game_id_ = GOOGLE_ULONGLONG(0); - h_steam_pipe_ = 0u; - ticket_crc_ = 0u; - ticket_ = const_cast< ::std::string*>(&_default_ticket_); - ::memset(_has_bits_, 0, sizeof(_has_bits_)); -} - -CMsgAuthTicket::~CMsgAuthTicket() { - SharedDtor(); -} - -void CMsgAuthTicket::SharedDtor() { - if (ticket_ != &_default_ticket_) { - delete ticket_; - } - if (this != default_instance_) { - } -} - -void CMsgAuthTicket::SetCachedSize(int size) const { - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); -} -const ::google::protobuf::Descriptor* CMsgAuthTicket::descriptor() { - protobuf_AssignDescriptorsOnce(); - return CMsgAuthTicket_descriptor_; -} - -const CMsgAuthTicket& CMsgAuthTicket::default_instance() { - if (default_instance_ == NULL) protobuf_AddDesc_steammessages_5fbase_2eproto(); return *default_instance_; -} - -CMsgAuthTicket* CMsgAuthTicket::default_instance_ = NULL; - -CMsgAuthTicket* CMsgAuthTicket::New() const { - return new CMsgAuthTicket; -} - -void CMsgAuthTicket::Clear() { - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - estate_ = 0u; - eresult_ = 2u; - steam_id_ = GOOGLE_ULONGLONG(0); - game_id_ = GOOGLE_ULONGLONG(0); - h_steam_pipe_ = 0u; - ticket_crc_ = 0u; - if (_has_bit(6)) { - if (ticket_ != &_default_ticket_) { - ticket_->clear(); - } - } - } - ::memset(_has_bits_, 0, sizeof(_has_bits_)); - mutable_unknown_fields()->Clear(); -} - -bool CMsgAuthTicket::MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input) { -#define DO_(EXPRESSION) if (!(EXPRESSION)) return false - ::google::protobuf::uint32 tag; - while ((tag = input->ReadTag()) != 0) { - switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { - // optional uint32 estate = 1; - case 1: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &estate_))); - _set_bit(0); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(16)) goto parse_eresult; - break; - } - - // optional uint32 eresult = 2 [default = 2]; - case 2: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_eresult: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &eresult_))); - _set_bit(1); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(25)) goto parse_steam_id; - break; - } - - // optional fixed64 steam_id = 3; - case 3: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) { - parse_steam_id: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>( - input, &steam_id_))); - _set_bit(2); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(33)) goto parse_game_id; - break; - } - - // optional fixed64 game_id = 4; - case 4: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) { - parse_game_id: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>( - input, &game_id_))); - _set_bit(3); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(40)) goto parse_h_steam_pipe; - break; - } - - // optional uint32 h_steam_pipe = 5; - case 5: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_h_steam_pipe: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &h_steam_pipe_))); - _set_bit(4); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(48)) goto parse_ticket_crc; - break; - } - - // optional uint32 ticket_crc = 6; - case 6: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { - parse_ticket_crc: - DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< - ::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>( - input, &ticket_crc_))); - _set_bit(5); - } else { - goto handle_uninterpreted; - } - if (input->ExpectTag(58)) goto parse_ticket; - break; - } - - // optional bytes ticket = 7; - case 7: { - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { - parse_ticket: - DO_(::google::protobuf::internal::WireFormatLite::ReadBytes( - input, this->mutable_ticket())); - } else { - goto handle_uninterpreted; - } - if (input->ExpectAtEnd()) return true; - break; - } - - default: { - handle_uninterpreted: - if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == - ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { - return true; - } - DO_(::google::protobuf::internal::WireFormat::SkipField( - input, tag, mutable_unknown_fields())); - break; - } - } - } - return true; -#undef DO_ -} - -void CMsgAuthTicket::SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const { - // optional uint32 estate = 1; - if (_has_bit(0)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->estate(), output); - } - - // optional uint32 eresult = 2 [default = 2]; - if (_has_bit(1)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->eresult(), output); - } - - // optional fixed64 steam_id = 3; - if (_has_bit(2)) { - ::google::protobuf::internal::WireFormatLite::WriteFixed64(3, this->steam_id(), output); - } - - // optional fixed64 game_id = 4; - if (_has_bit(3)) { - ::google::protobuf::internal::WireFormatLite::WriteFixed64(4, this->game_id(), output); - } - - // optional uint32 h_steam_pipe = 5; - if (_has_bit(4)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->h_steam_pipe(), output); - } - - // optional uint32 ticket_crc = 6; - if (_has_bit(5)) { - ::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->ticket_crc(), output); - } - - // optional bytes ticket = 7; - if (_has_bit(6)) { - ::google::protobuf::internal::WireFormatLite::WriteBytes( - 7, this->ticket(), output); - } - - if (!unknown_fields().empty()) { - ::google::protobuf::internal::WireFormat::SerializeUnknownFields( - unknown_fields(), output); - } -} - -::google::protobuf::uint8* CMsgAuthTicket::SerializeWithCachedSizesToArray( - ::google::protobuf::uint8* target) const { - // optional uint32 estate = 1; - if (_has_bit(0)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(1, this->estate(), target); - } - - // optional uint32 eresult = 2 [default = 2]; - if (_has_bit(1)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->eresult(), target); - } - - // optional fixed64 steam_id = 3; - if (_has_bit(2)) { - target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(3, this->steam_id(), target); - } - - // optional fixed64 game_id = 4; - if (_has_bit(3)) { - target = ::google::protobuf::internal::WireFormatLite::WriteFixed64ToArray(4, this->game_id(), target); - } - - // optional uint32 h_steam_pipe = 5; - if (_has_bit(4)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(5, this->h_steam_pipe(), target); - } - - // optional uint32 ticket_crc = 6; - if (_has_bit(5)) { - target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(6, this->ticket_crc(), target); - } - - // optional bytes ticket = 7; - if (_has_bit(6)) { - target = - ::google::protobuf::internal::WireFormatLite::WriteBytesToArray( - 7, this->ticket(), target); - } - - if (!unknown_fields().empty()) { - target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( - unknown_fields(), target); - } - return target; -} - -int CMsgAuthTicket::ByteSize() const { - int total_size = 0; - - if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { - // optional uint32 estate = 1; - if (has_estate()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->estate()); - } - - // optional uint32 eresult = 2 [default = 2]; - if (has_eresult()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->eresult()); - } - - // optional fixed64 steam_id = 3; - if (has_steam_id()) { - total_size += 1 + 8; - } - - // optional fixed64 game_id = 4; - if (has_game_id()) { - total_size += 1 + 8; - } - - // optional uint32 h_steam_pipe = 5; - if (has_h_steam_pipe()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->h_steam_pipe()); - } - - // optional uint32 ticket_crc = 6; - if (has_ticket_crc()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::UInt32Size( - this->ticket_crc()); - } - - // optional bytes ticket = 7; - if (has_ticket()) { - total_size += 1 + - ::google::protobuf::internal::WireFormatLite::BytesSize( - this->ticket()); - } - - } - if (!unknown_fields().empty()) { - total_size += - ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( - unknown_fields()); - } - GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); - _cached_size_ = total_size; - GOOGLE_SAFE_CONCURRENT_WRITES_END(); - return total_size; -} - -void CMsgAuthTicket::MergeFrom(const ::google::protobuf::Message& from) { - GOOGLE_CHECK_NE(&from, this); - const CMsgAuthTicket* source = - ::google::protobuf::internal::dynamic_cast_if_available( - &from); - if (source == NULL) { - ::google::protobuf::internal::ReflectionOps::Merge(from, this); - } else { - MergeFrom(*source); - } -} - -void CMsgAuthTicket::MergeFrom(const CMsgAuthTicket& from) { - GOOGLE_CHECK_NE(&from, this); - if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { - if (from._has_bit(0)) { - set_estate(from.estate()); - } - if (from._has_bit(1)) { - set_eresult(from.eresult()); - } - if (from._has_bit(2)) { - set_steam_id(from.steam_id()); - } - if (from._has_bit(3)) { - set_game_id(from.game_id()); - } - if (from._has_bit(4)) { - set_h_steam_pipe(from.h_steam_pipe()); - } - if (from._has_bit(5)) { - set_ticket_crc(from.ticket_crc()); - } - if (from._has_bit(6)) { - set_ticket(from.ticket()); - } - } - mutable_unknown_fields()->MergeFrom(from.unknown_fields()); -} - -void CMsgAuthTicket::CopyFrom(const ::google::protobuf::Message& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -void CMsgAuthTicket::CopyFrom(const CMsgAuthTicket& from) { - if (&from == this) return; - Clear(); - MergeFrom(from); -} - -bool CMsgAuthTicket::IsInitialized() const { - - return true; -} - -void CMsgAuthTicket::Swap(CMsgAuthTicket* other) { - if (other != this) { - std::swap(estate_, other->estate_); - std::swap(eresult_, other->eresult_); - std::swap(steam_id_, other->steam_id_); - std::swap(game_id_, other->game_id_); - std::swap(h_steam_pipe_, other->h_steam_pipe_); - std::swap(ticket_crc_, other->ticket_crc_); - std::swap(ticket_, other->ticket_); - std::swap(_has_bits_[0], other->_has_bits_[0]); - _unknown_fields_.Swap(&other->_unknown_fields_); - std::swap(_cached_size_, other->_cached_size_); - } -} - -::google::protobuf::Metadata CMsgAuthTicket::GetMetadata() const { - protobuf_AssignDescriptorsOnce(); - ::google::protobuf::Metadata metadata; - metadata.descriptor = CMsgAuthTicket_descriptor_; - metadata.reflection = CMsgAuthTicket_reflection_; - return metadata; -} - - -// @@protoc_insertion_point(namespace_scope) - -// @@protoc_insertion_point(global_scope) diff --git a/Resources/NetHook/steammessages_base.pb.h b/Resources/NetHook/steammessages_base.pb.h deleted file mode 100644 index eb17d9ce..00000000 --- a/Resources/NetHook/steammessages_base.pb.h +++ /dev/null @@ -1,759 +0,0 @@ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: steammessages_base.proto - -#ifndef PROTOBUF_steammessages_5fbase_2eproto__INCLUDED -#define PROTOBUF_steammessages_5fbase_2eproto__INCLUDED - -#include - -#include - -#if GOOGLE_PROTOBUF_VERSION < 2003000 -#error This file was generated by a newer version of protoc which is -#error incompatible with your Protocol Buffer headers. Please update -#error your headers. -#endif -#if 2003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION -#error This file was generated by an older version of protoc which is -#error incompatible with your Protocol Buffer headers. Please -#error regenerate this file with a newer version of protoc. -#endif - -#include -#include -#include -#include -// @@protoc_insertion_point(includes) - -// Internal implementation detail -- do not call these. -void protobuf_AddDesc_steammessages_5fbase_2eproto(); -void protobuf_AssignDesc_steammessages_5fbase_2eproto(); -void protobuf_ShutdownFile_steammessages_5fbase_2eproto(); - -class CMsgProtoBufHeader; -class CMsgMulti; -class CMsgAuthTicket; - -// =================================================================== - -class CMsgProtoBufHeader : public ::google::protobuf::Message { - public: - CMsgProtoBufHeader(); - virtual ~CMsgProtoBufHeader(); - - CMsgProtoBufHeader(const CMsgProtoBufHeader& from); - - inline CMsgProtoBufHeader& operator=(const CMsgProtoBufHeader& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const CMsgProtoBufHeader& default_instance(); - - void Swap(CMsgProtoBufHeader* other); - - // implements Message ---------------------------------------------- - - CMsgProtoBufHeader* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const CMsgProtoBufHeader& from); - void MergeFrom(const CMsgProtoBufHeader& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional fixed64 client_steam_id = 1; - inline bool has_client_steam_id() const; - inline void clear_client_steam_id(); - static const int kClientSteamIdFieldNumber = 1; - inline ::google::protobuf::uint64 client_steam_id() const; - inline void set_client_steam_id(::google::protobuf::uint64 value); - - // optional int32 client_session_id = 2; - inline bool has_client_session_id() const; - inline void clear_client_session_id(); - static const int kClientSessionIdFieldNumber = 2; - inline ::google::protobuf::int32 client_session_id() const; - inline void set_client_session_id(::google::protobuf::int32 value); - - // optional uint32 routing_appid = 3; - inline bool has_routing_appid() const; - inline void clear_routing_appid(); - static const int kRoutingAppidFieldNumber = 3; - inline ::google::protobuf::uint32 routing_appid() const; - inline void set_routing_appid(::google::protobuf::uint32 value); - - // optional fixed64 job_id_source = 10 [default = 18446744073709551615]; - inline bool has_job_id_source() const; - inline void clear_job_id_source(); - static const int kJobIdSourceFieldNumber = 10; - inline ::google::protobuf::uint64 job_id_source() const; - inline void set_job_id_source(::google::protobuf::uint64 value); - - // optional fixed64 job_id_target = 11 [default = 18446744073709551615]; - inline bool has_job_id_target() const; - inline void clear_job_id_target(); - static const int kJobIdTargetFieldNumber = 11; - inline ::google::protobuf::uint64 job_id_target() const; - inline void set_job_id_target(::google::protobuf::uint64 value); - - // optional string target_job_name = 12; - inline bool has_target_job_name() const; - inline void clear_target_job_name(); - static const int kTargetJobNameFieldNumber = 12; - inline const ::std::string& target_job_name() const; - inline void set_target_job_name(const ::std::string& value); - inline void set_target_job_name(const char* value); - inline void set_target_job_name(const char* value, size_t size); - inline ::std::string* mutable_target_job_name(); - - // @@protoc_insertion_point(class_scope:CMsgProtoBufHeader) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::uint64 client_steam_id_; - ::google::protobuf::int32 client_session_id_; - ::google::protobuf::uint32 routing_appid_; - ::google::protobuf::uint64 job_id_source_; - ::google::protobuf::uint64 job_id_target_; - ::std::string* target_job_name_; - static const ::std::string _default_target_job_name_; - friend void protobuf_AddDesc_steammessages_5fbase_2eproto(); - friend void protobuf_AssignDesc_steammessages_5fbase_2eproto(); - friend void protobuf_ShutdownFile_steammessages_5fbase_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(6 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static CMsgProtoBufHeader* default_instance_; -}; -// ------------------------------------------------------------------- - -class CMsgMulti : public ::google::protobuf::Message { - public: - CMsgMulti(); - virtual ~CMsgMulti(); - - CMsgMulti(const CMsgMulti& from); - - inline CMsgMulti& operator=(const CMsgMulti& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const CMsgMulti& default_instance(); - - void Swap(CMsgMulti* other); - - // implements Message ---------------------------------------------- - - CMsgMulti* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const CMsgMulti& from); - void MergeFrom(const CMsgMulti& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional uint32 size_unzipped = 1; - inline bool has_size_unzipped() const; - inline void clear_size_unzipped(); - static const int kSizeUnzippedFieldNumber = 1; - inline ::google::protobuf::uint32 size_unzipped() const; - inline void set_size_unzipped(::google::protobuf::uint32 value); - - // optional bytes message_body = 2; - inline bool has_message_body() const; - inline void clear_message_body(); - static const int kMessageBodyFieldNumber = 2; - inline const ::std::string& message_body() const; - inline void set_message_body(const ::std::string& value); - inline void set_message_body(const char* value); - inline void set_message_body(const void* value, size_t size); - inline ::std::string* mutable_message_body(); - - // @@protoc_insertion_point(class_scope:CMsgMulti) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::uint32 size_unzipped_; - ::std::string* message_body_; - static const ::std::string _default_message_body_; - friend void protobuf_AddDesc_steammessages_5fbase_2eproto(); - friend void protobuf_AssignDesc_steammessages_5fbase_2eproto(); - friend void protobuf_ShutdownFile_steammessages_5fbase_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static CMsgMulti* default_instance_; -}; -// ------------------------------------------------------------------- - -class CMsgAuthTicket : public ::google::protobuf::Message { - public: - CMsgAuthTicket(); - virtual ~CMsgAuthTicket(); - - CMsgAuthTicket(const CMsgAuthTicket& from); - - inline CMsgAuthTicket& operator=(const CMsgAuthTicket& from) { - CopyFrom(from); - return *this; - } - - inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { - return _unknown_fields_; - } - - inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { - return &_unknown_fields_; - } - - static const ::google::protobuf::Descriptor* descriptor(); - static const CMsgAuthTicket& default_instance(); - - void Swap(CMsgAuthTicket* other); - - // implements Message ---------------------------------------------- - - CMsgAuthTicket* New() const; - void CopyFrom(const ::google::protobuf::Message& from); - void MergeFrom(const ::google::protobuf::Message& from); - void CopyFrom(const CMsgAuthTicket& from); - void MergeFrom(const CMsgAuthTicket& from); - void Clear(); - bool IsInitialized() const; - - int ByteSize() const; - bool MergePartialFromCodedStream( - ::google::protobuf::io::CodedInputStream* input); - void SerializeWithCachedSizes( - ::google::protobuf::io::CodedOutputStream* output) const; - ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; - int GetCachedSize() const { return _cached_size_; } - private: - void SharedCtor(); - void SharedDtor(); - void SetCachedSize(int size) const; - public: - - ::google::protobuf::Metadata GetMetadata() const; - - // nested types ---------------------------------------------------- - - // accessors ------------------------------------------------------- - - // optional uint32 estate = 1; - inline bool has_estate() const; - inline void clear_estate(); - static const int kEstateFieldNumber = 1; - inline ::google::protobuf::uint32 estate() const; - inline void set_estate(::google::protobuf::uint32 value); - - // optional uint32 eresult = 2 [default = 2]; - inline bool has_eresult() const; - inline void clear_eresult(); - static const int kEresultFieldNumber = 2; - inline ::google::protobuf::uint32 eresult() const; - inline void set_eresult(::google::protobuf::uint32 value); - - // optional fixed64 steam_id = 3; - inline bool has_steam_id() const; - inline void clear_steam_id(); - static const int kSteamIdFieldNumber = 3; - inline ::google::protobuf::uint64 steam_id() const; - inline void set_steam_id(::google::protobuf::uint64 value); - - // optional fixed64 game_id = 4; - inline bool has_game_id() const; - inline void clear_game_id(); - static const int kGameIdFieldNumber = 4; - inline ::google::protobuf::uint64 game_id() const; - inline void set_game_id(::google::protobuf::uint64 value); - - // optional uint32 h_steam_pipe = 5; - inline bool has_h_steam_pipe() const; - inline void clear_h_steam_pipe(); - static const int kHSteamPipeFieldNumber = 5; - inline ::google::protobuf::uint32 h_steam_pipe() const; - inline void set_h_steam_pipe(::google::protobuf::uint32 value); - - // optional uint32 ticket_crc = 6; - inline bool has_ticket_crc() const; - inline void clear_ticket_crc(); - static const int kTicketCrcFieldNumber = 6; - inline ::google::protobuf::uint32 ticket_crc() const; - inline void set_ticket_crc(::google::protobuf::uint32 value); - - // optional bytes ticket = 7; - inline bool has_ticket() const; - inline void clear_ticket(); - static const int kTicketFieldNumber = 7; - inline const ::std::string& ticket() const; - inline void set_ticket(const ::std::string& value); - inline void set_ticket(const char* value); - inline void set_ticket(const void* value, size_t size); - inline ::std::string* mutable_ticket(); - - // @@protoc_insertion_point(class_scope:CMsgAuthTicket) - private: - ::google::protobuf::UnknownFieldSet _unknown_fields_; - mutable int _cached_size_; - - ::google::protobuf::uint32 estate_; - ::google::protobuf::uint32 eresult_; - ::google::protobuf::uint64 steam_id_; - ::google::protobuf::uint64 game_id_; - ::google::protobuf::uint32 h_steam_pipe_; - ::google::protobuf::uint32 ticket_crc_; - ::std::string* ticket_; - static const ::std::string _default_ticket_; - friend void protobuf_AddDesc_steammessages_5fbase_2eproto(); - friend void protobuf_AssignDesc_steammessages_5fbase_2eproto(); - friend void protobuf_ShutdownFile_steammessages_5fbase_2eproto(); - - ::google::protobuf::uint32 _has_bits_[(7 + 31) / 32]; - - // WHY DOES & HAVE LOWER PRECEDENCE THAN != !? - inline bool _has_bit(int index) const { - return (_has_bits_[index / 32] & (1u << (index % 32))) != 0; - } - inline void _set_bit(int index) { - _has_bits_[index / 32] |= (1u << (index % 32)); - } - inline void _clear_bit(int index) { - _has_bits_[index / 32] &= ~(1u << (index % 32)); - } - - void InitAsDefaultInstance(); - static CMsgAuthTicket* default_instance_; -}; -// =================================================================== - - -// =================================================================== - -// CMsgProtoBufHeader - -// optional fixed64 client_steam_id = 1; -inline bool CMsgProtoBufHeader::has_client_steam_id() const { - return _has_bit(0); -} -inline void CMsgProtoBufHeader::clear_client_steam_id() { - client_steam_id_ = GOOGLE_ULONGLONG(0); - _clear_bit(0); -} -inline ::google::protobuf::uint64 CMsgProtoBufHeader::client_steam_id() const { - return client_steam_id_; -} -inline void CMsgProtoBufHeader::set_client_steam_id(::google::protobuf::uint64 value) { - _set_bit(0); - client_steam_id_ = value; -} - -// optional int32 client_session_id = 2; -inline bool CMsgProtoBufHeader::has_client_session_id() const { - return _has_bit(1); -} -inline void CMsgProtoBufHeader::clear_client_session_id() { - client_session_id_ = 0; - _clear_bit(1); -} -inline ::google::protobuf::int32 CMsgProtoBufHeader::client_session_id() const { - return client_session_id_; -} -inline void CMsgProtoBufHeader::set_client_session_id(::google::protobuf::int32 value) { - _set_bit(1); - client_session_id_ = value; -} - -// optional uint32 routing_appid = 3; -inline bool CMsgProtoBufHeader::has_routing_appid() const { - return _has_bit(2); -} -inline void CMsgProtoBufHeader::clear_routing_appid() { - routing_appid_ = 0u; - _clear_bit(2); -} -inline ::google::protobuf::uint32 CMsgProtoBufHeader::routing_appid() const { - return routing_appid_; -} -inline void CMsgProtoBufHeader::set_routing_appid(::google::protobuf::uint32 value) { - _set_bit(2); - routing_appid_ = value; -} - -// optional fixed64 job_id_source = 10 [default = 18446744073709551615]; -inline bool CMsgProtoBufHeader::has_job_id_source() const { - return _has_bit(3); -} -inline void CMsgProtoBufHeader::clear_job_id_source() { - job_id_source_ = GOOGLE_ULONGLONG(18446744073709551615); - _clear_bit(3); -} -inline ::google::protobuf::uint64 CMsgProtoBufHeader::job_id_source() const { - return job_id_source_; -} -inline void CMsgProtoBufHeader::set_job_id_source(::google::protobuf::uint64 value) { - _set_bit(3); - job_id_source_ = value; -} - -// optional fixed64 job_id_target = 11 [default = 18446744073709551615]; -inline bool CMsgProtoBufHeader::has_job_id_target() const { - return _has_bit(4); -} -inline void CMsgProtoBufHeader::clear_job_id_target() { - job_id_target_ = GOOGLE_ULONGLONG(18446744073709551615); - _clear_bit(4); -} -inline ::google::protobuf::uint64 CMsgProtoBufHeader::job_id_target() const { - return job_id_target_; -} -inline void CMsgProtoBufHeader::set_job_id_target(::google::protobuf::uint64 value) { - _set_bit(4); - job_id_target_ = value; -} - -// optional string target_job_name = 12; -inline bool CMsgProtoBufHeader::has_target_job_name() const { - return _has_bit(5); -} -inline void CMsgProtoBufHeader::clear_target_job_name() { - if (target_job_name_ != &_default_target_job_name_) { - target_job_name_->clear(); - } - _clear_bit(5); -} -inline const ::std::string& CMsgProtoBufHeader::target_job_name() const { - return *target_job_name_; -} -inline void CMsgProtoBufHeader::set_target_job_name(const ::std::string& value) { - _set_bit(5); - if (target_job_name_ == &_default_target_job_name_) { - target_job_name_ = new ::std::string; - } - target_job_name_->assign(value); -} -inline void CMsgProtoBufHeader::set_target_job_name(const char* value) { - _set_bit(5); - if (target_job_name_ == &_default_target_job_name_) { - target_job_name_ = new ::std::string; - } - target_job_name_->assign(value); -} -inline void CMsgProtoBufHeader::set_target_job_name(const char* value, size_t size) { - _set_bit(5); - if (target_job_name_ == &_default_target_job_name_) { - target_job_name_ = new ::std::string; - } - target_job_name_->assign(reinterpret_cast(value), size); -} -inline ::std::string* CMsgProtoBufHeader::mutable_target_job_name() { - _set_bit(5); - if (target_job_name_ == &_default_target_job_name_) { - target_job_name_ = new ::std::string; - } - return target_job_name_; -} - -// ------------------------------------------------------------------- - -// CMsgMulti - -// optional uint32 size_unzipped = 1; -inline bool CMsgMulti::has_size_unzipped() const { - return _has_bit(0); -} -inline void CMsgMulti::clear_size_unzipped() { - size_unzipped_ = 0u; - _clear_bit(0); -} -inline ::google::protobuf::uint32 CMsgMulti::size_unzipped() const { - return size_unzipped_; -} -inline void CMsgMulti::set_size_unzipped(::google::protobuf::uint32 value) { - _set_bit(0); - size_unzipped_ = value; -} - -// optional bytes message_body = 2; -inline bool CMsgMulti::has_message_body() const { - return _has_bit(1); -} -inline void CMsgMulti::clear_message_body() { - if (message_body_ != &_default_message_body_) { - message_body_->clear(); - } - _clear_bit(1); -} -inline const ::std::string& CMsgMulti::message_body() const { - return *message_body_; -} -inline void CMsgMulti::set_message_body(const ::std::string& value) { - _set_bit(1); - if (message_body_ == &_default_message_body_) { - message_body_ = new ::std::string; - } - message_body_->assign(value); -} -inline void CMsgMulti::set_message_body(const char* value) { - _set_bit(1); - if (message_body_ == &_default_message_body_) { - message_body_ = new ::std::string; - } - message_body_->assign(value); -} -inline void CMsgMulti::set_message_body(const void* value, size_t size) { - _set_bit(1); - if (message_body_ == &_default_message_body_) { - message_body_ = new ::std::string; - } - message_body_->assign(reinterpret_cast(value), size); -} -inline ::std::string* CMsgMulti::mutable_message_body() { - _set_bit(1); - if (message_body_ == &_default_message_body_) { - message_body_ = new ::std::string; - } - return message_body_; -} - -// ------------------------------------------------------------------- - -// CMsgAuthTicket - -// optional uint32 estate = 1; -inline bool CMsgAuthTicket::has_estate() const { - return _has_bit(0); -} -inline void CMsgAuthTicket::clear_estate() { - estate_ = 0u; - _clear_bit(0); -} -inline ::google::protobuf::uint32 CMsgAuthTicket::estate() const { - return estate_; -} -inline void CMsgAuthTicket::set_estate(::google::protobuf::uint32 value) { - _set_bit(0); - estate_ = value; -} - -// optional uint32 eresult = 2 [default = 2]; -inline bool CMsgAuthTicket::has_eresult() const { - return _has_bit(1); -} -inline void CMsgAuthTicket::clear_eresult() { - eresult_ = 2u; - _clear_bit(1); -} -inline ::google::protobuf::uint32 CMsgAuthTicket::eresult() const { - return eresult_; -} -inline void CMsgAuthTicket::set_eresult(::google::protobuf::uint32 value) { - _set_bit(1); - eresult_ = value; -} - -// optional fixed64 steam_id = 3; -inline bool CMsgAuthTicket::has_steam_id() const { - return _has_bit(2); -} -inline void CMsgAuthTicket::clear_steam_id() { - steam_id_ = GOOGLE_ULONGLONG(0); - _clear_bit(2); -} -inline ::google::protobuf::uint64 CMsgAuthTicket::steam_id() const { - return steam_id_; -} -inline void CMsgAuthTicket::set_steam_id(::google::protobuf::uint64 value) { - _set_bit(2); - steam_id_ = value; -} - -// optional fixed64 game_id = 4; -inline bool CMsgAuthTicket::has_game_id() const { - return _has_bit(3); -} -inline void CMsgAuthTicket::clear_game_id() { - game_id_ = GOOGLE_ULONGLONG(0); - _clear_bit(3); -} -inline ::google::protobuf::uint64 CMsgAuthTicket::game_id() const { - return game_id_; -} -inline void CMsgAuthTicket::set_game_id(::google::protobuf::uint64 value) { - _set_bit(3); - game_id_ = value; -} - -// optional uint32 h_steam_pipe = 5; -inline bool CMsgAuthTicket::has_h_steam_pipe() const { - return _has_bit(4); -} -inline void CMsgAuthTicket::clear_h_steam_pipe() { - h_steam_pipe_ = 0u; - _clear_bit(4); -} -inline ::google::protobuf::uint32 CMsgAuthTicket::h_steam_pipe() const { - return h_steam_pipe_; -} -inline void CMsgAuthTicket::set_h_steam_pipe(::google::protobuf::uint32 value) { - _set_bit(4); - h_steam_pipe_ = value; -} - -// optional uint32 ticket_crc = 6; -inline bool CMsgAuthTicket::has_ticket_crc() const { - return _has_bit(5); -} -inline void CMsgAuthTicket::clear_ticket_crc() { - ticket_crc_ = 0u; - _clear_bit(5); -} -inline ::google::protobuf::uint32 CMsgAuthTicket::ticket_crc() const { - return ticket_crc_; -} -inline void CMsgAuthTicket::set_ticket_crc(::google::protobuf::uint32 value) { - _set_bit(5); - ticket_crc_ = value; -} - -// optional bytes ticket = 7; -inline bool CMsgAuthTicket::has_ticket() const { - return _has_bit(6); -} -inline void CMsgAuthTicket::clear_ticket() { - if (ticket_ != &_default_ticket_) { - ticket_->clear(); - } - _clear_bit(6); -} -inline const ::std::string& CMsgAuthTicket::ticket() const { - return *ticket_; -} -inline void CMsgAuthTicket::set_ticket(const ::std::string& value) { - _set_bit(6); - if (ticket_ == &_default_ticket_) { - ticket_ = new ::std::string; - } - ticket_->assign(value); -} -inline void CMsgAuthTicket::set_ticket(const char* value) { - _set_bit(6); - if (ticket_ == &_default_ticket_) { - ticket_ = new ::std::string; - } - ticket_->assign(value); -} -inline void CMsgAuthTicket::set_ticket(const void* value, size_t size) { - _set_bit(6); - if (ticket_ == &_default_ticket_) { - ticket_ = new ::std::string; - } - ticket_->assign(reinterpret_cast(value), size); -} -inline ::std::string* CMsgAuthTicket::mutable_ticket() { - _set_bit(6); - if (ticket_ == &_default_ticket_) { - ticket_ = new ::std::string; - } - return ticket_; -} - - -// @@protoc_insertion_point(namespace_scope) - -#ifndef SWIG -namespace google { -namespace protobuf { - - -} // namespace google -} // namespace protobuf -#endif // SWIG - -// @@protoc_insertion_point(global_scope) - -#endif // PROTOBUF_steammessages_5fbase_2eproto__INCLUDED diff --git a/Resources/NetHook/tier0.lib b/Resources/NetHook/tier0.lib deleted file mode 100644 index 54081731..00000000 Binary files a/Resources/NetHook/tier0.lib and /dev/null differ diff --git a/Resources/NetHook/tier0/EventMasks.h b/Resources/NetHook/tier0/EventMasks.h deleted file mode 100644 index bbc9c3d2..00000000 --- a/Resources/NetHook/tier0/EventMasks.h +++ /dev/null @@ -1,480 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#pragma once - -typedef union EVENT_MASK(TC_deliver_mode) -{ - struct - { - uint16 DD:1; // both logical processors in deliver mode }, - uint16 DB:1; // logical processor 0 in deliver mode, 1 in build mode }, - uint16 DI:1; // logical processor 0 in deliver mode, 1 is inactive }, - uint16 BD:1; // logical processor 0 in build mode, 1 in deliver mode }, - uint16 BB:1; // both logical processors in build mode }, - uint16 BI:1; // logical processor 0 in build mode, 1 is inactive }, - uint16 ID:1; // logical processor 0 is inactive, 1 in deliver mode }, - uint16 IB:1; // logical processor 0 is inactive, 1 in build mode } - }; - uint16 flat; -} EVENT_MASK(TC_deliver_mode); - -typedef union EVENT_MASK(BPU_fetch_request) -{ - - struct - { - uint16 TCMISS:1; // Trace cache lookup miss }, - }; - uint16 flat; -} EVENT_MASK(BPU_fetch_request); - - -typedef union EVENT_MASK(ITLB_reference) -{ - struct - { - uint16 HIT : 1; //ITLB hit }, - uint16 MISS : 1;//ITLB miss }, - uint16 HIT_UC :1; // Uncacheable ITLB hit } - }; - uint16 flat; -} EVENT_MASK(ITLB_reference); - -typedef union EVENT_MASK(memory_cancel) -{ - struct - { - uint16 dummy : 2; - - uint16 ST_RB_FULL:1; //Replayed because no store request buffer is available }, - uint16 _64K_CONF:1; //Conflicts due to 64K aliasing } - }; - uint16 flat; -}EVENT_MASK(memory_cancel); - -typedef union EVENT_MASK(memory_complete) -{ - struct - { - uint16 LSC:1; // Load split completed, excluding UC/WC loads }, - uint16 SSC:1; //Any split stores completed } } - }; - uint16 flat; -} EVENT_MASK(memory_complete); - -typedef union EVENT_MASK(load_port_replay) -{ - struct - { - uint16 dummy:1; - uint16 SPLIT_LD:1; //Split load } } - }; - uint16 flat; -} EVENT_MASK(load_port_replay); - -typedef union EVENT_MASK(store_port_replay) -{ - struct - { - uint16 dummy0:1; - uint16 SPLIT_ST:1; //Split store } } - - }; - uint16 flat; -} EVENT_MASK(store_port_replay); - -typedef union EVENT_MASK(MOB_load_replay) -{ - struct - { - uint16 dummy0:1; - - uint16 NO_STA:1; //Replayed because of unknown store address }, - - uint16 dummy2:1; - - uint16 NO_STD:1; //Replayed because of unknown store data }, - uint16 PARTIAL_DATA:1; //Replayed because of partially overlapped data access between the load and store operations }, - uint16 UNALGN_ADDR:1; //Replayed because the lower 4 bits of the linear address do not match between the load and store operations } } - }; - uint16 flat; -}EVENT_MASK(MOB_load_replay); - -typedef union EVENT_MASK(page_walk_type) -{ - struct - { - uint16 DTMISS:1; // Page walk for a data TLB miss }, - uint16 ITMISS:1; // Page walk for an instruction TLB miss } } - }; - uint16 flat; -}EVENT_MASK(page_walk_type); - - -typedef union EVENT_MASK(BSQ_cache_reference) -{ - struct - { - uint16 RD_2ndL_HITS:1; // Read 2nd level cache hit Shared }, - uint16 RD_2ndL_HITE:1; // Read 2nd level cache hit Exclusive }, - uint16 RD_2ndL_HITM:1; // Read 2nd level cache hit Modified }, - uint16 RD_3rdL_HITS:1; // Read 3rd level cache hit Shared }, - uint16 RD_3rdL_HITE:1; // Read 3rd level cache hit Exclusive }, - uint16 RD_3rdL_HITM:1; // Read 3rd level cache hit Modified }, - uint16 dummy6:1; - uint16 dummy7:1; - uint16 RD_2ndL_MISS:1; // Read 2nd level cache miss }, - uint16 RD_3rdL_MISS:1; // Read 3rd level cache miss }, - uint16 WR_2ndL_MISS:1; // Writeback lookup from DAC misses the 2nd level cache } } - }; - uint16 flat; -} EVENT_MASK(BSQ_cache_reference) ; - -typedef union EVENT_MASK(IOQ) -{ - struct - { - uint16 bit0:1; // bus request type (use 00001 for invalid or default) - uint16 bit1:1; // - uint16 bit2:1; // - uint16 bit3:1; // - uint16 bit4:1; // - uint16 ALL_READ:1; // Count read entries }, - uint16 ALL_WRITE:1; // Count write entries }, - uint16 MEM_UC:1; // Count UC memory access entries }, - uint16 MEM_WC:1; // Count WC memory access entries }, - uint16 MEM_WT:1; // Count WT memory access entries }, - uint16 MEM_WP:1; // Count WP memory access entries }, - uint16 MEM_WB:1; // Count WB memory access entries }, - uint16 dummy12:1; - - uint16 OWN:1; // Count own store requests }, - uint16 OTHER:1; // Count other and DMA store requests }, - uint16 PREFETCH:1; // Include HW and SW prefetch requests } } - }; - uint16 flat; -} EVENT_MASK(IOQ) ; - -typedef union EVENT_MASK(FSB_data_activity) -{ - struct - { - /* DRDY_OWN is mutually exclusive with DRDY_OTHER */ - /* DBSY_OWN is mutually exclusive with DBSY_OTHER */ - uint16 DRDY_DRV:1; // Count when this processor drives data onto the bus }, - uint16 DRDY_OWN:1; // Count when this processor reads data from the bus }, - uint16 DRDY_OTHER:1; // Count when data is on the bus but not being sampled by the processor }, - uint16 DBSY_DRV:1; // Count when this processor reserves the bus for driving data }, - uint16 DBSY_OWN:1; // Count when this processor reserves the bus for sampling data }, - uint16 DBSY_OTHER:1; // Count when the bus is reserved for driving data this processor will not sample } } - }; - uint16 flat; -}EVENT_MASK(FSB_data_activity); - -typedef union EVENT_MASK(BSQ) -{ - struct - { - uint16 REQ_TYPE0:1; // Request type encoding bit 0 }, - uint16 REQ_TYPE1:1; // Request type encoding bit 1 }, - uint16 REQ_LEN0:1; // Request length encoding bit 0 }, - uint16 REQ_LEN1:1; // Request length encoding bit 1 }, - uint16 dummy4: 1; - uint16 REQ_IO_TYPE:1; // Request type is input or output }, - uint16 REQ_LOCK_TYPE:1; // Request type is bus lock }, - uint16 REQ_CACHE_TYPE:1; // Request type is cacheable }, - uint16 REQ_SPLIT_TYPE:1; // Request type is a bus 8-byte chunk split across 8-byte boundary }, - uint16 REQ_DEM_TYPE:1; // Request type is a demand (1) or prefetch (0) }, - uint16 REQ_ORD_TYPE:1; // Request is an ordered type }, - uint16 MEM_TYPE0:1; // Memory type encoding bit 0 }, - uint16 MEM_TYPE1:1; // Memory type encoding bit 1 }, - uint16 MEM_TYPE2:1; // Memory type encoding bit 2 } } - }; - uint16 flat; -} EVENT_MASK(BSQ); - -typedef union EVENT_MASK(firm_uop) -{ - struct - { - uint16 dummy15 : 15; - uint16 ALL:1; // count all uops of this type } } - }; - uint16 flat; -} EVENT_MASK(firm_uop); - - - -typedef union EVENT_MASK(TC_misc) -{ - struct - { - uint16 dymmy4 : 4; - uint16 FLUSH:1; // Number of flushes } } - }; - uint16 flat; -} EVENT_MASK(TC_misc); - -typedef union EVENT_MASK(global_power_events) -{ - struct - { - uint16 Running:1; // The processor is active } } - }; - uint16 flat; -} EVENT_MASK(global_power_events); - -typedef union EVENT_MASK(tc_ms_xfer) -{ - struct - { - uint16 CISC:1; // A TC to MS transfer ocurred } } - }; - uint16 flat; -}EVENT_MASK(tc_ms_xfer); - - - -typedef union EVENT_MASK(uop_queue_writes) -{ - struct - { - uint16 FROM_TC_BUILD:1; // uops written from TC build mode - uint16 FROM_TC_DELIVER:1; // uops written from TC deliver mode - uint16 FROM_ROM:1; // uops written from microcode ROM } } - }; - uint16 flat; -} EVENT_MASK(uop_queue_writes); - -typedef union EVENT_MASK(branch_type) -{ - struct - { - uint16 dummy : 1; - uint16 CONDITIONAL:1; // Conditional jumps - uint16 CALL:1; // Direct or indirect call - uint16 RETURN:1; // Return branches - uint16 INDIRECT:1; // Returns, indirect calls, or indirect jumps - }; - uint16 flat; -} EVENT_MASK(branch_type); - - - -typedef union EVENT_MASK(resource_stall) -{ - struct - { - uint16 dummy1 : 5; - uint16 SBFULL:1; // A Stall due to lack of store buffers } } - }; - uint16 flat; -} EVENT_MASK(resource_stall); - - - - -typedef union EVENT_MASK(WC_Buffer) -{ - struct - { - uint16 WCB_EVICTS : 1; // all causes }, - uint16 WCB_FULL_EVICT : 1; // no WC buffer is available }, - /* XXX: 245472-011 no longer lists bit 2, but that looks like - a table formatting error. Keeping it for now. */ - uint16 WCB_HITM_EVICT : 1; // store encountered a Hit Modified condition } } - }; - uint16 flat; -} EVENT_MASK(WC_Buffer); - - -typedef union EVENT_MASK(b2b_cycles) -{ - struct - { - uint16 dummy0 : 1; - uint16 bit1 : 1; // - uint16 bit2 : 1; // - uint16 bit3 : 1; // - uint16 bit4 : 1; // - uint16 bit5 : 1; // - uint16 bit6 : 1; // - - }; - uint16 flat; -} EVENT_MASK(b2b_cycles); - -typedef union EVENT_MASK(bnr) -{ - struct - { - uint16 bit0:1; // - uint16 bit1:1; // - uint16 bit2:1; // - }; - uint16 flat; -} EVENT_MASK(bnr); - - -typedef union EVENT_MASK(snoop) -{ - struct - { - uint16 dummy0 : 1; - uint16 dummy1 : 1; - - uint16 bit2:1; // - uint16 dummy3:1; // - uint16 dummy4:1; // - uint16 dummy5:1; // - uint16 bit6:1; // - uint16 bit7:1; // - }; - uint16 flat; -} EVENT_MASK(snoop); - - -typedef union EVENT_MASK(response) -{ - struct - { - uint16 dummy0:1; // - uint16 bit1:1; // - uint16 bit2:1; // - uint16 dummy3:1; // - uint16 dummy4:1; // - uint16 dummy5:1; // - uint16 dummy6:1; // - uint16 dummy7:1; // - uint16 bit8:1; // - uint16 bit9:1; // - }; - uint16 flat; -} EVENT_MASK(response); - - -typedef union EVENT_MASK(nbogus_bogus) -{ - struct - { - uint16 NBOGUS:1; // The marked uops are not bogus - uint16 BOGUS:1; // The marked uops are bogus - }; - uint16 flat; -} EVENT_MASK(nbogus_bogus); - - -typedef union EVENT_MASK(execution_event) -{ - struct - { - uint16 NBOGUS0:1; // non-bogus uops with tag bit 0 set }, - uint16 NBOGUS1:1; // non-bogus uops with tag bit 1 set }, - uint16 NBOGUS2:1; // non-bogus uops with tag bit 2 set }, - uint16 NBOGUS3:1; // non-bogus uops with tag bit 3 set }, - uint16 BOGUS0:1; // bogus uops with tag bit 0 set }, - uint16 BOGUS1:1; // bogus uops with tag bit 1 set }, - uint16 BOGUS2:1; // bogus uops with tag bit 2 set }, - uint16 BOGUS3:1; // bogus uops with tag bit 3 set } } - }; - uint16 flat; -}EVENT_MASK(execution_event); - -typedef union EVENT_MASK(instr_retired) -{ - struct - { - uint16 NBOGUSNTAG:1; // Non-bogus instructions that are not tagged }, - uint16 NBOGUSTAG:1; // Non-bogus instructions that are tagged }, - uint16 BOGUSNTAG:1; // Bogus instructions that are not tagged }, - uint16 BOGUSTAG:1; // Bogus instructions that are tagged } } - }; - uint16 flat; -} EVENT_MASK(instr_retired); - - -typedef union EVENT_MASK(uop_type) -{ - struct - { - uint16 dummy0 : 1; - uint16 TAGLOADS:1; // The uop is a load operation }, - uint16 TAGSTORES:1; // The uop is a store operation } } - }; - uint16 flat; -} EVENT_MASK(uop_type); - -typedef union EVENT_MASK(branch_retired) -{ - struct - { - uint16 MMNP:1; // Branch Not-taken Predicted - uint16 MMNM:1; // Branch Not-taken Mispredicted - uint16 MMTP:1; // Branch Taken Predicted - uint16 MMTM:1; // Branch Taken Mispredicted - }; - uint16 flat; -} EVENT_MASK(branch_retired); - -typedef union EVENT_MASK(mispred_branch_retired) -{ - struct - { - uint16 NBOGUS:1; // The retired branch is not bogus } } - }; - uint16 flat; -} EVENT_MASK(mispred_branch_retired); - - -typedef union EVENT_MASK(x87_assist) -{ - struct - { - uint16 FPSU:1; // FP stack underflow }, - uint16 FPSO:1; // FP stack overflow }, - uint16 POAO:1; // x87 output overflow }, - uint16 POAU:1; // x87 output underflow }, - uint16 PREA:1; // x87 input assist } } - }; - uint16 flat; -}EVENT_MASK(x87_assist); - -typedef union EVENT_MASK(machine_clear) -{ - struct - { - uint16 CLEAR:1; // Count a portion of the cycles when the machine is cleared }, - uint16 dummy1: 1; - uint16 MOCLEAR:1; // Count clears due to memory ordering issues }, - uint16 dummy3: 1; - uint16 dummy4: 1; - uint16 dummy5: 1; - - uint16 SMCLEAR:1;// Count clears due to self-modifying code issues } } - }; - uint16 flat; -} EVENT_MASK(machine_clear); - - -typedef union EVENT_MASK(x87_SIMD_moves_uop) -{ - struct - { - uint16 dummy3:3; - uint16 ALLP0:1; // Count all x87/SIMD store/move uops }, - uint16 ALLP2:1; // count all x87/SIMD load uops } } - }; - uint16 flat; -} EVENT_MASK(x87_SIMD_moves_uop); - - - - - - - diff --git a/Resources/NetHook/tier0/EventModes.h b/Resources/NetHook/tier0/EventModes.h deleted file mode 100644 index f2d0146c..00000000 --- a/Resources/NetHook/tier0/EventModes.h +++ /dev/null @@ -1,1787 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef EVENTMODES_H -#define EVENTMODES_H - - -#pragma once - -/* - - - - Event Modes to choose from: - - P4Event_TC_deliver_mode - - P4Event_BPU_fetch_request - - P4Event_ITLB_reference - - P4Event_memory_cancel - - P4Event_memory_complete - - P4Event_load_port_replay - - P4Event_store_port_replay - - P4Event_MOB_load_replay - - P4Event_page_walk_type - - P4Event_BSQ_cache_reference - - P4Event_IOQ_allocation - - P4Event_IOQ_active_entries - - P4Event_FSB_data_activity - - P4Event_BSQ_allocation - - P4Event_BSQ_active_entries - - P4Event_SSE_input_assist - - P4Event_packed_SP_uop - - P4Event_packed_DP_uop - - P4Event_scalar_SP_uop - - P4Event_scalar_DP_uop - - P4Event_64bit_MMX_uop - - P4Event_128bit_MMX_uop - - P4Event_x87_FP_uop - - P4Event_x87_SIMD_moves_uop - - P4Event_TC_misc - - P4Event_global_power_events - - P4Event_tc_ms_xfer - - P4Event_uop_queue_writes - - P4Event_retired_mispred_branch_type - - P4Event_retired_branch_type - - P4Event_resource_stall - - P4Event_WC_Buffer - - P4Event_b2b_cycles - - P4Event_bnr - - P4Event_snoop - - P4Event_response - - P4Event_front_end_event - - P4Event_execution_event - - P4Event_replay_event - - P4Event_instr_retired - - P4Event_uops_retired - - P4Event_uop_type - - P4Event_branch_retired - - P4Event_mispred_branch_retired - - P4Event_x87_assist - - P4Event_machine_clear - - -*/ - - - -class P4P4Event_TC_deliver_mode: public P4BaseEvent -{ -public: - EVENT_MASK(TC_deliver_mode) * eventMask; - - P4P4Event_TC_deliver_mode() - { - eventMask = (EVENT_MASK(TC_deliver_mode) *)&m_eventMask; - - escr.ESCREventSelect = 0x01; - cccr.CCCRSelect = 0x01; - //// eventType = EVENT_TYPE(TC_deliver_mode); - description = _T("TC_deliver_mode"); - UseCounter4(); - } - - - void UseCounter4() - { - SetCounter(4);; - } - void UseCounter5() - { - SetCounter(5); - } - void UseCounter6() - { - SetCounter(6); - } - void UseCounter7() - { - SetCounter(7); - } -}; - -class P4P4Event_BPU_fetch_request: public P4BaseEvent - -{ -public: - EVENT_MASK(BPU_fetch_request)* eventMask; - - P4P4Event_BPU_fetch_request() - { - eventMask = (EVENT_MASK(BPU_fetch_request) *)&m_eventMask; - - escr.ESCREventSelect= 0x03; - cccr.CCCRSelect= 0x00; - // eventType = EVENT_TYPE(BPU_fetch_request); - description=_T("BPU_fetch_request"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } - -}; -class P4P4Event_ITLB_reference: public P4BaseEvent - -{ -public: - EVENT_MASK(ITLB_reference) * eventMask; - - P4P4Event_ITLB_reference() - { - eventMask = (EVENT_MASK(ITLB_reference) *)&m_eventMask; - - escr.ESCREventSelect= 0x18; - cccr.CCCRSelect= 0x03; - // eventType=EVENT_TYPE(ITLB_reference); - description=_T("ITLB_reference"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_memory_cancel: public P4BaseEvent - -{ -public: - EVENT_MASK(memory_cancel) * eventMask; - - P4Event_memory_cancel() - { - eventMask = (EVENT_MASK(memory_cancel) *)&m_eventMask; - - escr.ESCREventSelect= 0x02; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(memory_cancel); - description=_T("memory_cancel"); - UseCounter8(); - } - - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_memory_complete: public P4BaseEvent - -{ -public: - EVENT_MASK(memory_complete) * eventMask; - - P4Event_memory_complete() - { - eventMask = (EVENT_MASK(memory_complete) *)&m_eventMask; - - escr.ESCREventSelect= 0x08; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(memory_complete); - description=_T("memory_complete"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_load_port_replay: public P4BaseEvent - -{ -public: - EVENT_MASK(load_port_replay) * eventMask; - - P4Event_load_port_replay() - { - eventMask = (EVENT_MASK(load_port_replay) *)&m_eventMask; - - escr.ESCREventSelect= 0x04; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(load_port_replay); - description=_T("load_port_replay"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_store_port_replay: public P4BaseEvent - -{ -public: - EVENT_MASK(store_port_replay) * eventMask; - - P4Event_store_port_replay() - { - eventMask = (EVENT_MASK(store_port_replay) *)&m_eventMask; - - escr.ESCREventSelect= 0x05; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(store_port_replay); - description=_T("store_port_replay"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_MOB_load_replay: public P4BaseEvent - -{ -public: - EVENT_MASK(MOB_load_replay) * eventMask; - - P4Event_MOB_load_replay() - { - eventMask = (EVENT_MASK(MOB_load_replay) *)&m_eventMask; - - escr.ESCREventSelect= 0x03; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(MOB_load_replay); - description=_T("MOB_load_replay"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_page_walk_type: public P4BaseEvent - -{ -public: - EVENT_MASK(page_walk_type) * eventMask; - - P4Event_page_walk_type() - { - eventMask = (EVENT_MASK(page_walk_type) *)&m_eventMask; - - escr.ESCREventSelect= 0x01; - cccr.CCCRSelect= 0x04; - // eventType=EVENT_TYPE(page_walk_type); - description=_T("page_walk_type"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_BSQ_cache_reference: public P4BaseEvent - -{ -public: - EVENT_MASK(BSQ_cache_reference) * eventMask; - - P4Event_BSQ_cache_reference() - { - eventMask = (EVENT_MASK(BSQ_cache_reference) *)&m_eventMask; - - escr.ESCREventSelect= 0x0C; - cccr.CCCRSelect= 0x07; - // eventType=EVENT_TYPE(BSQ_cache_reference); - description=_T("BSQ_cache_reference"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_IOQ_allocation: public P4BaseEvent - -{ -public: - EVENT_MASK(IOQ) * eventMask; - - P4Event_IOQ_allocation() - { - eventMask = (EVENT_MASK(IOQ) *)&m_eventMask; - - escr.ESCREventSelect= 0x03; - cccr.CCCRSelect= 0x06; - // eventType=EVENT_TYPE(IOQ); - description=_T("IOQ_allocation"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_IOQ_active_entries: public P4BaseEvent - -{ -public: - EVENT_MASK(IOQ) * eventMask; - - P4Event_IOQ_active_entries() - { - eventMask = (EVENT_MASK(IOQ) *)&m_eventMask; - - escr.ESCREventSelect= 0x1A; - cccr.CCCRSelect= 0x06; - // eventType=EVENT_TYPE(IOQ); - description=_T("IOQ_active_entries"); - UseCounter2(); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_FSB_data_activity: public P4BaseEvent - -{ -public: - EVENT_MASK(FSB_data_activity) * eventMask; - - P4Event_FSB_data_activity() - { - eventMask = (EVENT_MASK(FSB_data_activity) *)&m_eventMask; - - escr.ESCREventSelect= 0x17; - cccr.CCCRSelect= 0x06; - // eventType=EVENT_TYPE(FSB_data_activity); - description=_T("FSB_data_activity"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_BSQ_allocation: public P4BaseEvent - -{ -public: - EVENT_MASK(BSQ) * eventMask; - - P4Event_BSQ_allocation() - { - eventMask = (EVENT_MASK(BSQ) *)&m_eventMask; - - escr.ESCREventSelect= 0x05; - cccr.CCCRSelect= 0x07; - // eventType=EVENT_TYPE(BSQ); - description=_T("BSQ_allocation"); - UseCounter0(); - } - - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - - } -}; -class P4Event_BSQ_active_entries: public P4BaseEvent - -{ -public: - EVENT_MASK(BSQ) * eventMask; - - P4Event_BSQ_active_entries() - { - eventMask = (EVENT_MASK(BSQ) *)&m_eventMask; - - escr.ESCREventSelect= 0x06; - cccr.CCCRSelect= 0x07; - // eventType=EVENT_TYPE(BSQ); - description=_T("bsq_active_entries"); - UseCounter2(); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_SSE_input_assist: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_SSE_input_assist() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x34; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("SSE_input_assist"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_packed_SP_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_packed_SP_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x08; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("packed_SP_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_packed_DP_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_packed_DP_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x0C; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("packed_DP_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_scalar_SP_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_scalar_SP_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x0A; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("scalar_SP_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_scalar_DP_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_scalar_DP_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x0E; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("scalar_DP_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_64bit_MMX_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_64bit_MMX_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x02; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("64bit_MMX_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_128bit_MMX_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_128bit_MMX_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x1A; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("128bit_MMX_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_x87_FP_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(firm_uop) * eventMask; - - P4Event_x87_FP_uop() - { - eventMask = (EVENT_MASK(firm_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x04; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(firm_uop); - description=_T("x87_FP_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_x87_SIMD_moves_uop: public P4BaseEvent - -{ -public: - EVENT_MASK(x87_SIMD_moves_uop) * eventMask; - - P4Event_x87_SIMD_moves_uop() - { - eventMask = (EVENT_MASK(x87_SIMD_moves_uop) *)&m_eventMask; - - escr.ESCREventSelect= 0x2E; - cccr.CCCRSelect= 0; - // eventType=EVENT_TYPE(x87_SIMD_moves_uop); - description=_T("x87_SIMD_moves_uop"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_TC_misc: public P4BaseEvent - -{ -public: - EVENT_MASK(TC_misc) * eventMask; - - P4Event_TC_misc() - { - eventMask = (EVENT_MASK(TC_misc) *)&m_eventMask; - - escr.ESCREventSelect= 0x06; - cccr.CCCRSelect= 0x01; - // eventType=EVENT_TYPE(TC_misc); - description=_T("TC_misc"); - UseCounter4(); - } - - void UseCounter4() - { - SetCounter(4);; - } - void UseCounter5() - { - SetCounter(5); - } - void UseCounter6() - { - SetCounter(6); - } - void UseCounter7() - { - SetCounter(7); - } -}; -class P4Event_global_power_events: public P4BaseEvent - -{ -public: - EVENT_MASK(global_power_events) * eventMask; - - P4Event_global_power_events() - { - eventMask = (EVENT_MASK(global_power_events) *)&m_eventMask; - - escr.ESCREventSelect= 0x13; - cccr.CCCRSelect= 0x06; - // eventType=EVENT_TYPE(global_power_events); - description=_T("global_power_events"); - UseCounter0(); - } - - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_tc_ms_xfer: public P4BaseEvent - -{ -public: - EVENT_MASK(tc_ms_xfer) * eventMask; - - P4Event_tc_ms_xfer() - { - eventMask = (EVENT_MASK(tc_ms_xfer) *)&m_eventMask; - - escr.ESCREventSelect= 0x05; - cccr.CCCRSelect= 0x00; - // eventType=EVENT_TYPE(tc_ms_xfer); - description=_T("tc_ms_xfer"); - UseCounter4(); - } - - void UseCounter4() - { - SetCounter(4);; - } - void UseCounter5() - { - SetCounter(5); - } - void UseCounter6() - { - SetCounter(6); - } - void UseCounter7() - { - SetCounter(7); - } -}; -class P4Event_uop_queue_writes: public P4BaseEvent - -{ -public: - EVENT_MASK(uop_queue_writes) * eventMask; - - P4Event_uop_queue_writes() - { - eventMask = (EVENT_MASK(uop_queue_writes) *)&m_eventMask; - - escr.ESCREventSelect= 0x09; - cccr.CCCRSelect= 0x00; - // eventType=EVENT_TYPE(uop_queue_writes); - description=_T("uop_queue_writes"); - UseCounter4(); - } - - void UseCounter4() - { - SetCounter(4);; - } - void UseCounter5() - { - SetCounter(5); - } - void UseCounter6() - { - SetCounter(6); - } - void UseCounter7() - { - SetCounter(7); - } -}; -class P4Event_retired_mispred_branch_type: public P4BaseEvent - -{ -public: - EVENT_MASK(branch_type) * eventMask; - - P4Event_retired_mispred_branch_type() - { - eventMask = (EVENT_MASK(branch_type) *)&m_eventMask; - - escr.ESCREventSelect= 0x05; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(branch_type); - description=_T("retired_mispred_branch_type"); - UseCounter4(); - } - - void UseCounter4() - { - SetCounter(4);; - } - void UseCounter5() - { - SetCounter(5); - } - void UseCounter6() - { - SetCounter(6); - } - void UseCounter7() - { - SetCounter(7); - } -}; -class P4Event_retired_branch_type: public P4BaseEvent - -{ -public: - EVENT_MASK(branch_type) * eventMask; - - P4Event_retired_branch_type() - { - eventMask = (EVENT_MASK(branch_type) *)&m_eventMask; - - escr.ESCREventSelect= 0x04; - cccr.CCCRSelect= 0x04; - // eventType=EVENT_TYPE(branch_type); - description=_T("retired_branch_type"); - UseCounter4(); - } - - void UseCounter4() - { - SetCounter(4);; - } - void UseCounter5() - { - SetCounter(5); - } - void UseCounter6() - { - SetCounter(6); - } - void UseCounter7() - { - SetCounter(7); - } -}; -class P4Event_resource_stall: public P4BaseEvent - -{ -public: - EVENT_MASK(resource_stall) * eventMask; - - P4Event_resource_stall() - { - eventMask = (EVENT_MASK(resource_stall) *)&m_eventMask; - - escr.ESCREventSelect= 0x01; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(resource_stall); - description=_T("resource_stall"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } - -}; -class P4Event_WC_Buffer: public P4BaseEvent - -{ -public: - EVENT_MASK(WC_Buffer) * eventMask; - - P4Event_WC_Buffer() - { - eventMask = (EVENT_MASK(WC_Buffer) *)&m_eventMask; - - escr.ESCREventSelect= 0x05; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(WC_Buffer); - description=_T("WC_Buffer"); - UseCounter8(); - } - void UseCounter8() - { - SetCounter(8); - } - void UseCounter9() - { - SetCounter(9); - } - void UseCounter10() - { - SetCounter(10); - } - void UseCounter11() - { - SetCounter(11); - } - -}; -class P4Event_b2b_cycles: public P4BaseEvent - -{ -public: - EVENT_MASK(b2b_cycles) * eventMask; - - P4Event_b2b_cycles() - { - eventMask = (EVENT_MASK(b2b_cycles) *)&m_eventMask; - - escr.ESCREventSelect= 0x16; - cccr.CCCRSelect= 0x03; - // eventType=EVENT_TYPE(b2b_cycles); - description=_T("b2b_cycles"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_bnr: public P4BaseEvent - -{ -public: - EVENT_MASK(bnr) * eventMask; - - P4Event_bnr() - { - eventMask = (EVENT_MASK(bnr) *)&m_eventMask; - - escr.ESCREventSelect= 0x08; - cccr.CCCRSelect= 0x03; - // eventType=EVENT_TYPE(bnr); - description=_T("bnr"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_snoop: public P4BaseEvent - -{ -public: - EVENT_MASK(snoop) * eventMask; - - P4Event_snoop() - { - eventMask = (EVENT_MASK(snoop) *)&m_eventMask; - - escr.ESCREventSelect= 0x06; - cccr.CCCRSelect= 0x03; - // eventType=EVENT_TYPE(snoop); - description=_T("snoop"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_response: public P4BaseEvent - -{ -public: - EVENT_MASK(response) * eventMask; - - P4Event_response() - { - eventMask = (EVENT_MASK(response) *)&m_eventMask; - - escr.ESCREventSelect= 0x04; - cccr.CCCRSelect= 0x03; - // eventType=EVENT_TYPE(response); - description=_T("response"); - UseCounter0(); - } - void UseCounter0() - { - SetCounter(0); - } - void UseCounter1() - { - SetCounter(1); - } - void UseCounter2() - { - SetCounter(2); - } - void UseCounter3() - { - SetCounter(3); - } -}; -class P4Event_front_end_event: public P4BaseEvent - -{ -public: - EVENT_MASK(nbogus_bogus) * eventMask; - - P4Event_front_end_event() - { - eventMask = (EVENT_MASK(nbogus_bogus) *)&m_eventMask; - - escr.ESCREventSelect= 0x08; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(nbogus_bogus); - description=_T("front_end_event"); - UseCounter12(); - } - - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_execution_event: public P4BaseEvent - -{ -public: - EVENT_MASK(execution_event) * eventMask; - - P4Event_execution_event() - { - eventMask = (EVENT_MASK(execution_event) *)&m_eventMask; - - escr.ESCREventSelect= 0x0C; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(execution_event); - description=_T("execution_event"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_replay_event: public P4BaseEvent - -{ -public: - EVENT_MASK(nbogus_bogus) * eventMask; - - P4Event_replay_event() - { - eventMask = (EVENT_MASK(nbogus_bogus) *)&m_eventMask; - - escr.ESCREventSelect= 0x09; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(nbogus_bogus); - description=_T("replay_event"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_instr_retired: public P4BaseEvent - -{ -public: - EVENT_MASK(instr_retired) * eventMask; - - P4Event_instr_retired() - { - eventMask = (EVENT_MASK(instr_retired) *)&m_eventMask; - - escr.ESCREventSelect= 0x02; - cccr.CCCRSelect= 0x04; - // eventType=EVENT_TYPE(instr_retired); - description=_T("instr_retired"); - UseCounter12(); - } - - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_uops_retired: public P4BaseEvent - -{ -public: - EVENT_MASK(nbogus_bogus) * eventMask; - - P4Event_uops_retired() - { - eventMask = (EVENT_MASK(nbogus_bogus) *)&m_eventMask; - - escr.ESCREventSelect= 0x01; - cccr.CCCRSelect= 0x04; - // eventType=EVENT_TYPE(nbogus_bogus); - description=_T("uops_retired"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_uop_type: public P4BaseEvent - -{ -public: - EVENT_MASK(uop_type) * eventMask; - - P4Event_uop_type() - { - eventMask = (EVENT_MASK(uop_type) *)&m_eventMask; - - escr.ESCREventSelect= 0x02; - cccr.CCCRSelect= 0x02; - // eventType=EVENT_TYPE(uop_type); - description=_T("uop_type"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_branch_retired: public P4BaseEvent - -{ -public: - EVENT_MASK(branch_retired) * eventMask; - - P4Event_branch_retired() - { - eventMask = (EVENT_MASK(branch_retired) *)&m_eventMask; - - escr.ESCREventSelect= 0x06; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(branch_retired); - description=_T("branch_retired"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_mispred_branch_retired: public P4BaseEvent - -{ -public: - EVENT_MASK(mispred_branch_retired) * eventMask; - - P4Event_mispred_branch_retired() - { - eventMask = (EVENT_MASK(mispred_branch_retired) *)&m_eventMask; - - escr.ESCREventSelect= 0x03; - cccr.CCCRSelect= 0x04; - // eventType=EVENT_TYPE(mispred_branch_retired); - description=_T("mispred_branch_retired"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_x87_assist: public P4BaseEvent - -{ -public: - EVENT_MASK(x87_assist) * eventMask; - - P4Event_x87_assist() - { - eventMask = (EVENT_MASK(x87_assist) *)&m_eventMask; - - escr.ESCREventSelect= 0x03; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(x87_assist); - description=_T("x87_assist"); - UseCounter12(); - } - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } -}; -class P4Event_machine_clear: public P4BaseEvent - -{ -public: - EVENT_MASK(machine_clear) * eventMask; - - P4Event_machine_clear() - { - eventMask = (EVENT_MASK(machine_clear) *)&m_eventMask; - escr.ESCREventSelect= 0x02; - cccr.CCCRSelect= 0x05; - // eventType=EVENT_TYPE(machine_clear); - description=_T("machine_clear"); - UseCounter12(); - } - - - - void UseCounter12() - { - SetCounter(12); - } - void UseCounter13() - { - SetCounter(13); - - } - - void UseCounter14() - { - SetCounter(14); - } - void UseCounter15() - { - SetCounter(15); - - } - - void UseCounter16() - { - SetCounter(16); - } - void UseCounter17() - { - SetCounter(17); - - } - -}; - -#endif // EVENTMODES_H diff --git a/Resources/NetHook/tier0/IOCTLCodes.h b/Resources/NetHook/tier0/IOCTLCodes.h deleted file mode 100644 index cc00aef5..00000000 --- a/Resources/NetHook/tier0/IOCTLCodes.h +++ /dev/null @@ -1,29 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef IOCTLCODES_H -#define IOCTLCODES_H -#pragma once - -// Define the IOCTL codes we will use. The IOCTL code contains a command -// identifier, plus other information about the device, the type of access -// with which the file must have been opened, and the type of buffering. - -// Device type -- in the "User Defined" range." -#define DEVICE_FILE_TYPE 40000 - - -// The IOCTL function codes from 0x800 to 0xFFF are for customer use. - -#define IOCTL_WRITE_MSR \ - CTL_CODE( DEVICE_FILE_TYPE, 0x900, METHOD_BUFFERED, FILE_READ_ACCESS ) - -#define IOCTL_READ_MSR \ - CTL_CODE( DEVICE_FILE_TYPE, 0x901, METHOD_BUFFERED, FILE_READ_ACCESS ) - - -#endif IOCTLCODES_H diff --git a/Resources/NetHook/tier0/K8PerformanceCounters.h b/Resources/NetHook/tier0/K8PerformanceCounters.h deleted file mode 100644 index ff30c4ac..00000000 --- a/Resources/NetHook/tier0/K8PerformanceCounters.h +++ /dev/null @@ -1,2028 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef K8PERFORMANCECOUNTERS_H -#define K8PERFORMANCECOUNTERS_H - -/* - * AMD K8 events. - * - */ - - - -typedef union EVENT_MASK(NULL_MASK) -{ - // no tests defined - uint16 flat; -} EVENT_MASK(NULL_MASK); - - -#define MSR_K8_EVNTSEL0 0xC0010000 /* .. 0xC0010003 */ -#define MSR_K8_PERFCTR0 0xC0010004 /* .. 0xC0010007 */ - -# pragma pack(push, 1) - - - -// access to these bits is through the methods -typedef union PerfEvtSel -{ - struct - { - uint64 EventMask : 8; - - uint64 UnitMask : 8; - uint64 USR : 1; - uint64 OS : 1; - uint64 Edge : 1; - uint64 PC : 1; - uint64 INTAPIC : 1; - uint64 Reserved21 : 1; - uint64 Enable : 1; - uint64 Complement : 1; // aka INV - uint64 Threshold : 8; // aka CounterMask - uint64 Reserver32 : 32; - }; - uint64 flat; - -} PerfEvtSel; - - -enum UnitEncode -{ - FP, - LS, - DC, - BU, - IC, - UE_Unknown, - FR, - NB -}; - -# pragma pack(pop) - -// Turn off the no return value warning in ReadCounter. -#pragma warning( disable : 4035 ) -#define k8NUM_COUNTERS 4 -class k8BaseEvent -{ -public: - - PME * pme; - - PerfEvtSel eventSelect[k8NUM_COUNTERS]; - - unsigned short m_eventMask; - int event_id; - tchar * name; - tchar revRequired; - int eventSelectNum; - UnitEncode unitEncode; - - - void SetCounter(int n) - { - if (n < 0) - n = 0; - else if (n > 3) - n = 3; - eventSelectNum = n; - - } - k8BaseEvent() - { - pme = PME::Instance(); - - for(int i = 0; i< k8NUM_COUNTERS; i++) - { - eventSelect[i].flat = 0; - - } - eventSelectNum = 0; - - m_eventMask = 0; - event_id = 0; - name = 0; - revRequired = 'A'; - - - } - - void SetCaptureMode(PrivilegeCapture priv) - { - PerfEvtSel & select = eventSelect[eventSelectNum]; - StopCounter(); - - switch (priv) - { - case OS_Only: - select.USR = 0; - select.OS = 1; - break; - - case USR_Only: - select.USR = 1; - select.OS = 0; - break; - - case OS_and_USR: - select.USR = 1; - select.OS = 1; - break; - } - - - select.UnitMask = m_eventMask; - select.EventMask = event_id; - - - int selectPort = MSR_K8_EVNTSEL0 + eventSelectNum; - pme->WriteMSR(selectPort, select.flat); - } - - - void SetFiltering(CompareState compareEnable, - CompareMethod compareMethod, - uint8 threshold, - EdgeState edgeEnable) - { - - PerfEvtSel & select = eventSelect[eventSelectNum]; - - StopCounter(); - - if (compareEnable == CompareDisable) - select.Threshold = 0; - else - select.Threshold = threshold; - - select.Complement = compareMethod; - - select.Edge = edgeEnable; - - int selectPort = MSR_K8_EVNTSEL0 + eventSelectNum; - pme->WriteMSR(selectPort, select.flat); - - - } - - - void StartCounter() - { - PerfEvtSel & select = eventSelect[eventSelectNum]; - - select.Enable = 1; - int selectPort = MSR_K8_EVNTSEL0 + eventSelectNum; - - pme->WriteMSR(selectPort, select.flat); - - } - void StopCounter() - { - PerfEvtSel & select = eventSelect[eventSelectNum]; - select.Enable = 0; - int selectPort = MSR_K8_EVNTSEL0 + eventSelectNum; - - pme->WriteMSR(selectPort, select.flat); - } - - - - void ClearCounter() - { - PerfEvtSel & select = eventSelect[eventSelectNum]; - - int counterPort = MSR_K8_PERFCTR0 + eventSelectNum; - - pme->WriteMSR(counterPort, 0ui64 ); // clear - } - - void WriteCounter(int64 value) - { - - PerfEvtSel & select = eventSelect[eventSelectNum]; - - int counterPort = MSR_K8_PERFCTR0 + eventSelectNum; - pme->WriteMSR(counterPort, value); // clear - } - - int64 ReadCounter() - { - -#if PME_DEBUG - PerfEvtSel & select = eventSelect[eventSelectNum]; - - if (select.USR == 0 && select.OS == 0) - return -1; // no area to collect, use SetCaptureMode - - if (select.EventMask == 0) - return -2; // no event mask set - - if (eventSelectNum < 0 || eventSelectNum > 3) - return -3; // counter not legal - - // check revision - -#endif - - // ReadMSR should work here too, but RDPMC should be faster - //ReadMSR(counterPort, int64); - - // we need to copy this into a temp for some reason - int temp = eventSelectNum; - _asm - { - mov ecx, temp - RDPMC - } - - } - - -}; -#pragma warning( default : 4035 ) - - - - -typedef union EVENT_MASK(k8_dispatched_fpu_ops) -{ - // event 0 - struct - { - uint16 AddPipeOps:1; // Add pipe ops excluding junk ops" }, - uint16 MulPipeOps:1; // Multiply pipe ops excluding junk ops" },, - uint16 StoreOps:1; // Store pipe ops excluding junk ops" }, - uint16 AndPipeOpsJunk:1; // Add pipe junk ops" },, - uint16 MulPipeOpsJunk:1; // Multiply pipe junk ops" }, - uint16 StoreOpsJunk:1; // Store pipe junk ops" } } - }; - uint16 flat; -} EVENT_MASK(k8_dispatched_fpu_ops); - -class k8Event_DISPATCHED_FPU_OPS : public k8BaseEvent -{ -public: - - k8Event_DISPATCHED_FPU_OPS() - { - eventMask = (EVENT_MASK(k8_dispatched_fpu_ops) *)&m_eventMask; - - event_id = 0x00; - unitEncode = FP; - name = _T("Dispatched FPU ops"); - revRequired = 'B'; - } - EVENT_MASK(k8_dispatched_fpu_ops) * eventMask; - -}; - -////////////////////////////////////////////////////////// - - - -class k8Event_NO_FPU_OPS : public k8BaseEvent -{ -public: - - k8Event_NO_FPU_OPS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - event_id = 0x01; - unitEncode = FP; - - name = _T("Cycles with no FPU ops retired"); - revRequired = 'B'; - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - -////////////////////////////////////////////////////////// - -class k8Event_FAST_FPU_OPS : public k8BaseEvent -{ -public: - - k8Event_FAST_FPU_OPS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - event_id = 0x02; - unitEncode = FP; - - name = _T("Dispatched FPU ops that use the fast flag interface"); - revRequired = 'B'; - - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - -////////////////////////////////////////////////////////// - - -typedef union EVENT_MASK(k8_segment_register_load) -{ - - struct - { - uint16 ES:1; - uint16 CS:1; - uint16 SS:1; - uint16 DS:1; - uint16 FS:1; - uint16 GS:1; - uint16 HS:1; - }; - uint16 flat; -} EVENT_MASK(k8_segment_register_load); - - -class k8Event_SEG_REG_LOAD : public k8BaseEvent -{ -public: - - k8Event_SEG_REG_LOAD() - { - eventMask = (EVENT_MASK(k8_segment_register_load) *)&m_eventMask; - name = _T("Segment register load"); - event_id = 0x20; - unitEncode = LS; - - } - EVENT_MASK(k8_segment_register_load) * eventMask; - -}; - - -class k8Event_SELF_MODIFY_RESYNC : public k8BaseEvent -{ -public: - - k8Event_SELF_MODIFY_RESYNC() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Microarchitectural resync caused by self modifying code"); - event_id = 0x21; - unitEncode = LS; - - } - EVENT_MASK(NULL_MASK) * eventMask; - - -}; -class k8Event_LS_RESYNC_BY_SNOOP : public k8BaseEvent -{ -public: - - k8Event_LS_RESYNC_BY_SNOOP() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - event_id = 0x22; - unitEncode = LS; - - name = _T("Microarchitectural resync caused by snoop"); - } - EVENT_MASK(NULL_MASK) * eventMask; - - -}; -class k8Event_LS_BUFFER_FULL : public k8BaseEvent -{ -public: - - k8Event_LS_BUFFER_FULL() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("LS Buffer 2 Full"); - event_id = 0x23; - unitEncode = LS; - - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - -typedef union EVENT_MASK(k8_locked_op) -{ - - - struct - { - uint16 NumLockInstr : 1; //Number of lock instructions executed - uint16 NumCyclesInRequestGrant : 1; //Number of cycles spent in the lock request/grant stage - - uint16 NumCyclesForLock:1; - /*Number of cycles a lock takes to complete once it is - non-speculative and is the oldest load/store operation - (non-speculative cycles in Ls2 entry 0)*/ - - - }; - uint16 flat; - - -} EVENT_MASK(k8_locked_op); - - - -class k8Event_LOCKED_OP : public k8BaseEvent -{ -public: - - EVENT_MASK(k8_locked_op) * eventMask; - - k8Event_LOCKED_OP() - { - eventMask = (EVENT_MASK(k8_locked_op) *)&m_eventMask; - name = _T("Locked operation"); - event_id = 0x24; - unitEncode = LS; - - revRequired = 'C'; - } - - -}; - -class k8Event_OP_LATE_CANCEL : public k8BaseEvent -{ -public: - - k8Event_OP_LATE_CANCEL() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Microarchitectural late cancel of an operation"); - event_id = 0x25; - unitEncode = LS; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("OP_LATE_CANCEL"); - - -}; -class k8Event_CFLUSH_RETIRED : public k8BaseEvent -{ -public: - - k8Event_CFLUSH_RETIRED() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Retired CFLUSH instructions"); - event_id = 0x26; - unitEncode = LS; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("CFLUSH_RETIRED"); - - -}; -class k8Event_CPUID_RETIRED : public k8BaseEvent -{ -public: - - k8Event_CPUID_RETIRED() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Retired CPUID instructions"); - event_id = 0x27; - unitEncode = LS; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("CPUID_RETIRED"); - - -}; - -typedef union EVENT_MASK( k8_cache) -{ - - struct - { - uint16 Invalid:1; - uint16 Exclusive:1; - uint16 Shared:1; - uint16 Owner:1; - uint16 Modified:1; - }; - uint16 flat; - -}EVENT_MASK( k8_cache); - /* 0x40-0x47: from K7 official event set */ - - -class k8Event_DATA_CACHE_ACCESSES : public k8BaseEvent -{ - k8Event_DATA_CACHE_ACCESSES() - { - - event_id = 0x40; - unitEncode = DC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - //_T("DATA_CACHE_ACCESSES"), - name = _T("Data cache accesses"); - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - -class k8Event_DATA_CACHE_MISSES : public k8BaseEvent -{ - k8Event_DATA_CACHE_MISSES() - { - - event_id = 0x41; - unitEncode = DC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - //_T("DATA_CACHE_MISSES"), - name = _T("Data cache misses"); - } - EVENT_MASK(NULL_MASK) * eventMask; -}; - -class k8Event_DATA_CACHE_REFILLS_FROM_L2 : public k8BaseEvent -{ - k8Event_DATA_CACHE_REFILLS_FROM_L2() - { - - event_id = 0x42; - unitEncode = DC; - - eventMask = (EVENT_MASK(k8_cache) *)&m_eventMask; - - - name = _T("Data cache refills from L2"); - } - EVENT_MASK(k8_cache) * eventMask; - -}; - -class k8Event_DATA_CACHE_REFILLS_FROM_SYSTEM : public k8BaseEvent -{ - k8Event_DATA_CACHE_REFILLS_FROM_SYSTEM() - { - - event_id = 0x43; - unitEncode = DC; - - - eventMask = (EVENT_MASK(k8_cache) *)&m_eventMask; - - //UM(k7_um_moesi), - //_T("DATA_CACHE_REFILLS_FROM_SYSTEM"), - name = _T("Data cache refills from system"); - } - EVENT_MASK(k8_cache) * eventMask; - -}; - -class k8Event_DATA_CACHE_WRITEBACKS : public k8BaseEvent -{ - k8Event_DATA_CACHE_WRITEBACKS() - { - - event_id = 0x44; - unitEncode = DC; - - eventMask = (EVENT_MASK(k8_cache) *)&m_eventMask; - - //UM(k7_um_moesi), - //_T("DATA_CACHE_WRITEBACKS"), - name = _T("Data cache writebacks"); - } - EVENT_MASK(k8_cache) * eventMask; - - -}; - -class k8Event_L1_DTLB_MISSES_AND_L2_DTLB_HITS : public k8BaseEvent -{ - k8Event_L1_DTLB_MISSES_AND_L2_DTLB_HITS() - { - - event_id = 0x45; - unitEncode = DC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - name = _T("L1 DTLB misses and L2 DTLB hits"); - } - EVENT_MASK(NULL_MASK) * eventMask; - - -}; - -class k8Event_L1_AND_L2_DTLB_MISSES : public k8BaseEvent -{ - k8Event_L1_AND_L2_DTLB_MISSES() - { - - event_id = 0x46; - unitEncode = DC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - name = _T("L1 and L2 DTLB misses") ; - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - -class k8Event_MISALIGNED_DATA_REFERENCES : public k8BaseEvent -{ - k8Event_MISALIGNED_DATA_REFERENCES() - { - - event_id = 0x47; - unitEncode = DC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - //NULL, _T("MISALIGNED_DATA_REFERENCES"), - name = _T("Misaligned data references"); - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - - -class k8Event_ACCESS_CANCEL_LATE : public k8BaseEvent -{ -public: - - k8Event_ACCESS_CANCEL_LATE() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Microarchitectural late cancel of an access"); - event_id = 0x48; - unitEncode = DC; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("ACCESS_CANCEL_LATE"); - - -}; -class k8Event_ACCESS_CANCEL_EARLY : public k8BaseEvent -{ -public: - - k8Event_ACCESS_CANCEL_EARLY() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Microarchitectural early cancel of an access"); - event_id = 0x49; - unitEncode = DC; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("ACCESS_CANCEL_EARLY"); - - -}; -typedef union EVENT_MASK( k8_ecc) -{ - struct - { - uint16 ScrubberError : 1; // Scrubber error" }, - uint16 PiggybackScrubberErrors : 1; // Piggyback scrubber errors" } } - }; - uint16 flat; - -}EVENT_MASK( k8_ecc); - - -class k8Event_ECC_BIT_ERR : public k8BaseEvent -{ -public: - - k8Event_ECC_BIT_ERR() - { - eventMask = (EVENT_MASK(k8_ecc) *)&m_eventMask; - name = _T("One bit ECC error recorded found by scrubber"); - event_id = 0x4A; - unitEncode = DC; - - } - EVENT_MASK(k8_ecc) * eventMask; - // name = _T("ECC_BIT_ERR"); - - -}; - -// 4B -typedef union EVENT_MASK( k8_distpatch_prefetch_instructions) -{ - struct - { - uint16 Load : 1; - uint16 Store : 1; - uint16 NTA : 1; - }; - uint16 flat; - - -}EVENT_MASK( k8_distpatch_prefetch_instructions); - -class k8Event_DISPATCHED_PRE_INSTRS : public k8BaseEvent -{ -public: - - k8Event_DISPATCHED_PRE_INSTRS() - { - eventMask = (EVENT_MASK(k8_distpatch_prefetch_instructions) *)&m_eventMask; - name = _T("Dispatched prefetch instructions"); - event_id = 0x4B; - unitEncode = DC; - - } - EVENT_MASK(k8_distpatch_prefetch_instructions) * eventMask; - // name = _T("DISPATCHED_PRE_INSTRS"); - - /* 0x4C: added in Revision C */ - -}; - - - -typedef union EVENT_MASK( k8_lock_accesses) -{ - struct - { - uint16 DcacheAccesses:1; // Number of dcache accesses by lock instructions" }, - uint16 DcacheMisses:1; // Number of dcache misses by lock instructions" } } - }; - uint16 flat; - -}EVENT_MASK( k8_lock_accesses); - - - -class k8Event_LOCK_ACCESSES : public k8BaseEvent -{ -public: - - k8Event_LOCK_ACCESSES() - { - eventMask = (EVENT_MASK(k8_lock_accesses) *)&m_eventMask; - name = _T("DCACHE accesses by locks") ; - event_id = 0x4C; - unitEncode = DC; - - revRequired = 'C'; - } - EVENT_MASK(k8_lock_accesses) * eventMask; - - -}; - - -class k8Event_CYCLES_PROCESSOR_IS_RUNNING : public k8BaseEvent -{ -public: - - k8Event_CYCLES_PROCESSOR_IS_RUNNING() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Cycles processor is running (not in HLT or STPCLK)"); - event_id = 0x76; - unitEncode = BU; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("CYCLES_PROCESSOR_IS_RUNNING"); /* undocumented *; - - -}; - - -typedef union EVENT_MASK( k8_internal_L2_request) -{ - struct - { - uint16 ICFill:1; // IC fill" }, - uint16 DCFill:1; // DC fill" }, - uint16 TLBReload:1; // TLB reload" }, - uint16 TagSnoopRequest:1; // Tag snoop request" }, - uint16 CancelledRequest:1; // Cancelled request" } } - }; - uint16 flat; - - -}EVENT_MASK( k8_internal_L2_request); - -class k8Event_BU_INT_L2_REQ : public k8BaseEvent -{ -public: - - k8Event_BU_INT_L2_REQ() - { - eventMask = (EVENT_MASK(k8_internal_L2_request) *)&m_eventMask; - name = _T("Internal L2 request"); - unitEncode = BU; - event_id = 0x7D; - } - - EVENT_MASK(k8_internal_L2_request) * eventMask; -} ; - - // name = _T("BU_INT_L2_REQ"); - - - -// 7E -typedef union EVENT_MASK( k8_fill_request_missed_L2) -{ - - struct - { - uint16 ICFill:1; // IC fill" }, - uint16 DCFill:1; // DC fill" }, - uint16 TLBReload:1; // TLB reload" }, - }; - uint16 flat; - -} EVENT_MASK( k8_fill_request_missed_L2); - - -class k8Event_BU_FILL_REQ : public k8BaseEvent -{ -public: - - k8Event_BU_FILL_REQ() - { - eventMask = (EVENT_MASK(k8_fill_request_missed_L2) *)&m_eventMask; - name = _T("Fill request that missed in L2"); - event_id = 0x7E; - unitEncode = BU; - - } - EVENT_MASK(k8_fill_request_missed_L2) * eventMask; - // name = _T("BU_FILL_REQ"); - - - -}; - - - - -// 7F -typedef union EVENT_MASK( k8_fill_into_L2) -{ - - struct - { - uint16 DirtyL2Victim:1; // Dirty L2 victim - uint16 VictimFromL2:1; // Victim from L2 - }; - uint16 flat; - -}EVENT_MASK( k8_fill_into_L2); - -class k8Event_BU_FILL_L2 : public k8BaseEvent -{ -public: - - k8Event_BU_FILL_L2() - { - eventMask = (EVENT_MASK(k8_fill_into_L2) *)&m_eventMask; - name = _T("Fill into L2"); - event_id = 0x7F; - unitEncode = BU; - - } - EVENT_MASK(k8_fill_into_L2) * eventMask; - // name = _T("BU_FILL_L2"); - - -}; - -class k8Event_INSTRUCTION_CACHE_FETCHES : public k8BaseEvent -{ -public: - k8Event_INSTRUCTION_CACHE_FETCHES() - { - event_id = 0x80; - unitEncode = IC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - name = _T("Instruction cache fetches"); - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - -class k8Event_INSTRUCTION_CACHE_MISSES : public k8BaseEvent -{ -public: - k8Event_INSTRUCTION_CACHE_MISSES() - { - event_id = 0x81; - unitEncode = IC; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - //0xF, NULL, _T("INSTRUCTION_CACHE_MISSES"), - name = _T("Instruction cache misses"); - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - -class k8Event_IC_REFILL_FROM_L2 : public k8BaseEvent -{ -public: - - k8Event_IC_REFILL_FROM_L2() - { - eventMask = (EVENT_MASK(k8_cache) *)&m_eventMask; - name = _T("Refill from L2"); - event_id = 0x82; - unitEncode = IC; - - } - EVENT_MASK(k8_cache) * eventMask; - // name = _T("IC_REFILL_FROM_L2"); - - - -}; -class k8Event_IC_REFILL_FROM_SYS : public k8BaseEvent -{ -public: - - k8Event_IC_REFILL_FROM_SYS() - { - eventMask = (EVENT_MASK(k8_cache) *)&m_eventMask; - name = _T("Refill from system"); - event_id = 0x83; - unitEncode = IC; - - } - EVENT_MASK(k8_cache) * eventMask; - // name = _T("IC_REFILL_FROM_SYS"); - - - -}; -class k8Event_L1_ITLB_MISSES_AND_L2_ITLB_HITS : public k8BaseEvent -{ -public: - k8Event_L1_ITLB_MISSES_AND_L2_ITLB_HITS() - { - - event_id = 0x84; - unitEncode = IC; - - name = _T("L1 ITLB misses (and L2 ITLB hits)"); - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - - } - EVENT_MASK(NULL_MASK) * eventMask; - - -}; - -class k8Event_L1_AND_L2_ITLB_MISSES : public k8BaseEvent -{ -public: - k8Event_L1_AND_L2_ITLB_MISSES() - { - event_id = 0x85; - unitEncode = IC; - - name = _T("(L1 and) L2 ITLB misses"); - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - - - -class k8Event_IC_RESYNC_BY_SNOOP : public k8BaseEvent -{ -public: - - k8Event_IC_RESYNC_BY_SNOOP() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - event_id = 0x86; - unitEncode = IC; - - name = _T("Microarchitectural resync caused by snoop"); - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("IC_RESYNC_BY_SNOOP"); - /* similar to 0x22; but IC unit instead of LS unit */ - - - -}; -class k8Event_IC_FETCH_STALL : public k8BaseEvent -{ -public: - - k8Event_IC_FETCH_STALL() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Instruction fetch stall"); - event_id = 0x87; - unitEncode = IC; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("IC_FETCH_STALL"); - - - -}; -class k8Event_IC_STACK_HIT : public k8BaseEvent -{ -public: - - k8Event_IC_STACK_HIT() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Return stack hit"); - event_id = 0x88; - unitEncode = IC; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("IC_STACK_HIT"); - - - -}; -class k8Event_IC_STACK_OVERFLOW : public k8BaseEvent -{ -public: - - k8Event_IC_STACK_OVERFLOW() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Return stack overflow"); - event_id = 0x89; - unitEncode = IC; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("IC_STACK_OVERFLOW"); - - - - -}; - - /* 0xC0-0xC7: from K7 official event set */ -class k8Event_RETIRED_INSTRUCTIONS : public k8BaseEvent -{ -public: - k8Event_RETIRED_INSTRUCTIONS() - { - event_id = 0xC0; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - //0xF, NULL, _T("RETIRED_INSTRUCTIONS"), - name = _T("Retired instructions (includes exceptions, interrupts, resyncs)"); - } - EVENT_MASK(NULL_MASK) * eventMask; -}; - -class k8Event_RETIRED_OPS : public k8BaseEvent -{ -public: - k8Event_RETIRED_OPS() - { - event_id = 0xC1; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_OPS"), - name = _T("Retired Ops") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; -class k8Event_RETIRED_BRANCHES : public k8BaseEvent -{ -public: - k8Event_RETIRED_BRANCHES() - { - event_id = 0xC2; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_BRANCHES"), - name = _T("Retired branches (conditional, unconditional, exceptions, interrupts)") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; -class k8Event_RETIRED_BRANCHES_MISPREDICTED : public k8BaseEvent -{ -public: - k8Event_RETIRED_BRANCHES_MISPREDICTED() - { - event_id = 0xC3; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_BRANCHES_MISPREDICTED"), - name = _T("Retired branches mispredicted") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; -class k8Event_RETIRED_TAKEN_BRANCHES : public k8BaseEvent -{ -public: - k8Event_RETIRED_TAKEN_BRANCHES() - { - event_id = 0xC4; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_TAKEN_BRANCHES"), - name = _T("Retired taken branches") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; -class k8Event_RETIRED_TAKEN_BRANCHES_MISPREDICTED : public k8BaseEvent -{ -public: - k8Event_RETIRED_TAKEN_BRANCHES_MISPREDICTED() - { - event_id = 0xC5; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_TAKEN_BRANCHES_MISPREDICTED"), - name = _T("Retired taken branches mispredicted") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; -class k8Event_RETIRED_FAR_CONTROL_TRANSFERS : public k8BaseEvent -{ -public: - k8Event_RETIRED_FAR_CONTROL_TRANSFERS() - { - event_id = 0xC6; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_FAR_CONTROL_TRANSFERS"), - name = _T("Retired far control transfers") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; -class k8Event_RETIRED_RESYNC_BRANCHES : public k8BaseEvent -{ -public: - k8Event_RETIRED_RESYNC_BRANCHES() - { - event_id = 0xC7; - unitEncode = FR; - - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - //0xF, NULL, _T("RETIRED_RESYNC_BRANCHES"), - name = _T("Retired resync branches (only non-control transfer branches counted)") ; - } - EVENT_MASK(NULL_MASK) * eventMask; -}; - -class k8Event_RETIRED_NEAR_RETURNS : public k8BaseEvent -{ -public: - - k8Event_RETIRED_NEAR_RETURNS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Retired near returns"); - event_id = 0xC8; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - - - -}; -class k8Event_RETIRED_RETURNS_MISPREDICT : public k8BaseEvent -{ -public: - - k8Event_RETIRED_RETURNS_MISPREDICT() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Retired near returns mispredicted"); - event_id = 0xC9; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("RETIRED_RETURNS_MISPREDICT"); - - -}; -class k8Event_RETIRED_BRANCH_MISCOMPARE : public k8BaseEvent -{ -public: - - k8Event_RETIRED_BRANCH_MISCOMPARE() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Retired taken branches mispredicted due to address miscompare"); - event_id = 0xCA; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("RETIRED_BRANCH_MISCOMPARE"); - - -}; - - - /* Revision B and later */ - -typedef union EVENT_MASK( k8_retired_fpu_instr) -{ - struct - { - uint16 DirtyL2Victim:1; // x87 instructions - uint16 CombinedMMX_3DNow:1; // Combined MMX & 3DNow! instructions" }, - uint16 CombinedPackedSSE_SSE2:1; // Combined packed SSE and SSE2 instructions" }, - uint16 CombinedScalarSSE_SSE2:1; // Combined scalar SSE and SSE2 instructions" } } - }; - uint16 flat; - - -}EVENT_MASK( k8_retired_fpu_instr); - - -class k8Event_RETIRED_FPU_INSTRS : public k8BaseEvent -{ -public: - - k8Event_RETIRED_FPU_INSTRS() - { - eventMask = (EVENT_MASK(k8_retired_fpu_instr) *)&m_eventMask; - event_id = 0xCB; - unitEncode = FR; - - name = _T("Retired FPU instructions"); - revRequired = 'B'; - } - EVENT_MASK(k8_retired_fpu_instr) * eventMask; - /* Revision B and later */ - - - -}; - -// CC -typedef union EVENT_MASK( k8_retired_fastpath_double_op_instr ) -{ - - struct - { - uint16 LowOpPosition0:1; // With low op in position 0" }, - uint16 LowOpPosition1:1; // With low op in position 1" }, - uint16 LowOpPosition2:1; // With low op in position 2" } } - }; - uint16 flat; - - -}EVENT_MASK( k8_retired_fastpath_double_op_instr); - -class k8Event_RETIRED_FASTPATH_INSTRS : public k8BaseEvent -{ -public: - - k8Event_RETIRED_FASTPATH_INSTRS() - { - eventMask = (EVENT_MASK(k8_retired_fastpath_double_op_instr) *)&m_eventMask; - event_id = 0xCC; - unitEncode = FR; - - name = _T("Retired fastpath double op instructions"); - revRequired = 'B'; - - } - EVENT_MASK(k8_retired_fastpath_double_op_instr) * eventMask; - - -}; - -class k8Event_INTERRUPTS_MASKED_CYCLES : public k8BaseEvent -{ -public: - k8Event_INTERRUPTS_MASKED_CYCLES() - { - event_id = 0xCD; - unitEncode = FR; - - //0xF, NULL, _T("INTERRUPTS_MASKED_CYCLES"), - name = _T("Interrupts masked cycles (IF=0)") ; - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; -class k8Event_INTERRUPTS_MASKED_WHILE_PENDING_CYCLES : public k8BaseEvent -{ -public: - k8Event_INTERRUPTS_MASKED_WHILE_PENDING_CYCLES() - { - event_id = 0xCE; - unitEncode = FR; - - //0xF, NULL, _T("INTERRUPTS_MASKED_WHILE_PENDING_CYCLES"), - name = _T("Interrupts masked while pending cycles (INTR while IF=0)") ; - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; -class k8Event_NUMBER_OF_TAKEN_HARDWARE_INTERRUPTS : public k8BaseEvent -{ -public: - k8Event_NUMBER_OF_TAKEN_HARDWARE_INTERRUPTS() - { - event_id = 0xCF; - unitEncode = FR; - - //0xF, NULL, _T("NUMBER_OF_TAKEN_HARDWARE_INTERRUPTS"), - name = _T("Number of taken hardware interrupts") ; - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - } - EVENT_MASK(NULL_MASK) * eventMask; - -}; - - -class k8Event_DECODER_EMPTY : public k8BaseEvent -{ -public: - - k8Event_DECODER_EMPTY() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Nothing to dispatch (decoder empty)"); - event_id = 0xD0; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DECODER_EMPTY"); - - -}; -class k8Event_DISPATCH_STALLS : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALLS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stalls (events 0xD2-0xDA combined)"); - event_id = 0xD1; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALLS"); - - - -}; -class k8Event_DISPATCH_STALL_FROM_BRANCH_ABORT : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_FROM_BRANCH_ABORT() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall from branch abort to retire"); - event_id = 0xD2; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_FROM_BRANCH_ABORT"); - - - -}; -class k8Event_DISPATCH_STALL_SERIALIZATION : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_SERIALIZATION() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall for serialization"); - event_id = 0xD3; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_SERIALIZATION"); - - -}; -class k8Event_DISPATCH_STALL_SEG_LOAD : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_SEG_LOAD() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall for segment load"); - event_id = 0xD4; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_SEG_LOAD"); - - - -}; -class k8Event_DISPATCH_STALL_REORDER_BUFFER : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_REORDER_BUFFER() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall when reorder buffer is full"); - event_id = 0xD5; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_REORDER_BUFFER"); - - -}; -class k8Event_DISPATCH_STALL_RESERVE_STATIONS : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_RESERVE_STATIONS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall when reservation stations are full"); - event_id = 0xD6; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_RESERVE_STATIONS"); - - -}; -class k8Event_DISPATCH_STALL_FPU : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_FPU() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall when FPU is full"); - event_id = 0xD7; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_FPU"); - - -}; -class k8Event_DISPATCH_STALL_LS : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_LS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall when LS is full"); - event_id = 0xD8; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_LS"); - - -}; -class k8Event_DISPATCH_STALL_QUIET_WAIT : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_QUIET_WAIT() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall when waiting for all to be quiet"); - event_id = 0xD9; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_QUIET_WAIT"); - - - -}; -class k8Event_DISPATCH_STALL_PENDING : public k8BaseEvent -{ -public: - - k8Event_DISPATCH_STALL_PENDING() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Dispatch stall when far control transfer or resync branch is pending"); - event_id = 0xDA; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DISPATCH_STALL_PENDING"); - - - -}; - - -typedef union EVENT_MASK( k8_fpu_exceptions) -{ - - - - struct - { - uint16 x87ReclassMicrofaults:1; // x87 reclass microfaults" }, - uint16 SSERetypeMicrofaults:1; // SSE retype microfaults" }, - uint16 SSEReclassMicrofaults:1; // SSE reclass microfaults" }, - uint16 SSE_x87Microtraps:1; // SSE and x87 microtraps" } } - }; - uint16 flat; - - - -}EVENT_MASK( k8_fpu_exceptions); - -class k8Event_FPU_EXCEPTIONS : public k8BaseEvent -{ -public: - - k8Event_FPU_EXCEPTIONS() - { - eventMask = (EVENT_MASK(k8_fpu_exceptions) *)&m_eventMask; - event_id = 0xDB; - unitEncode = FR; - - name = _T("FPU exceptions"); - revRequired = 'B'; - - } - EVENT_MASK(k8_fpu_exceptions) * eventMask; - // name = _T("FPU_EXCEPTIONS"); - /* Revision B and later */ - - - -}; -class k8Event_DR0_BREAKPOINTS : public k8BaseEvent -{ -public: - - k8Event_DR0_BREAKPOINTS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Number of breakpoints for DR0"); - event_id = 0xDC; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DR0_BREAKPOINTS"); - - - -}; -class k8Event_DR1_BREAKPOINTS : public k8BaseEvent -{ -public: - - k8Event_DR1_BREAKPOINTS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Number of breakpoints for DR1"); - event_id = 0xDD; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DR1_BREAKPOINTS"); - - - -}; -class k8Event_DR2_BREAKPOINTS : public k8BaseEvent -{ -public: - - k8Event_DR2_BREAKPOINTS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Number of breakpoints for DR2"); - event_id = 0xDE; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DR2_BREAKPOINTS"); - - -}; -class k8Event_DR3_BREAKPOINTS : public k8BaseEvent -{ -public: - - k8Event_DR3_BREAKPOINTS() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Number of breakpoints for DR3"); - event_id = 0xDF; - unitEncode = FR; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DR3_BREAKPOINTS"); - - -}; - - - -// E0 -typedef union EVENT_MASK( k8_page_access_event) -{ - struct - { - uint16 PageHit:1; // Page hit" }, - uint16 PageMiss:1; // Page miss" }, - uint16 PageConflict:1; // Page conflict" } } - }; - uint16 flat; - -}EVENT_MASK( k8_page_access_event); - -class k8Event_MEM_PAGE_ACCESS : public k8BaseEvent -{ -public: - - k8Event_MEM_PAGE_ACCESS() - { - eventMask = (EVENT_MASK(k8_page_access_event) *)&m_eventMask; - name = _T("Memory controller page access"); - event_id = 0xE0; - unitEncode = NB; - - } - EVENT_MASK(k8_page_access_event) * eventMask; - // name = _T("MEM_PAGE_ACCESS"); - - -}; -class k8Event_MEM_PAGE_TBL_OVERFLOW : public k8BaseEvent -{ -public: - - k8Event_MEM_PAGE_TBL_OVERFLOW() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Memory controller page table overflow"); - event_id = 0xE1; - unitEncode = NB; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("MEM_PAGE_TBL_OVERFLOW"); - - -}; -class k8Event_DRAM_SLOTS_MISSED : public k8BaseEvent -{ -public: - - k8Event_DRAM_SLOTS_MISSED() - { - eventMask = (EVENT_MASK(NULL_MASK) *)&m_eventMask; - name = _T("Memory controller DRAM command slots missed (in MemClks)"); - event_id = 0xE2; - unitEncode = NB; - - } - EVENT_MASK(NULL_MASK) * eventMask; - // name = _T("DRAM_SLOTS_MISSED"); - - -}; - - -// e3 -typedef union EVENT_MASK( k8_turnaround) -{ - - struct - { - uint16 DIMMTurnaround:1; //DIMM turnaround" }, - uint16 ReadToWriteTurnaround:1; //Read to write turnaround" }, - uint16 WriteToReadTurnaround:1; //Write to read turnaround" } } - }; - uint16 flat; - - -}EVENT_MASK( k8_turnaround); - -class k8Event_MEM_TURNAROUND : public k8BaseEvent -{ -public: - - k8Event_MEM_TURNAROUND() - { - eventMask = (EVENT_MASK(k8_turnaround) *)&m_eventMask; - name = _T("Memory controller turnaround"); - event_id = 0xE3; - unitEncode = NB; - - } - EVENT_MASK(k8_turnaround) * eventMask; - // name = _T("MEM_TURNAROUND"); - - -}; - - - - -// E4 -typedef union EVENT_MASK( k8_bypass_counter_saturation) -{ - struct - { - uint16 MEM_HighPriorityBypass:1; // Memory controller high priority bypass" }, - uint16 MEM_LowPriorityBypass:1; // Memory controller low priority bypass" }, - uint16 DRAM_InterfaceBypass:1; // DRAM controller interface bypass" }, - uint16 DRAM_QueueBypass:1; // DRAM controller queue bypass" } } - }; - uint16 flat; - -}EVENT_MASK( k8_bypass_counter_saturation); - -class k8Event_MEM_BYPASS_SAT : public k8BaseEvent -{ -public: - - k8Event_MEM_BYPASS_SAT() - { - eventMask = (EVENT_MASK(k8_bypass_counter_saturation) *)&m_eventMask; - name = _T("Memory controller bypass counter saturation"); - event_id = 0xE4; - unitEncode = NB; - - } - EVENT_MASK(k8_bypass_counter_saturation) * eventMask; - // name = _T("MEM_BYPASS_SAT"); - - -}; - - - -//EB -typedef union EVENT_MASK( k8_sized_commands) -{ - - struct - { - uint16 NonPostWrSzByte:1; // NonPostWrSzByte" }, - uint16 NonPostWrSzDword:1; // NonPostWrSzDword" }, - uint16 PostWrSzByte:1; // PostWrSzByte" }, - uint16 PostWrSzDword:1; // PostWrSzDword" }, - uint16 RdSzByte:1; // RdSzByte" }, - uint16 RdSzDword:1; // RdSzDword" }, - uint16 RdModWr:1; // RdModWr" } } - }; - uint16 flat; - - -}EVENT_MASK( k8_sized_commands); - - -class k8Event_SIZED_COMMANDS : public k8BaseEvent -{ -public: - - k8Event_SIZED_COMMANDS() - { - eventMask = (EVENT_MASK(k8_sized_commands) *)&m_eventMask; - name = _T("Sized commands"); - event_id = 0xEB; - unitEncode = NB; - - } - EVENT_MASK(k8_sized_commands) * eventMask; - // name = _T("SIZED_COMMANDS"); - - -}; - -typedef union EVENT_MASK( k8_probe_result) -{ - struct - { - uint16 ProbeMiss:1; // Probe miss" }, - uint16 ProbeHit:1; // Probe hit" }, - uint16 ProbeHitDirtyWithoutMemoryCancel:1; // Probe hit dirty without memory cancel" }, - uint16 ProbeHitDirtyWithMemoryCancel:1; // Probe hit dirty with memory cancel" } } - uint16 UpstreamDisplayRefreshReads:1; // Rev D and later - uint16 UpstreamNonDisplayRefreshReads:1; // Rev D and later - uint16 UpstreamWrites:1; // Rev D and later - }; - uint16 flat; - - -}EVENT_MASK( k8_probe_result); - - -class k8Event_PROBE_RESULT : public k8BaseEvent -{ -public: - - k8Event_PROBE_RESULT() - { - eventMask = (EVENT_MASK(k8_probe_result) *)&m_eventMask; - name = _T("Probe result"); - event_id = 0xEC; - unitEncode = NB; - - } - EVENT_MASK(k8_probe_result) * eventMask; - // name = _T("PROBE_RESULT"); - - -}; - -typedef union EVENT_MASK( k8_ht) -{ - - struct - { - uint16 CommandSent:1; //Command sent" }, - uint16 DataSent:1; //Data sent" }, - uint16 BufferReleaseSent:1; //Buffer release sent" - uint16 NopSent:1; //Nop sent" } } - }; - uint16 flat; - - -}EVENT_MASK( k8_ht); - - -class k8Event_HYPERTRANSPORT_BUS0_WIDTH : public k8BaseEvent -{ -public: - - k8Event_HYPERTRANSPORT_BUS0_WIDTH() - { - eventMask = (EVENT_MASK(k8_ht) *)&m_eventMask; - name = _T("Hypertransport (tm) bus 0 bandwidth"); - event_id = 0xF6; - unitEncode = NB; - - } - EVENT_MASK(k8_ht) * eventMask; - // name = _T("HYPERTRANSPORT_BUS0_WIDTH"); - - -}; -class k8Event_HYPERTRANSPORT_BUS1_WIDTH : public k8BaseEvent -{ -public: - - k8Event_HYPERTRANSPORT_BUS1_WIDTH() - { - eventMask = (EVENT_MASK(k8_ht) *)&m_eventMask; - name = _T("Hypertransport (tm) bus 1 bandwidth"); - event_id = 0xF7; - unitEncode = NB; - - } - EVENT_MASK(k8_ht) * eventMask; - // name = _T("HYPERTRANSPORT_BUS1_WIDTH"); - - -}; -class k8Event_HYPERTRANSPORT_BUS2_WIDTH : public k8BaseEvent -{ -public: - - k8Event_HYPERTRANSPORT_BUS2_WIDTH() - { - eventMask = (EVENT_MASK(k8_ht) *)&m_eventMask; - name = _T("Hypertransport (tm) bus 2 bandwidth"); - event_id = 0xF8; - unitEncode = NB; - - } - EVENT_MASK(k8_ht) * eventMask; - // name = _T("HYPERTRANSPORT_BUS2_WIDTH"); - -}; - -// -//typedef union EVENT_MASK( perfctr_event_set k8_common_event_set) -//{ -// -// .cpu_type = PERFCTR_X86_AMD_K8, -// .event_prefix = _T("K8_"), -// .include = &k7_official_event_set, -// .nevents = ARRAY_SIZE(k8_common_events), -// .events = k8_common_events, -//}EVENT_MASK( perfctr_event_set k8_common_event_set); -// -//typedef union EVENT_MASK( perfctr_event k8_events[]) -//{ -// -// { 0x24, 0xF, UM(NULL), _T("LOCKED_OP"), /* unit mask changed in Rev. C */ -// _T("Locked operation") }, -//}EVENT_MASK( perfctr_event k8_events[]); - - - - -//const struct perfctr_event_set perfctr_k8_event_set) -//{ -// -// .cpu_type = PERFCTR_X86_AMD_K8, -// .event_prefix = _T("K8_"), -// .include = &k8_common_event_set, -// .nevents = ARRAY_SIZE(k8_events), -// .events = k8_events, -//}; -// -/* - * K8 Revision C. Starts at CPUID 0xF58 for Opteron/Athlon64FX and - * CPUID 0xF48 for Athlon64. (CPUID 0xF51 is Opteron Revision B3.) - */ - - - - - - - - -// -//typedef union EVENT_MASK( k8_lock_accesses) -//{ -// struct -// { -// uint16 DcacheAccesses:1; // Number of dcache accesses by lock instructions" }, -// uint16 DcacheMisses:1; // Number of dcache misses by lock instructions" } } -// }; -// uint16 flat; -// -//}EVENT_MASK( k8_lock_accesses); -// - -#endif // K8PERFORMANCECOUNTERS_H diff --git a/Resources/NetHook/tier0/P4PerformanceCounters.h b/Resources/NetHook/tier0/P4PerformanceCounters.h deleted file mode 100644 index d4487785..00000000 --- a/Resources/NetHook/tier0/P4PerformanceCounters.h +++ /dev/null @@ -1,322 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef P4PERFORMANCECOUNTERS_H -#define P4PERFORMANCECOUNTERS_H - -#pragma once -// Pentium 4 support - -/* - http://developer.intel.com/design/Pentium4/documentation.htm - - IA-32 Intel Architecture Software Developer's Manual Volume 1: Basic Architecture - - IA-32 Intel Architecture Software Developer's Manual Volume 2A: Instruction Set Reference, A-M - - IA-32 Intel Architecture Software Developer's Manual Volume 2B: Instruction Set Reference, N-Z - - IA-32 Intel Architecture Software Developer's Manual Volume 3: System Programming Guide - - - From Mikael Pettersson's perfctr: - - http://user.it.uu.se/~mikpe/linux/perfctr/ - - * Known quirks: - - OVF_PMI+FORCE_OVF counters must have an ireset value of -1. - This allows the regular overflow check to also handle FORCE_OVF - counters. Not having this restriction would lead to MAJOR - complications in the driver's "detect overflow counters" code. - There is no loss of functionality since the ireset value doesn't - affect the counter's PMI rate for FORCE_OVF counters. - - - In experiments with FORCE_OVF counters, and regular OVF_PMI - counters with small ireset values between -8 and -1, it appears - that the faulting instruction is subjected to a new PMI before - it can complete, ad infinitum. This occurs even though the driver - clears the CCCR (and in testing also the ESCR) and invokes a - user-space signal handler before restoring the CCCR and resuming - the instruction. -*/ - -#define NCOUNTERS 18 - -// The 18 counters -enum Counters -{ - MSR_BPU_COUNTER0, - MSR_BPU_COUNTER1, - MSR_BPU_COUNTER2, - MSR_BPU_COUNTER3, - MSR_MS_COUNTER0, - MSR_MS_COUNTER1, - MSR_MS_COUNTER2, - MSR_MS_COUNTER3, - MSR_FLAME_COUNTER0, - MSR_FLAME_COUNTER1, - MSR_FLAME_COUNTER2, - MSR_FLAME_COUNTER3, - MSR_IQ_COUNTER0, - MSR_IQ_COUNTER1, - MSR_IQ_COUNTER2, - MSR_IQ_COUNTER3, - MSR_IQ_COUNTER4, - MSR_IQ_COUNTER5 -}; - -// register base for counters -#define MSR_COUNTER_BASE 0x300 - -// register base for CCCR register -#define MSR_CCCR_BASE 0x360 - -#pragma pack(push, 1) -// access to these bits is through the methods -typedef union ESCR -{ - struct - { - uint64 Reserved0_1 : 2; // - uint64 USR : 1; // - uint64 OS : 1; // - uint64 TagEnable : 1; // - uint64 TagValue : 4; // - uint64 EventMask : 16; // from event select - uint64 ESCREventSelect : 6; // 31:25 class of event - uint64 Reserved31 : 1; // - - uint64 Reserved32_63 : 32; // - }; - uint64 flat; - -} ESCR; - -typedef union CCCR -{ - struct - { - uint64 Reserved0_11 : 12;// 0 -11 - uint64 Enable : 1; // 12 - uint64 CCCRSelect : 3; // 13-15 - uint64 Reserved16_17 : 2; // 16 17 - - uint64 Compare : 1; // 18 - uint64 Complement : 1; // 19 - uint64 Threshold : 4; // 20-23 - uint64 Edge : 1; // 24 - uint64 FORCE_OVF : 1; // 25 - uint64 OVF_PMI : 1; // 26 - uint64 Reserved27_29 : 3; // 27-29 - uint64 Cascade : 1; // 30 - uint64 OVF : 1; // 31 - - uint64 Reserved32_63 : 32; // - }; - uint64 flat; - -} CCCR; - -#pragma pack(pop) - -extern const unsigned short cccr_escr_map[NCOUNTERS][8]; - -enum P4TagState -{ - TagDisable, // - TagEnable, // -}; - -enum P4ForceOverflow -{ - ForceOverflowDisable, - ForceOverflowEnable, -}; - -enum P4OverflowInterrupt -{ - OverflowInterruptDisable, - OverflowInterruptEnable, -}; - -// Turn off the no return value warning in ReadCounter. -#pragma warning( disable : 4035 ) -class P4BaseEvent -{ - int m_counter; - -protected: - - void SetCounter(int counter) - { - m_counter = counter; - cccrPort = MSR_CCCR_BASE + m_counter; - counterPort = MSR_COUNTER_BASE + m_counter; - escrPort = cccr_escr_map[m_counter][cccr.CCCRSelect]; - } - -public: - - unsigned short m_eventMask; - const tchar *description; - PME *pme; - ESCR escr; - CCCR cccr; - int counterPort; - int cccrPort; - int escrPort; - - P4BaseEvent() - { - pme = PME::Instance(); - m_eventMask = 0; - description = _T(""); - escr.flat = 0; - cccr.flat = 0; - cccr.Reserved16_17 = 3; // must be set - escrPort = 0; - m_counter = -1; - } - - void StartCounter() - { - cccr.Enable = 1; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - void StopCounter() - { - cccr.Enable = 0; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - void ClearCounter() - { - pme->WriteMSR( counterPort, 0ui64 ); // clear - } - - void WriteCounter( int64 value ) - { - pme->WriteMSR( counterPort, value ); // clear - } - - int64 ReadCounter() - { -#if PME_DEBUG - if ( escr.USR == 0 && escr.OS == 0 ) - return -1; // no area to collect, use SetCaptureMode - - if ( escr.EventMask == 0 ) - return -2; // no event mask set - - if ( m_counter == -1 ) - return -3; // counter not legal -#endif - - // ReadMSR should work here too, but RDPMC should be faster - int64 value = 0; - pme->ReadMSR( counterPort, &value ); - return value; -#if 0 - // we need to copy this into a temp for some reason - int temp = m_counter; - _asm - { - mov ecx, temp - RDPMC - } -#endif - } - - void SetCaptureMode( PrivilegeCapture priv ) - { - switch ( priv ) - { - case OS_Only: - { - escr.USR = 0; - escr.OS = 1; - break; - } - case USR_Only: - { - escr.USR = 1; - escr.OS = 0; - break; - } - case OS_and_USR: - { - escr.USR = 1; - escr.OS = 1; - break; - } - } - - escr.EventMask = m_eventMask; - pme->WriteMSR( escrPort, escr.flat ); - } - - void SetTagging( P4TagState tagEnable, uint8 tagValue ) - { - escr.TagEnable = tagEnable; - escr.TagValue = tagValue; - pme->WriteMSR( escrPort, escr.flat ); - } - - void SetFiltering( CompareState compareEnable, CompareMethod compareMethod, uint8 threshold, EdgeState edgeEnable ) - { - cccr.Compare = compareEnable; - cccr.Complement = compareMethod; - cccr.Threshold = threshold; - cccr.Edge = edgeEnable; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - void SetOverflowEnables( P4ForceOverflow overflowEnable, P4OverflowInterrupt overflowInterruptEnable ) - { - cccr.FORCE_OVF = overflowEnable; - cccr.OVF_PMI = overflowInterruptEnable; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - void SetOverflow() - { - cccr.OVF = 1; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - void ClearOverflow() - { - cccr.OVF = 0; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - bool isOverflow() - { - CCCR cccr_temp; - pme->ReadMSR( cccrPort, &cccr_temp.flat ); - return cccr_temp.OVF; - } - - void SetCascade() - { - cccr.Cascade = 1; - pme->WriteMSR( cccrPort, cccr.flat ); - } - - void ClearCascade() - { - cccr.Cascade = 0; - pme->WriteMSR( cccrPort, cccr.flat ); - } -}; -#pragma warning( default : 4035 ) - -#include "EventMasks.h" -#include "EventModes.h" - -#endif // P4PERFORMANCECOUNTERS_H diff --git a/Resources/NetHook/tier0/P5P6PerformanceCounters.h b/Resources/NetHook/tier0/P5P6PerformanceCounters.h deleted file mode 100644 index 5a0a5e66..00000000 --- a/Resources/NetHook/tier0/P5P6PerformanceCounters.h +++ /dev/null @@ -1,225 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef P5P6PERFORMANCECOUNTERS_H -#define P5P6PERFORMANCECOUNTERS_H - -// defined for < Pentium 4 - -//--------------------------------------------------------------------------- -// Format of the performance event IDs within this header file in case you -// wish to add any additional events that may not be present here. -// -// BITS 0-8 Unit Mask, Unsed on P5 processors -// BIT 9 Set if event can be set on counter 0 -// BIT 10 Set if event can be set on counter 1 -// BITS 11-15 Unused Set to zero -// BITS 16-23 Event Select ID, Only bits 16-21 used on P5 Family -// BITS 24-27 Unused set to zero -// BITS 28-32 Process family that the event belong to, as returned by -// the CPUID instruction. -//--------------------------------------------------------------------------- - -//--------------------------------------------------------------------------- -// PENTIUM PERFORMANCE COUNTERS. -//--------------------------------------------------------------------------- -#define P5_DTCRD 0x50000300 //Data Cache Reads -#define P5_DWRIT 0x50010300 //Data Cache Writes -#define P5_DTTLB 0x50020300 //Data TLB Miss -#define P5_DTRMS 0x50030300 //Data Read Misses -#define P5_DWRMS 0x50040300 //Data Write Miss -#define P5_WHLCL 0x50050300 //Write (Hit) to M- or E-state line -#define P5_DCLWB 0x50060300 //Data Cache Lines Written Back -#define P5_DCSNP 0x50070300 //External Snoops -#define P5_DCSHT 0x50080300 //Data Cache Snoop Hits -#define P5_MAIBP 0x50090300 //Memory Access in Both Pipes -#define P5_BANKS 0x500A0300 //Bank Conflicts -#define P5_MISAL 0x500B0300 //Misaligned Data Memory Reference -#define P5_COCRD 0x500C0300 //Code Cache Reads -#define P5_COTLB 0x500D0300 //Code TLB Misses -#define P5_COCMS 0x500E0300 //Code Cache Misses -#define P5_ANYSG 0x500F0300 //Any Segment Register Loaded -#define P5_BRANC 0x50120300 //Branches -#define P5_BTBHT 0x50130300 //BTB Hits -#define P5_TBRAN 0x50140300 //Taken Branch or BTB hit -#define P5_PFLSH 0x50150300 //Pipeline flushes -#define P5_INSTR 0x50160300 //Instructions Executed -#define P5_INSTV 0x50170300 //Instructions Executed in the V-Pipe (Pairing) -#define P5_CLOCL 0x50180300 //Bus active -#define P5_PSDWR 0x50190300 //Full write buffers -#define P5_PSWDR 0x501A0300 //Waiting for Data Memory Read -#define P5_NCLSW 0x501B0300 //Clocks stalled writing an E or M state line -#define P5_IORWC 0x501D0300 //I/O Read or Write Cycle -#define P5_NOCMR 0x501E0300 //Non-Cacheable Memory Reads -#define P5_PSLDA 0x501F0300 //Clocks stalled due to AGI -#define P5_FLOPS 0x50220300 //Floating Point Operations -#define P5_DBGR0 0x50230300 //Breakpoint match on DR0 -#define P5_DBGR1 0x50240300 //Breakpoint match on DR1 -#define P5_DBGR2 0x50250300 //Breakpoint match on DR2 -#define P5_DBGR3 0x50260300 //Breakpoint match on DR3 -#define P5_HWINT 0x50270300 //Hardware interrupts -#define P5_DTRWR 0x50280300 //Data reads or writes -#define P5_DTRWM 0x50290300 //Data read or write miss -#define P5_BOLAT 0x502A0100 //Bus ownership latency -#define P5_BOTFR 0x502A0200 //Bus ownership transfer -#define P5_MMXA1 0x502B0100 //MMX Instruction Executed in U-pipe -#define P5_MMXA2 0x502B0200 //MMX Instruction Executed in V-pipe -#define P5_MMXMS 0x502C0100 //Cache M state line sharing -#define P5_MMSLS 0x502C0200 //Cache line sharing -#define P5_MMXB1 0x502D0100 //EMMS Instructions Executed -#define P5_MMXB2 0x502D0200 //Transition from MMX to FP instructions -#define P5_NOCMW 0x502E0200 //Non-Cacheable Memory Writes -#define P5_MMXC1 0x502F0100 //Saturated MMX Instructions Executed -#define P5_MMXC2 0x502F0200 //Saturations Performed -#define P5_MMXHS 0x50300100 //Cycles Not in HALT State -#define P5_MMXD2 0x50310100 //MMX Data Read -#define P5_MMXFP 0x50320100 //Floating Point Stalls -#define P5_MMXTB 0x50320200 //Taken Branches -#define P5_MMXD0 0x50330100 //D1 Starvation and FIFO Empty -#define P5_MMXD1 0x50330200 //D1 Starvation and one instruction in FIFO -#define P5_MMXE1 0x50340100 //MMX Data Writes -#define P5_MMXE2 0x50340200 //MMX Data Write Misses -#define P5_MMXWB 0x50350100 //Pipeline flushes, wrong branch prediction -#define P5_MMXWJ 0x50350200 //Pipeline flushes, branch prediction WB-stage -#define P5_MMXF1 0x50360100 //Misaligned MMX Data Memory Reference -#define P5_MMXF2 0x50360200 //Pipeline Stalled Waiting for MMX data read -#define P5_MMXRI 0x50370100 //Returns Predicted Incorrectly -#define P5_MMXRP 0x50370200 //Returns Predicted -#define P5_MMXG1 0x50380100 //MMX Multiply Unit Interlock -#define P5_MMXG2 0x50380200 //MOVD/MOVQ store stall, previous operation -#define P5_MMXRT 0x50390100 //Returns -#define P5_MMXRO 0x50390200 //RSB Overflows -#define P5_MMXBF 0x503A0100 //BTB False entries -#define P5_MMXBM 0x503A0200 //BTB misprediction on a Not-Taken Branch -#define P5_PXDWR 0x503B0100 //stalled due MMX Full write buffers -#define P5_PXZWR 0x503B0200 //stalled on MMX write to E or M state line - -#define P5_CLOCK 0x503F0300 //Special value to count clocks on P5 - - -//--------------------------------------------------------------------------- -// PENTIUM PRO / PENTIUM II PERFORMANCE COUNTERS. -//--------------------------------------------------------------------------- -#define P6_STRBB 0x60030300 //Store Buffer Block -#define P6_STBDC 0x60040300 //Store Buffer Drain Cycles -#define P6_MISMM 0x60050300 //Misaligned Data Memory Reference -#define P6_SEGLD 0x60060300 //Segment register loads -#define P6_FPOPE 0x60100100 //FP Computational Op. (COUNTER 0 ONLY) -#define P6_FPEOA 0x60110200 //FP Microcode Exceptions (COUNTER 1 ONLY) -#define P6_FMULT 0x60120200 //Multiplies (COUNTER 1 ONLY) -#define P6_FPDIV 0x60130200 //Divides (COUNTER 1 ONLY) -#define P6_DBUSY 0x60140200 //Cycles Divider Busy (COUNTER 1 ONLY) -#define P6_L2STR 0x60210300 //L2 address strobes => address bus utilization -#define P6_L2BBS 0x60220300 //Cycles L2 Bus Busy -#define P6_L2BBT 0x60230300 //Cycles L2 Bus Busy transferring data to CPU -#define P6_L2ALO 0x60240300 //L2 Lines Allocated -#define P6_L2MAL 0x60250300 //L2 M-state Lines Allocated -#define P6_L2CEV 0x60260300 //L2 Lines Evicted -#define P6_L2MEV 0x60270300 //L2 M-state Lines Evicted -#define P6_L2MCF 0x60280301 //L2 Cache Instruction Fetch Misses -#define P6_L2FET 0x6028030F //L2 Cache Instruction Fetches -#define P6_L2DRM 0x60290301 //L2 Cache Read Misses -#define P6_L2DMR 0x6029030F //L2 Cache Reads -#define P6_L2DWM 0x602A0301 //L2 Cache Write Misses -#define P6_L2DMW 0x602A030F //L2 Cache Writes -#define P6_L2CMS 0x602E0301 //L2 Cache Request Misses -#define P6_L2DCR 0x602E030F //L2 Cache Requests -#define P6_DMREF 0x60430300 //Data Memory References -#define P6_DCALO 0x6045030F //L1 Lines Allocated -#define P6_DCMAL 0x60460300 //L1 M-state Data Cache Lines Allocated -#define P6_DCMEV 0x60470300 //L1 M-state Data Cache Lines Evicted -#define P6_DCOUT 0x60480300 //L1 Misses outstanding -#define P6_TSMCD 0x60520300 //Time Self-Modifiying Code Detected -#define P6_BRWRA 0x60600300 //External Bus Cycles While Receive Active -#define P6_BRDCD 0x60600300 //External Bus Request Outstanding -#define P6_BRBNR 0x60610300 //External Bus Cycles While BNR Asserted -#define P6_BUSBS 0x60620300 //External Bus Cycles-DRDY Asserted (busy) -#define P6_BLOCK 0x60630300 //External Bus Cycles-LOCK signal asserted -#define P6_BBRCV 0x60640300 //External Bus Cycles-Processor receiving data -#define P6_BURST 0x60650300 //External Bus Burst Read Operations -#define P6_BRINV 0x60660300 //External Bus Read for Ownership Transaction -#define P6_BMLEV 0x60670300 //External Bus Writeback M-state Evicted -#define P6_BBIFT 0x60680300 //External Bus Burst Instruction Fetches -#define P6_BINVL 0x60690300 //External Bus Invalidate Transactions -#define P6_BPRBT 0x606A0300 //External Bus Partial Read Transactions -#define P6_BPTMO 0x606B0300 //External Bus Partial Memory Transactions -#define P6_BUSIO 0x606C0300 //External Bus I/O Bus Transactions -#define P6_BUSDF 0x606D0300 //External Bus Deferred Transactions -#define P6_BUSTB 0x606E0300 //External Bus Burst Transactions -#define P6_BMALL 0x606F0300 //External Bus Memory Transactions -#define P6_BSALL 0x60700300 //External Bus Transactions -#define P6_CLOCK 0x60790300 //Clockticks -#define P6_BRHIT 0x607A0300 //External Bus Cycles While HIT Asserted -#define P6_BRHTM 0x607B0300 //External Bus Cycles While HITM Asserted -#define P6_BRSST 0x607E0300 //External Bus Cycles While Snoop Stalled -#define P6_CMREF 0x60800300 //Total Instruction Fetches -#define P6_TOIFM 0x60810300 //Total Instruction Fetch Misses -#define P6_INTLB 0x60850300 //Instructions TLB Misses -#define P6_CSFET 0x60860300 //Cycles Instruction Fetch Stalled -#define P6_FTSTL 0x60870300 //Cycles Instruction Fetch stalled -#define P6_RSTAL 0x60A20300 //Resource Related Stalls -#define P6_MMXIE 0x60B00300 //MMX Instructions Executed -#define P6_SAISE 0x60B10300 //Saturated Arithmetic Instructions Executed -#define P6_PORT0 0x60B20301 //MMX micro-ops executed on Port 0 -#define P6_PORT1 0x60B20302 //MMX micro-ops executed on Port 1 -#define P6_PORT2 0x60B20304 //MMX micro-ops executed on Port 2 -#define P6_PORT3 0x60B20308 //MMX micro-ops executed on Port 3 -#define P6_MMXPA 0x60B30300 //MMX Packed Arithmetic -#define P6_MMXPM 0x60B30301 //MMX Packed Multiply -#define P6_MMXPS 0x60B30302 //MMX Packed Shift -#define P6_MMXPO 0x60B30304 //MMX Packed Operations -#define P6_MMXUO 0x60B30308 //MMX Unpacked Operations -#define P6_MMXPL 0x60B30310 //MMX Packed Logical -#define P6_INSTR 0x60C00300 //Instructions Retired -#define P6_FPOPS 0x60C10100 //FP operations retired (COUNTER 0 ONLY) -#define P6_UOPSR 0x60C20300 //Micro-Ops Retired -#define P6_BRRET 0x60C40300 //Branch Instructions Retired -#define P6_BRMSR 0x60C50300 //Branch Mispredictions Retired -#define P6_MASKD 0x60C60300 //Clocks while interrupts masked -#define P6_MSKPN 0x60C70300 //Clocks while interrupt is pending -#define P6_HWINT 0x60C80300 //Hardware Interrupts Received -#define P6_BTAKR 0x60C90300 //Taken Branch Retired -#define P6_BTAKM 0x60CA0300 //Taken Branch Mispredictions -#define P6_FPMMX 0x60CC0301 //Transitions from Floating Point to MMX -#define P6_MMXFP 0x60CC0300 //Transitions from MMX to Floating Point -#define P6_SIMDA 0x60CD0300 //SIMD Assists (EMMS Instructions Executed) -#define P6_MMXIR 0x60CE0300 //MMX Instructions Retired -#define P6_SAISR 0x60CF0300 //Saturated Arithmetic Instructions Retired -#define P6_INSTD 0x60D00300 //Instructions Decoded -#define P6_NPRTL 0x60D20300 //Renaming Stalls -#define P6_SRSES 0x60D40301 //Segment Rename Stalls - ES -#define P6_SRSDS 0x60D40302 //Segment Rename Stalls - DS -#define P6_SRSFS 0x60D40304 //Segment Rename Stalls - FS -#define P6_SRSGS 0x60D40308 //Segment Rename Stalls - GS -#define P6_SRSXS 0x60D4030F //Segment Rename Stalls - ES DS FS GS -#define P6_SRNES 0x60D50301 //Segment Renames - ES -#define P6_SRNDS 0x60D50302 //Segment Renames - DS -#define P6_SRNFS 0x60D50304 //Segment Renames - FS -#define P6_SRNGS 0x60D50308 //Segment Renames - GS -#define P6_SRNXS 0x60D5030F //Segment Renames - ES DS FS GS -#define P6_BRDEC 0x60E00300 //Branch Instructions Decoded -#define P6_BTBMS 0x60E20301 //BTB Misses -#define P6_RETDC 0x60E40300 //Bogus Branches -#define P6_BACLR 0x60E60300 //BACLEARS Asserted (Testing) - - - - - - -// INTEL -#define PENTIUM_FAMILY 5 // define for pentium -#define PENTIUMPRO_FAMILY 6 // define for pentium pro -#define PENTIUM4_FAMILY 15 // define for pentium 4 - - -// AMD -#define K6_FAMILY 5 -#define K8_FAMILY 6 -#define EXTENDED_FAMILY 15 // AMD 64 and AMD Opteron - -#endif // P5P6PERFORMANCECOUNTERS_H diff --git a/Resources/NetHook/tier0/PMELib.h b/Resources/NetHook/tier0/PMELib.h deleted file mode 100644 index d989a5f8..00000000 --- a/Resources/NetHook/tier0/PMELib.h +++ /dev/null @@ -1,195 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef PMELIB_H -#define PMELIB_H - -#include "Windows.h" -#include "tier0/platform.h" - -// Get rid of a bunch of STL warnings! -#pragma warning( push, 3 ) -#pragma warning( disable : 4018 ) - -#define VERSION "1.0.2" - -// uncomment this list to add some runtime checks -//#define PME_DEBUG - -#include "tier0/valve_off.h" -#include -#include "tier0/valve_on.h" - -using namespace std; - -// RDTSC Instruction macro -#define RDTSC(var) \ -_asm RDTSC \ -_asm mov DWORD PTR var,eax \ -_asm mov DWORD PTR var+4,edx - -// RDPMC Instruction macro -#define RDPMC(counter, var) \ -_asm mov ecx, counter \ -_asm RDPMC \ -_asm mov DWORD PTR var,eax \ -_asm mov DWORD PTR var+4,edx - -// RDPMC Instruction macro, for performance counter 1 (ecx = 1) -#define RDPMC0(var) \ -_asm mov ecx, 0 \ -_asm RDPMC \ -_asm mov DWORD PTR var,eax \ -_asm mov DWORD PTR var+4,edx - -#define RDPMC1(var) \ -_asm mov ecx, 1 \ -_asm RDPMC \ -_asm mov DWORD PTR var,eax \ -_asm mov DWORD PTR var+4,edx - -#define EVENT_TYPE(mode) EventType##mode -#define EVENT_MASK(mode) EventMask##mode - -#include "ia32detect.h" - -enum ProcessPriority -{ - ProcessPriorityNormal, - ProcessPriorityHigh, -}; - -enum PrivilegeCapture -{ - OS_Only, // ring 0, kernel level - USR_Only, // app level - OS_and_USR, // all levels -}; - -enum CompareMethod -{ - CompareGreater, // - CompareLessEqual, // -}; - -enum EdgeState -{ - RisingEdgeDisabled, // - RisingEdgeEnabled, // -}; - -enum CompareState -{ - CompareDisable, // - CompareEnable, // -}; - -// Singletion Class -class PME : public ia32detect -{ -public: -//private: - - static PME* _singleton; - - HANDLE hFile; - bool bDriverOpen; - double m_CPUClockSpeed; - - //ia32detect detect; - HRESULT Init(); - HRESULT Close(); - -protected: - - PME() - { - hFile = NULL; - bDriverOpen = FALSE; - m_CPUClockSpeed = 0; - Init(); - } - -public: - - static PME* Instance(); // gives back a real object - - ~PME() - { - Close(); - } - - double GetCPUClockSpeedSlow( void ); - double GetCPUClockSpeedFast( void ); - - HRESULT SelectP5P6PerformanceEvent( uint32 dw_event, uint32 dw_counter, bool b_user, bool b_kernel ); - - HRESULT ReadMSR( uint32 dw_reg, int64 * pi64_value ); - HRESULT ReadMSR( uint32 dw_reg, uint64 * pi64_value ); - - HRESULT WriteMSR( uint32 dw_reg, const int64 & i64_value ); - HRESULT WriteMSR( uint32 dw_reg, const uint64 & i64_value ); - - void SetProcessPriority( ProcessPriority priority ) - { - switch( priority ) - { - case ProcessPriorityNormal: - { - SetPriorityClass (GetCurrentProcess(),NORMAL_PRIORITY_CLASS); - SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_NORMAL); - break; - } - case ProcessPriorityHigh: - { - SetPriorityClass (GetCurrentProcess(),REALTIME_PRIORITY_CLASS); - SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_HIGHEST); - break; - } - } - } - - //--------------------------------------------------------------------------- - // Return the family of the processor - //--------------------------------------------------------------------------- - CPUVendor GetVendor(void) - { - return vendor; - } - - int GetProcessorFamily(void) - { - return version.Family; - } - -#ifdef DBGFLAG_VALIDATE - void Validate( CValidator &validator, tchar *pchName ); // Validate our internal structures -#endif // DBGFLAG_VALIDATE - -}; - -#include "P5P6PerformanceCounters.h" -#include "P4PerformanceCounters.h" -#include "K8PerformanceCounters.h" - -enum PerfErrors -{ - E_UNKNOWN_CPU_VENDOR = -1, - E_BAD_COUNTER = -2, - E_UNKNOWN_CPU = -3, - E_CANT_OPEN_DRIVER = -4, - E_DRIVER_ALREADY_OPEN = -5, - E_DRIVER_NOT_OPEN = -6, - E_DISABLED = -7, - E_BAD_DATA = -8, - E_CANT_CLOSE = -9, - E_ILLEGAL_OPERATION = -10, -}; - -#pragma warning( pop ) - -#endif // PMELIB_H \ No newline at end of file diff --git a/Resources/NetHook/tier0/afxmem_override.cpp b/Resources/NetHook/tier0/afxmem_override.cpp deleted file mode 100644 index c1abbd23..00000000 --- a/Resources/NetHook/tier0/afxmem_override.cpp +++ /dev/null @@ -1,460 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -// File extracted from MFC due to symbol conflicts - -// This is a part of the Microsoft Foundation Classes C++ library. -// Copyright (C) Microsoft Corporation -// All rights reserved. -// -// This source code is only intended as a supplement to the -// Microsoft Foundation Classes Reference and related -// electronic documentation provided with the library. -// See these sources for detailed information regarding the -// Microsoft Foundation Classes product. - -#include "stdafx.h" - -#ifdef AFX_CORE1_SEG -#pragma code_seg(AFX_CORE1_SEG) -#endif - - -///////////////////////////////////////////////////////////////////////////// -// Debug memory globals and implementation helpers - -#ifdef _DEBUG // most of this file is for debugging - -void* __cdecl operator new(size_t nSize, int nType, LPCSTR lpszFileName, int nLine); -#if _MSC_VER >= 1210 -void* __cdecl operator new[](size_t nSize, int nType, LPCSTR lpszFileName, int nLine); -#endif - -///////////////////////////////////////////////////////////////////////////// -// test allocation routines - -void* PASCAL CObject::operator new(size_t nSize) -{ -#ifdef _AFX_NO_DEBUG_CRT - return ::operator new(nSize); -#else - return ::operator new(nSize, _AFX_CLIENT_BLOCK, NULL, 0); -#endif // _AFX_NO_DEBUG_CRT -} - -void PASCAL CObject::operator delete(void* p) -{ -#ifdef _AFX_NO_DEBUG_CRT - free(p); -#else - _free_dbg(p, _AFX_CLIENT_BLOCK); -#endif -} - -#if _MSC_VER >= 1200 -void PASCAL CObject::operator delete(void* p, void*) -{ -#ifdef _AFX_NO_DEBUG_CRT - free(p); -#else - _free_dbg(p, _AFX_CLIENT_BLOCK); -#endif -} -#endif - -#ifndef _AFX_NO_DEBUG_CRT - -void* __cdecl operator new(size_t nSize, LPCSTR lpszFileName, int nLine) -{ - return ::operator new(nSize, _NORMAL_BLOCK, lpszFileName, nLine); -} - -#if _MSC_VER >= 1210 -void* __cdecl operator new[](size_t nSize, LPCSTR lpszFileName, int nLine) -{ - return ::operator new[](nSize, _NORMAL_BLOCK, lpszFileName, nLine); -} -#endif - -#if _MSC_VER >= 1200 -void __cdecl operator delete(void* pData, LPCSTR /* lpszFileName */, - int /* nLine */) -{ - ::operator delete(pData); -} -#endif - -#if _MSC_VER >= 1210 -void __cdecl operator delete[](void* pData, LPCSTR /* lpszFileName */, - int /* nLine */) -{ - ::operator delete(pData); -} -#endif - -void* PASCAL -CObject::operator new(size_t nSize, LPCSTR lpszFileName, int nLine) -{ - return ::operator new(nSize, _AFX_CLIENT_BLOCK, lpszFileName, nLine); -} - -#if _MSC_VER >= 1200 -void PASCAL -CObject::operator delete(void *pObject, LPCSTR /* lpszFileName */, - int /* nLine */) -{ -#ifdef _AFX_NO_DEBUG_CRT - free(pObject); -#else - _free_dbg(pObject, _AFX_CLIENT_BLOCK); -#endif -} -#endif - -void* AFXAPI AfxAllocMemoryDebug(size_t nSize, BOOL bIsObject, LPCSTR lpszFileName, int nLine) -{ - return _malloc_dbg(nSize, bIsObject ? _AFX_CLIENT_BLOCK : _NORMAL_BLOCK, - lpszFileName, nLine); -} - -void AFXAPI AfxFreeMemoryDebug(void* pbData, BOOL bIsObject) -{ - _free_dbg(pbData, bIsObject ? _AFX_CLIENT_BLOCK : _NORMAL_BLOCK); -} - -///////////////////////////////////////////////////////////////////////////// -// allocation failure hook, tracking turn on - -BOOL AFXAPI _AfxDefaultAllocHook(size_t, BOOL, LONG) - { return TRUE; } - -AFX_STATIC_DATA AFX_ALLOC_HOOK pfnAllocHook = _AfxDefaultAllocHook; - -AFX_STATIC_DATA _CRT_ALLOC_HOOK pfnCrtAllocHook = NULL; -#if _MSC_VER >= 1200 -int __cdecl _AfxAllocHookProxy(int nAllocType, void * pvData, size_t nSize, - int nBlockUse, long lRequest, const unsigned char * szFilename, int nLine) -#else -int __cdecl _AfxAllocHookProxy(int nAllocType, void * pvData, size_t nSize, - int nBlockUse, long lRequest, const char * szFilename, int nLine) -#endif -{ -#if _MSC_VER >= 1200 - if (nAllocType != _HOOK_ALLOC) - return (pfnCrtAllocHook)(nAllocType, pvData, nSize, - nBlockUse, lRequest, (const unsigned char*) szFilename, nLine); - if ((pfnAllocHook)(nSize, _BLOCK_TYPE(nBlockUse) == _AFX_CLIENT_BLOCK, lRequest)) - return (pfnCrtAllocHook)(nAllocType, pvData, nSize, - nBlockUse, lRequest, (const unsigned char*) szFilename, nLine); -#else - if (nAllocType != _HOOK_ALLOC) - return (pfnCrtAllocHook)(nAllocType, pvData, nSize, - nBlockUse, lRequest, szFilename, nLine); - if ((pfnAllocHook)(nSize, _BLOCK_TYPE(nBlockUse) == _AFX_CLIENT_BLOCK, lRequest)) - return (pfnCrtAllocHook)(nAllocType, pvData, nSize, - nBlockUse, lRequest, szFilename, nLine); -#endif - return FALSE; -} - -AFX_ALLOC_HOOK AFXAPI AfxSetAllocHook(AFX_ALLOC_HOOK pfnNewHook) -{ - if (pfnCrtAllocHook == NULL) - pfnCrtAllocHook = _CrtSetAllocHook(_AfxAllocHookProxy); - - AFX_ALLOC_HOOK pfnOldHook = pfnAllocHook; - pfnAllocHook = pfnNewHook; - return pfnOldHook; -} - -// This can be set to TRUE to override all AfxEnableMemoryTracking calls, -// allowing all allocations, even MFC internal allocations to be tracked. -BOOL _afxMemoryLeakOverride = FALSE; - -BOOL AFXAPI AfxEnableMemoryTracking(BOOL bTrack) -{ - if (_afxMemoryLeakOverride) - return TRUE; - - int nOldState = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); - if (bTrack) - _CrtSetDbgFlag(nOldState | _CRTDBG_ALLOC_MEM_DF); - else - _CrtSetDbgFlag(nOldState & ~_CRTDBG_ALLOC_MEM_DF); - return nOldState & _CRTDBG_ALLOC_MEM_DF; -} - -///////////////////////////////////////////////////////////////////////////// -// stop on a specific memory request - -// Obsolete API -void AFXAPI AfxSetAllocStop(LONG lRequestNumber) -{ - _CrtSetBreakAlloc(lRequestNumber); -} - -BOOL AFXAPI AfxCheckMemory() - // check all of memory (look for memory tromps) -{ - return _CrtCheckMemory(); -} - -// -- true if block of exact size, allocated on the heap -// -- set *plRequestNumber to request number (or 0) -BOOL AFXAPI AfxIsMemoryBlock(const void* pData, UINT nBytes, - LONG* plRequestNumber) -{ - return _CrtIsMemoryBlock(pData, nBytes, plRequestNumber, NULL, NULL); -} - -///////////////////////////////////////////////////////////////////////////// -// CMemoryState - -CMemoryState::CMemoryState() -{ - memset(this, 0, sizeof(*this)); -} - -void CMemoryState::UpdateData() -{ - for(int i = 0; i < nBlockUseMax; i++) - { - m_lCounts[i] = m_memState.lCounts[i]; - m_lSizes[i] = m_memState.lSizes[i]; - } - m_lHighWaterCount = m_memState.lHighWaterCount; - m_lTotalCount = m_memState.lTotalCount; -} - -// fills 'this' with the difference, returns TRUE if significant -BOOL CMemoryState::Difference(const CMemoryState& oldState, - const CMemoryState& newState) -{ - int nResult = _CrtMemDifference(&m_memState, &oldState.m_memState, &newState.m_memState); - UpdateData(); - return nResult != 0; -} - -void CMemoryState::DumpStatistics() const -{ - _CrtMemDumpStatistics(&m_memState); -} - -// -- fill with current memory state -void CMemoryState::Checkpoint() -{ - _CrtMemCheckpoint(&m_memState); - UpdateData(); -} - -// Dump objects created after this memory state was checkpointed -// Will dump all objects if this memory state wasn't checkpointed -// Dump all objects, report about non-objects also -// List request number in {} -void CMemoryState::DumpAllObjectsSince() const -{ - _CrtMemDumpAllObjectsSince(&m_memState); -} - -///////////////////////////////////////////////////////////////////////////// -// Enumerate all objects allocated in the diagnostic memory heap - -struct _AFX_ENUM_CONTEXT -{ - void (*m_pfn)(CObject*,void*); - void* m_pContext; -}; - -AFX_STATIC void _AfxDoForAllObjectsProxy(void* pObject, void* pContext) -{ - _AFX_ENUM_CONTEXT* p = (_AFX_ENUM_CONTEXT*)pContext; - (*p->m_pfn)((CObject*)pObject, p->m_pContext); -} - -void AFXAPI -AfxDoForAllObjects(void (AFX_CDECL *pfn)(CObject*, void*), void* pContext) -{ - if (pfn == NULL) - { - AfxThrowInvalidArgException(); - } - _AFX_ENUM_CONTEXT context; - context.m_pfn = pfn; - context.m_pContext = pContext; - _CrtDoForAllClientObjects(_AfxDoForAllObjectsProxy, &context); -} - -///////////////////////////////////////////////////////////////////////////// -// Automatic debug memory diagnostics - -BOOL AFXAPI AfxDumpMemoryLeaks() -{ - return _CrtDumpMemoryLeaks(); -} - -#endif // _AFX_NO_DEBUG_CRT -#endif // _DEBUG - -///////////////////////////////////////////////////////////////////////////// -// Non-diagnostic memory routines - -int AFX_CDECL AfxNewHandler(size_t /* nSize */) -{ - AfxThrowMemoryException(); -} - -#pragma warning(disable: 4273) - -#ifndef _AFXDLL -_PNH _afxNewHandler = &AfxNewHandler; -#endif - -_PNH AFXAPI AfxGetNewHandler(void) -{ -#ifdef _AFXDLL - AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState(); - return pState->m_pfnNewHandler; -#else - return _afxNewHandler; -#endif -} - -_PNH AFXAPI AfxSetNewHandler(_PNH pfnNewHandler) -{ -#ifdef _AFXDLL - AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState(); - _PNH pfnOldHandler = pState->m_pfnNewHandler; - pState->m_pfnNewHandler = pfnNewHandler; - return pfnOldHandler; -#else - _PNH pfnOldHandler = _afxNewHandler; - _afxNewHandler = pfnNewHandler; - return pfnOldHandler; -#endif -} - -AFX_STATIC_DATA const _PNH _pfnUninitialized = (_PNH)-1; - -void* __cdecl operator new(size_t nSize) -{ - void* pResult; -#ifdef _AFXDLL - _PNH pfnNewHandler = _pfnUninitialized; -#endif - for (;;) - { -#if !defined(_AFX_NO_DEBUG_CRT) && defined(_DEBUG) - pResult = _malloc_dbg(nSize, _NORMAL_BLOCK, NULL, 0); -#else - pResult = malloc(nSize); -#endif - if (pResult != NULL) - return pResult; - -#ifdef _AFXDLL - if (pfnNewHandler == _pfnUninitialized) - { - AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState(); - pfnNewHandler = pState->m_pfnNewHandler; - } - if (pfnNewHandler == NULL || (*pfnNewHandler)(nSize) == 0) - break; -#else - if (_afxNewHandler == NULL || (*_afxNewHandler)(nSize) == 0) - break; -#endif - } - return pResult; -} - -void __cdecl operator delete(void* p) -{ -#if !defined(_AFX_NO_DEBUG_CRT) && defined(_DEBUG) - _free_dbg(p, _NORMAL_BLOCK); -#else - free(p); -#endif -} - -#if _MSC_VER >= 1210 -void* __cdecl operator new[](size_t nSize) -{ - return ::operator new(nSize); -} - -void __cdecl operator delete[](void* p) -{ - ::operator delete(p); -} -#endif - -#ifdef _DEBUG - -void* __cdecl operator new(size_t nSize, int nType, LPCSTR lpszFileName, int nLine) -{ -#ifdef _AFX_NO_DEBUG_CRT - UNUSED_ALWAYS(nType); - UNUSED_ALWAYS(lpszFileName); - UNUSED_ALWAYS(nLine); - return ::operator new(nSize); -#else - void* pResult; -#ifdef _AFXDLL - _PNH pfnNewHandler = _pfnUninitialized; -#endif - for (;;) - { - pResult = _malloc_dbg(nSize, nType, lpszFileName, nLine); - if (pResult != NULL) - return pResult; - -#ifdef _AFXDLL - if (pfnNewHandler == _pfnUninitialized) - { - AFX_MODULE_THREAD_STATE* pState = AfxGetModuleThreadState(); - pfnNewHandler = pState->m_pfnNewHandler; - } - if (pfnNewHandler == NULL || (*pfnNewHandler)(nSize) == 0) - break; -#else - if (_afxNewHandler == NULL || (*_afxNewHandler)(nSize) == 0) - break; -#endif - } - return pResult; -#endif -} - -#if 0 -#if _MSC_VER >= 1200 -void __cdecl operator delete(void* p, int nType, LPCSTR /* lpszFileName */, int /* nLine */) -{ -#if !defined(_AFX_NO_DEBUG_CRT) && defined(_DEBUG) - _free_dbg(p, nType); -#else - free(p); -#endif -} -#endif // _MSC_VER >= 1200 -#endif - -#if _MSC_VER >= 1210 -void* __cdecl operator new[](size_t nSize, int nType, LPCSTR lpszFileName, int nLine) -{ - return ::operator new(nSize, nType, lpszFileName, nLine); -} -#if 0 -void __cdecl operator delete[](void* p, int nType, LPCSTR lpszFileName, int nLine) -{ - ::operator delete(p, nType, lpszFileName, nLine); -} -#endif -#endif // _MSC_VER >= 1210 - -#endif //_DEBUG - -///////////////////////////////////////////////////////////////////////////// diff --git a/Resources/NetHook/tier0/basetypes.h b/Resources/NetHook/tier0/basetypes.h deleted file mode 100644 index 541b69d7..00000000 --- a/Resources/NetHook/tier0/basetypes.h +++ /dev/null @@ -1,372 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef BASETYPES_H -#define BASETYPES_H - -#include "commonmacros.h" -#include "wchartypes.h" - -#include "tier0/valve_off.h" - -#ifdef _WIN32 -#pragma once -#endif - - -#include "protected_things.h" - -// There's a different version of this file in the xbox codeline -// so the PC version built in the xbox branch includes things like -// tickrate changes. -#include "xbox_codeline_defines.h" - -#ifdef IN_XBOX_CODELINE -#define XBOX_CODELINE_ONLY() -#else -#define XBOX_CODELINE_ONLY() Error_Compiling_Code_Only_Valid_in_Xbox_Codeline -#endif - -// stdio.h -#ifndef NULL -#define NULL 0 -#endif - - -#ifdef _LINUX -typedef unsigned int uintptr_t; -#endif - -#define ExecuteNTimes( nTimes, x ) \ - { \ - static int __executeCount=0;\ - if ( __executeCount < nTimes )\ - { \ - x; \ - ++__executeCount; \ - } \ - } - - -#define ExecuteOnce( x ) ExecuteNTimes( 1, x ) - - -template -inline T AlignValue( T val, unsigned alignment ) -{ - return (T)( ( (uintptr_t)val + alignment - 1 ) & ~( alignment - 1 ) ); -} - - -// Pad a number so it lies on an N byte boundary. -// So PAD_NUMBER(0,4) is 0 and PAD_NUMBER(1,4) is 4 -#define PAD_NUMBER(number, boundary) \ - ( ((number) + ((boundary)-1)) / (boundary) ) * (boundary) - -// In case this ever changes -#define M_PI 3.14159265358979323846 - -#include "valve_minmax_on.h" - -#if !defined(_X360) -#define fpmin min -#define fpmax max -#endif - -#ifdef __cplusplus - template< class T > - inline T clamp( T const &val, T const &minVal, T const &maxVal ) - { - if( val < minVal ) - return minVal; - else if( val > maxVal ) - return maxVal; - else - return val; - } -#endif - -#ifndef FALSE -#define FALSE 0 -#define TRUE (!FALSE) -#endif - - -typedef int BOOL; -typedef int qboolean; -typedef unsigned long ULONG; -typedef unsigned char BYTE; -typedef unsigned char byte; -typedef unsigned short word; - -typedef unsigned int uintptr_t; - - -enum ThreeState_t -{ - TRS_FALSE, - TRS_TRUE, - TRS_NONE, -}; - -typedef float vec_t; - - -// FIXME: this should move -#ifndef __cplusplus -#define true TRUE -#define false FALSE -#endif - -//----------------------------------------------------------------------------- -// look for NANs, infinities, and underflows. -// This assumes the ANSI/IEEE 754-1985 standard -//----------------------------------------------------------------------------- - -#ifdef __cplusplus - -inline unsigned long& FloatBits( vec_t& f ) -{ - return *reinterpret_cast(&f); -} - -inline unsigned long const& FloatBits( vec_t const& f ) -{ - return *reinterpret_cast(&f); -} - -inline vec_t BitsToFloat( unsigned long i ) -{ - return *reinterpret_cast(&i); -} - -inline bool IsFinite( vec_t f ) -{ - return ((FloatBits(f) & 0x7F800000) != 0x7F800000); -} - -inline unsigned long FloatAbsBits( vec_t f ) -{ - return FloatBits(f) & 0x7FFFFFFF; -} - -inline float FloatMakeNegative( vec_t f ) -{ - return BitsToFloat( FloatBits(f) | 0x80000000 ); -} - -#if defined( WIN32 ) - -//#include -// Just use prototype from math.h -#ifdef __cplusplus -extern "C" -{ -#endif - double __cdecl fabs(double); -#ifdef __cplusplus -} -#endif - -// In win32 try to use the intrinsic fabs so the optimizer can do it's thing inline in the code -#pragma intrinsic( fabs ) -// Also, alias float make positive to use fabs, too -// NOTE: Is there a perf issue with double<->float conversion? -inline float FloatMakePositive( vec_t f ) -{ - return (float)fabs( f ); -} -#else -inline float FloatMakePositive( vec_t f ) -{ - return BitsToFloat( FloatBits(f) & 0x7FFFFFFF ); -} -#endif - -inline float FloatNegate( vec_t f ) -{ - return BitsToFloat( FloatBits(f) ^ 0x80000000 ); -} - - -#define FLOAT32_NAN_BITS (unsigned long)0x7FC00000 // not a number! -#define FLOAT32_NAN BitsToFloat( FLOAT32_NAN_BITS ) - -#define VEC_T_NAN FLOAT32_NAN - -#endif - -// FIXME: why are these here? Hardly anyone actually needs them. -struct color24 -{ - byte r, g, b; -}; - -typedef struct color32_s -{ - bool operator!=( const struct color32_s &other ) const; - - byte r, g, b, a; -} color32; - -inline bool color32::operator!=( const color32 &other ) const -{ - return r != other.r || g != other.g || b != other.b || a != other.a; -} - -struct colorVec -{ - unsigned r, g, b, a; -}; - - -#ifndef NOTE_UNUSED -#define NOTE_UNUSED(x) (x = x) // for pesky compiler / lint warnings -#endif -#ifdef __cplusplus - -struct vrect_t -{ - int x,y,width,height; - vrect_t *pnext; -}; - -#endif - - -//----------------------------------------------------------------------------- -// MaterialRect_t struct - used for DrawDebugText -//----------------------------------------------------------------------------- -struct Rect_t -{ - int x, y; - int width, height; -}; - - -//----------------------------------------------------------------------------- -// Interval, used by soundemittersystem + the game -//----------------------------------------------------------------------------- -struct interval_t -{ - float start; - float range; -}; - - -//----------------------------------------------------------------------------- -// Declares a type-safe handle type; you can't assign one handle to the next -//----------------------------------------------------------------------------- - -// 32-bit pointer handles. - -// Typesafe 8-bit and 16-bit handles. -template< class HandleType > -class CBaseIntHandle -{ -public: - - inline bool operator==( const CBaseIntHandle &other ) { return m_Handle == other.m_Handle; } - inline bool operator!=( const CBaseIntHandle &other ) { return m_Handle != other.m_Handle; } - - // Only the code that doles out these handles should use these functions. - // Everyone else should treat them as a transparent type. - inline HandleType GetHandleValue() { return m_Handle; } - inline void SetHandleValue( HandleType val ) { m_Handle = val; } - - typedef HandleType HANDLE_TYPE; - -protected: - - HandleType m_Handle; -}; - -template< class DummyType > -class CIntHandle16 : public CBaseIntHandle< unsigned short > -{ -public: - inline CIntHandle16() {} - - static inline CIntHandle16 MakeHandle( HANDLE_TYPE val ) - { - return CIntHandle16( val ); - } - -protected: - inline CIntHandle16( HANDLE_TYPE val ) - { - m_Handle = val; - } -}; - - -template< class DummyType > -class CIntHandle32 : public CBaseIntHandle< unsigned long > -{ -public: - inline CIntHandle32() {} - - static inline CIntHandle32 MakeHandle( HANDLE_TYPE val ) - { - return CIntHandle32( val ); - } - -protected: - inline CIntHandle32( HANDLE_TYPE val ) - { - m_Handle = val; - } -}; - - -// NOTE: This macro is the same as windows uses; so don't change the guts of it -#define DECLARE_HANDLE_16BIT(name) typedef CIntHandle16< struct name##__handle * > name; -#define DECLARE_HANDLE_32BIT(name) typedef CIntHandle32< struct name##__handle * > name; - -#define DECLARE_POINTER_HANDLE(name) struct name##__ { int unused; }; typedef struct name##__ *name -#define FORWARD_DECLARE_HANDLE(name) typedef struct name##__ *name - -// @TODO: Find a better home for this -#if !defined(_STATIC_LINKED) && !defined(PUBLISH_DLL_SUBSYSTEM) -// for platforms built with dynamic linking, the dll interface does not need spoofing -#define PUBLISH_DLL_SUBSYSTEM() -#endif - -#define UID_PREFIX generated_id_ -#define UID_CAT1(a,c) a ## c -#define UID_CAT2(a,c) UID_CAT1(a,c) -#define EXPAND_CONCAT(a,c) UID_CAT1(a,c) -#ifdef _MSC_VER -#define UNIQUE_ID UID_CAT2(UID_PREFIX,__COUNTER__) -#else -#define UNIQUE_ID UID_CAT2(UID_PREFIX,__LINE__) -#endif - -// this allows enumerations to be used as flags, and still remain type-safe! -#define DEFINE_ENUM_BITWISE_OPERATORS( Type ) \ - inline Type operator| ( Type a, Type b ) { return Type( int( a ) | int( b ) ); } \ - inline Type operator& ( Type a, Type b ) { return Type( int( a ) & int( b ) ); } \ - inline Type operator^ ( Type a, Type b ) { return Type( int( a ) ^ int( b ) ); } \ - inline Type operator<< ( Type a, int b ) { return Type( int( a ) << b ); } \ - inline Type operator>> ( Type a, int b ) { return Type( int( a ) >> b ); } \ - inline Type &operator|= ( Type &a, Type b ) { return a = a | b; } \ - inline Type &operator&= ( Type &a, Type b ) { return a = a & b; } \ - inline Type &operator^= ( Type &a, Type b ) { return a = a ^ b; } \ - inline Type &operator<<=( Type &a, int b ) { return a = a << b; } \ - inline Type &operator>>=( Type &a, int b ) { return a = a >> b; } \ - inline Type operator~( Type a ) { return Type( ~int( a ) ); } - -// defines increment/decrement operators for enums for easy iteration -#define DEFINE_ENUM_INCREMENT_OPERATORS( Type ) \ - inline Type &operator++( Type &a ) { return a = Type( int( a ) + 1 ); } \ - inline Type &operator--( Type &a ) { return a = Type( int( a ) - 1 ); } \ - inline Type operator++( Type &a, int ) { Type t = a; ++a; return t; } \ - inline Type operator--( Type &a, int ) { Type t = a; --a; return t; } - -#include "tier0/valve_on.h" - -#endif // BASETYPES_H diff --git a/Resources/NetHook/tier0/commonmacros.h b/Resources/NetHook/tier0/commonmacros.h deleted file mode 100644 index e8813f8f..00000000 --- a/Resources/NetHook/tier0/commonmacros.h +++ /dev/null @@ -1,144 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef COMMONMACROS_H -#define COMMONMACROS_H - -#ifdef _WIN32 -#pragma once -#endif - -// ------------------------------------------------------- -// -// commonmacros.h -// -// This should contain ONLY general purpose macros that are -// appropriate for use in engine/launcher/all tools -// -// ------------------------------------------------------- - -// Makes a 4-byte "packed ID" int out of 4 characters -#define MAKEID(d,c,b,a) ( ((int)(a) << 24) | ((int)(b) << 16) | ((int)(c) << 8) | ((int)(d)) ) - -// Compares a string with a 4-byte packed ID constant -#define STRING_MATCHES_ID( p, id ) ( (*((int *)(p)) == (id) ) ? true : false ) -#define ID_TO_STRING( id, p ) ( (p)[3] = (((id)>>24) & 0xFF), (p)[2] = (((id)>>16) & 0xFF), (p)[1] = (((id)>>8) & 0xFF), (p)[0] = (((id)>>0) & 0xFF) ) - -#define Q_ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) - -#define SETBITS(iBitVector, bits) ((iBitVector) |= (bits)) -#define CLEARBITS(iBitVector, bits) ((iBitVector) &= ~(bits)) -#define FBitSet(iBitVector, bit) ((iBitVector) & (bit)) - -inline bool IsPowerOfTwo( int value ) -{ - return (value & ( value - 1 )) == 0; -} - -#define CONST_INTEGER_AS_STRING(x) #x //Wraps the integer in quotes, allowing us to form constant strings with it -#define __HACK_LINE_AS_STRING__(x) CONST_INTEGER_AS_STRING(x) //__LINE__ can only be converted to an actual number by going through this, otherwise the output is literally "__LINE__" -#define __LINE__AS_STRING __HACK_LINE_AS_STRING__(__LINE__) //Gives you the line number in constant string form - -// Using ARRAYSIZE implementation from winnt.h: -#ifdef ARRAYSIZE -#undef ARRAYSIZE -#endif - -// Return the number of elements in a statically sized array. -// DWORD Buffer[100]; -// RTL_NUMBER_OF(Buffer) == 100 -// This is also popularly known as: NUMBER_OF, ARRSIZE, _countof, NELEM, etc. -// -#define RTL_NUMBER_OF_V1(A) (sizeof(A)/sizeof((A)[0])) - -#if defined(__cplusplus) && \ - !defined(MIDL_PASS) && \ - !defined(RC_INVOKED) && \ - !defined(_PREFAST_) && \ - (_MSC_FULL_VER >= 13009466) && \ - !defined(SORTPP_PASS) - -// From crtdefs.h -#if !defined(UNALIGNED) -#if defined(_M_IA64) || defined(_M_AMD64) -#define UNALIGNED __unaligned -#else -#define UNALIGNED -#endif -#endif - -// RtlpNumberOf is a function that takes a reference to an array of N Ts. -// -// typedef T array_of_T[N]; -// typedef array_of_T &reference_to_array_of_T; -// -// RtlpNumberOf returns a pointer to an array of N chars. -// We could return a reference instead of a pointer but older compilers do not accept that. -// -// typedef char array_of_char[N]; -// typedef array_of_char *pointer_to_array_of_char; -// -// sizeof(array_of_char) == N -// sizeof(*pointer_to_array_of_char) == N -// -// pointer_to_array_of_char RtlpNumberOf(reference_to_array_of_T); -// -// We never even call RtlpNumberOf, we just take the size of dereferencing its return type. -// We do not even implement RtlpNumberOf, we just decare it. -// -// Attempts to pass pointers instead of arrays to this macro result in compile time errors. -// That is the point. -extern "C++" // templates cannot be declared to have 'C' linkage -template -char (*RtlpNumberOf( UNALIGNED T (&)[N] ))[N]; - -#define RTL_NUMBER_OF_V2(A) (sizeof(*RtlpNumberOf(A))) - -// This does not work with: -// -// void Foo() -// { -// struct { int x; } y[2]; -// RTL_NUMBER_OF_V2(y); // illegal use of anonymous local type in template instantiation -// } -// -// You must instead do: -// -// struct Foo1 { int x; }; -// -// void Foo() -// { -// Foo1 y[2]; -// RTL_NUMBER_OF_V2(y); // ok -// } -// -// OR -// -// void Foo() -// { -// struct { int x; } y[2]; -// RTL_NUMBER_OF_V1(y); // ok -// } -// -// OR -// -// void Foo() -// { -// struct { int x; } y[2]; -// _ARRAYSIZE(y); // ok -// } - -#else -#define RTL_NUMBER_OF_V2(A) RTL_NUMBER_OF_V1(A) -#endif - -// ARRAYSIZE is more readable version of RTL_NUMBER_OF_V2 -// _ARRAYSIZE is a version useful for anonymous types -#define ARRAYSIZE(A) RTL_NUMBER_OF_V2(A) -#define _ARRAYSIZE(A) RTL_NUMBER_OF_V1(A) - -#endif // COMMONMACROS_H \ No newline at end of file diff --git a/Resources/NetHook/tier0/dbg.h b/Resources/NetHook/tier0/dbg.h deleted file mode 100644 index 66f29a0a..00000000 --- a/Resources/NetHook/tier0/dbg.h +++ /dev/null @@ -1,714 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ========// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef DBG_H -#define DBG_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "basetypes.h" -#include "dbgflag.h" -#include "platform.h" -#include -#include -#include - -#ifdef _LINUX -#define __cdecl -#endif - -//----------------------------------------------------------------------------- -// dll export stuff -//----------------------------------------------------------------------------- -#ifndef STATIC_TIER0 - -#ifdef TIER0_DLL_EXPORT -#define DBG_INTERFACE DLL_EXPORT -#define DBG_OVERLOAD DLL_GLOBAL_EXPORT -#define DBG_CLASS DLL_CLASS_EXPORT -#else -#define DBG_INTERFACE DLL_IMPORT -#define DBG_OVERLOAD DLL_GLOBAL_IMPORT -#define DBG_CLASS DLL_CLASS_IMPORT -#endif - -#else // BUILD_AS_DLL - -#define DBG_INTERFACE extern -#define DBG_OVERLOAD -#define DBG_CLASS -#endif // BUILD_AS_DLL - - -class Color; - - -//----------------------------------------------------------------------------- -// Usage model for the Dbg library -// -// 1. Spew. -// -// Spew can be used in a static and a dynamic mode. The static -// mode allows us to display assertions and other messages either only -// in debug builds, or in non-release builds. The dynamic mode allows us to -// turn on and off certain spew messages while the application is running. -// -// Static Spew messages: -// -// Assertions are used to detect and warn about invalid states -// Spews are used to display a particular status/warning message. -// -// To use an assertion, use -// -// Assert( (f == 5) ); -// AssertMsg( (f == 5), ("F needs to be %d here!\n", 5) ); -// AssertFunc( (f == 5), BadFunc() ); -// AssertEquals( f, 5 ); -// AssertFloatEquals( f, 5.0f, 1e-3 ); -// -// The first will simply report that an assertion failed on a particular -// code file and line. The second version will display a print-f formatted message -// along with the file and line, the third will display a generic message and -// will also cause the function BadFunc to be executed, and the last two -// will report an error if f is not equal to 5 (the last one asserts within -// a particular tolerance). -// -// To use a warning, use -// -// Warning("Oh I feel so %s all over\n", "yummy"); -// -// Warning will do its magic in only Debug builds. To perform spew in *all* -// builds, use RelWarning. -// -// Three other spew types, Msg, Log, and Error, are compiled into all builds. -// These error types do *not* need two sets of parenthesis. -// -// Msg( "Isn't this exciting %d?", 5 ); -// Error( "I'm just thrilled" ); -// -// Dynamic Spew messages -// -// It is possible to dynamically turn spew on and off. Dynamic spew is -// identified by a spew group and priority level. To turn spew on for a -// particular spew group, use SpewActivate( "group", level ). This will -// cause all spew in that particular group with priority levels <= the -// level specified in the SpewActivate function to be printed. Use DSpew -// to perform the spew: -// -// DWarning( "group", level, "Oh I feel even yummier!\n" ); -// -// Priority level 0 means that the spew will *always* be printed, and group -// '*' is the default spew group. If a DWarning is encountered using a group -// whose priority has not been set, it will use the priority of the default -// group. The priority of the default group is initially set to 0. -// -// Spew output -// -// The output of the spew system can be redirected to an externally-supplied -// function which is responsible for outputting the spew. By default, the -// spew is simply printed using printf. -// -// To redirect spew output, call SpewOutput. -// -// SpewOutputFunc( OutputFunc ); -// -// This will cause OutputFunc to be called every time a spew message is -// generated. OutputFunc will be passed a spew type and a message to print. -// It must return a value indicating whether the debugger should be invoked, -// whether the program should continue running, or whether the program -// should abort. -// -// 2. Code activation -// -// To cause code to be run only in debug builds, use DBG_CODE: -// An example is below. -// -// DBG_CODE( -// { -// int x = 5; -// ++x; -// } -// ); -// -// Code can be activated based on the dynamic spew groups also. Use -// -// DBG_DCODE( "group", level, -// { int x = 5; ++x; } -// ); -// -// 3. Breaking into the debugger. -// -// To cause an unconditional break into the debugger in debug builds only, use DBG_BREAK -// -// DBG_BREAK(); -// -// You can force a break in any build (release or debug) using -// -// DebuggerBreak(); -//----------------------------------------------------------------------------- - -/* Various types of spew messages */ -// I'm sure you're asking yourself why SPEW_ instead of DBG_ ? -// It's because DBG_ is used all over the place in windows.h -// For example, DBG_CONTINUE is defined. Feh. -enum SpewType_t -{ - SPEW_MESSAGE = 0, - SPEW_WARNING, - SPEW_ASSERT, - SPEW_ERROR, - SPEW_LOG, - - SPEW_TYPE_COUNT -}; - -enum SpewRetval_t -{ - SPEW_DEBUGGER = 0, - SPEW_CONTINUE, - SPEW_ABORT -}; - -/* type of externally defined function used to display debug spew */ -typedef SpewRetval_t (*SpewOutputFunc_t)( SpewType_t spewType, const tchar *pMsg ); - -/* Used to redirect spew output */ -DBG_INTERFACE void SpewOutputFunc( SpewOutputFunc_t func ); - -/* Used to get the current spew output function */ -DBG_INTERFACE SpewOutputFunc_t GetSpewOutputFunc( void ); - -/* Should be called only inside a SpewOutputFunc_t, returns groupname, level, color */ -DBG_INTERFACE const tchar* GetSpewOutputGroup( void ); -DBG_INTERFACE int GetSpewOutputLevel( void ); -DBG_INTERFACE const Color& GetSpewOutputColor( void ); - -/* Used to manage spew groups and subgroups */ -DBG_INTERFACE void SpewActivate( const tchar* pGroupName, int level ); -DBG_INTERFACE bool IsSpewActive( const tchar* pGroupName, int level ); - -/* Used to display messages, should never be called directly. */ -DBG_INTERFACE void _SpewInfo( SpewType_t type, const tchar* pFile, int line ); -DBG_INTERFACE SpewRetval_t _SpewMessage( const tchar* pMsg, ... ); -DBG_INTERFACE SpewRetval_t _DSpewMessage( const tchar *pGroupName, int level, const tchar* pMsg, ... ); -DBG_INTERFACE SpewRetval_t ColorSpewMessage( SpewType_t type, const Color *pColor, const tchar* pMsg, ... ); -DBG_INTERFACE void _ExitOnFatalAssert( const tchar* pFile, int line ); -DBG_INTERFACE bool ShouldUseNewAssertDialog(); - -DBG_INTERFACE bool SetupWin32ConsoleIO(); - -// Returns true if they want to break in the debugger. -DBG_INTERFACE bool DoNewAssertDialog( const tchar *pFile, int line, const tchar *pExpression ); - -/* Used to define macros, never use these directly. */ - -#define _AssertMsg( _exp, _msg, _executeExp, _bFatal ) \ - do { \ - if (!(_exp)) \ - { \ - _SpewInfo( SPEW_ASSERT, __TFILE__, __LINE__ ); \ - SpewRetval_t ret = _SpewMessage("%s", _msg); \ - _executeExp; \ - if ( ret == SPEW_DEBUGGER) \ - { \ - if ( !ShouldUseNewAssertDialog() || DoNewAssertDialog( __TFILE__, __LINE__, _msg ) ) \ - DebuggerBreak(); \ - if ( _bFatal ) \ - _ExitOnFatalAssert( __TFILE__, __LINE__ ); \ - } \ - } \ - } while (0) - -#define _AssertMsgOnce( _exp, _msg, _bFatal ) \ - do { \ - static bool fAsserted; \ - if (!fAsserted ) \ - { \ - _AssertMsg( _exp, _msg, (fAsserted = true), _bFatal ); \ - } \ - } while (0) - -/* Spew macros... */ - -// AssertFatal macros -// AssertFatal is used to detect an unrecoverable error condition. -// If enabled, it may display an assert dialog (if DBGFLAG_ASSERTDLG is turned on or running under the debugger), -// and always terminates the application - -#ifdef DBGFLAG_ASSERTFATAL - -#define AssertFatal( _exp ) _AssertMsg( _exp, _T("Assertion Failed: ") _T(#_exp), ((void)0), true ) -#define AssertFatalOnce( _exp ) _AssertMsgOnce( _exp, _T("Assertion Failed: ") _T(#_exp), true ) -#define AssertFatalMsg( _exp, _msg ) _AssertMsg( _exp, _msg, ((void)0), true ) -#define AssertFatalMsgOnce( _exp, _msg ) _AssertMsgOnce( _exp, _msg, true ) -#define AssertFatalFunc( _exp, _f ) _AssertMsg( _exp, _T("Assertion Failed: " _T(#_exp), _f, true ) -#define AssertFatalEquals( _exp, _expectedValue ) AssertFatalMsg2( (_exp) == (_expectedValue), _T("Expected %d but got %d!"), (_expectedValue), (_exp) ) -#define AssertFatalFloatEquals( _exp, _expectedValue, _tol ) AssertFatalMsg2( fabs((_exp) - (_expectedValue)) <= (_tol), _T("Expected %f but got %f!"), (_expectedValue), (_exp) ) -#define VerifyFatal( _exp ) AssertFatal( _exp ) -#define VerifyEqualsFatal( _exp, _expectedValue ) AssertFatalEquals( _exp, _expectedValue ) - -#define AssertFatalMsg1( _exp, _msg, a1 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1 ))) -#define AssertFatalMsg2( _exp, _msg, a1, a2 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2 ))) -#define AssertFatalMsg3( _exp, _msg, a1, a2, a3 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3 ))) -#define AssertFatalMsg4( _exp, _msg, a1, a2, a3, a4 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4 ))) -#define AssertFatalMsg5( _exp, _msg, a1, a2, a3, a4, a5 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5 ))) -#define AssertFatalMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6 ))) -#define AssertFatalMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6 ))) -#define AssertFatalMsg7( _exp, _msg, a1, a2, a3, a4, a5, a6, a7 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7 ))) -#define AssertFatalMsg8( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7, a8 ))) -#define AssertFatalMsg9( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) AssertFatalMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ))) - -#else // DBGFLAG_ASSERTFATAL - -#define AssertFatal( _exp ) ((void)0) -#define AssertFatalOnce( _exp ) ((void)0) -#define AssertFatalMsg( _exp, _msg ) ((void)0) -#define AssertFatalMsgOnce( _exp, _msg ) ((void)0) -#define AssertFatalFunc( _exp, _f ) ((void)0) -#define AssertFatalEquals( _exp, _expectedValue ) ((void)0) -#define AssertFatalFloatEquals( _exp, _expectedValue, _tol ) ((void)0) -#define VerifyFatal( _exp ) (_exp) -#define VerifyEqualsFatal( _exp, _expectedValue ) (_exp) - -#define AssertFatalMsg1( _exp, _msg, a1 ) ((void)0) -#define AssertFatalMsg2( _exp, _msg, a1, a2 ) ((void)0) -#define AssertFatalMsg3( _exp, _msg, a1, a2, a3 ) ((void)0) -#define AssertFatalMsg4( _exp, _msg, a1, a2, a3, a4 ) ((void)0) -#define AssertFatalMsg5( _exp, _msg, a1, a2, a3, a4, a5 ) ((void)0) -#define AssertFatalMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) ((void)0) -#define AssertFatalMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) ((void)0) -#define AssertFatalMsg7( _exp, _msg, a1, a2, a3, a4, a5, a6, a7 ) ((void)0) -#define AssertFatalMsg8( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) ((void)0) -#define AssertFatalMsg9( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) ((void)0) - -#endif // DBGFLAG_ASSERTFATAL - -// Assert macros -// Assert is used to detect an important but survivable error. -// It's only turned on when DBGFLAG_ASSERT is true. - -#ifdef DBGFLAG_ASSERT - -#define Assert( _exp ) _AssertMsg( _exp, _T("Assertion Failed: ") _T(#_exp), ((void)0), false ) -#define AssertMsg( _exp, _msg ) _AssertMsg( _exp, _msg, ((void)0), false ) -#define AssertOnce( _exp ) _AssertMsgOnce( _exp, _T("Assertion Failed: ") _T(#_exp), false ) -#define AssertMsgOnce( _exp, _msg ) _AssertMsgOnce( _exp, _msg, false ) -#define AssertFunc( _exp, _f ) _AssertMsg( _exp, _T("Assertion Failed: ") _T(#_exp), _f, false ) -#define AssertEquals( _exp, _expectedValue ) AssertMsg2( (_exp) == (_expectedValue), _T("Expected %d but got %d!"), (_expectedValue), (_exp) ) -#define AssertFloatEquals( _exp, _expectedValue, _tol ) AssertMsg2( fabs((_exp) - (_expectedValue)) <= (_tol), _T("Expected %f but got %f!"), (_expectedValue), (_exp) ) -#define Verify( _exp ) Assert( _exp ) -#define VerifyEquals( _exp, _expectedValue ) AssertEquals( _exp, _expectedValue ) - -#define AssertMsg1( _exp, _msg, a1 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1 )) ) -#define AssertMsg2( _exp, _msg, a1, a2 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2 )) ) -#define AssertMsg3( _exp, _msg, a1, a2, a3 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3 )) ) -#define AssertMsg4( _exp, _msg, a1, a2, a3, a4 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4 )) ) -#define AssertMsg5( _exp, _msg, a1, a2, a3, a4, a5 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5 )) ) -#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6 )) ) -#define AssertMsg7( _exp, _msg, a1, a2, a3, a4, a5, a6, a7 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7 )) ) -#define AssertMsg8( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7, a8 )) ) -#define AssertMsg9( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) AssertMsg( _exp, (const tchar *)(CDbgFmtMsg( _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 )) ) - -#else // DBGFLAG_ASSERT - -#define Assert( _exp ) ((void)0) -#define AssertOnce( _exp ) ((void)0) -#define AssertMsg( _exp, _msg ) ((void)0) -#define AssertMsgOnce( _exp, _msg ) ((void)0) -#define AssertFunc( _exp, _f ) ((void)0) -#define AssertEquals( _exp, _expectedValue ) ((void)0) -#define AssertFloatEquals( _exp, _expectedValue, _tol ) ((void)0) -#define Verify( _exp ) (_exp) -#define VerifyEquals( _exp, _expectedValue ) (_exp) - -#define AssertMsg1( _exp, _msg, a1 ) ((void)0) -#define AssertMsg2( _exp, _msg, a1, a2 ) ((void)0) -#define AssertMsg3( _exp, _msg, a1, a2, a3 ) ((void)0) -#define AssertMsg4( _exp, _msg, a1, a2, a3, a4 ) ((void)0) -#define AssertMsg5( _exp, _msg, a1, a2, a3, a4, a5 ) ((void)0) -#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) ((void)0) -#define AssertMsg6( _exp, _msg, a1, a2, a3, a4, a5, a6 ) ((void)0) -#define AssertMsg7( _exp, _msg, a1, a2, a3, a4, a5, a6, a7 ) ((void)0) -#define AssertMsg8( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8 ) ((void)0) -#define AssertMsg9( _exp, _msg, a1, a2, a3, a4, a5, a6, a7, a8, a9 ) ((void)0) - -#endif // DBGFLAG_ASSERT - - -#if !defined( _X360 ) || !defined( _RETAIL ) - -/* These are always compiled in */ -DBG_INTERFACE void Msg( const tchar* pMsg, ... ); -DBG_INTERFACE void DMsg( const tchar *pGroupName, int level, const tchar *pMsg, ... ); - -DBG_INTERFACE void Warning( const tchar *pMsg, ... ); -DBG_INTERFACE void DWarning( const tchar *pGroupName, int level, const tchar *pMsg, ... ); - -DBG_INTERFACE void Log( const tchar *pMsg, ... ); -DBG_INTERFACE void DLog( const tchar *pGroupName, int level, const tchar *pMsg, ... ); - -DBG_INTERFACE void Error( const tchar *pMsg, ... ); - -#else - -inline void Msg( ... ) {} -inline void DMsg( ... ) {} -inline void Warning( const tchar *pMsg, ... ) {} -inline void DWarning( ... ) {} -inline void Log( ... ) {} -inline void DLog( ... ) {} -inline void Error( ... ) {} - -#endif - -// You can use this macro like a runtime assert macro. -// If the condition fails, then Error is called with the message. This macro is called -// like AssertMsg, where msg must be enclosed in parenthesis: -// -// ErrorIfNot( bCondition, ("a b c %d %d %d", 1, 2, 3) ); -#define ErrorIfNot( condition, msg ) \ - if ( (condition) ) \ - ; \ - else \ - { \ - Error msg; \ - } - -#if !defined( _X360 ) || !defined( _RETAIL ) - -/* A couple of super-common dynamic spew messages, here for convenience */ -/* These looked at the "developer" group */ -DBG_INTERFACE void DevMsg( int level, const tchar* pMsg, ... ); -DBG_INTERFACE void DevWarning( int level, const tchar *pMsg, ... ); -DBG_INTERFACE void DevLog( int level, const tchar *pMsg, ... ); - -/* default level versions (level 1) */ -DBG_OVERLOAD void DevMsg( const tchar* pMsg, ... ); -DBG_OVERLOAD void DevWarning( const tchar *pMsg, ... ); -DBG_OVERLOAD void DevLog( const tchar *pMsg, ... ); - -/* These looked at the "console" group */ -DBG_INTERFACE void ConColorMsg( int level, const Color& clr, const tchar* pMsg, ... ); -DBG_INTERFACE void ConMsg( int level, const tchar* pMsg, ... ); -DBG_INTERFACE void ConWarning( int level, const tchar *pMsg, ... ); -DBG_INTERFACE void ConLog( int level, const tchar *pMsg, ... ); - -/* default console version (level 1) */ -DBG_OVERLOAD void ConColorMsg( const Color& clr, const tchar* pMsg, ... ); -DBG_OVERLOAD void ConMsg( const tchar* pMsg, ... ); -DBG_OVERLOAD void ConWarning( const tchar *pMsg, ... ); -DBG_OVERLOAD void ConLog( const tchar *pMsg, ... ); - -/* developer console version (level 2) */ -DBG_INTERFACE void ConDColorMsg( const Color& clr, const tchar* pMsg, ... ); -DBG_INTERFACE void ConDMsg( const tchar* pMsg, ... ); -DBG_INTERFACE void ConDWarning( const tchar *pMsg, ... ); -DBG_INTERFACE void ConDLog( const tchar *pMsg, ... ); - -/* These looked at the "network" group */ -DBG_INTERFACE void NetMsg( int level, const tchar* pMsg, ... ); -DBG_INTERFACE void NetWarning( int level, const tchar *pMsg, ... ); -DBG_INTERFACE void NetLog( int level, const tchar *pMsg, ... ); - -void ValidateSpew( class CValidator &validator ); - -#else - -inline void DevMsg( ... ) {} -inline void DevWarning( ... ) {} -inline void DevLog( ... ) {} -inline void ConMsg( ... ) {} -inline void ConLog( ... ) {} -inline void NetMsg( ... ) {} -inline void NetWarning( ... ) {} -inline void NetLog( ... ) {} - -#endif - -DBG_INTERFACE void COM_TimestampedLog( char const *fmt, ... ); - -/* Code macros, debugger interface */ - -#ifdef _DEBUG - -#define DBG_CODE( _code ) if (0) ; else { _code } -#define DBG_CODE_NOSCOPE( _code ) _code -#define DBG_DCODE( _g, _l, _code ) if (IsSpewActive( _g, _l )) { _code } else {} -#define DBG_BREAK() DebuggerBreak() /* defined in platform.h */ - -#else /* not _DEBUG */ - -#define DBG_CODE( _code ) ((void)0) -#define DBG_CODE_NOSCOPE( _code ) -#define DBG_DCODE( _g, _l, _code ) ((void)0) -#define DBG_BREAK() ((void)0) - -#endif /* _DEBUG */ - -//----------------------------------------------------------------------------- - -#ifndef _RETAIL -class CScopeMsg -{ -public: - CScopeMsg( const char *pszScope ) - { - m_pszScope = pszScope; - Msg( "%s { ", pszScope ); - } - ~CScopeMsg() - { - Msg( "} %s", m_pszScope ); - } - const char *m_pszScope; -}; -#define SCOPE_MSG( msg ) CScopeMsg scopeMsg( msg ) -#else -#define SCOPE_MSG( msg ) -#endif - - -//----------------------------------------------------------------------------- -// Macro to assist in asserting constant invariants during compilation - -#ifdef _DEBUG -#define COMPILE_TIME_ASSERT( pred ) switch(0){case 0:case pred:;} -#define ASSERT_INVARIANT( pred ) static void UNIQUE_ID() { COMPILE_TIME_ASSERT( pred ) } -#else -#define COMPILE_TIME_ASSERT( pred ) -#define ASSERT_INVARIANT( pred ) -#endif - -#ifdef _DEBUG -template -inline DEST_POINTER_TYPE assert_cast(SOURCE_POINTER_TYPE* pSource) -{ - Assert( static_cast(pSource) == dynamic_cast(pSource) ); - return static_cast(pSource); -} -#else -#define assert_cast static_cast -#endif - -//----------------------------------------------------------------------------- -// Templates to assist in validating pointers: - -// Have to use these stubs so we don't have to include windows.h here. -DBG_INTERFACE void _AssertValidReadPtr( void* ptr, int count = 1 ); -DBG_INTERFACE void _AssertValidWritePtr( void* ptr, int count = 1 ); -DBG_INTERFACE void _AssertValidReadWritePtr( void* ptr, int count = 1 ); - -DBG_INTERFACE void AssertValidStringPtr( const tchar* ptr, int maxchar = 0xFFFFFF ); -template inline void AssertValidReadPtr( T* ptr, int count = 1 ) { _AssertValidReadPtr( (void*)ptr, count ); } -template inline void AssertValidWritePtr( T* ptr, int count = 1 ) { _AssertValidWritePtr( (void*)ptr, count ); } -template inline void AssertValidReadWritePtr( T* ptr, int count = 1 ) { _AssertValidReadWritePtr( (void*)ptr, count ); } - -#define AssertValidThis() AssertValidReadWritePtr(this,sizeof(*this)) - -//----------------------------------------------------------------------------- -// Macro to protect functions that are not reentrant - -#ifdef _DEBUG -class CReentryGuard -{ -public: - CReentryGuard(int *pSemaphore) - : m_pSemaphore(pSemaphore) - { - ++(*m_pSemaphore); - } - - ~CReentryGuard() - { - --(*m_pSemaphore); - } - -private: - int *m_pSemaphore; -}; - -#define ASSERT_NO_REENTRY() \ - static int fSemaphore##__LINE__; \ - Assert( !fSemaphore##__LINE__ ); \ - CReentryGuard ReentryGuard##__LINE__( &fSemaphore##__LINE__ ) -#else -#define ASSERT_NO_REENTRY() -#endif - -//----------------------------------------------------------------------------- -// -// Purpose: Inline string formatter -// - -#include "tier0/valve_off.h" -class CDbgFmtMsg -{ -public: - CDbgFmtMsg(const tchar *pszFormat, ...) - { - va_list arg_ptr; - - va_start(arg_ptr, pszFormat); - _vsntprintf(m_szBuf, sizeof(m_szBuf)-1, pszFormat, arg_ptr); - va_end(arg_ptr); - - m_szBuf[sizeof(m_szBuf)-1] = 0; - } - - operator const tchar *() const - { - return m_szBuf; - } - -private: - tchar m_szBuf[256]; -}; -#include "tier0/valve_on.h" - -//----------------------------------------------------------------------------- -// -// Purpose: Embed debug info in each file. -// -#if defined( _WIN32 ) && !defined( _X360 ) - - #ifdef _DEBUG - #pragma comment(compiler) - #endif - -#endif - -//----------------------------------------------------------------------------- -// -// Purpose: Wrap around a variable to create a simple place to put a breakpoint -// - -#ifdef _DEBUG - -template< class Type > -class CDataWatcher -{ -public: - const Type& operator=( const Type &val ) - { - return Set( val ); - } - - const Type& operator=( const CDataWatcher &val ) - { - return Set( val.m_Value ); - } - - const Type& Set( const Type &val ) - { - // Put your breakpoint here - m_Value = val; - return m_Value; - } - - Type& GetForModify() - { - return m_Value; - } - - const Type& operator+=( const Type &val ) - { - return Set( m_Value + val ); - } - - const Type& operator-=( const Type &val ) - { - return Set( m_Value - val ); - } - - const Type& operator/=( const Type &val ) - { - return Set( m_Value / val ); - } - - const Type& operator*=( const Type &val ) - { - return Set( m_Value * val ); - } - - const Type& operator^=( const Type &val ) - { - return Set( m_Value ^ val ); - } - - const Type& operator|=( const Type &val ) - { - return Set( m_Value | val ); - } - - const Type& operator++() - { - return (*this += 1); - } - - Type operator--() - { - return (*this -= 1); - } - - Type operator++( int ) // postfix version.. - { - Type val = m_Value; - (*this += 1); - return val; - } - - Type operator--( int ) // postfix version.. - { - Type val = m_Value; - (*this -= 1); - return val; - } - - // For some reason the compiler only generates type conversion warnings for this operator when used like - // CNetworkVarBase = 0x1 - // (it warns about converting from an int to an unsigned char). - template< class C > - const Type& operator&=( C val ) - { - return Set( m_Value & val ); - } - - operator const Type&() const - { - return m_Value; - } - - const Type& Get() const - { - return m_Value; - } - - const Type* operator->() const - { - return &m_Value; - } - - Type m_Value; - -}; - -#else - -template< class Type > -class CDataWatcher -{ -private: - CDataWatcher(); // refuse to compile in non-debug builds -}; - -#endif - -//----------------------------------------------------------------------------- - -#endif /* DBG_H */ diff --git a/Resources/NetHook/tier0/dbgflag.h b/Resources/NetHook/tier0/dbgflag.h deleted file mode 100644 index d34cfd46..00000000 --- a/Resources/NetHook/tier0/dbgflag.h +++ /dev/null @@ -1,65 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: This file sets all of our debugging flags. It should be -// called before all other header files. -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef DBGFLAG_H -#define DBGFLAG_H -#ifdef _WIN32 -#pragma once -#endif - - -// Here are all the flags we support: -// DBGFLAG_MEMORY: Enables our memory debugging system, which overrides malloc & free -// DBGFLAG_MEMORY_NEWDEL: Enables new / delete tracking for memory debug system. Requires DBGFLAG_MEMORY to be enabled. -// DBGFLAG_VALIDATE: Enables our recursive validation system for checking integrity and memory leaks -// DBGFLAG_ASSERT: Turns Assert on or off (when off, it isn't compiled at all) -// DBGFLAG_ASSERTFATAL: Turns AssertFatal on or off (when off, it isn't compiled at all) -// DBGFLAG_ASSERTDLG: Turns assert dialogs on or off and debug breaks on or off when not under the debugger. -// (Dialogs will always be on when process is being debugged.) -// DBGFLAG_STRINGS: Turns on hardcore string validation (slow but safe) - -#undef DBGFLAG_MEMORY -#undef DBGFLAG_MEMORY_NEWDEL -#undef DBGFLAG_VALIDATE -#undef DBGFLAG_ASSERT -#undef DBGFLAG_ASSERTFATAL -#undef DBGFLAG_ASSERTDLG -#undef DBGFLAG_STRINGS - -//----------------------------------------------------------------------------- -// Default flags for debug builds -//----------------------------------------------------------------------------- -#ifdef _DEBUG - -#define DBGFLAG_MEMORY -#ifdef _SERVER // only enable new & delete tracking for server; on client it conflicts with CRT mem leak tracking -#define DBGFLAG_MEMORY_NEWDEL -#endif -#ifdef STEAM -#define DBGFLAG_VALIDATE -#endif -#define DBGFLAG_ASSERT -#define DBGFLAG_ASSERTFATAL -#define DBGFLAG_ASSERTDLG -#define DBGFLAG_STRINGS - - -//----------------------------------------------------------------------------- -// Default flags for release builds -//----------------------------------------------------------------------------- -#else // _DEBUG - -#ifdef STEAM -#define DBGFLAG_ASSERT -#endif -#define DBGFLAG_ASSERTFATAL // note: fatal asserts are enabled in release builds -#define DBGFLAG_ASSERTDLG - -#endif // _DEBUG - -#endif // DBGFLAG_H diff --git a/Resources/NetHook/tier0/fasttimer.h b/Resources/NetHook/tier0/fasttimer.h deleted file mode 100644 index 80b55b5a..00000000 --- a/Resources/NetHook/tier0/fasttimer.h +++ /dev/null @@ -1,591 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef FASTTIMER_H -#define FASTTIMER_H -#ifdef _WIN32 -#pragma once -#endif - -#include -#include "tier0/platform.h" - -PLATFORM_INTERFACE int64 g_ClockSpeed; -PLATFORM_INTERFACE unsigned long g_dwClockSpeed; -#if defined( _X360 ) && defined( _CERT ) -PLATFORM_INTERFACE unsigned long g_dwFakeFastCounter; -#endif - -PLATFORM_INTERFACE double g_ClockSpeedMicrosecondsMultiplier; -PLATFORM_INTERFACE double g_ClockSpeedMillisecondsMultiplier; -PLATFORM_INTERFACE double g_ClockSpeedSecondsMultiplier; - -class CCycleCount -{ -friend class CFastTimer; - -public: - CCycleCount(); - CCycleCount( int64 cycles ); - - void Sample(); // Sample the clock. This takes about 34 clocks to execute (or 26,000 calls per millisecond on a P900). - - void Init(); // Set to zero. - void Init( float initTimeMsec ); - void Init( double initTimeMsec ) { Init( (float)initTimeMsec ); } - void Init( int64 cycles ); - bool IsLessThan( CCycleCount const &other ) const; // Compare two counts. - - // Convert to other time representations. These functions are slow, so it's preferable to call them - // during display rather than inside a timing block. - unsigned long GetCycles() const; - int64 GetLongCycles() const; - - unsigned long GetMicroseconds() const; - uint64 GetUlMicroseconds() const; - double GetMicrosecondsF() const; - void SetMicroseconds( unsigned long nMicroseconds ); - - unsigned long GetMilliseconds() const; - double GetMillisecondsF() const; - - double GetSeconds() const; - - CCycleCount& operator+=( CCycleCount const &other ); - - // dest = rSrc1 + rSrc2 - static void Add( CCycleCount const &rSrc1, CCycleCount const &rSrc2, CCycleCount &dest ); // Add two samples together. - - // dest = rSrc1 - rSrc2 - static void Sub( CCycleCount const &rSrc1, CCycleCount const &rSrc2, CCycleCount &dest ); // Add two samples together. - - static int64 GetTimestamp(); - - int64 m_Int64; -}; - -class CClockSpeedInit -{ -public: - CClockSpeedInit() - { - Init(); - } - - static void Init() - { -#if defined( _X360 ) && !defined( _CERT ) - PMCStart(); - PMCInitIntervalTimer( 0 ); -#endif - const CPUInformation& pi = GetCPUInformation(); - - g_ClockSpeed = pi.m_Speed; - g_dwClockSpeed = (unsigned long)g_ClockSpeed; - - g_ClockSpeedMicrosecondsMultiplier = 1000000.0 / (double)g_ClockSpeed; - g_ClockSpeedMillisecondsMultiplier = 1000.0 / (double)g_ClockSpeed; - g_ClockSpeedSecondsMultiplier = 1.0f / (double)g_ClockSpeed; - } -}; - -class CFastTimer -{ -public: - // These functions are fast to call and should be called from your sampling code. - void Start(); - void End(); - - const CCycleCount & GetDuration() const; // Get the elapsed time between Start and End calls. - CCycleCount GetDurationInProgress() const; // Call without ending. Not that cheap. - - // Return number of cycles per second on this processor. - static inline unsigned long GetClockSpeed(); - -private: - CCycleCount m_Duration; -#ifdef DEBUG_FASTTIMER - bool m_bRunning; // Are we currently running? -#endif -}; - - -// This is a helper class that times whatever block of code it's in -class CTimeScope -{ -public: - CTimeScope( CFastTimer *pTimer ); - ~CTimeScope(); - -private: - CFastTimer *m_pTimer; -}; - -inline CTimeScope::CTimeScope( CFastTimer *pTotal ) -{ - m_pTimer = pTotal; - m_pTimer->Start(); -} - -inline CTimeScope::~CTimeScope() -{ - m_pTimer->End(); -} - -// This is a helper class that times whatever block of code it's in and -// adds the total (int microseconds) to a global counter. -class CTimeAdder -{ -public: - CTimeAdder( CCycleCount *pTotal ); - ~CTimeAdder(); - - void End(); - -private: - CCycleCount *m_pTotal; - CFastTimer m_Timer; -}; - -inline CTimeAdder::CTimeAdder( CCycleCount *pTotal ) -{ - m_pTotal = pTotal; - m_Timer.Start(); -} - -inline CTimeAdder::~CTimeAdder() -{ - End(); -} - -inline void CTimeAdder::End() -{ - if( m_pTotal ) - { - m_Timer.End(); - *m_pTotal += m_Timer.GetDuration(); - m_pTotal = 0; - } -} - - - -// -------------------------------------------------------------------------- // -// Simple tool to support timing a block of code, and reporting the results on -// program exit or at each iteration -// -// Macros used because dbg.h uses this header, thus Msg() is unavailable -// -------------------------------------------------------------------------- // - -#define PROFILE_SCOPE(name) \ - class C##name##ACC : public CAverageCycleCounter \ - { \ - public: \ - ~C##name##ACC() \ - { \ - Msg("%-48s: %6.3f avg (%8.1f total, %7.3f peak, %5d iters)\n", \ - #name, \ - GetAverageMilliseconds(), \ - GetTotalMilliseconds(), \ - GetPeakMilliseconds(), \ - GetIters() ); \ - } \ - }; \ - static C##name##ACC name##_ACC; \ - CAverageTimeMarker name##_ATM( &name##_ACC ) - -#define TIME_SCOPE(name) \ - class CTimeScopeMsg_##name \ - { \ - public: \ - CTimeScopeMsg_##name() { m_Timer.Start(); } \ - ~CTimeScopeMsg_##name() \ - { \ - m_Timer.End(); \ - Msg( #name "time: %.4fms\n", m_Timer.GetDuration().GetMillisecondsF() ); \ - } \ - private: \ - CFastTimer m_Timer; \ - } name##_TSM; - - -// -------------------------------------------------------------------------- // - -class CAverageCycleCounter -{ -public: - CAverageCycleCounter(); - - void Init(); - void MarkIter( const CCycleCount &duration ); - - unsigned GetIters() const; - - double GetAverageMilliseconds() const; - double GetTotalMilliseconds() const; - double GetPeakMilliseconds() const; - -private: - unsigned m_nIters; - CCycleCount m_Total; - CCycleCount m_Peak; - bool m_fReport; - const tchar *m_pszName; -}; - -// -------------------------------------------------------------------------- // - -class CAverageTimeMarker -{ -public: - CAverageTimeMarker( CAverageCycleCounter *pCounter ); - ~CAverageTimeMarker(); - -private: - CAverageCycleCounter *m_pCounter; - CFastTimer m_Timer; -}; - - -// -------------------------------------------------------------------------- // -// CCycleCount inlines. -// -------------------------------------------------------------------------- // - -inline CCycleCount::CCycleCount() -{ - Init( (int64)0 ); -} - -inline CCycleCount::CCycleCount( int64 cycles ) -{ - Init( cycles ); -} - -inline void CCycleCount::Init() -{ - Init( (int64)0 ); -} - -inline void CCycleCount::Init( float initTimeMsec ) -{ - if ( g_ClockSpeedMillisecondsMultiplier > 0 ) - Init( (int64)(initTimeMsec / g_ClockSpeedMillisecondsMultiplier) ); - else - Init( (int64)0 ); -} - -inline void CCycleCount::Init( int64 cycles ) -{ - m_Int64 = cycles; -} - -#pragma warning(push) -#pragma warning(disable : 4189) // warning C4189: local variable is initialized but not referenced - -inline void CCycleCount::Sample() -{ -#if defined( _X360 ) -#if !defined( _CERT ) - // read the highest resolution timer directly (ticks at native 3.2GHz), bypassing any calls into PMC - // can only resolve 32 bits, rollover is ~1.32 secs - // based on PMCGetIntervalTimer() from the April 2007 XDK - int64 temp; - __asm - { - lis r11,08FFFh - ld r11,011E0h(r11) - rldicl r11,r11,32,32 - // unforunate can't get the inline assembler to write directly into desired target - std r11,temp - } - m_Int64 = temp; -#else - m_Int64 = ++g_dwFakeFastCounter; -#endif -#elif defined( _WIN32 ) - unsigned long* pSample = (unsigned long *)&m_Int64; - __asm - { - // force the cpu to synchronize the instruction queue - // NJS: CPUID can really impact performance in tight loops. - //cpuid - //cpuid - //cpuid - mov ecx, pSample - rdtsc - mov [ecx], eax - mov [ecx+4], edx - } -#elif defined( _LINUX ) - unsigned long* pSample = (unsigned long *)&m_Int64; - __asm__ __volatile__ ( - "rdtsc\n\t" - "movl %%eax, (%0)\n\t" - "movl %%edx, 4(%0)\n\t" - : /* no output regs */ - : "D" (pSample) - : "%eax", "%edx" ); -#endif -} - -#pragma warning(pop) - - -inline CCycleCount& CCycleCount::operator+=( CCycleCount const &other ) -{ - m_Int64 += other.m_Int64; - return *this; -} - - -inline void CCycleCount::Add( CCycleCount const &rSrc1, CCycleCount const &rSrc2, CCycleCount &dest ) -{ - dest.m_Int64 = rSrc1.m_Int64 + rSrc2.m_Int64; -} - -inline void CCycleCount::Sub( CCycleCount const &rSrc1, CCycleCount const &rSrc2, CCycleCount &dest ) -{ - dest.m_Int64 = rSrc1.m_Int64 - rSrc2.m_Int64; -} - -inline int64 CCycleCount::GetTimestamp() -{ - CCycleCount c; - c.Sample(); - return c.GetLongCycles(); -} - -inline bool CCycleCount::IsLessThan(CCycleCount const &other) const -{ - return m_Int64 < other.m_Int64; -} - - -inline unsigned long CCycleCount::GetCycles() const -{ - return (unsigned long)m_Int64; -} - -inline int64 CCycleCount::GetLongCycles() const -{ - return m_Int64; -} - -inline unsigned long CCycleCount::GetMicroseconds() const -{ - return (unsigned long)((m_Int64 * 1000000) / g_ClockSpeed); -} - -inline uint64 CCycleCount::GetUlMicroseconds() const -{ - return ((m_Int64 * 1000000) / g_ClockSpeed); -} - - -inline double CCycleCount::GetMicrosecondsF() const -{ - return (double)( m_Int64 * g_ClockSpeedMicrosecondsMultiplier ); -} - - -inline void CCycleCount::SetMicroseconds( unsigned long nMicroseconds ) -{ - m_Int64 = ((int64)nMicroseconds * g_ClockSpeed) / 1000000; -} - - -inline unsigned long CCycleCount::GetMilliseconds() const -{ - return (unsigned long)((m_Int64 * 1000) / g_ClockSpeed); -} - - -inline double CCycleCount::GetMillisecondsF() const -{ - return (double)( m_Int64 * g_ClockSpeedMillisecondsMultiplier ); -} - - -inline double CCycleCount::GetSeconds() const -{ - return (double)( m_Int64 * g_ClockSpeedSecondsMultiplier ); -} - - -// -------------------------------------------------------------------------- // -// CFastTimer inlines. -// -------------------------------------------------------------------------- // -inline void CFastTimer::Start() -{ - m_Duration.Sample(); -#ifdef DEBUG_FASTTIMER - m_bRunning = true; -#endif -} - - -inline void CFastTimer::End() -{ - CCycleCount cnt; - cnt.Sample(); - if ( IsX360() ) - { - // have to handle rollover, hires timer is only accurate to 32 bits - // more than one overflow should not have occured, otherwise caller should use a slower timer - if ( (uint64)cnt.m_Int64 <= (uint64)m_Duration.m_Int64 ) - { - // rollover occured - cnt.m_Int64 += 0x100000000LL; - } - } - - m_Duration.m_Int64 = cnt.m_Int64 - m_Duration.m_Int64; - -#ifdef DEBUG_FASTTIMER - m_bRunning = false; -#endif -} - -inline CCycleCount CFastTimer::GetDurationInProgress() const -{ - CCycleCount cnt; - cnt.Sample(); - if ( IsX360() ) - { - // have to handle rollover, hires timer is only accurate to 32 bits - // more than one overflow should not have occured, otherwise caller should use a slower timer - if ( (uint64)cnt.m_Int64 <= (uint64)m_Duration.m_Int64 ) - { - // rollover occured - cnt.m_Int64 += 0x100000000LL; - } - } - - CCycleCount result; - result.m_Int64 = cnt.m_Int64 - m_Duration.m_Int64; - - return result; -} - - -inline unsigned long CFastTimer::GetClockSpeed() -{ - return g_dwClockSpeed; -} - - -inline CCycleCount const& CFastTimer::GetDuration() const -{ -#ifdef DEBUG_FASTTIMER - assert( !m_bRunning ); -#endif - return m_Duration; -} - - -// -------------------------------------------------------------------------- // -// CAverageCycleCounter inlines - -inline CAverageCycleCounter::CAverageCycleCounter() - : m_nIters( 0 ) -{ -} - -inline void CAverageCycleCounter::Init() -{ - m_Total.Init(); - m_Peak.Init(); - m_nIters = 0; -} - -inline void CAverageCycleCounter::MarkIter( const CCycleCount &duration ) -{ - ++m_nIters; - m_Total += duration; - if ( m_Peak.IsLessThan( duration ) ) - m_Peak = duration; -} - -inline unsigned CAverageCycleCounter::GetIters() const -{ - return m_nIters; -} - -inline double CAverageCycleCounter::GetAverageMilliseconds() const -{ - if ( m_nIters ) - return (m_Total.GetMillisecondsF() / (double)m_nIters); - else - return 0; -} - -inline double CAverageCycleCounter::GetTotalMilliseconds() const -{ - return m_Total.GetMillisecondsF(); -} - -inline double CAverageCycleCounter::GetPeakMilliseconds() const -{ - return m_Peak.GetMillisecondsF(); -} - -// -------------------------------------------------------------------------- // - -inline CAverageTimeMarker::CAverageTimeMarker( CAverageCycleCounter *pCounter ) -{ - m_pCounter = pCounter; - m_Timer.Start(); -} - -inline CAverageTimeMarker::~CAverageTimeMarker() -{ - m_Timer.End(); - m_pCounter->MarkIter( m_Timer.GetDuration() ); -} - - -// CLimitTimer -// Use this to time whether a desired interval of time has passed. It's extremely fast -// to check while running. -class CLimitTimer -{ -public: - void SetLimit( uint64 m_cMicroSecDuration ); - bool BLimitReached( void ); - -private: - int64 m_lCycleLimit; -}; - - -//----------------------------------------------------------------------------- -// Purpose: Initializes the limit timer with a period of time to measure. -// Input : cMicroSecDuration - How long a time period to measure -//----------------------------------------------------------------------------- -inline void CLimitTimer::SetLimit( uint64 m_cMicroSecDuration ) -{ - int64 dlCycles = ( ( uint64 ) m_cMicroSecDuration * ( int64 ) g_dwClockSpeed ) / ( int64 ) 1000000L; - CCycleCount cycleCount; - cycleCount.Sample( ); - m_lCycleLimit = cycleCount.GetLongCycles( ) + dlCycles; -} - - -//----------------------------------------------------------------------------- -// Purpose: Determines whether our specified time period has passed -// Output: true if at least the specified time period has passed -//----------------------------------------------------------------------------- -inline bool CLimitTimer::BLimitReached( ) -{ - CCycleCount cycleCount; - cycleCount.Sample( ); - return ( cycleCount.GetLongCycles( ) >= m_lCycleLimit ); -} - - - -#endif // FASTTIMER_H diff --git a/Resources/NetHook/tier0/ia32detect.h b/Resources/NetHook/tier0/ia32detect.h deleted file mode 100644 index a60bb1a5..00000000 --- a/Resources/NetHook/tier0/ia32detect.h +++ /dev/null @@ -1,351 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -#ifndef IA32DETECT_H -#define IA32DETECT_H - -/* - This section from http://iss.cs.cornell.edu/ia32.htm - - - */ -typedef unsigned bit; - -enum CPUVendor -{ - INTEL, - AMD, - UNKNOWN_VENDOR -}; -class ia32detect -{ -public: - - enum type_t - { - type_OEM, - type_OverDrive, - type_Dual, - type_reserved - }; - - enum brand_t - { - brand_na, - brand_Celeron, - brand_PentiumIII, - brand_PentiumIIIXeon, - brand_reserved1, - brand_reserved2, - brand_PentiumIIIMobile, - brand_reserved3, - brand_Pentium4, - brand_invalid - }; - -# pragma pack(push, 1) - - struct version_t - { - bit Stepping : 4; - bit Model : 4; - bit Family : 4; - bit Type : 2; - bit Reserved1 : 2; - bit XModel : 4; - bit XFamily : 8; - bit Reserved2 : 4; - }; - - struct misc_t - { - byte Brand; - byte CLFLUSH; - byte Reserved; - byte APICId; - }; - - struct feature_t - { - bit FPU : 1; // Floating Point Unit On-Chip - bit VME : 1; // Virtual 8086 Mode Enhancements - bit DE : 1; // Debugging Extensions - bit PSE : 1; // Page Size Extensions - bit TSC : 1; // Time Stamp Counter - bit MSR : 1; // Model Specific Registers - bit PAE : 1; // Physical Address Extension - bit MCE : 1; // Machine Check Exception - bit CX8 : 1; // CMPXCHG8 Instruction - bit APIC : 1; // APIC On-Chip - bit Reserved1 : 1; - bit SEP : 1; // SYSENTER and SYSEXIT instructions - bit MTRR : 1; // Memory Type Range Registers - bit PGE : 1; // PTE Global Bit - bit MCA : 1; // Machine Check Architecture - bit CMOV : 1; // Conditional Move Instructions - bit PAT : 1; // Page Attribute Table - bit PSE36 : 1; // 32-bit Page Size Extension - bit PSN : 1; // Processor Serial Number - bit CLFSH : 1; // CLFLUSH Instruction - bit Reserved2 : 1; - bit DS : 1; // Debug Store - bit ACPI : 1; // Thermal Monitor and Software Controlled Clock Facilities - bit MMX : 1; // Intel MMX Technology - bit FXSR : 1; // FXSAVE and FXRSTOR Instructions - bit SSE : 1; // Intel SSE Technology - bit SSE2 : 1; // Intel SSE2 Technology - bit SS : 1; // Self Snoop - bit HTT : 1; // Hyper Threading - bit TM : 1; // Thermal Monitor - bit Reserved3 : 1; - bit PBE : 1; // Pending Brk. EN. - }; - -# pragma pack(pop) - - tstring vendor_name; - CPUVendor vendor; - tstring brand; - version_t version; - misc_t misc; - feature_t feature; - byte *cache; - - ia32detect () - { - - cache = 0; - uint32 m = init0(); - - uint32 *d = new uint32[m * 4]; - - for (uint32 i = 1; i <= m; i++) - { - uint32 *t = d + (i - 1) * 4; - - __asm - { - mov eax, i; - mov esi, t; - - cpuid; - - mov dword ptr [esi + 0x0], eax; - mov dword ptr [esi + 0x4], ebx; - mov dword ptr [esi + 0x8], ecx; - mov dword ptr [esi + 0xC], edx; - } - } - - if (m >= 1) - init1(d); - - if (m >= 2) - init2(d[4] & 0xFF); - - delete [] d; - - init0x80000000(); - - - //----------------------------------------------------------------------- - // Get the vendor of the processor - //----------------------------------------------------------------------- - if (_tcscmp(vendor_name.c_str(), _T("GenuineIntel")) == 0) - { - vendor = INTEL; - - } - else if (_tcscmp(vendor_name.c_str(), _T("AuthenticAMD")) == 0) - { - vendor = AMD; - - } - else - { - vendor = UNKNOWN_VENDOR; - } - } - - const tstring version_text () const - { - tchar b[128]; - - _stprintf(b, _T("%d.%d.%d %s XVersion(%d.%d)"), - version.Family, version.Model, version.Stepping, type_text(), version.XFamily, version.XModel); - - return tstring(b); - } - -protected: - - const tchar * type_text () const - { - static const tchar *text[] = - { - _T("Intel OEM Processor"), - _T("Intel OverDrive(R) Processor"), - _T("Intel Dual Processor"), - _T("reserved") - }; - - return text[version.Type]; - } - - const tstring brand_text () const - { - static const tchar *text[] = - { - _T("n/a"), - _T("Celeron"), - _T("Pentium III"), - _T("Pentium III Xeon"), - _T("reserved (4)"), - _T("reserved (5)"), - _T("Pentium III Mobile"), - _T("reserved (7)"), - _T("Pentium 4") - }; - - if (misc.Brand < brand_invalid) - return tstring(text[misc.Brand]); - else - { - tchar b[32]; - - _stprintf(b, _T("Brand %d (Update)"), misc.Brand); - - return tstring(b); - } - } - -private: - - uint32 init0 () - { - uint32 m; - tchar s1[13]; - - s1[12] = '\0'; - - __asm - { - xor eax, eax; - cpuid; - mov m, eax; - mov dword ptr s1 + 0, ebx; - mov dword ptr s1 + 4, edx; - mov dword ptr s1 + 8, ecx; - } - - vendor_name = s1; - - return m; - } - - void init1 (uint32 *d) - { - version = *(version_t *)&d[0]; - misc = *(misc_t *)&d[1]; - feature = *(feature_t *)&d[3]; - } - - void process2 (uint32 d, bool c[]) - { - if ((d & 0x80000000) == 0) - for (int i = 0; i < 32; i += 8) - c[(d >> i) & 0xFF] = true; - } - - void init2 (byte count) - { - uint32 d[4]; - bool c[256]; - - for (int ci1 = 0; ci1 < 256; ci1++) - c[ci1] = false; - - for (int i = 0; i < count; i++) - { - __asm - { - mov eax, 2; - lea esi, d; - cpuid; - mov [esi + 0x0], eax; - mov [esi + 0x4], ebx; - mov [esi + 0x8], ecx; - mov [esi + 0xC], edx; - } - - if (i == 0) - d[0] &= 0xFFFFFF00; - - process2(d[0], c); - process2(d[1], c); - process2(d[2], c); - process2(d[3], c); - } - - int m = 0; - - for (int ci2 = 0; ci2 < 256; ci2++) - if (c[ci2]) - m++; - - cache = new byte[m]; - - m = 0; - - for (int ci3 = 1; ci3 < 256; ci3++) - if (c[ci3]) - cache[m++] = ci3; - - cache[m] = 0; - } - - void init0x80000000 () - { - uint32 m; - - __asm - { - mov eax, 0x80000000; - cpuid; - mov m, eax - } - - if ((m & 0x80000000) != 0) - { - uint32 *d = new uint32[(m - 0x80000000) * 4]; - - for (uint32 i = 0x80000001; i <= m; i++) - { - uint32 *t = d + (i - 0x80000001) * 4; - - __asm - { - mov eax, i; - mov esi, t; - cpuid; - mov dword ptr [esi + 0x0], eax; - mov dword ptr [esi + 0x4], ebx; - mov dword ptr [esi + 0x8], ecx; - mov dword ptr [esi + 0xC], edx; - } - } - - if (m >= 0x80000002) - brand = (tchar *)(d + 4); - - // note the assignment to brand above does a copy, we need to delete - delete[] d; - } - } -}; - -#endif // IA32DETECT_H diff --git a/Resources/NetHook/tier0/icommandline.h b/Resources/NetHook/tier0/icommandline.h deleted file mode 100644 index 54951caa..00000000 --- a/Resources/NetHook/tier0/icommandline.h +++ /dev/null @@ -1,53 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -#ifndef TIER0_ICOMMANDLINE_H -#define TIER0_ICOMMANDLINE_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/platform.h" - - -//----------------------------------------------------------------------------- -// Purpose: Interface to engine command line -//----------------------------------------------------------------------------- -abstract_class ICommandLine -{ -public: - virtual void CreateCmdLine( const char *commandline ) = 0; - virtual void CreateCmdLine( int argc, char **argv ) = 0; - virtual const char *GetCmdLine( void ) const = 0; - - // Check whether a particular parameter exists - virtual const char *CheckParm( const char *psz, const char **ppszValue = 0 ) const = 0; - virtual void RemoveParm( const char *parm ) = 0; - virtual void AppendParm( const char *pszParm, const char *pszValues ) = 0; - - // Returns the argument after the one specified, or the default if not found - virtual const char *ParmValue( const char *psz, const char *pDefaultVal = 0 ) const = 0; - virtual int ParmValue( const char *psz, int nDefaultVal ) const = 0; - virtual float ParmValue( const char *psz, float flDefaultVal ) const = 0; - - // Gets at particular parameters - virtual int ParmCount() const = 0; - virtual int FindParm( const char *psz ) const = 0; // Returns 0 if not found. - virtual const char* GetParm( int nIndex ) const = 0; -}; - -//----------------------------------------------------------------------------- -// Gets a singleton to the commandline interface -// NOTE: The #define trickery here is necessary for backwards compat: -// this interface used to lie in the vstdlib library. -//----------------------------------------------------------------------------- -PLATFORM_INTERFACE ICommandLine *CommandLine_Tier0(); - -#if !defined( VSTDLIB_BACKWARD_COMPAT ) -#define CommandLine CommandLine_Tier0 -#endif - -#endif // TIER0_ICOMMANDLINE_H \ No newline at end of file diff --git a/Resources/NetHook/tier0/l2cache.h b/Resources/NetHook/tier0/l2cache.h deleted file mode 100644 index 77636599..00000000 --- a/Resources/NetHook/tier0/l2cache.h +++ /dev/null @@ -1,46 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// -#ifndef CL2CACHE_H -#define CL2CACHE_H -#ifdef _WIN32 -#pragma once -#endif - -class P4Event_BSQ_cache_reference; - -class CL2Cache -{ -public: - - CL2Cache(); - ~CL2Cache(); - - void Start( void ); - void End( void ); - - //------------------------------------------------------------------------- - // GetL2CacheMisses - //------------------------------------------------------------------------- - int GetL2CacheMisses( void ) - { - return m_iL2CacheMissCount; - } - -#ifdef DBGFLAG_VALIDATE - void Validate( CValidator &validator, tchar *pchName ); // Validate our internal structures -#endif // DBGFLAG_VALIDATE - -private: - - int m_nID; - - P4Event_BSQ_cache_reference *m_pL2CacheEvent; - int64 m_i64Start; - int64 m_i64End; - int m_iL2CacheMissCount; -}; - -#endif // CL2CACHE_H \ No newline at end of file diff --git a/Resources/NetHook/tier0/mem.h b/Resources/NetHook/tier0/mem.h deleted file mode 100644 index 3c3b9e16..00000000 --- a/Resources/NetHook/tier0/mem.h +++ /dev/null @@ -1,45 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Memory allocation! -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef TIER0_MEM_H -#define TIER0_MEM_H - -#ifdef _WIN32 -#pragma once -#endif - -#include -#include "tier0/platform.h" - -#if !defined(STATIC_TIER0) && !defined(_STATIC_LINKED) - -#ifdef TIER0_DLL_EXPORT -# define MEM_INTERFACE DLL_EXPORT -#else -# define MEM_INTERFACE DLL_IMPORT -#endif - -#else // BUILD_AS_DLL - -#define MEM_INTERFACE extern - -#endif // BUILD_AS_DLL - - - -//----------------------------------------------------------------------------- -// DLL-exported methods for particular kinds of memory -//----------------------------------------------------------------------------- -MEM_INTERFACE void *MemAllocScratch( int nMemSize ); -MEM_INTERFACE void MemFreeScratch(); - -#ifdef _LINUX -MEM_INTERFACE void ZeroMemory( void *mem, size_t length ); -#endif - - -#endif /* TIER0_MEM_H */ diff --git a/Resources/NetHook/tier0/memalloc.h b/Resources/NetHook/tier0/memalloc.h deleted file mode 100644 index b76b3f14..00000000 --- a/Resources/NetHook/tier0/memalloc.h +++ /dev/null @@ -1,353 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: This header should never be used directly from leaf code!!! -// Instead, just add the file memoverride.cpp into your project and all this -// will automagically be used -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef TIER0_MEMALLOC_H -#define TIER0_MEMALLOC_H - -#ifdef _WIN32 -#pragma once -#endif - -// Define this in release to get memory tracking even in release builds -//#define USE_MEM_DEBUG 1 - -#if defined( _MEMTEST ) -#define USE_MEM_DEBUG 1 -#endif - -// Undefine this if using a compiler lacking threadsafe RTTI (like vc6) -#define MEM_DEBUG_CLASSNAME 1 - -#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE) - -#include -#include "tier0/mem.h" - -struct _CrtMemState; - -#define MEMALLOC_VERSION 1 - -typedef size_t (*MemAllocFailHandler_t)( size_t ); - -//----------------------------------------------------------------------------- -// NOTE! This should never be called directly from leaf code -// Just use new,delete,malloc,free etc. They will call into this eventually -//----------------------------------------------------------------------------- -abstract_class IMemAlloc -{ -public: - // Release versions - virtual void *Alloc( size_t nSize ) = 0; - virtual void *Realloc( void *pMem, size_t nSize ) = 0; - virtual void Free( void *pMem ) = 0; - virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize ) = 0; - - // Debug versions - virtual void *Alloc( size_t nSize, const char *pFileName, int nLine ) = 0; - virtual void *Realloc( void *pMem, size_t nSize, const char *pFileName, int nLine ) = 0; - virtual void Free( void *pMem, const char *pFileName, int nLine ) = 0; - virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize, const char *pFileName, int nLine ) = 0; - - // Returns size of a particular allocation - virtual size_t GetSize( void *pMem ) = 0; - - // Force file + line information for an allocation - virtual void PushAllocDbgInfo( const char *pFileName, int nLine ) = 0; - virtual void PopAllocDbgInfo() = 0; - - // FIXME: Remove when we have our own allocator - // these methods of the Crt debug code is used in our codebase currently - virtual long CrtSetBreakAlloc( long lNewBreakAlloc ) = 0; - virtual int CrtSetReportMode( int nReportType, int nReportMode ) = 0; - virtual int CrtIsValidHeapPointer( const void *pMem ) = 0; - virtual int CrtIsValidPointer( const void *pMem, unsigned int size, int access ) = 0; - virtual int CrtCheckMemory( void ) = 0; - virtual int CrtSetDbgFlag( int nNewFlag ) = 0; - virtual void CrtMemCheckpoint( _CrtMemState *pState ) = 0; - - // FIXME: Make a better stats interface - virtual void DumpStats() = 0; - virtual void DumpStatsFileBase( char const *pchFileBase ) = 0; - - // FIXME: Remove when we have our own allocator - virtual void* CrtSetReportFile( int nRptType, void* hFile ) = 0; - virtual void* CrtSetReportHook( void* pfnNewHook ) = 0; - virtual int CrtDbgReport( int nRptType, const char * szFile, - int nLine, const char * szModule, const char * pMsg ) = 0; - - virtual int heapchk() = 0; - - virtual bool IsDebugHeap() = 0; - - virtual void GetActualDbgInfo( const char *&pFileName, int &nLine ) = 0; - virtual void RegisterAllocation( const char *pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime ) = 0; - virtual void RegisterDeallocation( const char *pFileName, int nLine, int nLogicalSize, int nActualSize, unsigned nTime ) = 0; - - virtual int GetVersion() = 0; - - virtual void CompactHeap() = 0; - - // Function called when malloc fails or memory limits hit to attempt to free up memory (can come in any thread) - virtual MemAllocFailHandler_t SetAllocFailHandler( MemAllocFailHandler_t pfnMemAllocFailHandler ) = 0; - - virtual void DumpBlockStats( void * ) = 0; - -#if defined( _MEMTEST ) - virtual void SetStatsExtraInfo( const char *pMapName, const char *pComment ) = 0; -#endif - - // Returns 0 if no failure, otherwise the size_t of the last requested chunk - virtual size_t MemoryAllocFailed() = 0; -}; - -//----------------------------------------------------------------------------- -// Singleton interface -//----------------------------------------------------------------------------- -MEM_INTERFACE IMemAlloc *g_pMemAlloc; - -//----------------------------------------------------------------------------- - -inline void *MemAlloc_AllocAligned( size_t size, size_t align ) -{ - unsigned char *pAlloc, *pResult; - - if (!IsPowerOfTwo(align)) - return NULL; - - align = (align > sizeof(void *) ? align : sizeof(void *)) - 1; - - if ( (pAlloc = (unsigned char*)g_pMemAlloc->Alloc( sizeof(void *) + align + size ) ) == (unsigned char*)NULL) - return NULL; - - pResult = (unsigned char*)( (size_t)(pAlloc + sizeof(void *) + align ) & ~align ); - ((unsigned char**)(pResult))[-1] = pAlloc; - - return (void *)pResult; -} - -inline void *MemAlloc_AllocAligned( size_t size, size_t align, const char *pszFile, int nLine ) -{ - unsigned char *pAlloc, *pResult; - - if (!IsPowerOfTwo(align)) - return NULL; - - align = (align > sizeof(void *) ? align : sizeof(void *)) - 1; - - if ( (pAlloc = (unsigned char*)g_pMemAlloc->Alloc( sizeof(void *) + align + size, pszFile, nLine ) ) == (unsigned char*)NULL) - return NULL; - - pResult = (unsigned char*)( (size_t)(pAlloc + sizeof(void *) + align ) & ~align ); - ((unsigned char**)(pResult))[-1] = pAlloc; - - return (void *)pResult; -} - -inline void *MemAlloc_ReallocAligned( void *ptr, size_t size, size_t align ) -{ - if ( !IsPowerOfTwo( align ) ) - return NULL; - - // Don't change alignment between allocation + reallocation. - if ( ( (size_t)ptr & ( align - 1 ) ) != 0 ) - return NULL; - - if ( !ptr ) - return MemAlloc_AllocAligned( size, align ); - - void *pAlloc, *pResult; - - // Figure out the actual allocation point - pAlloc = ptr; - pAlloc = (void *)(((size_t)pAlloc & ~( sizeof(void *) - 1 ) ) - sizeof(void *)); - pAlloc = *( (void **)pAlloc ); - - // See if we have enough space - size_t nOffset = (size_t)ptr - (size_t)pAlloc; - size_t nOldSize = g_pMemAlloc->GetSize( pAlloc ); - if ( nOldSize >= size + nOffset ) - return ptr; - - pResult = MemAlloc_AllocAligned( size, align ); - memcpy( pResult, ptr, nOldSize - nOffset ); - g_pMemAlloc->Free( pAlloc ); - return pResult; -} - -inline void MemAlloc_FreeAligned( void *pMemBlock ) -{ - void *pAlloc; - - if ( pMemBlock == NULL ) - return; - - pAlloc = pMemBlock; - - // pAlloc points to the pointer to starting of the memory block - pAlloc = (void *)(((size_t)pAlloc & ~( sizeof(void *) - 1 ) ) - sizeof(void *)); - - // pAlloc is the pointer to the start of memory block - pAlloc = *( (void **)pAlloc ); - g_pMemAlloc->Free( pAlloc ); -} - -inline size_t MemAlloc_GetSizeAligned( void *pMemBlock ) -{ - void *pAlloc; - - if ( pMemBlock == NULL ) - return 0; - - pAlloc = pMemBlock; - - // pAlloc points to the pointer to starting of the memory block - pAlloc = (void *)(((size_t)pAlloc & ~( sizeof(void *) - 1 ) ) - sizeof(void *)); - - // pAlloc is the pointer to the start of memory block - pAlloc = *((void **)pAlloc ); - return g_pMemAlloc->GetSize( pAlloc ) - ( (byte *)pMemBlock - (byte *)pAlloc ); -} - -//----------------------------------------------------------------------------- - -#if (defined(_DEBUG) || defined(USE_MEM_DEBUG)) -#define MEM_ALLOC_CREDIT_(tag) CMemAllocAttributeAlloction memAllocAttributeAlloction( tag, __LINE__ ) -#define MemAlloc_PushAllocDbgInfo( pszFile, line ) g_pMemAlloc->PushAllocDbgInfo( pszFile, line ) -#define MemAlloc_PopAllocDbgInfo() g_pMemAlloc->PopAllocDbgInfo() -#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) -#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) g_pMemAlloc->RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) -#else -#define MEM_ALLOC_CREDIT_(tag) ((void)0) -#define MemAlloc_PushAllocDbgInfo( pszFile, line ) ((void)0) -#define MemAlloc_PopAllocDbgInfo() ((void)0) -#define MemAlloc_RegisterAllocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0) -#define MemAlloc_RegisterDeallocation( pFileName, nLine, nLogicalSize, nActualSize, nTime ) ((void)0) -#endif - -//----------------------------------------------------------------------------- - -class CMemAllocAttributeAlloction -{ -public: - CMemAllocAttributeAlloction( const char *pszFile, int line ) - { - MemAlloc_PushAllocDbgInfo( pszFile, line ); - } - - ~CMemAllocAttributeAlloction() - { - MemAlloc_PopAllocDbgInfo(); - } -}; - -#define MEM_ALLOC_CREDIT() MEM_ALLOC_CREDIT_(__FILE__) - -//----------------------------------------------------------------------------- - -#if defined(_WIN32) && ( defined(_DEBUG) || defined(USE_MEM_DEBUG) ) - - #pragma warning(disable:4290) - #pragma warning(push) - #include - - // MEM_DEBUG_CLASSNAME is opt-in. - // Note: typeid().name() is not threadsafe, so if the project needs to access it in multiple threads - // simultaneously, it'll need a mutex. - #if defined(_CPPRTTI) && defined(MEM_DEBUG_CLASSNAME) - #define MEM_ALLOC_CREDIT_CLASS() MEM_ALLOC_CREDIT_( typeid(*this).name() ) - #define MEM_ALLOC_CLASSNAME(type) (typeid((type*)(0)).name()) - #else - #define MEM_ALLOC_CREDIT_CLASS() MEM_ALLOC_CREDIT_( __FILE__ ) - #define MEM_ALLOC_CLASSNAME(type) (__FILE__) - #endif - - // MEM_ALLOC_CREDIT_FUNCTION is used when no this pointer is available ( inside 'new' overloads, for example ) - #ifdef _MSC_VER - #define MEM_ALLOC_CREDIT_FUNCTION() MEM_ALLOC_CREDIT_( __FUNCTION__ ) - #else - #define MEM_ALLOC_CREDIT_FUNCTION() (__FILE__) - #endif - - #pragma warning(pop) -#else - #define MEM_ALLOC_CREDIT_CLASS() - #define MEM_ALLOC_CLASSNAME(type) NULL - #define MEM_ALLOC_CREDIT_FUNCTION() -#endif - -//----------------------------------------------------------------------------- - -#if (defined(_DEBUG) || defined(USE_MEM_DEBUG)) -struct MemAllocFileLine_t -{ - const char *pszFile; - int line; -}; - -#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag ) \ - static CUtlMap g_##tag##Allocs( DefLessFunc( void *) ); \ - static const char *g_psz##tag##Alloc = strcpy( (char *)g_pMemAlloc->Alloc( strlen( #tag "Alloc" ) + 1, "intentional leak", 0 ), #tag "Alloc" ); - -#define MemAlloc_RegisterExternalAllocation( tag, p, size ) \ - if ( !p ) \ - ; \ - else \ - { \ - MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \ - g_pMemAlloc->GetActualDbgInfo( fileLine.pszFile, fileLine.line ); \ - if ( fileLine.pszFile != g_psz##tag##Alloc ) \ - { \ - g_##tag##Allocs.Insert( p, fileLine ); \ - } \ - \ - MemAlloc_RegisterAllocation( fileLine.pszFile, fileLine.line, size, size, 0); \ - } - -#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) \ - if ( !p ) \ - ; \ - else \ - { \ - MemAllocFileLine_t fileLine = { g_psz##tag##Alloc, 0 }; \ - CUtlMap::IndexType_t iRecordedFileLine = g_##tag##Allocs.Find( p ); \ - if ( iRecordedFileLine != g_##tag##Allocs.InvalidIndex() ) \ - { \ - fileLine = g_##tag##Allocs[iRecordedFileLine]; \ - g_##tag##Allocs.RemoveAt( iRecordedFileLine ); \ - } \ - \ - MemAlloc_RegisterDeallocation( fileLine.pszFile, fileLine.line, size, size, 0); \ - } - -#else - -#define MEMALLOC_DEFINE_EXTERNAL_TRACKING( tag ) -#define MemAlloc_RegisterExternalAllocation( tag, p, size ) ((void)0) -#define MemAlloc_RegisterExternalDeallocation( tag, p, size ) ((void)0) - -#endif - -//----------------------------------------------------------------------------- - -#endif // !STEAM && !NO_MALLOC_OVERRIDE - -//----------------------------------------------------------------------------- - -#if !defined(STEAM) && defined(NO_MALLOC_OVERRIDE) - -#define MEM_ALLOC_CREDIT_(tag) ((void)0) -#define MEM_ALLOC_CREDIT() MEM_ALLOC_CREDIT_(__FILE__) -#define MEM_ALLOC_CREDIT_CLASS() -#define MEM_ALLOC_CLASSNAME(type) NULL - -#endif !STEAM && NO_MALLOC_OVERRIDE - -//----------------------------------------------------------------------------- - -#endif /* TIER0_MEMALLOC_H */ diff --git a/Resources/NetHook/tier0/memdbgoff.h b/Resources/NetHook/tier0/memdbgoff.h deleted file mode 100644 index 685e2001..00000000 --- a/Resources/NetHook/tier0/memdbgoff.h +++ /dev/null @@ -1,25 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: This header, which must be the final line of a .h file, -// causes all crt methods to stop using debugging versions of the memory allocators. -// NOTE: Use memdbgon.h to re-enable memory debugging. -// -// $NoKeywords: $ -//=============================================================================// - -#ifdef MEM_OVERRIDE_ON - -#undef malloc -#undef realloc -#undef calloc -#undef free -#undef _expand -#undef _msize -#undef new -#undef _aligned_malloc -#undef _aligned_free -#undef _malloc_dbg - -#undef MEM_OVERRIDE_ON - -#endif diff --git a/Resources/NetHook/tier0/memdbgon.h b/Resources/NetHook/tier0/memdbgon.h deleted file mode 100644 index 59ad4675..00000000 --- a/Resources/NetHook/tier0/memdbgon.h +++ /dev/null @@ -1,243 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: This header, which must be the final include in a .cpp (or .h) file, -// causes all crt methods to use debugging versions of the memory allocators. -// NOTE: Use memdbgoff.h to disable memory debugging. -// -// $NoKeywords: $ -//=============================================================================// - -// SPECIAL NOTE! This file must *not* use include guards; we need to be able -// to include this potentially multiple times (since we can deactivate debugging -// by including memdbgoff.h) - -#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE) - -// SPECIAL NOTE #2: This must be the final include in a .cpp or .h file!!! - -#if defined(_DEBUG) && !defined(USE_MEM_DEBUG) -#define USE_MEM_DEBUG 1 -#endif - -// If debug build or ndebug and not already included MS custom alloc files, or already included this file -#if (defined(_DEBUG) || !defined(_INC_CRTDBG)) || defined(MEMDBGON_H) - -#include "basetypes.h" -#ifdef _WIN32 -#include -#else -#include -#endif -#include -#include -#include "commonmacros.h" -#include "memalloc.h" - -#if defined(USE_MEM_DEBUG) - #if defined(_LINUX) - - #define _NORMAL_BLOCK 1 - - #include - #include - #include - #include - - #if !defined( DID_THE_OPERATOR_NEW ) - #define DID_THE_OPERATOR_NEW - inline void* operator new( size_t nSize, int blah, const char *pFileName, int nLine ) - { - return g_pMemAlloc->Alloc( nSize, pFileName, nLine ); - } - inline void* operator new[]( size_t nSize, int blah, const char *pFileName, int nLine ) - { - return g_pMemAlloc->Alloc( nSize, pFileName, nLine ); - } - #endif - - #else // defined(_LINUX) - - // Include crtdbg.h and make sure _DEBUG is set to 1. - #if !defined(_DEBUG) - #define _DEBUG 1 - #include - #undef _DEBUG - #else - #include - #endif // !defined(_DEBUG) - - #endif // defined(_LINUX) -#endif - -#include "tier0/memdbgoff.h" - -// -------------------------------------------------------- -// Debug/non-debug agnostic elements - -#define MEM_OVERRIDE_ON 1 - -#undef malloc -#undef realloc -#undef calloc -#undef _expand -#undef free -#undef _msize -#undef _aligned_malloc -#undef _aligned_free - -#ifndef MEMDBGON_H -inline void *MemAlloc_InlineCallocMemset( void *pMem, size_t nCount, size_t nElementSize) -{ - memset(pMem, 0, nElementSize * nCount); - return pMem; -} -#endif - -#define calloc(c, s) MemAlloc_InlineCallocMemset(malloc(c*s), c, s) -#define free(p) g_pMemAlloc->Free( p ) -#define _msize(p) g_pMemAlloc->GetSize( p ) -#define _expand(p, s) _expand_NoLongerSupported(p, s) -#define _aligned_free( p ) MemAlloc_FreeAligned( p ) - -// -------------------------------------------------------- -// Debug path -#if defined(USE_MEM_DEBUG) - -#define malloc(s) g_pMemAlloc->Alloc( s, __FILE__, __LINE__) -#define realloc(p, s) g_pMemAlloc->Realloc( p, s, __FILE__, __LINE__ ) -#define _aligned_malloc( s, a ) MemAlloc_AllocAligned( s, a, __FILE__, __LINE__ ) - -#define _malloc_dbg(s, t, f, l) WHYCALLINGTHISDIRECTLY(s) - -#if defined(__AFX_H__) && defined(DEBUG_NEW) - #define new DEBUG_NEW -#else - #undef new - #define MEMALL_DEBUG_NEW new(_NORMAL_BLOCK, __FILE__, __LINE__) - #define new MEMALL_DEBUG_NEW -#endif - -#undef _strdup -#undef strdup -#undef _wcsdup -#undef wcsdup - -#define _strdup(s) MemAlloc_StrDup(s, __FILE__, __LINE__) -#define strdup(s) MemAlloc_StrDup(s, __FILE__, __LINE__) -#define _wcsdup(s) MemAlloc_WcStrDup(s, __FILE__, __LINE__) -#define wcsdup(s) MemAlloc_WcStrDup(s, __FILE__, __LINE__) - -// Make sure we don't define strdup twice -#if !defined(MEMDBGON_H) - -inline char *MemAlloc_StrDup(const char *pString, const char *pFileName, unsigned nLine) -{ - char *pMemory; - - if (!pString) - return NULL; - - size_t len = strlen(pString) + 1; - if ((pMemory = (char *)g_pMemAlloc->Alloc(len, pFileName, nLine)) != NULL) - { - return strcpy( pMemory, pString ); - } - - return NULL; -} - -inline wchar_t *MemAlloc_WcStrDup(const wchar_t *pString, const char *pFileName, unsigned nLine) -{ - wchar_t *pMemory; - - if (!pString) - return NULL; - - size_t len = (wcslen(pString) + 1); - if ((pMemory = (wchar_t *)g_pMemAlloc->Alloc(len * sizeof(wchar_t), pFileName, nLine)) != NULL) - { - return wcscpy( pMemory, pString ); - } - - return NULL; -} - -#endif // DBMEM_DEFINED_STRDUP - -#else -// -------------------------------------------------------- -// Release path - -#define malloc(s) g_pMemAlloc->Alloc( s ) -#define realloc(p, s) g_pMemAlloc->Realloc( p, s ) -#define _aligned_malloc( s, a ) MemAlloc_AllocAligned( s, a ) - -#ifndef _malloc_dbg -#define _malloc_dbg(s, t, f, l) WHYCALLINGTHISDIRECTLY(s) -#endif - -#undef new - -#undef _strdup -#undef strdup -#undef _wcsdup -#undef wcsdup - -#define _strdup(s) MemAlloc_StrDup(s) -#define strdup(s) MemAlloc_StrDup(s) -#define _wcsdup(s) MemAlloc_WcStrDup(s) -#define wcsdup(s) MemAlloc_WcStrDup(s) - -// Make sure we don't define strdup twice -#if !defined(MEMDBGON_H) - -inline char *MemAlloc_StrDup(const char *pString) -{ - char *pMemory; - - if (!pString) - return NULL; - - size_t len = strlen(pString) + 1; - if ((pMemory = (char *)g_pMemAlloc->Alloc(len)) != NULL) - { - return strcpy( pMemory, pString ); - } - - return NULL; -} - -inline wchar_t *MemAlloc_WcStrDup(const wchar_t *pString) -{ - wchar_t *pMemory; - - if (!pString) - return NULL; - - size_t len = (wcslen(pString) + 1); - if ((pMemory = (wchar_t *)g_pMemAlloc->Alloc(len * sizeof(wchar_t))) != NULL) - { - return wcscpy( pMemory, pString ); - } - - return NULL; -} - -#endif // DBMEM_DEFINED_STRDUP - -#endif // USE_MEM_DEBUG - -#define MEMDBGON_H // Defined here so can be used above - -#else - -#if defined(USE_MEM_DEBUG) -#ifndef _STATIC_LINKED -#pragma message ("Note: file includes crtdbg.h directly, therefore will cannot use memdbgon.h in non-debug build") -#else -#error "Error: file includes crtdbg.h directly, therefore will cannot use memdbgon.h in non-debug build. Not recoverable in static build" -#endif -#endif -#endif // _INC_CRTDBG - -#endif // !STEAM && !NO_MALLOC_OVERRIDE diff --git a/Resources/NetHook/tier0/memoverride.cpp b/Resources/NetHook/tier0/memoverride.cpp deleted file mode 100644 index 453ca48b..00000000 --- a/Resources/NetHook/tier0/memoverride.cpp +++ /dev/null @@ -1,1385 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Insert this file into all projects using the memory system -// It will cause that project to use the shader memory allocator -// -// $NoKeywords: $ -//=============================================================================// - - -#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE) - -#undef PROTECTED_THINGS_ENABLE // allow use of _vsnprintf - -#if defined( _WIN32 ) && !defined( _X360 ) -#define WIN_32_LEAN_AND_MEAN -#include -#endif - -#include "tier0/dbg.h" -#include "tier0/memalloc.h" -#include -#include -#include "memdbgoff.h" - -// Tags this DLL as debug -#if defined( _DEBUG ) && !defined( _X360 ) -DLL_EXPORT void BuiltDebug() {} -#endif - -#ifdef _WIN32 -// ARG: crtdbg is necessary for certain definitions below, -// but it also redefines malloc as a macro in release. -// To disable this, we gotta define _DEBUG before including it.. BLEAH! -#define _DEBUG 1 -#include "crtdbg.h" -#ifdef NDEBUG -#undef _DEBUG -#endif - -// Turn this back off in release mode. -#ifdef NDEBUG -#undef _DEBUG -#endif -#elif _LINUX -#define __cdecl -#endif - -#if defined( _WIN32 ) && !defined( _X360 ) -const char *MakeModuleFileName() -{ - if ( g_pMemAlloc->IsDebugHeap() ) - { - char *pszModuleName = (char *)HeapAlloc( GetProcessHeap(), 0, MAX_PATH ); // small leak, debug only - - MEMORY_BASIC_INFORMATION mbi; - static int dummy; - VirtualQuery( &dummy, &mbi, sizeof(mbi) ); - - GetModuleFileName( reinterpret_cast(mbi.AllocationBase), pszModuleName, MAX_PATH ); - char *pDot = strrchr( pszModuleName, '.' ); - if ( pDot ) - { - char *pSlash = strrchr( pszModuleName, '\\' ); - if ( pSlash ) - { - pszModuleName = pSlash + 1; - *pDot = 0; - } - } - - return pszModuleName; - } - return NULL; -} - -static void *AllocUnattributed( size_t nSize ) -{ - static const char *pszOwner = MakeModuleFileName(); - - if ( !pszOwner ) - return g_pMemAlloc->Alloc(nSize); - else - return g_pMemAlloc->Alloc(nSize, pszOwner, 0); -} - -static void *ReallocUnattributed( void *pMem, size_t nSize ) -{ - static const char *pszOwner = MakeModuleFileName(); - - if ( !pszOwner ) - return g_pMemAlloc->Realloc(pMem, nSize); - else - return g_pMemAlloc->Realloc(pMem, nSize, pszOwner, 0); -} - -#else -#define MakeModuleFileName() NULL -inline void *AllocUnattributed( size_t nSize ) -{ - return g_pMemAlloc->Alloc(nSize); -} - -inline void *ReallocUnattributed( void *pMem, size_t nSize ) -{ - return g_pMemAlloc->Realloc(pMem, nSize); -} -#endif - -//----------------------------------------------------------------------------- -// Standard functions in the CRT that we're going to override to call our allocator -//----------------------------------------------------------------------------- -#if defined(_WIN32) && !defined(_STATIC_LINKED) -// this magic only works under win32 -// under linux this malloc() overrides the libc malloc() and so we -// end up in a recursion (as g_pMemAlloc->Alloc() calls malloc) -#if _MSC_VER >= 1400 -#define ALLOC_CALL _CRTNOALIAS _CRTRESTRICT -#define FREE_CALL _CRTNOALIAS -#else -#define ALLOC_CALL -#define FREE_CALL -#endif - -extern "C" -{ - -ALLOC_CALL void *malloc( size_t nSize ) -{ - return AllocUnattributed( nSize ); -} - -FREE_CALL void free( void *pMem ) -{ - g_pMemAlloc->Free(pMem); -} - -ALLOC_CALL void *realloc( void *pMem, size_t nSize ) -{ - return ReallocUnattributed( pMem, nSize ); -} - -ALLOC_CALL void *calloc( size_t nCount, size_t nElementSize ) -{ - void *pMem = AllocUnattributed( nElementSize * nCount ); - memset(pMem, 0, nElementSize * nCount); - return pMem; -} - -} // end extern "C" - -//----------------------------------------------------------------------------- -// Non-standard MSVC functions that we're going to override to call our allocator -//----------------------------------------------------------------------------- -extern "C" -{ - -// 64-bit -#ifdef _WIN64 -void* __cdecl _malloc_base( size_t nSize ) -{ - return AllocUnattributed( nSize ); -} -#else -void *_malloc_base( size_t nSize ) -{ - return AllocUnattributed( nSize ); -} -#endif - -void *_calloc_base( size_t nSize ) -{ - void *pMem = AllocUnattributed( nSize ); - memset(pMem, 0, nSize); - return pMem; -} - -void *_realloc_base( void *pMem, size_t nSize ) -{ - return ReallocUnattributed( pMem, nSize ); -} - -void *_recalloc_base( void *pMem, size_t nSize ) -{ - void *pMemOut = ReallocUnattributed( pMem, nSize ); - memset(pMemOut, 0, nSize); - return pMemOut; -} - -void _free_base( void *pMem ) -{ - g_pMemAlloc->Free(pMem); -} - -void *__cdecl _expand_base( void *pMem, size_t nNewSize, int nBlockUse ) -{ - Assert( 0 ); - return NULL; -} - -// crt -void * __cdecl _malloc_crt(size_t size) -{ - return AllocUnattributed( size ); -} - -void * __cdecl _calloc_crt(size_t count, size_t size) -{ - return _calloc_base( count * size ); -} - -void * __cdecl _realloc_crt(void *ptr, size_t size) -{ - return _realloc_base( ptr, size ); -} - -void * __cdecl _recalloc_crt(void *ptr, size_t count, size_t size) -{ - return _recalloc_base( ptr, size * count ); -} - -ALLOC_CALL void * __cdecl _recalloc ( void * memblock, size_t count, size_t size ) -{ - void *pMem = ReallocUnattributed( memblock, size * count ); - memset( pMem, 0, size * count ); - return pMem; -} - -size_t _msize_base( void *pMem ) -{ - return g_pMemAlloc->GetSize(pMem); -} - -size_t _msize( void *pMem ) -{ - return _msize_base(pMem); -} - -size_t msize( void *pMem ) -{ - return g_pMemAlloc->GetSize(pMem); -} - -void *__cdecl _heap_alloc( size_t nSize ) -{ - return AllocUnattributed( nSize ); -} - -void *__cdecl _nh_malloc( size_t nSize, int ) -{ - return AllocUnattributed( nSize ); -} - -void *__cdecl _expand( void *pMem, size_t nSize ) -{ - Assert( 0 ); - return NULL; -} - -unsigned int _amblksiz = 16; //BYTES_PER_PARA; - -#if _MSC_VER >= 1400 -HANDLE _crtheap = (HANDLE)1; // PatM Can't be 0 or CRT pukes -int __active_heap = 1; -#endif // _MSC_VER >= 1400 - -size_t __cdecl _get_sbh_threshold( void ) -{ - return 0; -} - -int __cdecl _set_sbh_threshold( size_t ) -{ - return 0; -} - -int _heapchk() -{ - return g_pMemAlloc->heapchk(); -} - -int _heapmin() -{ - return 1; -} - -int __cdecl _heapadd( void *, size_t ) -{ - return 0; -} - -int __cdecl _heapset( unsigned int ) -{ - return 0; -} - -size_t __cdecl _heapused( size_t *, size_t * ) -{ - return 0; -} - -#ifdef _WIN32 -int __cdecl _heapwalk( _HEAPINFO * ) -{ - return 0; -} -#endif - -} // end extern "C" - - -//----------------------------------------------------------------------------- -// Debugging functions that we're going to override to call our allocator -// NOTE: These have to be here for release + debug builds in case we -// link to a debug static lib!!! -//----------------------------------------------------------------------------- - -extern "C" -{ - -void *malloc_db( size_t nSize, const char *pFileName, int nLine ) -{ - return g_pMemAlloc->Alloc(nSize, pFileName, nLine); -} - -void free_db( void *pMem, const char *pFileName, int nLine ) -{ - g_pMemAlloc->Free(pMem, pFileName, nLine); -} - -void *realloc_db( void *pMem, size_t nSize, const char *pFileName, int nLine ) -{ - return g_pMemAlloc->Realloc(pMem, nSize, pFileName, nLine); -} - -} // end extern "C" - -//----------------------------------------------------------------------------- -// These methods are standard MSVC heap initialization + shutdown methods -//----------------------------------------------------------------------------- -extern "C" -{ - -#if !defined( _X360 ) - int __cdecl _heap_init() - { - return g_pMemAlloc != NULL; - } - - void __cdecl _heap_term() - { - } -#endif - -} -#endif - - -//----------------------------------------------------------------------------- -// Prevents us from using an inappropriate new or delete method, -// ensures they are here even when linking against debug or release static libs -//----------------------------------------------------------------------------- -#ifndef NO_MEMOVERRIDE_NEW_DELETE -void *__cdecl operator new( unsigned int nSize ) -{ - return AllocUnattributed( nSize ); -} - -void *__cdecl operator new( unsigned int nSize, int nBlockUse, const char *pFileName, int nLine ) -{ - return g_pMemAlloc->Alloc(nSize, pFileName, nLine); -} - -void __cdecl operator delete( void *pMem ) -{ - g_pMemAlloc->Free( pMem ); -} - -void *__cdecl operator new[] ( unsigned int nSize ) -{ - return AllocUnattributed( nSize ); -} - -void *__cdecl operator new[] ( unsigned int nSize, int nBlockUse, const char *pFileName, int nLine ) -{ - return g_pMemAlloc->Alloc(nSize, pFileName, nLine); -} - -void __cdecl operator delete[] ( void *pMem ) -{ - g_pMemAlloc->Free( pMem ); -} -#endif - - -//----------------------------------------------------------------------------- -// Override some debugging allocation methods in MSVC -// NOTE: These have to be here for release + debug builds in case we -// link to a debug static lib!!! -//----------------------------------------------------------------------------- -#ifndef _STATIC_LINKED -#ifdef _WIN32 - -// This here just hides the internal file names, etc of allocations -// made in the c runtime library -#define CRT_INTERNAL_FILE_NAME "C-runtime internal" - -class CAttibCRT -{ -public: - CAttibCRT(int nBlockUse) : m_nBlockUse(nBlockUse) - { - if (m_nBlockUse == _CRT_BLOCK) - { - g_pMemAlloc->PushAllocDbgInfo(CRT_INTERNAL_FILE_NAME, 0); - } - } - - ~CAttibCRT() - { - if (m_nBlockUse == _CRT_BLOCK) - { - g_pMemAlloc->PopAllocDbgInfo(); - } - } - -private: - int m_nBlockUse; -}; - - -#define AttribIfCrt() CAttibCRT _attrib(nBlockUse) -#elif defined(_LINUX) -#define AttribIfCrt() -#endif // _WIN32 - - -extern "C" -{ - -void *__cdecl _nh_malloc_dbg( size_t nSize, int nFlag, int nBlockUse, - const char *pFileName, int nLine ) -{ - AttribIfCrt(); - return g_pMemAlloc->Alloc(nSize, pFileName, nLine); -} - -void *__cdecl _malloc_dbg( size_t nSize, int nBlockUse, - const char *pFileName, int nLine ) -{ - AttribIfCrt(); - return g_pMemAlloc->Alloc(nSize, pFileName, nLine); -} - -void *__cdecl _calloc_dbg( size_t nNum, size_t nSize, int nBlockUse, - const char *pFileName, int nLine ) -{ - AttribIfCrt(); - void *pMem = g_pMemAlloc->Alloc(nSize * nNum, pFileName, nLine); - memset(pMem, 0, nSize * nNum); - return pMem; -} - -void *__cdecl _realloc_dbg( void *pMem, size_t nNewSize, int nBlockUse, - const char *pFileName, int nLine ) -{ - AttribIfCrt(); - return g_pMemAlloc->Realloc(pMem, nNewSize, pFileName, nLine); -} - -void *__cdecl _expand_dbg( void *pMem, size_t nNewSize, int nBlockUse, - const char *pFileName, int nLine ) -{ - Assert( 0 ); - return NULL; -} - -void __cdecl _free_dbg( void *pMem, int nBlockUse ) -{ - AttribIfCrt(); - g_pMemAlloc->Free(pMem); -} - -size_t __cdecl _msize_dbg( void *pMem, int nBlockUse ) -{ -#ifdef _WIN32 - return _msize(pMem); -#elif _LINUX - Assert( "_msize_dbg unsupported" ); - return 0; -#endif -} - - -#ifdef _WIN32 - -#if defined(_DEBUG) && _MSC_VER >= 1300 -// X360TBD: aligned and offset allocations may be important on the 360 - -// aligned base -ALLOC_CALL void *__cdecl _aligned_malloc_base( size_t size, size_t align ) -{ - return MemAlloc_AllocAligned( size, align ); -} - -ALLOC_CALL void *__cdecl _aligned_realloc_base( void *ptr, size_t size, size_t align ) -{ - return MemAlloc_ReallocAligned( ptr, size, align ); -} - -ALLOC_CALL void *__cdecl _aligned_recalloc_base( void *ptr, size_t size, size_t align ) -{ - Error( "Unsupported function\n" ); - return NULL; -} - -FREE_CALL void __cdecl _aligned_free_base( void *ptr ) -{ - MemAlloc_FreeAligned( ptr ); -} - -// aligned -ALLOC_CALL void * __cdecl _aligned_malloc( size_t size, size_t align ) -{ - return _aligned_malloc_base(size, align); -} - -ALLOC_CALL void *__cdecl _aligned_realloc(void *memblock, size_t size, size_t align) -{ - return _aligned_realloc_base(memblock, size, align); -} - -ALLOC_CALL void * __cdecl _aligned_recalloc( void * memblock, size_t count, size_t size, size_t align ) -{ - return _aligned_recalloc_base(memblock, count * size, align); -} - -FREE_CALL void __cdecl _aligned_free( void *memblock ) -{ - _aligned_free_base(memblock); -} - -// aligned offset base -ALLOC_CALL void * __cdecl _aligned_offset_malloc_base( size_t size, size_t align, size_t offset ) -{ - Assert( IsPC() || 0 ); - return NULL; -} - -ALLOC_CALL void * __cdecl _aligned_offset_realloc_base( void * memblock, size_t size, size_t align, size_t offset) -{ - Assert( IsPC() || 0 ); - return NULL; -} - -ALLOC_CALL void * __cdecl _aligned_offset_recalloc_base( void * memblock, size_t size, size_t align, size_t offset) -{ - Assert( IsPC() || 0 ); - return NULL; -} - -// aligned offset -ALLOC_CALL void *__cdecl _aligned_offset_malloc(size_t size, size_t align, size_t offset) -{ - return _aligned_offset_malloc_base( size, align, offset ); -} - -ALLOC_CALL void *__cdecl _aligned_offset_realloc(void *memblock, size_t size, size_t align, size_t offset) -{ - return _aligned_offset_realloc_base( memblock, size, align, offset ); -} - -ALLOC_CALL void * __cdecl _aligned_offset_recalloc( void * memblock, size_t count, size_t size, size_t align, size_t offset ) -{ - return _aligned_offset_recalloc_base( memblock, count * size, align, offset ); -} - -#endif // _MSC_VER >= 1400 - -#endif - -} // end extern "C" - - -//----------------------------------------------------------------------------- -// Override some the _CRT debugging allocation methods in MSVC -//----------------------------------------------------------------------------- -#ifdef _WIN32 - -extern "C" -{ - -int _CrtDumpMemoryLeaks(void) -{ - return 0; -} - -_CRT_DUMP_CLIENT _CrtSetDumpClient( _CRT_DUMP_CLIENT dumpClient ) -{ - return NULL; -} - -int _CrtSetDbgFlag( int nNewFlag ) -{ - return g_pMemAlloc->CrtSetDbgFlag( nNewFlag ); -} - -// 64-bit port. -#define AFNAME(var) __p_ ## var -#define AFRET(var) &var - -int _crtDbgFlag = _CRTDBG_ALLOC_MEM_DF; -int* AFNAME(_crtDbgFlag)(void) -{ - return AFRET(_crtDbgFlag); -} - -long _crtBreakAlloc; /* Break on this allocation */ -long* AFNAME(_crtBreakAlloc) (void) -{ - return AFRET(_crtBreakAlloc); -} - -void __cdecl _CrtSetDbgBlockType( void *pMem, int nBlockUse ) -{ - DebuggerBreak(); -} - -_CRT_ALLOC_HOOK __cdecl _CrtSetAllocHook( _CRT_ALLOC_HOOK pfnNewHook ) -{ - DebuggerBreak(); - return NULL; -} - -long __cdecl _CrtSetBreakAlloc( long lNewBreakAlloc ) -{ - return g_pMemAlloc->CrtSetBreakAlloc( lNewBreakAlloc ); -} - -int __cdecl _CrtIsValidHeapPointer( const void *pMem ) -{ - return g_pMemAlloc->CrtIsValidHeapPointer( pMem ); -} - -int __cdecl _CrtIsValidPointer( const void *pMem, unsigned int size, int access ) -{ - return g_pMemAlloc->CrtIsValidPointer( pMem, size, access ); -} - -int __cdecl _CrtCheckMemory( void ) -{ - // FIXME: Remove this when we re-implement the heap - return g_pMemAlloc->CrtCheckMemory( ); -} - -int __cdecl _CrtIsMemoryBlock( const void *pMem, unsigned int nSize, - long *plRequestNumber, char **ppFileName, int *pnLine ) -{ - DebuggerBreak(); - return 1; -} - -int __cdecl _CrtMemDifference( _CrtMemState *pState, const _CrtMemState * oldState, const _CrtMemState * newState ) -{ - DebuggerBreak(); - return FALSE; -} - -void __cdecl _CrtMemDumpStatistics( const _CrtMemState *pState ) -{ - DebuggerBreak(); -} - -void __cdecl _CrtMemCheckpoint( _CrtMemState *pState ) -{ - // FIXME: Remove this when we re-implement the heap - g_pMemAlloc->CrtMemCheckpoint( pState ); -} - -void __cdecl _CrtMemDumpAllObjectsSince( const _CrtMemState *pState ) -{ - DebuggerBreak(); -} - -void __cdecl _CrtDoForAllClientObjects( void (*pfn)(void *, void *), void * pContext ) -{ - DebuggerBreak(); -} - - -//----------------------------------------------------------------------------- -// Methods in dbgrpt.cpp -//----------------------------------------------------------------------------- -long _crtAssertBusy = -1; - -int __cdecl _CrtSetReportMode( int nReportType, int nReportMode ) -{ - return g_pMemAlloc->CrtSetReportMode( nReportType, nReportMode ); -} - -_HFILE __cdecl _CrtSetReportFile( int nRptType, _HFILE hFile ) -{ - return (_HFILE)g_pMemAlloc->CrtSetReportFile( nRptType, hFile ); -} - -_CRT_REPORT_HOOK __cdecl _CrtSetReportHook( _CRT_REPORT_HOOK pfnNewHook ) -{ - return (_CRT_REPORT_HOOK)g_pMemAlloc->CrtSetReportHook( pfnNewHook ); -} - -int __cdecl _CrtDbgReport( int nRptType, const char * szFile, - int nLine, const char * szModule, const char * szFormat, ... ) -{ - static char output[1024]; - va_list args; - va_start( args, szFormat ); - _vsnprintf( output, sizeof( output )-1, szFormat, args ); - va_end( args ); - - return g_pMemAlloc->CrtDbgReport( nRptType, szFile, nLine, szModule, output ); -} - -#if _MSC_VER >= 1400 - -#if defined( _DEBUG ) - -// wrapper which passes no debug info; not available in debug -void __cdecl _invalid_parameter_noinfo(void) -{ - Assert(0); -} - -#endif /* defined( _DEBUG ) */ - -#if defined( _DEBUG ) || defined( USE_MEM_DEBUG ) - -int __cdecl __crtMessageWindowW( int nRptType, const wchar_t * szFile, const wchar_t * szLine, - const wchar_t * szModule, const wchar_t * szUserMessage ) -{ - Assert(0); - return 0; -} - -int __cdecl _CrtDbgReportV( int nRptType, const wchar_t *szFile, int nLine, - const wchar_t *szModule, const wchar_t *szFormat, va_list arglist ) -{ - Assert(0); - return 0; -} - -int __cdecl _CrtDbgReportW( int nRptType, const wchar_t *szFile, int nLine, - const wchar_t *szModule, const wchar_t *szFormat, ...) -{ - Assert(0); - return 0; -} - -int __cdecl _VCrtDbgReportA( int nRptType, const wchar_t * szFile, int nLine, - const wchar_t * szModule, const wchar_t * szFormat, va_list arglist ) -{ - Assert(0); - return 0; -} - -int __cdecl _CrtSetReportHook2( int mode, _CRT_REPORT_HOOK pfnNewHook ) -{ - _CrtSetReportHook( pfnNewHook ); - return 0; -} - - -#endif /* defined( _DEBUG ) || defined( USE_MEM_DEBUG ) */ - -extern "C" int __crtDebugCheckCount = FALSE; - -extern "C" int __cdecl _CrtSetCheckCount( int fCheckCount ) -{ - int oldCheckCount = __crtDebugCheckCount; - return oldCheckCount; -} - -extern "C" int __cdecl _CrtGetCheckCount( void ) -{ - return __crtDebugCheckCount; -} - -// aligned offset debug -extern "C" void * __cdecl _aligned_offset_recalloc_dbg( void * memblock, size_t count, size_t size, size_t align, size_t offset, const char * f_name, int line_n ) -{ - Assert( IsPC() || 0 ); - void *pMem = ReallocUnattributed( memblock, size * count ); - memset( pMem, 0, size * count ); - return pMem; -} - -extern "C" void * __cdecl _aligned_recalloc_dbg( void *memblock, size_t count, size_t size, size_t align, const char * f_name, int line_n ) -{ - return _aligned_offset_recalloc_dbg(memblock, count, size, align, 0, f_name, line_n); -} - -extern "C" void * __cdecl _recalloc_dbg ( void * memblock, size_t count, size_t size, int nBlockUse, const char * szFileName, int nLine ) -{ - return _aligned_offset_recalloc_dbg(memblock, count, size, 0, 0, szFileName, nLine); -} - -_CRT_REPORT_HOOK __cdecl _CrtGetReportHook( void ) -{ - return NULL; -} - -#endif -int __cdecl _CrtReportBlockType(const void * pUserData) -{ - return 0; -} - - -} // end extern "C" -#endif // _WIN32 - -// Most files include this file, so when it's used it adds an extra .ValveDbg section, -// to help identify debug binaries. -#ifdef _WIN32 - #ifndef NDEBUG // _DEBUG - #pragma data_seg("ValveDBG") - volatile const char* DBG = "*** DEBUG STUB ***"; - #endif -#endif - -#endif - -// Extras added prevent dbgheap.obj from being included - DAL -#ifdef _WIN32 - -extern "C" -{ -size_t __crtDebugFillThreshold = 0; - -extern "C" void * __cdecl _heap_alloc_base (size_t size) { - assert(0); - return NULL; -} - - -void * __cdecl _heap_alloc_dbg( size_t nSize, int nBlockUse, const char * szFileName, int nLine) -{ - return _heap_alloc(nSize); -} - -// 64-bit -#ifdef _WIN64 -static void * __cdecl realloc_help( void * pUserData, size_t * pnNewSize, int nBlockUse,const char * szFileName, - int nLine, int fRealloc ) -{ - assert(0); // Shouldn't be needed - return NULL; -} -#else -static void * __cdecl realloc_help( void * pUserData, size_t nNewSize, int nBlockUse, const char * szFileName, - int nLine, int fRealloc) -{ - assert(0); // Shouldn't be needed - return NULL; -} -#endif - -void __cdecl _free_nolock( void * pUserData) -{ - // I don't think the second param is used in memoverride - _free_dbg(pUserData, 0); -} - -void __cdecl _free_dbg_nolock( void * pUserData, int nBlockUse) -{ - _free_dbg(pUserData, 0); -} - -_CRT_ALLOC_HOOK __cdecl _CrtGetAllocHook ( void) -{ - assert(0); - return NULL; -} - -static int __cdecl CheckBytes( unsigned char * pb, unsigned char bCheck, size_t nSize) -{ - int bOkay = TRUE; - return bOkay; -} - - -_CRT_DUMP_CLIENT __cdecl _CrtGetDumpClient ( void) -{ - assert(0); - return NULL; -} - -#if _MSC_VER >= 1400 -static void __cdecl _printMemBlockData( _locale_t plocinfo, _CrtMemBlockHeader * pHead) -{ -} - -static void __cdecl _CrtMemDumpAllObjectsSince_stat( const _CrtMemState * state, _locale_t plocinfo) -{ -} -#endif -void * __cdecl _aligned_malloc_dbg( size_t size, size_t align, const char * f_name, int line_n) -{ - return _aligned_malloc(size, align); -} - -void * __cdecl _aligned_realloc_dbg( void *memblock, size_t size, size_t align, - const char * f_name, int line_n) -{ - return _aligned_realloc(memblock, size, align); -} - -void * __cdecl _aligned_offset_malloc_dbg( size_t size, size_t align, size_t offset, - const char * f_name, int line_n) -{ - return _aligned_offset_malloc(size, align, offset); -} - -void * __cdecl _aligned_offset_realloc_dbg( void * memblock, size_t size, size_t align, - size_t offset, const char * f_name, int line_n) -{ - return _aligned_offset_realloc(memblock, size, align, offset); -} - -void __cdecl _aligned_free_dbg( void * memblock) -{ - _aligned_free(memblock); -} - -size_t __cdecl _CrtSetDebugFillThreshold( size_t _NewDebugFillThreshold) -{ - assert(0); - return 0; -} - -//=========================================== -// NEW!!! 64-bit - -char * __cdecl _strdup ( const char * string ) -{ - int nSize = strlen(string) + 1; - char *pCopy = (char*)AllocUnattributed( nSize ); - if ( pCopy ) - memcpy( pCopy, string, nSize ); - return pCopy; -} - -#if 0 -_TSCHAR * __cdecl _tfullpath_dbg ( _TSCHAR *UserBuf, const _TSCHAR *path, size_t maxlen, int nBlockUse, const char * szFileName, int nLine ) -{ - Assert(0); - return NULL; -} - -_TSCHAR * __cdecl _tfullpath ( _TSCHAR *UserBuf, const _TSCHAR *path, size_t maxlen ) -{ - Assert(0); - return NULL; -} - -_TSCHAR * __cdecl _tgetdcwd_lk_dbg ( int drive, _TSCHAR *pnbuf, int maxlen, int nBlockUse, const char * szFileName, int nLine ) -{ - Assert(0); - return NULL; -} - -_TSCHAR * __cdecl _tgetdcwd_nolock ( int drive, _TSCHAR *pnbuf, int maxlen ) -{ - Assert(0); - return NULL; -} - -errno_t __cdecl _tdupenv_s_helper ( _TSCHAR **pBuffer, size_t *pBufferSizeInTChars, const _TSCHAR *varname, int nBlockUse, const char * szFileName, int nLine ) -{ - Assert(0); - return 0; -} - -errno_t __cdecl _tdupenv_s_helper ( _TSCHAR **pBuffer, size_t *pBufferSizeInTChars, const _TSCHAR *varname ) -{ - Assert(0); - return 0; -} - -_TSCHAR * __cdecl _ttempnam_dbg ( const _TSCHAR *dir, const _TSCHAR *pfx, int nBlockUse, const char * szFileName, int nLine ) -{ - Assert(0); - return 0; -} - -_TSCHAR * __cdecl _ttempnam ( const _TSCHAR *dir, const _TSCHAR *pfx ) -{ - Assert(0); - return 0; -} -#endif - -wchar_t * __cdecl _wcsdup_dbg ( const wchar_t * string, int nBlockUse, const char * szFileName, int nLine ) -{ - Assert(0); - return 0; -} - -wchar_t * __cdecl _wcsdup ( const wchar_t * string ) -{ - Assert(0); - return 0; -} - -} // end extern "C" - -#if _MSC_VER >= 1400 - -//----------------------------------------------------------------------------- -// XBox Memory Allocator Override -//----------------------------------------------------------------------------- -#if defined( _X360 ) -#if defined( _DEBUG ) || defined( USE_MEM_DEBUG ) -#include "UtlMap.h" - -MEMALLOC_DEFINE_EXTERNAL_TRACKING( XMem ); - -CThreadFastMutex g_XMemAllocMutex; - -void XMemAlloc_RegisterAllocation( void *p, DWORD dwAllocAttributes ) -{ - if ( !g_pMemAlloc ) - { - // core xallocs cannot be journaled until system is ready - return; - } - - AUTO_LOCK_FM( g_XMemAllocMutex ); - int size = XMemSize( p, dwAllocAttributes ); - MemAlloc_RegisterExternalAllocation( XMem, p, size ); -} - -void XMemAlloc_RegisterDeallocation( void *p, DWORD dwAllocAttributes ) -{ - if ( !g_pMemAlloc ) - { - // core xallocs cannot be journaled until system is ready - return; - } - - AUTO_LOCK_FM( g_XMemAllocMutex ); - int size = XMemSize( p, dwAllocAttributes ); - MemAlloc_RegisterExternalDeallocation( XMem, p, size ); -} - -#else - -#define XMemAlloc_RegisterAllocation( p, a ) ((void)0) -#define XMemAlloc_RegisterDeallocation( p, a ) ((void)0) - -#endif - -//----------------------------------------------------------------------------- -// XMemAlloc -// -// XBox Memory Allocator Override -//----------------------------------------------------------------------------- -LPVOID WINAPI XMemAlloc( SIZE_T dwSize, DWORD dwAllocAttributes ) -{ - LPVOID ptr; - XALLOC_ATTRIBUTES *pAttribs = (XALLOC_ATTRIBUTES *)&dwAllocAttributes; - bool bPhysical = ( pAttribs->dwMemoryType == XALLOC_MEMTYPE_PHYSICAL ); - - if ( !bPhysical && !pAttribs->dwHeapTracksAttributes && pAttribs->dwAllocatorId != eXALLOCAllocatorId_XUI ) - { - MEM_ALLOC_CREDIT(); - switch ( pAttribs->dwAlignment ) - { - case XALLOC_ALIGNMENT_4: - ptr = g_pMemAlloc->Alloc( dwSize ); - break; - case XALLOC_ALIGNMENT_8: - ptr = MemAlloc_AllocAligned( dwSize, 8 ); - break; - case XALLOC_ALIGNMENT_DEFAULT: - case XALLOC_ALIGNMENT_16: - default: - ptr = MemAlloc_AllocAligned( dwSize, 16 ); - break; - } - if ( pAttribs->dwZeroInitialize != 0 ) - { - memset( ptr, 0, XMemSize( ptr, dwAllocAttributes ) ); - } - return ptr; - } - - ptr = XMemAllocDefault( dwSize, dwAllocAttributes ); - if ( ptr ) - { - XMemAlloc_RegisterAllocation( ptr, dwAllocAttributes ); - } - - return ptr; -} - -//----------------------------------------------------------------------------- -// XMemFree -// -// XBox Memory Allocator Override -//----------------------------------------------------------------------------- -VOID WINAPI XMemFree( PVOID pAddress, DWORD dwAllocAttributes ) -{ - if ( !pAddress ) - { - return; - } - - XALLOC_ATTRIBUTES *pAttribs = (XALLOC_ATTRIBUTES *)&dwAllocAttributes; - bool bPhysical = ( pAttribs->dwMemoryType == XALLOC_MEMTYPE_PHYSICAL ); - - if ( !bPhysical && !pAttribs->dwHeapTracksAttributes && pAttribs->dwAllocatorId != eXALLOCAllocatorId_XUI ) - { - switch ( pAttribs->dwAlignment ) - { - case XALLOC_ALIGNMENT_4: - return g_pMemAlloc->Free( pAddress ); - default: - return MemAlloc_FreeAligned( pAddress ); - } - return; - } - - XMemAlloc_RegisterDeallocation( pAddress, dwAllocAttributes ); - - XMemFreeDefault( pAddress, dwAllocAttributes ); -} - -//----------------------------------------------------------------------------- -// XMemSize -// -// XBox Memory Allocator Override -//----------------------------------------------------------------------------- -SIZE_T WINAPI XMemSize( PVOID pAddress, DWORD dwAllocAttributes ) -{ - XALLOC_ATTRIBUTES *pAttribs = (XALLOC_ATTRIBUTES *)&dwAllocAttributes; - bool bPhysical = ( pAttribs->dwMemoryType == XALLOC_MEMTYPE_PHYSICAL ); - - if ( !bPhysical && !pAttribs->dwHeapTracksAttributes && pAttribs->dwAllocatorId != eXALLOCAllocatorId_XUI ) - { - switch ( pAttribs->dwAlignment ) - { - case XALLOC_ALIGNMENT_4: - return g_pMemAlloc->GetSize( pAddress ); - default: - return MemAlloc_GetSizeAligned( pAddress ); - } - } - - return XMemSizeDefault( pAddress, dwAllocAttributes ); -} -#endif // _X360 - -#define MAX_LANG_LEN 64 /* max language name length */ -#define MAX_CTRY_LEN 64 /* max country name length */ -#define MAX_MODIFIER_LEN 0 /* max modifier name length - n/a */ -#define MAX_LC_LEN (MAX_LANG_LEN+MAX_CTRY_LEN+MAX_MODIFIER_LEN+3) - -struct _is_ctype_compatible { - unsigned long id; - int is_clike; -}; -typedef struct setloc_struct { - /* getqloc static variables */ - char *pchLanguage; - char *pchCountry; - int iLcidState; - int iPrimaryLen; - BOOL bAbbrevLanguage; - BOOL bAbbrevCountry; - LCID lcidLanguage; - LCID lcidCountry; - /* expand_locale static variables */ - LC_ID _cacheid; - UINT _cachecp; - char _cachein[MAX_LC_LEN]; - char _cacheout[MAX_LC_LEN]; - /* _setlocale_set_cat (LC_CTYPE) static variable */ - struct _is_ctype_compatible _Lcid_c[5]; -} _setloc_struct, *_psetloc_struct; - -struct _tiddata { - unsigned long _tid; /* thread ID */ - - - uintptr_t _thandle; /* thread handle */ - - int _terrno; /* errno value */ - unsigned long _tdoserrno; /* _doserrno value */ - unsigned int _fpds; /* Floating Point data segment */ - unsigned long _holdrand; /* rand() seed value */ - char * _token; /* ptr to strtok() token */ - wchar_t * _wtoken; /* ptr to wcstok() token */ - unsigned char * _mtoken; /* ptr to _mbstok() token */ - - /* following pointers get malloc'd at runtime */ - char * _errmsg; /* ptr to strerror()/_strerror() buff */ - wchar_t * _werrmsg; /* ptr to _wcserror()/__wcserror() buff */ - char * _namebuf0; /* ptr to tmpnam() buffer */ - wchar_t * _wnamebuf0; /* ptr to _wtmpnam() buffer */ - char * _namebuf1; /* ptr to tmpfile() buffer */ - wchar_t * _wnamebuf1; /* ptr to _wtmpfile() buffer */ - char * _asctimebuf; /* ptr to asctime() buffer */ - wchar_t * _wasctimebuf; /* ptr to _wasctime() buffer */ - void * _gmtimebuf; /* ptr to gmtime() structure */ - char * _cvtbuf; /* ptr to ecvt()/fcvt buffer */ - unsigned char _con_ch_buf[MB_LEN_MAX]; - /* ptr to putch() buffer */ - unsigned short _ch_buf_used; /* if the _con_ch_buf is used */ - - /* following fields are needed by _beginthread code */ - void * _initaddr; /* initial user thread address */ - void * _initarg; /* initial user thread argument */ - - /* following three fields are needed to support signal handling and - * runtime errors */ - void * _pxcptacttab; /* ptr to exception-action table */ - void * _tpxcptinfoptrs; /* ptr to exception info pointers */ - int _tfpecode; /* float point exception code */ - - /* pointer to the copy of the multibyte character information used by - * the thread */ - pthreadmbcinfo ptmbcinfo; - - /* pointer to the copy of the locale informaton used by the thead */ - pthreadlocinfo ptlocinfo; - int _ownlocale; /* if 1, this thread owns its own locale */ - - /* following field is needed by NLG routines */ - unsigned long _NLG_dwCode; - - /* - * Per-Thread data needed by C++ Exception Handling - */ - void * _terminate; /* terminate() routine */ - void * _unexpected; /* unexpected() routine */ - void * _translator; /* S.E. translator */ - void * _purecall; /* called when pure virtual happens */ - void * _curexception; /* current exception */ - void * _curcontext; /* current exception context */ - int _ProcessingThrow; /* for uncaught_exception */ - void * _curexcspec; /* for handling exceptions thrown from std::unexpected */ -#if defined (_M_IA64) || defined (_M_AMD64) - void * _pExitContext; - void * _pUnwindContext; - void * _pFrameInfoChain; - unsigned __int64 _ImageBase; -#if defined (_M_IA64) - unsigned __int64 _TargetGp; -#endif /* defined (_M_IA64) */ - unsigned __int64 _ThrowImageBase; - void * _pForeignException; -#elif defined (_M_IX86) - void * _pFrameInfoChain; -#endif /* defined (_M_IX86) */ - _setloc_struct _setloc_data; - - void * _encode_ptr; /* EncodePointer() routine */ - void * _decode_ptr; /* DecodePointer() routine */ - - void * _reserved1; /* nothing */ - void * _reserved2; /* nothing */ - void * _reserved3; /* nothing */ - - int _cxxReThrow; /* Set to True if it's a rethrown C++ Exception */ - - unsigned long __initDomain; /* initial domain used by _beginthread[ex] for managed function */ -}; - -typedef struct _tiddata * _ptiddata; - -class _LocaleUpdate -{ - _locale_tstruct localeinfo; - _ptiddata ptd; - bool updated; - public: - _LocaleUpdate(_locale_t plocinfo) - : updated(false) - { - /* - if (plocinfo == NULL) - { - ptd = _getptd(); - localeinfo.locinfo = ptd->ptlocinfo; - localeinfo.mbcinfo = ptd->ptmbcinfo; - - __UPDATE_LOCALE(ptd, localeinfo.locinfo); - __UPDATE_MBCP(ptd, localeinfo.mbcinfo); - if (!(ptd->_ownlocale & _PER_THREAD_LOCALE_BIT)) - { - ptd->_ownlocale |= _PER_THREAD_LOCALE_BIT; - updated = true; - } - } - else - { - localeinfo=*plocinfo; - } - */ - } - ~_LocaleUpdate() - { -// if (updated) -// ptd->_ownlocale = ptd->_ownlocale & ~_PER_THREAD_LOCALE_BIT; - } - _locale_t GetLocaleT() - { - return &localeinfo; - } -}; - - -#pragma warning(push) -#pragma warning(disable: 4483) -#if _MSC_FULL_VER >= 140050415 -#define _NATIVE_STARTUP_NAMESPACE __identifier("") -#else /* _MSC_FULL_VER >= 140050415 */ -#define _NATIVE_STARTUP_NAMESPACE __CrtImplementationDetails -#endif /* _MSC_FULL_VER >= 140050415 */ - -namespace _NATIVE_STARTUP_NAMESPACE -{ - class NativeDll - { - private: - static const unsigned int ProcessDetach = 0; - static const unsigned int ProcessAttach = 1; - static const unsigned int ThreadAttach = 2; - static const unsigned int ThreadDetach = 3; - static const unsigned int ProcessVerifier = 4; - - public: - - inline static bool IsInDllMain() - { - return false; - } - - inline static bool IsInProcessAttach() - { - return false; - } - - inline static bool IsInProcessDetach() - { - return false; - } - - inline static bool IsInVcclrit() - { - return false; - } - - inline static bool IsSafeForManagedCode() - { - if (!IsInDllMain()) - { - return true; - } - - if (IsInVcclrit()) - { - return true; - } - - return !IsInProcessAttach() && !IsInProcessDetach(); - } - }; -} -#pragma warning(pop) - -#endif // _MSC_VER >= 1400 - -#endif // !STEAM && !NO_MALLOC_OVERRIDE - -#endif // _WIN32 diff --git a/Resources/NetHook/tier0/minidump.h b/Resources/NetHook/tier0/minidump.h deleted file mode 100644 index fab59678..00000000 --- a/Resources/NetHook/tier0/minidump.h +++ /dev/null @@ -1,53 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#ifndef MINIDUMP_H -#define MINIDUMP_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/platform.h" - -// writes out a minidump of the current stack trace with a unique filename -PLATFORM_INTERFACE void WriteMiniDump(); - -typedef void (*FnWMain)( int , tchar *[] ); - -#if defined(_WIN32) && !defined(_X360) - -// calls the passed in function pointer and catches any exceptions/crashes thrown by it, and writes a minidump -// use from wmain() to protect the whole program - -PLATFORM_INTERFACE void CatchAndWriteMiniDump( FnWMain pfn, int argc, tchar *argv[] ); - -#include - -// Replaces the current function pointer with the one passed in. -// Returns the previously-set function. -// The function is called internally by WriteMiniDump() and CatchAndWriteMiniDump() -// The default is the built-in function that uses DbgHlp.dll's MiniDumpWriteDump function -typedef void (*FnMiniDump)( unsigned int uStructuredExceptionCode, _EXCEPTION_POINTERS * pExceptionInfo ); -PLATFORM_INTERFACE FnMiniDump SetMiniDumpFunction( FnMiniDump pfn ); - -// Use this to write a minidump explicitly. -// Some of the tools choose to catch the minidump themselves instead of using CatchAndWriteMinidump -// so they can show their own dialog. -// -// ptchMinidumpFileNameBuffer if not-NULL should be a writable tchar buffer of length at -// least _MAX_PATH and on return will contain the name of the minidump file written. -// If ptchMinidumpFileNameBuffer is NULL the name of the minidump file written will not -// be available after the function returns. -// -PLATFORM_INTERFACE bool WriteMiniDumpUsingExceptionInfo( - unsigned int uStructuredExceptionCode, - _EXCEPTION_POINTERS * pExceptionInfo, - MINIDUMP_TYPE minidumpType, - tchar *ptchMinidumpFileNameBuffer = NULL - ); -#endif - -#endif // MINIDUMP_H diff --git a/Resources/NetHook/tier0/platform.h b/Resources/NetHook/tier0/platform.h deleted file mode 100644 index 5640620a..00000000 --- a/Resources/NetHook/tier0/platform.h +++ /dev/null @@ -1,1168 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -// -//===========================================================================// - -#ifndef PLATFORM_H -#define PLATFORM_H - -#if defined( _X360 ) -#define NO_STEAM -#define NO_VOICE -// for the 360, the ppc platform and the rtos are tightly coupled -// setup the 360 environment here !once! for much less leaf module include wackiness -// these are critical order and purposely appear *before* anything else -#define _XBOX -#include -#include -#include -#include -#include -#include -#include -#undef _XBOX -#endif - -#include "wchartypes.h" -#include "basetypes.h" -#include "tier0/valve_off.h" - -#ifdef _WIN32 -#pragma once -#endif - -// feature enables -#define NEW_SOFTWARE_LIGHTING - -#ifdef _LINUX -// need this for _alloca -#include -#endif // _LINUX - -#include -#include - - -// need this for memset -#include - -#include "tier0/valve_minmax_on.h" // GCC 4.2.2 headers screw up our min/max defs. - -#ifdef _RETAIL -#define IsRetail() true -#else -#define IsRetail() false -#endif - -#ifdef _DEBUG -#define IsRelease() false -#define IsDebug() true -#else -#define IsRelease() true -#define IsDebug() false -#endif - -// Deprecating, infavor of IsX360() which will revert to IsXbox() -// after confidence of xbox 1 code flush -#define IsXbox() false - -#ifdef _WIN32 - #define IsLinux() false - #ifndef _X360 - #define IsPC() true - #define IsConsole() false - #define IsX360() false - #define IsPS3() false - #define IS_WINDOWS_PC - #else - #ifndef _CONSOLE - #define _CONSOLE - #endif - #define IsPC() false - #define IsConsole() true - #define IsX360() true - #define IsPS3() false - #endif -#elif defined(_LINUX) - #define IsPC() true - #define IsConsole() false - #define IsX360() false - #define IsPS3() false - #define IsLinux() true -#else - #error -#endif - -typedef unsigned char uint8; -typedef signed char int8; - -#ifdef __x86_64__ -#define X64BITS -#endif - -#if defined( _WIN32 ) - -typedef __int16 int16; -typedef unsigned __int16 uint16; -typedef __int32 int32; -typedef unsigned __int32 uint32; -typedef __int64 int64; -typedef unsigned __int64 uint64; - -#ifdef X64BITS -typedef __int64 intp; // intp is an integer that can accomodate a pointer -typedef unsigned __int64 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) -#else -typedef __int32 intp; -typedef unsigned __int32 uintp; -#endif - -#if defined( _X360 ) -#ifdef __m128 - #undef __m128 -#endif -#define __m128 __vector4 -#endif - -#else // _WIN32 - -typedef short int16; -typedef unsigned short uint16; -typedef int int32; -typedef unsigned int uint32; -typedef long long int64; -typedef unsigned long long uint64; -#ifdef X64BITS -typedef long long intp; -typedef unsigned long long uintp; -#else -typedef int intp; -typedef unsigned int uintp; -#endif - -#endif // else _WIN32 - - -typedef float float32; -typedef double float64; - -// for when we don't care about how many bits we use -typedef unsigned int uint; - -// This can be used to ensure the size of pointers to members when declaring -// a pointer type for a class that has only been forward declared -#ifdef _MSC_VER -#define SINGLE_INHERITANCE __single_inheritance -#define MULTIPLE_INHERITANCE __multiple_inheritance -#else -#define SINGLE_INHERITANCE -#define MULTIPLE_INHERITANCE -#endif - -#ifdef _MSC_VER -#define NO_VTABLE __declspec( novtable ) -#else -#define NO_VTABLE -#endif - -// This can be used to declare an abstract (interface only) class. -// Classes marked abstract should not be instantiated. If they are, and access violation will occur. -// -// Example of use: -// -// abstract_class CFoo -// { -// ... -// } -// -// MSDN __declspec(novtable) documentation: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang/html/_langref_novtable.asp -// -// Note: NJS: This is not enabled for regular PC, due to not knowing the implications of exporting a class with no no vtable. -// It's probable that this shouldn't be an issue, but an experiment should be done to verify this. -// -#ifndef _X360 -#define abstract_class class -#else -#define abstract_class class NO_VTABLE -#endif - -/* -FIXME: Enable this when we no longer fear change =) - -// need these for the limits -#include -#include - -// Maximum and minimum representable values -#define INT8_MAX SCHAR_MAX -#define INT16_MAX SHRT_MAX -#define INT32_MAX LONG_MAX -#define INT64_MAX (((int64)~0) >> 1) - -#define INT8_MIN SCHAR_MIN -#define INT16_MIN SHRT_MIN -#define INT32_MIN LONG_MIN -#define INT64_MIN (((int64)1) << 63) - -#define UINT8_MAX ((uint8)~0) -#define UINT16_MAX ((uint16)~0) -#define UINT32_MAX ((uint32)~0) -#define UINT64_MAX ((uint64)~0) - -#define UINT8_MIN 0 -#define UINT16_MIN 0 -#define UINT32_MIN 0 -#define UINT64_MIN 0 - -#ifndef UINT_MIN -#define UINT_MIN UINT32_MIN -#endif - -#define FLOAT32_MAX FLT_MAX -#define FLOAT64_MAX DBL_MAX - -#define FLOAT32_MIN FLT_MIN -#define FLOAT64_MIN DBL_MIN -*/ - -// portability / compiler settings -#if defined(_WIN32) && !defined(WINDED) - -#if defined(_M_IX86) -#define __i386__ 1 -#endif - -#elif _LINUX -typedef unsigned int DWORD; -typedef unsigned short WORD; -typedef void * HINSTANCE; -#define _MAX_PATH PATH_MAX -#endif // defined(_WIN32) && !defined(WINDED) - - -// Defines MAX_PATH -#ifndef MAX_PATH -#define MAX_PATH 260 -#endif - -#define ALIGN_VALUE( val, alignment ) ( ( val + alignment - 1 ) & ~( alignment - 1 ) ) // need macro for constant expression - -// Used to step into the debugger -#if defined( _WIN32 ) && !defined( _X360 ) -#define DebuggerBreak() __asm { int 3 } -#elif defined( _X360 ) -#define DebuggerBreak() DebugBreak() -#else -#define DebuggerBreak() {} -#endif -#define DebuggerBreakIfDebugging() if ( !Plat_IsInDebugSession() ) ; else DebuggerBreak() - -// C functions for external declarations that call the appropriate C++ methods -#ifndef EXPORT - #ifdef _WIN32 - #define EXPORT _declspec( dllexport ) - #else - #define EXPORT /* */ - #endif -#endif - -#if defined __i386__ && !defined __linux__ - #define id386 1 -#else - #define id386 0 -#endif // __i386__ - -// decls for aligning data -#ifdef _WIN32 - #define DECL_ALIGN(x) __declspec(align(x)) - -#elif _LINUX - #define DECL_ALIGN(x) __attribute__((aligned(x))) -#elif - #define DECL_ALIGN(x) /* */ -#endif - -#define ALIGN8 DECL_ALIGN(8) -#define ALIGN16 DECL_ALIGN(16) -#define ALIGN32 DECL_ALIGN(32) -#define ALIGN128 DECL_ALIGN(128) - - -// Linux had a few areas where it didn't construct objects in the same order that Windows does. -// So when CVProfile::CVProfile() would access g_pMemAlloc, it would crash because the allocator wasn't initalized yet. -#ifdef _LINUX - #define CONSTRUCT_EARLY __attribute__((init_priority(101))) -#else - #define CONSTRUCT_EARLY -#endif - -#ifdef _WIN32 - #define SELECTANY __declspec(selectany) -#elif _LINUX - #define SELECTANY __attribute__((weak)) -#else - #define SELECTANY static -#endif - -#if defined( _WIN32 ) - -// Used for dll exporting and importing -#define DLL_EXPORT extern "C" __declspec( dllexport ) -#define DLL_IMPORT extern "C" __declspec( dllimport ) - -// Can't use extern "C" when DLL exporting a class -#define DLL_CLASS_EXPORT __declspec( dllexport ) -#define DLL_CLASS_IMPORT __declspec( dllimport ) - -// Can't use extern "C" when DLL exporting a global -#define DLL_GLOBAL_EXPORT extern __declspec( dllexport ) -#define DLL_GLOBAL_IMPORT extern __declspec( dllimport ) - -#elif defined _LINUX -// Used for dll exporting and importing -#define DLL_EXPORT extern "C" __attribute__ ((visibility("default"))) -#define DLL_IMPORT extern "C" - -// Can't use extern "C" when DLL exporting a class -#define DLL_CLASS_EXPORT __attribute__ ((visibility("default"))) -#define DLL_CLASS_IMPORT - -// Can't use extern "C" when DLL exporting a global -#define DLL_GLOBAL_EXPORT extern __attribute ((visibility("default"))) -#define DLL_GLOBAL_IMPORT extern - -#else -#error "Unsupported Platform." -#endif - -// Used for standard calling conventions -#if defined( _WIN32 ) && !defined( _X360 ) - #define STDCALL __stdcall - #define FASTCALL __fastcall - #define FORCEINLINE __forceinline - // GCC 3.4.1 has a bug in supporting forced inline of templated functions - // this macro lets us not force inlining in that case - #define FORCEINLINE_TEMPLATE __forceinline -#elif defined( _X360 ) - #define STDCALL __stdcall - #ifdef FORCEINLINE - #undef FORCEINLINE - #endif - #define FORCEINLINE __forceinline - #define FORCEINLINE_TEMPLATE __forceinline -#else - #define STDCALL - #define FASTCALL - #ifdef _LINUX_DEBUGGABLE - #define FORCEINLINE - #else - #define FORCEINLINE inline - #endif - // GCC 3.4.1 has a bug in supporting forced inline of templated functions - // this macro lets us not force inlining in that case - #define FORCEINLINE_TEMPLATE inline - #define __stdcall __attribute__ ((__stdcall__)) -#endif - -// Force a function call site -not- to inlined. (useful for profiling) -#define DONT_INLINE(a) (((int)(a)+1)?(a):(a)) - -// Pass hints to the compiler to prevent it from generating unnessecary / stupid code -// in certain situations. Several compilers other than MSVC also have an equivilent -// construct. -// -// Essentially the 'Hint' is that the condition specified is assumed to be true at -// that point in the compilation. If '0' is passed, then the compiler assumes that -// any subsequent code in the same 'basic block' is unreachable, and thus usually -// removed. -#ifdef _MSC_VER - #define HINT(THE_HINT) __assume((THE_HINT)) -#else - #define HINT(THE_HINT) 0 -#endif - -// Marks the codepath from here until the next branch entry point as unreachable, -// and asserts if any attempt is made to execute it. -#define UNREACHABLE() { Assert(0); HINT(0); } - -// In cases where no default is present or appropriate, this causes MSVC to generate -// as little code as possible, and throw an assertion in debug. -#define NO_DEFAULT default: UNREACHABLE(); - -#ifdef _WIN32 -// Alloca defined for this platform -#define stackalloc( _size ) _alloca( ALIGN_VALUE( _size, 16 ) ) -#define stackfree( _p ) 0 -#elif _LINUX -// Alloca defined for this platform -#define stackalloc( _size ) _alloca( ALIGN_VALUE( _size, 16 ) ) -#define stackfree( _p ) 0 -#endif - -#ifdef _WIN32 -#define RESTRICT __restrict -#define RESTRICT_FUNC __declspec(restrict) -#else -#define RESTRICT -#define RESTRICT_FUNC -#endif - - -#ifdef _WIN32 -// Remove warnings from warning level 4. -#pragma warning(disable : 4514) // warning C4514: 'acosl' : unreferenced inline function has been removed -#pragma warning(disable : 4100) // warning C4100: 'hwnd' : unreferenced formal parameter -#pragma warning(disable : 4127) // warning C4127: conditional expression is constant -#pragma warning(disable : 4512) // warning C4512: 'InFileRIFF' : assignment operator could not be generated -#pragma warning(disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable -#pragma warning(disable : 4710) // warning C4710: function 'x' not inlined -#pragma warning(disable : 4702) // warning C4702: unreachable code -#pragma warning(disable : 4505) // unreferenced local function has been removed -#pragma warning(disable : 4239) // nonstandard extension used : 'argument' ( conversion from class Vector to class Vector& ) -#pragma warning(disable : 4097) // typedef-name 'BaseClass' used as synonym for class-name 'CFlexCycler::CBaseFlex' -#pragma warning(disable : 4324) // Padding was added at the end of a structure -#pragma warning(disable : 4244) // type conversion warning. -#pragma warning(disable : 4305) // truncation from 'const double ' to 'float ' -#pragma warning(disable : 4786) // Disable warnings about long symbol names -#pragma warning(disable : 4250) // 'X' : inherits 'Y::Z' via dominance -#pragma warning(disable : 4201) // nonstandard extension used : nameless struct/union - -#if _MSC_VER >= 1300 -#pragma warning(disable : 4511) // Disable warnings about private copy constructors -#pragma warning(disable : 4121) // warning C4121: 'symbol' : alignment of a member was sensitive to packing -#pragma warning(disable : 4530) // warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc (disabled due to std headers having exception syntax) -#endif - -#if _MSC_VER >= 1400 -#pragma warning(disable : 4996) // functions declared deprecated -#endif - - -#endif - -// When we port to 64 bit, we'll have to resolve the int, ptr vs size_t 32/64 bit problems... -#if !defined( _WIN64 ) -#pragma warning( disable : 4267 ) // conversion from 'size_t' to 'int', possible loss of data -#pragma warning( disable : 4311 ) // pointer truncation from 'char *' to 'int' -#pragma warning( disable : 4312 ) // conversion from 'unsigned int' to 'memhandle_t' of greater size -#endif - - -//----------------------------------------------------------------------------- -// fsel -//----------------------------------------------------------------------------- -#ifndef _X360 - -static FORCEINLINE float fsel(float fComparand, float fValGE, float fLT) -{ - return fComparand >= 0 ? fValGE : fLT; -} -static FORCEINLINE double fsel(double fComparand, double fValGE, double fLT) -{ - return fComparand >= 0 ? fValGE : fLT; -} - -#else - -// __fsel(double fComparand, double fValGE, double fLT) == fComparand >= 0 ? fValGE : fLT -// this is much faster than if ( aFloat > 0 ) { x = .. } -#define fsel __fsel - -#endif - - -//----------------------------------------------------------------------------- -// FP exception handling -//----------------------------------------------------------------------------- -//#define CHECK_FLOAT_EXCEPTIONS 1 - -#if !defined( _X360 ) -#if defined( _MSC_VER ) - -inline void SetupFPUControlWordForceExceptions() -{ - // use local to get and store control word - uint16 tmpCtrlW; - __asm - { - fnclex /* clear all current exceptions */ - fnstcw word ptr [tmpCtrlW] /* get current control word */ - and [tmpCtrlW], 0FCC0h /* Keep infinity control + rounding control */ - or [tmpCtrlW], 0230h /* set to 53-bit, mask only inexact, underflow */ - fldcw word ptr [tmpCtrlW] /* put new control word in FPU */ - } -} - -#ifdef CHECK_FLOAT_EXCEPTIONS - -inline void SetupFPUControlWord() -{ - SetupFPUControlWordForceExceptions(); -} - -#else - -inline void SetupFPUControlWord() -{ - // use local to get and store control word - uint16 tmpCtrlW; - __asm - { - fnstcw word ptr [tmpCtrlW] /* get current control word */ - and [tmpCtrlW], 0FCC0h /* Keep infinity control + rounding control */ - or [tmpCtrlW], 023Fh /* set to 53-bit, mask only inexact, underflow */ - fldcw word ptr [tmpCtrlW] /* put new control word in FPU */ - } -} - -#endif - -#else - -inline void SetupFPUControlWord() -{ - __volatile unsigned short int __cw; - __asm __volatile ("fnstcw %0" : "=m" (__cw)); - __cw = __cw & 0x0FCC0; // keep infinity control, keep rounding mode - __cw = __cw | 0x023F; // set 53-bit, no exceptions - __asm __volatile ("fldcw %0" : : "m" (__cw)); -} - -#endif // _MSC_VER - -#else - -#ifdef _DEBUG -FORCEINLINE bool IsFPUControlWordSet() -{ - float f = 0.996f; - union - { - double flResult; - int pResult[2]; - }; - flResult = __fctiw( f ); - return ( pResult[1] == 1 ); -} -#endif - -inline void SetupFPUControlWord() -{ - // Set round-to-nearest in FPSCR - // (cannot assemble, must use op-code form) - __emit( 0xFF80010C ); // mtfsfi 7,0 - - // Favour compatibility over speed (make sure the VPU set to Java-compliant mode) - // NOTE: the VPU *always* uses round-to-nearest - __vector4 a = { 0.0f, 0.0f, 0.0f, 0.0f }; - a; // Avoid compiler warning - __asm - { - mtvscr a; // Clear the Vector Status & Control Register to zero - } -} - -#endif // _X360 - -//----------------------------------------------------------------------------- -// Purpose: Standard functions for handling endian-ness -//----------------------------------------------------------------------------- - -//------------------------------------- -// Basic swaps -//------------------------------------- - -template -inline T WordSwapC( T w ) -{ - uint16 temp; - - temp = ((*((uint16 *)&w) & 0xff00) >> 8); - temp |= ((*((uint16 *)&w) & 0x00ff) << 8); - - return *((T*)&temp); -} - -template -inline T DWordSwapC( T dw ) -{ - uint32 temp; - - temp = *((uint32 *)&dw) >> 24; - temp |= ((*((uint32 *)&dw) & 0x00FF0000) >> 8); - temp |= ((*((uint32 *)&dw) & 0x0000FF00) << 8); - temp |= ((*((uint32 *)&dw) & 0x000000FF) << 24); - - return *((T*)&temp); -} - -//------------------------------------- -// Fast swaps -//------------------------------------- - -#if defined( _X360 ) - -#define WordSwap WordSwap360Intr -#define DWordSwap DWordSwap360Intr - -template -inline T WordSwap360Intr( T w ) -{ - T output; - __storeshortbytereverse( w, 0, &output ); - return output; -} - -template -inline T DWordSwap360Intr( T dw ) -{ - T output; - __storewordbytereverse( dw, 0, &output ); - return output; -} - -#elif defined( _MSC_VER ) - -#define WordSwap WordSwapAsm -#define DWordSwap DWordSwapAsm - -#pragma warning(push) -#pragma warning (disable:4035) // no return value - -template -inline T WordSwapAsm( T w ) -{ - __asm - { - mov ax, w - xchg al, ah - } -} - -template -inline T DWordSwapAsm( T dw ) -{ - __asm - { - mov eax, dw - bswap eax - } -} - -#pragma warning(pop) - -#else - -#define WordSwap WordSwapC -#define DWordSwap DWordSwapC - -#endif - -//------------------------------------- -// The typically used methods. -//------------------------------------- - -#if defined(__i386__) -#define LITTLE_ENDIAN 1 -#endif - -#if defined( _SGI_SOURCE ) || defined( _X360 ) -#define BIG_ENDIAN 1 -#endif - -// If a swapped float passes through the fpu, the bytes may get changed. -// Prevent this by swapping floats as DWORDs. -#define SafeSwapFloat( pOut, pIn ) (*((uint*)pOut) = DWordSwap( *((uint*)pIn) )) - -#if defined(LITTLE_ENDIAN) - -#define BigShort( val ) WordSwap( val ) -#define BigWord( val ) WordSwap( val ) -#define BigLong( val ) DWordSwap( val ) -#define BigDWord( val ) DWordSwap( val ) -#define LittleShort( val ) ( val ) -#define LittleWord( val ) ( val ) -#define LittleLong( val ) ( val ) -#define LittleDWord( val ) ( val ) -#define SwapShort( val ) BigShort( val ) -#define SwapWord( val ) BigWord( val ) -#define SwapLong( val ) BigLong( val ) -#define SwapDWord( val ) BigDWord( val ) - -// Pass floats by pointer for swapping to avoid truncation in the fpu -#define BigFloat( pOut, pIn ) SafeSwapFloat( pOut, pIn ) -#define LittleFloat( pOut, pIn ) ( *pOut = *pIn ) -#define SwapFloat( pOut, pIn ) BigFloat( pOut, pIn ) - -#elif defined(BIG_ENDIAN) - -#define BigShort( val ) ( val ) -#define BigWord( val ) ( val ) -#define BigLong( val ) ( val ) -#define BigDWord( val ) ( val ) -#define LittleShort( val ) WordSwap( val ) -#define LittleWord( val ) WordSwap( val ) -#define LittleLong( val ) DWordSwap( val ) -#define LittleDWord( val ) DWordSwap( val ) -#define SwapShort( val ) LittleShort( val ) -#define SwapWord( val ) LittleWord( val ) -#define SwapLong( val ) LittleLong( val ) -#define SwapDWord( val ) LittleDWord( val ) - -// Pass floats by pointer for swapping to avoid truncation in the fpu -#define BigFloat( pOut, pIn ) ( *pOut = *pIn ) -#define LittleFloat( pOut, pIn ) SafeSwapFloat( pOut, pIn ) -#define SwapFloat( pOut, pIn ) LittleFloat( pOut, pIn ) - -#else - -// @Note (toml 05-02-02): this technique expects the compiler to -// optimize the expression and eliminate the other path. On any new -// platform/compiler this should be tested. -inline short BigShort( short val ) { int test = 1; return ( *(char *)&test == 1 ) ? WordSwap( val ) : val; } -inline uint16 BigWord( uint16 val ) { int test = 1; return ( *(char *)&test == 1 ) ? WordSwap( val ) : val; } -inline long BigLong( long val ) { int test = 1; return ( *(char *)&test == 1 ) ? DWordSwap( val ) : val; } -inline uint32 BigDWord( uint32 val ) { int test = 1; return ( *(char *)&test == 1 ) ? DWordSwap( val ) : val; } -inline short LittleShort( short val ) { int test = 1; return ( *(char *)&test == 1 ) ? val : WordSwap( val ); } -inline uint16 LittleWord( uint16 val ) { int test = 1; return ( *(char *)&test == 1 ) ? val : WordSwap( val ); } -inline long LittleLong( long val ) { int test = 1; return ( *(char *)&test == 1 ) ? val : DWordSwap( val ); } -inline uint32 LittleDWord( uint32 val ) { int test = 1; return ( *(char *)&test == 1 ) ? val : DWordSwap( val ); } -inline short SwapShort( short val ) { return WordSwap( val ); } -inline uint16 SwapWord( uint16 val ) { return WordSwap( val ); } -inline long SwapLong( long val ) { return DWordSwap( val ); } -inline uint32 SwapDWord( uint32 val ) { return DWordSwap( val ); } - -// Pass floats by pointer for swapping to avoid truncation in the fpu -inline void BigFloat( float *pOut, const float *pIn ) { int test = 1; ( *(char *)&test == 1 ) ? SafeSwapFloat( pOut, pIn ) : ( *pOut = *pIn ); } -inline void LittleFloat( float *pOut, const float *pIn ) { int test = 1; ( *(char *)&test == 1 ) ? ( *pOut = *pIn ) : SafeSwapFloat( pOut, pIn ); } -inline void SwapFloat( float *pOut, const float *pIn ) { SafeSwapFloat( pOut, pIn ); } - -#endif - -#if _X360 -inline unsigned long LoadLittleDWord( unsigned long *base, unsigned int dwordIndex ) -{ - return __loadwordbytereverse( dwordIndex<<2, base ); -} - -inline void StoreLittleDWord( unsigned long *base, unsigned int dwordIndex, unsigned long dword ) -{ - __storewordbytereverse( dword, dwordIndex<<2, base ); -} -#else -inline unsigned long LoadLittleDWord( unsigned long *base, unsigned int dwordIndex ) -{ - return LittleDWord( base[dwordIndex] ); -} - -inline void StoreLittleDWord( unsigned long *base, unsigned int dwordIndex, unsigned long dword ) -{ - base[dwordIndex] = LittleDWord(dword); -} -#endif - - -#ifndef STATIC_TIER0 - -#ifdef TIER0_DLL_EXPORT - #define PLATFORM_INTERFACE DLL_EXPORT - #define PLATFORM_OVERLOAD DLL_GLOBAL_EXPORT -#else - #define PLATFORM_INTERFACE DLL_IMPORT - #define PLATFORM_OVERLOAD DLL_GLOBAL_IMPORT -#endif - -#else // BUILD_AS_DLL - -#define PLATFORM_INTERFACE extern -#define PLATFORM_OVERLOAD - -#endif // BUILD_AS_DLL - - -// When in benchmark mode, the timer returns a simple incremented value each time you call it. -// -// It should not be changed after startup unless you really know what you're doing. The only place -// that should do this is the benchmark code itself so it can output a legit duration. -PLATFORM_INTERFACE void Plat_SetBenchmarkMode( bool bBenchmarkMode ); -PLATFORM_INTERFACE bool Plat_IsInBenchmarkMode(); - - -PLATFORM_INTERFACE double Plat_FloatTime(); // Returns time in seconds since the module was loaded. -PLATFORM_INTERFACE unsigned long Plat_MSTime(); // Time in milliseconds. - -// b/w compatibility -#define Sys_FloatTime Plat_FloatTime - - -// Processor Information: -struct CPUInformation -{ - int m_Size; // Size of this structure, for forward compatability. - - bool m_bRDTSC : 1, // Is RDTSC supported? - m_bCMOV : 1, // Is CMOV supported? - m_bFCMOV : 1, // Is FCMOV supported? - m_bSSE : 1, // Is SSE supported? - m_bSSE2 : 1, // Is SSE2 Supported? - m_b3DNow : 1, // Is 3DNow! Supported? - m_bMMX : 1, // Is MMX supported? - m_bHT : 1; // Is HyperThreading supported? - - uint8 m_nLogicalProcessors; // Number op logical processors. - uint8 m_nPhysicalProcessors; // Number of physical processors - - int64 m_Speed; // In cycles per second. - - tchar* m_szProcessorID; // Processor vendor Identification. -}; - -PLATFORM_INTERFACE const CPUInformation& GetCPUInformation(); - -PLATFORM_INTERFACE void GetCurrentDate( int *pDay, int *pMonth, int *pYear ); - -// ---------------------------------------------------------------------------------- // -// Performance Monitoring Events - L2 stats etc... -// ---------------------------------------------------------------------------------- // -PLATFORM_INTERFACE void InitPME(); -PLATFORM_INTERFACE void ShutdownPME(); - -//----------------------------------------------------------------------------- -// Thread related functions -//----------------------------------------------------------------------------- -// Registers the current thread with Tier0's thread management system. -// This should be called on every thread created in the game. -PLATFORM_INTERFACE unsigned long Plat_RegisterThread( const tchar *pName = _T("Source Thread")); - -// Registers the current thread as the primary thread. -PLATFORM_INTERFACE unsigned long Plat_RegisterPrimaryThread(); - -// VC-specific. Sets the thread's name so it has a friendly name in the debugger. -// This should generally only be handled by Plat_RegisterThread and Plat_RegisterPrimaryThread -PLATFORM_INTERFACE void Plat_SetThreadName( unsigned long dwThreadID, const tchar *pName ); - -// These would be private if it were possible to export private variables from a .DLL. -// They need to be variables because they are checked by inline functions at performance -// critical places. -PLATFORM_INTERFACE unsigned long Plat_PrimaryThreadID; - -// Returns the ID of the currently executing thread. -PLATFORM_INTERFACE unsigned long Plat_GetCurrentThreadID(); - -// Returns the ID of the primary thread. -inline unsigned long Plat_GetPrimaryThreadID() -{ - return Plat_PrimaryThreadID; -} - -// Returns true if the current thread is the primary thread. -inline bool Plat_IsPrimaryThread() -{ - //return true; - return (Plat_GetPrimaryThreadID() == Plat_GetCurrentThreadID() ); -} - -//----------------------------------------------------------------------------- -// Process related functions -//----------------------------------------------------------------------------- -PLATFORM_INTERFACE const tchar *Plat_GetCommandLine(); -#ifndef _WIN32 -// helper function for OS's that don't have a ::GetCommandLine() call -PLATFORM_INTERFACE void Plat_SetCommandLine( const char *cmdLine ); -#endif -PLATFORM_INTERFACE const char *Plat_GetCommandLineA(); - -//----------------------------------------------------------------------------- -// Security related functions -//----------------------------------------------------------------------------- -// Ensure that the hardware key's drivers have been installed. -PLATFORM_INTERFACE bool Plat_VerifyHardwareKeyDriver(); - -// Ok, so this isn't a very secure way to verify the hardware key for now. It -// is primarially depending on the fact that all the binaries have been wrapped -// with the secure wrapper provided by the hardware keys vendor. -PLATFORM_INTERFACE bool Plat_VerifyHardwareKey(); - -// The same as above, but notifies user with a message box when the key isn't in -// and gives him an opportunity to correct the situation. -PLATFORM_INTERFACE bool Plat_VerifyHardwareKeyPrompt(); - -// Can be called in real time, doesn't perform the verify every frame. Mainly just -// here to allow the game to drop out quickly when the key is removed, rather than -// allowing the wrapper to pop up it's own blocking dialog, which the engine doesn't -// like much. -PLATFORM_INTERFACE bool Plat_FastVerifyHardwareKey(); - -//----------------------------------------------------------------------------- -// Just logs file and line to simple.log -//----------------------------------------------------------------------------- -PLATFORM_INTERFACE void* Plat_SimpleLog( const tchar* file, int line ); - -//----------------------------------------------------------------------------- -// Returns true if debugger attached, false otherwise -//----------------------------------------------------------------------------- -#if defined(_WIN32) -PLATFORM_INTERFACE bool Plat_IsInDebugSession(); -PLATFORM_INTERFACE void Plat_DebugString( const char * ); -#else -#define Plat_IsInDebugSession() (false) -#define Plat_DebugString(s) ((void)0) -#endif - -//----------------------------------------------------------------------------- -// XBOX Components valid in PC compilation space -//----------------------------------------------------------------------------- - -#define XBOX_DVD_SECTORSIZE 2048 -#define XBOX_DVD_ECC_SIZE 32768 // driver reads in quantum ECC blocks -#define XBOX_HDD_SECTORSIZE 512 - -// Custom windows messages for Xbox input -#define WM_XREMOTECOMMAND (WM_USER + 100) -#define WM_XCONTROLLER_KEY (WM_USER + 101) -#define WM_SYS_UI (WM_USER + 102) -#define WM_SYS_SIGNINCHANGED (WM_USER + 103) -#define WM_SYS_STORAGEDEVICESCHANGED (WM_USER + 104) -#define WM_SYS_PROFILESETTINGCHANGED (WM_USER + 105) -#define WM_SYS_MUTELISTCHANGED (WM_USER + 106) -#define WM_SYS_INPUTDEVICESCHANGED (WM_USER + 107) -#define WM_SYS_INPUTDEVICECONFIGCHANGED (WM_USER + 108) -#define WM_LIVE_CONNECTIONCHANGED (WM_USER + 109) -#define WM_LIVE_INVITE_ACCEPTED (WM_USER + 110) -#define WM_LIVE_LINK_STATE_CHANGED (WM_USER + 111) -#define WM_LIVE_CONTENT_INSTALLED (WM_USER + 112) -#define WM_LIVE_MEMBERSHIP_PURCHASED (WM_USER + 113) -#define WM_LIVE_VOICECHAT_AWAY (WM_USER + 114) -#define WM_LIVE_PRESENCE_CHANGED (WM_USER + 115) -#define WM_FRIENDS_PRESENCE_CHANGED (WM_USER + 116) -#define WM_FRIENDS_FRIEND_ADDED (WM_USER + 117) -#define WM_FRIENDS_FRIEND_REMOVED (WM_USER + 118) -#define WM_CUSTOM_GAMEBANNERPRESSED (WM_USER + 119) -#define WM_CUSTOM_ACTIONPRESSED (WM_USER + 120) -#define WM_XMP_STATECHANGED (WM_USER + 121) -#define WM_XMP_PLAYBACKBEHAVIORCHANGED (WM_USER + 122) -#define WM_XMP_PLAYBACKCONTROLLERCHANGED (WM_USER + 123) - -inline const char *GetPlatformExt( void ) -{ - return IsX360() ? ".360" : ""; -} - -// flat view, 6 hw threads -#define XBOX_PROCESSOR_0 ( 1<<0 ) -#define XBOX_PROCESSOR_1 ( 1<<1 ) -#define XBOX_PROCESSOR_2 ( 1<<2 ) -#define XBOX_PROCESSOR_3 ( 1<<3 ) -#define XBOX_PROCESSOR_4 ( 1<<4 ) -#define XBOX_PROCESSOR_5 ( 1<<5 ) - -// core view, 3 cores with 2 hw threads each -#define XBOX_CORE_0_HWTHREAD_0 XBOX_PROCESSOR_0 -#define XBOX_CORE_0_HWTHREAD_1 XBOX_PROCESSOR_1 -#define XBOX_CORE_1_HWTHREAD_0 XBOX_PROCESSOR_2 -#define XBOX_CORE_1_HWTHREAD_1 XBOX_PROCESSOR_3 -#define XBOX_CORE_2_HWTHREAD_0 XBOX_PROCESSOR_4 -#define XBOX_CORE_2_HWTHREAD_1 XBOX_PROCESSOR_5 - -//----------------------------------------------------------------------------- -// Include additional dependant header components. -//----------------------------------------------------------------------------- -#include "tier0/fasttimer.h" - -#if defined( _X360 ) -#include "xbox/xbox_core.h" -#endif - -//----------------------------------------------------------------------------- -// Methods to invoke the constructor, copy constructor, and destructor -//----------------------------------------------------------------------------- - -template -inline void Construct( T* pMemory ) -{ - ::new( pMemory ) T; -} - -template -inline void CopyConstruct( T* pMemory, T const& src ) -{ - ::new( pMemory ) T(src); -} - -template -inline void Destruct( T* pMemory ) -{ - pMemory->~T(); - -#ifdef _DEBUG - memset( pMemory, 0xDD, sizeof(T) ); -#endif -} - - -// -// GET_OUTER() -// -// A platform-independent way for a contained class to get a pointer to its -// owner. If you know a class is exclusively used in the context of some -// "outer" class, this is a much more space efficient way to get at the outer -// class than having the inner class store a pointer to it. -// -// class COuter -// { -// class CInner // Note: this does not need to be a nested class to work -// { -// void PrintAddressOfOuter() -// { -// printf( "Outer is at 0x%x\n", GET_OUTER( COuter, m_Inner ) ); -// } -// }; -// -// CInner m_Inner; -// friend class CInner; -// }; - -#define GET_OUTER( OuterType, OuterMember ) \ - ( ( OuterType * ) ( (uint8 *)this - offsetof( OuterType, OuterMember ) ) ) - - -/* TEMPLATE_FUNCTION_TABLE() - - (Note added to platform.h so platforms that correctly support templated - functions can handle portions as templated functions rather than wrapped - functions) - - Helps automate the process of creating an array of function - templates that are all specialized by a single integer. - This sort of thing is often useful in optimization work. - - For example, using TEMPLATE_FUNCTION_TABLE, this: - - TEMPLATE_FUNCTION_TABLE(int, Function, ( int blah, int blah ), 10) - { - return argument * argument; - } - - is equivilent to the following: - - (NOTE: the function has to be wrapped in a class due to code - generation bugs involved with directly specializing a function - based on a constant.) - - template - class FunctionWrapper - { - public: - int Function( int blah, int blah ) - { - return argument*argument; - } - } - - typedef int (*FunctionType)( int blah, int blah ); - - class FunctionName - { - public: - enum { count = 10 }; - FunctionType functions[10]; - }; - - FunctionType FunctionName::functions[] = - { - FunctionWrapper<0>::Function, - FunctionWrapper<1>::Function, - FunctionWrapper<2>::Function, - FunctionWrapper<3>::Function, - FunctionWrapper<4>::Function, - FunctionWrapper<5>::Function, - FunctionWrapper<6>::Function, - FunctionWrapper<7>::Function, - FunctionWrapper<8>::Function, - FunctionWrapper<9>::Function - }; -*/ - -PLATFORM_INTERFACE bool vtune( bool resume ); - - -#define TEMPLATE_FUNCTION_TABLE(RETURN_TYPE, NAME, ARGS, COUNT) \ - \ -typedef RETURN_TYPE (FASTCALL *__Type_##NAME) ARGS; \ - \ -template \ -struct __Function_##NAME \ -{ \ - static RETURN_TYPE FASTCALL Run ARGS; \ -}; \ - \ -template \ -struct __MetaLooper_##NAME : __MetaLooper_##NAME \ -{ \ - __Type_##NAME func; \ - inline __MetaLooper_##NAME() { func = __Function_##NAME::Run; } \ -}; \ - \ -template<> \ -struct __MetaLooper_##NAME<0> \ -{ \ - __Type_##NAME func; \ - inline __MetaLooper_##NAME() { func = __Function_##NAME<0>::Run; } \ -}; \ - \ -class NAME \ -{ \ -private: \ - static const __MetaLooper_##NAME m; \ -public: \ - enum { count = COUNT }; \ - static const __Type_##NAME* functions; \ -}; \ -const __MetaLooper_##NAME NAME::m; \ -const __Type_##NAME* NAME::functions = (__Type_##NAME*)&m; \ -template \ -RETURN_TYPE FASTCALL __Function_##NAME::Run ARGS - - -#define LOOP_INTERCHANGE(BOOLEAN, CODE)\ - if( (BOOLEAN) )\ - {\ - CODE;\ - } else\ - {\ - CODE;\ - } - -//----------------------------------------------------------------------------- - -#if defined(_INC_WINDOWS) && defined(_WIN32) -template -class CDynamicFunction -{ -public: - CDynamicFunction( const char *pszModule, const char *pszName, FUNCPTR_TYPE pfnFallback = NULL ) - { - m_pfn = pfnFallback; - - HMODULE hModule = ::LoadLibrary( pszModule ); - if ( hModule ) - m_pfn = (FUNCPTR_TYPE)::GetProcAddress( hModule, pszName ); - } - - operator bool() { return m_pfn != NULL; } - bool operator !() { return !m_pfn; } - operator FUNCPTR_TYPE() { return m_pfn; } - -private: - FUNCPTR_TYPE m_pfn; -}; -#endif - -//----------------------------------------------------------------------------- - -#include "tier0/valve_on.h" - -#endif /* PLATFORM_H */ diff --git a/Resources/NetHook/tier0/pmc360.h b/Resources/NetHook/tier0/pmc360.h deleted file mode 100644 index 4c99cd63..00000000 --- a/Resources/NetHook/tier0/pmc360.h +++ /dev/null @@ -1,73 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Analogous to l2cache.h, this class represents information gleaned -// from the 360's Performance Monitor Counters. In particular we -// are interested in l2 cache misses and load-hit-stores. -// -//=============================================================================// -#ifndef CPMCDATA_H -#define CPMCDATA_H -#ifdef _WIN32 -#pragma once -#endif - -#ifndef _X360 -#error This file must only be compiled for XBOX360! -#endif - - -// Warning: -// As written, this class only supports profiling thread 0, processor 0. - -class CPMCData -{ -public: - - CPMCData(); - ~CPMCData() {}; - - void Start( void ); - void End( void ); - - /// This function should be called exactly once during the lifespan of the program; - /// it will set up the counters to record the information we are interested in. - /// This will stomp on whoever else might have set the performance counters elsewhere - /// in the game. - static void InitializeOnceProgramWide( void ); - static bool IsInitialized(); - - //------------------------------------------------------------------------- - // GetL2CacheMisses - //------------------------------------------------------------------------- - uint64 GetL2CacheMisses( void ) const - { - return m_Delta.L2CacheMiss; - } - - uint64 GetLHS( void ) const - { - return m_Delta.LHS; - } - -/* -#ifdef DBGFLAG_VALIDATE - void Validate( CValidator &validator, tchar *pchName ); // Validate our internal structures -#endif // DBGFLAG_VALIDATE -*/ - -private: - /// represents saved numbers from the counters we are interested in - struct PMCounters - { - uint64 L2CacheMiss; - uint64 LHS; ///< load hit store - - PMCounters(int64 _l2cm, int64 _lhs ) : L2CacheMiss(_l2cm), LHS(_lhs) {}; - PMCounters() : L2CacheMiss(0), LHS(0) {}; - }; - - PMCounters m_OnStart; ///< values when we began the timer - PMCounters m_Delta ; ///< computed total delta between start/stop -}; - -#endif // CPMCDATA_H \ No newline at end of file diff --git a/Resources/NetHook/tier0/progressbar.h b/Resources/NetHook/tier0/progressbar.h deleted file mode 100644 index a58ca1f5..00000000 --- a/Resources/NetHook/tier0/progressbar.h +++ /dev/null @@ -1,23 +0,0 @@ -//========= Copyright © 1996-2006, Valve Corporation, All rights reserved. ============// -// -// Purpose: Provide a shared place for library fucntions to report progress % for display -// -//=============================================================================// - -#ifndef PROGRESSBAR_H -#define PROGRESSBAR_H -#ifdef _WIN32 -#pragma once -#endif - - -PLATFORM_INTERFACE void ReportProgress(char const *job_name, int total_units_to_do, - int n_units_completed); - -typedef void (*ProgressReportHandler_t)( char const*, int, int ); - -// install your own handler. returns previous handler -PLATFORM_INTERFACE ProgressReportHandler_t InstallProgressReportHandler( ProgressReportHandler_t pfn); - - -#endif diff --git a/Resources/NetHook/tier0/protected_things.h b/Resources/NetHook/tier0/protected_things.h deleted file mode 100644 index 0445503c..00000000 --- a/Resources/NetHook/tier0/protected_things.h +++ /dev/null @@ -1,284 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef PROTECTED_THINGS_H -#define PROTECTED_THINGS_H -#ifdef _WIN32 -#pragma once -#endif - - -// This header tries to prevent people from using potentially dangerous functions -// (like the notorious non-null-terminating strncpy) and functions that will break -// VCR mode (like time, input, registry, etc). -// -// This header should be included by ALL of our source code. - -// Eventually, ALL of these should be protected, but one man can only accomplish so much in -// one day AND work on features too! -#if defined( PROTECTED_STRINGS_ENABLE ) - - #if defined( printf ) - #undef printf - #endif - #define printf printf__HEY_YOU__USE_VSTDLIB - - #if defined( wprintf ) - #undef wprintf - #endif - #define wprintf wprintf__HEY_YOU__USE_VSTDLIB - - #if defined( strcmp ) - #undef strcmp - #endif - #define strcmp strcmp__HEY_YOU__USE_VSTDLIB - - #if defined( wcscmp ) - #undef wcscmp - #endif - #define wcscmp wcscmp__HEY_YOU__USE_VSTDLIB - - #if defined( strncpy ) - #undef strncpy - #endif - #define strncpy strncpy__HEY_YOU__USE_VSTDLIB - - #if defined( wcsncpy ) - #undef wcsncpy - #endif - #define wcsncpy wcsncpy__HEY_YOU__USE_VSTDLIB - - #if defined( strlen ) - #undef strlen - #endif - #define strlen strlen__HEY_YOU__USE_VSTDLIB - - #if defined( wcslen ) - #undef wcslen - #endif - #define wcslen wcslen__HEY_YOU__USE_VSTDLIB - - #if defined( Q_strlen ) - #undef Q_strlen - #endif - #define Q_strlen Q_strlen__HEY_YOU__USE_VSTDLIB - - #if defined( _snprintf ) - #undef _snprintf - #endif - #define _snprintf snprintf__HEY_YOU__USE_VSTDLIB - - #if defined( _snwprintf ) - #undef _snwprintf - #endif - #define _snwprintf snwprintf__HEY_YOU__USE_VSTDLIB - - #if defined( sprintf ) - #undef sprintf - #endif - #define sprintf sprintf__HEY_YOU__USE_VSTDLIB - - #if defined( swprintf ) - #undef swprintf - #endif - #define swprintf swprintf__HEY_YOU__USE_VSTDLIB - - #if defined( vsprintf ) - #undef vsprintf - #endif - #define vsprintf vsprintf__HEY_YOU__USE_VSTDLIB - - #if defined( vswprintf ) - #undef vswprintf - #endif - #define vswprintf vswprintf__HEY_YOU__USE_VSTDLIB - - #if defined( _vsnprintf ) - #undef _vsnprintf - #endif - #define _vsnprintf vsnprintf__HEY_YOU__USE_VSTDLIB - - #if defined( _vsnwprintf ) - #undef _vsnwprintf - #endif - #define _vsnwprintf vsnwprintf__HEY_YOU__USE_VSTDLIB - - #if defined( strcat ) - #undef strcat - #endif - #define strcat strcat__HEY_YOU__USE_VSTDLIB - - #if defined( wcscat ) - #undef wcscat - #endif - #define wcscat wcscat__HEY_YOU__USE_VSTDLIB - - #if defined( strncat ) - #undef strncat - #endif - #define strncat strncat__HEY_YOU__USE_VSTDLIB - - #if defined( wcsncat ) - #undef wcsncat - #endif - #define wcsncat wcsncat__HEY_YOU__USE_VSTDLIB - -#endif - - -#if defined( PROTECT_FILEIO_FUNCTIONS ) && ( ! defined( _LINUX ) ) - #if defined( fopen ) - #undef fopen - #endif - #define fopen fopen_USE_FILESYSTEM_INSTEAD - - #if defined( _wfopen ) - #undef _wfopen - #endif - #define _wfopen _wfopen_USE_FILESYSTEM_INSTEAD -#endif - - -#if defined( PROTECTED_THINGS_ENABLE ) && !defined( _X360 ) - - #if defined( GetTickCount ) - #undef GetTickCount - #endif - #define GetTickCount GetTickCount__USE_VCR_MODE - - - #if defined( timeGetTime ) - #undef timeGetTime - #endif - #define timeGetTime timeGetTime__USE_VCR_MODE - #if defined( clock ) - #undef clock - #endif - #define time time__USE_VCR_MODE - - - #if defined( recvfrom ) - #undef recvfrom - #endif - #define recvfrom recvfrom__USE_VCR_MODE - - - #if defined( GetCursorPos ) - #undef GetCursorPos - #endif - #define GetCursorPos GetCursorPos__USE_VCR_MODE - - - #if defined( ScreenToClient ) - #undef ScreenToClient - #endif - #define ScreenToClient ScreenToClient__USE_VCR_MODE - - - #if defined( GetCommandLine ) - #undef GetCommandLine - #endif - #define GetCommandLine GetCommandLine__USE_VCR_MODE - - - #if defined( RegOpenKeyEx ) - #undef RegOpenKeyEx - #endif - #define RegOpenKeyEx RegOpenKeyEx__USE_VCR_MODE - - - #if defined( RegOpenKey ) - #undef RegOpenKey - #endif - #define RegOpenKey RegOpenKey__USE_VCR_MODE - - - #if defined( RegSetValueEx ) - #undef RegSetValueEx - #endif - #define RegSetValueEx RegSetValueEx__USE_VCR_MODE - - - #if defined( RegSetValue ) - #undef RegSetValue - #endif - #define RegSetValue RegSetValue__USE_VCR_MODE - - - #if defined( RegQueryValueEx ) - #undef RegQueryValueEx - #endif - #define RegQueryValueEx RegQueryValueEx__USE_VCR_MODE - - - #if defined( RegQueryValue ) - #undef RegQueryValue - #endif - #define RegQueryValue RegQueryValue__USE_VCR_MODE - - - #if defined( RegCreateKeyEx ) - #undef RegCreateKeyEx - #endif - #define RegCreateKeyEx RegCreateKeyEx__USE_VCR_MODE - - - #if defined( RegCreateKey ) - #undef RegCreateKey - #endif - #define RegCreateKey RegCreateKey__USE_VCR_MODE - - - #if defined( RegCloseKey ) - #undef RegCloseKey - #endif - #define RegCloseKey RegCloseKey__USE_VCR_MODE - - - #if defined( GetNumberOfConsoleInputEvents ) - #undef GetNumberOfConsoleInputEvents - #endif - #define GetNumberOfConsoleInputEvents GetNumberOfConsoleInputEvents__USE_VCR_MODE - - - #if defined( ReadConsoleInput ) - #undef ReadConsoleInput - #endif - #define ReadConsoleInput ReadConsoleInput__USE_VCR_MODE - - - #if defined( GetAsyncKeyState ) - #undef GetAsyncKeyState - #endif - #define GetAsyncKeyState GetAsyncKeyState__USE_VCR_MODE - - - #if defined( GetKeyState ) - #undef GetKeyState - #endif - #define GetKeyState GetKeyState__USE_VCR_MODE - - - #if defined( CreateThread ) - #undef CreateThread - #endif - #define CreateThread CreateThread__USE_VCR_MODE - - #if defined( WaitForSingleObject ) - #undef WaitForSingleObject - #endif - #define WaitForSingleObject WaitForSingleObject__USE_VCR_MODE - - #if defined( EnterCriticalSection ) - #undef EnterCriticalSection - #endif - #define EnterCriticalSection EnterCriticalSection__USE_VCR_MODE - -#endif - - -#endif // PROTECTED_THINGS_H diff --git a/Resources/NetHook/tier0/systeminformation.h b/Resources/NetHook/tier0/systeminformation.h deleted file mode 100644 index a64b13cb..00000000 --- a/Resources/NetHook/tier0/systeminformation.h +++ /dev/null @@ -1,56 +0,0 @@ -//====== Copyright c 1996-2007, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#ifndef SYSTEMINFORMATION_H -#define SYSTEMINFORMATION_H - -#ifdef _WIN32 - #pragma once -#endif - -#ifndef PLATFORM_INTERFACE - #define PLATFORM_INTERFACE -#endif - -// -// Defines a possible outcome of a system call -// -enum SYSTEM_CALL_RESULT_t -{ - SYSCALL_SUCCESS = 0, // System call succeeded - SYSCALL_FAILED = 1, // System call failed - SYSCALL_NOPROC = 2, // Failed to find required system procedure - SYSCALL_NODLL = 3, // Failed to find or load required system module - SYSCALL_UNSUPPORTED = 4, // System call unsupported on the OS -}; - - -// -// Information about paged pool memory -// -struct PAGED_POOL_INFO_t -{ - unsigned long numPagesUsed; // Number of Paged Pool pages used - unsigned long numPagesFree; // Number of Paged Pool pages free -}; - -// -// Plat_GetMemPageSize -// Returns the size of a memory page in kilobytes. -// -PLATFORM_INTERFACE unsigned long Plat_GetMemPageSize(); - -// -// Plat_GetPagedPoolInfo -// Fills in the paged pool info structure if successful. -// -PLATFORM_INTERFACE SYSTEM_CALL_RESULT_t Plat_GetPagedPoolInfo( PAGED_POOL_INFO_t *pPPI ); - - - -#endif // #ifndef SYSTEMINFORMATION_H diff --git a/Resources/NetHook/tier0/testthread.h b/Resources/NetHook/tier0/testthread.h deleted file mode 100644 index 4dbd2576..00000000 --- a/Resources/NetHook/tier0/testthread.h +++ /dev/null @@ -1,60 +0,0 @@ -//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= -// -// Purpose: exposes testing thread functions -// -//============================================================================= - -#ifndef TESTTHREAD_H -#define TESTTHREAD_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" - -// test callback -typedef void (STDCALL *TestFunc)(void *pv); - -// runs the test function -DBG_INTERFACE void Test_RunTest(TestFunc func, void *pvArg); - -// call to give the test thread a chance to run -// calling thread will block until the test thread yields -// doesn't do anything if no tests are running -DBG_INTERFACE void Test_RunFrame(); - -// true if any tests are running, or have ran -DBG_INTERFACE bool Test_IsActive(); - -// sets that the test has failed -DBG_INTERFACE void Test_SetFailed(); - -// true if any tests have failed, due to an assert, warning, or explicit fail -DBG_INTERFACE bool Test_HasFailed(); - -// true if any tests have completed -DBG_INTERFACE bool Test_HasFinished(); - -// terminates the test thread -DBG_INTERFACE void Test_TerminateThread(); - -// the following functions should only be called from the test thread - -// yields to the main thread for a single frame -// passing in is a count of the number of frames that have been yielded by this yield macro -// can be used to assert if a test thread is blocked foor -DBG_INTERFACE void TestThread_Yield(); - -// utility functions to pause the test frame until the selected condition is true -#define YIELD_UNTIL(x) { int iYieldCount = 0; while (!(x)) { TestThread_Yield(); iYieldCount++; if ( iYieldCount >= 100 ) { AssertMsg( false, #x ); break; } } } - -// use this like a while(1) loop, with break; to stop yielding -#define YIELD_UNTIL_BREAK() for (; true; TestThread_Yield()) - -// yields for a single frame -#define YIELD_FRAME() { TestThread_Yield(); } -#define YIELD_TWO_FRAMES() { TestThread_Yield(); TestThread_Yield(); } - - - -#endif // TESTTHREAD_H diff --git a/Resources/NetHook/tier0/threadtools.h b/Resources/NetHook/tier0/threadtools.h deleted file mode 100644 index e974da4d..00000000 --- a/Resources/NetHook/tier0/threadtools.h +++ /dev/null @@ -1,1577 +0,0 @@ -//========== Copyright © 2005, Valve Corporation, All rights reserved. ======== -// -// Purpose: A collection of utility classes to simplify thread handling, and -// as much as possible contain portability problems. Here avoiding -// including windows.h. -// -//============================================================================= - -#ifndef THREADTOOLS_H -#define THREADTOOLS_H - -#include - -#include "tier0/platform.h" -#include "tier0/dbg.h" -#include "tier0/vcrmode.h" - -#ifdef _LINUX -#include -#include -#endif - -#if defined( _WIN32 ) -#pragma once -#pragma warning(push) -#pragma warning(disable:4251) -#endif - -// #define THREAD_PROFILER 1 - -#ifndef STATIC_TIER0 - -#ifdef TIER0_DLL_EXPORT -#define TT_INTERFACE DLL_EXPORT -#define TT_OVERLOAD DLL_GLOBAL_EXPORT -#define TT_CLASS DLL_CLASS_EXPORT -#else -#define TT_INTERFACE DLL_IMPORT -#define TT_OVERLOAD DLL_GLOBAL_IMPORT -#define TT_CLASS DLL_CLASS_IMPORT -#endif - -#else // BUILD_AS_DLL - -#define TT_INTERFACE extern -#define TT_OVERLOAD -#define TT_CLASS -#endif // BUILD_AS_DLL - -#ifndef _RETAIL -#define THREAD_MUTEX_TRACING_SUPPORTED -#if defined(_WIN32) && defined(_DEBUG) -#define THREAD_MUTEX_TRACING_ENABLED -#endif -#endif - -#ifdef _WIN32 -typedef void *HANDLE; -#endif - -//----------------------------------------------------------------------------- -// -//----------------------------------------------------------------------------- - -const unsigned TT_INFINITE = 0xffffffff; - -#ifndef NO_THREAD_LOCAL - -#ifndef THREAD_LOCAL -#ifdef _WIN32 -#define THREAD_LOCAL __declspec(thread) -#elif _LINUX -#define THREAD_LOCAL __thread -#endif -#endif - -#endif // NO_THREAD_LOCAL - -typedef unsigned long ThreadId_t; - -//----------------------------------------------------------------------------- -// -// Simple thread creation. Differs from VCR mode/CreateThread/_beginthreadex -// in that it accepts a standard C function rather than compiler specific one. -// -//----------------------------------------------------------------------------- -FORWARD_DECLARE_HANDLE( ThreadHandle_t ); -typedef unsigned (*ThreadFunc_t)( void *pParam ); - -TT_OVERLOAD ThreadHandle_t CreateSimpleThread( ThreadFunc_t, void *pParam, ThreadId_t *pID, unsigned stackSize = 0 ); -TT_INTERFACE ThreadHandle_t CreateSimpleThread( ThreadFunc_t, void *pParam, unsigned stackSize = 0 ); -TT_INTERFACE bool ReleaseThreadHandle( ThreadHandle_t ); - - -//----------------------------------------------------------------------------- - -TT_INTERFACE void ThreadSleep(unsigned duration = 0); -TT_INTERFACE uint ThreadGetCurrentId(); -TT_INTERFACE ThreadHandle_t ThreadGetCurrentHandle(); -TT_INTERFACE int ThreadGetPriority( ThreadHandle_t hThread = NULL ); -TT_INTERFACE bool ThreadSetPriority( ThreadHandle_t hThread, int priority ); -inline bool ThreadSetPriority( int priority ) { return ThreadSetPriority( NULL, priority ); } -TT_INTERFACE bool ThreadInMainThread(); -TT_INTERFACE void DeclareCurrentThreadIsMainThread(); - -// NOTE: ThreadedLoadLibraryFunc_t needs to return the sleep time in milliseconds or TT_INFINITE -typedef int (*ThreadedLoadLibraryFunc_t)(); -TT_INTERFACE void SetThreadedLoadLibraryFunc( ThreadedLoadLibraryFunc_t func ); -TT_INTERFACE ThreadedLoadLibraryFunc_t GetThreadedLoadLibraryFunc(); - -#if defined( _WIN32 ) && !defined( _WIN64 ) && !defined( _X360 ) -extern "C" unsigned long __declspec(dllimport) __stdcall GetCurrentThreadId(); -#define ThreadGetCurrentId GetCurrentThreadId -#endif - -inline void ThreadPause() -{ -#if defined( _WIN32 ) && !defined( _X360 ) - __asm pause; -#elif _LINUX - __asm __volatile("pause"); -#elif defined( _X360 ) -#else -#error "implement me" -#endif -} - -TT_INTERFACE bool ThreadJoin( ThreadHandle_t, unsigned timeout = TT_INFINITE ); - -TT_INTERFACE void ThreadSetDebugName( ThreadId_t id, const char *pszName ); -inline void ThreadSetDebugName( const char *pszName ) { ThreadSetDebugName( (ThreadId_t)-1, pszName ); } - -TT_INTERFACE void ThreadSetAffinity( ThreadHandle_t hThread, int nAffinityMask ); - -//----------------------------------------------------------------------------- - -enum ThreadWaitResult_t -{ - TW_FAILED = 0xffffffff, // WAIT_FAILED - TW_TIMEOUT = 0x00000102, // WAIT_TIMEOUT -}; - -#ifdef _WIN32 -TT_INTERFACE int ThreadWaitForObjects( int nEvents, const HANDLE *pHandles, bool bWaitAll = true, unsigned timeout = TT_INFINITE ); -inline int ThreadWaitForObject( HANDLE handle, bool bWaitAll = true, unsigned timeout = TT_INFINITE ) { return ThreadWaitForObjects( 1, &handle, bWaitAll, timeout ); } -#endif - -//----------------------------------------------------------------------------- -// -// Interlock methods. These perform very fast atomic thread -// safe operations. These are especially relevant in a multi-core setting. -// -//----------------------------------------------------------------------------- - -#ifdef _WIN32 -#define NOINLINE -#elif _LINUX -#define NOINLINE __attribute__ ((noinline)) -#endif - -#if defined(_WIN32) && !defined(_X360) -#if ( _MSC_VER >= 1310 ) -#define USE_INTRINSIC_INTERLOCKED -#endif -#endif - -#ifdef USE_INTRINSIC_INTERLOCKED -extern "C" -{ - long __cdecl _InterlockedIncrement(volatile long*); - long __cdecl _InterlockedDecrement(volatile long*); - long __cdecl _InterlockedExchange(volatile long*, long); - long __cdecl _InterlockedExchangeAdd(volatile long*, long); - long __cdecl _InterlockedCompareExchange(volatile long*, long, long); -} - -#pragma intrinsic( _InterlockedCompareExchange ) -#pragma intrinsic( _InterlockedDecrement ) -#pragma intrinsic( _InterlockedExchange ) -#pragma intrinsic( _InterlockedExchangeAdd ) -#pragma intrinsic( _InterlockedIncrement ) - -inline long ThreadInterlockedIncrement( long volatile *p ) { Assert( (size_t)p % 4 == 0 ); return _InterlockedIncrement( p ); } -inline long ThreadInterlockedDecrement( long volatile *p ) { Assert( (size_t)p % 4 == 0 ); return _InterlockedDecrement( p ); } -inline long ThreadInterlockedExchange( long volatile *p, long value ) { Assert( (size_t)p % 4 == 0 ); return _InterlockedExchange( p, value ); } -inline long ThreadInterlockedExchangeAdd( long volatile *p, long value ) { Assert( (size_t)p % 4 == 0 ); return _InterlockedExchangeAdd( p, value ); } -inline long ThreadInterlockedCompareExchange( long volatile *p, long value, long comperand ) { Assert( (size_t)p % 4 == 0 ); return _InterlockedCompareExchange( p, value, comperand ); } -inline bool ThreadInterlockedAssignIf( long volatile *p, long value, long comperand ) { Assert( (size_t)p % 4 == 0 ); return ( _InterlockedCompareExchange( p, value, comperand ) == comperand ); } -#else -TT_INTERFACE long ThreadInterlockedIncrement( long volatile * ) NOINLINE; -TT_INTERFACE long ThreadInterlockedDecrement( long volatile * ) NOINLINE; -TT_INTERFACE long ThreadInterlockedExchange( long volatile *, long value ) NOINLINE; -TT_INTERFACE long ThreadInterlockedExchangeAdd( long volatile *, long value ) NOINLINE; -TT_INTERFACE long ThreadInterlockedCompareExchange( long volatile *, long value, long comperand ) NOINLINE; -TT_INTERFACE bool ThreadInterlockedAssignIf( long volatile *, long value, long comperand ) NOINLINE; -#endif - -inline unsigned ThreadInterlockedExchangeSubtract( long volatile *p, long value ) { return ThreadInterlockedExchangeAdd( (long volatile *)p, -value ); } - -#if defined( USE_INTRINSIC_INTERLOCKED ) && !defined( _WIN64 ) -#define TIPTR() -inline void *ThreadInterlockedExchangePointer( void * volatile *p, void *value ) { return (void *)_InterlockedExchange( reinterpret_cast(p), reinterpret_cast(value) ); } -inline void *ThreadInterlockedCompareExchangePointer( void * volatile *p, void *value, void *comperand ) { return (void *)_InterlockedCompareExchange( reinterpret_cast(p), reinterpret_cast(value), reinterpret_cast(comperand) ); } -inline bool ThreadInterlockedAssignPointerIf( void * volatile *p, void *value, void *comperand ) { return ( _InterlockedCompareExchange( reinterpret_cast(p), reinterpret_cast(value), reinterpret_cast(comperand) ) == reinterpret_cast(comperand) ); } -#else -TT_INTERFACE void *ThreadInterlockedExchangePointer( void * volatile *, void *value ) NOINLINE; -TT_INTERFACE void *ThreadInterlockedCompareExchangePointer( void * volatile *, void *value, void *comperand ) NOINLINE; -TT_INTERFACE bool ThreadInterlockedAssignPointerIf( void * volatile *, void *value, void *comperand ) NOINLINE; -#endif - -inline void const *ThreadInterlockedExchangePointerToConst( void const * volatile *p, void const *value ) { return ThreadInterlockedExchangePointer( const_cast < void * volatile * > ( p ), const_cast < void * > ( value ) ); } -inline void const *ThreadInterlockedCompareExchangePointerToConst( void const * volatile *p, void const *value, void const *comperand ) { return ThreadInterlockedCompareExchangePointer( const_cast < void * volatile * > ( p ), const_cast < void * > ( value ), const_cast < void * > ( comperand ) ); } -inline bool ThreadInterlockedAssignPointerToConstIf( void const * volatile *p, void const *value, void const *comperand ) { return ThreadInterlockedAssignPointerIf( const_cast < void * volatile * > ( p ), const_cast < void * > ( value ), const_cast < void * > ( comperand ) ); } - -TT_INTERFACE int64 ThreadInterlockedIncrement64( int64 volatile * ) NOINLINE; -TT_INTERFACE int64 ThreadInterlockedDecrement64( int64 volatile * ) NOINLINE; -TT_INTERFACE int64 ThreadInterlockedCompareExchange64( int64 volatile *, int64 value, int64 comperand ) NOINLINE; -TT_INTERFACE int64 ThreadInterlockedExchange64( int64 volatile *, int64 value ) NOINLINE; -TT_INTERFACE int64 ThreadInterlockedExchangeAdd64( int64 volatile *, int64 value ) NOINLINE; -TT_INTERFACE bool ThreadInterlockedAssignIf64(volatile int64 *pDest, int64 value, int64 comperand ) NOINLINE; - -inline unsigned ThreadInterlockedExchangeSubtract( unsigned volatile *p, unsigned value ) { return ThreadInterlockedExchangeAdd( (long volatile *)p, value ); } -inline unsigned ThreadInterlockedIncrement( unsigned volatile *p ) { return ThreadInterlockedIncrement( (long volatile *)p ); } -inline unsigned ThreadInterlockedDecrement( unsigned volatile *p ) { return ThreadInterlockedDecrement( (long volatile *)p ); } -inline unsigned ThreadInterlockedExchange( unsigned volatile *p, unsigned value ) { return ThreadInterlockedExchange( (long volatile *)p, value ); } -inline unsigned ThreadInterlockedExchangeAdd( unsigned volatile *p, unsigned value ) { return ThreadInterlockedExchangeAdd( (long volatile *)p, value ); } -inline unsigned ThreadInterlockedCompareExchange( unsigned volatile *p, unsigned value, unsigned comperand ) { return ThreadInterlockedCompareExchange( (long volatile *)p, value, comperand ); } -inline bool ThreadInterlockedAssignIf( unsigned volatile *p, unsigned value, unsigned comperand ) { return ThreadInterlockedAssignIf( (long volatile *)p, value, comperand ); } - -inline int ThreadInterlockedExchangeSubtract( int volatile *p, int value ) { return ThreadInterlockedExchangeAdd( (long volatile *)p, value ); } -inline int ThreadInterlockedIncrement( int volatile *p ) { return ThreadInterlockedIncrement( (long volatile *)p ); } -inline int ThreadInterlockedDecrement( int volatile *p ) { return ThreadInterlockedDecrement( (long volatile *)p ); } -inline int ThreadInterlockedExchange( int volatile *p, int value ) { return ThreadInterlockedExchange( (long volatile *)p, value ); } -inline int ThreadInterlockedExchangeAdd( int volatile *p, int value ) { return ThreadInterlockedExchangeAdd( (long volatile *)p, value ); } -inline int ThreadInterlockedCompareExchange( int volatile *p, int value, int comperand ) { return ThreadInterlockedCompareExchange( (long volatile *)p, value, comperand ); } -inline bool ThreadInterlockedAssignIf( int volatile *p, int value, int comperand ) { return ThreadInterlockedAssignIf( (long volatile *)p, value, comperand ); } - -//----------------------------------------------------------------------------- -// Access to VTune thread profiling -//----------------------------------------------------------------------------- -#if defined(_WIN32) && defined(THREAD_PROFILER) -TT_INTERFACE void ThreadNotifySyncPrepare(void *p); -TT_INTERFACE void ThreadNotifySyncCancel(void *p); -TT_INTERFACE void ThreadNotifySyncAcquired(void *p); -TT_INTERFACE void ThreadNotifySyncReleasing(void *p); -#else -#define ThreadNotifySyncPrepare(p) ((void)0) -#define ThreadNotifySyncCancel(p) ((void)0) -#define ThreadNotifySyncAcquired(p) ((void)0) -#define ThreadNotifySyncReleasing(p) ((void)0) -#endif - -//----------------------------------------------------------------------------- -// Encapsulation of a thread local datum (needed because THREAD_LOCAL doesn't -// work in a DLL loaded with LoadLibrary() -//----------------------------------------------------------------------------- - -#ifndef __AFXTLS_H__ // not compatible with some Windows headers -#ifndef NO_THREAD_LOCAL - -class TT_CLASS CThreadLocalBase -{ -public: - CThreadLocalBase(); - ~CThreadLocalBase(); - - void * Get() const; - void Set(void *); - -private: -#ifdef _WIN32 - uint32 m_index; -#elif _LINUX - pthread_key_t m_index; -#endif -}; - -//--------------------------------------------------------- - -#ifndef __AFXTLS_H__ - -template -class CThreadLocal : public CThreadLocalBase -{ -public: - CThreadLocal() - { - COMPILE_TIME_ASSERT( sizeof(T) == sizeof(void *) ); - } - - T Get() const - { - return reinterpret_cast(CThreadLocalBase::Get()); - } - - void Set(T val) - { - CThreadLocalBase::Set(reinterpret_cast(val)); - } -}; - -#endif - -//--------------------------------------------------------- - -template -class CThreadLocalInt : public CThreadLocal -{ -public: - operator const T() const { return Get(); } - int operator=( T i ) { Set( i ); return i; } - - T operator++() { T i = Get(); Set( ++i ); return i; } - T operator++(int) { T i = Get(); Set( i + 1 ); return i; } - - T operator--() { T i = Get(); Set( --i ); return i; } - T operator--(int) { T i = Get(); Set( i - 1 ); return i; } -}; - -//--------------------------------------------------------- - -template -class CThreadLocalPtr : private CThreadLocalBase -{ -public: - CThreadLocalPtr() {} - - operator const void *() const { return (T *)Get(); } - operator void *() { return (T *)Get(); } - - operator const T *() const { return (T *)Get(); } - operator const T *() { return (T *)Get(); } - operator T *() { return (T *)Get(); } - - int operator=( int i ) { AssertMsg( i == 0, "Only NULL allowed on integer assign" ); Set( NULL ); return 0; } - T * operator=( T *p ) { Set( p ); return p; } - - bool operator !() const { return (!Get()); } - bool operator!=( int i ) const { AssertMsg( i == 0, "Only NULL allowed on integer compare" ); return (Get() != NULL); } - bool operator==( int i ) const { AssertMsg( i == 0, "Only NULL allowed on integer compare" ); return (Get() == NULL); } - bool operator==( const void *p ) const { return (Get() == p); } - bool operator!=( const void *p ) const { return (Get() != p); } - bool operator==( const T *p ) const { return operator==((void*)p); } - bool operator!=( const T *p ) const { return operator!=((void*)p); } - - T * operator->() { return (T *)Get(); } - T & operator *() { return *((T *)Get()); } - - const T * operator->() const { return (T *)Get(); } - const T & operator *() const { return *((T *)Get()); } - - const T & operator[]( int i ) const { return *((T *)Get() + i); } - T & operator[]( int i ) { return *((T *)Get() + i); } - -private: - // Disallowed operations - CThreadLocalPtr( T *pFrom ); - CThreadLocalPtr( const CThreadLocalPtr &from ); - T **operator &(); - T * const *operator &() const; - void operator=( const CThreadLocalPtr &from ); - bool operator==( const CThreadLocalPtr &p ) const; - bool operator!=( const CThreadLocalPtr &p ) const; -}; - -#endif // NO_THREAD_LOCAL -#endif // !__AFXTLS_H__ - -//----------------------------------------------------------------------------- -// -// A super-fast thread-safe integer A simple class encapsulating the notion of an -// atomic integer used across threads that uses the built in and faster -// "interlocked" functionality rather than a full-blown mutex. Useful for simple -// things like reference counts, etc. -// -//----------------------------------------------------------------------------- - -template -class CInterlockedIntT -{ -public: - CInterlockedIntT() : m_value( 0 ) { COMPILE_TIME_ASSERT( sizeof(T) == sizeof(long) ); } - CInterlockedIntT( T value ) : m_value( value ) {} - - operator T() const { return m_value; } - - bool operator!() const { return ( m_value == 0 ); } - bool operator==( T rhs ) const { return ( m_value == rhs ); } - bool operator!=( T rhs ) const { return ( m_value != rhs ); } - - T operator++() { return (T)ThreadInterlockedIncrement( (long *)&m_value ); } - T operator++(int) { return operator++() - 1; } - - T operator--() { return (T)ThreadInterlockedDecrement( (long *)&m_value ); } - T operator--(int) { return operator--() + 1; } - - bool AssignIf( T conditionValue, T newValue ) { return ThreadInterlockedAssignIf( (long *)&m_value, (long)newValue, (long)conditionValue ); } - - T operator=( T newValue ) { ThreadInterlockedExchange((long *)&m_value, newValue); return m_value; } - - void operator+=( T add ) { ThreadInterlockedExchangeAdd( (long *)&m_value, (long)add ); } - void operator-=( T subtract ) { operator+=( -subtract ); } - void operator*=( T multiplier ) { - T original, result; - do - { - original = m_value; - result = original * multiplier; - } while ( !AssignIf( original, result ) ); - } - void operator/=( T divisor ) { - T original, result; - do - { - original = m_value; - result = original / divisor; - } while ( !AssignIf( original, result ) ); - } - - T operator+( T rhs ) const { return m_value + rhs; } - T operator-( T rhs ) const { return m_value - rhs; } - -private: - volatile T m_value; -}; - -typedef CInterlockedIntT CInterlockedInt; -typedef CInterlockedIntT CInterlockedUInt; - -//----------------------------------------------------------------------------- - -template -class CInterlockedPtr -{ -public: - CInterlockedPtr() : m_value( 0 ) { COMPILE_TIME_ASSERT( sizeof(T *) == sizeof(long) ); /* Will need to rework operator+= for 64 bit */ } - CInterlockedPtr( T *value ) : m_value( value ) {} - - operator T *() const { return m_value; } - - bool operator!() const { return ( m_value == 0 ); } - bool operator==( T *rhs ) const { return ( m_value == rhs ); } - bool operator!=( T *rhs ) const { return ( m_value != rhs ); } - - T *operator++() { return ((T *)ThreadInterlockedExchangeAdd( (long *)&m_value, sizeof(T) )) + 1; } - T *operator++(int) { return (T *)ThreadInterlockedExchangeAdd( (long *)&m_value, sizeof(T) ); } - - T *operator--() { return ((T *)ThreadInterlockedExchangeAdd( (long *)&m_value, -sizeof(T) )) - 1; } - T *operator--(int) { return (T *)ThreadInterlockedExchangeAdd( (long *)&m_value, -sizeof(T) ); } - - bool AssignIf( T *conditionValue, T *newValue ) { return ThreadInterlockedAssignPointerToConstIf( (void const **) &m_value, (void const *) newValue, (void const *) conditionValue ); } - - T *operator=( T *newValue ) { ThreadInterlockedExchangePointerToConst( (void const **) &m_value, (void const *) newValue ); return newValue; } - - void operator+=( int add ) { ThreadInterlockedExchangeAdd( (long *)&m_value, add * sizeof(T) ); } - void operator-=( int subtract ) { operator+=( -subtract ); } - - T *operator+( int rhs ) const { return m_value + rhs; } - T *operator-( int rhs ) const { return m_value - rhs; } - T *operator+( unsigned rhs ) const { return m_value + rhs; } - T *operator-( unsigned rhs ) const { return m_value - rhs; } - size_t operator-( T *p ) const { return m_value - p; } - size_t operator-( const CInterlockedPtr &p ) const { return m_value - p.m_value; } - -private: - T * volatile m_value; -}; - - -//----------------------------------------------------------------------------- -// -// Platform independent for critical sections management -// -//----------------------------------------------------------------------------- - -class TT_CLASS CThreadMutex -{ -public: - CThreadMutex(); - ~CThreadMutex(); - - //------------------------------------------------------ - // Mutex acquisition/release. Const intentionally defeated. - //------------------------------------------------------ - void Lock(); - void Lock() const { (const_cast(this))->Lock(); } - void Unlock(); - void Unlock() const { (const_cast(this))->Unlock(); } - - bool TryLock(); - bool TryLock() const { return (const_cast(this))->TryLock(); } - - //------------------------------------------------------ - // Use this to make deadlocks easier to track by asserting - // when it is expected that the current thread owns the mutex - //------------------------------------------------------ - bool AssertOwnedByCurrentThread(); - - //------------------------------------------------------ - // Enable tracing to track deadlock problems - //------------------------------------------------------ - void SetTrace( bool ); - -private: - // Disallow copying - CThreadMutex( const CThreadMutex & ); - CThreadMutex &operator=( const CThreadMutex & ); - -#if defined( _WIN32 ) - // Efficient solution to breaking the windows.h dependency, invariant is tested. -#ifdef _WIN64 - #define TT_SIZEOF_CRITICALSECTION 40 -#else -#ifndef _X360 - #define TT_SIZEOF_CRITICALSECTION 24 -#else - #define TT_SIZEOF_CRITICALSECTION 28 -#endif // !_XBOX -#endif // _WIN64 - byte m_CriticalSection[TT_SIZEOF_CRITICALSECTION]; -#elif _LINUX - pthread_mutex_t m_Mutex; - pthread_mutexattr_t m_Attr; -#else -#error -#endif - -#ifdef THREAD_MUTEX_TRACING_SUPPORTED - // Debugging (always here to allow mixed debug/release builds w/o changing size) - uint m_currentOwnerID; - uint16 m_lockCount; - bool m_bTrace; -#endif -}; - -//----------------------------------------------------------------------------- -// -// An alternative mutex that is useful for cases when thread contention is -// rare, but a mutex is required. Instances should be declared volatile. -// Sleep of 0 may not be sufficient to keep high priority threads from starving -// lesser threads. This class is not a suitable replacement for a critical -// section if the resource contention is high. -// -//----------------------------------------------------------------------------- - -#if defined(_WIN32) && !defined(THREAD_PROFILER) - -class CThreadFastMutex -{ -public: - CThreadFastMutex() - : m_ownerID( 0 ), - m_depth( 0 ) - { - } - -private: - FORCEINLINE bool TryLockInline( const uint32 threadId ) volatile - { - if ( threadId != m_ownerID && !ThreadInterlockedAssignIf( (volatile long *)&m_ownerID, (long)threadId, 0 ) ) - return false; - - ++m_depth; - return true; - } - - bool TryLock( const uint32 threadId ) volatile - { - return TryLockInline( threadId ); - } - - TT_CLASS void Lock( const uint32 threadId, unsigned nSpinSleepTime ) volatile; - -public: - bool TryLock() volatile - { -#ifdef _DEBUG - if ( m_depth == INT_MAX ) - DebuggerBreak(); - - if ( m_depth < 0 ) - DebuggerBreak(); -#endif - return TryLockInline( ThreadGetCurrentId() ); - } - -#ifndef _DEBUG - FORCEINLINE -#endif - void Lock( unsigned nSpinSleepTime = 0 ) volatile - { - const uint32 threadId = ThreadGetCurrentId(); - - if ( !TryLockInline( threadId ) ) - { - ThreadPause(); - Lock( threadId, nSpinSleepTime ); - } -#ifdef _DEBUG - if ( m_ownerID != ThreadGetCurrentId() ) - DebuggerBreak(); - - if ( m_depth == INT_MAX ) - DebuggerBreak(); - - if ( m_depth < 0 ) - DebuggerBreak(); -#endif - } - -#ifndef _DEBUG - FORCEINLINE -#endif - void Unlock() volatile - { -#ifdef _DEBUG - if ( m_ownerID != ThreadGetCurrentId() ) - DebuggerBreak(); - - if ( m_depth <= 0 ) - DebuggerBreak(); -#endif - - --m_depth; - if ( !m_depth ) - ThreadInterlockedExchange( &m_ownerID, 0 ); - } - - bool TryLock() const volatile { return (const_cast(this))->TryLock(); } - void Lock(unsigned nSpinSleepTime = 1 ) const volatile { (const_cast(this))->Lock( nSpinSleepTime ); } - void Unlock() const volatile { (const_cast(this))->Unlock(); } - - // To match regular CThreadMutex: - bool AssertOwnedByCurrentThread() { return true; } - void SetTrace( bool ) {} - - uint32 GetOwnerId() const { return m_ownerID; } - int GetDepth() const { return m_depth; } -private: - volatile uint32 m_ownerID; - int m_depth; -}; - -class ALIGN128 CAlignedThreadFastMutex : public CThreadFastMutex -{ -public: - CAlignedThreadFastMutex() - { - Assert( (size_t)this % 128 == 0 && sizeof(*this) == 128 ); - } - -private: - uint8 pad[128-sizeof(CThreadFastMutex)]; -}; - -#else -typedef CThreadMutex CThreadFastMutex; -#endif - -//----------------------------------------------------------------------------- -// -//----------------------------------------------------------------------------- - -class CThreadNullMutex -{ -public: - static void Lock() {} - static void Unlock() {} - - static bool TryLock() { return true; } - static bool AssertOwnedByCurrentThread() { return true; } - static void SetTrace( bool b ) {} - - static uint32 GetOwnerId() { return 0; } - static int GetDepth() { return 0; } -}; - -//----------------------------------------------------------------------------- -// -// A mutex decorator class used to control the use of a mutex, to make it -// less expensive when not multithreading -// -//----------------------------------------------------------------------------- - -template -class CThreadConditionalMutex : public BaseClass -{ -public: - void Lock() { if ( *pCondition ) BaseClass::Lock(); } - void Lock() const { if ( *pCondition ) BaseClass::Lock(); } - void Unlock() { if ( *pCondition ) BaseClass::Unlock(); } - void Unlock() const { if ( *pCondition ) BaseClass::Unlock(); } - - bool TryLock() { if ( *pCondition ) return BaseClass::TryLock(); else return true; } - bool TryLock() const { if ( *pCondition ) return BaseClass::TryLock(); else return true; } - bool AssertOwnedByCurrentThread() { if ( *pCondition ) return BaseClass::AssertOwnedByCurrentThread(); else return true; } - void SetTrace( bool b ) { if ( *pCondition ) BaseClass::SetTrace( b ); } -}; - -//----------------------------------------------------------------------------- -// Mutex decorator that blows up if another thread enters -//----------------------------------------------------------------------------- - -template -class CThreadTerminalMutex : public BaseClass -{ -public: - bool TryLock() { if ( !BaseClass::TryLock() ) { DebuggerBreak(); return false; } return true; } - bool TryLock() const { if ( !BaseClass::TryLock() ) { DebuggerBreak(); return false; } return true; } - void Lock() { if ( !TryLock() ) BaseClass::Lock(); } - void Lock() const { if ( !TryLock() ) BaseClass::Lock(); } - -}; - -//----------------------------------------------------------------------------- -// -// Class to Lock a critical section, and unlock it automatically -// when the lock goes out of scope -// -//----------------------------------------------------------------------------- - -template -class CAutoLockT -{ -public: - FORCEINLINE CAutoLockT( MUTEX_TYPE &lock) - : m_lock(lock) - { - m_lock.Lock(); - } - - FORCEINLINE CAutoLockT(const MUTEX_TYPE &lock) - : m_lock(const_cast(lock)) - { - m_lock.Lock(); - } - - FORCEINLINE ~CAutoLockT() - { - m_lock.Unlock(); - } - - -private: - MUTEX_TYPE &m_lock; - - // Disallow copying - CAutoLockT( const CAutoLockT & ); - CAutoLockT &operator=( const CAutoLockT & ); -}; - -typedef CAutoLockT CAutoLock; - -//--------------------------------------------------------- - -template struct CAutoLockTypeDeducer {}; -template <> struct CAutoLockTypeDeducer { typedef CThreadMutex Type_t; }; -template <> struct CAutoLockTypeDeducer { typedef CThreadNullMutex Type_t; }; -#if defined(_WIN32) && !defined(THREAD_PROFILER) -template <> struct CAutoLockTypeDeducer { typedef CThreadFastMutex Type_t; }; -template <> struct CAutoLockTypeDeducer { typedef CAlignedThreadFastMutex Type_t; }; -#endif - -#define AUTO_LOCK_( type, mutex ) \ - CAutoLockT< type > UNIQUE_ID( static_cast( mutex ) ) - -#define AUTO_LOCK( mutex ) \ - AUTO_LOCK_( CAutoLockTypeDeducer::Type_t, mutex ) - - -#define AUTO_LOCK_FM( mutex ) \ - AUTO_LOCK_( CThreadFastMutex, mutex ) - -#define LOCAL_THREAD_LOCK_( tag ) \ - ; \ - static CThreadFastMutex autoMutex_##tag; \ - AUTO_LOCK( autoMutex_##tag ) - -#define LOCAL_THREAD_LOCK() \ - LOCAL_THREAD_LOCK_(_) - -//----------------------------------------------------------------------------- -// -// Base class for event, semaphore and mutex objects. -// -//----------------------------------------------------------------------------- - -class TT_CLASS CThreadSyncObject -{ -public: - ~CThreadSyncObject(); - - //----------------------------------------------------- - // Query if object is useful - //----------------------------------------------------- - bool operator!() const; - - //----------------------------------------------------- - // Access handle - //----------------------------------------------------- -#ifdef _WIN32 - operator HANDLE() { return m_hSyncObject; } -#endif - //----------------------------------------------------- - // Wait for a signal from the object - //----------------------------------------------------- - bool Wait( uint32 dwTimeout = TT_INFINITE ); - -protected: - CThreadSyncObject(); - void AssertUseable(); - -#ifdef _WIN32 - HANDLE m_hSyncObject; -#elif _LINUX - pthread_mutex_t m_Mutex; - pthread_cond_t m_Condition; - bool m_bInitalized; - int m_cSet; - bool m_bManualReset; -#else -#error "Implement me" -#endif - -private: - CThreadSyncObject( const CThreadSyncObject & ); - CThreadSyncObject &operator=( const CThreadSyncObject & ); -}; - - -//----------------------------------------------------------------------------- -// -// Wrapper for unnamed event objects -// -//----------------------------------------------------------------------------- - -#if defined( _WIN32 ) - -//----------------------------------------------------------------------------- -// -// CThreadSemaphore -// -//----------------------------------------------------------------------------- - -class TT_CLASS CThreadSemaphore : public CThreadSyncObject -{ -public: - CThreadSemaphore(long initialValue, long maxValue); - - //----------------------------------------------------- - // Increases the count of the semaphore object by a specified - // amount. Wait() decreases the count by one on return. - //----------------------------------------------------- - bool Release(long releaseCount = 1, long * pPreviousCount = NULL ); - -private: - CThreadSemaphore(const CThreadSemaphore &); - CThreadSemaphore &operator=(const CThreadSemaphore &); -}; - - -//----------------------------------------------------------------------------- -// -// A mutex suitable for out-of-process, multi-processor usage -// -//----------------------------------------------------------------------------- - -class TT_CLASS CThreadFullMutex : public CThreadSyncObject -{ -public: - CThreadFullMutex( bool bEstablishInitialOwnership = false, const char * pszName = NULL ); - - //----------------------------------------------------- - // Release ownership of the mutex - //----------------------------------------------------- - bool Release(); - - // To match regular CThreadMutex: - void Lock() { Wait(); } - void Lock( unsigned timeout ) { Wait( timeout ); } - void Unlock() { Release(); } - bool AssertOwnedByCurrentThread() { return true; } - void SetTrace( bool ) {} - -private: - CThreadFullMutex( const CThreadFullMutex & ); - CThreadFullMutex &operator=( const CThreadFullMutex & ); -}; -#endif - - -class TT_CLASS CThreadEvent : public CThreadSyncObject -{ -public: - CThreadEvent( bool fManualReset = false ); - - //----------------------------------------------------- - // Set the state to signaled - //----------------------------------------------------- - bool Set(); - - //----------------------------------------------------- - // Set the state to nonsignaled - //----------------------------------------------------- - bool Reset(); - - //----------------------------------------------------- - // Check if the event is signaled - //----------------------------------------------------- - bool Check(); - - bool Wait( uint32 dwTimeout = TT_INFINITE ); - -private: - CThreadEvent( const CThreadEvent & ); - CThreadEvent &operator=( const CThreadEvent & ); -#ifdef _LINUX - CInterlockedInt m_cSet; -#endif -}; - -// Hard-wired manual event for use in array declarations -class CThreadManualEvent : public CThreadEvent -{ -public: - CThreadManualEvent() - : CThreadEvent( true ) - { - } -}; - -inline int ThreadWaitForEvents( int nEvents, const CThreadEvent *pEvents, bool bWaitAll = true, unsigned timeout = TT_INFINITE ) -{ -#ifdef _LINUX - Assert(0); - return 0; -#else - return ThreadWaitForObjects( nEvents, (const HANDLE *)pEvents, bWaitAll, timeout ); -#endif -} - -//----------------------------------------------------------------------------- -// -// CThreadRWLock -// -//----------------------------------------------------------------------------- - -class TT_CLASS CThreadRWLock -{ -public: - CThreadRWLock(); - - void LockForRead(); - void UnlockRead(); - void LockForWrite(); - void UnlockWrite(); - - void LockForRead() const { const_cast(this)->LockForRead(); } - void UnlockRead() const { const_cast(this)->UnlockRead(); } - void LockForWrite() const { const_cast(this)->LockForWrite(); } - void UnlockWrite() const { const_cast(this)->UnlockWrite(); } - -private: - void WaitForRead(); - - CThreadFastMutex m_mutex; - CThreadEvent m_CanWrite; - CThreadEvent m_CanRead; - - int m_nWriters; - int m_nActiveReaders; - int m_nPendingReaders; -}; - -//----------------------------------------------------------------------------- -// -// CThreadSpinRWLock -// -//----------------------------------------------------------------------------- - -#define TFRWL_ALIGN ALIGN8 - -TFRWL_ALIGN -class TT_CLASS CThreadSpinRWLock -{ -public: - CThreadSpinRWLock() { COMPILE_TIME_ASSERT( sizeof( LockInfo_t ) == sizeof( int64 ) ); Assert( (int)this % 8 == 0 ); memset( this, 0, sizeof( *this ) ); } - - bool TryLockForWrite(); - bool TryLockForRead(); - - void LockForRead(); - void UnlockRead(); - void LockForWrite(); - void UnlockWrite(); - - bool TryLockForWrite() const { return const_cast(this)->TryLockForWrite(); } - bool TryLockForRead() const { return const_cast(this)->TryLockForRead(); } - void LockForRead() const { const_cast(this)->LockForRead(); } - void UnlockRead() const { const_cast(this)->UnlockRead(); } - void LockForWrite() const { const_cast(this)->LockForWrite(); } - void UnlockWrite() const { const_cast(this)->UnlockWrite(); } - -private: - struct LockInfo_t - { - uint32 m_writerId; - int m_nReaders; - }; - - bool AssignIf( const LockInfo_t &newValue, const LockInfo_t &comperand ); - bool TryLockForWrite( const uint32 threadId ); - void SpinLockForWrite( const uint32 threadId ); - - volatile LockInfo_t m_lockInfo; - CInterlockedInt m_nWriters; -}; - -//----------------------------------------------------------------------------- -// -// A thread wrapper similar to a Java thread. -// -//----------------------------------------------------------------------------- - -class TT_CLASS CThread -{ -public: - CThread(); - virtual ~CThread(); - - //----------------------------------------------------- - - const char *GetName(); - void SetName( const char * ); - - size_t CalcStackDepth( void *pStackVariable ) { return ((byte *)m_pStackBase - (byte *)pStackVariable); } - - //----------------------------------------------------- - // Functions for the other threads - //----------------------------------------------------- - - // Start thread running - error if already running - virtual bool Start( unsigned nBytesStack = 0 ); - - // Returns true if thread has been created and hasn't yet exited - bool IsAlive(); - - // This method causes the current thread to wait until this thread - // is no longer alive. - bool Join( unsigned timeout = TT_INFINITE ); - -#ifdef _WIN32 - // Access the thread handle directly - HANDLE GetThreadHandle(); - uint GetThreadId(); -#endif - - //----------------------------------------------------- - - int GetResult(); - - //----------------------------------------------------- - // Functions for both this, and maybe, and other threads - //----------------------------------------------------- - - // Forcibly, abnormally, but relatively cleanly stop the thread - void Stop( int exitCode = 0 ); - - // Get the priority - int GetPriority() const; - - // Set the priority - bool SetPriority( int ); - - // Suspend a thread - unsigned Suspend(); - - // Resume a suspended thread - unsigned Resume(); - - // Force hard-termination of thread. Used for critical failures. - bool Terminate( int exitCode = 0 ); - - //----------------------------------------------------- - // Global methods - //----------------------------------------------------- - - // Get the Thread object that represents the current thread, if any. - // Can return NULL if the current thread was not created using - // CThread - static CThread *GetCurrentCThread(); - - // Offer a context switch. Under Win32, equivalent to Sleep(0) -#ifdef Yield -#undef Yield -#endif - static void Yield(); - - // This method causes the current thread to yield and not to be - // scheduled for further execution until a certain amount of real - // time has elapsed, more or less. - static void Sleep( unsigned duration ); - -protected: - - // Optional pre-run call, with ability to fail-create. Note Init() - // is forced synchronous with Start() - virtual bool Init(); - - // Thread will run this function on startup, must be supplied by - // derived class, performs the intended action of the thread. - virtual int Run() = 0; - - // Called when the thread exits - virtual void OnExit(); - -#ifdef _WIN32 - // Allow for custom start waiting - virtual bool WaitForCreateComplete( CThreadEvent *pEvent ); -#endif - - // "Virtual static" facility - typedef unsigned (__stdcall *ThreadProc_t)( void * ); - virtual ThreadProc_t GetThreadProc(); - - CThreadMutex m_Lock; - -private: - enum Flags - { - SUPPORT_STOP_PROTOCOL = 1 << 0 - }; - - // Thread initially runs this. param is actually 'this'. function - // just gets this and calls ThreadProc - struct ThreadInit_t - { - CThread * pThread; -#ifdef _WIN32 - CThreadEvent *pInitCompleteEvent; -#endif - bool * pfInitSuccess; - }; - - static unsigned __stdcall ThreadProc( void * pv ); - - // make copy constructor and assignment operator inaccessible - CThread( const CThread & ); - CThread &operator=( const CThread & ); - -#ifdef _WIN32 - HANDLE m_hThread; - ThreadId_t m_threadId; -#elif _LINUX - pthread_t m_threadId; -#endif - int m_result; - char m_szName[32]; - void * m_pStackBase; - unsigned m_flags; -}; - -//----------------------------------------------------------------------------- -// Simple thread class encompasses the notion of a worker thread, handing -// synchronized communication. -//----------------------------------------------------------------------------- - -#ifdef _WIN32 - -// These are internal reserved error results from a call attempt -enum WTCallResult_t -{ - WTCR_FAIL = -1, - WTCR_TIMEOUT = -2, - WTCR_THREAD_GONE = -3, -}; - -class TT_CLASS CWorkerThread : public CThread -{ -public: - CWorkerThread(); - - //----------------------------------------------------- - // - // Inter-thread communication - // - // Calls in either direction take place on the same "channel." - // Seperate functions are specified to make identities obvious - // - //----------------------------------------------------- - - // Master: Signal the thread, and block for a response - int CallWorker( unsigned, unsigned timeout = TT_INFINITE, bool fBoostWorkerPriorityToMaster = true ); - - // Worker: Signal the thread, and block for a response - int CallMaster( unsigned, unsigned timeout = TT_INFINITE ); - - // Wait for the next request - bool WaitForCall( unsigned dwTimeout, unsigned *pResult = NULL ); - bool WaitForCall( unsigned *pResult = NULL ); - - // Is there a request? - bool PeekCall( unsigned *pParam = NULL ); - - // Reply to the request - void Reply( unsigned ); - - // Wait for a reply in the case when CallWorker() with timeout != TT_INFINITE - int WaitForReply( unsigned timeout = TT_INFINITE ); - - // If you want to do WaitForMultipleObjects you'll need to include - // this handle in your wait list or you won't be responsive - HANDLE GetCallHandle(); - - // Find out what the request was - unsigned GetCallParam() const; - - // Boost the worker thread to the master thread, if worker thread is lesser, return old priority - int BoostPriority(); - -protected: - typedef uint32 (__stdcall *WaitFunc_t)( uint32 nHandles, const HANDLE*pHandles, int bWaitAll, uint32 timeout ); - int Call( unsigned, unsigned timeout, bool fBoost, WaitFunc_t = NULL ); - int WaitForReply( unsigned timeout, WaitFunc_t ); - -private: - CWorkerThread( const CWorkerThread & ); - CWorkerThread &operator=( const CWorkerThread & ); - -#ifdef _WIN32 - CThreadEvent m_EventSend; - CThreadEvent m_EventComplete; -#endif - - unsigned m_Param; - int m_ReturnVal; -}; - -#else - -typedef CThread CWorkerThread; - -#endif - -// a unidirectional message queue. A queue of type T. Not especially high speed since each message -// is malloced/freed. Note that if your message class has destructors/constructors, they MUST be -// thread safe! -template class CMessageQueue -{ - CThreadEvent SignalEvent; // signals presence of data - CThreadMutex QueueAccessMutex; - - // the parts protected by the mutex - struct MsgNode - { - MsgNode *Next; - T Data; - }; - - MsgNode *Head; - MsgNode *Tail; - -public: - CMessageQueue( void ) - { - Head = Tail = NULL; - } - - // check for a message. not 100% reliable - someone could grab the message first - bool MessageWaiting( void ) - { - return ( Head != NULL ); - } - - void WaitMessage( T *pMsg ) - { - for(;;) - { - while( ! MessageWaiting() ) - SignalEvent.Wait(); - QueueAccessMutex.Lock(); - if (! Head ) - { - // multiple readers could make this null - QueueAccessMutex.Unlock(); - continue; - } - *( pMsg ) = Head->Data; - MsgNode *remove_this = Head; - Head = Head->Next; - if (! Head) // if empty, fix tail ptr - Tail = NULL; - QueueAccessMutex.Unlock(); - delete remove_this; - break; - } - } - - void QueueMessage( T const &Msg) - { - MsgNode *new1=new MsgNode; - new1->Data=Msg; - new1->Next=NULL; - QueueAccessMutex.Lock(); - if ( Tail ) - { - Tail->Next=new1; - Tail = new1; - } - else - { - Head = new1; - Tail = new1; - } - SignalEvent.Set(); - QueueAccessMutex.Unlock(); - } -}; - - -//----------------------------------------------------------------------------- -// -// CThreadMutex. Inlining to reduce overhead and to allow client code -// to decide debug status (tracing) -// -//----------------------------------------------------------------------------- - -#ifdef _WIN32 -typedef struct _RTL_CRITICAL_SECTION RTL_CRITICAL_SECTION; -typedef RTL_CRITICAL_SECTION CRITICAL_SECTION; - -#ifndef _X360 -extern "C" -{ - void __declspec(dllimport) __stdcall InitializeCriticalSection(CRITICAL_SECTION *); - void __declspec(dllimport) __stdcall EnterCriticalSection(CRITICAL_SECTION *); - void __declspec(dllimport) __stdcall LeaveCriticalSection(CRITICAL_SECTION *); - void __declspec(dllimport) __stdcall DeleteCriticalSection(CRITICAL_SECTION *); -}; -#endif - -//--------------------------------------------------------- - -inline void CThreadMutex::Lock() -{ -#ifdef THREAD_MUTEX_TRACING_ENABLED - uint thisThreadID = ThreadGetCurrentId(); - if ( m_bTrace && m_currentOwnerID && ( m_currentOwnerID != thisThreadID ) ) - Msg( "Thread %u about to wait for lock %x owned by %u\n", ThreadGetCurrentId(), (CRITICAL_SECTION *)&m_CriticalSection, m_currentOwnerID ); -#endif - - VCRHook_EnterCriticalSection((CRITICAL_SECTION *)&m_CriticalSection); - -#ifdef THREAD_MUTEX_TRACING_ENABLED - if (m_lockCount == 0) - { - // we now own it for the first time. Set owner information - m_currentOwnerID = thisThreadID; - if ( m_bTrace ) - Msg( "Thread %u now owns lock 0x%x\n", m_currentOwnerID, (CRITICAL_SECTION *)&m_CriticalSection ); - } - m_lockCount++; -#endif -} - -//--------------------------------------------------------- - -inline void CThreadMutex::Unlock() -{ -#ifdef THREAD_MUTEX_TRACING_ENABLED - AssertMsg( m_lockCount >= 1, "Invalid unlock of thread lock" ); - m_lockCount--; - if (m_lockCount == 0) - { - if ( m_bTrace ) - Msg( "Thread %u releasing lock 0x%x\n", m_currentOwnerID, (CRITICAL_SECTION *)&m_CriticalSection ); - m_currentOwnerID = 0; - } -#endif - LeaveCriticalSection((CRITICAL_SECTION *)&m_CriticalSection); -} - -//--------------------------------------------------------- - -inline bool CThreadMutex::AssertOwnedByCurrentThread() -{ -#ifdef THREAD_MUTEX_TRACING_ENABLED - if (ThreadGetCurrentId() == m_currentOwnerID) - return true; - AssertMsg3( 0, "Expected thread %u as owner of lock 0x%x, but %u owns", ThreadGetCurrentId(), (CRITICAL_SECTION *)&m_CriticalSection, m_currentOwnerID ); - return false; -#else - return true; -#endif -} - -//--------------------------------------------------------- - -inline void CThreadMutex::SetTrace( bool bTrace ) -{ -#ifdef THREAD_MUTEX_TRACING_ENABLED - m_bTrace = bTrace; -#endif -} - -//--------------------------------------------------------- - -#elif _LINUX - -inline CThreadMutex::CThreadMutex() -{ - // enable recursive locks as we need them - pthread_mutexattr_init( &m_Attr ); - pthread_mutexattr_settype( &m_Attr, PTHREAD_MUTEX_RECURSIVE_NP ); - pthread_mutex_init( &m_Mutex, &m_Attr ); -} - -//--------------------------------------------------------- - -inline CThreadMutex::~CThreadMutex() -{ - pthread_mutex_destroy( &m_Mutex ); -} - -//--------------------------------------------------------- - -inline void CThreadMutex::Lock() -{ - pthread_mutex_lock( &m_Mutex ); -} - -//--------------------------------------------------------- - -inline void CThreadMutex::Unlock() -{ - pthread_mutex_unlock( &m_Mutex ); -} - -//--------------------------------------------------------- - -inline bool CThreadMutex::AssertOwnedByCurrentThread() -{ - return true; -} - -//--------------------------------------------------------- - -inline void CThreadMutex::SetTrace(bool fTrace) -{ -} - -#endif // _LINUX - -//----------------------------------------------------------------------------- -// -// CThreadRWLock inline functions -// -//----------------------------------------------------------------------------- - -inline CThreadRWLock::CThreadRWLock() -: m_CanRead( true ), - m_nWriters( 0 ), - m_nActiveReaders( 0 ), - m_nPendingReaders( 0 ) -{ -} - -inline void CThreadRWLock::LockForRead() -{ - m_mutex.Lock(); - if ( m_nWriters) - { - WaitForRead(); - } - m_nActiveReaders++; - m_mutex.Unlock(); -} - -inline void CThreadRWLock::UnlockRead() -{ - m_mutex.Lock(); - m_nActiveReaders--; - if ( m_nActiveReaders == 0 && m_nWriters != 0 ) - { - m_CanWrite.Set(); - } - m_mutex.Unlock(); -} - - -//----------------------------------------------------------------------------- -// -// CThreadSpinRWLock inline functions -// -//----------------------------------------------------------------------------- - -inline bool CThreadSpinRWLock::AssignIf( const LockInfo_t &newValue, const LockInfo_t &comperand ) -{ - return ThreadInterlockedAssignIf64( (int64 *)&m_lockInfo, *((int64 *)&newValue), *((int64 *)&comperand) ); -} - -inline bool CThreadSpinRWLock::TryLockForWrite( const uint32 threadId ) -{ - // In order to grab a write lock, there can be no readers and no owners of the write lock - if ( m_lockInfo.m_nReaders > 0 || ( m_lockInfo.m_writerId && m_lockInfo.m_writerId != threadId ) ) - { - return false; - } - - static const LockInfo_t oldValue = { 0, 0 }; - LockInfo_t newValue = { threadId, 0 }; - const bool bSuccess = AssignIf( newValue, oldValue ); -#if defined(_X360) - if ( bSuccess ) - { - // X360TBD: Serious perf implications. Not Yet. __sync(); - } -#endif - return bSuccess; -} - -inline bool CThreadSpinRWLock::TryLockForWrite() -{ - m_nWriters++; - if ( !TryLockForWrite( ThreadGetCurrentId() ) ) - { - m_nWriters--; - return false; - } - return true; -} - -inline bool CThreadSpinRWLock::TryLockForRead() -{ - if ( m_nWriters != 0 ) - { - return false; - } - // In order to grab a write lock, the number of readers must not change and no thread can own the write - LockInfo_t oldValue; - LockInfo_t newValue; - - oldValue.m_nReaders = m_lockInfo.m_nReaders; - oldValue.m_writerId = 0; - newValue.m_nReaders = oldValue.m_nReaders + 1; - newValue.m_writerId = 0; - - const bool bSuccess = AssignIf( newValue, oldValue ); -#if defined(_X360) - if ( bSuccess ) - { - // X360TBD: Serious perf implications. Not Yet. __sync(); - } -#endif - return bSuccess; -} - -inline void CThreadSpinRWLock::LockForWrite() -{ - const uint32 threadId = ThreadGetCurrentId(); - - m_nWriters++; - - if ( !TryLockForWrite( threadId ) ) - { - ThreadPause(); - SpinLockForWrite( threadId ); - } -} - -//----------------------------------------------------------------------------- - -#if defined( _WIN32 ) -#pragma warning(pop) -#endif - -#endif // THREADTOOLS_H diff --git a/Resources/NetHook/tier0/tslist.h b/Resources/NetHook/tier0/tslist.h deleted file mode 100644 index c0df0b25..00000000 --- a/Resources/NetHook/tier0/tslist.h +++ /dev/null @@ -1,794 +0,0 @@ -//========== Copyright © 2005, Valve Corporation, All rights reserved. ======== -// -// Purpose: -// -// LIFO from disassembly of Windows API and http://perso.wanadoo.fr/gmem/evenements/jim2002/articles/L17_Fober.pdf -// FIFO from http://perso.wanadoo.fr/gmem/evenements/jim2002/articles/L17_Fober.pdf -// -//============================================================================= - -#ifndef TSLIST_H -#define TSLIST_H - -#if defined( _WIN32 ) -#pragma once -#endif - -#if ( defined(_WIN64) || defined(_X360) ) -#define USE_NATIVE_SLIST -#endif - -#if defined( USE_NATIVE_SLIST ) && !defined( _X360 ) -#define WIN32_LEAN_AND_MEAN -#include -#endif - -#include "tier0/dbg.h" -#include "tier0/threadtools.h" - -#include "tier0/memdbgon.h" - -//----------------------------------------------------------------------------- - -#if defined(_WIN64) -#define TSLIST_HEAD_ALIGNMENT MEMORY_ALLOCATION_ALIGNMENT -#define TSLIST_NODE_ALIGNMENT MEMORY_ALLOCATION_ALIGNMENT -#else -#define TSLIST_HEAD_ALIGNMENT 8 -#define TSLIST_NODE_ALIGNMENT 8 -#endif - -#define TSLIST_HEAD_ALIGN DECL_ALIGN(TSLIST_HEAD_ALIGNMENT) -#define TSLIST_NODE_ALIGN DECL_ALIGN(TSLIST_NODE_ALIGNMENT) - -//----------------------------------------------------------------------------- - -PLATFORM_INTERFACE bool RunTSQueueTests( int nListSize = 10000, int nTests = 1 ); -PLATFORM_INTERFACE bool RunTSListTests( int nListSize = 10000, int nTests = 1 ); - -//----------------------------------------------------------------------------- -// Lock free list. -//----------------------------------------------------------------------------- -//#define USE_NATIVE_SLIST - -#ifdef USE_NATIVE_SLIST -typedef SLIST_ENTRY TSLNodeBase_t; -typedef SLIST_HEADER TSLHead_t; -#else -struct TSLIST_NODE_ALIGN TSLNodeBase_t -{ - TSLNodeBase_t *Next; // name to match Windows -}; - -union TSLHead_t -{ - struct Value_t - { - TSLNodeBase_t *Next; - int16 Depth; - int16 Sequence; - } value; - - int64 value64; -}; -#endif - -//------------------------------------- - -class TSLIST_HEAD_ALIGN CTSListBase -{ -public: - CTSListBase() - { - if ( ((size_t)&m_Head) % TSLIST_HEAD_ALIGNMENT != 0 ) - { - Error( "CTSListBase: Misaligned list\n" ); - DebuggerBreak(); - } - -#ifdef USE_NATIVE_SLIST - InitializeSListHead( &m_Head ); -#else - m_Head.value64 = (int64)0; -#endif - } - - ~CTSListBase() - { - Detach(); - } - - TSLNodeBase_t *Push( TSLNodeBase_t *pNode ) - { - if ( (size_t)pNode % TSLIST_NODE_ALIGNMENT != 0 ) - { - Error( "CTSListBase: Misaligned node\n" ); - DebuggerBreak(); - } - -#ifdef USE_NATIVE_SLIST -#ifdef _X360 - // integrated write-release barrier - return (TSLNodeBase_t *)InterlockedPushEntrySListRelease( &m_Head, pNode ); -#else - return (TSLNodeBase_t *)InterlockedPushEntrySList( &m_Head, pNode ); -#endif -#else - TSLHead_t oldHead; - TSLHead_t newHead; - - for (;;) - { - oldHead.value64 = m_Head.value64; - pNode->Next = oldHead.value.Next; - newHead.value.Next = pNode; - *((uint32 *)&newHead.value.Depth) = *((uint32 *)&oldHead.value.Depth) + 0x10001; - - if ( ThreadInterlockedAssignIf64( &m_Head.value64, newHead.value64, oldHead.value64 ) ) - { - break; - } - ThreadPause(); - }; - - return (TSLNodeBase_t *)oldHead.value.Next; -#endif - } - - TSLNodeBase_t *Pop() - { -#ifdef USE_NATIVE_SLIST -#ifdef _X360 - // integrated read-acquire barrier - TSLNodeBase_t *pNode = (TSLNodeBase_t *)InterlockedPopEntrySListAcquire( &m_Head ); -#else - TSLNodeBase_t *pNode = (TSLNodeBase_t *)InterlockedPopEntrySList( &m_Head ); -#endif - return pNode; -#else - TSLHead_t oldHead; - TSLHead_t newHead; - - for (;;) - { - oldHead.value64 = m_Head.value64; - if ( !oldHead.value.Next ) - return NULL; - - newHead.value.Next = oldHead.value.Next->Next; - *((uint32 *)&newHead.value.Depth) = *((uint32 *)&oldHead.value.Depth) - 1; - - if ( ThreadInterlockedAssignIf64( &m_Head.value64, newHead.value64, oldHead.value64 ) ) - { - break; - } - ThreadPause(); - }; - - return (TSLNodeBase_t *)oldHead.value.Next; -#endif - } - - TSLNodeBase_t *Detach() - { -#ifdef USE_NATIVE_SLIST - TSLNodeBase_t *pBase = (TSLNodeBase_t *)InterlockedFlushSList( &m_Head ); -#ifdef _X360 - __lwsync(); // read-acquire barrier -#endif - return pBase; -#else - TSLHead_t oldHead; - TSLHead_t newHead; - - do - { - ThreadPause(); - - oldHead.value64 = m_Head.value64; - if ( !oldHead.value.Next ) - return NULL; - - newHead.value.Next = NULL; - *((uint32 *)&newHead.value.Depth) = *((uint32 *)&oldHead.value.Depth) & 0xffff0000; - - } while( !ThreadInterlockedAssignIf64( &m_Head.value64, newHead.value64, oldHead.value64 ) ); - - return (TSLNodeBase_t *)oldHead.value.Next; -#endif - } - - int Count() const - { -#ifdef USE_NATIVE_SLIST - return QueryDepthSList( &m_Head ); -#else - return m_Head.value.Depth; -#endif - } - -private: - TSLHead_t m_Head; -}; - -//------------------------------------- - -template -class TSLIST_HEAD_ALIGN CTSSimpleList : public CTSListBase -{ -public: - void Push( T *pNode ) - { - Assert( sizeof(T) >= sizeof(TSLNodeBase_t) ); - CTSListBase::Push( (TSLNodeBase_t *)pNode ); - } - - T *Pop() - { - return (T *)CTSListBase::Pop(); - } -}; - -//------------------------------------- - -template -class TSLIST_HEAD_ALIGN CTSList : public CTSListBase -{ -public: - struct TSLIST_NODE_ALIGN Node_t : public TSLNodeBase_t - { - Node_t() {} - Node_t( const T &init ) : elem( init ) {} - - T elem; - - }; - - ~CTSList() - { - Purge(); - } - - void Purge() - { - Node_t *pCurrent = Detach(); - Node_t *pNext; - while ( pCurrent ) - { - pNext = (Node_t *)pCurrent->Next; - delete pCurrent; - pCurrent = pNext; - } - } - - void RemoveAll() - { - Purge(); - } - - Node_t *Push( Node_t *pNode ) - { - return (Node_t *)CTSListBase::Push( pNode ); - } - - Node_t *Pop() - { - return (Node_t *)CTSListBase::Pop(); - } - - void PushItem( const T &init ) - { - Push( new Node_t( init ) ); - } - - bool PopItem( T *pResult) - { - Node_t *pNode = Pop(); - if ( !pNode ) - return false; - *pResult = pNode->elem; - delete pNode; - return true; - } - - Node_t *Detach() - { - return (Node_t *)CTSListBase::Detach(); - } - -}; - -// this is a replacement for CTSList<> and CObjectPool<> that does not -// have a per-item, per-alloc new/delete overhead -// similar to CTSSimpleList except that it allocates it's own pool objects -// and frees them on destruct. Also it does not overlay the TSNodeBase_t memory -// on T's memory -template< class T > -class TSLIST_HEAD_ALIGN CTSPool : public CTSListBase -{ - // packs the node and the item (T) into a single struct and pools those - struct TSLIST_NODE_ALIGN simpleTSPoolStruct_t : public TSLNodeBase_t - { - T elem; - }; - -public: - - ~CTSPool() - { - simpleTSPoolStruct_t *pNode = NULL; - while ( 1 ) - { - pNode = (simpleTSPoolStruct_t *)CTSListBase::Pop(); - if ( !pNode ) - break; - delete pNode; - } - } - - void PutObject( T *pInfo ) - { - char *pElem = (char *)pInfo; - pElem -= offsetof(simpleTSPoolStruct_t,elem); - simpleTSPoolStruct_t *pNode = (simpleTSPoolStruct_t *)pElem; - - CTSListBase::Push( pNode ); - } - - T *GetObject() - { - simpleTSPoolStruct_t *pNode = (simpleTSPoolStruct_t *)CTSListBase::Pop(); - if ( !pNode ) - { - pNode = new simpleTSPoolStruct_t; - } - return &pNode->elem; - } -}; - -//------------------------------------- - -template -class TSLIST_HEAD_ALIGN CTSListWithFreeList : public CTSListBase -{ -public: - struct TSLIST_NODE_ALIGN Node_t : public TSLNodeBase_t - { - Node_t() {} - Node_t( const T &init ) : elem( init ) {} - - T elem; - }; - - ~CTSListWithFreeList() - { - Purge(); - } - - void Purge() - { - Node_t *pCurrent = Detach(); - Node_t *pNext; - while ( pCurrent ) - { - pNext = (Node_t *)pCurrent->Next; - delete pCurrent; - pCurrent = pNext; - } - pCurrent = (Node_t *)m_FreeList.Detach(); - while ( pCurrent ) - { - pNext = (Node_t *)pCurrent->Next; - delete pCurrent; - pCurrent = pNext; - } - } - - void RemoveAll() - { - Node_t *pCurrent = Detach(); - Node_t *pNext; - while ( pCurrent ) - { - pNext = (Node_t *)pCurrent->Next; - m_FreeList.Push( pCurrent ); - pCurrent = pNext; - } - } - - Node_t *Push( Node_t *pNode ) - { - return (Node_t *)CTSListBase::Push( pNode ); - } - - Node_t *Pop() - { - return (Node_t *)CTSListBase::Pop(); - } - - void PushItem( const T &init ) - { - Node_t *pNode = (Node_t *)m_FreeList.Pop(); - if ( !pNode ) - { - pNode = new Node_t; - } - pNode->elem = init; - Push( pNode ); - } - - bool PopItem( T *pResult) - { - Node_t *pNode = Pop(); - if ( !pNode ) - return false; - *pResult = pNode->elem; - m_FreeList.Push( pNode ); - return true; - } - - Node_t *Detach() - { - return (Node_t *)CTSListBase::Detach(); - } - - void FreeNode( Node_t *pNode ) - { - m_FreeList.Push( pNode ); - } - -private: - CTSListBase m_FreeList; -}; - -//----------------------------------------------------------------------------- -// Lock free queue -// -// A special consideration: the element type should be simple. This code -// actually dereferences freed nodes as part of pop, but later detects -// that. If the item in the queue is a complex type, only bad things can -// come of that. Also, therefore, if you're using Push/Pop instead of -// push item, be aware that the node memory cannot be freed until -// all threads that might have been popping have completed the pop. -// The PushItem()/PopItem() for handles this by keeping a persistent -// free list. Dont mix Push/PushItem. Note also nodes will be freed at the end, -// and are expected to have been allocated with operator new. -//----------------------------------------------------------------------------- - -template -class TSLIST_HEAD_ALIGN CTSQueue -{ -public: - struct TSLIST_NODE_ALIGN Node_t - { - Node_t() {} - Node_t( const T &init ) : elem( init ) {} - - Node_t *pNext; - T elem; - }; - - union TSLIST_HEAD_ALIGN NodeLink_t - { - struct Value_t - { - Node_t *pNode; - int32 sequence; - } value; - - int64 value64; - }; - - CTSQueue() - { - COMPILE_TIME_ASSERT( sizeof(Node_t) >= sizeof(TSLNodeBase_t) ); - if ( ((size_t)&m_Head) % TSLIST_HEAD_ALIGNMENT != 0 ) - { - Error( "CTSQueue: Misaligned queue\n" ); - DebuggerBreak(); - } - if ( ((size_t)&m_Tail) % TSLIST_HEAD_ALIGNMENT != 0 ) - { - Error( "CTSQueue: Misaligned queue\n" ); - DebuggerBreak(); - } - m_Count = 0; - m_Head.value.sequence = m_Tail.value.sequence = 0; - m_Head.value.pNode = m_Tail.value.pNode = new Node_t; // list always contains a dummy node - m_Head.value.pNode->pNext = End(); - } - - ~CTSQueue() - { - Purge(); - Assert( m_Count == 0 ); - Assert( m_Head.value.pNode == m_Tail.value.pNode ); - Assert( m_Head.value.pNode->pNext == End() ); - delete m_Head.value.pNode; - } - - // Note: Purge, RemoveAll, and Validate are *not* threadsafe - void Purge() - { - if ( IsDebug() ) - { - Validate(); - } - - Node_t *pNode; - while ( ( pNode = Pop() ) != NULL ) - { - delete pNode; - } - - while ( ( pNode = (Node_t *)m_FreeNodes.Pop() ) != NULL ) - { - delete pNode; - } - - Assert( m_Count == 0 ); - Assert( m_Head.value.pNode == m_Tail.value.pNode ); - Assert( m_Head.value.pNode->pNext == End() ); - - m_Head.value.sequence = m_Tail.value.sequence = 0; - } - - void RemoveAll() - { - if ( IsDebug() ) - { - Validate(); - } - - Node_t *pNode; - while ( ( pNode = Pop() ) != NULL ) - { - m_FreeNodes.Push( (TSLNodeBase_t *)pNode ); - } - } - - bool Validate() - { - bool bResult = true; - int nNodes = 0; - if ( m_Tail.value.pNode->pNext != End() ) - { - DebuggerBreakIfDebugging(); - bResult = false; - } - - if ( m_Count == 0 ) - { - if ( m_Head.value.pNode != m_Tail.value.pNode ) - { - DebuggerBreakIfDebugging(); - bResult = false; - } - } - - Node_t *pNode = m_Head.value.pNode; - while ( pNode != End() ) - { - nNodes++; - pNode = pNode->pNext; - } - - nNodes--;// skip dummy node - - if ( nNodes != m_Count ) - { - DebuggerBreakIfDebugging(); - bResult = false; - } - - if ( !bResult ) - { - Msg( "Corrupt CTSQueueDetected" ); - } - - return bResult; - } - - void FinishPush( Node_t *pNode, const NodeLink_t &oldTail ) - { - NodeLink_t newTail; - - newTail.value.pNode = pNode; - newTail.value.sequence = oldTail.value.sequence + 1; - -#ifdef _X360 - __lwsync(); // write-release barrier -#endif - InterlockedCompareExchangeNodeLink( &m_Tail, newTail, oldTail ); - } - - Node_t *Push( Node_t *pNode ) - { -#ifdef _DEBUG - if ( (size_t)pNode % TSLIST_NODE_ALIGNMENT != 0 ) - { - Error( "CTSListBase: Misaligned node\n" ); - DebuggerBreak(); - } -#endif - - NodeLink_t oldTail; - - pNode->pNext = End(); - - for (;;) - { - oldTail = m_Tail; - if ( InterlockedCompareExchangeNode( &(oldTail.value.pNode->pNext), pNode, End() ) == End() ) - { - break; - } - else - { - // Another thread is trying to push, help it along - FinishPush( oldTail.value.pNode->pNext, oldTail ); - } - } - - FinishPush( pNode, oldTail ); - - m_Count++; - - return oldTail.value.pNode; - } - - Node_t *Pop() - { - #define TSQUEUE_BAD_NODE_LINK ((Node_t *)0xdeadbeef) - NodeLink_t * volatile pHead = &m_Head; - NodeLink_t * volatile pTail = &m_Tail; - Node_t * volatile * pHeadNode = &m_Head.value.pNode; - volatile int * volatile pHeadSequence = &m_Head.value.sequence; - Node_t * volatile * pTailNode = &pTail->value.pNode; - - NodeLink_t head; - NodeLink_t newHead; - Node_t *pNext; - int tailSequence; - T elem; - - for (;;) - { - head.value.sequence = *pHeadSequence; // must grab sequence first, which allows condition below to ensure pNext is valid -#ifdef _X360 - __lwsync(); // 360 needs a barrier to prevent reordering of these assignments -#endif - head.value.pNode = *pHeadNode; - tailSequence = pTail->value.sequence; - pNext = head.value.pNode->pNext; - - if ( pNext && head.value.sequence == *pHeadSequence ) // Checking pNext only to force optimizer to not reorder the assignment to pNext and the compare of the sequence - { - if ( bTestOptimizer ) - { - if ( pNext == TSQUEUE_BAD_NODE_LINK ) - { - Msg( "Bad node link detected\n" ); - continue; - } - } - if ( head.value.pNode == *pTailNode ) - { - if ( pNext == End() ) - { - return NULL; - } - - // Another thread is trying to push, help it along - NodeLink_t &oldTail = head; // just reuse local memory for head to build old tail - oldTail.value.sequence = tailSequence; // reuse head pNode - FinishPush( pNext, oldTail ); - } - else if ( pNext != End() ) - { - elem = pNext->elem; // NOTE: next could be a freed node here, by design - newHead.value.pNode = pNext; - newHead.value.sequence = head.value.sequence + 1; - if ( InterlockedCompareExchangeNodeLink( pHead, newHead, head ) ) - { -#ifdef _X360 - __lwsync(); // read-acquire barrier -#endif - if ( bTestOptimizer ) - { - head.value.pNode->pNext = TSQUEUE_BAD_NODE_LINK; - } - break; - } - } - } - } - - m_Count--; - head.value.pNode->elem = elem; - return head.value.pNode; - } - - void FreeNode( Node_t *pNode ) - { - m_FreeNodes.Push( (TSLNodeBase_t *)pNode ); - } - - void PushItem( const T &init ) - { - Node_t *pNode = (Node_t *)m_FreeNodes.Pop(); - if ( pNode ) - { - pNode->elem = init; - } - else - { - pNode = new Node_t( init ); - } - Push( pNode ); - } - - bool PopItem( T *pResult) - { - Node_t *pNode = Pop(); - if ( !pNode ) - return false; - *pResult = pNode->elem; - m_FreeNodes.Push( (TSLNodeBase_t *)pNode ); - return true; - } - - int Count() - { - return m_Count; - } - -private: - Node_t *End() { return (Node_t *)this; } // just need a unique signifier - -#ifndef _WIN64 - Node_t *InterlockedCompareExchangeNode( Node_t * volatile *ppNode, Node_t *value, Node_t *comperand ) - { - return (Node_t *)::ThreadInterlockedCompareExchangePointer( (void **)ppNode, value, comperand ); - } - - bool InterlockedCompareExchangeNodeLink( NodeLink_t volatile *pLink, const NodeLink_t &value, const NodeLink_t &comperand ) - { - return ThreadInterlockedAssignIf64( (int64 *)pLink, value.value64, comperand.value64 ); - } - -#else - Node_t *InterlockedCompareExchangeNode( Node_t * volatile *ppNode, Node_t *value, Node_t *comperand ) - { - AUTO_LOCK( m_ExchangeMutex ); - Node_t *retVal = *ppNode; - if ( *ppNode == comperand ) - *ppNode = value; - return retVal; - } - - bool InterlockedCompareExchangeNodeLink( NodeLink_t volatile *pLink, const NodeLink_t &value, const NodeLink_t &comperand ) - { - AUTO_LOCK( m_ExchangeMutex ); - if ( pLink->value64 == comperand.value64 ) - { - pLink->value64 = value.value64; - return true; - } - return false; - } - - CThreadFastMutex m_ExchangeMutex; -#endif - - NodeLink_t m_Head; - NodeLink_t m_Tail; - - CInterlockedInt m_Count; - - CTSListBase m_FreeNodes; -}; - -#include "tier0/memdbgoff.h" - -#endif // TSLIST_H diff --git a/Resources/NetHook/tier0/validator.h b/Resources/NetHook/tier0/validator.h deleted file mode 100644 index d2cc2dba..00000000 --- a/Resources/NetHook/tier0/validator.h +++ /dev/null @@ -1,73 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - - -#include "valobject.h" - -#ifndef VALIDATOR_H -#define VALIDATOR_H - -#ifdef _WIN32 -#pragma once -#endif - - -#ifdef DBGFLAG_VALIDATE - - -class CValidator -{ -public: - // Constructors & destructors - CValidator( void ); - ~CValidator( void ); - - // Call this each time we enter a new Validate function - void Push( tchar *pchType, void *pvObj, tchar *pchName ); - - // Call this each time we exit a Validate function - void Pop( void ); - - // Claim ownership of a memory block - void ClaimMemory( void *pvMem ); - - // Finish performing a check and perform necessary computations - void Finalize( void ); - - // Render our results to the console - void RenderObjects( int cubThreshold ); // Render all reported objects - void RenderLeaks( void ); // Render all memory leaks - - // List manipulation functions: - CValObject *FindObject( void *pvObj ); // Returns CValObject containing pvObj, or NULL. - void DiffAgainst( CValidator *pOtherValidator ); // Removes any entries from this validator that are also present in the other. - - // Accessors - bool BMemLeaks( void ) { return m_bMemLeaks; }; - CValObject *PValObjectFirst( void ) { return m_pValObjectFirst; }; - - void Validate( CValidator &validator, tchar *pchName ); // Validate our internal structures - - -private: - CValObject *m_pValObjectFirst; // Linked list of all ValObjects - CValObject *m_pValObjectLast; // Last ValObject on the linked list - - CValObject *m_pValObjectCur; // Object we're current processing - - int m_cpvOwned; // Total # of blocks owned - - int m_cpubLeaked; // # of leaked memory blocks - int m_cubLeaked; // Amount of leaked memory - bool m_bMemLeaks; // Has any memory leaked? -}; - - -#endif // DBGFLAG_VALIDATE - - -#endif // VALIDATOR_H diff --git a/Resources/NetHook/tier0/valobject.h b/Resources/NetHook/tier0/valobject.h deleted file mode 100644 index 59ecca68..00000000 --- a/Resources/NetHook/tier0/valobject.h +++ /dev/null @@ -1,72 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: CValObject is used for tracking individual objects that report -// in to CValidator. Whenever a new object reports in (via CValidator::Push), -// we create a new CValObject to aggregate stats for it. -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef VALOBJECT_H -#define VALOBJECT_H -#ifdef _WIN32 -#pragma once -#endif - - -#ifdef DBGFLAG_VALIDATE -class CValObject -{ -public: - // Constructors & destructors - CValObject( void ) { }; - ~CValObject( void ); - - void Init( tchar *pchType, void *pvObj, tchar *pchName, CValObject *pValObjectParent, - CValObject *pValObjectPrev ); - - // Our object has claimed ownership of a memory block - void ClaimMemoryBlock( void *pvMem ); - - // A child of ours has claimed ownership of a memory block - void ClaimChildMemoryBlock( int cubUser ); - - // Accessors - tchar *PchType( void ) { return m_rgchType; }; - void *PvObj( void ) { return m_pvObj; }; - tchar *PchName( void ) { return m_rgchName; }; - CValObject *PValObjectParent( void ) { return m_pValObjectParent; }; - int NLevel( void ) { return m_nLevel; }; - CValObject *PValObjectNext( void ) { return m_pValObjectNext; }; - int CpubMemSelf( void ) { return m_cpubMemSelf; }; - int CubMemSelf( void ) { return m_cubMemSelf; }; - int CpubMemTree( void ) { return m_cpubMemTree; }; - int CubMemTree( void ) { return m_cubMemTree; }; - int NUser( void ) { return m_nUser; }; - void SetNUser( int nUser ) { m_nUser = nUser; }; - void SetBNewSinceSnapshot( bool bNewSinceSnapshot ) { m_bNewSinceSnapshot = bNewSinceSnapshot; } - bool BNewSinceSnapshot( void ) { return m_bNewSinceSnapshot; } - -private: - bool m_bNewSinceSnapshot; // If this block is new since the snapshot. - tchar m_rgchType[64]; // Type of the object we represent - tchar m_rgchName[64]; // Name of this particular object - void *m_pvObj; // Pointer to the object we represent - - CValObject *m_pValObjectParent; // Our parent object in the tree. - int m_nLevel; // Our depth in the tree - - CValObject *m_pValObjectNext; // Next ValObject in the linked list - - int m_cpubMemSelf; // # of memory blocks we own directly - int m_cubMemSelf; // Total size of the memory blocks we own directly - - int m_cpubMemTree; // # of memory blocks owned by us and our children - int m_cubMemTree; // Total size of the memory blocks owned by us and our children - - int m_nUser; // Field provided for use by our users -}; -#endif // DBGFLAG_VALIDATE - - -#endif // VALOBJECT_H diff --git a/Resources/NetHook/tier0/valve_minmax_off.h b/Resources/NetHook/tier0/valve_minmax_off.h deleted file mode 100644 index ade5f284..00000000 --- a/Resources/NetHook/tier0/valve_minmax_off.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifdef min - #undef min -#endif - -#ifdef max - #undef max -#endif - diff --git a/Resources/NetHook/tier0/valve_minmax_on.h b/Resources/NetHook/tier0/valve_minmax_on.h deleted file mode 100644 index 2ede7be3..00000000 --- a/Resources/NetHook/tier0/valve_minmax_on.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef min - #define min(a,b) (((a) < (b)) ? (a) : (b)) -#endif - -#ifndef max - #define max(a,b) (((a) > (b)) ? (a) : (b)) -#endif - diff --git a/Resources/NetHook/tier0/valve_off.h b/Resources/NetHook/tier0/valve_off.h deleted file mode 100644 index eced1aac..00000000 --- a/Resources/NetHook/tier0/valve_off.h +++ /dev/null @@ -1,30 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: This turns off all Valve-specific #defines. Because we sometimes -// call external include files from inside .cpp files, we need to -// wrap those includes like this: -// #include "tier0/valve_off.h" -// #include -// #include "tier0/valve_on.h" -// -// $NoKeywords: $ -//=============================================================================// - - -#ifdef STEAM - -//----------------------------------------------------------------------------- -// Unicode-related #defines (see wchartypes.h) -//----------------------------------------------------------------------------- -#undef char - - -//----------------------------------------------------------------------------- -// Memory-related #defines -//----------------------------------------------------------------------------- -#undef malloc -#undef realloc -#undef _expand -#undef free - -#endif diff --git a/Resources/NetHook/tier0/valve_on.h b/Resources/NetHook/tier0/valve_on.h deleted file mode 100644 index 4fb50876..00000000 --- a/Resources/NetHook/tier0/valve_on.h +++ /dev/null @@ -1,31 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: This turns on all Valve-specific #defines. Because we sometimes -// call external include files from inside .cpp files, we need to -// wrap those includes like this: -// #include "tier0/valve_off.h" -// #include -// #include "tier0/valve_on.h" -// -// $NoKeywords: $ -//=============================================================================// - - -#ifdef STEAM -//----------------------------------------------------------------------------- -// Unicode-related #defines (see wchartypes.h) -//----------------------------------------------------------------------------- -#ifdef ENFORCE_WCHAR -#define char DontUseChar_SeeWcharOn.h -#endif - - -//----------------------------------------------------------------------------- -// Memory-related #defines -//----------------------------------------------------------------------------- -#define malloc( cub ) HEY_DONT_USE_MALLOC_USE_PVALLOC -#define realloc( pvOld, cub ) HEY_DONT_USE_REALLOC_USE_PVREALLOC -#define _expand( pvOld, cub ) HEY_DONT_USE_EXPAND_USE_PVEXPAND -#define free( pv ) HEY_DONT_USE_FREE_USE_FREEPV - -#endif diff --git a/Resources/NetHook/tier0/vcr_shared.h b/Resources/NetHook/tier0/vcr_shared.h deleted file mode 100644 index c7b6f638..00000000 --- a/Resources/NetHook/tier0/vcr_shared.h +++ /dev/null @@ -1,54 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef VCR_SHARED_H -#define VCR_SHARED_H -#ifdef _WIN32 -#pragma once -#endif - - -#define VCRFILE_VERSION 2 - - -// Identifiers for the things we record. When playing back, these things should -// be asked for in the exact same order (otherwise, the engine isn't making all -// the calls in the same order). -typedef enum -{ - VCREvent_Sys_FloatTime=0, - VCREvent_recvfrom, - VCREvent_SyncToken, - VCREvent_GetCursorPos, - VCREvent_SetCursorPos, - VCREvent_ScreenToClient, - VCREvent_Cmd_Exec, - VCREvent_CmdLine, - VCREvent_RegOpenKeyEx, - VCREvent_RegSetValueEx, - VCREvent_RegQueryValueEx, - VCREvent_RegCreateKeyEx, - VCREvent_RegCloseKey, - VCREvent_PeekMessage, - VCREvent_GameMsg, - VCREvent_GetNumberOfConsoleInputEvents, - VCREvent_ReadConsoleInput, - VCREvent_GetKeyState, - VCREvent_recv, - VCREvent_send, - VCREvent_Generic, - VCREvent_CreateThread, - VCREvent_WaitForSingleObject, - VCREvent_EnterCriticalSection, - VCREvent_Time, - VCREvent_LocalTime, - VCREvent_GenericString, - VCREvent_NUMEVENTS -} VCREvent; - - -#endif // VCR_SHARED_H diff --git a/Resources/NetHook/tier0/vcrmode.h b/Resources/NetHook/tier0/vcrmode.h deleted file mode 100644 index 00e0cba3..00000000 --- a/Resources/NetHook/tier0/vcrmode.h +++ /dev/null @@ -1,306 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: VCR mode records a client's game and allows you to -// play it back and reproduce it exactly. When playing it back, nothing -// is simulated on the server, but all server packets are recorded. -// -// Most of the VCR mode functionality is accomplished through hooks -// called at various points in the engine. -// -// $NoKeywords: $ -//===========================================================================// -#ifndef VCRMODE_H -#define VCRMODE_H - -#ifdef _WIN32 -#include -#endif - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/platform.h" -#include "tier0/vcr_shared.h" -#include "tier0/dbg.h" - -#ifdef _LINUX -DBG_INTERFACE void BuildCmdLine( int argc, tchar **argv ); -tchar *GetCommandLine(); -#endif - -#ifdef _X360 -#define NO_VCR 1 -#endif - - -// Enclose lines of code in this if you don't want anything in them written to or read from the VCR file. -#ifndef NO_VCR -#define NOVCR(x) \ -{\ - VCRSetEnabled(0);\ - x;\ - VCRSetEnabled(1);\ -} -#else -#define NOVCR(x) \ -{\ - x;\ -} -#endif - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -struct InputEvent_t; - - -//----------------------------------------------------------------------------- -// Definitions. -//----------------------------------------------------------------------------- -enum VCRMode_t -{ - VCR_Invalid=-1, - VCR_Disabled=0, - VCR_Record, - VCR_Playback -}; - - -//----------------------------------------------------------------------------- -// Functions. -//----------------------------------------------------------------------------- -abstract_class IVCRHelpers -{ -public: - virtual void ErrorMessage( const tchar *pMsg ) = 0; - virtual void* GetMainWindow() = 0; -}; - - -// Used by the vcrtrace program. -abstract_class IVCRTrace -{ -public: - virtual VCREvent ReadEvent() = 0; - virtual void Read( void *pDest, int size ) = 0; -}; - -typedef struct VCR_s -{ - // Start VCR record or play. - int (*Start)( tchar const *pFilename, bool bRecord, IVCRHelpers *pHelpers ); - void (*End)(); - - // Used by the VCR trace app. - IVCRTrace* (*GetVCRTraceInterface)(); - - // Get the current mode the VCR is in. - VCRMode_t (*GetMode)(); - - // This can be used to block out areas of code that are unpredictable (like things triggered by WM_TIMER messages). - // Note: this enables/disables VCR mode usage on a PER-THREAD basis. The assumption is that you're marking out - // specific sections of code that you don't want to use VCR mode inside of, but you're not intending to - // stop all the other threads from using VCR mode. - void (*SetEnabled)(int bEnabled); - - // This can be called any time to put in a debug check to make sure things are synchronized. - void (*SyncToken)(tchar const *pToken); - - // Hook for Sys_FloatTime(). - double (*Hook_Sys_FloatTime)(double time); - - // Note: this makes no guarantees about msg.hwnd being the same on playback. If it needs to be, then we need to add - // an ID system for Windows and store the ID like in Goldsrc. - int (*Hook_PeekMessage)( - struct tagMSG *msg, - void *hWnd, - unsigned int wMsgFilterMin, - unsigned int wMsgFilterMax, - unsigned int wRemoveMsg - ); - - // Call this to record game messages. - void (*Hook_RecordGameMsg)( const InputEvent_t &event ); - void (*Hook_RecordEndGameMsg)(); - - // Call this to playback game messages until it returns false. - bool (*Hook_PlaybackGameMsg)( InputEvent_t *pEvent ); - - // Hook for recvfrom() calls. This replaces the recvfrom() call. - int (*Hook_recvfrom)(int s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen); - - void (*Hook_GetCursorPos)(struct tagPOINT *pt); - void (*Hook_ScreenToClient)(void *hWnd, struct tagPOINT *pt); - - void (*Hook_Cmd_Exec)(tchar **f); - - tchar* (*Hook_GetCommandLine)(); - - // Registry hooks. - long (*Hook_RegOpenKeyEx)( void *hKey, const tchar *lpSubKey, unsigned long ulOptions, unsigned long samDesired, void *pHKey ); - long (*Hook_RegSetValueEx)(void *hKey, tchar const *lpValueName, unsigned long Reserved, unsigned long dwType, uint8 const *lpData, unsigned long cbData); - long (*Hook_RegQueryValueEx)(void *hKey, tchar const *lpValueName, unsigned long *lpReserved, unsigned long *lpType, uint8 *lpData, unsigned long *lpcbData); - long (*Hook_RegCreateKeyEx)(void *hKey, tchar const *lpSubKey, unsigned long Reserved, tchar *lpClass, unsigned long dwOptions, unsigned long samDesired, void *lpSecurityAttributes, void *phkResult, unsigned long *lpdwDisposition); - void (*Hook_RegCloseKey)(void *hKey); - - // hInput is a HANDLE. - int (*Hook_GetNumberOfConsoleInputEvents)( void *hInput, unsigned long *pNumEvents ); - - // hInput is a HANDLE. - // pRecs is an INPUT_RECORD pointer. - int (*Hook_ReadConsoleInput)( void *hInput, void *pRecs, int nMaxRecs, unsigned long *pNumRead ); - - - // This calls time() then gives you localtime()'s result. - void (*Hook_LocalTime)( struct tm *today ); - - short (*Hook_GetKeyState)( int nVirtKey ); - - // TCP calls. - int (*Hook_recv)( int s, char *buf, int len, int flags ); - int (*Hook_send)( int s, const char *buf, int len, int flags ); - - // These can be used to add events without having to modify VCR mode. - // pEventName is used for verification to make sure it's playing back correctly. - // If pEventName is null, then verification is not performed. - void (*GenericRecord)( const tchar *pEventName, const void *pData, int len ); - - - // Returns the number of bytes written in the generic event. - // If bForceLenSame is true, then it will error out unless the value in the VCR file is the same as maxLen. - int (*GenericPlayback)( const tchar *pEventName, void *pOutData, int maxLen, bool bForceLenSame ); - - // If you just want to record and playback a value and not worry about whether or not you're - // recording or playing back, use this. It also will do nothing if you're not recording or playing back. - // - // NOTE: also see GenericValueVerify, which allows you to have it VERIFY that pData's contents are the same upon playback - // (rather than just copying whatever is in the VCR file into pData). - void (*GenericValue)( const tchar *pEventName, void *pData, int maxLen ); - - // Get the current percent (0.0 - 1.0) that it's played back through the file (only valid in playback). - double (*GetPercentCompleted)(); - - // If you use this, then any VCR stuff the thread does will work with VCR mode. - // This mirrors the Windows API CreateThread function and returns a HANDLE the same way. - void* (*Hook_CreateThread)( - void *lpThreadAttributes, - unsigned long dwStackSize, - void *lpStartAddress, - void *lpParameter, - unsigned long dwCreationFlags, - unsigned long *lpThreadID ); - - unsigned long (*Hook_WaitForSingleObject)( - void *handle, - unsigned long dwMilliseconds ); - - void (*Hook_EnterCriticalSection)( void *pCS ); - - void (*Hook_Time)( long *pTime ); - - // String value. Playback just verifies that the incoming string is the same as it was when recording. - void (*GenericString)( const char *pEventName, const char *pString ); - - // Works like GenericValue, except upon playback it will verify that pData's contents are the same as it was during recording. - void (*GenericValueVerify)( const tchar *pEventName, const void *pData, int maxLen ); - - unsigned long (*Hook_WaitForMultipleObjects)( uint32 nHandles, const void **pHandles, int bWaitAll, uint32 timeout ); - -} VCR_t; - -#ifndef NO_VCR - -// In the launcher, this is created by vcrmode.c. -// In the engine, this is set when the launcher initializes its DLL. -PLATFORM_INTERFACE VCR_t *g_pVCR; - -#endif - - -#ifndef NO_VCR -#define VCRStart g_pVCR->Start -#define VCREnd g_pVCR->End -#define VCRGetVCRTraceInterface g_pVCR->GetVCRTraceInterface -#define VCRGetMode g_pVCR->GetMode -#define VCRSetEnabled g_pVCR->SetEnabled -#define VCRSyncToken g_pVCR->SyncToken -#define VCRGenericString g_pVCR->GenericString -#define VCRGenericValueVerify g_pVCR->GenericValueVerify -#define VCRHook_Sys_FloatTime g_pVCR->Hook_Sys_FloatTime -#define VCRHook_PeekMessage g_pVCR->Hook_PeekMessage -#define VCRHook_RecordGameMsg g_pVCR->Hook_RecordGameMsg -#define VCRHook_RecordEndGameMsg g_pVCR->Hook_RecordEndGameMsg -#define VCRHook_PlaybackGameMsg g_pVCR->Hook_PlaybackGameMsg -#define VCRHook_recvfrom g_pVCR->Hook_recvfrom -#define VCRHook_GetCursorPos g_pVCR->Hook_GetCursorPos -#define VCRHook_ScreenToClient g_pVCR->Hook_ScreenToClient -#define VCRHook_Cmd_Exec g_pVCR->Hook_Cmd_Exec -#define VCRHook_GetCommandLine g_pVCR->Hook_GetCommandLine -#define VCRHook_RegOpenKeyEx g_pVCR->Hook_RegOpenKeyEx -#define VCRHook_RegSetValueEx g_pVCR->Hook_RegSetValueEx -#define VCRHook_RegQueryValueEx g_pVCR->Hook_RegQueryValueEx -#define VCRHook_RegCreateKeyEx g_pVCR->Hook_RegCreateKeyEx -#define VCRHook_RegCloseKey g_pVCR->Hook_RegCloseKey -#define VCRHook_GetNumberOfConsoleInputEvents g_pVCR->Hook_GetNumberOfConsoleInputEvents -#define VCRHook_ReadConsoleInput g_pVCR->Hook_ReadConsoleInput -#define VCRHook_LocalTime g_pVCR->Hook_LocalTime -#define VCRHook_GetKeyState g_pVCR->Hook_GetKeyState -#define VCRHook_recv g_pVCR->Hook_recv -#define VCRHook_send g_pVCR->Hook_send -#define VCRGenericRecord g_pVCR->GenericRecord -#define VCRGenericPlayback g_pVCR->GenericPlayback -#define VCRGenericValue g_pVCR->GenericValue -#define VCRGetPercentCompleted g_pVCR->GetPercentCompleted -#define VCRHook_CreateThread g_pVCR->Hook_CreateThread -#define VCRHook_WaitForSingleObject g_pVCR->Hook_WaitForSingleObject -#define VCRHook_EnterCriticalSection g_pVCR->Hook_EnterCriticalSection -#define VCRHook_Time g_pVCR->Hook_Time -#define VCRHook_WaitForMultipleObjects( a, b, c, d) g_pVCR->Hook_WaitForMultipleObjects( a, (const void **)b, c, d) -#else -#define VCRStart( a, b, c ) (1) -#define VCREnd ((void)(0)) -#define VCRGetVCRTraceInterface (NULL) -#define VCRGetMode() (VCR_Disabled) -#define VCRSetEnabled( a ) ((void)(0)) -#define VCRSyncToken( a ) ((void)(0)) -#define VCRGenericRecord MUST_IFDEF_OUT_GenericRecord -#define VCRGenericPlayback MUST_IFDEF_OUT_GenericPlayback -#define VCRGenericValue MUST_IFDEF_OUT_GenericValue -#define VCRGenericString MUST_IFDEF_OUT_GenericString -#define VCRGenericValueVerify MUST_IFDEF_OUT_GenericValueVerify -#define VCRGetPercentCompleted() (0.0f) -#define VCRHook_Sys_FloatTime Sys_FloatTime -#define VCRHook_PeekMessage PeekMessage -#define VCRHook_RecordGameMsg RecordGameMsg -#define VCRHook_RecordEndGameMsg RecordEndGameMsg -#define VCRHook_PlaybackGameMsg PlaybackGameMsg -#define VCRHook_recvfrom recvfrom -#define VCRHook_GetCursorPos GetCursorPos -#define VCRHook_ScreenToClient ScreenToClient -#define VCRHook_Cmd_Exec( a ) ((void)(0)) -#define VCRHook_GetCommandLine GetCommandLine -#define VCRHook_RegOpenKeyEx RegOpenKeyEx -#define VCRHook_RegSetValueEx RegSetValueEx -#define VCRHook_RegQueryValueEx RegQueryValueEx -#define VCRHook_RegCreateKeyEx RegCreateKeyEx -#define VCRHook_RegCloseKey RegCloseKey -#define VCRHook_GetNumberOfConsoleInputEvents GetNumberOfConsoleInputEvents -#define VCRHook_ReadConsoleInput ReadConsoleInput -#define VCRHook_LocalTime( a ) memset(a, 0, sizeof(*a)); -#define VCRHook_GetKeyState GetKeyState -#define VCRHook_recv recv -#define VCRHook_send send -#if defined( _X360 ) -#define VCRHook_CreateThread CreateThread -#else -#define VCRHook_CreateThread (void*)_beginthreadex -#endif -#define VCRHook_WaitForSingleObject WaitForSingleObject -#define VCRHook_EnterCriticalSection EnterCriticalSection -#define VCRHook_WaitForMultipleObjects( a, b, c, d) WaitForMultipleObjects( a, (const HANDLE *)b, c, d) -#define VCRHook_Time Time -#endif - -#endif // VCRMODE_H diff --git a/Resources/NetHook/tier0/vprof.h b/Resources/NetHook/tier0/vprof.h deleted file mode 100644 index d5228e5f..00000000 --- a/Resources/NetHook/tier0/vprof.h +++ /dev/null @@ -1,1187 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Real-Time Hierarchical Profiling -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef VPROF_H -#define VPROF_H - -#include "tier0/dbg.h" -#include "tier0/fasttimer.h" -#include "tier0/l2cache.h" -#include "tier0/threadtools.h" - -// VProf is enabled by default in all configurations -except- X360 Retail. -#if !( defined(_X360) && ( defined(_RETAIL) || defined(_CERT) ) ) -#define VPROF_ENABLED -#endif - -#if defined(_X360) && defined(VPROF_ENABLED) -#include "tier0/pmc360.h" -#ifndef USE_PIX -#define VPROF_UNDO_PIX -#undef _PIX_H_ -#undef PIXBeginNamedEvent -#undef PIXEndNamedEvent -#undef PIXSetMarker -#undef PIXNameThread -#define USE_PIX -#include -#undef USE_PIX -#else -#include -#endif -#endif - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable:4251) -#endif - -// enable this to get detailed nodes beneath budget -// #define VPROF_LEVEL 1 - -// enable this to use pix (360 only) -// #define VPROF_PIX 1 - -#if defined(VPROF_PIX) -#pragma comment( lib, "Xapilibi" ) -#endif - -//----------------------------------------------------------------------------- -// -// Profiling instrumentation macros -// - -#define MAXCOUNTERS 256 - - -#ifdef VPROF_ENABLED - -#define VPROF_VTUNE_GROUP - -#define VPROF( name ) VPROF_(name, 1, VPROF_BUDGETGROUP_OTHER_UNACCOUNTED, false, 0) -#define VPROF_ASSERT_ACCOUNTED( name ) VPROF_(name, 1, VPROF_BUDGETGROUP_OTHER_UNACCOUNTED, true, 0) -#define VPROF_( name, detail, group, bAssertAccounted, budgetFlags ) VPROF_##detail(name,group, bAssertAccounted, budgetFlags) - -#define VPROF_BUDGET( name, group ) VPROF_BUDGET_FLAGS(name, group, BUDGETFLAG_OTHER) -#define VPROF_BUDGET_FLAGS( name, group, flags ) VPROF_(name, 0, group, false, flags) - -#define VPROF_SCOPE_BEGIN( tag ) do { VPROF( tag ) -#define VPROF_SCOPE_END() } while (0) - -#define VPROF_ONLY( expression ) expression - -#define VPROF_ENTER_SCOPE( name ) g_VProfCurrentProfile.EnterScope( name, 1, VPROF_BUDGETGROUP_OTHER_UNACCOUNTED, false, 0 ) -#define VPROF_EXIT_SCOPE() g_VProfCurrentProfile.ExitScope() - -#define VPROF_BUDGET_GROUP_ID_UNACCOUNTED 0 - - -// Budgetgroup flags. These are used with VPROF_BUDGET_FLAGS. -// These control which budget panels the groups show up in. -// If a budget group uses VPROF_BUDGET, it gets the default -// which is BUDGETFLAG_OTHER. -#define BUDGETFLAG_CLIENT (1<<0) // Shows up in the client panel. -#define BUDGETFLAG_SERVER (1<<1) // Shows up in the server panel. -#define BUDGETFLAG_OTHER (1<<2) // Unclassified (the client shows these but the dedicated server doesn't). -#define BUDGETFLAG_HIDDEN (1<<15) -#define BUDGETFLAG_ALL 0xFFFF - - -// NOTE: You can use strings instead of these defines. . they are defined here and added -// in vprof.cpp so that they are always in the same order. -#define VPROF_BUDGETGROUP_OTHER_UNACCOUNTED _T("Unaccounted") -#define VPROF_BUDGETGROUP_WORLD_RENDERING _T("World Rendering") -#define VPROF_BUDGETGROUP_DISPLACEMENT_RENDERING _T("Displacement_Rendering") -#define VPROF_BUDGETGROUP_GAME _T("Game") -#define VPROF_BUDGETGROUP_NPCS _T("NPCs") -#define VPROF_BUDGETGROUP_SERVER_ANIM _T("Server Animation") -#define VPROF_BUDGETGROUP_PHYSICS _T("Physics") -#define VPROF_BUDGETGROUP_STATICPROP_RENDERING _T("Static_Prop_Rendering") -#define VPROF_BUDGETGROUP_MODEL_RENDERING _T("Other_Model_Rendering") -#define VPROF_BUDGETGROUP_BRUSHMODEL_RENDERING _T("Brush_Model_Rendering") -#define VPROF_BUDGETGROUP_SHADOW_RENDERING _T("Shadow_Rendering") -#define VPROF_BUDGETGROUP_DETAILPROP_RENDERING _T("Detail_Prop_Rendering") -#define VPROF_BUDGETGROUP_PARTICLE_RENDERING _T("Particle/Effect_Rendering") -#define VPROF_BUDGETGROUP_ROPES _T("Ropes") -#define VPROF_BUDGETGROUP_DLIGHT_RENDERING _T("Dynamic_Light_Rendering") -#define VPROF_BUDGETGROUP_OTHER_NETWORKING _T("Networking") -#define VPROF_BUDGETGROUP_CLIENT_ANIMATION _T("Client_Animation") -#define VPROF_BUDGETGROUP_OTHER_SOUND _T("Sound") -#define VPROF_BUDGETGROUP_OTHER_VGUI _T("VGUI") -#define VPROF_BUDGETGROUP_OTHER_FILESYSTEM _T("FileSystem") -#define VPROF_BUDGETGROUP_PREDICTION _T("Prediction") -#define VPROF_BUDGETGROUP_INTERPOLATION _T("Interpolation") -#define VPROF_BUDGETGROUP_SWAP_BUFFERS _T("Swap_Buffers") -#define VPROF_BUDGETGROUP_PLAYER _T("Player") -#define VPROF_BUDGETGROUP_OCCLUSION _T("Occlusion") -#define VPROF_BUDGETGROUP_OVERLAYS _T("Overlays") -#define VPROF_BUDGETGROUP_TOOLS _T("Tools") -#define VPROF_BUDGETGROUP_LIGHTCACHE _T("Light_Cache") -#define VPROF_BUDGETGROUP_DISP_HULLTRACES _T("Displacement_Hull_Traces") -#define VPROF_BUDGETGROUP_TEXTURE_CACHE _T("Texture_Cache") -#define VPROF_BUDGETGROUP_PARTICLE_SIMULATION _T("Particle Simulation") -#define VPROF_BUDGETGROUP_SHADOW_DEPTH_TEXTURING _T("Flashlight Shadows") -#define VPROF_BUDGETGROUP_CLIENT_SIM _T("Client Simulation") // think functions, tempents, etc. -#define VPROF_BUDGETGROUP_STEAM _T("Steam") - -#ifdef _X360 -// update flags -#define VPROF_UPDATE_BUDGET 0x01 // send budget data every frame -#define VPROF_UPDATE_TEXTURE_GLOBAL 0x02 // send global texture data every frame -#define VPROF_UPDATE_TEXTURE_PERFRAME 0x04 // send perframe texture data every frame -#endif - -//------------------------------------- - -#ifndef VPROF_LEVEL -#define VPROF_LEVEL 0 -#endif - -#define VPROF_0(name,group,assertAccounted,budgetFlags) CVProfScope VProf_(name, 0, group, assertAccounted, budgetFlags); - -#if VPROF_LEVEL > 0 -#define VPROF_1(name,group,assertAccounted,budgetFlags) CVProfScope VProf_(name, 1, group, assertAccounted, budgetFlags); -#else -#define VPROF_1(name,group,assertAccounted,budgetFlags) ((void)0) -#endif - -#if VPROF_LEVEL > 1 -#define VPROF_2(name,group,assertAccounted,budgetFlags) CVProfScope VProf_(name, 2, group, assertAccounted, budgetFlags); -#else -#define VPROF_2(name,group,assertAccounted,budgetFlags) ((void)0) -#endif - -#if VPROF_LEVEL > 2 -#define VPROF_3(name,group,assertAccounted,budgetFlags) CVProfScope VProf_(name, 3, group, assertAccounted, budgetFlags); -#else -#define VPROF_3(name,group,assertAccounted,budgetFlags) ((void)0) -#endif - -#if VPROF_LEVEL > 3 -#define VPROF_4(name,group,assertAccounted,budgetFlags) CVProfScope VProf_(name, 4, group, assertAccounted, budgetFlags); -#else -#define VPROF_4(name,group,assertAccounted,budgetFlags) ((void)0) -#endif - -//------------------------------------- - -#define VPROF_INCREMENT_COUNTER(name,amount) do { static CVProfCounter _counter( name ); _counter.Increment( amount ); } while( 0 ) -#define VPROF_INCREMENT_GROUP_COUNTER(name,group,amount) do { static CVProfCounter _counter( name, group ); _counter.Increment( amount ); } while( 0 ) - -#else - -#define VPROF( name ) ((void)0) -#define VPROF_ASSERT_ACCOUNTED( name ) ((void)0) -#define VPROF_( name, detail, group, bAssertAccounted ) ((void)0) -#define VPROF_BUDGET( name, group ) ((void)0) -#define VPROF_BUDGET_FLAGS( name, group, flags ) ((void)0) - -#define VPROF_SCOPE_BEGIN( tag ) do { -#define VPROF_SCOPE_END() } while (0) - -#define VPROF_ONLY( expression ) ((void)0) - -#define VPROF_ENTER_SCOPE( name ) -#define VPROF_EXIT_SCOPE() - -#define VPROF_INCREMENT_COUNTER(name,amount) ((void)0) -#define VPROF_INCREMENT_GROUP_COUNTER(name,group,amount) ((void)0) - -#endif - -//----------------------------------------------------------------------------- - -#ifdef VPROF_ENABLED - -//----------------------------------------------------------------------------- -// -// A node in the call graph hierarchy -// - -class DBG_CLASS CVProfNode -{ -friend class CVProfRecorder; -friend class CVProfile; - -public: - CVProfNode( const tchar * pszName, int detailLevel, CVProfNode *pParent, const tchar *pBudgetGroupName, int budgetFlags ); - ~CVProfNode(); - - CVProfNode *GetSubNode( const tchar *pszName, int detailLevel, const tchar *pBudgetGroupName, int budgetFlags ); - CVProfNode *GetSubNode( const tchar *pszName, int detailLevel, const tchar *pBudgetGroupName ); - CVProfNode *GetParent(); - CVProfNode *GetSibling(); - CVProfNode *GetPrevSibling(); - CVProfNode *GetChild(); - - void MarkFrame(); - void ResetPeak(); - - void Pause(); - void Resume(); - void Reset(); - - void EnterScope(); - bool ExitScope(); - - const tchar *GetName(); - - int GetBudgetGroupID() - { - return m_BudgetGroupID; - } - - // Only used by the record/playback stuff. - void SetBudgetGroupID( int id ) - { - m_BudgetGroupID = id; - } - - int GetCurCalls(); - double GetCurTime(); - int GetPrevCalls(); - double GetPrevTime(); - int GetTotalCalls(); - double GetTotalTime(); - double GetPeakTime(); - - double GetCurTimeLessChildren(); - double GetPrevTimeLessChildren(); - double GetTotalTimeLessChildren(); - - int GetPrevL2CacheMissLessChildren(); - int GetPrevLoadHitStoreLessChildren(); - - void ClearPrevTime(); - - int GetL2CacheMisses(); - - // Not used in the common case... - void SetCurFrameTime( unsigned long milliseconds ); - - void SetClientData( int iClientData ) { m_iClientData = iClientData; } - int GetClientData() const { return m_iClientData; } - -#ifdef DBGFLAG_VALIDATE - void Validate( CValidator &validator, tchar *pchName ); // Validate our internal structures -#endif // DBGFLAG_VALIDATE - - -// Used by vprof record/playback. -private: - - void SetUniqueNodeID( int id ) - { - m_iUniqueNodeID = id; - } - - int GetUniqueNodeID() const - { - return m_iUniqueNodeID; - } - - static int s_iCurrentUniqueNodeID; - - -private: - const tchar *m_pszName; - CFastTimer m_Timer; - - // L2 Cache data. - int m_iPrevL2CacheMiss; - int m_iCurL2CacheMiss; - int m_iTotalL2CacheMiss; - -#ifndef _X360 - // L2 Cache data. - CL2Cache m_L2Cache; -#else // 360: - - unsigned int m_iBitFlags; // see enum below for settings - CPMCData m_PMCData; - int m_iPrevLoadHitStores; - int m_iCurLoadHitStores; - int m_iTotalLoadHitStores; - - public: - enum FlagBits - { - kRecordL2 = 0x01, - kCPUTrace = 0x02, ///< cause a PIX trace inside this node. - }; - // call w/ true to enable L2 and LHS recording; false to turn it off - inline void EnableL2andLHS(bool enable) - { - if (enable) - m_iBitFlags |= kRecordL2; - else - m_iBitFlags &= (~kRecordL2); - } - - inline bool IsL2andLHSEnabled( void ) - { - return (m_iBitFlags & kRecordL2) != 0; - } - - int GetLoadHitStores(); - - private: - -#endif - - int m_nRecursions; - - unsigned m_nCurFrameCalls; - CCycleCount m_CurFrameTime; - - unsigned m_nPrevFrameCalls; - CCycleCount m_PrevFrameTime; - - unsigned m_nTotalCalls; - CCycleCount m_TotalTime; - - CCycleCount m_PeakTime; - - CVProfNode *m_pParent; - CVProfNode *m_pChild; - CVProfNode *m_pSibling; - - int m_BudgetGroupID; - - int m_iClientData; - int m_iUniqueNodeID; -}; - -//----------------------------------------------------------------------------- -// -// Coordinator and root node of the profile hierarchy tree -// - -enum VProfReportType_t -{ - VPRT_SUMMARY = ( 1 << 0 ), - VPRT_HIERARCHY = ( 1 << 1 ), - VPRT_HIERARCHY_TIME_PER_FRAME_AND_COUNT_ONLY = ( 1 << 2 ), - VPRT_LIST_BY_TIME = ( 1 << 3 ), - VPRT_LIST_BY_TIME_LESS_CHILDREN = ( 1 << 4 ), - VPRT_LIST_BY_AVG_TIME = ( 1 << 5 ), - VPRT_LIST_BY_AVG_TIME_LESS_CHILDREN = ( 1 << 6 ), - VPRT_LIST_BY_PEAK_TIME = ( 1 << 7 ), - VPRT_LIST_BY_PEAK_OVER_AVERAGE = ( 1 << 8 ), - VPRT_LIST_TOP_ITEMS_ONLY = ( 1 << 9 ), - - VPRT_FULL = (0xffffffff & ~(VPRT_HIERARCHY_TIME_PER_FRAME_AND_COUNT_ONLY|VPRT_LIST_TOP_ITEMS_ONLY)), -}; - -enum CounterGroup_t -{ - COUNTER_GROUP_DEFAULT=0, - COUNTER_GROUP_NO_RESET, // The engine doesn't reset these counters. Usually, they are used - // like global variables that can be accessed across modules. - COUNTER_GROUP_TEXTURE_GLOBAL, // Global texture usage counters (totals for what is currently in memory). - COUNTER_GROUP_TEXTURE_PER_FRAME // Per-frame texture usage counters. -}; - -class DBG_CLASS CVProfile -{ -public: - CVProfile(); - ~CVProfile(); - - void Term(); - - // - // Runtime operations - // - - void Start(); - void Stop(); - -#ifdef _X360 - enum VXConsoleReportMode_t - { - VXCONSOLE_REPORT_TIME = 0, - VXCONSOLE_REPORT_L2CACHE_MISSES, - VXCONSOLE_REPORT_LOAD_HIT_STORE, - - VXCONSOLE_REPORT_COUNT, - }; - - // piggyback to profiler - void VXProfileStart(); - void VXProfileUpdate(); - void VXEnableUpdateMode(int event, bool bEnable); - - void PMCDisableAllNodes(CVProfNode *pStartNode = NULL); ///< turn off l2 and lhs recording for everywhere - bool PMCEnableL2Upon(const tchar *pszNodeName, bool bRecursive = false); ///< enable l2 and lhs recording for one given node - bool PMCDisableL2Upon(const tchar *pszNodeName, bool bRecursive = false); ///< enable l2 and lhs recording for one given node - - void DumpEnabledPMCNodes( void ); - - void VXConsoleReportMode( VXConsoleReportMode_t mode ); - void VXConsoleReportScale( VXConsoleReportMode_t mode, float flScale ); - - // the CPU trace mode is actually a small state machine; it can be off, primed for - // single capture, primed for everything-in-a-frame capture, or currently in everything-in-a-frame - // capture. - enum CPUTraceState - { - kDisabled, - kFirstHitNode, /// < record from the first time we hit the node until that node ends - kAllNodesInFrame_WaitingForMark, ///< we're going to record all the times a node is hit in a frame, but are waiting for the frame to start - kAllNodesInFrame_Recording, ///< we're recording all hits on a node this frame. - }; - - /// Global switch to turn CPU tracing on or off at all. The idea is you set up a node first, - /// then trigger tracing by throwing this to true. It'll reset back to false after the trace - /// happens. - inline CPUTraceState GetCPUTraceMode(); - inline void SetCPUTraceEnabled(CPUTraceState enabled); - inline void IncrementMultiTraceIndex(); /// tick up the counter that gets appended to the multi-per-frame traces - inline unsigned int GetMultiTraceIndex(); /// return the counter - void CPUTraceDisableAllNodes(CVProfNode *pStartNode = NULL); //< disable the cpu trace flag wherever it may be - CVProfNode *CPUTraceEnableForNode(const tchar *pszNodeName); ///< enable cpu trace on this node only, disabling it wherever else it may be on. - CVProfNode *CPUTraceGetEnabledNode(CVProfNode *pStartNode = NULL); ///< return the node enabled for CPU tracing, or NULL. - const char *GetCPUTraceFilename(); ///< get the filename the trace should write into. - const char *SetCPUTraceFilename(const char *filename); ///< set the filename the trace should write into. (don't specify the extension; I'll do that.) - -#endif - - void EnterScope( const tchar *pszName, int detailLevel, const tchar *pBudgetGroupName, bool bAssertAccounted ); - void EnterScope( const tchar *pszName, int detailLevel, const tchar *pBudgetGroupName, bool bAssertAccounted, int budgetFlags ); - void ExitScope(); - - void MarkFrame(); - void ResetPeaks(); - - void Pause(); - void Resume(); - void Reset(); - - bool IsEnabled() const; - int GetDetailLevel() const; - - bool AtRoot() const; - - // - // Queries - // - -#ifdef VPROF_VTUNE_GROUP -# define MAX_GROUP_STACK_DEPTH 1024 - - void EnableVTuneGroup( const tchar *pGroupName ) - { - m_nVTuneGroupID = BudgetGroupNameToBudgetGroupID( pGroupName ); - m_bVTuneGroupEnabled = true; - } - void DisableVTuneGroup( void ) - { - m_bVTuneGroupEnabled = false; - } - - inline void PushGroup( int nGroupID ); - inline void PopGroup( void ); -#endif - - int NumFramesSampled() { return m_nFrames; } - double GetPeakFrameTime(); - double GetTotalTimeSampled(); - double GetTimeLastFrame(); - - CVProfNode *GetRoot(); - CVProfNode *FindNode( CVProfNode *pStartNode, const tchar *pszNode ); - - void OutputReport( int type = VPRT_FULL, const tchar *pszStartNode = NULL, int budgetGroupID = -1 ); - - const tchar *GetBudgetGroupName( int budgetGroupID ); - int GetBudgetGroupFlags( int budgetGroupID ) const; // Returns a combination of BUDGETFLAG_ defines. - int GetNumBudgetGroups( void ); - void GetBudgetGroupColor( int budgetGroupID, int &r, int &g, int &b, int &a ); - int BudgetGroupNameToBudgetGroupID( const tchar *pBudgetGroupName ); - int BudgetGroupNameToBudgetGroupID( const tchar *pBudgetGroupName, int budgetFlagsToORIn ); - void RegisterNumBudgetGroupsChangedCallBack( void (*pCallBack)(void) ); - - int BudgetGroupNameToBudgetGroupIDNoCreate( const tchar *pBudgetGroupName ) { return FindBudgetGroupName( pBudgetGroupName ); } - - void HideBudgetGroup( int budgetGroupID, bool bHide = true ); - void HideBudgetGroup( const char *pszName, bool bHide = true ) { HideBudgetGroup( BudgetGroupNameToBudgetGroupID( pszName), bHide ); } - - int *FindOrCreateCounter( const tchar *pName, CounterGroup_t eCounterGroup=COUNTER_GROUP_DEFAULT ); - void ResetCounters( CounterGroup_t eCounterGroup ); - - int GetNumCounters( void ) const; - - const tchar *GetCounterName( int index ) const; - int GetCounterValue( int index ) const; - const tchar *GetCounterNameAndValue( int index, int &val ) const; - CounterGroup_t GetCounterGroup( int index ) const; - - // Performance monitoring events. - void PMEInitialized( bool bInit ) { m_bPMEInit = bInit; } - void PMEEnable( bool bEnable ) { m_bPMEEnabled = bEnable; } - -#ifndef _X360 - bool UsePME( void ) { return ( m_bPMEInit && m_bPMEEnabled ); } -#else - bool UsePME( void ) { return ( CPMCData::IsInitialized() && m_bPMEEnabled ); } -#endif - -#ifdef DBGFLAG_VALIDATE - void Validate( CValidator &validator, tchar *pchName ); // Validate our internal structures -#endif // DBGFLAG_VALIDATE - -protected: - - void FreeNodes_R( CVProfNode *pNode ); - -#ifdef VPROF_VTUNE_GROUP - bool VTuneGroupEnabled() - { - return m_bVTuneGroupEnabled; - } - int VTuneGroupID() - { - return m_nVTuneGroupID; - } -#endif - - void SumTimes( const tchar *pszStartNode, int budgetGroupID ); - void SumTimes( CVProfNode *pNode, int budgetGroupID ); - void DumpNodes( CVProfNode *pNode, int indent, bool bAverageAndCountOnly ); - int FindBudgetGroupName( const tchar *pBudgetGroupName ); - int AddBudgetGroupName( const tchar *pBudgetGroupName, int budgetFlags ); - -#ifdef VPROF_VTUNE_GROUP - bool m_bVTuneGroupEnabled; - int m_nVTuneGroupID; - int m_GroupIDStack[MAX_GROUP_STACK_DEPTH]; - int m_GroupIDStackDepth; -#endif - int m_enabled; - bool m_fAtRoot; // tracked for efficiency of the "not profiling" case - CVProfNode *m_pCurNode; - CVProfNode m_Root; - int m_nFrames; - int m_ProfileDetailLevel; - int m_pausedEnabledDepth; - - class CBudgetGroup - { - public: - tchar *m_pName; - int m_BudgetFlags; - }; - - CBudgetGroup *m_pBudgetGroups; - int m_nBudgetGroupNamesAllocated; - int m_nBudgetGroupNames; - void (*m_pNumBudgetGroupsChangedCallBack)(void); - - // Performance monitoring events. - bool m_bPMEInit; - bool m_bPMEEnabled; - - int m_Counters[MAXCOUNTERS]; - char m_CounterGroups[MAXCOUNTERS]; // (These are CounterGroup_t's). - tchar *m_CounterNames[MAXCOUNTERS]; - int m_NumCounters; - -#ifdef _X360 - int m_UpdateMode; - CPUTraceState m_iCPUTraceEnabled; - char m_CPUTraceFilename[128]; - unsigned int m_iSuccessiveTraceIndex; - VXConsoleReportMode_t m_ReportMode; - float m_pReportScale[VXCONSOLE_REPORT_COUNT]; -#endif -}; - -//------------------------------------- - -DBG_INTERFACE CVProfile g_VProfCurrentProfile; - - -//----------------------------------------------------------------------------- - -#ifdef VPROF_VTUNE_GROUP -inline void CVProfile::PushGroup( int nGroupID ) -{ - // There is always at least one item on the stack since we force - // the first element to be VPROF_BUDGETGROUP_OTHER_UNACCOUNTED. - Assert( m_GroupIDStackDepth > 0 ); - Assert( m_GroupIDStackDepth < MAX_GROUP_STACK_DEPTH ); - m_GroupIDStack[m_GroupIDStackDepth] = nGroupID; - m_GroupIDStackDepth++; - if( m_GroupIDStack[m_GroupIDStackDepth-2] != nGroupID && - VTuneGroupEnabled() && - nGroupID == VTuneGroupID() ) - { - vtune( true ); - } -} -#endif // VPROF_VTUNE_GROUP - -#ifdef VPROF_VTUNE_GROUP -inline void CVProfile::PopGroup( void ) -{ - m_GroupIDStackDepth--; - // There is always at least one item on the stack since we force - // the first element to be VPROF_BUDGETGROUP_OTHER_UNACCOUNTED. - Assert( m_GroupIDStackDepth > 0 ); - if( m_GroupIDStack[m_GroupIDStackDepth] != m_GroupIDStack[m_GroupIDStackDepth+1] && - VTuneGroupEnabled() && - m_GroupIDStack[m_GroupIDStackDepth+1] == VTuneGroupID() ) - { - vtune( false ); - } -} -#endif // VPROF_VTUNE_GROUP - -//----------------------------------------------------------------------------- - -class CVProfScope -{ -public: - CVProfScope( const tchar * pszName, int detailLevel, const tchar *pBudgetGroupName, bool bAssertAccounted, int budgetFlags ); - ~CVProfScope(); -}; - -//----------------------------------------------------------------------------- -// -// CVProfNode, inline methods -// - -inline CVProfNode::CVProfNode( const tchar * pszName, int detailLevel, CVProfNode *pParent, const tchar *pBudgetGroupName, int budgetFlags ) - : m_pszName( pszName ), - m_nCurFrameCalls( 0 ), - m_nPrevFrameCalls( 0 ), - m_nRecursions( 0 ), - m_pParent( pParent ), - m_pChild( NULL ), - m_pSibling( NULL ), - m_iClientData( -1 ) -#ifdef _X360 - , m_iBitFlags( 0 ) -#endif -{ - m_iUniqueNodeID = s_iCurrentUniqueNodeID++; - - if ( m_iUniqueNodeID > 0 ) - { - m_BudgetGroupID = g_VProfCurrentProfile.BudgetGroupNameToBudgetGroupID( pBudgetGroupName, budgetFlags ); - } - else - { - m_BudgetGroupID = 0; // "m_Root" can't call BudgetGroupNameToBudgetGroupID because g_VProfCurrentProfile not yet initialized - } - - Reset(); - - if( m_pParent && ( m_BudgetGroupID == VPROF_BUDGET_GROUP_ID_UNACCOUNTED ) ) - { - m_BudgetGroupID = m_pParent->GetBudgetGroupID(); - } -} - - -//------------------------------------- - -inline CVProfNode *CVProfNode::GetParent() -{ - Assert( m_pParent ); - return m_pParent; -} - -//------------------------------------- - -inline CVProfNode *CVProfNode::GetSibling() -{ - return m_pSibling; -} - -//------------------------------------- -// Hacky way to the previous sibling, only used from vprof panel at the moment, -// so it didn't seem like it was worth the memory waste to add the reverse -// link per node. - -inline CVProfNode *CVProfNode::GetPrevSibling() -{ - CVProfNode* p = GetParent(); - - if(!p) - return NULL; - - CVProfNode* s; - for( s = p->GetChild(); - s && ( s->GetSibling() != this ); - s = s->GetSibling() ) - ; - - return s; -} - -//------------------------------------- - -inline CVProfNode *CVProfNode::GetChild() -{ - return m_pChild; -} - -//------------------------------------- - -inline const tchar *CVProfNode::GetName() -{ - Assert( m_pszName ); - return m_pszName; -} - -//------------------------------------- - -inline int CVProfNode::GetTotalCalls() -{ - return m_nTotalCalls; -} - -//------------------------------------- - -inline double CVProfNode::GetTotalTime() -{ - return m_TotalTime.GetMillisecondsF(); -} - -//------------------------------------- - -inline int CVProfNode::GetCurCalls() -{ - return m_nCurFrameCalls; -} - -//------------------------------------- - -inline double CVProfNode::GetCurTime() -{ - return m_CurFrameTime.GetMillisecondsF(); -} - -//------------------------------------- - -inline int CVProfNode::GetPrevCalls() -{ - return m_nPrevFrameCalls; -} - -//------------------------------------- - -inline double CVProfNode::GetPrevTime() -{ - return m_PrevFrameTime.GetMillisecondsF(); -} - -//------------------------------------- - -inline double CVProfNode::GetPeakTime() -{ - return m_PeakTime.GetMillisecondsF(); -} - -//------------------------------------- - -inline double CVProfNode::GetTotalTimeLessChildren() -{ - double result = GetTotalTime(); - CVProfNode *pChild = GetChild(); - while ( pChild ) - { - result -= pChild->GetTotalTime(); - pChild = pChild->GetSibling(); - } - return result; -} - -//------------------------------------- - -inline double CVProfNode::GetCurTimeLessChildren() -{ - double result = GetCurTime(); - CVProfNode *pChild = GetChild(); - while ( pChild ) - { - result -= pChild->GetCurTime(); - pChild = pChild->GetSibling(); - } - return result; -} - -inline double CVProfNode::GetPrevTimeLessChildren() -{ - double result = GetPrevTime(); - CVProfNode *pChild = GetChild(); - while ( pChild ) - { - result -= pChild->GetPrevTime(); - pChild = pChild->GetSibling(); - } - return result; -} - -//----------------------------------------------------------------------------- -inline int CVProfNode::GetPrevL2CacheMissLessChildren() -{ - int result = m_iPrevL2CacheMiss; - CVProfNode *pChild = GetChild(); - while ( pChild ) - { - result -= pChild->m_iPrevL2CacheMiss; - pChild = pChild->GetSibling(); - } - return result; -} - -//----------------------------------------------------------------------------- -inline int CVProfNode::GetPrevLoadHitStoreLessChildren() -{ -#ifndef _X360 - return 0; -#else - int result = m_iPrevLoadHitStores; - CVProfNode *pChild = GetChild(); - while ( pChild ) - { - result -= pChild->m_iPrevLoadHitStores; - pChild = pChild->GetSibling(); - } - return result; -#endif -} - - -//----------------------------------------------------------------------------- -inline void CVProfNode::ClearPrevTime() -{ - m_PrevFrameTime.Init(); -} - -//----------------------------------------------------------------------------- -inline int CVProfNode::GetL2CacheMisses( void ) -{ -#ifndef _X360 - return m_L2Cache.GetL2CacheMisses(); -#else - return m_iTotalL2CacheMiss; -#endif -} - -#ifdef _X360 -inline int CVProfNode::GetLoadHitStores( void ) -{ - return m_iTotalLoadHitStores; -} -#endif - -//----------------------------------------------------------------------------- -// -// CVProfile, inline methods -// - -//------------------------------------- - -inline bool CVProfile::IsEnabled() const -{ - return ( m_enabled != 0 ); -} - -//------------------------------------- - -inline int CVProfile::GetDetailLevel() const -{ - return m_ProfileDetailLevel; -} - - -//------------------------------------- - -inline bool CVProfile::AtRoot() const -{ - return m_fAtRoot; -} - -//------------------------------------- - -inline void CVProfile::Start() -{ - if ( ++m_enabled == 1 ) - { - m_Root.EnterScope(); -#ifdef _X360 - VXProfileStart(); - CPMCData::InitializeOnceProgramWide(); -#endif - } -} - -//------------------------------------- - -inline void CVProfile::Stop() -{ - if ( --m_enabled == 0 ) - m_Root.ExitScope(); -} - -//------------------------------------- - -inline void CVProfile::EnterScope( const tchar *pszName, int detailLevel, const tchar *pBudgetGroupName, bool bAssertAccounted, int budgetFlags ) -{ - if ( ( m_enabled != 0 || !m_fAtRoot ) && ThreadInMainThread() ) // if became disabled, need to unwind back to root before stopping - { - // Only account for vprof stuff on the primary thread. - //if( !Plat_IsPrimaryThread() ) - // return; - - if ( pszName != m_pCurNode->GetName() ) - { - m_pCurNode = m_pCurNode->GetSubNode( pszName, detailLevel, pBudgetGroupName, budgetFlags ); - } - m_pBudgetGroups[m_pCurNode->GetBudgetGroupID()].m_BudgetFlags |= budgetFlags; - -#if defined( _DEBUG ) && !defined( _X360 ) - // 360 doesn't want this to allow tier0 debug/release .def files to match - if ( bAssertAccounted ) - { - // FIXME - AssertOnce( m_pCurNode->GetBudgetGroupID() != 0 ); - } -#endif - m_pCurNode->EnterScope(); - m_fAtRoot = false; - } -#if defined(_X360) && defined(VPROF_PIX) - if ( m_pCurNode->GetBudgetGroupID() != VPROF_BUDGET_GROUP_ID_UNACCOUNTED ) - PIXBeginNamedEvent( 0, pszName ); -#endif -} - -inline void CVProfile::EnterScope( const tchar *pszName, int detailLevel, const tchar *pBudgetGroupName, bool bAssertAccounted ) -{ - EnterScope( pszName, detailLevel, pBudgetGroupName, bAssertAccounted, BUDGETFLAG_OTHER ); -} - -//------------------------------------- - -inline void CVProfile::ExitScope() -{ -#if defined(_X360) && defined(VPROF_PIX) -#ifdef PIXBeginNamedEvent -#error -#endif - if ( m_pCurNode->GetBudgetGroupID() != VPROF_BUDGET_GROUP_ID_UNACCOUNTED ) - PIXEndNamedEvent(); -#endif - if ( ( !m_fAtRoot || m_enabled != 0 ) && ThreadInMainThread() ) - { - // Only account for vprof stuff on the primary thread. - //if( !Plat_IsPrimaryThread() ) - // return; - - // ExitScope will indicate whether we should back up to our parent (we may - // be profiling a recursive function) - if (m_pCurNode->ExitScope()) - { - m_pCurNode = m_pCurNode->GetParent(); - } - m_fAtRoot = ( m_pCurNode == &m_Root ); - } -} - -//------------------------------------- - -inline void CVProfile::Pause() -{ - m_pausedEnabledDepth = m_enabled; - m_enabled = 0; - if ( !AtRoot() ) - m_Root.Pause(); -} - -//------------------------------------- - -inline void CVProfile::Resume() -{ - m_enabled = m_pausedEnabledDepth; - if ( !AtRoot() ) - m_Root.Resume(); -} - -//------------------------------------- - -inline void CVProfile::Reset() -{ - m_Root.Reset(); - m_nFrames = 0; -} - -//------------------------------------- - -inline void CVProfile::ResetPeaks() -{ - m_Root.ResetPeak(); -} - -//------------------------------------- - -inline void CVProfile::MarkFrame() -{ - if ( m_enabled ) - { - ++m_nFrames; - m_Root.ExitScope(); - m_Root.MarkFrame(); - m_Root.EnterScope(); - -#ifdef _X360 - // update the CPU trace state machine if enabled - switch ( GetCPUTraceMode() ) - { - case kAllNodesInFrame_WaitingForMark: - // mark! Start recording a zillion traces. - m_iCPUTraceEnabled = kAllNodesInFrame_Recording; - - break; - case kAllNodesInFrame_Recording: - // end of frame. stop recording. - m_iCPUTraceEnabled = kDisabled; - Msg("Frame ended. Recording no more CPU traces\n"); - - break; - - default: - // no default - break; - } -#endif - } -} - -//------------------------------------- - -inline double CVProfile::GetTotalTimeSampled() -{ - return m_Root.GetTotalTime(); -} - -//------------------------------------- - -inline double CVProfile::GetPeakFrameTime() -{ - return m_Root.GetPeakTime(); -} - -//------------------------------------- - -inline double CVProfile::GetTimeLastFrame() -{ - return m_Root.GetCurTime(); -} - -//------------------------------------- - -inline CVProfNode *CVProfile::GetRoot() -{ - return &m_Root; -} - - -inline const tchar *CVProfile::GetBudgetGroupName( int budgetGroupID ) -{ - Assert( budgetGroupID >= 0 && budgetGroupID < m_nBudgetGroupNames ); - return m_pBudgetGroups[budgetGroupID].m_pName; -} - -inline int CVProfile::GetBudgetGroupFlags( int budgetGroupID ) const -{ - Assert( budgetGroupID >= 0 && budgetGroupID < m_nBudgetGroupNames ); - return m_pBudgetGroups[budgetGroupID].m_BudgetFlags; -} - -#ifdef _X360 - -inline CVProfile::CPUTraceState CVProfile::GetCPUTraceMode() -{ - return m_iCPUTraceEnabled; -} - -inline void CVProfile::SetCPUTraceEnabled(CPUTraceState enabled) -{ - m_iCPUTraceEnabled = enabled; -} - -inline void CVProfile::IncrementMultiTraceIndex() -{ - ++m_iSuccessiveTraceIndex; -} - -inline unsigned int CVProfile::GetMultiTraceIndex() -{ - return m_iSuccessiveTraceIndex; -} - -#endif - - -//----------------------------------------------------------------------------- - -inline CVProfScope::CVProfScope( const tchar * pszName, int detailLevel, const tchar *pBudgetGroupName, bool bAssertAccounted, int budgetFlags ) -{ - g_VProfCurrentProfile.EnterScope( pszName, detailLevel, pBudgetGroupName, bAssertAccounted, budgetFlags ); -} - -//------------------------------------- - -inline CVProfScope::~CVProfScope() -{ - g_VProfCurrentProfile.ExitScope(); -} - -class CVProfCounter -{ -public: - CVProfCounter( const tchar *pName, CounterGroup_t group=COUNTER_GROUP_DEFAULT ) - { - m_pCounter = g_VProfCurrentProfile.FindOrCreateCounter( pName, group ); - Assert( m_pCounter ); - } - ~CVProfCounter() - { - } - void Increment( int val ) - { - Assert( m_pCounter ); - *m_pCounter += val; - } -private: - int *m_pCounter; -}; - -#endif - -#ifdef VPROF_UNDO_PIX -#undef USE_PIX -#undef _PIX_H_ -#undef PIXBeginNamedEvent -#undef PIXEndNamedEvent -#undef PIXSetMarker -#undef PIXNameThread -#include -#endif - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif - -//============================================================================= diff --git a/Resources/NetHook/tier0/wchartypes.h b/Resources/NetHook/tier0/wchartypes.h deleted file mode 100644 index 79bc5f53..00000000 --- a/Resources/NetHook/tier0/wchartypes.h +++ /dev/null @@ -1,101 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: All of our code is completely Unicode. Instead of char, you should -// use wchar, uint8, or char8, as explained below. -// -// $NoKeywords: $ -//=============================================================================// - - -#ifndef WCHARTYPES_H -#define WCHARTYPES_H -#ifdef _WIN32 -#pragma once -#endif - -#ifdef _INC_TCHAR -#error ("Must include tier0 type headers before tchar.h") -#endif - -// Temporarily turn off Valve defines -#include "tier0/valve_off.h" - -#ifndef _WCHAR_T_DEFINED -typedef unsigned short wchar_t; -#define _WCHAR_T_DEFINED -#endif - -// char8 -// char8 is equivalent to char, and should be used when you really need a char -// (for example, when calling an external function that's declared to take -// chars). -typedef char char8; - -// uint8 -// uint8 is equivalent to byte (but is preferred over byte for clarity). Use this -// whenever you mean a byte (for example, one byte of a network packet). -typedef unsigned char uint8; -typedef unsigned char BYTE; -typedef unsigned char byte; - -// wchar -// wchar is a single character of text (currently 16 bits, as all of our text is -// Unicode). Use this whenever you mean a piece of text (for example, in a string). -typedef wchar_t wchar; -//typedef char wchar; - -// __WFILE__ -// This is a Unicode version of __FILE__ -#define WIDEN2(x) L ## x -#define WIDEN(x) WIDEN2(x) -#define __WFILE__ WIDEN(__FILE__) - -#ifdef STEAM -#ifndef _UNICODE -#define FORCED_UNICODE -#endif -#define _UNICODE -#endif - -#ifdef _WIN32 -#include -#else -#define _tcsstr strstr -#define _tcsicmp stricmp -#define _tcscmp strcmp -#define _tcscpy strcpy -#define _tcsncpy strncpy -#define _tcsrchr strrchr -#define _tcslen strlen -#define _tfopen fopen -#define _stprintf sprintf -#define _ftprintf fprintf -#define _vsntprintf _vsnprintf -#define _tprintf printf -#define _sntprintf _snprintf -#define _T(s) s -#endif - -#if defined(_UNICODE) -typedef wchar tchar; -#define tstring wstring -#define __TFILE__ __WFILE__ -#define TCHAR_IS_WCHAR -#else -typedef char tchar; -#define tstring string -#define __TFILE__ __FILE__ -#define TCHAR_IS_CHAR -#endif - -#ifdef FORCED_UNICODE -#undef _UNICODE -#endif - -// Turn valve defines back on -#include "tier0/valve_on.h" - - -#endif // WCHARTYPES - - diff --git a/Resources/NetHook/tier0/xbox_codeline_defines.h b/Resources/NetHook/tier0/xbox_codeline_defines.h deleted file mode 100644 index 3a4147b4..00000000 --- a/Resources/NetHook/tier0/xbox_codeline_defines.h +++ /dev/null @@ -1,16 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef XBOX_CODELINE_DEFINES_H -#define XBOX_CODELINE_DEFINES_H - - -// In the regular src_main codeline, we leave this out. -//#define IN_XBOX_CODELINE - - -#endif // XBOX_CODELINE_DEFINES_H diff --git a/Resources/NetHook/tier1/CommandBuffer.h b/Resources/NetHook/tier1/CommandBuffer.h deleted file mode 100644 index 0a3c4433..00000000 --- a/Resources/NetHook/tier1/CommandBuffer.h +++ /dev/null @@ -1,160 +0,0 @@ -//===== Copyright © 1996-2006, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// $NoKeywords: $ -//===========================================================================// - - -#ifndef COMMANDBUFFER_H -#define COMMANDBUFFER_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier1/utllinkedlist.h" -#include "tier1/convar.h" - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -class CUtlBuffer; - - -//----------------------------------------------------------------------------- -// Invalid command handle -//----------------------------------------------------------------------------- -typedef int CommandHandle_t; -enum -{ - COMMAND_BUFFER_INVALID_COMMAND_HANDLE = 0 -}; - - -//----------------------------------------------------------------------------- -// A command buffer class- a queue of argc/argv based commands associated -// with a particular time -//----------------------------------------------------------------------------- -class CCommandBuffer -{ -public: - // Constructor, destructor - CCommandBuffer( ); - ~CCommandBuffer(); - - // Inserts text into the command buffer - bool AddText( const char *pText, int nTickDelay = 0 ); - - // Used to iterate over all commands appropriate for the current time - void BeginProcessingCommands( int nDeltaTicks ); - bool DequeueNextCommand( ); - int DequeueNextCommand( const char **& ppArgv ); - int ArgC() const; - const char **ArgV() const; - const char *ArgS() const; // All args that occur after the 0th arg, in string form - const char *GetCommandString() const; // The entire command in string form, including the 0th arg - const CCommand& GetCommand() const; - void EndProcessingCommands(); - - // Are we in the middle of processing commands? - bool IsProcessingCommands(); - - // Delays all queued commands to execute at a later time - void DelayAllQueuedCommands( int nTickDelay ); - - // Indicates how long to delay when encoutering a 'wait' command - void SetWaitDelayTime( int nTickDelay ); - - // Returns a handle to the next command to process - // (useful when inserting commands into the buffer during processing - // of commands to force immediate execution of those commands, - // most relevantly, to implement a feature where you stream a file - // worth of commands into the buffer, where the file size is too large - // to entirely contain in the buffer). - CommandHandle_t GetNextCommandHandle(); - - // Specifies a max limit of the args buffer. For unittesting. Size == 0 means use default - void LimitArgumentBufferSize( int nSize ); - -private: - enum - { - ARGS_BUFFER_LENGTH = 8192, - }; - - struct Command_t - { - int m_nTick; - int m_nFirstArgS; - int m_nBufferSize; - }; - - // Insert a command into the command queue at the appropriate time - void InsertCommandAtAppropriateTime( int hCommand ); - - // Insert a command into the command queue - // Only happens if it's inserted while processing other commands - void InsertImmediateCommand( int hCommand ); - - // Insert a command into the command queue - bool InsertCommand( const char *pArgS, int nCommandSize, int nTick ); - - // Returns the length of the next command, as well as the offset to the next command - void GetNextCommandLength( const char *pText, int nMaxLen, int *pCommandLength, int *pNextCommandOffset ); - - // Compacts the command buffer - void Compact(); - - // Parses argv0 out of the buffer - bool ParseArgV0( CUtlBuffer &buf, char *pArgv0, int nMaxLen, const char **pArgs ); - - char m_pArgSBuffer[ ARGS_BUFFER_LENGTH ]; - int m_nLastUsedArgSSize; - int m_nArgSBufferSize; - CUtlFixedLinkedList< Command_t > m_Commands; - int m_nCurrentTick; - int m_nLastTickToProcess; - int m_nWaitDelayTicks; - int m_hNextCommand; - int m_nMaxArgSBufferLength; - bool m_bIsProcessingCommands; - - // NOTE: This is here to avoid the pointers returned by DequeueNextCommand - // to become invalid by calling AddText. Is there a way we can avoid the memcpy? - CCommand m_CurrentCommand; -}; - - -//----------------------------------------------------------------------------- -// Returns the next command -//----------------------------------------------------------------------------- -inline int CCommandBuffer::ArgC() const -{ - return m_CurrentCommand.ArgC(); -} - -inline const char **CCommandBuffer::ArgV() const -{ - return m_CurrentCommand.ArgV(); -} - -inline const char *CCommandBuffer::ArgS() const -{ - return m_CurrentCommand.ArgS(); -} - -inline const char *CCommandBuffer::GetCommandString() const -{ - return m_CurrentCommand.GetCommandString(); -} - -inline const CCommand& CCommandBuffer::GetCommand() const -{ - return m_CurrentCommand; -} - -#endif // COMMANDBUFFER_H diff --git a/Resources/NetHook/tier1/KeyValues.cpp b/Resources/NetHook/tier1/KeyValues.cpp deleted file mode 100644 index 9916ddfd..00000000 --- a/Resources/NetHook/tier1/KeyValues.cpp +++ /dev/null @@ -1,2516 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#if defined( _WIN32 ) && !defined( _X360 ) -#include // for WideCharToMultiByte and MultiByteToWideChar -#elif defined(_LINUX) -#include // wcslen() -#define _alloca alloca -#endif - -#include -#include "filesystem.h" -#include - -#include -#include -#include "tier0/dbg.h" -#include "tier0/mem.h" -#include "utlvector.h" -#include "utlbuffer.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include - -static char * s_LastFileLoadingFrom = "unknown"; // just needed for error messages - -#define KEYVALUES_TOKEN_SIZE 1024 -static char s_pTokenBuf[KEYVALUES_TOKEN_SIZE]; - - -#define INTERNALWRITE( pData, len ) InternalWrite( filesystem, f, pBuf, pData, len ) - - -// a simple class to keep track of a stack of valid parsed symbols -const int MAX_ERROR_STACK = 64; -class CKeyValuesErrorStack -{ -public: - CKeyValuesErrorStack() : m_pFilename("NULL"), m_errorIndex(0), m_maxErrorIndex(0) {} - - void SetFilename( const char *pFilename ) - { - m_pFilename = pFilename; - m_maxErrorIndex = 0; - } - - // entering a new keyvalues block, save state for errors - // Not save symbols instead of pointers because the pointers can move! - int Push( int symName ) - { - if ( m_errorIndex < MAX_ERROR_STACK ) - { - m_errorStack[m_errorIndex] = symName; - } - m_errorIndex++; - m_maxErrorIndex = max( m_maxErrorIndex, (m_errorIndex-1) ); - return m_errorIndex-1; - } - - // exiting block, error isn't in this block, remove. - void Pop() - { - m_errorIndex--; - Assert(m_errorIndex>=0); - } - - // Allows you to keep the same stack level, but change the name as you parse peers - void Reset( int stackLevel, int symName ) - { - Assert( stackLevel >= 0 && stackLevel < m_errorIndex ); - m_errorStack[stackLevel] = symName; - } - - // Hit an error, report it and the parsing stack for context - void ReportError( const char *pError ) - { - Warning( "KeyValues Error: %s in file %s\n", pError, m_pFilename ); - for ( int i = 0; i < m_maxErrorIndex; i++ ) - { - if ( m_errorStack[i] != INVALID_KEY_SYMBOL ) - { - if ( i < m_errorIndex ) - { - Warning( "%s, ", KeyValuesSystem()->GetStringForSymbol(m_errorStack[i]) ); - } - else - { - Warning( "(*%s*), ", KeyValuesSystem()->GetStringForSymbol(m_errorStack[i]) ); - } - } - } - Warning( "\n" ); - } - -private: - int m_errorStack[MAX_ERROR_STACK]; - const char *m_pFilename; - int m_errorIndex; - int m_maxErrorIndex; -} g_KeyValuesErrorStack; - - -// a simple helper that creates stack entries as it goes in & out of scope -class CKeyErrorContext -{ -public: - CKeyErrorContext( KeyValues *pKv ) - { - Init( pKv->GetNameSymbol() ); - } - - ~CKeyErrorContext() - { - g_KeyValuesErrorStack.Pop(); - } - CKeyErrorContext( int symName ) - { - Init( symName ); - } - void Reset( int symName ) - { - g_KeyValuesErrorStack.Reset( m_stackLevel, symName ); - } -private: - void Init( int symName ) - { - m_stackLevel = g_KeyValuesErrorStack.Push( symName ); - } - - int m_stackLevel; -}; - -// Uncomment this line to hit the ~CLeakTrack assert to see what's looking like it's leaking -// #define LEAKTRACK - -#ifdef LEAKTRACK - -class CLeakTrack -{ -public: - CLeakTrack() - { - } - ~CLeakTrack() - { - if ( keys.Count() != 0 ) - { - Assert( 0 ); - } - } - - struct kve - { - KeyValues *kv; - char name[ 256 ]; - }; - - void AddKv( KeyValues *kv, char const *name ) - { - kve k; - Q_strncpy( k.name, name ? name : "NULL", sizeof( k.name ) ); - k.kv = kv; - - keys.AddToTail( k ); - } - - void RemoveKv( KeyValues *kv ) - { - int c = keys.Count(); - for ( int i = 0; i < c; i++ ) - { - if ( keys[i].kv == kv ) - { - keys.Remove( i ); - break; - } - } - } - - CUtlVector< kve > keys; -}; - -static CLeakTrack track; - -#define TRACK_KV_ADD( ptr, name ) track.AddKv( ptr, name ) -#define TRACK_KV_REMOVE( ptr ) track.RemoveKv( ptr ) - -#else - -#define TRACK_KV_ADD( ptr, name ) -#define TRACK_KV_REMOVE( ptr ) - -#endif - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -KeyValues::KeyValues( const char *setName ) -{ - TRACK_KV_ADD( this, setName ); - - Init(); - SetName ( setName ); -} - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -KeyValues::KeyValues( const char *setName, const char *firstKey, const char *firstValue ) -{ - TRACK_KV_ADD( this, setName ); - - Init(); - SetName( setName ); - SetString( firstKey, firstValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -KeyValues::KeyValues( const char *setName, const char *firstKey, const wchar_t *firstValue ) -{ - TRACK_KV_ADD( this, setName ); - - Init(); - SetName( setName ); - SetWString( firstKey, firstValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -KeyValues::KeyValues( const char *setName, const char *firstKey, int firstValue ) -{ - TRACK_KV_ADD( this, setName ); - - Init(); - SetName( setName ); - SetInt( firstKey, firstValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -KeyValues::KeyValues( const char *setName, const char *firstKey, const char *firstValue, const char *secondKey, const char *secondValue ) -{ - TRACK_KV_ADD( this, setName ); - - Init(); - SetName( setName ); - SetString( firstKey, firstValue ); - SetString( secondKey, secondValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -KeyValues::KeyValues( const char *setName, const char *firstKey, int firstValue, const char *secondKey, int secondValue ) -{ - TRACK_KV_ADD( this, setName ); - - Init(); - SetName( setName ); - SetInt( firstKey, firstValue ); - SetInt( secondKey, secondValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: Initialize member variables -//----------------------------------------------------------------------------- -void KeyValues::Init() -{ - m_iKeyName = INVALID_KEY_SYMBOL; - m_iDataType = TYPE_NONE; - - m_pSub = NULL; - m_pPeer = NULL; - m_pChain = NULL; - - m_sValue = NULL; - m_wsValue = NULL; - m_pValue = NULL; - - m_bHasEscapeSequences = false; - - // for future proof - memset( unused, 0, sizeof(unused) ); -} - -//----------------------------------------------------------------------------- -// Purpose: Destructor -//----------------------------------------------------------------------------- -KeyValues::~KeyValues() -{ - TRACK_KV_REMOVE( this ); - - RemoveEverything(); -} - -//----------------------------------------------------------------------------- -// Purpose: remove everything -//----------------------------------------------------------------------------- -void KeyValues::RemoveEverything() -{ - KeyValues *dat; - KeyValues *datNext = NULL; - for ( dat = m_pSub; dat != NULL; dat = datNext ) - { - datNext = dat->m_pPeer; - dat->m_pPeer = NULL; - delete dat; - } - - for ( dat = m_pPeer; dat && dat != this; dat = datNext ) - { - datNext = dat->m_pPeer; - dat->m_pPeer = NULL; - delete dat; - } - - delete [] m_sValue; - m_sValue = NULL; - delete [] m_wsValue; - m_wsValue = NULL; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *f - -//----------------------------------------------------------------------------- - -void KeyValues::RecursiveSaveToFile( CUtlBuffer& buf, int indentLevel ) -{ - RecursiveSaveToFile( NULL, FILESYSTEM_INVALID_HANDLE, &buf, indentLevel ); -} - -//----------------------------------------------------------------------------- -// Adds a chain... if we don't find stuff in this keyvalue, we'll look -// in the one we're chained to. -//----------------------------------------------------------------------------- - -void KeyValues::ChainKeyValue( KeyValues* pChain ) -{ - m_pChain = pChain; -} - -//----------------------------------------------------------------------------- -// Purpose: Get the name of the current key section -//----------------------------------------------------------------------------- -const char *KeyValues::GetName( void ) const -{ - return KeyValuesSystem()->GetStringForSymbol(m_iKeyName); -} - -//----------------------------------------------------------------------------- -// Purpose: Get the symbol name of the current key section -//----------------------------------------------------------------------------- -int KeyValues::GetNameSymbol() const -{ - return m_iKeyName; -} - - -//----------------------------------------------------------------------------- -// Purpose: Read a single token from buffer (0 terminated) -//----------------------------------------------------------------------------- -#pragma warning (disable:4706) -const char *KeyValues::ReadToken( CUtlBuffer &buf, bool &wasQuoted, bool &wasConditional ) -{ - wasQuoted = false; - wasConditional = false; - - if ( !buf.IsValid() ) - return NULL; - - // eating white spaces and remarks loop - while ( true ) - { - buf.EatWhiteSpace(); - if ( !buf.IsValid() ) - return NULL; // file ends after reading whitespaces - - // stop if it's not a comment; a new token starts here - if ( !buf.EatCPPComment() ) - break; - } - - const char *c = (const char*)buf.PeekGet( sizeof(char), 0 ); - if ( !c ) - return NULL; - - // read quoted strings specially - if ( *c == '\"' ) - { - wasQuoted = true; - buf.GetDelimitedString( m_bHasEscapeSequences ? GetCStringCharConversion() : GetNoEscCharConversion(), - s_pTokenBuf, KEYVALUES_TOKEN_SIZE ); - return s_pTokenBuf; - } - - if ( *c == '{' || *c == '}' ) - { - // it's a control char, just add this one char and stop reading - s_pTokenBuf[0] = *c; - s_pTokenBuf[1] = 0; - buf.SeekGet( CUtlBuffer::SEEK_CURRENT, 1 ); - return s_pTokenBuf; - } - - // read in the token until we hit a whitespace or a control character - bool bReportedError = false; - bool bConditionalStart = false; - int nCount = 0; - while ( c = (const char*)buf.PeekGet( sizeof(char), 0 ) ) - { - // end of file - if ( *c == 0 ) - break; - - // break if any control character appears in non quoted tokens - if ( *c == '"' || *c == '{' || *c == '}' ) - break; - - if ( *c == '[' ) - bConditionalStart = true; - - if ( *c == ']' && bConditionalStart ) - { - wasConditional = true; - } - - // break on whitespace - if ( isspace(*c) ) - break; - - if (nCount < (KEYVALUES_TOKEN_SIZE-1) ) - { - s_pTokenBuf[nCount++] = *c; // add char to buffer - } - else if ( !bReportedError ) - { - bReportedError = true; - g_KeyValuesErrorStack.ReportError(" ReadToken overflow" ); - } - - buf.SeekGet( CUtlBuffer::SEEK_CURRENT, 1 ); - } - s_pTokenBuf[ nCount ] = 0; - return s_pTokenBuf; -} -#pragma warning (default:4706) - - - -//----------------------------------------------------------------------------- -// Purpose: if parser should translate escape sequences ( /n, /t etc), set to true -//----------------------------------------------------------------------------- -void KeyValues::UsesEscapeSequences(bool state) -{ - m_bHasEscapeSequences = state; -} - - -//----------------------------------------------------------------------------- -// Purpose: Load keyValues from disk -//----------------------------------------------------------------------------- -bool KeyValues::LoadFromFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID ) -{ - Assert(filesystem); - Assert( IsX360() || ( IsPC() && _heapchk() == _HEAPOK ) ); - - FileHandle_t f = filesystem->Open(resourceName, "rb", pathID); - if ( !f ) - return false; - - s_LastFileLoadingFrom = (char*)resourceName; - - // load file into a null-terminated buffer - int fileSize = filesystem->Size( f ); - unsigned bufSize = ((IFileSystem *)filesystem)->GetOptimalReadSize( f, fileSize + 1 ); - - char *buffer = (char*)((IFileSystem *)filesystem)->AllocOptimalReadBuffer( f, bufSize ); - Assert( buffer ); - - // read into local buffer - bool bRetOK = ( ((IFileSystem *)filesystem)->ReadEx( buffer, bufSize, fileSize, f ) != 0 ); - - filesystem->Close( f ); // close file after reading - - if ( bRetOK ) - { - buffer[fileSize] = 0; // null terminate file as EOF - bRetOK = LoadFromBuffer( resourceName, buffer, filesystem ); - } - - ((IFileSystem *)filesystem)->FreeOptimalReadBuffer( buffer ); - - return bRetOK; -} - -//----------------------------------------------------------------------------- -// Purpose: Save the keyvalues to disk -// Creates the path to the file if it doesn't exist -//----------------------------------------------------------------------------- -bool KeyValues::SaveToFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID ) -{ - // create a write file - FileHandle_t f = filesystem->Open(resourceName, "wb", pathID); - - if ( f == FILESYSTEM_INVALID_HANDLE ) - { - DevMsg(1, "KeyValues::SaveToFile: couldn't open file \"%s\" in path \"%s\".\n", - resourceName?resourceName:"NULL", pathID?pathID:"NULL" ); - return false; - } - - RecursiveSaveToFile(filesystem, f, NULL, 0); - filesystem->Close(f); - - return true; -} - -//----------------------------------------------------------------------------- -// Purpose: Write out a set of indenting -//----------------------------------------------------------------------------- -void KeyValues::WriteIndents( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel ) -{ - for ( int i = 0; i < indentLevel; i++ ) - { - INTERNALWRITE( "\t", 1 ); - } -} - -//----------------------------------------------------------------------------- -// Purpose: Write out a string where we convert the double quotes to backslash double quote -//----------------------------------------------------------------------------- -void KeyValues::WriteConvertedString( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const char *pszString ) -{ - // handle double quote chars within the string - // the worst possible case is that the whole string is quotes - int len = Q_strlen(pszString); - char *convertedString = (char *) _alloca ((len + 1) * sizeof(char) * 2); - int j=0; - for (int i=0; i <= len; i++) - { - if (pszString[i] == '\"') - { - convertedString[j] = '\\'; - j++; - } - else if ( m_bHasEscapeSequences && pszString[i] == '\\' ) - { - convertedString[j] = '\\'; - j++; - } - convertedString[j] = pszString[i]; - j++; - } - - INTERNALWRITE(convertedString, strlen(convertedString)); -} - - -void KeyValues::InternalWrite( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const void *pData, int len ) -{ - if ( filesystem ) - { - filesystem->Write( pData, len, f ); - } - - if ( pBuf ) - { - pBuf->Put( pData, len ); - } -} - - -//----------------------------------------------------------------------------- -// Purpose: Save keyvalues from disk, if subkey values are detected, calls -// itself to save those -//----------------------------------------------------------------------------- -void KeyValues::RecursiveSaveToFile( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel ) -{ - // write header - WriteIndents( filesystem, f, pBuf, indentLevel ); - INTERNALWRITE("\"", 1); - WriteConvertedString(filesystem, f, pBuf, GetName()); - INTERNALWRITE("\"\n", 2); - WriteIndents( filesystem, f, pBuf, indentLevel ); - INTERNALWRITE("{\n", 2); - - // loop through all our keys writing them to disk - for ( KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer ) - { - if ( dat->m_pSub ) - { - dat->RecursiveSaveToFile( filesystem, f, pBuf, indentLevel + 1 ); - } - else - { - // only write non-empty keys - - switch (dat->m_iDataType) - { - case TYPE_STRING: - { - if (dat->m_sValue && *(dat->m_sValue)) - { - WriteIndents(filesystem, f, pBuf, indentLevel + 1); - INTERNALWRITE("\"", 1); - WriteConvertedString(filesystem, f, pBuf, dat->GetName()); - INTERNALWRITE("\"\t\t\"", 4); - - WriteConvertedString(filesystem, f, pBuf, dat->m_sValue); - - INTERNALWRITE("\"\n", 2); - } - break; - } - case TYPE_WSTRING: - { -#ifdef _WIN32 - if ( dat->m_wsValue ) - { - static char buf[KEYVALUES_TOKEN_SIZE]; - // make sure we have enough space - Assert(::WideCharToMultiByte(CP_UTF8, 0, dat->m_wsValue, -1, NULL, 0, NULL, NULL) < KEYVALUES_TOKEN_SIZE); - int result = ::WideCharToMultiByte(CP_UTF8, 0, dat->m_wsValue, -1, buf, KEYVALUES_TOKEN_SIZE, NULL, NULL); - if (result) - { - WriteIndents(filesystem, f, pBuf, indentLevel + 1); - INTERNALWRITE("\"", 1); - INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName())); - INTERNALWRITE("\"\t\t\"", 4); - - WriteConvertedString(filesystem, f, pBuf, buf); - - INTERNALWRITE("\"\n", 2); - } - } -#endif - break; - } - - case TYPE_INT: - { - WriteIndents(filesystem, f, pBuf, indentLevel + 1); - INTERNALWRITE("\"", 1); - INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName())); - INTERNALWRITE("\"\t\t\"", 4); - - char buf[32]; - Q_snprintf(buf, sizeof( buf ), "%d", dat->m_iValue); - - INTERNALWRITE(buf, Q_strlen(buf)); - INTERNALWRITE("\"\n", 2); - break; - } - - case TYPE_UINT64: - { - WriteIndents(filesystem, f, pBuf, indentLevel + 1); - INTERNALWRITE("\"", 1); - INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName())); - INTERNALWRITE("\"\t\t\"", 4); - - char buf[32]; - // write "0x" + 16 char 0-padded hex encoded 64 bit value - Q_snprintf( buf, sizeof( buf ), "0x%016I64X", *( (uint64 *)dat->m_sValue ) ); - - INTERNALWRITE(buf, Q_strlen(buf)); - INTERNALWRITE("\"\n", 2); - break; - } - - case TYPE_FLOAT: - { - WriteIndents(filesystem, f, pBuf, indentLevel + 1); - INTERNALWRITE("\"", 1); - INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName())); - INTERNALWRITE("\"\t\t\"", 4); - - char buf[48]; - Q_snprintf(buf, sizeof( buf ), "%f", dat->m_flValue); - - INTERNALWRITE(buf, Q_strlen(buf)); - INTERNALWRITE("\"\n", 2); - break; - } - case TYPE_COLOR: - DevMsg(1, "KeyValues::RecursiveSaveToFile: TODO, missing code for TYPE_COLOR.\n"); - break; - - default: - break; - } - } - } - - // write tail - WriteIndents(filesystem, f, pBuf, indentLevel); - INTERNALWRITE("}\n", 2); -} - -//----------------------------------------------------------------------------- -// Purpose: looks up a key by symbol name -//----------------------------------------------------------------------------- -KeyValues *KeyValues::FindKey(int keySymbol) const -{ - for (KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer) - { - if (dat->m_iKeyName == keySymbol) - return dat; - } - - return NULL; -} - -//----------------------------------------------------------------------------- -// Purpose: Find a keyValue, create it if it is not found. -// Set bCreate to true to create the key if it doesn't already exist -// (which ensures a valid pointer will be returned) -//----------------------------------------------------------------------------- -KeyValues *KeyValues::FindKey(const char *keyName, bool bCreate) -{ - // return the current key if a NULL subkey is asked for - if (!keyName || !keyName[0]) - return this; - - // look for '/' characters deliminating sub fields - char szBuf[256]; - const char *subStr = strchr(keyName, '/'); - const char *searchStr = keyName; - - // pull out the substring if it exists - if (subStr) - { - int size = subStr - keyName; - Q_memcpy( szBuf, keyName, size ); - szBuf[size] = 0; - searchStr = szBuf; - } - - // lookup the symbol for the search string - HKeySymbol iSearchStr = KeyValuesSystem()->GetSymbolForString( searchStr, bCreate ); - if ( iSearchStr == INVALID_KEY_SYMBOL ) - { - // not found, couldn't possibly be in key value list - return NULL; - } - - KeyValues *lastItem = NULL; - KeyValues *dat; - // find the searchStr in the current peer list - for (dat = m_pSub; dat != NULL; dat = dat->m_pPeer) - { - lastItem = dat; // record the last item looked at (for if we need to append to the end of the list) - - // symbol compare - if (dat->m_iKeyName == iSearchStr) - { - break; - } - } - - if ( !dat && m_pChain ) - { - dat = m_pChain->FindKey(keyName, false); - } - - // make sure a key was found - if (!dat) - { - if (bCreate) - { - // we need to create a new key - dat = new KeyValues( searchStr ); -// Assert(dat != NULL); - - // insert new key at end of list - if (lastItem) - { - lastItem->m_pPeer = dat; - } - else - { - m_pSub = dat; - } - dat->m_pPeer = NULL; - - // a key graduates to be a submsg as soon as it's m_pSub is set - // this should be the only place m_pSub is set - m_iDataType = TYPE_NONE; - } - else - { - return NULL; - } - } - - // if we've still got a subStr we need to keep looking deeper in the tree - if ( subStr ) - { - // recursively chain down through the paths in the string - return dat->FindKey(subStr + 1, bCreate); - } - - return dat; -} - -//----------------------------------------------------------------------------- -// Purpose: Create a new key, with an autogenerated name. -// Name is guaranteed to be an integer, of value 1 higher than the highest -// other integer key name -//----------------------------------------------------------------------------- -KeyValues *KeyValues::CreateNewKey() -{ - int newID = 1; - - // search for any key with higher values - for (KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer) - { - // case-insensitive string compare - int val = atoi(dat->GetName()); - if (newID <= val) - { - newID = val + 1; - } - } - - char buf[12]; - Q_snprintf( buf, sizeof(buf), "%d", newID ); - - return CreateKey( buf ); -} - - -//----------------------------------------------------------------------------- -// Create a key -//----------------------------------------------------------------------------- -KeyValues* KeyValues::CreateKey( const char *keyName ) -{ - // key wasn't found so just create a new one - KeyValues* dat = new KeyValues( keyName ); - - dat->UsesEscapeSequences( m_bHasEscapeSequences != 0 ); // use same format as parent does - - // add into subkey list - AddSubKey( dat ); - - return dat; -} - - -//----------------------------------------------------------------------------- -// Adds a subkey. Make sure the subkey isn't a child of some other keyvalues -//----------------------------------------------------------------------------- -void KeyValues::AddSubKey( KeyValues *pSubkey ) -{ - // Make sure the subkey isn't a child of some other keyvalues - Assert( pSubkey->m_pPeer == NULL ); - - // add into subkey list - if ( m_pSub == NULL ) - { - m_pSub = pSubkey; - } - else - { - KeyValues *pTempDat = m_pSub; - while ( pTempDat->GetNextKey() != NULL ) - { - pTempDat = pTempDat->GetNextKey(); - } - - pTempDat->SetNextKey( pSubkey ); - } -} - - - -//----------------------------------------------------------------------------- -// Purpose: Remove a subkey from the list -//----------------------------------------------------------------------------- -void KeyValues::RemoveSubKey(KeyValues *subKey) -{ - if (!subKey) - return; - - // check the list pointer - if (m_pSub == subKey) - { - m_pSub = subKey->m_pPeer; - } - else - { - // look through the list - KeyValues *kv = m_pSub; - while (kv->m_pPeer) - { - if (kv->m_pPeer == subKey) - { - kv->m_pPeer = subKey->m_pPeer; - break; - } - - kv = kv->m_pPeer; - } - } - - subKey->m_pPeer = NULL; -} - - - -//----------------------------------------------------------------------------- -// Purpose: Return the first subkey in the list -//----------------------------------------------------------------------------- -KeyValues *KeyValues::GetFirstSubKey() -{ - return m_pSub; -} - -//----------------------------------------------------------------------------- -// Purpose: Return the next subkey -//----------------------------------------------------------------------------- -KeyValues *KeyValues::GetNextKey() -{ - return m_pPeer; -} - -//----------------------------------------------------------------------------- -// Purpose: Sets this key's peer to the KeyValues passed in -//----------------------------------------------------------------------------- -void KeyValues::SetNextKey( KeyValues *pDat ) -{ - m_pPeer = pDat; -} - - -KeyValues* KeyValues::GetFirstTrueSubKey() -{ - KeyValues *pRet = m_pSub; - while ( pRet && pRet->m_iDataType != TYPE_NONE ) - pRet = pRet->m_pPeer; - - return pRet; -} - -KeyValues* KeyValues::GetNextTrueSubKey() -{ - KeyValues *pRet = m_pPeer; - while ( pRet && pRet->m_iDataType != TYPE_NONE ) - pRet = pRet->m_pPeer; - - return pRet; -} - -KeyValues* KeyValues::GetFirstValue() -{ - KeyValues *pRet = m_pSub; - while ( pRet && pRet->m_iDataType == TYPE_NONE ) - pRet = pRet->m_pPeer; - - return pRet; -} - -KeyValues* KeyValues::GetNextValue() -{ - KeyValues *pRet = m_pPeer; - while ( pRet && pRet->m_iDataType == TYPE_NONE ) - pRet = pRet->m_pPeer; - - return pRet; -} - - -//----------------------------------------------------------------------------- -// Purpose: Get the integer value of a keyName. Default value is returned -// if the keyName can't be found. -//----------------------------------------------------------------------------- -int KeyValues::GetInt( const char *keyName, int defaultValue ) -{ - KeyValues *dat = FindKey( keyName, false ); - if ( dat ) - { - switch ( dat->m_iDataType ) - { - case TYPE_STRING: - return atoi(dat->m_sValue); - case TYPE_WSTRING: -#ifdef _WIN32 - return _wtoi(dat->m_wsValue); -#else - DevMsg( "TODO: implement _wtoi\n"); - return 0; -#endif - case TYPE_FLOAT: - return (int)dat->m_flValue; - case TYPE_UINT64: - // can't convert, since it would lose data - Assert(0); - return 0; - case TYPE_INT: - case TYPE_PTR: - default: - return dat->m_iValue; - }; - } - return defaultValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Get the integer value of a keyName. Default value is returned -// if the keyName can't be found. -//----------------------------------------------------------------------------- -uint64 KeyValues::GetUint64( const char *keyName, uint64 defaultValue ) -{ - KeyValues *dat = FindKey( keyName, false ); - if ( dat ) - { - switch ( dat->m_iDataType ) - { - case TYPE_STRING: - return atoi(dat->m_sValue); - case TYPE_WSTRING: -#ifdef _WIN32 - return _wtoi(dat->m_wsValue); -#else - AssertFatal( 0 ); - return 0; -#endif - case TYPE_FLOAT: - return (int)dat->m_flValue; - case TYPE_UINT64: - return *((uint64 *)dat->m_sValue); - case TYPE_INT: - case TYPE_PTR: - default: - return dat->m_iValue; - }; - } - return defaultValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Get the pointer value of a keyName. Default value is returned -// if the keyName can't be found. -//----------------------------------------------------------------------------- -void *KeyValues::GetPtr( const char *keyName, void *defaultValue ) -{ - KeyValues *dat = FindKey( keyName, false ); - if ( dat ) - { - switch ( dat->m_iDataType ) - { - case TYPE_PTR: - return dat->m_pValue; - - case TYPE_WSTRING: - case TYPE_STRING: - case TYPE_FLOAT: - case TYPE_INT: - case TYPE_UINT64: - default: - return NULL; - }; - } - return defaultValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Get the float value of a keyName. Default value is returned -// if the keyName can't be found. -//----------------------------------------------------------------------------- -float KeyValues::GetFloat( const char *keyName, float defaultValue ) -{ - KeyValues *dat = FindKey( keyName, false ); - if ( dat ) - { - switch ( dat->m_iDataType ) - { - case TYPE_STRING: - return (float)atof(dat->m_sValue); - case TYPE_WSTRING: -#ifdef _WIN32 - return (float) _wtof(dat->m_wsValue); // no wtof -#else - Assert(0); - return 0.; -#endif - case TYPE_FLOAT: - return dat->m_flValue; - case TYPE_INT: - return (float)dat->m_iValue; - case TYPE_UINT64: - return (float)(*((uint64 *)dat->m_sValue)); - case TYPE_PTR: - default: - return 0.0f; - }; - } - return defaultValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Get the string pointer of a keyName. Default value is returned -// if the keyName can't be found. -//----------------------------------------------------------------------------- -const char *KeyValues::GetString( const char *keyName, const char *defaultValue ) -{ - KeyValues *dat = FindKey( keyName, false ); - if ( dat ) - { - // convert the data to string form then return it - char buf[64]; - switch ( dat->m_iDataType ) - { - case TYPE_FLOAT: - Q_snprintf( buf, sizeof( buf ), "%f", dat->m_flValue ); - SetString( keyName, buf ); - break; - case TYPE_INT: - case TYPE_PTR: - Q_snprintf( buf, sizeof( buf ), "%d", dat->m_iValue ); - SetString( keyName, buf ); - break; - case TYPE_UINT64: - Q_snprintf( buf, sizeof( buf ), "%I64i", *((uint64 *)(dat->m_sValue)) ); - SetString( keyName, buf ); - break; - - case TYPE_WSTRING: - { -#ifdef _WIN32 - // convert the string to char *, set it for future use, and return it - char wideBuf[512]; - int result = ::WideCharToMultiByte(CP_UTF8, 0, dat->m_wsValue, -1, wideBuf, 512, NULL, NULL); - if ( result ) - { - // note: this will copy wideBuf - SetString( keyName, wideBuf ); - } - else - { - return defaultValue; - } -#endif - break; - } - case TYPE_STRING: - break; - default: - return defaultValue; - }; - - return dat->m_sValue; - } - return defaultValue; -} - -const wchar_t *KeyValues::GetWString( const char *keyName, const wchar_t *defaultValue) -{ - KeyValues *dat = FindKey( keyName, false ); -#ifdef _WIN32 - if ( dat ) - { - wchar_t wbuf[64]; - switch ( dat->m_iDataType ) - { - case TYPE_FLOAT: - swprintf(wbuf, L"%f", dat->m_flValue); - SetWString( keyName, wbuf); - break; - case TYPE_INT: - case TYPE_PTR: - swprintf( wbuf, L"%d", dat->m_iValue ); - SetWString( keyName, wbuf ); - break; - case TYPE_UINT64: - { - swprintf( wbuf, L"%I64i", *((uint64 *)(dat->m_sValue)) ); - SetWString( keyName, wbuf ); - } - break; - - case TYPE_WSTRING: - break; - case TYPE_STRING: - { - static wchar_t wbuftemp[512]; // convert to wide - int result = ::MultiByteToWideChar(CP_UTF8, 0, dat->m_sValue, -1, wbuftemp, 512); - if ( result ) - { - SetWString( keyName, wbuftemp); - } - else - { - return defaultValue; - } - break; - } - default: - return defaultValue; - }; - - return (const wchar_t* )dat->m_wsValue; - } -#else - DevMsg("TODO: implement wide char functions\n"); -#endif - return defaultValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Gets a color -//----------------------------------------------------------------------------- -Color KeyValues::GetColor( const char *keyName ) -{ - Color color(0, 0, 0, 0); - KeyValues *dat = FindKey( keyName, false ); - if ( dat ) - { - if ( dat->m_iDataType == TYPE_COLOR ) - { - color[0] = dat->m_Color[0]; - color[1] = dat->m_Color[1]; - color[2] = dat->m_Color[2]; - color[3] = dat->m_Color[3]; - } - else if ( dat->m_iDataType == TYPE_FLOAT ) - { - color[0] = dat->m_flValue; - } - else if ( dat->m_iDataType == TYPE_INT ) - { - color[0] = dat->m_iValue; - } - else if ( dat->m_iDataType == TYPE_STRING ) - { - // parse the colors out of the string - float a, b, c, d; - sscanf(dat->m_sValue, "%f %f %f %f", &a, &b, &c, &d); - color[0] = (unsigned char)a; - color[1] = (unsigned char)b; - color[2] = (unsigned char)c; - color[3] = (unsigned char)d; - } - } - return color; -} - -//----------------------------------------------------------------------------- -// Purpose: Sets a color -//----------------------------------------------------------------------------- -void KeyValues::SetColor( const char *keyName, Color value) -{ - KeyValues *dat = FindKey( keyName, true ); - - if ( dat ) - { - dat->m_iDataType = TYPE_COLOR; - dat->m_Color[0] = value[0]; - dat->m_Color[1] = value[1]; - dat->m_Color[2] = value[2]; - dat->m_Color[3] = value[3]; - } -} - -void KeyValues::SetStringValue( char const *strValue ) -{ - // delete the old value - delete [] m_sValue; - // make sure we're not storing the WSTRING - as we're converting over to STRING - delete [] m_wsValue; - m_wsValue = NULL; - - if (!strValue) - { - // ensure a valid value - strValue = ""; - } - - // allocate memory for the new value and copy it in - int len = Q_strlen( strValue ); - m_sValue = new char[len + 1]; - Q_memcpy( m_sValue, strValue, len+1 ); - - m_iDataType = TYPE_STRING; -} - -//----------------------------------------------------------------------------- -// Purpose: Set the string value of a keyName. -//----------------------------------------------------------------------------- -void KeyValues::SetString( const char *keyName, const char *value ) -{ - KeyValues *dat = FindKey( keyName, true ); - - if ( dat ) - { - // delete the old value - delete [] dat->m_sValue; - // make sure we're not storing the WSTRING - as we're converting over to STRING - delete [] dat->m_wsValue; - dat->m_wsValue = NULL; - - if (!value) - { - // ensure a valid value - value = ""; - } - - // allocate memory for the new value and copy it in - int len = Q_strlen( value ); - dat->m_sValue = new char[len + 1]; - Q_memcpy( dat->m_sValue, value, len+1 ); - - dat->m_iDataType = TYPE_STRING; - } -} - -//----------------------------------------------------------------------------- -// Purpose: Set the string value of a keyName. -//----------------------------------------------------------------------------- -void KeyValues::SetWString( const char *keyName, const wchar_t *value ) -{ - KeyValues *dat = FindKey( keyName, true ); - if ( dat ) - { - // delete the old value - delete [] dat->m_wsValue; - // make sure we're not storing the STRING - as we're converting over to WSTRING - delete [] dat->m_sValue; - dat->m_sValue = NULL; - - if (!value) - { - // ensure a valid value - value = L""; - } - - // allocate memory for the new value and copy it in - int len = wcslen( value ); - dat->m_wsValue = new wchar_t[len + 1]; - Q_memcpy( dat->m_wsValue, value, (len+1) * sizeof(wchar_t) ); - - dat->m_iDataType = TYPE_WSTRING; - } -} - -//----------------------------------------------------------------------------- -// Purpose: Set the integer value of a keyName. -//----------------------------------------------------------------------------- -void KeyValues::SetInt( const char *keyName, int value ) -{ - KeyValues *dat = FindKey( keyName, true ); - - if ( dat ) - { - dat->m_iValue = value; - dat->m_iDataType = TYPE_INT; - } -} - -//----------------------------------------------------------------------------- -// Purpose: Set the integer value of a keyName. -//----------------------------------------------------------------------------- -void KeyValues::SetUint64( const char *keyName, uint64 value ) -{ - KeyValues *dat = FindKey( keyName, true ); - - if ( dat ) - { - // delete the old value - delete [] dat->m_sValue; - // make sure we're not storing the WSTRING - as we're converting over to STRING - delete [] dat->m_wsValue; - dat->m_wsValue = NULL; - - dat->m_sValue = new char[sizeof(uint64)]; - *((uint64 *)dat->m_sValue) = value; - dat->m_iDataType = TYPE_UINT64; - } -} - -//----------------------------------------------------------------------------- -// Purpose: Set the float value of a keyName. -//----------------------------------------------------------------------------- -void KeyValues::SetFloat( const char *keyName, float value ) -{ - KeyValues *dat = FindKey( keyName, true ); - - if ( dat ) - { - dat->m_flValue = value; - dat->m_iDataType = TYPE_FLOAT; - } -} - -void KeyValues::SetName( const char * setName ) -{ - m_iKeyName = KeyValuesSystem()->GetSymbolForString( setName ); -} - -//----------------------------------------------------------------------------- -// Purpose: Set the pointer value of a keyName. -//----------------------------------------------------------------------------- -void KeyValues::SetPtr( const char *keyName, void *value ) -{ - KeyValues *dat = FindKey( keyName, true ); - - if ( dat ) - { - dat->m_pValue = value; - dat->m_iDataType = TYPE_PTR; - } -} - -void KeyValues::RecursiveCopyKeyValues( KeyValues& src ) -{ - // garymcthack - need to check this code for possible buffer overruns. - - m_iKeyName = src.GetNameSymbol(); - - if( !src.m_pSub ) - { - m_iDataType = src.m_iDataType; - char buf[256]; - switch( src.m_iDataType ) - { - case TYPE_NONE: - break; - case TYPE_STRING: - if( src.m_sValue ) - { - int len = Q_strlen(src.m_sValue) + 1; - m_sValue = new char[len]; - Q_strncpy( m_sValue, src.m_sValue, len ); - } - break; - case TYPE_INT: - { - m_iValue = src.m_iValue; - Q_snprintf( buf,sizeof(buf), "%d", m_iValue ); - int len = Q_strlen(buf) + 1; - m_sValue = new char[len]; - Q_strncpy( m_sValue, buf, len ); - } - break; - case TYPE_FLOAT: - { - m_flValue = src.m_flValue; - Q_snprintf( buf,sizeof(buf), "%f", m_flValue ); - int len = Q_strlen(buf) + 1; - m_sValue = new char[len]; - Q_strncpy( m_sValue, buf, len ); - } - break; - case TYPE_PTR: - { - m_pValue = src.m_pValue; - } - break; - case TYPE_UINT64: - { - m_sValue = new char[sizeof(uint64)]; - Q_memcpy( m_sValue, src.m_sValue, sizeof(uint64) ); - } - break; - case TYPE_COLOR: - { - m_Color[0] = src.m_Color[0]; - m_Color[1] = src.m_Color[1]; - m_Color[2] = src.m_Color[2]; - m_Color[3] = src.m_Color[3]; - } - break; - - default: - { - // do nothing . .what the heck is this? - Assert( 0 ); - } - break; - } - - } -#if 0 - KeyValues *pDst = this; - for ( KeyValues *pSrc = src.m_pSub; pSrc; pSrc = pSrc->m_pPeer ) - { - if ( pSrc->m_pSub ) - { - pDst->m_pSub = new KeyValues( pSrc->m_pSub->getName() ); - pDst->m_pSub->RecursiveCopyKeyValues( *pSrc->m_pSub ); - } - else - { - // copy non-empty keys - if ( pSrc->m_sValue && *(pSrc->m_sValue) ) - { - pDst->m_pPeer = new KeyValues( - } - } - } -#endif - - // Handle the immediate child - if( src.m_pSub ) - { - m_pSub = new KeyValues( NULL ); - m_pSub->RecursiveCopyKeyValues( *src.m_pSub ); - } - - // Handle the immediate peer - if( src.m_pPeer ) - { - m_pPeer = new KeyValues( NULL ); - m_pPeer->RecursiveCopyKeyValues( *src.m_pPeer ); - } -} - -KeyValues& KeyValues::operator=( KeyValues& src ) -{ - RemoveEverything(); - Init(); // reset all values - RecursiveCopyKeyValues( src ); - return *this; -} - - -//----------------------------------------------------------------------------- -// Make a new copy of all subkeys, add them all to the passed-in keyvalues -//----------------------------------------------------------------------------- -void KeyValues::CopySubkeys( KeyValues *pParent ) const -{ - // recursively copy subkeys - // Also maintain ordering.... - KeyValues *pPrev = NULL; - for ( KeyValues *sub = m_pSub; sub != NULL; sub = sub->m_pPeer ) - { - // take a copy of the subkey - KeyValues *dat = sub->MakeCopy(); - - // add into subkey list - if (pPrev) - { - pPrev->m_pPeer = dat; - } - else - { - pParent->m_pSub = dat; - } - dat->m_pPeer = NULL; - pPrev = dat; - } -} - - -//----------------------------------------------------------------------------- -// Purpose: Makes a copy of the whole key-value pair set -//----------------------------------------------------------------------------- -KeyValues *KeyValues::MakeCopy( void ) const -{ - KeyValues *newKeyValue = new KeyValues(GetName()); - - // copy data - newKeyValue->m_iDataType = m_iDataType; - switch ( m_iDataType ) - { - case TYPE_STRING: - { - if ( m_sValue ) - { - int len = Q_strlen( m_sValue ); - Assert( !newKeyValue->m_sValue ); - newKeyValue->m_sValue = new char[len + 1]; - Q_memcpy( newKeyValue->m_sValue, m_sValue, len+1 ); - } - } - break; - case TYPE_WSTRING: - { - if ( m_wsValue ) - { - int len = wcslen( m_wsValue ); - newKeyValue->m_wsValue = new wchar_t[len+1]; - Q_memcpy( newKeyValue->m_wsValue, m_wsValue, (len+1)*sizeof(wchar_t)); - } - } - break; - - case TYPE_INT: - newKeyValue->m_iValue = m_iValue; - break; - - case TYPE_FLOAT: - newKeyValue->m_flValue = m_flValue; - break; - - case TYPE_PTR: - newKeyValue->m_pValue = m_pValue; - break; - - case TYPE_COLOR: - newKeyValue->m_Color[0] = m_Color[0]; - newKeyValue->m_Color[1] = m_Color[1]; - newKeyValue->m_Color[2] = m_Color[2]; - newKeyValue->m_Color[3] = m_Color[3]; - break; - - case TYPE_UINT64: - newKeyValue->m_sValue = new char[sizeof(uint64)]; - Q_memcpy( newKeyValue->m_sValue, m_sValue, sizeof(uint64) ); - break; - }; - - // recursively copy subkeys - CopySubkeys( newKeyValue ); - return newKeyValue; -} - - -//----------------------------------------------------------------------------- -// Purpose: Check if a keyName has no value assigned to it. -//----------------------------------------------------------------------------- -bool KeyValues::IsEmpty(const char *keyName) -{ - KeyValues *dat = FindKey(keyName, false); - if (!dat) - return true; - - if (dat->m_iDataType == TYPE_NONE && dat->m_pSub == NULL) - return true; - - return false; -} - -//----------------------------------------------------------------------------- -// Purpose: Clear out all subkeys, and the current value -//----------------------------------------------------------------------------- -void KeyValues::Clear( void ) -{ - delete m_pSub; - m_pSub = NULL; - m_iDataType = TYPE_NONE; -} - -//----------------------------------------------------------------------------- -// Purpose: Get the data type of the value stored in a keyName -//----------------------------------------------------------------------------- -KeyValues::types_t KeyValues::GetDataType(const char *keyName) -{ - KeyValues *dat = FindKey(keyName, false); - if (dat) - return (types_t)dat->m_iDataType; - - return TYPE_NONE; -} - -//----------------------------------------------------------------------------- -// Purpose: Deletion, ensures object gets deleted from correct heap -//----------------------------------------------------------------------------- -void KeyValues::deleteThis() -{ - delete this; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : includedKeys - -//----------------------------------------------------------------------------- -void KeyValues::AppendIncludedKeys( CUtlVector< KeyValues * >& includedKeys ) -{ - // Append any included keys, too... - int includeCount = includedKeys.Count(); - int i; - for ( i = 0; i < includeCount; i++ ) - { - KeyValues *kv = includedKeys[ i ]; - Assert( kv ); - - KeyValues *insertSpot = this; - while ( insertSpot->GetNextKey() ) - { - insertSpot = insertSpot->GetNextKey(); - } - - insertSpot->SetNextKey( kv ); - } -} - -void KeyValues::ParseIncludedKeys( char const *resourceName, const char *filetoinclude, - IBaseFileSystem* pFileSystem, const char *pPathID, CUtlVector< KeyValues * >& includedKeys ) -{ - Assert( resourceName ); - Assert( filetoinclude ); - Assert( pFileSystem ); - - // Load it... - if ( !pFileSystem ) - { - return; - } - - // Get relative subdirectory - char fullpath[ 512 ]; - Q_strncpy( fullpath, resourceName, sizeof( fullpath ) ); - - // Strip off characters back to start or first / - bool done = false; - int len = Q_strlen( fullpath ); - while ( !done ) - { - if ( len <= 0 ) - { - break; - } - - if ( fullpath[ len - 1 ] == '\\' || - fullpath[ len - 1 ] == '/' ) - { - break; - } - - // zero it - fullpath[ len - 1 ] = 0; - --len; - } - - // Append included file - Q_strncat( fullpath, filetoinclude, sizeof( fullpath ), COPY_ALL_CHARACTERS ); - - KeyValues *newKV = new KeyValues( fullpath ); - - // CUtlSymbol save = s_CurrentFileSymbol; // did that had any use ??? - - newKV->UsesEscapeSequences( m_bHasEscapeSequences != 0 ); // use same format as parent - - if ( newKV->LoadFromFile( pFileSystem, fullpath, pPathID ) ) - { - includedKeys.AddToTail( newKV ); - } - else - { - DevMsg( "KeyValues::ParseIncludedKeys: Couldn't load included keyvalue file %s\n", fullpath ); - newKV->deleteThis(); - } - - // s_CurrentFileSymbol = save; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : baseKeys - -//----------------------------------------------------------------------------- -void KeyValues::MergeBaseKeys( CUtlVector< KeyValues * >& baseKeys ) -{ - int includeCount = baseKeys.Count(); - int i; - for ( i = 0; i < includeCount; i++ ) - { - KeyValues *kv = baseKeys[ i ]; - Assert( kv ); - - RecursiveMergeKeyValues( kv ); - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : baseKV - keyvalues we're basing ourselves on -//----------------------------------------------------------------------------- -void KeyValues::RecursiveMergeKeyValues( KeyValues *baseKV ) -{ - // Merge ourselves - // we always want to keep our value, so nothing to do here - - // Now merge our children - for ( KeyValues *baseChild = baseKV->m_pSub; baseChild != NULL; baseChild = baseChild->m_pPeer ) - { - // for each child in base, see if we have a matching kv - - bool bFoundMatch = false; - - // If we have a child by the same name, merge those keys - for ( KeyValues *newChild = m_pSub; newChild != NULL; newChild = newChild->m_pPeer ) - { - if ( !Q_strcmp( baseChild->GetName(), newChild->GetName() ) ) - { - newChild->RecursiveMergeKeyValues( baseChild ); - bFoundMatch = true; - break; - } - } - - // If not merged, append this key - if ( !bFoundMatch ) - { - KeyValues *dat = baseChild->MakeCopy(); - Assert( dat ); - AddSubKey( dat ); - } - } -} - -//----------------------------------------------------------------------------- -// Returns whether a keyvalues conditional evaluates to true or false -// Needs more flexibility with conditionals, checking convars would be nice. -//----------------------------------------------------------------------------- -bool EvaluateConditional( const char *str ) -{ - bool bResult = false; - bool bXboxUI = IsX360(); - - if ( bXboxUI ) - { - bResult = !Q_stricmp( "[$X360]", str ); - } - else - { - bResult = !Q_stricmp( "[$WIN32]", str ); - } - - return bResult; -} - - -//----------------------------------------------------------------------------- -// Read from a buffer... -//----------------------------------------------------------------------------- -bool KeyValues::LoadFromBuffer( char const *resourceName, CUtlBuffer &buf, IBaseFileSystem* pFileSystem, const char *pPathID ) -{ - KeyValues *pPreviousKey = NULL; - KeyValues *pCurrentKey = this; - CUtlVector< KeyValues * > includedKeys; - CUtlVector< KeyValues * > baseKeys; - bool wasQuoted; - bool wasConditional; - g_KeyValuesErrorStack.SetFilename( resourceName ); - do - { - bool bAccepted = true; - - // the first thing must be a key - const char *s = ReadToken( buf, wasQuoted, wasConditional ); - if ( !buf.IsValid() || !s || *s == 0 ) - break; - - if ( !Q_stricmp( s, "#include" ) ) // special include macro (not a key name) - { - s = ReadToken( buf, wasQuoted, wasConditional ); - // Name of subfile to load is now in s - - if ( !s || *s == 0 ) - { - g_KeyValuesErrorStack.ReportError("#include is NULL " ); - } - else - { - ParseIncludedKeys( resourceName, s, pFileSystem, pPathID, includedKeys ); - } - - continue; - } - else if ( !Q_stricmp( s, "#base" ) ) - { - s = ReadToken( buf, wasQuoted, wasConditional ); - // Name of subfile to load is now in s - - if ( !s || *s == 0 ) - { - g_KeyValuesErrorStack.ReportError("#base is NULL " ); - } - else - { - ParseIncludedKeys( resourceName, s, pFileSystem, pPathID, baseKeys ); - } - - continue; - } - - if ( !pCurrentKey ) - { - pCurrentKey = new KeyValues( s ); - Assert( pCurrentKey ); - - pCurrentKey->UsesEscapeSequences( m_bHasEscapeSequences != 0 ); // same format has parent use - - if ( pPreviousKey ) - { - pPreviousKey->SetNextKey( pCurrentKey ); - } - } - else - { - pCurrentKey->SetName( s ); - } - - // get the '{' - s = ReadToken( buf, wasQuoted, wasConditional ); - - if ( wasConditional ) - { - bAccepted = EvaluateConditional( s ); - - // Now get the '{' - s = ReadToken( buf, wasQuoted, wasConditional ); - } - - if ( s && *s == '{' && !wasQuoted ) - { - // header is valid so load the file - pCurrentKey->RecursiveLoadFromBuffer( resourceName, buf ); - } - else - { - g_KeyValuesErrorStack.ReportError("LoadFromBuffer: missing {" ); - } - - if ( !bAccepted ) - { - if ( pPreviousKey ) - { - pPreviousKey->SetNextKey( NULL ); - } - pCurrentKey->Clear(); - } - else - { - pPreviousKey = pCurrentKey; - pCurrentKey = NULL; - } - } while ( buf.IsValid() ); - - AppendIncludedKeys( includedKeys ); - { - // delete included keys! - int i; - for ( i = includedKeys.Count() - 1; i > 0; i-- ) - { - KeyValues *kv = includedKeys[ i ]; - kv->deleteThis(); - } - } - - MergeBaseKeys( baseKeys ); - { - // delete base keys! - int i; - for ( i = baseKeys.Count() - 1; i >= 0; i-- ) - { - KeyValues *kv = baseKeys[ i ]; - kv->deleteThis(); - } - } - - g_KeyValuesErrorStack.SetFilename( "" ); - - return true; -} - - -//----------------------------------------------------------------------------- -// Read from a buffer... -//----------------------------------------------------------------------------- -bool KeyValues::LoadFromBuffer( char const *resourceName, const char *pBuffer, IBaseFileSystem* pFileSystem, const char *pPathID ) -{ - if ( !pBuffer ) - return true; - - int nLen = Q_strlen( pBuffer ); - CUtlBuffer buf( pBuffer, nLen, CUtlBuffer::READ_ONLY | CUtlBuffer::TEXT_BUFFER ); - return LoadFromBuffer( resourceName, buf, pFileSystem, pPathID ); -} - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -void KeyValues::RecursiveLoadFromBuffer( char const *resourceName, CUtlBuffer &buf ) -{ - CKeyErrorContext errorReport(this); - bool wasQuoted; - bool wasConditional; - // keep this out of the stack until a key is parsed - CKeyErrorContext errorKey( INVALID_KEY_SYMBOL ); - while ( 1 ) - { - bool bAccepted = true; - - // get the key name - const char * name = ReadToken( buf, wasQuoted, wasConditional ); - - if ( !name ) // EOF stop reading - { - g_KeyValuesErrorStack.ReportError("RecursiveLoadFromBuffer: got EOF instead of keyname" ); - break; - } - - if ( !*name ) // empty token, maybe "" or EOF - { - g_KeyValuesErrorStack.ReportError("RecursiveLoadFromBuffer: got empty keyname" ); - break; - } - - if ( *name == '}' && !wasQuoted ) // top level closed, stop reading - break; - - // Always create the key; note that this could potentially - // cause some duplication, but that's what we want sometimes - KeyValues *dat = CreateKey( name ); - - errorKey.Reset( dat->GetNameSymbol() ); - - // get the value - const char * value = ReadToken( buf, wasQuoted, wasConditional ); - - if ( wasConditional && value ) - { - bAccepted = EvaluateConditional( value ); - - // get the real value - value = ReadToken( buf, wasQuoted, wasConditional ); - } - - if ( !value ) - { - g_KeyValuesErrorStack.ReportError("RecursiveLoadFromBuffer: got NULL key" ); - break; - } - - if ( *value == '}' && !wasQuoted ) - { - g_KeyValuesErrorStack.ReportError("RecursiveLoadFromBuffer: got } in key" ); - break; - } - - if ( *value == '{' && !wasQuoted ) - { - // this isn't a key, it's a section - errorKey.Reset( INVALID_KEY_SYMBOL ); - // sub value list - dat->RecursiveLoadFromBuffer( resourceName, buf ); - } - else - { - if ( wasConditional ) - { - g_KeyValuesErrorStack.ReportError("RecursiveLoadFromBuffer: got conditional between key and value" ); - break; - } - - if (dat->m_sValue) - { - delete[] dat->m_sValue; - dat->m_sValue = NULL; - } - - int len = Q_strlen( value ); - - // Here, let's determine if we got a float or an int.... - char* pIEnd; // pos where int scan ended - char* pFEnd; // pos where float scan ended - const char* pSEnd = value + len ; // pos where token ends - - int ival = strtol( value, &pIEnd, 10 ); - float fval = (float)strtod( value, &pFEnd ); - - if ( *value == 0 ) - { - dat->m_iDataType = TYPE_STRING; - } - else if ( ( 18 == len ) && ( value[0] == '0' ) && ( value[1] == 'x' ) ) - { - // an 18-byte value prefixed with "0x" (followed by 16 hex digits) is an int64 value - int64 retVal = 0; - for( int i=2; i < 2 + 16; i++ ) - { - char digit = value[i]; - if ( digit >= 'a' ) - digit -= 'a' - ( '9' + 1 ); - else - if ( digit >= 'A' ) - digit -= 'A' - ( '9' + 1 ); - retVal = ( retVal * 16 ) + ( digit - '0' ); - } - dat->m_sValue = new char[sizeof(uint64)]; - *((uint64 *)dat->m_sValue) = retVal; - dat->m_iDataType = TYPE_UINT64; - } - else if ( (pFEnd > pIEnd) && (pFEnd == pSEnd) ) - { - dat->m_flValue = fval; - dat->m_iDataType = TYPE_FLOAT; - } - else if (pIEnd == pSEnd) - { - dat->m_iValue = ival; - dat->m_iDataType = TYPE_INT; - } - else - { - dat->m_iDataType = TYPE_STRING; - } - - if (dat->m_iDataType == TYPE_STRING) - { - // copy in the string information - dat->m_sValue = new char[len+1]; - Q_memcpy( dat->m_sValue, value, len+1 ); - } - - // Look ahead one token for a conditional tag - int prevPos = buf.TellGet(); - const char *peek = ReadToken( buf, wasQuoted, wasConditional ); - if ( wasConditional ) - { - bAccepted = EvaluateConditional( peek ); - } - else - { - buf.SeekGet( CUtlBuffer::SEEK_HEAD, prevPos ); - } - } - - if ( !bAccepted ) - { - this->RemoveSubKey( dat ); - dat->deleteThis(); - dat = NULL; - } - } -} - - - -// writes KeyValue as binary data to buffer -bool KeyValues::WriteAsBinary( CUtlBuffer &buffer ) -{ - if ( buffer.IsText() ) // must be a binary buffer - return false; - - if ( !buffer.IsValid() ) // must be valid, no overflows etc - return false; - - // Write subkeys: - - // loop through all our peers - for ( KeyValues *dat = this; dat != NULL; dat = dat->m_pPeer ) - { - // write type - buffer.PutUnsignedChar( dat->m_iDataType ); - - // write name - buffer.PutString( dat->GetName() ); - - // write type - switch (dat->m_iDataType) - { - case TYPE_NONE: - { - dat->m_pSub->WriteAsBinary( buffer ); - break; - } - case TYPE_STRING: - { - if (dat->m_sValue && *(dat->m_sValue)) - { - buffer.PutString( dat->m_sValue ); - } - else - { - buffer.PutString( "" ); - } - break; - } - case TYPE_WSTRING: - { - Assert( !"TYPE_WSTRING" ); - break; - } - - case TYPE_INT: - { - buffer.PutInt( dat->m_iValue ); - break; - } - - case TYPE_UINT64: - { - buffer.PutDouble( *((double *)dat->m_sValue) ); - break; - } - - case TYPE_FLOAT: - { - buffer.PutFloat( dat->m_flValue ); - break; - } - case TYPE_COLOR: - { - buffer.PutUnsignedChar( dat->m_Color[0] ); - buffer.PutUnsignedChar( dat->m_Color[1] ); - buffer.PutUnsignedChar( dat->m_Color[2] ); - buffer.PutUnsignedChar( dat->m_Color[3] ); - break; - } - case TYPE_PTR: - { - buffer.PutUnsignedInt( (int)dat->m_pValue ); - } - - default: - break; - } - } - - // write tail, marks end of peers - buffer.PutUnsignedChar( TYPE_NUMTYPES ); - - return buffer.IsValid(); -} - -// read KeyValues from binary buffer, returns true if parsing was successful -bool KeyValues::ReadAsBinary( CUtlBuffer &buffer ) -{ - if ( buffer.IsText() ) // must be a binary buffer - return false; - - if ( !buffer.IsValid() ) // must be valid, no overflows etc - return false; - - RemoveEverything(); // remove current content - Init(); // reset - - char token[KEYVALUES_TOKEN_SIZE]; - KeyValues *dat = this; - types_t type = (types_t)buffer.GetUnsignedChar(); - - // loop through all our peers - while ( true ) - { - if ( type == TYPE_NUMTYPES ) - break; // no more peers - - dat->m_iDataType = type; - - buffer.GetString( token, KEYVALUES_TOKEN_SIZE-1 ); - token[KEYVALUES_TOKEN_SIZE-1] = 0; - - dat->SetName( token ); - - switch ( type ) - { - case TYPE_NONE: - { - dat->m_pSub = new KeyValues(""); - dat->m_pSub->ReadAsBinary( buffer ); - break; - } - case TYPE_STRING: - { - buffer.GetString( token, KEYVALUES_TOKEN_SIZE-1 ); - token[KEYVALUES_TOKEN_SIZE-1] = 0; - - int len = Q_strlen( token ); - dat->m_sValue = new char[len + 1]; - Q_memcpy( dat->m_sValue, token, len+1 ); - - break; - } - case TYPE_WSTRING: - { - Assert( !"TYPE_WSTRING" ); - break; - } - - case TYPE_INT: - { - dat->m_iValue = buffer.GetInt(); - break; - } - - case TYPE_UINT64: - { - dat->m_sValue = new char[sizeof(uint64)]; - *((double *)dat->m_sValue) = buffer.GetDouble(); - } - - case TYPE_FLOAT: - { - dat->m_flValue = buffer.GetFloat(); - break; - } - case TYPE_COLOR: - { - dat->m_Color[0] = buffer.GetUnsignedChar(); - dat->m_Color[1] = buffer.GetUnsignedChar(); - dat->m_Color[2] = buffer.GetUnsignedChar(); - dat->m_Color[3] = buffer.GetUnsignedChar(); - break; - } - case TYPE_PTR: - { - dat->m_pValue = (void*)buffer.GetUnsignedInt(); - } - - default: - break; - } - - if ( !buffer.IsValid() ) // error occured - return false; - - type = (types_t)buffer.GetUnsignedChar(); - - if ( type == TYPE_NUMTYPES ) - break; - - // new peer follows - dat->m_pPeer = new KeyValues(""); - dat = dat->m_pPeer; - } - - return buffer.IsValid(); -} - -#include "tier0/memdbgoff.h" - -//----------------------------------------------------------------------------- -// Purpose: memory allocator -//----------------------------------------------------------------------------- -void *KeyValues::operator new( unsigned int iAllocSize ) -{ - MEM_ALLOC_CREDIT(); - return KeyValuesSystem()->AllocKeyValuesMemory(iAllocSize); -} - -void *KeyValues::operator new( unsigned int iAllocSize, int nBlockUse, const char *pFileName, int nLine ) -{ - MemAlloc_PushAllocDbgInfo( pFileName, nLine ); - void *p = KeyValuesSystem()->AllocKeyValuesMemory(iAllocSize); - MemAlloc_PopAllocDbgInfo(); - return p; -} - -//----------------------------------------------------------------------------- -// Purpose: deallocator -//----------------------------------------------------------------------------- -void KeyValues::operator delete( void *pMem ) -{ - KeyValuesSystem()->FreeKeyValuesMemory(pMem); -} - -void KeyValues::operator delete( void *pMem, int nBlockUse, const char *pFileName, int nLine ) -{ - KeyValuesSystem()->FreeKeyValuesMemory(pMem); -} - -void KeyValues::UnpackIntoStructure( KeyValuesUnpackStructure const *pUnpackTable, void *pDest ) -{ - uint8 *dest=(uint8 *) pDest; - while( pUnpackTable->m_pKeyName ) - { - uint8 *dest_field=dest+pUnpackTable->m_nFieldOffset; - KeyValues *find_it=FindKey( pUnpackTable->m_pKeyName ); - switch( pUnpackTable->m_eDataType ) - { - case UNPACK_TYPE_FLOAT: - { - float default_value=(pUnpackTable->m_pKeyDefault)?atof(pUnpackTable->m_pKeyDefault):0.0; - *( ( float *) dest_field)=GetFloat( pUnpackTable->m_pKeyName, default_value ); - break; - } - break; - - case UNPACK_TYPE_VECTOR: - { - Vector *dest_v=(Vector *) dest_field; - char const *src_string= - GetString( pUnpackTable->m_pKeyName, pUnpackTable->m_pKeyDefault ); - if ( (!src_string) || - ( sscanf(src_string,"%f %f %f", - &(dest_v->x), &(dest_v->y), &(dest_v->z)) != 3)) - dest_v->Init( 0, 0, 0 ); - } - break; - - case UNPACK_TYPE_FOUR_FLOATS: - { - float *dest_f=(float *) dest_field; - char const *src_string= - GetString( pUnpackTable->m_pKeyName, pUnpackTable->m_pKeyDefault ); - if ( (!src_string) || - ( sscanf(src_string,"%f %f %f %f", - dest_f,dest_f+1,dest_f+2,dest_f+3)) != 4) - memset( dest_f, 0, 4*sizeof(float) ); - } - break; - - case UNPACK_TYPE_TWO_FLOATS: - { - float *dest_f=(float *) dest_field; - char const *src_string= - GetString( pUnpackTable->m_pKeyName, pUnpackTable->m_pKeyDefault ); - if ( (!src_string) || - ( sscanf(src_string,"%f %f", - dest_f,dest_f+1)) != 2) - memset( dest_f, 0, 2*sizeof(float) ); - } - break; - - case UNPACK_TYPE_STRING: - { - char *dest_s=(char *) dest_field; - strncpy( dest_s, GetString( pUnpackTable->m_pKeyName, - pUnpackTable->m_pKeyDefault ), - pUnpackTable->m_nFieldSize ); - - } - break; - - case UNPACK_TYPE_INT: - { - int *dest_i=(int *) dest_field; - int default_int=0; - if ( pUnpackTable->m_pKeyDefault) - default_int = atoi( pUnpackTable->m_pKeyDefault ); - *(dest_i)=GetInt( pUnpackTable->m_pKeyName, default_int ); - } - break; - - case UNPACK_TYPE_VECTOR_COLOR: - { - Vector *dest_v=(Vector *) dest_field; - if (find_it) - { - Color c=GetColor( pUnpackTable->m_pKeyName ); - dest_v->x = c.r(); - dest_v->y = c.g(); - dest_v->z = c.b(); - } - else - { - if ( pUnpackTable->m_pKeyDefault ) - sscanf(pUnpackTable->m_pKeyDefault,"%f %f %f", - &(dest_v->x), &(dest_v->y), &(dest_v->z)); - else - dest_v->Init( 0, 0, 0 ); - } - *(dest_v) *= (1.0/255); - } - } - pUnpackTable++; - } -} - -//----------------------------------------------------------------------------- -// Helper function for processing a keyvalue tree for console resolution support. -// Alters key/values for easier console video resolution support. -// If running SD (640x480), the presence of "???_lodef" creates or slams "???". -// If running HD (1280x720), the presence of "???_hidef" creates or slams "???". -//----------------------------------------------------------------------------- -bool KeyValues::ProcessResolutionKeys( const char *pResString ) -{ - if ( !pResString ) - { - // not for pc, console only - return false; - } - - KeyValues *pSubKey = GetFirstSubKey(); - if ( !pSubKey ) - { - // not a block - return false; - } - - for ( ; pSubKey != NULL; pSubKey = pSubKey->GetNextKey() ) - { - // recursively descend each sub block - pSubKey->ProcessResolutionKeys( pResString ); - - // check to see if our substring is present - if ( Q_stristr( pSubKey->GetName(), pResString ) != NULL ) - { - char normalKeyName[128]; - V_strncpy( normalKeyName, pSubKey->GetName(), sizeof( normalKeyName ) ); - - // substring must match exactly, otherwise keys like "_lodef" and "_lodef_wide" would clash. - char *pString = Q_stristr( normalKeyName, pResString ); - if ( pString && !Q_stricmp( pString, pResString ) ) - { - *pString = '\0'; - - // find and delete the original key (if any) - KeyValues *pKey = FindKey( normalKeyName ); - if ( pKey ) - { - // remove the key - RemoveSubKey( pKey ); - } - - // rename the marked key - pSubKey->SetName( normalKeyName ); - } - } - } - - return true; -} diff --git a/Resources/NetHook/tier1/KeyValues.h b/Resources/NetHook/tier1/KeyValues.h deleted file mode 100644 index 52856d64..00000000 --- a/Resources/NetHook/tier1/KeyValues.h +++ /dev/null @@ -1,357 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef KEYVALUES_H -#define KEYVALUES_H - -#ifdef _WIN32 -#pragma once -#endif - -// #include - -#ifndef NULL -#ifdef __cplusplus -#define NULL 0 -#else -#define NULL ((void *)0) -#endif -#endif - -#include "utlvector.h" -#include "Color.h" - -class IBaseFileSystem; -class CUtlBuffer; -class Color; -typedef void * FileHandle_t; - -//----------------------------------------------------------------------------- -// Purpose: Simple recursive data access class -// Used in vgui for message parameters and resource files -// Destructor deletes all child KeyValues nodes -// Data is stored in key (string names) - (string/int/float)value pairs called nodes. -// -// About KeyValues Text File Format: - -// It has 3 control characters '{', '}' and '"'. Names and values may be quoted or -// not. The quote '"' charater must not be used within name or values, only for -// quoting whole tokens. You may use escape sequences wile parsing and add within a -// quoted token a \" to add quotes within your name or token. When using Escape -// Sequence the parser must now that by setting KeyValues::UsesEscapeSequences( true ), -// which it's off by default. Non-quoted tokens ends with a whitespace, '{', '}' and '"'. -// So you may use '{' and '}' within quoted tokens, but not for non-quoted tokens. -// An open bracket '{' after a key name indicates a list of subkeys which is finished -// with a closing bracket '}'. Subkeys use the same definitions recursively. -// Whitespaces are space, return, newline and tabulator. Allowed Escape sequences -// are \n, \t, \\, \n and \". The number character '#' is used for macro purposes -// (eg #include), don't use it as first charater in key names. -//----------------------------------------------------------------------------- -class KeyValues -{ -public: - KeyValues( const char *setName ); - - // - // AutoDelete class to automatically free the keyvalues. - // Simply construct it with the keyvalues you allocated and it will free them when falls out of scope. - // When you decide that keyvalues shouldn't be deleted call Assign(NULL) on it. - // If you constructed AutoDelete(NULL) you can later assign the keyvalues to be deleted with Assign(pKeyValues). - // You can also pass temporary KeyValues object as an argument to a function by wrapping it into KeyValues::AutoDelete - // instance: call_my_function( KeyValues::AutoDelete( new KeyValues( "test" ) ) ) - // - class AutoDelete - { - public: - explicit inline AutoDelete( KeyValues *pKeyValues ) : m_pKeyValues( pKeyValues ) {} - inline ~AutoDelete( void ) { if( m_pKeyValues ) m_pKeyValues->deleteThis(); } - inline void Assign( KeyValues *pKeyValues ) { m_pKeyValues = pKeyValues; } - private: - AutoDelete( AutoDelete const &x ); // forbid - AutoDelete & operator= ( AutoDelete const &x ); // forbid - KeyValues *m_pKeyValues; - }; - - // Quick setup constructors - KeyValues( const char *setName, const char *firstKey, const char *firstValue ); - KeyValues( const char *setName, const char *firstKey, const wchar_t *firstValue ); - KeyValues( const char *setName, const char *firstKey, int firstValue ); - KeyValues( const char *setName, const char *firstKey, const char *firstValue, const char *secondKey, const char *secondValue ); - KeyValues( const char *setName, const char *firstKey, int firstValue, const char *secondKey, int secondValue ); - - // Section name - const char *GetName() const; - void SetName( const char *setName); - - // gets the name as a unique int - int GetNameSymbol() const; - - // File access. Set UsesEscapeSequences true, if resource file/buffer uses Escape Sequences (eg \n, \t) - void UsesEscapeSequences(bool state); // default false - bool LoadFromFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID = NULL ); - bool SaveToFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID = NULL); - - // Read from a buffer... Note that the buffer must be null terminated - bool LoadFromBuffer( char const *resourceName, const char *pBuffer, IBaseFileSystem* pFileSystem = NULL, const char *pPathID = NULL ); - - // Read from a utlbuffer... - bool LoadFromBuffer( char const *resourceName, CUtlBuffer &buf, IBaseFileSystem* pFileSystem = NULL, const char *pPathID = NULL ); - - // Find a keyValue, create it if it is not found. - // Set bCreate to true to create the key if it doesn't already exist (which ensures a valid pointer will be returned) - KeyValues *FindKey(const char *keyName, bool bCreate = false); - KeyValues *FindKey(int keySymbol) const; - KeyValues *CreateNewKey(); // creates a new key, with an autogenerated name. name is guaranteed to be an integer, of value 1 higher than the highest other integer key name - void AddSubKey( KeyValues *pSubkey ); // Adds a subkey. Make sure the subkey isn't a child of some other keyvalues - void RemoveSubKey(KeyValues *subKey); // removes a subkey from the list, DOES NOT DELETE IT - - // Key iteration. - // - // NOTE: GetFirstSubKey/GetNextKey will iterate keys AND values. Use the functions - // below if you want to iterate over just the keys or just the values. - // - KeyValues *GetFirstSubKey(); // returns the first subkey in the list - KeyValues *GetNextKey(); // returns the next subkey - void SetNextKey( KeyValues * pDat); - - // - // These functions can be used to treat it like a true key/values tree instead of - // confusing values with keys. - // - // So if you wanted to iterate all subkeys, then all values, it would look like this: - // for ( KeyValues *pKey = pRoot->GetFirstTrueSubKey(); pKey; pKey = pKey->GetNextTrueSubKey() ) - // { - // Msg( "Key name: %s\n", pKey->GetName() ); - // } - // for ( KeyValues *pValue = pRoot->GetFirstValue(); pKey; pKey = pKey->GetNextValue() ) - // { - // Msg( "Int value: %d\n", pValue->GetInt() ); // Assuming pValue->GetDataType() == TYPE_INT... - // } - KeyValues* GetFirstTrueSubKey(); - KeyValues* GetNextTrueSubKey(); - - KeyValues* GetFirstValue(); // When you get a value back, you can use GetX and pass in NULL to get the value. - KeyValues* GetNextValue(); - - - // Data access - int GetInt( const char *keyName = NULL, int defaultValue = 0 ); - uint64 GetUint64( const char *keyName = NULL, uint64 defaultValue = 0 ); - float GetFloat( const char *keyName = NULL, float defaultValue = 0.0f ); - const char *GetString( const char *keyName = NULL, const char *defaultValue = "" ); - const wchar_t *GetWString( const char *keyName = NULL, const wchar_t *defaultValue = L"" ); - void *GetPtr( const char *keyName = NULL, void *defaultValue = (void*)0 ); - Color GetColor( const char *keyName = NULL /* default value is all black */); - bool IsEmpty(const char *keyName = NULL); - - // Data access - int GetInt( int keySymbol, int defaultValue = 0 ); - float GetFloat( int keySymbol, float defaultValue = 0.0f ); - const char *GetString( int keySymbol, const char *defaultValue = "" ); - const wchar_t *GetWString( int keySymbol, const wchar_t *defaultValue = L"" ); - void *GetPtr( int keySymbol, void *defaultValue = (void*)0 ); - Color GetColor( int keySymbol /* default value is all black */); - bool IsEmpty( int keySymbol ); - - // Key writing - void SetWString( const char *keyName, const wchar_t *value ); - void SetString( const char *keyName, const char *value ); - void SetInt( const char *keyName, int value ); - void SetUint64( const char *keyName, uint64 value ); - void SetFloat( const char *keyName, float value ); - void SetPtr( const char *keyName, void *value ); - void SetColor( const char *keyName, Color value); - - // Memory allocation (optimized) - void *operator new( unsigned int iAllocSize ); - void *operator new( unsigned int iAllocSize, int nBlockUse, const char *pFileName, int nLine ); - void operator delete( void *pMem ); - void operator delete( void *pMem, int nBlockUse, const char *pFileName, int nLine ); - - KeyValues& operator=( KeyValues& src ); - - // Adds a chain... if we don't find stuff in this keyvalue, we'll look - // in the one we're chained to. - void ChainKeyValue( KeyValues* pChain ); - - void RecursiveSaveToFile( CUtlBuffer& buf, int indentLevel ); - - bool WriteAsBinary( CUtlBuffer &buffer ); - bool ReadAsBinary( CUtlBuffer &buffer ); - - // Allocate & create a new copy of the keys - KeyValues *MakeCopy( void ) const; - - // Make a new copy of all subkeys, add them all to the passed-in keyvalues - void CopySubkeys( KeyValues *pParent ) const; - - // Clear out all subkeys, and the current value - void Clear( void ); - - // Data type - enum types_t - { - TYPE_NONE = 0, - TYPE_STRING, - TYPE_INT, - TYPE_FLOAT, - TYPE_PTR, - TYPE_WSTRING, - TYPE_COLOR, - TYPE_UINT64, - TYPE_NUMTYPES, - }; - types_t GetDataType(const char *keyName = NULL); - - // Virtual deletion function - ensures that KeyValues object is deleted from correct heap - void deleteThis(); - - void SetStringValue( char const *strValue ); - - // unpack a key values list into a structure - void UnpackIntoStructure( struct KeyValuesUnpackStructure const *pUnpackTable, void *pDest ); - - // Process conditional keys for widescreen support. - bool ProcessResolutionKeys( const char *pResString ); - -private: - KeyValues( KeyValues& ); // prevent copy constructor being used - - // prevent delete being called except through deleteThis() - ~KeyValues(); - - KeyValues* CreateKey( const char *keyName ); - - void RecursiveCopyKeyValues( KeyValues& src ); - void RemoveEverything(); -// void RecursiveSaveToFile( IBaseFileSystem *filesystem, CUtlBuffer &buffer, int indentLevel ); -// void WriteConvertedString( CUtlBuffer &buffer, const char *pszString ); - - // NOTE: If both filesystem and pBuf are non-null, it'll save to both of them. - // If filesystem is null, it'll ignore f. - void RecursiveSaveToFile( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel ); - void WriteConvertedString( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const char *pszString ); - - void RecursiveLoadFromBuffer( char const *resourceName, CUtlBuffer &buf ); - - // For handling #include "filename" - void AppendIncludedKeys( CUtlVector< KeyValues * >& includedKeys ); - void ParseIncludedKeys( char const *resourceName, const char *filetoinclude, - IBaseFileSystem* pFileSystem, const char *pPathID, CUtlVector< KeyValues * >& includedKeys ); - - // For handling #base "filename" - void MergeBaseKeys( CUtlVector< KeyValues * >& baseKeys ); - void RecursiveMergeKeyValues( KeyValues *baseKV ); - - // NOTE: If both filesystem and pBuf are non-null, it'll save to both of them. - // If filesystem is null, it'll ignore f. - void InternalWrite( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const void *pData, int len ); - - void Init(); - const char * ReadToken( CUtlBuffer &buf, bool &wasQuoted, bool &wasConditional ); - void WriteIndents( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel ); - - void FreeAllocatedValue(); - void AllocateValueBlock(int size); - - int m_iKeyName; // keyname is a symbol defined in KeyValuesSystem - - // These are needed out of the union because the API returns string pointers - char *m_sValue; - wchar_t *m_wsValue; - - // we don't delete these - union - { - int m_iValue; - float m_flValue; - void *m_pValue; - unsigned char m_Color[4]; - }; - - char m_iDataType; - char m_bHasEscapeSequences; // true, if while parsing this KeyValue, Escape Sequences are used (default false) - char unused[2]; - - KeyValues *m_pPeer; // pointer to next key in list - KeyValues *m_pSub; // pointer to Start of a new sub key list - KeyValues *m_pChain;// Search here if it's not in our list -}; - -enum KeyValuesUnpackDestinationTypes_t -{ - UNPACK_TYPE_FLOAT, // dest is a float - UNPACK_TYPE_VECTOR, // dest is a Vector - UNPACK_TYPE_VECTOR_COLOR, // dest is a vector, src is a color - UNPACK_TYPE_STRING, // dest is a char *. unpacker will allocate. - UNPACK_TYPE_INT, // dest is an int - UNPACK_TYPE_FOUR_FLOATS, // dest is an array of 4 floats. source is a string like "1 2 3 4" - UNPACK_TYPE_TWO_FLOATS, // dest is an array of 2 floats. source is a string like "1 2" -}; - -#define UNPACK_FIXED( kname, kdefault, dtype, ofs ) { kname, kdefault, dtype, ofs, 0 } -#define UNPACK_VARIABLE( kname, kdefault, dtype, ofs, sz ) { kname, kdefault, dtype, ofs, sz } -#define UNPACK_END_MARKER { NULL, NULL, UNPACK_TYPE_FLOAT, 0 } - -struct KeyValuesUnpackStructure -{ - char const *m_pKeyName; // null to terminate tbl - char const *m_pKeyDefault; // null ok - KeyValuesUnpackDestinationTypes_t m_eDataType; // UNPACK_TYPE_INT, .. - size_t m_nFieldOffset; // use offsetof to set - size_t m_nFieldSize; // for strings or other variable length -}; - -//----------------------------------------------------------------------------- -// inline methods -//----------------------------------------------------------------------------- -inline int KeyValues::GetInt( int keySymbol, int defaultValue ) -{ - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->GetInt( (const char *)NULL, defaultValue ) : defaultValue; -} - -inline float KeyValues::GetFloat( int keySymbol, float defaultValue ) -{ - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->GetFloat( (const char *)NULL, defaultValue ) : defaultValue; -} - -inline const char *KeyValues::GetString( int keySymbol, const char *defaultValue ) -{ - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->GetString( (const char *)NULL, defaultValue ) : defaultValue; -} - -inline const wchar_t *KeyValues::GetWString( int keySymbol, const wchar_t *defaultValue ) -{ - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->GetWString( (const char *)NULL, defaultValue ) : defaultValue; -} - -inline void *KeyValues::GetPtr( int keySymbol, void *defaultValue ) -{ - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->GetPtr( (const char *)NULL, defaultValue ) : defaultValue; -} - -inline Color KeyValues::GetColor( int keySymbol ) -{ - Color defaultValue( 0, 0, 0, 0 ); - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->GetColor( ) : defaultValue; -} - -inline bool KeyValues::IsEmpty( int keySymbol ) -{ - KeyValues *dat = FindKey( keySymbol ); - return dat ? dat->IsEmpty( ) : true; -} - -bool EvaluateConditional( const char *str ); - -#endif // KEYVALUES_H diff --git a/Resources/NetHook/tier1/NetAdr.cpp b/Resources/NetHook/tier1/NetAdr.cpp deleted file mode 100644 index 0d636f4f..00000000 --- a/Resources/NetHook/tier1/NetAdr.cpp +++ /dev/null @@ -1,331 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// NetAdr.cpp: implementation of the CNetAdr class. -// -//===========================================================================// -#if defined( _WIN32 ) && !defined( _X360 ) -#include -#endif - -#include "tier0/dbg.h" -#include "netadr.h" -#include "tier1/strtools.h" - -#if defined( _WIN32 ) && !defined( _X360 ) -#define WIN32_LEAN_AND_MEAN -#include -typedef int socklen_t; -#elif !defined( _X360 ) -#include // ntohs() -#include // gethostbyname() -#include // getsockname() -#endif - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -bool netadr_t::CompareAdr (const netadr_t &a, bool onlyBase) const -{ - if ( a.type != type ) - return false; - - if ( type == NA_LOOPBACK ) - return true; - - if ( type == NA_BROADCAST ) - return true; - - if ( type == NA_IP ) - { - if ( !onlyBase && (port != a.port) ) - return false; - - if ( a.ip[0] == ip[0] && a.ip[1] == ip[1] && a.ip[2] == ip[2] && a.ip[3] == ip[3] ) - return true; - } - - return false; -} - -bool netadr_t::CompareClassBAdr (const netadr_t &a) const -{ - if ( a.type != type ) - return false; - - if ( type == NA_LOOPBACK ) - return true; - - if ( type == NA_IP ) - { - if (a.ip[0] == ip[0] && a.ip[1] == ip[1] ) - return true; - } - - return false; -} - -bool netadr_t::CompareClassCAdr (const netadr_t &a) const -{ - if ( a.type != type ) - return false; - - if ( type == NA_LOOPBACK ) - return true; - - if ( type == NA_IP ) - { - if (a.ip[0] == ip[0] && a.ip[1] == ip[1] && a.ip[2] == ip[2] ) - return true; - } - - return false; -} -// reserved addresses are not routeable, so they can all be used in a LAN game -bool netadr_t::IsReservedAdr () const -{ - if ( type == NA_LOOPBACK ) - return true; - - if ( type == NA_IP ) - { - if ( (ip[0] == 10) || // 10.x.x.x is reserved - (ip[0] == 127) || // 127.x.x.x - (ip[0] == 172 && ip[1] >= 16 && ip[1] <= 31) || // 172.16.x.x - 172.31.x.x - (ip[0] == 192 && ip[1] >= 168) ) // 192.168.x.x - return true; - } - return false; -} - -const char * netadr_t::ToString(bool baseOnly) const -{ - static char s[64]; - - Q_strncpy (s, "unknown", sizeof( s ) ); - - if (type == NA_LOOPBACK) - { - Q_strncpy (s, "loopback", sizeof( s ) ); - } - else if (type == NA_BROADCAST) - { - Q_strncpy (s, "broadcast", sizeof( s ) ); - } - else if (type == NA_IP) - { - if ( baseOnly) - { - Q_snprintf (s, sizeof( s ), "%i.%i.%i.%i", ip[0], ip[1], ip[2], ip[3]); - } - else - { - Q_snprintf (s, sizeof( s ), "%i.%i.%i.%i:%i", ip[0], ip[1], ip[2], ip[3], ntohs(port)); - } - } - - return s; -} - -bool netadr_t::IsLocalhost() const -{ - // are we 127.0.0.1 ? - return (ip[0] == 127) && (ip[1] == 0) && (ip[2] == 0) && (ip[3] == 1); -} - -bool netadr_t::IsLoopback() const -{ - // are we useding engine loopback buffers - return type == NA_LOOPBACK; -} - -void netadr_t::Clear() -{ - ip[0] = ip[1] = ip[2] = ip[3] = 0; - port = 0; - type = NA_NULL; -} - -void netadr_t::SetIP(uint8 b1, uint8 b2, uint8 b3, uint8 b4) -{ - ip[0] = b1; - ip[1] = b2; - ip[2] = b3; - ip[3] = b4; -} - -void netadr_t::SetIP(uint unIP) -{ - *((uint*)ip) = BigLong( unIP ); -} - -void netadr_t::SetType(netadrtype_t newtype) -{ - type = newtype; -} - -netadrtype_t netadr_t::GetType() const -{ - return type; -} - -unsigned short netadr_t::GetPort() const -{ - return BigShort( port ); -} - -unsigned int netadr_t::GetIP() const -{ - return *(unsigned int *)&ip;; -} - -unsigned long netadr_t::addr_ntohl() const -{ - return ntohl( GetIP() ); -} - -unsigned long netadr_t::addr_htonl() const -{ - return htonl( GetIP() ); -} - - -void netadr_t::ToSockadr (struct sockaddr * s) const -{ - Q_memset ( s, 0, sizeof(struct sockaddr)); - - if (type == NA_BROADCAST) - { - ((struct sockaddr_in*)s)->sin_family = AF_INET; - ((struct sockaddr_in*)s)->sin_port = port; - ((struct sockaddr_in*)s)->sin_addr.s_addr = INADDR_BROADCAST; - } - else if (type == NA_IP) - { - ((struct sockaddr_in*)s)->sin_family = AF_INET; - ((struct sockaddr_in*)s)->sin_addr.s_addr = *(int *)&ip; - ((struct sockaddr_in*)s)->sin_port = port; - } - else if (type == NA_LOOPBACK ) - { - ((struct sockaddr_in*)s)->sin_family = AF_INET; - ((struct sockaddr_in*)s)->sin_port = port; - ((struct sockaddr_in*)s)->sin_addr.s_addr = INADDR_LOOPBACK ; - } -} - -bool netadr_t::SetFromSockadr(const struct sockaddr * s) -{ - if (s->sa_family == AF_INET) - { - type = NA_IP; - *(int *)&ip = ((struct sockaddr_in *)s)->sin_addr.s_addr; - port = ((struct sockaddr_in *)s)->sin_port; - return true; - } - else - { - Clear(); - return false; - } -} - -bool netadr_t::IsValid() const -{ - return ( (port !=0 ) && (type != NA_NULL) && - ( ip[0] != 0 || ip[1] != 0 || ip[2] != 0 || ip[3] != 0 ) ); -} - -#ifdef _WIN32 -#undef SetPort // get around stupid WINSPOOL.H macro -#endif - -void netadr_t::SetPort(unsigned short newport) -{ - port = BigShort( newport ); -} - -void netadr_t::SetFromString( const char *pch, bool bUseDNS ) -{ - Clear(); - type = NA_IP; - - Assert( pch ); // invalid to call this with NULL pointer; fix your code bug! - if ( !pch ) // but let's not crash - return; - - - if ( pch[0] >= '0' && pch[0] <= '9' && strchr( pch, '.' ) ) - { - int n1, n2, n3, n4, n5; - int nRes = sscanf( pch, "%d.%d.%d.%d:%d", &n1, &n2, &n3, &n4, &n5 ); - if ( nRes >= 4 ) - { - SetIP( n1, n2, n3, n4 ); - } - - if ( nRes == 5 ) - { - SetPort( ( uint16 ) n5 ); - } - } - else if ( bUseDNS ) - { -// X360TBD: -#if !defined( _X360 ) - char szHostName[ 256 ]; - Q_strncpy( szHostName, pch, sizeof(szHostName) ); - char *pchColon = strchr( szHostName, ':' ); - if ( pchColon ) - { - *pchColon = 0; - } - - // DNS it - struct hostent *h = gethostbyname( szHostName ); - if ( !h ) - return; - - SetIP( ntohl( *(int *)h->h_addr_list[0] ) ); - - if ( pchColon ) - { - SetPort( atoi( ++pchColon ) ); - } -#else - Assert( 0 ); -#endif - } -} - -bool netadr_t::operator<(const netadr_t &netadr) const -{ - if ( *((uint *)netadr.ip) < *((uint *)ip) ) - return true; - else if ( *((uint *)netadr.ip) > *((uint *)ip) ) - return false; - return ( netadr.port < port ); -} - - -void netadr_t::SetFromSocket( int hSocket ) -{ -#if !defined(_X360) - Clear(); - type = NA_IP; - - struct sockaddr address; - int namelen = sizeof(address); - if ( getsockname( hSocket, (struct sockaddr *)&address, (int *)&namelen) == 0 ) - { - SetFromSockadr( &address ); - } -#else - Assert(0); -#endif -} diff --git a/Resources/NetHook/tier1/UtlSortVector.h b/Resources/NetHook/tier1/UtlSortVector.h deleted file mode 100644 index e57ff78b..00000000 --- a/Resources/NetHook/tier1/UtlSortVector.h +++ /dev/null @@ -1,311 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// $Header: $ -// $NoKeywords: $ -// -// A growable array class that keeps all elements in order using binary search -//===========================================================================// - -#ifndef UTLSORTVECTOR_H -#define UTLSORTVECTOR_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "utlvector.h" - - -//----------------------------------------------------------------------------- -// class CUtlSortVector: -// description: -// This in an sorted order-preserving vector. Items may be inserted or removed -// at any point in the vector. When an item is inserted, all elements are -// moved down by one element using memmove. When an item is removed, all -// elements are shifted back down. Items are searched for in the vector -// using a binary search technique. Clients must pass in a Less() function -// into the constructor of the vector to determine the sort order. -//----------------------------------------------------------------------------- - -#ifndef _WIN32 -// gcc has no qsort_s, so i need to use a static var to hold the sort context. this makes cutlsortvector _not_ thread sfae under linux -extern void *g_pUtlSortVectorQSortContext; -#endif - -template -class CUtlSortVector : public CUtlVector -{ -public: - - // constructor - CUtlSortVector( int nGrowSize = 0, int initSize = 0 ); - CUtlSortVector( T* pMemory, int numElements ); - - // inserts (copy constructs) an element in sorted order into the list - int Insert( const T& src ); - - // Finds an element within the list using a binary search - int Find( const T& search ) const; - int FindLessOrEqual( const T& search ) const; - int FindLess( const T& search ) const; - - // Removes a particular element - void Remove( const T& search ); - void Remove( int i ); - - // Allows methods to set a context to be used with the less function.. - void SetLessContext( void *pCtx ); - - // Note that you can only use this index until sorting is redone!!! - int InsertNoSort( const T& src ); - void RedoSort( bool bForceSort = false ); - -protected: - // No copy constructor - CUtlSortVector( const CUtlSortVector & ); - - // never call these; illegal for this class - int AddToHead(); - int AddToTail(); - int InsertBefore( int elem ); - int InsertAfter( int elem ); - int AddToHead( const T& src ); - int AddToTail( const T& src ); - int InsertBefore( int elem, const T& src ); - int InsertAfter( int elem, const T& src ); - int AddMultipleToHead( int num ); - int AddMultipleToTail( int num, const T *pToCopy=NULL ); - int InsertMultipleBefore( int elem, int num, const T *pToCopy=NULL ); - int InsertMultipleAfter( int elem, int num ); - int AddVectorToTail( CUtlVector const &src ); - - struct QSortContext_t - { - void *m_pLessContext; - LessFunc *m_pLessFunc; - }; - -#ifdef _WIN32 - static int CompareHelper( void *context, const T *lhs, const T *rhs ) - { - QSortContext_t *ctx = reinterpret_cast< QSortContext_t * >( context ); - if ( ctx->m_pLessFunc->Less( *lhs, *rhs, ctx->m_pLessContext ) ) - return -1; - if ( ctx->m_pLessFunc->Less( *rhs, *lhs, ctx->m_pLessContext ) ) - return 1; - return 0; - } -#else - static int CompareHelper( const T *lhs, const T *rhs ) - { - QSortContext_t *ctx = reinterpret_cast< QSortContext_t * >( g_pUtlSortVectorQSortContext ); - if ( ctx->m_pLessFunc->Less( *lhs, *rhs, ctx->m_pLessContext ) ) - return -1; - if ( ctx->m_pLessFunc->Less( *rhs, *lhs, ctx->m_pLessContext ) ) - return 1; - return 0; - } -#endif - - void *m_pLessContext; - bool m_bNeedsSort; - -private: - void QuickSort( LessFunc& less, int X, int I ); -}; - - -//----------------------------------------------------------------------------- -// constructor -//----------------------------------------------------------------------------- -template -CUtlSortVector::CUtlSortVector( int nGrowSize, int initSize ) : - m_pLessContext(NULL), CUtlVector( nGrowSize, initSize ), m_bNeedsSort( false ) -{ -} - -template -CUtlSortVector::CUtlSortVector( T* pMemory, int numElements ) : - m_pLessContext(NULL), CUtlVector( pMemory, numElements ), m_bNeedsSort( false ) -{ -} - -//----------------------------------------------------------------------------- -// Allows methods to set a context to be used with the less function.. -//----------------------------------------------------------------------------- -template -void CUtlSortVector::SetLessContext( void *pCtx ) -{ - m_pLessContext = pCtx; -} - -//----------------------------------------------------------------------------- -// grows the vector -//----------------------------------------------------------------------------- -template -int CUtlSortVector::Insert( const T& src ) -{ - AssertFatal( !m_bNeedsSort ); - - int pos = FindLessOrEqual( src ) + 1; - GrowVector(); - ShiftElementsRight(pos); - CopyConstruct( &Element(pos), src ); - return pos; -} - -template -int CUtlSortVector::InsertNoSort( const T& src ) -{ - m_bNeedsSort = true; - int lastElement = CUtlVector::m_Size; - // Just stick the new element at the end of the vector, but don't do a sort - GrowVector(); - ShiftElementsRight(lastElement); - CopyConstruct( &Element(lastElement), src ); - return lastElement; -} - -template -void CUtlSortVector::QuickSort( LessFunc& less, int nLower, int nUpper ) -{ -#ifdef _WIN32 - typedef int (__cdecl *QSortCompareFunc_t)(void *context, const void *, const void *); - if ( Count() > 1 ) - { - QSortContext_t ctx; - ctx.m_pLessContext = m_pLessContext; - ctx.m_pLessFunc = &less; - - qsort_s( Base(), Count(), sizeof(T), (QSortCompareFunc_t)&CUtlSortVector::CompareHelper, &ctx ); - } -#else - typedef int (__cdecl *QSortCompareFunc_t)( const void *, const void *); - if ( Count() > 1 ) - { - QSortContext_t ctx; - ctx.m_pLessContext = m_pLessContext; - ctx.m_pLessFunc = &less; - g_pUtlSortVectorQSortContext = &ctx; - - qsort( Base(), Count(), sizeof(T), (QSortCompareFunc_t)&CUtlSortVector::CompareHelper ); - } -#endif -} - -template -void CUtlSortVector::RedoSort( bool bForceSort /*= false */ ) -{ - if ( !m_bNeedsSort && !bForceSort ) - return; - - m_bNeedsSort = false; - LessFunc less; - QuickSort( less, 0, Count() - 1 ); -} - -//----------------------------------------------------------------------------- -// finds a particular element -//----------------------------------------------------------------------------- -template -int CUtlSortVector::Find( const T& src ) const -{ - AssertFatal( !m_bNeedsSort ); - - LessFunc less; - - int start = 0, end = Count() - 1; - while (start <= end) - { - int mid = (start + end) >> 1; - if ( less.Less( Element(mid), src, m_pLessContext ) ) - { - start = mid + 1; - } - else if ( less.Less( src, Element(mid), m_pLessContext ) ) - { - end = mid - 1; - } - else - { - return mid; - } - } - return -1; -} - - -//----------------------------------------------------------------------------- -// finds a particular element -//----------------------------------------------------------------------------- -template -int CUtlSortVector::FindLessOrEqual( const T& src ) const -{ - AssertFatal( !m_bNeedsSort ); - - LessFunc less; - int start = 0, end = Count() - 1; - while (start <= end) - { - int mid = (start + end) >> 1; - if ( less.Less( Element(mid), src, m_pLessContext ) ) - { - start = mid + 1; - } - else if ( less.Less( src, Element(mid), m_pLessContext ) ) - { - end = mid - 1; - } - else - { - return mid; - } - } - return end; -} - -template -int CUtlSortVector::FindLess( const T& src ) const -{ - AssertFatal( !m_bNeedsSort ); - - LessFunc less; - int start = 0, end = Count() - 1; - while (start <= end) - { - int mid = (start + end) >> 1; - if ( less.Less( Element(mid), src, m_pLessContext ) ) - { - start = mid + 1; - } - else - { - end = mid - 1; - } - } - return end; -} - - -//----------------------------------------------------------------------------- -// Removes a particular element -//----------------------------------------------------------------------------- -template -void CUtlSortVector::Remove( const T& search ) -{ - AssertFatal( !m_bNeedsSort ); - - int pos = Find(search); - if (pos != -1) - { - CUtlVector::Remove(pos); - } -} - -template -void CUtlSortVector::Remove( int i ) -{ - CUtlVector::Remove( i ); -} - -#endif // UTLSORTVECTOR_H diff --git a/Resources/NetHook/tier1/UtlStringMap.h b/Resources/NetHook/tier1/UtlStringMap.h deleted file mode 100644 index e1e11ba1..00000000 --- a/Resources/NetHook/tier1/UtlStringMap.h +++ /dev/null @@ -1,99 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -#ifndef UTLSTRINGMAP_H -#define UTLSTRINGMAP_H -#ifdef _WIN32 -#pragma once -#endif - -#include "utlsymbol.h" - -template -class CUtlStringMap -{ -public: - CUtlStringMap( bool caseInsensitive = true ) : m_SymbolTable( 0, 32, caseInsensitive ) - { - } - - // Get data by the string itself: - T& operator[]( const char *pString ) - { - CUtlSymbol symbol = m_SymbolTable.AddString( pString ); - int index = ( int )( UtlSymId_t )symbol; - if( m_Vector.Count() <= index ) - { - m_Vector.EnsureCount( index + 1 ); - } - return m_Vector[index]; - } - - // Get data by the string's symbol table ID - only used to retrieve a pre-existing symbol, not create a new one! - T& operator[]( UtlSymId_t n ) - { - Assert( n >=0 && n <= m_Vector.Count() ); - return m_Vector[n]; - } - - const T& operator[]( UtlSymId_t n ) const - { - Assert( n >=0 && n <= m_Vector.Count() ); - return m_Vector[n]; - } - - bool Defined( const char *pString ) const - { - return m_SymbolTable.Find( pString ) != UTL_INVAL_SYMBOL; - } - - UtlSymId_t Find( const char *pString ) const - { - return m_SymbolTable.Find( pString ); - } - - static UtlSymId_t InvalidIndex() - { - return UTL_INVAL_SYMBOL; - } - - int GetNumStrings( void ) const - { - return m_SymbolTable.GetNumStrings(); - } - - const char *String( int n ) const - { - return m_SymbolTable.String( n ); - } - - // Clear all of the data from the map - void Clear() - { - m_Vector.RemoveAll(); - m_SymbolTable.RemoveAll(); - } - - void Purge() - { - m_Vector.Purge(); - m_SymbolTable.RemoveAll(); - } - - void PurgeAndDeleteElements() - { - m_Vector.PurgeAndDeleteElements(); - m_SymbolTable.RemoveAll(); - } - - - -private: - CUtlVector m_Vector; - CUtlSymbolTable m_SymbolTable; -}; - -#endif // UTLSTRINGMAP_H diff --git a/Resources/NetHook/tier1/bitbuf.cpp b/Resources/NetHook/tier1/bitbuf.cpp deleted file mode 100644 index 933b02d1..00000000 --- a/Resources/NetHook/tier1/bitbuf.cpp +++ /dev/null @@ -1,1269 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#include "bitbuf.h" -#include "coordsize.h" -#include "mathlib/vector.h" -#include "mathlib/mathlib.h" -#include "tier1/strtools.h" -#include "bitvec.h" - -// FIXME: Can't use this until we get multithreaded allocations in tier0 working for tools -// This is used by VVIS and fails to link -// NOTE: This must be the last file included!!! -//#include "tier0/memdbgon.h" - -#ifdef _X360 -// mandatory ... wary of above comment and isolating, tier0 is built as MT though -#include "tier0/memdbgon.h" -#endif - -#if _WIN32 -#define FAST_BIT_SCAN 1 -#if _X360 -#define CountLeadingZeros(x) _CountLeadingZeros(x) -inline unsigned int CountTrailingZeros( unsigned int elem ) -{ - // this implements CountTrailingZeros() / BitScanForward() - unsigned int mask = elem-1; - unsigned int comp = ~elem; - elem = mask & comp; - return (32 - _CountLeadingZeros(elem)); -} -#else -#include -#pragma intrinsic(_BitScanReverse) -#pragma intrinsic(_BitScanForward) - -inline unsigned int CountLeadingZeros(unsigned int x) -{ - unsigned long firstBit; - if ( _BitScanReverse(&firstBit,x) ) - return 31 - firstBit; - return 32; -} -inline unsigned int CountTrailingZeros(unsigned int elem) -{ - unsigned long out; - if ( _BitScanForward(&out, elem) ) - return out; - return 32; -} - -#endif -#else -#define FAST_BIT_SCAN 0 -#endif - - -static BitBufErrorHandler g_BitBufErrorHandler = 0; - -inline int BitForBitnum(int bitnum) -{ - return GetBitForBitnum(bitnum); -} - -void InternalBitBufErrorHandler( BitBufErrorType errorType, const char *pDebugName ) -{ - if ( g_BitBufErrorHandler ) - g_BitBufErrorHandler( errorType, pDebugName ); -} - - -void SetBitBufErrorHandler( BitBufErrorHandler fn ) -{ - g_BitBufErrorHandler = fn; -} - - -// #define BB_PROFILING - - -// Precalculated bit masks for WriteUBitLong. Using these tables instead of -// doing the calculations gives a 33% speedup in WriteUBitLong. -unsigned long g_BitWriteMasks[32][33]; - -// (1 << i) - 1 -unsigned long g_ExtraMasks[32]; - -class CBitWriteMasksInit -{ -public: - CBitWriteMasksInit() - { - for( unsigned int startbit=0; startbit < 32; startbit++ ) - { - for( unsigned int nBitsLeft=0; nBitsLeft < 33; nBitsLeft++ ) - { - unsigned int endbit = startbit + nBitsLeft; - g_BitWriteMasks[startbit][nBitsLeft] = BitForBitnum(startbit) - 1; - if(endbit < 32) - g_BitWriteMasks[startbit][nBitsLeft] |= ~(BitForBitnum(endbit) - 1); - } - } - - for ( unsigned int maskBit=0; maskBit < 32; maskBit++ ) - g_ExtraMasks[maskBit] = BitForBitnum(maskBit) - 1; - } -}; -CBitWriteMasksInit g_BitWriteMasksInit; - - -// ---------------------------------------------------------------------------------------- // -// old_bf_write -// ---------------------------------------------------------------------------------------- // - -old_bf_write::old_bf_write() -{ - m_pData = NULL; - m_nDataBytes = 0; - m_nDataBits = -1; // set to -1 so we generate overflow on any operation - m_iCurBit = 0; - m_bOverflow = false; - m_bAssertOnOverflow = true; - m_pDebugName = NULL; -} - -old_bf_write::old_bf_write( const char *pDebugName, void *pData, int nBytes, int nBits ) -{ - m_bAssertOnOverflow = true; - m_pDebugName = pDebugName; - StartWriting( pData, nBytes, 0, nBits ); -} - -old_bf_write::old_bf_write( void *pData, int nBytes, int nBits ) -{ - m_bAssertOnOverflow = true; - m_pDebugName = NULL; - StartWriting( pData, nBytes, 0, nBits ); -} - -void old_bf_write::StartWriting( void *pData, int nBytes, int iStartBit, int nBits ) -{ - // Make sure it's dword aligned and padded. - Assert( (nBytes % 4) == 0 ); - Assert(((unsigned long)pData & 3) == 0); - - // The writing code will overrun the end of the buffer if it isn't dword aligned, so truncate to force alignment - nBytes &= ~3; - - m_pData = (unsigned char*)pData; - m_nDataBytes = nBytes; - - if ( nBits == -1 ) - { - m_nDataBits = nBytes << 3; - } - else - { - Assert( nBits <= nBytes*8 ); - m_nDataBits = nBits; - } - - m_iCurBit = iStartBit; - m_bOverflow = false; -} - -void old_bf_write::Reset() -{ - m_iCurBit = 0; - m_bOverflow = false; -} - - -void old_bf_write::SetAssertOnOverflow( bool bAssert ) -{ - m_bAssertOnOverflow = bAssert; -} - - -const char* old_bf_write::GetDebugName() -{ - return m_pDebugName; -} - - -void old_bf_write::SetDebugName( const char *pDebugName ) -{ - m_pDebugName = pDebugName; -} - - -void old_bf_write::SeekToBit( int bitPos ) -{ - m_iCurBit = bitPos; -} - - -// Sign bit comes first -void old_bf_write::WriteSBitLong( int data, int numbits ) -{ - // Do we have a valid # of bits to encode with? - Assert( numbits >= 1 ); - - // Note: it does this wierdness here so it's bit-compatible with regular integer data in the buffer. - // (Some old code writes direct integers right into the buffer). - if(data < 0) - { -#ifdef _DEBUG - if( numbits < 32 ) - { - // Make sure it doesn't overflow. - - if( data < 0 ) - { - Assert( data >= -(BitForBitnum(numbits-1)) ); - } - else - { - Assert( data < (BitForBitnum(numbits-1)) ); - } - } -#endif - - WriteUBitLong( (unsigned int)(0x80000000 + data), numbits - 1, false ); - WriteOneBit( 1 ); - } - else - { - WriteUBitLong((unsigned int)data, numbits - 1); - WriteOneBit( 0 ); - } -} - -#if _WIN32 -inline unsigned int BitCountNeededToEncode(unsigned int data) -{ -#if defined(_X360) - return (32 - CountLeadingZeros(data+1)) - 1; -#else - unsigned long firstBit; - _BitScanReverse(&firstBit,data+1); - return firstBit; -#endif -} -#endif // _WIN32 - -// writes an unsigned integer with variable bit length -void old_bf_write::WriteUBitVar( unsigned int data ) -{ - if ( ( data &0xf ) == data ) - { - WriteUBitLong( 0, 2 ); - WriteUBitLong( data, 4 ); - } - else - { - if ( ( data & 0xff ) == data ) - { - WriteUBitLong( 1, 2 ); - WriteUBitLong( data, 8 ); - } - else - { - if ( ( data & 0xfff ) == data ) - { - WriteUBitLong( 2, 2 ); - WriteUBitLong( data, 12 ); - } - else - { - WriteUBitLong( 0x3, 2 ); - WriteUBitLong( data, 32 ); - } - } - } -#if 0 -#if !FAST_BIT_SCAN - unsigned int bits = 0; - unsigned int base = 0; - - while (data > (base<<1)) - { - bits++; - base = BitForBitnum(bits)-1; - } -#else - unsigned int bits = BitCountNeededToEncode(data); - unsigned int base = GetBitForBitnum(bits)-1; -#endif - - // how many bits do we use - WriteUBitLong( 0, bits ); - - // end marker - WriteOneBit( 1 ); - - // write the value - if ( bits > 0) - WriteUBitLong( data - base , bits ); -#endif -} - -void old_bf_write::WriteBitLong(unsigned int data, int numbits, bool bSigned) -{ - if(bSigned) - WriteSBitLong((int)data, numbits); - else - WriteUBitLong(data, numbits); -} - -bool old_bf_write::WriteBits(const void *pInData, int nBits) -{ -#if defined( BB_PROFILING ) - VPROF( "old_bf_write::WriteBits" ); -#endif - - unsigned char *pOut = (unsigned char*)pInData; - int nBitsLeft = nBits; - - // Bounds checking.. - if ( (m_iCurBit+nBits) > m_nDataBits ) - { - SetOverflowFlag(); - CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() ); - return false; - } - - // Align output to dword boundary - while (((unsigned long)pOut & 3) != 0 && nBitsLeft >= 8) - { - - WriteUBitLong( *pOut, 8, false ); - ++pOut; - nBitsLeft -= 8; - } - - if ( IsPC() && (nBitsLeft >= 32) && (m_iCurBit & 7) == 0 ) - { - // current bit is byte aligned, do block copy - int numbytes = nBitsLeft >> 3; - int numbits = numbytes << 3; - - Q_memcpy( m_pData+(m_iCurBit>>3), pOut, numbytes ); - pOut += numbytes; - nBitsLeft -= numbits; - m_iCurBit += numbits; - } - - // X360TBD: Can't write dwords in WriteBits because they'll get swapped - if ( IsPC() && nBitsLeft >= 32 ) - { - unsigned long iBitsRight = (m_iCurBit & 31); - unsigned long iBitsLeft = 32 - iBitsRight; - unsigned long bitMaskLeft = g_BitWriteMasks[iBitsRight][32]; - unsigned long bitMaskRight = g_BitWriteMasks[0][iBitsRight]; - - unsigned long *pData = &((unsigned long*)m_pData)[m_iCurBit>>5]; - - // Read dwords. - while(nBitsLeft >= 32) - { - unsigned long curData = *(unsigned long*)pOut; - pOut += sizeof(unsigned long); - - *pData &= bitMaskLeft; - *pData |= curData << iBitsRight; - - pData++; - - if ( iBitsLeft < 32 ) - { - curData >>= iBitsLeft; - *pData &= bitMaskRight; - *pData |= curData; - } - - nBitsLeft -= 32; - m_iCurBit += 32; - } - } - - - // write remaining bytes - while ( nBitsLeft >= 8 ) - { - WriteUBitLong( *pOut, 8, false ); - ++pOut; - nBitsLeft -= 8; - } - - // write remaining bits - if ( nBitsLeft ) - { - WriteUBitLong( *pOut, nBitsLeft, false ); - } - - return !IsOverflowed(); -} - - -bool old_bf_write::WriteBitsFromBuffer( bf_read *pIn, int nBits ) -{ - // This could be optimized a little by - while ( nBits > 32 ) - { - WriteUBitLong( pIn->ReadUBitLong( 32 ), 32 ); - nBits -= 32; - } - - WriteUBitLong( pIn->ReadUBitLong( nBits ), nBits ); - return !IsOverflowed() && !pIn->IsOverflowed(); -} - - -void old_bf_write::WriteBitAngle( float fAngle, int numbits ) -{ - int d; - unsigned int mask; - unsigned int shift; - - shift = BitForBitnum(numbits); - mask = shift - 1; - - d = (int)( (fAngle / 360.0) * shift ); - d &= mask; - - WriteUBitLong((unsigned int)d, numbits); -} - -void old_bf_write::WriteBitCoordMP( const float f, bool bIntegral, bool bLowPrecision ) -{ -#if defined( BB_PROFILING ) - VPROF( "old_bf_write::WriteBitCoordMP" ); -#endif - int signbit = (f <= -( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION )); - int intval = (int)abs(f); - int fractval = bLowPrecision ? - ( abs((int)(f*COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION-1) ) : - ( abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1) ); - - - bool bInBounds = intval < (1 << COORD_INTEGER_BITS_MP ); - - WriteOneBit( bInBounds ); - - if ( bIntegral ) - { - // Send the sign bit - WriteOneBit( intval ); - if ( intval ) - { - WriteOneBit( signbit ); - // Send the integer if we have one. - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - if ( bInBounds ) - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS_MP ); - } - else - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS ); - } - } - } - else - { - // Send the bit flags that indicate whether we have an integer part and/or a fraction part. - WriteOneBit( intval ); - // Send the sign bit - WriteOneBit( signbit ); - - if ( intval ) - { - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - if ( bInBounds ) - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS_MP ); - } - else - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS ); - } - } - WriteUBitLong( (unsigned int)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS ); - } -} - -void old_bf_write::WriteBitCoord (const float f) -{ -#if defined( BB_PROFILING ) - VPROF( "old_bf_write::WriteBitCoord" ); -#endif - int signbit = (f <= -COORD_RESOLUTION); - int intval = (int)abs(f); - int fractval = abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1); - - - // Send the bit flags that indicate whether we have an integer part and/or a fraction part. - WriteOneBit( intval ); - WriteOneBit( fractval ); - - if ( intval || fractval ) - { - // Send the sign bit - WriteOneBit( signbit ); - - // Send the integer if we have one. - if ( intval ) - { - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS ); - } - - // Send the fraction if we have one - if ( fractval ) - { - WriteUBitLong( (unsigned int)fractval, COORD_FRACTIONAL_BITS ); - } - } -} - -void old_bf_write::WriteBitFloat(float val) -{ - long intVal; - - Assert(sizeof(long) == sizeof(float)); - Assert(sizeof(float) == 4); - - intVal = *((long*)&val); - WriteUBitLong( intVal, 32 ); -} - -void old_bf_write::WriteBitVec3Coord( const Vector& fa ) -{ - int xflag, yflag, zflag; - - xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION); - yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION); - zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION); - - WriteOneBit( xflag ); - WriteOneBit( yflag ); - WriteOneBit( zflag ); - - if ( xflag ) - WriteBitCoord( fa[0] ); - if ( yflag ) - WriteBitCoord( fa[1] ); - if ( zflag ) - WriteBitCoord( fa[2] ); -} - -void old_bf_write::WriteBitNormal( float f ) -{ - int signbit = (f <= -NORMAL_RESOLUTION); - - // NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones - unsigned int fractval = abs( (int)(f*NORMAL_DENOMINATOR) ); - - // clamp.. - if (fractval > NORMAL_DENOMINATOR) - fractval = NORMAL_DENOMINATOR; - - // Send the sign bit - WriteOneBit( signbit ); - - // Send the fractional component - WriteUBitLong( fractval, NORMAL_FRACTIONAL_BITS ); -} - -void old_bf_write::WriteBitVec3Normal( const Vector& fa ) -{ - int xflag, yflag; - - xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION); - yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION); - - WriteOneBit( xflag ); - WriteOneBit( yflag ); - - if ( xflag ) - WriteBitNormal( fa[0] ); - if ( yflag ) - WriteBitNormal( fa[1] ); - - // Write z sign bit - int signbit = (fa[2] <= -NORMAL_RESOLUTION); - WriteOneBit( signbit ); -} - -void old_bf_write::WriteBitAngles( const QAngle& fa ) -{ - // FIXME: - Vector tmp( fa.x, fa.y, fa.z ); - WriteBitVec3Coord( tmp ); -} - -void old_bf_write::WriteChar(int val) -{ - WriteSBitLong(val, sizeof(char) << 3); -} - -void old_bf_write::WriteByte(int val) -{ - WriteUBitLong(val, sizeof(unsigned char) << 3); -} - -void old_bf_write::WriteShort(int val) -{ - WriteSBitLong(val, sizeof(short) << 3); -} - -void old_bf_write::WriteWord(int val) -{ - WriteUBitLong(val, sizeof(unsigned short) << 3); -} - -void old_bf_write::WriteLong(long val) -{ - WriteSBitLong(val, sizeof(long) << 3); -} - -void old_bf_write::WriteLongLong(int64 val) -{ - uint *pLongs = (uint*)&val; - - // Insert the two DWORDS according to network endian - const short endianIndex = 0x0100; - byte *idx = (byte*)&endianIndex; - WriteUBitLong(pLongs[*idx++], sizeof(long) << 3); - WriteUBitLong(pLongs[*idx], sizeof(long) << 3); -} - -void old_bf_write::WriteFloat(float val) -{ - // Pre-swap the float, since WriteBits writes raw data - LittleFloat( &val, &val ); - - WriteBits(&val, sizeof(val) << 3); -} - -bool old_bf_write::WriteBytes( const void *pBuf, int nBytes ) -{ - return WriteBits(pBuf, nBytes << 3); -} - -bool old_bf_write::WriteString(const char *pStr) -{ - if(pStr) - { - do - { - WriteChar( *pStr ); - ++pStr; - } while( *(pStr-1) != 0 ); - } - else - { - WriteChar( 0 ); - } - - return !IsOverflowed(); -} - -// ---------------------------------------------------------------------------------------- // -// old_bf_read -// ---------------------------------------------------------------------------------------- // - -old_bf_read::old_bf_read() -{ - m_pData = NULL; - m_nDataBytes = 0; - m_nDataBits = -1; // set to -1 so we overflow on any operation - m_iCurBit = 0; - m_bOverflow = false; - m_bAssertOnOverflow = true; - m_pDebugName = NULL; -} - -old_bf_read::old_bf_read( const void *pData, int nBytes, int nBits ) -{ - m_bAssertOnOverflow = true; - StartReading( pData, nBytes, 0, nBits ); -} - -old_bf_read::old_bf_read( const char *pDebugName, const void *pData, int nBytes, int nBits ) -{ - m_bAssertOnOverflow = true; - m_pDebugName = pDebugName; - StartReading( pData, nBytes, 0, nBits ); -} - -void old_bf_read::StartReading( const void *pData, int nBytes, int iStartBit, int nBits ) -{ - // Make sure we're dword aligned. - Assert(((unsigned long)pData & 3) == 0); - - m_pData = (unsigned char*)pData; - m_nDataBytes = nBytes; - - if ( nBits == -1 ) - { - m_nDataBits = m_nDataBytes << 3; - } - else - { - Assert( nBits <= nBytes*8 ); - m_nDataBits = nBits; - } - - m_iCurBit = iStartBit; - m_bOverflow = false; -} - -void old_bf_read::Reset() -{ - m_iCurBit = 0; - m_bOverflow = false; -} - -void old_bf_read::SetAssertOnOverflow( bool bAssert ) -{ - m_bAssertOnOverflow = bAssert; -} - -const char* old_bf_read::GetDebugName() -{ - return m_pDebugName; -} - -void old_bf_read::SetDebugName( const char *pName ) -{ - m_pDebugName = pName; -} - -unsigned int old_bf_read::CheckReadUBitLong(int numbits) -{ - // Ok, just read bits out. - int i, nBitValue; - unsigned int r = 0; - - for(i=0; i < numbits; i++) - { - nBitValue = ReadOneBitNoCheck(); - r |= nBitValue << i; - } - m_iCurBit -= numbits; - - return r; -} - -void old_bf_read::ReadBits(void *pOutData, int nBits) -{ -#if defined( BB_PROFILING ) - VPROF( "old_bf_write::ReadBits" ); -#endif - - unsigned char *pOut = (unsigned char*)pOutData; - int nBitsLeft = nBits; - - - // align output to dword boundary - while( ((unsigned long)pOut & 3) != 0 && nBitsLeft >= 8 ) - { - *pOut = (unsigned char)ReadUBitLong(8); - ++pOut; - nBitsLeft -= 8; - } - - // X360TBD: Can't read dwords in ReadBits because they'll get swapped - if ( IsPC() ) - { - // read dwords - while ( nBitsLeft >= 32 ) - { - *((unsigned long*)pOut) = ReadUBitLong(32); - pOut += sizeof(unsigned long); - nBitsLeft -= 32; - } - } - - // read remaining bytes - while ( nBitsLeft >= 8 ) - { - *pOut = ReadUBitLong(8); - ++pOut; - nBitsLeft -= 8; - } - - // read remaining bits - if ( nBitsLeft ) - { - *pOut = ReadUBitLong(nBitsLeft); - } - -} - -float old_bf_read::ReadBitAngle( int numbits ) -{ - float fReturn; - int i; - float shift; - - shift = (float)( BitForBitnum(numbits) ); - - i = ReadUBitLong( numbits ); - fReturn = (float)i * (360.0 / shift); - - return fReturn; -} - -unsigned int old_bf_read::PeekUBitLong( int numbits ) -{ - unsigned int r; - int i, nBitValue; -#ifdef BIT_VERBOSE - int nShifts = numbits; -#endif - - old_bf_read savebf; - - savebf = *this; // Save current state info - - r = 0; - for(i=0; i < numbits; i++) - { - nBitValue = ReadOneBit(); - - // Append to current stream - if ( nBitValue ) - { - r |= BitForBitnum(i); - } - } - - *this = savebf; - -#ifdef BIT_VERBOSE - Con_Printf( "PeekBitLong: %i %i\n", nShifts, (unsigned int)r ); -#endif - - return r; -} - -// Append numbits least significant bits from data to the current bit stream -int old_bf_read::ReadSBitLong( int numbits ) -{ - int r, sign; - - r = ReadUBitLong(numbits - 1); - - // Note: it does this wierdness here so it's bit-compatible with regular integer data in the buffer. - // (Some old code writes direct integers right into the buffer). - sign = ReadOneBit(); - if(sign) - r = -((BitForBitnum(numbits-1)) - r); - - return r; -} - -const byte g_BitMask[8] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80}; -const byte g_TrailingMask[8] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80}; - -inline int old_bf_read::CountRunOfZeros() -{ - int bits = 0; - if ( m_iCurBit + 32 < m_nDataBits ) - { -#if !FAST_BIT_SCAN - while (true) - { - int value = (m_pData[m_iCurBit >> 3] & g_BitMask[m_iCurBit & 7]); - ++m_iCurBit; - if ( value ) - return bits; - ++bits; - } -#else - while (true) - { - int value = (m_pData[m_iCurBit >> 3] & g_TrailingMask[m_iCurBit & 7]); - if ( !value ) - { - int zeros = (8-(m_iCurBit&7)); - bits += zeros; - m_iCurBit += zeros; - } - else - { - int zeros = CountTrailingZeros(value) - (m_iCurBit & 7); - m_iCurBit += zeros + 1; - bits += zeros; - return bits; - } - } -#endif - } - else - { - while ( ReadOneBit() == 0 ) - bits++; - } - return bits; -} - -unsigned int old_bf_read::ReadUBitVar() -{ - switch( ReadUBitLong( 2 ) ) - { - case 0: - return ReadUBitLong( 4 ); - - case 1: - return ReadUBitLong( 8 ); - - case 2: - return ReadUBitLong( 12 ); - - default: - case 3: - return ReadUBitLong( 32 ); - } -#if 0 - int bits = CountRunOfZeros(); - - unsigned int data = BitForBitnum(bits)-1; - - // read the value - if ( bits > 0) - data += ReadUBitLong( bits ); - - return data; -#endif -} - - -unsigned int old_bf_read::ReadBitLong(int numbits, bool bSigned) -{ - if(bSigned) - return (unsigned int)ReadSBitLong(numbits); - else - return ReadUBitLong(numbits); -} - - -// Basic Coordinate Routines (these contain bit-field size AND fixed point scaling constants) -float old_bf_read::ReadBitCoord (void) -{ -#if defined( BB_PROFILING ) - VPROF( "old_bf_write::ReadBitCoord" ); -#endif - int intval=0,fractval=0,signbit=0; - float value = 0.0; - - - // Read the required integer and fraction flags - intval = ReadOneBit(); - fractval = ReadOneBit(); - - // If we got either parse them, otherwise it's a zero. - if ( intval || fractval ) - { - // Read the sign bit - signbit = ReadOneBit(); - - // If there's an integer, read it in - if ( intval ) - { - // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] - intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1; - } - - // If there's a fraction, read it in - if ( fractval ) - { - fractval = ReadUBitLong( COORD_FRACTIONAL_BITS ); - } - - // Calculate the correct floating point value - value = intval + ((float)fractval * COORD_RESOLUTION); - - // Fixup the sign if negative. - if ( signbit ) - value = -value; - } - - return value; -} - -float old_bf_read::ReadBitCoordMP( bool bIntegral, bool bLowPrecision ) -{ -#if defined( BB_PROFILING ) - VPROF( "old_bf_write::ReadBitCoordMP" ); -#endif - int intval=0,fractval=0,signbit=0; - float value = 0.0; - - - bool bInBounds = ReadOneBit() ? true : false; - - if ( bIntegral ) - { - // Read the required integer and fraction flags - intval = ReadOneBit(); - // If we got either parse them, otherwise it's a zero. - if ( intval ) - { - // Read the sign bit - signbit = ReadOneBit(); - - // If there's an integer, read it in - // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] - if ( bInBounds ) - { - value = ReadUBitLong( COORD_INTEGER_BITS_MP ) + 1; - } - else - { - value = ReadUBitLong( COORD_INTEGER_BITS ) + 1; - } - } - } - else - { - // Read the required integer and fraction flags - intval = ReadOneBit(); - - // Read the sign bit - signbit = ReadOneBit(); - - // If we got either parse them, otherwise it's a zero. - if ( intval ) - { - if ( bInBounds ) - { - intval = ReadUBitLong( COORD_INTEGER_BITS_MP ) + 1; - } - else - { - intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1; - } - } - - // If there's a fraction, read it in - fractval = ReadUBitLong( bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS ); - - // Calculate the correct floating point value - value = intval + ((float)fractval * ( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION ) ); - } - - // Fixup the sign if negative. - if ( signbit ) - value = -value; - - return value; -} - -void old_bf_read::ReadBitVec3Coord( Vector& fa ) -{ - int xflag, yflag, zflag; - - // This vector must be initialized! Otherwise, If any of the flags aren't set, - // the corresponding component will not be read and will be stack garbage. - fa.Init( 0, 0, 0 ); - - xflag = ReadOneBit(); - yflag = ReadOneBit(); - zflag = ReadOneBit(); - - if ( xflag ) - fa[0] = ReadBitCoord(); - if ( yflag ) - fa[1] = ReadBitCoord(); - if ( zflag ) - fa[2] = ReadBitCoord(); -} - -float old_bf_read::ReadBitNormal (void) -{ - // Read the sign bit - int signbit = ReadOneBit(); - - // Read the fractional part - unsigned int fractval = ReadUBitLong( NORMAL_FRACTIONAL_BITS ); - - // Calculate the correct floating point value - float value = (float)fractval * NORMAL_RESOLUTION; - - // Fixup the sign if negative. - if ( signbit ) - value = -value; - - return value; -} - -void old_bf_read::ReadBitVec3Normal( Vector& fa ) -{ - int xflag = ReadOneBit(); - int yflag = ReadOneBit(); - - if (xflag) - fa[0] = ReadBitNormal(); - else - fa[0] = 0.0f; - - if (yflag) - fa[1] = ReadBitNormal(); - else - fa[1] = 0.0f; - - // The first two imply the third (but not its sign) - int znegative = ReadOneBit(); - - float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1]; - if (fafafbfb < 1.0f) - fa[2] = sqrt( 1.0f - fafafbfb ); - else - fa[2] = 0.0f; - - if (znegative) - fa[2] = -fa[2]; -} - -void old_bf_read::ReadBitAngles( QAngle& fa ) -{ - Vector tmp; - ReadBitVec3Coord( tmp ); - fa.Init( tmp.x, tmp.y, tmp.z ); -} - -int old_bf_read::ReadChar() -{ - return ReadSBitLong(sizeof(char) << 3); -} - -int old_bf_read::ReadByte() -{ - return ReadUBitLong(sizeof(unsigned char) << 3); -} - -int old_bf_read::ReadShort() -{ - return ReadSBitLong(sizeof(short) << 3); -} - -int old_bf_read::ReadWord() -{ - return ReadUBitLong(sizeof(unsigned short) << 3); -} - -long old_bf_read::ReadLong() -{ - return ReadSBitLong(sizeof(long) << 3); -} - -int64 old_bf_read::ReadLongLong() -{ - int64 retval; - uint *pLongs = (uint*)&retval; - - // Read the two DWORDs according to network endian - const short endianIndex = 0x0100; - byte *idx = (byte*)&endianIndex; - pLongs[*idx++] = ReadUBitLong(sizeof(long) << 3); - pLongs[*idx] = ReadUBitLong(sizeof(long) << 3); - - return retval; -} - -float old_bf_read::ReadFloat() -{ - float ret; - Assert( sizeof(ret) == 4 ); - ReadBits(&ret, 32); - - // Swap the float, since ReadBits reads raw data - LittleFloat( &ret, &ret ); - return ret; -} - -bool old_bf_read::ReadBytes(void *pOut, int nBytes) -{ - ReadBits(pOut, nBytes << 3); - return !IsOverflowed(); -} - -bool old_bf_read::ReadString( char *pStr, int maxLen, bool bLine, int *pOutNumChars ) -{ - Assert( maxLen != 0 ); - - bool bTooSmall = false; - int iChar = 0; - while(1) - { - char val = ReadChar(); - if ( val == 0 ) - break; - else if ( bLine && val == '\n' ) - break; - - if ( iChar < (maxLen-1) ) - { - pStr[iChar] = val; - ++iChar; - } - else - { - bTooSmall = true; - } - } - - // Make sure it's null-terminated. - Assert( iChar < maxLen ); - pStr[iChar] = 0; - - if ( pOutNumChars ) - *pOutNumChars = iChar; - - return !IsOverflowed() && !bTooSmall; -} - - -char* old_bf_read::ReadAndAllocateString( bool *pOverflow ) -{ - char str[2048]; - - int nChars; - bool bOverflow = !ReadString( str, sizeof( str ), false, &nChars ); - if ( pOverflow ) - *pOverflow = bOverflow; - - // Now copy into the output and return it; - char *pRet = new char[ nChars + 1 ]; - for ( int i=0; i <= nChars; i++ ) - pRet[i] = str[i]; - - return pRet; -} - -void old_bf_read::ExciseBits( int startbit, int bitstoremove ) -{ - int endbit = startbit + bitstoremove; - int remaining_to_end = m_nDataBits - endbit; - - old_bf_write temp; - temp.StartWriting( (void *)m_pData, m_nDataBits << 3, startbit ); - - Seek( endbit ); - - for ( int i = 0; i < remaining_to_end; i++ ) - { - temp.WriteOneBit( ReadOneBit() ); - } - - Seek( startbit ); - - m_nDataBits -= bitstoremove; - m_nDataBytes = m_nDataBits >> 3; -} - - diff --git a/Resources/NetHook/tier1/bitbuf.h b/Resources/NetHook/tier1/bitbuf.h deleted file mode 100644 index f72bf4c2..00000000 --- a/Resources/NetHook/tier1/bitbuf.h +++ /dev/null @@ -1,1500 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -// NOTE: old_bf_read is guaranteed to return zeros if it overflows. - -#ifndef BITBUF_H -#define BITBUF_H - -#ifdef _WIN32 -#pragma once -#endif - - -#include "mathlib/mathlib.h" -#include "mathlib/vector.h" -#include "basetypes.h" -#include "tier0/dbg.h" - - - - -//----------------------------------------------------------------------------- -// Forward declarations. -//----------------------------------------------------------------------------- - -class Vector; -class QAngle; - -//----------------------------------------------------------------------------- -// You can define a handler function that will be called in case of -// out-of-range values and overruns here. -// -// NOTE: the handler is only called in debug mode. -// -// Call SetBitBufErrorHandler to install a handler. -//----------------------------------------------------------------------------- - -typedef enum -{ - BITBUFERROR_VALUE_OUT_OF_RANGE=0, // Tried to write a value with too few bits. - BITBUFERROR_BUFFER_OVERRUN, // Was about to overrun a buffer. - - BITBUFERROR_NUM_ERRORS -} BitBufErrorType; - - -typedef void (*BitBufErrorHandler)( BitBufErrorType errorType, const char *pDebugName ); - - -#if defined( _DEBUG ) - extern void InternalBitBufErrorHandler( BitBufErrorType errorType, const char *pDebugName ); - #define CallErrorHandler( errorType, pDebugName ) InternalBitBufErrorHandler( errorType, pDebugName ); -#else - #define CallErrorHandler( errorType, pDebugName ) -#endif - - -// Use this to install the error handler. Call with NULL to uninstall your error handler. -void SetBitBufErrorHandler( BitBufErrorHandler fn ); - - -//----------------------------------------------------------------------------- -// Helpers. -//----------------------------------------------------------------------------- - -inline int BitByte( int bits ) -{ - // return PAD_NUMBER( bits, 8 ) >> 3; - return (bits + 7) >> 3; -} - -//----------------------------------------------------------------------------- -// Used for serialization -//----------------------------------------------------------------------------- - -class old_bf_write -{ -public: - old_bf_write(); - - // nMaxBits can be used as the number of bits in the buffer. - // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8. - old_bf_write( void *pData, int nBytes, int nMaxBits = -1 ); - old_bf_write( const char *pDebugName, void *pData, int nBytes, int nMaxBits = -1 ); - - // Start writing to the specified buffer. - // nMaxBits can be used as the number of bits in the buffer. - // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8. - void StartWriting( void *pData, int nBytes, int iStartBit = 0, int nMaxBits = -1 ); - - // Restart buffer writing. - void Reset(); - - // Get the base pointer. - unsigned char* GetBasePointer() { return m_pData; } - - // Enable or disable assertion on overflow. 99% of the time, it's a bug that we need to catch, - // but there may be the occasional buffer that is allowed to overflow gracefully. - void SetAssertOnOverflow( bool bAssert ); - - // This can be set to assign a name that gets output if the buffer overflows. - const char* GetDebugName(); - void SetDebugName( const char *pDebugName ); - - -// Seek to a specific position. -public: - - void SeekToBit( int bitPos ); - - -// Bit functions. -public: - - void WriteOneBit(int nValue); - void WriteOneBitNoCheck(int nValue); - void WriteOneBitAt( int iBit, int nValue ); - - // Write signed or unsigned. Range is only checked in debug. - void WriteUBitLong( unsigned int data, int numbits, bool bCheckRange=true ); - void WriteSBitLong( int data, int numbits ); - - // Tell it whether or not the data is unsigned. If it's signed, - // cast to unsigned before passing in (it will cast back inside). - void WriteBitLong(unsigned int data, int numbits, bool bSigned); - - // Write a list of bits in. - bool WriteBits(const void *pIn, int nBits); - - // writes an unsigned integer with variable bit length - void WriteUBitVar( unsigned int data ); - - // Copy the bits straight out of pIn. This seeks pIn forward by nBits. - // Returns an error if this buffer or the read buffer overflows. - bool WriteBitsFromBuffer( class bf_read *pIn, int nBits ); - - void WriteBitAngle( float fAngle, int numbits ); - void WriteBitCoord (const float f); - void WriteBitCoordMP( const float f, bool bIntegral, bool bLowPrecision ); - void WriteBitFloat(float val); - void WriteBitVec3Coord( const Vector& fa ); - void WriteBitNormal( float f ); - void WriteBitVec3Normal( const Vector& fa ); - void WriteBitAngles( const QAngle& fa ); - - -// Byte functions. -public: - - void WriteChar(int val); - void WriteByte(int val); - void WriteShort(int val); - void WriteWord(int val); - void WriteLong(long val); - void WriteLongLong(int64 val); - void WriteFloat(float val); - bool WriteBytes( const void *pBuf, int nBytes ); - - // Returns false if it overflows the buffer. - bool WriteString(const char *pStr); - - -// Status. -public: - - // How many bytes are filled in? - int GetNumBytesWritten(); - int GetNumBitsWritten(); - int GetMaxNumBits(); - int GetNumBitsLeft(); - int GetNumBytesLeft(); - unsigned char* GetData(); - - // Has the buffer overflowed? - bool CheckForOverflow(int nBits); - inline bool IsOverflowed() const {return m_bOverflow;} - - inline void SetOverflowFlag(); - - -public: - // The current buffer. - unsigned char* m_pData; - int m_nDataBytes; - int m_nDataBits; - - // Where we are in the buffer. - int m_iCurBit; - -private: - - // Errors? - bool m_bOverflow; - - bool m_bAssertOnOverflow; - const char *m_pDebugName; -}; - - -//----------------------------------------------------------------------------- -// Inlined methods -//----------------------------------------------------------------------------- - -// How many bytes are filled in? -inline int old_bf_write::GetNumBytesWritten() -{ - return BitByte(m_iCurBit); -} - -inline int old_bf_write::GetNumBitsWritten() -{ - return m_iCurBit; -} - -inline int old_bf_write::GetMaxNumBits() -{ - return m_nDataBits; -} - -inline int old_bf_write::GetNumBitsLeft() -{ - return m_nDataBits - m_iCurBit; -} - -inline int old_bf_write::GetNumBytesLeft() -{ - return GetNumBitsLeft() >> 3; -} - -inline unsigned char* old_bf_write::GetData() -{ - return m_pData; -} - -inline bool old_bf_write::CheckForOverflow(int nBits) -{ - if ( m_iCurBit + nBits > m_nDataBits ) - { - SetOverflowFlag(); - CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() ); - } - - return m_bOverflow; -} - -inline void old_bf_write::SetOverflowFlag() -{ - if ( m_bAssertOnOverflow ) - { - Assert( false ); - } - - m_bOverflow = true; -} - -inline void old_bf_write::WriteOneBitNoCheck(int nValue) -{ - if(nValue) - m_pData[m_iCurBit >> 3] |= (1 << (m_iCurBit & 7)); - else - m_pData[m_iCurBit >> 3] &= ~(1 << (m_iCurBit & 7)); - - ++m_iCurBit; -} - -inline void old_bf_write::WriteOneBit(int nValue) -{ - if( !CheckForOverflow(1) ) - WriteOneBitNoCheck( nValue ); -} - - -inline void old_bf_write::WriteOneBitAt( int iBit, int nValue ) -{ - if( iBit+1 > m_nDataBits ) - { - SetOverflowFlag(); - CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() ); - return; - } - - if( nValue ) - m_pData[iBit >> 3] |= (1 << (iBit & 7)); - else - m_pData[iBit >> 3] &= ~(1 << (iBit & 7)); -} - - -inline void old_bf_write::WriteUBitLong( unsigned int curData, int numbits, bool bCheckRange ) -{ -#ifdef _DEBUG - // Make sure it doesn't overflow. - if ( bCheckRange && numbits < 32 ) - { - if ( curData >= (unsigned long)(1 << numbits) ) - { - CallErrorHandler( BITBUFERROR_VALUE_OUT_OF_RANGE, GetDebugName() ); - } - } - Assert( numbits >= 0 && numbits <= 32 ); -#endif - - extern unsigned long g_BitWriteMasks[32][33]; - - // Bounds checking.. - if ((m_iCurBit+numbits) > m_nDataBits) - { - m_iCurBit = m_nDataBits; - SetOverflowFlag(); - CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() ); - return; - } - - int nBitsLeft = numbits; - int iCurBit = m_iCurBit; - - // Mask in a dword. - unsigned int iDWord = iCurBit >> 5; - Assert( (iDWord*4 + sizeof(long)) <= (unsigned int)m_nDataBytes ); - - unsigned long iCurBitMasked = iCurBit & 31; - - unsigned long dword = LoadLittleDWord( (unsigned long*)m_pData, iDWord ); - - dword &= g_BitWriteMasks[iCurBitMasked][nBitsLeft]; - dword |= curData << iCurBitMasked; - - // write to stream (lsb to msb ) properly - StoreLittleDWord( (unsigned long*)m_pData, iDWord, dword ); - - // Did it span a dword? - int nBitsWritten = 32 - iCurBitMasked; - if ( nBitsWritten < nBitsLeft ) - { - nBitsLeft -= nBitsWritten; - curData >>= nBitsWritten; - - // read from stream (lsb to msb) properly - dword = LoadLittleDWord( (unsigned long*)m_pData, iDWord+1 ); - - dword &= g_BitWriteMasks[0][nBitsLeft]; - dword |= curData; - - // write to stream (lsb to msb) properly - StoreLittleDWord( (unsigned long*)m_pData, iDWord+1, dword ); - } - - m_iCurBit += numbits; -} - - -//----------------------------------------------------------------------------- -// This is useful if you just want a buffer to write into on the stack. -//----------------------------------------------------------------------------- - -template -class old_bf_write_static : public old_bf_write -{ -public: - inline old_bf_write_static() : old_bf_write(m_StaticData, SIZE) {} - - char m_StaticData[SIZE]; -}; - - - -//----------------------------------------------------------------------------- -// Used for unserialization -//----------------------------------------------------------------------------- - -class old_bf_read -{ -public: - old_bf_read(); - - // nMaxBits can be used as the number of bits in the buffer. - // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8. - old_bf_read( const void *pData, int nBytes, int nBits = -1 ); - old_bf_read( const char *pDebugName, const void *pData, int nBytes, int nBits = -1 ); - - // Start reading from the specified buffer. - // pData's start address must be dword-aligned. - // nMaxBits can be used as the number of bits in the buffer. - // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8. - void StartReading( const void *pData, int nBytes, int iStartBit = 0, int nBits = -1 ); - - // Restart buffer reading. - void Reset(); - - // Enable or disable assertion on overflow. 99% of the time, it's a bug that we need to catch, - // but there may be the occasional buffer that is allowed to overflow gracefully. - void SetAssertOnOverflow( bool bAssert ); - - // This can be set to assign a name that gets output if the buffer overflows. - const char* GetDebugName(); - void SetDebugName( const char *pName ); - - void ExciseBits( int startbit, int bitstoremove ); - - -// Bit functions. -public: - - // Returns 0 or 1. - int ReadOneBit(); - - -protected: - - unsigned int CheckReadUBitLong(int numbits); // For debugging. - int ReadOneBitNoCheck(); // Faster version, doesn't check bounds and is inlined. - bool CheckForOverflow(int nBits); - - -public: - - // Get the base pointer. - const unsigned char* GetBasePointer() { return m_pData; } - - FORCEINLINE int TotalBytesAvailable( void ) const - { - return m_nDataBytes; - } - - // Read a list of bits in.. - void ReadBits(void *pOut, int nBits); - - float ReadBitAngle( int numbits ); - - unsigned int ReadUBitLong( int numbits ); - unsigned int PeekUBitLong( int numbits ); - int ReadSBitLong( int numbits ); - - // reads an unsigned integer with variable bit length - unsigned int ReadUBitVar(); - - // You can read signed or unsigned data with this, just cast to - // a signed int if necessary. - unsigned int ReadBitLong(int numbits, bool bSigned); - - float ReadBitCoord(); - float ReadBitCoordMP( bool bIntegral, bool bLowPrecision ); - float ReadBitFloat(); - float ReadBitNormal(); - void ReadBitVec3Coord( Vector& fa ); - void ReadBitVec3Normal( Vector& fa ); - void ReadBitAngles( QAngle& fa ); - - -// Byte functions (these still read data in bit-by-bit). -public: - - int ReadChar(); - int ReadByte(); - int ReadShort(); - int ReadWord(); - long ReadLong(); - int64 ReadLongLong(); - float ReadFloat(); - bool ReadBytes(void *pOut, int nBytes); - - // Returns false if bufLen isn't large enough to hold the - // string in the buffer. - // - // Always reads to the end of the string (so you can read the - // next piece of data waiting). - // - // If bLine is true, it stops when it reaches a '\n' or a null-terminator. - // - // pStr is always null-terminated (unless bufLen is 0). - // - // pOutNumChars is set to the number of characters left in pStr when the routine is - // complete (this will never exceed bufLen-1). - // - bool ReadString( char *pStr, int bufLen, bool bLine=false, int *pOutNumChars=NULL ); - - // Reads a string and allocates memory for it. If the string in the buffer - // is > 2048 bytes, then pOverflow is set to true (if it's not NULL). - char* ReadAndAllocateString( bool *pOverflow = 0 ); - -// Status. -public: - int GetNumBytesLeft(); - int GetNumBytesRead(); - int GetNumBitsLeft(); - int GetNumBitsRead() const; - - // Has the buffer overflowed? - inline bool IsOverflowed() const {return m_bOverflow;} - - inline bool Seek(int iBit); // Seek to a specific bit. - inline bool SeekRelative(int iBitDelta); // Seek to an offset from the current position. - - // Called when the buffer is overflowed. - inline void SetOverflowFlag(); - - -public: - - // The current buffer. - const unsigned char* m_pData; - int m_nDataBytes; - int m_nDataBits; - - // Where we are in the buffer. - int m_iCurBit; - - -private: - // used by varbit reads internally - inline int CountRunOfZeros(); - - // Errors? - bool m_bOverflow; - - // For debugging.. - bool m_bAssertOnOverflow; - - const char *m_pDebugName; -}; - -//----------------------------------------------------------------------------- -// Inlines. -//----------------------------------------------------------------------------- - -inline int old_bf_read::GetNumBytesRead() -{ - return BitByte(m_iCurBit); -} - -inline int old_bf_read::GetNumBitsLeft() -{ - return m_nDataBits - m_iCurBit; -} - -inline int old_bf_read::GetNumBytesLeft() -{ - return GetNumBitsLeft() >> 3; -} - -inline int old_bf_read::GetNumBitsRead() const -{ - return m_iCurBit; -} - -inline void old_bf_read::SetOverflowFlag() -{ - if ( m_bAssertOnOverflow ) - { - Assert( false ); - } - - m_bOverflow = true; -} - -inline bool old_bf_read::Seek(int iBit) -{ - if(iBit < 0 || iBit > m_nDataBits) - { - SetOverflowFlag(); - m_iCurBit = m_nDataBits; - return false; - } - else - { - m_iCurBit = iBit; - return true; - } -} - -// Seek to an offset from the current position. -inline bool old_bf_read::SeekRelative(int iBitDelta) -{ - return Seek(m_iCurBit+iBitDelta); -} - -inline bool old_bf_read::CheckForOverflow(int nBits) -{ - if( m_iCurBit + nBits > m_nDataBits ) - { - SetOverflowFlag(); - CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() ); - } - - return m_bOverflow; -} - -inline int old_bf_read::ReadOneBitNoCheck() -{ - int value = m_pData[m_iCurBit >> 3] & (1 << (m_iCurBit & 7)); - ++m_iCurBit; - return !!value; -} - -inline int old_bf_read::ReadOneBit() -{ - return (!CheckForOverflow(1)) ? ReadOneBitNoCheck() : 0; -} - -inline float old_bf_read::ReadBitFloat() -{ - long val; - - Assert(sizeof(float) == sizeof(long)); - Assert(sizeof(float) == 4); - - if(CheckForOverflow(32)) - return 0.0f; - - int bit = m_iCurBit & 0x7; - int byte = m_iCurBit >> 3; - val = m_pData[byte] >> bit; - val |= ((int)m_pData[byte + 1]) << (8 - bit); - val |= ((int)m_pData[byte + 2]) << (16 - bit); - val |= ((int)m_pData[byte + 3]) << (24 - bit); - if (bit != 0) - val |= ((int)m_pData[byte + 4]) << (32 - bit); - m_iCurBit += 32; - return *((float*)&val); -} - - -inline unsigned int old_bf_read::ReadUBitLong( int numbits ) -{ - extern unsigned long g_ExtraMasks[32]; - - if ( (m_iCurBit+numbits) > m_nDataBits ) - { - m_iCurBit = m_nDataBits; - SetOverflowFlag(); - return 0; - } - - Assert( numbits > 0 && numbits <= 32 ); - - // Read the current dword. - int idword1 = m_iCurBit >> 5; - unsigned int dword1 = LoadLittleDWord( (unsigned long*)m_pData, idword1 ); - - dword1 >>= (m_iCurBit & 31); // Get the bits we're interested in. - - m_iCurBit += numbits; - unsigned int ret = dword1; - - // Does it span this dword? - if ( (m_iCurBit-1) >> 5 == idword1 ) - { - if (numbits != 32) - ret &= g_ExtraMasks[numbits]; - } - else - { - int nExtraBits = m_iCurBit & 31; - unsigned int dword2 = LoadLittleDWord( (unsigned long*)m_pData, idword1+1 ); - - dword2 &= g_ExtraMasks[nExtraBits]; - - // No need to mask since we hit the end of the dword. - // Shift the second dword's part into the high bits. - ret |= (dword2 << (numbits - nExtraBits)); - } - - return ret; -} - - -class CBitBuffer -{ -public: - char const * m_pDebugName; - bool m_bOverflow; - int m_nDataBits; - size_t m_nDataBytes; - - void SetDebugName( char const *pName ) - { - m_pDebugName = pName; - } - - CBitBuffer( void ) - { - m_bOverflow = false; - m_pDebugName = NULL; - m_nDataBits = -1; - m_nDataBytes = 0; - } - - FORCEINLINE void SetOverflowFlag( void ) - { - m_bOverflow = true; - } - - FORCEINLINE bool IsOverflowed( void ) const - { - return m_bOverflow; - } - - static const uint32 s_nMaskTable[33]; // 0 1 3 7 15 .. - -}; - - -class CBitWrite : public CBitBuffer -{ - uint32 m_nOutBufWord; - int m_nOutBitsAvail; - uint32 *m_pDataOut; - uint32 *m_pBufferEnd; - uint32 *m_pData; - bool m_bFlushed; - -public: - void StartWriting( void *pData, int nBytes, int iStartBit = 0, int nMaxBits = -1 ); - - - CBitWrite( void *pData, int nBytes, int nBits = -1 ) - { - m_bFlushed = false; - StartWriting( pData, nBytes, 0, nBits ); - } - - CBitWrite( const char *pDebugName, void *pData, int nBytes, int nBits = -1 ) - { - m_bFlushed = false; - SetDebugName( pDebugName ); - StartWriting( pData, nBytes, 0, nBits ); - } - - CBitWrite( void ) - { - m_bFlushed = false; - } - - ~CBitWrite( void ) - { - TempFlush(); - Assert( (! m_pData ) || m_bFlushed ); - } - FORCEINLINE int GetNumBitsLeft( void ) const - { - return m_nOutBitsAvail + ( 32 * ( m_pBufferEnd - m_pDataOut -1 ) ); - } - - FORCEINLINE void Reset( void ) - { - m_bOverflow = false; - m_nOutBitsAvail = 32; - m_pDataOut = m_pData; - m_nOutBufWord = 0; - - } - - FORCEINLINE void TempFlush( void ) - { - // someone wants to know how much data we have written, or the pointer to it, so we'd better make - // sure we write our data - if ( m_nOutBitsAvail != 32 ) - { - if ( m_pDataOut == m_pBufferEnd ) - { - SetOverflowFlag(); - } - else - { - *( m_pDataOut ) = (*m_pDataOut & ~s_nMaskTable[ 32 - m_nOutBitsAvail ] ) | m_nOutBufWord; - m_bFlushed = true; - } - } - } - - FORCEINLINE unsigned char *GetBasePointer() - { - TempFlush(); - return reinterpret_cast< unsigned char *>( m_pData ); - } - - FORCEINLINE unsigned char *GetData() - { - return GetBasePointer(); - } - - FORCEINLINE void Finish(); - FORCEINLINE void Flush(); - FORCEINLINE void FlushNoCheck(); - FORCEINLINE void WriteOneBit(int nValue); - FORCEINLINE void WriteOneBitNoCheck(int nValue); - FORCEINLINE void WriteUBitLong( unsigned int data, int numbits, bool bCheckRange=true ); - FORCEINLINE void WriteSBitLong( int data, int numbits ); - FORCEINLINE void WriteUBitVar( unsigned int data ); - FORCEINLINE void WriteBitFloat( float flValue ); - FORCEINLINE void WriteFloat( float flValue ); - bool WriteBits(const void *pInData, int nBits); - void WriteBytes( const void *pBuf, int nBytes ); - void SeekToBit( int nSeekPos ); - - FORCEINLINE int GetNumBitsWritten( void ) const - { - return ( 32 - m_nOutBitsAvail ) + ( 32 * ( m_pDataOut - m_pData ) ); - } - - FORCEINLINE int GetNumBytesWritten( void ) const - { - return ( GetNumBitsWritten() + 7 ) >> 3; - } - - - FORCEINLINE void WriteLong(long val) - { - WriteSBitLong( val, 32 ); - } - - - - FORCEINLINE void WriteChar( int val ) - { - WriteSBitLong(val, sizeof(char) << 3 ); - } - - FORCEINLINE void WriteByte( int val ) - { - WriteUBitLong(val, sizeof(unsigned char) << 3, false ); - } - - FORCEINLINE void WriteShort(int val) - { - WriteSBitLong(val, sizeof(short) << 3); - } - - FORCEINLINE void WriteWord(int val) - { - WriteUBitLong(val, sizeof(unsigned short) << 3); - } - - bool WriteString( const char *pStr ); - - void WriteLongLong( int64 val ); - - void WriteBitAngle( float fAngle, int numbits ); - void WriteBitCoord (const float f); - void WriteBitCoordMP( const float f, bool bIntegral, bool bLowPrecision ); - void WriteBitVec3Coord( const Vector& fa ); - void WriteBitNormal( float f ); - void WriteBitVec3Normal( const Vector& fa ); - void WriteBitAngles( const QAngle& fa ); - - // Copy the bits straight out of pIn. This seeks pIn forward by nBits. - // Returns an error if this buffer or the read buffer overflows. - bool WriteBitsFromBuffer( class bf_read *pIn, int nBits ); - -}; - -void CBitWrite::Finish( void ) -{ - if ( m_nOutBitsAvail != 32 ) - { - if ( m_pDataOut == m_pBufferEnd ) - { - SetOverflowFlag(); - } - *( m_pDataOut ) = m_nOutBufWord; - } -} - -void CBitWrite::FlushNoCheck( void ) -{ - *( m_pDataOut++ ) = m_nOutBufWord; - m_nOutBitsAvail = 32; - m_nOutBufWord = 0; // ugh - I need this because of 32 bit writes. a<<=32 is a nop - -} -void CBitWrite::Flush( void ) -{ - if ( m_pDataOut == m_pBufferEnd ) - { - SetOverflowFlag(); - } - else - *( m_pDataOut++ ) = m_nOutBufWord; - m_nOutBufWord = 0; // ugh - I need this because of 32 bit writes. a<<=32 is a nop - m_nOutBitsAvail = 32; - -} -void CBitWrite::WriteOneBitNoCheck( int nValue ) -{ - m_nOutBufWord |= ( nValue & 1 ) << ( 32 - m_nOutBitsAvail ); - if ( --m_nOutBitsAvail == 0 ) - { - FlushNoCheck(); - } -} - -void CBitWrite::WriteOneBit( int nValue ) -{ - m_nOutBufWord |= ( nValue & 1 ) << ( 32 - m_nOutBitsAvail ); - if ( --m_nOutBitsAvail == 0 ) - { - Flush(); - } -} - -FORCEINLINE void CBitWrite::WriteUBitLong( unsigned int nData, int nNumBits, bool bCheckRange ) -{ - -#ifdef _DEBUG - // Make sure it doesn't overflow. - if ( bCheckRange && nNumBits < 32 ) - { - Assert( nData <= (unsigned long)(1 << nNumBits ) ); - } - Assert( nNumBits >= 0 && nNumBits <= 32 ); -#endif - if ( nNumBits <= m_nOutBitsAvail ) - { - if ( bCheckRange ) - m_nOutBufWord |= ( nData ) << ( 32 - m_nOutBitsAvail ); - else - m_nOutBufWord |= ( nData & s_nMaskTable[ nNumBits] ) << ( 32 - m_nOutBitsAvail ); - m_nOutBitsAvail -= nNumBits; - if ( m_nOutBitsAvail == 0 ) - { - Flush(); - } - } - else - { - // split dwords case - int nOverflowBits = ( nNumBits - m_nOutBitsAvail ); - m_nOutBufWord |= ( nData & s_nMaskTable[m_nOutBitsAvail] ) << ( 32 - m_nOutBitsAvail ); - Flush(); - m_nOutBufWord = ( nData >> ( nNumBits - nOverflowBits ) ); - m_nOutBitsAvail = 32 - nOverflowBits; - } -} - -FORCEINLINE void CBitWrite::WriteSBitLong( int nData, int nNumBits ) -{ - WriteUBitLong( ( uint32 ) nData, nNumBits, false ); -} - -FORCEINLINE void CBitWrite::WriteUBitVar( unsigned int data ) -{ - if ( ( data &0xf ) == data ) - { - WriteUBitLong( 0, 2 ); - WriteUBitLong( data, 4 ); - } - else - { - if ( ( data & 0xff ) == data ) - { - WriteUBitLong( 1, 2 ); - WriteUBitLong( data, 8 ); - } - else - { - if ( ( data & 0xfff ) == data ) - { - WriteUBitLong( 2, 2 ); - WriteUBitLong( data, 12 ); - } - else - { - WriteUBitLong( 0x3, 2 ); - WriteUBitLong( data, 32 ); - } - } - } -} - -FORCEINLINE void CBitWrite::WriteBitFloat( float flValue ) -{ - WriteUBitLong( *((uint32 *) &flValue ), 32 ); -} - -FORCEINLINE void CBitWrite::WriteFloat( float flValue ) -{ - // Pre-swap the float, since WriteBits writes raw data - LittleFloat( &flValue, &flValue ); - WriteUBitLong( *((uint32 *) &flValue ), 32 ); -} - -class CBitRead : public CBitBuffer -{ - uint32 m_nInBufWord; - int m_nBitsAvail; - uint32 const *m_pDataIn; - uint32 const *m_pBufferEnd; - uint32 const *m_pData; - -public: - CBitRead( const void *pData, int nBytes, int nBits = -1 ) - { - StartReading( pData, nBytes, 0, nBits ); - } - - CBitRead( const char *pDebugName, const void *pData, int nBytes, int nBits = -1 ) - { - SetDebugName( pDebugName ); - StartReading( pData, nBytes, 0, nBits ); - } - - CBitRead( void ) : CBitBuffer() - { - } - - FORCEINLINE int Tell( void ) const - { - return GetNumBitsRead(); - } - - FORCEINLINE size_t TotalBytesAvailable( void ) const - { - return m_nDataBytes; - } - - FORCEINLINE int GetNumBitsLeft() const - { - return m_nDataBits - Tell(); - } - - FORCEINLINE int GetNumBytesLeft() const - { - return GetNumBitsLeft() >> 3; - } - - bool Seek( int nPosition ); - - FORCEINLINE bool SeekRelative( int nOffset ) - { - return Seek( GetNumBitsRead() + nOffset ); - } - - FORCEINLINE unsigned char const * GetBasePointer() - { - return reinterpret_cast< unsigned char const *>( m_pData ); - } - - void StartReading( const void *pData, int nBytes, int iStartBit = 0, int nBits = -1 ); - - FORCEINLINE int CBitRead::GetNumBitsRead( void ) const; - - FORCEINLINE void GrabNextDWord( bool bOverFlowImmediately = false ); - FORCEINLINE void FetchNext( void ); - FORCEINLINE unsigned int ReadUBitLong( int numbits ); - FORCEINLINE int ReadSBitLong( int numbits ); - FORCEINLINE unsigned int ReadUBitVar( void ); - FORCEINLINE unsigned int PeekUBitLong( int numbits ); - FORCEINLINE float ReadBitFloat( void ); - float ReadBitCoord(); - float ReadBitCoordMP( bool bIntegral, bool bLowPrecision ); - float ReadBitNormal(); - void ReadBitVec3Coord( Vector& fa ); - void ReadBitVec3Normal( Vector& fa ); - void ReadBitAngles( QAngle& fa ); - bool ReadBytes(void *pOut, int nBytes); - float ReadBitAngle( int numbits ); - - // Returns 0 or 1. - FORCEINLINE int ReadOneBit( void ); - FORCEINLINE int ReadLong( void ); - FORCEINLINE int ReadChar( void ); - FORCEINLINE int ReadByte( void ); - FORCEINLINE int ReadShort( void ); - FORCEINLINE int ReadWord( void ); - FORCEINLINE float ReadFloat( void ); - void ReadBits(void *pOut, int nBits); - - // Returns false if bufLen isn't large enough to hold the - // string in the buffer. - // - // Always reads to the end of the string (so you can read the - // next piece of data waiting). - // - // If bLine is true, it stops when it reaches a '\n' or a null-terminator. - // - // pStr is always null-terminated (unless bufLen is 0). - // - // pOutN m_pBufferEnd ) - { - SetOverflowFlag(); - m_nInBufWord = 0; - } - else - { - Assert( reinterpret_cast(m_pDataIn) + 3 < reinterpret_cast(m_pBufferEnd)); - m_nInBufWord = LittleDWord( *( m_pDataIn++ ) ); - } -} - -FORCEINLINE void CBitRead::FetchNext( void ) -{ - m_nBitsAvail = 32; - GrabNextDWord( false ); -} - -int CBitRead::ReadOneBit( void ) -{ - int nRet = m_nInBufWord & 1; - if ( --m_nBitsAvail == 0 ) - { - FetchNext(); - } - else - m_nInBufWord >>= 1; - return nRet; -} - - -unsigned int CBitRead::ReadUBitLong( int numbits ) -{ - if ( m_nBitsAvail >= numbits ) - { - unsigned int nRet = m_nInBufWord & s_nMaskTable[ numbits ]; - m_nBitsAvail -= numbits; - if ( m_nBitsAvail ) - { - m_nInBufWord >>= numbits; - } - else - { - FetchNext(); - } - return nRet; - } - else - { - // need to merge words - unsigned int nRet = m_nInBufWord; - numbits -= m_nBitsAvail; - GrabNextDWord( true ); - if ( m_bOverflow ) - return 0; - nRet |= ( ( m_nInBufWord & s_nMaskTable[numbits] ) << m_nBitsAvail ); - m_nBitsAvail = 32 - numbits; - m_nInBufWord >>= numbits; - return nRet; - } -} - -FORCEINLINE unsigned int CBitRead::PeekUBitLong( int numbits ) -{ - int nSaveBA = m_nBitsAvail; - int nSaveW = m_nInBufWord; - uint32 const *pSaveP = m_pDataIn; - unsigned int nRet = ReadUBitLong( numbits ); - m_nBitsAvail = nSaveBA; - m_nInBufWord = nSaveW; - m_pDataIn = pSaveP; - return nRet; -} - -FORCEINLINE int CBitRead::ReadSBitLong( int numbits ) -{ - int nRet = ReadUBitLong( numbits ); - // sign extend - return ( nRet << ( 32 - numbits ) ) >> ( 32 - numbits ); -} - -FORCEINLINE int CBitRead::ReadLong( void ) -{ - return ( int ) ReadUBitLong( sizeof(long) << 3 ); -} - -FORCEINLINE float CBitRead::ReadFloat( void ) -{ - uint32 nUval = ReadUBitLong( sizeof(long) << 3 ); - return * ( ( float * ) &nUval ); -} - -#ifdef _WIN32 -#pragma warning(push) -#pragma warning(disable : 4715) // disable warning on not all cases - // returning a value. throwing default: - // in measurably reduces perf in bit - // packing benchmark -#endif -FORCEINLINE unsigned int CBitRead::ReadUBitVar( void ) -{ - switch( ReadUBitLong( 2 ) ) - { - case 0: - return ReadUBitLong( 4 ); - - case 1: - return ReadUBitLong( 8 ); - - case 2: - return ReadUBitLong( 12 ); - - case 3: - return ReadUBitLong( 32 ); - } -} -#ifdef _WIN32 -#pragma warning(pop) -#endif - -FORCEINLINE float CBitRead::ReadBitFloat( void ) -{ - uint32 nvalue = ReadUBitLong( 32 ); - return *( ( float * ) &nvalue ); -} - -int CBitRead::ReadChar( void ) -{ - return ReadSBitLong(sizeof(char) << 3); -} - -int CBitRead::ReadByte( void ) -{ - return ReadUBitLong(sizeof(unsigned char) << 3); -} - -int CBitRead::ReadShort( void ) -{ - return ReadSBitLong(sizeof(short) << 3); -} - -int CBitRead::ReadWord( void ) -{ - return ReadUBitLong(sizeof(unsigned short) << 3); -} - -#define WRAP_READ( bc ) \ -class bf_read : public bc \ -{ \ -public: \ - FORCEINLINE bf_read( void ) : bc( ) \ - { \ - } \ - \ - FORCEINLINE bf_read( const void *pData, int nBytes, int nBits = -1 ) : bc( pData, nBytes, nBits ) \ - { \ - } \ - \ - FORCEINLINE bf_read( const char *pDebugName, const void *pData, int nBytes, int nBits = -1 ) : bc( pDebugName, pData, nBytes, nBits ) \ - { \ - } \ -}; - -#define WRAP_WRITE( bc ) \ -class bf_write : public bc \ -{ \ -public: \ - FORCEINLINE bf_write(void) : bc() \ - { \ - } \ - FORCEINLINE bf_write( void *pData, int nBytes, int nMaxBits = -1 ) : bc( pData, nBytes, nMaxBits ) \ - { \ - } \ - \ - FORCEINLINE bf_write( const char *pDebugName, void *pData, int nBytes, int nMaxBits = -1 ) : bc( pDebugName, pData, nBytes, nMaxBits ) \ - { \ - } \ -}; -#if 0 - - -#define DELEGATE0( t, m ) t m() \ -{ \ - Check(); \ - t nOld = old1.m(); \ - t nNew = new1.m(); \ - Assert( nOld == nNew ); \ - Check(); \ - return nOld; \ -} -#define DELEGATE1( t, m, t1 ) t m( t1 x) \ -{ \ - Check(); \ - t nOld = old1.m( x); \ - t nNew = new1.m( x ); \ - Assert( nOld == nNew ); \ - Check(); \ - return nOld; \ -} - -#define DELEGATE0I( m ) DELEGATE0( int, m ) -#define DELEGATE0LL( m ) DELEGATE0( int64, m ) - -class bf_read -{ - old_bf_read old1; - CBitRead new1; - - void Check( void ) const - { - int n=new1.GetNumBitsRead(); - int o=old1.GetNumBitsRead(); - Assert( n == o ); - Assert( old1.IsOverflowed() == new1.IsOverflowed() ); - } - -public: - FORCEINLINE bf_read( void ) : old1(), new1() - { - } - - FORCEINLINE bf_read( const void *pData, int nBytes, int nBits = -1 ) : old1( pData, nBytes, nBits ),new1( pData, nBytes, nBits ) - { - } - - FORCEINLINE bf_read( const char *pDebugName, const void *pData, int nBytes, int nBits = -1 ) : old1( pDebugName, pData, nBytes, nBits ), new1( pDebugName, pData, nBytes, nBits ) - { - } - - FORCEINLINE bool IsOverflowed( void ) const - { - bool bOld = old1.IsOverflowed(); - bool bNew = new1.IsOverflowed(); - Assert( bOld == bNew ); - Check(); - return bOld; - - } - - void ReadBits(void *pOut, int nBits) - { - old1.ReadBits( pOut, nBits ); - void *mem=stackalloc( 1+ ( nBits / 8 ) ); - new1.ReadBits( mem, nBits ); - Assert( memcmp( mem, pOut, nBits / 8 ) == 0 ); - } - - bool ReadBytes(void *pOut, int nBytes) - { - ReadBits(pOut, nBytes << 3); - return ! IsOverflowed(); - } - - - unsigned int ReadUBitLong( int numbits ) - { - unsigned int nOld = old1.ReadUBitLong( numbits ); - unsigned int nNew = new1.ReadUBitLong( numbits ); - Assert( nOld == nNew ); - Check(); - return nOld; - } - - unsigned const char* GetBasePointer() - { - Assert( old1.GetBasePointer() == new1.GetBasePointer() ); - Check(); - return old1.GetBasePointer(); - } - void SetDebugName( const char *pDebugName ) - { - old1.SetDebugName( pDebugName ); - new1.SetDebugName( pDebugName ); - Check(); - } - - void StartReading( const void *pData, int nBytes, int iStartBit = 0, int nBits = -1 ) - { - old1.StartReading( pData, nBytes, iStartBit, nBits ); - new1.StartReading( pData, nBytes, iStartBit, nBits ); - Check(); - } - - void SetAssertOnOverflow( bool bAssert ) - { - old1.SetAssertOnOverflow( bAssert ); -// new1.SetAssertOnOverflow( bAssert ); - Check(); - } - - DELEGATE0I( ReadOneBit ); - DELEGATE0I( ReadByte ); - DELEGATE0I( ReadWord ); - DELEGATE0I( ReadLong ); - DELEGATE0I( GetNumBytesLeft ); - DELEGATE0I( ReadShort ); - DELEGATE1( int, PeekUBitLong, int ); - DELEGATE0I( ReadChar ); - DELEGATE0I( GetNumBitsRead ); - DELEGATE0LL( ReadLongLong ); - DELEGATE0( float, ReadFloat); - DELEGATE0( unsigned int, ReadUBitVar ); - DELEGATE0( float, ReadBitCoord); - DELEGATE2( float, ReadBitCoordMP, bool, bool ); - DELEGATE0( float, ReadBitFloat); - DELEGATE0( float, ReadBitNormal); - DELEGATE1( bool,Seek, int ); - DELEGATE1( float, ReadBitAngle, int ); - DELEGATE1( bool,SeekRelative,int); - DELEGATE0I( GetNumBitsLeft ); - DELEGATE0I( TotalBytesAvailable ); - - void SetOverflowFlag() - { - old1.SetOverflowFlag(); - new1.SetOverflowFlag(); - Check(); - } - - bool ReadString( char *pStr, int bufLen, bool bLine=false, int *pOutNumChars=NULL ) - { - Check(); - int oldn, newn; - bool bOld = old1.ReadString( pStr, bufLen, bLine, &oldn ); - bool bNew = new1.ReadString( pStr, bufLen, bLine, &newn ); - Assert( bOld == bNew ); - Assert( oldn == newn ); - if ( pOutNumChars ) - *pOutNumChars = oldn; - Check(); - return bOld; - } - - void ReadBitVec3Coord( Vector& fa ) - { - Check(); - old1.ReadBitVec3Coord( fa ); - Vector test; - new1.ReadBitVec3Coord( test ); - Assert( VectorsAreEqual( fa, test )); - Check(); - } - void ReadBitVec3Normal( Vector& fa ) - { - Check(); - old1.ReadBitVec3Coord( fa ); - Vector test; - new1.ReadBitVec3Coord( test ); - Assert( VectorsAreEqual( fa, test )); - Check(); - } - - char* ReadAndAllocateString( bool *pOverflow = NULL ) - { - Check(); - bool bold, bnew; - char *pold = old1.ReadAndAllocateString( &bold ); - char *pnew = new1.ReadAndAllocateString( &bnew ); - Assert( bold == bnew ); - Assert(strcmp( pold, pnew ) == 0 ); - delete[] pnew; - Check(); - if ( pOverflow ) - *pOverflow = bold; - return pold; - - } - - DELEGATE1( int, ReadSBitLong, int ); - -}; -#endif - - -#ifdef _LINUX -WRAP_READ( old_bf_read ); -#else -WRAP_READ( CBitRead ); -#endif -WRAP_WRITE( old_bf_write ); - - -#endif - - - diff --git a/Resources/NetHook/tier1/byteswap.cpp b/Resources/NetHook/tier1/byteswap.cpp deleted file mode 100644 index e43f5da5..00000000 --- a/Resources/NetHook/tier1/byteswap.cpp +++ /dev/null @@ -1,90 +0,0 @@ -//========= Copyright © 1996-2006, Valve LLC, All rights reserved. ============ -// -// Purpose: Low level byte swapping routines. -// -// $NoKeywords: $ -//============================================================================= - -#include "byteswap.h" - -//----------------------------------------------------------------------------- -// Copy a single field from the input buffer to the output buffer, swapping the bytes if necessary -//----------------------------------------------------------------------------- -void CByteswap::SwapFieldToTargetEndian( void* pOutputBuffer, void *pData, typedescription_t *pField ) -{ - switch ( pField->fieldType ) - { - case FIELD_CHARACTER: - SwapBufferToTargetEndian( (char*)pOutputBuffer, (char*)pData, pField->fieldSize ); - break; - - case FIELD_BOOLEAN: - SwapBufferToTargetEndian( (bool*)pOutputBuffer, (bool*)pData, pField->fieldSize ); - break; - - case FIELD_SHORT: - SwapBufferToTargetEndian( (short*)pOutputBuffer, (short*)pData, pField->fieldSize ); - break; - - case FIELD_FLOAT: - SwapBufferToTargetEndian( (uint*)pOutputBuffer, (uint*)pData, pField->fieldSize ); - break; - - case FIELD_INTEGER: - SwapBufferToTargetEndian( (int*)pOutputBuffer, (int*)pData, pField->fieldSize ); - break; - - case FIELD_VECTOR: - SwapBufferToTargetEndian( (uint*)pOutputBuffer, (uint*)pData, pField->fieldSize * 3 ); - break; - - case FIELD_VECTOR2D: - SwapBufferToTargetEndian( (uint*)pOutputBuffer, (uint*)pData, pField->fieldSize * 2 ); - break; - - case FIELD_QUATERNION: - SwapBufferToTargetEndian( (uint*)pOutputBuffer, (uint*)pData, pField->fieldSize * 4 ); - break; - - case FIELD_EMBEDDED: - { - typedescription_t *pEmbed = pField->td->dataDesc; - for ( int i = 0; i < pField->fieldSize; ++i ) - { - SwapFieldsToTargetEndian( (byte*)pOutputBuffer + pEmbed->fieldOffset[ TD_OFFSET_NORMAL ], - (byte*)pData + pEmbed->fieldOffset[ TD_OFFSET_NORMAL ], - pField->td ); - - pOutputBuffer = (byte*)pOutputBuffer + pField->fieldSizeInBytes; - pData = (byte*)pData + pField->fieldSizeInBytes; - } - } - break; - - default: - assert(0); - } -} - -//----------------------------------------------------------------------------- -// Write a block of fields. Works a bit like the saverestore code. -//----------------------------------------------------------------------------- -void CByteswap::SwapFieldsToTargetEndian( void *pOutputBuffer, void *pBaseData, datamap_t *pDataMap ) -{ - // deal with base class first - if ( pDataMap->baseMap ) - { - SwapFieldsToTargetEndian( pOutputBuffer, pBaseData, pDataMap->baseMap ); - } - - typedescription_t *pFields = pDataMap->dataDesc; - int fieldCount = pDataMap->dataNumFields; - for ( int i = 0; i < fieldCount; ++i ) - { - typedescription_t *pField = &pFields[i]; - SwapFieldToTargetEndian( (BYTE*)pOutputBuffer + pField->fieldOffset[ TD_OFFSET_NORMAL ], - (BYTE*)pBaseData + pField->fieldOffset[ TD_OFFSET_NORMAL ], - pField ); - } -} - diff --git a/Resources/NetHook/tier1/byteswap.h b/Resources/NetHook/tier1/byteswap.h deleted file mode 100644 index 253ae4fd..00000000 --- a/Resources/NetHook/tier1/byteswap.h +++ /dev/null @@ -1,249 +0,0 @@ -//========= Copyright © 1996-2006, Valve LLC, All rights reserved. ============ -// -// Purpose: Low level byte swapping routines. -// -// $NoKeywords: $ -//============================================================================= -#ifndef BYTESWAP_H -#define BYTESWAP_H -#if defined(_WIN32) -#pragma once -#endif - -#include "datamap.h" // Needed for typedescription_t. Note datamap.h is tier1 as well. - -class CByteswap -{ -public: - CByteswap() - { - // Default behavior sets the target endian to match the machine native endian (no swap). - SetTargetBigEndian( IsMachineBigEndian() ); - } - - //----------------------------------------------------------------------------- - // Write a single field. - //----------------------------------------------------------------------------- - void SwapFieldToTargetEndian( void* pOutputBuffer, void *pData, typedescription_t *pField ); - - //----------------------------------------------------------------------------- - // Write a block of fields. Works a bit like the saverestore code. - //----------------------------------------------------------------------------- - void SwapFieldsToTargetEndian( void *pOutputBuffer, void *pBaseData, datamap_t *pDataMap ); - - // Swaps fields for the templated type to the output buffer. - template inline void SwapFieldsToTargetEndian( T* pOutputBuffer, void *pBaseData, unsigned int objectCount = 1 ) - { - for ( unsigned int i = 0; i < objectCount; ++i, ++pOutputBuffer ) - { - SwapFieldsToTargetEndian( (void*)pOutputBuffer, pBaseData, &T::m_DataMap ); - pBaseData = (byte*)pBaseData + sizeof(T); - } - } - - // Swaps fields for the templated type in place. - template inline void SwapFieldsToTargetEndian( T* pOutputBuffer, unsigned int objectCount = 1 ) - { - SwapFieldsToTargetEndian( pOutputBuffer, (void*)pOutputBuffer, objectCount ); - } - - //----------------------------------------------------------------------------- - // True if the current machine is detected as big endian. - // (Endienness is effectively detected at compile time when optimizations are - // enabled) - //----------------------------------------------------------------------------- - static bool IsMachineBigEndian() - { - short nIsBigEndian = 1; - - // if we are big endian, the first byte will be a 0, if little endian, it will be a one. - return (bool)(0 == *(char *)&nIsBigEndian ); - } - - //----------------------------------------------------------------------------- - // Sets the target byte ordering we are swapping to or from. - // - // Braindead Endian Reference: - // x86 is LITTLE Endian - // PowerPC is BIG Endian - //----------------------------------------------------------------------------- - inline void SetTargetBigEndian( bool bigEndian ) - { - m_bBigEndian = bigEndian; - m_bSwapBytes = IsMachineBigEndian() != bigEndian; - } - - // Changes target endian - inline void FlipTargetEndian( void ) - { - m_bSwapBytes = !m_bSwapBytes; - m_bBigEndian = !m_bBigEndian; - } - - // Forces byte swapping state, regardless of endianess - inline void ActivateByteSwapping( bool bActivate ) - { - SetTargetBigEndian( IsMachineBigEndian() != bActivate ); - } - - //----------------------------------------------------------------------------- - // Returns true if the target machine is the same as this one in endianness. - // - // Used to determine when a byteswap needs to take place. - //----------------------------------------------------------------------------- - inline bool IsSwappingBytes( void ) // Are bytes being swapped? - { - return m_bSwapBytes; - } - - inline bool IsTargetBigEndian( void ) // What is the current target endian? - { - return m_bBigEndian; - } - - //----------------------------------------------------------------------------- - // IsByteSwapped() - // - // When supplied with a chunk of input data and a constant or magic number - // (in native format) determines the endienness of the current machine in - // relation to the given input data. - // - // Returns: - // 1 if input is the same as nativeConstant. - // 0 if input is byteswapped relative to nativeConstant. - // -1 if input is not the same as nativeConstant and not byteswapped either. - // - // ( This is useful for detecting byteswapping in magic numbers in structure - // headers for example. ) - //----------------------------------------------------------------------------- - template inline int SourceIsNativeEndian( T input, T nativeConstant ) - { - // If it's the same, it isn't byteswapped: - if( input == nativeConstant ) - return 1; - - int output; - LowLevelByteSwap( &output, &input ); - if( output == nativeConstant ) - return 0; - - assert( 0 ); // if we get here, input is neither a swapped nor unswapped version of nativeConstant. - return -1; - } - - //----------------------------------------------------------------------------- - // Swaps an input buffer full of type T into the given output buffer. - // - // Swaps [count] items from the inputBuffer to the outputBuffer. - // If inputBuffer is omitted or NULL, then it is assumed to be the same as - // outputBuffer - effectively swapping the contents of the buffer in place. - //----------------------------------------------------------------------------- - template inline void SwapBuffer( T* outputBuffer, T* inputBuffer = NULL, int count = 1 ) - { - assert( count >= 0 ); - assert( outputBuffer ); - - // Fail gracefully in release: - if( count <=0 || !outputBuffer ) - return; - - // Optimization for the case when we are swapping in place. - if( inputBuffer == NULL ) - { - inputBuffer = outputBuffer; - } - - // Swap everything in the buffer: - for( int i = 0; i < count; i++ ) - { - LowLevelByteSwap( &outputBuffer[i], &inputBuffer[i] ); - } - } - - //----------------------------------------------------------------------------- - // Swaps an input buffer full of type T into the given output buffer. - // - // Swaps [count] items from the inputBuffer to the outputBuffer. - // If inputBuffer is omitted or NULL, then it is assumed to be the same as - // outputBuffer - effectively swapping the contents of the buffer in place. - //----------------------------------------------------------------------------- - template inline void SwapBufferToTargetEndian( T* outputBuffer, T* inputBuffer = NULL, int count = 1 ) - { - assert( count >= 0 ); - assert( outputBuffer ); - - // Fail gracefully in release: - if( count <=0 || !outputBuffer ) - return; - - // Optimization for the case when we are swapping in place. - if( inputBuffer == NULL ) - { - inputBuffer = outputBuffer; - } - - // Are we already the correct endienness? ( or are we swapping 1 byte items? ) - if( !m_bSwapBytes || ( sizeof(T) == 1 ) ) - { - // If we were just going to swap in place then return. - if( !inputBuffer ) - return; - - // Otherwise copy the inputBuffer to the outputBuffer: - memcpy( outputBuffer, inputBuffer, count * sizeof( T ) ); - return; - - } - - // Swap everything in the buffer: - for( int i = 0; i < count; i++ ) - { - LowLevelByteSwap( &outputBuffer[i], &inputBuffer[i] ); - } - } - -private: - //----------------------------------------------------------------------------- - // The lowest level byte swapping workhorse of doom. output always contains the - // swapped version of input. ( Doesn't compare machine to target endianness ) - //----------------------------------------------------------------------------- - template static void LowLevelByteSwap( T *output, T *input ) - { - T temp = *output; -#if defined( _X360 ) - // Intrinsics need the source type to be fixed-point - DWORD* word = (DWORD*)input; - switch( sizeof(T) ) - { - case 8: - { - __storewordbytereverse( *word, 0, &temp ); - __storewordbytereverse( *(word+1), 4, &temp ); - } - break; - - case 4: - __storewordbytereverse( *word, 0, &temp ); - break; - - case 2: - __storeshortbytereverse( *input, 0, &temp ); - break; - - default: - Assert( "Invalid size in CByteswap::LowLevelByteSwap" && 0 ); - } -#else - for( int i = 0; i < sizeof(T); i++ ) - { - ((unsigned char* )&temp)[i] = ((unsigned char*)input)[sizeof(T)-(i+1)]; - } -#endif - Q_memcpy( output, &temp, sizeof(T) ); - } - - unsigned int m_bSwapBytes : 1; - unsigned int m_bBigEndian : 1; -}; - -#endif /* !BYTESWAP_H */ diff --git a/Resources/NetHook/tier1/callqueue.h b/Resources/NetHook/tier1/callqueue.h deleted file mode 100644 index 4a385b28..00000000 --- a/Resources/NetHook/tier1/callqueue.h +++ /dev/null @@ -1,203 +0,0 @@ -//========== Copyright © 2006, Valve Corporation, All rights reserved. ======== -// -// Purpose: -// -//============================================================================= - -#ifndef CALLQUEUE_H -#define CALLQUEUE_H - -#include "tier0/tslist.h" -#include "functors.h" - -#if defined( _WIN32 ) -#pragma once -#endif - -//----------------------------------------------------- -// Avert thy eyes! Imagine rather: -// -// void QueueCall( , [args1, [arg2,]...] -// void QueueCall( , , [args1, [arg2,]...] -// void QueueRefCall( , <, [args1, [arg2,]...] -//----------------------------------------------------- - -#define DEFINE_CALLQUEUE_NONMEMBER_QUEUE_CALL(N) \ - template \ - void QueueCall(FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - QueueFunctorInternal( CreateFunctor( pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \ - } - -//------------------------------------- - -#define DEFINE_CALLQUEUE_MEMBER_QUEUE_CALL(N) \ - template \ - void QueueCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - QueueFunctorInternal( CreateFunctor( pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \ - } - -//------------------------------------- - -#define DEFINE_CALLQUEUE_CONST_MEMBER_QUEUE_CALL(N) \ - template \ - void QueueCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - QueueFunctorInternal( CreateFunctor( pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \ - } - -//------------------------------------- - -#define DEFINE_CALLQUEUE_REF_COUNTING_MEMBER_QUEUE_CALL(N) \ - template \ - void QueueRefCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - QueueFunctorInternal( CreateRefCountingFunctor( pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \ - } - -//------------------------------------- - -#define DEFINE_CALLQUEUE_REF_COUNTING_CONST_MEMBER_QUEUE_CALL(N) \ - template \ - void QueueRefCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - QueueFunctorInternal( CreateRefCountingFunctor( pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \ - \ - } - -#define FUNC_GENERATE_QUEUE_METHODS() \ - FUNC_GENERATE_ALL( DEFINE_CALLQUEUE_NONMEMBER_QUEUE_CALL ); \ - FUNC_GENERATE_ALL( DEFINE_CALLQUEUE_MEMBER_QUEUE_CALL ); \ - FUNC_GENERATE_ALL( DEFINE_CALLQUEUE_CONST_MEMBER_QUEUE_CALL );\ - FUNC_GENERATE_ALL( DEFINE_CALLQUEUE_REF_COUNTING_MEMBER_QUEUE_CALL ); \ - FUNC_GENERATE_ALL( DEFINE_CALLQUEUE_REF_COUNTING_CONST_MEMBER_QUEUE_CALL ) - -//----------------------------------------------------- - -template > -class CCallQueueT -{ -public: - CCallQueueT() - : m_bNoQueue( false ) - { -#ifdef _DEBUG - m_nCurSerialNumber = 0; - m_nBreakSerialNumber = (unsigned)-1; -#endif - } - - void DisableQueue( bool bDisable ) - { - if ( m_bNoQueue == bDisable ) - { - return; - } - if ( !m_bNoQueue ) - CallQueued(); - - m_bNoQueue = bDisable; - } - - bool IsDisabled() const - { - return m_bNoQueue; - } - - int Count() - { - return m_queue.Count(); - } - - void CallQueued() - { - if ( !m_queue.Count() ) - { - return; - } - - m_queue.PushItem( NULL ); - - CFunctor *pFunctor; - - while ( m_queue.PopItem( &pFunctor ) && pFunctor != NULL ) - { -#ifdef _DEBUG - if ( pFunctor->m_nUserID == m_nBreakSerialNumber) - { - m_nBreakSerialNumber = (unsigned)-1; - } -#endif - (*pFunctor)(); - pFunctor->Release(); - } - - } - - void QueueFunctor( CFunctor *pFunctor ) - { - Assert( pFunctor ); - QueueFunctorInternal( RetAddRef( pFunctor ) ); - } - - void Flush() - { - m_queue.PushItem( NULL ); - - CFunctor *pFunctor; - - while ( m_queue.PopItem( &pFunctor ) && pFunctor != NULL ) - { - pFunctor->Release(); - } - } - - FUNC_GENERATE_QUEUE_METHODS(); - -private: - void QueueFunctorInternal( CFunctor *pFunctor ) - { - if ( !m_bNoQueue ) - { -#ifdef _DEBUG - pFunctor->m_nUserID = m_nCurSerialNumber++; -#endif - m_queue.PushItem( pFunctor ); - } - else - { - (*pFunctor)(); - pFunctor->Release(); - } - } - - QUEUE_TYPE m_queue; - bool m_bNoQueue; - unsigned m_nCurSerialNumber; - unsigned m_nBreakSerialNumber; -}; - -class CCallQueue : public CCallQueueT<> -{ -}; - -//----------------------------------------------------- -// Optional interface that can be bound to concrete CCallQueue -//----------------------------------------------------- - -class ICallQueue -{ -public: - void QueueFunctor( CFunctor *pFunctor ) - { - QueueFunctorInternal( RetAddRef( pFunctor ) ); - } - - FUNC_GENERATE_QUEUE_METHODS(); - -private: - virtual void QueueFunctorInternal( CFunctor *pFunctor ) = 0; -}; - -#endif // CALLQUEUE_H diff --git a/Resources/NetHook/tier1/characterset.cpp b/Resources/NetHook/tier1/characterset.cpp deleted file mode 100644 index 0fa3fced..00000000 --- a/Resources/NetHook/tier1/characterset.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// -//----------------------------------------------------------------------------- -// $Log: $ -// -// $NoKeywords: $ -//============================================================================= - -#include -#include "characterset.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -//----------------------------------------------------------------------------- -// Purpose: builds a simple lookup table of a group of important characters -// Input : *pParseGroup - pointer to the buffer for the group -// *pGroupString - null terminated list of characters to flag -//----------------------------------------------------------------------------- -void CharacterSetBuild( characterset_t *pSetBuffer, const char *pszSetString ) -{ - int i = 0; - - // Test our pointers - if ( !pSetBuffer || !pszSetString ) - return; - - memset( pSetBuffer->set, 0, sizeof(pSetBuffer->set) ); - - while ( pszSetString[i] ) - { - pSetBuffer->set[ pszSetString[i] ] = 1; - i++; - } - -} diff --git a/Resources/NetHook/tier1/characterset.h b/Resources/NetHook/tier1/characterset.h deleted file mode 100644 index 53734a27..00000000 --- a/Resources/NetHook/tier1/characterset.h +++ /dev/null @@ -1,43 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: Shared code for parsing / searching for characters in a string -// using lookup tables -// -// $Workfile: $ -// $Date: $ -// $NoKeywords: $ -//===========================================================================// - -#ifndef CHARACTERSET_H -#define CHARACTERSET_H - -#ifdef _WIN32 -#pragma once -#endif - - -struct characterset_t -{ - char set[256]; -}; - - -// This is essentially a strpbrk() using a precalculated lookup table -//----------------------------------------------------------------------------- -// Purpose: builds a simple lookup table of a group of important characters -// Input : *pSetBuffer - pointer to the buffer for the group -// *pSetString - list of characters to flag -//----------------------------------------------------------------------------- -extern void CharacterSetBuild( characterset_t *pSetBuffer, const char *pSetString ); - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *pSetBuffer - pre-build group buffer -// character - character to lookup -// Output : int - 1 if the character was in the set -//----------------------------------------------------------------------------- -#define IN_CHARACTERSET( SetBuffer, character ) ((SetBuffer).set[(character)]) - - -#endif // CHARACTERSET_H diff --git a/Resources/NetHook/tier1/checksum_crc.cpp b/Resources/NetHook/tier1/checksum_crc.cpp deleted file mode 100644 index 3e0f20d4..00000000 --- a/Resources/NetHook/tier1/checksum_crc.cpp +++ /dev/null @@ -1,180 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Generic CRC functions -// -//=============================================================================// - -#include "basetypes.h" -#include "commonmacros.h" -#include "checksum_crc.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -#define CRC32_INIT_VALUE 0xFFFFFFFFUL -#define CRC32_XOR_VALUE 0xFFFFFFFFUL - -#define NUM_BYTES 256 -static const CRC32_t pulCRCTable[NUM_BYTES] = -{ - 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 -}; - -void CRC32_Init(CRC32_t *pulCRC) -{ - *pulCRC = CRC32_INIT_VALUE; -} - -void CRC32_Final(CRC32_t *pulCRC) -{ - *pulCRC ^= CRC32_XOR_VALUE; -} - -CRC32_t CRC32_GetTableEntry( unsigned int slot ) -{ - return pulCRCTable[(unsigned char)slot]; -} - -void CRC32_ProcessBuffer(CRC32_t *pulCRC, const void *pBuffer, int nBuffer) -{ - CRC32_t ulCrc = *pulCRC; - unsigned char *pb = (unsigned char *)pBuffer; - unsigned int nFront; - int nMain; - -JustAfew: - - switch (nBuffer) - { - case 7: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - - case 6: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - - case 5: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - - case 4: - ulCrc ^= LittleLong( *(CRC32_t *)pb ); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - *pulCRC = ulCrc; - return; - - case 3: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - - case 2: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - - case 1: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - - case 0: - *pulCRC = ulCrc; - return; - } - - // We may need to do some alignment work up front, and at the end, so that - // the main loop is aligned and only has to worry about 8 byte at a time. - // - // The low-order two bits of pb and nBuffer in total control the - // upfront work. - // - nFront = ((unsigned int)pb) & 3; - nBuffer -= nFront; - switch (nFront) - { - case 3: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - case 2: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - case 1: - ulCrc = pulCRCTable[*pb++ ^ (unsigned char)ulCrc] ^ (ulCrc >> 8); - } - - nMain = nBuffer >> 3; - while (nMain--) - { - ulCrc ^= LittleLong( *(CRC32_t *)pb ); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc ^= LittleLong( *(CRC32_t *)(pb + 4) ); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - ulCrc = pulCRCTable[(unsigned char)ulCrc] ^ (ulCrc >> 8); - pb += 8; - } - - nBuffer &= 7; - goto JustAfew; -} diff --git a/Resources/NetHook/tier1/checksum_crc.h b/Resources/NetHook/tier1/checksum_crc.h deleted file mode 100644 index 3f6e9ec1..00000000 --- a/Resources/NetHook/tier1/checksum_crc.h +++ /dev/null @@ -1,31 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Generic CRC functions -// -// $NoKeywords: $ -//=============================================================================// -#ifndef CHECKSUM_CRC_H -#define CHECKSUM_CRC_H -#ifdef _WIN32 -#pragma once -#endif - -typedef unsigned long CRC32_t; - -void CRC32_Init( CRC32_t *pulCRC ); -void CRC32_ProcessBuffer( CRC32_t *pulCRC, const void *p, int len ); -void CRC32_Final( CRC32_t *pulCRC ); -CRC32_t CRC32_GetTableEntry( unsigned int slot ); - -inline CRC32_t CRC32_ProcessSingleBuffer( const void *p, int len ) -{ - CRC32_t crc; - - CRC32_Init( &crc ); - CRC32_ProcessBuffer( &crc, p, len ); - CRC32_Final( &crc ); - - return crc; -} - -#endif // CHECKSUM_CRC_H diff --git a/Resources/NetHook/tier1/checksum_md5.cpp b/Resources/NetHook/tier1/checksum_md5.cpp deleted file mode 100644 index d41f1de2..00000000 --- a/Resources/NetHook/tier1/checksum_md5.cpp +++ /dev/null @@ -1,271 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -#include "basetypes.h" -#include "commonmacros.h" -#include "checksum_md5.h" -#include -#include -#include "tier1/strtools.h" -#include "tier0/dbg.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -// The four core functions - F1 is optimized somewhat -// #define F1(x, y, z) (x & y | ~x & z) -#define F1(x, y, z) (z ^ (x & (y ^ z))) -#define F2(x, y, z) F1(z, x, y) -#define F3(x, y, z) (x ^ y ^ z) -#define F4(x, y, z) (y ^ (x | ~z)) - -// This is the central step in the MD5 algorithm. -#define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) - -//----------------------------------------------------------------------------- -// Purpose: The core of the MD5 algorithm, this alters an existing MD5 hash to -// reflect the addition of 16 longwords of new data. MD5Update blocks -// the data and converts bytes into longwords for this routine. -// Input : buf[4] - -// in[16] - -// Output : static void -//----------------------------------------------------------------------------- -static void MD5Transform(unsigned int buf[4], unsigned int const in[16]) -{ - register unsigned int a, b, c, d; - - a = buf[0]; - b = buf[1]; - c = buf[2]; - d = buf[3]; - - MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); - MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); - MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); - MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); - MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); - MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - - MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); - MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); - MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); - MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - - MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); - MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); - MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); - MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); - MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); - MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - - MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); - MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); - MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); - MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); - MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); - MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); - - buf[0] += a; - buf[1] += b; - buf[2] += c; - buf[3] += d; -} - -//----------------------------------------------------------------------------- -// Purpose: Start MD5 accumulation. Set bit count to 0 and buffer to mysterious initialization constants. - -// Input : *ctx - -//----------------------------------------------------------------------------- -void MD5Init(MD5Context_t *ctx) -{ - ctx->buf[0] = 0x67452301; - ctx->buf[1] = 0xefcdab89; - ctx->buf[2] = 0x98badcfe; - ctx->buf[3] = 0x10325476; - - ctx->bits[0] = 0; - ctx->bits[1] = 0; -} - -//----------------------------------------------------------------------------- -// Purpose: Update context to reflect the concatenation of another buffer full of bytes. -// Input : *ctx - -// *buf - -// len - -//----------------------------------------------------------------------------- -void MD5Update(MD5Context_t *ctx, unsigned char const *buf, unsigned int len) -{ - unsigned int t; - - /* Update bitcount */ - - t = ctx->bits[0]; - if ((ctx->bits[0] = t + ((unsigned int) len << 3)) < t) - ctx->bits[1]++; /* Carry from low to high */ - ctx->bits[1] += len >> 29; - - t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ - - /* Handle any leading odd-sized chunks */ - - if (t) - { - unsigned char *p = (unsigned char *) ctx->in + t; - - t = 64 - t; - if (len < t) - { - memcpy(p, buf, len); - return; - } - memcpy(p, buf, t); - //byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (unsigned int *) ctx->in); - buf += t; - len -= t; - } - /* Process data in 64-byte chunks */ - - while (len >= 64) - { - memcpy(ctx->in, buf, 64); - //byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (unsigned int *) ctx->in); - buf += 64; - len -= 64; - } - - /* Handle any remaining bytes of data. */ - memcpy(ctx->in, buf, len); -} - -//----------------------------------------------------------------------------- -// Purpose: Final wrapup - pad to 64-byte boundary with the bit pattern -// 1 0* (64-bit count of bits processed, MSB-first) -// Input : digest[MD5_DIGEST_LENGTH] - -// *ctx - -//----------------------------------------------------------------------------- -void MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5Context_t *ctx) -{ - unsigned count; - unsigned char *p; - - /* Compute number of bytes mod 64 */ - count = (ctx->bits[0] >> 3) & 0x3F; - - /* Set the first char of padding to 0x80. This is safe since there is - always at least one byte free */ - p = ctx->in + count; - *p++ = 0x80; - - /* Bytes of padding needed to make 64 bytes */ - count = 64 - 1 - count; - - /* Pad out to 56 mod 64 */ - if (count < 8) - { - /* Two lots of padding: Pad the first block to 64 bytes */ - memset(p, 0, count); - //byteReverse(ctx->in, 16); - MD5Transform(ctx->buf, (unsigned int *) ctx->in); - - /* Now fill the next block with 56 bytes */ - memset(ctx->in, 0, 56); - } - else - { - /* Pad block to 56 bytes */ - memset(p, 0, count - 8); - } - //byteReverse(ctx->in, 14); - - /* Append length in bits and transform */ - ((unsigned int *) ctx->in)[14] = ctx->bits[0]; - ((unsigned int *) ctx->in)[15] = ctx->bits[1]; - - MD5Transform(ctx->buf, (unsigned int *) ctx->in); - //byteReverse((unsigned char *) ctx->buf, 4); - memcpy(digest, ctx->buf, MD5_DIGEST_LENGTH); - memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */ -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *hash - -// hashlen - -// Output : char -//----------------------------------------------------------------------------- -char *MD5_Print( unsigned char *hash, int hashlen ) -{ - static char szReturn[64]; - - Assert( hashlen <= 32 ); - - Q_binarytohex( hash, hashlen, szReturn, sizeof( szReturn ) ); - return szReturn; -} - -//----------------------------------------------------------------------------- -// Purpose: generate pseudo random number from a seed number -// Input : seed number -// Output : pseudo random number -//----------------------------------------------------------------------------- -unsigned int MD5_PseudoRandom(unsigned int nSeed) -{ - MD5Context_t ctx; - unsigned char digest[MD5_DIGEST_LENGTH]; // The MD5 Hash - - memset( &ctx, 0, sizeof( ctx ) ); - - MD5Init(&ctx); - MD5Update(&ctx, (unsigned char*)&nSeed, sizeof(nSeed) ); - MD5Final(digest, &ctx); - - return *(unsigned int*)(digest+6); // use 4 middle bytes for random value -} diff --git a/Resources/NetHook/tier1/checksum_md5.h b/Resources/NetHook/tier1/checksum_md5.h deleted file mode 100644 index 134d2b52..00000000 --- a/Resources/NetHook/tier1/checksum_md5.h +++ /dev/null @@ -1,33 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Generic MD5 hashing algo -// -//=============================================================================// - -#ifndef CHECKSUM_MD5_H -#define CHECKSUM_MD5_H - -#ifdef _WIN32 -#pragma once -#endif - -// 16 bytes == 128 bit digest -#define MD5_DIGEST_LENGTH 16 - -// MD5 Hash -typedef struct -{ - unsigned int buf[4]; - unsigned int bits[2]; - unsigned char in[64]; -} MD5Context_t; - -void MD5Init( MD5Context_t *context ); -void MD5Update( MD5Context_t *context, unsigned char const *buf, unsigned int len ); -void MD5Final( unsigned char digest[ MD5_DIGEST_LENGTH ], MD5Context_t *context ); - -char *MD5_Print(unsigned char *digest, int hashlen ); - -unsigned int MD5_PseudoRandom(unsigned int nSeed); - -#endif // CHECKSUM_MD5_H diff --git a/Resources/NetHook/tier1/commandbuffer.cpp b/Resources/NetHook/tier1/commandbuffer.cpp deleted file mode 100644 index a8f600a7..00000000 --- a/Resources/NetHook/tier1/commandbuffer.cpp +++ /dev/null @@ -1,636 +0,0 @@ -//===== Copyright © 1996-2006, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// $NoKeywords: $ -//===========================================================================// - -#include "tier1/CommandBuffer.h" -#include "tier1/utlbuffer.h" -#include "tier1/strtools.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -#define MAX_ALIAS_NAME 32 -#define MAX_COMMAND_LENGTH 1024 - -struct cmdalias_t -{ - cmdalias_t *next; - char name[ MAX_ALIAS_NAME ]; - char *value; -}; - - -//----------------------------------------------------------------------------- -// Constructor, destructor -//----------------------------------------------------------------------------- -CCommandBuffer::CCommandBuffer( ) : m_Commands( 32, 32 ) -{ - m_hNextCommand = m_Commands.InvalidIndex(); - m_nWaitDelayTicks = 1; - m_nCurrentTick = 0; - m_nLastTickToProcess = -1; - m_nArgSBufferSize = 0; - m_bIsProcessingCommands = false; - m_nMaxArgSBufferLength = ARGS_BUFFER_LENGTH; -} - -CCommandBuffer::~CCommandBuffer() -{ -} - - -//----------------------------------------------------------------------------- -// Indicates how long to delay when encoutering a 'wait' command -//----------------------------------------------------------------------------- -void CCommandBuffer::SetWaitDelayTime( int nTickDelay ) -{ - Assert( nTickDelay >= 0 ); - m_nWaitDelayTicks = nTickDelay; -} - - -//----------------------------------------------------------------------------- -// Specifies a max limit of the args buffer. For unittesting. Size == 0 means use default -//----------------------------------------------------------------------------- -void CCommandBuffer::LimitArgumentBufferSize( int nSize ) -{ - if ( nSize > ARGS_BUFFER_LENGTH ) - { - nSize = ARGS_BUFFER_LENGTH; - } - - m_nMaxArgSBufferLength = ( nSize == 0 ) ? ARGS_BUFFER_LENGTH : nSize; -} - - -//----------------------------------------------------------------------------- -// Parses argv0 out of the buffer -//----------------------------------------------------------------------------- -bool CCommandBuffer::ParseArgV0( CUtlBuffer &buf, char *pArgV0, int nMaxLen, const char **pArgS ) -{ - pArgV0[0] = 0; - *pArgS = NULL; - - if ( !buf.IsValid() ) - return false; - - int nSize = buf.ParseToken( CCommand::DefaultBreakSet(), pArgV0, nMaxLen ); - if ( ( nSize <= 0 ) || ( nMaxLen == nSize ) ) - return false; - - int nArgSLen = buf.TellMaxPut() - buf.TellGet(); - *pArgS = (nArgSLen > 0) ? (const char*)buf.PeekGet() : NULL; - return true; -} - - -//----------------------------------------------------------------------------- -// Insert a command into the command queue -//----------------------------------------------------------------------------- -void CCommandBuffer::InsertCommandAtAppropriateTime( int hCommand ) -{ - int i; - Command_t &command = m_Commands[hCommand]; - for ( i = m_Commands.Head(); i != m_Commands.InvalidIndex(); i = m_Commands.Next(i) ) - { - if ( m_Commands[i].m_nTick > command.m_nTick ) - break; - } - m_Commands.LinkBefore( i, hCommand ); -} - - -//----------------------------------------------------------------------------- -// Insert a command into the command queue at the appropriate time -//----------------------------------------------------------------------------- -void CCommandBuffer::InsertImmediateCommand( int hCommand ) -{ - m_Commands.LinkBefore( m_hNextCommand, hCommand ); -} - - -//----------------------------------------------------------------------------- -// Insert a command into the command queue -//----------------------------------------------------------------------------- -bool CCommandBuffer::InsertCommand( const char *pArgS, int nCommandSize, int nTick ) -{ - if ( nCommandSize >= CCommand::MaxCommandLength() ) - { - Warning( "WARNING: Command too long... ignoring!\n%s\n", pArgS ); - return false; - } - - // Add one for null termination - if ( m_nArgSBufferSize + nCommandSize + 1 > m_nMaxArgSBufferLength ) - { - Compact(); - if ( m_nArgSBufferSize + nCommandSize + 1 > m_nMaxArgSBufferLength ) - return false; - } - - memcpy( &m_pArgSBuffer[m_nArgSBufferSize], pArgS, nCommandSize ); - m_pArgSBuffer[m_nArgSBufferSize + nCommandSize] = 0; - ++nCommandSize; - - int hCommand = m_Commands.Alloc(); - Command_t &command = m_Commands[hCommand]; - command.m_nTick = nTick; - command.m_nFirstArgS = m_nArgSBufferSize; - command.m_nBufferSize = nCommandSize; - - m_nArgSBufferSize += nCommandSize; - - if ( !m_bIsProcessingCommands || ( nTick > m_nCurrentTick ) ) - { - InsertCommandAtAppropriateTime( hCommand ); - } - else - { - InsertImmediateCommand( hCommand ); - } - return true; -} - - -//----------------------------------------------------------------------------- -// Returns the length of the next command -//----------------------------------------------------------------------------- -void CCommandBuffer::GetNextCommandLength( const char *pText, int nMaxLen, int *pCommandLength, int *pNextCommandOffset ) -{ - int nCommandLength = 0; - int nNextCommandOffset; - bool bIsQuoted = false; - bool bIsCommented = false; - for ( nNextCommandOffset=0; nNextCommandOffset < nMaxLen; ++nNextCommandOffset, nCommandLength += bIsCommented ? 0 : 1 ) - { - char c = pText[nNextCommandOffset]; - if ( !bIsCommented ) - { - if ( c == '"' ) - { - bIsQuoted = !bIsQuoted; - continue; - } - - // don't break if inside a C++ style comment - if ( !bIsQuoted && c == '/' ) - { - bIsCommented = ( nNextCommandOffset < nMaxLen-1 ) && pText[nNextCommandOffset+1] == '/'; - if ( bIsCommented ) - { - ++nNextCommandOffset; - continue; - } - } - - // don't break if inside a quoted string - if ( !bIsQuoted && c == ';' ) - break; - } - - // FIXME: This is legacy behavior; should we not break if a \n is inside a quoted string? - if ( c == '\n' ) - break; - } - - *pCommandLength = nCommandLength; - *pNextCommandOffset = nNextCommandOffset; -} - - -//----------------------------------------------------------------------------- -// Add text to command buffer, return false if it couldn't owing to overflow -//----------------------------------------------------------------------------- -bool CCommandBuffer::AddText( const char *pText, int nTickDelay ) -{ - Assert( nTickDelay >= 0 ); - - int nLen = Q_strlen( pText ); - int nTick = m_nCurrentTick + nTickDelay; - - // Parse the text into distinct commands - const char *pCurrentCommand = pText; - int nOffsetToNextCommand; - for( ; nLen > 0; nLen -= nOffsetToNextCommand+1, pCurrentCommand += nOffsetToNextCommand+1 ) - { - // find a \n or ; line break - int nCommandLength; - GetNextCommandLength( pCurrentCommand, nLen, &nCommandLength, &nOffsetToNextCommand ); - if ( nCommandLength <= 0 ) - continue; - - const char *pArgS; - char *pArgV0 = (char*)_alloca( nCommandLength+1 ); - CUtlBuffer bufParse( pCurrentCommand, nCommandLength, CUtlBuffer::TEXT_BUFFER | CUtlBuffer::READ_ONLY ); - ParseArgV0( bufParse, pArgV0, nCommandLength+1, &pArgS ); - if ( pArgV0[0] == 0 ) - continue; - - // Deal with the special 'wait' command - if ( !Q_stricmp( pArgV0, "wait" ) ) - { - int nDelay = pArgS ? atoi( pArgS ) : m_nWaitDelayTicks; - nTick += nDelay; - continue; - } - - if ( !InsertCommand( pCurrentCommand, nCommandLength, nTick ) ) - return false; - } - - return true; -} - - -//----------------------------------------------------------------------------- -// Are we in the middle of processing commands? -//----------------------------------------------------------------------------- -bool CCommandBuffer::IsProcessingCommands() -{ - return m_bIsProcessingCommands; -} - - -//----------------------------------------------------------------------------- -// Delays all queued commands to execute at a later time -//----------------------------------------------------------------------------- -void CCommandBuffer::DelayAllQueuedCommands( int nDelay ) -{ - if ( nDelay <= 0 ) - return; - - for ( int i = m_Commands.Head(); i != m_Commands.InvalidIndex(); i = m_Commands.Next(i) ) - { - m_Commands[i].m_nTick += nDelay; - } -} - - -//----------------------------------------------------------------------------- -// Call this to begin iterating over all commands up to flCurrentTime -//----------------------------------------------------------------------------- -void CCommandBuffer::BeginProcessingCommands( int nDeltaTicks ) -{ - if ( nDeltaTicks == 0 ) - return; - - Assert( !m_bIsProcessingCommands ); - m_bIsProcessingCommands = true; - m_nLastTickToProcess = m_nCurrentTick + nDeltaTicks - 1; - - // Necessary to insert commands while commands are being processed - m_hNextCommand = m_Commands.Head(); -} - - -//----------------------------------------------------------------------------- -// Returns the next command -//----------------------------------------------------------------------------- -bool CCommandBuffer::DequeueNextCommand( ) -{ - m_CurrentCommand.Reset(); - - Assert( m_bIsProcessingCommands ); - if ( m_Commands.Count() == 0 ) - return false; - - int nHead = m_Commands.Head(); - Command_t &command = m_Commands[ nHead ]; - if ( command.m_nTick > m_nLastTickToProcess ) - return false; - - m_nCurrentTick = command.m_nTick; - - // Copy the current command into a temp buffer - // NOTE: This is here to avoid the pointers returned by DequeueNextCommand - // to become invalid by calling AddText. Is there a way we can avoid the memcpy? - if ( command.m_nBufferSize > 0 ) - { - m_CurrentCommand.Tokenize( &m_pArgSBuffer[command.m_nFirstArgS] ); - } - - m_Commands.Remove( nHead ); - - // Necessary to insert commands while commands are being processed - m_hNextCommand = m_Commands.Head(); - -// Msg("Dequeue : "); -// for ( int i = 0; i < nArgc; ++i ) -// { -// Msg("%s ", m_pCurrentArgv[i] ); -// } -// Msg("\n"); - return true; -} - - -//----------------------------------------------------------------------------- -// Returns the next command -//----------------------------------------------------------------------------- -int CCommandBuffer::DequeueNextCommand( const char **& ppArgv ) -{ - DequeueNextCommand(); - ppArgv = ArgV(); - return ArgC(); -} - - -//----------------------------------------------------------------------------- -// Compacts the command buffer -//----------------------------------------------------------------------------- -void CCommandBuffer::Compact() -{ - // Compress argvbuffer + argv - // NOTE: I'm using this choice instead of calling malloc + free - // per command to allocate arguments because I expect to post a - // bunch of commands but not have many delayed commands; - // avoiding the allocation cost seems more important that the memcpy - // cost here since I expect to not have much to copy. - m_nArgSBufferSize = 0; - - char pTempBuffer[ ARGS_BUFFER_LENGTH ]; - for ( int i = m_Commands.Head(); i != m_Commands.InvalidIndex(); i = m_Commands.Next(i) ) - { - Command_t &command = m_Commands[ i ]; - - memcpy( &pTempBuffer[m_nArgSBufferSize], &m_pArgSBuffer[command.m_nFirstArgS], command.m_nBufferSize ); - command.m_nFirstArgS = m_nArgSBufferSize; - m_nArgSBufferSize += command.m_nBufferSize; - } - - // NOTE: We could also store 2 buffers in the command buffer and switch - // between the two to avoid the 2nd memcpy; but again I'm guessing the memory - // tradeoff isn't worth it - memcpy( m_pArgSBuffer, pTempBuffer, m_nArgSBufferSize ); -} - - -//----------------------------------------------------------------------------- -// Call this to finish iterating over all commands -//----------------------------------------------------------------------------- -void CCommandBuffer::EndProcessingCommands() -{ - Assert( m_bIsProcessingCommands ); - m_bIsProcessingCommands = false; - m_nCurrentTick = m_nLastTickToProcess + 1; - m_hNextCommand = m_Commands.InvalidIndex(); - - // Extract commands that are before the end time - // NOTE: This is a bug for this to - int i = m_Commands.Head(); - if ( i == m_Commands.InvalidIndex() ) - { - m_nArgSBufferSize = 0; - return; - } - - while ( i != m_Commands.InvalidIndex() ) - { - if ( m_Commands[i].m_nTick >= m_nCurrentTick ) - break; - - AssertMsgOnce( false, "CCommandBuffer::EndProcessingCommands() called before all appropriate commands were dequeued.\n" ); - int nNext = i; - Msg( "Warning: Skipping command %s\n", m_pArgSBuffer[ m_Commands[i].m_nFirstArgS ] ); - m_Commands.Remove( i ); - i = nNext; - } - - Compact(); -} - - -//----------------------------------------------------------------------------- -// Returns a handle to the next command to process -//----------------------------------------------------------------------------- -CommandHandle_t CCommandBuffer::GetNextCommandHandle() -{ - Assert( m_bIsProcessingCommands ); - return m_Commands.Head(); -} - - -#if 0 -/* -=============== -Cmd_Alias_f - -Creates a new command that executes a command string (possibly ; seperated) -=============== -*/ -void Cmd_Alias_f (void) -{ - cmdalias_t *a; - char cmd[MAX_COMMAND_LENGTH]; - int i, c; - char *s; - - if (Cmd_Argc() == 1) - { - Con_Printf ("Current alias commands:\n"); - for (a = cmd_alias ; a ; a=a->next) - Con_Printf ("%s : %s\n", a->name, a->value); - return; - } - - s = Cmd_Argv(1); - if (strlen(s) >= MAX_ALIAS_NAME) - { - Con_Printf ("Alias name is too long\n"); - return; - } - -// copy the rest of the command line - cmd[0] = 0; // start out with a null string - c = Cmd_Argc(); - for (i=2 ; i< c ; i++) - { - Q_strncat(cmd, Cmd_Argv(i), sizeof( cmd ), COPY_ALL_CHARACTERS); - if (i != c) - { - Q_strncat (cmd, " ", sizeof( cmd ), COPY_ALL_CHARACTERS ); - } - } - Q_strncat (cmd, "\n", sizeof( cmd ), COPY_ALL_CHARACTERS); - - // if the alias already exists, reuse it - for (a = cmd_alias ; a ; a=a->next) - { - if (!strcmp(s, a->name)) - { - if ( !strcmp( a->value, cmd ) ) // Re-alias the same thing - return; - - delete[] a->value; - break; - } - } - - if (!a) - { - a = (cmdalias_t *)new cmdalias_t; - a->next = cmd_alias; - cmd_alias = a; - } - Q_strncpy (a->name, s, sizeof( a->name ) ); - - a->value = COM_StringCopy(cmd); -} - - - -/* -============================================================================= - - COMMAND EXECUTION - -============================================================================= -*/ - -#define MAX_ARGS 80 - -static int cmd_argc; -static char *cmd_argv[MAX_ARGS]; -static char *cmd_null_string = ""; -static const char *cmd_args = NULL; - -cmd_source_t cmd_source; - -//----------------------------------------------------------------------------- -// Purpose: -// Output : void Cmd_Init -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -void Cmd_Shutdown( void ) -{ - // TODO, cleanup - while ( cmd_alias ) - { - cmdalias_t *next = cmd_alias->next; - delete cmd_alias->value; // created by StringCopy() - delete cmd_alias; - cmd_alias = next; - } -} - - - -/* -============ -Cmd_ExecuteString - -A complete command line has been parsed, so try to execute it -FIXME: lookupnoadd the token to speed search? -============ -*/ -const ConCommandBase *Cmd_ExecuteString (const char *text, cmd_source_t src) -{ - cmdalias_t *a; - - cmd_source = src; - Cmd_TokenizeString (text); - -// execute the command line - if (!Cmd_Argc()) - return NULL; // no tokens - -// check alias - for (a=cmd_alias ; a ; a=a->next) - { - if (!Q_strcasecmp (cmd_argv[0], a->name)) - { - Cbuf_InsertText (a->value); - return NULL; - } - } - -// check ConCommands - ConCommandBase const *pCommand = ConCommandBase::FindCommand( cmd_argv[ 0 ] ); - if ( pCommand && pCommand->IsCommand() ) - { - bool isServerCommand = ( pCommand->IsBitSet( FCVAR_GAMEDLL ) && - // Typed at console - cmd_source == src_command && - // Not HLDS - !sv.IsDedicated() ); - - // Hook to allow game .dll to figure out who type the message on a listen server - if ( serverGameClients ) - { - // We're actually the server, so set it up locally - if ( sv.IsActive() ) - { - g_pServerPluginHandler->SetCommandClient( -1 ); - -#ifndef SWDS - // Special processing for listen server player - if ( isServerCommand ) - { - g_pServerPluginHandler->SetCommandClient( cl.m_nPlayerSlot ); - } -#endif - } - // We're not the server, but we've been a listen server (game .dll loaded) - // forward this command tot he server instead of running it locally if we're still - // connected - // Otherwise, things like "say" won't work unless you quit and restart - else if ( isServerCommand ) - { - if ( cl.IsConnected() ) - { - Cmd_ForwardToServer(); - return NULL; - } - else - { - // It's a server command, but we're not connected to a server. Don't try to execute it. - return NULL; - } - } - } - - // Allow cheat commands in singleplayer, debug, or multiplayer with sv_cheats on -#ifndef _DEBUG - if ( pCommand->IsBitSet( FCVAR_CHEAT ) ) - { - if ( !Host_IsSinglePlayerGame() && sv_cheats.GetInt() == 0 ) - { - Msg( "Can't use cheat command %s in multiplayer, unless the server has sv_cheats set to 1.\n", pCommand->GetName() ); - return NULL; - } - } -#endif - - (( ConCommand * )pCommand )->Dispatch(); - return pCommand; - } - - // check cvars - if ( cv->IsCommand() ) - { - return pCommand; - } - - // forward the command line to the server, so the entity DLL can parse it - if ( cmd_source == src_command ) - { - if ( cl.IsConnected() ) - { - Cmd_ForwardToServer(); - return NULL; - } - } - - Msg("Unknown command \"%s\"\n", Cmd_Argv(0)); - - return NULL; -} -#endif diff --git a/Resources/NetHook/tier1/convar.cpp b/Resources/NetHook/tier1/convar.cpp deleted file mode 100644 index d246eb58..00000000 --- a/Resources/NetHook/tier1/convar.cpp +++ /dev/null @@ -1,1241 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -// -//===========================================================================// - -#include -#include -#include -#include "basetypes.h" -#include "tier1/convar.h" -#include "tier1/strtools.h" -#include "tier1/characterset.h" -#include "tier1/utlbuffer.h" -#include "tier1/tier1.h" -#include "tier1/convar_serverbounded.h" -#include "icvar.h" -#include "tier0/dbg.h" -#include "Color.h" -#if defined( _X360 ) -#include "xbox/xbox_console.h" -#endif -#include "tier0/memdbgon.h" - - -// Comment this out when we release. -//#define ALLOW_DEVELOPMENT_CVARS - - - -//----------------------------------------------------------------------------- -// Statically constructed list of ConCommandBases, -// used for registering them with the ICVar interface -//----------------------------------------------------------------------------- -ConCommandBase *ConCommandBase::s_pConCommandBases = NULL; -IConCommandBaseAccessor *ConCommandBase::s_pAccessor = NULL; -static int s_nCVarFlag = 0; -static int s_nDLLIdentifier = -1; // A unique identifier indicating which DLL this convar came from -static bool s_bRegistered = false; - -class CDefaultAccessor : public IConCommandBaseAccessor -{ -public: - virtual bool RegisterConCommandBase( ConCommandBase *pVar ) - { - // Link to engine's list instead - g_pCVar->RegisterConCommand( pVar ); - return true; - } -}; - -static CDefaultAccessor s_DefaultAccessor; - -//----------------------------------------------------------------------------- -// Called by the framework to register ConCommandBases with the ICVar -//----------------------------------------------------------------------------- -void ConVar_Register( int nCVarFlag, IConCommandBaseAccessor *pAccessor ) -{ - if ( !g_pCVar || s_bRegistered ) - return; - - Assert( s_nDLLIdentifier < 0 ); - s_bRegistered = true; - s_nCVarFlag = nCVarFlag; - s_nDLLIdentifier = g_pCVar->AllocateDLLIdentifier(); - - ConCommandBase *pCur, *pNext; - - ConCommandBase::s_pAccessor = pAccessor ? pAccessor : &s_DefaultAccessor; - pCur = ConCommandBase::s_pConCommandBases; - while ( pCur ) - { - pNext = pCur->m_pNext; - pCur->AddFlags( s_nCVarFlag ); - pCur->Init(); - pCur = pNext; - } - - ConCommandBase::s_pConCommandBases = NULL; -} - -void ConVar_Unregister( ) -{ - if ( !g_pCVar || !s_bRegistered ) - return; - - Assert( s_nDLLIdentifier >= 0 ); - g_pCVar->UnregisterConCommands( s_nDLLIdentifier ); - s_nDLLIdentifier = -1; - s_bRegistered = false; -} - - -//----------------------------------------------------------------------------- -// Purpose: Default constructor -//----------------------------------------------------------------------------- -ConCommandBase::ConCommandBase( void ) -{ - m_bRegistered = false; - m_pszName = NULL; - m_pszHelpString = NULL; - - m_nFlags = 0; - m_pNext = NULL; -} - -//----------------------------------------------------------------------------- -// Purpose: The base console invoked command/cvar interface -// Input : *pName - name of variable/command -// *pHelpString - help text -// flags - flags -//----------------------------------------------------------------------------- -ConCommandBase::ConCommandBase( const char *pName, const char *pHelpString /*=0*/, int flags /*= 0*/ ) -{ - Create( pName, pHelpString, flags ); -} - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -ConCommandBase::~ConCommandBase( void ) -{ -} - -//----------------------------------------------------------------------------- -// Purpose: -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool ConCommandBase::IsCommand( void ) const -{ -// Assert( 0 ); This can't assert. . causes a recursive assert in Sys_Printf, etc. - return true; -} - - -//----------------------------------------------------------------------------- -// Returns the DLL identifier -//----------------------------------------------------------------------------- -CVarDLLIdentifier_t ConCommandBase::GetDLLIdentifier() const -{ - return s_nDLLIdentifier; -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *pName - -// callback - -// *pHelpString - -// flags - -//----------------------------------------------------------------------------- -void ConCommandBase::Create( const char *pName, const char *pHelpString /*= 0*/, int flags /*= 0*/ ) -{ - static char *empty_string = ""; - - m_bRegistered = false; - - // Name should be static data - Assert( pName ); - m_pszName = pName; - m_pszHelpString = pHelpString ? pHelpString : empty_string; - - m_nFlags = flags; - -#ifdef ALLOW_DEVELOPMENT_CVARS - m_nFlags &= ~FCVAR_DEVELOPMENTONLY; -#endif - - if ( !( m_nFlags & FCVAR_UNREGISTERED ) ) - { - m_pNext = s_pConCommandBases; - s_pConCommandBases = this; - } - else - { - // It's unregistered - m_pNext = NULL; - } - - // If s_pAccessor is already set (this ConVar is not a global variable), - // register it. - if ( s_pAccessor ) - { - Init(); - } -} - - -//----------------------------------------------------------------------------- -// Purpose: Used internally by OneTimeInit to initialize. -//----------------------------------------------------------------------------- -void ConCommandBase::Init() -{ - if ( s_pAccessor ) - { - s_pAccessor->RegisterConCommandBase( this ); - } -} - -void ConCommandBase::Shutdown() -{ - if ( g_pCVar ) - { - g_pCVar->UnregisterConCommand( this ); - } -} - - -//----------------------------------------------------------------------------- -// Purpose: Return name of the command/var -// Output : const char -//----------------------------------------------------------------------------- -const char *ConCommandBase::GetName( void ) const -{ - return m_pszName; -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : flag - -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool ConCommandBase::IsFlagSet( int flag ) const -{ - return ( flag & m_nFlags ) ? true : false; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : flags - -//----------------------------------------------------------------------------- -void ConCommandBase::AddFlags( int flags ) -{ - m_nFlags |= flags; - -#ifdef ALLOW_DEVELOPMENT_CVARS - m_nFlags &= ~FCVAR_DEVELOPMENTONLY; -#endif -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Output : const ConCommandBase -//----------------------------------------------------------------------------- -const ConCommandBase *ConCommandBase::GetNext( void ) const -{ - return m_pNext; -} - -ConCommandBase *ConCommandBase::GetNext( void ) -{ - return m_pNext; -} - - -//----------------------------------------------------------------------------- -// Purpose: Copies string using local new/delete operators -// Input : *from - -// Output : char -//----------------------------------------------------------------------------- -char *ConCommandBase::CopyString( const char *from ) -{ - int len; - char *to; - - len = strlen( from ); - if ( len <= 0 ) - { - to = new char[1]; - to[0] = 0; - } - else - { - to = new char[len+1]; - Q_strncpy( to, from, len+1 ); - } - return to; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Output : const char -//----------------------------------------------------------------------------- -const char *ConCommandBase::GetHelpText( void ) const -{ - return m_pszHelpString; -} - -//----------------------------------------------------------------------------- -// Purpose: Has this cvar been registered -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool ConCommandBase::IsRegistered( void ) const -{ - return m_bRegistered; -} - - -//----------------------------------------------------------------------------- -// -// Con Commands start here -// -//----------------------------------------------------------------------------- - - -//----------------------------------------------------------------------------- -// Global methods -//----------------------------------------------------------------------------- -static characterset_t s_BreakSet; -static bool s_bBuiltBreakSet = false; - - -//----------------------------------------------------------------------------- -// Tokenizer class -//----------------------------------------------------------------------------- -CCommand::CCommand() -{ - if ( !s_bBuiltBreakSet ) - { - s_bBuiltBreakSet = true; - CharacterSetBuild( &s_BreakSet, "{}()':" ); - } - - Reset(); -} - -CCommand::CCommand( int nArgC, const char **ppArgV ) -{ - Assert( nArgC > 0 ); - - if ( !s_bBuiltBreakSet ) - { - s_bBuiltBreakSet = true; - CharacterSetBuild( &s_BreakSet, "{}()':" ); - } - - Reset(); - - char *pBuf = m_pArgvBuffer; - char *pSBuf = m_pArgSBuffer; - m_nArgc = nArgC; - for ( int i = 0; i < nArgC; ++i ) - { - m_ppArgv[i] = pBuf; - int nLen = Q_strlen( ppArgV[i] ); - memcpy( pBuf, ppArgV[i], nLen+1 ); - if ( i == 0 ) - { - m_nArgv0Size = nLen; - } - pBuf += nLen+1; - - bool bContainsSpace = strchr( ppArgV[i], ' ' ) != NULL; - if ( bContainsSpace ) - { - *pSBuf++ = '\"'; - } - memcpy( pSBuf, ppArgV[i], nLen ); - pSBuf += nLen; - if ( bContainsSpace ) - { - *pSBuf++ = '\"'; - } - - if ( i != nArgC - 1 ) - { - *pSBuf++ = ' '; - } - } -} - -void CCommand::Reset() -{ - m_nArgc = 0; - m_nArgv0Size = 0; - m_pArgSBuffer[0] = 0; -} - -characterset_t* CCommand::DefaultBreakSet() -{ - return &s_BreakSet; -} - -bool CCommand::Tokenize( const char *pCommand, characterset_t *pBreakSet ) -{ - Reset(); - if ( !pCommand ) - return false; - - // Use default break set - if ( !pBreakSet ) - { - pBreakSet = &s_BreakSet; - } - - // Copy the current command into a temp buffer - // NOTE: This is here to avoid the pointers returned by DequeueNextCommand - // to become invalid by calling AddText. Is there a way we can avoid the memcpy? - int nLen = Q_strlen( pCommand ); - if ( nLen >= COMMAND_MAX_LENGTH - 1 ) - { - Warning( "CCommand::Tokenize: Encountered command which overflows the tokenizer buffer.. Skipping!\n" ); - return false; - } - - memcpy( m_pArgSBuffer, pCommand, nLen + 1 ); - - // Parse the current command into the current command buffer - CUtlBuffer bufParse( m_pArgSBuffer, nLen, CUtlBuffer::TEXT_BUFFER | CUtlBuffer::READ_ONLY ); - int nArgvBufferSize = 0; - while ( bufParse.IsValid() && ( m_nArgc < COMMAND_MAX_ARGC ) ) - { - char *pArgvBuf = &m_pArgvBuffer[nArgvBufferSize]; - int nMaxLen = COMMAND_MAX_LENGTH - nArgvBufferSize; - int nStartGet = bufParse.TellGet(); - int nSize = bufParse.ParseToken( pBreakSet, pArgvBuf, nMaxLen ); - if ( nSize < 0 ) - break; - - // Check for overflow condition - if ( nMaxLen == nSize ) - { - Reset(); - return false; - } - - if ( m_nArgc == 1 ) - { - // Deal with the case where the arguments were quoted - m_nArgv0Size = bufParse.TellGet(); - bool bFoundEndQuote = m_pArgSBuffer[m_nArgv0Size-1] == '\"'; - if ( bFoundEndQuote ) - { - --m_nArgv0Size; - } - m_nArgv0Size -= nSize; - Assert( m_nArgv0Size != 0 ); - - // The StartGet check is to handle this case: "foo"bar - // which will parse into 2 different args. ArgS should point to bar. - bool bFoundStartQuote = ( m_nArgv0Size > nStartGet ) && ( m_pArgSBuffer[m_nArgv0Size-1] == '\"' ); - Assert( bFoundEndQuote == bFoundStartQuote ); - if ( bFoundStartQuote ) - { - --m_nArgv0Size; - } - } - - m_ppArgv[ m_nArgc++ ] = pArgvBuf; - if( m_nArgc >= COMMAND_MAX_ARGC ) - { - Warning( "CCommand::Tokenize: Encountered command which overflows the argument buffer.. Clamped!\n" ); - } - - nArgvBufferSize += nSize + 1; - Assert( nArgvBufferSize <= COMMAND_MAX_LENGTH ); - } - - return true; -} - - -//----------------------------------------------------------------------------- -// Helper function to parse arguments to commands. -//----------------------------------------------------------------------------- -const char* CCommand::FindArg( const char *pName ) const -{ - int nArgC = ArgC(); - for ( int i = 1; i < nArgC; i++ ) - { - if ( !Q_stricmp( Arg(i), pName ) ) - return (i+1) < nArgC ? Arg( i+1 ) : ""; - } - return 0; -} - -int CCommand::FindArgInt( const char *pName, int nDefaultVal ) const -{ - const char *pVal = FindArg( pName ); - if ( pVal ) - return atoi( pVal ); - else - return nDefaultVal; -} - - -//----------------------------------------------------------------------------- -// Default console command autocompletion function -//----------------------------------------------------------------------------- -int DefaultCompletionFunc( const char *partial, char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ] ) -{ - return 0; -} - - -//----------------------------------------------------------------------------- -// Purpose: Constructs a console command -//----------------------------------------------------------------------------- -//ConCommand::ConCommand() -//{ -// m_bIsNewConCommand = true; -//} - -ConCommand::ConCommand( const char *pName, FnCommandCallbackV1_t callback, const char *pHelpString /*= 0*/, int flags /*= 0*/, FnCommandCompletionCallback completionFunc /*= 0*/ ) -{ - // Set the callback - m_fnCommandCallbackV1 = callback; - m_bUsingNewCommandCallback = false; - m_bUsingCommandCallbackInterface = false; - m_fnCompletionCallback = completionFunc ? completionFunc : DefaultCompletionFunc; - m_bHasCompletionCallback = completionFunc != 0 ? true : false; - - // Setup the rest - BaseClass::Create( pName, pHelpString, flags ); -} - -ConCommand::ConCommand( const char *pName, FnCommandCallback_t callback, const char *pHelpString /*= 0*/, int flags /*= 0*/, FnCommandCompletionCallback completionFunc /*= 0*/ ) -{ - // Set the callback - m_fnCommandCallback = callback; - m_bUsingNewCommandCallback = true; - m_fnCompletionCallback = completionFunc ? completionFunc : DefaultCompletionFunc; - m_bHasCompletionCallback = completionFunc != 0 ? true : false; - m_bUsingCommandCallbackInterface = false; - - // Setup the rest - BaseClass::Create( pName, pHelpString, flags ); -} - -ConCommand::ConCommand( const char *pName, ICommandCallback *pCallback, const char *pHelpString /*= 0*/, int flags /*= 0*/, ICommandCompletionCallback *pCompletionCallback /*= 0*/ ) -{ - // Set the callback - m_pCommandCallback = pCallback; - m_bUsingNewCommandCallback = false; - m_pCommandCompletionCallback = pCompletionCallback; - m_bHasCompletionCallback = ( pCompletionCallback != 0 ); - m_bUsingCommandCallbackInterface = true; - - // Setup the rest - BaseClass::Create( pName, pHelpString, flags ); -} - -//----------------------------------------------------------------------------- -// Destructor -//----------------------------------------------------------------------------- -ConCommand::~ConCommand( void ) -{ -} - - -//----------------------------------------------------------------------------- -// Purpose: Returns true if this is a command -//----------------------------------------------------------------------------- -bool ConCommand::IsCommand( void ) const -{ - return true; -} - - -//----------------------------------------------------------------------------- -// Purpose: Invoke the function if there is one -//----------------------------------------------------------------------------- -void ConCommand::Dispatch( const CCommand &command ) -{ - if ( m_bUsingNewCommandCallback ) - { - if ( m_fnCommandCallback ) - { - ( *m_fnCommandCallback )( command ); - return; - } - } - else if ( m_bUsingCommandCallbackInterface ) - { - if ( m_pCommandCallback ) - { - m_pCommandCallback->CommandCallback( command ); - return; - } - } - else - { - if ( m_fnCommandCallbackV1 ) - { - ( *m_fnCommandCallbackV1 )(); - return; - } - } - - // Command without callback!!! - AssertMsg( 0, ( "Encountered ConCommand '%s' without a callback!\n", GetName() ) ); -} - - -//----------------------------------------------------------------------------- -// Purpose: Calls the autocompletion method to get autocompletion suggestions -//----------------------------------------------------------------------------- -int ConCommand::AutoCompleteSuggest( const char *partial, CUtlVector< CUtlString > &commands ) -{ - if ( m_bUsingCommandCallbackInterface ) - { - if ( !m_pCommandCompletionCallback ) - return 0; - return m_pCommandCompletionCallback->CommandCompletionCallback( partial, commands ); - } - - Assert( m_fnCompletionCallback ); - if ( !m_fnCompletionCallback ) - return 0; - - char rgpchCommands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ]; - int iret = ( m_fnCompletionCallback )( partial, rgpchCommands ); - for ( int i = 0 ; i < iret; ++i ) - { - CUtlString str = rgpchCommands[ i ]; - commands.AddToTail( str ); - } - return iret; -} - - -//----------------------------------------------------------------------------- -// Returns true if the console command can autocomplete -//----------------------------------------------------------------------------- -bool ConCommand::CanAutoComplete( void ) -{ - return m_bHasCompletionCallback; -} - - - -//----------------------------------------------------------------------------- -// -// Console Variables -// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Various constructors -//----------------------------------------------------------------------------- -ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags /* = 0 */ ) -{ - Create( pName, pDefaultValue, flags ); -} - -ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString ) -{ - Create( pName, pDefaultValue, flags, pHelpString ); -} - -ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax ) -{ - Create( pName, pDefaultValue, flags, pHelpString, bMin, fMin, bMax, fMax ); -} - -ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString, FnChangeCallback_t callback ) -{ - Create( pName, pDefaultValue, flags, pHelpString, false, 0.0, false, 0.0, callback ); -} - -ConVar::ConVar( const char *pName, const char *pDefaultValue, int flags, const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax, FnChangeCallback_t callback ) -{ - Create( pName, pDefaultValue, flags, pHelpString, bMin, fMin, bMax, fMax, callback ); -} - - -//----------------------------------------------------------------------------- -// Destructor -//----------------------------------------------------------------------------- -ConVar::~ConVar( void ) -{ - if ( m_pszString ) - { - delete[] m_pszString; - m_pszString = NULL; - } -} - - -//----------------------------------------------------------------------------- -// Install a change callback (there shouldn't already be one....) -//----------------------------------------------------------------------------- -void ConVar::InstallChangeCallback( FnChangeCallback_t callback ) -{ - Assert( !m_pParent->m_fnChangeCallback || !callback ); - m_pParent->m_fnChangeCallback = callback; - - if ( m_pParent->m_fnChangeCallback ) - { - // Call it immediately to set the initial value... - m_pParent->m_fnChangeCallback( this, m_pszString, m_fValue ); - } -} - -bool ConVar::IsFlagSet( int flag ) const -{ - return ( flag & m_pParent->m_nFlags ) ? true : false; -} - -const char *ConVar::GetHelpText( void ) const -{ - return m_pParent->m_pszHelpString; -} - -void ConVar::AddFlags( int flags ) -{ - m_pParent->m_nFlags |= flags; - -#ifdef ALLOW_DEVELOPMENT_CVARS - m_pParent->m_nFlags &= ~FCVAR_DEVELOPMENTONLY; -#endif -} - -bool ConVar::IsRegistered( void ) const -{ - return m_pParent->m_bRegistered; -} - -const char *ConVar::GetName( void ) const -{ - return m_pParent->m_pszName; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool ConVar::IsCommand( void ) const -{ - return false; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : -//----------------------------------------------------------------------------- -void ConVar::Init() -{ - BaseClass::Init(); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *value - -//----------------------------------------------------------------------------- -void ConVar::InternalSetValue( const char *value ) -{ - float fNewValue; - char tempVal[ 32 ]; - char *val; - - Assert(m_pParent == this); // Only valid for root convars. - - float flOldValue = m_fValue; - - val = (char *)value; - fNewValue = ( float )atof( value ); - - if ( ClampValue( fNewValue ) ) - { - Q_snprintf( tempVal,sizeof(tempVal), "%f", fNewValue ); - val = tempVal; - } - - // Redetermine value - m_fValue = fNewValue; - m_nValue = ( int )( m_fValue ); - - if ( !( m_nFlags & FCVAR_NEVER_AS_STRING ) ) - { - ChangeStringValue( val, flOldValue ); - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *tempVal - -//----------------------------------------------------------------------------- -void ConVar::ChangeStringValue( const char *tempVal, float flOldValue ) -{ - Assert( !( m_nFlags & FCVAR_NEVER_AS_STRING ) ); - - char* pszOldValue = (char*)stackalloc( m_StringLength ); - memcpy( pszOldValue, m_pszString, m_StringLength ); - - int len = Q_strlen(tempVal) + 1; - - if ( len > m_StringLength) - { - if (m_pszString) - { - delete[] m_pszString; - } - - m_pszString = new char[len]; - m_StringLength = len; - } - - memcpy( m_pszString, tempVal, len ); - - // Invoke any necessary callback function - if ( m_fnChangeCallback ) - { - m_fnChangeCallback( this, pszOldValue, flOldValue ); - } - - g_pCVar->CallGlobalChangeCallbacks( this, pszOldValue, flOldValue ); - - stackfree( pszOldValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: Check whether to clamp and then perform clamp -// Input : value - -// Output : Returns true if value changed -//----------------------------------------------------------------------------- -bool ConVar::ClampValue( float& value ) -{ - if ( m_bHasMin && ( value < m_fMinVal ) ) - { - value = m_fMinVal; - return true; - } - - if ( m_bHasMax && ( value > m_fMaxVal ) ) - { - value = m_fMaxVal; - return true; - } - - return false; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *value - -//----------------------------------------------------------------------------- -void ConVar::InternalSetFloatValue( float fNewValue ) -{ - if ( fNewValue == m_fValue ) - return; - - Assert( m_pParent == this ); // Only valid for root convars. - - // Check bounds - ClampValue( fNewValue ); - - // Redetermine value - float flOldValue = m_fValue; - m_fValue = fNewValue; - m_nValue = ( int )m_fValue; - - if ( !( m_nFlags & FCVAR_NEVER_AS_STRING ) ) - { - char tempVal[ 32 ]; - Q_snprintf( tempVal, sizeof( tempVal), "%f", m_fValue ); - ChangeStringValue( tempVal, flOldValue ); - } - else - { - Assert( !m_fnChangeCallback ); - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *value - -//----------------------------------------------------------------------------- -void ConVar::InternalSetIntValue( int nValue ) -{ - if ( nValue == m_nValue ) - return; - - Assert( m_pParent == this ); // Only valid for root convars. - - float fValue = (float)nValue; - if ( ClampValue( fValue ) ) - { - nValue = ( int )( fValue ); - } - - // Redetermine value - float flOldValue = m_fValue; - m_fValue = fValue; - m_nValue = nValue; - - if ( !( m_nFlags & FCVAR_NEVER_AS_STRING ) ) - { - char tempVal[ 32 ]; - Q_snprintf( tempVal, sizeof( tempVal ), "%d", m_nValue ); - ChangeStringValue( tempVal, flOldValue ); - } - else - { - Assert( !m_fnChangeCallback ); - } -} - -//----------------------------------------------------------------------------- -// Purpose: Private creation -//----------------------------------------------------------------------------- -void ConVar::Create( const char *pName, const char *pDefaultValue, int flags /*= 0*/, - const char *pHelpString /*= NULL*/, bool bMin /*= false*/, float fMin /*= 0.0*/, - bool bMax /*= false*/, float fMax /*= false*/, FnChangeCallback_t callback /*= NULL*/ ) -{ - static char *empty_string = ""; - - m_pParent = this; - - // Name should be static data - m_pszDefaultValue = pDefaultValue ? pDefaultValue : empty_string; - Assert( m_pszDefaultValue ); - - m_StringLength = strlen( m_pszDefaultValue ) + 1; - m_pszString = new char[m_StringLength]; - memcpy( m_pszString, m_pszDefaultValue, m_StringLength ); - - m_bHasMin = bMin; - m_fMinVal = fMin; - m_bHasMax = bMax; - m_fMaxVal = fMax; - - m_fnChangeCallback = callback; - - m_fValue = ( float )atof( m_pszString ); - - // Bounds Check, should never happen, if it does, no big deal - if ( m_bHasMin && ( m_fValue < m_fMinVal ) ) - { - Assert( 0 ); - } - - if ( m_bHasMax && ( m_fValue > m_fMaxVal ) ) - { - Assert( 0 ); - } - - m_nValue = ( int )m_fValue; - - BaseClass::Create( pName, pHelpString, flags ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *value - -//----------------------------------------------------------------------------- -void ConVar::SetValue(const char *value) -{ - ConVar *var = ( ConVar * )m_pParent; - var->InternalSetValue( value ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : value - -//----------------------------------------------------------------------------- -void ConVar::SetValue( float value ) -{ - ConVar *var = ( ConVar * )m_pParent; - var->InternalSetFloatValue( value ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : value - -//----------------------------------------------------------------------------- -void ConVar::SetValue( int value ) -{ - ConVar *var = ( ConVar * )m_pParent; - var->InternalSetIntValue( value ); -} - -//----------------------------------------------------------------------------- -// Purpose: Reset to default value -//----------------------------------------------------------------------------- -void ConVar::Revert( void ) -{ - // Force default value again - ConVar *var = ( ConVar * )m_pParent; - var->SetValue( var->m_pszDefaultValue ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : minVal - -// Output : true if there is a min set -//----------------------------------------------------------------------------- -bool ConVar::GetMin( float& minVal ) const -{ - minVal = m_pParent->m_fMinVal; - return m_pParent->m_bHasMin; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : maxVal - -//----------------------------------------------------------------------------- -bool ConVar::GetMax( float& maxVal ) const -{ - maxVal = m_pParent->m_fMaxVal; - return m_pParent->m_bHasMax; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Output : const char -//----------------------------------------------------------------------------- -const char *ConVar::GetDefault( void ) const -{ - return m_pParent->m_pszDefaultValue; -} - - -//----------------------------------------------------------------------------- -// This version is simply used to make reading convars simpler. -// Writing convars isn't allowed in this mode -//----------------------------------------------------------------------------- -class CEmptyConVar : public ConVar -{ -public: - CEmptyConVar() : ConVar( "", "0" ) {} - // Used for optimal read access - virtual void SetValue( const char *pValue ) {} - virtual void SetValue( float flValue ) {} - virtual void SetValue( int nValue ) {} - virtual const char *GetName( void ) const { return ""; } - virtual bool IsFlagSet( int nFlags ) const { return false; } -}; - -static CEmptyConVar s_EmptyConVar; - -ConVarRef::ConVarRef( const char *pName ) -{ - Init( pName, false ); -} - -ConVarRef::ConVarRef( const char *pName, bool bIgnoreMissing ) -{ - Init( pName, bIgnoreMissing ); -} - -void ConVarRef::Init( const char *pName, bool bIgnoreMissing ) -{ - m_pConVar = g_pCVar ? g_pCVar->FindVar( pName ) : &s_EmptyConVar; - if ( !m_pConVar ) - { - m_pConVar = &s_EmptyConVar; - } - m_pConVarState = static_cast< ConVar * >( m_pConVar ); - if( !IsValid() ) - { - static bool bFirst = true; - if ( g_pCVar || bFirst ) - { - if ( !bIgnoreMissing ) - { - Warning( "ConVarRef %s doesn't point to an existing ConVar\n", pName ); - } - bFirst = false; - } - } -} - -ConVarRef::ConVarRef( IConVar *pConVar ) -{ - m_pConVar = pConVar ? pConVar : &s_EmptyConVar; - m_pConVarState = static_cast< ConVar * >( m_pConVar ); -} - -bool ConVarRef::IsValid() const -{ - return m_pConVar != &s_EmptyConVar; -} - - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -void ConVar_PrintFlags( const ConCommandBase *var ) -{ - bool any = false; - if ( var->IsFlagSet( FCVAR_GAMEDLL ) ) - { - ConMsg( " game" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_CLIENTDLL ) ) - { - ConMsg( " client" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_ARCHIVE ) ) - { - ConMsg( " archive" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_NOTIFY ) ) - { - ConMsg( " notify" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_SPONLY ) ) - { - ConMsg( " singleplayer" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_NOT_CONNECTED ) ) - { - ConMsg( " notconnected" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_CHEAT ) ) - { - ConMsg( " cheat" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_REPLICATED ) ) - { - ConMsg( " replicated" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_SERVER_CAN_EXECUTE ) ) - { - ConMsg( " server_can_execute" ); - any = true; - } - - if ( var->IsFlagSet( FCVAR_CLIENTCMD_CAN_EXECUTE ) ) - { - ConMsg( " clientcmd_can_execute" ); - any = true; - } - - if ( any ) - { - ConMsg( "\n" ); - } -} - - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -void ConVar_PrintDescription( const ConCommandBase *pVar ) -{ - bool bMin, bMax; - float fMin, fMax; - const char *pStr; - - assert( pVar ); - - Color clr; - clr.SetColor( 255, 100, 100, 255 ); - - if ( !pVar->IsCommand() ) - { - ConVar *var = ( ConVar * )pVar; - const ConVar_ServerBounded *pBounded = dynamic_cast( var ); - - bMin = var->GetMin( fMin ); - bMax = var->GetMax( fMax ); - - const char *value = NULL; - char tempVal[ 32 ]; - - if ( pBounded || var->IsFlagSet( FCVAR_NEVER_AS_STRING ) ) - { - value = tempVal; - - int intVal = pBounded ? pBounded->GetInt() : var->GetInt(); - float floatVal = pBounded ? pBounded->GetFloat() : var->GetFloat(); - - if ( fabs( (float)intVal - floatVal ) < 0.000001 ) - { - Q_snprintf( tempVal, sizeof( tempVal ), "%d", intVal ); - } - else - { - Q_snprintf( tempVal, sizeof( tempVal ), "%f", floatVal ); - } - } - else - { - value = var->GetString(); - } - - if ( value ) - { - ConColorMsg( clr, "\"%s\" = \"%s\"", var->GetName(), value ); - - if ( stricmp( value, var->GetDefault() ) ) - { - ConMsg( " ( def. \"%s\" )", var->GetDefault() ); - } - } - - if ( bMin ) - { - ConMsg( " min. %f", fMin ); - } - if ( bMax ) - { - ConMsg( " max. %f", fMax ); - } - - ConMsg( "\n" ); - - // Handled virtualized cvars. - if ( pBounded && fabs( pBounded->GetFloat() - var->GetFloat() ) > 0.0001f ) - { - ConColorMsg( clr, "** NOTE: The real value is %.3f but the server has temporarily restricted it to %.3f **\n", - var->GetFloat(), pBounded->GetFloat() ); - } - } - else - { - ConCommand *var = ( ConCommand * )pVar; - - ConColorMsg( clr, "\"%s\"\n", var->GetName() ); - } - - ConVar_PrintFlags( pVar ); - - pStr = pVar->GetHelpText(); - if ( pStr && pStr[0] ) - { - ConMsg( " - %s\n", pStr ); - } -} diff --git a/Resources/NetHook/tier1/convar.h b/Resources/NetHook/tier1/convar.h deleted file mode 100644 index 126aa78a..00000000 --- a/Resources/NetHook/tier1/convar.h +++ /dev/null @@ -1,671 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// -//----------------------------------------------------------------------------- -// $NoKeywords: $ -//===========================================================================// - -#ifndef CONVAR_H -#define CONVAR_H - -#if _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "tier1/iconvar.h" -#include "tier1/utlvector.h" -#include "tier1/utlstring.h" -#include "icvar.h" - -#ifdef _WIN32 -#define FORCEINLINE_CVAR FORCEINLINE -#elif _LINUX -#define FORCEINLINE_CVAR inline -#else -#error "implement me" -#endif - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -class ConVar; -class CCommand; -class ConCommand; -class ConCommandBase; -struct characterset_t; - - - -//----------------------------------------------------------------------------- -// Any executable that wants to use ConVars need to implement one of -// these to hook up access to console variables. -//----------------------------------------------------------------------------- -class IConCommandBaseAccessor -{ -public: - // Flags is a combination of FCVAR flags in cvar.h. - // hOut is filled in with a handle to the variable. - virtual bool RegisterConCommandBase( ConCommandBase *pVar ) = 0; -}; - - -//----------------------------------------------------------------------------- -// Helper method for console development -//----------------------------------------------------------------------------- -#if defined( _X360 ) && !defined( _RETAIL ) -void ConVar_PublishToVXConsole(); -#endif - - -//----------------------------------------------------------------------------- -// Called when a ConCommand needs to execute -//----------------------------------------------------------------------------- -typedef void ( *FnCommandCallbackV1_t )( void ); -typedef void ( *FnCommandCallback_t )( const CCommand &command ); - -#define COMMAND_COMPLETION_MAXITEMS 64 -#define COMMAND_COMPLETION_ITEM_LENGTH 64 - -//----------------------------------------------------------------------------- -// Returns 0 to COMMAND_COMPLETION_MAXITEMS worth of completion strings -//----------------------------------------------------------------------------- -typedef int ( *FnCommandCompletionCallback )( const char *partial, char commands[ COMMAND_COMPLETION_MAXITEMS ][ COMMAND_COMPLETION_ITEM_LENGTH ] ); - - -//----------------------------------------------------------------------------- -// Interface version -//----------------------------------------------------------------------------- -class ICommandCallback -{ -public: - virtual void CommandCallback( const CCommand &command ) = 0; -}; - -class ICommandCompletionCallback -{ -public: - virtual int CommandCompletionCallback( const char *pPartial, CUtlVector< CUtlString > &commands ) = 0; -}; - -//----------------------------------------------------------------------------- -// Purpose: The base console invoked command/cvar interface -//----------------------------------------------------------------------------- -class ConCommandBase -{ - friend class CCvar; - friend class ConVar; - friend class ConCommand; - friend void ConVar_Register( int nCVarFlag, IConCommandBaseAccessor *pAccessor ); - friend void ConVar_PublishToVXConsole(); - - // FIXME: Remove when ConVar changes are done - friend class CDefaultCvar; - -public: - ConCommandBase( void ); - ConCommandBase( const char *pName, const char *pHelpString = 0, - int flags = 0 ); - - virtual ~ConCommandBase( void ); - - virtual bool IsCommand( void ) const; - - // Check flag - virtual bool IsFlagSet( int flag ) const; - // Set flag - virtual void AddFlags( int flags ); - - // Return name of cvar - virtual const char *GetName( void ) const; - - // Return help text for cvar - virtual const char *GetHelpText( void ) const; - - // Deal with next pointer - const ConCommandBase *GetNext( void ) const; - ConCommandBase *GetNext( void ); - - virtual bool IsRegistered( void ) const; - - // Returns the DLL identifier - virtual CVarDLLIdentifier_t GetDLLIdentifier() const; - -protected: - virtual void Create( const char *pName, const char *pHelpString = 0, - int flags = 0 ); - - // Used internally by OneTimeInit to initialize/shutdown - virtual void Init(); - void Shutdown(); - - // Internal copy routine ( uses new operator from correct module ) - char *CopyString( const char *from ); - -private: - // Next ConVar in chain - // Prior to register, it points to the next convar in the DLL. - // Once registered, though, m_pNext is reset to point to the next - // convar in the global list - ConCommandBase *m_pNext; - - // Has the cvar been added to the global list? - bool m_bRegistered; - - // Static data - const char *m_pszName; - const char *m_pszHelpString; - - // ConVar flags - int m_nFlags; - -protected: - // ConVars add themselves to this list for the executable. - // Then ConVar_Register runs through all the console variables - // and registers them into a global list stored in vstdlib.dll - static ConCommandBase *s_pConCommandBases; - - // ConVars in this executable use this 'global' to access values. - static IConCommandBaseAccessor *s_pAccessor; -}; - - -//----------------------------------------------------------------------------- -// Command tokenizer -//----------------------------------------------------------------------------- -class CCommand -{ -public: - CCommand(); - CCommand( int nArgC, const char **ppArgV ); - bool Tokenize( const char *pCommand, characterset_t *pBreakSet = NULL ); - void Reset(); - - int ArgC() const; - const char **ArgV() const; - const char *ArgS() const; // All args that occur after the 0th arg, in string form - const char *GetCommandString() const; // The entire command in string form, including the 0th arg - const char *operator[]( int nIndex ) const; // Gets at arguments - const char *Arg( int nIndex ) const; // Gets at arguments - - // Helper functions to parse arguments to commands. - const char* FindArg( const char *pName ) const; - int FindArgInt( const char *pName, int nDefaultVal ) const; - - static int MaxCommandLength(); - static characterset_t* DefaultBreakSet(); - -private: - enum - { - COMMAND_MAX_ARGC = 64, - COMMAND_MAX_LENGTH = 512, - }; - - int m_nArgc; - int m_nArgv0Size; - char m_pArgSBuffer[ COMMAND_MAX_LENGTH ]; - char m_pArgvBuffer[ COMMAND_MAX_LENGTH ]; - const char* m_ppArgv[ COMMAND_MAX_ARGC ]; -}; - -inline int CCommand::MaxCommandLength() -{ - return COMMAND_MAX_LENGTH - 1; -} - -inline int CCommand::ArgC() const -{ - return m_nArgc; -} - -inline const char **CCommand::ArgV() const -{ - return m_nArgc ? (const char**)m_ppArgv : NULL; -} - -inline const char *CCommand::ArgS() const -{ - return m_nArgv0Size ? &m_pArgSBuffer[m_nArgv0Size] : ""; -} - -inline const char *CCommand::GetCommandString() const -{ - return m_nArgc ? m_pArgSBuffer : ""; -} - -inline const char *CCommand::Arg( int nIndex ) const -{ - // FIXME: Many command handlers appear to not be particularly careful - // about checking for valid argc range. For now, we're going to - // do the extra check and return an empty string if it's out of range - if ( nIndex < 0 || nIndex >= m_nArgc ) - return ""; - return m_ppArgv[nIndex]; -} - -inline const char *CCommand::operator[]( int nIndex ) const -{ - return Arg( nIndex ); -} - - -//----------------------------------------------------------------------------- -// Purpose: The console invoked command -//----------------------------------------------------------------------------- -class ConCommand : public ConCommandBase -{ -friend class CCvar; - -public: - typedef ConCommandBase BaseClass; - - ConCommand( const char *pName, FnCommandCallbackV1_t callback, - const char *pHelpString = 0, int flags = 0, FnCommandCompletionCallback completionFunc = 0 ); - ConCommand( const char *pName, FnCommandCallback_t callback, - const char *pHelpString = 0, int flags = 0, FnCommandCompletionCallback completionFunc = 0 ); - ConCommand( const char *pName, ICommandCallback *pCallback, - const char *pHelpString = 0, int flags = 0, ICommandCompletionCallback *pCommandCompletionCallback = 0 ); - - virtual ~ConCommand( void ); - - virtual bool IsCommand( void ) const; - - virtual int AutoCompleteSuggest( const char *partial, CUtlVector< CUtlString > &commands ); - - virtual bool CanAutoComplete( void ); - - // Invoke the function - virtual void Dispatch( const CCommand &command ); - -private: - // NOTE: To maintain backward compat, we have to be very careful: - // All public virtual methods must appear in the same order always - // since engine code will be calling into this code, which *does not match* - // in the mod code; it's using slightly different, but compatible versions - // of this class. Also: Be very careful about adding new fields to this class. - // Those fields will not exist in the version of this class that is instanced - // in mod code. - - // Call this function when executing the command - union - { - FnCommandCallbackV1_t m_fnCommandCallbackV1; - FnCommandCallback_t m_fnCommandCallback; - ICommandCallback *m_pCommandCallback; - }; - - union - { - FnCommandCompletionCallback m_fnCompletionCallback; - ICommandCompletionCallback *m_pCommandCompletionCallback; - }; - - bool m_bHasCompletionCallback : 1; - bool m_bUsingNewCommandCallback : 1; - bool m_bUsingCommandCallbackInterface : 1; -}; - - -//----------------------------------------------------------------------------- -// Purpose: A console variable -//----------------------------------------------------------------------------- -class ConVar : public ConCommandBase, public IConVar -{ -friend class CCvar; -friend class ConVarRef; - -public: - typedef ConCommandBase BaseClass; - - ConVar( const char *pName, const char *pDefaultValue, int flags = 0); - - ConVar( const char *pName, const char *pDefaultValue, int flags, - const char *pHelpString ); - ConVar( const char *pName, const char *pDefaultValue, int flags, - const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax ); - ConVar( const char *pName, const char *pDefaultValue, int flags, - const char *pHelpString, FnChangeCallback_t callback ); - ConVar( const char *pName, const char *pDefaultValue, int flags, - const char *pHelpString, bool bMin, float fMin, bool bMax, float fMax, - FnChangeCallback_t callback ); - - virtual ~ConVar( void ); - - virtual bool IsFlagSet( int flag ) const; - virtual const char* GetHelpText( void ) const; - virtual bool IsRegistered( void ) const; - virtual const char *GetName( void ) const; - virtual void AddFlags( int flags ); - virtual bool IsCommand( void ) const; - - // Install a change callback (there shouldn't already be one....) - void InstallChangeCallback( FnChangeCallback_t callback ); - - // Retrieve value - FORCEINLINE_CVAR float GetFloat( void ) const; - FORCEINLINE_CVAR int GetInt( void ) const; - FORCEINLINE_CVAR bool GetBool() const { return !!GetInt(); } - FORCEINLINE_CVAR char const *GetString( void ) const; - - // Any function that allocates/frees memory needs to be virtual or else you'll have crashes - // from alloc/free across dll/exe boundaries. - - // These just call into the IConCommandBaseAccessor to check flags and set the var (which ends up calling InternalSetValue). - virtual void SetValue( const char *value ); - virtual void SetValue( float value ); - virtual void SetValue( int value ); - - // Reset to default value - void Revert( void ); - - // True if it has a min/max setting - bool GetMin( float& minVal ) const; - bool GetMax( float& maxVal ) const; - const char *GetDefault( void ) const; - -private: - // Called by CCvar when the value of a var is changing. - virtual void InternalSetValue(const char *value); - // For CVARs marked FCVAR_NEVER_AS_STRING - virtual void InternalSetFloatValue( float fNewValue ); - virtual void InternalSetIntValue( int nValue ); - - virtual bool ClampValue( float& value ); - virtual void ChangeStringValue( const char *tempVal, float flOldValue ); - - virtual void Create( const char *pName, const char *pDefaultValue, int flags = 0, - const char *pHelpString = 0, bool bMin = false, float fMin = 0.0, - bool bMax = false, float fMax = false, FnChangeCallback_t callback = 0 ); - - // Used internally by OneTimeInit to initialize. - virtual void Init(); - -private: - - // This either points to "this" or it points to the original declaration of a ConVar. - // This allows ConVars to exist in separate modules, and they all use the first one to be declared. - // m_pParent->m_pParent must equal m_pParent (ie: m_pParent must be the root, or original, ConVar). - ConVar *m_pParent; - - // Static data - const char *m_pszDefaultValue; - - // Value - // Dynamically allocated - char *m_pszString; - int m_StringLength; - - // Values - float m_fValue; - int m_nValue; - - // Min/Max values - bool m_bHasMin; - float m_fMinVal; - bool m_bHasMax; - float m_fMaxVal; - - // Call this function when ConVar changes - FnChangeCallback_t m_fnChangeCallback; -}; - - -//----------------------------------------------------------------------------- -// Purpose: Return ConVar value as a float -// Output : float -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR float ConVar::GetFloat( void ) const -{ - return m_pParent->m_fValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Return ConVar value as an int -// Output : int -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR int ConVar::GetInt( void ) const -{ - return m_pParent->m_nValue; -} - - -//----------------------------------------------------------------------------- -// Purpose: Return ConVar value as a string, return "" for bogus string pointer, etc. -// Output : const char * -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR const char *ConVar::GetString( void ) const -{ - if ( m_nFlags & FCVAR_NEVER_AS_STRING ) - return "FCVAR_NEVER_AS_STRING"; - - return ( m_pParent->m_pszString ) ? m_pParent->m_pszString : ""; -} - - -//----------------------------------------------------------------------------- -// Used to read/write convars that already exist (replaces the FindVar method) -//----------------------------------------------------------------------------- -class ConVarRef -{ -public: - ConVarRef( const char *pName ); - ConVarRef( const char *pName, bool bIgnoreMissing ); - ConVarRef( IConVar *pConVar ); - - void Init( const char *pName, bool bIgnoreMissing ); - bool IsValid() const; - bool IsFlagSet( int nFlags ) const; - IConVar *GetLinkedConVar(); - - // Get/Set value - float GetFloat( void ) const; - int GetInt( void ) const; - bool GetBool() const { return !!GetInt(); } - const char *GetString( void ) const; - - void SetValue( const char *pValue ); - void SetValue( float flValue ); - void SetValue( int nValue ); - void SetValue( bool bValue ); - - const char *GetName() const; - - const char *GetDefault() const; - -private: - // High-speed method to read convar data - IConVar *m_pConVar; - ConVar *m_pConVarState; -}; - - -//----------------------------------------------------------------------------- -// Did we find an existing convar of that name? -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR bool ConVarRef::IsFlagSet( int nFlags ) const -{ - return ( m_pConVar->IsFlagSet( nFlags ) != 0 ); -} - -FORCEINLINE_CVAR IConVar *ConVarRef::GetLinkedConVar() -{ - return m_pConVar; -} - -FORCEINLINE_CVAR const char *ConVarRef::GetName() const -{ - return m_pConVar->GetName(); -} - - -//----------------------------------------------------------------------------- -// Purpose: Return ConVar value as a float -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR float ConVarRef::GetFloat( void ) const -{ - return m_pConVarState->m_fValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Return ConVar value as an int -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR int ConVarRef::GetInt( void ) const -{ - return m_pConVarState->m_nValue; -} - -//----------------------------------------------------------------------------- -// Purpose: Return ConVar value as a string, return "" for bogus string pointer, etc. -//----------------------------------------------------------------------------- -FORCEINLINE_CVAR const char *ConVarRef::GetString( void ) const -{ - Assert( !IsFlagSet( FCVAR_NEVER_AS_STRING ) ); - return m_pConVarState->m_pszString; -} - - -FORCEINLINE_CVAR void ConVarRef::SetValue( const char *pValue ) -{ - m_pConVar->SetValue( pValue ); -} - -FORCEINLINE_CVAR void ConVarRef::SetValue( float flValue ) -{ - m_pConVar->SetValue( flValue ); -} - -FORCEINLINE_CVAR void ConVarRef::SetValue( int nValue ) -{ - m_pConVar->SetValue( nValue ); -} - -FORCEINLINE_CVAR void ConVarRef::SetValue( bool bValue ) -{ - m_pConVar->SetValue( bValue ? 1 : 0 ); -} - -FORCEINLINE_CVAR const char *ConVarRef::GetDefault() const -{ - return m_pConVarState->m_pszDefaultValue; -} - - -//----------------------------------------------------------------------------- -// Called by the framework to register ConCommands with the ICVar -//----------------------------------------------------------------------------- -void ConVar_Register( int nCVarFlag = 0, IConCommandBaseAccessor *pAccessor = NULL ); -void ConVar_Unregister( ); - - -//----------------------------------------------------------------------------- -// Utility methods -//----------------------------------------------------------------------------- -void ConVar_PrintFlags( const ConCommandBase *var ); -void ConVar_PrintDescription( const ConCommandBase *pVar ); - - -//----------------------------------------------------------------------------- -// Purpose: Utility class to quickly allow ConCommands to call member methods -//----------------------------------------------------------------------------- -#pragma warning (disable : 4355 ) - -template< class T > -class CConCommandMemberAccessor : public ConCommand, public ICommandCallback, public ICommandCompletionCallback -{ - typedef ConCommand BaseClass; - typedef void ( T::*FnMemberCommandCallback_t )( const CCommand &command ); - typedef int ( T::*FnMemberCommandCompletionCallback_t )( const char *pPartial, CUtlVector< CUtlString > &commands ); - -public: - CConCommandMemberAccessor( T* pOwner, const char *pName, FnMemberCommandCallback_t callback, const char *pHelpString = 0, - int flags = 0, FnMemberCommandCompletionCallback_t completionFunc = 0 ) : - BaseClass( pName, this, pHelpString, flags, ( completionFunc != 0 ) ? this : NULL ) - { - m_pOwner = pOwner; - m_Func = callback; - m_CompletionFunc = completionFunc; - } - - ~CConCommandMemberAccessor() - { - Shutdown(); - } - - void SetOwner( T* pOwner ) - { - m_pOwner = pOwner; - } - - virtual void CommandCallback( const CCommand &command ) - { - Assert( m_pOwner && m_Func ); - (m_pOwner->*m_Func)( command ); - } - - virtual int CommandCompletionCallback( const char *pPartial, CUtlVector< CUtlString > &commands ) - { - Assert( m_pOwner && m_CompletionFunc ); - return (m_pOwner->*m_CompletionFunc)( pPartial, commands ); - } - -private: - T* m_pOwner; - FnMemberCommandCallback_t m_Func; - FnMemberCommandCompletionCallback_t m_CompletionFunc; -}; - -#pragma warning ( default : 4355 ) - - -//----------------------------------------------------------------------------- -// Purpose: Utility macros to quicky generate a simple console command -//----------------------------------------------------------------------------- -#define CON_COMMAND( name, description ) \ - static void name( const CCommand &args ); \ - static ConCommand name##_command( #name, name, description ); \ - static void name( const CCommand &args ) - -#define CON_COMMAND_F( name, description, flags ) \ - static void name( const CCommand &args ); \ - static ConCommand name##_command( #name, name, description, flags ); \ - static void name( const CCommand &args ) - -#define CON_COMMAND_F_COMPLETION( name, description, flags, completion ) \ - static void name( const CCommand &args ); \ - static ConCommand name##_command( #name, name, description, flags, completion ); \ - static void name( const CCommand &args ) - -#define CON_COMMAND_EXTERN( name, _funcname, description ) \ - void _funcname( const CCommand &args ); \ - static ConCommand name##_command( #name, _funcname, description ); \ - void _funcname( const CCommand &args ) - -#define CON_COMMAND_EXTERN_F( name, _funcname, description, flags ) \ - void _funcname( const CCommand &args ); \ - static ConCommand name##_command( #name, _funcname, description, flags ); \ - void _funcname( const CCommand &args ) - -#define CON_COMMAND_MEMBER_F( _thisclass, name, _funcname, description, flags ) \ - void _funcname( const CCommand &args ); \ - friend class CCommandMemberInitializer_##_funcname; \ - class CCommandMemberInitializer_##_funcname \ - { \ - public: \ - CCommandMemberInitializer_##_funcname() : m_ConCommandAccessor( NULL, name, &_thisclass::_funcname, description, flags ) \ - { \ - m_ConCommandAccessor.SetOwner( GET_OUTER( _thisclass, m_##_funcname##_register ) ); \ - } \ - private: \ - CConCommandMemberAccessor< _thisclass > m_ConCommandAccessor; \ - }; \ - \ - CCommandMemberInitializer_##_funcname m_##_funcname##_register; \ - - -#endif // CONVAR_H diff --git a/Resources/NetHook/tier1/convar_serverbounded.h b/Resources/NetHook/tier1/convar_serverbounded.h deleted file mode 100644 index 26d74dc6..00000000 --- a/Resources/NetHook/tier1/convar_serverbounded.h +++ /dev/null @@ -1,53 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Helper class for cvars that have restrictions on their value. -// -//=============================================================================// - -#ifndef CONVAR_SERVERBOUNDED_H -#define CONVAR_SERVERBOUNDED_H -#ifdef _WIN32 -#pragma once -#endif - - -// This class is used to virtualize a ConVar's value, so the client can restrict its -// value while connected to a server. When using this across modules, it's important -// to dynamic_cast it to a ConVar_ServerBounded or you won't get the restricted value. -// -// NOTE: FCVAR_USERINFO vars are not virtualized before they are sent to the server -// (we have no way to detect if the virtualized value would change), so -// if you want to use a bounded cvar's value on the server, you must rebound it -// the same way the client does. -class ConVar_ServerBounded : public ConVar -{ -public: - ConVar_ServerBounded( char const *pName, char const *pDefaultValue, int flags, char const *pHelpString ) - : ConVar( pName, pDefaultValue, flags, pHelpString ) - { - } - - ConVar_ServerBounded( char const *pName, char const *pDefaultValue, int flags, char const *pHelpString, FnChangeCallback_t callback ) - : ConVar( pName, pDefaultValue, flags, pHelpString, callback ) - { - } - - ConVar_ServerBounded( char const *pName, char const *pDefaultValue, int flags, char const *pHelpString, bool bMin, float fMin, bool bMax, float fMax ) - : ConVar( pName, pDefaultValue, flags, pHelpString, bMin, fMin, bMax, fMax ) {} - - // You must implement GetFloat. - virtual float GetFloat() const = 0; - - // You can optionally implement these. - virtual int GetInt() const { return (int)GetFloat(); } - virtual bool GetBool() const { return ( GetInt() != 0 ); } - - // Use this to get the underlying cvar's value. - float GetBaseFloatValue() const - { - return ConVar::GetFloat(); - } -}; - - -#endif // CONVAR_SERVERBOUNDED_H diff --git a/Resources/NetHook/tier1/datamanager.cpp b/Resources/NetHook/tier1/datamanager.cpp deleted file mode 100644 index 24935280..00000000 --- a/Resources/NetHook/tier1/datamanager.cpp +++ /dev/null @@ -1,410 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#include "basetypes.h" -#include "datamanager.h" - -DECLARE_POINTER_HANDLE( memhandle_t ); - -#define AUTO_LOCK_DM() AUTO_LOCK_( CDataManagerBase, *this ) - -CDataManagerBase::CDataManagerBase( unsigned int maxSize ) -{ - m_targetMemorySize = maxSize; - m_memUsed = 0; - m_lruList = m_memoryLists.CreateList(); - m_lockList = m_memoryLists.CreateList(); - m_freeList = m_memoryLists.CreateList(); - m_listsAreFreed = 0; -} - -CDataManagerBase::~CDataManagerBase() -{ - Assert( m_listsAreFreed ); -} - -void CDataManagerBase::NotifySizeChanged( memhandle_t handle, unsigned int oldSize, unsigned int newSize ) -{ - Lock(); - m_memUsed += (int)newSize - (int)oldSize; - Unlock(); -} - -void CDataManagerBase::SetTargetSize( unsigned int targetSize ) -{ - m_targetMemorySize = targetSize; -} - -unsigned int CDataManagerBase::FlushAllUnlocked() -{ - Lock(); - - int nFlush = m_memoryLists.Count( m_lruList ); - void **pScratch = (void **)_alloca( nFlush * sizeof(void *) ); - CUtlVector destroyList( pScratch, nFlush ); - - unsigned nBytesInitial = MemUsed_Inline(); - - int node = m_memoryLists.Head(m_lruList); - while ( node != m_memoryLists.InvalidIndex() ) - { - int next = m_memoryLists.Next(node); - m_memoryLists.Unlink( m_lruList, node ); - destroyList.AddToTail( GetForFreeByIndex( node ) ); - node = next; - } - - Unlock(); - - for ( int i = 0; i < nFlush; i++ ) - { - DestroyResourceStorage( destroyList[i] ); - } - - return ( nBytesInitial - MemUsed_Inline() ); -} - -unsigned int CDataManagerBase::FlushToTargetSize() -{ - return EnsureCapacity(0); -} - -// Frees everything! The LRU AND the LOCKED items. This is only used to forcibly free the resources, -// not to make space. - -unsigned int CDataManagerBase::FlushAll() -{ - Lock(); - - int nFlush = m_memoryLists.Count( m_lruList ) + m_memoryLists.Count( m_lockList ); - void **pScratch = (void **)_alloca( nFlush * sizeof(void *) ); - CUtlVector destroyList( pScratch, nFlush ); - - unsigned result = MemUsed_Inline(); - int node; - int nextNode; - - node = m_memoryLists.Head(m_lruList); - while ( node != m_memoryLists.InvalidIndex() ) - { - nextNode = m_memoryLists.Next(node); - m_memoryLists.Unlink( m_lruList, node ); - destroyList.AddToTail( GetForFreeByIndex( node ) ); - node = nextNode; - } - - node = m_memoryLists.Head(m_lockList); - while ( node != m_memoryLists.InvalidIndex() ) - { - nextNode = m_memoryLists.Next(node); - m_memoryLists.Unlink( m_lockList, node ); - m_memoryLists[node].lockCount = 0; - destroyList.AddToTail( GetForFreeByIndex( node ) ); - node = nextNode; - } - - m_listsAreFreed = false; - Unlock(); - - for ( int i = 0; i < nFlush; i++ ) - { - DestroyResourceStorage( destroyList[i] ); - } - - return result; -} - -unsigned int CDataManagerBase::Purge( unsigned int nBytesToPurge ) -{ - unsigned int nTargetSize = MemUsed_Inline() - nBytesToPurge; - if ( nTargetSize < 0 ) - nTargetSize = 0; - unsigned int nImpliedCapacity = MemTotal_Inline() - nTargetSize; - return EnsureCapacity( nImpliedCapacity ); -} - - -void CDataManagerBase::DestroyResource( memhandle_t handle ) -{ - Lock(); - unsigned short index = FromHandle( handle ); - if ( !m_memoryLists.IsValidIndex(index) ) - { - Unlock(); - return; - } - - Assert( m_memoryLists[index].lockCount == 0 ); - if ( m_memoryLists[index].lockCount ) - BreakLock( handle ); - m_memoryLists.Unlink( m_lruList, index ); - void *p = GetForFreeByIndex( index ); - Unlock(); - - DestroyResourceStorage( p ); -} - - -void *CDataManagerBase::LockResource( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - if ( m_memoryLists[memoryIndex].lockCount == 0 ) - { - m_memoryLists.Unlink( m_lruList, memoryIndex ); - m_memoryLists.LinkToTail( m_lockList, memoryIndex ); - } - Assert(m_memoryLists[memoryIndex].lockCount != (unsigned short)-1); - m_memoryLists[memoryIndex].lockCount++; - return m_memoryLists[memoryIndex].pStore; - } - - return NULL; -} - -int CDataManagerBase::UnlockResource( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - Assert( m_memoryLists[memoryIndex].lockCount > 0 ); - if ( m_memoryLists[memoryIndex].lockCount > 0 ) - { - m_memoryLists[memoryIndex].lockCount--; - if ( m_memoryLists[memoryIndex].lockCount == 0 ) - { - m_memoryLists.Unlink( m_lockList, memoryIndex ); - m_memoryLists.LinkToTail( m_lruList, memoryIndex ); - } - } - return m_memoryLists[memoryIndex].lockCount; - } - - return 0; -} - -void *CDataManagerBase::GetResource_NoLockNoLRUTouch( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - return m_memoryLists[memoryIndex].pStore; - } - return NULL; -} - - -void *CDataManagerBase::GetResource_NoLock( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - TouchByIndex( memoryIndex ); - return m_memoryLists[memoryIndex].pStore; - } - return NULL; -} - -void CDataManagerBase::TouchResource( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - TouchByIndex( FromHandle(handle) ); -} - -void CDataManagerBase::MarkAsStale( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - if ( m_memoryLists[memoryIndex].lockCount == 0 ) - { - m_memoryLists.Unlink( m_lruList, memoryIndex ); - m_memoryLists.LinkToHead( m_lruList, memoryIndex ); - } - } -} - -int CDataManagerBase::BreakLock( memhandle_t handle ) -{ - AUTO_LOCK_DM(); - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() && m_memoryLists[memoryIndex].lockCount ) - { - int nBroken = m_memoryLists[memoryIndex].lockCount; - m_memoryLists[memoryIndex].lockCount = 0; - m_memoryLists.Unlink( m_lockList, memoryIndex ); - m_memoryLists.LinkToTail( m_lruList, memoryIndex ); - - return nBroken; - } - return 0; -} - -int CDataManagerBase::BreakAllLocks() -{ - AUTO_LOCK_DM(); - int nBroken = 0; - int node; - int nextNode; - - node = m_memoryLists.Head(m_lockList); - while ( node != m_memoryLists.InvalidIndex() ) - { - nBroken++; - nextNode = m_memoryLists.Next(node); - m_memoryLists[node].lockCount = 0; - m_memoryLists.Unlink( m_lockList, node ); - m_memoryLists.LinkToTail( m_lruList, node ); - node = nextNode; - } - - return nBroken; - -} - -unsigned short CDataManagerBase::CreateHandle( bool bCreateLocked ) -{ - AUTO_LOCK_DM(); - int memoryIndex = m_memoryLists.Head(m_freeList); - unsigned short list = ( bCreateLocked ) ? m_lockList : m_lruList; - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - m_memoryLists.Unlink( m_freeList, memoryIndex ); - m_memoryLists.LinkToTail( list, memoryIndex ); - } - else - { - memoryIndex = m_memoryLists.AddToTail( list ); - } - - if ( bCreateLocked ) - { - m_memoryLists[memoryIndex].lockCount++; - } - - return memoryIndex; -} - -memhandle_t CDataManagerBase::StoreResourceInHandle( unsigned short memoryIndex, void *pStore, unsigned int realSize ) -{ - AUTO_LOCK_DM(); - resource_lru_element_t &mem = m_memoryLists[memoryIndex]; - mem.pStore = pStore; - m_memUsed += realSize; - return ToHandle(memoryIndex); -} - -void CDataManagerBase::TouchByIndex( unsigned short memoryIndex ) -{ - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - if ( m_memoryLists[memoryIndex].lockCount == 0 ) - { - m_memoryLists.Unlink( m_lruList, memoryIndex ); - m_memoryLists.LinkToTail( m_lruList, memoryIndex ); - } - } -} - -memhandle_t CDataManagerBase::ToHandle( unsigned short index ) -{ - unsigned int hiword = m_memoryLists.Element(index).serial; - hiword <<= 16; - index++; - return (memhandle_t)( hiword|index ); -} - -unsigned int CDataManagerBase::TargetSize() -{ - return MemTotal_Inline(); -} - -unsigned int CDataManagerBase::AvailableSize() -{ - return MemAvailable_Inline(); -} - - -unsigned int CDataManagerBase::UsedSize() -{ - return MemUsed_Inline(); -} - -// free resources until there is enough space to hold "size" -unsigned int CDataManagerBase::EnsureCapacity( unsigned int size ) -{ - unsigned nBytesInitial = MemUsed_Inline(); - while ( MemUsed_Inline() > MemTotal_Inline() || MemAvailable_Inline() < size ) - { - Lock(); - int lruIndex = m_memoryLists.Head( m_lruList ); - if ( lruIndex == m_memoryLists.InvalidIndex() ) - { - Unlock(); - break; - } - m_memoryLists.Unlink( m_lruList, lruIndex ); - void *p = GetForFreeByIndex( lruIndex ); - Unlock(); - DestroyResourceStorage( p ); - } - return ( nBytesInitial - MemUsed_Inline() ); -} - -// free this resource and move the handle to the free list -void *CDataManagerBase::GetForFreeByIndex( unsigned short memoryIndex ) -{ - void *p = NULL; - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - Assert( m_memoryLists[memoryIndex].lockCount == 0 ); - - resource_lru_element_t &mem = m_memoryLists[memoryIndex]; - unsigned size = GetRealSize( mem.pStore ); - if ( size > m_memUsed ) - { - ExecuteOnce( Warning( "Data manager 'used' memory incorrect\n" ) ); - size = m_memUsed; - } - m_memUsed -= size; - p = mem.pStore; - mem.pStore = NULL; - mem.serial++; - m_memoryLists.LinkToTail( m_freeList, memoryIndex ); - } - return p; -} - -// get a list of everything in the LRU -void CDataManagerBase::GetLRUHandleList( CUtlVector< memhandle_t >& list ) -{ - for ( int node = m_memoryLists.Tail(m_lruList); - node != m_memoryLists.InvalidIndex(); - node = m_memoryLists.Previous(node) ) - { - list.AddToTail( ToHandle( node ) ); - } -} - -// get a list of everything locked -void CDataManagerBase::GetLockHandleList( CUtlVector< memhandle_t >& list ) -{ - for ( int node = m_memoryLists.Head(m_lockList); - node != m_memoryLists.InvalidIndex(); - node = m_memoryLists.Next(node) ) - { - list.AddToTail( ToHandle( node ) ); - } -} - diff --git a/Resources/NetHook/tier1/datamanager.h b/Resources/NetHook/tier1/datamanager.h deleted file mode 100644 index 02181541..00000000 --- a/Resources/NetHook/tier1/datamanager.h +++ /dev/null @@ -1,277 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#ifndef RESOURCEMANAGER_H -#define RESOURCEMANAGER_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/threadtools.h" -#include "utlmultilist.h" -#include "utlvector.h" - -FORWARD_DECLARE_HANDLE( memhandle_t ); - -#define INVALID_MEMHANDLE ((memhandle_t)0xffffffff) - -class CDataManagerBase -{ -public: - - // public API - // ----------------------------------------------------------------------------- - // memhandle_t CreateResource( params ) // implemented by derived class - void DestroyResource( memhandle_t handle ); - - // type-safe implementation in derived class - //void *LockResource( memhandle_t handle ); - int UnlockResource( memhandle_t handle ); - void TouchResource( memhandle_t handle ); - void MarkAsStale( memhandle_t handle ); // move to head of LRU - - int LockCount( memhandle_t handle ); - int BreakLock( memhandle_t handle ); - int BreakAllLocks(); - - // HACKHACK: For convenience - offers no lock protection - // type-safe implementation in derived class - //void *GetResource_NoLock( memhandle_t handle ); - - unsigned int TargetSize(); - unsigned int AvailableSize(); - unsigned int UsedSize(); - - void NotifySizeChanged( memhandle_t handle, unsigned int oldSize, unsigned int newSize ); - - void SetTargetSize( unsigned int targetSize ); - - // NOTE: flush is equivalent to Destroy - unsigned int FlushAllUnlocked(); - unsigned int FlushToTargetSize(); - unsigned int FlushAll(); - unsigned int Purge( unsigned int nBytesToPurge ); - unsigned int EnsureCapacity( unsigned int size ); - - // Thread lock - virtual void Lock() {} - virtual bool TryLock() { return true; } - virtual void Unlock() {} - - // Iteration - - // ----------------------------------------------------------------------------- - - // Debugging only!!!! - void GetLRUHandleList( CUtlVector< memhandle_t >& list ); - void GetLockHandleList( CUtlVector< memhandle_t >& list ); - - -protected: - // derived class must call these to implement public API - unsigned short CreateHandle( bool bCreateLocked ); - memhandle_t StoreResourceInHandle( unsigned short memoryIndex, void *pStore, unsigned int realSize ); - void *GetResource_NoLock( memhandle_t handle ); - void *GetResource_NoLockNoLRUTouch( memhandle_t handle ); - void *LockResource( memhandle_t handle ); - - // NOTE: you must call this from the destructor of the derived class! (will assert otherwise) - void FreeAllLists() { FlushAll(); m_listsAreFreed = true; } - - CDataManagerBase( unsigned int maxSize ); - virtual ~CDataManagerBase(); - - - inline unsigned int MemTotal_Inline() const { return m_targetMemorySize; } - inline unsigned int MemAvailable_Inline() const { return m_targetMemorySize - m_memUsed; } - inline unsigned int MemUsed_Inline() const { return m_memUsed; } - -// Implemented by derived class: - virtual void DestroyResourceStorage( void * ) = 0; - virtual unsigned int GetRealSize( void * ) = 0; - - memhandle_t ToHandle( unsigned short index ); - unsigned short FromHandle( memhandle_t handle ); - - void TouchByIndex( unsigned short memoryIndex ); - void * GetForFreeByIndex( unsigned short memoryIndex ); - - // One of these is stored per active allocation - struct resource_lru_element_t - { - resource_lru_element_t() - { - lockCount = 0; - serial = 1; - pStore = 0; - } - - unsigned short lockCount; - unsigned short serial; - void *pStore; - }; - - unsigned int m_targetMemorySize; - unsigned int m_memUsed; - - CUtlMultiList< resource_lru_element_t, unsigned short > m_memoryLists; - - unsigned short m_lruList; - unsigned short m_lockList; - unsigned short m_freeList; - unsigned short m_listsAreFreed : 1; - unsigned short m_unused : 15; - -}; - -template< class STORAGE_TYPE, class CREATE_PARAMS, class LOCK_TYPE = STORAGE_TYPE *, class MUTEX_TYPE = CThreadNullMutex> -class CDataManager : public CDataManagerBase -{ - typedef CDataManagerBase BaseClass; -public: - - CDataManager( unsigned int size = (unsigned)-1 ) : BaseClass(size) {} - - - ~CDataManager() - { - // NOTE: This must be called in all implementations of CDataManager - FreeAllLists(); - } - - // Use GetData() to translate pointer to LOCK_TYPE - LOCK_TYPE LockResource( memhandle_t hMem ) - { - void *pLock = BaseClass::LockResource( hMem ); - if ( pLock ) - { - return StoragePointer(pLock)->GetData(); - } - - return NULL; - } - - // Use GetData() to translate pointer to LOCK_TYPE - LOCK_TYPE GetResource_NoLock( memhandle_t hMem ) - { - void *pLock = const_cast(BaseClass::GetResource_NoLock( hMem )); - if ( pLock ) - { - return StoragePointer(pLock)->GetData(); - } - return NULL; - } - - // Use GetData() to translate pointer to LOCK_TYPE - // Doesn't touch the memory LRU - LOCK_TYPE GetResource_NoLockNoLRUTouch( memhandle_t hMem ) - { - void *pLock = const_cast(BaseClass::GetResource_NoLockNoLRUTouch( hMem )); - if ( pLock ) - { - return StoragePointer(pLock)->GetData(); - } - return NULL; - } - - // Wrapper to match implementation of allocation with typed storage & alloc params. - memhandle_t CreateResource( const CREATE_PARAMS &createParams, bool bCreateLocked = false ) - { - BaseClass::EnsureCapacity(STORAGE_TYPE::EstimatedSize(createParams)); - unsigned short memoryIndex = BaseClass::CreateHandle( bCreateLocked ); - STORAGE_TYPE *pStore = STORAGE_TYPE::CreateResource( createParams ); - return BaseClass::StoreResourceInHandle( memoryIndex, pStore, pStore->Size() ); - } - - // Iteration. Must lock first - memhandle_t GetFirstUnlocked() - { - unsigned node = m_memoryLists.Head(m_lruList); - if ( node == m_memoryLists.InvalidIndex() ) - { - return INVALID_MEMHANDLE; - } - return ToHandle( node ); - } - - memhandle_t GetFirstLocked() - { - unsigned node = m_memoryLists.Head(m_lockList); - if ( node == m_memoryLists.InvalidIndex() ) - { - return INVALID_MEMHANDLE; - } - return ToHandle( node ); - } - - memhandle_t GetNext( memhandle_t hPrev ) - { - if ( hPrev == INVALID_MEMHANDLE ) - { - return INVALID_MEMHANDLE; - } - - unsigned short iNext = m_memoryLists.Next( FromHandle( hPrev ) ); - if ( iNext == m_memoryLists.InvalidIndex() ) - { - return INVALID_MEMHANDLE; - } - - return ToHandle( iNext ); - } - - MUTEX_TYPE &AccessMutex() { return m_mutex; } - virtual void Lock() { m_mutex.Lock(); } - virtual bool TryLock() { return m_mutex.TryLock(); } - virtual void Unlock() { m_mutex.Unlock(); } - -private: - STORAGE_TYPE *StoragePointer( void *pMem ) - { - return static_cast(pMem); - } - - virtual void DestroyResourceStorage( void *pStore ) - { - StoragePointer(pStore)->DestroyResource(); - } - - virtual unsigned int GetRealSize( void *pStore ) - { - return StoragePointer(pStore)->Size(); - } - - MUTEX_TYPE m_mutex; -}; - -//----------------------------------------------------------------------------- - -inline unsigned short CDataManagerBase::FromHandle( memhandle_t handle ) -{ - unsigned int fullWord = (unsigned int)handle; - unsigned short serial = fullWord>>16; - unsigned short index = fullWord & 0xFFFF; - index--; - if ( m_memoryLists.IsValidIndex(index) && m_memoryLists[index].serial == serial ) - return index; - return m_memoryLists.InvalidIndex(); -} - -inline int CDataManagerBase::LockCount( memhandle_t handle ) -{ - Lock(); - int result = 0; - unsigned short memoryIndex = FromHandle(handle); - if ( memoryIndex != m_memoryLists.InvalidIndex() ) - { - result = m_memoryLists[memoryIndex].lockCount; - } - Unlock(); - return result; -} - - -#endif // RESOURCEMANAGER_H diff --git a/Resources/NetHook/tier1/delegates.h b/Resources/NetHook/tier1/delegates.h deleted file mode 100644 index aa357c28..00000000 --- a/Resources/NetHook/tier1/delegates.h +++ /dev/null @@ -1,99 +0,0 @@ -//========== Copyright © 2005, Valve Corporation, All rights reserved. ======== -// -// Purpose: Simple macros to generate delegation code -// -//============================================================================= - -#ifndef DELEGATES_H -#define DELEGATES_H - -#if defined( _WIN32 ) -#pragma once -#endif - -#define DELEGATE_TO_OBJECT_0( RetType, FuncName, pDelegated ) RetType FuncName() { return (pDelegated)->FuncName(); } -#define DELEGATE_TO_OBJECT_0V( FuncName, pDelegated ) void FuncName() { (pDelegated)->FuncName(); } -#define DELEGATE_TO_OBJECT_1( RetType, FuncName, ArgType1, pDelegated ) RetType FuncName( ArgType1 a1 ) { return (pDelegated)->FuncName( a1 ); } -#define DELEGATE_TO_OBJECT_1V( FuncName, ArgType1, pDelegated ) void FuncName( ArgType1 a1 ) { (pDelegated)->FuncName( a1 ); } -#define DELEGATE_TO_OBJECT_2( RetType, FuncName, ArgType1, ArgType2, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2 ) { return (pDelegated)->FuncName( a1, a2 ); } -#define DELEGATE_TO_OBJECT_2V( FuncName, ArgType1, ArgType2, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2 ) { (pDelegated)->FuncName( a1, a2 ); } -#define DELEGATE_TO_OBJECT_3( RetType, FuncName, ArgType1, ArgType2, ArgType3, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) { return (pDelegated)->FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_OBJECT_3V( FuncName, ArgType1, ArgType2, ArgType3, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) { (pDelegated)->FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_OBJECT_4( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) { return (pDelegated)->FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_OBJECT_4V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) { (pDelegated)->FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_OBJECT_5( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) { return (pDelegated)->FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_OBJECT_5V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) { (pDelegated)->FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_OBJECT_6( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_OBJECT_6V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_OBJECT_7( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_OBJECT_7V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_OBJECT_8( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_OBJECT_8V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_OBJECT_9( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } -#define DELEGATE_TO_OBJECT_9V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } -#define DELEGATE_TO_OBJECT_11V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9, ArgType10 a10, ArgType11 a11 ) { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11 ); } - -#define DELEGATE_TO_OBJECT_0C( RetType, FuncName, pDelegated ) RetType FuncName() const { return (pDelegated)->FuncName(); } -#define DELEGATE_TO_OBJECT_0VC( FuncName, pDelegated ) void FuncName() const { (pDelegated)->FuncName(); } -#define DELEGATE_TO_OBJECT_1C( RetType, FuncName, ArgType1, pDelegated ) RetType FuncName( ArgType1 a1 ) const { return (pDelegated)->FuncName( a1 ); } -#define DELEGATE_TO_OBJECT_1VC( FuncName, ArgType1, pDelegated ) void FuncName( ArgType1 a1 ) const { (pDelegated)->FuncName( a1 ); } -#define DELEGATE_TO_OBJECT_2C( RetType, FuncName, ArgType1, ArgType2, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2 ) const { return (pDelegated)->FuncName( a1, a2 ); } -#define DELEGATE_TO_OBJECT_2VC( FuncName, ArgType1, ArgType2, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2 ) const { (pDelegated)->FuncName( a1, a2 ); } -#define DELEGATE_TO_OBJECT_3C( RetType, FuncName, ArgType1, ArgType2, ArgType3, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) const { return (pDelegated)->FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_OBJECT_3VC( FuncName, ArgType1, ArgType2, ArgType3, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) const { (pDelegated)->FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_OBJECT_4C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) const { return (pDelegated)->FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_OBJECT_4VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) const { (pDelegated)->FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_OBJECT_5C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) const { return (pDelegated)->FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_OBJECT_5VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) const { (pDelegated)->FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_OBJECT_6C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) const { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_OBJECT_6VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) const { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_OBJECT_7C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) const { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_OBJECT_7VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) const { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_OBJECT_8C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) const { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_OBJECT_8VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) const { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_OBJECT_9C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, pDelegated ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) const { return (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } -#define DELEGATE_TO_OBJECT_9VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, pDelegated ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) const { (pDelegated)->FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } - -#define DELEGATE_TO_BASE_0( RetType, FuncName, BaseClass ) RetType FuncName() { return BaseClass::FuncName(); } -#define DELEGATE_TO_BASE_0V( FuncName, BaseClass ) void FuncName() { BaseClass::FuncName(); } -#define DELEGATE_TO_BASE_1( RetType, FuncName, ArgType1, BaseClass ) RetType FuncName( ArgType1 a1 ) { return BaseClass::FuncName( a1 ); } -#define DELEGATE_TO_BASE_1V( FuncName, ArgType1, BaseClass ) void FuncName( ArgType1 a1 ) { BaseClass::FuncName( a1 ); } -#define DELEGATE_TO_BASE_2( RetType, FuncName, ArgType1, ArgType2, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2 ) { return BaseClass::FuncName( a1, a2 ); } -#define DELEGATE_TO_BASE_2V( FuncName, ArgType1, ArgType2, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2 ) { BaseClass::FuncName( a1, a2 ); } -#define DELEGATE_TO_BASE_3( RetType, FuncName, ArgType1, ArgType2, ArgType3, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) { return BaseClass::FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_BASE_3V( FuncName, ArgType1, ArgType2, ArgType3, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) { BaseClass::FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_BASE_4( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) { return BaseClass::FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_BASE_4V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) { BaseClass::FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_BASE_5( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) { return BaseClass::FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_BASE_5V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) { BaseClass::FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_BASE_6( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_BASE_6V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_BASE_7( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_BASE_7V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_BASE_8( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_BASE_8V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_BASE_9( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } -#define DELEGATE_TO_BASE_9V( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } - -#define DELEGATE_TO_BASE_0C( RetType, FuncName, BaseClass ) RetType FuncName() const { return BaseClass::FuncName(); } -#define DELEGATE_TO_BASE_0VC( FuncName, BaseClass ) void FuncName() const { BaseClass::FuncName(); } -#define DELEGATE_TO_BASE_1C( RetType, FuncName, ArgType1, BaseClass ) RetType FuncName( ArgType1 a1 ) const { return BaseClass::FuncName( a1 ); } -#define DELEGATE_TO_BASE_1VC( FuncName, ArgType1, BaseClass ) void FuncName( ArgType1 a1 ) const { BaseClass::FuncName( a1 ); } -#define DELEGATE_TO_BASE_2C( RetType, FuncName, ArgType1, ArgType2, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2 ) const { return BaseClass::FuncName( a1, a2 ); } -#define DELEGATE_TO_BASE_2VC( FuncName, ArgType1, ArgType2, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2 ) const { BaseClass::FuncName( a1, a2 ); } -#define DELEGATE_TO_BASE_3C( RetType, FuncName, ArgType1, ArgType2, ArgType3, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) const { return BaseClass::FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_BASE_3VC( FuncName, ArgType1, ArgType2, ArgType3, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) const { BaseClass::FuncName( a1, a2, a3 ); } -#define DELEGATE_TO_BASE_4C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) const { return BaseClass::FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_BASE_4VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) const { BaseClass::FuncName( a1, a2, a3, a4 ); } -#define DELEGATE_TO_BASE_5C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) const { return BaseClass::FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_BASE_5VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5 ); } -#define DELEGATE_TO_BASE_6C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) const { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_BASE_6VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6 ); } -#define DELEGATE_TO_BASE_7C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) const { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_BASE_7VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7 ); } -#define DELEGATE_TO_BASE_8C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) const { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_BASE_8VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); } -#define DELEGATE_TO_BASE_9C( RetType, FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, BaseClass ) RetType FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) const { return BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } -#define DELEGATE_TO_BASE_9VC( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, BaseClass ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); } - -#endif // DELEGATES_H diff --git a/Resources/NetHook/tier1/diff.cpp b/Resources/NetHook/tier1/diff.cpp deleted file mode 100644 index 8951193c..00000000 --- a/Resources/NetHook/tier1/diff.cpp +++ /dev/null @@ -1,547 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#include "tier0/platform.h" -#include "tier0/dbg.h" -#include "tier1/diff.h" -#include "mathlib/mathlib.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - - -// format of diff output: -// 0NN (N=1..127) copy next N literaly -// -// 1NN (N=1..127) ofs (-128..127) copy next N bytes from original, changin offset by N bytes from -// last copy end -// 100 N ofs(-32768..32767) copy next N, with larger delta offset -// 00 NNNN(1..65535) ofs(-32768..32767) big copy from old -// 80 00 NN NN NN big raw copy -// -// available codes (could be used for additonal compression ops) -// long offset form whose offset could have fit in short offset - -// note - this algorithm uses storage equal to 8* the old buffer size. 64k=.5mb - - -#define MIN_MATCH_LEN 8 -#define ACCEPTABLE_MATCH_LEN 4096 - -struct BlockPtr -{ - BlockPtr *Next; - uint8 const *dataptr; -}; - -template static inline void AddToHead(T * & head, V * node) -{ - node->Next=head; - head=node; -} - -void Fail(char const *msg) -{ - Assert(0); -} - -void ApplyDiffs(uint8 const *OldBlock, uint8 const *DiffList, - int OldSize, int DiffListSize, int &ResultListSize,uint8 *Output,uint32 OutSize) -{ - uint8 const *copy_src=OldBlock; - uint8 const *end_of_diff_list=DiffList+DiffListSize; - uint8 const *obuf=Output; - while(DiffList32767) - copy_ofs|=0xffff0000; - // printf("long cp from %x to %x len=%d\n", copy_src+copy_ofs-OldBlock,Output-obuf,copy_sz); - - memcpy(Output,copy_src+copy_ofs,copy_sz); - Output+=copy_sz; - copy_src=copy_src+copy_ofs+copy_sz; - DiffList+=4; - } - else - { - if (op & 0x80) - { - int copy_sz=op & 0x7f; - int copy_ofs; - if (copy_sz==0) - { - copy_sz=DiffList[0]; - if (copy_sz==0) - { - // big raw copy - copy_sz=DiffList[1]+256*DiffList[2]+65536*DiffList[3]; - memcpy(Output,DiffList+4,copy_sz); - // printf("big rawcopy to %x len=%d\n", Output-obuf,copy_sz); - - DiffList+=copy_sz+4; - Output+=copy_sz; - } - else - { - copy_ofs=DiffList[1]+(DiffList[2]*256); - if (copy_ofs>32767) - copy_ofs|=0xffff0000; - // printf("long ofs cp from %x to %x len=%d\n", copy_src+copy_ofs-OldBlock,Output-obuf,copy_sz); - - memcpy(Output,copy_src+copy_ofs,copy_sz); - Output+=copy_sz; - copy_src=copy_src+copy_ofs+copy_sz; - DiffList+=3; - } - } - else - { - copy_ofs=DiffList[0]; - if (copy_ofs>127) - copy_ofs|=0xffffff80; - // printf("cp from %x to %x len=%d\n", copy_src+copy_ofs-OldBlock,Output-obuf,copy_sz); - - memcpy(Output,copy_src+copy_ofs,copy_sz); - Output+=copy_sz; - copy_src=copy_src+copy_ofs+copy_sz; - DiffList++; - } - } - else - { - // printf("raw copy %d to %x\n",op & 127,Output-obuf); - memcpy(Output,DiffList,op & 127); - Output+=op & 127; - DiffList+=(op & 127); - } - } - } - ResultListSize=Output-obuf; - -} - -static void CopyPending(int len, uint8 const *rawbytes,uint8 * &outbuf, uint8 const *limit) -{ -// printf("copy raw len=%d\n",len); - if (len<128) - { - if (limit-outbuf < len+1) - Fail("diff buffer overrun"); - *(outbuf++)=len; - memcpy(outbuf,rawbytes,len); - outbuf+=len; - } - else - { - if (limit-outbuf < len+5) - Fail("diff buffer overrun"); - *(outbuf++)=0x80; - *(outbuf++)=0x00; - *(outbuf++)=(len & 255); - *(outbuf++)=((len>>8) & 255); - *(outbuf++)=((len>>16) & 255); - memcpy(outbuf,rawbytes,len); - outbuf+=len; - } -} - -static uint32 hasher(uint8 const *mdata) -{ - // attempt to scramble the bits of h1 and h2 together - uint32 ret=0; - for(int i=0;idataptr=walk; - AddToHead(HashedMatches[hash1],newnode); - walk++; - } - else - ret=1; - // now, we have the hash table which may be used to search. begin the output step - int pending_raw_len=0; - walk=NewBlock; - uint8 *outbuf=Output; - uint8 const *lastmatchend=OldBlock; - while(walkMIN_MATCH_LEN, take it - for(BlockPtr *b=HashedMatches[hash1];b;b=b->Next) - { - // find the match length - int match_of=b->dataptr-lastmatchend; - if ((match_of>-32768) && (match_of<32767)) - { - int max_mlength=min(65535,OldBlock+OldSize-b->dataptr); - max_mlength=min(max_mlength,NewBlock+NewSize-walk); - int i; - for(i=0;idataptr[i]) - break; - if ((i>MIN_MATCH_LEN) && (i>longest)) - { - longest=i; - longest_block=b; - if (longest>ACCEPTABLE_MATCH_LEN) - break; - } - } - } - } - // now, we have a match maybe - if (longest_block) - { - if (pending_raw_len) // must output - { - ret=1; - CopyPending(pending_raw_len,walk-pending_raw_len,outbuf,Output+OutSize); - pending_raw_len=0; - } - // now, output copy block - int match_of=longest_block->dataptr-lastmatchend; - int nremaining=OutSize-(outbuf-Output); - - if (match_of) - ret=1; -// printf("copy from %x to %x len=%d\n", match_of,outbuf-Output,longest); - if (longest>127) - { - // use really long encoding - if (nremaining<5) - Fail("diff buff needs increase"); - *(outbuf++)=00; - *(outbuf++)=(longest & 255); - *(outbuf++)=((longest>>8) & 255); - *(outbuf++)=(match_of & 255); - *(outbuf++)=((match_of>>8) & 255); - - } - else - { - if ((match_of>=-128) && (match_of<128)) - { - if (nremaining<2) - Fail("diff buff needs increase"); - *(outbuf++)=128+longest; - *(outbuf++)=(match_of&255); - } - else - { - // use long encoding - if (nremaining<4) - Fail("diff buff needs increase"); - *(outbuf++)=0x80; - *(outbuf++)=longest; - *(outbuf++)=(match_of & 255); - *(outbuf++)=((match_of>>8) & 255); - } - } - lastmatchend=longest_block->dataptr+longest; - walk+=longest; - } - else - { - walk++; - pending_raw_len++; - } - } - // now, flush pending raw copy - if (pending_raw_len) // must output - { - ret=1; - CopyPending(pending_raw_len,walk-pending_raw_len,outbuf,Output+OutSize); - pending_raw_len=0; - } - delete[] HashedMatches; - if (Blocks) - delete[] Blocks; - DiffListSize=outbuf-Output; - return ret; -} - - -int FindDiffs(uint8 const *NewBlock, uint8 const *OldBlock, - int NewSize, int OldSize, int &DiffListSize,uint8 *Output,uint32 OutSize) -{ - - int ret=0; - if (OldSize!=NewSize) - ret=1; - // first, build the hash table - BlockPtr *HashedMatches[65536]; - memset(HashedMatches,0,sizeof(HashedMatches)); - BlockPtr *Blocks=0; - if (OldSize) - Blocks=new BlockPtr[OldSize]; - BlockPtr *FreeList=Blocks; - // now, build the hash table - uint8 const *walk=OldBlock; - if (OldBlock && OldSize) - while(walkdataptr=walk; - AddToHead(HashedMatches[hash1],newnode); - walk++; - } - else - ret=1; - // now, we have the hash table which may be used to search. begin the output step - int pending_raw_len=0; - walk=NewBlock; - uint8 *outbuf=Output; - uint8 const *lastmatchend=OldBlock; - while(walkMIN_MATCH_LEN, take it - for(BlockPtr *b=HashedMatches[hash1];b;b=b->Next) - { - // find the match length - int match_of=b->dataptr-lastmatchend; - if ((match_of>-32768) && (match_of<32767)) - { - int max_mlength=min(65535,OldBlock+OldSize-b->dataptr); - max_mlength=min(max_mlength,NewBlock+NewSize-walk); - int i; - for(i=0;idataptr[i]) - break; - if ((i>MIN_MATCH_LEN) && (i>longest)) - { - longest=i; - longest_block=b; - } - } - } - } - // now, we have a match maybe - if (longest_block) - { - if (pending_raw_len) // must output - { - ret=1; - CopyPending(pending_raw_len,walk-pending_raw_len,outbuf,Output+OutSize); - pending_raw_len=0; - } - // now, output copy block - int match_of=longest_block->dataptr-lastmatchend; - int nremaining=OutSize-(outbuf-Output); - if (match_of) - ret=1; - if (longest>127) - { - // use really long encoding - if (nremaining<5) - Fail("diff buff needs increase"); - *(outbuf++)=00; - *(outbuf++)=(longest & 255); - *(outbuf++)=((longest>>8) & 255); - *(outbuf++)=(match_of & 255); - *(outbuf++)=((match_of>>8) & 255); - } - else - { - if ((match_of>=-128) && (match_of<128)) - { - if (nremaining<2) - Fail("diff buff needs increase"); - *(outbuf++)=128+longest; - *(outbuf++)=(match_of&255); - } - else - { - // use long encoding - if (nremaining<4) - Fail("diff buff needs increase"); - *(outbuf++)=0x80; - *(outbuf++)=longest; - *(outbuf++)=(match_of & 255); - *(outbuf++)=((match_of>>8) & 255); - } - } - lastmatchend=longest_block->dataptr+longest; - walk+=longest; - } - else - { - walk++; - pending_raw_len++; - } - } - // now, flush pending raw copy - if (pending_raw_len) // must output - { - ret=1; - CopyPending(pending_raw_len,walk-pending_raw_len,outbuf,Output+OutSize); - pending_raw_len=0; - } - if (Blocks) - delete[] Blocks; - DiffListSize=outbuf-Output; - return ret; -} - - -int FindDiffsLowMemory(uint8 const *NewBlock, uint8 const *OldBlock, - int NewSize, int OldSize, int &DiffListSize,uint8 *Output,uint32 OutSize) -{ - - int ret=0; - if (OldSize!=NewSize) - ret=1; - uint8 const *old_data_hash[256]; - memset(old_data_hash,0,sizeof(old_data_hash)); - int pending_raw_len=0; - uint8 const *walk=NewBlock; - uint8 const *oldptr=OldBlock; - uint8 *outbuf=Output; - uint8 const *lastmatchend=OldBlock; - while(walkMIN_MATCH_LEN) - { - longest_block=old_data_hash[hash1]; - longest=nmatches; - } - } - } - // now, we have a match maybe - if (longest_block) - { - if (pending_raw_len) // must output - { - ret=1; - CopyPending(pending_raw_len,walk-pending_raw_len,outbuf,Output+OutSize); - pending_raw_len=0; - } - // now, output copy block - int match_of=longest_block-lastmatchend; - int nremaining=OutSize-(outbuf-Output); - if (match_of) - ret=1; - if (longest>127) - { - // use really long encoding - if (nremaining<5) - Fail("diff buff needs increase"); - *(outbuf++)=00; - *(outbuf++)=(longest & 255); - *(outbuf++)=((longest>>8) & 255); - *(outbuf++)=(match_of & 255); - *(outbuf++)=((match_of>>8) & 255); - } - else - { - if ((match_of>=-128) && (match_of<128)) - { - if (nremaining<2) - Fail("diff buff needs increase"); - *(outbuf++)=128+longest; - *(outbuf++)=(match_of&255); - } - else - { - // use long encoding - if (nremaining<4) - Fail("diff buff needs increase"); - *(outbuf++)=0x80; - *(outbuf++)=longest; - *(outbuf++)=(match_of & 255); - *(outbuf++)=((match_of>>8) & 255); - } - } - lastmatchend=longest_block+longest; - walk+=longest; - } - else - { - walk++; - pending_raw_len++; - } - } - // now, flush pending raw copy - if (pending_raw_len) // must output - { - ret=1; - CopyPending(pending_raw_len,walk-pending_raw_len,outbuf,Output+OutSize); - pending_raw_len=0; - } - DiffListSize=outbuf-Output; - return ret; -} - - diff --git a/Resources/NetHook/tier1/diff.h b/Resources/NetHook/tier1/diff.h deleted file mode 100644 index 3828d1be..00000000 --- a/Resources/NetHook/tier1/diff.h +++ /dev/null @@ -1,29 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -// Serialization/unserialization buffer -//=============================================================================// - -#ifndef DIFF_H -#define DIFF_H -#pragma once - -int FindDiffs(uint8 const *NewBlock, uint8 const *OldBlock, - int NewSize, int OldSize, int &DiffListSize,uint8 *Output,uint32 OutSize); - -int FindDiffsForLargeFiles(uint8 const *NewBlock, uint8 const *OldBlock, - int NewSize, int OldSize, int &DiffListSize,uint8 *Output, - uint32 OutSize, - int hashsize=65536); - -void ApplyDiffs(uint8 const *OldBlock, uint8 const *DiffList, - int OldSize, int DiffListSize, int &ResultListSize,uint8 *Output,uint32 OutSize); - -int FindDiffsLowMemory(uint8 const *NewBlock, uint8 const *OldBlock, - int NewSize, int OldSize, int &DiffListSize,uint8 *Output,uint32 OutSize); - -#endif - diff --git a/Resources/NetHook/tier1/fmtstr.h b/Resources/NetHook/tier1/fmtstr.h deleted file mode 100644 index 50d9f9f2..00000000 --- a/Resources/NetHook/tier1/fmtstr.h +++ /dev/null @@ -1,82 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: A simple class for performing safe and in-expression sprintf-style -// string formatting -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef FMTSTR_H -#define FMTSTR_H - -#include -#include -#include "tier0/platform.h" -#include "tier1/strtools.h" - -#if defined( _WIN32 ) -#pragma once -#endif - -//============================================================================= - -// using macro to be compatable with GCC -#define FmtStrVSNPrintf( szBuf, nBufSize, ppszFormat ) \ - do \ - { \ - int result; \ - va_list arg_ptr; \ - \ - va_start(arg_ptr, (*(ppszFormat))); \ - result = Q_vsnprintf((szBuf), (nBufSize)-1, (*(ppszFormat)), arg_ptr); \ - va_end(arg_ptr); \ - \ - (szBuf)[(nBufSize)-1] = 0; \ - } \ - while (0) - -//----------------------------------------------------------------------------- -// -// Purpose: String formatter with specified size -// - -template -class CFmtStrN -{ -public: - CFmtStrN() { m_szBuf[0] = 0; } - - // Standard C formatting - CFmtStrN(const char *pszFormat, ...) { FmtStrVSNPrintf(m_szBuf, SIZE_BUF, &pszFormat); } - - // Use this for pass-through formatting - CFmtStrN(const char ** ppszFormat, ...) { FmtStrVSNPrintf(m_szBuf, SIZE_BUF, ppszFormat); } - - // Explicit reformat - const char *sprintf(const char *pszFormat, ...) { FmtStrVSNPrintf(m_szBuf, SIZE_BUF, &pszFormat); return m_szBuf; } - - // Use this for pass-through formatting - void VSprintf(const char **ppszFormat, ...) { FmtStrVSNPrintf(m_szBuf, SIZE_BUF, ppszFormat); } - - // Use for access - operator const char *() const { return m_szBuf; } - char *Access() { return m_szBuf; } - - void Clear() { m_szBuf[0] = 0; } - -private: - char m_szBuf[SIZE_BUF]; -}; - -//----------------------------------------------------------------------------- -// -// Purpose: Default-sized string formatter -// - -#define FMTSTR_STD_LEN 256 - -typedef CFmtStrN CFmtStr; - -//============================================================================= - -#endif // FMTSTR_H diff --git a/Resources/NetHook/tier1/functors.h b/Resources/NetHook/tier1/functors.h deleted file mode 100644 index 3619310a..00000000 --- a/Resources/NetHook/tier1/functors.h +++ /dev/null @@ -1,617 +0,0 @@ -//========== Copyright © 2006, Valve Corporation, All rights reserved. ======== -// -// Purpose: Implements a generic infrastucture for functors combining -// a number of techniques to provide transparent parameter type -// deduction and packaging. Supports both member and non-member functions. -// -// See also: http://en.wikipedia.org/wiki/Function_object -// -// Note that getting into the guts of this file is not for the -// feint of heart. The core concept here is that the compiler can -// figure out all the parameter types. -// -// E.g.: -// -// struct CMyClass -// { -// void foo( int i) {} -// }; -// -// int bar(int i) { return i; } -// -// CMyClass myInstance; -// -// CFunctor *pFunctor = CreateFunctor( &myInstance, CMyClass::foo, 8675 ); -// CFunctor *pFunctor2 = CreateFunctor( &bar, 309 ); -// -// void CallEm() -// { -// (*pFunctor)(); -// (*pFunctor2)(); -// } -// -//============================================================================= - -#ifndef FUNCTORS_H -#define FUNCTORS_H - -#include "tier0/platform.h" -#include "tier1/refcount.h" -#include "tier1/utlenvelope.h" - -#if defined( _WIN32 ) -#pragma once -#endif - -//----------------------------------------------------------------------------- -// -// Macros used as basis for template generation. Just ignore the man behind the -// curtain -// -//----------------------------------------------------------------------------- - -#define FUNC_TEMPLATE_ARG_PARAMS_0 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_0 -#define FUNC_ARG_MEMBERS_0 -#define FUNC_ARG_FORMAL_PARAMS_0 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_0 -#define FUNC_CALL_ARGS_INIT_0 -#define FUNC_CALL_MEMBER_ARGS_0 -#define FUNC_CALL_ARGS_0 -#define FUNC_FUNCTOR_CALL_ARGS_0 -#define FUNC_TEMPLATE_FUNC_PARAMS_0 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_0 - -#define FUNC_TEMPLATE_ARG_PARAMS_1 , typename ARG_TYPE_1 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_1 , ARG_TYPE_1 -#define FUNC_ARG_MEMBERS_1 ARG_TYPE_1 m_arg1 -#define FUNC_ARG_FORMAL_PARAMS_1 , const ARG_TYPE_1 &arg1 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_1 const ARG_TYPE_1 &arg1 -#define FUNC_CALL_ARGS_INIT_1 , m_arg1( arg1 ) -#define FUNC_CALL_MEMBER_ARGS_1 m_arg1 -#define FUNC_CALL_ARGS_1 arg1 -#define FUNC_FUNCTOR_CALL_ARGS_1 , arg1 -#define FUNC_TEMPLATE_FUNC_PARAMS_1 , typename FUNC_ARG_TYPE_1 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_1 FUNC_ARG_TYPE_1 - -#define FUNC_TEMPLATE_ARG_PARAMS_2 , typename ARG_TYPE_1, typename ARG_TYPE_2 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_2 , ARG_TYPE_1, ARG_TYPE_2 -#define FUNC_ARG_MEMBERS_2 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2 -#define FUNC_ARG_FORMAL_PARAMS_2 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_2 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2 -#define FUNC_CALL_ARGS_INIT_2 , m_arg1( arg1 ), m_arg2( arg2 ) -#define FUNC_CALL_MEMBER_ARGS_2 m_arg1, m_arg2 -#define FUNC_CALL_ARGS_2 arg1, arg2 -#define FUNC_FUNCTOR_CALL_ARGS_2 , arg1, arg2 -#define FUNC_TEMPLATE_FUNC_PARAMS_2 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_2 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2 - -#define FUNC_TEMPLATE_ARG_PARAMS_3 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_3 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3 -#define FUNC_ARG_MEMBERS_3 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3 -#define FUNC_ARG_FORMAL_PARAMS_3 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_3 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3 -#define FUNC_CALL_ARGS_INIT_3 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ) -#define FUNC_CALL_MEMBER_ARGS_3 m_arg1, m_arg2, m_arg3 -#define FUNC_CALL_ARGS_3 arg1, arg2, arg3 -#define FUNC_FUNCTOR_CALL_ARGS_3 , arg1, arg2, arg3 -#define FUNC_TEMPLATE_FUNC_PARAMS_3 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_3 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3 - -#define FUNC_TEMPLATE_ARG_PARAMS_4 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_4 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4 -#define FUNC_ARG_MEMBERS_4 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4 -#define FUNC_ARG_FORMAL_PARAMS_4 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_4 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4 -#define FUNC_CALL_ARGS_INIT_4 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ) -#define FUNC_CALL_MEMBER_ARGS_4 m_arg1, m_arg2, m_arg3, m_arg4 -#define FUNC_CALL_ARGS_4 arg1, arg2, arg3, arg4 -#define FUNC_FUNCTOR_CALL_ARGS_4 , arg1, arg2, arg3, arg4 -#define FUNC_TEMPLATE_FUNC_PARAMS_4 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_4 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4 - -#define FUNC_TEMPLATE_ARG_PARAMS_5 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_5 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5 -#define FUNC_ARG_MEMBERS_5 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5 -#define FUNC_ARG_FORMAL_PARAMS_5 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_5 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5 -#define FUNC_CALL_ARGS_INIT_5 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ) -#define FUNC_CALL_MEMBER_ARGS_5 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5 -#define FUNC_CALL_ARGS_5 arg1, arg2, arg3, arg4, arg5 -#define FUNC_FUNCTOR_CALL_ARGS_5 , arg1, arg2, arg3, arg4, arg5 -#define FUNC_TEMPLATE_FUNC_PARAMS_5 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_5 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5 - -#define FUNC_TEMPLATE_ARG_PARAMS_6 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_6 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6 -#define FUNC_ARG_MEMBERS_6 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6 -#define FUNC_ARG_FORMAL_PARAMS_6 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_6 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6 -#define FUNC_CALL_ARGS_INIT_6 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ) -#define FUNC_CALL_MEMBER_ARGS_6 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6 -#define FUNC_CALL_ARGS_6 arg1, arg2, arg3, arg4, arg5, arg6 -#define FUNC_FUNCTOR_CALL_ARGS_6 , arg1, arg2, arg3, arg4, arg5, arg6 -#define FUNC_TEMPLATE_FUNC_PARAMS_6 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_6 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6 - -#define FUNC_TEMPLATE_ARG_PARAMS_7 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_7 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7 -#define FUNC_ARG_MEMBERS_7 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; -#define FUNC_ARG_FORMAL_PARAMS_7 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_7 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7 -#define FUNC_CALL_ARGS_INIT_7 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ) -#define FUNC_CALL_MEMBER_ARGS_7 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7 -#define FUNC_CALL_ARGS_7 arg1, arg2, arg3, arg4, arg5, arg6, arg7 -#define FUNC_FUNCTOR_CALL_ARGS_7 , arg1, arg2, arg3, arg4, arg5, arg6, arg7 -#define FUNC_TEMPLATE_FUNC_PARAMS_7 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_7 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7 - -#define FUNC_TEMPLATE_ARG_PARAMS_8 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_8 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8 -#define FUNC_ARG_MEMBERS_8 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; -#define FUNC_ARG_FORMAL_PARAMS_8 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_8 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8 -#define FUNC_CALL_ARGS_INIT_8 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ) -#define FUNC_CALL_MEMBER_ARGS_8 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8 -#define FUNC_CALL_ARGS_8 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 -#define FUNC_FUNCTOR_CALL_ARGS_8 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 -#define FUNC_TEMPLATE_FUNC_PARAMS_8 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_8 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8 - -#define FUNC_TEMPLATE_ARG_PARAMS_9 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8, typename ARG_TYPE_9 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_9 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8, ARG_TYPE_9 -#define FUNC_ARG_MEMBERS_9 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; ARG_TYPE_9 m_arg9; -#define FUNC_ARG_FORMAL_PARAMS_9 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_9 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9 -#define FUNC_CALL_ARGS_INIT_9 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ), m_arg9( arg9 ) -#define FUNC_CALL_MEMBER_ARGS_9 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8, m_arg9 -#define FUNC_CALL_ARGS_9 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 -#define FUNC_FUNCTOR_CALL_ARGS_9 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 -#define FUNC_TEMPLATE_FUNC_PARAMS_9 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8, typename FUNC_ARG_TYPE_9 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_9 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8, FUNC_ARG_TYPE_9 - -#define FUNC_TEMPLATE_ARG_PARAMS_10 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8, typename ARG_TYPE_9, typename ARG_TYPE_10 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_10 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8, ARG_TYPE_9, ARG_TYPE_10 -#define FUNC_ARG_MEMBERS_10 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; ARG_TYPE_9 m_arg9; ARG_TYPE_10 m_arg10; -#define FUNC_ARG_FORMAL_PARAMS_10 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_10 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10 -#define FUNC_CALL_ARGS_INIT_10 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ), m_arg9( arg9 ), m_arg10( arg10 ) -#define FUNC_CALL_MEMBER_ARGS_10 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8, m_arg9, m_arg10 -#define FUNC_CALL_ARGS_10 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 -#define FUNC_FUNCTOR_CALL_ARGS_10 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 -#define FUNC_TEMPLATE_FUNC_PARAMS_10 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8, typename FUNC_ARG_TYPE_9, typename FUNC_ARG_TYPE_10 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_10 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8, FUNC_ARG_TYPE_9, FUNC_ARG_TYPE_10 - -#define FUNC_TEMPLATE_ARG_PARAMS_11 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8, typename ARG_TYPE_9, typename ARG_TYPE_10, typename ARG_TYPE_11 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_11 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8, ARG_TYPE_9, ARG_TYPE_10, ARG_TYPE_11 -#define FUNC_ARG_MEMBERS_11 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; ARG_TYPE_9 m_arg9; ARG_TYPE_10 m_arg10; ARG_TYPE_11 m_arg11 -#define FUNC_ARG_FORMAL_PARAMS_11 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_11 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11 -#define FUNC_CALL_ARGS_INIT_11 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ), m_arg9( arg9 ), m_arg10( arg10 ), m_arg11( arg11 ) -#define FUNC_CALL_MEMBER_ARGS_11 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8, m_arg9, m_arg10, m_arg11 -#define FUNC_CALL_ARGS_11 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 -#define FUNC_FUNCTOR_CALL_ARGS_11 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 -#define FUNC_TEMPLATE_FUNC_PARAMS_11 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8, typename FUNC_ARG_TYPE_9, typename FUNC_ARG_TYPE_10, typename FUNC_ARG_TYPE_11 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_11 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8, FUNC_ARG_TYPE_9, FUNC_ARG_TYPE_10, FUNC_ARG_TYPE_11 - -#define FUNC_TEMPLATE_ARG_PARAMS_12 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8, typename ARG_TYPE_9, typename ARG_TYPE_10, typename ARG_TYPE_11, typename ARG_TYPE_12 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_12 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8, ARG_TYPE_9, ARG_TYPE_10, ARG_TYPE_11, ARG_TYPE_12 -#define FUNC_ARG_MEMBERS_12 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; ARG_TYPE_9 m_arg9; ARG_TYPE_10 m_arg10; ARG_TYPE_11 m_arg11; ARG_TYPE_12 m_arg12 -#define FUNC_ARG_FORMAL_PARAMS_12 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11, const ARG_TYPE_12 &arg12 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_12 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11, const ARG_TYPE_12 &arg12 -#define FUNC_CALL_ARGS_INIT_12 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ), m_arg9( arg9 ), m_arg10( arg10 ), m_arg11( arg11 ), m_arg12( arg12 ) -#define FUNC_CALL_MEMBER_ARGS_12 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8, m_arg9, m_arg10, m_arg11, m_arg12 -#define FUNC_CALL_ARGS_12 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 -#define FUNC_FUNCTOR_CALL_ARGS_12 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12 -#define FUNC_TEMPLATE_FUNC_PARAMS_12 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8, typename FUNC_ARG_TYPE_9, typename FUNC_ARG_TYPE_10, typename FUNC_ARG_TYPE_11, typename FUNC_ARG_TYPE_12 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_12 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8, FUNC_ARG_TYPE_9, FUNC_ARG_TYPE_10, FUNC_ARG_TYPE_11, FUNC_ARG_TYPE_12 - -#define FUNC_TEMPLATE_ARG_PARAMS_13 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8, typename ARG_TYPE_9, typename ARG_TYPE_10, typename ARG_TYPE_11, typename ARG_TYPE_12, typename ARG_TYPE_13 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_13 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8, ARG_TYPE_9, ARG_TYPE_10, ARG_TYPE_11, ARG_TYPE_12, ARG_TYPE_13 -#define FUNC_ARG_MEMBERS_13 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; ARG_TYPE_9 m_arg9; ARG_TYPE_10 m_arg10; ARG_TYPE_11 m_arg11; ARG_TYPE_12 m_arg12; ARG_TYPE_13 m_arg13 -#define FUNC_ARG_FORMAL_PARAMS_13 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11, const ARG_TYPE_12 &arg12, const ARG_TYPE_13 &arg13 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_13 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11, const ARG_TYPE_12 &arg12, const ARG_TYPE_13 &arg13 -#define FUNC_CALL_ARGS_INIT_13 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ), m_arg9( arg9 ), m_arg10( arg10 ), m_arg11( arg11 ), m_arg12( arg12 ), m_arg13( arg13 ) -#define FUNC_CALL_MEMBER_ARGS_13 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8, m_arg9, m_arg10, m_arg11, m_arg12, m_arg13 -#define FUNC_CALL_ARGS_13 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13 -#define FUNC_FUNCTOR_CALL_ARGS_13 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13 -#define FUNC_TEMPLATE_FUNC_PARAMS_13 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8, typename FUNC_ARG_TYPE_9, typename FUNC_ARG_TYPE_10, typename FUNC_ARG_TYPE_11, typename FUNC_ARG_TYPE_12, typename FUNC_ARG_TYPE_13 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_13 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8, FUNC_ARG_TYPE_9, FUNC_ARG_TYPE_10, FUNC_ARG_TYPE_11, FUNC_ARG_TYPE_12, FUNC_ARG_TYPE_13 - -#define FUNC_TEMPLATE_ARG_PARAMS_14 , typename ARG_TYPE_1, typename ARG_TYPE_2, typename ARG_TYPE_3, typename ARG_TYPE_4, typename ARG_TYPE_5, typename ARG_TYPE_6, typename ARG_TYPE_7, typename ARG_TYPE_8, typename ARG_TYPE_9, typename ARG_TYPE_10, typename ARG_TYPE_11, typename ARG_TYPE_12, typename ARG_TYPE_13, typename ARG_TYPE_14 -#define FUNC_BASE_TEMPLATE_ARG_PARAMS_14 , ARG_TYPE_1, ARG_TYPE_2, ARG_TYPE_3, ARG_TYPE_4, ARG_TYPE_5, ARG_TYPE_6, ARG_TYPE_7, ARG_TYPE_8, ARG_TYPE_9, ARG_TYPE_10, ARG_TYPE_11, ARG_TYPE_12, ARG_TYPE_13, ARG_TYPE_14 -#define FUNC_ARG_MEMBERS_14 ARG_TYPE_1 m_arg1; ARG_TYPE_2 m_arg2; ARG_TYPE_3 m_arg3; ARG_TYPE_4 m_arg4; ARG_TYPE_5 m_arg5; ARG_TYPE_6 m_arg6; ARG_TYPE_7 m_arg7; ARG_TYPE_8 m_arg8; ARG_TYPE_9 m_arg9; ARG_TYPE_10 m_arg10; ARG_TYPE_11 m_arg11; ARG_TYPE_12 m_arg12; ARG_TYPE_13 m_arg13; ARG_TYPE_14 m_arg14 -#define FUNC_ARG_FORMAL_PARAMS_14 , const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11, const ARG_TYPE_12 &arg12, const ARG_TYPE_13 &arg13, const ARG_TYPE_14 &arg14 -#define FUNC_PROXY_ARG_FORMAL_PARAMS_14 const ARG_TYPE_1 &arg1, const ARG_TYPE_2 &arg2, const ARG_TYPE_3 &arg3, const ARG_TYPE_4 &arg4, const ARG_TYPE_5 &arg5, const ARG_TYPE_6 &arg6, const ARG_TYPE_7 &arg7, const ARG_TYPE_8 &arg8, const ARG_TYPE_9 &arg9, const ARG_TYPE_10 &arg10, const ARG_TYPE_11 &arg11, const ARG_TYPE_12 &arg12, const ARG_TYPE_13 &arg13, const ARG_TYPE_14 &arg14 -#define FUNC_CALL_ARGS_INIT_14 , m_arg1( arg1 ), m_arg2( arg2 ), m_arg3( arg3 ), m_arg4( arg4 ), m_arg5( arg5 ), m_arg6( arg6 ), m_arg7( arg7 ), m_arg8( arg8 ), m_arg9( arg9 ), m_arg10( arg10 ), m_arg11( arg11 ), m_arg12( arg12 ), m_arg13( arg13 ), m_arg14( arg14 ) -#define FUNC_CALL_MEMBER_ARGS_14 m_arg1, m_arg2, m_arg3, m_arg4, m_arg5, m_arg6, m_arg7, m_arg8, m_arg9, m_arg10, m_arg11, m_arg12, m_arg13, m_arg14 -#define FUNC_CALL_ARGS_14 arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14 -#define FUNC_FUNCTOR_CALL_ARGS_14 , arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14 -#define FUNC_TEMPLATE_FUNC_PARAMS_14 , typename FUNC_ARG_TYPE_1, typename FUNC_ARG_TYPE_2, typename FUNC_ARG_TYPE_3, typename FUNC_ARG_TYPE_4, typename FUNC_ARG_TYPE_5, typename FUNC_ARG_TYPE_6, typename FUNC_ARG_TYPE_7, typename FUNC_ARG_TYPE_8, typename FUNC_ARG_TYPE_9, typename FUNC_ARG_TYPE_10, typename FUNC_ARG_TYPE_11, typename FUNC_ARG_TYPE_12, typename FUNC_ARG_TYPE_13, typename FUNC_ARG_TYPE_14 -#define FUNC_BASE_TEMPLATE_FUNC_PARAMS_14 FUNC_ARG_TYPE_1, FUNC_ARG_TYPE_2, FUNC_ARG_TYPE_3, FUNC_ARG_TYPE_4, FUNC_ARG_TYPE_5, FUNC_ARG_TYPE_6, FUNC_ARG_TYPE_7, FUNC_ARG_TYPE_8, FUNC_ARG_TYPE_9, FUNC_ARG_TYPE_10, FUNC_ARG_TYPE_11, FUNC_ARG_TYPE_12, FUNC_ARG_TYPE_13, FUNC_ARG_TYPE_14 - -#define FUNC_GENERATE_ALL( INNERMACRONAME ) \ - INNERMACRONAME(0); \ - INNERMACRONAME(1); \ - INNERMACRONAME(2); \ - INNERMACRONAME(3); \ - INNERMACRONAME(4); \ - INNERMACRONAME(5); \ - INNERMACRONAME(6); \ - INNERMACRONAME(7); \ - INNERMACRONAME(8); \ - INNERMACRONAME(9); \ - INNERMACRONAME(10);\ - INNERMACRONAME(11);\ - INNERMACRONAME(12);\ - INNERMACRONAME(13);\ - INNERMACRONAME(14) - -//----------------------------------------------------------------------------- -// -// Purpose: Base class of all function objects -// -//----------------------------------------------------------------------------- - -abstract_class CFunctor : public IRefCounted -{ -public: - CFunctor() - { -#ifdef DEBUG - m_nUserID = 0; -#endif - } - virtual void operator()() = 0; - - unsigned m_nUserID; // For debugging -}; - - -//----------------------------------------------------------------------------- -// When calling through a functor, care needs to be taken to not pass objects that might go away. -// Since this code determines the type to store in the functor based on the actual arguments, -// this is achieved by changing the point of call. -// -// See also CUtlEnvelope -//----------------------------------------------------------------------------- - -// convert a reference to a passable value -template -inline T RefToVal(const T &item) -{ - return item; -} - -//----------------------------------------------------------------------------- -// This class can be used to pass into a functor a proxy object for a pointer -// to be resolved later. For example, you can execute a "call" on a resource -// whose actual value is not known until a later time -//----------------------------------------------------------------------------- - -template -class CLateBoundPtr -{ -public: - CLateBoundPtr( T **ppObject ) - : m_ppObject( ppObject ) - { - } - - T *operator->() { return *m_ppObject; } - T &operator *() { return **m_ppObject; } - operator T *() const { return (T*)(*m_ppObject); } - operator void *() { return *m_ppObject; } - -private: - T **m_ppObject; -}; - -//----------------------------------------------------------------------------- -// -// Purpose: Classes to define memory management policies when operating -// on pointers to members -// -//----------------------------------------------------------------------------- - -class CFuncMemPolicyNone -{ -public: - static void OnAcquire(void *pObject) {} - static void OnRelease(void *pObject) {} -}; - -template -class CFuncMemPolicyRefCount -{ -public: - static void OnAcquire(OBJECT_TYPE_PTR pObject) { pObject->AddRef(); } - static void OnRelease(OBJECT_TYPE_PTR pObject) { pObject->Release(); } -}; - -//----------------------------------------------------------------------------- -// -// Purpose: Function proxy is a generic facility for holding a function -// pointer. Can be used on own, though primarily for use -// by this file -// -//----------------------------------------------------------------------------- - -template -class CMemberFuncProxyBase -{ -protected: - CMemberFuncProxyBase( OBJECT_TYPE_PTR pObject, FUNCTION_TYPE pfnProxied ) - : m_pObject( pObject ), - m_pfnProxied( pfnProxied ) - { - MEM_POLICY::OnAcquire(m_pObject); - } - - ~CMemberFuncProxyBase() - { - MEM_POLICY::OnRelease(m_pObject); - } - - void Set( OBJECT_TYPE_PTR pObject, FUNCTION_TYPE pfnProxied ) - { - m_pfnProxied = pfnProxied; - m_pObject = pObject; - } - - void OnCall() - { - Assert( (void *)m_pObject != NULL ); - } - - FUNCTION_TYPE m_pfnProxied; - OBJECT_TYPE_PTR m_pObject; -}; - - -#define DEFINE_MEMBER_FUNC_PROXY( N ) \ - template \ - class CMemberFuncProxy##N : public CMemberFuncProxyBase \ - { \ - public: \ - CMemberFuncProxy##N( OBJECT_TYPE_PTR pObject = NULL, FUNCTION_TYPE pfnProxied = NULL ) \ - : CMemberFuncProxyBase( pObject, pfnProxied ) \ - { \ - } \ - \ - void operator()( FUNC_PROXY_ARG_FORMAL_PARAMS_##N ) \ - { \ - this->OnCall(); \ - ((*this->m_pObject).*this->m_pfnProxied)( FUNC_CALL_ARGS_##N ); \ - } \ - } - -FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNC_PROXY ); - - -//----------------------------------------------------------------------------- -// -// The actual functor implementation -// -//----------------------------------------------------------------------------- - -#include "tier0/memdbgon.h" - -typedef CRefCounted1 CFunctorBase; - -#define DEFINE_FUNCTOR_TEMPLATE(N) \ - template \ - class CFunctor##N : public CFunctorBase \ - { \ - public: \ - CFunctor##N( FUNC_TYPE pfnProxied FUNC_ARG_FORMAL_PARAMS_##N ) : m_pfnProxied( pfnProxied ) FUNC_CALL_ARGS_INIT_##N {} \ - void operator()() { m_pfnProxied(FUNC_CALL_MEMBER_ARGS_##N); } \ - \ - private: \ - FUNC_TYPE m_pfnProxied; \ - FUNC_ARG_MEMBERS_##N; \ - } - -FUNC_GENERATE_ALL( DEFINE_FUNCTOR_TEMPLATE ); - -#define DEFINE_MEMBER_FUNCTOR( N ) \ - template \ - class CMemberFunctor##N : public FUNCTOR_BASE \ - { \ - public: \ - CMemberFunctor##N( OBJECT_TYPE_PTR pObject, FUNCTION_TYPE pfnProxied FUNC_ARG_FORMAL_PARAMS_##N ) : m_Proxy( pObject, pfnProxied ) FUNC_CALL_ARGS_INIT_##N {} \ - void operator()() { m_Proxy(FUNC_CALL_MEMBER_ARGS_##N); } \ - \ - private: \ - CMemberFuncProxy##N m_Proxy; \ - FUNC_ARG_MEMBERS_##N; \ - }; - - -FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNCTOR ); - -//----------------------------------------------------------------------------- -// -// The real magic, letting the compiler figure out all the right template parameters -// -//----------------------------------------------------------------------------- - -#define DEFINE_NONMEMBER_FUNCTOR_FACTORY(N) \ - template \ - inline CFunctor *CreateFunctor(FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - typedef FUNCTION_RETTYPE (*Func_t)(FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N); \ - return new CFunctor##N( pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ); \ - } - -FUNC_GENERATE_ALL( DEFINE_NONMEMBER_FUNCTOR_FACTORY ); - -//------------------------------------- - -#define DEFINE_MEMBER_FUNCTOR_FACTORY(N) \ -template \ -inline CFunctor *CreateFunctor(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ -{ \ - return new CMemberFunctor##N(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ -} - -FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNCTOR_FACTORY ); - -//------------------------------------- - -#define DEFINE_CONST_MEMBER_FUNCTOR_FACTORY(N) \ - template \ - inline CFunctor *CreateFunctor(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new CMemberFunctor##N(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - -FUNC_GENERATE_ALL( DEFINE_CONST_MEMBER_FUNCTOR_FACTORY ); - -//------------------------------------- - -#define DEFINE_REF_COUNTING_MEMBER_FUNCTOR_FACTORY(N) \ - template \ - inline CFunctor *CreateRefCountingFunctor(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new CMemberFunctor##N >(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - -FUNC_GENERATE_ALL( DEFINE_REF_COUNTING_MEMBER_FUNCTOR_FACTORY ); - -//------------------------------------- - -#define DEFINE_REF_COUNTING_CONST_MEMBER_FUNCTOR_FACTORY(N) \ - template \ - inline CFunctor *CreateRefCountingFunctor(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new CMemberFunctor##N >(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - -FUNC_GENERATE_ALL( DEFINE_REF_COUNTING_CONST_MEMBER_FUNCTOR_FACTORY ); - -//----------------------------------------------------------------------------- -// -// Templates to assist early-out direct call code -// -//----------------------------------------------------------------------------- - -#define DEFINE_NONMEMBER_FUNCTOR_DIRECT(N) \ - template \ - inline void FunctorDirectCall(FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ -{ \ - (*pfnProxied)( FUNC_CALL_ARGS_##N ); \ -} - -FUNC_GENERATE_ALL( DEFINE_NONMEMBER_FUNCTOR_DIRECT ); - - -//------------------------------------- - -#define DEFINE_MEMBER_FUNCTOR_DIRECT(N) \ - template \ - inline void FunctorDirectCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ -{ \ - ((*pObject).*pfnProxied)(FUNC_CALL_ARGS_##N); \ -} - -FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNCTOR_DIRECT ); - -//------------------------------------- - -#define DEFINE_CONST_MEMBER_FUNCTOR_DIRECT(N) \ - template \ - inline void FunctorDirectCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ -{ \ - ((*pObject).*pfnProxied)(FUNC_CALL_ARGS_##N); \ -} - -FUNC_GENERATE_ALL( DEFINE_CONST_MEMBER_FUNCTOR_DIRECT ); - -#include "tier0/memdbgoff.h" - -//----------------------------------------------------------------------------- -// Factory class useable as templated traits -//----------------------------------------------------------------------------- - -class CDefaultFunctorFactory -{ -public: - FUNC_GENERATE_ALL( DEFINE_NONMEMBER_FUNCTOR_FACTORY ); - FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNCTOR_FACTORY ); - FUNC_GENERATE_ALL( DEFINE_CONST_MEMBER_FUNCTOR_FACTORY ); - FUNC_GENERATE_ALL( DEFINE_REF_COUNTING_MEMBER_FUNCTOR_FACTORY ); - FUNC_GENERATE_ALL( DEFINE_REF_COUNTING_CONST_MEMBER_FUNCTOR_FACTORY ); -}; - -template -class CCustomizedFunctorFactory -{ -public: - void SetAllocator( CAllocator *pAllocator ) - { - m_pAllocator = pAllocator; - } - - #define DEFINE_NONMEMBER_FUNCTOR_FACTORY_CUSTOM(N) \ - template \ - inline CFunctor *CreateFunctor( FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - typedef FUNCTION_RETTYPE (*Func_t)(FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N); \ - return new (m_pAllocator->Alloc( sizeof(CFunctor##N) )) CFunctor##N( pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ); \ - } - - FUNC_GENERATE_ALL( DEFINE_NONMEMBER_FUNCTOR_FACTORY_CUSTOM ); - - //------------------------------------- - - #define DEFINE_MEMBER_FUNCTOR_FACTORY_CUSTOM(N) \ - template \ - inline CFunctor *CreateFunctor(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new (m_pAllocator->Alloc( sizeof(CMemberFunctor##N) )) CMemberFunctor##N(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - - FUNC_GENERATE_ALL( DEFINE_MEMBER_FUNCTOR_FACTORY_CUSTOM ); - - //------------------------------------- - - #define DEFINE_CONST_MEMBER_FUNCTOR_FACTORY_CUSTOM(N) \ - template \ - inline CFunctor *CreateFunctor( OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new (m_pAllocator->Alloc( sizeof(CMemberFunctor##N) )) CMemberFunctor##N(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - - FUNC_GENERATE_ALL( DEFINE_CONST_MEMBER_FUNCTOR_FACTORY_CUSTOM ); - - //------------------------------------- - - #define DEFINE_REF_COUNTING_MEMBER_FUNCTOR_FACTORY_CUSTOM(N) \ - template \ - inline CFunctor *CreateRefCountingFunctor( OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new (m_pAllocator->Alloc( sizeof(CMemberFunctor##N >) )) CMemberFunctor##N >(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - - FUNC_GENERATE_ALL( DEFINE_REF_COUNTING_MEMBER_FUNCTOR_FACTORY_CUSTOM ); - - //------------------------------------- - - #define DEFINE_REF_COUNTING_CONST_MEMBER_FUNCTOR_FACTORY_CUSTOM(N) \ - template \ - inline CFunctor *CreateRefCountingFunctor( OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \ - { \ - return new (m_pAllocator->Alloc( sizeof(CMemberFunctor##N >) )) CMemberFunctor##N >(pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N); \ - } - - FUNC_GENERATE_ALL( DEFINE_REF_COUNTING_CONST_MEMBER_FUNCTOR_FACTORY_CUSTOM ); - -private: - CAllocator *m_pAllocator; - -}; - -//----------------------------------------------------------------------------- - -#endif // FUNCTORS_H diff --git a/Resources/NetHook/tier1/generichash.cpp b/Resources/NetHook/tier1/generichash.cpp deleted file mode 100644 index af784fc4..00000000 --- a/Resources/NetHook/tier1/generichash.cpp +++ /dev/null @@ -1,303 +0,0 @@ -//======= Copyright © 2005, , Valve Corporation, All rights reserved. ========= -// -// Purpose: Variant Pearson Hash general purpose hashing algorithm described -// by Cargill in C++ Report 1994. Generates a 16-bit result. -// -//============================================================================= - -#include -#include "tier0/basetypes.h" -#include "tier0/platform.h" -#include "generichash.h" -#include - -//----------------------------------------------------------------------------- -// -// Table of randomly shuffled values from 0-255 generated by: -// -//----------------------------------------------------------------------------- -/* -void MakeRandomValues() -{ - int i, j, r; - unsigned t; - srand( 0xdeadbeef ); - - for ( i = 0; i < 256; i++ ) - { - g_nRandomValues[i] = (unsigned )i; - } - - for (j = 0; j < 8; j++) - { - for (i = 0; i < 256; i++) - { - r = rand() & 0xff; - t = g_nRandomValues[i]; - g_nRandomValues[i] = g_nRandomValues[r]; - g_nRandomValues[r] = t; - } - } - - printf("static unsigned g_nRandomValues[256] =\n{\n"); - - for (i = 0; i < 256; i += 16) - { - printf("\t"); - for (j = 0; j < 16; j++) - printf(" %3d,", g_nRandomValues[i+j]); - printf("\n"); - } - printf("};\n"); -} -*/ - -static unsigned g_nRandomValues[256] = -{ - 238, 164, 191, 168, 115, 16, 142, 11, 213, 214, 57, 151, 248, 252, 26, 198, - 13, 105, 102, 25, 43, 42, 227, 107, 210, 251, 86, 66, 83, 193, 126, 108, - 131, 3, 64, 186, 192, 81, 37, 158, 39, 244, 14, 254, 75, 30, 2, 88, - 172, 176, 255, 69, 0, 45, 116, 139, 23, 65, 183, 148, 33, 46, 203, 20, - 143, 205, 60, 197, 118, 9, 171, 51, 233, 135, 220, 49, 71, 184, 82, 109, - 36, 161, 169, 150, 63, 96, 173, 125, 113, 67, 224, 78, 232, 215, 35, 219, - 79, 181, 41, 229, 149, 153, 111, 217, 21, 72, 120, 163, 133, 40, 122, 140, - 208, 231, 211, 200, 160, 182, 104, 110, 178, 237, 15, 101, 27, 50, 24, 189, - 177, 130, 187, 92, 253, 136, 100, 212, 19, 174, 70, 22, 170, 206, 162, 74, - 247, 5, 47, 32, 179, 117, 132, 195, 124, 123, 245, 128, 236, 223, 12, 84, - 54, 218, 146, 228, 157, 94, 106, 31, 17, 29, 194, 34, 56, 134, 239, 246, - 241, 216, 127, 98, 7, 204, 154, 152, 209, 188, 48, 61, 87, 97, 225, 85, - 90, 167, 155, 112, 145, 114, 141, 93, 250, 4, 201, 156, 38, 89, 226, 196, - 1, 235, 44, 180, 159, 121, 119, 166, 190, 144, 10, 91, 76, 230, 221, 80, - 207, 55, 58, 53, 175, 8, 6, 52, 68, 242, 18, 222, 103, 249, 147, 129, - 138, 243, 28, 185, 62, 59, 240, 202, 234, 99, 77, 73, 199, 137, 95, 165, -}; - -//----------------------------------------------------------------------------- -// String -//----------------------------------------------------------------------------- -unsigned FASTCALL HashString( const char *pszKey ) -{ - const uint8 *k = (const uint8 *)pszKey; - unsigned even = 0, - odd = 0, - n; - - while ((n = *k++) != 0) - { - even = g_nRandomValues[odd ^ n]; - if ((n = *k++) != 0) - odd = g_nRandomValues[even ^ n]; - else - break; - } - - return (even << 8) | odd ; -} - - -//----------------------------------------------------------------------------- -// Case-insensitive string -//----------------------------------------------------------------------------- -unsigned FASTCALL HashStringCaseless( const char *pszKey ) -{ - const uint8 *k = (const uint8 *) pszKey; - unsigned even = 0, - odd = 0, - n; - - while ((n = toupper(*k++)) != 0) - { - even = g_nRandomValues[odd ^ n]; - if ((n = toupper(*k++)) != 0) - odd = g_nRandomValues[even ^ n]; - else - break; - } - - return (even << 8) | odd; -} - -//----------------------------------------------------------------------------- -// 32 bit conventional case-insensitive string -//----------------------------------------------------------------------------- -unsigned FASTCALL HashStringCaselessConventional( const char *pszKey ) -{ - unsigned hash = 0xAAAAAAAA; // Alternating 1's and 0's to maximize the effect of the later multiply and add - - for( ; *pszKey ; pszKey++ ) - { - hash = ( ( hash << 5 ) + hash ) + (uint8)tolower(*pszKey); - } - - return hash; -} - -//----------------------------------------------------------------------------- -// int hash -//----------------------------------------------------------------------------- -unsigned FASTCALL HashInt( const int n ) -{ - register unsigned even, odd; - even = g_nRandomValues[n & 0xff]; - odd = g_nRandomValues[((n >> 8) & 0xff)]; - - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ (n >> 16) & 0xff]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - return (even << 8) | odd; -} - -//----------------------------------------------------------------------------- -// 4-byte hash -//----------------------------------------------------------------------------- -unsigned FASTCALL Hash4( const void *pKey ) -{ - register const uint32 * p = (const uint32 *) pKey; - register unsigned even, - odd, - n; - n = *p; - even = g_nRandomValues[n & 0xff]; - odd = g_nRandomValues[((n >> 8) & 0xff)]; - - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ (n >> 16) & 0xff]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - return (even << 8) | odd; -} - - -//----------------------------------------------------------------------------- -// 8-byte hash -//----------------------------------------------------------------------------- -unsigned FASTCALL Hash8( const void *pKey ) -{ - register const uint32 * p = (const uint32 *) pKey; - register unsigned even, - odd, - n; - n = *p; - even = g_nRandomValues[n & 0xff]; - odd = g_nRandomValues[((n >> 8) & 0xff)]; - - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ (n >> 16) & 0xff]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - n = *(p+1); - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ ((n >> 16) & 0xff)]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - return (even << 8) | odd; -} - - -//----------------------------------------------------------------------------- -// 12-byte hash -//----------------------------------------------------------------------------- -unsigned FASTCALL Hash12( const void *pKey ) -{ - register const uint32 * p = (const uint32 *) pKey; - register unsigned even, - odd, - n; - n = *p; - even = g_nRandomValues[n & 0xff]; - odd = g_nRandomValues[((n >> 8) & 0xff)]; - - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ (n >> 16) & 0xff]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - n = *(p+1); - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ ((n >> 16) & 0xff)]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - n = *(p+2); - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ ((n >> 16) & 0xff)]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - return (even << 8) | odd; -} - - -//----------------------------------------------------------------------------- -// 16-byte hash -//----------------------------------------------------------------------------- -unsigned FASTCALL Hash16( const void *pKey ) -{ - register const uint32 * p = (const uint32 *) pKey; - register unsigned even, - odd, - n; - n = *p; - even = g_nRandomValues[n & 0xff]; - odd = g_nRandomValues[((n >> 8) & 0xff)]; - - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ (n >> 16) & 0xff]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - n = *(p+1); - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ ((n >> 16) & 0xff)]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - n = *(p+2); - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ ((n >> 16) & 0xff)]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - n = *(p+3); - even = g_nRandomValues[odd ^ (n >> 24)]; - odd = g_nRandomValues[even ^ ((n >> 16) & 0xff)]; - even = g_nRandomValues[odd ^ ((n >> 8) & 0xff)]; - odd = g_nRandomValues[even ^ (n & 0xff)]; - - return (even << 8) | odd; -} - - -//----------------------------------------------------------------------------- -// Arbitrary fixed length hash -//----------------------------------------------------------------------------- -unsigned FASTCALL HashBlock( const void *pKey, unsigned size ) -{ - const uint8 * k = (const uint8 *) pKey; - unsigned even = 0, - odd = 0, - n; - - while (size) - { - --size; - n = *k++; - even = g_nRandomValues[odd ^ n]; - if (size) - { - --size; - n = *k++; - odd = g_nRandomValues[even ^ n]; - } - else - break; - } - - return (even << 8) | odd; -} - diff --git a/Resources/NetHook/tier1/generichash.h b/Resources/NetHook/tier1/generichash.h deleted file mode 100644 index 057ca971..00000000 --- a/Resources/NetHook/tier1/generichash.h +++ /dev/null @@ -1,92 +0,0 @@ -//======= Copyright © 2005, , Valve Corporation, All rights reserved. ========= -// -// Purpose: Variant Pearson Hash general purpose hashing algorithm described -// by Cargill in C++ Report 1994. Generates a 16-bit result. -// -//============================================================================= - -#ifndef GENERICHASH_H -#define GENERICHASH_H - -#if defined(_WIN32) -#pragma once -#endif - -//----------------------------------------------------------------------------- - -unsigned FASTCALL HashString( const char *pszKey ); -unsigned FASTCALL HashStringCaseless( const char *pszKey ); -unsigned FASTCALL HashStringCaselessConventional( const char *pszKey ); -unsigned FASTCALL Hash4( const void *pKey ); -unsigned FASTCALL Hash8( const void *pKey ); -unsigned FASTCALL Hash12( const void *pKey ); -unsigned FASTCALL Hash16( const void *pKey ); -unsigned FASTCALL HashBlock( const void *pKey, unsigned size ); - -unsigned FASTCALL HashInt( const int key ); - -inline unsigned HashIntConventional( const int n ) // faster but less effective -{ - // first byte - unsigned hash = 0xAAAAAAAA + (n & 0xFF); - // second byte - hash = ( hash << 5 ) + hash + ( (n >> 8) & 0xFF ); - // third byte - hash = ( hash << 5 ) + hash + ( (n >> 16) & 0xFF ); - // fourth byte - hash = ( hash << 5 ) + hash + ( (n >> 24) & 0xFF ); - - return hash; - - /* this is the old version, which would cause a load-hit-store on every - line on a PowerPC, and therefore took hundreds of clocks to execute! - - byte *p = (byte *)&n; - unsigned hash = 0xAAAAAAAA + *p++; - hash = ( ( hash << 5 ) + hash ) + *p++; - hash = ( ( hash << 5 ) + hash ) + *p++; - return ( ( hash << 5 ) + hash ) + *p; - */ -} - -//----------------------------------------------------------------------------- - -template -inline unsigned HashItem( const T &item ) -{ - // TODO: Confirm comiler optimizes out unused paths - if ( sizeof(item) == 4 ) - return Hash4( &item ); - else if ( sizeof(item) == 8 ) - return Hash8( &item ); - else if ( sizeof(item) == 12 ) - return Hash12( &item ); - else if ( sizeof(item) == 16 ) - return Hash16( &item ); - else - return HashBlock( &item, sizeof(item) ); -} - -template <> inline unsigned HashItem(const int &key ) -{ - return HashInt( key ); -} - -template <> inline unsigned HashItem(const unsigned &key ) -{ - return HashInt( (int)key ); -} - -template<> inline unsigned HashItem(const char * const &pszKey ) -{ - return HashString( pszKey ); -} - -template<> inline unsigned HashItem(char * const &pszKey ) -{ - return HashString( pszKey ); -} - -//----------------------------------------------------------------------------- - -#endif /* !GENERICHASH_H */ diff --git a/Resources/NetHook/tier1/iconvar.h b/Resources/NetHook/tier1/iconvar.h deleted file mode 100644 index 53a7e126..00000000 --- a/Resources/NetHook/tier1/iconvar.h +++ /dev/null @@ -1,114 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// -//----------------------------------------------------------------------------- -// $NoKeywords: $ -//===========================================================================// - -#ifndef ICONVAR_H -#define ICONVAR_H - -#if _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "tier0/platform.h" -#include "tier1/strtools.h" - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -class IConVar; -class CCommand; - - -//----------------------------------------------------------------------------- -// ConVar flags -//----------------------------------------------------------------------------- -// The default, no flags at all -#define FCVAR_NONE 0 - -// Command to ConVars and ConCommands -// ConVar Systems -#define FCVAR_UNREGISTERED (1<<0) // If this is set, don't add to linked list, etc. -#define FCVAR_DEVELOPMENTONLY (1<<1) // Hidden in released products. Flag is removed automatically if ALLOW_DEVELOPMENT_CVARS is defined. -#define FCVAR_GAMEDLL (1<<2) // defined by the game DLL -#define FCVAR_CLIENTDLL (1<<3) // defined by the client DLL -#define FCVAR_HIDDEN (1<<4) // Hidden. Doesn't appear in find or autocomplete. Like DEVELOPMENTONLY, but can't be compiled out. - -// ConVar only -#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. Sends 1 if it's not bland/zero, 0 otherwise as value -#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server. -#define FCVAR_ARCHIVE (1<<7) // set to cause it to be saved to vars.rc -#define FCVAR_NOTIFY (1<<8) // notifies players when changed -#define FCVAR_USERINFO (1<<9) // changes the client's info string -#define FCVAR_CHEAT (1<<14) // Only useable in singleplayer / debug / multiplayer & sv_cheats - -#define FCVAR_PRINTABLEONLY (1<<10) // This cvar's string cannot contain unprintable characters ( e.g., used for player name etc ). -#define FCVAR_UNLOGGED (1<<11) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log -#define FCVAR_NEVER_AS_STRING (1<<12) // never try to print that cvar - -// It's a ConVar that's shared between the client and the server. -// At signon, the values of all such ConVars are sent from the server to the client (skipped for local -// client, of course ) -// If a change is requested it must come from the console (i.e., no remote client changes) -// If a value is changed while a server is active, it's replicated to all connected clients -#define FCVAR_REPLICATED (1<<13) // server setting enforced on clients, TODO rename to FCAR_SERVER at some time -#define FCVAR_DEMO (1<<16) // record this cvar when starting a demo file -#define FCVAR_DONTRECORD (1<<17) // don't record these command in demofiles - -#define FCVAR_NOT_CONNECTED (1<<22) // cvar cannot be changed by a client that is connected to a server - -#define FCVAR_ARCHIVE_XBOX (1<<24) // cvar written to config.cfg on the Xbox - -#define FCVAR_SERVER_CAN_EXECUTE (1<<28)// the server is allowed to execute this command on clients via ClientCommand/NET_StringCmd/CBaseClientState::ProcessStringCmd. -#define FCVAR_SERVER_CANNOT_QUERY (1<<29)// If this is set, then the server is not allowed to query this cvar's value (via IServerPluginHelpers::StartQueryCvarValue). -#define FCVAR_CLIENTCMD_CAN_EXECUTE (1<<30) // IVEngineClient::ClientCmd is allowed to execute this command. - // Note: IVEngineClient::ClientCmd_Unrestricted can run any client command. - -// #define FCVAR_AVAILABLE (1<<15) -// #define FCVAR_AVAILABLE (1<<18) -// #define FCVAR_AVAILABLE (1<<19) -// #define FCVAR_AVAILABLE (1<<20) -// #define FCVAR_AVAILABLE (1<<21) -// #define FCVAR_AVAILABLE (1<<23) -// #define FCVAR_AVAILABLE (1<<25) -// #define FCVAR_AVAILABLE (1<<26) -// #define FCVAR_AVAILABLE (1<<27) -// #define FCVAR_AVAILABLE (1<<31) - - -//----------------------------------------------------------------------------- -// Called when a ConVar changes value -// NOTE: For FCVAR_NEVER_AS_STRING ConVars, pOldValue == NULL -//----------------------------------------------------------------------------- -typedef void ( *FnChangeCallback_t )( IConVar *var, const char *pOldValue, float flOldValue ); - - -//----------------------------------------------------------------------------- -// Abstract interface for ConVars -//----------------------------------------------------------------------------- -abstract_class IConVar -{ -public: - // Value set - virtual void SetValue( const char *pValue ) = 0; - virtual void SetValue( float flValue ) = 0; - virtual void SetValue( int nValue ) = 0; - - // Return name of command - virtual const char *GetName( void ) const = 0; - - // Accessors.. not as efficient as using GetState()/GetInfo() - // if you call these methods multiple times on the same IConVar - virtual bool IsFlagSet( int nFlag ) const = 0; -}; - - -#endif // ICONVAR_H diff --git a/Resources/NetHook/tier1/interface.cpp b/Resources/NetHook/tier1/interface.cpp deleted file mode 100644 index 0e87b614..00000000 --- a/Resources/NetHook/tier1/interface.cpp +++ /dev/null @@ -1,462 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// -#if defined( _WIN32 ) && !defined( _X360 ) -#include -#endif - -#if !defined( DONT_PROTECT_FILEIO_FUNCTIONS ) -#define DONT_PROTECT_FILEIO_FUNCTIONS // for protected_things.h -#endif - -#if defined( PROTECTED_THINGS_ENABLE ) -#undef PROTECTED_THINGS_ENABLE // from protected_things.h -#endif - -#include -#include "interface.h" -#include "basetypes.h" -#include "tier0/dbg.h" -#include -#include -#include "tier1/strtools.h" -#include "tier0/icommandline.h" -#include "tier0/dbg.h" -#include "tier0/threadtools.h" -#ifdef _WIN32 -#include // getcwd -#elif _LINUX -#define _getcwd getcwd -#endif -#if defined( _X360 ) -#include "xbox/xbox_win32stubs.h" -#endif - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -// ------------------------------------------------------------------------------------ // -// InterfaceReg. -// ------------------------------------------------------------------------------------ // -InterfaceReg *InterfaceReg::s_pInterfaceRegs = NULL; - -InterfaceReg::InterfaceReg( InstantiateInterfaceFn fn, const char *pName ) : - m_pName(pName) -{ - m_CreateFn = fn; - m_pNext = s_pInterfaceRegs; - s_pInterfaceRegs = this; -} - -// ------------------------------------------------------------------------------------ // -// CreateInterface. -// This is the primary exported function by a dll, referenced by name via dynamic binding -// that exposes an opqaue function pointer to the interface. -// ------------------------------------------------------------------------------------ // -void* CreateInterface( const char *pName, int *pReturnCode ) -{ - InterfaceReg *pCur; - - for (pCur=InterfaceReg::s_pInterfaceRegs; pCur; pCur=pCur->m_pNext) - { - if (strcmp(pCur->m_pName, pName) == 0) - { - if (pReturnCode) - { - *pReturnCode = IFACE_OK; - } - return pCur->m_CreateFn(); - } - } - - if (pReturnCode) - { - *pReturnCode = IFACE_FAILED; - } - return NULL; -} - - -#ifdef _LINUX -// Linux doesn't have this function so this emulates its functionality -void *GetModuleHandle(const char *name) -{ - void *handle; - - if( name == NULL ) - { - // hmm, how can this be handled under linux.... - // is it even needed? - return NULL; - } - - if( (handle=dlopen(name, RTLD_NOW))==NULL) - { - printf("DLOPEN Error:%s\n",dlerror()); - // couldn't open this file - return NULL; - } - - // read "man dlopen" for details - // in short dlopen() inc a ref count - // so dec the ref count by performing the close - dlclose(handle); - return handle; -} -#endif - -#if defined( _WIN32 ) && !defined( _X360 ) -#define WIN32_LEAN_AND_MEAN -#include "windows.h" -#endif - -//----------------------------------------------------------------------------- -// Purpose: returns a pointer to a function, given a module -// Input : pModuleName - module name -// *pName - proc name -//----------------------------------------------------------------------------- -static void *Sys_GetProcAddress( const char *pModuleName, const char *pName ) -{ - HMODULE hModule = GetModuleHandle( pModuleName ); - return GetProcAddress( hModule, pName ); -} - -static void *Sys_GetProcAddress( HMODULE hModule, const char *pName ) -{ - return GetProcAddress( hModule, pName ); -} - -bool Sys_IsDebuggerPresent() -{ - return Plat_IsInDebugSession(); -} - -struct ThreadedLoadLibaryContext_t -{ - const char *m_pLibraryName; - HMODULE m_hLibrary; -}; - -#ifdef _WIN32 - -// wraps LoadLibraryEx() since 360 doesn't support that -static HMODULE InternalLoadLibrary( const char *pName ) -{ -#if defined(_X360) - return LoadLibrary( pName ); -#else - return LoadLibraryEx( pName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH ); -#endif -} -unsigned ThreadedLoadLibraryFunc( void *pParam ) -{ - ThreadedLoadLibaryContext_t *pContext = (ThreadedLoadLibaryContext_t*)pParam; - pContext->m_hLibrary = InternalLoadLibrary(pContext->m_pLibraryName); - return 0; -} -#endif - -HMODULE Sys_LoadLibrary( const char *pLibraryName ) -{ - char str[1024]; -#if defined( _WIN32 ) && !defined( _X360 ) - const char *pModuleExtension = ".dll"; - const char *pModuleAddition = pModuleExtension; -#elif defined( _X360 ) - const char *pModuleExtension = "_360.dll"; - const char *pModuleAddition = pModuleExtension; -#elif defined( _LINUX ) - const char *pModuleExtension = ".so"; - const char *pModuleAddition = "_i486.so"; // if an extension is on the filename assume the i486 binary set -#endif - Q_strncpy( str, pLibraryName, sizeof(str) ); - if ( !Q_stristr( str, pModuleExtension ) ) - { - if ( IsX360() ) - { - Q_StripExtension( str, str, sizeof(str) ); - } - Q_strncat( str, pModuleAddition, sizeof(str) ); - } - Q_FixSlashes( str ); - -#ifdef _WIN32 - ThreadedLoadLibraryFunc_t threadFunc = GetThreadedLoadLibraryFunc(); - if ( !threadFunc ) - return InternalLoadLibrary( str ); - - ThreadedLoadLibaryContext_t context; - context.m_pLibraryName = str; - context.m_hLibrary = 0; - - ThreadHandle_t h = CreateSimpleThread( ThreadedLoadLibraryFunc, &context ); - -#ifdef _X360 - ThreadSetAffinity( h, XBOX_PROCESSOR_3 ); -#endif - - unsigned int nTimeout = 0; - while( ThreadWaitForObject( h, true, nTimeout ) == TW_TIMEOUT ) - { - nTimeout = threadFunc(); - } - - ReleaseThreadHandle( h ); - return context.m_hLibrary; - -#elif _LINUX - HMODULE ret = dlopen( str, RTLD_NOW ); - if ( ! ret ) - { - const char *pError = dlerror(); - if ( pError && ( strstr( pError, "No such file" ) == 0 ) ) - { - Msg( " failed to dlopen %s error=%s\n", str, pError ); - - } - } - - return ret; -#endif -} - -//----------------------------------------------------------------------------- -// Purpose: Loads a DLL/component from disk and returns a handle to it -// Input : *pModuleName - filename of the component -// Output : opaque handle to the module (hides system dependency) -//----------------------------------------------------------------------------- -CSysModule *Sys_LoadModule( const char *pModuleName ) -{ - // If using the Steam filesystem, either the DLL must be a minimum footprint - // file in the depot (MFP) or a filesystem GetLocalCopy() call must be made - // prior to the call to this routine. - char szCwd[1024]; - HMODULE hDLL = NULL; - - if ( !Q_IsAbsolutePath( pModuleName ) ) - { - // full path wasn't passed in, using the current working dir - _getcwd( szCwd, sizeof( szCwd ) ); - if ( IsX360() ) - { - int i = CommandLine()->FindParm( "-basedir" ); - if ( i ) - { - strcpy( szCwd, CommandLine()->GetParm( i+1 ) ); - } - } - if (szCwd[strlen(szCwd) - 1] == '/' || szCwd[strlen(szCwd) - 1] == '\\' ) - { - szCwd[strlen(szCwd) - 1] = 0; - } - - char szAbsoluteModuleName[1024]; - if ( strstr( pModuleName, "bin/") == pModuleName ) - { - // don't make bin/bin path - Q_snprintf( szAbsoluteModuleName, sizeof(szAbsoluteModuleName), "%s/%s", szCwd, pModuleName ); - } - else - { - Q_snprintf( szAbsoluteModuleName, sizeof(szAbsoluteModuleName), "%s/bin/%s", szCwd, pModuleName ); - } - hDLL = Sys_LoadLibrary( szAbsoluteModuleName ); - } - - if ( !hDLL ) - { - // full path failed, let LoadLibrary() try to search the PATH now - hDLL = Sys_LoadLibrary( pModuleName ); -#if defined( _DEBUG ) - if ( !hDLL ) - { -// So you can see what the error is in the debugger... -#if defined( _WIN32 ) && !defined( _X360 ) - char *lpMsgBuf; - - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &lpMsgBuf, - 0, - NULL - ); - - LocalFree( (HLOCAL)lpMsgBuf ); -#elif defined( _X360 ) - Msg( "Failed to load %s:\n", pModuleName ); -#else - Error( "Failed to load %s: %s\n", pModuleName, dlerror() ); -#endif // _WIN32 - } -#endif // DEBUG - } - - // If running in the debugger, assume debug binaries are okay, otherwise they must run with -allowdebug - if ( !IsX360() && hDLL && - !CommandLine()->FindParm( "-allowdebug" ) && - !Sys_IsDebuggerPresent() ) - { - if ( Sys_GetProcAddress( hDLL, "BuiltDebug" ) ) - { - Error( "Module %s is a debug build\n", pModuleName ); - } - } - - return reinterpret_cast(hDLL); -} - - -//----------------------------------------------------------------------------- -// Purpose: Unloads a DLL/component from -// Input : *pModuleName - filename of the component -// Output : opaque handle to the module (hides system dependency) -//----------------------------------------------------------------------------- -void Sys_UnloadModule( CSysModule *pModule ) -{ - if ( !pModule ) - return; - - HMODULE hDLL = reinterpret_cast(pModule); - -#ifdef _WIN32 - FreeLibrary( hDLL ); -#elif defined(_LINUX) - dlclose((void *)hDLL); -#endif -} - -//----------------------------------------------------------------------------- -// Purpose: returns a pointer to a function, given a module -// Input : module - windows HMODULE from Sys_LoadModule() -// *pName - proc name -// Output : factory for this module -//----------------------------------------------------------------------------- -CreateInterfaceFn Sys_GetFactory( CSysModule *pModule ) -{ - if ( !pModule ) - return NULL; - - HMODULE hDLL = reinterpret_cast(pModule); -#ifdef _WIN32 - return reinterpret_cast(GetProcAddress( hDLL, CREATEINTERFACE_PROCNAME )); -#elif defined(_LINUX) - // Linux gives this error: - //../public/interface.cpp: In function `IBaseInterface *(*Sys_GetFactory - //(CSysModule *)) (const char *, int *)': - //../public/interface.cpp:154: ISO C++ forbids casting between - //pointer-to-function and pointer-to-object - // - // so lets get around it :) - return (CreateInterfaceFn)(GetProcAddress( hDLL, CREATEINTERFACE_PROCNAME )); -#endif -} - -//----------------------------------------------------------------------------- -// Purpose: returns the instance of this module -// Output : interface_instance_t -//----------------------------------------------------------------------------- -CreateInterfaceFn Sys_GetFactoryThis( void ) -{ - return CreateInterface; -} - -//----------------------------------------------------------------------------- -// Purpose: returns the instance of the named module -// Input : *pModuleName - name of the module -// Output : interface_instance_t - instance of that module -//----------------------------------------------------------------------------- -CreateInterfaceFn Sys_GetFactory( const char *pModuleName ) -{ -#ifdef _WIN32 - return static_cast( Sys_GetProcAddress( pModuleName, CREATEINTERFACE_PROCNAME ) ); -#elif defined(_LINUX) - // see Sys_GetFactory( CSysModule *pModule ) for an explanation - return (CreateInterfaceFn)( Sys_GetProcAddress( pModuleName, CREATEINTERFACE_PROCNAME ) ); -#endif -} - -//----------------------------------------------------------------------------- -// Purpose: get the interface for the specified module and version -// Input : -// Output : -//----------------------------------------------------------------------------- -bool Sys_LoadInterface( - const char *pModuleName, - const char *pInterfaceVersionName, - CSysModule **pOutModule, - void **pOutInterface ) -{ - CSysModule *pMod = Sys_LoadModule( pModuleName ); - if ( !pMod ) - return false; - - CreateInterfaceFn fn = Sys_GetFactory( pMod ); - if ( !fn ) - { - Sys_UnloadModule( pMod ); - return false; - } - - *pOutInterface = fn( pInterfaceVersionName, NULL ); - if ( !( *pOutInterface ) ) - { - Sys_UnloadModule( pMod ); - return false; - } - - if ( pOutModule ) - *pOutModule = pMod; - - return true; -} - -//----------------------------------------------------------------------------- -// Purpose: Place this as a singleton at module scope (e.g.) and use it to get the factory from the specified module name. -// -// When the singleton goes out of scope (.dll unload if at module scope), -// then it'll call Sys_UnloadModule on the module so that the refcount is decremented -// and the .dll actually can unload from memory. -//----------------------------------------------------------------------------- -CDllDemandLoader::CDllDemandLoader( char const *pchModuleName ) : - m_pchModuleName( pchModuleName ), - m_hModule( 0 ), - m_bLoadAttempted( false ) -{ -} - -CDllDemandLoader::~CDllDemandLoader() -{ - Unload(); -} - -CreateInterfaceFn CDllDemandLoader::GetFactory() -{ - if ( !m_hModule && !m_bLoadAttempted ) - { - m_bLoadAttempted = true; - m_hModule = Sys_LoadModule( m_pchModuleName ); - } - - if ( !m_hModule ) - { - return NULL; - } - - return Sys_GetFactory( m_hModule ); -} - -void CDllDemandLoader::Unload() -{ - if ( m_hModule ) - { - Sys_UnloadModule( m_hModule ); - m_hModule = 0; - } -} diff --git a/Resources/NetHook/tier1/interface.h b/Resources/NetHook/tier1/interface.h deleted file mode 100644 index 73ed499a..00000000 --- a/Resources/NetHook/tier1/interface.h +++ /dev/null @@ -1,219 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -// This header defines the interface convention used in the valve engine. -// To make an interface and expose it: -// 1. The interface must be ALL pure virtuals, and have no data members. -// 2. Define a name for it. -// 3. In its implementation file, use EXPOSE_INTERFACE or EXPOSE_SINGLE_INTERFACE. - -// Versioning -// There are two versioning cases that are handled by this: -// 1. You add functions to the end of an interface, so it is binary compatible with the previous interface. In this case, -// you need two EXPOSE_INTERFACEs: one to expose your class as the old interface and one to expose it as the new interface. -// 2. You update an interface so it's not compatible anymore (but you still want to be able to expose the old interface -// for legacy code). In this case, you need to make a new version name for your new interface, and make a wrapper interface and -// expose it for the old interface. - -// Static Linking: -// Must mimic unique seperate class 'InterfaceReg' constructors per subsystem. -// Each subsystem can then import and export interfaces as expected. -// This is achieved through unique namespacing 'InterfaceReg' via symbol _SUBSYSTEM. -// Static Linking also needs to generate unique symbols per interface so as to -// provide a 'stitching' method whereby these interface symbols can be referenced -// via the lib's primary module (usually the lib's interface exposure) -// therby stitching all of that lib's code/data together for eventual final exe link inclusion. - -#ifndef INTERFACE_H -#define INTERFACE_H - -#ifdef _WIN32 -#pragma once -#endif - -#ifdef _LINUX -#include // dlopen,dlclose, et al -#include - -#define HMODULE void * -#define GetProcAddress dlsym - -#define _snprintf snprintf -#endif - -// TODO: move interface.cpp into tier0 library. -#include "tier0/platform.h" - -// All interfaces derive from this. -class IBaseInterface -{ -public: - virtual ~IBaseInterface() {} -}; - -#if !defined( _X360 ) -#define CREATEINTERFACE_PROCNAME "CreateInterface" -#else -// x360 only allows ordinal exports, .def files export "CreateInterface" at 1 -#define CREATEINTERFACE_PROCNAME ((const char*)1) -#endif - -typedef void* (*CreateInterfaceFn)(const char *pName, int *pReturnCode); -typedef void* (*InstantiateInterfaceFn)(); - -// Used internally to register classes. -class InterfaceReg -{ -public: - InterfaceReg(InstantiateInterfaceFn fn, const char *pName); - -public: - InstantiateInterfaceFn m_CreateFn; - const char *m_pName; - - InterfaceReg *m_pNext; // For the global list. - static InterfaceReg *s_pInterfaceRegs; -}; - -// Use this to expose an interface that can have multiple instances. -// e.g.: -// EXPOSE_INTERFACE( CInterfaceImp, IInterface, "MyInterface001" ) -// This will expose a class called CInterfaceImp that implements IInterface (a pure class) -// clients can receive a pointer to this class by calling CreateInterface( "MyInterface001" ) -// -// In practice, the shared header file defines the interface (IInterface) and version name ("MyInterface001") -// so that each component can use these names/vtables to communicate -// -// A single class can support multiple interfaces through multiple inheritance -// -// Use this if you want to write the factory function. -#if !defined(_STATIC_LINKED) || !defined(_SUBSYSTEM) -#define EXPOSE_INTERFACE_FN(functionName, interfaceName, versionName) \ - static InterfaceReg __g_Create##interfaceName##_reg(functionName, versionName); -#else -#define EXPOSE_INTERFACE_FN(functionName, interfaceName, versionName) \ - namespace _SUBSYSTEM \ - { \ - static InterfaceReg __g_Create##interfaceName##_reg(functionName, versionName); \ - } -#endif - -#if !defined(_STATIC_LINKED) || !defined(_SUBSYSTEM) -#define EXPOSE_INTERFACE(className, interfaceName, versionName) \ - static void* __Create##className##_interface() {return static_cast( new className );} \ - static InterfaceReg __g_Create##className##_reg(__Create##className##_interface, versionName ); -#else -#define EXPOSE_INTERFACE(className, interfaceName, versionName) \ - namespace _SUBSYSTEM \ - { \ - static void* __Create##className##_interface() {return static_cast( new className );} \ - static InterfaceReg __g_Create##className##_reg(__Create##className##_interface, versionName ); \ - } -#endif - -// Use this to expose a singleton interface with a global variable you've created. -#if !defined(_STATIC_LINKED) || !defined(_SUBSYSTEM) -#define EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, globalVarName) \ - static void* __Create##className##interfaceName##_interface() {return static_cast( &globalVarName );} \ - static InterfaceReg __g_Create##className##interfaceName##_reg(__Create##className##interfaceName##_interface, versionName); -#else -#define EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, globalVarName) \ - namespace _SUBSYSTEM \ - { \ - static void* __Create##className##interfaceName##_interface() {return static_cast( &globalVarName );} \ - static InterfaceReg __g_Create##className##interfaceName##_reg(__Create##className##interfaceName##_interface, versionName); \ - } -#endif - -// Use this to expose a singleton interface. This creates the global variable for you automatically. -#if !defined(_STATIC_LINKED) || !defined(_SUBSYSTEM) -#define EXPOSE_SINGLE_INTERFACE(className, interfaceName, versionName) \ - static className __g_##className##_singleton; \ - EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, __g_##className##_singleton) -#else -#define EXPOSE_SINGLE_INTERFACE(className, interfaceName, versionName) \ - namespace _SUBSYSTEM \ - { \ - static className __g_##className##_singleton; \ - } \ - EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, __g_##className##_singleton) -#endif - -// load/unload components -class CSysModule; - -// interface return status -enum -{ - IFACE_OK = 0, - IFACE_FAILED -}; - -//----------------------------------------------------------------------------- -// This function is automatically exported and allows you to access any interfaces exposed with the above macros. -// if pReturnCode is set, it will return one of the following values (IFACE_OK, IFACE_FAILED) -// extend this for other error conditions/code -//----------------------------------------------------------------------------- -DLL_EXPORT void* CreateInterface(const char *pName, int *pReturnCode); - -#if defined( _X360 ) -DLL_EXPORT void *CreateInterfaceThunk( const char *pName, int *pReturnCode ); -#endif - -//----------------------------------------------------------------------------- -// UNDONE: This is obsolete, use the module load/unload/get instead!!! -//----------------------------------------------------------------------------- -extern CreateInterfaceFn Sys_GetFactory( CSysModule *pModule ); -extern CreateInterfaceFn Sys_GetFactory( const char *pModuleName ); -extern CreateInterfaceFn Sys_GetFactoryThis( void ); - -//----------------------------------------------------------------------------- -// Load & Unload should be called in exactly one place for each module -// The factory for that module should be passed on to dependent components for -// proper versioning. -//----------------------------------------------------------------------------- -extern CSysModule *Sys_LoadModule( const char *pModuleName ); -extern void Sys_UnloadModule( CSysModule *pModule ); - -// This is a helper function to load a module, get its factory, and get a specific interface. -// You are expected to free all of these things. -// Returns false and cleans up if any of the steps fail. -bool Sys_LoadInterface( - const char *pModuleName, - const char *pInterfaceVersionName, - CSysModule **pOutModule, - void **pOutInterface ); - -bool Sys_IsDebuggerPresent(); - -//----------------------------------------------------------------------------- -// Purpose: Place this as a singleton at module scope (e.g.) and use it to get the factory from the specified module name. -// -// When the singleton goes out of scope (.dll unload if at module scope), -// then it'll call Sys_UnloadModule on the module so that the refcount is decremented -// and the .dll actually can unload from memory. -//----------------------------------------------------------------------------- -class CDllDemandLoader -{ -public: - CDllDemandLoader( char const *pchModuleName ); - virtual ~CDllDemandLoader(); - CreateInterfaceFn GetFactory(); - void Unload(); - -private: - - char const *m_pchModuleName; - CSysModule *m_hModule; - bool m_bLoadAttempted; -}; - -#endif - - - diff --git a/Resources/NetHook/tier1/lzmaDecoder.h b/Resources/NetHook/tier1/lzmaDecoder.h deleted file mode 100644 index 197fd6bf..00000000 --- a/Resources/NetHook/tier1/lzmaDecoder.h +++ /dev/null @@ -1,42 +0,0 @@ -//========= Copyright © 1996-2007, Valve Corporation, All rights reserved. ============// -// -// LZMA Decoder. Designed for run time decoding. -// -// LZMA SDK 4.43 Copyright (c) 1999-2006 Igor Pavlov (2006-05-01) -// http://www.7-zip.org/ -// -//=====================================================================================// - -#ifndef _LZMADECODER_H -#define _LZMADECODER_H -#pragma once - -#if !defined( _X360 ) -#define LZMA_ID (('A'<<24)|('M'<<16)|('Z'<<8)|('L')) -#else -#define LZMA_ID (('L'<<24)|('Z'<<16)|('M'<<8)|('A')) -#endif - -// bind the buffer for correct identification -#pragma pack(1) -struct lzma_header_t -{ - unsigned int id; - unsigned int actualSize; // always little endian - unsigned int lzmaSize; // always little endian - unsigned char properties[5]; -}; -#pragma pack() - -class CLZMA -{ -public: - unsigned int Uncompress( unsigned char *pInput, unsigned char *pOutput ); - bool IsCompressed( unsigned char *pInput ); - unsigned int GetActualSize( unsigned char *pInput ); - -private: -}; - -#endif - diff --git a/Resources/NetHook/tier1/lzss.h b/Resources/NetHook/tier1/lzss.h deleted file mode 100644 index 5c923176..00000000 --- a/Resources/NetHook/tier1/lzss.h +++ /dev/null @@ -1,71 +0,0 @@ -//========= Copyright © 1996-2007, Valve Corporation, All rights reserved. ============// -// -// LZSS Codec. Designed for fast cheap gametime encoding/decoding. Compression results -// are not aggresive as other alogrithms, but gets 2:1 on most arbitrary uncompressed data. -// -//=====================================================================================// - -#ifndef _LZSS_H -#define _LZSS_H -#pragma once - -#if !defined( _X360 ) -#define LZSS_ID (('S'<<24)|('S'<<16)|('Z'<<8)|('L')) -#else -#define LZSS_ID (('L'<<24)|('Z'<<16)|('S'<<8)|('S')) -#endif - -// bind the buffer for correct identification -struct lzss_header_t -{ - unsigned int id; - unsigned int actualSize; // always little endian -}; - -class CUtlBuffer; - -#define DEFAULT_LZSS_WINDOW_SIZE 4096 - -class CLZSS -{ -public: - unsigned char* Compress( unsigned char *pInput, int inputlen, unsigned int *pOutputSize ); - unsigned char* CompressNoAlloc( unsigned char *pInput, int inputlen, unsigned char *pOutput, unsigned int *pOutputSize ); - unsigned int Uncompress( unsigned char *pInput, unsigned char *pOutput ); - //unsigned int Uncompress( unsigned char *pInput, CUtlBuffer &buf ); - unsigned int SafeUncompress( unsigned char *pInput, unsigned char *pOutput, unsigned int unBufSize ); - bool IsCompressed( unsigned char *pInput ); - unsigned int GetActualSize( unsigned char *pInput ); - - // windowsize must be a power of two. - FORCEINLINE CLZSS( int nWindowSize = DEFAULT_LZSS_WINDOW_SIZE ); - -private: - // expected to be sixteen bytes - struct lzss_node_t - { - unsigned char *pData; - lzss_node_t *pPrev; - lzss_node_t *pNext; - char empty[4]; - }; - - struct lzss_list_t - { - lzss_node_t *pStart; - lzss_node_t *pEnd; - }; - - void BuildHash( unsigned char *pData ); - lzss_list_t *m_pHashTable; - lzss_node_t *m_pHashTarget; - int m_nWindowSize; - -}; - -FORCEINLINE CLZSS::CLZSS( int nWindowSize ) -{ - m_nWindowSize = nWindowSize; -} -#endif - diff --git a/Resources/NetHook/tier1/mempool.cpp b/Resources/NetHook/tier1/mempool.cpp deleted file mode 100644 index 5c770036..00000000 --- a/Resources/NetHook/tier1/mempool.cpp +++ /dev/null @@ -1,312 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -//===========================================================================// - -#include "mempool.h" -#include -#include -#include -#include "tier0/dbg.h" -#include -#include "tier1/strtools.h" - -// Should be last include -#include "tier0/memdbgon.h" - -MemoryPoolReportFunc_t CMemoryPool::g_ReportFunc = 0; - -//----------------------------------------------------------------------------- -// Error reporting... (debug only) -//----------------------------------------------------------------------------- - -void CMemoryPool::SetErrorReportFunc( MemoryPoolReportFunc_t func ) -{ - g_ReportFunc = func; -} - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -CMemoryPool::CMemoryPool( int blockSize, int numElements, int growMode, const char *pszAllocOwner, int nAlignment ) -{ -#ifdef _X360 - if( numElements > 0 && growMode != GROW_NONE ) - { - numElements = 1; - } -#endif - - m_nAlignment = ( nAlignment != 0 ) ? nAlignment : 1; - Assert( IsPowerOfTwo( m_nAlignment ) ); - m_BlockSize = blockSize < sizeof(void*) ? sizeof(void*) : blockSize; - m_BlockSize = AlignValue( m_BlockSize, m_nAlignment ); - m_BlocksPerBlob = numElements; - m_PeakAlloc = 0; - m_GrowMode = growMode; - if ( !pszAllocOwner ) - { - pszAllocOwner = __FILE__; - } - m_pszAllocOwner = pszAllocOwner; - Init(); - AddNewBlob(); -} - -//----------------------------------------------------------------------------- -// Purpose: Frees the memory contained in the mempool, and invalidates it for -// any further use. -// Input : *memPool - the mempool to shutdown -//----------------------------------------------------------------------------- -CMemoryPool::~CMemoryPool() -{ - if (m_BlocksAllocated > 0) - { - ReportLeaks(); - } - Clear(); -} - - -//----------------------------------------------------------------------------- -// Resets the pool -//----------------------------------------------------------------------------- -void CMemoryPool::Init() -{ - m_NumBlobs = 0; - m_BlocksAllocated = 0; - m_pHeadOfFreeList = 0; - m_BlobHead.m_pNext = m_BlobHead.m_pPrev = &m_BlobHead; -} - - -//----------------------------------------------------------------------------- -// Frees everything -//----------------------------------------------------------------------------- -void CMemoryPool::Clear() -{ - // Free everything.. - CBlob *pNext; - for( CBlob *pCur = m_BlobHead.m_pNext; pCur != &m_BlobHead; pCur = pNext ) - { - pNext = pCur->m_pNext; - free( pCur ); - } - Init(); -} - -//----------------------------------------------------------------------------- -// Purpose: Reports memory leaks -//----------------------------------------------------------------------------- - -void CMemoryPool::ReportLeaks() -{ - if (!g_ReportFunc) - return; - - g_ReportFunc("Memory leak: mempool blocks left in memory: %d\n", m_BlocksAllocated); - -#ifdef _DEBUG - // walk and destroy the free list so it doesn't intefere in the scan - while (m_pHeadOfFreeList != NULL) - { - void *next = *((void**)m_pHeadOfFreeList); - memset(m_pHeadOfFreeList, 0, m_BlockSize); - m_pHeadOfFreeList = next; - } - - g_ReportFunc("Dumping memory: \'"); - - for( CBlob *pCur=m_BlobHead.m_pNext; pCur != &m_BlobHead; pCur=pCur->m_pNext ) - { - // scan the memory block and dump the leaks - char *scanPoint = (char *)pCur->m_Data; - char *scanEnd = pCur->m_Data + pCur->m_NumBytes; - bool needSpace = false; - - while (scanPoint < scanEnd) - { - // search for and dump any strings - if ((unsigned)(*scanPoint + 1) <= 256 && isprint(*scanPoint)) - { - g_ReportFunc("%c", *scanPoint); - needSpace = true; - } - else if (needSpace) - { - needSpace = false; - g_ReportFunc(" "); - } - - scanPoint++; - } - } - - g_ReportFunc("\'\n"); -#endif // _DEBUG -} - - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -void CMemoryPool::AddNewBlob() -{ - MEM_ALLOC_CREDIT_(m_pszAllocOwner); - - int sizeMultiplier; - - if( m_GrowMode == GROW_SLOW ) - { - sizeMultiplier = 1; - } - else - { - if ( m_GrowMode == GROW_NONE ) - { - // Can only have one allocation when we're in this mode - if( m_NumBlobs != 0 ) - { - Assert( !"CMemoryPool::AddNewBlob: mode == GROW_NONE" ); - return; - } - } - - // GROW_FAST and GROW_NONE use this. - sizeMultiplier = m_NumBlobs + 1; - } - - // maybe use something other than malloc? - int nElements = m_BlocksPerBlob * sizeMultiplier; - int blobSize = m_BlockSize * nElements; - CBlob *pBlob = (CBlob*)malloc( sizeof(CBlob) - 1 + blobSize + ( m_nAlignment - 1 ) ); - Assert( pBlob ); - - // Link it in at the end of the blob list. - pBlob->m_NumBytes = blobSize; - pBlob->m_pNext = &m_BlobHead; - pBlob->m_pPrev = pBlob->m_pNext->m_pPrev; - pBlob->m_pNext->m_pPrev = pBlob->m_pPrev->m_pNext = pBlob; - - // setup the free list - m_pHeadOfFreeList = AlignValue( pBlob->m_Data, m_nAlignment ); - Assert (m_pHeadOfFreeList); - - void **newBlob = (void**)m_pHeadOfFreeList; - for (int j = 0; j < nElements-1; j++) - { - newBlob[0] = (char*)newBlob + m_BlockSize; - newBlob = (void**)newBlob[0]; - } - - // null terminate list - newBlob[0] = NULL; - m_NumBlobs++; -} - - -void* CMemoryPool::Alloc() -{ - return Alloc( m_BlockSize ); -} - - -void* CMemoryPool::AllocZero() -{ - return AllocZero( m_BlockSize ); -} - - -//----------------------------------------------------------------------------- -// Purpose: Allocs a single block of memory from the pool. -// Input : amount - -//----------------------------------------------------------------------------- -void *CMemoryPool::Alloc( unsigned int amount ) -{ - void *returnBlock; - - if ( amount > (unsigned int)m_BlockSize ) - return NULL; - - if( !m_pHeadOfFreeList ) - { - // returning NULL is fine in GROW_NONE - if( m_GrowMode == GROW_NONE ) - { - //Assert( !"CMemoryPool::Alloc: tried to make new blob with GROW_NONE" ); - return NULL; - } - - // overflow - AddNewBlob(); - - // still failure, error out - if( !m_pHeadOfFreeList ) - { - Assert( !"CMemoryPool::Alloc: ran out of memory" ); - return NULL; - } - } - m_BlocksAllocated++; - m_PeakAlloc = max(m_PeakAlloc, m_BlocksAllocated); - - returnBlock = m_pHeadOfFreeList; - - // move the pointer the next block - m_pHeadOfFreeList = *((void**)m_pHeadOfFreeList); - - return returnBlock; -} - -//----------------------------------------------------------------------------- -// Purpose: Allocs a single block of memory from the pool, zeroes the memory before returning -// Input : amount - -//----------------------------------------------------------------------------- -void *CMemoryPool::AllocZero( unsigned int amount ) -{ - void *mem = Alloc( amount ); - if ( mem ) - { - V_memset( mem, 0x00, amount ); - } - return mem; -} - -//----------------------------------------------------------------------------- -// Purpose: Frees a block of memory -// Input : *memBlock - the memory to free -//----------------------------------------------------------------------------- -void CMemoryPool::Free( void *memBlock ) -{ - if ( !memBlock ) - return; // trying to delete NULL pointer, ignore - -#ifdef _DEBUG - // check to see if the memory is from the allocated range - bool bOK = false; - for( CBlob *pCur=m_BlobHead.m_pNext; pCur != &m_BlobHead; pCur=pCur->m_pNext ) - { - if (memBlock >= pCur->m_Data && (char*)memBlock < (pCur->m_Data + pCur->m_NumBytes)) - { - bOK = true; - } - } - Assert (bOK); -#endif // _DEBUG - -#ifdef _DEBUG - // invalidate the memory - memset( memBlock, 0xDD, m_BlockSize ); -#endif - - m_BlocksAllocated--; - - // make the block point to the first item in the list - *((void**)memBlock) = m_pHeadOfFreeList; - - // the list head is now the new block - m_pHeadOfFreeList = memBlock; -} - - diff --git a/Resources/NetHook/tier1/mempool.h b/Resources/NetHook/tier1/mempool.h deleted file mode 100644 index 3f334596..00000000 --- a/Resources/NetHook/tier1/mempool.h +++ /dev/null @@ -1,541 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $Workfile: $ -// $Date: $ -// -//----------------------------------------------------------------------------- -// $Log: $ -// -// $NoKeywords: $ -//===========================================================================// - -#ifndef MEMPOOL_H -#define MEMPOOL_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/memalloc.h" -#include "tier0/tslist.h" -#include "tier0/platform.h" -#include "tier1/utlvector.h" -#include "tier1/utlrbtree.h" - -//----------------------------------------------------------------------------- -// Purpose: Optimized pool memory allocator -//----------------------------------------------------------------------------- - -typedef void (*MemoryPoolReportFunc_t)( char const* pMsg, ... ); - -class CMemoryPool -{ -public: - // Ways the memory pool can grow when it needs to make a new blob. - enum MemoryPoolGrowType_t - { - GROW_NONE=0, // Don't allow new blobs. - GROW_FAST=1, // New blob size is numElements * (i+1) (ie: the blocks it allocates - // get larger and larger each time it allocates one). - GROW_SLOW=2 // New blob size is numElements. - }; - - CMemoryPool( int blockSize, int numElements, int growMode = GROW_FAST, const char *pszAllocOwner = NULL, int nAlignment = 0 ); - ~CMemoryPool(); - - void* Alloc(); // Allocate the element size you specified in the constructor. - void* Alloc( size_t amount ); - void* AllocZero(); // Allocate the element size you specified in the constructor, zero the memory before construction - void* AllocZero( size_t amount ); - void Free(void *pMem); - - // Frees everything - void Clear(); - - // Error reporting... - static void SetErrorReportFunc( MemoryPoolReportFunc_t func ); - - // returns number of allocated blocks - int Count() { return m_BlocksAllocated; } - int PeakCount() { return m_PeakAlloc; } - -protected: - class CBlob - { - public: - CBlob *m_pPrev, *m_pNext; - int m_NumBytes; // Number of bytes in this blob. - char m_Data[1]; - }; - - // Resets the pool - void Init(); - void AddNewBlob(); - void ReportLeaks(); - - int m_BlockSize; - int m_BlocksPerBlob; - - int m_GrowMode; // GROW_ enum. - - // FIXME: Change m_ppMemBlob into a growable array? - CBlob m_BlobHead; - void *m_pHeadOfFreeList; - int m_BlocksAllocated; - int m_PeakAlloc; - unsigned short m_nAlignment; - unsigned short m_NumBlobs; - const char * m_pszAllocOwner; - - static MemoryPoolReportFunc_t g_ReportFunc; -}; - - -//----------------------------------------------------------------------------- -// -//----------------------------------------------------------------------------- -class CMemoryPoolMT : public CMemoryPool -{ -public: - CMemoryPoolMT(int blockSize, int numElements, int growMode = GROW_FAST, const char *pszAllocOwner = NULL) : CMemoryPool( blockSize, numElements, growMode, pszAllocOwner) {} - - - void* Alloc() { AUTO_LOCK( m_mutex ); return CMemoryPool::Alloc(); } - void* Alloc( size_t amount ) { AUTO_LOCK( m_mutex ); return CMemoryPool::Alloc( amount ); } - void* AllocZero() { AUTO_LOCK( m_mutex ); return CMemoryPool::AllocZero(); } - void* AllocZero( size_t amount ) { AUTO_LOCK( m_mutex ); return CMemoryPool::AllocZero( amount ); } - void Free(void *pMem) { AUTO_LOCK( m_mutex ); CMemoryPool::Free( pMem ); } - - // Frees everything - void Clear() { AUTO_LOCK( m_mutex ); return CMemoryPool::Clear(); } -private: - CThreadFastMutex m_mutex; // @TODO: Rework to use tslist (toml 7/6/2007) -}; - - -//----------------------------------------------------------------------------- -// Wrapper macro to make an allocator that returns particular typed allocations -// and construction and destruction of objects. -//----------------------------------------------------------------------------- -template< class T > -class CClassMemoryPool : public CMemoryPool -{ -public: - CClassMemoryPool(int numElements, int growMode = GROW_FAST, int nAlignment = 0 ) : - CMemoryPool( sizeof(T), numElements, growMode, MEM_ALLOC_CLASSNAME(T), nAlignment ) {} - - T* Alloc(); - T* AllocZero(); - void Free( T *pMem ); - - void Clear(); -}; - - -//----------------------------------------------------------------------------- -// Specialized pool for aligned data management (e.g., Xbox cubemaps) -//----------------------------------------------------------------------------- -template -class CAlignedMemPool -{ - enum - { - BLOCK_SIZE = max( ALIGN_VALUE( ITEM_SIZE, ALIGNMENT ), 8 ), - }; - -public: - CAlignedMemPool(); - - void *Alloc(); - void Free( void *p ); - - static int __cdecl CompareChunk( void * const *ppLeft, void * const *ppRight ); - void Compact(); - - int NumTotal() { return m_Chunks.Count() * ( CHUNK_SIZE / BLOCK_SIZE ); } - int NumAllocated() { return NumTotal() - m_nFree; } - int NumFree() { return m_nFree; } - - int BytesTotal() { return NumTotal() * BLOCK_SIZE; } - int BytesAllocated() { return NumAllocated() * BLOCK_SIZE; } - int BytesFree() { return NumFree() * BLOCK_SIZE; } - - int ItemSize() { return ITEM_SIZE; } - int BlockSize() { return BLOCK_SIZE; } - int ChunkSize() { return CHUNK_SIZE; } - -private: - struct FreeBlock_t - { - FreeBlock_t *pNext; - byte reserved[ BLOCK_SIZE - sizeof( FreeBlock_t *) ]; - }; - - CUtlVector m_Chunks; // Chunks are tracked outside blocks (unlike CMemoryPool) to simplify alignment issues - FreeBlock_t * m_pFirstFree; - int m_nFree; - CAllocator m_Allocator; - float m_TimeLastCompact; -}; - -//----------------------------------------------------------------------------- -// Pool variant using standard allocation -//----------------------------------------------------------------------------- -template -class CObjectPool -{ -public: - CObjectPool() - { - int i = nInitialCount; - while ( i-- > 0 ) - { - m_AvailableObjects.PushItem( new T ); - } - } - - ~CObjectPool() - { - Purge(); - } - - int NumAvailable() - { - return m_AvailableObjects.Count(); - } - - void Purge() - { - T *p; - while ( m_AvailableObjects.PopItem( &p ) ) - { - delete p; - } - } - - T *GetObject( bool bCreateNewIfEmpty = bDefCreateNewIfEmpty ) - { - T *p; - if ( !m_AvailableObjects.PopItem( &p ) ) - { - p = ( bCreateNewIfEmpty ) ? new T : NULL; - } - return p; - } - - void PutObject( T *p ) - { - m_AvailableObjects.PushItem( p ); - } - -private: - CTSList m_AvailableObjects; -}; - -//----------------------------------------------------------------------------- - - -template< class T > -inline T* CClassMemoryPool::Alloc() -{ - T *pRet; - - { - MEM_ALLOC_CREDIT_(MEM_ALLOC_CLASSNAME(T)); - pRet = (T*)CMemoryPool::Alloc(); - } - - if ( pRet ) - { - Construct( pRet ); - } - return pRet; -} - -template< class T > -inline T* CClassMemoryPool::AllocZero() -{ - T *pRet; - - { - MEM_ALLOC_CREDIT_(MEM_ALLOC_CLASSNAME(T)); - pRet = (T*)CMemoryPool::AllocZero(); - } - - if ( pRet ) - { - Construct( pRet ); - } - return pRet; -} - -template< class T > -inline void CClassMemoryPool::Free(T *pMem) -{ - if ( pMem ) - { - Destruct( pMem ); - } - - CMemoryPool::Free( pMem ); -} - -template< class T > -inline void CClassMemoryPool::Clear() -{ - CUtlRBTree freeBlocks; - SetDefLessFunc( freeBlocks ); - - void *pCurFree = m_pHeadOfFreeList; - while ( pCurFree != NULL ) - { - freeBlocks.Insert( pCurFree ); - pCurFree = *((void**)pCurFree); - } - - for( CBlob *pCur=m_BlobHead.m_pNext; pCur != &m_BlobHead; pCur=pCur->m_pNext ) - { - T *p = (T *)pCur->m_Data; - T *pLimit = (T *)(pCur->m_Data + pCur->m_NumBytes); - while ( p < pLimit ) - { - if ( freeBlocks.Find( p ) == freeBlocks.InvalidIndex() ) - { - Destruct( p ); - } - p++; - } - } - - CMemoryPool::Clear(); -} - - -//----------------------------------------------------------------------------- -// Macros that make it simple to make a class use a fixed-size allocator -// Put DECLARE_FIXEDSIZE_ALLOCATOR in the private section of a class, -// Put DEFINE_FIXEDSIZE_ALLOCATOR in the CPP file -//----------------------------------------------------------------------------- -#define DECLARE_FIXEDSIZE_ALLOCATOR( _class ) \ - public: \ - inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \ - inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \ - inline void operator delete( void* p ) { s_Allocator.Free(p); } \ - inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { s_Allocator.Free(p); } \ - private: \ - static CMemoryPool s_Allocator - -#define DEFINE_FIXEDSIZE_ALLOCATOR( _class, _initsize, _grow ) \ - CMemoryPool _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool") - -#define DEFINE_FIXEDSIZE_ALLOCATOR_ALIGNED( _class, _initsize, _grow, _alignment ) \ - CMemoryPool _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool", _alignment ) - -#define DECLARE_FIXEDSIZE_ALLOCATOR_MT( _class ) \ - public: \ - inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \ - inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_Allocator.Alloc(size); } \ - inline void operator delete( void* p ) { s_Allocator.Free(p); } \ - inline void operator delete( void* p, int nBlockUse, const char *pFileName, int nLine ) { s_Allocator.Free(p); } \ - private: \ - static CMemoryPoolMT s_Allocator - -#define DEFINE_FIXEDSIZE_ALLOCATOR_MT( _class, _initsize, _grow ) \ - CMemoryPoolMT _class::s_Allocator(sizeof(_class), _initsize, _grow, #_class " pool") - -//----------------------------------------------------------------------------- -// Macros that make it simple to make a class use a fixed-size allocator -// This version allows us to use a memory pool which is externally defined... -// Put DECLARE_FIXEDSIZE_ALLOCATOR_EXTERNAL in the private section of a class, -// Put DEFINE_FIXEDSIZE_ALLOCATOR_EXTERNAL in the CPP file -//----------------------------------------------------------------------------- - -#define DECLARE_FIXEDSIZE_ALLOCATOR_EXTERNAL( _class ) \ - public: \ - inline void* operator new( size_t size ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_pAllocator->Alloc(size); } \ - inline void* operator new( size_t size, int nBlockUse, const char *pFileName, int nLine ) { MEM_ALLOC_CREDIT_(#_class " pool"); return s_pAllocator->Alloc(size); } \ - inline void operator delete( void* p ) { s_pAllocator->Free(p); } \ - private: \ - static CMemoryPool* s_pAllocator - -#define DEFINE_FIXEDSIZE_ALLOCATOR_EXTERNAL( _class, _allocator ) \ - CMemoryPool* _class::s_pAllocator = _allocator - - -template -inline CAlignedMemPool::CAlignedMemPool() - : m_pFirstFree( 0 ), - m_nFree( 0 ), - m_TimeLastCompact( 0 ) -{ - COMPILE_TIME_ASSERT( sizeof( FreeBlock_t ) >= BLOCK_SIZE ); - COMPILE_TIME_ASSERT( ALIGN_VALUE( sizeof( FreeBlock_t ), ALIGNMENT ) == sizeof( FreeBlock_t ) ); -} - -template -inline void *CAlignedMemPool::Alloc() -{ - if ( !m_pFirstFree ) - { - FreeBlock_t *pNew = (FreeBlock_t *)m_Allocator.Alloc( CHUNK_SIZE ); - Assert( (unsigned)pNew % ALIGNMENT == 0 ); - m_Chunks.AddToTail( pNew ); - m_nFree = CHUNK_SIZE / BLOCK_SIZE; - m_pFirstFree = pNew; - for ( int i = 0; i < m_nFree - 1; i++ ) - { - pNew->pNext = pNew + 1; - pNew++; - } - pNew->pNext = NULL; - } - - void *p = m_pFirstFree; - m_pFirstFree = m_pFirstFree->pNext; - m_nFree--; - - return p; -} - -template -inline void CAlignedMemPool::Free( void *p ) -{ - // Insertion sort to encourage allocation clusters in chunks - FreeBlock_t *pFree = ((FreeBlock_t *)p); - FreeBlock_t *pCur = m_pFirstFree; - FreeBlock_t *pPrev = NULL; - - while ( pCur && pFree > pCur ) - { - pPrev = pCur; - pCur = pCur->pNext; - } - - pFree->pNext = pCur; - - if ( pPrev ) - { - pPrev->pNext = pFree; - } - else - { - m_pFirstFree = pFree; - } - m_nFree++; - - if ( m_nFree >= ( CHUNK_SIZE / BLOCK_SIZE ) * COMPACT_THRESHOLD ) - { - float time = Plat_FloatTime(); - float compactTime = ( m_nFree >= ( CHUNK_SIZE / BLOCK_SIZE ) * COMPACT_THRESHOLD * 4 ) ? 15.0 : 30.0; - if ( m_TimeLastCompact > time || m_TimeLastCompact + compactTime < Plat_FloatTime() ) - { - Compact(); - m_TimeLastCompact = time; - } - } -} - -template -inline int __cdecl CAlignedMemPool::CompareChunk( void * const *ppLeft, void * const *ppRight ) -{ - return ((unsigned)*ppLeft) - ((unsigned)*ppRight); -} - -template -inline void CAlignedMemPool::Compact() -{ - FreeBlock_t *pCur = m_pFirstFree; - FreeBlock_t *pPrev = NULL; - - m_Chunks.Sort( CompareChunk ); - -#ifdef VALIDATE_ALIGNED_MEM_POOL - { - FreeBlock_t *p = m_pFirstFree; - while ( p ) - { - if ( p->pNext && p > p->pNext ) - { - __asm { int 3 } - } - p = p->pNext; - } - - for ( int i = 0; i < m_Chunks.Count(); i++ ) - { - if ( i + 1 < m_Chunks.Count() ) - { - if ( m_Chunks[i] > m_Chunks[i + 1] ) - { - __asm { int 3 } - } - } - } - } -#endif - - int i; - - for ( i = 0; i < m_Chunks.Count(); i++ ) - { - int nBlocksPerChunk = CHUNK_SIZE / BLOCK_SIZE; - FreeBlock_t *pChunkLimit = ((FreeBlock_t *)m_Chunks[i]) + nBlocksPerChunk; - int nFromChunk = 0; - if ( pCur == m_Chunks[i] ) - { - FreeBlock_t *pFirst = pCur; - while ( pCur && pCur >= m_Chunks[i] && pCur < pChunkLimit ) - { - pCur = pCur->pNext; - nFromChunk++; - } - pCur = pFirst; - - } - - while ( pCur && pCur >= m_Chunks[i] && pCur < pChunkLimit ) - { - if ( nFromChunk != nBlocksPerChunk ) - { - if ( pPrev ) - { - pPrev->pNext = pCur; - } - else - { - m_pFirstFree = pCur; - } - pPrev = pCur; - } - else if ( pPrev ) - { - pPrev->pNext = NULL; - } - else - { - m_pFirstFree = NULL; - } - - pCur = pCur->pNext; - } - - if ( nFromChunk == nBlocksPerChunk ) - { - m_Allocator.Free( m_Chunks[i] ); - m_nFree -= nBlocksPerChunk; - m_Chunks[i] = 0; - } - } - - for ( i = m_Chunks.Count() - 1; i >= 0 ; i-- ) - { - if ( !m_Chunks[i] ) - { - m_Chunks.FastRemove( i ); - } - } -} - -#endif // MEMPOOL_H diff --git a/Resources/NetHook/tier1/memstack.cpp b/Resources/NetHook/tier1/memstack.cpp deleted file mode 100644 index 5efe33f8..00000000 --- a/Resources/NetHook/tier1/memstack.cpp +++ /dev/null @@ -1,297 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#if defined( _WIN32 ) && !defined( _X360 ) -#define WIN_32_LEAN_AND_MEAN -#include -#define VA_COMMIT_FLAGS MEM_COMMIT -#define VA_RESERVE_FLAGS MEM_RESERVE -#elif defined( _X360 ) -#define VA_COMMIT_FLAGS (MEM_COMMIT|MEM_NOZERO|MEM_LARGE_PAGES) -#define VA_RESERVE_FLAGS (MEM_RESERVE|MEM_LARGE_PAGES) -#endif - -#include "tier0/dbg.h" -#include "memstack.h" -#include "utlmap.h" -#include "tier0/memdbgon.h" - -#ifdef _WIN32 -#pragma warning(disable:4073) -#pragma init_seg(lib) -#endif - -//----------------------------------------------------------------------------- - -MEMALLOC_DEFINE_EXTERNAL_TRACKING(CMemoryStack); - -//----------------------------------------------------------------------------- - -CMemoryStack::CMemoryStack() - : m_pBase( NULL ), - m_pNextAlloc( NULL ), - m_pAllocLimit( NULL ), - m_pCommitLimit( NULL ), - m_alignment( 16 ), -#if defined(_WIN32) - m_commitSize( 0 ), - m_minCommit( 0 ), -#endif - m_maxSize( 0 ) -{ -} - -//------------------------------------- - -CMemoryStack::~CMemoryStack() -{ - if ( m_pBase ) - Term(); -} - -//------------------------------------- - -bool CMemoryStack::Init( unsigned maxSize, unsigned commitSize, unsigned initialCommit, unsigned alignment ) -{ - Assert( !m_pBase ); - -#ifdef _X360 - m_bPhysical = false; -#endif - - m_maxSize = maxSize; - m_alignment = AlignValue( alignment, 4 ); - - Assert( m_alignment == alignment ); - Assert( m_maxSize > 0 ); - -#if defined(_WIN32) - if ( commitSize != 0 ) - { - m_commitSize = commitSize; - } - - unsigned pageSize; - -#ifndef _X360 - SYSTEM_INFO sysInfo; - GetSystemInfo( &sysInfo ); - Assert( !( sysInfo.dwPageSize & (sysInfo.dwPageSize-1)) ); - pageSize = sysInfo.dwPageSize; -#else - pageSize = 64*1024; -#endif - - if ( m_commitSize == 0 ) - { - m_commitSize = pageSize; - } - else - { - m_commitSize = AlignValue( m_commitSize, pageSize ); - } - - m_maxSize = AlignValue( m_maxSize, m_commitSize ); - - Assert( m_maxSize % pageSize == 0 && m_commitSize % pageSize == 0 && m_commitSize <= m_maxSize ); - - m_pBase = (unsigned char *)VirtualAlloc( NULL, m_maxSize, VA_RESERVE_FLAGS, PAGE_NOACCESS ); - Assert( m_pBase ); - m_pCommitLimit = m_pNextAlloc = m_pBase; - - if ( initialCommit ) - { - initialCommit = AlignValue( initialCommit, m_commitSize ); - Assert( initialCommit < m_maxSize ); - if ( !VirtualAlloc( m_pCommitLimit, initialCommit, VA_COMMIT_FLAGS, PAGE_READWRITE ) ) - return false; - m_minCommit = initialCommit; - m_pCommitLimit += initialCommit; - MemAlloc_RegisterExternalAllocation( CMemoryStack, GetBase(), GetSize() ); - } - -#else - m_pBase = MemAlloc_AllocAligned( m_maxSize, alignment ? alignment : 1 ); - m_pNextAlloc = m_pBase; - m_pCommitLimit = m_pBase + m_maxSize; -#endif - - m_pAllocLimit = m_pBase + m_maxSize; - - return ( m_pBase != NULL ); -} - -//------------------------------------- - -#ifdef _X360 -bool CMemoryStack::InitPhysical( unsigned size, unsigned alignment ) -{ - m_bPhysical = true; - - m_maxSize = m_commitSize = size; - m_alignment = AlignValue( alignment, 4 ); - - int flags = PAGE_READWRITE; - if ( size >= 16*1024*1024 ) - { - flags |= MEM_16MB_PAGES; - } - else - { - flags |= MEM_LARGE_PAGES; - } - m_pBase = (unsigned char *)XPhysicalAlloc( m_maxSize, MAXULONG_PTR, 4096, flags ); - Assert( m_pBase ); - m_pNextAlloc = m_pBase; - m_pCommitLimit = m_pBase + m_maxSize; - m_pAllocLimit = m_pBase + m_maxSize; - - MemAlloc_RegisterExternalAllocation( CMemoryStack, GetBase(), GetSize() ); - return ( m_pBase != NULL ); -} -#endif - -//------------------------------------- - -void CMemoryStack::Term() -{ - FreeAll(); - if ( m_pBase ) - { -#if defined(_WIN32) - VirtualFree( m_pBase, 0, MEM_RELEASE ); -#else - MemAlloc_FreeAligned( m_pBase ); -#endif - m_pBase = NULL; - } -} - -//------------------------------------- - -int CMemoryStack::GetSize() -{ -#ifdef _WIN32 - return m_pCommitLimit - m_pBase; -#else - return m_maxSize; -#endif -} - - -//------------------------------------- - -bool CMemoryStack::CommitTo( byte *pNextAlloc ) RESTRICT -{ -#ifdef _X360 - if ( m_bPhysical ) - { - return NULL; - } -#endif -#if defined(_WIN32) - unsigned char * pNewCommitLimit = AlignValue( pNextAlloc, m_commitSize ); - unsigned commitSize = pNewCommitLimit - m_pCommitLimit; - - if ( GetSize() ) - MemAlloc_RegisterExternalDeallocation( CMemoryStack, GetBase(), GetSize() ); - - if( m_pCommitLimit + commitSize > m_pAllocLimit ) - { - return false; - } - - if ( !VirtualAlloc( m_pCommitLimit, commitSize, VA_COMMIT_FLAGS, PAGE_READWRITE ) ) - { - Assert( 0 ); - return false; - } - m_pCommitLimit = pNewCommitLimit; - - if ( GetSize() ) - MemAlloc_RegisterExternalAllocation( CMemoryStack, GetBase(), GetSize() ); - return true; -#else - Assert( 0 ); - return false; -#endif -} - -//------------------------------------- - -void CMemoryStack::FreeToAllocPoint( MemoryStackMark_t mark, bool bDecommit ) -{ - void *pAllocPoint = m_pBase + mark; - Assert( pAllocPoint >= m_pBase && pAllocPoint <= m_pNextAlloc ); - - if ( pAllocPoint >= m_pBase && pAllocPoint < m_pNextAlloc ) - { - if ( bDecommit ) - { -#if defined(_WIN32) - unsigned char *pDecommitPoint = AlignValue( (unsigned char *)pAllocPoint, m_commitSize ); - - if ( pDecommitPoint < m_pBase + m_minCommit ) - { - pDecommitPoint = m_pBase + m_minCommit; - } - - unsigned decommitSize = m_pCommitLimit - pDecommitPoint; - - if ( decommitSize > 0 ) - { - MemAlloc_RegisterExternalDeallocation( CMemoryStack, GetBase(), GetSize() ); - - VirtualFree( pDecommitPoint, decommitSize, MEM_DECOMMIT ); - m_pCommitLimit = pDecommitPoint; - - if ( mark > 0 ) - { - MemAlloc_RegisterExternalAllocation( CMemoryStack, GetBase(), GetSize() ); - } - } -#endif - } - m_pNextAlloc = (unsigned char *)pAllocPoint; - } -} - -//------------------------------------- - -void CMemoryStack::FreeAll( bool bDecommit ) -{ - if ( m_pBase && m_pCommitLimit - m_pBase > 0 ) - { - if ( bDecommit ) - { -#if defined(_WIN32) - MemAlloc_RegisterExternalDeallocation( CMemoryStack, GetBase(), GetSize() ); - - VirtualFree( m_pBase, m_pCommitLimit - m_pBase, MEM_DECOMMIT ); - m_pCommitLimit = m_pBase; -#endif - } - m_pNextAlloc = m_pBase; - } -} - -//------------------------------------- - -void CMemoryStack::Access( void **ppRegion, unsigned *pBytes ) -{ - *ppRegion = m_pBase; - *pBytes = ( m_pNextAlloc - m_pBase); -} - -//------------------------------------- - -void CMemoryStack::PrintContents() -{ - Msg( "Total used memory: %d\n", GetUsed() ); - Msg( "Total committed memory: %d\n", GetSize() ); -} - -//----------------------------------------------------------------------------- diff --git a/Resources/NetHook/tier1/memstack.h b/Resources/NetHook/tier1/memstack.h deleted file mode 100644 index 8ebebb01..00000000 --- a/Resources/NetHook/tier1/memstack.h +++ /dev/null @@ -1,204 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: A fast stack memory allocator that uses virtual memory if available -// -//=============================================================================// - -#ifndef MEMSTACK_H -#define MEMSTACK_H - -#if defined( _WIN32 ) -#pragma once -#endif - -//----------------------------------------------------------------------------- - -typedef unsigned MemoryStackMark_t; - -class CMemoryStack -{ -public: - CMemoryStack(); - ~CMemoryStack(); - - bool Init( unsigned maxSize = 0, unsigned commitSize = 0, unsigned initialCommit = 0, unsigned alignment = 16 ); -#ifdef _X360 - bool InitPhysical( unsigned size = 0, unsigned alignment = 16 ); -#endif - void Term(); - - int GetSize(); - int GetMaxSize(); - int GetUsed(); - - void *Alloc( unsigned bytes, bool bClear = false ) RESTRICT; - - MemoryStackMark_t GetCurrentAllocPoint(); - void FreeToAllocPoint( MemoryStackMark_t mark, bool bDecommit = true ); - void FreeAll( bool bDecommit = true ); - - void Access( void **ppRegion, unsigned *pBytes ); - - void PrintContents(); - - void *GetBase(); - const void *GetBase() const { return const_cast(this)->GetBase(); } - -private: - bool CommitTo( byte * ) RESTRICT; - - byte *m_pNextAlloc; - byte *m_pCommitLimit; - byte *m_pAllocLimit; - - byte *m_pBase; - - unsigned m_maxSize; - unsigned m_alignment; -#ifdef _WIN32 - unsigned m_commitSize; - unsigned m_minCommit; -#endif -#ifdef _X360 - bool m_bPhysical; -#endif -}; - -//------------------------------------- - -FORCEINLINE void *CMemoryStack::Alloc( unsigned bytes, bool bClear ) RESTRICT -{ - Assert( m_pBase ); - - int alignment = m_alignment; - if ( bytes ) - { - bytes = AlignValue( bytes, alignment ); - } - else - { - bytes = alignment; - } - - - void *pResult = m_pNextAlloc; - byte *pNextAlloc = m_pNextAlloc + bytes; - - if ( pNextAlloc > m_pCommitLimit ) - { - if ( !CommitTo( pNextAlloc ) ) - { - return NULL; - } - } - - if ( bClear ) - { - memset( pResult, 0, bytes ); - } - - m_pNextAlloc = pNextAlloc; - - return pResult; -} - -//------------------------------------- - -inline int CMemoryStack::GetMaxSize() -{ - return m_maxSize; -} - -//------------------------------------- - -inline int CMemoryStack::GetUsed() -{ - return ( m_pNextAlloc - m_pBase ); -} - -//------------------------------------- - -inline void *CMemoryStack::GetBase() -{ - return m_pBase; -} - -//------------------------------------- - -inline MemoryStackMark_t CMemoryStack::GetCurrentAllocPoint() -{ - return ( m_pNextAlloc - m_pBase ); -} - -//----------------------------------------------------------------------------- -// The CUtlMemoryStack class: -// A fixed memory class -//----------------------------------------------------------------------------- -template< typename T, typename I, size_t MAX_SIZE, size_t COMMIT_SIZE = 0, size_t INITIAL_COMMIT = 0 > -class CUtlMemoryStack -{ -public: - // constructor, destructor - CUtlMemoryStack( int nGrowSize = 0, int nInitSize = 0 ) { m_MemoryStack.Init( MAX_SIZE * sizeof(T), COMMIT_SIZE * sizeof(T), INITIAL_COMMIT * sizeof(T), 4 ); COMPILE_TIME_ASSERT( sizeof(T) % 4 == 0 ); } - CUtlMemoryStack( T* pMemory, int numElements ) { Assert( 0 ); } - - // Can we use this index? - bool IsIdxValid( I i ) const { return (i >= 0) && (i < m_nAllocated); } - static int InvalidIndex() { return -1; } - - class Iterator_t - { - Iterator_t( I i ) : index( i ) {} - I index; - friend class CUtlMemoryStack; - public: - bool operator==( const Iterator_t it ) const { return index == it.index; } - bool operator!=( const Iterator_t it ) const { return index != it.index; } - }; - Iterator_t First() const { return Iterator_t( m_nAllocated ? 0 : InvalidIndex() ); } - Iterator_t Next( const Iterator_t &it ) const { return Iterator_t( it.index < m_nAllocated ? it.index + 1 : InvalidIndex() ); } - I GetIndex( const Iterator_t &it ) const { return it.index; } - bool IsIdxAfter( I i, const Iterator_t &it ) const { return i > it.index; } - bool IsValidIterator( const Iterator_t &it ) const { return it.index >= 0 && it.index < m_nAllocated; } - Iterator_t InvalidIterator() const { return Iterator_t( InvalidIndex() ); } - - // Gets the base address - T* Base() { return (T*)m_MemoryStack.GetBase(); } - const T* Base() const { return (const T*)m_MemoryStack.GetBase(); } - - // element access - T& operator[]( I i ) { Assert( IsIdxValid(i) ); return Base()[i]; } - const T& operator[]( I i ) const { Assert( IsIdxValid(i) ); return Base()[i]; } - T& Element( I i ) { Assert( IsIdxValid(i) ); return Base()[i]; } - const T& Element( I i ) const { Assert( IsIdxValid(i) ); return Base()[i]; } - - // Attaches the buffer to external memory.... - void SetExternalBuffer( T* pMemory, int numElements ) { Assert( 0 ); } - - // Size - int NumAllocated() const { return m_nAllocated; } - int Count() const { return m_nAllocated; } - - // Grows the memory, so that at least allocated + num elements are allocated - void Grow( int num = 1 ) { Assert( num > 0 ); m_nAllocated += num; m_MemoryStack.Alloc( num * sizeof(T) ); } - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ) { Assert( num <= MAX_SIZE ); if ( m_nAllocated < num ) Grow( num - m_nAllocated ); } - - // Memory deallocation - void Purge() { m_MemoryStack.FreeAll(); m_nAllocated = 0; } - - // is the memory externally allocated? - bool IsExternallyAllocated() const { return false; } - - // Set the size by which the memory grows - void SetGrowSize( int size ) {} - -private: - CMemoryStack m_MemoryStack; - int m_nAllocated; -}; - -//----------------------------------------------------------------------------- - -#endif // MEMSTACK_H diff --git a/Resources/NetHook/tier1/netadr.h b/Resources/NetHook/tier1/netadr.h deleted file mode 100644 index e03e7be9..00000000 --- a/Resources/NetHook/tier1/netadr.h +++ /dev/null @@ -1,70 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// -// netadr.h -#ifndef NETADR_H -#define NETADR_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/platform.h" -#undef SetPort - -typedef enum -{ - NA_NULL = 0, - NA_LOOPBACK, - NA_BROADCAST, - NA_IP, -} netadrtype_t; - -typedef struct netadr_s -{ -public: - netadr_s() { SetIP( 0 ); SetPort( 0 ); SetType( NA_IP ); } - netadr_s( uint unIP, uint16 usPort ) { SetIP( unIP ); SetPort( usPort ); SetType( NA_IP ); } - netadr_s( const char *pch ) { SetFromString( pch ); } - void Clear(); // invalids Address - - void SetType( netadrtype_t type ); - void SetPort( unsigned short port ); - bool SetFromSockadr(const struct sockaddr *s); - void SetIP(uint8 b1, uint8 b2, uint8 b3, uint8 b4); - void SetIP(uint unIP); // Sets IP. unIP is in host order (little-endian) - void SetIPAndPort( uint unIP, unsigned short usPort ) { SetIP( unIP ); SetPort( usPort ); } - void SetFromString(const char *pch, bool bUseDNS = false ); // if bUseDNS is true then do a DNS lookup if needed - - bool CompareAdr (const netadr_s &a, bool onlyBase = false) const; - bool CompareClassBAdr (const netadr_s &a) const; - bool CompareClassCAdr (const netadr_s &a) const; - - netadrtype_t GetType() const; - unsigned short GetPort() const; - const char* ToString( bool onlyBase = false ) const; // returns xxx.xxx.xxx.xxx:ppppp - void ToSockadr(struct sockaddr *s) const; - unsigned int GetIP() const; - - bool IsLocalhost() const; // true, if this is the localhost IP - bool IsLoopback() const; // true if engine loopback buffers are used - bool IsReservedAdr() const; // true, if this is a private LAN IP - bool IsValid() const; // ip & port != 0 - void SetFromSocket( int hSocket ); - // These function names are decorated because the Xbox360 defines macros for ntohl and htonl - unsigned long addr_ntohl() const; - unsigned long addr_htonl() const; - bool operator==(const netadr_s &netadr) const {return ( CompareAdr( netadr ) );} - bool operator<(const netadr_s &netadr) const; - -public: // members are public to avoid to much changes - - netadrtype_t type; - unsigned char ip[4]; - unsigned short port; -} netadr_t; - -#endif // NETADR_H diff --git a/Resources/NetHook/tier1/newbitbuf.cpp b/Resources/NetHook/tier1/newbitbuf.cpp deleted file mode 100644 index 5fdfa986..00000000 --- a/Resources/NetHook/tier1/newbitbuf.cpp +++ /dev/null @@ -1,713 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -//=============================================================================// - -#include "bitbuf.h" -#include "coordsize.h" -#include "mathlib/vector.h" -#include "mathlib/mathlib.h" -#include "tier1/strtools.h" -#include "bitvec.h" - -// FIXME: Can't use this until we get multithreaded allocations in tier0 working for tools -// This is used by VVIS and fails to link -// NOTE: This must be the last file included!!! -//#include "tier0/memdbgon.h" - -#ifdef _X360 -// mandatory ... wary of above comment and isolating, tier0 is built as MT though -#include "tier0/memdbgon.h" -#endif - -#include "stdio.h" - -void CBitWrite::StartWriting( void *pData, int nBytes, int iStartBit, int nBits ) -{ - // Make sure it's dword aligned and padded. - Assert( (nBytes % 4) == 0 ); - Assert(((unsigned long)pData & 3) == 0); - Assert( iStartBit == 0 ); - m_pData = (uint32 *) pData; - m_pDataOut = m_pData; - m_nDataBytes = nBytes; - - if ( nBits == -1 ) - { - m_nDataBits = nBytes << 3; - } - else - { - Assert( nBits <= nBytes*8 ); - m_nDataBits = nBits; - } - m_bOverflow = false; - m_nOutBufWord = 0; - m_nOutBitsAvail = 32; - m_pBufferEnd = m_pDataOut + ( nBytes >> 2 ); -} - -const uint32 CBitBuffer::s_nMaskTable[33] = { - 0, - ( 1 << 1 ) - 1, - ( 1 << 2 ) - 1, - ( 1 << 3 ) - 1, - ( 1 << 4 ) - 1, - ( 1 << 5 ) - 1, - ( 1 << 6 ) - 1, - ( 1 << 7 ) - 1, - ( 1 << 8 ) - 1, - ( 1 << 9 ) - 1, - ( 1 << 10 ) - 1, - ( 1 << 11 ) - 1, - ( 1 << 12 ) - 1, - ( 1 << 13 ) - 1, - ( 1 << 14 ) - 1, - ( 1 << 15 ) - 1, - ( 1 << 16 ) - 1, - ( 1 << 17 ) - 1, - ( 1 << 18 ) - 1, - ( 1 << 19 ) - 1, - ( 1 << 20 ) - 1, - ( 1 << 21 ) - 1, - ( 1 << 22 ) - 1, - ( 1 << 23 ) - 1, - ( 1 << 24 ) - 1, - ( 1 << 25 ) - 1, - ( 1 << 26 ) - 1, - ( 1 << 27 ) - 1, - ( 1 << 28 ) - 1, - ( 1 << 29 ) - 1, - ( 1 << 30 ) - 1, - 0x7fffffff, - 0xffffffff, -}; - -bool CBitWrite::WriteString( const char *pStr ) -{ - if(pStr) - { - while( *pStr ) - { - WriteChar( * ( pStr++ ) ); - } - } - WriteChar( 0 ); - return !IsOverflowed(); -} - - -void CBitWrite::WriteLongLong(int64 val) -{ - uint *pLongs = (uint*)&val; - - // Insert the two DWORDS according to network endian - const short endianIndex = 0x0100; - byte *idx = (byte*)&endianIndex; - WriteUBitLong(pLongs[*idx++], sizeof(long) << 3); - WriteUBitLong(pLongs[*idx], sizeof(long) << 3); -} - -bool CBitWrite::WriteBits(const void *pInData, int nBits) -{ - unsigned char *pOut = (unsigned char*)pInData; - int nBitsLeft = nBits; - - // Bounds checking.. - if ( ( GetNumBitsWritten() + nBits) > m_nDataBits ) - { - SetOverflowFlag(); - CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, m_pDebugName ); - return false; - } - - // !! speed!! need fast paths - // write remaining bytes - while ( nBitsLeft >= 8 ) - { - WriteUBitLong( *pOut, 8, false ); - ++pOut; - nBitsLeft -= 8; - } - - // write remaining bits - if ( nBitsLeft ) - { - WriteUBitLong( *pOut, nBitsLeft, false ); - } - - return !IsOverflowed(); -} - -void CBitWrite::WriteBytes( const void *pBuf, int nBytes ) -{ - WriteBits(pBuf, nBytes << 3); -} - -void CBitWrite::WriteBitCoord (const float f) -{ - int signbit = (f <= -COORD_RESOLUTION); - int intval = (int)abs(f); - int fractval = abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1); - - - // Send the bit flags that indicate whether we have an integer part and/or a fraction part. - WriteOneBit( intval ); - WriteOneBit( fractval ); - - if ( intval || fractval ) - { - // Send the sign bit - WriteOneBit( signbit ); - - // Send the integer if we have one. - if ( intval ) - { - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS ); - } - - // Send the fraction if we have one - if ( fractval ) - { - WriteUBitLong( (unsigned int)fractval, COORD_FRACTIONAL_BITS ); - } - } -} - -void CBitWrite::WriteBitCoordMP (const float f, bool bIntegral, bool bLowPrecision ) -{ - int signbit = (f <= -( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION )); - int intval = (int)abs(f); - int fractval = bLowPrecision ? - ( abs((int)(f*COORD_DENOMINATOR_LOWPRECISION)) & (COORD_DENOMINATOR_LOWPRECISION-1) ) : - ( abs((int)(f*COORD_DENOMINATOR)) & (COORD_DENOMINATOR-1) ); - - bool bInBounds = intval < (1 << COORD_INTEGER_BITS_MP ); - - WriteOneBit( bInBounds ); - - if ( bIntegral ) - { - // Send the sign bit - WriteOneBit( intval ); - if ( intval ) - { - WriteOneBit( signbit ); - // Send the integer if we have one. - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - if ( bInBounds ) - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS_MP ); - } - else - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS ); - } - } - } - else - { - // Send the bit flags that indicate whether we have an integer part and/or a fraction part. - WriteOneBit( intval ); - // Send the sign bit - WriteOneBit( signbit ); - - // Send the integer if we have one. - if ( intval ) - { - // Adjust the integers from [1..MAX_COORD_VALUE] to [0..MAX_COORD_VALUE-1] - intval--; - if ( bInBounds ) - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS_MP ); - } - else - { - WriteUBitLong( (unsigned int)intval, COORD_INTEGER_BITS ); - } - } - WriteUBitLong( (unsigned int)fractval, bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS ); - } -} - -void CBitWrite::SeekToBit( int nBit ) -{ - TempFlush(); - m_pDataOut = m_pData + ( nBit / 32 ); - m_nOutBufWord = *( m_pDataOut ); - m_nOutBitsAvail = 32 - ( nBit & 31 ); -} - - - -void CBitWrite::WriteBitVec3Coord( const Vector& fa ) -{ - int xflag, yflag, zflag; - - xflag = (fa[0] >= COORD_RESOLUTION) || (fa[0] <= -COORD_RESOLUTION); - yflag = (fa[1] >= COORD_RESOLUTION) || (fa[1] <= -COORD_RESOLUTION); - zflag = (fa[2] >= COORD_RESOLUTION) || (fa[2] <= -COORD_RESOLUTION); - - WriteOneBit( xflag ); - WriteOneBit( yflag ); - WriteOneBit( zflag ); - - if ( xflag ) - WriteBitCoord( fa[0] ); - if ( yflag ) - WriteBitCoord( fa[1] ); - if ( zflag ) - WriteBitCoord( fa[2] ); -} - -void CBitWrite::WriteBitNormal( float f ) -{ - int signbit = (f <= -NORMAL_RESOLUTION); - - // NOTE: Since +/-1 are valid values for a normal, I'm going to encode that as all ones - unsigned int fractval = abs( (int)(f*NORMAL_DENOMINATOR) ); - - // clamp.. - if (fractval > NORMAL_DENOMINATOR) - fractval = NORMAL_DENOMINATOR; - - // Send the sign bit - WriteOneBit( signbit ); - - // Send the fractional component - WriteUBitLong( fractval, NORMAL_FRACTIONAL_BITS ); -} - -void CBitWrite::WriteBitVec3Normal( const Vector& fa ) -{ - int xflag, yflag; - - xflag = (fa[0] >= NORMAL_RESOLUTION) || (fa[0] <= -NORMAL_RESOLUTION); - yflag = (fa[1] >= NORMAL_RESOLUTION) || (fa[1] <= -NORMAL_RESOLUTION); - - WriteOneBit( xflag ); - WriteOneBit( yflag ); - - if ( xflag ) - WriteBitNormal( fa[0] ); - if ( yflag ) - WriteBitNormal( fa[1] ); - - // Write z sign bit - int signbit = (fa[2] <= -NORMAL_RESOLUTION); - WriteOneBit( signbit ); -} - -void CBitWrite::WriteBitAngle( float fAngle, int numbits ) -{ - - unsigned int shift = GetBitForBitnum(numbits); - unsigned int mask = shift - 1; - - int d = (int)( (fAngle / 360.0) * shift ); - d &= mask; - - WriteUBitLong((unsigned int)d, numbits); -} - -bool CBitWrite::WriteBitsFromBuffer( bf_read *pIn, int nBits ) -{ -// This could be optimized a little by - while ( nBits > 32 ) - { - WriteUBitLong( pIn->ReadUBitLong( 32 ), 32 ); - nBits -= 32; - } - - WriteUBitLong( pIn->ReadUBitLong( nBits ), nBits ); - return !IsOverflowed() && !pIn->IsOverflowed(); -} - -void CBitWrite::WriteBitAngles( const QAngle& fa ) -{ - // FIXME: - Vector tmp( fa.x, fa.y, fa.z ); - WriteBitVec3Coord( tmp ); -} - -bool CBitRead::Seek( int nPosition ) -{ - bool bSucc = true; - if ( nPosition < 0 || nPosition > m_nDataBits) - { - SetOverflowFlag(); - bSucc = false; - nPosition = m_nDataBits; - } - int nHead = m_nDataBytes & 3; // non-multiple-of-4 bytes at head of buffer. We put the "round off" - // at the head to make reading and detecting the end efficient. - - int nByteOfs = nPosition / 8; - if ( ( m_nDataBytes < 4 ) || ( nHead && ( nByteOfs < nHead ) ) ) - { - // partial first dword - uint8 const *pPartial = ( uint8 const *) m_pData; - if ( m_pData ) - { - m_nInBufWord = *( pPartial++ ); - if ( nHead > 1 ) - m_nInBufWord |= ( *pPartial++ ) << 8; - if ( nHead > 2 ) - m_nInBufWord |= ( *pPartial++ ) << 16; - } - m_pDataIn = ( uint32 const * ) pPartial; - m_nInBufWord >>= ( nPosition & 31 ); - m_nBitsAvail = ( nHead << 3 ) - ( nPosition & 31 ); - } - else - { - int nAdjPosition = nPosition - ( nHead << 3 ); - m_pDataIn = reinterpret_cast ( - reinterpret_cast( m_pData ) + ( ( nAdjPosition / 32 ) << 2 ) + nHead ); - if ( m_pData ) - { - m_nBitsAvail = 32; - GrabNextDWord(); - } - else - { - m_nInBufWord = 0; - m_nBitsAvail = 1; - } - m_nInBufWord >>= ( nAdjPosition & 31 ); - m_nBitsAvail = min( m_nBitsAvail, 32 - ( nAdjPosition & 31 ) ); // in case grabnextdword overflowed - } - return bSucc; -} - - -void CBitRead::StartReading( const void *pData, int nBytes, int iStartBit, int nBits ) -{ -// Make sure it's dword aligned and padded. - Assert(((unsigned long)pData & 3) == 0); - m_pData = (uint32 *) pData; - m_pDataIn = m_pData; - m_nDataBytes = nBytes; - - if ( nBits == -1 ) - { - m_nDataBits = nBytes << 3; - } - else - { - Assert( nBits <= nBytes*8 ); - m_nDataBits = nBits; - } - m_bOverflow = false; - m_pBufferEnd = reinterpret_cast ( reinterpret_cast< uint8 const *> (m_pData) + nBytes ); - if ( m_pData ) - Seek( iStartBit ); - -} - -bool CBitRead::ReadString( char *pStr, int maxLen, bool bLine, int *pOutNumChars ) -{ - Assert( maxLen != 0 ); - - bool bTooSmall = false; - int iChar = 0; - while(1) - { - char val = ReadChar(); - if ( val == 0 ) - break; - else if ( bLine && val == '\n' ) - break; - - if ( iChar < (maxLen-1) ) - { - pStr[iChar] = val; - ++iChar; - } - else - { - bTooSmall = true; - } - } - - // Make sure it's null-terminated. - Assert( iChar < maxLen ); - pStr[iChar] = 0; - - if ( pOutNumChars ) - *pOutNumChars = iChar; - - return !IsOverflowed() && !bTooSmall; -} - -char* CBitRead::ReadAndAllocateString( bool *pOverflow ) -{ - char str[2048]; - - int nChars; - bool bOverflow = !ReadString( str, sizeof( str ), false, &nChars ); - if ( pOverflow ) - *pOverflow = bOverflow; - - // Now copy into the output and return it; - char *pRet = new char[ nChars + 1 ]; - for ( int i=0; i <= nChars; i++ ) - pRet[i] = str[i]; - - return pRet; -} - -int64 CBitRead::ReadLongLong( void ) -{ - int64 retval; - uint *pLongs = (uint*)&retval; - - // Read the two DWORDs according to network endian - const short endianIndex = 0x0100; - byte *idx = (byte*)&endianIndex; - pLongs[*idx++] = ReadUBitLong(sizeof(long) << 3); - pLongs[*idx] = ReadUBitLong(sizeof(long) << 3); - return retval; -} - -void CBitRead::ReadBits(void *pOutData, int nBits) -{ - unsigned char *pOut = (unsigned char*)pOutData; - int nBitsLeft = nBits; - - - // align output to dword boundary - while( ((unsigned long)pOut & 3) != 0 && nBitsLeft >= 8 ) - { - *pOut = (unsigned char)ReadUBitLong(8); - ++pOut; - nBitsLeft -= 8; - } - - // X360TBD: Can't read dwords in ReadBits because they'll get swapped - if ( IsPC() ) - { - // read dwords - while ( nBitsLeft >= 32 ) - { - *((unsigned long*)pOut) = ReadUBitLong(32); - pOut += sizeof(unsigned long); - nBitsLeft -= 32; - } - } - - // read remaining bytes - while ( nBitsLeft >= 8 ) - { - *pOut = ReadUBitLong(8); - ++pOut; - nBitsLeft -= 8; - } - - // read remaining bits - if ( nBitsLeft ) - { - *pOut = ReadUBitLong(nBitsLeft); - } - -} - -bool CBitRead::ReadBytes(void *pOut, int nBytes) -{ - ReadBits(pOut, nBytes << 3); - return !IsOverflowed(); -} - -float CBitRead::ReadBitAngle( int numbits ) -{ - float shift = (float)( GetBitForBitnum(numbits) ); - - int i = ReadUBitLong( numbits ); - float fReturn = (float)i * (360.0 / shift); - - return fReturn; -} - -// Basic Coordinate Routines (these contain bit-field size AND fixed point scaling constants) -float CBitRead::ReadBitCoord (void) -{ - int intval=0,fractval=0,signbit=0; - float value = 0.0; - - - // Read the required integer and fraction flags - intval = ReadOneBit(); - fractval = ReadOneBit(); - - // If we got either parse them, otherwise it's a zero. - if ( intval || fractval ) - { - // Read the sign bit - signbit = ReadOneBit(); - - // If there's an integer, read it in - if ( intval ) - { - // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] - intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1; - } - - // If there's a fraction, read it in - if ( fractval ) - { - fractval = ReadUBitLong( COORD_FRACTIONAL_BITS ); - } - - // Calculate the correct floating point value - value = intval + ((float)fractval * COORD_RESOLUTION); - - // Fixup the sign if negative. - if ( signbit ) - value = -value; - } - - return value; -} - -float CBitRead::ReadBitCoordMP( bool bIntegral, bool bLowPrecision ) -{ - int intval=0,fractval=0,signbit=0; - float value = 0.0; - - bool bInBounds = ReadOneBit() ? true : false; - - if ( bIntegral ) - { - // Read the required integer and fraction flags - intval = ReadOneBit(); - // If we got either parse them, otherwise it's a zero. - if ( intval ) - { - // Read the sign bit - signbit = ReadOneBit(); - - // If there's an integer, read it in - // Adjust the integers from [0..MAX_COORD_VALUE-1] to [1..MAX_COORD_VALUE] - if ( bInBounds ) - { - value = ReadUBitLong( COORD_INTEGER_BITS_MP ) + 1; - } - else - { - value = ReadUBitLong( COORD_INTEGER_BITS ) + 1; - } - } - } - else - { - // Read the required integer and fraction flags - intval = ReadOneBit(); - - // Read the sign bit - signbit = ReadOneBit(); - - // If we got either parse them, otherwise it's a zero. - if ( intval ) - { - if ( bInBounds ) - { - intval = ReadUBitLong( COORD_INTEGER_BITS_MP ) + 1; - } - else - { - intval = ReadUBitLong( COORD_INTEGER_BITS ) + 1; - } - } - - // If there's a fraction, read it in - fractval = ReadUBitLong( bLowPrecision ? COORD_FRACTIONAL_BITS_MP_LOWPRECISION : COORD_FRACTIONAL_BITS ); - - // Calculate the correct floating point value - value = intval + ((float)fractval * ( bLowPrecision ? COORD_RESOLUTION_LOWPRECISION : COORD_RESOLUTION ) ); - } - - // Fixup the sign if negative. - if ( signbit ) - value = -value; - - return value; -} - -void CBitRead::ReadBitVec3Coord( Vector& fa ) -{ - int xflag, yflag, zflag; - - // This vector must be initialized! Otherwise, If any of the flags aren't set, - // the corresponding component will not be read and will be stack garbage. - fa.Init( 0, 0, 0 ); - - xflag = ReadOneBit(); - yflag = ReadOneBit(); - zflag = ReadOneBit(); - - if ( xflag ) - fa[0] = ReadBitCoord(); - if ( yflag ) - fa[1] = ReadBitCoord(); - if ( zflag ) - fa[2] = ReadBitCoord(); -} - -float CBitRead::ReadBitNormal (void) -{ - // Read the sign bit - int signbit = ReadOneBit(); - - // Read the fractional part - unsigned int fractval = ReadUBitLong( NORMAL_FRACTIONAL_BITS ); - - // Calculate the correct floating point value - float value = (float)fractval * NORMAL_RESOLUTION; - - // Fixup the sign if negative. - if ( signbit ) - value = -value; - - return value; -} - -void CBitRead::ReadBitVec3Normal( Vector& fa ) -{ - int xflag = ReadOneBit(); - int yflag = ReadOneBit(); - - if (xflag) - fa[0] = ReadBitNormal(); - else - fa[0] = 0.0f; - - if (yflag) - fa[1] = ReadBitNormal(); - else - fa[1] = 0.0f; - - // The first two imply the third (but not its sign) - int znegative = ReadOneBit(); - - float fafafbfb = fa[0] * fa[0] + fa[1] * fa[1]; - if (fafafbfb < 1.0f) - fa[2] = sqrt( 1.0f - fafafbfb ); - else - fa[2] = 0.0f; - - if (znegative) - fa[2] = -fa[2]; -} - -void CBitRead::ReadBitAngles( QAngle& fa ) -{ - Vector tmp; - ReadBitVec3Coord( tmp ); - fa.Init( tmp.x, tmp.y, tmp.z ); -} diff --git a/Resources/NetHook/tier1/processor_detect.cpp b/Resources/NetHook/tier1/processor_detect.cpp deleted file mode 100644 index 2639ec88..00000000 --- a/Resources/NetHook/tier1/processor_detect.cpp +++ /dev/null @@ -1,278 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: win32 dependant ASM code for CPU capability detection -// -// $Workfile: $ -// $NoKeywords: $ -//=============================================================================// - -#ifdef _LINUX - -#include "processor_detect_linux.cpp" - -#elif defined( _X360 ) - -bool CheckMMXTechnology(void) { return false; } -bool CheckSSETechnology(void) { return false; } -bool CheckSSE2Technology(void) { return false; } -bool Check3DNowTechnology(void) { return false; } - -#elif defined( _WIN32 ) && !defined( _X360 ) - -#pragma optimize( "", off ) -#pragma warning( disable: 4800 ) //'int' : forcing value to bool 'true' or 'false' (performance warning) - -// stuff from windows.h -#ifndef EXCEPTION_EXECUTE_HANDLER -#define EXCEPTION_EXECUTE_HANDLER 1 -#endif - -bool CheckMMXTechnology(void) -{ - int retval = true; - unsigned int RegEDX = 0; - -#ifdef CPUID - _asm pushad; -#endif - - __try - { - _asm - { -#ifdef CPUID - xor edx, edx // Clue the compiler that EDX is about to be used. -#endif - mov eax, 1 // set up CPUID to return processor version and features - // 0 = vendor string, 1 = version info, 2 = cache info - CPUID // code bytes = 0fh, 0a2h - mov RegEDX, edx // features returned in edx - } - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - retval = false; - } - - // If CPUID not supported, then certainly no MMX extensions. - if (retval) - { - if (RegEDX & 0x800000) // bit 23 is set for MMX technology - { - __try - { - // try executing the MMX instruction "emms" - _asm EMMS - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - retval = false; - } - } - - else - retval = false; // processor supports CPUID but does not support MMX technology - - // if retval == 0 here, it means the processor has MMX technology but - // floating-point emulation is on; so MMX technology is unavailable - } - -#ifdef CPUID - _asm popad; -#endif - - return retval; -} - -bool CheckSSETechnology(void) -{ - int retval = true; - unsigned int RegEDX = 0; - -#ifdef CPUID - _asm pushad; -#endif - - // Do we have support for the CPUID function? - __try - { - _asm - { -#ifdef CPUID - xor edx, edx // Clue the compiler that EDX is about to be used. -#endif - mov eax, 1 // set up CPUID to return processor version and features - // 0 = vendor string, 1 = version info, 2 = cache info - CPUID // code bytes = 0fh, 0a2h - mov RegEDX, edx // features returned in edx - } - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - retval = false; - } - - // If CPUID not supported, then certainly no SSE extensions. - if (retval) - { - // Do we have support for SSE in this processor? - if ( RegEDX & 0x2000000L ) // bit 25 is set for SSE technology - { - // Make sure that SSE is supported by executing an inline SSE instruction - -// BUGBUG, FIXME - Visual C Version 6.0 does not support SSE inline code YET (No macros from Intel either) -// Fix this if VC7 supports inline SSE instructinons like "xorps" as shown below. -#if 1 - __try - { - _asm - { - // Attempt execution of a SSE instruction to make sure OS supports SSE FPU context switches - xorps xmm0, xmm0 - // This will work on Win2k+ (Including masking SSE FPU exception to "normalized" values) - // This will work on Win98+ (But no "masking" of FPU exceptions provided) - } - } - __except(EXCEPTION_EXECUTE_HANDLER) -#endif - - { - retval = false; - } - } - else - retval = false; - } -#ifdef CPUID - _asm popad; -#endif - - return retval; -} - -bool CheckSSE2Technology(void) -{ - int retval = true; - unsigned int RegEDX = 0; - -#ifdef CPUID - _asm pushad; -#endif - - // Do we have support for the CPUID function? - __try - { - _asm - { -#ifdef CPUID - xor edx, edx // Clue the compiler that EDX is about to be used. -#endif - mov eax, 1 // set up CPUID to return processor version and features - // 0 = vendor string, 1 = version info, 2 = cache info - CPUID // code bytes = 0fh, 0a2h - mov RegEDX, edx // features returned in edx - } - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - retval = false; - } - - // If CPUID not supported, then certainly no SSE extensions. - if (retval) - { - // Do we have support for SSE in this processor? - if ( RegEDX & 0x04000000 ) // bit 26 is set for SSE2 technology - { - // Make sure that SSE is supported by executing an inline SSE instruction - - __try - { - _asm - { - // Attempt execution of a SSE2 instruction to make sure OS supports SSE FPU context switches - xorpd xmm0, xmm0 - } - } - __except(EXCEPTION_EXECUTE_HANDLER) - - { - retval = false; - } - } - else - retval = false; - } -#ifdef CPUID - _asm popad; -#endif - - return retval; -} - -bool Check3DNowTechnology(void) -{ - int retval = true; - unsigned int RegEAX = 0; - -#ifdef CPUID - _asm pushad; -#endif - - // First see if we can execute CPUID at all - __try - { - _asm - { -#ifdef CPUID -// xor edx, edx // Clue the compiler that EDX is about to be used. -#endif - mov eax, 0x80000000 // setup CPUID to return whether AMD >0x80000000 function are supported. - // 0x80000000 = Highest 0x80000000+ function, 0x80000001 = 3DNow support - CPUID // code bytes = 0fh, 0a2h - mov RegEAX, eax // result returned in eax - } - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - retval = false; - } - - // If CPUID not supported, then there is definitely no 3DNow support - if (retval) - { - // Are there any "higher" AMD CPUID functions? - if (RegEAX > 0x80000000L ) - { - __try - { - _asm - { - mov eax, 0x80000001 // setup to test for CPU features - CPUID // code bytes = 0fh, 0a2h - shr edx, 31 // If bit 31 is set, we have 3DNow support! - mov retval, edx // Save the return value for end of function - } - } - __except(EXCEPTION_EXECUTE_HANDLER) - { - retval = false; - } - } - else - { - // processor supports CPUID but does not support AMD CPUID functions - retval = false; - } - } - -#ifdef CPUID - _asm popad; -#endif - - return retval; -} - -#pragma optimize( "", on ) - -#endif // _WIN32 diff --git a/Resources/NetHook/tier1/processor_detect.h b/Resources/NetHook/tier1/processor_detect.h deleted file mode 100644 index 64cb5559..00000000 --- a/Resources/NetHook/tier1/processor_detect.h +++ /dev/null @@ -1,12 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: functions to expose CPU capabilities -// -// $NoKeywords: $ -//=============================================================================// - -bool CheckMMXTechnology(void); -bool CheckSSETechnology(void); -bool CheckSSE2Technology(void); -bool Check3DNowTechnology(void); - diff --git a/Resources/NetHook/tier1/processor_detect_linux.cpp b/Resources/NetHook/tier1/processor_detect_linux.cpp deleted file mode 100644 index b09df0e0..00000000 --- a/Resources/NetHook/tier1/processor_detect_linux.cpp +++ /dev/null @@ -1,47 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: linux dependant ASM code for CPU capability detection -// -// $Workfile: $ -// $NoKeywords: $ -//=============================================================================// - -#define cpuid(in,a,b,c,d) \ - asm("pushl %%ebx\n\t" "cpuid\n\t" "movl %%ebx,%%esi\n\t" "pop %%ebx": "=a" (a), "=S" (b), "=c" (c), "=d" (d) : "a" (in)); - -bool CheckMMXTechnology(void) -{ - unsigned long eax,ebx,edx,unused; - cpuid(1,eax,ebx,unused,edx); - - return edx & 0x800000; -} - -bool CheckSSETechnology(void) -{ - unsigned long eax,ebx,edx,unused; - cpuid(1,eax,ebx,unused,edx); - - return edx & 0x2000000L; -} - -bool CheckSSE2Technology(void) -{ - unsigned long eax,ebx,edx,unused; - cpuid(1,eax,ebx,unused,edx); - - return edx & 0x04000000; -} - -bool Check3DNowTechnology(void) -{ - unsigned long eax, unused; - cpuid(0x80000000,eax,unused,unused,unused); - - if ( eax > 0x80000000L ) - { - cpuid(0x80000001,unused,unused,unused,eax); - return ( eax & 1<<31 ); - } - return false; -} diff --git a/Resources/NetHook/tier1/rangecheckedvar.cpp b/Resources/NetHook/tier1/rangecheckedvar.cpp deleted file mode 100644 index a342dcd9..00000000 --- a/Resources/NetHook/tier1/rangecheckedvar.cpp +++ /dev/null @@ -1,41 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#include "rangecheckedvar.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -bool g_bDoRangeChecks = true; - - -static int g_nDisables = 0; - - -CDisableRangeChecks::CDisableRangeChecks() -{ - if ( !ThreadInMainThread() ) - return; - g_nDisables++; - g_bDoRangeChecks = false; -} - - -CDisableRangeChecks::~CDisableRangeChecks() -{ - if ( !ThreadInMainThread() ) - return; - Assert( g_nDisables > 0 ); - --g_nDisables; - if ( g_nDisables == 0 ) - { - g_bDoRangeChecks = true; - } -} - - - - diff --git a/Resources/NetHook/tier1/rangecheckedvar.h b/Resources/NetHook/tier1/rangecheckedvar.h deleted file mode 100644 index cf04e7b9..00000000 --- a/Resources/NetHook/tier1/rangecheckedvar.h +++ /dev/null @@ -1,113 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -//=============================================================================// - -#ifndef RANGECHECKEDVAR_H -#define RANGECHECKEDVAR_H -#ifdef _WIN32 -#pragma once -#endif - - -#include "tier0/dbg.h" -#include "tier0/threadtools.h" -#include "mathlib/vector.h" -#include - - -// Use this to disable range checks within a scope. -class CDisableRangeChecks -{ -public: - CDisableRangeChecks(); - ~CDisableRangeChecks(); -}; - - -template< class T > -inline void RangeCheck( const T &value, int minValue, int maxValue ) -{ -#ifdef _DEBUG - extern bool g_bDoRangeChecks; - if ( ThreadInMainThread() && g_bDoRangeChecks ) - { - // Ignore the min/max stuff for now.. just make sure it's not a NAN. - Assert( _finite( value ) ); - } -#endif -} - -inline void RangeCheck( const Vector &value, int minValue, int maxValue ) -{ -#ifdef _DEBUG - RangeCheck( value.x, minValue, maxValue ); - RangeCheck( value.y, minValue, maxValue ); - RangeCheck( value.z, minValue, maxValue ); -#endif -} - - -template< class T, int minValue, int maxValue, int startValue > -class CRangeCheckedVar -{ -public: - - inline CRangeCheckedVar() - { - m_Val = startValue; - } - - inline CRangeCheckedVar( const T &value ) - { - *this = value; - } - - // Clamp the value to its limits. Interpolation code uses this after interpolating. - inline void Clamp() - { - if ( m_Val < minValue ) - m_Val = minValue; - else if ( m_Val > maxValue ) - m_Val = maxValue; - } - - inline operator const T&() const - { - return m_Val; - } - - inline CRangeCheckedVar& operator=( const T &value ) - { - RangeCheck( value, minValue, maxValue ); - m_Val = value; - return *this; - } - - inline CRangeCheckedVar& operator+=( const T &value ) - { - return (*this = m_Val + value); - } - - inline CRangeCheckedVar& operator-=( const T &value ) - { - return (*this = m_Val - value); - } - - inline CRangeCheckedVar& operator*=( const T &value ) - { - return (*this = m_Val * value); - } - - inline CRangeCheckedVar& operator/=( const T &value ) - { - return (*this = m_Val / value); - } - -private: - - T m_Val; -}; - -#endif // RANGECHECKEDVAR_H diff --git a/Resources/NetHook/tier1/refcount.h b/Resources/NetHook/tier1/refcount.h deleted file mode 100644 index d5a7e2d4..00000000 --- a/Resources/NetHook/tier1/refcount.h +++ /dev/null @@ -1,385 +0,0 @@ -//========== Copyright © 2005, Valve Corporation, All rights reserved. ======== -// -// Purpose: Tools for correctly implementing & handling reference counted -// objects -// -//============================================================================= - -#ifndef REFCOUNT_H -#define REFCOUNT_H - -#include "tier0/threadtools.h" - -#if defined( _WIN32 ) -#pragma once -#endif - -//----------------------------------------------------------------------------- -// Purpose: Implement a standard reference counted interface. Use of this -// is optional insofar as all the concrete tools only require -// at compile time that the function signatures match. -//----------------------------------------------------------------------------- - -class IRefCounted -{ -public: - virtual int AddRef() = 0; - virtual int Release() = 0; -}; - - -//----------------------------------------------------------------------------- -// Purpose: Release a pointer and mark it NULL -//----------------------------------------------------------------------------- - -template -inline int SafeRelease( REFCOUNTED_ITEM_PTR &pRef ) -{ - // Use funny syntax so that this works on "auto pointers" - REFCOUNTED_ITEM_PTR *ppRef = &pRef; - if ( *ppRef ) - { - int result = (*ppRef)->Release(); - *ppRef = NULL; - return result; - } - return 0; -} - -//----------------------------------------------------------------------------- -// Purpose: Maintain a reference across a scope -//----------------------------------------------------------------------------- - -template -class CAutoRef -{ -public: - CAutoRef( T *pRef ) - : m_pRef( pRef ) - { - if ( m_pRef ) - m_pRef->AddRef(); - } - - ~CAutoRef() - { - if (m_pRef) - m_pRef->Release(); - } - -private: - T *m_pRef; -}; - -//----------------------------------------------------------------------------- -// Purpose: Do a an inline AddRef then return the pointer, useful when -// returning an object from a function -//----------------------------------------------------------------------------- - -#define RetAddRef( p ) ( (p)->AddRef(), (p) ) -#define InlineAddRef( p ) ( (p)->AddRef(), (p) ) - - -//----------------------------------------------------------------------------- -// Purpose: A class to both hold a pointer to an object and its reference. -// Base exists to support other cleanup models -//----------------------------------------------------------------------------- - -template -class CBaseAutoPtr -{ -public: - CBaseAutoPtr() : m_pObject(0) {} - CBaseAutoPtr(T *pFrom) : m_pObject(pFrom) {} - - operator const void *() const { return m_pObject; } - operator void *() { return m_pObject; } - - operator const T *() const { return m_pObject; } - operator const T *() { return m_pObject; } - operator T *() { return m_pObject; } - - int operator=( int i ) { AssertMsg( i == 0, "Only NULL allowed on integer assign" ); m_pObject = 0; return 0; } - T * operator=( T *p ) { m_pObject = p; return p; } - - bool operator !() const { return ( !m_pObject ); } - bool operator!=( int i ) const { AssertMsg( i == 0, "Only NULL allowed on integer compare" ); return (m_pObject != NULL); } - bool operator==( const void *p ) const { return ( m_pObject == p ); } - bool operator!=( const void *p ) const { return ( m_pObject != p ); } - bool operator==( T *p ) const { return operator==( (void *)p ); } - bool operator!=( T *p ) const { return operator!=( (void *)p ); } - bool operator==( const CBaseAutoPtr &p ) const { return operator==( (const void *)p ); } - bool operator!=( const CBaseAutoPtr &p ) const { return operator!=( (const void *)p ); } - - T * operator->() { return m_pObject; } - T & operator *() { return *m_pObject; } - T ** operator &() { return &m_pObject; } - - const T * operator->() const { return m_pObject; } - const T & operator *() const { return *m_pObject; } - T * const * operator &() const { return &m_pObject; } - -protected: - CBaseAutoPtr( const CBaseAutoPtr &from ) : m_pObject( from.m_pObject ) {} - void operator=( const CBaseAutoPtr &from ) { m_pObject = from.m_pObject; } - - T *m_pObject; -}; - -//--------------------------------------------------------- - -template -class CRefPtr : public CBaseAutoPtr -{ - typedef CBaseAutoPtr BaseClass; -public: - CRefPtr() {} - CRefPtr( T *pInit ) : BaseClass( pInit ) {} - CRefPtr( const CRefPtr &from ) : BaseClass( from ) {} - ~CRefPtr() { if ( BaseClass::m_pObject ) BaseClass::m_pObject->Release(); } - - void operator=( const CRefPtr &from ) { BaseClass::operator=( from ); } - - int operator=( int i ) { return BaseClass::operator=( i ); } - T *operator=( T *p ) { return BaseClass::operator=( p ); } - - operator bool() const { return !BaseClass::operator!(); } - operator bool() { return !BaseClass::operator!(); } - - void SafeRelease() { if ( BaseClass::m_pObject ) BaseClass::m_pObject->Release(); BaseClass::m_pObject = 0; } - void AssignAddRef( T *pFrom ) { SafeRelease(); if (pFrom) pFrom->AddRef(); BaseClass::m_pObject = pFrom; } - void AddRefAssignTo( T *&pTo ) { ::SafeRelease( pTo ); if ( BaseClass::m_pObject ) BaseClass::m_pObject->AddRef(); pTo = BaseClass::m_pObject; } -}; - - -//----------------------------------------------------------------------------- -// Purpose: Traits classes defining reference count threading model -//----------------------------------------------------------------------------- - -class CRefMT -{ -public: - static int Increment( int *p) { return ThreadInterlockedIncrement( (long *)p ); } - static int Decrement( int *p) { return ThreadInterlockedDecrement( (long *)p ); } -}; - -class CRefST -{ -public: - static int Increment( int *p) { return ++(*p); } - static int Decrement( int *p) { return --(*p); } -}; - -//----------------------------------------------------------------------------- -// Purpose: Actual reference counting implementation. Pulled out to reduce -// code bloat. -//----------------------------------------------------------------------------- - -template -class NO_VTABLE CRefCountServiceBase -{ -protected: - CRefCountServiceBase() - : m_iRefs( 1 ) - { - } - - virtual ~CRefCountServiceBase() - { - } - - virtual bool OnFinalRelease() - { - return true; - } - - int GetRefCount() const - { - return m_iRefs; - } - - int DoAddRef() - { - return CRefThreading::Increment( &m_iRefs ); - } - - int DoRelease() - { - int result = CRefThreading::Decrement( &m_iRefs ); - if ( result ) - return result; - if ( OnFinalRelease() && bSelfDelete ) - delete this; - return 0; - } - -private: - int m_iRefs; -}; - -class CRefCountServiceNull -{ -protected: - static int DoAddRef() { return 1; } - static int DoRelease() { return 1; } -}; - -template -class NO_VTABLE CRefCountServiceDestruct -{ -protected: - CRefCountServiceDestruct() - : m_iRefs( 1 ) - { - } - - virtual ~CRefCountServiceDestruct() - { - } - - int GetRefCount() const - { - return m_iRefs; - } - - int DoAddRef() - { - return CRefThreading::Increment( &m_iRefs ); - } - - int DoRelease() - { - int result = CRefThreading::Decrement( &m_iRefs ); - if ( result ) - return result; - this->~CRefCountServiceDestruct(); - return 0; - } - -private: - int m_iRefs; -}; - - -typedef CRefCountServiceBase CRefCountServiceST; -typedef CRefCountServiceBase CRefCountServiceNoDeleteST; - -typedef CRefCountServiceBase CRefCountServiceMT; -typedef CRefCountServiceBase CRefCountServiceNoDeleteMT; - -// Default to threadsafe -typedef CRefCountServiceNoDeleteMT CRefCountServiceNoDelete; -typedef CRefCountServiceMT CRefCountService; - -//----------------------------------------------------------------------------- -// Purpose: Base classes to implement reference counting -//----------------------------------------------------------------------------- - -template < class REFCOUNT_SERVICE = CRefCountService > -class NO_VTABLE CRefCounted : public REFCOUNT_SERVICE -{ -public: - virtual ~CRefCounted() {} - int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); } - int Release() { return REFCOUNT_SERVICE::DoRelease(); } -}; - -//------------------------------------- - -template < class BASE1, class REFCOUNT_SERVICE = CRefCountService > -class NO_VTABLE CRefCounted1 : public BASE1, - public REFCOUNT_SERVICE -{ -public: - virtual ~CRefCounted1() {} - int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); } - int Release() { return REFCOUNT_SERVICE::DoRelease(); } -}; - -//------------------------------------- - -template < class BASE1, class BASE2, class REFCOUNT_SERVICE = CRefCountService > -class NO_VTABLE CRefCounted2 : public BASE1, public BASE2, - public REFCOUNT_SERVICE -{ -public: - virtual ~CRefCounted2() {} - int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); } - int Release() { return REFCOUNT_SERVICE::DoRelease(); } -}; - -//------------------------------------- - -template < class BASE1, class BASE2, class BASE3, class REFCOUNT_SERVICE = CRefCountService > -class NO_VTABLE CRefCounted3 : public BASE1, public BASE2, public BASE3, - public REFCOUNT_SERVICE -{ - virtual ~CRefCounted3() {} - int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); } - int Release() { return REFCOUNT_SERVICE::DoRelease(); } -}; - -//------------------------------------- - -template < class BASE1, class BASE2, class BASE3, class BASE4, class REFCOUNT_SERVICE = CRefCountService > -class NO_VTABLE CRefCounted4 : public BASE1, public BASE2, public BASE3, public BASE4, - public REFCOUNT_SERVICE -{ -public: - virtual ~CRefCounted4() {} - int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); } - int Release() { return REFCOUNT_SERVICE::DoRelease(); } -}; - -//------------------------------------- - -template < class BASE1, class BASE2, class BASE3, class BASE4, class BASE5, class REFCOUNT_SERVICE = CRefCountService > -class NO_VTABLE CRefCounted5 : public BASE1, public BASE2, public BASE3, public BASE4, public BASE5, - public REFCOUNT_SERVICE -{ -public: - virtual ~CRefCounted5() {} - int AddRef() { return REFCOUNT_SERVICE::DoAddRef(); } - int Release() { return REFCOUNT_SERVICE::DoRelease(); } -}; - -//----------------------------------------------------------------------------- -// Purpose: Class to throw around a reference counted item to debug -// referencing problems -//----------------------------------------------------------------------------- - -template -class CRefDebug : public BASE_REFCOUNTED -{ -public: -#ifdef _DEBUG - CRefDebug() - { - AssertMsg( GetRefCount() == 1, "Expected initial ref count of 1" ); - DevMsg( "%s:create 0x%x\n", ( pszName ) ? pszName : "", this ); - } - - virtual ~CRefDebug() - { - AssertDevMsg( GetRefCount() == FINAL_REFS, "Object still referenced on destroy?" ); - DevMsg( "%s:destroy 0x%x\n", ( pszName ) ? pszName : "", this ); - } - - int AddRef() - { - DevMsg( "%s:(0x%x)->AddRef() --> %d\n", ( pszName ) ? pszName : "", this, GetRefCount() + 1 ); - return BASE_REFCOUNTED::AddRef(); - } - - int Release() - { - DevMsg( "%s:(0x%x)->Release() --> %d\n", ( pszName ) ? pszName : "", this, GetRefCount() - 1 ); - Assert( GetRefCount() > 0 ); - return BASE_REFCOUNTED::Release(); - } -#endif -}; - -//----------------------------------------------------------------------------- - -#endif // REFCOUNT_H diff --git a/Resources/NetHook/tier1/smartptr.h b/Resources/NetHook/tier1/smartptr.h deleted file mode 100644 index fa17a792..00000000 --- a/Resources/NetHook/tier1/smartptr.h +++ /dev/null @@ -1,279 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef SMARTPTR_H -#define SMARTPTR_H -#ifdef _WIN32 -#pragma once -#endif - - -class CRefCountAccessor -{ -public: - template< class T > - static void AddRef( T *pObj ) - { - pObj->AddRef(); - } - - template< class T > - static void Release( T *pObj ) - { - pObj->Release(); - } -}; - -// This can be used if your objects use AddReference/ReleaseReference function names. -class CRefCountAccessorLongName -{ -public: - template< class T > - static void AddRef( T *pObj ) - { - pObj->AddReference(); - } - - template< class T > - static void Release( T *pObj ) - { - pObj->ReleaseReference(); - } -}; - - -// -// CPlainAutoPtr -// is a smart wrapper for a pointer on the stack that performs "delete" upon destruction. -// -// No reference counting is performed, copying is prohibited "s_p2.Attach( s_p1.Detach() )" should be used -// for readability and ease of maintenance. -// -// Auto pointer supports an "arrow" operator for invoking methods on the pointee and a "dereference" operator -// for getting a pointee reference. -// -// No automatic casting to bool/ptrtype is performed to avoid bugs and problems (read on "safe bool idiom" -// if casting to bool or pointer happens to be useful). -// -// Test for validity with "IsValid", get the pointer with "Get". -// -template < typename T > -class CPlainAutoPtr -{ -public: - explicit CPlainAutoPtr( T *p = NULL ) : m_p( p ) {} - ~CPlainAutoPtr( void ) { Delete(); } - -public: - void Delete( void ) { delete Detach(); } - -private: // Disallow copying, use Detach() instead to avoid ambiguity - CPlainAutoPtr( CPlainAutoPtr const &x ); - CPlainAutoPtr & operator = ( CPlainAutoPtr const &x ); - -public: - void Attach( T *p ) { m_p = p; } - T * Detach( void ) { T * p( m_p ); m_p = NULL; return p; } - -public: - bool IsValid( void ) const { return m_p != NULL; } - T * Get( void ) const { return m_p; } - T * operator -> ( void ) const { return Get(); } - T & operator * ( void ) const { return *Get(); } - -private: - T * m_p; -}; - -// -// CArrayAutoPtr -// is a smart wrapper for an array pointer on the stack that performs "delete []" upon destruction. -// -// No reference counting is performed, copying is prohibited "s_p2.Attach( s_p1.Detach() )" should be used -// for readability and ease of maintenance. -// -// Auto pointer supports an "indexing" operator for accessing array elements. -// -// No automatic casting to bool/ptrtype is performed to avoid bugs and problems (read on "safe bool idiom" -// if casting to bool or pointer happens to be useful). -// -// Test for validity with "IsValid", get the array pointer with "Get". -// -template < typename T > -class CArrayAutoPtr : public CPlainAutoPtr < T > // Warning: no polymorphic destructor (delete on base class will be a mistake) -{ -public: - explicit CArrayAutoPtr( T *p = NULL ) { Attach( p ); } - ~CArrayAutoPtr( void ) { Delete(); } - -public: - void Delete( void ) { delete [] Detach(); } - -public: - T & operator [] ( int k ) const { return Get()[ k ]; } -}; - - -// Smart pointers can be used to automatically free an object when nobody points -// at it anymore. Things contained in smart pointers must implement AddRef and Release -// functions. If those functions are private, then the class must make -// CRefCountAccessor a friend. -template -class CSmartPtr -{ -public: - CSmartPtr(); - CSmartPtr( T *pObj ); - CSmartPtr( const CSmartPtr &other ); - ~CSmartPtr(); - - T* operator=( T *pObj ); - void operator=( const CSmartPtr &other ); - const T* operator->() const; - T* operator->(); - bool operator!() const; - bool operator==( const T *pOther ) const; - bool IsValid() const; // Tells if the pointer is valid. - T* GetObject() const; // Get temporary object pointer, don't store it for later reuse! - void MarkDeleted(); - -private: - T *m_pObj; -}; - - -template< class T, class RefCountAccessor > -inline CSmartPtr::CSmartPtr() -{ - m_pObj = NULL; -} - -template< class T, class RefCountAccessor > -inline CSmartPtr::CSmartPtr( T *pObj ) -{ - m_pObj = NULL; - *this = pObj; -} - -template< class T, class RefCountAccessor > -inline CSmartPtr::CSmartPtr( const CSmartPtr &other ) -{ - m_pObj = NULL; - *this = other; -} - -template< class T, class RefCountAccessor > -inline CSmartPtr::~CSmartPtr() -{ - if ( m_pObj ) - { - RefCountAccessor::Release( m_pObj ); - } -} - -template< class T, class RefCountAccessor > -inline T* CSmartPtr::operator=( T *pObj ) -{ - if ( pObj == m_pObj ) - return pObj; - - if ( pObj ) - { - RefCountAccessor::AddRef( pObj ); - } - if ( m_pObj ) - { - RefCountAccessor::Release( m_pObj ); - } - m_pObj = pObj; - return pObj; -} - -template< class T, class RefCountAccessor > -inline void CSmartPtr::MarkDeleted() -{ - m_pObj = NULL; -} - -template< class T, class RefCountAccessor > -inline void CSmartPtr::operator=( const CSmartPtr &other ) -{ - *this = other.m_pObj; -} - -template< class T, class RefCountAccessor > -inline const T* CSmartPtr::operator->() const -{ - return m_pObj; -} - -template< class T, class RefCountAccessor > -inline T* CSmartPtr::operator->() -{ - return m_pObj; -} - -template< class T, class RefCountAccessor > -inline bool CSmartPtr::operator!() const -{ - return !m_pObj; -} - -template< class T, class RefCountAccessor > -inline bool CSmartPtr::operator==( const T *pOther ) const -{ - return m_pObj == pOther; -} - -template< class T, class RefCountAccessor > -inline bool CSmartPtr::IsValid() const -{ - return m_pObj != NULL; -} - -template< class T, class RefCountAccessor > -inline T* CSmartPtr::GetObject() const -{ - return m_pObj; -} - - -// -// CAutoPushPop -// allows you to set value of a variable upon construction and destruction. -// Constructors: -// CAutoPushPop x( myvar ) -// saves the value and restores upon destruction. -// CAutoPushPop x( myvar, newvalue ) -// saves the value, assigns new value upon construction, restores saved value upon destruction. -// CAutoPushPop x( myvar, newvalue, restorevalue ) -// assigns new value upon construction, assignes restorevalue upon destruction. -// -template < typename T > -class CAutoPushPop -{ -public: - explicit CAutoPushPop( T& var ) : m_rVar( var ), m_valPop( var ) {} - CAutoPushPop( T& var, T const &valPush ) : m_rVar( var ), m_valPop( var ) { m_rVar = valPush; } - CAutoPushPop( T& var, T const &valPush, T const &valPop ) : m_rVar( var ), m_valPop( var ) { m_rVar = valPush; } - - ~CAutoPushPop() { m_rVar = m_valPop; } - -private: // forbid copying - CAutoPushPop( CAutoPushPop const &x ); - CAutoPushPop & operator = ( CAutoPushPop const &x ); - -public: - T & Get() { return m_rVar; } - -private: - T &m_rVar; - T m_valPop; -}; - - -#endif // SMARTPTR_H diff --git a/Resources/NetHook/tier1/stringpool.cpp b/Resources/NetHook/tier1/stringpool.cpp deleted file mode 100644 index 8924034e..00000000 --- a/Resources/NetHook/tier1/stringpool.cpp +++ /dev/null @@ -1,334 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -//===========================================================================// - -#include "convar.h" -#include "tier0/dbg.h" -#include "stringpool.h" -#include "tier1/strtools.h" -#include "generichash.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -//----------------------------------------------------------------------------- -// Purpose: Comparison function for string sorted associative data structures -//----------------------------------------------------------------------------- - -bool StrLess( const char * const &pszLeft, const char * const &pszRight ) -{ - return ( Q_stricmp( pszLeft, pszRight) < 0 ); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - -CStringPool::CStringPool() - : m_Strings( 32, 256, StrLess ) -{ -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - -CStringPool::~CStringPool() -{ - FreeAll(); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - -unsigned int CStringPool::Count() const -{ - return m_Strings.Count(); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -const char * CStringPool::Find( const char *pszValue ) -{ - unsigned short i = m_Strings.Find(pszValue); - if ( m_Strings.IsValidIndex(i) ) - return m_Strings[i]; - - return NULL; -} - -const char * CStringPool::Allocate( const char *pszValue ) -{ - char *pszNew; - - unsigned short i = m_Strings.Find(pszValue); - bool bNew = (i == m_Strings.InvalidIndex()); - - if ( !bNew ) - return m_Strings[i]; - - pszNew = strdup( pszValue ); - - if ( bNew ) - m_Strings.Insert( pszNew ); - - return pszNew; -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - -void CStringPool::FreeAll() -{ - unsigned short i = m_Strings.FirstInorder(); - while ( i != m_Strings.InvalidIndex() ) - { - free( (void *)m_Strings[i] ); - i = m_Strings.NextInorder(i); - } - m_Strings.RemoveAll(); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- - - -CCountedStringPool::CCountedStringPool() -{ - MEM_ALLOC_CREDIT(); - m_HashTable.EnsureCount(HASH_TABLE_SIZE); - - for( int i = 0; i < m_HashTable.Count(); i++ ) - { - m_HashTable[i] = INVALID_ELEMENT; - } - - m_FreeListStart = INVALID_ELEMENT; - m_Elements.AddToTail(); - m_Elements[0].pString = NULL; - m_Elements[0].nReferenceCount = 0; - m_Elements[0].nNextElement = INVALID_ELEMENT; -} - -CCountedStringPool::~CCountedStringPool() -{ - FreeAll(); -} - -void CCountedStringPool::FreeAll() -{ - int i; - - // Reset the hash table: - for( i = 0; i < m_HashTable.Count(); i++ ) - { - m_HashTable[i] = INVALID_ELEMENT; - } - - // Blow away the free list: - m_FreeListStart = INVALID_ELEMENT; - - for( i = 0; i < m_Elements.Count(); i++ ) - { - if( m_Elements[i].pString ) - { - delete [] m_Elements[i].pString; - m_Elements[i].pString = NULL; - m_Elements[i].nReferenceCount = 0; - m_Elements[i].nNextElement = INVALID_ELEMENT; - } - } - - // Remove all but the invalid element: - m_Elements.RemoveAll(); - m_Elements.AddToTail(); - m_Elements[0].pString = NULL; - m_Elements[0].nReferenceCount = 0; - m_Elements[0].nNextElement = INVALID_ELEMENT; -} - - -unsigned short CCountedStringPool::FindStringHandle( const char* pIntrinsic ) -{ - if( pIntrinsic == NULL ) - return INVALID_ELEMENT; - - unsigned short nHashBucketIndex = (HashStringCaseless(pIntrinsic ) %HASH_TABLE_SIZE); - unsigned short nCurrentBucket = m_HashTable[ nHashBucketIndex ]; - - // Does the bucket already exist? - if( nCurrentBucket != INVALID_ELEMENT ) - { - for( ; nCurrentBucket != INVALID_ELEMENT ; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement ) - { - if( !Q_stricmp( pIntrinsic, m_Elements[nCurrentBucket].pString ) ) - { - return nCurrentBucket; - } - } - } - - return 0; - -} - -char* CCountedStringPool::FindString( const char* pIntrinsic ) -{ - if( pIntrinsic == NULL ) - return NULL; - - // Yes, this will be NULL on failure. - return m_Elements[FindStringHandle(pIntrinsic)].pString; -} - -unsigned short CCountedStringPool::ReferenceStringHandle( const char* pIntrinsic ) -{ - if( pIntrinsic == NULL ) - return INVALID_ELEMENT; - - unsigned short nHashBucketIndex = (HashStringCaseless( pIntrinsic ) % HASH_TABLE_SIZE); - unsigned short nCurrentBucket = m_HashTable[ nHashBucketIndex ]; - - // Does the bucket already exist? - if( nCurrentBucket != INVALID_ELEMENT ) - { - for( ; nCurrentBucket != INVALID_ELEMENT ; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement ) - { - if( !Q_stricmp( pIntrinsic, m_Elements[nCurrentBucket].pString ) ) - { - // Anyone who hits 65k references is permanant - if( m_Elements[nCurrentBucket].nReferenceCount < MAX_REFERENCE ) - { - m_Elements[nCurrentBucket].nReferenceCount ++ ; - } - return nCurrentBucket; - } - } - } - - if( m_FreeListStart != INVALID_ELEMENT ) - { - nCurrentBucket = m_FreeListStart; - m_FreeListStart = m_Elements[nCurrentBucket].nNextElement; - } - else - { - nCurrentBucket = m_Elements.AddToTail(); - } - - m_Elements[nCurrentBucket].nReferenceCount = 1; - - // Insert at the beginning of the bucket: - m_Elements[nCurrentBucket].nNextElement = m_HashTable[ nHashBucketIndex ]; - m_HashTable[ nHashBucketIndex ] = nCurrentBucket; - - m_Elements[nCurrentBucket].pString = new char[Q_strlen( pIntrinsic ) + 1]; - Q_strcpy( m_Elements[nCurrentBucket].pString, pIntrinsic ); - - return nCurrentBucket; -} - - -char* CCountedStringPool::ReferenceString( const char* pIntrinsic ) -{ - if(!pIntrinsic) - return NULL; - - return m_Elements[ReferenceStringHandle( pIntrinsic)].pString; -} - -void CCountedStringPool::DereferenceString( const char* pIntrinsic ) -{ - // If we get a NULL pointer, just return - if (!pIntrinsic) - return; - - unsigned short nHashBucketIndex = (HashStringCaseless( pIntrinsic ) % m_HashTable.Count()); - unsigned short nCurrentBucket = m_HashTable[ nHashBucketIndex ]; - - // If there isn't anything in the bucket, just return. - if ( nCurrentBucket == INVALID_ELEMENT ) - return; - - for( unsigned short previous = INVALID_ELEMENT; nCurrentBucket != INVALID_ELEMENT ; nCurrentBucket = m_Elements[nCurrentBucket].nNextElement ) - { - if( !Q_stricmp( pIntrinsic, m_Elements[nCurrentBucket].pString ) ) - { - // Anyone who hits 65k references is permanant - if( m_Elements[nCurrentBucket].nReferenceCount < MAX_REFERENCE ) - { - m_Elements[nCurrentBucket].nReferenceCount --; - } - - if( m_Elements[nCurrentBucket].nReferenceCount == 0 ) - { - if( previous == INVALID_ELEMENT ) - { - m_HashTable[nHashBucketIndex] = m_Elements[nCurrentBucket].nNextElement; - } - else - { - m_Elements[previous].nNextElement = m_Elements[nCurrentBucket].nNextElement; - } - - delete [] m_Elements[nCurrentBucket].pString; - m_Elements[nCurrentBucket].pString = NULL; - m_Elements[nCurrentBucket].nReferenceCount = 0; - - m_Elements[nCurrentBucket].nNextElement = m_FreeListStart; - m_FreeListStart = nCurrentBucket; - break; - - } - } - - previous = nCurrentBucket; - } -} - -char* CCountedStringPool::HandleToString( unsigned short handle ) -{ - return m_Elements[handle].pString; -} - -void CCountedStringPool::SpewStrings() -{ - int i; - for ( i = 0; i < m_Elements.Count(); i++ ) - { - char* string = m_Elements[i].pString; - - Msg("String %d: ref:%d %s", i, m_Elements[i].nReferenceCount, string == NULL? "EMPTY - ok for slot zero only!" : string); - } - - Msg("\n%d total counted strings.", m_Elements.Count()); -} - -#ifdef _DEBUG -CON_COMMAND( test_stringpool, "Tests the class CStringPool" ) -{ - CStringPool pool; - - Assert(pool.Count() == 0); - - pool.Allocate("test"); - Assert(pool.Count() == 1); - - pool.Allocate("test"); - Assert(pool.Count() == 1); - - pool.Allocate("test2"); - Assert(pool.Count() == 2); - - Assert( pool.Find("test2") != NULL ); - Assert( pool.Find("TEST") != NULL ); - Assert( pool.Find("Test2") != NULL ); - Assert( pool.Find("test") != NULL ); - - pool.FreeAll(); - Assert(pool.Count() == 0); - - Msg("Pass."); -} -#endif diff --git a/Resources/NetHook/tier1/stringpool.h b/Resources/NetHook/tier1/stringpool.h deleted file mode 100644 index 42eb6c90..00000000 --- a/Resources/NetHook/tier1/stringpool.h +++ /dev/null @@ -1,91 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef STRINGPOOL_H -#define STRINGPOOL_H - -#if defined( _WIN32 ) -#pragma once -#endif - -#include "utlrbtree.h" -#include "utlvector.h" - -//----------------------------------------------------------------------------- -// Purpose: Allocates memory for strings, checking for duplicates first, -// reusing exising strings if duplicate found. -//----------------------------------------------------------------------------- - -class CStringPool -{ -public: - CStringPool(); - ~CStringPool(); - - unsigned int Count() const; - - const char * Allocate( const char *pszValue ); - void FreeAll(); - - // searches for a string already in the pool - const char * CStringPool::Find( const char *pszValue ); - -protected: - typedef CUtlRBTree CStrSet; - - CStrSet m_Strings; -}; - -//----------------------------------------------------------------------------- -// Purpose: A reference counted string pool. -// -// Elements are stored more efficiently than in the conventional string pool, -// quicker to look up, and storage is tracked via reference counts. -// -// At some point this should replace CStringPool -//----------------------------------------------------------------------------- -class CCountedStringPool -{ -public: // HACK, hash_item_t structure should not be public. - - struct hash_item_t - { - char* pString; - unsigned short nNextElement; - unsigned char nReferenceCount; - unsigned char pad; - }; - - enum - { - INVALID_ELEMENT = 0, - MAX_REFERENCE = 0xFF, - HASH_TABLE_SIZE = 1024 - }; - - CUtlVector m_HashTable; // Points to each element - CUtlVector m_Elements; - unsigned short m_FreeListStart; - -public: - CCountedStringPool(); - virtual ~CCountedStringPool(); - - void FreeAll(); - - char *FindString( const char* pIntrinsic ); - char *ReferenceString( const char* pIntrinsic ); - void DereferenceString( const char* pIntrinsic ); - - // These are only reliable if there are less than 64k strings in your string pool - unsigned short FindStringHandle( const char* pIntrinsic ); - unsigned short ReferenceStringHandle( const char* pIntrinsic ); - char *HandleToString( unsigned short handle ); - void SpewStrings(); -}; - -#endif // STRINGPOOL_H diff --git a/Resources/NetHook/tier1/strtools.cpp b/Resources/NetHook/tier1/strtools.cpp deleted file mode 100644 index 76a6a20e..00000000 --- a/Resources/NetHook/tier1/strtools.cpp +++ /dev/null @@ -1,2015 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: String Tools -// -//===========================================================================// - -// These are redefined in the project settings to prevent anyone from using them. -// We in this module are of a higher caste and thus are privileged in their use. -#ifdef strncpy - #undef strncpy -#endif - -#ifdef _snprintf - #undef _snprintf -#endif - -#if defined( sprintf ) - #undef sprintf -#endif - -#if defined( vsprintf ) - #undef vsprintf -#endif - -#ifdef _vsnprintf -#ifdef _WIN32 - #undef _vsnprintf -#endif -#endif - -#ifdef vsnprintf -#ifndef _WIN32 - #undef vsnprintf -#endif -#endif - -#if defined( strcat ) - #undef strcat -#endif - -#ifdef strncat - #undef strncat -#endif - -// NOTE: I have to include stdio + stdarg first so vsnprintf gets compiled in -#include -#include - -#ifdef _LINUX -#include -#include -#include -#define _getcwd getcwd -#elif _WIN32 -#include -#if !defined( _X360 ) -#define WIN32_LEAN_AND_MEAN -#include -#endif -#endif - -#ifdef _WIN32 -#ifndef CP_UTF8 -#define CP_UTF8 65001 -#endif -#endif -#include "tier0/dbg.h" -#include "tier1/strtools.h" -#include -#include -#include "tier0/basetypes.h" -#include "tier1/utldict.h" -#if defined( _X360 ) -#include "xbox/xbox_win32stubs.h" -#endif -#include "tier0/memdbgon.h" - -void _V_memset (const char* file, int line, void *dest, int fill, int count) -{ - Assert( count >= 0 ); - AssertValidWritePtr( dest, count ); - - memset(dest,fill,count); -} - -void _V_memcpy (const char* file, int line, void *dest, const void *src, int count) -{ - Assert( count >= 0 ); - AssertValidReadPtr( src, count ); - AssertValidWritePtr( dest, count ); - - memcpy( dest, src, count ); -} - -void _V_memmove(const char* file, int line, void *dest, const void *src, int count) -{ - Assert( count >= 0 ); - AssertValidReadPtr( src, count ); - AssertValidWritePtr( dest, count ); - - memmove( dest, src, count ); -} - -int _V_memcmp (const char* file, int line, const void *m1, const void *m2, int count) -{ - Assert( count >= 0 ); - AssertValidReadPtr( m1, count ); - AssertValidReadPtr( m2, count ); - - return memcmp( m1, m2, count ); -} - -int _V_strlen(const char* file, int line, const char *str) -{ - AssertValidStringPtr(str); - return strlen( str ); -} - -void _V_strcpy (const char* file, int line, char *dest, const char *src) -{ - AssertValidWritePtr(dest); - AssertValidStringPtr(src); - - strcpy( dest, src ); -} - -int _V_wcslen(const char* file, int line, const wchar_t *pwch) -{ - return wcslen( pwch ); -} - -char *_V_strrchr(const char* file, int line, const char *s, char c) -{ - AssertValidStringPtr( s ); - int len = V_strlen(s); - s += len; - while (len--) - if (*--s == c) return (char *)s; - return 0; -} - -int _V_strcmp (const char* file, int line, const char *s1, const char *s2) -{ - AssertValidStringPtr( s1 ); - AssertValidStringPtr( s2 ); - - return strcmp( s1, s2 ); -} - -int _V_wcscmp (const char* file, int line, const wchar_t *s1, const wchar_t *s2) -{ - while (1) - { - if (*s1 != *s2) - return -1; // strings not equal - if (!*s1) - return 0; // strings are equal - s1++; - s2++; - } - - return -1; -} - - - -int _V_stricmp(const char* file, int line, const char *s1, const char *s2 ) -{ - AssertValidStringPtr( s1 ); - AssertValidStringPtr( s2 ); - - return stricmp( s1, s2 ); -} - - -char *_V_strstr(const char* file, int line, const char *s1, const char *search ) -{ - AssertValidStringPtr( s1 ); - AssertValidStringPtr( search ); - -#if defined( _X360 ) - return (char *)strstr( (char *)s1, search ); -#else - return (char *)strstr( s1, search ); -#endif -} - -char *_V_strupr (const char* file, int line, char *start) -{ - AssertValidStringPtr( start ); - return strupr( start ); -} - - -char *_V_strlower (const char* file, int line, char *start) -{ - AssertValidStringPtr( start ); - return strlwr(start); -} - -int V_strncmp (const char *s1, const char *s2, int count) -{ - Assert( count >= 0 ); - AssertValidStringPtr( s1, count ); - AssertValidStringPtr( s2, count ); - - while ( count-- > 0 ) - { - if ( *s1 != *s2 ) - return *s1 < *s2 ? -1 : 1; // string different - if ( *s1 == '\0' ) - return 0; // null terminator hit - strings the same - s1++; - s2++; - } - - return 0; // count characters compared the same -} - -char *V_strnlwr(char *s, size_t count) -{ - Assert( count >= 0 ); - AssertValidStringPtr( s, count ); - - char* pRet = s; - if ( !s ) - return s; - - while ( --count >= 0 ) - { - if ( !*s ) - break; - - *s = tolower( *s ); - ++s; - } - - if ( count > 0 ) - { - s[count-1] = 0; - } - - return pRet; -} - - -int V_strncasecmp (const char *s1, const char *s2, int n) -{ - Assert( n >= 0 ); - AssertValidStringPtr( s1 ); - AssertValidStringPtr( s2 ); - - while ( n-- > 0 ) - { - int c1 = *s1++; - int c2 = *s2++; - - if (c1 != c2) - { - if (c1 >= 'a' && c1 <= 'z') - c1 -= ('a' - 'A'); - if (c2 >= 'a' && c2 <= 'z') - c2 -= ('a' - 'A'); - if (c1 != c2) - return c1 < c2 ? -1 : 1; - } - if ( c1 == '\0' ) - return 0; // null terminator hit - strings the same - } - - return 0; // n characters compared the same -} - -int V_strcasecmp( const char *s1, const char *s2 ) -{ - AssertValidStringPtr( s1 ); - AssertValidStringPtr( s2 ); - - return stricmp( s1, s2 ); -} - -int V_strnicmp (const char *s1, const char *s2, int n) -{ - Assert( n >= 0 ); - AssertValidStringPtr(s1); - AssertValidStringPtr(s2); - - return V_strncasecmp( s1, s2, n ); -} - - -const char *StringAfterPrefix( const char *str, const char *prefix ) -{ - AssertValidStringPtr( str ); - AssertValidStringPtr( prefix ); - do - { - if ( !*prefix ) - return str; - } - while ( tolower( *str++ ) == tolower( *prefix++ ) ); - return NULL; -} - -const char *StringAfterPrefixCaseSensitive( const char *str, const char *prefix ) -{ - AssertValidStringPtr( str ); - AssertValidStringPtr( prefix ); - do - { - if ( !*prefix ) - return str; - } - while ( *str++ == *prefix++ ); - return NULL; -} - - -int V_atoi (const char *str) -{ - AssertValidStringPtr( str ); - - int val; - int sign; - int c; - - Assert( str ); - if (*str == '-') - { - sign = -1; - str++; - } - else - sign = 1; - - val = 0; - -// -// check for hex -// - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) - { - str += 2; - while (1) - { - c = *str++; - if (c >= '0' && c <= '9') - val = (val<<4) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val<<4) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val<<4) + c - 'A' + 10; - else - return val*sign; - } - } - -// -// check for character -// - if (str[0] == '\'') - { - return sign * str[1]; - } - -// -// assume decimal -// - while (1) - { - c = *str++; - if (c <'0' || c > '9') - return val*sign; - val = val*10 + c - '0'; - } - - return 0; -} - - -float V_atof (const char *str) -{ - AssertValidStringPtr( str ); - double val; - int sign; - int c; - int decimal, total; - - if (*str == '-') - { - sign = -1; - str++; - } - else - sign = 1; - - val = 0; - -// -// check for hex -// - if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') ) - { - str += 2; - while (1) - { - c = *str++; - if (c >= '0' && c <= '9') - val = (val*16) + c - '0'; - else if (c >= 'a' && c <= 'f') - val = (val*16) + c - 'a' + 10; - else if (c >= 'A' && c <= 'F') - val = (val*16) + c - 'A' + 10; - else - return val*sign; - } - } - -// -// check for character -// - if (str[0] == '\'') - { - return sign * str[1]; - } - -// -// assume decimal -// - decimal = -1; - total = 0; - while (1) - { - c = *str++; - if (c == '.') - { - decimal = total; - continue; - } - if (c <'0' || c > '9') - break; - val = val*10 + c - '0'; - total++; - } - - if (decimal == -1) - return val*sign; - while (total > decimal) - { - val /= 10; - total--; - } - - return val*sign; -} - -//----------------------------------------------------------------------------- -// Normalizes a float string in place. -// -// (removes leading zeros, trailing zeros after the decimal point, and the decimal point itself where possible) -//----------------------------------------------------------------------------- -void V_normalizeFloatString( char* pFloat ) -{ - // If we have a decimal point, remove trailing zeroes: - if( strchr( pFloat,'.' ) ) - { - int len = V_strlen(pFloat); - - while( len > 1 && pFloat[len - 1] == '0' ) - { - pFloat[len - 1] = '\0'; - len--; - } - - if( len > 1 && pFloat[ len - 1 ] == '.' ) - { - pFloat[len - 1] = '\0'; - len--; - } - } - - // TODO: Strip leading zeros - -} - - -//----------------------------------------------------------------------------- -// Finds a string in another string with a case insensitive test -//----------------------------------------------------------------------------- -char const* V_stristr( char const* pStr, char const* pSearch ) -{ - AssertValidStringPtr(pStr); - AssertValidStringPtr(pSearch); - - if (!pStr || !pSearch) - return 0; - - char const* pLetter = pStr; - - // Check the entire string - while (*pLetter != 0) - { - // Skip over non-matches - if (tolower((unsigned char)*pLetter) == tolower((unsigned char)*pSearch)) - { - // Check for match - char const* pMatch = pLetter + 1; - char const* pTest = pSearch + 1; - while (*pTest != 0) - { - // We've run off the end; don't bother. - if (*pMatch == 0) - return 0; - - if (tolower((unsigned char)*pMatch) != tolower((unsigned char)*pTest)) - break; - - ++pMatch; - ++pTest; - } - - // Found a match! - if (*pTest == 0) - return pLetter; - } - - ++pLetter; - } - - return 0; -} - -char* V_stristr( char* pStr, char const* pSearch ) -{ - AssertValidStringPtr( pStr ); - AssertValidStringPtr( pSearch ); - - return (char*)V_stristr( (char const*)pStr, pSearch ); -} - -//----------------------------------------------------------------------------- -// Finds a string in another string with a case insensitive test w/ length validation -//----------------------------------------------------------------------------- -char const* V_strnistr( char const* pStr, char const* pSearch, int n ) -{ - AssertValidStringPtr(pStr); - AssertValidStringPtr(pSearch); - - if (!pStr || !pSearch) - return 0; - - char const* pLetter = pStr; - - // Check the entire string - while (*pLetter != 0) - { - if ( n <= 0 ) - return 0; - - // Skip over non-matches - if (tolower(*pLetter) == tolower(*pSearch)) - { - int n1 = n - 1; - - // Check for match - char const* pMatch = pLetter + 1; - char const* pTest = pSearch + 1; - while (*pTest != 0) - { - if ( n1 <= 0 ) - return 0; - - // We've run off the end; don't bother. - if (*pMatch == 0) - return 0; - - if (tolower(*pMatch) != tolower(*pTest)) - break; - - ++pMatch; - ++pTest; - --n1; - } - - // Found a match! - if (*pTest == 0) - return pLetter; - } - - ++pLetter; - --n; - } - - return 0; -} - -const char* V_strnchr( const char* pStr, char c, int n ) -{ - char const* pLetter = pStr; - char const* pLast = pStr + n; - - // Check the entire string - while ( (pLetter < pLast) && (*pLetter != 0) ) - { - if (*pLetter == c) - return pLetter; - ++pLetter; - } - return NULL; -} - -void V_strncpy( char *pDest, char const *pSrc, int maxLen ) -{ - Assert( maxLen >= 0 ); - AssertValidWritePtr( pDest, maxLen ); - AssertValidStringPtr( pSrc ); - - strncpy( pDest, pSrc, maxLen ); - if ( maxLen > 0 ) - { - pDest[maxLen-1] = 0; - } -} - -void V_wcsncpy( wchar_t *pDest, wchar_t const *pSrc, int maxLenInBytes ) -{ - Assert( maxLenInBytes >= 0 ); - AssertValidWritePtr( pDest, maxLenInBytes ); - AssertValidReadPtr( pSrc ); - - int maxLen = maxLenInBytes / sizeof(wchar_t); - - wcsncpy( pDest, pSrc, maxLen ); - if( maxLen ) - { - pDest[maxLen-1] = 0; - } -} - - - -int V_snwprintf( wchar_t *pDest, int maxLen, const wchar_t *pFormat, ... ) -{ - Assert( maxLen >= 0 ); - AssertValidWritePtr( pDest, maxLen ); - AssertValidReadPtr( pFormat ); - - va_list marker; - - va_start( marker, pFormat ); -#ifdef _WIN32 - int len = _snwprintf( pDest, maxLen, pFormat, marker ); -#elif _LINUX - int len = swprintf( pDest, maxLen, pFormat, marker ); -#else -#error "define vsnwprintf type." -#endif - va_end( marker ); - - // Len < 0 represents an overflow - if( len < 0 ) - { - len = maxLen; - pDest[maxLen-1] = 0; - } - - return len; -} - - -int V_snprintf( char *pDest, int maxLen, char const *pFormat, ... ) -{ - Assert( maxLen >= 0 ); - AssertValidWritePtr( pDest, maxLen ); - AssertValidStringPtr( pFormat ); - - va_list marker; - - va_start( marker, pFormat ); -#ifdef _WIN32 - int len = _vsnprintf( pDest, maxLen, pFormat, marker ); -#elif _LINUX - int len = vsnprintf( pDest, maxLen, pFormat, marker ); -#else - #error "define vsnprintf type." -#endif - va_end( marker ); - - // Len < 0 represents an overflow - if( len < 0 ) - { - len = maxLen; - pDest[maxLen-1] = 0; - } - - return len; -} - - -int V_vsnprintf( char *pDest, int maxLen, char const *pFormat, va_list params ) -{ - Assert( maxLen > 0 ); - AssertValidWritePtr( pDest, maxLen ); - AssertValidStringPtr( pFormat ); - - int len = _vsnprintf( pDest, maxLen, pFormat, params ); - - if( len < 0 ) - { - len = maxLen; - pDest[maxLen-1] = 0; - } - - return len; -} - - - -//----------------------------------------------------------------------------- -// Purpose: If COPY_ALL_CHARACTERS == max_chars_to_copy then we try to add the whole pSrc to the end of pDest, otherwise -// we copy only as many characters as are specified in max_chars_to_copy (or the # of characters in pSrc if thats's less). -// Input : *pDest - destination buffer -// *pSrc - string to append -// destBufferSize - sizeof the buffer pointed to by pDest -// max_chars_to_copy - COPY_ALL_CHARACTERS in pSrc or max # to copy -// Output : char * the copied buffer -//----------------------------------------------------------------------------- -char *V_strncat(char *pDest, const char *pSrc, size_t destBufferSize, int max_chars_to_copy ) -{ - size_t charstocopy = (size_t)0; - - Assert( destBufferSize >= 0 ); - AssertValidStringPtr( pDest); - AssertValidStringPtr( pSrc ); - - size_t len = strlen(pDest); - size_t srclen = strlen( pSrc ); - if ( max_chars_to_copy <= COPY_ALL_CHARACTERS ) - { - charstocopy = srclen; - } - else - { - charstocopy = (size_t)min( max_chars_to_copy, (int)srclen ); - } - - if ( len + charstocopy >= destBufferSize ) - { - charstocopy = destBufferSize - len - 1; - } - - if ( !charstocopy ) - { - return pDest; - } - - char *pOut = strncat( pDest, pSrc, charstocopy ); - pOut[destBufferSize-1] = 0; - return pOut; -} - - - -//----------------------------------------------------------------------------- -// Purpose: Converts value into x.xx MB/ x.xx KB, x.xx bytes format, including commas -// Input : value - -// 2 - -// false - -// Output : char -//----------------------------------------------------------------------------- -#define NUM_PRETIFYMEM_BUFFERS 8 -char *V_pretifymem( float value, int digitsafterdecimal /*= 2*/, bool usebinaryonek /*= false*/ ) -{ - static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ]; - static int current; - - float onekb = usebinaryonek ? 1024.0f : 1000.0f; - float onemb = onekb * onekb; - - char *out = output[ current ]; - current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 ); - - char suffix[ 8 ]; - - // First figure out which bin to use - if ( value > onemb ) - { - value /= onemb; - V_snprintf( suffix, sizeof( suffix ), " MB" ); - } - else if ( value > onekb ) - { - value /= onekb; - V_snprintf( suffix, sizeof( suffix ), " KB" ); - } - else - { - V_snprintf( suffix, sizeof( suffix ), " bytes" ); - } - - char val[ 32 ]; - - // Clamp to >= 0 - digitsafterdecimal = max( digitsafterdecimal, 0 ); - - // If it's basically integral, don't do any decimals - if ( FloatMakePositive( value - (int)value ) < 0.00001 ) - { - V_snprintf( val, sizeof( val ), "%i%s", (int)value, suffix ); - } - else - { - char fmt[ 32 ]; - - // Otherwise, create a format string for the decimals - V_snprintf( fmt, sizeof( fmt ), "%%.%if%s", digitsafterdecimal, suffix ); - V_snprintf( val, sizeof( val ), fmt, value ); - } - - // Copy from in to out - char *i = val; - char *o = out; - - // Search for decimal or if it was integral, find the space after the raw number - char *dot = strstr( i, "." ); - if ( !dot ) - { - dot = strstr( i, " " ); - } - - // Compute position of dot - int pos = dot - i; - // Don't put a comma if it's <= 3 long - pos -= 3; - - while ( *i ) - { - // If pos is still valid then insert a comma every third digit, except if we would be - // putting one in the first spot - if ( pos >= 0 && !( pos % 3 ) ) - { - // Never in first spot - if ( o != out ) - { - *o++ = ','; - } - } - - // Count down comma position - pos--; - - // Copy rest of data as normal - *o++ = *i++; - } - - // Terminate - *o = 0; - - return out; -} - -//----------------------------------------------------------------------------- -// Purpose: Returns a string representation of an integer with commas -// separating the 1000s (ie, 37,426,421) -// Input : value - Value to convert -// Output : Pointer to a static buffer containing the output -//----------------------------------------------------------------------------- -#define NUM_PRETIFYNUM_BUFFERS 8 -char *V_pretifynum( int64 value ) -{ - static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ]; - static int current; - - char *out = output[ current ]; - current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 ); - - *out = 0; - - // Render the leading -, if necessary - if ( value < 0 ) - { - char *pchRender = out + V_strlen( out ); - V_snprintf( pchRender, 32, "-" ); - value = -value; - } - - // Render quadrillions - if ( value >= 1000000000000 ) - { - char *pchRender = out + V_strlen( out ); - V_snprintf( pchRender, 32, "%d,", value / 1000000000000 ); - } - - // Render trillions - if ( value >= 1000000000000 ) - { - char *pchRender = out + V_strlen( out ); - V_snprintf( pchRender, 32, "%d,", value / 1000000000000 ); - } - - // Render billions - if ( value >= 1000000000 ) - { - char *pchRender = out + V_strlen( out ); - V_snprintf( pchRender, 32, "%d,", value / 1000000000 ); - } - - // Render millions - if ( value >= 1000000 ) - { - char *pchRender = out + V_strlen( out ); - if ( value >= 1000000000 ) - V_snprintf( pchRender, 32, "%03d,", ( value / 1000000 ) % 1000 ); - else - V_snprintf( pchRender, 32, "%d,", ( value / 1000000 ) % 1000 ); - } - - // Render thousands - if ( value >= 1000 ) - { - char *pchRender = out + V_strlen( out ); - if ( value >= 1000000 ) - V_snprintf( pchRender, 32, "%03d,", ( value / 1000 ) % 1000 ); - else - V_snprintf( pchRender, 32, "%d,", ( value / 1000 ) % 1000 ); - } - - // Render units - char *pchRender = out + V_strlen( out ); - if ( value > 1000 ) - V_snprintf( pchRender, 32, "%03d", value % 1000 ); - else - V_snprintf( pchRender, 32, "%d", value % 1000 ); - - return out; -} - - -//----------------------------------------------------------------------------- -// Purpose: Converts a UTF8 string into a unicode string -//----------------------------------------------------------------------------- -int V_UTF8ToUnicode( const char *pUTF8, wchar_t *pwchDest, int cubDestSizeInBytes ) -{ - AssertValidStringPtr(pUTF8); - AssertValidWritePtr(pwchDest); - - pwchDest[0] = 0; -#ifdef _WIN32 - int cchResult = MultiByteToWideChar( CP_UTF8, 0, pUTF8, -1, pwchDest, cubDestSizeInBytes / sizeof(wchar_t) ); -#elif _LINUX - int cchResult = mbstowcs( pwchDest, pUTF8, cubDestSizeInBytes / sizeof(wchar_t) ); -#endif - pwchDest[(cubDestSizeInBytes / sizeof(wchar_t)) - 1] = 0; - return cchResult; -} - -//----------------------------------------------------------------------------- -// Purpose: Converts a unicode string into a UTF8 (standard) string -//----------------------------------------------------------------------------- -int V_UnicodeToUTF8( const wchar_t *pUnicode, char *pUTF8, int cubDestSizeInBytes ) -{ - AssertValidStringPtr(pUTF8, cubDestSizeInBytes); - AssertValidReadPtr(pUnicode); - - pUTF8[0] = 0; -#ifdef _WIN32 - int cchResult = WideCharToMultiByte( CP_UTF8, 0, pUnicode, -1, pUTF8, cubDestSizeInBytes, NULL, NULL ); -#elif _LINUX - int cchResult = wcstombs( pUTF8, pUnicode, cubDestSizeInBytes ); -#endif - pUTF8[cubDestSizeInBytes - 1] = 0; - return cchResult; -} - -//----------------------------------------------------------------------------- -// Purpose: Returns the 4 bit nibble for a hex character -// Input : c - -// Output : unsigned char -//----------------------------------------------------------------------------- -static unsigned char V_nibble( char c ) -{ - if ( ( c >= '0' ) && - ( c <= '9' ) ) - { - return (unsigned char)(c - '0'); - } - - if ( ( c >= 'A' ) && - ( c <= 'F' ) ) - { - return (unsigned char)(c - 'A' + 0x0a); - } - - if ( ( c >= 'a' ) && - ( c <= 'f' ) ) - { - return (unsigned char)(c - 'a' + 0x0a); - } - - return '0'; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *in - -// numchars - -// *out - -// maxoutputbytes - -//----------------------------------------------------------------------------- -void V_hextobinary( char const *in, int numchars, byte *out, int maxoutputbytes ) -{ - int len = V_strlen( in ); - numchars = min( len, numchars ); - // Make sure it's even - numchars = ( numchars ) & ~0x1; - - // Must be an even # of input characters (two chars per output byte) - Assert( numchars >= 2 ); - - memset( out, 0x00, maxoutputbytes ); - - byte *p; - int i; - - p = out; - for ( i = 0; - ( i < numchars ) && ( ( p - out ) < maxoutputbytes ); - i+=2, p++ ) - { - *p = ( V_nibble( in[i] ) << 4 ) | V_nibble( in[i+1] ); - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *in - -// inputbytes - -// *out - -// outsize - -//----------------------------------------------------------------------------- -void V_binarytohex( const byte *in, int inputbytes, char *out, int outsize ) -{ - Assert( outsize >= 1 ); - char doublet[10]; - int i; - - out[0]=0; - - for ( i = 0; i < inputbytes; i++ ) - { - unsigned char c = in[i]; - V_snprintf( doublet, sizeof( doublet ), "%02x", c ); - V_strncat( out, doublet, outsize, COPY_ALL_CHARACTERS ); - } -} - -#if defined( _WIN32 ) || defined( WIN32 ) -#define PATHSEPARATOR(c) ((c) == '\\' || (c) == '/') -#else //_WIN32 -#define PATHSEPARATOR(c) ((c) == '/') -#endif //_WIN32 - - -//----------------------------------------------------------------------------- -// Purpose: Extracts the base name of a file (no path, no extension, assumes '/' or '\' as path separator) -// Input : *in - -// *out - -// maxlen - -//----------------------------------------------------------------------------- -void V_FileBase( const char *in, char *out, int maxlen ) -{ - Assert( maxlen >= 1 ); - Assert( in ); - Assert( out ); - - if ( !in || !in[ 0 ] ) - { - *out = 0; - return; - } - - int len, start, end; - - len = V_strlen( in ); - - // scan backward for '.' - end = len - 1; - while ( end&& in[end] != '.' && !PATHSEPARATOR( in[end] ) ) - { - end--; - } - - if ( in[end] != '.' ) // no '.', copy to end - { - end = len-1; - } - else - { - end--; // Found ',', copy to left of '.' - } - - // Scan backward for '/' - start = len-1; - while ( start >= 0 && !PATHSEPARATOR( in[start] ) ) - { - start--; - } - - if ( start < 0 || !PATHSEPARATOR( in[start] ) ) - { - start = 0; - } - else - { - start++; - } - - // Length of new sting - len = end - start + 1; - - int maxcopy = min( len + 1, maxlen ); - - // Copy partial string - V_strncpy( out, &in[start], maxcopy ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *ppath - -//----------------------------------------------------------------------------- -void V_StripTrailingSlash( char *ppath ) -{ - Assert( ppath ); - - int len = V_strlen( ppath ); - if ( len > 0 ) - { - if ( PATHSEPARATOR( ppath[ len - 1 ] ) ) - { - ppath[ len - 1 ] = 0; - } - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *in - -// *out - -// outSize - -//----------------------------------------------------------------------------- -void V_StripExtension( const char *in, char *out, int outSize ) -{ - // Find the last dot. If it's followed by a dot or a slash, then it's part of a - // directory specifier like ../../somedir/./blah. - - // scan backward for '.' - int end = V_strlen( in ) - 1; - while ( end > 0 && in[end] != '.' && !PATHSEPARATOR( in[end] ) ) - { - --end; - } - - if (end > 0 && !PATHSEPARATOR( in[end] ) && end < outSize) - { - int nChars = min( end, outSize-1 ); - if ( out != in ) - { - memcpy( out, in, nChars ); - } - out[nChars] = 0; - } - else - { - // nothing found - if ( out != in ) - { - V_strncpy( out, in, outSize ); - } - } -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *path - -// *extension - -// pathStringLength - -//----------------------------------------------------------------------------- -void V_DefaultExtension( char *path, const char *extension, int pathStringLength ) -{ - Assert( path ); - Assert( pathStringLength >= 1 ); - Assert( extension ); - Assert( extension[0] == '.' ); - - char *src; - - // if path doesn't have a .EXT, append extension - // (extension should include the .) - src = path + V_strlen(path) - 1; - - while ( !PATHSEPARATOR( *src ) && ( src > path ) ) - { - if (*src == '.') - { - // it has an extension - return; - } - src--; - } - - // Concatenate the desired extension - V_strncat( path, extension, pathStringLength, COPY_ALL_CHARACTERS ); -} - -//----------------------------------------------------------------------------- -// Purpose: Force extension... -// Input : *path - -// *extension - -// pathStringLength - -//----------------------------------------------------------------------------- -void V_SetExtension( char *path, const char *extension, int pathStringLength ) -{ - V_StripExtension( path, path, pathStringLength ); - V_DefaultExtension( path, extension, pathStringLength ); -} - -//----------------------------------------------------------------------------- -// Purpose: Remove final filename from string -// Input : *path - -// Output : void V_StripFilename -//----------------------------------------------------------------------------- -void V_StripFilename (char *path) -{ - int length; - - length = V_strlen( path )-1; - if ( length <= 0 ) - return; - - while ( length > 0 && - !PATHSEPARATOR( path[length] ) ) - { - length--; - } - - path[ length ] = 0; -} - -#ifdef _WIN32 -#define CORRECT_PATH_SEPARATOR '\\' -#define INCORRECT_PATH_SEPARATOR '/' -#elif _LINUX -#define CORRECT_PATH_SEPARATOR '/' -#define INCORRECT_PATH_SEPARATOR '\\' -#endif - -//----------------------------------------------------------------------------- -// Purpose: Changes all '/' or '\' characters into separator -// Input : *pname - -// separator - -//----------------------------------------------------------------------------- -void V_FixSlashes( char *pname, char separator /* = CORRECT_PATH_SEPARATOR */ ) -{ - while ( *pname ) - { - if ( *pname == INCORRECT_PATH_SEPARATOR || *pname == CORRECT_PATH_SEPARATOR ) - { - *pname = separator; - } - pname++; - } -} - - -//----------------------------------------------------------------------------- -// Purpose: This function fixes cases of filenames like materials\\blah.vmt or somepath\otherpath\\ and removes the extra double slash. -//----------------------------------------------------------------------------- -void V_FixDoubleSlashes( char *pStr ) -{ - int len = V_strlen( pStr ); - - for ( int i=1; i < len-1; i++ ) - { - if ( (pStr[i] == '/' || pStr[i] == '\\') && (pStr[i+1] == '/' || pStr[i+1] == '\\') ) - { - // This means there's a double slash somewhere past the start of the filename. That - // can happen in Hammer if they use a material in the root directory. You'll get a filename - // that looks like 'materials\\blah.vmt' - V_memmove( &pStr[i], &pStr[i+1], len - i ); - --len; - } - } -} - -//----------------------------------------------------------------------------- -// Purpose: Strip off the last directory from dirName -// Input : *dirName - -// maxlen - -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool V_StripLastDir( char *dirName, int maxlen ) -{ - if( dirName[0] == 0 || - !V_stricmp( dirName, "./" ) || - !V_stricmp( dirName, ".\\" ) ) - return false; - - int len = V_strlen( dirName ); - - Assert( len < maxlen ); - - // skip trailing slash - if ( PATHSEPARATOR( dirName[len-1] ) ) - { - len--; - } - - while ( len > 0 ) - { - if ( PATHSEPARATOR( dirName[len-1] ) ) - { - dirName[len] = 0; - V_FixSlashes( dirName, CORRECT_PATH_SEPARATOR ); - return true; - } - len--; - } - - // Allow it to return an empty string and true. This can happen if something like "tf2/" is passed in. - // The correct behavior is to strip off the last directory ("tf2") and return true. - if( len == 0 ) - { - V_snprintf( dirName, maxlen, ".%c", CORRECT_PATH_SEPARATOR ); - return true; - } - - return true; -} - - -//----------------------------------------------------------------------------- -// Purpose: Returns a pointer to the beginning of the unqualified file name -// (no path information) -// Input: in - file name (may be unqualified, relative or absolute path) -// Output: pointer to unqualified file name -//----------------------------------------------------------------------------- -const char * V_UnqualifiedFileName( const char * in ) -{ - // back up until the character after the first path separator we find, - // or the beginning of the string - const char * out = in + strlen( in ) - 1; - while ( ( out > in ) && ( !PATHSEPARATOR( *( out-1 ) ) ) ) - out--; - return out; -} - - -//----------------------------------------------------------------------------- -// Purpose: Composes a path and filename together, inserting a path separator -// if need be -// Input: path - path to use -// filename - filename to use -// dest - buffer to compose result in -// destSize - size of destination buffer -//----------------------------------------------------------------------------- -void V_ComposeFileName( const char *path, const char *filename, char *dest, int destSize ) -{ - V_strncpy( dest, path, destSize ); - V_AppendSlash( dest, destSize ); - V_strncat( dest, filename, destSize, COPY_ALL_CHARACTERS ); - V_FixSlashes( dest ); -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *path - -// *dest - -// destSize - -// Output : void V_ExtractFilePath -//----------------------------------------------------------------------------- -bool V_ExtractFilePath (const char *path, char *dest, int destSize ) -{ - Assert( destSize >= 1 ); - if ( destSize < 1 ) - { - return false; - } - - // Last char - int len = V_strlen(path); - const char *src = path + (len ? len-1 : 0); - - // back up until a \ or the start - while ( src != path && !PATHSEPARATOR( *(src-1) ) ) - { - src--; - } - - int copysize = min( src - path, destSize - 1 ); - memcpy( dest, path, copysize ); - dest[copysize] = 0; - - return copysize != 0 ? true : false; -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *path - -// *dest - -// destSize - -// Output : void V_ExtractFileExtension -//----------------------------------------------------------------------------- -void V_ExtractFileExtension( const char *path, char *dest, int destSize ) -{ - *dest = NULL; - const char * extension = V_GetFileExtension( path ); - if ( NULL != extension ) - V_strncpy( dest, extension, destSize ); -} - - -//----------------------------------------------------------------------------- -// Purpose: Returns a pointer to the file extension within a file name string -// Input: in - file name -// Output: pointer to beginning of extension (after the "."), or NULL -// if there is no extension -//----------------------------------------------------------------------------- -const char * V_GetFileExtension( const char * path ) -{ - const char *src; - - src = path + strlen(path) - 1; - -// -// back up until a . or the start -// - while (src != path && *(src-1) != '.' ) - src--; - - // check to see if the '.' is part of a pathname - if (src == path || PATHSEPARATOR( *src ) ) - { - return NULL; // no extension - } - - return src; -} - -bool V_RemoveDotSlashes( char *pFilename, char separator ) -{ - // Remove '//' or '\\' - char *pIn = pFilename; - char *pOut = pFilename; - bool bPrevPathSep = false; - while ( *pIn ) - { - bool bIsPathSep = PATHSEPARATOR( *pIn ); - if ( !bIsPathSep || !bPrevPathSep ) - { - *pOut++ = *pIn; - } - bPrevPathSep = bIsPathSep; - ++pIn; - } - *pOut = 0; - - // Get rid of "./"'s - pIn = pFilename; - pOut = pFilename; - while ( *pIn ) - { - // The logic on the second line is preventing it from screwing up "../" - if ( pIn[0] == '.' && PATHSEPARATOR( pIn[1] ) && - (pIn == pFilename || pIn[-1] != '.') ) - { - pIn += 2; - } - else - { - *pOut = *pIn; - ++pIn; - ++pOut; - } - } - *pOut = 0; - - // Get rid of a trailing "/." (needless). - int len = strlen( pFilename ); - if ( len > 2 && pFilename[len-1] == '.' && PATHSEPARATOR( pFilename[len-2] ) ) - { - pFilename[len-2] = 0; - } - - // Each time we encounter a "..", back up until we've read the previous directory name, - // then get rid of it. - pIn = pFilename; - while ( *pIn ) - { - if ( pIn[0] == '.' && - pIn[1] == '.' && - (pIn == pFilename || PATHSEPARATOR(pIn[-1])) && // Preceding character must be a slash. - (pIn[2] == 0 || PATHSEPARATOR(pIn[2])) ) // Following character must be a slash or the end of the string. - { - char *pEndOfDots = pIn + 2; - char *pStart = pIn - 2; - - // Ok, now scan back for the path separator that starts the preceding directory. - while ( 1 ) - { - if ( pStart < pFilename ) - return false; - - if ( PATHSEPARATOR( *pStart ) ) - break; - - --pStart; - } - - // Now slide the string down to get rid of the previous directory and the ".." - memmove( pStart, pEndOfDots, strlen( pEndOfDots ) + 1 ); - - // Start over. - pIn = pFilename; - } - else - { - ++pIn; - } - } - - V_FixSlashes( pFilename, separator ); - return true; -} - - -void V_AppendSlash( char *pStr, int strSize ) -{ - int len = V_strlen( pStr ); - if ( len > 0 && !PATHSEPARATOR(pStr[len-1]) ) - { - if ( len+1 >= strSize ) - Error( "V_AppendSlash: ran out of space on %s.", pStr ); - - pStr[len] = CORRECT_PATH_SEPARATOR; - pStr[len+1] = 0; - } -} - - -void V_MakeAbsolutePath( char *pOut, int outLen, const char *pPath, const char *pStartingDir ) -{ - if ( V_IsAbsolutePath( pPath ) ) - { - // pPath is not relative.. just copy it. - V_strncpy( pOut, pPath, outLen ); - } - else - { - // Make sure the starting directory is absolute.. - if ( pStartingDir && V_IsAbsolutePath( pStartingDir ) ) - { - V_strncpy( pOut, pStartingDir, outLen ); - } - else - { - if ( !_getcwd( pOut, outLen ) ) - Error( "V_MakeAbsolutePath: _getcwd failed." ); - - if ( pStartingDir ) - { - V_AppendSlash( pOut, outLen ); - V_strncat( pOut, pStartingDir, outLen, COPY_ALL_CHARACTERS ); - } - } - - // Concatenate the paths. - V_AppendSlash( pOut, outLen ); - V_strncat( pOut, pPath, outLen, COPY_ALL_CHARACTERS ); - } - - if ( !V_RemoveDotSlashes( pOut ) ) - Error( "V_MakeAbsolutePath: tried to \"..\" past the root." ); - - V_FixSlashes( pOut ); -} - - -//----------------------------------------------------------------------------- -// Makes a relative path -//----------------------------------------------------------------------------- -bool V_MakeRelativePath( const char *pFullPath, const char *pDirectory, char *pRelativePath, int nBufLen ) -{ - pRelativePath[0] = 0; - - const char *pPath = pFullPath; - const char *pDir = pDirectory; - - // Strip out common parts of the path - const char *pLastCommonPath = NULL; - const char *pLastCommonDir = NULL; - while ( *pPath && ( tolower( *pPath ) == tolower( *pDir ) || - ( PATHSEPARATOR( *pPath ) && ( PATHSEPARATOR( *pDir ) || (*pDir == 0) ) ) ) ) - { - if ( PATHSEPARATOR( *pPath ) ) - { - pLastCommonPath = pPath + 1; - pLastCommonDir = pDir + 1; - } - if ( *pDir == 0 ) - { - --pLastCommonDir; - break; - } - ++pDir; ++pPath; - } - - // Nothing in common - if ( !pLastCommonPath ) - return false; - - // For each path separator remaining in the dir, need a ../ - int nOutLen = 0; - bool bLastCharWasSeparator = true; - for ( ; *pLastCommonDir; ++pLastCommonDir ) - { - if ( PATHSEPARATOR( *pLastCommonDir ) ) - { - pRelativePath[nOutLen++] = '.'; - pRelativePath[nOutLen++] = '.'; - pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR; - bLastCharWasSeparator = true; - } - else - { - bLastCharWasSeparator = false; - } - } - - // Deal with relative paths not specified with a trailing slash - if ( !bLastCharWasSeparator ) - { - pRelativePath[nOutLen++] = '.'; - pRelativePath[nOutLen++] = '.'; - pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR; - } - - // Copy the remaining part of the relative path over, fixing the path separators - for ( ; *pLastCommonPath; ++pLastCommonPath ) - { - if ( PATHSEPARATOR( *pLastCommonPath ) ) - { - pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR; - } - else - { - pRelativePath[nOutLen++] = *pLastCommonPath; - } - - // Check for overflow - if ( nOutLen == nBufLen - 1 ) - break; - } - - pRelativePath[nOutLen] = 0; - return true; -} - - -//----------------------------------------------------------------------------- -// small helper function shared by lots of modules -//----------------------------------------------------------------------------- -bool V_IsAbsolutePath( const char *pStr ) -{ - bool bIsAbsolute = ( pStr[0] && pStr[1] == ':' ) || pStr[0] == '/' || pStr[0] == '\\'; - if ( IsX360() && !bIsAbsolute ) - { - bIsAbsolute = ( V_stristr( pStr, ":" ) != NULL ); - } - return bIsAbsolute; -} - - -// Copies at most nCharsToCopy bytes from pIn into pOut. -// Returns false if it would have overflowed pOut's buffer. -static bool CopyToMaxChars( char *pOut, int outSize, const char *pIn, int nCharsToCopy ) -{ - if ( outSize == 0 ) - return false; - - int iOut = 0; - while ( *pIn && nCharsToCopy > 0 ) - { - if ( iOut == (outSize-1) ) - { - pOut[iOut] = 0; - return false; - } - pOut[iOut] = *pIn; - ++iOut; - ++pIn; - --nCharsToCopy; - } - - pOut[iOut] = 0; - return true; -} - - -//----------------------------------------------------------------------------- -// Fixes up a file name, removing dot slashes, fixing slashes, converting to lowercase, etc. -//----------------------------------------------------------------------------- -void V_FixupPathName( char *pOut, size_t nOutLen, const char *pPath ) -{ - V_strncpy( pOut, pPath, nOutLen ); - V_FixSlashes( pOut ); - V_RemoveDotSlashes( pOut ); - V_FixDoubleSlashes( pOut ); - V_strlower( pOut ); -} - - -// Returns true if it completed successfully. -// If it would overflow pOut, it fills as much as it can and returns false. -bool V_StrSubst( - const char *pIn, - const char *pMatch, - const char *pReplaceWith, - char *pOut, - int outLen, - bool bCaseSensitive - ) -{ - int replaceFromLen = strlen( pMatch ); - int replaceToLen = strlen( pReplaceWith ); - - const char *pInStart = pIn; - char *pOutPos = pOut; - pOutPos[0] = 0; - - while ( 1 ) - { - int nRemainingOut = outLen - (pOutPos - pOut); - - const char *pTestPos = ( bCaseSensitive ? strstr( pInStart, pMatch ) : V_stristr( pInStart, pMatch ) ); - if ( pTestPos ) - { - // Found an occurence of pMatch. First, copy whatever leads up to the string. - int copyLen = pTestPos - pInStart; - if ( !CopyToMaxChars( pOutPos, nRemainingOut, pInStart, copyLen ) ) - return false; - - // Did we hit the end of the output string? - if ( copyLen > nRemainingOut-1 ) - return false; - - pOutPos += strlen( pOutPos ); - nRemainingOut = outLen - (pOutPos - pOut); - - // Now add the replacement string. - if ( !CopyToMaxChars( pOutPos, nRemainingOut, pReplaceWith, replaceToLen ) ) - return false; - - pInStart += copyLen + replaceFromLen; - pOutPos += replaceToLen; - } - else - { - // We're at the end of pIn. Copy whatever remains and get out. - int copyLen = strlen( pInStart ); - V_strncpy( pOutPos, pInStart, nRemainingOut ); - return ( copyLen <= nRemainingOut-1 ); - } - } -} - - -char* AllocString( const char *pStr, int nMaxChars ) -{ - int allocLen; - if ( nMaxChars == -1 ) - allocLen = strlen( pStr ) + 1; - else - allocLen = min( (int)strlen(pStr), nMaxChars ) + 1; - - char *pOut = new char[allocLen]; - V_strncpy( pOut, pStr, allocLen ); - return pOut; -} - - -void V_SplitString2( const char *pString, const char **pSeparators, int nSeparators, CUtlVector &outStrings ) -{ - outStrings.Purge(); - const char *pCurPos = pString; - while ( 1 ) - { - int iFirstSeparator = -1; - const char *pFirstSeparator = 0; - for ( int i=0; i < nSeparators; i++ ) - { - const char *pTest = V_stristr( pCurPos, pSeparators[i] ); - if ( pTest && (!pFirstSeparator || pTest < pFirstSeparator) ) - { - iFirstSeparator = i; - pFirstSeparator = pTest; - } - } - - if ( pFirstSeparator ) - { - // Split on this separator and continue on. - int separatorLen = strlen( pSeparators[iFirstSeparator] ); - if ( pFirstSeparator > pCurPos ) - { - outStrings.AddToTail( AllocString( pCurPos, pFirstSeparator-pCurPos ) ); - } - - pCurPos = pFirstSeparator + separatorLen; - } - else - { - // Copy the rest of the string - if ( strlen( pCurPos ) ) - { - outStrings.AddToTail( AllocString( pCurPos, -1 ) ); - } - return; - } - } -} - - -void V_SplitString( const char *pString, const char *pSeparator, CUtlVector &outStrings ) -{ - V_SplitString2( pString, &pSeparator, 1, outStrings ); -} - - -bool V_GetCurrentDirectory( char *pOut, int maxLen ) -{ -#ifdef LINUX - return getcwd( pOut, maxLen ) == pOut; -#else - return _getcwd( pOut, maxLen ) == pOut; -#endif -} - - -bool V_SetCurrentDirectory( const char *pDirName ) -{ -#ifdef LINUX - return chdir( pDirName ) == 0; -#else - return _chdir( pDirName ) == 0; -#endif -} - - -// This function takes a slice out of pStr and stores it in pOut. -// It follows the Python slice convention: -// Negative numbers wrap around the string (-1 references the last character). -// Numbers are clamped to the end of the string. -void V_StrSlice( const char *pStr, int firstChar, int lastCharNonInclusive, char *pOut, int outSize ) -{ - if ( outSize == 0 ) - return; - - int length = strlen( pStr ); - - // Fixup the string indices. - if ( firstChar < 0 ) - { - firstChar = length - (-firstChar % length); - } - else if ( firstChar >= length ) - { - pOut[0] = 0; - return; - } - - if ( lastCharNonInclusive < 0 ) - { - lastCharNonInclusive = length - (-lastCharNonInclusive % length); - } - else if ( lastCharNonInclusive > length ) - { - lastCharNonInclusive %= length; - } - - if ( lastCharNonInclusive <= firstChar ) - { - pOut[0] = 0; - return; - } - - int copyLen = lastCharNonInclusive - firstChar; - if ( copyLen <= (outSize-1) ) - { - memcpy( pOut, &pStr[firstChar], copyLen ); - pOut[copyLen] = 0; - } - else - { - memcpy( pOut, &pStr[firstChar], outSize-1 ); - pOut[outSize-1] = 0; - } -} - - -void V_StrLeft( const char *pStr, int nChars, char *pOut, int outSize ) -{ - if ( nChars == 0 ) - { - if ( outSize != 0 ) - pOut[0] = 0; - - return; - } - - V_StrSlice( pStr, 0, nChars, pOut, outSize ); -} - - -void V_StrRight( const char *pStr, int nChars, char *pOut, int outSize ) -{ - int len = strlen( pStr ); - if ( nChars >= len ) - { - V_strncpy( pOut, pStr, outSize ); - } - else - { - V_StrSlice( pStr, -nChars, strlen( pStr ), pOut, outSize ); - } -} - -//----------------------------------------------------------------------------- -// Convert multibyte to wchar + back -//----------------------------------------------------------------------------- -void V_strtowcs( const char *pString, int nInSize, wchar_t *pWString, int nOutSize ) -{ -#ifdef _WIN32 - if ( !MultiByteToWideChar( CP_UTF8, 0, pString, nInSize, pWString, nOutSize ) ) - { - *pWString = L'\0'; - } -#elif _LINUX - if ( mbstowcs( pWString, pString, nOutSize / sizeof(wchar_t) ) <= 0 ) - { - *pWString = 0; - } -#endif -} - -void V_wcstostr( const wchar_t *pWString, int nInSize, char *pString, int nOutSize ) -{ -#ifdef _WIN32 - if ( !WideCharToMultiByte( CP_UTF8, 0, pWString, nInSize, pString, nOutSize, NULL, NULL ) ) - { - *pString = '\0'; - } -#elif _LINUX - if ( wcstombs( pString, pWString, nOutSize ) <= 0 ) - { - *pString = '\0'; - } -#endif -} - - - -//-------------------------------------------------------------------------------- -// backslashification -//-------------------------------------------------------------------------------- - -static char s_BackSlashMap[]="\tt\nn\rr\"\"\\\\"; - -char *V_AddBackSlashesToSpecialChars( char const *pSrc ) -{ - // first, count how much space we are going to need - int nSpaceNeeded = 0; - for( char const *pScan = pSrc; *pScan; pScan++ ) - { - nSpaceNeeded++; - for(char const *pCharSet=s_BackSlashMap; *pCharSet; pCharSet += 2 ) - { - if ( *pCharSet == *pScan ) - nSpaceNeeded++; // we need to store a bakslash - } - } - char *pRet = new char[ nSpaceNeeded + 1 ]; // +1 for null - char *pOut = pRet; - - for( char const *pScan = pSrc; *pScan; pScan++ ) - { - bool bIsSpecial = false; - for(char const *pCharSet=s_BackSlashMap; *pCharSet; pCharSet += 2 ) - { - if ( *pCharSet == *pScan ) - { - *( pOut++ ) = '\\'; - *( pOut++ ) = pCharSet[1]; - bIsSpecial = true; - break; - } - } - if (! bIsSpecial ) - { - *( pOut++ ) = *pScan; - } - } - *( pOut++ ) = 0; - return pRet; -} diff --git a/Resources/NetHook/tier1/strtools.h b/Resources/NetHook/tier1/strtools.h deleted file mode 100644 index 986f236c..00000000 --- a/Resources/NetHook/tier1/strtools.h +++ /dev/null @@ -1,462 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -// -//===========================================================================// - -#ifndef TIER1_STRTOOLS_H -#define TIER1_STRTOOLS_H - -#include "tier0/platform.h" - -#ifdef _WIN32 -#pragma once -#elif _LINUX -#include -#include -#endif - -#include -#include - -template< class T, class I > class CUtlMemory; -template< class T, class A > class CUtlVector; - - -//----------------------------------------------------------------------------- -// Portable versions of standard string functions -//----------------------------------------------------------------------------- -void _V_memset ( const char* file, int line, void *dest, int fill, int count ); -void _V_memcpy ( const char* file, int line, void *dest, const void *src, int count ); -void _V_memmove ( const char* file, int line, void *dest, const void *src, int count ); -int _V_memcmp ( const char* file, int line, const void *m1, const void *m2, int count ); -int _V_strlen ( const char* file, int line, const char *str ); -void _V_strcpy ( const char* file, int line, char *dest, const char *src ); -char* _V_strrchr ( const char* file, int line, const char *s, char c ); -int _V_strcmp ( const char* file, int line, const char *s1, const char *s2 ); -int _V_wcscmp ( const char* file, int line, const wchar_t *s1, const wchar_t *s2 ); -int _V_stricmp ( const char* file, int line, const char *s1, const char *s2 ); -char* _V_strstr ( const char* file, int line, const char *s1, const char *search ); -char* _V_strupr ( const char* file, int line, char *start ); -char* _V_strlower ( const char* file, int line, char *start ); -int _V_wcslen ( const char* file, int line, const wchar_t *pwch ); - - -#ifdef _DEBUG - -#define V_memset(dest, fill, count) _V_memset (__FILE__, __LINE__, (dest), (fill), (count)) -#define V_memcpy(dest, src, count) _V_memcpy (__FILE__, __LINE__, (dest), (src), (count)) -#define V_memmove(dest, src, count) _V_memmove (__FILE__, __LINE__, (dest), (src), (count)) -#define V_memcmp(m1, m2, count) _V_memcmp (__FILE__, __LINE__, (m1), (m2), (count)) -#define V_strlen(str) _V_strlen (__FILE__, __LINE__, (str)) -#define V_strcpy(dest, src) _V_strcpy (__FILE__, __LINE__, (dest), (src)) -#define V_strrchr(s, c) _V_strrchr (__FILE__, __LINE__, (s), (c)) -#define V_strcmp(s1, s2) _V_strcmp (__FILE__, __LINE__, (s1), (s2)) -#define V_wcscmp(s1, s2) _V_wcscmp (__FILE__, __LINE__, (s1), (s2)) -#define V_stricmp(s1, s2 ) _V_stricmp (__FILE__, __LINE__, (s1), (s2) ) -#define V_strstr(s1, search ) _V_strstr (__FILE__, __LINE__, (s1), (search) ) -#define V_strupr(start) _V_strupr (__FILE__, __LINE__, (start)) -#define V_strlower(start) _V_strlower (__FILE__, __LINE__, (start)) -#define V_wcslen(pwch) _V_wcslen (__FILE__, __LINE__, (pwch)) - -#else - -#ifdef _LINUX -inline char *strupr( char *start ) -{ - char *str = start; - while( str && *str ) - { - *str = (char)toupper(*str); - str++; - } - return start; -} - -inline char *strlwr( char *start ) -{ - char *str = start; - while( str && *str ) - { - *str = (char)tolower(*str); - str++; - } - return start; -} - -#endif // _LINUX - -inline void V_memset (void *dest, int fill, int count) { memset( dest, fill, count ); } -inline void V_memcpy (void *dest, const void *src, int count) { memcpy( dest, src, count ); } -inline void V_memmove (void *dest, const void *src, int count) { memmove( dest, src, count ); } -inline int V_memcmp (const void *m1, const void *m2, int count){ return memcmp( m1, m2, count ); } -inline int V_strlen (const char *str) { return (int) strlen ( str ); } -inline void V_strcpy (char *dest, const char *src) { strcpy( dest, src ); } -inline int V_wcslen(const wchar_t *pwch) { return (int)wcslen(pwch); } -inline char* V_strrchr (const char *s, char c) { return (char*)strrchr( s, c ); } -inline int V_strcmp (const char *s1, const char *s2) { return strcmp( s1, s2 ); } -inline int V_wcscmp (const wchar_t *s1, const wchar_t *s2) { return wcscmp( s1, s2 ); } -inline int V_stricmp( const char *s1, const char *s2 ) { return stricmp( s1, s2 ); } -inline char* V_strstr( const char *s1, const char *search ) { return (char*)strstr( s1, search ); } -inline char* V_strupr (char *start) { return strupr( start ); } -inline char* V_strlower (char *start) { return strlwr( start ); } - -#endif - -int V_strncmp (const char *s1, const char *s2, int count); -int V_strcasecmp (const char *s1, const char *s2); -int V_strncasecmp (const char *s1, const char *s2, int n); -int V_strnicmp (const char *s1, const char *s2, int n); -int V_atoi (const char *str); -float V_atof (const char *str); -char* V_stristr( char* pStr, const char* pSearch ); -const char* V_stristr( const char* pStr, const char* pSearch ); -const char* V_strnistr( const char* pStr, const char* pSearch, int n ); -const char* V_strnchr( const char* pStr, char c, int n ); - -// returns string immediately following prefix, (ie str+strlen(prefix)) or NULL if prefix not found -const char *StringAfterPrefix ( const char *str, const char *prefix ); -const char *StringAfterPrefixCaseSensitive( const char *str, const char *prefix ); -inline bool StringHasPrefix ( const char *str, const char *prefix ) { return StringAfterPrefix ( str, prefix ) != NULL; } -inline bool StringHasPrefixCaseSensitive( const char *str, const char *prefix ) { return StringAfterPrefixCaseSensitive( str, prefix ) != NULL; } - - -// Normalizes a float string in place. -// (removes leading zeros, trailing zeros after the decimal point, and the decimal point itself where possible) -void V_normalizeFloatString( char* pFloat ); - - - -// These are versions of functions that guarantee NULL termination. -// -// maxLen is the maximum number of bytes in the destination string. -// pDest[maxLen-1] is always NULL terminated if pSrc's length is >= maxLen. -// -// This means the last parameter can usually be a sizeof() of a string. -void V_strncpy( char *pDest, const char *pSrc, int maxLen ); -int V_snprintf( char *pDest, int destLen, const char *pFormat, ... ); -void V_wcsncpy( wchar_t *pDest, wchar_t const *pSrc, int maxLenInBytes ); -int V_snwprintf( wchar_t *pDest, int destLen, const wchar_t *pFormat, ... ); - -#define COPY_ALL_CHARACTERS -1 -char *V_strncat(char *, const char *, size_t destBufferSize, int max_chars_to_copy=COPY_ALL_CHARACTERS ); -char *V_strnlwr(char *, size_t); - - -// UNDONE: Find a non-compiler-specific way to do this -#ifdef _WIN32 -#ifndef _VA_LIST_DEFINED - -#ifdef _M_ALPHA - -struct va_list -{ - char *a0; /* pointer to first homed integer argument */ - int offset; /* byte offset of next parameter */ -}; - -#else // !_M_ALPHA - -typedef char * va_list; - -#endif // !_M_ALPHA - -#define _VA_LIST_DEFINED - -#endif // _VA_LIST_DEFINED - -#elif _LINUX -#include -#endif - -#ifdef _WIN32 -#define CORRECT_PATH_SEPARATOR '\\' -#define INCORRECT_PATH_SEPARATOR '/' -#elif _LINUX -#define CORRECT_PATH_SEPARATOR '/' -#define INCORRECT_PATH_SEPARATOR '\\' -#endif - -int V_vsnprintf( char *pDest, int maxLen, const char *pFormat, va_list params ); - -// Prints out a pretified memory counter string value ( e.g., 7,233.27 Mb, 1,298.003 Kb, 127 bytes ) -char *V_pretifymem( float value, int digitsafterdecimal = 2, bool usebinaryonek = false ); - -// Prints out a pretified integer with comma separators (eg, 7,233,270,000) -char *V_pretifynum( int64 value ); - -// conversion functions wchar_t <-> char, returning the number of characters converted -int V_UTF8ToUnicode( const char *pUTF8, wchar_t *pwchDest, int cubDestSizeInBytes ); -int V_UnicodeToUTF8( const wchar_t *pUnicode, char *pUTF8, int cubDestSizeInBytes ); - -// Functions for converting hexidecimal character strings back into binary data etc. -// -// e.g., -// int output; -// V_hextobinary( "ffffffff", 8, &output, sizeof( output ) ); -// would make output == 0xfffffff or -1 -// Similarly, -// char buffer[ 9 ]; -// V_binarytohex( &output, sizeof( output ), buffer, sizeof( buffer ) ); -// would put "ffffffff" into buffer (note null terminator!!!) -void V_hextobinary( char const *in, int numchars, byte *out, int maxoutputbytes ); -void V_binarytohex( const byte *in, int inputbytes, char *out, int outsize ); - -// Tools for working with filenames -// Extracts the base name of a file (no path, no extension, assumes '/' or '\' as path separator) -void V_FileBase( const char *in, char *out,int maxlen ); -// Remove the final characters of ppath if it's '\' or '/'. -void V_StripTrailingSlash( char *ppath ); -// Remove any extension from in and return resulting string in out -void V_StripExtension( const char *in, char *out, int outLen ); -// Make path end with extension if it doesn't already have an extension -void V_DefaultExtension( char *path, const char *extension, int pathStringLength ); -// Strips any current extension from path and ensures that extension is the new extension -void V_SetExtension( char *path, const char *extension, int pathStringLength ); -// Removes any filename from path ( strips back to previous / or \ character ) -void V_StripFilename( char *path ); -// Remove the final directory from the path -bool V_StripLastDir( char *dirName, int maxlen ); -// Returns a pointer to the unqualified file name (no path) of a file name -const char * V_UnqualifiedFileName( const char * in ); -// Given a path and a filename, composes "path\filename", inserting the (OS correct) separator if necessary -void V_ComposeFileName( const char *path, const char *filename, char *dest, int destSize ); - -// Copy out the path except for the stuff after the final pathseparator -bool V_ExtractFilePath( const char *path, char *dest, int destSize ); -// Copy out the file extension into dest -void V_ExtractFileExtension( const char *path, char *dest, int destSize ); - -const char *V_GetFileExtension( const char * path ); - -// This removes "./" and "../" from the pathname. pFilename should be a full pathname. -// Returns false if it tries to ".." past the root directory in the drive (in which case -// it is an invalid path). -bool V_RemoveDotSlashes( char *pFilename, char separator = CORRECT_PATH_SEPARATOR ); - -// If pPath is a relative path, this function makes it into an absolute path -// using the current working directory as the base, or pStartingDir if it's non-NULL. -// Returns false if it runs out of room in the string, or if pPath tries to ".." past the root directory. -void V_MakeAbsolutePath( char *pOut, int outLen, const char *pPath, const char *pStartingDir = NULL ); - -// Creates a relative path given two full paths -// The first is the full path of the file to make a relative path for. -// The second is the full path of the directory to make the first file relative to -// Returns false if they can't be made relative (on separate drives, for example) -bool V_MakeRelativePath( const char *pFullPath, const char *pDirectory, char *pRelativePath, int nBufLen ); - -// Fixes up a file name, removing dot slashes, fixing slashes, converting to lowercase, etc. -void V_FixupPathName( char *pOut, size_t nOutLen, const char *pPath ); - -// Adds a path separator to the end of the string if there isn't one already. Returns false if it would run out of space. -void V_AppendSlash( char *pStr, int strSize ); - -// Returns true if the path is an absolute path. -bool V_IsAbsolutePath( const char *pPath ); - -// Scans pIn and replaces all occurences of pMatch with pReplaceWith. -// Writes the result to pOut. -// Returns true if it completed successfully. -// If it would overflow pOut, it fills as much as it can and returns false. -bool V_StrSubst( const char *pIn, const char *pMatch, const char *pReplaceWith, - char *pOut, int outLen, bool bCaseSensitive=false ); - -// Split the specified string on the specified separator. -// Returns a list of strings separated by pSeparator. -// You are responsible for freeing the contents of outStrings (call outStrings.PurgeAndDeleteElements). -void V_SplitString( const char *pString, const char *pSeparator, CUtlVector > &outStrings ); - -// Just like V_SplitString, but it can use multiple possible separators. -void V_SplitString2( const char *pString, const char **pSeparators, int nSeparators, CUtlVector > &outStrings ); - -// Returns false if the buffer is not large enough to hold the working directory name. -bool V_GetCurrentDirectory( char *pOut, int maxLen ); - -// Set the working directory thus. -bool V_SetCurrentDirectory( const char *pDirName ); - - -// This function takes a slice out of pStr and stores it in pOut. -// It follows the Python slice convention: -// Negative numbers wrap around the string (-1 references the last character). -// Large numbers are clamped to the end of the string. -void V_StrSlice( const char *pStr, int firstChar, int lastCharNonInclusive, char *pOut, int outSize ); - -// Chop off the left nChars of a string. -void V_StrLeft( const char *pStr, int nChars, char *pOut, int outSize ); - -// Chop off the right nChars of a string. -void V_StrRight( const char *pStr, int nChars, char *pOut, int outSize ); - -// change "special" characters to have their c-style backslash sequence. like \n, \r, \t, ", etc. -// returns a pointer to a newly allocated string, which you must delete[] when finished with. -char *V_AddBackSlashesToSpecialChars( char const *pSrc ); - -// Force slashes of either type to be = separator character -void V_FixSlashes( char *pname, char separator = CORRECT_PATH_SEPARATOR ); - -// This function fixes cases of filenames like materials\\blah.vmt or somepath\otherpath\\ and removes the extra double slash. -void V_FixDoubleSlashes( char *pStr ); - -// Convert multibyte to wchar + back -// Specify -1 for nInSize for null-terminated string -void V_strtowcs( const char *pString, int nInSize, wchar_t *pWString, int nOutSize ); -void V_wcstostr( const wchar_t *pWString, int nInSize, char *pString, int nOutSize ); - -// buffer-safe strcat -inline void V_strcat( char *dest, const char *src, int cchDest ) -{ - V_strncat( dest, src, cchDest, COPY_ALL_CHARACTERS ); -} - - -//----------------------------------------------------------------------------- -// generic unique name helper functions -//----------------------------------------------------------------------------- - -// returns startindex if none found, 2 if "prefix" found, and n+1 if "prefixn" found -template < class NameArray > -int V_GenerateUniqueNameIndex( const char *prefix, const NameArray &nameArray, int startindex = 0 ) -{ - if ( prefix == NULL ) - return 0; - - int freeindex = startindex; - - int nNames = nameArray.Count(); - for ( int i = 0; i < nNames; ++i ) - { - const char *pName = nameArray[ i ]; - if ( !pName ) - continue; - - const char *pIndexStr = StringAfterPrefix( pName, prefix ); - if ( pIndexStr ) - { - int index = *pIndexStr ? atoi( pIndexStr ) : 1; - if ( index >= freeindex ) - { - // TODO - check that there isn't more junk after the index in pElementName - freeindex = index + 1; - } - } - } - - return freeindex; -} - -template < class NameArray > -bool V_GenerateUniqueName( char *name, int memsize, const char *prefix, const NameArray &nameArray ) -{ - if ( name == NULL || memsize == 0 ) - return false; - - if ( prefix == NULL ) - { - name[ 0 ] = '\0'; - return false; - } - - int prefixLength = V_strlen( prefix ); - if ( prefixLength + 1 > memsize ) - { - name[ 0 ] = '\0'; - return false; - } - - int i = V_GenerateUniqueNameIndex( prefix, nameArray ); - if ( i <= 0 ) - { - V_strncpy( name, prefix, memsize ); - return true; - } - - int newlen = prefixLength + ( int )log10( ( float )i ) + 1; - if ( newlen + 1 > memsize ) - { - V_strncpy( name, prefix, memsize ); - return false; - } - - V_snprintf( name, memsize, "%s%d", prefix, i ); - return true; -} - - - -// NOTE: This is for backward compatability! -// We need to DLL-export the Q methods in vstdlib but not link to them in other projects -#if !defined( VSTDLIB_BACKWARD_COMPAT ) - -#define Q_memset V_memset -#define Q_memcpy V_memcpy -#define Q_memmove V_memmove -#define Q_memcmp V_memcmp -#define Q_strlen V_strlen -#define Q_strcpy V_strcpy -#define Q_strrchr V_strrchr -#define Q_strcmp V_strcmp -#define Q_wcscmp V_wcscmp -#define Q_stricmp V_stricmp -#define Q_strstr V_strstr -#define Q_strupr V_strupr -#define Q_strlower V_strlower -#define Q_wcslen V_wcslen -#define Q_strncmp V_strncmp -#define Q_strcasecmp V_strcasecmp -#define Q_strncasecmp V_strncasecmp -#define Q_strnicmp V_strnicmp -#define Q_atoi V_atoi -#define Q_atof V_atof -#define Q_stristr V_stristr -#define Q_strnistr V_strnistr -#define Q_strnchr V_strnchr -#define Q_normalizeFloatString V_normalizeFloatString -#define Q_strncpy V_strncpy -#define Q_snprintf V_snprintf -#define Q_wcsncpy V_wcsncpy -#define Q_strncat V_strncat -#define Q_strnlwr V_strnlwr -#define Q_vsnprintf V_vsnprintf -#define Q_pretifymem V_pretifymem -#define Q_pretifynum V_pretifynum -#define Q_UTF8ToUnicode V_UTF8ToUnicode -#define Q_UnicodeToUTF8 V_UnicodeToUTF8 -#define Q_hextobinary V_hextobinary -#define Q_binarytohex V_binarytohex -#define Q_FileBase V_FileBase -#define Q_StripTrailingSlash V_StripTrailingSlash -#define Q_StripExtension V_StripExtension -#define Q_DefaultExtension V_DefaultExtension -#define Q_SetExtension V_SetExtension -#define Q_StripFilename V_StripFilename -#define Q_StripLastDir V_StripLastDir -#define Q_UnqualifiedFileName V_UnqualifiedFileName -#define Q_ComposeFileName V_ComposeFileName -#define Q_ExtractFilePath V_ExtractFilePath -#define Q_ExtractFileExtension V_ExtractFileExtension -#define Q_GetFileExtension V_GetFileExtension -#define Q_RemoveDotSlashes V_RemoveDotSlashes -#define Q_MakeAbsolutePath V_MakeAbsolutePath -#define Q_AppendSlash V_AppendSlash -#define Q_IsAbsolutePath V_IsAbsolutePath -#define Q_StrSubst V_StrSubst -#define Q_SplitString V_SplitString -#define Q_SplitString2 V_SplitString2 -#define Q_StrSlice V_StrSlice -#define Q_StrLeft V_StrLeft -#define Q_StrRight V_StrRight -#define Q_FixSlashes V_FixSlashes -#define Q_strtowcs V_strtowcs -#define Q_wcstostr V_wcstostr -#define Q_strcat V_strcat -#define Q_GenerateUniqueNameIndex V_GenerateUniqueNameIndex -#define Q_GenerateUniqueName V_GenerateUniqueName -#define Q_MakeRelativePath V_MakeRelativePath - -#endif // !defined( VSTDLIB_DLL_EXPORT ) - - -#endif // TIER1_STRTOOLS_H diff --git a/Resources/NetHook/tier1/tier1.cpp b/Resources/NetHook/tier1/tier1.cpp deleted file mode 100644 index 7a20917d..00000000 --- a/Resources/NetHook/tier1/tier1.cpp +++ /dev/null @@ -1,63 +0,0 @@ -//===== Copyright © 2005-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: A higher level link library for general use in the game and tools. -// -//===========================================================================// - -#include -#include "tier0/dbg.h" -#include "vstdlib/iprocessutils.h" -#include "icvar.h" - - -//----------------------------------------------------------------------------- -// These tier1 libraries must be set by any users of this library. -// They can be set by calling ConnectTier1Libraries or InitDefaultFileSystem. -// It is hoped that setting this, and using this library will be the common mechanism for -// allowing link libraries to access tier1 library interfaces -//----------------------------------------------------------------------------- -ICvar *cvar = 0; -ICvar *g_pCVar = 0; -IProcessUtils *g_pProcessUtils = 0; -static bool s_bConnected = false; - -// for utlsortvector.h -#ifndef _WIN32 - void *g_pUtlSortVectorQSortContext = NULL; -#endif - - -//----------------------------------------------------------------------------- -// Call this to connect to all tier 1 libraries. -// It's up to the caller to check the globals it cares about to see if ones are missing -//----------------------------------------------------------------------------- -void ConnectTier1Libraries( CreateInterfaceFn *pFactoryList, int nFactoryCount ) -{ - // Don't connect twice.. - if ( s_bConnected ) - return; - - s_bConnected = true; - - for ( int i = 0; i < nFactoryCount; ++i ) - { - if ( !g_pCVar ) - { - cvar = g_pCVar = ( ICvar * )pFactoryList[i]( CVAR_INTERFACE_VERSION, NULL ); - } - if ( !g_pProcessUtils ) - { - g_pProcessUtils = ( IProcessUtils * )pFactoryList[i]( PROCESS_UTILS_INTERFACE_VERSION, NULL ); - } - } -} - -void DisconnectTier1Libraries() -{ - if ( !s_bConnected ) - return; - - g_pCVar = cvar = 0; - g_pProcessUtils = NULL; - s_bConnected = false; -} diff --git a/Resources/NetHook/tier1/tier1.h b/Resources/NetHook/tier1/tier1.h deleted file mode 100644 index f12c7171..00000000 --- a/Resources/NetHook/tier1/tier1.h +++ /dev/null @@ -1,106 +0,0 @@ -//===== Copyright © 2005-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: A higher level link library for general use in the game and tools. -// -//===========================================================================// - - -#ifndef TIER1_H -#define TIER1_H - -#if defined( _WIN32 ) -#pragma once -#endif - -#include "appframework/IAppSystem.h" -#include "tier1/convar.h" - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -class ICvar; -class IProcessUtils; - - -//----------------------------------------------------------------------------- -// These tier1 libraries must be set by any users of this library. -// They can be set by calling ConnectTier1Libraries. -// It is hoped that setting this, and using this library will be the common mechanism for -// allowing link libraries to access tier1 library interfaces -//----------------------------------------------------------------------------- - -// These are marked DLL_EXPORT for Linux. -DLL_EXPORT ICvar *cvar; -DLL_EXPORT ICvar *g_pCVar; -extern IProcessUtils *g_pProcessUtils; - - -//----------------------------------------------------------------------------- -// Call this to connect to/disconnect from all tier 1 libraries. -// It's up to the caller to check the globals it cares about to see if ones are missing -//----------------------------------------------------------------------------- -void ConnectTier1Libraries( CreateInterfaceFn *pFactoryList, int nFactoryCount ); -void DisconnectTier1Libraries(); - - -//----------------------------------------------------------------------------- -// Helper empty implementation of an IAppSystem for tier2 libraries -//----------------------------------------------------------------------------- -template< class IInterface, int ConVarFlag = 0 > -class CTier1AppSystem : public CTier0AppSystem< IInterface > -{ - typedef CTier0AppSystem< IInterface > BaseClass; - -public: - CTier1AppSystem( bool bIsPrimaryAppSystem = true ) : BaseClass( bIsPrimaryAppSystem ) - { - } - - virtual bool Connect( CreateInterfaceFn factory ) - { - if ( !BaseClass::Connect( factory ) ) - return false; - - if ( IsPrimaryAppSystem() ) - { - ConnectTier1Libraries( &factory, 1 ); - } - return true; - } - - virtual void Disconnect() - { - if ( IsPrimaryAppSystem() ) - { - DisconnectTier1Libraries(); - } - BaseClass::Disconnect(); - } - - virtual InitReturnVal_t Init() - { - InitReturnVal_t nRetVal = BaseClass::Init(); - if ( nRetVal != INIT_OK ) - return nRetVal; - - if ( g_pCVar && IsPrimaryAppSystem() ) - { - ConVar_Register( ConVarFlag ); - } - return INIT_OK; - } - - virtual void Shutdown() - { - if ( g_pCVar && IsPrimaryAppSystem() ) - { - ConVar_Unregister( ); - } - BaseClass::Shutdown( ); - } -}; - - -#endif // TIER1_H - diff --git a/Resources/NetHook/tier1/tokenreader.cpp b/Resources/NetHook/tier1/tokenreader.cpp deleted file mode 100644 index 46d9547c..00000000 --- a/Resources/NetHook/tier1/tokenreader.cpp +++ /dev/null @@ -1,480 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -//===========================================================================// - -#include -#include -#include -#include "tokenreader.h" -#include "tier0/platform.h" -#include "tier1/strtools.h" -#include "tier0/dbg.h" - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -TokenReader::TokenReader(void) -{ - m_szFilename[0] = '\0'; - m_nLine = 1; - m_nErrorCount = 0; - m_bStuffed = false; -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *pszFilename - -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool TokenReader::Open(const char *pszFilename) -{ - open(pszFilename, std::ios::in | std::ios::binary ); - Q_strncpy(m_szFilename, pszFilename, sizeof( m_szFilename ) ); - m_nLine = 1; - m_nErrorCount = 0; - m_bStuffed = false; - return(is_open() != 0); -} - - -//----------------------------------------------------------------------------- -// Purpose: -//----------------------------------------------------------------------------- -void TokenReader::Close() -{ - close(); -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *error - -// Output : const char -//----------------------------------------------------------------------------- -const char *TokenReader::Error(char *error, ...) -{ - static char szErrorBuf[256]; - Q_snprintf(szErrorBuf, sizeof( szErrorBuf ), "File %s, line %d: ", m_szFilename, m_nLine); - Q_strncat(szErrorBuf, error, sizeof( szErrorBuf ), COPY_ALL_CHARACTERS ); - m_nErrorCount++; - return(szErrorBuf); -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : pszStore - -// nSize - -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -trtoken_t TokenReader::GetString(char *pszStore, int nSize) -{ - if (nSize <= 0) - { - return TOKENERROR; - } - - char szBuf[1024]; - - // - // Until we reach the end of this string or run out of room in - // the destination buffer... - // - while (true) - { - // - // Fetch the next batch of text from the file. - // - get(szBuf, sizeof(szBuf), '\"'); - if (eof()) - { - return TOKENEOF; - } - - if (fail()) - { - // Just means nothing was read (empty string probably "") - clear(); - } - - // - // Transfer the text to the destination buffer. - // - char *pszSrc = szBuf; - while ((*pszSrc != '\0') && (nSize > 1)) - { - if (*pszSrc == 0x0d) - { - // - // Newline encountered before closing quote -- unterminated string. - // - *pszStore = '\0'; - return TOKENSTRINGTOOLONG; - } - else if (*pszSrc != '\\') - { - *pszStore = *pszSrc; - pszSrc++; - } - else - { - // - // Backslash sequence - replace with the appropriate character. - // - pszSrc++; - - if (*pszSrc == 'n') - { - *pszStore = '\n'; - } - - pszSrc++; - } - - pszStore++; - nSize--; - } - - if (*pszSrc != '\0') - { - // - // Ran out of room in the destination buffer. Skip to the close-quote, - // terminate the string, and exit. - // - ignore(1024, '\"'); - *pszStore = '\0'; - return TOKENSTRINGTOOLONG; - } - - // - // Check for closing quote. - // - if (peek() == '\"') - { - // - // Eat the close quote and any whitespace. - // - get(); - - bool bCombineStrings = SkipWhiteSpace(); - - // - // Combine consecutive quoted strings if the combine strings character was - // encountered between the two strings. - // - if (bCombineStrings && (peek() == '\"')) - { - // - // Eat the open quote and keep parsing this string. - // - get(); - } - else - { - // - // Done with this string, terminate the string and exit. - // - *pszStore = '\0'; - return STRING; - } - } - } -} - - -//----------------------------------------------------------------------------- -// Purpose: Returns the next token, allocating enough memory to store the token -// plus a terminating NULL. -// Input : pszStore - Pointer to a string that will be allocated. -// Output : Returns the type of token that was read, or TOKENERROR. -//----------------------------------------------------------------------------- -trtoken_t TokenReader::NextTokenDynamic(char **ppszStore) -{ - char szTempBuffer[8192]; - trtoken_t eType = NextToken(szTempBuffer, sizeof(szTempBuffer)); - - int len = Q_strlen(szTempBuffer) + 1; - *ppszStore = new char [len]; - Assert( *ppszStore ); - Q_strncpy(*ppszStore, szTempBuffer, len ); - - return(eType); -} - - -//----------------------------------------------------------------------------- -// Purpose: Returns the next token. -// Input : pszStore - Pointer to a string that will receive the token. -// Output : Returns the type of token that was read, or TOKENERROR. -//----------------------------------------------------------------------------- -trtoken_t TokenReader::NextToken(char *pszStore, int nSize) -{ - char *pStart = pszStore; - - if (!is_open()) - { - return TOKENEOF; - } - - // - // If they stuffed a token, return that token. - // - if (m_bStuffed) - { - m_bStuffed = false; - Q_strncpy( pszStore, m_szStuffed, nSize ); - return m_eStuffed; - } - - SkipWhiteSpace(); - - if (eof()) - { - return TOKENEOF; - } - - if (fail()) - { - return TOKENEOF; - } - - char ch = get(); - - // - // Look for all the valid operators. - // - switch (ch) - { - case '@': - case ',': - case '!': - case '+': - case '&': - case '*': - case '$': - case '.': - case '=': - case ':': - case '[': - case ']': - case '(': - case ')': - case '{': - case '}': - case '\\': - { - pszStore[0] = ch; - pszStore[1] = 0; - return OPERATOR; - } - } - - // - // Look for the start of a quoted string. - // - if (ch == '\"') - { - return GetString(pszStore, nSize); - } - - // - // Integers consist of numbers with an optional leading minus sign. - // - if (isdigit(ch) || (ch == '-')) - { - do - { - if ( (pszStore - pStart + 1) < nSize ) - { - *pszStore = ch; - pszStore++; - } - - ch = get(); - if (ch == '-') - { - return TOKENERROR; - } - } while (isdigit(ch)); - - // - // No identifier characters are allowed contiguous with numbers. - // - if (isalpha(ch) || (ch == '_')) - { - return TOKENERROR; - } - - // - // Put back the non-numeric character for the next call. - // - putback(ch); - *pszStore = '\0'; - return INTEGER; - } - - // - // Identifiers consist of a consecutive string of alphanumeric - // characters and underscores. - // - while ( isalpha(ch) || isdigit(ch) || (ch == '_') ) - { - if ( (pszStore - pStart + 1) < nSize ) - { - *pszStore = ch; - pszStore++; - } - - ch = get(); - } - - // - // Put back the non-identifier character for the next call. - // - putback(ch); - *pszStore = '\0'; - return IDENT; -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : ttype - -// *pszToken - -//----------------------------------------------------------------------------- -void TokenReader::IgnoreTill(trtoken_t ttype, const char *pszToken) -{ - trtoken_t _ttype; - char szBuf[1024]; - - while(1) - { - _ttype = NextToken(szBuf, sizeof(szBuf)); - if(_ttype == TOKENEOF) - return; - if(_ttype == ttype) - { - if(IsToken(pszToken, szBuf)) - { - Stuff(ttype, pszToken); - return; - } - } - } -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : ttype - -// pszToken - -//----------------------------------------------------------------------------- -void TokenReader::Stuff(trtoken_t eType, const char *pszToken) -{ - m_eStuffed = eType; - Q_strncpy(m_szStuffed, pszToken, sizeof( m_szStuffed ) ); - m_bStuffed = true; -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : ttype - -// pszToken - -// Output : Returns true on success, false on failure. -//----------------------------------------------------------------------------- -bool TokenReader::Expecting(trtoken_t ttype, const char *pszToken) -{ - char szBuf[1024]; - if (NextToken(szBuf, sizeof(szBuf)) != ttype || !IsToken(pszToken, szBuf)) - { - return false; - } - return true; -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : pszStore - -// Output : -//----------------------------------------------------------------------------- -trtoken_t TokenReader::PeekTokenType(char *pszStore, int maxlen ) -{ - if (!m_bStuffed) - { - m_eStuffed = NextToken(m_szStuffed, sizeof(m_szStuffed)); - m_bStuffed = true; - } - - if (pszStore) - { - Q_strncpy(pszStore, m_szStuffed, maxlen ); - } - - return(m_eStuffed); -} - - -//----------------------------------------------------------------------------- -// Purpose: Gets the next non-whitespace character from the file. -// Input : ch - Receives the character. -// Output : Returns true if the whitespace contained the combine strings -// character '\', which is used to merge consecutive quoted strings. -//----------------------------------------------------------------------------- -bool TokenReader::SkipWhiteSpace(void) -{ - bool bCombineStrings = false; - - while (true) - { - char ch = get(); - - if ((ch == ' ') || (ch == '\t') || (ch == '\r') || (ch == 0)) - { - continue; - } - - if (ch == '+') - { - bCombineStrings = true; - continue; - } - - if (ch == '\n') - { - m_nLine++; - continue; - } - - if (eof()) - { - return(bCombineStrings); - } - - // - // Check for the start of a comment. - // - if (ch == '/') - { - if (peek() == '/') - { - ignore(1024, '\n'); - m_nLine++; - } - } - else - { - // - // It is a worthy character. Put it back. - // - putback(ch); - return(bCombineStrings); - } - } -} - diff --git a/Resources/NetHook/tier1/tokenreader.h b/Resources/NetHook/tier1/tokenreader.h deleted file mode 100644 index c2a918aa..00000000 --- a/Resources/NetHook/tier1/tokenreader.h +++ /dev/null @@ -1,105 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef TOKENREADER_H -#define TOKENREADER_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/basetypes.h" - -#ifdef _WIN32 -#pragma warning(push, 1) -#pragma warning(disable:4701 4702 4530) -#endif - -#include - -#ifdef _WIN32 -#pragma warning(pop) -#endif - -#include - - -typedef enum -{ - TOKENSTRINGTOOLONG = -4, - TOKENERROR = -3, - TOKENNONE = -2, - TOKENEOF = -1, - OPERATOR, - INTEGER, - STRING, - IDENT -} trtoken_t; - - -#define IsToken(s1, s2) !strcmpi(s1, s2) - -#define MAX_TOKEN 128 + 1 -#define MAX_IDENT 64 + 1 -#define MAX_STRING 128 + 1 - - -class TokenReader : private std::ifstream -{ -public: - - TokenReader(); - - bool Open(const char *pszFilename); - trtoken_t NextToken(char *pszStore, int nSize); - trtoken_t NextTokenDynamic(char **ppszStore); - void Close(); - - void IgnoreTill(trtoken_t ttype, const char *pszToken); - void Stuff(trtoken_t ttype, const char *pszToken); - bool Expecting(trtoken_t ttype, const char *pszToken); - const char *Error(char *error, ...); - trtoken_t PeekTokenType(char* = NULL, int maxlen = 0); - - inline int GetErrorCount(void); - - inline TokenReader(TokenReader const &) - { - // prevent vc7 warning. compiler can't generate a copy constructor since descended from - // std::ifstream - assert(0); - } - inline int operator=(TokenReader const &) - { - // prevent vc7 warning. compiler can't generate an assignment operator since descended from - // std::ifstream - assert(0); - } -private: - - trtoken_t GetString(char *pszStore, int nSize); - bool SkipWhiteSpace(void); - - int m_nLine; - int m_nErrorCount; - - char m_szFilename[128]; - char m_szStuffed[128]; - bool m_bStuffed; - trtoken_t m_eStuffed; -}; - - -//----------------------------------------------------------------------------- -// Purpose: Returns the total number of parsing errors since this file was opened. -//----------------------------------------------------------------------------- -int TokenReader::GetErrorCount(void) -{ - return(m_nErrorCount); -} - - -#endif // TOKENREADER_H diff --git a/Resources/NetHook/tier1/undiff.cpp b/Resources/NetHook/tier1/undiff.cpp deleted file mode 100644 index 17505b27..00000000 --- a/Resources/NetHook/tier1/undiff.cpp +++ /dev/null @@ -1,94 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// UnDiff - Apply difference block -// -//=============================================================================// - -#include "tier0/platform.h" -#include "tier0/dbg.h" -#include "tier1/diff.h" -#include "mathlib/mathlib.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -void ApplyDiffs(uint8 const *OldBlock, uint8 const *DiffList, - int OldSize, int DiffListSize, int &ResultListSize,uint8 *Output,uint32 OutSize) -{ - uint8 const *copy_src=OldBlock; - uint8 const *end_of_diff_list=DiffList+DiffListSize; - uint8 const *obuf=Output; - while(DiffList32767) - copy_ofs|=0xffff0000; - // printf("long cp from %x to %x len=%d\n", copy_src+copy_ofs-OldBlock,Output-obuf,copy_sz); - - memcpy(Output,copy_src+copy_ofs,copy_sz); - Output+=copy_sz; - copy_src=copy_src+copy_ofs+copy_sz; - DiffList+=4; - } - else - { - if (op & 0x80) - { - int copy_sz=op & 0x7f; - int copy_ofs; - if (copy_sz==0) - { - copy_sz=DiffList[0]; - if (copy_sz==0) - { - // big raw copy - copy_sz=DiffList[1]+256*DiffList[2]+65536*DiffList[3]; - memcpy(Output,DiffList+4,copy_sz); - // printf("big rawcopy to %x len=%d\n", Output-obuf,copy_sz); - - DiffList+=copy_sz+4; - Output+=copy_sz; - } - else - { - copy_ofs=DiffList[1]+(DiffList[2]*256); - if (copy_ofs>32767) - copy_ofs|=0xffff0000; - // printf("long ofs cp from %x to %x len=%d\n", copy_src+copy_ofs-OldBlock,Output-obuf,copy_sz); - - memcpy(Output,copy_src+copy_ofs,copy_sz); - Output+=copy_sz; - copy_src=copy_src+copy_ofs+copy_sz; - DiffList+=3; - } - } - else - { - copy_ofs=DiffList[0]; - if (copy_ofs>127) - copy_ofs|=0xffffff80; - // printf("cp from %x to %x len=%d\n", copy_src+copy_ofs-OldBlock,Output-obuf,copy_sz); - - memcpy(Output,copy_src+copy_ofs,copy_sz); - Output+=copy_sz; - copy_src=copy_src+copy_ofs+copy_sz; - DiffList++; - } - } - else - { - // printf("raw copy %d to %x\n",op & 127,Output-obuf); - memcpy(Output,DiffList,op & 127); - Output+=op & 127; - DiffList+=(op & 127); - } - } - } - ResultListSize=Output-obuf; - -} diff --git a/Resources/NetHook/tier1/uniqueid.cpp b/Resources/NetHook/tier1/uniqueid.cpp deleted file mode 100644 index 3fa2661d..00000000 --- a/Resources/NetHook/tier1/uniqueid.cpp +++ /dev/null @@ -1,177 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -// Unique ID generation -//=============================================================================// - -#include "tier0/platform.h" - -#ifdef IS_WINDOWS_PC -#include // UUIDCreate -#else -#include "checksum_crc.h" -#endif -#include "tier1/uniqueid.h" -#include "tier1/utlbuffer.h" - -//----------------------------------------------------------------------------- -// Creates a new unique id -//----------------------------------------------------------------------------- -void CreateUniqueId( UniqueId_t *pDest ) -{ -#ifdef IS_WINDOWS_PC - Assert( sizeof( UUID ) == sizeof( *pDest ) ); - UuidCreate( (UUID *)pDest ); -#else - // X360/linux TBD: Need a real UUID Implementation - Q_memset( pDest, 0, sizeof( UniqueId_t ) ); -#endif -} - - -//----------------------------------------------------------------------------- -// Creates a new unique id from a string representation of one -//----------------------------------------------------------------------------- -bool UniqueIdFromString( UniqueId_t *pDest, const char *pBuf, int nMaxLen ) -{ - if ( nMaxLen == 0 ) - { - nMaxLen = Q_strlen( pBuf ); - } - - char *pTemp = (char*)stackalloc( nMaxLen + 1 ); - V_strncpy( pTemp, pBuf, nMaxLen + 1 ); - --nMaxLen; - while( (nMaxLen >= 0) && isspace( pTemp[nMaxLen] ) ) - { - --nMaxLen; - } - pTemp[ nMaxLen + 1 ] = 0; - - while( *pTemp && isspace( *pTemp ) ) - { - ++pTemp; - } - -#ifdef IS_WINDOWS_PC - Assert( sizeof( UUID ) == sizeof( *pDest ) ); - - if ( RPC_S_OK != UuidFromString( (unsigned char *)pTemp, (UUID *)pDest ) ) - { - InvalidateUniqueId( pDest ); - return false; - } -#else - // X360TBD: Need a real UUID Implementation - // For now, use crc to generate a unique ID from the UUID string. - Q_memset( pDest, 0, sizeof( UniqueId_t ) ); - if ( nMaxLen > 0 ) - { - CRC32_t crc; - CRC32_Init( &crc ); - CRC32_ProcessBuffer( &crc, pBuf, nMaxLen ); - CRC32_Final( &crc ); - Q_memcpy( pDest, &crc, sizeof( CRC32_t ) ); - } -#endif - - return true; -} - -//----------------------------------------------------------------------------- -// Sets an object ID to be an invalid state -//----------------------------------------------------------------------------- -void InvalidateUniqueId( UniqueId_t *pDest ) -{ - Assert( pDest ); - memset( pDest, 0, sizeof( UniqueId_t ) ); -} - -bool IsUniqueIdValid( const UniqueId_t &id ) -{ - UniqueId_t invalidId; - memset( &invalidId, 0, sizeof( UniqueId_t ) ); - return !IsUniqueIdEqual( invalidId, id ); -} - -bool IsUniqueIdEqual( const UniqueId_t &id1, const UniqueId_t &id2 ) -{ - return memcmp( &id1, &id2, sizeof( UniqueId_t ) ) == 0; -} - -void UniqueIdToString( const UniqueId_t &id, char *pBuf, int nMaxLen ) -{ - pBuf[ 0 ] = 0; - -// X360TBD: Need a real UUID Implementation -#ifdef IS_WINDOWS_PC - UUID *self = ( UUID * )&id; - - unsigned char *outstring = NULL; - - UuidToString( self, &outstring ); - if ( outstring && *outstring ) - { - Q_strncpy( pBuf, (const char *)outstring, nMaxLen ); - RpcStringFree( &outstring ); - } -#endif -} - -void CopyUniqueId( const UniqueId_t &src, UniqueId_t *pDest ) -{ - memcpy( pDest, &src, sizeof( UniqueId_t ) ); -} - -bool Serialize( CUtlBuffer &buf, const UniqueId_t &src ) -{ -// X360TBD: Need a real UUID Implementation -#ifdef IS_WINDOWS_PC - if ( buf.IsText() ) - { - UUID *pId = ( UUID * )&src; - - unsigned char *outstring = NULL; - - UuidToString( pId, &outstring ); - if ( outstring && *outstring ) - { - buf.PutString( (const char *)outstring ); - RpcStringFree( &outstring ); - } - else - { - buf.PutChar( '\0' ); - } - } - else - { - buf.Put( &src, sizeof(UniqueId_t) ); - } - return buf.IsValid(); -#else - return false; -#endif -} - -bool Unserialize( CUtlBuffer &buf, UniqueId_t &dest ) -{ - if ( buf.IsText() ) - { - int nTextLen = buf.PeekStringLength(); - char *pBuf = (char*)stackalloc( nTextLen ); - buf.GetString( pBuf, nTextLen ); - UniqueIdFromString( &dest, pBuf, nTextLen ); - } - else - { - buf.Get( &dest, sizeof(UniqueId_t) ); - } - return buf.IsValid(); -} - - - diff --git a/Resources/NetHook/tier1/uniqueid.h b/Resources/NetHook/tier1/uniqueid.h deleted file mode 100644 index ca1cc24b..00000000 --- a/Resources/NetHook/tier1/uniqueid.h +++ /dev/null @@ -1,56 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -// Utilities for globally unique IDs -//=============================================================================// - -#ifndef UNIQUEID_H -#define UNIQUEID_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier1/utlvector.h" - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -struct UniqueId_t; -class CUtlBuffer; - - -//----------------------------------------------------------------------------- -// Defines a globally unique ID -//----------------------------------------------------------------------------- -struct UniqueId_t -{ - unsigned char m_Value[16]; -}; - - -//----------------------------------------------------------------------------- -// Methods related to unique ids -//----------------------------------------------------------------------------- -void CreateUniqueId( UniqueId_t *pDest ); -void InvalidateUniqueId( UniqueId_t *pDest ); -bool IsUniqueIdValid( const UniqueId_t &id ); -bool IsUniqueIdEqual( const UniqueId_t &id1, const UniqueId_t &id2 ); -void UniqueIdToString( const UniqueId_t &id, char *pBuf, int nMaxLen ); -bool UniqueIdFromString( UniqueId_t *pDest, const char *pBuf, int nMaxLen = 0 ); -void CopyUniqueId( const UniqueId_t &src, UniqueId_t *pDest ); -bool Serialize( CUtlBuffer &buf, const UniqueId_t &src ); -bool Unserialize( CUtlBuffer &buf, UniqueId_t &dest ); - -inline bool operator ==( const UniqueId_t& lhs, const UniqueId_t& rhs ) -{ - return !Q_memcmp( (void *)&lhs.m_Value[ 0 ], (void *)&rhs.m_Value[ 0 ], sizeof( lhs.m_Value ) ); -} - - -#endif // UNIQUEID_H - diff --git a/Resources/NetHook/tier1/utlbidirectionalset.h b/Resources/NetHook/tier1/utlbidirectionalset.h deleted file mode 100644 index 32b8622d..00000000 --- a/Resources/NetHook/tier1/utlbidirectionalset.h +++ /dev/null @@ -1,381 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Bi-directional set. A Bucket knows about the elements that lie -// in it, and the elements know about the buckets they lie in. -// -// $Revision: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLBIDIRECTIONALSET_H -#define UTLBIDIRECTIONALSET_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "utllinkedlist.h" - -//----------------------------------------------------------------------------- -// Templatized helper class to deal with the kinds of things that spatial -// partition code always seems to have; buckets with lists of lots of elements -// and elements that live in lots of buckets. This makes it really quick to -// add and remove elements, and to iterate over all elements in a bucket. -// -// For this to work, you must initialize the set with two functions one that -// maps from bucket to the index of the first element in that bucket, and one -// that maps from element to the index of the first bucket that element lies in. -// The set will completely manage the index, it's just expected that those -// indices will be stored outside the set. -// -// S is the storage type of the index; it is the type that you may use to -// save indices into memory. I is the local iterator type, which you should -// use in any local scope (eg, inside a for() loop.) The reason for this is -// that you may wish to use unsigned shorts inside the structs you are -// saving with a CBidirectionalSet; but 16-bit arithmetic is catastrophically -// slow on a PowerPC -- during testing we saw CBidirectionalSet:: operations -// consume as much as 8% of the frame. -// -// For this reason, on the 360, the handles have been typedef'd to native -// register types (U32) which are accepted as parameters by the functions. -// The implicit assumption is that CBucketHandle and CElementHandle can -// be safely cast to ints! You can increase to U64 without performance -// penalty if necessary; the PowerPC is a 64-bit processor. -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I = S > -class CBidirectionalSet -{ -public: - // Install methods to get at the first bucket given a element - // and vice versa... - typedef S& (*FirstElementFunc_t)(CBucketHandle); - typedef S& (*FirstBucketFunc_t)(CElementHandle); - -#ifdef _X360 - typedef uint32 CBucketHandlePram; - typedef uint32 CElementHandlePram; -#else - typedef CBucketHandle CBucketHandlePram; - typedef CElementHandle CElementHandlePram; -#endif - - // Constructor - CBidirectionalSet(); - - // Call this before using the set - void Init( FirstElementFunc_t elemFunc, FirstBucketFunc_t bucketFunc ); - - // Add an element to a particular bucket - void AddElementToBucket( CBucketHandlePram bucket, CElementHandlePram element ); - - // Prevalidate an add to a particular bucket - // NOTE: EXPENSIVE!!! - void ValidateAddElementToBucket( CBucketHandlePram bucket, CElementHandlePram element ); - - // Test if an element is in a particular bucket. - // NOTE: EXPENSIVE!!! - bool IsElementInBucket( CBucketHandlePram bucket, CElementHandlePram element ); - - // Remove an element from a particular bucket - void RemoveElementFromBucket( CBucketHandlePram bucket, CElementHandlePram element ); - - // Remove an element from all buckets - void RemoveElement( CElementHandlePram element ); - void RemoveBucket( CBucketHandlePram element ); - - // Used to iterate elements in a bucket; I is the iterator - I FirstElement( CBucketHandlePram bucket ) const; - I NextElement( I idx ) const; - CElementHandle Element( I idx ) const; - - // Used to iterate buckets associated with an element; I is the iterator - I FirstBucket( CElementHandlePram bucket ) const; - I NextBucket( I idx ) const; - CBucketHandle Bucket( I idx ) const; - - static S InvalidIndex(); - - // Ensure capacity - void EnsureCapacity( int count ); - - // Deallocate.... - void Purge(); - -private: - struct BucketListInfo_t - { - CElementHandle m_Element; - S m_BucketListIndex; // what's the m_BucketsUsedByElement index of the entry? - }; - - struct ElementListInfo_t - { - CBucketHandle m_Bucket; - S m_ElementListIndex; // what's the m_ElementsInBucket index of the entry? - }; - - // Maintains a list of all elements in a particular bucket - CUtlLinkedList< BucketListInfo_t, S, true, I > m_ElementsInBucket; - - // Maintains a list of all buckets a particular element lives in - CUtlLinkedList< ElementListInfo_t, S, true, I > m_BucketsUsedByElement; - - FirstBucketFunc_t m_FirstBucket; - FirstElementFunc_t m_FirstElement; -}; - - -//----------------------------------------------------------------------------- -// Constructor -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -CBidirectionalSet::CBidirectionalSet( ) -{ - m_FirstBucket = NULL; - m_FirstElement = NULL; -} - - -//----------------------------------------------------------------------------- -// Call this before using the set -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::Init( FirstElementFunc_t elemFunc, FirstBucketFunc_t bucketFunc ) -{ - m_FirstBucket = bucketFunc; - m_FirstElement = elemFunc; -} - - -//----------------------------------------------------------------------------- -// Adds an element to the bucket -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::ValidateAddElementToBucket( CBucketHandlePram bucket, CElementHandlePram element ) -{ -#ifdef _DEBUG - // Make sure that this element doesn't already exist in the list of elements in the bucket - I elementInBucket = m_FirstElement( bucket ); - while( elementInBucket != m_ElementsInBucket.InvalidIndex() ) - { - // If you hit an Assert here, fix the calling code. It's too expensive to ensure - // that each item only shows up once here. Hopefully you can do something better - // outside of here. - Assert( m_ElementsInBucket[elementInBucket].m_Element != element ); - elementInBucket = m_ElementsInBucket.Next( elementInBucket ); - } - // Make sure that this bucket doesn't already exist in the element's list of buckets. - I bucketInElement = m_FirstBucket( element ); - while( bucketInElement != m_BucketsUsedByElement.InvalidIndex() ) - { - // If you hit an Assert here, fix the calling code. It's too expensive to ensure - // that each item only shows up once here. Hopefully you can do something better - // outside of here. - Assert( m_BucketsUsedByElement[bucketInElement].m_Bucket != bucket ); - bucketInElement = m_BucketsUsedByElement.Next( bucketInElement ); - } -#endif -} - - -//----------------------------------------------------------------------------- -// Adds an element to the bucket -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::AddElementToBucket( CBucketHandlePram bucket, CElementHandlePram element ) -{ - Assert( m_FirstBucket && m_FirstElement ); - - // Allocate new element + bucket entries - I idx = m_ElementsInBucket.Alloc(true); - I list = m_BucketsUsedByElement.Alloc( true ); - - // Store off the element data - m_ElementsInBucket[idx].m_Element = element; - m_ElementsInBucket[idx].m_BucketListIndex = list; - - // Here's the bucket data - m_BucketsUsedByElement[list].m_Bucket = bucket; - m_BucketsUsedByElement[list].m_ElementListIndex = idx; - - // Insert the element into the list of elements in the bucket - S& firstElementInBucket = m_FirstElement( bucket ); - if ( firstElementInBucket != m_ElementsInBucket.InvalidIndex() ) - m_ElementsInBucket.LinkBefore( firstElementInBucket, idx ); - firstElementInBucket = idx; - - // Insert the bucket into the element's list of buckets - S& firstBucketInElement = m_FirstBucket( element ); - if ( firstBucketInElement != m_BucketsUsedByElement.InvalidIndex() ) - m_BucketsUsedByElement.LinkBefore( firstBucketInElement, list ); - firstBucketInElement = list; -} - -//----------------------------------------------------------------------------- -// Test if an element is in a particular bucket. -// NOTE: EXPENSIVE!!! -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -bool CBidirectionalSet::IsElementInBucket( CBucketHandlePram bucket, CElementHandlePram element ) -{ - // Search through all elements in this bucket to see if element is in there. - I elementInBucket = m_FirstElement( bucket ); - while( elementInBucket != m_ElementsInBucket.InvalidIndex() ) - { - if( m_ElementsInBucket[elementInBucket].m_Element == element ) - { - return true; - } - elementInBucket = m_ElementsInBucket.Next( elementInBucket ); - } - return false; -} - - -//----------------------------------------------------------------------------- -// Remove an element from a particular bucket -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::RemoveElementFromBucket( CBucketHandlePram bucket, CElementHandlePram element ) -{ - // FIXME: Implement me! - Assert(0); -} - - -//----------------------------------------------------------------------------- -// Removes an element from all buckets -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::RemoveElement( CElementHandlePram element ) -{ - Assert( m_FirstBucket && m_FirstElement ); - - // Iterate over the list of all buckets the element is in - I i = m_FirstBucket( element ); - while (i != m_BucketsUsedByElement.InvalidIndex()) - { - CBucketHandlePram bucket = m_BucketsUsedByElement[i].m_Bucket; - I elementListIndex = m_BucketsUsedByElement[i].m_ElementListIndex; - - // Unhook the element from the bucket's list of elements - if (elementListIndex == m_FirstElement(bucket)) - m_FirstElement(bucket) = m_ElementsInBucket.Next(elementListIndex); - m_ElementsInBucket.Free(elementListIndex); - - I prevNode = i; - i = m_BucketsUsedByElement.Next(i); - m_BucketsUsedByElement.Free(prevNode); - } - - // Mark the list as empty - m_FirstBucket( element ) = m_BucketsUsedByElement.InvalidIndex(); -} - -//----------------------------------------------------------------------------- -// Removes a bucket from all elements -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::RemoveBucket( CBucketHandlePram bucket ) -{ - // Iterate over the list of all elements in the bucket - I i = m_FirstElement( bucket ); - while (i != m_ElementsInBucket.InvalidIndex()) - { - CElementHandlePram element = m_ElementsInBucket[i].m_Element; - I bucketListIndex = m_ElementsInBucket[i].m_BucketListIndex; - - // Unhook the bucket from the element's list of buckets - if (bucketListIndex == m_FirstBucket(element)) - m_FirstBucket(element) = m_BucketsUsedByElement.Next(bucketListIndex); - m_BucketsUsedByElement.Free(bucketListIndex); - - // Remove the list element - I prevNode = i; - i = m_ElementsInBucket.Next(i); - m_ElementsInBucket.Free(prevNode); - } - - // Mark the bucket list as empty - m_FirstElement( bucket ) = m_ElementsInBucket.InvalidIndex(); -} - - -//----------------------------------------------------------------------------- -// Ensure capacity -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::EnsureCapacity( int count ) -{ - m_ElementsInBucket.EnsureCapacity( count ); - m_BucketsUsedByElement.EnsureCapacity( count ); -} - - -//----------------------------------------------------------------------------- -// Deallocate.... -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -void CBidirectionalSet::Purge() -{ - m_ElementsInBucket.Purge( ); - m_BucketsUsedByElement.Purge( ); -} - - -//----------------------------------------------------------------------------- -// Invalid index for iteration.. -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -inline S CBidirectionalSet::InvalidIndex() -{ - return CUtlLinkedList< CElementHandle, I >::InvalidIndex(); -} - - -//----------------------------------------------------------------------------- -// Used to iterate elements in a bucket; I is the iterator -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -inline I CBidirectionalSet::FirstElement( CBucketHandlePram bucket ) const -{ - Assert( m_FirstElement ); - return m_FirstElement(bucket); -} - -template< class CBucketHandle, class CElementHandle, class S, class I > -inline I CBidirectionalSet::NextElement( I idx ) const -{ - return m_ElementsInBucket.Next(idx); -} - -template< class CBucketHandle, class CElementHandle, class S, class I > -inline CElementHandle CBidirectionalSet::Element( I idx ) const -{ - return m_ElementsInBucket[idx].m_Element; -} - -//----------------------------------------------------------------------------- -// Used to iterate buckets an element lies in; I is the iterator -//----------------------------------------------------------------------------- -template< class CBucketHandle, class CElementHandle, class S, class I > -inline I CBidirectionalSet::FirstBucket( CElementHandlePram element ) const -{ - Assert( m_FirstBucket ); - return m_FirstBucket(element); -} - -template< class CBucketHandle, class CElementHandle, class S, class I > -inline I CBidirectionalSet::NextBucket( I idx ) const -{ - return m_BucketsUsedByElement.Next(idx); -} - -template< class CBucketHandle, class CElementHandle, class S, class I > -inline CBucketHandle CBidirectionalSet::Bucket( I idx ) const -{ - return m_BucketsUsedByElement[idx].m_Bucket; -} - -#endif // UTLBIDIRECTIONALSET_H diff --git a/Resources/NetHook/tier1/utlblockmemory.h b/Resources/NetHook/tier1/utlblockmemory.h deleted file mode 100644 index 4812d45a..00000000 --- a/Resources/NetHook/tier1/utlblockmemory.h +++ /dev/null @@ -1,349 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -// -// A growable memory class. -//===========================================================================// - -#ifndef UTLBLOCKMEMORY_H -#define UTLBLOCKMEMORY_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "tier0/platform.h" -#include "mathlib/mathlib.h" - -#include "tier0/memalloc.h" -#include "tier0/memdbgon.h" - -#pragma warning (disable:4100) -#pragma warning (disable:4514) - -//----------------------------------------------------------------------------- - -#ifdef UTLMEMORY_TRACK -#define UTLMEMORY_TRACK_ALLOC() MemAlloc_RegisterAllocation( "Sum of all UtlBlockMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 ) -#define UTLMEMORY_TRACK_FREE() if ( !m_pMemory ) ; else MemAlloc_RegisterDeallocation( "Sum of all UtlBlockMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 ) -#else -#define UTLMEMORY_TRACK_ALLOC() ((void)0) -#define UTLMEMORY_TRACK_FREE() ((void)0) -#endif - - -//----------------------------------------------------------------------------- -// The CUtlBlockMemory class: -// A growable memory class that allocates non-sequential blocks, but is indexed sequentially -//----------------------------------------------------------------------------- -template< class T, class I > -class CUtlBlockMemory -{ -public: - // constructor, destructor - CUtlBlockMemory( int nGrowSize = 0, int nInitSize = 0 ); - ~CUtlBlockMemory(); - - // Set the size by which the memory grows - round up to the next power of 2 - void Init( int nGrowSize = 0, int nInitSize = 0 ); - - // here to match CUtlMemory, but only used by ResetDbgInfo, so it can just return NULL - T* Base() { return NULL; } - const T* Base() const { return NULL; } - - class Iterator_t - { - public: - Iterator_t( I i ) : index( i ) {} - I index; - - bool operator==( const Iterator_t it ) const { return index == it.index; } - bool operator!=( const Iterator_t it ) const { return index != it.index; } - }; - Iterator_t First() const { return Iterator_t( IsIdxValid( 0 ) ? 0 : InvalidIndex() ); } - Iterator_t Next( const Iterator_t &it ) const { return Iterator_t( IsIdxValid( it.index + 1 ) ? it.index + 1 : InvalidIndex() ); } - I GetIndex( const Iterator_t &it ) const { return it.index; } - bool IsIdxAfter( I i, const Iterator_t &it ) const { return i > it.index; } - bool IsValidIterator( const Iterator_t &it ) const { return IsIdxValid( it.index ); } - Iterator_t InvalidIterator() const { return Iterator_t( InvalidIndex() ); } - - // element access - T& operator[]( I i ); - const T& operator[]( I i ) const; - T& Element( I i ); - const T& Element( I i ) const; - - // Can we use this index? - bool IsIdxValid( I i ) const; - static I InvalidIndex() { return ( I )-1; } - - void Swap( CUtlBlockMemory< T, I > &mem ); - - // Size - int NumAllocated() const; - int Count() const { return NumAllocated(); } - - // Grows memory by max(num,growsize) rounded up to the next power of 2, and returns the allocation index/ptr - void Grow( int num = 1 ); - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ); - - // Memory deallocation - void Purge(); - - // Purge all but the given number of elements - void Purge( int numElements ); - -protected: - int Index( int major, int minor ) const { return ( major << m_nIndexShift ) | minor; } - int MajorIndex( int i ) const { return i >> m_nIndexShift; } - int MinorIndex( int i ) const { return i & m_nIndexMask; } - void ChangeSize( int nBlocks ); - int NumElementsInBlock() const { return m_nIndexMask + 1; } - - T** m_pMemory; - int m_nBlocks; - int m_nIndexMask : 27; - int m_nIndexShift : 5; -}; - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template< class T, class I > -CUtlBlockMemory::CUtlBlockMemory( int nGrowSize, int nInitAllocationCount ) -: m_pMemory( 0 ), m_nBlocks( 0 ), m_nIndexMask( 0 ), m_nIndexShift( 0 ) -{ - Init( nGrowSize, nInitAllocationCount ); -} - -template< class T, class I > -CUtlBlockMemory::~CUtlBlockMemory() -{ - Purge(); -} - - -//----------------------------------------------------------------------------- -// Fast swap -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlBlockMemory::Swap( CUtlBlockMemory< T, I > &mem ) -{ - swap( m_pMemory, mem.m_pMemory ); - swap( m_nBlocks, mem.m_nBlocks ); - swap( m_nIndexMask, mem.m_nIndexMask ); - swap( m_nIndexShift, mem.m_nIndexShift ); -} - - -//----------------------------------------------------------------------------- -// Set the size by which the memory grows - round up to the next power of 2 -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlBlockMemory::Init( int nGrowSize /* = 0 */, int nInitSize /* = 0 */ ) -{ - Purge(); - - if ( nGrowSize == 0) - { - // default grow size is smallest size s.t. c++ allocation overhead is ~6% of block size - nGrowSize = ( 127 + sizeof( T ) ) / sizeof( T ); - } - nGrowSize = SmallestPowerOfTwoGreaterOrEqual( nGrowSize ); - m_nIndexMask = nGrowSize - 1; - - m_nIndexShift = 0; - while ( nGrowSize > 1 ) - { - nGrowSize >>= 1; - ++m_nIndexShift; - } - Assert( m_nIndexMask + 1 == ( 1 << m_nIndexShift ) ); - - Grow( nInitSize ); -} - - -//----------------------------------------------------------------------------- -// element access -//----------------------------------------------------------------------------- -template< class T, class I > -inline T& CUtlBlockMemory::operator[]( I i ) -{ - Assert( IsIdxValid(i) ); - T *pBlock = m_pMemory[ MajorIndex( i ) ]; - return pBlock[ MinorIndex( i ) ]; -} - -template< class T, class I > -inline const T& CUtlBlockMemory::operator[]( I i ) const -{ - Assert( IsIdxValid(i) ); - const T *pBlock = m_pMemory[ MajorIndex( i ) ]; - return pBlock[ MinorIndex( i ) ]; -} - -template< class T, class I > -inline T& CUtlBlockMemory::Element( I i ) -{ - Assert( IsIdxValid(i) ); - T *pBlock = m_pMemory[ MajorIndex( i ) ]; - return pBlock[ MinorIndex( i ) ]; -} - -template< class T, class I > -inline const T& CUtlBlockMemory::Element( I i ) const -{ - Assert( IsIdxValid(i) ); - const T *pBlock = m_pMemory[ MajorIndex( i ) ]; - return pBlock[ MinorIndex( i ) ]; -} - - -//----------------------------------------------------------------------------- -// Size -//----------------------------------------------------------------------------- -template< class T, class I > -inline int CUtlBlockMemory::NumAllocated() const -{ - return m_nBlocks * NumElementsInBlock(); -} - - -//----------------------------------------------------------------------------- -// Is element index valid? -//----------------------------------------------------------------------------- -template< class T, class I > -inline bool CUtlBlockMemory::IsIdxValid( I i ) const -{ - return ( i >= 0 ) && ( MajorIndex( i ) < m_nBlocks ); -} - -template< class T, class I > -void CUtlBlockMemory::Grow( int num ) -{ - if ( num <= 0 ) - return; - - int nBlockSize = NumElementsInBlock(); - int nBlocks = ( num + nBlockSize - 1 ) / nBlockSize; - - ChangeSize( m_nBlocks + nBlocks ); -} - -template< class T, class I > -void CUtlBlockMemory::ChangeSize( int nBlocks ) -{ - UTLMEMORY_TRACK_FREE(); // this must stay before the recalculation of m_nBlocks, since it implicitly uses the old value - - int nBlocksOld = m_nBlocks; - m_nBlocks = nBlocks; - - UTLMEMORY_TRACK_ALLOC(); // this must stay after the recalculation of m_nBlocks, since it implicitly uses the new value - - // free old blocks if shrinking - for ( int i = m_nBlocks; i < nBlocksOld; ++i ) - { - UTLMEMORY_TRACK_FREE(); - free( (void*)m_pMemory[ i ] ); - } - - if ( m_pMemory ) - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T**)realloc( m_pMemory, m_nBlocks * sizeof(T*) ); - Assert( m_pMemory ); - } - else - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T**)malloc( m_nBlocks * sizeof(T*) ); - Assert( m_pMemory ); - } - - if ( !m_pMemory ) - { - Error( "CUtlBlockMemory overflow!\n" ); - } - - // allocate new blocks if growing - int nBlockSize = NumElementsInBlock(); - for ( int i = nBlocksOld; i < m_nBlocks; ++i ) - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory[ i ] = (T*)malloc( nBlockSize * sizeof( T ) ); - Assert( m_pMemory[ i ] ); - } -} - - -//----------------------------------------------------------------------------- -// Makes sure we've got at least this much memory -//----------------------------------------------------------------------------- -template< class T, class I > -inline void CUtlBlockMemory::EnsureCapacity( int num ) -{ - Grow( num - NumAllocated() ); -} - - -//----------------------------------------------------------------------------- -// Memory deallocation -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlBlockMemory::Purge() -{ - if ( !m_pMemory ) - return; - - for ( int i = 0; i < m_nBlocks; ++i ) - { - UTLMEMORY_TRACK_FREE(); - free( (void*)m_pMemory[ i ] ); - } - m_nBlocks = 0; - - UTLMEMORY_TRACK_FREE(); - free( (void*)m_pMemory ); - m_pMemory = 0; -} - -template< class T, class I > -void CUtlBlockMemory::Purge( int numElements ) -{ - Assert( numElements >= 0 ); - - int nAllocated = NumAllocated(); - if ( numElements > nAllocated ) - { - // Ensure this isn't a grow request in disguise. - Assert( numElements <= nAllocated ); - return; - } - - if ( numElements <= 0 ) - { - Purge(); - return; - } - - int nBlockSize = NumElementsInBlock(); - int nBlocksOld = m_nBlocks; - int nBlocks = ( numElements + nBlockSize - 1 ) / nBlockSize; - - // If the number of blocks is the same as the allocated number of blocks, we are done. - if ( nBlocks == m_nBlocks ) - return; - - ChangeSize( nBlocks ); -} - -#include "tier0/memdbgoff.h" - -#endif // UTLBLOCKMEMORY_H diff --git a/Resources/NetHook/tier1/utlbuffer.cpp b/Resources/NetHook/tier1/utlbuffer.cpp deleted file mode 100644 index 6babdf5d..00000000 --- a/Resources/NetHook/tier1/utlbuffer.cpp +++ /dev/null @@ -1,1747 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// $Header: $ -// $NoKeywords: $ -// -// Serialization buffer -//===========================================================================// - -#pragma warning (disable : 4514) - -#include "utlbuffer.h" -#include -#include -#include -#include -#include -#include "tier1/strtools.h" -#include "tier1/characterset.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - - -//----------------------------------------------------------------------------- -// Character conversions for C strings -//----------------------------------------------------------------------------- -class CUtlCStringConversion : public CUtlCharConversion -{ -public: - CUtlCStringConversion( char nEscapeChar, const char *pDelimiter, int nCount, ConversionArray_t *pArray ); - - // Finds a conversion for the passed-in string, returns length - virtual char FindConversion( const char *pString, int *pLength ); - -private: - char m_pConversion[255]; -}; - - -//----------------------------------------------------------------------------- -// Character conversions for no-escape sequence strings -//----------------------------------------------------------------------------- -class CUtlNoEscConversion : public CUtlCharConversion -{ -public: - CUtlNoEscConversion( char nEscapeChar, const char *pDelimiter, int nCount, ConversionArray_t *pArray ) : - CUtlCharConversion( nEscapeChar, pDelimiter, nCount, pArray ) {} - - // Finds a conversion for the passed-in string, returns length - virtual char FindConversion( const char *pString, int *pLength ) { *pLength = 0; return 0; } -}; - - -//----------------------------------------------------------------------------- -// List of character conversions -//----------------------------------------------------------------------------- -BEGIN_CUSTOM_CHAR_CONVERSION( CUtlCStringConversion, s_StringCharConversion, "\"", '\\' ) - { '\n', "n" }, - { '\t', "t" }, - { '\v', "v" }, - { '\b', "b" }, - { '\r', "r" }, - { '\f', "f" }, - { '\a', "a" }, - { '\\', "\\" }, - { '\?', "\?" }, - { '\'', "\'" }, - { '\"', "\"" }, -END_CUSTOM_CHAR_CONVERSION( CUtlCStringConversion, s_StringCharConversion, "\"", '\\' ) - -CUtlCharConversion *GetCStringCharConversion() -{ - return &s_StringCharConversion; -} - -BEGIN_CUSTOM_CHAR_CONVERSION( CUtlNoEscConversion, s_NoEscConversion, "\"", 0x7F ) - { 0x7F, "" }, -END_CUSTOM_CHAR_CONVERSION( CUtlNoEscConversion, s_NoEscConversion, "\"", 0x7F ) - -CUtlCharConversion *GetNoEscCharConversion() -{ - return &s_NoEscConversion; -} - - -//----------------------------------------------------------------------------- -// Constructor -//----------------------------------------------------------------------------- -CUtlCStringConversion::CUtlCStringConversion( char nEscapeChar, const char *pDelimiter, int nCount, ConversionArray_t *pArray ) : - CUtlCharConversion( nEscapeChar, pDelimiter, nCount, pArray ) -{ - memset( m_pConversion, 0x0, sizeof(m_pConversion) ); - for ( int i = 0; i < nCount; ++i ) - { - m_pConversion[ pArray[i].m_pReplacementString[0] ] = pArray[i].m_nActualChar; - } -} - -// Finds a conversion for the passed-in string, returns length -char CUtlCStringConversion::FindConversion( const char *pString, int *pLength ) -{ - char c = m_pConversion[ pString[0] ]; - *pLength = (c != '\0') ? 1 : 0; - return c; -} - - - -//----------------------------------------------------------------------------- -// Constructor -//----------------------------------------------------------------------------- -CUtlCharConversion::CUtlCharConversion( char nEscapeChar, const char *pDelimiter, int nCount, ConversionArray_t *pArray ) -{ - m_nEscapeChar = nEscapeChar; - m_pDelimiter = pDelimiter; - m_nCount = nCount; - m_nDelimiterLength = Q_strlen( pDelimiter ); - m_nMaxConversionLength = 0; - - memset( m_pReplacements, 0, sizeof(m_pReplacements) ); - - for ( int i = 0; i < nCount; ++i ) - { - m_pList[i] = pArray[i].m_nActualChar; - ConversionInfo_t &info = m_pReplacements[ m_pList[i] ]; - Assert( info.m_pReplacementString == 0 ); - info.m_pReplacementString = pArray[i].m_pReplacementString; - info.m_nLength = Q_strlen( info.m_pReplacementString ); - if ( info.m_nLength > m_nMaxConversionLength ) - { - m_nMaxConversionLength = info.m_nLength; - } - } -} - - -//----------------------------------------------------------------------------- -// Escape character + delimiter -//----------------------------------------------------------------------------- -char CUtlCharConversion::GetEscapeChar() const -{ - return m_nEscapeChar; -} - -const char *CUtlCharConversion::GetDelimiter() const -{ - return m_pDelimiter; -} - -int CUtlCharConversion::GetDelimiterLength() const -{ - return m_nDelimiterLength; -} - - -//----------------------------------------------------------------------------- -// Constructor -//----------------------------------------------------------------------------- -const char *CUtlCharConversion::GetConversionString( char c ) const -{ - return m_pReplacements[ c ].m_pReplacementString; -} - -int CUtlCharConversion::GetConversionLength( char c ) const -{ - return m_pReplacements[ c ].m_nLength; -} - -int CUtlCharConversion::MaxConversionLength() const -{ - return m_nMaxConversionLength; -} - - -//----------------------------------------------------------------------------- -// Finds a conversion for the passed-in string, returns length -//----------------------------------------------------------------------------- -char CUtlCharConversion::FindConversion( const char *pString, int *pLength ) -{ - for ( int i = 0; i < m_nCount; ++i ) - { - if ( !Q_strcmp( pString, m_pReplacements[ m_pList[i] ].m_pReplacementString ) ) - { - *pLength = m_pReplacements[ m_pList[i] ].m_nLength; - return m_pList[i]; - } - } - - *pLength = 0; - return '\0'; -} - - -//----------------------------------------------------------------------------- -// constructors -//----------------------------------------------------------------------------- -CUtlBuffer::CUtlBuffer( int growSize, int initSize, int nFlags ) : - m_Memory( growSize, initSize ), m_Error(0) -{ - m_Get = 0; - m_Put = 0; - m_nTab = 0; - m_nOffset = 0; - m_Flags = nFlags; - if ( (initSize != 0) && !IsReadOnly() ) - { - m_nMaxPut = -1; - AddNullTermination(); - } - else - { - m_nMaxPut = 0; - } - SetOverflowFuncs( &CUtlBuffer::GetOverflow, &CUtlBuffer::PutOverflow ); -} - -CUtlBuffer::CUtlBuffer( const void *pBuffer, int nSize, int nFlags ) : - m_Memory( (unsigned char*)pBuffer, nSize ), m_Error(0) -{ - Assert( nSize != 0 ); - - m_Get = 0; - m_Put = 0; - m_nTab = 0; - m_nOffset = 0; - m_Flags = nFlags; - if ( IsReadOnly() ) - { - m_nMaxPut = nSize; - } - else - { - m_nMaxPut = -1; - AddNullTermination(); - } - SetOverflowFuncs( &CUtlBuffer::GetOverflow, &CUtlBuffer::PutOverflow ); -} - - -//----------------------------------------------------------------------------- -// Modifies the buffer to be binary or text; Blows away the buffer and the CONTAINS_CRLF value. -//----------------------------------------------------------------------------- -void CUtlBuffer::SetBufferType( bool bIsText, bool bContainsCRLF ) -{ -#ifdef _DEBUG - // If the buffer is empty, there is no opportunity for this stuff to fail - if ( TellMaxPut() != 0 ) - { - if ( IsText() ) - { - if ( bIsText ) - { - Assert( ContainsCRLF() == bContainsCRLF ); - } - else - { - Assert( ContainsCRLF() ); - } - } - else - { - if ( bIsText ) - { - Assert( bContainsCRLF ); - } - } - } -#endif - - if ( bIsText ) - { - m_Flags |= TEXT_BUFFER; - } - else - { - m_Flags &= ~TEXT_BUFFER; - } - if ( bContainsCRLF ) - { - m_Flags |= CONTAINS_CRLF; - } - else - { - m_Flags &= ~CONTAINS_CRLF; - } -} - - -//----------------------------------------------------------------------------- -// Attaches the buffer to external memory.... -//----------------------------------------------------------------------------- -void CUtlBuffer::SetExternalBuffer( void* pMemory, int nSize, int nInitialPut, int nFlags ) -{ - m_Memory.SetExternalBuffer( (unsigned char*)pMemory, nSize ); - - // Reset all indices; we just changed memory - m_Get = 0; - m_Put = nInitialPut; - m_nTab = 0; - m_Error = 0; - m_nOffset = 0; - m_Flags = nFlags; - m_nMaxPut = -1; - AddNullTermination(); -} - -//----------------------------------------------------------------------------- -// Assumes an external buffer but manages its deletion -//----------------------------------------------------------------------------- -void CUtlBuffer::AssumeMemory( void *pMemory, int nSize, int nInitialPut, int nFlags ) -{ - m_Memory.AssumeMemory( (unsigned char*) pMemory, nSize ); - - // Reset all indices; we just changed memory - m_Get = 0; - m_Put = nInitialPut; - m_nTab = 0; - m_Error = 0; - m_nOffset = 0; - m_Flags = nFlags; - m_nMaxPut = -1; - AddNullTermination(); -} - -//----------------------------------------------------------------------------- -// Makes sure we've got at least this much memory -//----------------------------------------------------------------------------- -void CUtlBuffer::EnsureCapacity( int num ) -{ - // Add one extra for the null termination - num += 1; - if ( m_Memory.IsExternallyAllocated() ) - { - if ( IsGrowable() && ( m_Memory.NumAllocated() < num ) ) - { - m_Memory.ConvertToGrowableMemory( 0 ); - } - else - { - num -= 1; - } - } - - m_Memory.EnsureCapacity( num ); -} - - -//----------------------------------------------------------------------------- -// Base get method from which all others derive -//----------------------------------------------------------------------------- -void CUtlBuffer::Get( void* pMem, int size ) -{ - if ( CheckGet( size ) ) - { - memcpy( pMem, &m_Memory[m_Get - m_nOffset], size ); - m_Get += size; - } -} - - -//----------------------------------------------------------------------------- -// This will get at least 1 byte and up to nSize bytes. -// It will return the number of bytes actually read. -//----------------------------------------------------------------------------- -int CUtlBuffer::GetUpTo( void *pMem, int nSize ) -{ - if ( CheckArbitraryPeekGet( 0, nSize ) ) - { - memcpy( pMem, &m_Memory[m_Get - m_nOffset], nSize ); - m_Get += nSize; - return nSize; - } - return 0; -} - - -//----------------------------------------------------------------------------- -// Eats whitespace -//----------------------------------------------------------------------------- -void CUtlBuffer::EatWhiteSpace() -{ - if ( IsText() && IsValid() ) - { - while ( CheckGet( sizeof(char) ) ) - { - if ( !isspace( *(const unsigned char*)PeekGet() ) ) - break; - m_Get += sizeof(char); - } - } -} - - -//----------------------------------------------------------------------------- -// Eats C++ style comments -//----------------------------------------------------------------------------- -bool CUtlBuffer::EatCPPComment() -{ - if ( IsText() && IsValid() ) - { - // If we don't have a a c++ style comment next, we're done - const char *pPeek = (const char *)PeekGet( 2 * sizeof(char), 0 ); - if ( !pPeek || ( pPeek[0] != '/' ) || ( pPeek[1] != '/' ) ) - return false; - - // Deal with c++ style comments - m_Get += 2; - - // read complete line - for ( char c = GetChar(); IsValid(); c = GetChar() ) - { - if ( c == '\n' ) - break; - } - return true; - } - return false; -} - - -//----------------------------------------------------------------------------- -// Peeks how much whitespace to eat -//----------------------------------------------------------------------------- -int CUtlBuffer::PeekWhiteSpace( int nOffset ) -{ - if ( !IsText() || !IsValid() ) - return 0; - - while ( CheckPeekGet( nOffset, sizeof(char) ) ) - { - if ( !isspace( *(unsigned char*)PeekGet( nOffset ) ) ) - break; - nOffset += sizeof(char); - } - - return nOffset; -} - - -//----------------------------------------------------------------------------- -// Peek size of sting to come, check memory bound -//----------------------------------------------------------------------------- -int CUtlBuffer::PeekStringLength() -{ - if ( !IsValid() ) - return 0; - - // Eat preceeding whitespace - int nOffset = 0; - if ( IsText() ) - { - nOffset = PeekWhiteSpace( nOffset ); - } - - int nStartingOffset = nOffset; - - do - { - int nPeekAmount = 128; - - // NOTE: Add 1 for the terminating zero! - if ( !CheckArbitraryPeekGet( nOffset, nPeekAmount ) ) - { - if ( nOffset == nStartingOffset ) - return 0; - return nOffset - nStartingOffset + 1; - } - - const char *pTest = (const char *)PeekGet( nOffset ); - - if ( !IsText() ) - { - for ( int i = 0; i < nPeekAmount; ++i ) - { - // The +1 here is so we eat the terminating 0 - if ( pTest[i] == 0 ) - return (i + nOffset - nStartingOffset + 1); - } - } - else - { - for ( int i = 0; i < nPeekAmount; ++i ) - { - // The +1 here is so we eat the terminating 0 - if ( isspace((unsigned char)pTest[i]) || (pTest[i] == 0) ) - return (i + nOffset - nStartingOffset + 1); - } - } - - nOffset += nPeekAmount; - - } while ( true ); -} - - -//----------------------------------------------------------------------------- -// Peek size of line to come, check memory bound -//----------------------------------------------------------------------------- -int CUtlBuffer::PeekLineLength() -{ - if ( !IsValid() ) - return 0; - - int nOffset = 0; - int nStartingOffset = nOffset; - - do - { - int nPeekAmount = 128; - - // NOTE: Add 1 for the terminating zero! - if ( !CheckArbitraryPeekGet( nOffset, nPeekAmount ) ) - { - if ( nOffset == nStartingOffset ) - return 0; - return nOffset - nStartingOffset + 1; - } - - const char *pTest = (const char *)PeekGet( nOffset ); - - for ( int i = 0; i < nPeekAmount; ++i ) - { - // The +2 here is so we eat the terminating '\n' and 0 - if ( pTest[i] == '\n' || pTest[i] == '\r' ) - return (i + nOffset - nStartingOffset + 2); - // The +1 here is so we eat the terminating 0 - if ( pTest[i] == 0 ) - return (i + nOffset - nStartingOffset + 1); - } - - nOffset += nPeekAmount; - - } while ( true ); -} - - -//----------------------------------------------------------------------------- -// Does the next bytes of the buffer match a pattern? -//----------------------------------------------------------------------------- -bool CUtlBuffer::PeekStringMatch( int nOffset, const char *pString, int nLen ) -{ - if ( !CheckPeekGet( nOffset, nLen ) ) - return false; - return !Q_strncmp( (const char*)PeekGet(nOffset), pString, nLen ); -} - - -//----------------------------------------------------------------------------- -// This version of PeekStringLength converts \" to \\ and " to \, etc. -// It also reads a " at the beginning and end of the string -//----------------------------------------------------------------------------- -int CUtlBuffer::PeekDelimitedStringLength( CUtlCharConversion *pConv, bool bActualSize ) -{ - if ( !IsText() || !pConv ) - return PeekStringLength(); - - // Eat preceeding whitespace - int nOffset = 0; - if ( IsText() ) - { - nOffset = PeekWhiteSpace( nOffset ); - } - - if ( !PeekStringMatch( nOffset, pConv->GetDelimiter(), pConv->GetDelimiterLength() ) ) - return 0; - - // Try to read ending ", but don't accept \" - int nActualStart = nOffset; - nOffset += pConv->GetDelimiterLength(); - int nLen = 1; // Starts at 1 for the '\0' termination - - do - { - if ( PeekStringMatch( nOffset, pConv->GetDelimiter(), pConv->GetDelimiterLength() ) ) - break; - - if ( !CheckPeekGet( nOffset, 1 ) ) - break; - - char c = *(const char*)PeekGet( nOffset ); - ++nLen; - ++nOffset; - if ( c == pConv->GetEscapeChar() ) - { - int nLength = pConv->MaxConversionLength(); - if ( !CheckArbitraryPeekGet( nOffset, nLength ) ) - break; - - pConv->FindConversion( (const char*)PeekGet(nOffset), &nLength ); - nOffset += nLength; - } - } while (true); - - return bActualSize ? nLen : nOffset - nActualStart + pConv->GetDelimiterLength() + 1; -} - - -//----------------------------------------------------------------------------- -// Reads a null-terminated string -//----------------------------------------------------------------------------- -void CUtlBuffer::GetString( char* pString, int nMaxChars ) -{ - if (!IsValid()) - { - *pString = 0; - return; - } - - if ( nMaxChars == 0 ) - { - nMaxChars = INT_MAX; - } - - // Remember, this *includes* the null character - // It will be 0, however, if the buffer is empty. - int nLen = PeekStringLength(); - - if ( IsText() ) - { - EatWhiteSpace(); - } - - if ( nLen == 0 ) - { - *pString = 0; - m_Error |= GET_OVERFLOW; - return; - } - - // Strip off the terminating NULL - if ( nLen <= nMaxChars ) - { - Get( pString, nLen - 1 ); - pString[ nLen - 1 ] = 0; - } - else - { - Get( pString, nMaxChars - 1 ); - pString[ nMaxChars - 1 ] = 0; - SeekGet( SEEK_CURRENT, nLen - 1 - nMaxChars ); - } - - // Read the terminating NULL in binary formats - if ( !IsText() ) - { - VerifyEquals( GetChar(), 0 ); - } -} - - -//----------------------------------------------------------------------------- -// Reads up to and including the first \n -//----------------------------------------------------------------------------- -void CUtlBuffer::GetLine( char* pLine, int nMaxChars ) -{ - Assert( IsText() && !ContainsCRLF() ); - - if ( !IsValid() ) - { - *pLine = 0; - return; - } - - if ( nMaxChars == 0 ) - { - nMaxChars = INT_MAX; - } - - // Remember, this *includes* the null character - // It will be 0, however, if the buffer is empty. - int nLen = PeekLineLength(); - if ( nLen == 0 ) - { - *pLine = 0; - m_Error |= GET_OVERFLOW; - return; - } - - // Strip off the terminating NULL - if ( nLen <= nMaxChars ) - { - Get( pLine, nLen - 1 ); - pLine[ nLen - 1 ] = 0; - } - else - { - Get( pLine, nMaxChars - 1 ); - pLine[ nMaxChars - 1 ] = 0; - SeekGet( SEEK_CURRENT, nLen - 1 - nMaxChars ); - } -} - - -//----------------------------------------------------------------------------- -// This version of GetString converts \ to \\ and " to \", etc. -// It also places " at the beginning and end of the string -//----------------------------------------------------------------------------- -char CUtlBuffer::GetDelimitedCharInternal( CUtlCharConversion *pConv ) -{ - char c = GetChar(); - if ( c == pConv->GetEscapeChar() ) - { - int nLength = pConv->MaxConversionLength(); - if ( !CheckArbitraryPeekGet( 0, nLength ) ) - return '\0'; - - c = pConv->FindConversion( (const char *)PeekGet(), &nLength ); - SeekGet( SEEK_CURRENT, nLength ); - } - - return c; -} - -char CUtlBuffer::GetDelimitedChar( CUtlCharConversion *pConv ) -{ - if ( !IsText() || !pConv ) - return GetChar( ); - return GetDelimitedCharInternal( pConv ); -} - -void CUtlBuffer::GetDelimitedString( CUtlCharConversion *pConv, char *pString, int nMaxChars ) -{ - if ( !IsText() || !pConv ) - { - GetString( pString, nMaxChars ); - return; - } - - if (!IsValid()) - { - *pString = 0; - return; - } - - if ( nMaxChars == 0 ) - { - nMaxChars = INT_MAX; - } - - EatWhiteSpace(); - if ( !PeekStringMatch( 0, pConv->GetDelimiter(), pConv->GetDelimiterLength() ) ) - return; - - // Pull off the starting delimiter - SeekGet( SEEK_CURRENT, pConv->GetDelimiterLength() ); - - int nRead = 0; - while ( IsValid() ) - { - if ( PeekStringMatch( 0, pConv->GetDelimiter(), pConv->GetDelimiterLength() ) ) - { - SeekGet( SEEK_CURRENT, pConv->GetDelimiterLength() ); - break; - } - - char c = GetDelimitedCharInternal( pConv ); - - if ( nRead < nMaxChars ) - { - pString[nRead] = c; - ++nRead; - } - } - - if ( nRead >= nMaxChars ) - { - nRead = nMaxChars - 1; - } - pString[nRead] = '\0'; -} - - -//----------------------------------------------------------------------------- -// Checks if a get is ok -//----------------------------------------------------------------------------- -bool CUtlBuffer::CheckGet( int nSize ) -{ - if ( m_Error & GET_OVERFLOW ) - return false; - - if ( TellMaxPut() < m_Get + nSize ) - { - m_Error |= GET_OVERFLOW; - return false; - } - - if ( ( m_Get < m_nOffset ) || ( m_Memory.NumAllocated() < m_Get - m_nOffset + nSize ) ) - { - if ( !OnGetOverflow( nSize ) ) - { - m_Error |= GET_OVERFLOW; - return false; - } - } - - return true; -} - - -//----------------------------------------------------------------------------- -// Checks if a peek get is ok -//----------------------------------------------------------------------------- -bool CUtlBuffer::CheckPeekGet( int nOffset, int nSize ) -{ - if ( m_Error & GET_OVERFLOW ) - return false; - - // Checking for peek can't set the overflow flag - bool bOk = CheckGet( nOffset + nSize ); - m_Error &= ~GET_OVERFLOW; - return bOk; -} - - -//----------------------------------------------------------------------------- -// Call this to peek arbitrarily long into memory. It doesn't fail unless -// it can't read *anything* new -//----------------------------------------------------------------------------- -bool CUtlBuffer::CheckArbitraryPeekGet( int nOffset, int &nIncrement ) -{ - if ( TellGet() + nOffset >= TellMaxPut() ) - { - nIncrement = 0; - return false; - } - - if ( TellGet() + nOffset + nIncrement > TellMaxPut() ) - { - nIncrement = TellMaxPut() - TellGet() - nOffset; - } - - // NOTE: CheckPeekGet could modify TellMaxPut for streaming files - // We have to call TellMaxPut again here - CheckPeekGet( nOffset, nIncrement ); - int nMaxGet = TellMaxPut() - TellGet(); - if ( nMaxGet < nIncrement ) - { - nIncrement = nMaxGet; - } - return (nIncrement != 0); -} - - -//----------------------------------------------------------------------------- -// Peek part of the butt -//----------------------------------------------------------------------------- -const void* CUtlBuffer::PeekGet( int nMaxSize, int nOffset ) -{ - if ( !CheckPeekGet( nOffset, nMaxSize ) ) - return NULL; - return &m_Memory[ m_Get + nOffset - m_nOffset ]; -} - - -//----------------------------------------------------------------------------- -// Change where I'm reading -//----------------------------------------------------------------------------- -void CUtlBuffer::SeekGet( SeekType_t type, int offset ) -{ - switch( type ) - { - case SEEK_HEAD: - m_Get = offset; - break; - - case SEEK_CURRENT: - m_Get += offset; - break; - - case SEEK_TAIL: - m_Get = m_nMaxPut - offset; - break; - } - - if ( m_Get > m_nMaxPut ) - { - m_Error |= GET_OVERFLOW; - } - else - { - m_Error &= ~GET_OVERFLOW; - if ( m_Get < m_nOffset || m_Get >= m_nOffset + Size() ) - { - OnGetOverflow( -1 ); - } - } -} - - -//----------------------------------------------------------------------------- -// Parse... -//----------------------------------------------------------------------------- - -#pragma warning ( disable : 4706 ) - -int CUtlBuffer::VaScanf( const char* pFmt, va_list list ) -{ - Assert( pFmt ); - if ( m_Error || !IsText() ) - return 0; - - int numScanned = 0; - int nLength; - char c; - char* pEnd; - while ( c = *pFmt++ ) - { - // Stop if we hit the end of the buffer - if ( m_Get >= TellMaxPut() ) - { - m_Error |= GET_OVERFLOW; - break; - } - - switch (c) - { - case ' ': - // eat all whitespace - EatWhiteSpace(); - break; - - case '%': - { - // Conversion character... try to convert baby! - char type = *pFmt++; - if (type == 0) - return numScanned; - - switch(type) - { - case 'c': - { - char* ch = va_arg( list, char * ); - if ( CheckPeekGet( 0, sizeof(char) ) ) - { - *ch = *(const char*)PeekGet(); - ++m_Get; - } - else - { - *ch = 0; - return numScanned; - } - } - break; - - case 'i': - case 'd': - { - int* i = va_arg( list, int * ); - - // NOTE: This is not bullet-proof; it assumes numbers are < 128 characters - nLength = 128; - if ( !CheckArbitraryPeekGet( 0, nLength ) ) - { - *i = 0; - return numScanned; - } - - *i = strtol( (char*)PeekGet(), &pEnd, 10 ); - int nBytesRead = (int)( pEnd - (char*)PeekGet() ); - if ( nBytesRead == 0 ) - return numScanned; - m_Get += nBytesRead; - } - break; - - case 'x': - { - int* i = va_arg( list, int * ); - - // NOTE: This is not bullet-proof; it assumes numbers are < 128 characters - nLength = 128; - if ( !CheckArbitraryPeekGet( 0, nLength ) ) - { - *i = 0; - return numScanned; - } - - *i = strtol( (char*)PeekGet(), &pEnd, 16 ); - int nBytesRead = (int)( pEnd - (char*)PeekGet() ); - if ( nBytesRead == 0 ) - return numScanned; - m_Get += nBytesRead; - } - break; - - case 'u': - { - unsigned int* u = va_arg( list, unsigned int *); - - // NOTE: This is not bullet-proof; it assumes numbers are < 128 characters - nLength = 128; - if ( !CheckArbitraryPeekGet( 0, nLength ) ) - { - *u = 0; - return numScanned; - } - - *u = strtoul( (char*)PeekGet(), &pEnd, 10 ); - int nBytesRead = (int)( pEnd - (char*)PeekGet() ); - if ( nBytesRead == 0 ) - return numScanned; - m_Get += nBytesRead; - } - break; - - case 'f': - { - float* f = va_arg( list, float *); - - // NOTE: This is not bullet-proof; it assumes numbers are < 128 characters - nLength = 128; - if ( !CheckArbitraryPeekGet( 0, nLength ) ) - { - *f = 0.0f; - return numScanned; - } - - *f = (float)strtod( (char*)PeekGet(), &pEnd ); - int nBytesRead = (int)( pEnd - (char*)PeekGet() ); - if ( nBytesRead == 0 ) - return numScanned; - m_Get += nBytesRead; - } - break; - - case 's': - { - char* s = va_arg( list, char * ); - GetString( s ); - } - break; - - default: - { - // unimplemented scanf type - Assert(0); - return numScanned; - } - break; - } - - ++numScanned; - } - break; - - default: - { - // Here we have to match the format string character - // against what's in the buffer or we're done. - if ( !CheckPeekGet( 0, sizeof(char) ) ) - return numScanned; - - if ( c != *(const char*)PeekGet() ) - return numScanned; - - ++m_Get; - } - } - } - return numScanned; -} - -#pragma warning ( default : 4706 ) - -int CUtlBuffer::Scanf( const char* pFmt, ... ) -{ - va_list args; - - va_start( args, pFmt ); - int count = VaScanf( pFmt, args ); - va_end( args ); - - return count; -} - - -//----------------------------------------------------------------------------- -// Advance the get index until after the particular string is found -// Do not eat whitespace before starting. Return false if it failed -//----------------------------------------------------------------------------- -bool CUtlBuffer::GetToken( const char *pToken ) -{ - Assert( pToken ); - - // Look for the token - int nLen = Q_strlen( pToken ); - - int nSizeToCheck = Size() - TellGet() - m_nOffset; - - int nGet = TellGet(); - do - { - int nMaxSize = TellMaxPut() - TellGet(); - if ( nMaxSize < nSizeToCheck ) - { - nSizeToCheck = nMaxSize; - } - if ( nLen > nSizeToCheck ) - break; - - if ( !CheckPeekGet( 0, nSizeToCheck ) ) - break; - - const char *pBufStart = (const char*)PeekGet(); - const char *pFoundEnd = Q_strnistr( pBufStart, pToken, nSizeToCheck ); - if ( pFoundEnd ) - { - size_t nOffset = (size_t)pFoundEnd - (size_t)pBufStart; - SeekGet( CUtlBuffer::SEEK_CURRENT, nOffset + nLen ); - return true; - } - - SeekGet( CUtlBuffer::SEEK_CURRENT, nSizeToCheck - nLen - 1 ); - nSizeToCheck = Size() - (nLen-1); - - } while ( true ); - - SeekGet( CUtlBuffer::SEEK_HEAD, nGet ); - return false; -} - - -//----------------------------------------------------------------------------- -// (For text buffers only) -// Parse a token from the buffer: -// Grab all text that lies between a starting delimiter + ending delimiter -// (skipping whitespace that leads + trails both delimiters). -// Note the delimiter checks are case-insensitive. -// If successful, the get index is advanced and the function returns true, -// otherwise the index is not advanced and the function returns false. -//----------------------------------------------------------------------------- -bool CUtlBuffer::ParseToken( const char *pStartingDelim, const char *pEndingDelim, char* pString, int nMaxLen ) -{ - int nCharsToCopy = 0; - int nCurrentGet = 0; - - size_t nEndingDelimLen; - - // Starting delimiter is optional - char emptyBuf = '\0'; - if ( !pStartingDelim ) - { - pStartingDelim = &emptyBuf; - } - - // Ending delimiter is not - Assert( pEndingDelim && pEndingDelim[0] ); - nEndingDelimLen = Q_strlen( pEndingDelim ); - - int nStartGet = TellGet(); - char nCurrChar; - int nTokenStart = -1; - EatWhiteSpace( ); - while ( *pStartingDelim ) - { - nCurrChar = *pStartingDelim++; - if ( !isspace((unsigned char)nCurrChar) ) - { - if ( tolower( GetChar() ) != tolower( nCurrChar ) ) - goto parseFailed; - } - else - { - EatWhiteSpace(); - } - } - - EatWhiteSpace(); - nTokenStart = TellGet(); - if ( !GetToken( pEndingDelim ) ) - goto parseFailed; - - nCurrentGet = TellGet(); - nCharsToCopy = (nCurrentGet - nEndingDelimLen) - nTokenStart; - if ( nCharsToCopy >= nMaxLen ) - { - nCharsToCopy = nMaxLen - 1; - } - - if ( nCharsToCopy > 0 ) - { - SeekGet( CUtlBuffer::SEEK_HEAD, nTokenStart ); - Get( pString, nCharsToCopy ); - if ( !IsValid() ) - goto parseFailed; - - // Eat trailing whitespace - for ( ; nCharsToCopy > 0; --nCharsToCopy ) - { - if ( !isspace( (unsigned char)pString[ nCharsToCopy-1 ] ) ) - break; - } - } - pString[ nCharsToCopy ] = '\0'; - - // Advance the Get index - SeekGet( CUtlBuffer::SEEK_HEAD, nCurrentGet ); - return true; - -parseFailed: - // Revert the get index - SeekGet( SEEK_HEAD, nStartGet ); - pString[0] = '\0'; - return false; -} - - -//----------------------------------------------------------------------------- -// Parses the next token, given a set of character breaks to stop at -//----------------------------------------------------------------------------- -int CUtlBuffer::ParseToken( characterset_t *pBreaks, char *pTokenBuf, int nMaxLen, bool bParseComments ) -{ - Assert( nMaxLen > 0 ); - pTokenBuf[0] = 0; - - // skip whitespace + comments - while ( true ) - { - if ( !IsValid() ) - return -1; - EatWhiteSpace(); - if ( bParseComments ) - { - if ( !EatCPPComment() ) - break; - } - else - { - break; - } - } - - char c = GetChar(); - - // End of buffer - if ( c == 0 ) - return -1; - - // handle quoted strings specially - if ( c == '\"' ) - { - int nLen = 0; - while( IsValid() ) - { - c = GetChar(); - if ( c == '\"' || !c ) - { - pTokenBuf[nLen] = 0; - return nLen; - } - pTokenBuf[nLen] = c; - if ( ++nLen == nMaxLen ) - { - pTokenBuf[nLen-1] = 0; - return nMaxLen; - } - } - - // In this case, we hit the end of the buffer before hitting the end qoute - pTokenBuf[nLen] = 0; - return nLen; - } - - // parse single characters - if ( IN_CHARACTERSET( *pBreaks, c ) ) - { - pTokenBuf[0] = c; - pTokenBuf[1] = 0; - return 1; - } - - // parse a regular word - int nLen = 0; - while ( true ) - { - pTokenBuf[nLen] = c; - if ( ++nLen == nMaxLen ) - { - pTokenBuf[nLen-1] = 0; - return nMaxLen; - } - c = GetChar(); - if ( !IsValid() ) - break; - - if ( IN_CHARACTERSET( *pBreaks, c ) || c == '\"' || c <= ' ' ) - { - SeekGet( SEEK_CURRENT, -1 ); - break; - } - } - - pTokenBuf[nLen] = 0; - return nLen; -} - - - -//----------------------------------------------------------------------------- -// Serialization -//----------------------------------------------------------------------------- -void CUtlBuffer::Put( const void *pMem, int size ) -{ - if ( size && CheckPut( size ) ) - { - memcpy( &m_Memory[m_Put - m_nOffset], pMem, size ); - m_Put += size; - - AddNullTermination(); - } -} - - -//----------------------------------------------------------------------------- -// Writes a null-terminated string -//----------------------------------------------------------------------------- -void CUtlBuffer::PutString( const char* pString ) -{ - if (!IsText()) - { - if ( pString ) - { - // Not text? append a null at the end. - size_t nLen = Q_strlen( pString ) + 1; - Put( pString, nLen * sizeof(char) ); - return; - } - else - { - PutTypeBin( 0 ); - } - } - else if (pString) - { - int nTabCount = ( m_Flags & AUTO_TABS_DISABLED ) ? 0 : m_nTab; - if ( nTabCount > 0 ) - { - if ( WasLastCharacterCR() ) - { - PutTabs(); - } - - const char* pEndl = strchr( pString, '\n' ); - while ( pEndl ) - { - size_t nSize = (size_t)pEndl - (size_t)pString + sizeof(char); - Put( pString, nSize ); - pString = pEndl + 1; - if ( *pString ) - { - PutTabs(); - pEndl = strchr( pString, '\n' ); - } - else - { - pEndl = NULL; - } - } - } - size_t nLen = Q_strlen( pString ); - if ( nLen ) - { - Put( pString, nLen * sizeof(char) ); - } - } -} - - -//----------------------------------------------------------------------------- -// This version of PutString converts \ to \\ and " to \", etc. -// It also places " at the beginning and end of the string -//----------------------------------------------------------------------------- -inline void CUtlBuffer::PutDelimitedCharInternal( CUtlCharConversion *pConv, char c ) -{ - int l = pConv->GetConversionLength( c ); - if ( l == 0 ) - { - PutChar( c ); - } - else - { - PutChar( pConv->GetEscapeChar() ); - Put( pConv->GetConversionString( c ), l ); - } -} - -void CUtlBuffer::PutDelimitedChar( CUtlCharConversion *pConv, char c ) -{ - if ( !IsText() || !pConv ) - { - PutChar( c ); - return; - } - - PutDelimitedCharInternal( pConv, c ); -} - -void CUtlBuffer::PutDelimitedString( CUtlCharConversion *pConv, const char *pString ) -{ - if ( !IsText() || !pConv ) - { - PutString( pString ); - return; - } - - if ( WasLastCharacterCR() ) - { - PutTabs(); - } - Put( pConv->GetDelimiter(), pConv->GetDelimiterLength() ); - - int nLen = pString ? Q_strlen( pString ) : 0; - for ( int i = 0; i < nLen; ++i ) - { - PutDelimitedCharInternal( pConv, pString[i] ); - } - - if ( WasLastCharacterCR() ) - { - PutTabs(); - } - Put( pConv->GetDelimiter(), pConv->GetDelimiterLength() ); -} - - -void CUtlBuffer::VaPrintf( const char* pFmt, va_list list ) -{ - char temp[2048]; -#ifdef _DEBUG - int nLen = -#endif - Q_vsnprintf( temp, sizeof( temp ), pFmt, list ); - Assert( nLen < 2048 ); - PutString( temp ); -} - -void CUtlBuffer::Printf( const char* pFmt, ... ) -{ - va_list args; - - va_start( args, pFmt ); - VaPrintf( pFmt, args ); - va_end( args ); -} - - -//----------------------------------------------------------------------------- -// Calls the overflow functions -//----------------------------------------------------------------------------- -void CUtlBuffer::SetOverflowFuncs( UtlBufferOverflowFunc_t getFunc, UtlBufferOverflowFunc_t putFunc ) -{ - m_GetOverflowFunc = getFunc; - m_PutOverflowFunc = putFunc; -} - - -//----------------------------------------------------------------------------- -// Calls the overflow functions -//----------------------------------------------------------------------------- -bool CUtlBuffer::OnPutOverflow( int nSize ) -{ - return (this->*m_PutOverflowFunc)( nSize ); -} - -bool CUtlBuffer::OnGetOverflow( int nSize ) -{ - return (this->*m_GetOverflowFunc)( nSize ); -} - - -//----------------------------------------------------------------------------- -// Checks if a put is ok -//----------------------------------------------------------------------------- -bool CUtlBuffer::PutOverflow( int nSize ) -{ - if ( m_Memory.IsExternallyAllocated() ) - { - if ( !IsGrowable() ) - return false; - - m_Memory.ConvertToGrowableMemory( 0 ); - } - - while( Size() < m_Put - m_nOffset + nSize ) - { - m_Memory.Grow(); - } - - return true; -} - -bool CUtlBuffer::GetOverflow( int nSize ) -{ - return false; -} - - -//----------------------------------------------------------------------------- -// Checks if a put is ok -//----------------------------------------------------------------------------- -bool CUtlBuffer::CheckPut( int nSize ) -{ - if ( ( m_Error & PUT_OVERFLOW ) || IsReadOnly() ) - return false; - - if ( ( m_Put < m_nOffset ) || ( m_Memory.NumAllocated() < m_Put - m_nOffset + nSize ) ) - { - if ( !OnPutOverflow( nSize ) ) - { - m_Error |= PUT_OVERFLOW; - return false; - } - } - return true; -} - -void CUtlBuffer::SeekPut( SeekType_t type, int offset ) -{ - int nNextPut = m_Put; - switch( type ) - { - case SEEK_HEAD: - nNextPut = offset; - break; - - case SEEK_CURRENT: - nNextPut += offset; - break; - - case SEEK_TAIL: - nNextPut = m_nMaxPut - offset; - break; - } - - // Force a write of the data - // FIXME: We could make this more optimal potentially by writing out - // the entire buffer if you seek outside the current range - - // NOTE: This call will write and will also seek the file to nNextPut. - OnPutOverflow( -nNextPut-1 ); - m_Put = nNextPut; - - AddNullTermination(); -} - - -void CUtlBuffer::ActivateByteSwapping( bool bActivate ) -{ - m_Byteswap.ActivateByteSwapping( bActivate ); -} - -void CUtlBuffer::SetBigEndian( bool bigEndian ) -{ - m_Byteswap.SetTargetBigEndian( bigEndian ); -} - -bool CUtlBuffer::IsBigEndian( void ) -{ - return m_Byteswap.IsTargetBigEndian(); -} - - -//----------------------------------------------------------------------------- -// null terminate the buffer -//----------------------------------------------------------------------------- -void CUtlBuffer::AddNullTermination( void ) -{ - if ( m_Put > m_nMaxPut ) - { - if ( !IsReadOnly() && ((m_Error & PUT_OVERFLOW) == 0) ) - { - // Add null termination value - if ( CheckPut( 1 ) ) - { - m_Memory[m_Put - m_nOffset] = 0; - } - else - { - // Restore the overflow state, it was valid before... - m_Error &= ~PUT_OVERFLOW; - } - } - m_nMaxPut = m_Put; - } -} - - -//----------------------------------------------------------------------------- -// Converts a buffer from a CRLF buffer to a CR buffer (and back) -// Returns false if no conversion was necessary (and outBuf is left untouched) -// If the conversion occurs, outBuf will be cleared. -//----------------------------------------------------------------------------- -bool CUtlBuffer::ConvertCRLF( CUtlBuffer &outBuf ) -{ - if ( !IsText() || !outBuf.IsText() ) - return false; - - if ( ContainsCRLF() == outBuf.ContainsCRLF() ) - return false; - - int nInCount = TellMaxPut(); - - outBuf.Purge(); - outBuf.EnsureCapacity( nInCount ); - - bool bFromCRLF = ContainsCRLF(); - - // Start reading from the beginning - int nGet = TellGet(); - int nPut = TellPut(); - int nGetDelta = 0; - int nPutDelta = 0; - - const char *pBase = (const char*)Base(); - int nCurrGet = 0; - while ( nCurrGet < nInCount ) - { - const char *pCurr = &pBase[nCurrGet]; - if ( bFromCRLF ) - { - const char *pNext = Q_strnistr( pCurr, "\r\n", nInCount - nCurrGet ); - if ( !pNext ) - { - outBuf.Put( pCurr, nInCount - nCurrGet ); - break; - } - - int nBytes = (size_t)pNext - (size_t)pCurr; - outBuf.Put( pCurr, nBytes ); - outBuf.PutChar( '\n' ); - nCurrGet += nBytes + 2; - if ( nGet >= nCurrGet - 1 ) - { - --nGetDelta; - } - if ( nPut >= nCurrGet - 1 ) - { - --nPutDelta; - } - } - else - { - const char *pNext = Q_strnchr( pCurr, '\n', nInCount - nCurrGet ); - if ( !pNext ) - { - outBuf.Put( pCurr, nInCount - nCurrGet ); - break; - } - - int nBytes = (size_t)pNext - (size_t)pCurr; - outBuf.Put( pCurr, nBytes ); - outBuf.PutChar( '\r' ); - outBuf.PutChar( '\n' ); - nCurrGet += nBytes + 1; - if ( nGet >= nCurrGet ) - { - ++nGetDelta; - } - if ( nPut >= nCurrGet ) - { - ++nPutDelta; - } - } - } - - Assert( nPut + nPutDelta <= outBuf.TellMaxPut() ); - - outBuf.SeekGet( SEEK_HEAD, nGet + nGetDelta ); - outBuf.SeekPut( SEEK_HEAD, nPut + nPutDelta ); - - return true; -} - - -//--------------------------------------------------------------------------- -// Implementation of CUtlInplaceBuffer -//--------------------------------------------------------------------------- - -CUtlInplaceBuffer::CUtlInplaceBuffer( int growSize /* = 0 */, int initSize /* = 0 */, int nFlags /* = 0 */ ) : - CUtlBuffer( growSize, initSize, nFlags ) -{ - NULL; -} - -bool CUtlInplaceBuffer::InplaceGetLinePtr( char **ppszInBufferPtr, int *pnLineLength ) -{ - Assert( IsText() && !ContainsCRLF() ); - - int nLineLen = PeekLineLength(); - if ( nLineLen <= 1 ) - { - SeekGet( SEEK_TAIL, 0 ); - return false; - } - - -- nLineLen; // because it accounts for putting a terminating null-character - - char *pszLine = ( char * ) const_cast< void * >( PeekGet() ); - SeekGet( SEEK_CURRENT, nLineLen ); - - // Set the out args - if ( ppszInBufferPtr ) - *ppszInBufferPtr = pszLine; - - if ( pnLineLength ) - *pnLineLength = nLineLen; - - return true; -} - -char * CUtlInplaceBuffer::InplaceGetLinePtr( void ) -{ - char *pszLine = NULL; - int nLineLen = 0; - - if ( InplaceGetLinePtr( &pszLine, &nLineLen ) ) - { - Assert( nLineLen >= 1 ); - - switch ( pszLine[ nLineLen - 1 ] ) - { - case '\n': - case '\r': - pszLine[ nLineLen - 1 ] = 0; - if ( -- nLineLen ) - { - switch ( pszLine[ nLineLen - 1 ] ) - { - case '\n': - case '\r': - pszLine[ nLineLen - 1 ] = 0; - break; - } - } - break; - - default: - Assert( pszLine[ nLineLen ] == 0 ); - break; - } - } - - return pszLine; -} - diff --git a/Resources/NetHook/tier1/utlbuffer.h b/Resources/NetHook/tier1/utlbuffer.h deleted file mode 100644 index 5b423f1a..00000000 --- a/Resources/NetHook/tier1/utlbuffer.h +++ /dev/null @@ -1,1028 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -// Serialization/unserialization buffer -//=============================================================================// - -#ifndef UTLBUFFER_H -#define UTLBUFFER_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier1/utlmemory.h" -#include "tier1/byteswap.h" -#include - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -struct characterset_t; - - -//----------------------------------------------------------------------------- -// Description of character conversions for string output -// Here's an example of how to use the macros to define a character conversion -// BEGIN_CHAR_CONVERSION( CStringConversion, '\\' ) -// { '\n', "n" }, -// { '\t', "t" } -// END_CHAR_CONVERSION( CStringConversion, '\\' ) -//----------------------------------------------------------------------------- -class CUtlCharConversion -{ -public: - struct ConversionArray_t - { - char m_nActualChar; - char *m_pReplacementString; - }; - - CUtlCharConversion( char nEscapeChar, const char *pDelimiter, int nCount, ConversionArray_t *pArray ); - char GetEscapeChar() const; - const char *GetDelimiter() const; - int GetDelimiterLength() const; - - const char *GetConversionString( char c ) const; - int GetConversionLength( char c ) const; - int MaxConversionLength() const; - - // Finds a conversion for the passed-in string, returns length - virtual char FindConversion( const char *pString, int *pLength ); - -protected: - struct ConversionInfo_t - { - int m_nLength; - char *m_pReplacementString; - }; - - char m_nEscapeChar; - const char *m_pDelimiter; - int m_nDelimiterLength; - int m_nCount; - int m_nMaxConversionLength; - char m_pList[255]; - ConversionInfo_t m_pReplacements[255]; -}; - -#define BEGIN_CHAR_CONVERSION( _name, _delimiter, _escapeChar ) \ - static CUtlCharConversion::ConversionArray_t s_pConversionArray ## _name[] = { - -#define END_CHAR_CONVERSION( _name, _delimiter, _escapeChar ) \ - }; \ - CUtlCharConversion _name( _escapeChar, _delimiter, sizeof( s_pConversionArray ## _name ) / sizeof( CUtlCharConversion::ConversionArray_t ), s_pConversionArray ## _name ); - -#define BEGIN_CUSTOM_CHAR_CONVERSION( _className, _name, _delimiter, _escapeChar ) \ - static CUtlCharConversion::ConversionArray_t s_pConversionArray ## _name[] = { - -#define END_CUSTOM_CHAR_CONVERSION( _className, _name, _delimiter, _escapeChar ) \ - }; \ - _className _name( _escapeChar, _delimiter, sizeof( s_pConversionArray ## _name ) / sizeof( CUtlCharConversion::ConversionArray_t ), s_pConversionArray ## _name ); - -//----------------------------------------------------------------------------- -// Character conversions for C strings -//----------------------------------------------------------------------------- -CUtlCharConversion *GetCStringCharConversion(); - -//----------------------------------------------------------------------------- -// Character conversions for quoted strings, with no escape sequences -//----------------------------------------------------------------------------- -CUtlCharConversion *GetNoEscCharConversion(); - - -//----------------------------------------------------------------------------- -// Macro to set overflow functions easily -//----------------------------------------------------------------------------- -#define SetUtlBufferOverflowFuncs( _get, _put ) \ - SetOverflowFuncs( static_cast ( _get ), static_cast ( _put ) ) - - -//----------------------------------------------------------------------------- -// Command parsing.. -//----------------------------------------------------------------------------- -class CUtlBuffer -{ -public: - enum SeekType_t - { - SEEK_HEAD = 0, - SEEK_CURRENT, - SEEK_TAIL - }; - - // flags - enum BufferFlags_t - { - TEXT_BUFFER = 0x1, // Describes how get + put work (as strings, or binary) - EXTERNAL_GROWABLE = 0x2, // This is used w/ external buffers and causes the utlbuf to switch to reallocatable memory if an overflow happens when Putting. - CONTAINS_CRLF = 0x4, // For text buffers only, does this contain \n or \n\r? - READ_ONLY = 0x8, // For external buffers; prevents null termination from happening. - AUTO_TABS_DISABLED = 0x10, // Used to disable/enable push/pop tabs - }; - - // Overflow functions when a get or put overflows - typedef bool (CUtlBuffer::*UtlBufferOverflowFunc_t)( int nSize ); - - // Constructors for growable + external buffers for serialization/unserialization - CUtlBuffer( int growSize = 0, int initSize = 0, int nFlags = 0 ); - CUtlBuffer( const void* pBuffer, int size, int nFlags = 0 ); - // This one isn't actually defined so that we catch contructors that are trying to pass a bool in as the third param. - CUtlBuffer( const void *pBuffer, int size, bool crap ); - - unsigned char GetFlags() const; - - // NOTE: This will assert if you attempt to recast it in a way that - // is not compatible. The only valid conversion is binary-> text w/CRLF - void SetBufferType( bool bIsText, bool bContainsCRLF ); - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ); - - // Attaches the buffer to external memory.... - void SetExternalBuffer( void* pMemory, int nSize, int nInitialPut, int nFlags = 0 ); - bool IsExternallyAllocated() const; - void AssumeMemory( void *pMemory, int nSize, int nInitialPut, int nFlags = 0 ); - - FORCEINLINE void ActivateByteSwappingIfBigEndian( void ) - { - if ( IsX360() ) - ActivateByteSwapping( true ); - } - - - // Controls endian-ness of binary utlbufs - default matches the current platform - void ActivateByteSwapping( bool bActivate ); - void SetBigEndian( bool bigEndian ); - bool IsBigEndian( void ); - - // Resets the buffer; but doesn't free memory - void Clear(); - - // Clears out the buffer; frees memory - void Purge(); - - // Read stuff out. - // Binary mode: it'll just read the bits directly in, and characters will be - // read for strings until a null character is reached. - // Text mode: it'll parse the file, turning text #s into real numbers. - // GetString will read a string until a space is reached - char GetChar( ); - unsigned char GetUnsignedChar( ); - short GetShort( ); - unsigned short GetUnsignedShort( ); - int GetInt( ); - int GetIntHex( ); - unsigned int GetUnsignedInt( ); - float GetFloat( ); - double GetDouble( ); - void GetString( char* pString, int nMaxChars = 0 ); - void Get( void* pMem, int size ); - void GetLine( char* pLine, int nMaxChars = 0 ); - - // Used for getting objects that have a byteswap datadesc defined - template void GetObjects( T *dest, int count = 1 ); - - // This will get at least 1 byte and up to nSize bytes. - // It will return the number of bytes actually read. - int GetUpTo( void *pMem, int nSize ); - - // This version of GetString converts \" to \\ and " to \, etc. - // It also reads a " at the beginning and end of the string - void GetDelimitedString( CUtlCharConversion *pConv, char *pString, int nMaxChars = 0 ); - char GetDelimitedChar( CUtlCharConversion *pConv ); - - // This will return the # of characters of the string about to be read out - // NOTE: The count will *include* the terminating 0!! - // In binary mode, it's the number of characters until the next 0 - // In text mode, it's the number of characters until the next space. - int PeekStringLength(); - - // This version of PeekStringLength converts \" to \\ and " to \, etc. - // It also reads a " at the beginning and end of the string - // NOTE: The count will *include* the terminating 0!! - // In binary mode, it's the number of characters until the next 0 - // In text mode, it's the number of characters between "s (checking for \") - // Specifying false for bActualSize will return the pre-translated number of characters - // including the delimiters and the escape characters. So, \n counts as 2 characters when bActualSize == false - // and only 1 character when bActualSize == true - int PeekDelimitedStringLength( CUtlCharConversion *pConv, bool bActualSize = true ); - - // Just like scanf, but doesn't work in binary mode - int Scanf( const char* pFmt, ... ); - int VaScanf( const char* pFmt, va_list list ); - - // Eats white space, advances Get index - void EatWhiteSpace(); - - // Eats C++ style comments - bool EatCPPComment(); - - // (For text buffers only) - // Parse a token from the buffer: - // Grab all text that lies between a starting delimiter + ending delimiter - // (skipping whitespace that leads + trails both delimiters). - // If successful, the get index is advanced and the function returns true, - // otherwise the index is not advanced and the function returns false. - bool ParseToken( const char *pStartingDelim, const char *pEndingDelim, char* pString, int nMaxLen ); - - // Advance the get index until after the particular string is found - // Do not eat whitespace before starting. Return false if it failed - // String test is case-insensitive. - bool GetToken( const char *pToken ); - - // Parses the next token, given a set of character breaks to stop at - // Returns the length of the token parsed in bytes (-1 if none parsed) - int ParseToken( characterset_t *pBreaks, char *pTokenBuf, int nMaxLen, bool bParseComments = true ); - - // Write stuff in - // Binary mode: it'll just write the bits directly in, and strings will be - // written with a null terminating character - // Text mode: it'll convert the numbers to text versions - // PutString will not write a terminating character - void PutChar( char c ); - void PutUnsignedChar( unsigned char uc ); - void PutShort( short s ); - void PutUnsignedShort( unsigned short us ); - void PutInt( int i ); - void PutUnsignedInt( unsigned int u ); - void PutFloat( float f ); - void PutDouble( double d ); - void PutString( const char* pString ); - void Put( const void* pMem, int size ); - - // Used for putting objects that have a byteswap datadesc defined - template void PutObjects( T *src, int count = 1 ); - - // This version of PutString converts \ to \\ and " to \", etc. - // It also places " at the beginning and end of the string - void PutDelimitedString( CUtlCharConversion *pConv, const char *pString ); - void PutDelimitedChar( CUtlCharConversion *pConv, char c ); - - // Just like printf, writes a terminating zero in binary mode - void Printf( const char* pFmt, ... ); - void VaPrintf( const char* pFmt, va_list list ); - - // What am I writing (put)/reading (get)? - void* PeekPut( int offset = 0 ); - const void* PeekGet( int offset = 0 ) const; - const void* PeekGet( int nMaxSize, int nOffset ); - - // Where am I writing (put)/reading (get)? - int TellPut( ) const; - int TellGet( ) const; - - // What's the most I've ever written? - int TellMaxPut( ) const; - - // How many bytes remain to be read? - // NOTE: This is not accurate for streaming text files; it overshoots - int GetBytesRemaining() const; - - // Change where I'm writing (put)/reading (get) - void SeekPut( SeekType_t type, int offset ); - void SeekGet( SeekType_t type, int offset ); - - // Buffer base - const void* Base() const; - void* Base(); - - // memory allocation size, does *not* reflect size written or read, - // use TellPut or TellGet for that - int Size() const; - - // Am I a text buffer? - bool IsText() const; - - // Can I grow if I'm externally allocated? - bool IsGrowable() const; - - // Am I valid? (overflow or underflow error), Once invalid it stays invalid - bool IsValid() const; - - // Do I contain carriage return/linefeeds? - bool ContainsCRLF() const; - - // Am I read-only - bool IsReadOnly() const; - - // Converts a buffer from a CRLF buffer to a CR buffer (and back) - // Returns false if no conversion was necessary (and outBuf is left untouched) - // If the conversion occurs, outBuf will be cleared. - bool ConvertCRLF( CUtlBuffer &outBuf ); - - // Push/pop pretty-printing tabs - void PushTab(); - void PopTab(); - - // Temporarily disables pretty print - void EnableTabs( bool bEnable ); - -protected: - // error flags - enum - { - PUT_OVERFLOW = 0x1, - GET_OVERFLOW = 0x2, - MAX_ERROR_FLAG = GET_OVERFLOW, - }; - - void SetOverflowFuncs( UtlBufferOverflowFunc_t getFunc, UtlBufferOverflowFunc_t putFunc ); - - bool OnPutOverflow( int nSize ); - bool OnGetOverflow( int nSize ); - -protected: - // Checks if a get/put is ok - bool CheckPut( int size ); - bool CheckGet( int size ); - - void AddNullTermination( ); - - // Methods to help with pretty-printing - bool WasLastCharacterCR(); - void PutTabs(); - - // Help with delimited stuff - char GetDelimitedCharInternal( CUtlCharConversion *pConv ); - void PutDelimitedCharInternal( CUtlCharConversion *pConv, char c ); - - // Default overflow funcs - bool PutOverflow( int nSize ); - bool GetOverflow( int nSize ); - - // Does the next bytes of the buffer match a pattern? - bool PeekStringMatch( int nOffset, const char *pString, int nLen ); - - // Peek size of line to come, check memory bound - int PeekLineLength(); - - // How much whitespace should I skip? - int PeekWhiteSpace( int nOffset ); - - // Checks if a peek get is ok - bool CheckPeekGet( int nOffset, int nSize ); - - // Call this to peek arbitrarily long into memory. It doesn't fail unless - // it can't read *anything* new - bool CheckArbitraryPeekGet( int nOffset, int &nIncrement ); - - template void GetType( T& dest, const char *pszFmt ); - template void GetTypeBin( T& dest ); - template void GetObject( T *src ); - - template void PutType( T src, const char *pszFmt ); - template void PutTypeBin( T src ); - template void PutObject( T *src ); - - CUtlMemory m_Memory; - int m_Get; - int m_Put; - - unsigned char m_Error; - unsigned char m_Flags; - unsigned char m_Reserved; -#if defined( _X360 ) - unsigned char pad; -#endif - - int m_nTab; - int m_nMaxPut; - int m_nOffset; - - UtlBufferOverflowFunc_t m_GetOverflowFunc; - UtlBufferOverflowFunc_t m_PutOverflowFunc; - - CByteswap m_Byteswap; -}; - - -// Stream style output operators for CUtlBuffer -inline CUtlBuffer &operator<<( CUtlBuffer &b, char v ) -{ - b.PutChar( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, unsigned char v ) -{ - b.PutUnsignedChar( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, short v ) -{ - b.PutShort( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, unsigned short v ) -{ - b.PutUnsignedShort( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, int v ) -{ - b.PutInt( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, unsigned int v ) -{ - b.PutUnsignedInt( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, float v ) -{ - b.PutFloat( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, double v ) -{ - b.PutDouble( v ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, const char *pv ) -{ - b.PutString( pv ); - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, const Vector &v ) -{ - b << v.x << " " << v.y << " " << v.z; - return b; -} - -inline CUtlBuffer &operator<<( CUtlBuffer &b, const Vector2D &v ) -{ - b << v.x << " " << v.y; - return b; -} - - -class CUtlInplaceBuffer : public CUtlBuffer -{ -public: - CUtlInplaceBuffer( int growSize = 0, int initSize = 0, int nFlags = 0 ); - - // - // Routines returning buffer-inplace-pointers - // -public: - // - // Upon success, determines the line length, fills out the pointer to the - // beginning of the line and the line length, advances the "get" pointer - // offset by the line length and returns "true". - // - // If end of file is reached or upon error returns "false". - // - // Note: the returned length of the line is at least one character because the - // trailing newline characters are also included as part of the line. - // - // Note: the pointer returned points into the local memory of this buffer, in - // case the buffer gets relocated or destroyed the pointer becomes invalid. - // - // e.g.: ------------- - // - // char *pszLine; - // int nLineLen; - // while ( pUtlInplaceBuffer->InplaceGetLinePtr( &pszLine, &nLineLen ) ) - // { - // ... - // } - // - // ------------- - // - // @param ppszInBufferPtr on return points into this buffer at start of line - // @param pnLineLength on return holds num bytes accessible via (*ppszInBufferPtr) - // - // @returns true if line was successfully read - // false when EOF is reached or error occurs - // - bool InplaceGetLinePtr( /* out */ char **ppszInBufferPtr, /* out */ int *pnLineLength ); - - // - // Determines the line length, advances the "get" pointer offset by the line length, - // replaces the newline character with null-terminator and returns the initial pointer - // to now null-terminated line. - // - // If end of file is reached or upon error returns NULL. - // - // Note: the pointer returned points into the local memory of this buffer, in - // case the buffer gets relocated or destroyed the pointer becomes invalid. - // - // e.g.: ------------- - // - // while ( char *pszLine = pUtlInplaceBuffer->InplaceGetLinePtr() ) - // { - // ... - // } - // - // ------------- - // - // @returns ptr-to-zero-terminated-line if line was successfully read and buffer modified - // NULL when EOF is reached or error occurs - // - char * InplaceGetLinePtr( void ); -}; - - -//----------------------------------------------------------------------------- -// Where am I reading? -//----------------------------------------------------------------------------- -inline int CUtlBuffer::TellGet( ) const -{ - return m_Get; -} - - -//----------------------------------------------------------------------------- -// How many bytes remain to be read? -//----------------------------------------------------------------------------- -inline int CUtlBuffer::GetBytesRemaining() const -{ - return m_nMaxPut - TellGet(); -} - - -//----------------------------------------------------------------------------- -// What am I reading? -//----------------------------------------------------------------------------- -inline const void* CUtlBuffer::PeekGet( int offset ) const -{ - return &m_Memory[ m_Get + offset - m_nOffset ]; -} - - -//----------------------------------------------------------------------------- -// Unserialization -//----------------------------------------------------------------------------- - -template -inline void CUtlBuffer::GetObject( T *dest ) -{ - if ( CheckGet( sizeof(T) ) ) - { - if ( !m_Byteswap.IsSwappingBytes() || ( sizeof( T ) == 1 ) ) - { - *dest = *(T *)PeekGet(); - } - else - { - m_Byteswap.SwapFieldsToTargetEndian( dest, (T*)PeekGet() ); - } - m_Get += sizeof(T); - } - else - { - Q_memset( &dest, 0, sizeof(T) ); - } -} - - -template -inline void CUtlBuffer::GetObjects( T *dest, int count ) -{ - for ( int i = 0; i < count; ++i, ++dest ) - { - GetObject( dest ); - } -} - - -template -inline void CUtlBuffer::GetTypeBin( T &dest ) -{ - if ( CheckGet( sizeof(T) ) ) - { - if ( !m_Byteswap.IsSwappingBytes() || ( sizeof( T ) == 1 ) ) - { - dest = *(T *)PeekGet(); - } - else - { - m_Byteswap.SwapBufferToTargetEndian( &dest, (T*)PeekGet() ); - } - m_Get += sizeof(T); - } - else - { - dest = 0; - } -} - -template <> -inline void CUtlBuffer::GetTypeBin< float >( float &dest ) -{ - if ( CheckGet( sizeof( float ) ) ) - { - unsigned int pData = (unsigned int)PeekGet(); - if ( IsX360() && ( pData & 0x03 ) ) - { - // handle unaligned read - ((unsigned char*)&dest)[0] = ((unsigned char*)pData)[0]; - ((unsigned char*)&dest)[1] = ((unsigned char*)pData)[1]; - ((unsigned char*)&dest)[2] = ((unsigned char*)pData)[2]; - ((unsigned char*)&dest)[3] = ((unsigned char*)pData)[3]; - } - else - { - // aligned read - dest = *(float *)pData; - } - if ( m_Byteswap.IsSwappingBytes() ) - { - m_Byteswap.SwapBufferToTargetEndian< float >( &dest, &dest ); - } - m_Get += sizeof( float ); - } - else - { - dest = 0; - } -} - -template -inline void CUtlBuffer::GetType( T &dest, const char *pszFmt ) -{ - if (!IsText()) - { - GetTypeBin( dest ); - } - else - { - dest = 0; - Scanf( pszFmt, &dest ); - } -} - -inline char CUtlBuffer::GetChar( ) -{ - char c; - GetType( c, "%c" ); - return c; -} - -inline unsigned char CUtlBuffer::GetUnsignedChar( ) -{ - unsigned char c; - GetType( c, "%u" ); - return c; -} - -inline short CUtlBuffer::GetShort( ) -{ - short s; - GetType( s, "%d" ); - return s; -} - -inline unsigned short CUtlBuffer::GetUnsignedShort( ) -{ - unsigned short s; - GetType( s, "%u" ); - return s; -} - -inline int CUtlBuffer::GetInt( ) -{ - int i; - GetType( i, "%d" ); - return i; -} - -inline int CUtlBuffer::GetIntHex( ) -{ - int i; - GetType( i, "%x" ); - return i; -} - -inline unsigned int CUtlBuffer::GetUnsignedInt( ) -{ - unsigned int u; - GetType( u, "%u" ); - return u; -} - -inline float CUtlBuffer::GetFloat( ) -{ - float f; - GetType( f, "%f" ); - return f; -} - -inline double CUtlBuffer::GetDouble( ) -{ - double d; - GetType( d, "%f" ); - return d; -} - - -//----------------------------------------------------------------------------- -// Where am I writing? -//----------------------------------------------------------------------------- -inline unsigned char CUtlBuffer::GetFlags() const -{ - return m_Flags; -} - - -//----------------------------------------------------------------------------- -// -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::IsExternallyAllocated() const -{ - return m_Memory.IsExternallyAllocated(); -} - - -//----------------------------------------------------------------------------- -// Where am I writing? -//----------------------------------------------------------------------------- -inline int CUtlBuffer::TellPut( ) const -{ - return m_Put; -} - - -//----------------------------------------------------------------------------- -// What's the most I've ever written? -//----------------------------------------------------------------------------- -inline int CUtlBuffer::TellMaxPut( ) const -{ - return m_nMaxPut; -} - - -//----------------------------------------------------------------------------- -// What am I reading? -//----------------------------------------------------------------------------- -inline void* CUtlBuffer::PeekPut( int offset ) -{ - return &m_Memory[m_Put + offset - m_nOffset]; -} - - -//----------------------------------------------------------------------------- -// Various put methods -//----------------------------------------------------------------------------- - -template -inline void CUtlBuffer::PutObject( T *src ) -{ - if ( CheckPut( sizeof(T) ) ) - { - if ( !m_Byteswap.IsSwappingBytes() || ( sizeof( T ) == 1 ) ) - { - *(T *)PeekPut() = *src; - } - else - { - m_Byteswap.SwapFieldsToTargetEndian( (T*)PeekPut(), src ); - } - m_Put += sizeof(T); - AddNullTermination(); - } -} - - -template -inline void CUtlBuffer::PutObjects( T *src, int count ) -{ - for ( int i = 0; i < count; ++i, ++src ) - { - PutObject( src ); - } -} - - -template -inline void CUtlBuffer::PutTypeBin( T src ) -{ - if ( CheckPut( sizeof(T) ) ) - { - if ( !m_Byteswap.IsSwappingBytes() || ( sizeof( T ) == 1 ) ) - { - *(T *)PeekPut() = src; - } - else - { - m_Byteswap.SwapBufferToTargetEndian( (T*)PeekPut(), &src ); - } - m_Put += sizeof(T); - AddNullTermination(); - } -} - -template -inline void CUtlBuffer::PutType( T src, const char *pszFmt ) -{ - if (!IsText()) - { - PutTypeBin( src ); - } - else - { - Printf( pszFmt, src ); - } -} - -//----------------------------------------------------------------------------- -// Methods to help with pretty-printing -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::WasLastCharacterCR() -{ - if ( !IsText() || (TellPut() == 0) ) - return false; - return ( *( const char * )PeekPut( -1 ) == '\n' ); -} - -inline void CUtlBuffer::PutTabs() -{ - int nTabCount = ( m_Flags & AUTO_TABS_DISABLED ) ? 0 : m_nTab; - for (int i = nTabCount; --i >= 0; ) - { - PutTypeBin( '\t' ); - } -} - - -//----------------------------------------------------------------------------- -// Push/pop pretty-printing tabs -//----------------------------------------------------------------------------- -inline void CUtlBuffer::PushTab( ) -{ - ++m_nTab; -} - -inline void CUtlBuffer::PopTab() -{ - if ( --m_nTab < 0 ) - { - m_nTab = 0; - } -} - - -//----------------------------------------------------------------------------- -// Temporarily disables pretty print -//----------------------------------------------------------------------------- -inline void CUtlBuffer::EnableTabs( bool bEnable ) -{ - if ( bEnable ) - { - m_Flags &= ~AUTO_TABS_DISABLED; - } - else - { - m_Flags |= AUTO_TABS_DISABLED; - } -} - -inline void CUtlBuffer::PutChar( char c ) -{ - if ( WasLastCharacterCR() ) - { - PutTabs(); - } - - PutTypeBin( c ); -} - -inline void CUtlBuffer::PutUnsignedChar( unsigned char c ) -{ - PutType( c, "%u" ); -} - -inline void CUtlBuffer::PutShort( short s ) -{ - PutType( s, "%d" ); -} - -inline void CUtlBuffer::PutUnsignedShort( unsigned short s ) -{ - PutType( s, "%u" ); -} - -inline void CUtlBuffer::PutInt( int i ) -{ - PutType( i, "%d" ); -} - -inline void CUtlBuffer::PutUnsignedInt( unsigned int u ) -{ - PutType( u, "%u" ); -} - -inline void CUtlBuffer::PutFloat( float f ) -{ - PutType( f, "%f" ); -} - -inline void CUtlBuffer::PutDouble( double d ) -{ - PutType( d, "%f" ); -} - - -//----------------------------------------------------------------------------- -// Am I a text buffer? -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::IsText() const -{ - return (m_Flags & TEXT_BUFFER) != 0; -} - - -//----------------------------------------------------------------------------- -// Can I grow if I'm externally allocated? -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::IsGrowable() const -{ - return (m_Flags & EXTERNAL_GROWABLE) != 0; -} - - -//----------------------------------------------------------------------------- -// Am I valid? (overflow or underflow error), Once invalid it stays invalid -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::IsValid() const -{ - return m_Error == 0; -} - - -//----------------------------------------------------------------------------- -// Do I contain carriage return/linefeeds? -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::ContainsCRLF() const -{ - return IsText() && ((m_Flags & CONTAINS_CRLF) != 0); -} - - -//----------------------------------------------------------------------------- -// Am I read-only -//----------------------------------------------------------------------------- -inline bool CUtlBuffer::IsReadOnly() const -{ - return (m_Flags & READ_ONLY) != 0; -} - - -//----------------------------------------------------------------------------- -// Buffer base and size -//----------------------------------------------------------------------------- -inline const void* CUtlBuffer::Base() const -{ - return m_Memory.Base(); -} - -inline void* CUtlBuffer::Base() -{ - return m_Memory.Base(); -} - -inline int CUtlBuffer::Size() const -{ - return m_Memory.NumAllocated(); -} - - -//----------------------------------------------------------------------------- -// Clears out the buffer; frees memory -//----------------------------------------------------------------------------- -inline void CUtlBuffer::Clear() -{ - m_Get = 0; - m_Put = 0; - m_Error = 0; - m_nOffset = 0; - m_nMaxPut = -1; - AddNullTermination(); -} - -inline void CUtlBuffer::Purge() -{ - m_Get = 0; - m_Put = 0; - m_nOffset = 0; - m_nMaxPut = 0; - m_Error = 0; - m_Memory.Purge(); -} - - -#endif // UTLBUFFER_H - diff --git a/Resources/NetHook/tier1/utlbufferutil.cpp b/Resources/NetHook/tier1/utlbufferutil.cpp deleted file mode 100644 index b89ab554..00000000 --- a/Resources/NetHook/tier1/utlbufferutil.cpp +++ /dev/null @@ -1,559 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// $Header: $ -// $NoKeywords: $ -// -// Serialization buffer -//===========================================================================// - -#pragma warning (disable : 4514) - -#include "tier1/utlbufferutil.h" -#include "tier1/utlbuffer.h" -#include "mathlib/vector.h" -#include "mathlib/vector2d.h" -#include "mathlib/vector4d.h" -#include "mathlib/vmatrix.h" -#include "Color.h" -#include -#include -#include -#include -#include -#include "tier1/utlstring.h" -#include "tier1/strtools.h" -#include "tier1/characterset.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - - -//----------------------------------------------------------------------------- -// For serialization, set the delimiter rules -//----------------------------------------------------------------------------- -CUtlCharConversion *s_pConv = NULL; -const char *s_pUtlBufferUtilArrayDelim = NULL; -void SetSerializationDelimiter( CUtlCharConversion *pConv ) -{ - s_pConv = pConv; -} - -void SetSerializationArrayDelimiter( const char *pDelimiter ) -{ - s_pUtlBufferUtilArrayDelim = pDelimiter; -} - - -//----------------------------------------------------------------------------- -// Serialize a floating point number in text mode in a readably friendly fashion -//----------------------------------------------------------------------------- -static void SerializeFloat( CUtlBuffer &buf, float f ) -{ - Assert( buf.IsText() ); - - // FIXME: Print this in a way that we never lose precision - char pTemp[256]; - int nLen = Q_snprintf( pTemp, sizeof(pTemp), "%.10f", f ); - while ( nLen > 0 && pTemp[nLen-1] == '0' ) - { - --nLen; - pTemp[nLen] = 0; - } - if ( nLen > 0 && pTemp[nLen-1] == '.' ) - { - --nLen; - pTemp[nLen] = 0; - } - buf.PutString( pTemp ); -} - -static void SerializeFloats( CUtlBuffer &buf, int nCount, const float *pFloats ) -{ - for ( int i = 0; i < nCount; ++i ) - { - SerializeFloat( buf, pFloats[i] ); - if ( i != nCount-1 ) - { - buf.PutChar( ' ' ); - } - } -} - - -//----------------------------------------------------------------------------- -// Serialization methods for basic types -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const bool &src ) -{ - if ( buf.IsText() ) - { - buf.Printf( "%d", src ); - } - else - { - buf.PutChar( src ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, bool &dest ) -{ - if ( buf.IsText() ) - { - int nValue = 0; - int nRetVal = buf.Scanf( "%d", &nValue ); - dest = ( nValue != 0 ); - return (nRetVal == 1) && buf.IsValid(); - } - - dest = ( buf.GetChar( ) != 0 ); - return buf.IsValid(); -} - - -bool Serialize( CUtlBuffer &buf, const int &src ) -{ - if ( buf.IsText() ) - { - buf.Printf( "%d", src ); - } - else - { - buf.PutInt( src ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, int &dest ) -{ - if ( buf.IsText() ) - { - int nRetVal = buf.Scanf( "%d", &dest ); - return (nRetVal == 1) && buf.IsValid(); - } - - dest = buf.GetInt( ); - return buf.IsValid(); -} - -bool Serialize( CUtlBuffer &buf, const float &src ) -{ - if ( buf.IsText() ) - { - SerializeFloat( buf, src ); - } - else - { - buf.PutFloat( src ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, float &dest ) -{ - if ( buf.IsText() ) - { - // FIXME: Print this in a way that we never lose precision - int nRetVal = buf.Scanf( "%f", &dest ); - return (nRetVal == 1) && buf.IsValid(); - } - - dest = buf.GetFloat( ); - return buf.IsValid(); -} - - -//----------------------------------------------------------------------------- -// Attribute types related to vector math -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const Vector2D &src ) -{ - if ( buf.IsText() ) - { - SerializeFloats( buf, 2, src.Base() ); - } - else - { - buf.PutFloat( src.x ); - buf.PutFloat( src.y ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, Vector2D &dest ) -{ - if ( buf.IsText() ) - { - // FIXME: Print this in a way that we never lose precision - int nRetVal = buf.Scanf( "%f %f", &dest.x, &dest.y ); - return (nRetVal == 2) && buf.IsValid(); - } - - dest.x = buf.GetFloat( ); - dest.y = buf.GetFloat( ); - return buf.IsValid(); -} - -bool Serialize( CUtlBuffer &buf, const Vector &src ) -{ - if ( buf.IsText() ) - { - SerializeFloats( buf, 3, src.Base() ); - } - else - { - buf.PutFloat( src.x ); - buf.PutFloat( src.y ); - buf.PutFloat( src.z ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, Vector &dest ) -{ - if ( buf.IsText() ) - { - // FIXME: Print this in a way that we never lose precision - int nRetVal = buf.Scanf( "%f %f %f", &dest.x, &dest.y, &dest.z ); - return (nRetVal == 3) && buf.IsValid(); - } - - dest.x = buf.GetFloat( ); - dest.y = buf.GetFloat( ); - dest.z = buf.GetFloat( ); - return buf.IsValid(); -} - -bool Serialize( CUtlBuffer &buf, const Vector4D &src ) -{ - if ( buf.IsText() ) - { - SerializeFloats( buf, 4, src.Base() ); - } - else - { - buf.PutFloat( src.x ); - buf.PutFloat( src.y ); - buf.PutFloat( src.z ); - buf.PutFloat( src.w ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, Vector4D &dest ) -{ - if ( buf.IsText() ) - { - // FIXME: Print this in a way that we never lose precision - int nRetVal = buf.Scanf( "%f %f %f %f", &dest.x, &dest.y, &dest.z, &dest.w ); - return (nRetVal == 4) && buf.IsValid(); - } - - dest.x = buf.GetFloat( ); - dest.y = buf.GetFloat( ); - dest.z = buf.GetFloat( ); - dest.w = buf.GetFloat( ); - return buf.IsValid(); -} - -bool Serialize( CUtlBuffer &buf, const QAngle &src ) -{ - if ( buf.IsText() ) - { - SerializeFloats( buf, 3, src.Base() ); - } - else - { - buf.PutFloat( src.x ); - buf.PutFloat( src.y ); - buf.PutFloat( src.z ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, QAngle &dest ) -{ - if ( buf.IsText() ) - { - // FIXME: Print this in a way that we never lose precision - int nRetVal = buf.Scanf( "%f %f %f", &dest.x, &dest.y, &dest.z ); - return (nRetVal == 3) && buf.IsValid(); - } - - dest.x = buf.GetFloat( ); - dest.y = buf.GetFloat( ); - dest.z = buf.GetFloat( ); - return buf.IsValid(); -} - -bool Serialize( CUtlBuffer &buf, const Quaternion &src ) -{ - if ( buf.IsText() ) - { - SerializeFloats( buf, 4, &src.x ); - } - else - { - buf.PutFloat( src.x ); - buf.PutFloat( src.y ); - buf.PutFloat( src.z ); - buf.PutFloat( src.w ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, Quaternion &dest ) -{ - if ( buf.IsText() ) - { - // FIXME: Print this in a way that we never lose precision - int nRetVal = buf.Scanf( "%f %f %f %f", &dest.x, &dest.y, &dest.z, &dest.w ); - return (nRetVal == 4) && buf.IsValid(); - } - - dest.x = buf.GetFloat( ); - dest.y = buf.GetFloat( ); - dest.z = buf.GetFloat( ); - dest.w = buf.GetFloat( ); - return buf.IsValid(); -} - -bool Serialize( CUtlBuffer &buf, const VMatrix &src ) -{ - if ( buf.IsText() ) - { - buf.Printf( "\n" ); - SerializeFloats( buf, 4, src[0] ); - buf.Printf( "\n" ); - SerializeFloats( buf, 4, src[1] ); - buf.Printf( "\n" ); - SerializeFloats( buf, 4, src[2] ); - buf.Printf( "\n" ); - SerializeFloats( buf, 4, src[3] ); - buf.Printf( "\n" ); - } - else - { - buf.Put( &src, sizeof(VMatrix) ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, VMatrix &dest ) -{ - if ( !buf.IsValid() ) - return false; - - if ( buf.IsText() ) - { - int nRetVal = buf.Scanf( "%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f", - &dest[ 0 ][ 0 ], &dest[ 0 ][ 1 ], &dest[ 0 ][ 2 ], &dest[ 0 ][ 3 ], - &dest[ 1 ][ 0 ], &dest[ 1 ][ 1 ], &dest[ 1 ][ 2 ], &dest[ 1 ][ 3 ], - &dest[ 2 ][ 0 ], &dest[ 2 ][ 1 ], &dest[ 2 ][ 2 ], &dest[ 2 ][ 3 ], - &dest[ 3 ][ 0 ], &dest[ 3 ][ 1 ], &dest[ 3 ][ 2 ], &dest[ 3 ][ 3 ] ); - return (nRetVal == 16); - } - - buf.Get( &dest, sizeof(VMatrix) ); - return true; -} - - -//----------------------------------------------------------------------------- -// Color attribute -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const Color &src ) -{ - if ( buf.IsText() ) - { - buf.Printf( "%d %d %d %d", src[0], src[1], src[2], src[3] ); - } - else - { - buf.PutUnsignedChar( src[0] ); - buf.PutUnsignedChar( src[1] ); - buf.PutUnsignedChar( src[2] ); - buf.PutUnsignedChar( src[3] ); - } - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, Color &dest ) -{ - if ( buf.IsText() ) - { - int r = 0, g = 0, b = 0, a = 255; - int nRetVal = buf.Scanf( "%d %d %d %d", &r, &g, &b, &a ); - dest.SetColor( r, g, b, a ); - return (nRetVal == 4) && buf.IsValid(); - } - - dest[0] = buf.GetUnsignedChar( ); - dest[1] = buf.GetUnsignedChar( ); - dest[2] = buf.GetUnsignedChar( ); - dest[3] = buf.GetUnsignedChar( ); - return buf.IsValid(); -} - -/* -//----------------------------------------------------------------------------- -// Object ID attribute -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const DmObjectId_t &src ) -{ - return g_pDataModel->Serialize( buf, src ); -} - -bool Unserialize( CUtlBuffer &buf, DmObjectId_t &dest ) -{ - return g_pDataModel->Unserialize( buf, &dest ); -} -*/ - -//----------------------------------------------------------------------------- -// Binary buffer attribute -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const CUtlBinaryBlock &src ) -{ - int nLength = src.Length(); - if ( !buf.IsText() ) - { - buf.PutInt( nLength ); - if ( nLength != 0 ) - { - buf.Put( src.Get(), nLength ); - } - return buf.IsValid(); - } - - // Writes out uuencoded binaries - for ( int i = 0; i < nLength; ++i ) - { - if ( (i % 40) == 0 ) - { - buf.PutChar( '\n' ); - } - - char b1 = src[i] & 0xF; - char b2 = src[i] >> 4; - - char c1 = ( b1 <= 9 ) ? b1 + '0' : b1 - 10 + 'A'; - char c2 = ( b2 <= 9 ) ? b2 + '0' : b2 - 10 + 'A'; - - buf.PutChar( c2 ); - buf.PutChar( c1 ); - } - - buf.PutChar( '\n' ); - return buf.IsValid(); -} - -static int CountBinaryBytes( CUtlBuffer &buf, int *pEndGet ) -{ - // This counts the number of bytes in the uuencoded text - int nStartGet = buf.TellGet(); - buf.EatWhiteSpace(); - *pEndGet = buf.TellGet(); - int nByteCount = 0; - while ( buf.IsValid() ) - { - char c1 = buf.GetChar(); - char c2 = buf.GetChar(); - - bool bIsNum1 = ( c1 >= '0' ) && ( c1 <= '9' ); - bool bIsNum2 = ( c2 >= '0' ) && ( c2 <= '9' ); - - bool bIsAlpha1 = (( c1 >= 'A' ) && ( c1 <= 'F' )) || (( c1 >= 'a' ) && ( c1 <= 'f' )); - bool bIsAlpha2 = (( c2 >= 'A' ) && ( c2 <= 'F' )) || (( c2 >= 'a' ) && ( c2 <= 'f' )); - - if ( !(bIsNum1 || bIsAlpha1) || !(bIsNum2 || bIsAlpha2) ) - break; - - buf.EatWhiteSpace(); - *pEndGet = buf.TellGet(); - ++nByteCount; - } - buf.SeekGet( CUtlBuffer::SEEK_HEAD, nStartGet ); - return nByteCount; -} - -inline static unsigned char HexCharToInt( int c1 ) -{ - if (( c1 >= '0' ) && ( c1 <= '9' )) - return c1 - '0'; - - if (( c1 >= 'A' ) && ( c1 <= 'F' )) - return 10 + c1 - 'A'; - - if (( c1 >= 'a' ) && ( c1 <= 'f' )) - return 10 + c1 - 'a'; - - return 0xFF; -} - -bool Unserialize( CUtlBuffer &buf, CUtlBinaryBlock &dest ) -{ - if ( !buf.IsText() ) - { - int nLen = buf.GetInt( ); - dest.SetLength( nLen ); - if ( dest.Length() != 0 ) - { - buf.Get( dest.Get(), dest.Length() ); - } - - if ( nLen != dest.Length() ) - { - buf.SeekGet( CUtlBuffer::SEEK_CURRENT, nLen - dest.Length() ); - return false; - } - - return buf.IsValid(); - } - - int nEndGet; - int nByteCount = CountBinaryBytes( buf, &nEndGet ); - if ( nByteCount < 0 ) - return false; - - buf.EatWhiteSpace(); - int nDest = 0; - dest.SetLength( nByteCount ); - while( buf.TellGet() < nEndGet ) - { - char c1 = buf.GetChar(); - char c2 = buf.GetChar(); - - unsigned char b1 = HexCharToInt( c1 ); - unsigned char b2 = HexCharToInt( c2 ); - if ( b1 == 0xFF || b2 == 0xFF ) - return false; - - dest[ nDest++ ] = b2 | ( b1 << 4 ); - buf.EatWhiteSpace(); - } - - return true; -} - - -//----------------------------------------------------------------------------- -// String attribute -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const CUtlString &src ) -{ - buf.PutDelimitedString( s_pConv, src.Get() ); - return buf.IsValid(); -} - -bool Unserialize( CUtlBuffer &buf, CUtlString &dest ) -{ - int nLen = buf.PeekDelimitedStringLength( s_pConv ); - dest.SetLength( nLen - 1 ); // -1 because the length returned includes space for \0 - buf.GetDelimitedString( s_pConv, dest.Get(), nLen ); - return buf.IsValid(); -} - - - - diff --git a/Resources/NetHook/tier1/utlbufferutil.h b/Resources/NetHook/tier1/utlbufferutil.h deleted file mode 100644 index 2c7ca2c7..00000000 --- a/Resources/NetHook/tier1/utlbufferutil.h +++ /dev/null @@ -1,192 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -// Utilities for serialization/unserialization buffer -//=============================================================================// - -#ifndef UTLBUFFERUTIL_H -#define UTLBUFFERUTIL_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier1/utlvector.h" -#include "tier1/utlbuffer.h" - - -//----------------------------------------------------------------------------- -// Forward declarations -//----------------------------------------------------------------------------- -class Vector2D; -class Vector; -class Vector4D; -class QAngle; -class Quaternion; -class VMatrix; -class Color; -class CUtlBinaryBlock; -class CUtlString; -class CUtlCharConversion; - - -//----------------------------------------------------------------------------- -// For string serialization, set the delimiter rules -//----------------------------------------------------------------------------- -void SetSerializationDelimiter( CUtlCharConversion *pConv ); -void SetSerializationArrayDelimiter( const char *pDelimiter ); - - -//----------------------------------------------------------------------------- -// Standard serialization methods for basic types -//----------------------------------------------------------------------------- -bool Serialize( CUtlBuffer &buf, const bool &src ); -bool Unserialize( CUtlBuffer &buf, bool &dest ); - -bool Serialize( CUtlBuffer &buf, const int &src ); -bool Unserialize( CUtlBuffer &buf, int &dest ); - -bool Serialize( CUtlBuffer &buf, const float &src ); -bool Unserialize( CUtlBuffer &buf, float &dest ); - -bool Serialize( CUtlBuffer &buf, const Vector2D &src ); -bool Unserialize( CUtlBuffer &buf, Vector2D &dest ); - -bool Serialize( CUtlBuffer &buf, const Vector &src ); -bool Unserialize( CUtlBuffer &buf, Vector &dest ); - -bool Serialize( CUtlBuffer &buf, const Vector4D &src ); -bool Unserialize( CUtlBuffer &buf, Vector4D &dest ); - -bool Serialize( CUtlBuffer &buf, const QAngle &src ); -bool Unserialize( CUtlBuffer &buf, QAngle &dest ); - -bool Serialize( CUtlBuffer &buf, const Quaternion &src ); -bool Unserialize( CUtlBuffer &buf, Quaternion &dest ); - -bool Serialize( CUtlBuffer &buf, const VMatrix &src ); -bool Unserialize( CUtlBuffer &buf, VMatrix &dest ); - -bool Serialize( CUtlBuffer &buf, const Color &src ); -bool Unserialize( CUtlBuffer &buf, Color &dest ); - -bool Serialize( CUtlBuffer &buf, const CUtlBinaryBlock &src ); -bool Unserialize( CUtlBuffer &buf, CUtlBinaryBlock &dest ); - -bool Serialize( CUtlBuffer &buf, const CUtlString &src ); -bool Unserialize( CUtlBuffer &buf, CUtlString &dest ); - - -//----------------------------------------------------------------------------- -// You can use this to check if a type serializes on multiple lines -//----------------------------------------------------------------------------- -template< class T > -inline bool SerializesOnMultipleLines() -{ - return false; -} - -template< > -inline bool SerializesOnMultipleLines() -{ - return true; -} - -template< > -inline bool SerializesOnMultipleLines() -{ - return true; -} - - -//----------------------------------------------------------------------------- -// Vector serialization -//----------------------------------------------------------------------------- -template< class T > -bool Serialize( CUtlBuffer &buf, const CUtlVector &src ) -{ - extern const char *s_pUtlBufferUtilArrayDelim; - - int nCount = src.Count(); - - if ( !buf.IsText() ) - { - buf.PutInt( nCount ); - for ( int i = 0; i < nCount; ++i ) - { - ::Serialize( buf, src[i] ); - } - return buf.IsValid(); - } - - if ( !SerializesOnMultipleLines() ) - { - buf.PutChar('\n'); - for ( int i = 0; i < nCount; ++i ) - { - ::Serialize( buf, src[i] ); - if ( s_pUtlBufferUtilArrayDelim && (i != nCount-1) ) - { - buf.PutString( s_pUtlBufferUtilArrayDelim ); - } - buf.PutChar('\n'); - } - } - else - { - for ( int i = 0; i < nCount; ++i ) - { - ::Serialize( buf, src[i] ); - if ( s_pUtlBufferUtilArrayDelim && (i != nCount-1) ) - { - buf.PutString( s_pUtlBufferUtilArrayDelim ); - } - buf.PutChar(' '); - } - } - - return buf.IsValid(); -} - -template< class T > -bool Unserialize( CUtlBuffer &buf, CUtlVector &dest ) -{ - dest.RemoveAll(); - - MEM_ALLOC_CREDIT_FUNCTION(); - - if ( !buf.IsText() ) - { - int nCount = buf.GetInt(); - if ( nCount ) - { - dest.EnsureCapacity( nCount ); - for ( int i = 0; i < nCount; ++i ) - { - VerifyEquals( dest.AddToTail(), i ); - if ( !::Unserialize( buf, dest[i] ) ) - return false; - } - } - return buf.IsValid(); - } - - while ( true ) - { - buf.EatWhiteSpace(); - if ( !buf.IsValid() ) - break; - - int i = dest.AddToTail( ); - if ( ! ::Unserialize( buf, dest[i] ) ) - return false; - } - return true; -} - - -#endif // UTLBUFFERUTIL_H - diff --git a/Resources/NetHook/tier1/utldict.h b/Resources/NetHook/tier1/utldict.h deleted file mode 100644 index d6e777d1..00000000 --- a/Resources/NetHook/tier1/utldict.h +++ /dev/null @@ -1,320 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: A dictionary mapping from symbol to structure -// -// $Header: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLDICT_H -#define UTLDICT_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "tier1/utlmap.h" - -// Include this because tons of code was implicitly getting utlsymbol or utlvector via utldict.h -#include "tier1/utlsymbol.h" - -#include "tier0/memdbgon.h" - -enum EDictCompareType -{ - k_eDictCompareTypeCaseSensitive=0, - k_eDictCompareTypeCaseInsensitive=1, - k_eDictCompareTypeFilenames // Slashes and backslashes count as the same character.. -}; - -//----------------------------------------------------------------------------- -// A dictionary mapping from symbol to structure -//----------------------------------------------------------------------------- -template -class CUtlDict -{ -public: - // constructor, destructor - // Left at growSize = 0, the memory will first allocate 1 element and double in size - // at each increment. - CUtlDict( int compareType = k_eDictCompareTypeCaseInsensitive, int growSize = 0, int initSize = 0 ); - ~CUtlDict( ); - - void EnsureCapacity( int ); - - // gets particular elements - T& Element( I i ); - const T& Element( I i ) const; - T& operator[]( I i ); - const T& operator[]( I i ) const; - - // gets element names - char *GetElementName( I i ); - char const *GetElementName( I i ) const; - - void SetElementName( I i, char const *pName ); - - // Number of elements - unsigned int Count() const; - - // Checks if a node is valid and in the tree - bool IsValidIndex( I i ) const; - - // Invalid index - static I InvalidIndex(); - - // Insert method (inserts in order) - I Insert( const char *pName, const T &element ); - I Insert( const char *pName ); - - // Find method - I Find( const char *pName ) const; - - // Remove methods - void RemoveAt( I i ); - void Remove( const char *pName ); - void RemoveAll( ); - - // Purge memory - void Purge(); - void PurgeAndDeleteElements(); // Call delete on each element. - - // Iteration methods - I First() const; - I Next( I i ) const; - -protected: - typedef CUtlMap DictElementMap_t; - DictElementMap_t m_Elements; -}; - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- -template -CUtlDict::CUtlDict( int compareType, int growSize, int initSize ) : m_Elements( growSize, initSize ) -{ - if ( compareType == k_eDictCompareTypeFilenames ) - { - m_Elements.SetLessFunc( CaselessStringLessThanIgnoreSlashes ); - } - else if ( compareType == k_eDictCompareTypeCaseInsensitive ) - { - m_Elements.SetLessFunc( CaselessStringLessThan ); - } - else - { - m_Elements.SetLessFunc( StringLessThan ); - } -} - -template -CUtlDict::~CUtlDict() -{ - Purge(); -} - -template -inline void CUtlDict::EnsureCapacity( int num ) -{ - return m_Elements.EnsureCapacity( num ); -} - -//----------------------------------------------------------------------------- -// gets particular elements -//----------------------------------------------------------------------------- -template -inline T& CUtlDict::Element( I i ) -{ - return m_Elements[i]; -} - -template -inline const T& CUtlDict::Element( I i ) const -{ - return m_Elements[i]; -} - -//----------------------------------------------------------------------------- -// gets element names -//----------------------------------------------------------------------------- -template -inline char *CUtlDict::GetElementName( I i ) -{ - return (char *)m_Elements.Key( i ); -} - -template -inline char const *CUtlDict::GetElementName( I i ) const -{ - return m_Elements.Key( i ); -} - -template -inline T& CUtlDict::operator[]( I i ) -{ - return Element(i); -} - -template -inline const T & CUtlDict::operator[]( I i ) const -{ - return Element(i); -} - -template -inline void CUtlDict::SetElementName( I i, char const *pName ) -{ - MEM_ALLOC_CREDIT_CLASS(); - // TODO: This makes a copy of the old element - // TODO: This relies on the rb tree putting the most recently - // removed element at the head of the insert list - free( (void *)m_Elements.Key( i ) ); - m_Elements.Reinsert( strdup( pName ), i ); -} - -//----------------------------------------------------------------------------- -// Num elements -//----------------------------------------------------------------------------- -template -inline unsigned int CUtlDict::Count() const -{ - return m_Elements.Count(); -} - - -//----------------------------------------------------------------------------- -// Checks if a node is valid and in the tree -//----------------------------------------------------------------------------- -template -inline bool CUtlDict::IsValidIndex( I i ) const -{ - return m_Elements.IsValidIndex(i); -} - - -//----------------------------------------------------------------------------- -// Invalid index -//----------------------------------------------------------------------------- -template -inline I CUtlDict::InvalidIndex() -{ - return DictElementMap_t::InvalidIndex(); -} - - -//----------------------------------------------------------------------------- -// Delete a node from the tree -//----------------------------------------------------------------------------- -template -void CUtlDict::RemoveAt(I elem) -{ - free( (void *)m_Elements.Key( elem ) ); - m_Elements.RemoveAt(elem); -} - - -//----------------------------------------------------------------------------- -// remove a node in the tree -//----------------------------------------------------------------------------- -template void CUtlDict::Remove( const char *search ) -{ - I node = Find( search ); - if (node != InvalidIndex()) - { - RemoveAt(node); - } -} - - -//----------------------------------------------------------------------------- -// Removes all nodes from the tree -//----------------------------------------------------------------------------- -template -void CUtlDict::RemoveAll() -{ - typename DictElementMap_t::IndexType_t index = m_Elements.FirstInorder(); - while ( index != m_Elements.InvalidIndex() ) - { - free( (void *)m_Elements.Key( index ) ); - index = m_Elements.NextInorder( index ); - } - - m_Elements.RemoveAll(); -} - -template -void CUtlDict::Purge() -{ - RemoveAll(); -} - - -template -void CUtlDict::PurgeAndDeleteElements() -{ - // Delete all the elements. - I index = m_Elements.FirstInorder(); - while ( index != m_Elements.InvalidIndex() ) - { - free( (void *)m_Elements.Key( index ) ); - delete m_Elements[index]; - index = m_Elements.NextInorder( index ); - } - - m_Elements.RemoveAll(); -} - - -//----------------------------------------------------------------------------- -// inserts a node into the tree -//----------------------------------------------------------------------------- -template -I CUtlDict::Insert( const char *pName, const T &element ) -{ - MEM_ALLOC_CREDIT_CLASS(); - return m_Elements.Insert( strdup( pName ), element ); -} - -template -I CUtlDict::Insert( const char *pName ) -{ - MEM_ALLOC_CREDIT_CLASS(); - return m_Elements.Insert( strdup( pName ) ); -} - - -//----------------------------------------------------------------------------- -// finds a node in the tree -//----------------------------------------------------------------------------- -template -I CUtlDict::Find( const char *pName ) const -{ - MEM_ALLOC_CREDIT_CLASS(); - if ( pName ) - return m_Elements.Find( pName ); - else - return InvalidIndex(); -} - - -//----------------------------------------------------------------------------- -// Iteration methods -//----------------------------------------------------------------------------- -template -I CUtlDict::First() const -{ - return m_Elements.FirstInorder(); -} - -template -I CUtlDict::Next( I i ) const -{ - return m_Elements.NextInorder(i); -} - -#include "tier0/memdbgoff.h" - -#endif // UTLDICT_H diff --git a/Resources/NetHook/tier1/utlenvelope.h b/Resources/NetHook/tier1/utlenvelope.h deleted file mode 100644 index 58fe0727..00000000 --- a/Resources/NetHook/tier1/utlenvelope.h +++ /dev/null @@ -1,240 +0,0 @@ -//========== Copyright © 2005, Valve Corporation, All rights reserved. ======== -// -// Purpose: A class to wrap data for transport over a boundary like a thread -// or window. -// -//============================================================================= - -#include "tier1/utlstring.h" -#include "tier0/basetypes.h" - -#ifndef UTLENVELOPE_H -#define UTLENVELOPE_H - -#if defined( _WIN32 ) -#pragma once -#endif - -//----------------------------------------------------------------------------- - -class CUtlDataEnvelope -{ -public: - CUtlDataEnvelope( const void *pData, int nBytes ); - CUtlDataEnvelope( const CUtlDataEnvelope &from ); - ~CUtlDataEnvelope(); - - CUtlDataEnvelope &operator=( const CUtlDataEnvelope &from ); - - operator void *(); - operator void *() const; - -private: - void Assign( const void *pData, int nBytes ); - void Assign( const CUtlDataEnvelope &from ); - void Purge(); - - // TODO: switch to a reference counted array? - union - { - byte *m_pData; - byte m_data[4]; - }; - int m_nBytes; -}; - - -//----------------------------------------------------------------------------- - -template -class CUtlEnvelope : protected CUtlDataEnvelope -{ -public: - CUtlEnvelope( const T *pData, int nElems = 1 ); - CUtlEnvelope( const CUtlEnvelope &from ); - - CUtlEnvelope &operator=( const CUtlEnvelope &from ); - - operator T *(); - operator T *() const; - - operator void *(); - operator void *() const; -}; - -//----------------------------------------------------------------------------- - -template <> -class CUtlEnvelope -{ -public: - CUtlEnvelope( const char *pData ) - { - m_string = pData; - } - - CUtlEnvelope( const CUtlEnvelope &from ) - { - m_string = from.m_string; - } - - CUtlEnvelope &operator=( const CUtlEnvelope &from ) - { - m_string = from.m_string; - } - - operator char *() - { - return (char *) m_string.Get(); - } - - operator char *() const - { - return (char *) m_string.Get(); - } - - operator void *() - { - return (void *) m_string.Get(); - } - - operator void *() const - { - return (void *) m_string.Get(); - } - -private: - CUtlString m_string; -}; - -//----------------------------------------------------------------------------- - -#include "tier0/memdbgon.h" - -inline void CUtlDataEnvelope::Assign( const void *pData, int nBytes ) -{ - if ( pData ) - { - m_nBytes = nBytes; - if ( m_nBytes > 4 ) - { - m_pData = new byte[nBytes]; - memcpy( m_pData, pData, nBytes ); - } - else - { - memcpy( m_data, pData, nBytes ); - } - } - else - { - m_pData = NULL; - m_nBytes = 0; - } -} - -inline void CUtlDataEnvelope::Assign( const CUtlDataEnvelope &from ) -{ - Assign( from.operator void *(), from.m_nBytes ); -} - -inline void CUtlDataEnvelope::Purge() -{ - if (m_nBytes > 4) - delete [] m_pData; - m_nBytes = 0; -} - -inline CUtlDataEnvelope::CUtlDataEnvelope( const void *pData, int nBytes ) -{ - Assign( pData, nBytes ); -} - -inline CUtlDataEnvelope::CUtlDataEnvelope( const CUtlDataEnvelope &from ) -{ - Assign( from ); -} - -inline CUtlDataEnvelope::~CUtlDataEnvelope() -{ - Purge(); -} - -inline CUtlDataEnvelope &CUtlDataEnvelope::operator=( const CUtlDataEnvelope &from ) -{ - Purge(); - Assign( from ); - return *this; -} - -inline CUtlDataEnvelope::operator void *() -{ - if ( !m_nBytes ) - { - return NULL; - } - - return ( m_nBytes > 4) ? m_pData : m_data; -} - -inline CUtlDataEnvelope::operator void *() const -{ - if ( !m_nBytes ) - { - return NULL; - } - - return ( m_nBytes > 4) ? (void *)m_pData : (void *)m_data; -} - -//----------------------------------------------------------------------------- - -template -inline CUtlEnvelope::CUtlEnvelope( const T *pData, int nElems = 1 ) - : CUtlDataEnvelope( pData, sizeof(T) * nElems ) -{ -} - -template -inline CUtlEnvelope::CUtlEnvelope( const CUtlEnvelope &from ) - : CUtlDataEnvelope( from ) -{ - -} - -template -inline CUtlEnvelope &CUtlEnvelope::operator=( const CUtlEnvelope &from ) -{ - CUtlDataEnvelope::operator=( from ); - return *this; -} - -template -inline CUtlEnvelope::operator T *() -{ - return (T *)CUtlDataEnvelope::operator void *(); -} - -template -inline CUtlEnvelope::operator T *() const -{ - return (T *)( (const_cast *>(this))->operator T *() ); -} - -template -inline CUtlEnvelope::operator void *() -{ - return CUtlDataEnvelope::operator void *(); -} - -template -inline CUtlEnvelope::operator void *() const -{ - return ( (const_cast *>(this))->operator void *() ); -} - -//----------------------------------------------------------------------------- - -#include "tier0/memdbgoff.h" - -#endif // UTLENVELOPE_H diff --git a/Resources/NetHook/tier1/utlfixedmemory.h b/Resources/NetHook/tier1/utlfixedmemory.h deleted file mode 100644 index 3a05c3ef..00000000 --- a/Resources/NetHook/tier1/utlfixedmemory.h +++ /dev/null @@ -1,356 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -// -// A growable memory class. -//===========================================================================// - -#ifndef UTLFIXEDMEMORY_H -#define UTLFIXEDMEMORY_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "tier0/platform.h" - -#include "tier0/memalloc.h" -#include "tier0/memdbgon.h" - -#pragma warning (disable:4100) -#pragma warning (disable:4514) - -//----------------------------------------------------------------------------- - -#ifdef UTLMEMORY_TRACK -#define UTLMEMORY_TRACK_ALLOC() MemAlloc_RegisterAllocation( "Sum of all UtlFixedMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 ) -#define UTLMEMORY_TRACK_FREE() if ( !m_pMemory ) ; else MemAlloc_RegisterDeallocation( "Sum of all UtlFixedMemory", 0, NumAllocated() * sizeof(T), NumAllocated() * sizeof(T), 0 ) -#else -#define UTLMEMORY_TRACK_ALLOC() ((void)0) -#define UTLMEMORY_TRACK_FREE() ((void)0) -#endif - - -//----------------------------------------------------------------------------- -// The CUtlFixedMemory class: -// A growable memory class that allocates non-sequential blocks, but is indexed sequentially -//----------------------------------------------------------------------------- -template< class T > -class CUtlFixedMemory -{ -public: - // constructor, destructor - CUtlFixedMemory( int nGrowSize = 0, int nInitSize = 0 ); - ~CUtlFixedMemory(); - - // Set the size by which the memory grows - void Init( int nGrowSize = 0, int nInitSize = 0 ); - - // here to match CUtlMemory, but only used by ResetDbgInfo, so it can just return NULL - T* Base() { return NULL; } - const T* Base() const { return NULL; } - -protected: - struct BlockHeader_t; - -public: - class Iterator_t - { - public: - Iterator_t( BlockHeader_t *p, int i ) : m_pBlockHeader( p ), m_nIndex( i ) {} - BlockHeader_t *m_pBlockHeader; - int m_nIndex; - - bool operator==( const Iterator_t it ) const { return m_pBlockHeader == it.m_pBlockHeader && m_nIndex == it.m_nIndex; } - bool operator!=( const Iterator_t it ) const { return m_pBlockHeader != it.m_pBlockHeader || m_nIndex != it.m_nIndex; } - }; - Iterator_t First() const { return m_pBlocks ? Iterator_t( m_pBlocks, 0 ) : InvalidIterator(); } - Iterator_t Next( const Iterator_t &it ) const - { - Assert( IsValidIterator( it ) ); - if ( !IsValidIterator( it ) ) - return InvalidIterator(); - - BlockHeader_t * RESTRICT pHeader = it.m_pBlockHeader; - if ( it.m_nIndex + 1 < pHeader->m_nBlockSize ) - return Iterator_t( pHeader, it.m_nIndex + 1 ); - - return pHeader->m_pNext ? Iterator_t( pHeader->m_pNext, 0 ) : InvalidIterator(); - } - int GetIndex( const Iterator_t &it ) const - { - Assert( IsValidIterator( it ) ); - if ( !IsValidIterator( it ) ) - return InvalidIndex(); - - return ( int )( HeaderToBlock( it.m_pBlockHeader ) + it.m_nIndex ); - } - bool IsIdxAfter( int i, const Iterator_t &it ) const - { - Assert( IsValidIterator( it ) ); - if ( !IsValidIterator( it ) ) - return false; - - if ( IsInBlock( i, it.m_pBlockHeader ) ) - return i > GetIndex( it ); - - for ( BlockHeader_t * RESTRICT pbh = it.m_pBlockHeader->m_pNext; pbh; pbh = pbh->m_pNext ) - { - if ( IsInBlock( i, pbh ) ) - return true; - } - return false; - } - bool IsValidIterator( const Iterator_t &it ) const { return it.m_pBlockHeader && it.m_nIndex >= 0 && it.m_nIndex < it.m_pBlockHeader->m_nBlockSize; } - Iterator_t InvalidIterator() const { return Iterator_t( NULL, -1 ); } - - // element access - T& operator[]( int i ); - const T& operator[]( int i ) const; - T& Element( int i ); - const T& Element( int i ) const; - - // Can we use this index? - bool IsIdxValid( int i ) const; - static int InvalidIndex() { return 0; } - - // Size - int NumAllocated() const; - int Count() const { return NumAllocated(); } - - // Grows memory by max(num,growsize), and returns the allocation index/ptr - void Grow( int num = 1 ); - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ); - - // Memory deallocation - void Purge(); - -protected: - // Fast swap - WARNING: Swap invalidates all ptr-based indices!!! - void Swap( CUtlFixedMemory< T > &mem ); - - bool IsInBlock( int i, BlockHeader_t *pBlockHeader ) const - { - T *p = ( T* )i; - const T *p0 = HeaderToBlock( pBlockHeader ); - return p >= p0 && p < p0 + pBlockHeader->m_nBlockSize; - } - - struct BlockHeader_t - { - BlockHeader_t *m_pNext; - int m_nBlockSize; - }; - - const T *HeaderToBlock( const BlockHeader_t *pHeader ) const { return ( T* )( pHeader + 1 ); } - const BlockHeader_t *BlockToHeader( const T *pBlock ) const { return ( BlockHeader_t* )( pBlock ) - 1; } - - BlockHeader_t* m_pBlocks; - int m_nAllocationCount; - int m_nGrowSize; -}; - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template< class T > -CUtlFixedMemory::CUtlFixedMemory( int nGrowSize, int nInitAllocationCount ) -: m_pBlocks( 0 ), m_nAllocationCount( 0 ), m_nGrowSize( 0 ) -{ - Init( nGrowSize, nInitAllocationCount ); -} - -template< class T > -CUtlFixedMemory::~CUtlFixedMemory() -{ - Purge(); -} - - -//----------------------------------------------------------------------------- -// Fast swap - WARNING: Swap invalidates all ptr-based indices!!! -//----------------------------------------------------------------------------- -template< class T > -void CUtlFixedMemory::Swap( CUtlFixedMemory< T > &mem ) -{ - swap( m_pBlocks, mem.m_pBlocks ); - swap( m_nAllocationCount, mem.m_nAllocationCount ); - swap( m_nGrowSize, mem.m_nGrowSize ); -} - - -//----------------------------------------------------------------------------- -// Set the size by which the memory grows - round up to the next power of 2 -//----------------------------------------------------------------------------- -template< class T > -void CUtlFixedMemory::Init( int nGrowSize /* = 0 */, int nInitSize /* = 0 */ ) -{ - Purge(); - - if ( nGrowSize == 0) - { - // Compute an allocation which is at least as big as a cache line... - nGrowSize = ( 31 + sizeof( T ) ) / sizeof( T ); - } - m_nGrowSize = nGrowSize; - - Grow( nInitSize ); -} - -//----------------------------------------------------------------------------- -// element access -//----------------------------------------------------------------------------- -template< class T > -inline T& CUtlFixedMemory::operator[]( int i ) -{ - Assert( IsIdxValid(i) ); - return *( T* )i; -} - -template< class T > -inline const T& CUtlFixedMemory::operator[]( int i ) const -{ - Assert( IsIdxValid(i) ); - return *( T* )i; -} - -template< class T > -inline T& CUtlFixedMemory::Element( int i ) -{ - Assert( IsIdxValid(i) ); - return *( T* )i; -} - -template< class T > -inline const T& CUtlFixedMemory::Element( int i ) const -{ - Assert( IsIdxValid(i) ); - return *( T* )i; -} - - -//----------------------------------------------------------------------------- -// Size -//----------------------------------------------------------------------------- -template< class T > -inline int CUtlFixedMemory::NumAllocated() const -{ - return m_nAllocationCount; -} - - -//----------------------------------------------------------------------------- -// Is element index valid? -//----------------------------------------------------------------------------- -template< class T > -inline bool CUtlFixedMemory::IsIdxValid( int i ) const -{ -#ifdef _DEBUG - for ( BlockHeader_t *pbh = m_pBlocks; pbh; pbh = pbh->m_pNext ) - { - if ( IsInBlock( i, pbh ) ) - return true; - } - return false; -#else - return i != InvalidIndex(); -#endif -} - -template< class T > -void CUtlFixedMemory::Grow( int num ) -{ - if ( num <= 0 ) - return; - - int nBlockSize = m_nGrowSize; - if ( nBlockSize == 0 ) - { - if ( m_nAllocationCount ) - { - nBlockSize = m_nAllocationCount; - } - else - { - // Compute an allocation which is at least as big as a cache line... - nBlockSize = ( 31 + sizeof( T ) ) / sizeof( T ); - Assert( nBlockSize ); - } - } - if ( nBlockSize < num ) - { - int n = ( num + nBlockSize -1 ) / nBlockSize; - Assert( n * nBlockSize >= num ); - Assert( ( n - 1 ) * nBlockSize < num ); - nBlockSize *= n; - } - m_nAllocationCount += nBlockSize; - - MEM_ALLOC_CREDIT_CLASS(); - BlockHeader_t * RESTRICT pBlockHeader = ( BlockHeader_t* )malloc( sizeof( BlockHeader_t ) + nBlockSize * sizeof( T ) ); - if ( !pBlockHeader ) - { - Error( "CUtlFixedMemory overflow!\n" ); - } - pBlockHeader->m_pNext = NULL; - pBlockHeader->m_nBlockSize = nBlockSize; - - if ( !m_pBlocks ) - { - m_pBlocks = pBlockHeader; - } - else - { -#if 1 // IsIdxAfter assumes that newly allocated blocks are at the end - BlockHeader_t * RESTRICT pbh = m_pBlocks; - while ( pbh->m_pNext ) - { - pbh = pbh->m_pNext; - } - pbh->m_pNext = pBlockHeader; -#else - pBlockHeader = m_pBlocks; - pBlockHeader->m_pNext = m_pBlocks; -#endif - } -} - - -//----------------------------------------------------------------------------- -// Makes sure we've got at least this much memory -//----------------------------------------------------------------------------- -template< class T > -inline void CUtlFixedMemory::EnsureCapacity( int num ) -{ - Grow( num - NumAllocated() ); -} - - -//----------------------------------------------------------------------------- -// Memory deallocation -//----------------------------------------------------------------------------- -template< class T > -void CUtlFixedMemory::Purge() -{ - if ( !m_pBlocks ) - return; - - for ( BlockHeader_t *pbh = m_pBlocks; pbh; ) - { - BlockHeader_t *pFree = pbh; - pbh = pbh->m_pNext; - free( pFree ); - } - m_pBlocks = NULL; - m_nAllocationCount = 0; -} - -#include "tier0/memdbgoff.h" - -#endif // UTLFIXEDMEMORY_H diff --git a/Resources/NetHook/tier1/utlflags.h b/Resources/NetHook/tier1/utlflags.h deleted file mode 100644 index 889cb8a9..00000000 --- a/Resources/NetHook/tier1/utlflags.h +++ /dev/null @@ -1,124 +0,0 @@ -//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= -// -// Purpose: Simple class to make it easier to deal with flags -// -//============================================================================= - -#ifndef UTLFLAGS_H -#define UTLFLAGS_H -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" - - -//----------------------------------------------------------------------------- -// Simple class to make it easier to deal with flags -//----------------------------------------------------------------------------- -template< class T > -class CUtlFlags -{ -public: - CUtlFlags( int nInitialFlags = 0 ); - - // Flag setting - void SetFlag( int nFlagMask ); - void SetFlag( int nFlagMask, bool bEnable ); - - // Flag clearing - void ClearFlag( int nFlagMask ); - void ClearAllFlags(); - bool IsFlagSet( int nFlagMask ) const; - - // Is any flag set? - bool IsAnyFlagSet() const; - -private: - T m_nFlags; -}; - - -//----------------------------------------------------------------------------- -// Constructor -//----------------------------------------------------------------------------- -template< class T > -CUtlFlags::CUtlFlags( int nInitialFlags ) -{ - // Makes sure we didn't truncate - Assert( nInitialFlags == (T)nInitialFlags ); - - m_nFlags = (T)nInitialFlags; -} - - -//----------------------------------------------------------------------------- -// Set flags -//----------------------------------------------------------------------------- -template< class T > -void CUtlFlags::SetFlag( int nFlagMask ) -{ - // Makes sure we didn't truncate - Assert( nFlagMask == (T)nFlagMask ); - - m_nFlags |= (T)nFlagMask; -} - -template< class T > -void CUtlFlags::SetFlag( int nFlagMask, bool bEnable ) -{ - // Makes sure we didn't truncate - Assert( nFlagMask == (T)nFlagMask ); - - if ( bEnable ) - { - m_nFlags |= (T)nFlagMask; - } - else - { - m_nFlags &= ~((T)nFlagMask); - } -} - - -//----------------------------------------------------------------------------- -// Clear flags -//----------------------------------------------------------------------------- -template< class T > -void CUtlFlags::ClearFlag( int nFlagMask ) -{ - // Makes sure we didn't truncate - Assert( nFlagMask == (T)nFlagMask ); - m_nFlags &= ~((T)nFlagMask); -} - -template< class T > -void CUtlFlags::ClearAllFlags() -{ - m_nFlags = 0; -} - - -//----------------------------------------------------------------------------- -// Is a flag set? -//----------------------------------------------------------------------------- -template< class T > -bool CUtlFlags::IsFlagSet( int nFlagMask ) const -{ - // Makes sure we didn't truncate - Assert( nFlagMask == (T)nFlagMask ); - return ( m_nFlags & nFlagMask ) != 0; -} - - -//----------------------------------------------------------------------------- -// Is any flag set? -//----------------------------------------------------------------------------- -template< class T > -bool CUtlFlags::IsAnyFlagSet() const -{ - return m_nFlags != 0; -} - - -#endif // UTLFLAGS_H diff --git a/Resources/NetHook/tier1/utlhandletable.h b/Resources/NetHook/tier1/utlhandletable.h deleted file mode 100644 index 12bcdafd..00000000 --- a/Resources/NetHook/tier1/utlhandletable.h +++ /dev/null @@ -1,586 +0,0 @@ -//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= -// -// Purpose: -// -//============================================================================= - -#ifndef UTLHANDLETABLE_H -#define UTLHANDLETABLE_H - -#ifdef _WIN32 -#pragma once -#endif - - -#include "tier1/utlvector.h" -#include "tier1/utlqueue.h" - - -//----------------------------------------------------------------------------- -// Handles are 32 bits. Invalid handles are all 1s -//----------------------------------------------------------------------------- -typedef unsigned int UtlHandle_t; -#define UTLHANDLE_INVALID ((UtlHandle_t)~0) - - -//----------------------------------------------------------------------------- -// Purpose: This is a table used to allocate handles -// HandleBits specifies the max # of simultaneously allocated handles. -// An extra bit is used for the validity state -// The rest of the 32 bits are used for a serial number -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -class CUtlHandleTable -{ -public: - CUtlHandleTable(); - - // Allocate, deallocate handles - UtlHandle_t AddHandle(); - void RemoveHandle( UtlHandle_t h ); - - // Set/get handle values - void SetHandle( UtlHandle_t h, T *pData ); - T *GetHandle( UtlHandle_t h ) const; - T *GetHandle( UtlHandle_t h, bool checkValidity ) const; - - // Is a handle valid? - bool IsHandleValid( UtlHandle_t h ) const; - - // Iterate over handles; they may not be valid - unsigned int GetValidHandleCount() const; - unsigned int GetHandleCount() const; - UtlHandle_t GetHandleFromIndex( int i ) const; - int GetIndexFromHandle( UtlHandle_t h ) const; - - void MarkHandleInvalid( UtlHandle_t h ); - void MarkHandleValid( UtlHandle_t h ); - -private: - struct HandleType_t - { - HandleType_t( unsigned int i, unsigned int s ) : nIndex( i ), nSerial( s ) - { - Assert( i < ( 1 << HandleBits ) ); - Assert( s < ( 1 << ( 31 - HandleBits ) ) ); - } - unsigned int nIndex : HandleBits; - unsigned int nSerial : 31 - HandleBits; - }; - - struct EntryType_t - { - EntryType_t() : m_nSerial( 0 ), nInvalid( 0 ), m_pData( 0 ) {} - unsigned int m_nSerial : 31; - unsigned int nInvalid : 1; - T *m_pData; - }; - - static unsigned int GetSerialNumber( UtlHandle_t handle ); - static unsigned int GetListIndex( UtlHandle_t handle ); - static UtlHandle_t CreateHandle( unsigned int nSerial, unsigned int nIndex ); - const EntryType_t *GetEntry( UtlHandle_t handle, bool checkValidity ) const; - - unsigned int m_nValidHandles; - CUtlVector< EntryType_t > m_list; - CUtlQueue< int > m_unused; -}; - - -//----------------------------------------------------------------------------- -// Constructor, destructor -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -CUtlHandleTable::CUtlHandleTable() : m_nValidHandles( 0 ) -{ -} - - -//----------------------------------------------------------------------------- -// Allocate, deallocate handles -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -UtlHandle_t CUtlHandleTable::AddHandle() -{ - unsigned int nIndex = ( m_unused.Count() > 0 ) ? m_unused.RemoveAtHead() : m_list.AddToTail(); - - EntryType_t &entry = m_list[ nIndex ]; - entry.nInvalid = 0; - entry.m_pData = NULL; - - ++m_nValidHandles; - - return CreateHandle( entry.m_nSerial, nIndex ); -} - -template< class T, int HandleBits > -void CUtlHandleTable::RemoveHandle( UtlHandle_t handle ) -{ - unsigned int nIndex = GetListIndex( handle ); - Assert( nIndex < ( unsigned int )m_list.Count() ); - if ( nIndex >= ( unsigned int )m_list.Count() ) - return; - - EntryType_t &entry = m_list[ nIndex ]; - ++entry.m_nSerial; // mark old serial# invalid - if ( !entry.nInvalid ) - { - entry.nInvalid = 1; - --m_nValidHandles; - } - entry.m_pData = NULL; - - - // If a handle has been used this many times, then we need to take it out of service, otherwise if the - // serial # wraps around we'll possibly revalidate old handles and they'll start to point at the wrong objects. Unlikely, but possible. - bool bStopUsing = ( entry.m_nSerial >= ( (1 << ( 31 - HandleBits ) ) - 1 ) ); - if ( !bStopUsing ) - { - m_unused.Insert( nIndex ); - } -} - - -//----------------------------------------------------------------------------- -// Set/get handle values -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -void CUtlHandleTable::SetHandle( UtlHandle_t handle, T *pData ) -{ - EntryType_t *entry = const_cast< EntryType_t* >( GetEntry( handle, false ) ); - Assert( entry ); - if ( entry == NULL ) - return; - - // Validate the handle - if ( entry->nInvalid ) - { - ++m_nValidHandles; - entry->nInvalid = 0; - } - entry->m_pData = pData; -} - -template< class T, int HandleBits > -T *CUtlHandleTable::GetHandle( UtlHandle_t handle ) const -{ - const EntryType_t *entry = GetEntry( handle, true ); - return entry ? entry->m_pData : NULL; -} - -template< class T, int HandleBits > -T *CUtlHandleTable::GetHandle( UtlHandle_t handle, bool checkValidity ) const -{ - const EntryType_t *entry = GetEntry( handle, checkValidity ); - return entry ? entry->m_pData : NULL; -} - - -//----------------------------------------------------------------------------- -// Is a handle valid? -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -bool CUtlHandleTable::IsHandleValid( UtlHandle_t handle ) const -{ - if ( handle == UTLHANDLE_INVALID ) - return false; - - unsigned int nIndex = GetListIndex( handle ); - AssertOnce( nIndex < ( unsigned int )m_list.Count() ); - if ( nIndex >= ( unsigned int )m_list.Count() ) - return false; - - const EntryType_t &entry = m_list[ nIndex ]; - if ( entry.m_nSerial != GetSerialNumber( handle ) ) - return false; - - if ( 1 == entry.nInvalid ) - return false; - - return true; -} - - -//----------------------------------------------------------------------------- -// Current max handle -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -unsigned int CUtlHandleTable::GetValidHandleCount() const -{ - return m_nValidHandles; -} - -template< class T, int HandleBits > -unsigned int CUtlHandleTable::GetHandleCount() const -{ - return m_list.Count(); -} - -template< class T, int HandleBits > -UtlHandle_t CUtlHandleTable::GetHandleFromIndex( int i ) const -{ - if ( m_list[i].m_pData ) - return CreateHandle( m_list[i].m_nSerial, i ); - return UTLHANDLE_INVALID; -} - -template< class T, int HandleBits > -int CUtlHandleTable::GetIndexFromHandle( UtlHandle_t h ) const -{ - if ( h == UTLHANDLE_INVALID ) - return -1; - - return GetListIndex( h ); -} - - - -//----------------------------------------------------------------------------- -// Cracking handles into indices + serial numbers -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -unsigned int CUtlHandleTable::GetSerialNumber( UtlHandle_t handle ) -{ - return ( ( HandleType_t* )&handle )->nSerial; -} - -template< class T, int HandleBits > -unsigned int CUtlHandleTable::GetListIndex( UtlHandle_t handle ) -{ - return ( ( HandleType_t* )&handle )->nIndex; -} - -template< class T, int HandleBits > -UtlHandle_t CUtlHandleTable::CreateHandle( unsigned int nSerial, unsigned int nIndex ) -{ - HandleType_t h( nIndex, nSerial ); - return *( UtlHandle_t* )&h; -} - - -//----------------------------------------------------------------------------- -// Looks up a entry by handle -//----------------------------------------------------------------------------- -template< class T, int HandleBits > -const typename CUtlHandleTable::EntryType_t *CUtlHandleTable::GetEntry( UtlHandle_t handle, bool checkValidity ) const -{ - if ( handle == UTLHANDLE_INVALID ) - return NULL; - - unsigned int nIndex = GetListIndex( handle ); - Assert( nIndex < ( unsigned int )m_list.Count() ); - if ( nIndex >= ( unsigned int )m_list.Count() ) - return NULL; - - const EntryType_t &entry = m_list[ nIndex ]; - if ( entry.m_nSerial != GetSerialNumber( handle ) ) - return NULL; - - if ( checkValidity && - ( 1 == entry.nInvalid ) ) - return NULL; - - return &entry; -} - -template< class T, int HandleBits > -void CUtlHandleTable::MarkHandleInvalid( UtlHandle_t handle ) -{ - if ( handle == UTLHANDLE_INVALID ) - return; - - unsigned int nIndex = GetListIndex( handle ); - Assert( nIndex < ( unsigned int )m_list.Count() ); - if ( nIndex >= ( unsigned int )m_list.Count() ) - return; - - EntryType_t &entry = m_list[ nIndex ]; - if ( entry.m_nSerial != GetSerialNumber( handle ) ) - return; - - if ( !entry.nInvalid ) - { - --m_nValidHandles; - entry.nInvalid = 1; - } -} - -template< class T, int HandleBits > -void CUtlHandleTable::MarkHandleValid( UtlHandle_t handle ) -{ - if ( handle == UTLHANDLE_INVALID ) - return; - - unsigned int nIndex = GetListIndex( handle ); - Assert( nIndex < ( unsigned int )m_list.Count() ); - if ( nIndex >= ( unsigned int )m_list.Count() ) - return; - - EntryType_t &entry = m_list[ nIndex ]; - if ( entry.m_nSerial != GetSerialNumber( handle ) ) - return; - - if ( entry.nInvalid ) - { - ++m_nValidHandles; - entry.nInvalid = 0; - } -} - - -//----------------------------------------------------------------------------- -// Handle wrapper. Assumes 2 things -// 1) That class T has a non-static method called GetHandle which returns a UtlHandle_t -// 2) That class T has a static method called GetPtrFromHandle which returns a T* given a UtlHandle_t -// 3) That class T has a static method called IsHandleValid which accepts a UtlHandle_t -//----------------------------------------------------------------------------- -template< class T > -class CUtlHandle -{ -public: - // Constructors - CUtlHandle(); - explicit CUtlHandle( T *pObject ); - CUtlHandle( UtlHandle_t h ); - CUtlHandle( const CUtlHandle &h ); - - // Assignment - void Set( T *pObject ); - void Set( UtlHandle_t h ); - const CUtlHandle &operator=( UtlHandle_t h ); - const CUtlHandle &operator=( T *pObject ); - - // Retrieval - T *Get(); - const T* Get() const; - - // Is the handle valid? - bool IsValid() const; - - // Casting - operator T*(); - operator UtlHandle_t(); - operator bool(); - T* operator->(); - const T* operator->() const; - - // Equality - bool operator==( CUtlHandle h ) const; - bool operator==( T *pObject ) const; - bool operator==( UtlHandle_t h ) const; - bool operator!=( CUtlHandle h ) const; - bool operator!=( T *pObject ) const; - bool operator!=( UtlHandle_t h ) const; - -private: - UtlHandle_t m_handle; -}; - - -//----------------------------------------------------------------------------- -// Constructors -//----------------------------------------------------------------------------- -template< class T > -CUtlHandle::CUtlHandle() : m_handle( UTLHANDLE_INVALID ) -{ -} - -template< class T > -CUtlHandle::CUtlHandle( T *pObject ) -{ - Set( pObject ); -} - -template< class T > -CUtlHandle::CUtlHandle( UtlHandle_t h ) -{ - m_handle = h; -} - -template< class T > -CUtlHandle::CUtlHandle( const CUtlHandle &h ) -{ - m_handle = h.m_handle; -} - - -//----------------------------------------------------------------------------- -// Assignment -//----------------------------------------------------------------------------- -template< class T > -void CUtlHandle::Set( T *pObject ) -{ - // Assumes T has a member function GetHandle - m_handle = pObject ? pObject->GetHandle() : UTLHANDLE_INVALID; -} - -template< class T > -void CUtlHandle::Set( UtlHandle_t h ) -{ - m_handle = h; -} - -template< class T > -const CUtlHandle &CUtlHandle::operator=( UtlHandle_t h ) -{ - Set( h ); - return *this; -} - -template< class T > -const CUtlHandle &CUtlHandle::operator=( T *pObject ) -{ - Set( pObject ); - return *this; -} - - -//----------------------------------------------------------------------------- -// Is the handle valid? -//----------------------------------------------------------------------------- -template< class T > -bool CUtlHandle::IsValid() const -{ - // Assumes T has a static member function IsHandleValid - return T::IsHandleValid( m_handle ); -} - - -//----------------------------------------------------------------------------- -// Retrieval -//----------------------------------------------------------------------------- -template< class T > -T *CUtlHandle::Get() -{ - // Assumes T has a static member function GetPtrFromHandle - return T::GetPtrFromHandle( m_handle ); -} - -template< class T > -const T* CUtlHandle::Get() const -{ - // Assumes T has a static member function GetPtrFromHandle - return T::GetPtrFromHandle( m_handle ); -} - - -//----------------------------------------------------------------------------- -// Casting -//----------------------------------------------------------------------------- -template< class T > -CUtlHandle::operator T*() -{ - return Get(); -} - -template< class T > -CUtlHandle::operator UtlHandle_t() -{ - return m_handle; -} - -template< class T > -T* CUtlHandle::operator->() -{ - return Get(); -} - -template< class T > -const T* CUtlHandle::operator->() const -{ - return Get(); -} - -template< class T > -CUtlHandle::operator bool() -{ - return m_handle != UTLHANDLE_INVALID; -} - - -//----------------------------------------------------------------------------- -// Equality -//----------------------------------------------------------------------------- -template< class T > -bool CUtlHandle::operator==( CUtlHandle h ) const -{ - return m_handle == h.m_handle; -} - -template< class T > -bool CUtlHandle::operator==( T *pObject ) const -{ - UtlHandle_t h = pObject ? pObject->GetHandle() : UTLHANDLE_INVALID; - return m_handle == h; -} - -template< class T > -bool CUtlHandle::operator==( UtlHandle_t h ) const -{ - return m_handle == h; -} - -template< class T > -bool CUtlHandle::operator!=( CUtlHandle h ) const -{ - return m_handle != h.m_handle; -} - -template< class T > -bool CUtlHandle::operator!=( T *pObject ) const -{ - UtlHandle_t h = pObject ? pObject->GetHandle() : UTLHANDLE_INVALID; - return m_handle != h; -} - -template< class T > -bool CUtlHandle::operator!=( UtlHandle_t h ) const -{ - return m_handle != h; -} - - -//----------------------------------------------------------------------------- -// Add this macro to a class definition to hook in handles for it! -//----------------------------------------------------------------------------- -#define DECLARE_HANDLES( _className, _handleBitCount ) \ - public: \ - UtlHandle_t GetHandle() \ - { \ - return m_Handle; \ - } \ - static _className* GetPtrFromHandle( UtlHandle_t h ) \ - { \ - return m_HandleTable.GetHandle( h ); \ - } \ - static bool IsHandleValid( UtlHandle_t h ) \ - { \ - return m_HandleTable.IsHandleValid( h ); \ - } \ - private: \ - UtlHandle_t m_Handle; \ - static CUtlHandleTable< _className, _handleBitCount > m_HandleTable - - -//----------------------------------------------------------------------------- -// Add this macro to a .cpp file to hook in handles for it! -//----------------------------------------------------------------------------- -#define IMPLEMENT_HANDLES( _className, _handleBitCount ) \ - CUtlHandleTable< _className, _handleBitCount > _className::m_HandleTable; - - -//----------------------------------------------------------------------------- -// Add these macro to the class constructor + destructor -//----------------------------------------------------------------------------- -#define CONSTRUCT_HANDLE( ) \ - m_Handle = m_HandleTable.AddHandle(); \ - m_HandleTable.SetHandle( m_Handle, this ) - -#define DESTRUCT_HANDLE() \ - m_HandleTable.RemoveHandle( m_Handle ); \ - m_Handle = UTLHANDLE_INVALID - - - -#endif // UTLHANDLETABLE_H - diff --git a/Resources/NetHook/tier1/utlhash.h b/Resources/NetHook/tier1/utlhash.h deleted file mode 100644 index b7cba7d4..00000000 --- a/Resources/NetHook/tier1/utlhash.h +++ /dev/null @@ -1,936 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -// Serialization/unserialization buffer -//=============================================================================// - -#ifndef UTLHASH_H -#define UTLHASH_H -#pragma once - -#include -#include -#include "utlmemory.h" -#include "utlvector.h" -#include "utllinkedlist.h" -#include "utllinkedlist.h" -#include "commonmacros.h" -#include "generichash.h" - -typedef unsigned int UtlHashHandle_t; - -template -class CUtlHash -{ -public: - // compare and key functions - implemented by the - typedef C CompareFunc_t; - typedef K KeyFunc_t; - - // constructor/deconstructor - CUtlHash( int bucketCount = 0, int growCount = 0, int initCount = 0, - CompareFunc_t compareFunc = 0, KeyFunc_t keyFunc = 0 ); - ~CUtlHash(); - - // invalid handle - static UtlHashHandle_t InvalidHandle( void ) { return ( UtlHashHandle_t )~0; } - bool IsValidHandle( UtlHashHandle_t handle ) const; - - // size - int Count( void ) const; - - // memory - void Purge( void ); - - // insertion methods - UtlHashHandle_t Insert( Data const &src ); - UtlHashHandle_t Insert( Data const &src, bool *pDidInsert ); - UtlHashHandle_t AllocEntryFromKey( Data const &src ); - - // removal methods - void Remove( UtlHashHandle_t handle ); - void RemoveAll(); - - // retrieval methods - UtlHashHandle_t Find( Data const &src ) const; - - Data &Element( UtlHashHandle_t handle ); - Data const &Element( UtlHashHandle_t handle ) const; - Data &operator[]( UtlHashHandle_t handle ); - Data const &operator[]( UtlHashHandle_t handle ) const; - - UtlHashHandle_t GetFirstHandle() const; - UtlHashHandle_t GetNextHandle( UtlHashHandle_t h ) const; - - // debugging!! - void Log( const char *filename ); - -protected: - - int GetBucketIndex( UtlHashHandle_t handle ) const; - int GetKeyDataIndex( UtlHashHandle_t handle ) const; - UtlHashHandle_t BuildHandle( int ndxBucket, int ndxKeyData ) const; - - bool DoFind( Data const &src, unsigned int *pBucket, int *pIndex ) const; - -protected: - - // handle upper 16 bits = bucket index (bucket heads) - // handle lower 16 bits = key index (bucket list) - typedef CUtlVector HashBucketList_t; - CUtlVector m_Buckets; - - CompareFunc_t m_CompareFunc; // function used to handle unique compares on data - KeyFunc_t m_KeyFunc; // function used to generate the key value - - bool m_bPowerOfTwo; // if the bucket value is a power of two, - unsigned int m_ModMask; // use the mod mask to "mod" -}; - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -CUtlHash::CUtlHash( int bucketCount, int growCount, int initCount, - CompareFunc_t compareFunc, KeyFunc_t keyFunc ) : - m_CompareFunc( compareFunc ), - m_KeyFunc( keyFunc ) -{ - m_Buckets.SetSize( bucketCount ); - for( int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++ ) - { - m_Buckets[ndxBucket].SetSize( initCount ); - m_Buckets[ndxBucket].SetGrowSize( growCount ); - } - - // check to see if the bucket count is a power of 2 and set up - // optimizations appropriately - m_bPowerOfTwo = IsPowerOfTwo( bucketCount ); - m_ModMask = m_bPowerOfTwo ? (bucketCount-1) : 0; -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -CUtlHash::~CUtlHash() -{ - Purge(); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline bool CUtlHash::IsValidHandle( UtlHashHandle_t handle ) const -{ - int ndxBucket = GetBucketIndex( handle ); - int ndxKeyData = GetKeyDataIndex( handle ); - - // ndxBucket and ndxKeyData can't possibly be less than zero -- take a - // look at the definition of the Get..Index functions for why. However, - // if you override those functions, you will need to override this one - // as well. - if( /*( ndxBucket >= 0 ) && */ ( ndxBucket < m_Buckets.Count() ) ) - { - if( /*( ndxKeyData >= 0 ) && */ ( ndxKeyData < m_Buckets[ndxBucket].Count() ) ) - return true; - } - - return false; -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline int CUtlHash::Count( void ) const -{ - int count = 0; - - int bucketCount = m_Buckets.Count(); - for( int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++ ) - { - count += m_Buckets[ndxBucket].Count(); - } - - return count; -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline int CUtlHash::GetBucketIndex( UtlHashHandle_t handle ) const -{ - return ( ( ( handle >> 16 ) & 0x0000ffff ) ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline int CUtlHash::GetKeyDataIndex( UtlHashHandle_t handle ) const -{ - return ( handle & 0x0000ffff ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline UtlHashHandle_t CUtlHash::BuildHandle( int ndxBucket, int ndxKeyData ) const -{ - assert( ( ndxBucket >= 0 ) && ( ndxBucket < 65536 ) ); - assert( ( ndxKeyData >= 0 ) && ( ndxKeyData < 65536 ) ); - - UtlHashHandle_t handle = ndxKeyData; - handle |= ( ndxBucket << 16 ); - - return handle; -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline void CUtlHash::Purge( void ) -{ - int bucketCount = m_Buckets.Count(); - for( int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++ ) - { - m_Buckets[ndxBucket].Purge(); - } -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline bool CUtlHash::DoFind( Data const &src, unsigned int *pBucket, int *pIndex ) const -{ - // generate the data "key" - unsigned int key = m_KeyFunc( src ); - - // hash the "key" - get the correct hash table "bucket" - unsigned int ndxBucket; - if( m_bPowerOfTwo ) - { - *pBucket = ndxBucket = ( key & m_ModMask ); - } - else - { - int bucketCount = m_Buckets.Count(); - *pBucket = ndxBucket = key % bucketCount; - } - - int ndxKeyData; - const CUtlVector &bucket = m_Buckets[ndxBucket]; - int keyDataCount = bucket.Count(); - for( ndxKeyData = 0; ndxKeyData < keyDataCount; ndxKeyData++ ) - { - if( m_CompareFunc( bucket.Element( ndxKeyData ), src ) ) - break; - } - - if( ndxKeyData == keyDataCount ) - return false; - - *pIndex = ndxKeyData; - return true; -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline UtlHashHandle_t CUtlHash::Find( Data const &src ) const -{ - unsigned int ndxBucket; - int ndxKeyData; - - if ( DoFind( src, &ndxBucket, &ndxKeyData ) ) - { - return ( BuildHandle( ndxBucket, ndxKeyData ) ); - } - return ( InvalidHandle() ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline UtlHashHandle_t CUtlHash::Insert( Data const &src ) -{ - unsigned int ndxBucket; - int ndxKeyData; - - if ( DoFind( src, &ndxBucket, &ndxKeyData ) ) - { - return ( BuildHandle( ndxBucket, ndxKeyData ) ); - } - - ndxKeyData = m_Buckets[ndxBucket].AddToTail( src ); - - return ( BuildHandle( ndxBucket, ndxKeyData ) ); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline UtlHashHandle_t CUtlHash::Insert( Data const &src, bool *pDidInsert ) -{ - unsigned int ndxBucket; - int ndxKeyData; - - if ( DoFind( src, &ndxBucket, &ndxKeyData ) ) - { - *pDidInsert = false; - return ( BuildHandle( ndxBucket, ndxKeyData ) ); - } - - *pDidInsert = true; - ndxKeyData = m_Buckets[ndxBucket].AddToTail( src ); - - return ( BuildHandle( ndxBucket, ndxKeyData ) ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline UtlHashHandle_t CUtlHash::AllocEntryFromKey( Data const &src ) -{ - unsigned int ndxBucket; - int ndxKeyData; - - if ( DoFind( src, &ndxBucket, &ndxKeyData ) ) - { - return ( BuildHandle( ndxBucket, ndxKeyData ) ); - } - - ndxKeyData = m_Buckets[ndxBucket].AddToTail(); - - return ( BuildHandle( ndxBucket, ndxKeyData ) ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline void CUtlHash::Remove( UtlHashHandle_t handle ) -{ - assert( IsValidHandle( handle ) ); - - // check to see if the bucket exists - int ndxBucket = GetBucketIndex( handle ); - int ndxKeyData = GetKeyDataIndex( handle ); - - if( m_Buckets[ndxBucket].IsValidIndex( ndxKeyData ) ) - { - m_Buckets[ndxBucket].FastRemove( ndxKeyData ); - } -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline void CUtlHash::RemoveAll() -{ - int bucketCount = m_Buckets.Count(); - for( int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++ ) - { - m_Buckets[ndxBucket].RemoveAll(); - } -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline Data &CUtlHash::Element( UtlHashHandle_t handle ) -{ - int ndxBucket = GetBucketIndex( handle ); - int ndxKeyData = GetKeyDataIndex( handle ); - - return ( m_Buckets[ndxBucket].Element( ndxKeyData ) ); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline Data const &CUtlHash::Element( UtlHashHandle_t handle ) const -{ - int ndxBucket = GetBucketIndex( handle ); - int ndxKeyData = GetKeyDataIndex( handle ); - - return ( m_Buckets[ndxBucket].Element( ndxKeyData ) ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline Data &CUtlHash::operator[]( UtlHashHandle_t handle ) -{ - int ndxBucket = GetBucketIndex( handle ); - int ndxKeyData = GetKeyDataIndex( handle ); - - return ( m_Buckets[ndxBucket].Element( ndxKeyData ) ); -} - - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline Data const &CUtlHash::operator[]( UtlHashHandle_t handle ) const -{ - int ndxBucket = GetBucketIndex( handle ); - int ndxKeyData = GetKeyDataIndex( handle ); - - return ( m_Buckets[ndxBucket].Element( ndxKeyData ) ); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline UtlHashHandle_t CUtlHash::GetFirstHandle() const -{ - return GetNextHandle( ( UtlHashHandle_t )-1 ); -} - -template -inline UtlHashHandle_t CUtlHash::GetNextHandle( UtlHashHandle_t handle ) const -{ - ++handle; // start at the first possible handle after the one given - - int bi = GetBucketIndex( handle ); - int ki = GetKeyDataIndex( handle ); - - int nBuckets = m_Buckets.Count(); - for ( ; bi < nBuckets; ++bi ) - { - if ( ki < m_Buckets[ bi ].Count() ) - return BuildHandle( bi, ki ); - - ki = 0; - } - - return InvalidHandle(); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -inline void CUtlHash::Log( const char *filename ) -{ - FILE *pDebugFp; - pDebugFp = fopen( filename, "w" ); - if( !pDebugFp ) - return; - - int maxBucketSize = 0; - int numBucketsEmpty = 0; - - int bucketCount = m_Buckets.Count(); - fprintf( pDebugFp, "\n%d Buckets\n", bucketCount ); - - for( int ndxBucket = 0; ndxBucket < bucketCount; ndxBucket++ ) - { - int count = m_Buckets[ndxBucket].Count(); - - if( count > maxBucketSize ) { maxBucketSize = count; } - if( count == 0 ) - numBucketsEmpty++; - - fprintf( pDebugFp, "Bucket %d: %d\n", ndxBucket, count ); - } - - fprintf( pDebugFp, "\nBucketHeads Used: %d\n", bucketCount - numBucketsEmpty ); - fprintf( pDebugFp, "Max Bucket Size: %d\n", maxBucketSize ); - - fclose( pDebugFp ); -} - -//============================================================================= -// -// Fast Hash -// -// Number of buckets must be a power of 2. -// Key must be 32-bits (unsigned int). -// -typedef int UtlHashFastHandle_t; - -#define UTLHASH_POOL_SCALAR 2 - -class CUtlHashFastNoHash -{ -public: - static int Hash( int key, int bucketMask ) - { - return ( key & bucketMask ); - } -}; - -class CUtlHashFastGenericHash -{ -public: - static int Hash( int key, int bucketMask ) - { - return ( HashIntConventional( key ) & bucketMask ); - } -}; - -template -class CUtlHashFast -{ -public: - - // Constructor/Deconstructor. - CUtlHashFast(); - ~CUtlHashFast(); - - // Memory. - void Purge( void ); - - // Invalid handle. - static UtlHashFastHandle_t InvalidHandle( void ) { return ( UtlHashFastHandle_t )~0; } - - // Initialize. - bool Init( int nBucketCount ); - - // Size. - int Count( void ); - - // Insertion. - UtlHashFastHandle_t Insert( unsigned int uiKey, const Data &data ); - UtlHashFastHandle_t FastInsert( unsigned int uiKey, const Data &data ); - - // Removal. - void Remove( UtlHashFastHandle_t hHash ); - void RemoveAll( void ); - - // Retrieval. - UtlHashFastHandle_t Find( unsigned int uiKey ); - - Data &Element( UtlHashFastHandle_t hHash ); - Data const &Element( UtlHashFastHandle_t hHash ) const; - Data &operator[]( UtlHashFastHandle_t hHash ); - Data const &operator[]( UtlHashFastHandle_t hHash ) const; - -//protected: - - // Templatized for memory tracking purposes - template - struct HashFastData_t_ - { - unsigned int m_uiKey; - HashData m_Data; - }; - - typedef HashFastData_t_ HashFastData_t; - - unsigned int m_uiBucketMask; - CUtlVector m_aBuckets; - CUtlFixedLinkedList m_aDataPool; -}; - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -template CUtlHashFast::CUtlHashFast() -{ - Purge(); -} - -//----------------------------------------------------------------------------- -// Purpose: Deconstructor -//----------------------------------------------------------------------------- -template CUtlHashFast::~CUtlHashFast() -{ - Purge(); -} - -//----------------------------------------------------------------------------- -// Purpose: Destroy dynamically allocated hash data. -//----------------------------------------------------------------------------- -template inline void CUtlHashFast::Purge( void ) -{ - m_aBuckets.Purge(); - m_aDataPool.Purge(); -} - -//----------------------------------------------------------------------------- -// Purpose: Initialize the hash - set bucket count and hash grow amount. -//----------------------------------------------------------------------------- -template bool CUtlHashFast::Init( int nBucketCount ) -{ - // Verify the bucket count is power of 2. - if ( !IsPowerOfTwo( nBucketCount ) ) - return false; - - // Set the bucket size. - m_aBuckets.SetSize( nBucketCount ); - for ( int iBucket = 0; iBucket < nBucketCount; ++iBucket ) - { - m_aBuckets[iBucket] = m_aDataPool.InvalidIndex(); - } - - // Set the mod mask. - m_uiBucketMask = nBucketCount - 1; - - // Calculate the grow size. - int nGrowSize = UTLHASH_POOL_SCALAR * nBucketCount; - m_aDataPool.SetGrowSize( nGrowSize ); - - return true; -} - -//----------------------------------------------------------------------------- -// Purpose: Return the number of elements in the hash. -//----------------------------------------------------------------------------- -template inline int CUtlHashFast::Count( void ) -{ - return m_aDataPool.Count(); -} - -//----------------------------------------------------------------------------- -// Purpose: Insert data into the hash table given its key (unsigned int), with -// a check to see if the element already exists within the tree. -//----------------------------------------------------------------------------- -template inline UtlHashFastHandle_t CUtlHashFast::Insert( unsigned int uiKey, const Data &data ) -{ - // Check to see if that key already exists in the buckets (should be unique). - UtlHashFastHandle_t hHash = Find( uiKey ); - if( hHash != InvalidHandle() ) - return hHash; - - return FastInsert( uiKey, data ); -} - -//----------------------------------------------------------------------------- -// Purpose: Insert data into the hash table given its key (unsigned int), -// without a check to see if the element already exists within the tree. -//----------------------------------------------------------------------------- -template inline UtlHashFastHandle_t CUtlHashFast::FastInsert( unsigned int uiKey, const Data &data ) -{ - // Get a new element from the pool. - int iHashData = m_aDataPool.Alloc( true ); - HashFastData_t *pHashData = &m_aDataPool[iHashData]; - if ( !pHashData ) - return InvalidHandle(); - - // Add data to new element. - pHashData->m_uiKey = uiKey; - pHashData->m_Data = data; - - // Link element. - int iBucket = HashFuncs::Hash( uiKey, m_uiBucketMask ); - m_aDataPool.LinkBefore( m_aBuckets[iBucket], iHashData ); - m_aBuckets[iBucket] = iHashData; - - return iHashData; -} - -//----------------------------------------------------------------------------- -// Purpose: Remove a given element from the hash. -//----------------------------------------------------------------------------- -template inline void CUtlHashFast::Remove( UtlHashFastHandle_t hHash ) -{ - int iBucket = HashFuncs::Hash( m_aDataPool[hHash].m_uiKey, m_uiBucketMask ); - if ( m_aBuckets[iBucket] == hHash ) - { - // It is a bucket head. - m_aBuckets[iBucket] = m_aDataPool.Next( hHash ); - } - else - { - // Not a bucket head. - m_aDataPool.Unlink( hHash ); - } - - // Remove the element. - m_aDataPool.Remove( hHash ); -} - -//----------------------------------------------------------------------------- -// Purpose: Remove all elements from the hash -//----------------------------------------------------------------------------- -template inline void CUtlHashFast::RemoveAll( void ) -{ - m_aBuckets.RemoveAll(); - m_aDataPool.RemoveAll(); -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template inline UtlHashFastHandle_t CUtlHashFast::Find( unsigned int uiKey ) -{ - // hash the "key" - get the correct hash table "bucket" - int iBucket = HashFuncs::Hash( uiKey, m_uiBucketMask ); - - for ( int iElement = m_aBuckets[iBucket]; iElement != m_aDataPool.InvalidIndex(); iElement = m_aDataPool.Next( iElement ) ) - { - if ( m_aDataPool[iElement].m_uiKey == uiKey ) - return iElement; - } - - return InvalidHandle(); -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data &CUtlHashFast::Element( UtlHashFastHandle_t hHash ) -{ - return ( m_aDataPool[hHash].m_Data ); -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data const &CUtlHashFast::Element( UtlHashFastHandle_t hHash ) const -{ - return ( m_aDataPool[hHash].m_Data ); -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data &CUtlHashFast::operator[]( UtlHashFastHandle_t hHash ) -{ - return ( m_aDataPool[hHash].m_Data ); -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data const &CUtlHashFast::operator[]( UtlHashFastHandle_t hHash ) const -{ - return ( m_aDataPool[hHash].m_Data ); -} - -//============================================================================= -// -// Fixed Hash -// -// Number of buckets must be a power of 2. -// Key must be 32-bits (unsigned int). -// -typedef int UtlHashFixedHandle_t; - -template -class CUtlHashFixedGenericHash -{ -public: - static int Hash( int key, int bucketMask ) - { - int hash = HashIntConventional( key ); - if ( NUM_BUCKETS <= USHRT_MAX ) - { - hash ^= ( hash >> 16 ); - } - if ( NUM_BUCKETS <= UCHAR_MAX ) - { - hash ^= ( hash >> 8 ); - } - return ( hash & bucketMask ); - } -}; - -template -class CUtlHashFixed -{ -public: - - // Constructor/Deconstructor. - CUtlHashFixed(); - ~CUtlHashFixed(); - - // Memory. - void Purge( void ); - - // Invalid handle. - static UtlHashFixedHandle_t InvalidHandle( void ) { return ( UtlHashFixedHandle_t )~0; } - - // Size. - int Count( void ); - - // Insertion. - UtlHashFixedHandle_t Insert( unsigned int uiKey, const Data &data ); - UtlHashFixedHandle_t FastInsert( unsigned int uiKey, const Data &data ); - - // Removal. - void Remove( UtlHashFixedHandle_t hHash ); - void RemoveAll( void ); - - // Retrieval. - UtlHashFixedHandle_t Find( unsigned int uiKey ); - - Data &Element( UtlHashFixedHandle_t hHash ); - Data const &Element( UtlHashFixedHandle_t hHash ) const; - Data &operator[]( UtlHashFixedHandle_t hHash ); - Data const &operator[]( UtlHashFixedHandle_t hHash ) const; - - //protected: - - // Templatized for memory tracking purposes - template - struct HashFixedData_t_ - { - unsigned int m_uiKey; - Data_t m_Data; - }; - - typedef HashFixedData_t_ HashFixedData_t; - - enum - { - BUCKET_MASK = NUM_BUCKETS - 1 - }; - CUtlPtrLinkedList m_aBuckets[NUM_BUCKETS]; - int m_nElements; -}; - -//----------------------------------------------------------------------------- -// Purpose: Constructor -//----------------------------------------------------------------------------- -template CUtlHashFixed::CUtlHashFixed() -{ - Purge(); -} - -//----------------------------------------------------------------------------- -// Purpose: Deconstructor -//----------------------------------------------------------------------------- -template CUtlHashFixed::~CUtlHashFixed() -{ - Purge(); -} - -//----------------------------------------------------------------------------- -// Purpose: Destroy dynamically allocated hash data. -//----------------------------------------------------------------------------- -template inline void CUtlHashFixed::Purge( void ) -{ - RemoveAll(); -} - -//----------------------------------------------------------------------------- -// Purpose: Return the number of elements in the hash. -//----------------------------------------------------------------------------- -template inline int CUtlHashFixed::Count( void ) -{ - return m_nElements; -} - -//----------------------------------------------------------------------------- -// Purpose: Insert data into the hash table given its key (unsigned int), with -// a check to see if the element already exists within the tree. -//----------------------------------------------------------------------------- -template inline UtlHashFixedHandle_t CUtlHashFixed::Insert( unsigned int uiKey, const Data &data ) -{ - // Check to see if that key already exists in the buckets (should be unique). - UtlHashFixedHandle_t hHash = Find( uiKey ); - if( hHash != InvalidHandle() ) - return hHash; - - return FastInsert( uiKey, data ); -} - -//----------------------------------------------------------------------------- -// Purpose: Insert data into the hash table given its key (unsigned int), -// without a check to see if the element already exists within the tree. -//----------------------------------------------------------------------------- -template inline UtlHashFixedHandle_t CUtlHashFixed::FastInsert( unsigned int uiKey, const Data &data ) -{ - int iBucket = HashFuncs::Hash( uiKey, NUM_BUCKETS - 1 ); - UtlPtrLinkedListIndex_t iElem = m_aBuckets[iBucket].AddToHead(); - - HashFixedData_t *pHashData = &m_aBuckets[iBucket][iElem]; - - Assert( (UtlPtrLinkedListIndex_t)pHashData == iElem ); - - // Add data to new element. - pHashData->m_uiKey = uiKey; - pHashData->m_Data = data; - - m_nElements++; - return (UtlHashFixedHandle_t)pHashData; -} - -//----------------------------------------------------------------------------- -// Purpose: Remove a given element from the hash. -//----------------------------------------------------------------------------- -template inline void CUtlHashFixed::Remove( UtlHashFixedHandle_t hHash ) -{ - HashFixedData_t *pHashData = (HashFixedData_t *)hHash; - Assert( Find(pHashData->m_uiKey) != InvalidHandle() ); - int iBucket = HashFuncs::Hash( pHashData->m_uiKey, NUM_BUCKETS - 1 ); - m_aBuckets[iBucket].Remove( (UtlPtrLinkedListIndex_t)pHashData ); - m_nElements--; -} - -//----------------------------------------------------------------------------- -// Purpose: Remove all elements from the hash -//----------------------------------------------------------------------------- -template inline void CUtlHashFixed::RemoveAll( void ) -{ - for ( int i = 0; i < NUM_BUCKETS; i++ ) - { - m_aBuckets[i].RemoveAll(); - } - m_nElements = 0; -} - -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template inline UtlHashFixedHandle_t CUtlHashFixed::Find( unsigned int uiKey ) -{ - int iBucket = HashFuncs::Hash( uiKey, NUM_BUCKETS - 1 ); - CUtlPtrLinkedList &bucket = m_aBuckets[iBucket]; - - for ( UtlPtrLinkedListIndex_t iElement = bucket.Head(); iElement != bucket.InvalidIndex(); iElement = bucket.Next( iElement ) ) - { - if ( bucket[iElement].m_uiKey == uiKey ) - return (UtlHashFixedHandle_t)iElement; - } - - return InvalidHandle(); -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data &CUtlHashFixed::Element( UtlHashFixedHandle_t hHash ) -{ - return ((HashFixedData_t *)hHash)->m_Data; -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data const &CUtlHashFixed::Element( UtlHashFixedHandle_t hHash ) const -{ - return ((HashFixedData_t *)hHash)->m_Data; -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data &CUtlHashFixed::operator[]( UtlHashFixedHandle_t hHash ) -{ - return ((HashFixedData_t *)hHash)->m_Data; -} - -//----------------------------------------------------------------------------- -// Purpose: Return data given a hash handle. -//----------------------------------------------------------------------------- -template inline Data const &CUtlHashFixed::operator[]( UtlHashFixedHandle_t hHash ) const -{ - return ((HashFixedData_t *)hHash)->m_Data; -} - -#endif // UTLHASH_H diff --git a/Resources/NetHook/tier1/utlhashdict.h b/Resources/NetHook/tier1/utlhashdict.h deleted file mode 100644 index 4826b673..00000000 --- a/Resources/NetHook/tier1/utlhashdict.h +++ /dev/null @@ -1,342 +0,0 @@ -//========== Copyright © 2005, Valve Corporation, All rights reserved. ======== -// -// Purpose: -// -//============================================================================= - -#ifndef UTLHASHDICT_H -#define UTLHASHDICT_H - -#if defined( _WIN32 ) -#pragma once -#endif - -#include "tier1/utlhash.h" -#include "tier1/generichash.h" -#include "mathlib/mathlib.h" - -//----------------------------------------------------------------------------- -// -//----------------------------------------------------------------------------- -template -class CUtlHashDict -{ -public: - // constructor, destructor - CUtlHashDict( int bucketCount = 16, int growCount = 0, int initCount = 0 ); - ~CUtlHashDict( ); - - // gets particular elements - T& Element( unsigned i ); - const T& Element( unsigned i ) const; - T& operator[]( unsigned i ); - const T& operator[]( unsigned i ) const; - - // gets element names - char const *GetElementName( unsigned i ) const; - - // Number of elements - int Count() const; - - // Checks if a node is valid and in the tree - bool IsValidIndex( unsigned i ) const; - - // Invalid index - static unsigned InvalidHandle(); - - // Insert method (inserts in order) - unsigned Insert( const char *pName, const T &element ); - unsigned Insert( const char *pName ); - - // Find method - unsigned Find( const char *pName ) const; - - // Remove methods - void RemoveAt( unsigned i ); - void Remove( const char *pName ); - void RemoveAll( ); - - // Purge memory - void Purge(); - void PurgeAndDeleteElements(); // Call delete on each element. - - // Iteration methods - unsigned First() const; - unsigned Next( unsigned i ) const; - -protected: - struct Entry_t - { - const char *pszSymbol; - T value; - }; - - template - class CCompare - { - public: - CCompare( int ignored ) {} - - bool operator()( const Entry_t &entry1, const Entry_t &entry2 ) const - { - return !( ( bCaseInsensitive ) ? stricmp( entry1.pszSymbol, entry2.pszSymbol ) : strcmp( entry1.pszSymbol, entry2.pszSymbol ) ); - } - }; - - template - class CHash - { - public: - CHash( int ignored ) {} - - unsigned operator()( const Entry_t &entry ) const - { - return !( ( bCaseInsensitive ) ? HashStringCaseless( entry.pszSymbol ) : HashString( entry.pszSymbol ) ); - } - }; - - typedef CUtlHash, CHash > CHashTable; - CHashTable m_Elements; - int m_nCount; -}; - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- -template -CUtlHashDict::CUtlHashDict( int bucketCount = 16, int growCount = 0, int initCount = 0 ) : - m_Elements( SmallestPowerOfTwoGreaterOrEqual(bucketCount), growCount, initCount ) -{ - Assert( SmallestPowerOfTwoGreaterOrEqual(bucketCount) <= 0xffff ); -} - -template -CUtlHashDict::~CUtlHashDict() -{ - Purge(); -} - -//----------------------------------------------------------------------------- -// gets particular elements -//----------------------------------------------------------------------------- -template -inline T& CUtlHashDict::Element( unsigned i ) -{ - return m_Elements[i].value; -} - -template -inline const T& CUtlHashDict::Element( unsigned i ) const -{ - return m_Elements[i].value; -} - -//----------------------------------------------------------------------------- -// gets element names -//----------------------------------------------------------------------------- -template -inline char const *CUtlHashDict::GetElementName( unsigned i ) const -{ - return m_Elements[i].pszSymbol; -} - -template -inline T& CUtlHashDict::operator[]( unsigned i ) -{ - return m_Elements[i].value; -} - -template -inline const T & CUtlHashDict::operator[]( unsigned i ) const -{ - return m_Elements[i].value; -} - -//----------------------------------------------------------------------------- -// Num elements -//----------------------------------------------------------------------------- -template -inline int CUtlHashDict::Count() const -{ - Assert( m_nCount == m_Elements.Count() ); - return m_nCount; -} - - -//----------------------------------------------------------------------------- -// Checks if a node is valid and in the tree -//----------------------------------------------------------------------------- -template -inline bool CUtlHashDict::IsValidIndex( unsigned i ) const -{ - return m_Elements.IsValidHandle(i); -} - - -//----------------------------------------------------------------------------- -// Invalid index -//----------------------------------------------------------------------------- -template -inline unsigned CUtlHashDict::InvalidHandle() -{ - return CHashTable::InvalidHandle(); -} - - -//----------------------------------------------------------------------------- -// Delete a node from the tree -//----------------------------------------------------------------------------- -template -void CUtlHashDict::RemoveAt(unsigned elem) -{ - if ( bDupeStrings ) - { - free( (void *)m_Elements[elem].pszSymbol ); - } - m_Elements.Remove(elem); - m_nCount--; -} - - -//----------------------------------------------------------------------------- -// remove a node in the tree -//----------------------------------------------------------------------------- -template void CUtlHashDict::Remove( const char *search ) -{ - unsigned node = Find( search ); - if (node != InvalidHandle()) - { - RemoveAt(node); - } -} - - -//----------------------------------------------------------------------------- -// Removes all nodes from the tree -//----------------------------------------------------------------------------- -template -void CUtlHashDict::RemoveAll() -{ - if ( bDupeStrings ) - { - typename UtlHashHandle_t index = m_Elements.GetFirstHandle(); - while ( index != m_Elements.InvalidHandle() ) - { - free( (void *)m_Elements[index].pszSymbol ); - index = m_Elements.GetNextHandle( index ); - } - } - - m_Elements.RemoveAll(); - m_nCount = 0; -} - -template -void CUtlHashDict::Purge() -{ - if ( bDupeStrings ) - { - typename UtlHashHandle_t index = m_Elements.GetFirstHandle(); - while ( index != m_Elements.InvalidHandle() ) - { - free( (void *)m_Elements[index].pszSymbol ); - index = m_Elements.GetNextHandle( index ); - } - } - - m_Elements.Purge(); - m_nCount = 0; -} - - -template -void CUtlHashDict::PurgeAndDeleteElements() -{ - // Delete all the elements. - unsigned index = m_Elements.GetFirstHandle(); - while ( index != m_Elements.InvalidHandle() ) - { - if ( bDupeStrings ) - { - free( (void *)m_Elements[index].pszSymbol ); - } - delete m_Elements[index].value; - index = m_Elements.GetNextHandle( index ); - } - - m_Elements.RemoveAll(); - m_nCount = 0; -} - - -//----------------------------------------------------------------------------- -// inserts a node into the tree -//----------------------------------------------------------------------------- -template -unsigned CUtlHashDict::Insert( const char *pName, const T &element ) -{ - MEM_ALLOC_CREDIT_CLASS(); - m_nCount++; - Entry_t entry = - { - (bDupeStrings) ? strdup( pName ) : pName, - element - }; - bool bInserted; - unsigned result = m_Elements.Insert( entry, &bInserted ); - if ( bDupeStrings && !bInserted ) - { - free( (void *)entry.pszSymbol ); - } - return result; -} - -template -unsigned CUtlHashDict::Insert( const char *pName ) -{ - MEM_ALLOC_CREDIT_CLASS(); - m_nCount++; - Entry_t entry = - { - (bDupeStrings) ? strdup( pName ) : pName - }; - bool bInserted; - unsigned result = m_Elements.Insert( entry, &bInserted ); - if ( bDupeStrings && !bInserted ) - { - free( (void *)entry.pszSymbol ); - } - return result; -} - - -//----------------------------------------------------------------------------- -// finds a node in the tree -//----------------------------------------------------------------------------- -template -unsigned CUtlHashDict::Find( const char *pName ) const -{ - MEM_ALLOC_CREDIT_CLASS(); - if ( pName ) - return m_Elements.Find( *((Entry_t *)&pName) ); - else - return InvalidHandle(); -} - - -//----------------------------------------------------------------------------- -// Iteration methods -//----------------------------------------------------------------------------- -template -unsigned CUtlHashDict::First() const -{ - return m_Elements.GetFirstHandle(); -} - -template -unsigned CUtlHashDict::Next( unsigned i ) const -{ - return m_Elements.GetNextHandle(i); -} - -#endif // UTLHASHDICT_H diff --git a/Resources/NetHook/tier1/utlintrusivelist.h b/Resources/NetHook/tier1/utlintrusivelist.h deleted file mode 100644 index a09ac7bb..00000000 --- a/Resources/NetHook/tier1/utlintrusivelist.h +++ /dev/null @@ -1,772 +0,0 @@ -//===== Copyright © 1996-2006, Valve Corporation, All rights reserved. ======// -// -// Purpose: Intrusive linked list templates, both for singly and doubly linked lists -// -// $Revision: $ -// $NoKeywords: $ -//===========================================================================// - -#ifndef UTILINTRUSIVELIST_H -#define UTILINTRUSIVELIST_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "basetypes.h" -#include "utlmemory.h" -#include "tier0/dbg.h" - - -// -// These templates are used for intrusive linked list classes. Intrusive linked list templates -// force the structs and classes contained within them to have their own m_pNext, (optionally), -// m_pPrev, and other fileds contained within. All memory management is up to the caller and -// their classes. No data will ever be copied. Nodes can only exist on one list at a time, because -// of only having on m_Next field, and manipulating the list while walking it requires that care on -// the part of the caller. All accessing and searching functions work by passing and returning -// pointers. -// -// -// -// naming and field conventions: -// functions referring to a DList are for doubly linked lists. nodes must have m_pHead and -// m_pPrev pointer fields. -// Functions using Priority require an m_Priority field, which must be comparable. -// -// Some functions are meanto for use with lists which maintain both a head and tail pointer -// in order to support fast adding to the end. - - -/// validates that the doubly linked list has the proper structure, pointer-wise - -namespace IntrusiveList -{ -#ifdef SUPERSLOW_DEBUG_VERSION - template inline void ValidateDList(T *head) - { - if (head) - { - Assert(head->m_pPrev==0); - } - while(head) - { - if (head->m_pNext) - { - Assert(head->m_pNext->m_pPrev==head); - } - if (head->m_pPrev) - { - Assert(head->m_pPrev->m_pNext==head); - } - head=head->m_pNext; - } - } -#else - template inline void ValidateDList(T * /*head*/) - { - } -#endif - - - -// move a node in a doubly linked list backwards one step. - template inline void MoveDNodeBackwards( T *which, T * &head) - { - if (which->m_pPrev) - { - T *p=which->m_pPrev; - T *pp=p->m_pPrev; - T *n=which->m_pNext; - Assert(p->m_pNext == which); - if (n) - { - Assert(n->m_pPrev==which); - n->m_pPrev=p; - } - if (pp) - { - Assert(pp->m_pNext==p); - pp->m_pNext=which; - } - else - { - head=which; // this node is the new root! - } - which->m_pNext=p; - which->m_pPrev=pp; - p->m_pNext=n; - p->m_pPrev=which; - } - ValidateDList(head); - } - - - - // removes node 'which' from doubly linked list with 'head' - template inline void RemoveFromDList(T * &head, T *which) - { - if (which->m_pPrev) - { - Assert(which->m_pPrev->m_pNext==which); - which->m_pPrev->m_pNext=which->m_pNext; - if (which->m_pNext) - { - Assert(which->m_pNext->m_pPrev==which); - which->m_pNext->m_pPrev=which->m_pPrev; - } - } - else - { - if (head==which) - { - head=which->m_pNext; - if (head) - { - Assert(head->m_pPrev==which); - head->m_pPrev=0; - } - } - } - which->m_pNext=which->m_pPrev=0; - ValidateDList(head); - - } - - //checks to see if node is in doubly linked list - template bool OnDList(T const *head, T const *which) - { - return (head==which) || (which->m_pNext !=0) || (which->m_pPrev !=0); - } - - // add a node to the end of a singly linked list - template void AddToDTail(T * & head, T * node) - { - node->m_pNext=0; - if (! head) - { - head=node; - } - else - { - T *ptr=head; - while(ptr->m_pNext) - { - ptr=ptr->m_pNext; - } - ptr->m_pNext=node; - node->m_pPrev=ptr; // - } - } - - // add a node to end of doubly linked list. - template inline void AddToDHead(T * &head, T *which) - { - which->m_pNext=head; - if (head) - { - head->m_pPrev=which; - } - which->m_pPrev=0; - head=which; - ValidateDList(head); - } - - // add a node to front of doubly linked list which maintains a tail ptr - template inline void AddToDHeadWithTailPtr(T * &head, T *which, T * &tailptr) - { - which->m_pNext=head; - if (head) - { - head->m_pPrev=which; - } - else - { - tailptr=which; - } - which->m_pPrev=0; - head=which; - ValidateDList(head); - } - - // add a node to end of doubly linked list which maintains a tail ptr - template inline void AddToDTailWithTailPtr(T * &head, T *which, T * & tailptr) - { - if (! tailptr) - { - Assert(! head); - which->m_pPrev=which->m_pNext=0; - tailptr=head=which; - } - else - { - which->m_pNext=0; - which->m_pPrev=tailptr; - tailptr->m_pNext=which; - tailptr=which; - } - } - - // Remove a node from a dlist , maintaining the tail ptr. node is not 'delete' d - template inline void RemoveFromDListWithTailPtr(T * &head, T *which, T * & tailptr) - { - if (which==tailptr) - { - tailptr=which->m_pPrev; - } - if (which->m_pPrev) - { - Assert(which->m_pPrev->m_pNext==which); - which->m_pPrev->m_pNext=which->m_pNext; - if (which->m_pNext) - { - Assert(which->m_pNext->m_pPrev==which); - which->m_pNext->m_pPrev=which->m_pPrev; - } - } - else - { - if (head==which) - { - head=which->m_pNext; - if (head) - { - Assert(head->m_pPrev==which); - head->m_pPrev=0; - } - } - } - which->m_pNext=which->m_pPrev=0; - ValidateDList(head); - - } - - // this function removes a node, and delete's the node - template inline void DeleteFromDListWithTailPtr(T * &head, T *which, T * & tailptr) - { - T *tmp=which; - if (which==tailptr) - { - tailptr=which->m_pPrev; - } - if (which->m_pPrev) - { - Assert(which->m_pPrev->m_pNext==which); - which->m_pPrev->m_pNext=which->m_pNext; - if (which->m_pNext) - { - Assert(which->m_pNext->m_pPrev==which); - which->m_pNext->m_pPrev=which->m_pPrev; - } - } - else - { - if (head==which) - { - head=which->m_pNext; - if (head) - { - Assert(head->m_pPrev==which); - head->m_pPrev=0; - } - } - } - which->m_pNext=which->m_pPrev=0; - delete tmp; - ValidateDList(head); - } - - // Add a node to a d-list, keeping the highest priority nodes first. This is a simple - // linear search to insert, NOT a O(logn) heap. - template inline void AddToDPriority(T * &head, T *which) - { - T* prevnode=0; - for(T *curnode=head;curnode;curnode=curnode->m_pNext) - { - if (which->m_Priority>=curnode->m_Priority) - break; - prevnode=curnode; - } - // now, we have either run out of list, or we have found an - // element to add this one before - if (! prevnode) - { - AddToDHead(head,which); - } - else - { - which->m_pNext=prevnode->m_pNext; - prevnode->m_pNext=which; - which->m_pPrev=prevnode; - if (which->m_pNext) - which->m_pNext->m_pPrev=which; - } - } - - // same as AddToDPriority, except with reverse order - template inline void AddToDPriorityLowestFirst(T * &head, T *which) - { - T* prevnode=0; - for(T *curnode=head;curnode;curnode=curnode->m_pNext) - { - if (which->m_Priority<=curnode->m_Priority) - break; - prevnode=curnode; - } - // now, we have either run out of list, or we have found an - // element to add this one before - if (! prevnode) - { - AddToDHead(head,which); - } - else - { - which->m_pNext=prevnode->m_pNext; - prevnode->m_pNext=which; - which->m_pPrev=prevnode; - if (which->m_pNext) - which->m_pNext->m_pPrev=which; - } - } - - - // return a pointer to the last node in a singly-linked (or doubly) list - template T * LastNode(T * head) - { - if (head) - { - while(head->m_pNext) - { - head=head->m_pNext; - } - } - return head; - } - - - // Remove from a singly linked list. no delete called. - template void RemoveFromList(T * & head, V *which) - { - if (head==which) - { - head=which->m_pNext; - } - else - { - for(T * i=head; i; i=i->m_pNext) - { - if (i->m_pNext==which) - { - i->m_pNext=which->m_pNext; - return; - } - } - } - } - - // same as RemoveFromList, but 'delete' is called. - template void DeleteFromList(T * & head, V *which) - { - T *tmp; - if (head==which) - { - tmp=which->m_pNext; - delete(head); - head=tmp; - } - else - { - for(T * i=head; i; i=i->m_pNext) - { - if (i->m_pNext==which) - { - tmp=which->m_pNext; - delete(which); - i->m_pNext=tmp; - return; - } - } - } - } - - // find the position in a list of a node. -1 if not found. Linear search. - // nodes must have comparison functions - template int PositionInList(T *head, V *node) - { - int pos=0; - while(head) - { - if (head==node) return pos; - head=head->m_pNext; - pos++; - } - return -1; - } - - // find the Nth node in a list. null if index too high. - template T *NthNode(T * head, int idx) - { - while(idx && head) - { - idx--; - head=head->m_pNext; - } - return head; - } - - //Add a node to the head of a singly-linked - // Note that the head var passed to this will be modified. - template static inline void AddToHead(T * & head, V * node) - { - node->m_pNext=head; - head=node; - } - - //Add a node to the tail of a singly-linked. Not fast - // Note that the head var passed to this will be modified. - template static inline void AddToTail(T * & head, V * node) - { - node->m_pNext = NULL; - if ( ! head ) - head = node; - else - { - T *pLastNode = head; - while( pLastNode->m_pNext ) - pLastNode = pLastNode->m_pNext; - pLastNode->m_pNext = node; - } - } - - //Add a node to the head of a singly-linked list, maintaining a tail pointer - template static inline void AddToHead(T * & head, T * &tail,V * node) - { - if (! head) - { - tail=node; - } - node->m_pNext=head; - head=node; - } - - - - // return the node in head before in a singly linked list. returns null if head is empty, n is - // null, or if n is the first node. not fast. - template static inline T * PrevNode(T *head, T *node) - { - for(T *i=head;i;i=i->m_pNext) - { - if (i->m_pNext == node) - break; - } - return i; - } - - - // add a node to the end of a singly linked list. Not fast. - template void AddToEnd(T * & head, V * node) - { - node->m_pNext=0; - if (! head) - { - head=node; - } - else - { - T *ptr=head; - while(ptr->m_pNext) - { - ptr=ptr->m_pNext; - } - ptr->m_pNext=node; - } - } - - // add a node to the end of a singly linked list, maintaining a tail pointer. - // the head and tail pointer can be modified by this routine. - template void AddToEndWithTail(T * & head, T * & tail,V * node) - { - Assert((head && tail) || ((!head) && (!tail))); - node->m_pNext=0; - if (! head) - { - head=tail=node; - } - else - { - tail->m_pNext=node; - tail=node; - } - } - - // Add a node to a singly linked list, sorting by the m_Name field - template void AddSortedByName(T * & head, T * node) - { - if ( (! head) || // empty list? - (stricmp(node->m_Name,head->m_Name)==-1)) // or we should be first? - { - node->m_pNext=head; // make us head - head=node; - } - else - { - for(T *t=head;t->m_pNext;t=t->m_pNext) // find the node we should be before - if (stricmp(t->m_pNext->m_Name,node->m_Name)>=0) - break; - node->m_pNext=t->m_pNext; - t->m_pNext=node; - } - } - - // count # of elements in list - template int ListLength(T *head) - { - int len=0; - while(head) - { - len++; - head=head->m_pNext; - } - return len; - } - - // this will kill a list if the list is of objects which automatically - // remove themselves from the list when delete is called - template void KillList(T * & head) - { - while(head) - { - delete head; - } - } - - - // this will kill all elements in a list if - // the elements are of a type which does NOT remove itself from - // the list when the destructor is called. - template void DeleteList(T * & head) - { - while (head) - { - T* tmp=head->m_pNext; - delete head; - head=tmp; - } - } - - // find a named node in any list which has both a Next field and a Name field. - template static inline T * FindNamedNode(T * head, char const *name) - { - for(;head && stricmp(head->m_Name,name); head=head->m_pNext) - { - } - return head; - } - - template static inline T * FindNamedNodeCaseSensitive(T * head, char const *name) - { - for(;head && strcmp(head->m_Name,name); head=head->m_pNext) - { - } - return head; - } - - // find data in a singly linked list, using equality match on any field - // usage: FindNodeByField(listptr,data,&list::fieldname) - template static inline T * FindNodeByField(T * head, U data, U V::*field) - { - while(head) - { - if (data==(*head).*field) - return head; - head=head->m_pNext; - } - return 0; - } - - // find a node and its predecessor, matching on equality of a given field. - // usage: FindNodeByFieldWithPrev(listptr,data,&list::fieldname, prevptr) - template static inline T * FindNodeByFieldWithPrev(T * head, U data, U V::*field, T * & prev) - { - prev=0; - for(T *i=head; i; i=i->m_pNext) - { - if(data==(*i).*field) - return i; - prev=i; - } - prev=0; - return 0; - } - - - /// sort a list. comparefn should return 0 if the items are equal, 1 if A goes first, and -1 if A goes last. - // NOT fast. - template void SortList(T * &head, int (*comparefn)(T * a, T * b)) - { - int didswap=1; - while(didswap) - { - didswap=0; - T *prev=0; - for(T *i=head;i && i->m_pNext; i=i->m_pNext) - { - /// compare i and i+1 - int rslt=(*comparefn)(i,i->m_pNext); - if (rslt==-1) - { - /// need to swap - didswap=1; - T *newfirst=i->m_pNext; - if (prev) - { - prev->m_pNext=newfirst; - i->m_pNext=newfirst->m_pNext; - newfirst->m_pNext=i; - } - else - { - head=i->m_pNext; - i->m_pNext=newfirst->m_pNext; - newfirst->m_pNext=i; - } - i=newfirst; - } - prev=i; - } - } - } - - // sort a doubly linked list. NOt fast. - template void SortDList(T * & head, int (*comparefn)(T * a, T * b)) - { - SortList(head,comparefn); - /// now, regen prev ptrs - T *prev=0; - for(T *i=head;i;i=i->m_pNext) - { - i->m_pPrev=prev; - prev=i; - } - } - - // reverse a singly linked list. not recommended for anything other than valve programming - // interview :-) - template T *ReversedList( T * head ) - { - T * pNewHead=NULL; - while( head ) - { - T *pNext=head->m_pNext; -#ifdef INTERVIEW_QUESTION - head->m_pNext=pNewHead; - pNewHead = head; -#else - AddToHead( pNewHead, head ); -#endif - head = pNext; - } - return pNewHead; - } -}; - -// singly linked list -template class CUtlIntrusiveList -{ -public: - T *m_pHead; - - FORCEINLINE CUtlIntrusiveList(void) - { - m_pHead = NULL; - } - - FORCEINLINE void AddToHead( T * node ) - { - IntrusiveList::AddToHead( m_pHead, node ); - } - - FORCEINLINE void AddToTail( T * node ) - { - IntrusiveList::AddToTail( m_pHead, node ); - } - - void RemoveNode(T *which) - { - IntrusiveList::RemoveFromList( m_pHead, which ); - } - - // this will kill a list if the list is of objects which automatically - // remove themselves from the list when delete is called - void KillList( void ) - { - while(m_pHead) - { - delete m_pHead; - } - } - - - // return the node in head before in a singly linked list. returns null if head is empty, n is - // null, or if n is the first node. not fast. Fast for dlists - T * PrevNode(T *node) - { - return IntrusiveList::PrevNode( m_pHead, node ); - } - - int NthNode( int n ) - { - return NthNode( m_pHead, n ); - } - - // this will kill all elements in a list if - // the elements are of a type which does NOT remove itself from - // the list when the destructor is called. - void Purge( void ) - { - while (m_pHead) - { - T* tmp=m_pHead->m_pNext; - delete m_pHead; - m_pHead=tmp; - } - } - - int Count( void ) - { - return IntrusiveList::ListLength( m_pHead ); - } - -}; - -// doubly linked list -template class CUtlIntrusiveDList : public CUtlIntrusiveList -{ -public: - - FORCEINLINE void AddToHead( T * node ) - { - IntrusiveList::AddToDHead( CUtlIntrusiveList::m_pHead, node ); - } - FORCEINLINE void AddToTail( T * node ) - { - IntrusiveList::AddToDTail( CUtlIntrusiveList::m_pHead, node ); - } - - void RemoveNode(T *which) - { - IntrusiveList::RemoveFromDList( CUtlIntrusiveList::m_pHead, which ); - } - - T * PrevNode(T *node) - { - return ( node )?node->m_Prev:NULL; - } - -}; - - - - -#endif diff --git a/Resources/NetHook/tier1/utllinkedlist.h b/Resources/NetHook/tier1/utllinkedlist.h deleted file mode 100644 index de87cebf..00000000 --- a/Resources/NetHook/tier1/utllinkedlist.h +++ /dev/null @@ -1,1018 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Linked list container class -// -// $Revision: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLLINKEDLIST_H -#define UTLLINKEDLIST_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/basetypes.h" -#include "utlmemory.h" -#include "utlfixedmemory.h" -#include "utlblockmemory.h" -#include "tier0/dbg.h" - - -// This is a useful macro to iterate from head to tail in a linked list. -#define FOR_EACH_LL( listName, iteratorName ) \ - for( int iteratorName=listName.Head(); iteratorName != listName.InvalidIndex(); iteratorName = listName.Next( iteratorName ) ) - -//----------------------------------------------------------------------------- -// class CUtlLinkedList: -// description: -// A lovely index-based linked list! T is the class type, I is the index -// type, which usually should be an unsigned short or smaller. However, -// you must avoid using 16- or 8-bit arithmetic on PowerPC architectures; -// therefore you should not use UtlLinkedListElem_t::I as the type of -// a local variable... ever. PowerPC integer arithmetic must be 32- or -// 64-bit only; otherwise performance plummets. -//----------------------------------------------------------------------------- - -template -struct UtlLinkedListElem_t -{ - T m_Element; - I m_Previous; - I m_Next; - -private: - // No copy constructor for these... - UtlLinkedListElem_t( const UtlLinkedListElem_t& ); -}; - - -// Class S is the storage type; the type you can use to save off indices in -// persistent memory. Class I is the iterator type, which is what should be used -// in local scopes. I defaults to be S, but be aware that on the 360, 16-bit -// arithmetic is catastrophically slow. Therefore you should try to save shorts -// in memory, but always operate on 32's or 64's in local scope. -// The ideal parameter order would be TSMI (you are more likely to override M than I) -// but since M depends on I we can't have the defaults in that order, alas. -template , I > > -class CUtlLinkedList -{ -public: - typedef T ElemType_t; - typedef S IndexType_t; // should really be called IndexStorageType_t, but that would be a huge change -typedef I IndexLocalType_t; - typedef M MemoryAllocator_t; - - // constructor, destructor - CUtlLinkedList( int growSize = 0, int initSize = 0 ); - ~CUtlLinkedList(); - - // gets particular elements - T& Element( I i ); - T const& Element( I i ) const; - T& operator[]( I i ); - T const& operator[]( I i ) const; - - // Make sure we have a particular amount of memory - void EnsureCapacity( int num ); - - void SetGrowSize( int growSize ); - - // Memory deallocation - void Purge(); - - // Delete all the elements then call Purge. - void PurgeAndDeleteElements(); - - // Insertion methods.... - I InsertBefore( I before ); - I InsertAfter( I after ); - I AddToHead( ); - I AddToTail( ); - - I InsertBefore( I before, T const& src ); - I InsertAfter( I after, T const& src ); - I AddToHead( T const& src ); - I AddToTail( T const& src ); - - // Find an element and return its index or InvalidIndex() if it couldn't be found. - I Find( const T &src ) const; - - // Look for the element. If it exists, remove it and return true. Otherwise, return false. - bool FindAndRemove( const T &src ); - - // Removal methods - void Remove( I elem ); - void RemoveAll(); - - // Allocation/deallocation methods - // If multilist == true, then list list may contain many - // non-connected lists, and IsInList and Head + Tail are meaningless... - I Alloc( bool multilist = false ); - void Free( I elem ); - - // list modification - void LinkBefore( I before, I elem ); - void LinkAfter( I after, I elem ); - void Unlink( I elem ); - void LinkToHead( I elem ); - void LinkToTail( I elem ); - - // invalid index - inline static S InvalidIndex() { return ( S )M::InvalidIndex(); } - inline static size_t ElementSize() { return sizeof( ListElem_t ); } - - // list statistics - int Count() const; - I MaxElementIndex() const; - - // Traversing the list - I Head() const; - I Tail() const; - I Previous( I i ) const; - I Next( I i ) const; - - // Are nodes in the list or valid? - bool IsValidIndex( I i ) const; - bool IsInList( I i ) const; - -protected: - - // What the linked list element looks like - typedef UtlLinkedListElem_t ListElem_t; - - // constructs the class - I AllocInternal( bool multilist = false ); - void ConstructList(); - - // Gets at the list element.... - ListElem_t& InternalElement( I i ) { return m_Memory[i]; } - ListElem_t const& InternalElement( I i ) const { return m_Memory[i]; } - - // copy constructors not allowed - CUtlLinkedList( CUtlLinkedList const& list ) { Assert(0); } - - M m_Memory; - I m_Head; - I m_Tail; - I m_FirstFree; - I m_ElementCount; // The number actually in the list - typename M::Iterator_t m_LastAlloc; // the last index allocated - - // For debugging purposes; - // it's in release builds so this can be used in libraries correctly - ListElem_t *m_pElements; - - FORCEINLINE M const &Memory( void ) const - { - return m_Memory; - } - - void ResetDbgInfo() - { - m_pElements = m_Memory.Base(); - } -}; - - -// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice -template < class T > -class CUtlFixedLinkedList : public CUtlLinkedList< T, int, true, int, CUtlFixedMemory< UtlLinkedListElem_t< T, int > > > -{ -public: - CUtlFixedLinkedList( int growSize = 0, int initSize = 0 ) - : CUtlLinkedList< T, int, true, int, CUtlFixedMemory< UtlLinkedListElem_t< T, int > > >( growSize, initSize ) {} - - bool IsValidIndex( int i ) const - { - if ( !Memory().IsIdxValid( i ) ) - return false; - -#ifdef _DEBUG // it's safe to skip this here, since the only way to get indices after m_LastAlloc is to use MaxElementIndex - if ( Memory().IsIdxAfter( i, this->m_LastAlloc ) ) - { - Assert( 0 ); - return false; // don't read values that have been allocated, but not constructed - } -#endif - - return ( Memory()[ i ].m_Previous != i ) || ( Memory()[ i ].m_Next == i ); - } - -private: - int MaxElementIndex() const { Assert( 0 ); return InvalidIndex(); } // fixedmemory containers don't support iteration from 0..maxelements-1 - void ResetDbgInfo() {} -}; - -// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice -template < class T, class I = unsigned short > -class CUtlBlockLinkedList : public CUtlLinkedList< T, I, true, I, CUtlBlockMemory< UtlLinkedListElem_t< T, I >, I > > -{ -public: - CUtlBlockLinkedList( int growSize = 0, int initSize = 0 ) - : CUtlLinkedList< T, I, true, I, CUtlBlockMemory< UtlLinkedListElem_t< T, I >, I > >( growSize, initSize ) {} -protected: - void ResetDbgInfo() {} -}; - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template -CUtlLinkedList::CUtlLinkedList( int growSize, int initSize ) : - m_Memory( growSize, initSize ), m_LastAlloc( m_Memory.InvalidIterator() ) -{ - // Prevent signed non-int datatypes - COMPILE_TIME_ASSERT( sizeof(S) == 4 || ( ( (S)-1 ) > 0 ) ); - ConstructList(); - ResetDbgInfo(); -} - -template -CUtlLinkedList::~CUtlLinkedList( ) -{ - RemoveAll(); -} - -template -void CUtlLinkedList::ConstructList() -{ - m_Head = InvalidIndex(); - m_Tail = InvalidIndex(); - m_FirstFree = InvalidIndex(); - m_ElementCount = 0; -} - - -//----------------------------------------------------------------------------- -// gets particular elements -//----------------------------------------------------------------------------- - -template -inline T& CUtlLinkedList::Element( I i ) -{ - return m_Memory[i].m_Element; -} - -template -inline T const& CUtlLinkedList::Element( I i ) const -{ - return m_Memory[i].m_Element; -} - -template -inline T& CUtlLinkedList::operator[]( I i ) -{ - return m_Memory[i].m_Element; -} - -template -inline T const& CUtlLinkedList::operator[]( I i ) const -{ - return m_Memory[i].m_Element; -} - -//----------------------------------------------------------------------------- -// list statistics -//----------------------------------------------------------------------------- - -template -inline int CUtlLinkedList::Count() const -{ - return m_ElementCount; -} - -template -inline I CUtlLinkedList::MaxElementIndex() const -{ - return m_Memory.NumAllocated(); -} - - -//----------------------------------------------------------------------------- -// Traversing the list -//----------------------------------------------------------------------------- - -template -inline I CUtlLinkedList::Head() const -{ - return m_Head; -} - -template -inline I CUtlLinkedList::Tail() const -{ - return m_Tail; -} - -template -inline I CUtlLinkedList::Previous( I i ) const -{ - Assert( IsValidIndex(i) ); - return InternalElement(i).m_Previous; -} - -template -inline I CUtlLinkedList::Next( I i ) const -{ - Assert( IsValidIndex(i) ); - return InternalElement(i).m_Next; -} - - -//----------------------------------------------------------------------------- -// Are nodes in the list or valid? -//----------------------------------------------------------------------------- - -template -inline bool CUtlLinkedList::IsValidIndex( I i ) const -{ - if ( !m_Memory.IsIdxValid( i ) ) - return false; - - if ( m_Memory.IsIdxAfter( i, m_LastAlloc ) ) - return false; // don't read values that have been allocated, but not constructed - - return ( m_Memory[ i ].m_Previous != i ) || ( m_Memory[ i ].m_Next == i ); -} - -template -inline bool CUtlLinkedList::IsInList( I i ) const -{ - if ( !m_Memory.IsIdxValid( i ) || m_Memory.IsIdxAfter( i, m_LastAlloc ) ) - return false; // don't read values that have been allocated, but not constructed - - return Previous( i ) != i; -} - -/* -template -inline bool CUtlFixedLinkedList::IsInList( int i ) const -{ - return m_Memory.IsIdxValid( i ) && (Previous( i ) != i); -} -*/ - -//----------------------------------------------------------------------------- -// Makes sure we have enough memory allocated to store a requested # of elements -//----------------------------------------------------------------------------- - -template< class T, class S, bool ML, class I, class M > -void CUtlLinkedList::EnsureCapacity( int num ) -{ - MEM_ALLOC_CREDIT_CLASS(); - m_Memory.EnsureCapacity(num); - ResetDbgInfo(); -} - -template< class T, class S, bool ML, class I, class M > -void CUtlLinkedList::SetGrowSize( int growSize ) -{ - RemoveAll(); - m_Memory.Init( growSize ); - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Deallocate memory -//----------------------------------------------------------------------------- - -template -void CUtlLinkedList::Purge() -{ - RemoveAll(); - - m_Memory.Purge(); - m_FirstFree = InvalidIndex(); - - //Routing "m_LastAlloc = m_Memory.InvalidIterator();" through a local const to sidestep an internal compiler error on 360 builds - const typename M::Iterator_t scInvalidIterator = m_Memory.InvalidIterator(); - m_LastAlloc = scInvalidIterator; - ResetDbgInfo(); -} - - -template -void CUtlLinkedList::PurgeAndDeleteElements() -{ - int iNext; - for( int i=Head(); i != InvalidIndex(); i=iNext ) - { - iNext = Next(i); - delete Element(i); - } - - Purge(); -} - - -//----------------------------------------------------------------------------- -// Node allocation/deallocation -//----------------------------------------------------------------------------- -template -I CUtlLinkedList::AllocInternal( bool multilist ) RESTRICT -{ - Assert( !multilist || ML ); - I elem; - if ( m_FirstFree == InvalidIndex() ) - { - Assert( m_Memory.IsValidIterator( m_LastAlloc ) || m_ElementCount == 0 ); - typename M::Iterator_t it = m_Memory.IsValidIterator( m_LastAlloc ) ? m_Memory.Next( m_LastAlloc ) : m_Memory.First(); - if ( !m_Memory.IsValidIterator( it ) ) - { - MEM_ALLOC_CREDIT_CLASS(); - m_Memory.Grow(); - - it = m_Memory.IsValidIterator( m_LastAlloc ) ? m_Memory.Next( m_LastAlloc ) : m_Memory.First(); - - Assert( m_Memory.IsValidIterator( it ) ); - if ( !m_Memory.IsValidIterator( it ) ) - { - Error( "CUtlLinkedList overflow!\n" ); - } - } - m_LastAlloc = it; - elem = m_Memory.GetIndex( m_LastAlloc ); - } - else - { - elem = m_FirstFree; - m_FirstFree = InternalElement( m_FirstFree ).m_Next; - } - - if ( !multilist ) - { - InternalElement( elem ).m_Next = elem; - InternalElement( elem ).m_Previous = elem; - } - else - { - InternalElement( elem ).m_Next = InvalidIndex(); - InternalElement( elem ).m_Previous = InvalidIndex(); - } - - ResetDbgInfo(); - - return elem; -} - -template -I CUtlLinkedList::Alloc( bool multilist ) -{ - I elem = AllocInternal( multilist ); - Construct( &Element(elem) ); - - return elem; -} - -template -void CUtlLinkedList::Free( I elem ) -{ - Assert( IsValidIndex(elem) ); - Unlink(elem); - - ListElem_t &internalElem = InternalElement(elem); - Destruct( &internalElem.m_Element ); - internalElem.m_Next = m_FirstFree; - m_FirstFree = elem; -} - -//----------------------------------------------------------------------------- -// Insertion methods; allocates and links (uses default constructor) -//----------------------------------------------------------------------------- - -template -I CUtlLinkedList::InsertBefore( I before ) -{ - // Make a new node - I newNode = AllocInternal(); - - // Link it in - LinkBefore( before, newNode ); - - // Construct the data - Construct( &Element(newNode) ); - - return newNode; -} - -template -I CUtlLinkedList::InsertAfter( I after ) -{ - // Make a new node - I newNode = AllocInternal(); - - // Link it in - LinkAfter( after, newNode ); - - // Construct the data - Construct( &Element(newNode) ); - - return newNode; -} - -template -inline I CUtlLinkedList::AddToHead( ) -{ - return InsertAfter( InvalidIndex() ); -} - -template -inline I CUtlLinkedList::AddToTail( ) -{ - return InsertBefore( InvalidIndex() ); -} - - -//----------------------------------------------------------------------------- -// Insertion methods; allocates and links (uses copy constructor) -//----------------------------------------------------------------------------- - -template -I CUtlLinkedList::InsertBefore( I before, T const& src ) -{ - // Make a new node - I newNode = AllocInternal(); - - // Link it in - LinkBefore( before, newNode ); - - // Construct the data - CopyConstruct( &Element(newNode), src ); - - return newNode; -} - -template -I CUtlLinkedList::InsertAfter( I after, T const& src ) -{ - // Make a new node - I newNode = AllocInternal(); - - // Link it in - LinkAfter( after, newNode ); - - // Construct the data - CopyConstruct( &Element(newNode), src ); - - return newNode; -} - -template -inline I CUtlLinkedList::AddToHead( T const& src ) -{ - return InsertAfter( InvalidIndex(), src ); -} - -template -inline I CUtlLinkedList::AddToTail( T const& src ) -{ - return InsertBefore( InvalidIndex(), src ); -} - - -//----------------------------------------------------------------------------- -// Removal methods -//----------------------------------------------------------------------------- - -template -I CUtlLinkedList::Find( const T &src ) const -{ - for ( I i=Head(); i != InvalidIndex(); i = Next( i ) ) - { - if ( Element( i ) == src ) - return i; - } - return InvalidIndex(); -} - - -template -bool CUtlLinkedList::FindAndRemove( const T &src ) -{ - I i = Find( src ); - if ( i == InvalidIndex() ) - { - return false; - } - else - { - Remove( i ); - return true; - } -} - - -template -void CUtlLinkedList::Remove( I elem ) -{ - Free( elem ); -} - -template -void CUtlLinkedList::RemoveAll() -{ - // Have to do some convoluted stuff to invoke the destructor on all - // valid elements for the multilist case (since we don't have all elements - // connected to each other in a list). - - if ( m_LastAlloc == m_Memory.InvalidIterator() ) - { - Assert( m_Head == InvalidIndex() ); - Assert( m_Tail == InvalidIndex() ); - Assert( m_FirstFree == InvalidIndex() ); - Assert( m_ElementCount == 0 ); - return; - } - - if ( ML ) - { - for ( typename M::Iterator_t it = m_Memory.First(); it != m_Memory.InvalidIterator(); it = m_Memory.Next( it ) ) - { - I i = m_Memory.GetIndex( it ); - if ( IsValidIndex( i ) ) // skip elements already in the free list - { - ListElem_t &internalElem = InternalElement( i ); - Destruct( &internalElem.m_Element ); - internalElem.m_Previous = i; - internalElem.m_Next = m_FirstFree; - m_FirstFree = i; - } - - if ( it == m_LastAlloc ) - break; // don't destruct elements that haven't ever been constructed - } - } - else - { - I i = Head(); - I next; - while ( i != InvalidIndex() ) - { - next = Next( i ); - ListElem_t &internalElem = InternalElement( i ); - Destruct( &internalElem.m_Element ); - internalElem.m_Previous = i; - internalElem.m_Next = next == InvalidIndex() ? m_FirstFree : next; - i = next; - } - if ( Head() != InvalidIndex() ) - { - m_FirstFree = Head(); - } - } - - // Clear everything else out - m_Head = InvalidIndex(); - m_Tail = InvalidIndex(); - m_ElementCount = 0; -} - - -//----------------------------------------------------------------------------- -// list modification -//----------------------------------------------------------------------------- - -template -void CUtlLinkedList::LinkBefore( I before, I elem ) -{ - Assert( IsValidIndex(elem) ); - - // Unlink it if it's in the list at the moment - Unlink(elem); - - ListElem_t * RESTRICT pNewElem = &InternalElement(elem); - - // The element *after* our newly linked one is the one we linked before. - pNewElem->m_Next = before; - - S newElem_mPrevious; // we need to hang on to this for the compairson against InvalidIndex() - // below; otherwise we get a a load-hit-store on pNewElem->m_Previous, even - // with RESTRICT - if (before == InvalidIndex()) - { - // In this case, we're linking to the end of the list, so reset the tail - newElem_mPrevious = m_Tail; - pNewElem->m_Previous = m_Tail; - m_Tail = elem; - } - else - { - // Here, we're not linking to the end. Set the prev pointer to point to - // the element we're linking. - Assert( IsInList(before) ); - ListElem_t * RESTRICT beforeElem = &InternalElement(before); - pNewElem->m_Previous = newElem_mPrevious = beforeElem->m_Previous; - beforeElem->m_Previous = elem; - } - - // Reset the head if we linked to the head of the list - if (newElem_mPrevious == InvalidIndex()) - m_Head = elem; - else - InternalElement(newElem_mPrevious).m_Next = elem; - - // one more element baby - ++m_ElementCount; -} - -template -void CUtlLinkedList::LinkAfter( I after, I elem ) -{ - Assert( IsValidIndex(elem) ); - - // Unlink it if it's in the list at the moment - if ( IsInList(elem) ) - Unlink(elem); - - ListElem_t& newElem = InternalElement(elem); - - // The element *before* our newly linked one is the one we linked after - newElem.m_Previous = after; - if (after == InvalidIndex()) - { - // In this case, we're linking to the head of the list, reset the head - newElem.m_Next = m_Head; - m_Head = elem; - } - else - { - // Here, we're not linking to the end. Set the next pointer to point to - // the element we're linking. - Assert( IsInList(after) ); - ListElem_t& afterElem = InternalElement(after); - newElem.m_Next = afterElem.m_Next; - afterElem.m_Next = elem; - } - - // Reset the tail if we linked to the tail of the list - if (newElem.m_Next == InvalidIndex()) - m_Tail = elem; - else - InternalElement(newElem.m_Next).m_Previous = elem; - - // one more element baby - ++m_ElementCount; -} - -template -void CUtlLinkedList::Unlink( I elem ) -{ - Assert( IsValidIndex(elem) ); - if (IsInList(elem)) - { - ListElem_t * RESTRICT pOldElem = &m_Memory[ elem ]; - - // If we're the first guy, reset the head - // otherwise, make our previous node's next pointer = our next - if ( pOldElem->m_Previous != InvalidIndex() ) - { - m_Memory[ pOldElem->m_Previous ].m_Next = pOldElem->m_Next; - } - else - { - m_Head = pOldElem->m_Next; - } - - // If we're the last guy, reset the tail - // otherwise, make our next node's prev pointer = our prev - if ( pOldElem->m_Next != InvalidIndex() ) - { - m_Memory[ pOldElem->m_Next ].m_Previous = pOldElem->m_Previous; - } - else - { - m_Tail = pOldElem->m_Previous; - } - - // This marks this node as not in the list, - // but not in the free list either - pOldElem->m_Previous = pOldElem->m_Next = elem; - - // One less puppy - --m_ElementCount; - } -} - -template -inline void CUtlLinkedList::LinkToHead( I elem ) -{ - LinkAfter( InvalidIndex(), elem ); -} - -template -inline void CUtlLinkedList::LinkToTail( I elem ) -{ - LinkBefore( InvalidIndex(), elem ); -} - - -//----------------------------------------------------------------------------- -// Class to drop in to replace a CUtlLinkedList that needs to be more memory agressive -//----------------------------------------------------------------------------- - -DECLARE_POINTER_HANDLE( UtlPtrLinkedListIndex_t ); // to enforce correct usage - -template < typename T > -class CUtlPtrLinkedList -{ -public: - CUtlPtrLinkedList() - : m_pFirst( NULL ), - m_nElems( 0 ) - { - COMPILE_TIME_ASSERT( sizeof(IndexType_t) == sizeof(Node_t *) ); - } - - ~CUtlPtrLinkedList() - { - RemoveAll(); - } - - typedef UtlPtrLinkedListIndex_t IndexType_t; - - T &operator[]( IndexType_t i ) - { - return (( Node_t * )i)->elem; - } - - const T &operator[]( IndexType_t i ) const - { - return (( Node_t * )i)->elem; - } - - IndexType_t AddToTail() - { - return DoInsertBefore( (IndexType_t)m_pFirst, NULL ); - } - - IndexType_t AddToTail( T const& src ) - { - return DoInsertBefore( (IndexType_t)m_pFirst, &src ); - } - - IndexType_t AddToHead() - { - IndexType_t result = DoInsertBefore( (IndexType_t)m_pFirst, NULL ); - m_pFirst = ((Node_t *)result); - return result; - } - - IndexType_t AddToHead( T const& src ) - { - IndexType_t result = DoInsertBefore( (IndexType_t)m_pFirst, &src ); - m_pFirst = ((Node_t *)result); - return result; - } - - IndexType_t InsertBefore( IndexType_t before ) - { - return DoInsertBefore( before, NULL ); - } - - IndexType_t InsertAfter( IndexType_t after ) - { - Node_t *pBefore = ((Node_t *)after)->next; - return DoInsertBefore( pBefore, NULL ); - } - - IndexType_t InsertBefore( IndexType_t before, T const& src ) - { - return DoInsertBefore( before, &src ); - } - - IndexType_t InsertAfter( IndexType_t after, T const& src ) - { - Node_t *pBefore = ((Node_t *)after)->next; - return DoInsertBefore( pBefore, &src ); - } - - void Remove( IndexType_t elem ) - { - Node_t *p = (Node_t *)elem; - - if ( p->pNext == p ) - { - m_pFirst = NULL; - } - else - { - if ( m_pFirst == p ) - { - m_pFirst = p->pNext; - } - p->pNext->pPrev = p->pPrev; - p->pPrev->pNext = p->pNext; - } - - delete p; - m_nElems--; - } - - void RemoveAll() - { - Node_t *p = m_pFirst; - if ( p ) - { - do - { - Node_t *pNext = p->pNext; - delete p; - p = pNext; - } while( p != m_pFirst ); - } - - m_pFirst = NULL; - m_nElems = 0; - } - - int Count() const - { - return m_nElems; - } - - IndexType_t Head() const - { - return (IndexType_t)m_pFirst; - } - - IndexType_t Next( IndexType_t i ) const - { - Node_t *p = ((Node_t *)i)->pNext; - if ( p != m_pFirst ) - { - return (IndexType_t)p; - } - return NULL; - } - - bool IsValidIndex( IndexType_t i ) const - { - Node_t *p = ((Node_t *)i); - return ( p && p->pNext && p->pPrev ); - } - - inline static IndexType_t InvalidIndex() - { - return NULL; - } -private: - - struct Node_t - { - Node_t() {} - Node_t( const T &elem ) : elem( elem ) {} - - T elem; - Node_t *pPrev, *pNext; - }; - - Node_t *AllocNode( const T *pCopyFrom ) - { - MEM_ALLOC_CREDIT_CLASS(); - Node_t *p; - - if ( !pCopyFrom ) - { - p = new Node_t; - } - else - { - p = new Node_t( *pCopyFrom ); - } - - return p; - } - - IndexType_t DoInsertBefore( IndexType_t before, const T *pCopyFrom ) - { - Node_t *p = AllocNode( pCopyFrom ); - Node_t *pBefore = (Node_t *)before; - if ( pBefore ) - { - p->pNext = pBefore; - p->pPrev = pBefore->pPrev; - pBefore->pPrev = p; - p->pPrev->pNext = p; - } - else - { - Assert( !m_pFirst ); - m_pFirst = p->pNext = p->pPrev = p; - } - - m_nElems++; - return (IndexType_t)p; - } - - Node_t *m_pFirst; - unsigned m_nElems; -}; - -//----------------------------------------------------------------------------- - -#endif // UTLLINKEDLIST_H diff --git a/Resources/NetHook/tier1/utlmap.h b/Resources/NetHook/tier1/utlmap.h deleted file mode 100644 index 6f933c81..00000000 --- a/Resources/NetHook/tier1/utlmap.h +++ /dev/null @@ -1,203 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $Header: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLMAP_H -#define UTLMAP_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include "utlrbtree.h" - -//----------------------------------------------------------------------------- -// -// Purpose: An associative container. Pretty much identical to std::map. -// -//----------------------------------------------------------------------------- - -// This is a useful macro to iterate from start to end in order in a map -#define FOR_EACH_MAP( mapName, iteratorName ) \ - for ( int iteratorName = mapName.FirstInorder(); iteratorName != mapName.InvalidIndex(); iteratorName = mapName.NextInorder( iteratorName ) ) - -// faster iteration, but in an unspecified order -#define FOR_EACH_MAP_FAST( mapName, iteratorName ) \ - for ( int iteratorName = 0; iteratorName < mapName.MaxElement(); ++iteratorName ) if ( !mapName.IsValidIndex( iteratorName ) ) continue; else - -template -class CUtlMap -{ -public: - typedef K KeyType_t; - typedef T ElemType_t; - typedef I IndexType_t; - - // Less func typedef - // Returns true if the first parameter is "less" than the second - typedef bool (*LessFunc_t)( const KeyType_t &, const KeyType_t & ); - - // constructor, destructor - // Left at growSize = 0, the memory will first allocate 1 element and double in size - // at each increment. - // LessFunc_t is required, but may be set after the constructor using SetLessFunc() below - CUtlMap( int growSize = 0, int initSize = 0, LessFunc_t lessfunc = 0 ) - : m_Tree( growSize, initSize, CKeyLess( lessfunc ) ) - { - } - - CUtlMap( LessFunc_t lessfunc ) - : m_Tree( CKeyLess( lessfunc ) ) - { - } - - void EnsureCapacity( int num ) { m_Tree.EnsureCapacity( num ); } - - // gets particular elements - ElemType_t & Element( IndexType_t i ) { return m_Tree.Element( i ).elem; } - const ElemType_t & Element( IndexType_t i ) const { return m_Tree.Element( i ).elem; } - ElemType_t & operator[]( IndexType_t i ) { return m_Tree.Element( i ).elem; } - const ElemType_t & operator[]( IndexType_t i ) const { return m_Tree.Element( i ).elem; } - KeyType_t & Key( IndexType_t i ) { return m_Tree.Element( i ).key; } - const KeyType_t & Key( IndexType_t i ) const { return m_Tree.Element( i ).key; } - - - // Num elements - unsigned int Count() const { return m_Tree.Count(); } - - // Max "size" of the vector - IndexType_t MaxElement() const { return m_Tree.MaxElement(); } - - // Checks if a node is valid and in the map - bool IsValidIndex( IndexType_t i ) const { return m_Tree.IsValidIndex( i ); } - - // Checks if the map as a whole is valid - bool IsValid() const { return m_Tree.IsValid(); } - - // Invalid index - static IndexType_t InvalidIndex() { return CTree::InvalidIndex(); } - - // Sets the less func - void SetLessFunc( LessFunc_t func ) - { - m_Tree.SetLessFunc( CKeyLess( func ) ); - } - - // Insert method (inserts in order) - IndexType_t Insert( const KeyType_t &key, const ElemType_t &insert ) - { - Node_t node; - node.key = key; - node.elem = insert; - return m_Tree.Insert( node ); - } - - IndexType_t Insert( const KeyType_t &key ) - { - Node_t node; - node.key = key; - return m_Tree.Insert( node ); - } - - // Find method - IndexType_t Find( const KeyType_t &key ) const - { - Node_t dummyNode; - dummyNode.key = key; - return m_Tree.Find( dummyNode ); - } - - // Remove methods - void RemoveAt( IndexType_t i ) { m_Tree.RemoveAt( i ); } - bool Remove( const KeyType_t &key ) - { - Node_t dummyNode; - dummyNode.key = key; - return m_Tree.Remove( dummyNode ); - } - - void RemoveAll( ) { m_Tree.RemoveAll(); } - void Purge( ) { m_Tree.Purge(); } - - // Iteration - IndexType_t FirstInorder() const { return m_Tree.FirstInorder(); } - IndexType_t NextInorder( IndexType_t i ) const { return m_Tree.NextInorder( i ); } - IndexType_t PrevInorder( IndexType_t i ) const { return m_Tree.PrevInorder( i ); } - IndexType_t LastInorder() const { return m_Tree.LastInorder(); } - - // If you change the search key, this can be used to reinsert the - // element into the map. - void Reinsert( const KeyType_t &key, IndexType_t i ) - { - m_Tree[i].key = key; - m_Tree.Reinsert(i); - } - - IndexType_t InsertOrReplace( const KeyType_t &key, const ElemType_t &insert ) - { - IndexType_t i = Find( key ); - if ( i != InvalidIndex() ) - { - Element( i ) = insert; - return i; - } - - return Insert( key, insert ); - } - - void Swap( CUtlMap< K, T, I > &that ) - { - m_Tree.Swap( that.m_Tree ); - } - - - struct Node_t - { - Node_t() - { - } - - Node_t( const Node_t &from ) - : key( from.key ), - elem( from.elem ) - { - } - - KeyType_t key; - ElemType_t elem; - }; - - class CKeyLess - { - public: - CKeyLess( LessFunc_t lessFunc ) : m_LessFunc(lessFunc) {} - - bool operator!() const - { - return !m_LessFunc; - } - - bool operator()( const Node_t &left, const Node_t &right ) const - { - return m_LessFunc( left.key, right.key ); - } - - LessFunc_t m_LessFunc; - }; - - typedef CUtlRBTree CTree; - - CTree *AccessTree() { return &m_Tree; } - -protected: - CTree m_Tree; -}; - -//----------------------------------------------------------------------------- - -#endif // UTLMAP_H diff --git a/Resources/NetHook/tier1/utlmemory.h b/Resources/NetHook/tier1/utlmemory.h deleted file mode 100644 index 299ce546..00000000 --- a/Resources/NetHook/tier1/utlmemory.h +++ /dev/null @@ -1,925 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: -// -// $NoKeywords: $ -// -// A growable memory class. -//===========================================================================// - -#ifndef UTLMEMORY_H -#define UTLMEMORY_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/dbg.h" -#include -#include "tier0/platform.h" - -#include "tier0/memalloc.h" -#include "tier0/memdbgon.h" - -#pragma warning (disable:4100) -#pragma warning (disable:4514) - - -//----------------------------------------------------------------------------- - - -#ifdef UTLMEMORY_TRACK -#define UTLMEMORY_TRACK_ALLOC() MemAlloc_RegisterAllocation( "Sum of all UtlMemory", 0, m_nAllocationCount * sizeof(T), m_nAllocationCount * sizeof(T), 0 ) -#define UTLMEMORY_TRACK_FREE() if ( !m_pMemory ) ; else MemAlloc_RegisterDeallocation( "Sum of all UtlMemory", 0, m_nAllocationCount * sizeof(T), m_nAllocationCount * sizeof(T), 0 ) -#else -#define UTLMEMORY_TRACK_ALLOC() ((void)0) -#define UTLMEMORY_TRACK_FREE() ((void)0) -#endif - - -//----------------------------------------------------------------------------- -// The CUtlMemory class: -// A growable memory class which doubles in size by default. -//----------------------------------------------------------------------------- -template< class T, class I = int > -class CUtlMemory -{ -public: - // constructor, destructor - CUtlMemory( int nGrowSize = 0, int nInitSize = 0 ); - CUtlMemory( T* pMemory, int numElements ); - CUtlMemory( const T* pMemory, int numElements ); - ~CUtlMemory(); - - // Set the size by which the memory grows - void Init( int nGrowSize = 0, int nInitSize = 0 ); - - class Iterator_t - { - public: - Iterator_t( I i ) : index( i ) {} - I index; - - bool operator==( const Iterator_t it ) const { return index == it.index; } - bool operator!=( const Iterator_t it ) const { return index != it.index; } - }; - Iterator_t First() const { return Iterator_t( IsIdxValid( 0 ) ? 0 : InvalidIndex() ); } - Iterator_t Next( const Iterator_t &it ) const { return Iterator_t( IsIdxValid( it.index + 1 ) ? it.index + 1 : InvalidIndex() ); } - I GetIndex( const Iterator_t &it ) const { return it.index; } - bool IsIdxAfter( I i, const Iterator_t &it ) const { return i > it.index; } - bool IsValidIterator( const Iterator_t &it ) const { return IsIdxValid( it.index ); } - Iterator_t InvalidIterator() const { return Iterator_t( InvalidIndex() ); } - - // element access - T& operator[]( I i ); - const T& operator[]( I i ) const; - T& Element( I i ); - const T& Element( I i ) const; - - // Can we use this index? - bool IsIdxValid( I i ) const; - static I InvalidIndex() { return ( I )-1; } - - // Gets the base address (can change when adding elements!) - T* Base(); - const T* Base() const; - - // Attaches the buffer to external memory.... - void SetExternalBuffer( T* pMemory, int numElements ); - void SetExternalBuffer( const T* pMemory, int numElements ); - void AssumeMemory( T *pMemory, int nSize ); - - // Fast swap - void Swap( CUtlMemory< T, I > &mem ); - - // Switches the buffer from an external memory buffer to a reallocatable buffer - // Will copy the current contents of the external buffer to the reallocatable buffer - void ConvertToGrowableMemory( int nGrowSize ); - - // Size - int NumAllocated() const; - int Count() const; - - // Grows the memory, so that at least allocated + num elements are allocated - void Grow( int num = 1 ); - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ); - - // Memory deallocation - void Purge(); - - // Purge all but the given number of elements - void Purge( int numElements ); - - // is the memory externally allocated? - bool IsExternallyAllocated() const; - - // is the memory read only? - bool IsReadOnly() const; - - // Set the size by which the memory grows - void SetGrowSize( int size ); - -protected: - void ValidateGrowSize() - { -#ifdef _X360 - if ( m_nGrowSize && m_nGrowSize != EXTERNAL_BUFFER_MARKER ) - { - // Max grow size at 128 bytes on XBOX - const int MAX_GROW = 128; - if ( m_nGrowSize * sizeof(T) > MAX_GROW ) - { - m_nGrowSize = max( 1, MAX_GROW / sizeof(T) ); - } - } -#endif - } - - enum - { - EXTERNAL_BUFFER_MARKER = -1, - EXTERNAL_CONST_BUFFER_MARKER = -2, - }; - - T* m_pMemory; - int m_nAllocationCount; - int m_nGrowSize; -}; - - -//----------------------------------------------------------------------------- -// The CUtlMemory class: -// A growable memory class which doubles in size by default. -//----------------------------------------------------------------------------- -template< class T, size_t SIZE, class I = int > -class CUtlMemoryFixedGrowable : public CUtlMemory< T, I > -{ - typedef CUtlMemory< T, I > BaseClass; - -public: - CUtlMemoryFixedGrowable( int nGrowSize = 0, int nInitSize = SIZE ) : BaseClass( m_pFixedMemory, SIZE ) - { - Assert( nInitSize == 0 || nInitSize == SIZE ); - m_nMallocGrowSize = nGrowSize; - } - - void Grow( int nCount = 1 ) - { - if ( IsExternallyAllocated() ) - { - ConvertToGrowableMemory( m_nMallocGrowSize ); - } - BaseClass::Grow( nCount ); - } - - void EnsureCapacity( int num ) - { - if ( CUtlMemory::m_nAllocationCount >= num ) - return; - - if ( IsExternallyAllocated() ) - { - // Can't grow a buffer whose memory was externally allocated - ConvertToGrowableMemory( m_nMallocGrowSize ); - } - - BaseClass::EnsureCapacity( num ); - } - -private: - int m_nMallocGrowSize; - T m_pFixedMemory[ SIZE ]; -}; - -//----------------------------------------------------------------------------- -// The CUtlMemoryFixed class: -// A fixed memory class -//----------------------------------------------------------------------------- -template< typename T, size_t SIZE, int nAlignment = 0 > -class CUtlMemoryFixed -{ -public: - // constructor, destructor - CUtlMemoryFixed( int nGrowSize = 0, int nInitSize = 0 ) { Assert( nInitSize == 0 || nInitSize == SIZE ); } - CUtlMemoryFixed( T* pMemory, int numElements ) { Assert( 0 ); } - - // Can we use this index? - bool IsIdxValid( int i ) const { return (i >= 0) && (i < SIZE); } - static int InvalidIndex() { return -1; } - - // Gets the base address - T* Base() { if ( nAlignment == 0 ) return (T*)(&m_Memory[0]); else return (T*)AlignValue( &m_Memory[0], nAlignment ); } - const T* Base() const { if ( nAlignment == 0 ) return (T*)(&m_Memory[0]); else return (T*)AlignValue( &m_Memory[0], nAlignment ); } - - // element access - T& operator[]( int i ) { Assert( IsIdxValid(i) ); return Base()[i]; } - const T& operator[]( int i ) const { Assert( IsIdxValid(i) ); return Base()[i]; } - T& Element( int i ) { Assert( IsIdxValid(i) ); return Base()[i]; } - const T& Element( int i ) const { Assert( IsIdxValid(i) ); return Base()[i]; } - - // Attaches the buffer to external memory.... - void SetExternalBuffer( T* pMemory, int numElements ) { Assert( 0 ); } - - // Size - int NumAllocated() const { return SIZE; } - int Count() const { return SIZE; } - - // Grows the memory, so that at least allocated + num elements are allocated - void Grow( int num = 1 ) { Assert( 0 ); } - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ) { Assert( num <= SIZE ); } - - // Memory deallocation - void Purge() {} - - // Purge all but the given number of elements (NOT IMPLEMENTED IN CUtlMemoryFixed) - void Purge( int numElements ) { Assert( 0 ); } - - // is the memory externally allocated? - bool IsExternallyAllocated() const { return false; } - - // Set the size by which the memory grows - void SetGrowSize( int size ) {} - - class Iterator_t - { - public: - Iterator_t( int i ) : index( i ) {} - int index; - bool operator==( const Iterator_t it ) const { return index == it.index; } - bool operator!=( const Iterator_t it ) const { return index != it.index; } - }; - Iterator_t First() const { return Iterator_t( IsIdxValid( 0 ) ? 0 : InvalidIndex() ); } - Iterator_t Next( const Iterator_t &it ) const { return Iterator_t( IsIdxValid( it.index + 1 ) ? it.index + 1 : InvalidIndex() ); } - int GetIndex( const Iterator_t &it ) const { return it.index; } - bool IsIdxAfter( int i, const Iterator_t &it ) const { return i > it.index; } - bool IsValidIterator( const Iterator_t &it ) const { return IsIdxValid( it.index ); } - Iterator_t InvalidIterator() const { return Iterator_t( InvalidIndex() ); } - -private: - char m_Memory[ SIZE*sizeof(T) + nAlignment ]; -}; - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template< class T, class I > -CUtlMemory::CUtlMemory( int nGrowSize, int nInitAllocationCount ) : m_pMemory(0), - m_nAllocationCount( nInitAllocationCount ), m_nGrowSize( nGrowSize ) -{ - ValidateGrowSize(); - Assert( nGrowSize >= 0 ); - if (m_nAllocationCount) - { - UTLMEMORY_TRACK_ALLOC(); - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)malloc( m_nAllocationCount * sizeof(T) ); - } -} - -template< class T, class I > -CUtlMemory::CUtlMemory( T* pMemory, int numElements ) : m_pMemory(pMemory), - m_nAllocationCount( numElements ) -{ - // Special marker indicating externally supplied modifyable memory - m_nGrowSize = EXTERNAL_BUFFER_MARKER; -} - -template< class T, class I > -CUtlMemory::CUtlMemory( const T* pMemory, int numElements ) : m_pMemory( (T*)pMemory ), - m_nAllocationCount( numElements ) -{ - // Special marker indicating externally supplied modifyable memory - m_nGrowSize = EXTERNAL_CONST_BUFFER_MARKER; -} - -template< class T, class I > -CUtlMemory::~CUtlMemory() -{ - Purge(); -} - -template< class T, class I > -void CUtlMemory::Init( int nGrowSize /*= 0*/, int nInitSize /*= 0*/ ) -{ - Purge(); - - m_nGrowSize = nGrowSize; - m_nAllocationCount = nInitSize; - ValidateGrowSize(); - Assert( nGrowSize >= 0 ); - if (m_nAllocationCount) - { - UTLMEMORY_TRACK_ALLOC(); - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)malloc( m_nAllocationCount * sizeof(T) ); - } -} - -//----------------------------------------------------------------------------- -// Fast swap -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlMemory::Swap( CUtlMemory &mem ) -{ - swap( m_nGrowSize, mem.m_nGrowSize ); - swap( m_pMemory, mem.m_pMemory ); - swap( m_nAllocationCount, mem.m_nAllocationCount ); -} - - -//----------------------------------------------------------------------------- -// Switches the buffer from an external memory buffer to a reallocatable buffer -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlMemory::ConvertToGrowableMemory( int nGrowSize ) -{ - if ( !IsExternallyAllocated() ) - return; - - m_nGrowSize = nGrowSize; - if (m_nAllocationCount) - { - UTLMEMORY_TRACK_ALLOC(); - MEM_ALLOC_CREDIT_CLASS(); - - int nNumBytes = m_nAllocationCount * sizeof(T); - T *pMemory = (T*)malloc( nNumBytes ); - memcpy( pMemory, m_pMemory, nNumBytes ); - m_pMemory = pMemory; - } - else - { - m_pMemory = NULL; - } -} - - -//----------------------------------------------------------------------------- -// Attaches the buffer to external memory.... -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlMemory::SetExternalBuffer( T* pMemory, int numElements ) -{ - // Blow away any existing allocated memory - Purge(); - - m_pMemory = pMemory; - m_nAllocationCount = numElements; - - // Indicate that we don't own the memory - m_nGrowSize = EXTERNAL_BUFFER_MARKER; -} - -template< class T, class I > -void CUtlMemory::SetExternalBuffer( const T* pMemory, int numElements ) -{ - // Blow away any existing allocated memory - Purge(); - - m_pMemory = const_cast( pMemory ); - m_nAllocationCount = numElements; - - // Indicate that we don't own the memory - m_nGrowSize = EXTERNAL_CONST_BUFFER_MARKER; -} - -template< class T, class I > -void CUtlMemory::AssumeMemory( T* pMemory, int numElements ) -{ - // Blow away any existing allocated memory - Purge(); - - // Simply take the pointer but don't mark us as external - m_pMemory = pMemory; - m_nAllocationCount = numElements; -} - - -//----------------------------------------------------------------------------- -// element access -//----------------------------------------------------------------------------- -template< class T, class I > -inline T& CUtlMemory::operator[]( I i ) -{ - Assert( !IsReadOnly() ); - Assert( IsIdxValid(i) ); - return m_pMemory[i]; -} - -template< class T, class I > -inline const T& CUtlMemory::operator[]( I i ) const -{ - Assert( IsIdxValid(i) ); - return m_pMemory[i]; -} - -template< class T, class I > -inline T& CUtlMemory::Element( I i ) -{ - Assert( !IsReadOnly() ); - Assert( IsIdxValid(i) ); - return m_pMemory[i]; -} - -template< class T, class I > -inline const T& CUtlMemory::Element( I i ) const -{ - Assert( IsIdxValid(i) ); - return m_pMemory[i]; -} - - -//----------------------------------------------------------------------------- -// is the memory externally allocated? -//----------------------------------------------------------------------------- -template< class T, class I > -bool CUtlMemory::IsExternallyAllocated() const -{ - return (m_nGrowSize < 0); -} - - -//----------------------------------------------------------------------------- -// is the memory read only? -//----------------------------------------------------------------------------- -template< class T, class I > -bool CUtlMemory::IsReadOnly() const -{ - return (m_nGrowSize == EXTERNAL_CONST_BUFFER_MARKER); -} - - -template< class T, class I > -void CUtlMemory::SetGrowSize( int nSize ) -{ - Assert( !IsExternallyAllocated() ); - Assert( nSize >= 0 ); - m_nGrowSize = nSize; - ValidateGrowSize(); -} - - -//----------------------------------------------------------------------------- -// Gets the base address (can change when adding elements!) -//----------------------------------------------------------------------------- -template< class T, class I > -inline T* CUtlMemory::Base() -{ - Assert( !IsReadOnly() ); - return m_pMemory; -} - -template< class T, class I > -inline const T *CUtlMemory::Base() const -{ - return m_pMemory; -} - - -//----------------------------------------------------------------------------- -// Size -//----------------------------------------------------------------------------- -template< class T, class I > -inline int CUtlMemory::NumAllocated() const -{ - return m_nAllocationCount; -} - -template< class T, class I > -inline int CUtlMemory::Count() const -{ - return m_nAllocationCount; -} - - -//----------------------------------------------------------------------------- -// Is element index valid? -//----------------------------------------------------------------------------- -template< class T, class I > -inline bool CUtlMemory::IsIdxValid( I i ) const -{ - return ( ((int) i) >= 0 ) && ( ((int) i) < m_nAllocationCount ); -} - -//----------------------------------------------------------------------------- -// Grows the memory -//----------------------------------------------------------------------------- -inline int UtlMemory_CalcNewAllocationCount( int nAllocationCount, int nGrowSize, int nNewSize, int nBytesItem ) -{ - if ( nGrowSize ) - { - nAllocationCount = ((1 + ((nNewSize - 1) / nGrowSize)) * nGrowSize); - } - else - { - if ( !nAllocationCount ) - { - // Compute an allocation which is at least as big as a cache line... - nAllocationCount = (31 + nBytesItem) / nBytesItem; - } - - while (nAllocationCount < nNewSize) - { -#ifndef _X360 - nAllocationCount *= 2; -#else - int nNewAllocationCount = ( nAllocationCount * 9) / 8; // 12.5 % - if ( nNewAllocationCount > nAllocationCount ) - nAllocationCount = nNewAllocationCount; - else - nAllocationCount *= 2; -#endif - } - } - - return nAllocationCount; -} - -template< class T, class I > -void CUtlMemory::Grow( int num ) -{ - Assert( num > 0 ); - - if ( IsExternallyAllocated() ) - { - // Can't grow a buffer whose memory was externally allocated - Assert(0); - return; - } - - // Make sure we have at least numallocated + num allocations. - // Use the grow rules specified for this memory (in m_nGrowSize) - int nAllocationRequested = m_nAllocationCount + num; - - UTLMEMORY_TRACK_FREE(); - - m_nAllocationCount = UtlMemory_CalcNewAllocationCount( m_nAllocationCount, m_nGrowSize, nAllocationRequested, sizeof(T) ); - - // if m_nAllocationRequested wraps index type I, recalculate - if ( ( int )( I )m_nAllocationCount < nAllocationRequested ) - { - if ( ( int )( I )m_nAllocationCount == 0 && ( int )( I )( m_nAllocationCount - 1 ) >= nAllocationRequested ) - { - --m_nAllocationCount; // deal w/ the common case of m_nAllocationCount == MAX_USHORT + 1 - } - else - { - if ( ( int )( I )nAllocationRequested != nAllocationRequested ) - { - // we've been asked to grow memory to a size s.t. the index type can't address the requested amount of memory - Assert( 0 ); - return; - } - while ( ( int )( I )m_nAllocationCount < nAllocationRequested ) - { - m_nAllocationCount = ( m_nAllocationCount + nAllocationRequested ) / 2; - } - } - } - - UTLMEMORY_TRACK_ALLOC(); - - if (m_pMemory) - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)realloc( m_pMemory, m_nAllocationCount * sizeof(T) ); - Assert( m_pMemory ); - } - else - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)malloc( m_nAllocationCount * sizeof(T) ); - Assert( m_pMemory ); - } -} - - -//----------------------------------------------------------------------------- -// Makes sure we've got at least this much memory -//----------------------------------------------------------------------------- -template< class T, class I > -inline void CUtlMemory::EnsureCapacity( int num ) -{ - if (m_nAllocationCount >= num) - return; - - if ( IsExternallyAllocated() ) - { - // Can't grow a buffer whose memory was externally allocated - Assert(0); - return; - } - - UTLMEMORY_TRACK_FREE(); - - m_nAllocationCount = num; - - UTLMEMORY_TRACK_ALLOC(); - - if (m_pMemory) - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)realloc( m_pMemory, m_nAllocationCount * sizeof(T) ); - } - else - { - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)malloc( m_nAllocationCount * sizeof(T) ); - } -} - - -//----------------------------------------------------------------------------- -// Memory deallocation -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlMemory::Purge() -{ - if ( !IsExternallyAllocated() ) - { - if (m_pMemory) - { - UTLMEMORY_TRACK_FREE(); - free( (void*)m_pMemory ); - m_pMemory = 0; - } - m_nAllocationCount = 0; - } -} - -template< class T, class I > -void CUtlMemory::Purge( int numElements ) -{ - Assert( numElements >= 0 ); - - if( numElements > m_nAllocationCount ) - { - // Ensure this isn't a grow request in disguise. - Assert( numElements <= m_nAllocationCount ); - return; - } - - // If we have zero elements, simply do a purge: - if( numElements == 0 ) - { - Purge(); - return; - } - - if ( IsExternallyAllocated() ) - { - // Can't shrink a buffer whose memory was externally allocated, fail silently like purge - return; - } - - // If the number of elements is the same as the allocation count, we are done. - if( numElements == m_nAllocationCount ) - { - return; - } - - - if( !m_pMemory ) - { - // Allocation count is non zero, but memory is null. - Assert( m_pMemory ); - return; - } - - UTLMEMORY_TRACK_FREE(); - - m_nAllocationCount = numElements; - - UTLMEMORY_TRACK_ALLOC(); - - // Allocation count > 0, shrink it down. - MEM_ALLOC_CREDIT_CLASS(); - m_pMemory = (T*)realloc( m_pMemory, m_nAllocationCount * sizeof(T) ); -} - -//----------------------------------------------------------------------------- -// The CUtlMemory class: -// A growable memory class which doubles in size by default. -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -class CUtlMemoryAligned : public CUtlMemory -{ -public: - // constructor, destructor - CUtlMemoryAligned( int nGrowSize = 0, int nInitSize = 0 ); - CUtlMemoryAligned( T* pMemory, int numElements ); - CUtlMemoryAligned( const T* pMemory, int numElements ); - ~CUtlMemoryAligned(); - - // Attaches the buffer to external memory.... - void SetExternalBuffer( T* pMemory, int numElements ); - void SetExternalBuffer( const T* pMemory, int numElements ); - - // Grows the memory, so that at least allocated + num elements are allocated - void Grow( int num = 1 ); - - // Makes sure we've got at least this much memory - void EnsureCapacity( int num ); - - // Memory deallocation - void Purge(); - - // Purge all but the given number of elements (NOT IMPLEMENTED IN CUtlMemoryAligned) - void Purge( int numElements ) { Assert( 0 ); } - -private: - void *Align( const void *pAddr ); -}; - - -//----------------------------------------------------------------------------- -// Aligns a pointer -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -void *CUtlMemoryAligned::Align( const void *pAddr ) -{ - size_t nAlignmentMask = nAlignment - 1; - return (void*)( ((size_t)pAddr + nAlignmentMask) & (~nAlignmentMask) ); -} - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -CUtlMemoryAligned::CUtlMemoryAligned( int nGrowSize, int nInitAllocationCount ) -{ - CUtlMemory::m_pMemory = 0; - CUtlMemory::m_nAllocationCount = nInitAllocationCount; - CUtlMemory::m_nGrowSize = nGrowSize; - ValidateGrowSize(); - - // Alignment must be a power of two - COMPILE_TIME_ASSERT( (nAlignment & (nAlignment-1)) == 0 ); - Assert( (nGrowSize >= 0) && (nGrowSize != CUtlMemory::EXTERNAL_BUFFER_MARKER) ); - if ( CUtlMemory::m_nAllocationCount ) - { - UTLMEMORY_TRACK_ALLOC(); - MEM_ALLOC_CREDIT_CLASS(); - CUtlMemory::m_pMemory = (T*)_aligned_malloc( nInitAllocationCount * sizeof(T), nAlignment ); - } -} - -template< class T, int nAlignment > -CUtlMemoryAligned::CUtlMemoryAligned( T* pMemory, int numElements ) -{ - // Special marker indicating externally supplied memory - CUtlMemory::m_nGrowSize = CUtlMemory::EXTERNAL_BUFFER_MARKER; - - CUtlMemory::m_pMemory = (T*)Align( pMemory ); - CUtlMemory::m_nAllocationCount = ( (int)(pMemory + numElements) - (int)CUtlMemory::m_pMemory ) / sizeof(T); -} - -template< class T, int nAlignment > -CUtlMemoryAligned::CUtlMemoryAligned( const T* pMemory, int numElements ) -{ - // Special marker indicating externally supplied memory - CUtlMemory::m_nGrowSize = CUtlMemory::EXTERNAL_CONST_BUFFER_MARKER; - - CUtlMemory::m_pMemory = (T*)Align( pMemory ); - CUtlMemory::m_nAllocationCount = ( (int)(pMemory + numElements) - (int)CUtlMemory::m_pMemory ) / sizeof(T); -} - -template< class T, int nAlignment > -CUtlMemoryAligned::~CUtlMemoryAligned() -{ - Purge(); -} - - -//----------------------------------------------------------------------------- -// Attaches the buffer to external memory.... -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -void CUtlMemoryAligned::SetExternalBuffer( T* pMemory, int numElements ) -{ - // Blow away any existing allocated memory - Purge(); - - CUtlMemory::m_pMemory = (T*)Align( pMemory ); - CUtlMemory::m_nAllocationCount = ( (int)(pMemory + numElements) - (int)CUtlMemory::m_pMemory ) / sizeof(T); - - // Indicate that we don't own the memory - CUtlMemory::m_nGrowSize = CUtlMemory::EXTERNAL_BUFFER_MARKER; -} - -template< class T, int nAlignment > -void CUtlMemoryAligned::SetExternalBuffer( const T* pMemory, int numElements ) -{ - // Blow away any existing allocated memory - Purge(); - - CUtlMemory::m_pMemory = (T*)Align( pMemory ); - CUtlMemory::m_nAllocationCount = ( (int)(pMemory + numElements) - (int)CUtlMemory::m_pMemory ) / sizeof(T); - - // Indicate that we don't own the memory - CUtlMemory::m_nGrowSize = CUtlMemory::EXTERNAL_CONST_BUFFER_MARKER; -} - - -//----------------------------------------------------------------------------- -// Grows the memory -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -void CUtlMemoryAligned::Grow( int num ) -{ - Assert( num > 0 ); - - if ( IsExternallyAllocated() ) - { - // Can't grow a buffer whose memory was externally allocated - Assert(0); - return; - } - - UTLMEMORY_TRACK_FREE(); - - // Make sure we have at least numallocated + num allocations. - // Use the grow rules specified for this memory (in m_nGrowSize) - int nAllocationRequested = CUtlMemory::m_nAllocationCount + num; - - CUtlMemory::m_nAllocationCount = UtlMemory_CalcNewAllocationCount( CUtlMemory::m_nAllocationCount, CUtlMemory::m_nGrowSize, nAllocationRequested, sizeof(T) ); - - UTLMEMORY_TRACK_ALLOC(); - - if ( CUtlMemory::m_pMemory ) - { - MEM_ALLOC_CREDIT_CLASS(); - CUtlMemory::m_pMemory = (T*)_aligned_realloc( CUtlMemory::m_pMemory, CUtlMemory::m_nAllocationCount * sizeof(T), nAlignment ); - Assert( CUtlMemory::m_pMemory ); - } - else - { - MEM_ALLOC_CREDIT_CLASS(); - CUtlMemory::m_pMemory = (T*)_aligned_malloc( CUtlMemory::m_nAllocationCount * sizeof(T), nAlignment ); - Assert( CUtlMemory::m_pMemory ); - } -} - - -//----------------------------------------------------------------------------- -// Makes sure we've got at least this much memory -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -inline void CUtlMemoryAligned::EnsureCapacity( int num ) -{ - if ( CUtlMemory::m_nAllocationCount >= num ) - return; - - if ( IsExternallyAllocated() ) - { - // Can't grow a buffer whose memory was externally allocated - Assert(0); - return; - } - - UTLMEMORY_TRACK_FREE(); - - CUtlMemory::m_nAllocationCount = num; - - UTLMEMORY_TRACK_ALLOC(); - - if ( CUtlMemory::m_pMemory ) - { - MEM_ALLOC_CREDIT_CLASS(); - CUtlMemory::m_pMemory = (T*)_aligned_realloc( CUtlMemory::m_pMemory, CUtlMemory::m_nAllocationCount * sizeof(T), nAlignment ); - } - else - { - MEM_ALLOC_CREDIT_CLASS(); - CUtlMemory::m_pMemory = (T*)_aligned_malloc( CUtlMemory::m_nAllocationCount * sizeof(T), nAlignment ); - } -} - - -//----------------------------------------------------------------------------- -// Memory deallocation -//----------------------------------------------------------------------------- -template< class T, int nAlignment > -void CUtlMemoryAligned::Purge() -{ - if ( !IsExternallyAllocated() ) - { - if ( CUtlMemory::m_pMemory ) - { - UTLMEMORY_TRACK_FREE(); - _aligned_free( CUtlMemory::m_pMemory ); - CUtlMemory::m_pMemory = 0; - } - CUtlMemory::m_nAllocationCount = 0; - } -} - -#include "tier0/memdbgoff.h" - -#endif // UTLMEMORY_H diff --git a/Resources/NetHook/tier1/utlmultilist.h b/Resources/NetHook/tier1/utlmultilist.h deleted file mode 100644 index c4436fc3..00000000 --- a/Resources/NetHook/tier1/utlmultilist.h +++ /dev/null @@ -1,725 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Multiple linked list container class -// -// $Revision: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLMULTILIST_H -#define UTLMULTILIST_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "utllinkedlist.h" - -// memdbgon must be the last include file in a .h file!!! -#include "tier0/memdbgon.h" - - -// This is a useful macro to iterate from head to tail in a linked list. -#define FOR_EACH_LL( listName, iteratorName ) \ - for( int iteratorName=listName.Head(); iteratorName != listName.InvalidIndex(); iteratorName = listName.Next( iteratorName ) ) - -//----------------------------------------------------------------------------- -// class CUtlMultiList: -// description: -// A lovely index-based linked list! T is the class type, I is the index -// type, which usually should be an unsigned short or smaller. -// This list can contain multiple lists -//----------------------------------------------------------------------------- -template -class CUtlMultiList -{ -public: - typedef I ListHandle_t; - - // constructor, destructor - CUtlMultiList( int growSize = 0, int initSize = 0 ); - CUtlMultiList( void *pMemory, int memsize ); - ~CUtlMultiList( ); - - // gets particular elements - T& Element( I i ); - T const& Element( I i ) const; - T& operator[]( I i ); - T const& operator[]( I i ) const; - - // Make sure we have a particular amount of memory - void EnsureCapacity( int num ); - - // Memory deallocation - void Purge(); - - // List Creation/deletion - ListHandle_t CreateList(); - void DestroyList( ListHandle_t list ); - bool IsValidList( ListHandle_t list ) const; - - // Insertion methods (call default constructor).... - I InsertBefore( ListHandle_t list, I before ); - I InsertAfter( ListHandle_t list, I after ); - I AddToHead( ListHandle_t list ); - I AddToTail( ListHandle_t list ); - - // Insertion methods (call copy constructor).... - I InsertBefore( ListHandle_t list, I before, T const& src ); - I InsertAfter( ListHandle_t list, I after, T const& src ); - I AddToHead( ListHandle_t list, T const& src ); - I AddToTail( ListHandle_t list, T const& src ); - - // Removal methods - void Remove( ListHandle_t list, I elem ); - - // Removes all items in a single list - void RemoveAll( ListHandle_t list ); - - // Removes all items in all lists - void RemoveAll(); - - // Allocation/deallocation methods - // NOTE: To free, it must *not* be in a list! - I Alloc( ); - void Free( I elem ); - - // list modification - void LinkBefore( ListHandle_t list, I before, I elem ); - void LinkAfter( ListHandle_t list, I after, I elem ); - void Unlink( ListHandle_t list, I elem ); - void LinkToHead( ListHandle_t list, I elem ); - void LinkToTail( ListHandle_t list, I elem ); - - // invalid index - static I InvalidIndex() { return (I)~0; } - static size_t ElementSize() { return sizeof(ListElem_t); } - - // list statistics - int Count( ListHandle_t list ) const; - int TotalCount( ) const; - I MaxElementIndex() const; - - // Traversing the list - I Head( ListHandle_t list ) const; - I Tail( ListHandle_t list ) const; - I Previous( I element ) const; - I Next( I element ) const; - - // Are nodes in a list or valid? - bool IsValidIndex( I i ) const; - bool IsInList( I i ) const; - -protected: - // What the linked list element looks like - struct ListElem_t - { - T m_Element; - I m_Previous; - I m_Next; - }; - - struct List_t - { - I m_Head; - I m_Tail; - I m_Count; - }; - - // constructs the class - void ConstructList( ); - - // Gets at the list element.... - ListElem_t& InternalElement( I i ) { return m_Memory[i]; } - ListElem_t const& InternalElement( I i ) const { return m_Memory[i]; } - - // A test for debug mode only... - bool IsElementInList( ListHandle_t list, I elem ) const; - - // copy constructors not allowed - CUtlMultiList( CUtlMultiList const& list ) { Assert(0); } - - CUtlMemory m_Memory; - CUtlLinkedList m_List; - I* m_pElementList; - - I m_FirstFree; - I m_TotalElements; - I m_MaxElementIndex; // The number allocated - - void ResetDbgInfo() - { - m_pElements = m_Memory.Base(); - -#ifdef _DEBUG - // Allocate space for the element list (which list is each element in) - if (m_Memory.NumAllocated() > 0) - { - if (!m_pElementList) - { - m_pElementList = (I*)malloc( m_Memory.NumAllocated() * sizeof(I) ); - } - else - { - m_pElementList = (I*)realloc( m_pElementList, m_Memory.NumAllocated() * sizeof(I) ); - } - } -#endif - } - - // For debugging purposes; - // it's in release builds so this can be used in libraries correctly - ListElem_t *m_pElements; -}; - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template -CUtlMultiList::CUtlMultiList( int growSize, int initSize ) : - m_Memory(growSize, initSize), m_pElementList(0) -{ - ConstructList(); -} - -template -CUtlMultiList::CUtlMultiList( void* pMemory, int memsize ) : - m_Memory((ListElem_t *)pMemory, memsize/sizeof(ListElem_t)), m_pElementList(0) -{ - ConstructList(); -} - -template -CUtlMultiList::~CUtlMultiList( ) -{ - RemoveAll(); - if (m_pElementList) - free(m_pElementList); -} - -template -void CUtlMultiList::ConstructList( ) -{ - m_FirstFree = InvalidIndex(); - m_TotalElements = 0; - m_MaxElementIndex = 0; - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// gets particular elements -//----------------------------------------------------------------------------- -template -inline T& CUtlMultiList::Element( I i ) -{ - return m_Memory[i].m_Element; -} - -template -inline T const& CUtlMultiList::Element( I i ) const -{ - return m_Memory[i].m_Element; -} - -template -inline T& CUtlMultiList::operator[]( I i ) -{ - return m_Memory[i].m_Element; -} - -template -inline T const& CUtlMultiList::operator[]( I i ) const -{ - return m_Memory[i].m_Element; -} - - -//----------------------------------------------------------------------------- -// list creation/destruction -//----------------------------------------------------------------------------- -template -typename CUtlMultiList::ListHandle_t CUtlMultiList::CreateList() -{ - ListHandle_t l = m_List.AddToTail(); - m_List[l].m_Head = m_List[l].m_Tail = InvalidIndex(); - m_List[l].m_Count = 0; - return l; -} - -template -void CUtlMultiList::DestroyList( ListHandle_t list ) -{ - Assert( IsValidList(list) ); - RemoveAll( list ); - m_List.Remove(list); -} - -template -bool CUtlMultiList::IsValidList( ListHandle_t list ) const -{ - return m_List.IsValidIndex(list); -} - - -//----------------------------------------------------------------------------- -// list statistics -//----------------------------------------------------------------------------- -template -inline int CUtlMultiList::TotalCount() const -{ - return m_TotalElements; -} - -template -inline int CUtlMultiList::Count( ListHandle_t list ) const -{ - Assert( IsValidList(list) ); - return m_List[list].m_Count; -} - -template -inline I CUtlMultiList::MaxElementIndex() const -{ - return m_MaxElementIndex; -} - - -//----------------------------------------------------------------------------- -// Traversing the list -//----------------------------------------------------------------------------- -template -inline I CUtlMultiList::Head(ListHandle_t list) const -{ - Assert( IsValidList(list) ); - return m_List[list].m_Head; -} - -template -inline I CUtlMultiList::Tail(ListHandle_t list) const -{ - Assert( IsValidList(list) ); - return m_List[list].m_Tail; -} - -template -inline I CUtlMultiList::Previous( I i ) const -{ - Assert( IsValidIndex(i) ); - return InternalElement(i).m_Previous; -} - -template -inline I CUtlMultiList::Next( I i ) const -{ - Assert( IsValidIndex(i) ); - return InternalElement(i).m_Next; -} - - -//----------------------------------------------------------------------------- -// Are nodes in the list or valid? -//----------------------------------------------------------------------------- -template -inline bool CUtlMultiList::IsValidIndex( I i ) const -{ - return (i < m_MaxElementIndex) && (i >= 0) && - ((m_Memory[i].m_Previous != i) || (m_Memory[i].m_Next == i)); -} - -template -inline bool CUtlMultiList::IsInList( I i ) const -{ - return (i < m_MaxElementIndex) && (i >= 0) && (Previous(i) != i); -} - - -//----------------------------------------------------------------------------- -// Makes sure we have enough memory allocated to store a requested # of elements -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlMultiList::EnsureCapacity( int num ) -{ - m_Memory.EnsureCapacity(num); - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Deallocate memory -//----------------------------------------------------------------------------- -template -void CUtlMultiList::Purge() -{ - RemoveAll(); - m_List.Purge(); - m_Memory.Purge( ); - m_List.Purge(); - m_FirstFree = InvalidIndex(); - m_TotalElements = 0; - m_MaxElementIndex = 0; - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Node allocation/deallocation -//----------------------------------------------------------------------------- -template -I CUtlMultiList::Alloc( ) -{ - I elem; - if (m_FirstFree == InvalidIndex()) - { - // Nothing in the free list; add. - // Since nothing is in the free list, m_TotalElements == total # of elements - // the list knows about. - if (m_MaxElementIndex == m_Memory.NumAllocated()) - { - m_Memory.Grow(); - ResetDbgInfo(); - } - - elem = (I)m_MaxElementIndex; - ++m_MaxElementIndex; - } - else - { - elem = m_FirstFree; - m_FirstFree = InternalElement(m_FirstFree).m_Next; - } - - // Mark the element as not being in a list - InternalElement(elem).m_Next = InternalElement(elem).m_Previous = elem; - - ++m_TotalElements; - - Construct( &Element(elem) ); - - return elem; -} - -template -void CUtlMultiList::Free( I elem ) -{ - Assert( IsValidIndex(elem) && !IsInList(elem) ); - Destruct( &Element(elem) ); - InternalElement(elem).m_Next = m_FirstFree; - m_FirstFree = elem; - --m_TotalElements; -} - - -//----------------------------------------------------------------------------- -// A test for debug mode only... -//----------------------------------------------------------------------------- -template -inline bool CUtlMultiList::IsElementInList( ListHandle_t list, I elem ) const -{ - if (!m_pElementList) - return true; - - return m_pElementList[elem] == list; -} - - -//----------------------------------------------------------------------------- -// list modification -//----------------------------------------------------------------------------- -template -void CUtlMultiList::LinkBefore( ListHandle_t list, I before, I elem ) -{ - Assert( IsValidIndex(elem) && IsValidList(list) ); - - // Unlink it if it's in the list at the moment - Unlink(list, elem); - - ListElem_t& newElem = InternalElement(elem); - - // The element *after* our newly linked one is the one we linked before. - newElem.m_Next = before; - - if (before == InvalidIndex()) - { - // In this case, we're linking to the end of the list, so reset the tail - newElem.m_Previous = m_List[list].m_Tail; - m_List[list].m_Tail = elem; - } - else - { - // Here, we're not linking to the end. Set the prev pointer to point to - // the element we're linking. - Assert( IsInList(before) ); - ListElem_t& beforeElem = InternalElement(before); - newElem.m_Previous = beforeElem.m_Previous; - beforeElem.m_Previous = elem; - } - - // Reset the head if we linked to the head of the list - if (newElem.m_Previous == InvalidIndex()) - m_List[list].m_Head = elem; - else - InternalElement(newElem.m_Previous).m_Next = elem; - - // one more element baby - ++m_List[list].m_Count; - - // Store the element into the list - if (m_pElementList) - m_pElementList[elem] = list; -} - -template -void CUtlMultiList::LinkAfter( ListHandle_t list, I after, I elem ) -{ - Assert( IsValidIndex(elem) ); - - // Unlink it if it's in the list at the moment - Unlink(list, elem); - - ListElem_t& newElem = InternalElement(elem); - - // The element *before* our newly linked one is the one we linked after - newElem.m_Previous = after; - if (after == InvalidIndex()) - { - // In this case, we're linking to the head of the list, reset the head - newElem.m_Next = m_List[list].m_Head; - m_List[list].m_Head = elem; - } - else - { - // Here, we're not linking to the end. Set the next pointer to point to - // the element we're linking. - Assert( IsInList(after) ); - ListElem_t& afterElem = InternalElement(after); - newElem.m_Next = afterElem.m_Next; - afterElem.m_Next = elem; - } - - // Reset the tail if we linked to the tail of the list - if (newElem.m_Next == InvalidIndex()) - m_List[list].m_Tail = elem; - else - InternalElement(newElem.m_Next).m_Previous = elem; - - // one more element baby - ++m_List[list].m_Count; - - // Store the element into the list - if (m_pElementList) - m_pElementList[elem] = list; -} - -template -void CUtlMultiList::Unlink( ListHandle_t list, I elem ) -{ - Assert( IsValidIndex(elem) && IsValidList(list) ); - - if (IsInList(elem)) - { - // Make sure the element is in the right list - Assert( IsElementInList( list, elem ) ); - ListElem_t& oldElem = InternalElement(elem); - - // If we're the first guy, reset the head - // otherwise, make our previous node's next pointer = our next - if (oldElem.m_Previous != InvalidIndex()) - InternalElement(oldElem.m_Previous).m_Next = oldElem.m_Next; - else - m_List[list].m_Head = oldElem.m_Next; - - // If we're the last guy, reset the tail - // otherwise, make our next node's prev pointer = our prev - if (oldElem.m_Next != InvalidIndex()) - InternalElement(oldElem.m_Next).m_Previous = oldElem.m_Previous; - else - m_List[list].m_Tail = oldElem.m_Previous; - - // This marks this node as not in the list, - // but not in the free list either - oldElem.m_Previous = oldElem.m_Next = elem; - - // One less puppy - --m_List[list].m_Count; - - // Store the element into the list - if (m_pElementList) - m_pElementList[elem] = m_List.InvalidIndex(); - } -} - -template -inline void CUtlMultiList::LinkToHead( ListHandle_t list, I elem ) -{ - LinkAfter( list, InvalidIndex(), elem ); -} - -template -inline void CUtlMultiList::LinkToTail( ListHandle_t list, I elem ) -{ - LinkBefore( list, InvalidIndex(), elem ); -} - - -//----------------------------------------------------------------------------- -// Insertion methods; allocates and links (uses default constructor) -//----------------------------------------------------------------------------- -template -I CUtlMultiList::InsertBefore( ListHandle_t list, I before ) -{ - // Make a new node - I newNode = Alloc(); - - // Link it in - LinkBefore( list, before, newNode ); - - // Construct the data - Construct( &Element(newNode) ); - - return newNode; -} - -template -I CUtlMultiList::InsertAfter( ListHandle_t list, I after ) -{ - // Make a new node - I newNode = Alloc(); - - // Link it in - LinkAfter( list, after, newNode ); - - // Construct the data - Construct( &Element(newNode) ); - - return newNode; -} - -template -inline I CUtlMultiList::AddToHead( ListHandle_t list ) -{ - return InsertAfter( list, InvalidIndex() ); -} - -template -inline I CUtlMultiList::AddToTail( ListHandle_t list ) -{ - return InsertBefore( list, InvalidIndex() ); -} - - -//----------------------------------------------------------------------------- -// Insertion methods; allocates and links (uses copy constructor) -//----------------------------------------------------------------------------- -template -I CUtlMultiList::InsertBefore( ListHandle_t list, I before, T const& src ) -{ - // Make a new node - I newNode = Alloc(); - - // Link it in - LinkBefore( list, before, newNode ); - - // Construct the data - CopyConstruct( &Element(newNode), src ); - - return newNode; -} - -template -I CUtlMultiList::InsertAfter( ListHandle_t list, I after, T const& src ) -{ - // Make a new node - I newNode = Alloc(); - - // Link it in - LinkAfter( list, after, newNode ); - - // Construct the data - CopyConstruct( &Element(newNode), src ); - - return newNode; -} - -template -inline I CUtlMultiList::AddToHead( ListHandle_t list, T const& src ) -{ - return InsertAfter( list, InvalidIndex(), src ); -} - -template -inline I CUtlMultiList::AddToTail( ListHandle_t list, T const& src ) -{ - return InsertBefore( list, InvalidIndex(), src ); -} - - -//----------------------------------------------------------------------------- -// Removal methods -//----------------------------------------------------------------------------- -template -void CUtlMultiList::Remove( ListHandle_t list, I elem ) -{ - if (IsInList(elem)) - Unlink(list, elem); - Free( elem ); -} - -// Removes all items in a single list -template -void CUtlMultiList::RemoveAll( ListHandle_t list ) -{ - Assert( IsValidList(list) ); - I i = Head(list); - I next; - while( i != InvalidIndex() ) - { - next = Next(i); - Remove(list, i); - i = next; - } -} - - -template -void CUtlMultiList::RemoveAll() -{ - if (m_MaxElementIndex == 0) - return; - - // Put everything into the free list - I prev = InvalidIndex(); - for (int i = (int)m_MaxElementIndex; --i >= 0; ) - { - // Invoke the destructor - if (IsValidIndex((I)i)) - Destruct( &Element((I)i) ); - - // next points to the next free list item - InternalElement((I)i).m_Next = prev; - - // Indicates it's in the free list - InternalElement((I)i).m_Previous = (I)i; - prev = (I)i; - } - - // First free points to the first element - m_FirstFree = 0; - - // Clear everything else out - for (I list = m_List.Head(); list != m_List.InvalidIndex(); list = m_List.Next(list) ) - { - m_List[list].m_Head = InvalidIndex(); - m_List[list].m_Tail = InvalidIndex(); - m_List[list].m_Count = 0; - } - - m_TotalElements = 0; -} - - -#include "tier0/memdbgoff.h" - -#endif // UTLMULTILIST_H diff --git a/Resources/NetHook/tier1/utlntree.h b/Resources/NetHook/tier1/utlntree.h deleted file mode 100644 index 1d937eb2..00000000 --- a/Resources/NetHook/tier1/utlntree.h +++ /dev/null @@ -1,624 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: N-way tree container class -// -// $Revision: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLNTREE_H -#define UTLNTREE_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "basetypes.h" -#include "utlmemory.h" -#include "tier0/dbg.h" - - -#define INVALID_NTREE_IDX ((I)~0) - -//----------------------------------------------------------------------------- -// class CUtlNTree: -// description: -// A lovely index-based linked list! T is the class type, I is the index -// type, which usually should be an unsigned short or smaller. -//----------------------------------------------------------------------------- -template -class CUtlNTree -{ -public: - typedef T ElemType_t; - typedef I IndexType_t; - - // constructor, destructor - CUtlNTree( int growSize = 0, int initSize = 0 ); - CUtlNTree( void *pMemory, int memsize ); - ~CUtlNTree( ); - - // gets particular elements - T& Element( I i ); - const T& Element( I i ) const; - T& operator[]( I i ); - const T& operator[]( I i ) const; - - // Make sure we have a particular amount of memory - void EnsureCapacity( int num ); - - // Clears the tree, doesn't deallocate memory - void RemoveAll(); - - // Memory deallocation - void Purge(); - - // Allocation/deallocation methods - I Alloc( ); - void Free( I elem ); - void FreeSubTree( I elem ); - - // list modification - void SetRoot( I root ); - void LinkChildBefore( I parent, I before, I elem ); - void LinkChildAfter( I parent, I after, I elem ); - void Unlink( I elem ); - - // Alloc + link combined - I InsertChildBefore( I parent, I before ); - I InsertChildAfter( I parent, I after ); - I InsertChildBefore( I parent, I before, const T &elem ); - I InsertChildAfter( I parent, I after, const T &elem ); - - // Unlink + free combined - void Remove( I elem ); - void RemoveSubTree( I elem ); - - // invalid index - inline static I InvalidIndex() { return INVALID_NTREE_IDX; } - inline static size_t ElementSize() { return sizeof(Node_t); } - - // list statistics - int Count() const; - I MaxElementIndex() const; - - // Traversing the list - I Root() const; - I FirstChild( I i ) const; - I PrevSibling( I i ) const; - I NextSibling( I i ) const; - I Parent( I i ) const; - - // Are nodes in the list or valid? - bool IsValidIndex( I i ) const; - bool IsInTree( I i ) const; - -protected: - // What the linked list element looks like - struct Node_t - { - T m_Element; - I m_Parent; - I m_FirstChild; - I m_PrevSibling; - I m_NextSibling; - - private: - // No copy constructor for these... - Node_t( const Node_t& ); - }; - - // constructs the class - void ConstructList(); - - // Allocates the element, doesn't call the constructor - I AllocInternal(); - - // Gets at the node element.... - Node_t& InternalNode( I i ) { return m_Memory[i]; } - const Node_t& InternalNode( I i ) const { return m_Memory[i]; } - - void ResetDbgInfo() - { - m_pElements = m_Memory.Base(); - } - - // copy constructors not allowed - CUtlNTree( CUtlNTree const& tree ) { Assert(0); } - - CUtlMemory m_Memory; - I m_Root; - I m_FirstFree; - I m_ElementCount; // The number actually in the tree - I m_MaxElementIndex; // The max index we've ever assigned - - // For debugging purposes; - // it's in release builds so this can be used in libraries correctly - Node_t *m_pElements; -}; - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template -CUtlNTree::CUtlNTree( int growSize, int initSize ) : - m_Memory(growSize, initSize) -{ - ConstructList(); - ResetDbgInfo(); -} - -template -CUtlNTree::CUtlNTree( void* pMemory, int memsize ) : - m_Memory((ListElem_t *)pMemory, memsize/sizeof(ListElem_t)) -{ - ConstructList(); - ResetDbgInfo(); -} - -template -CUtlNTree::~CUtlNTree( ) -{ - RemoveAll(); -} - -template -void CUtlNTree::ConstructList() -{ - m_Root = InvalidIndex(); - m_FirstFree = InvalidIndex(); - m_ElementCount = m_MaxElementIndex = 0; -} - - -//----------------------------------------------------------------------------- -// gets particular elements -//----------------------------------------------------------------------------- -template -inline T& CUtlNTree::Element( I i ) -{ - return m_Memory[i].m_Element; -} - -template -inline const T& CUtlNTree::Element( I i ) const -{ - return m_Memory[i].m_Element; -} - -template -inline T& CUtlNTree::operator[]( I i ) -{ - return m_Memory[i].m_Element; -} - -template -inline const T& CUtlNTree::operator[]( I i ) const -{ - return m_Memory[i].m_Element; -} - - -//----------------------------------------------------------------------------- -// list statistics -//----------------------------------------------------------------------------- -template -inline int CUtlNTree::Count() const -{ - return m_ElementCount; -} - -template -inline I CUtlNTree::MaxElementIndex() const -{ - return m_MaxElementIndex; -} - - -//----------------------------------------------------------------------------- -// Traversing the list -//----------------------------------------------------------------------------- -template -inline I CUtlNTree::Root() const -{ - return m_Root; -} - -template -inline I CUtlNTree::FirstChild( I i ) const -{ - Assert( IsInTree(i) ); - return InternalNode(i).m_FirstChild; -} - -template -inline I CUtlNTree::PrevSibling( I i ) const -{ - Assert( IsInTree(i) ); - return InternalNode(i).m_PrevSibling; -} - -template -inline I CUtlNTree::NextSibling( I i ) const -{ - Assert( IsInTree(i) ); - return InternalNode(i).m_NextSibling; -} - -template -inline I CUtlNTree::Parent( I i ) const -{ - Assert( IsInTree(i) ); - return InternalNode(i).m_Parent; -} - - -//----------------------------------------------------------------------------- -// Are nodes in the list or valid? -//----------------------------------------------------------------------------- -template -inline bool CUtlNTree::IsValidIndex( I i ) const -{ - return (i < m_MaxElementIndex) && (i >= 0); -} - -template -inline bool CUtlNTree::IsInTree( I i ) const -{ - return (i < m_MaxElementIndex) && (i >= 0) && (InternalNode(i).m_PrevSibling != i); -} - - -//----------------------------------------------------------------------------- -// Makes sure we have enough memory allocated to store a requested # of elements -//----------------------------------------------------------------------------- -template< class T, class I > -void CUtlNTree::EnsureCapacity( int num ) -{ - MEM_ALLOC_CREDIT_CLASS(); - m_Memory.EnsureCapacity(num); - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Deallocate memory -//----------------------------------------------------------------------------- -template -void CUtlNTree::Purge() -{ - RemoveAll(); - m_Memory.Purge( ); - m_FirstFree = InvalidIndex(); - m_MaxElementIndex = 0; - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Node allocation/deallocation -//----------------------------------------------------------------------------- -template -I CUtlNTree::AllocInternal( ) -{ - I elem; - if ( m_FirstFree == INVALID_NTREE_IDX ) - { - // Nothing in the free list; add. - // Since nothing is in the free list, m_MaxElementIndex == total # of elements - // the list knows about. - if ((int)m_MaxElementIndex == m_Memory.NumAllocated()) - { - MEM_ALLOC_CREDIT_CLASS(); - m_Memory.Grow(); - } - - Assert( m_MaxElementIndex != INVALID_NTREE_IDX ); - - elem = (I)m_MaxElementIndex; - ++m_MaxElementIndex; - - if ( elem == InvalidIndex() ) - { - Error("CUtlNTree overflow!\n"); - } - } - else - { - elem = m_FirstFree; - m_FirstFree = InternalNode( m_FirstFree ).m_NextSibling; - } - - Node_t &node = InternalNode( elem ); - node.m_NextSibling = node.m_PrevSibling = node.m_Parent = node.m_FirstChild = INVALID_NTREE_IDX; - ResetDbgInfo(); - - // one more element baby - ++m_ElementCount; - - return elem; -} - -template -I CUtlNTree::Alloc( ) -{ - I elem = AllocInternal(); - Construct( &Element(elem) ); - return elem; -} - -template -void CUtlNTree::Free( I elem ) -{ - Assert( IsInTree( elem ) ); - Unlink( elem ); - - // If there's children, this will result in leaks. Use FreeSubTree instead. - Assert( FirstChild( elem ) == INVALID_NTREE_IDX ); - - Node_t &node = InternalNode( elem ); - Destruct( &node.m_Element ); - node.m_NextSibling = m_FirstFree; - node.m_PrevSibling = elem; // Marks it as being in the free list - node.m_Parent = node.m_FirstChild = INVALID_NTREE_IDX; - m_FirstFree = elem; - - // one less element baby - --m_ElementCount; -} - -template -void CUtlNTree::FreeSubTree( I elem ) -{ - Assert( IsValidIndex( elem ) ); - - I child = FirstChild( elem ); - while ( child != INVALID_NTREE_IDX ) - { - I next = NextSibling( child ); - FreeSubTree( child ); - child = next; - } - - Free( elem ); -} - - -//----------------------------------------------------------------------------- -// Clears the tree -//----------------------------------------------------------------------------- -template -void CUtlNTree::RemoveAll() -{ - if ( m_MaxElementIndex == 0 ) - return; - - // Put everything into the free list (even unlinked things ) - I prev = InvalidIndex(); - for (int i = (int)m_MaxElementIndex; --i >= 0; prev = (I)i ) - { - Node_t &node = InternalNode( i ); - if ( IsInTree( i ) ) - { - Destruct( &node.m_Element ); - } - - node.m_NextSibling = prev; - node.m_PrevSibling = (I)i; // Marks it as being in the free list - node.m_Parent = node.m_FirstChild = INVALID_NTREE_IDX; - } - - // First free points to the first element - m_FirstFree = 0; - - // Clear everything else out - m_Root = INVALID_NTREE_IDX; - m_ElementCount = 0; -} - - -//----------------------------------------------------------------------------- -// list modification -//----------------------------------------------------------------------------- -template -void CUtlNTree::SetRoot( I root ) -{ - // Resetting the root while it's got stuff in it is bad... - Assert( m_Root == InvalidIndex() ); - m_Root = root; -} - - -//----------------------------------------------------------------------------- -// Links a node after a particular node -//----------------------------------------------------------------------------- -template -void CUtlNTree::LinkChildAfter( I parent, I after, I elem ) -{ - Assert( IsInTree(elem) ); - - // Unlink it if it's in the list at the moment - Unlink(elem); - - Node_t& newElem = InternalNode(elem); - newElem.m_Parent = parent; - newElem.m_PrevSibling = after; - if ( after != INVALID_NTREE_IDX ) - { - Node_t& prevSiblingNode = InternalNode( after ); - newElem.m_NextSibling = prevSiblingNode.m_NextSibling; - prevSiblingNode.m_NextSibling = elem; - } - else - { - if ( parent != INVALID_NTREE_IDX ) - { - Node_t& parentNode = InternalNode( parent ); - newElem.m_NextSibling = parentNode.m_FirstChild; - parentNode.m_FirstChild = elem; - } - else - { - newElem.m_NextSibling = m_Root; - if ( m_Root != INVALID_NTREE_IDX ) - { - Node_t& rootNode = InternalNode( m_Root ); - rootNode.m_PrevSibling = elem; - } - m_Root = elem; - } - } - - if ( newElem.m_NextSibling != INVALID_NTREE_IDX ) - { - Node_t& nextSiblingNode = InternalNode( newElem.m_NextSibling ); - nextSiblingNode.m_PrevSibling = elem; - } -} - - -//----------------------------------------------------------------------------- -// Links a node before a particular node -//----------------------------------------------------------------------------- -template -void CUtlNTree::LinkChildBefore( I parent, I before, I elem ) -{ - Assert( IsValidIndex(elem) ); - - if ( before != INVALID_NTREE_IDX ) - { - LinkChildAfter( parent, InternalNode( before ).m_PrevSibling, elem ); - return; - } - - // NOTE: I made the choice to do an O(n) operation here - // instead of store more data per node (LastChild). - // This might not be the right choice. Revisit if we get perf problems. - I after; - if ( parent != INVALID_NTREE_IDX ) - { - after = InternalNode( parent ).m_FirstChild; - } - else - { - after = m_Root; - } - - if ( after == INVALID_NTREE_IDX ) - { - LinkChildAfter( parent, after, elem ); - return; - } - - I next = InternalNode( after ).m_NextSibling; - while ( next != InvalidIndex() ) - { - after = next; - next = InternalNode( next ).m_NextSibling; - } - - LinkChildAfter( parent, after, elem ); -} - - -//----------------------------------------------------------------------------- -// Unlinks a node from the tree -//----------------------------------------------------------------------------- -template -void CUtlNTree::Unlink( I elem ) -{ - Assert( IsInTree(elem) ); - - Node_t *pOldNode = &InternalNode( elem ); - - // If we're the first guy, reset the head - // otherwise, make our previous node's next pointer = our next - if ( pOldNode->m_PrevSibling != INVALID_NTREE_IDX ) - { - InternalNode( pOldNode->m_PrevSibling ).m_NextSibling = pOldNode->m_NextSibling; - } - else - { - if ( pOldNode->m_Parent != INVALID_NTREE_IDX ) - { - InternalNode( pOldNode->m_Parent ).m_FirstChild = pOldNode->m_NextSibling; - } - else if ( m_Root == elem ) - { - m_Root = pOldNode->m_NextSibling; - } - } - - // If we're the last guy, reset the tail - // otherwise, make our next node's prev pointer = our prev - if ( pOldNode->m_NextSibling != INVALID_NTREE_IDX ) - { - InternalNode( pOldNode->m_NextSibling ).m_PrevSibling = pOldNode->m_PrevSibling; - } - - // Unlink everything except children - pOldNode->m_Parent = pOldNode->m_PrevSibling = pOldNode->m_NextSibling = INVALID_NTREE_IDX; -} - - -//----------------------------------------------------------------------------- -// Alloc + link combined -//----------------------------------------------------------------------------- -template -I CUtlNTree::InsertChildBefore( I parent, I before ) -{ - I elem = AllocInternal(); - Construct( &Element( elem ) ); - LinkChildBefore( parent, before, elem ); - return elem; -} - -template -I CUtlNTree::InsertChildAfter( I parent, I after ) -{ - I elem = AllocInternal(); - Construct( &Element( elem ) ); - LinkChildAfter( parent, after, elem ); - return elem; -} - -template -I CUtlNTree::InsertChildBefore( I parent, I before, const T &data ) -{ - I elem = AllocInternal(); - CopyConstruct( &Element( elem ), data ); - LinkChildBefore( parent, before, elem ); - return elem; -} - -template -I CUtlNTree::InsertChildAfter( I parent, I after, const T &data ) -{ - I elem = AllocInternal(); - CopyConstruct( &Element( elem ), data ); - LinkChildAfter( parent, after, elem ); - return elem; -} - - -//----------------------------------------------------------------------------- -// Unlink + free combined -//----------------------------------------------------------------------------- -template -void CUtlNTree::Remove( I elem ) -{ - Unlink( elem ); - Free( elem ); -} - -template -void CUtlNTree::RemoveSubTree( I elem ) -{ - UnlinkSubTree( elem ); - Free( elem ); -} - - -#endif // UTLNTREE_H diff --git a/Resources/NetHook/tier1/utlobjectreference.h b/Resources/NetHook/tier1/utlobjectreference.h deleted file mode 100644 index 6b09b04c..00000000 --- a/Resources/NetHook/tier1/utlobjectreference.h +++ /dev/null @@ -1,165 +0,0 @@ -//===== Copyright © 1996-2006, Valve Corporation, All rights reserved. ======// -// -// $Revision: $ -// $NoKeywords: $ -//===========================================================================// - -#ifndef UTLOBJECTREFERENCE_H -#define UTLOBJECTREFERENCE_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier1/utlintrusivelist.h" -#include "mathlib/mathlib.h" - - -// Purpose: class for keeping track of all the references that exist to an object. When the object -// being referenced is freed, all of the references pointing at it will become null. -// -// To Use: -// Add a DECLARE_REFERENCED_CLASS to the class that you want to use CutlReferences with. -// Replace pointers to that class with CUtlReferences. -// Check these references for null in appropriate places. -// -// NOTE : You can still happily use pointers instead of references where you want to - these -// pointers will not magically become null like references would, but if you know no one is going -// to delete the underlying object during a partcular section of code, it doesn't -// matter. Basically, CUtlReferences don't rely on every use of an object using one. - - - - -template class CUtlReference -{ -public: - FORCEINLINE CUtlReference(void) - { - m_pNext = m_pPrev = NULL; - m_pObject = NULL; - } - - FORCEINLINE CUtlReference(T *pObj) - { - m_pNext = m_pPrev = NULL; - AddRef( pObj ); - } - - FORCEINLINE ~CUtlReference(void) - { - KillRef(); - } - - FORCEINLINE void Set(T *pObj) - { - if ( m_pObject != pObj ) - { - KillRef(); - AddRef( pObj ); - } - } - - FORCEINLINE T * operator()(void) const - { - return m_pObject; - } - - FORCEINLINE operator T*() - { - return m_pObject; - } - - FORCEINLINE operator const T*() const - { - return m_pObject; - } - - FORCEINLINE T* operator->() - { - return m_pObject; - } - - FORCEINLINE const T* operator->() const - { - return m_pObject; - } - - FORCEINLINE CUtlReference &operator=( const CUtlReference& otherRef ) - { - Set( otherRef.m_pObject ); - return *this; - } - - FORCEINLINE CUtlReference &operator=( T *pObj ) - { - Set( pObj ); - return *this; - } - - - FORCEINLINE bool operator==( const CUtlReference& o ) const - { - return ( o.m_pObject == m_pObject ); - } - -public: - CUtlReference *m_pNext; - CUtlReference *m_pPrev; - - T *m_pObject; - - FORCEINLINE void AddRef( T *pObj ) - { - m_pObject = pObj; - if ( pObj ) - { - pObj->m_References.AddToHead( this ); - } - } - - FORCEINLINE void KillRef(void) - { - if ( m_pObject ) - { - m_pObject->m_References.RemoveNode( this ); - m_pObject = NULL; - } - } - -}; - -template class CUtlReferenceList : public CUtlIntrusiveDList< CUtlReference > -{ -public: - ~CUtlReferenceList( void ) - { - CUtlReference *i = CUtlIntrusiveDList >::m_pHead; - while( i ) - { - CUtlReference *n = i->m_pNext; - i->m_pNext = NULL; - i->m_pPrev = NULL; - i->m_pObject = NULL; - i = n; - } - CUtlIntrusiveDList >::m_pHead = NULL; - } -}; - - -//----------------------------------------------------------------------------- -// Put this macro in classes that are referenced by CUtlReference -//----------------------------------------------------------------------------- -#define DECLARE_REFERENCED_CLASS( _className ) \ - private: \ - CUtlReferenceList< _className > m_References; \ - template friend class CUtlReference; - - -#endif - - - - - diff --git a/Resources/NetHook/tier1/utlpriorityqueue.h b/Resources/NetHook/tier1/utlpriorityqueue.h deleted file mode 100644 index 98486a6c..00000000 --- a/Resources/NetHook/tier1/utlpriorityqueue.h +++ /dev/null @@ -1,198 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLPRIORITYQUEUE_H -#define UTLPRIORITYQUEUE_H -#ifdef _WIN32 -#pragma once -#endif - -#include "utlvector.h" - -// T is the type stored in the queue, it must include the priority -// The head of the list contains the element with GREATEST priority -// configure the LessFunc_t to get the desired queue order -template< class T > -class CUtlPriorityQueue -{ -public: - // Less func typedef - // Returns true if the first parameter is "less priority" than the second - // Items that are "less priority" sort toward the tail of the queue - typedef bool (*LessFunc_t)( T const&, T const& ); - - typedef T ElemType_t; - - // constructor: lessfunc is required, but may be set after the constructor with - // SetLessFunc - CUtlPriorityQueue( int growSize = 0, int initSize = 0, LessFunc_t lessfunc = 0 ); - CUtlPriorityQueue( T *pMemory, int numElements, LessFunc_t lessfunc = 0 ); - - // gets particular elements - inline T const& ElementAtHead() const { return m_heap.Element(0); } - - inline bool IsValidIndex(int index) { return m_heap.IsValidIndex(index); } - - // O(lgn) to rebalance the heap - void RemoveAtHead(); - void RemoveAt( int index ); - - // O(lgn) to rebalance heap - void Insert( T const &element ); - // Sets the less func - void SetLessFunc( LessFunc_t func ); - - // Returns the count of elements in the queue - inline int Count() const { return m_heap.Count(); } - - // doesn't deallocate memory - void RemoveAll() { m_heap.RemoveAll(); } - - // Memory deallocation - void Purge() { m_heap.Purge(); } - - inline const T & Element( int index ) const { return m_heap.Element(index); } - -protected: - CUtlVector m_heap; - - void Swap( int index1, int index2 ); - - // Used for sorting. - LessFunc_t m_LessFunc; -}; - -template< class T > -inline CUtlPriorityQueue::CUtlPriorityQueue( int growSize, int initSize, LessFunc_t lessfunc ) : - m_heap(growSize, initSize), m_LessFunc(lessfunc) -{ -} - -template< class T > -inline CUtlPriorityQueue::CUtlPriorityQueue( T *pMemory, int numElements, LessFunc_t lessfunc ) : - m_heap(pMemory, numElements), m_LessFunc(lessfunc) -{ -} - -template -void CUtlPriorityQueue::RemoveAtHead() -{ - m_heap.FastRemove( 0 ); - int index = 0; - - int count = Count(); - if ( !count ) - return; - - int half = count/2; - int larger = index; - while ( index < half ) - { - int child = ((index+1) * 2) - 1; // if we wasted an element, this math would be more compact (1 based array) - if ( child < count ) - { - // Item has been filtered down to its proper place, terminate. - if ( m_LessFunc( m_heap[index], m_heap[child] ) ) - { - // mark the potential swap and check the other child - larger = child; - } - } - // go to sibling - child++; - if ( child < count ) - { - // If this child is larger, swap it instead - if ( m_LessFunc( m_heap[larger], m_heap[child] ) ) - larger = child; - } - - if ( larger == index ) - break; - - // swap with the larger child - Swap( index, larger ); - index = larger; - } -} - - -template -void CUtlPriorityQueue::RemoveAt( int index ) -{ - Assert(m_heap.IsValidIndex(index)); - m_heap.FastRemove( index ); - - int count = Count(); - if ( !count ) - return; - - int half = count/2; - int larger = index; - while ( index < half ) - { - int child = ((index+1) * 2) - 1; // if we wasted an element, this math would be more compact (1 based array) - if ( child < count ) - { - // Item has been filtered down to its proper place, terminate. - if ( m_LessFunc( m_heap[index], m_heap[child] ) ) - { - // mark the potential swap and check the other child - larger = child; - } - } - // go to sibling - child++; - if ( child < count ) - { - // If this child is larger, swap it instead - if ( m_LessFunc( m_heap[larger], m_heap[child] ) ) - larger = child; - } - - if ( larger == index ) - break; - - // swap with the larger child - Swap( index, larger ); - index = larger; - } -} - -template -void CUtlPriorityQueue::Insert( T const &element ) -{ - int index = m_heap.AddToTail(); - m_heap[index] = element; - - while ( index != 0 ) - { - int parent = ((index+1) / 2) - 1; - if ( m_LessFunc( m_heap[index], m_heap[parent] ) ) - break; - - // swap with parent and repeat - Swap( parent, index ); - index = parent; - } -} - -template -void CUtlPriorityQueue::Swap( int index1, int index2 ) -{ - T tmp = m_heap[index1]; - m_heap[index1] = m_heap[index2]; - m_heap[index2] = tmp; -} - -template -void CUtlPriorityQueue::SetLessFunc( LessFunc_t lessfunc ) -{ - m_LessFunc = lessfunc; -} - -#endif // UTLPRIORITYQUEUE_H diff --git a/Resources/NetHook/tier1/utlqueue.h b/Resources/NetHook/tier1/utlqueue.h deleted file mode 100644 index a148560e..00000000 --- a/Resources/NetHook/tier1/utlqueue.h +++ /dev/null @@ -1,114 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLQUEUE_H -#define UTLQUEUE_H -#ifdef _WIN32 -#pragma once -#endif - -#include "utlvector.h" - -// T is the type stored in the stack -template< class T > -class CUtlQueue -{ -public: - - // constructor: lessfunc is required, but may be set after the constructor with - // SetLessFunc - CUtlQueue( int growSize = 0, int initSize = 0 ); - CUtlQueue( T *pMemory, int numElements ); - - // return the item from the front of the queue and delete it - T const& RemoveAtHead(); - // return the item from the end of the queue and delete it - T const& RemoveAtTail(); - - // return item at the front of the queue - T const& Head(); - // return item at the end of the queue - T const& Tail(); - - // put a new item on the stack - void Insert( T const &element ); - - // checks if an element of this value already exists on the stack, returns true if it does - bool Check( T const element ); - - // Returns the count of elements in the stack - int Count() const { return m_heap.Count(); } - - // doesn't deallocate memory - void RemoveAll() { m_heap.RemoveAll(); } - - // Memory deallocation - void Purge() { m_heap.Purge(); } - -protected: - CUtlVector m_heap; - T m_current; -}; - -template< class T > -inline CUtlQueue::CUtlQueue( int growSize, int initSize ) : - m_heap(growSize, initSize) -{ -} - -template< class T > -inline CUtlQueue::CUtlQueue( T *pMemory, int numElements ) : - m_heap(pMemory, numElements) -{ -} - -template -inline T const& CUtlQueue::RemoveAtHead() -{ - m_current = m_heap[0]; - m_heap.Remove((int)0); - return m_current; -} - -template -inline T const& CUtlQueue::RemoveAtTail() -{ - m_current = m_heap[ m_heap.Count() - 1 ]; - m_heap.Remove((int)(m_heap.Count() - 1)); - return m_current; -} - -template -inline T const& CUtlQueue::Head() -{ - m_current = m_heap[0]; - return m_current; -} - -template -inline T const& CUtlQueue::Tail() -{ - m_current = m_heap[ m_heap.Count() - 1 ]; - return m_current; -} - -template -void CUtlQueue::Insert( T const &element ) -{ - int index = m_heap.AddToTail(); - m_heap[index] = element; -} - -template -bool CUtlQueue::Check( T const element ) -{ - int index = m_heap.Find(element); - return ( index != -1 ); -} - - -#endif // UTLQUEUE_H diff --git a/Resources/NetHook/tier1/utlrbtree.h b/Resources/NetHook/tier1/utlrbtree.h deleted file mode 100644 index ff30898b..00000000 --- a/Resources/NetHook/tier1/utlrbtree.h +++ /dev/null @@ -1,1557 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $Header: $ -// $NoKeywords: $ -//=============================================================================// - -#ifndef UTLRBTREE_H -#define UTLRBTREE_H - -#include "tier1/utlmemory.h" -#include "tier1/utlfixedmemory.h" -#include "tier1/utlblockmemory.h" - -//----------------------------------------------------------------------------- -// Tool to generate a default compare function for any type that implements -// operator<, including all simple types -//----------------------------------------------------------------------------- - -template -class CDefOps -{ -public: - static bool LessFunc( const T &lhs, const T &rhs ) { return ( lhs < rhs ); } -}; - -#define DefLessFunc( type ) CDefOps< type >::LessFunc - -//------------------------------------- - -inline bool StringLessThan( const char * const &lhs, const char * const &rhs) { return ( strcmp( lhs, rhs) < 0 ); } -inline bool CaselessStringLessThan( const char * const &lhs, const char * const &rhs ) { return ( stricmp( lhs, rhs) < 0 ); } - -// Same as CaselessStringLessThan, but it ignores differences in / and \. -inline bool CaselessStringLessThanIgnoreSlashes( const char * const &lhs, const char * const &rhs ) -{ - const char *pa = lhs; - const char *pb = rhs; - while ( *pa && *pb ) - { - char a = *pa; - char b = *pb; - - // Check for dir slashes. - if ( a == '/' || a == '\\' ) - { - if ( b != '/' && b != '\\' ) - return ('/' < b); - } - else - { - if ( a >= 'a' && a <= 'z' ) - a = 'A' + (a - 'a'); - - if ( b >= 'a' && b <= 'z' ) - b = 'A' + (b - 'a'); - - if ( a > b ) - return false; - else if ( a < b ) - return true; - } - ++pa; - ++pb; - } - - return false; -} - -//------------------------------------- -// inline these two templates to stop multiple definitions of the same code -template <> inline bool CDefOps::LessFunc( const char * const &lhs, const char * const &rhs ) { return StringLessThan( lhs, rhs ); } -template <> inline bool CDefOps::LessFunc( char * const &lhs, char * const &rhs ) { return StringLessThan( lhs, rhs ); } - -//------------------------------------- - -template -void SetDefLessFunc( RBTREE_T &RBTree ) -{ -#ifdef _WIN32 - RBTree.SetLessFunc( DefLessFunc( RBTREE_T::KeyType_t ) ); -#elif _LINUX - RBTree.SetLessFunc( DefLessFunc( typename RBTREE_T::KeyType_t ) ); -#endif -} - -//----------------------------------------------------------------------------- -// A red-black binary search tree -//----------------------------------------------------------------------------- - -template < class I > -struct UtlRBTreeLinks_t -{ - I m_Left; - I m_Right; - I m_Parent; - I m_Tag; -}; - -template < class T, class I > -struct UtlRBTreeNode_t : public UtlRBTreeLinks_t< I > -{ - T m_Data; -}; - -template < class T, class I = unsigned short, typename L = bool (*)( const T &, const T & ), class M = CUtlMemory< UtlRBTreeNode_t< T, I >, I > > -class CUtlRBTree -{ -public: - - typedef T KeyType_t; - typedef T ElemType_t; - typedef I IndexType_t; - - // Less func typedef - // Returns true if the first parameter is "less" than the second - typedef L LessFunc_t; - - // constructor, destructor - // Left at growSize = 0, the memory will first allocate 1 element and double in size - // at each increment. - // LessFunc_t is required, but may be set after the constructor using SetLessFunc() below - CUtlRBTree( int growSize = 0, int initSize = 0, const LessFunc_t &lessfunc = 0 ); - CUtlRBTree( const LessFunc_t &lessfunc ); - ~CUtlRBTree( ); - - void EnsureCapacity( int num ); - - void CopyFrom( const CUtlRBTree &other ); - - // gets particular elements - T& Element( I i ); - T const &Element( I i ) const; - T& operator[]( I i ); - T const &operator[]( I i ) const; - - // Gets the root - I Root() const; - - // Num elements - unsigned int Count() const; - - // Max "size" of the vector - // it's not generally safe to iterate from index 0 to MaxElement()-1 - // it IS safe to do so when using CUtlMemory as the allocator, - // but we should really remove patterns using this anyways, for safety and generality - I MaxElement() const; - - // Gets the children - I Parent( I i ) const; - I LeftChild( I i ) const; - I RightChild( I i ) const; - - // Tests if a node is a left or right child - bool IsLeftChild( I i ) const; - bool IsRightChild( I i ) const; - - // Tests if root or leaf - bool IsRoot( I i ) const; - bool IsLeaf( I i ) const; - - // Checks if a node is valid and in the tree - bool IsValidIndex( I i ) const; - - // Checks if the tree as a whole is valid - bool IsValid() const; - - // Invalid index - static I InvalidIndex(); - - // returns the tree depth (not a very fast operation) - int Depth( I node ) const; - int Depth() const; - - // Sets the less func - void SetLessFunc( const LessFunc_t &func ); - - // Allocation method - I NewNode(); - - // Insert method (inserts in order) - I Insert( T const &insert ); - void Insert( const T *pArray, int nItems ); - I InsertIfNotFound( T const &insert ); - - // Find method - I Find( T const &search ) const; - - // Remove methods - void RemoveAt( I i ); - bool Remove( T const &remove ); - void RemoveAll( ); - void Purge(); - - // Allocation, deletion - void FreeNode( I i ); - - // Iteration - I FirstInorder() const; - I NextInorder( I i ) const; - I PrevInorder( I i ) const; - I LastInorder() const; - - I FirstPreorder() const; - I NextPreorder( I i ) const; - I PrevPreorder( I i ) const; - I LastPreorder( ) const; - - I FirstPostorder() const; - I NextPostorder( I i ) const; - - // If you change the search key, this can be used to reinsert the - // element into the tree. - void Reinsert( I elem ); - - // swap in place - void Swap( CUtlRBTree< T, I, L > &that ); - -private: - // Can't copy the tree this way! - CUtlRBTree& operator=( const CUtlRBTree &other ); - -protected: - enum NodeColor_t - { - RED = 0, - BLACK - }; - - typedef UtlRBTreeNode_t< T, I > Node_t; - typedef UtlRBTreeLinks_t< I > Links_t; - - // Sets the children - void SetParent( I i, I parent ); - void SetLeftChild( I i, I child ); - void SetRightChild( I i, I child ); - void LinkToParent( I i, I parent, bool isLeft ); - - // Gets at the links - Links_t const &Links( I i ) const; - Links_t &Links( I i ); - - // Checks if a link is red or black - bool IsRed( I i ) const; - bool IsBlack( I i ) const; - - // Sets/gets node color - NodeColor_t Color( I i ) const; - void SetColor( I i, NodeColor_t c ); - - // operations required to preserve tree balance - void RotateLeft(I i); - void RotateRight(I i); - void InsertRebalance(I i); - void RemoveRebalance(I i); - - // Insertion, removal - I InsertAt( I parent, bool leftchild ); - - // copy constructors not allowed - CUtlRBTree( CUtlRBTree const &tree ); - - // Inserts a node into the tree, doesn't copy the data in. - void FindInsertionPosition( T const &insert, I &parent, bool &leftchild ); - - // Remove and add back an element in the tree. - void Unlink( I elem ); - void Link( I elem ); - - // Used for sorting. - LessFunc_t m_LessFunc; - - M m_Elements; - I m_Root; - I m_NumElements; - I m_FirstFree; - typename M::Iterator_t m_LastAlloc; // the last index allocated - - Node_t* m_pElements; - - FORCEINLINE M const &Elements( void ) const - { - return m_Elements; - } - - - void ResetDbgInfo() - { - m_pElements = (Node_t*)m_Elements.Base(); - } -}; - -// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice -template < class T, class I = int, typename L = bool (*)( const T &, const T & ) > -class CUtlFixedRBTree : public CUtlRBTree< T, I, L, CUtlFixedMemory< UtlRBTreeNode_t< T, I > > > -{ -public: - - typedef L LessFunc_t; - - CUtlFixedRBTree( int growSize = 0, int initSize = 0, const LessFunc_t &lessfunc = 0 ) - : CUtlRBTree< T, I, L, CUtlFixedMemory< UtlRBTreeNode_t< T, I > > >( growSize, initSize, lessfunc ) {} - CUtlFixedRBTree( const LessFunc_t &lessfunc ) - : CUtlRBTree< T, I, L, CUtlFixedMemory< UtlRBTreeNode_t< T, I > > >( lessfunc ) {} - - bool IsValidIndex( I i ) const - { - if ( !Elements().IsIdxValid( i ) ) - return false; - -#ifdef _DEBUG // it's safe to skip this here, since the only way to get indices after m_LastAlloc is to use MaxElement() - if ( Elements().IsIdxAfter( i, this->m_LastAlloc ) ) - { - Assert( 0 ); - return false; // don't read values that have been allocated, but not constructed - } -#endif - - return LeftChild(i) != i; - } - -protected: - void ResetDbgInfo() {} - -private: - // this doesn't make sense for fixed rbtrees, since there's no useful max pointer, and the index space isn't contiguous anyways - I MaxElement() const; -}; - -// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice -template < class T, class I = unsigned short, typename L = bool (*)( const T &, const T & ) > -class CUtlBlockRBTree : public CUtlRBTree< T, I, L, CUtlBlockMemory< UtlRBTreeNode_t< T, I >, I > > -{ -public: - typedef L LessFunc_t; - CUtlBlockRBTree( int growSize = 0, int initSize = 0, const LessFunc_t &lessfunc = 0 ) - : CUtlRBTree< T, I, L, CUtlBlockMemory< UtlRBTreeNode_t< T, I >, I > >( growSize, initSize, lessfunc ) {} - CUtlBlockRBTree( const LessFunc_t &lessfunc ) - : CUtlRBTree< T, I, L, CUtlBlockMemory< UtlRBTreeNode_t< T, I >, I > >( lessfunc ) {} -protected: - void ResetDbgInfo() {} -}; - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline CUtlRBTree::CUtlRBTree( int growSize, int initSize, const LessFunc_t &lessfunc ) : -m_Elements( growSize, initSize ), -m_LessFunc( lessfunc ), -m_Root( InvalidIndex() ), -m_NumElements( 0 ), -m_FirstFree( InvalidIndex() ), -m_LastAlloc( m_Elements.InvalidIterator() ) -{ - ResetDbgInfo(); -} - -template < class T, class I, typename L, class M > -inline CUtlRBTree::CUtlRBTree( const LessFunc_t &lessfunc ) : -m_Elements( 0, 0 ), -m_LessFunc( lessfunc ), -m_Root( InvalidIndex() ), -m_NumElements( 0 ), -m_FirstFree( InvalidIndex() ), -m_LastAlloc( m_Elements.InvalidIterator() ) -{ - ResetDbgInfo(); -} - -template < class T, class I, typename L, class M > -inline CUtlRBTree::~CUtlRBTree() -{ - Purge(); -} - -template < class T, class I, typename L, class M > -inline void CUtlRBTree::EnsureCapacity( int num ) -{ - m_Elements.EnsureCapacity( num ); -} - -template < class T, class I, typename L, class M > -inline void CUtlRBTree::CopyFrom( const CUtlRBTree &other ) -{ - Purge(); - m_Elements.EnsureCapacity( other.m_Elements.Count() ); - memcpy( m_Elements.Base(), other.m_Elements.Base(), other.m_Elements.Count() * sizeof( T ) ); - m_LessFunc = other.m_LessFunc; - m_Root = other.m_Root; - m_NumElements = other.m_NumElements; - m_FirstFree = other.m_FirstFree; - m_LastAlloc = other.m_LastAlloc; - ResetDbgInfo(); -} - -//----------------------------------------------------------------------------- -// gets particular elements -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline T &CUtlRBTree::Element( I i ) -{ - return m_Elements[i].m_Data; -} - -template < class T, class I, typename L, class M > -inline T const &CUtlRBTree::Element( I i ) const -{ - return m_Elements[i].m_Data; -} - -template < class T, class I, typename L, class M > -inline T &CUtlRBTree::operator[]( I i ) -{ - return Element(i); -} - -template < class T, class I, typename L, class M > -inline T const &CUtlRBTree::operator[]( I i ) const -{ - return Element(i); -} - -//----------------------------------------------------------------------------- -// -// various accessors -// -//----------------------------------------------------------------------------- - -//----------------------------------------------------------------------------- -// Gets the root -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline I CUtlRBTree::Root() const -{ - return m_Root; -} - -//----------------------------------------------------------------------------- -// Num elements -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline unsigned int CUtlRBTree::Count() const -{ - return (unsigned int)m_NumElements; -} - -//----------------------------------------------------------------------------- -// Max "size" of the vector -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline I CUtlRBTree::MaxElement() const -{ - return ( I )m_Elements.NumAllocated(); -} - - -//----------------------------------------------------------------------------- -// Gets the children -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline I CUtlRBTree::Parent( I i ) const -{ - return Links(i).m_Parent; -} - -template < class T, class I, typename L, class M > -inline I CUtlRBTree::LeftChild( I i ) const -{ - return Links(i).m_Left; -} - -template < class T, class I, typename L, class M > -inline I CUtlRBTree::RightChild( I i ) const -{ - return Links(i).m_Right; -} - -//----------------------------------------------------------------------------- -// Tests if a node is a left or right child -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsLeftChild( I i ) const -{ - return LeftChild(Parent(i)) == i; -} - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsRightChild( I i ) const -{ - return RightChild(Parent(i)) == i; -} - - -//----------------------------------------------------------------------------- -// Tests if root or leaf -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsRoot( I i ) const -{ - return i == m_Root; -} - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsLeaf( I i ) const -{ - return (LeftChild(i) == InvalidIndex()) && (RightChild(i) == InvalidIndex()); -} - - -//----------------------------------------------------------------------------- -// Checks if a node is valid and in the tree -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsValidIndex( I i ) const -{ - if ( !m_Elements.IsIdxValid( i ) ) - return false; - - if ( m_Elements.IsIdxAfter( i, m_LastAlloc ) ) - return false; // don't read values that have been allocated, but not constructed - - return LeftChild(i) != i; -} - - -//----------------------------------------------------------------------------- -// Invalid index -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline I CUtlRBTree::InvalidIndex() -{ - return ( I )M::InvalidIndex(); -} - - -//----------------------------------------------------------------------------- -// returns the tree depth (not a very fast operation) -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline int CUtlRBTree::Depth() const -{ - return Depth(Root()); -} - -//----------------------------------------------------------------------------- -// Sets the children -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline void CUtlRBTree::SetParent( I i, I parent ) -{ - Links(i).m_Parent = parent; -} - -template < class T, class I, typename L, class M > -inline void CUtlRBTree::SetLeftChild( I i, I child ) -{ - Links(i).m_Left = child; -} - -template < class T, class I, typename L, class M > -inline void CUtlRBTree::SetRightChild( I i, I child ) -{ - Links(i).m_Right = child; -} - -//----------------------------------------------------------------------------- -// Gets at the links -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline typename CUtlRBTree::Links_t const &CUtlRBTree::Links( I i ) const -{ - // Sentinel node, makes life easier - static Links_t s_Sentinel = - { - InvalidIndex(), InvalidIndex(), InvalidIndex(), CUtlRBTree::BLACK - }; - - return (i != InvalidIndex()) ? *(Links_t*)&m_Elements[i] : *(Links_t*)&s_Sentinel; -} - -template < class T, class I, typename L, class M > -inline typename CUtlRBTree::Links_t &CUtlRBTree::Links( I i ) -{ - Assert(i != InvalidIndex()); - return *(Links_t *)&m_Elements[i]; -} - -//----------------------------------------------------------------------------- -// Checks if a link is red or black -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsRed( I i ) const -{ - return (Links(i).m_Tag == RED); -} - -template < class T, class I, typename L, class M > -inline bool CUtlRBTree::IsBlack( I i ) const -{ - return (Links(i).m_Tag == BLACK); -} - - -//----------------------------------------------------------------------------- -// Sets/gets node color -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -inline typename CUtlRBTree::NodeColor_t CUtlRBTree::Color( I i ) const -{ - return (NodeColor_t)Links(i).m_Tag; -} - -template < class T, class I, typename L, class M > -inline void CUtlRBTree::SetColor( I i, typename CUtlRBTree::NodeColor_t c ) -{ - Links(i).m_Tag = (I)c; -} - -//----------------------------------------------------------------------------- -// Allocates/ deallocates nodes -//----------------------------------------------------------------------------- -#pragma warning(push) -#pragma warning(disable:4389) // '==' : signed/unsigned mismatch -template < class T, class I, typename L, class M > -I CUtlRBTree::NewNode() -{ - I elem; - - // Nothing in the free list; add. - if ( m_FirstFree == InvalidIndex() ) - { - Assert( m_Elements.IsValidIterator( m_LastAlloc ) || m_NumElements == 0 ); - typename M::Iterator_t it = m_Elements.IsValidIterator( m_LastAlloc ) ? m_Elements.Next( m_LastAlloc ) : m_Elements.First(); - if ( !m_Elements.IsValidIterator( it ) ) - { - MEM_ALLOC_CREDIT_CLASS(); - m_Elements.Grow(); - - it = m_Elements.IsValidIterator( m_LastAlloc ) ? m_Elements.Next( m_LastAlloc ) : m_Elements.First(); - - Assert( m_Elements.IsValidIterator( it ) ); - if ( !m_Elements.IsValidIterator( it ) ) - { - Error( "CUtlRBTree overflow!\n" ); - } - } - m_LastAlloc = it; - elem = m_Elements.GetIndex( m_LastAlloc ); - Assert( m_Elements.IsValidIterator( m_LastAlloc ) ); - } - else - { - elem = m_FirstFree; - m_FirstFree = Links( m_FirstFree ).m_Right; - } - -#ifdef _DEBUG - // reset links to invalid.... - Links_t &node = Links( elem ); - node.m_Left = node.m_Right = node.m_Parent = InvalidIndex(); -#endif - - Construct( &Element( elem ) ); - ResetDbgInfo(); - - return elem; -} -#pragma warning(pop) - -template < class T, class I, typename L, class M > -void CUtlRBTree::FreeNode( I i ) -{ - Assert( IsValidIndex(i) && (i != InvalidIndex()) ); - Destruct( &Element(i) ); - SetLeftChild( i, i ); // indicates it's in not in the tree - SetRightChild( i, m_FirstFree ); - m_FirstFree = i; -} - - -//----------------------------------------------------------------------------- -// Rotates node i to the left -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::RotateLeft(I elem) -{ - I rightchild = RightChild(elem); - SetRightChild( elem, LeftChild(rightchild) ); - if (LeftChild(rightchild) != InvalidIndex()) - SetParent( LeftChild(rightchild), elem ); - - if (rightchild != InvalidIndex()) - SetParent( rightchild, Parent(elem) ); - if (!IsRoot(elem)) - { - if (IsLeftChild(elem)) - SetLeftChild( Parent(elem), rightchild ); - else - SetRightChild( Parent(elem), rightchild ); - } - else - m_Root = rightchild; - - SetLeftChild( rightchild, elem ); - if (elem != InvalidIndex()) - SetParent( elem, rightchild ); -} - - -//----------------------------------------------------------------------------- -// Rotates node i to the right -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::RotateRight(I elem) -{ - I leftchild = LeftChild(elem); - SetLeftChild( elem, RightChild(leftchild) ); - if (RightChild(leftchild) != InvalidIndex()) - SetParent( RightChild(leftchild), elem ); - - if (leftchild != InvalidIndex()) - SetParent( leftchild, Parent(elem) ); - if (!IsRoot(elem)) - { - if (IsRightChild(elem)) - SetRightChild( Parent(elem), leftchild ); - else - SetLeftChild( Parent(elem), leftchild ); - } - else - m_Root = leftchild; - - SetRightChild( leftchild, elem ); - if (elem != InvalidIndex()) - SetParent( elem, leftchild ); -} - - -//----------------------------------------------------------------------------- -// Rebalances the tree after an insertion -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::InsertRebalance(I elem) -{ - while ( !IsRoot(elem) && (Color(Parent(elem)) == RED) ) - { - I parent = Parent(elem); - I grandparent = Parent(parent); - - /* we have a violation */ - if (IsLeftChild(parent)) - { - I uncle = RightChild(grandparent); - if (IsRed(uncle)) - { - /* uncle is RED */ - SetColor(parent, BLACK); - SetColor(uncle, BLACK); - SetColor(grandparent, RED); - elem = grandparent; - } - else - { - /* uncle is BLACK */ - if (IsRightChild(elem)) - { - /* make x a left child, will change parent and grandparent */ - elem = parent; - RotateLeft(elem); - parent = Parent(elem); - grandparent = Parent(parent); - } - /* recolor and rotate */ - SetColor(parent, BLACK); - SetColor(grandparent, RED); - RotateRight(grandparent); - } - } - else - { - /* mirror image of above code */ - I uncle = LeftChild(grandparent); - if (IsRed(uncle)) - { - /* uncle is RED */ - SetColor(parent, BLACK); - SetColor(uncle, BLACK); - SetColor(grandparent, RED); - elem = grandparent; - } - else - { - /* uncle is BLACK */ - if (IsLeftChild(elem)) - { - /* make x a right child, will change parent and grandparent */ - elem = parent; - RotateRight(parent); - parent = Parent(elem); - grandparent = Parent(parent); - } - /* recolor and rotate */ - SetColor(parent, BLACK); - SetColor(grandparent, RED); - RotateLeft(grandparent); - } - } - } - SetColor( m_Root, BLACK ); -} - - -//----------------------------------------------------------------------------- -// Insert a node into the tree -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -I CUtlRBTree::InsertAt( I parent, bool leftchild ) -{ - I i = NewNode(); - LinkToParent( i, parent, leftchild ); - ++m_NumElements; - - Assert(IsValid()); - - return i; -} - -template < class T, class I, typename L, class M > -void CUtlRBTree::LinkToParent( I i, I parent, bool isLeft ) -{ - Links_t &elem = Links(i); - elem.m_Parent = parent; - elem.m_Left = elem.m_Right = InvalidIndex(); - elem.m_Tag = RED; - - /* insert node in tree */ - if (parent != InvalidIndex()) - { - if (isLeft) - Links(parent).m_Left = i; - else - Links(parent).m_Right = i; - } - else - { - m_Root = i; - } - - InsertRebalance(i); -} - -//----------------------------------------------------------------------------- -// Rebalance the tree after a deletion -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::RemoveRebalance(I elem) -{ - while (elem != m_Root && IsBlack(elem)) - { - I parent = Parent(elem); - - // If elem is the left child of the parent - if (elem == LeftChild(parent)) - { - // Get our sibling - I sibling = RightChild(parent); - if (IsRed(sibling)) - { - SetColor(sibling, BLACK); - SetColor(parent, RED); - RotateLeft(parent); - - // We may have a new parent now - parent = Parent(elem); - sibling = RightChild(parent); - } - if ( (IsBlack(LeftChild(sibling))) && (IsBlack(RightChild(sibling))) ) - { - if (sibling != InvalidIndex()) - SetColor(sibling, RED); - elem = parent; - } - else - { - if (IsBlack(RightChild(sibling))) - { - SetColor(LeftChild(sibling), BLACK); - SetColor(sibling, RED); - RotateRight(sibling); - - // rotation may have changed this - parent = Parent(elem); - sibling = RightChild(parent); - } - SetColor( sibling, Color(parent) ); - SetColor( parent, BLACK ); - SetColor( RightChild(sibling), BLACK ); - RotateLeft( parent ); - elem = m_Root; - } - } - else - { - // Elem is the right child of the parent - I sibling = LeftChild(parent); - if (IsRed(sibling)) - { - SetColor(sibling, BLACK); - SetColor(parent, RED); - RotateRight(parent); - - // We may have a new parent now - parent = Parent(elem); - sibling = LeftChild(parent); - } - if ( (IsBlack(RightChild(sibling))) && (IsBlack(LeftChild(sibling))) ) - { - if (sibling != InvalidIndex()) - SetColor( sibling, RED ); - elem = parent; - } - else - { - if (IsBlack(LeftChild(sibling))) - { - SetColor( RightChild(sibling), BLACK ); - SetColor( sibling, RED ); - RotateLeft( sibling ); - - // rotation may have changed this - parent = Parent(elem); - sibling = LeftChild(parent); - } - SetColor( sibling, Color(parent) ); - SetColor( parent, BLACK ); - SetColor( LeftChild(sibling), BLACK ); - RotateRight( parent ); - elem = m_Root; - } - } - } - SetColor( elem, BLACK ); -} - -template < class T, class I, typename L, class M > -void CUtlRBTree::Unlink( I elem ) -{ - if ( elem != InvalidIndex() ) - { - I x, y; - - if ((LeftChild(elem) == InvalidIndex()) || - (RightChild(elem) == InvalidIndex())) - { - /* y has a NIL node as a child */ - y = elem; - } - else - { - /* find tree successor with a NIL node as a child */ - y = RightChild(elem); - while (LeftChild(y) != InvalidIndex()) - y = LeftChild(y); - } - - /* x is y's only child */ - if (LeftChild(y) != InvalidIndex()) - x = LeftChild(y); - else - x = RightChild(y); - - /* remove y from the parent chain */ - if (x != InvalidIndex()) - SetParent( x, Parent(y) ); - if (!IsRoot(y)) - { - if (IsLeftChild(y)) - SetLeftChild( Parent(y), x ); - else - SetRightChild( Parent(y), x ); - } - else - m_Root = x; - - // need to store this off now, we'll be resetting y's color - NodeColor_t ycolor = Color(y); - if (y != elem) - { - // Standard implementations copy the data around, we cannot here. - // Hook in y to link to the same stuff elem used to. - SetParent( y, Parent(elem) ); - SetRightChild( y, RightChild(elem) ); - SetLeftChild( y, LeftChild(elem) ); - - if (!IsRoot(elem)) - if (IsLeftChild(elem)) - SetLeftChild( Parent(elem), y ); - else - SetRightChild( Parent(elem), y ); - else - m_Root = y; - - if (LeftChild(y) != InvalidIndex()) - SetParent( LeftChild(y), y ); - if (RightChild(y) != InvalidIndex()) - SetParent( RightChild(y), y ); - - SetColor( y, Color(elem) ); - } - - if ((x != InvalidIndex()) && (ycolor == BLACK)) - RemoveRebalance(x); - } -} - -template < class T, class I, typename L, class M > -void CUtlRBTree::Link( I elem ) -{ - if ( elem != InvalidIndex() ) - { - I parent; - bool leftchild; - - FindInsertionPosition( Element( elem ), parent, leftchild ); - - LinkToParent( elem, parent, leftchild ); - - Assert(IsValid()); - } -} - -//----------------------------------------------------------------------------- -// Delete a node from the tree -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::RemoveAt(I elem) -{ - if ( elem != InvalidIndex() ) - { - Unlink( elem ); - - FreeNode(elem); - --m_NumElements; - - Assert(IsValid()); - } -} - - -//----------------------------------------------------------------------------- -// remove a node in the tree -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > bool CUtlRBTree::Remove( T const &search ) -{ - I node = Find( search ); - if (node != InvalidIndex()) - { - RemoveAt(node); - return true; - } - return false; -} - - -//----------------------------------------------------------------------------- -// Removes all nodes from the tree -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::RemoveAll() -{ - // Have to do some convoluted stuff to invoke the destructor on all - // valid elements for the multilist case (since we don't have all elements - // connected to each other in a list). - - if ( m_LastAlloc == m_Elements.InvalidIterator() ) - { - Assert( m_Root == InvalidIndex() ); - Assert( m_FirstFree == InvalidIndex() ); - Assert( m_NumElements == 0 ); - return; - } - - for ( typename M::Iterator_t it = m_Elements.First(); it != m_Elements.InvalidIterator(); it = m_Elements.Next( it ) ) - { - I i = m_Elements.GetIndex( it ); - if ( IsValidIndex( i ) ) // skip elements in the free list - { - Destruct( &Element( i ) ); - SetRightChild( i, m_FirstFree ); - SetLeftChild( i, i ); - m_FirstFree = i; - } - - if ( it == m_LastAlloc ) - break; // don't destruct elements that haven't ever been constucted - } - - // Clear everything else out - m_Root = InvalidIndex(); - m_NumElements = 0; - - Assert( IsValid() ); -} - -//----------------------------------------------------------------------------- -// Removes all nodes from the tree and purges memory -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::Purge() -{ - RemoveAll(); - m_FirstFree = InvalidIndex(); - m_Elements.Purge(); - m_LastAlloc = m_Elements.InvalidIterator(); -} - - -//----------------------------------------------------------------------------- -// iteration -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -I CUtlRBTree::FirstInorder() const -{ - I i = m_Root; - while (LeftChild(i) != InvalidIndex()) - i = LeftChild(i); - return i; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::NextInorder( I i ) const -{ - Assert(IsValidIndex(i)); - - if (RightChild(i) != InvalidIndex()) - { - i = RightChild(i); - while (LeftChild(i) != InvalidIndex()) - i = LeftChild(i); - return i; - } - - I parent = Parent(i); - while (IsRightChild(i)) - { - i = parent; - if (i == InvalidIndex()) break; - parent = Parent(i); - } - return parent; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::PrevInorder( I i ) const -{ - Assert(IsValidIndex(i)); - - if (LeftChild(i) != InvalidIndex()) - { - i = LeftChild(i); - while (RightChild(i) != InvalidIndex()) - i = RightChild(i); - return i; - } - - I parent = Parent(i); - while (IsLeftChild(i)) - { - i = parent; - if (i == InvalidIndex()) break; - parent = Parent(i); - } - return parent; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::LastInorder() const -{ - I i = m_Root; - while (RightChild(i) != InvalidIndex()) - i = RightChild(i); - return i; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::FirstPreorder() const -{ - return m_Root; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::NextPreorder( I i ) const -{ - if (LeftChild(i) != InvalidIndex()) - return LeftChild(i); - - if (RightChild(i) != InvalidIndex()) - return RightChild(i); - - I parent = Parent(i); - while( parent != InvalidIndex()) - { - if (IsLeftChild(i) && (RightChild(parent) != InvalidIndex())) - return RightChild(parent); - i = parent; - parent = Parent(parent); - } - return InvalidIndex(); -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::PrevPreorder( I i ) const -{ - Assert(0); // not implemented yet - return InvalidIndex(); -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::LastPreorder() const -{ - I i = m_Root; - while (1) - { - while (RightChild(i) != InvalidIndex()) - i = RightChild(i); - - if (LeftChild(i) != InvalidIndex()) - i = LeftChild(i); - else - break; - } - return i; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::FirstPostorder() const -{ - I i = m_Root; - while (!IsLeaf(i)) - { - if (LeftChild(i)) - i = LeftChild(i); - else - i = RightChild(i); - } - return i; -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::NextPostorder( I i ) const -{ - I parent = Parent(i); - if (parent == InvalidIndex()) - return InvalidIndex(); - - if (IsRightChild(i)) - return parent; - - if (RightChild(parent) == InvalidIndex()) - return parent; - - i = RightChild(parent); - while (!IsLeaf(i)) - { - if (LeftChild(i)) - i = LeftChild(i); - else - i = RightChild(i); - } - return i; -} - - -template < class T, class I, typename L, class M > -void CUtlRBTree::Reinsert( I elem ) -{ - Unlink( elem ); - Link( elem ); -} - - -//----------------------------------------------------------------------------- -// returns the tree depth (not a very fast operation) -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -int CUtlRBTree::Depth( I node ) const -{ - if (node == InvalidIndex()) - return 0; - - int depthright = Depth( RightChild(node) ); - int depthleft = Depth( LeftChild(node) ); - return max(depthright, depthleft) + 1; -} - - -//#define UTLTREE_PARANOID - -//----------------------------------------------------------------------------- -// Makes sure the tree is valid after every operation -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -bool CUtlRBTree::IsValid() const -{ - if ( !Count() ) - return true; - - if ( m_LastAlloc == m_Elements.InvalidIterator() ) - return false; - - if ( !m_Elements.IsIdxValid( Root() ) ) - return false; - - if ( Parent( Root() ) != InvalidIndex() ) - return false; - -#ifdef UTLTREE_PARANOID - - // First check to see that mNumEntries matches reality. - // count items on the free list - int numFree = 0; - for ( int i = m_FirstFree; i != InvalidIndex(); i = RightChild( i ) ) - { - ++numFree; - if ( !m_Elements.IsIdxValid( i ) ) - return false; - } - - // iterate over all elements, looking for validity - // based on the self pointers - int nElements = 0; - int numFree2 = 0; - for ( M::Iterator_t it = m_Elements.First(); it != m_Elements.InvalidIterator(); it = m_Elements.Next( it ) ) - { - I i = m_Elements.GetIndex( it ); - if ( !IsValidIndex( i ) ) - { - ++numFree2; - } - else - { - ++nElements; - - int right = RightChild( i ); - int left = LeftChild( i ); - if ( ( right == left ) && ( right != InvalidIndex() ) ) - return false; - - if ( right != InvalidIndex() ) - { - if ( !IsValidIndex( right ) ) - return false; - if ( Parent( right ) != i ) - return false; - if ( IsRed( i ) && IsRed( right ) ) - return false; - } - - if ( left != InvalidIndex() ) - { - if ( !IsValidIndex( left ) ) - return false; - if ( Parent( left ) != i ) - return false; - if ( IsRed( i ) && IsRed( left ) ) - return false; - } - } - - if ( it == m_LastAlloc ) - break; - } - if ( numFree2 != numFree ) - return false; - - if ( nElements != m_NumElements ) - return false; - -#endif // UTLTREE_PARANOID - - return true; -} - - -//----------------------------------------------------------------------------- -// Sets the less func -//----------------------------------------------------------------------------- - -template < class T, class I, typename L, class M > -void CUtlRBTree::SetLessFunc( const typename CUtlRBTree::LessFunc_t &func ) -{ - if (!m_LessFunc) - { - m_LessFunc = func; - } - else if ( Count() > 0 ) - { - // need to re-sort the tree here.... - Assert(0); - } -} - - -//----------------------------------------------------------------------------- -// inserts a node into the tree -//----------------------------------------------------------------------------- - -// Inserts a node into the tree, doesn't copy the data in. -template < class T, class I, typename L, class M > -void CUtlRBTree::FindInsertionPosition( T const &insert, I &parent, bool &leftchild ) -{ - Assert( m_LessFunc ); - - /* find where node belongs */ - I current = m_Root; - parent = InvalidIndex(); - leftchild = false; - while (current != InvalidIndex()) - { - parent = current; - if (m_LessFunc( insert, Element(current) )) - { - leftchild = true; current = LeftChild(current); - } - else - { - leftchild = false; current = RightChild(current); - } - } -} - -template < class T, class I, typename L, class M > -I CUtlRBTree::Insert( T const &insert ) -{ - // use copy constructor to copy it in - I parent; - bool leftchild; - FindInsertionPosition( insert, parent, leftchild ); - I newNode = InsertAt( parent, leftchild ); - CopyConstruct( &Element( newNode ), insert ); - return newNode; -} - - -template < class T, class I, typename L, class M > -void CUtlRBTree::Insert( const T *pArray, int nItems ) -{ - while ( nItems-- ) - { - Insert( *pArray++ ); - } -} - - -template < class T, class I, typename L, class M > -I CUtlRBTree::InsertIfNotFound( T const &insert ) -{ - // use copy constructor to copy it in - I parent; - bool leftchild; - - I current = m_Root; - parent = InvalidIndex(); - leftchild = false; - while (current != InvalidIndex()) - { - parent = current; - if (m_LessFunc( insert, Element(current) )) - { - leftchild = true; current = LeftChild(current); - } - else if (m_LessFunc( Element(current), insert )) - { - leftchild = false; current = RightChild(current); - } - else - // Match found, no insertion - return InvalidIndex(); - } - - I newNode = InsertAt( parent, leftchild ); - CopyConstruct( &Element( newNode ), insert ); - return newNode; -} - - -//----------------------------------------------------------------------------- -// finds a node in the tree -//----------------------------------------------------------------------------- -template < class T, class I, typename L, class M > -I CUtlRBTree::Find( T const &search ) const -{ - Assert( m_LessFunc ); - - I current = m_Root; - while (current != InvalidIndex()) - { - if (m_LessFunc( search, Element(current) )) - current = LeftChild(current); - else if (m_LessFunc( Element(current), search )) - current = RightChild(current); - else - break; - } - return current; -} - - -//----------------------------------------------------------------------------- -// swap in place -//----------------------------------------------------------------------------- -template < class T, class I, typename L, class M > -void CUtlRBTree::Swap( CUtlRBTree< T, I, L > &that ) -{ - m_Elements.Swap( that.m_Elements ); - swap( m_LessFunc, that.m_LessFunc ); - swap( m_Root, that.m_Root ); - swap( m_NumElements, that.m_NumElements ); - swap( m_FirstFree, that.m_FirstFree ); - swap( m_pElements, that.m_pElements ); - swap( m_LastAlloc, that.m_LastAlloc ); - Assert( IsValid() ); - Assert( m_Elements.IsValidIterator( m_LastAlloc ) || ( m_NumElements == 0 && m_FirstFree == InvalidIndex() ) ); -} - - -#endif // UTLRBTREE_H diff --git a/Resources/NetHook/tier1/utlsoacontainer.h b/Resources/NetHook/tier1/utlsoacontainer.h deleted file mode 100644 index b056358c..00000000 --- a/Resources/NetHook/tier1/utlsoacontainer.h +++ /dev/null @@ -1,334 +0,0 @@ -//====== Copyright © 1996-2007, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -// A Fixed-allocation class for maintaining a 1d or 2d or 3d array of data in a structure-of-arrays -// (SOA) sse-friendly manner. -// =============================================================================// - -#ifndef UTLSOACONTAINER_H -#define UTLSOACONTAINER_H - -#ifdef _WIN32 -#pragma once -#endif - - -#include "tier0/platform.h" -#include "tier0/dbg.h" -#include "tier0/threadtools.h" -#include "tier1/utlmemory.h" -#include "tier1/utlblockmemory.h" -#include "mathlib/ssemath.h" - - -// strided pointers. gives you a class that acts like a pointer, but the ++ and += operators do the -// right thing -template class CStridedPtr -{ -protected: - T *m_pData; - size_t m_nStride; - -public: - FORCEINLINE CStridedPtr( void *pData, size_t nByteStride ) - { - m_pData = reinterpret_cast( pData ); - m_nStride = nByteStride / sizeof( T ); - } - - FORCEINLINE CStridedPtr( void ) {} - T *operator->(void) const - { - return m_pData; - } - - T & operator*(void) const - { - return *m_pData; - } - - FORCEINLINE operator T *(void) - { - return m_pData; - } - - FORCEINLINE CStridedPtr & operator++(void) - { - m_pData += m_nStride; - return *this; - } - - FORCEINLINE void operator+=( size_t nNumElements ) - { - m_pData += nNumElements * m_nStride; - } - -}; - -template class CStridedConstPtr -{ -protected: - const T *m_pData; - size_t m_nStride; - -public: - FORCEINLINE CStridedConstPtr( void const *pData, size_t nByteStride ) - { - m_pData = reinterpret_cast( pData ); - m_nStride = nByteStride / sizeof( T ); - } - - FORCEINLINE CStridedConstPtr( void ) {} - - const T *operator->(void) const - { - return m_pData; - } - - const T & operator*(void) const - { - return *m_pData; - } - - FORCEINLINE operator const T *(void) const - { - return m_pData; - } - - FORCEINLINE CStridedConstPtr &operator++(void) - { - m_pData += m_nStride; - return *this; - } - FORCEINLINE void operator+=( size_t nNumElements ) - { - m_pData += nNumElements*m_nStride; - } -}; - -// allowed field data types. if you change these values, you need to change the tables in the .cpp file -enum EAttributeDataType -{ - ATTRDATATYPE_FLOAT = 0, // a float attribute - ATTRDATATYPE_4V = 1, // vector data type, stored as class FourVectors - ATTRDATATYPE_INT = 2, // integer. not especially sse-able on - // all architectures. - ATTRDATATYPE_POINTER = 3, // a pointer. - ATTRDATATYPE_NONE = -1, // pad and varargs ender -}; - -#define MAX_SOA_FIELDS 32 - -class CSOAContainer -{ - -protected: - int m_nColumns; // # of rows and columns created with - int m_nRows; - int m_nSlices; - - int m_nPaddedColumns; // # of columns rounded up for sse - int m_nNumQuadsPerRow; // # of groups of 4 elements per row - - uint8 *m_pDataMemory; // the actual data memory - uint8 *m_pAttributePtrs[MAX_SOA_FIELDS]; - - EAttributeDataType m_nDataType[MAX_SOA_FIELDS]; - - size_t m_nStrideInBytes[MAX_SOA_FIELDS]; // stride from one field datum to another - size_t m_nRowStrideInBytes[MAX_SOA_FIELDS]; // stride from one row datum to another per field - size_t m_nSliceStrideInBytes[MAX_SOA_FIELDS]; // stride from one slice datum to another per field - - - - uint32 m_nFieldPresentMask; - - FORCEINLINE void Init( void ) - { - memset( m_nDataType, 0xff, sizeof( m_nDataType ) ); - m_pDataMemory = 0; - m_nColumns = m_nPaddedColumns = m_nRows = m_nSlices = 0; - m_nFieldPresentMask = 0; - } -public: - - - CSOAContainer( void ) // an empoty one with no attributes - { - Init(); - } - - void Purge( void ); // set back to un-initted state, freeing memory - - ~CSOAContainer( void ); - - // easy constructor for 2d using varargs. call like - // #define ATTR_RED 0 - // #define ATTR_GREEN 1 - // #define ATTR_BLUE 2 - // CSOAContainer myimage( 256, 256, ATTR_RED, ATTRDATATYPE_FLOAT, ATTR_GREEN, ATTRDATATYPE_FLOAT, - // ATTR_BLUE, ATTRDATATYPE_FLOAT, -1 ); - - CSOAContainer( int nCols, int nRows, ... ); - - size_t ElementSize( void ) const; // total bytes per element. not super fast. - - // set the data type for an attribute. If you set the data type, but tell it not to allocate, - // the data type will be set but writes will assert, and reads will give you back zeros. - FORCEINLINE void SetAttributeType( int nAttrIdx, EAttributeDataType nDataType, bool bAllocateMemory = true ) - { - Assert( !m_pDataMemory ); // can't change after memory allocated - Assert( nAttrIdx < MAX_SOA_FIELDS ); - m_nDataType[nAttrIdx] = nDataType; - if ( ( m_nDataType[nAttrIdx] != ATTRDATATYPE_NONE ) && bAllocateMemory ) - m_nFieldPresentMask |= ( 1 << nAttrIdx ); - else - m_nFieldPresentMask &= ~( 1 << nAttrIdx ); - } - - FORCEINLINE int NumRows( void ) const - { - return m_nRows; - } - - FORCEINLINE int NumCols( void ) const - { - return m_nColumns; - } - FORCEINLINE int NumSlices( void ) const - { - return m_nSlices; - } - - - FORCEINLINE void AssertDataType( int nAttrIdx, EAttributeDataType nDataType ) const - { - Assert( nAttrIdx >= 0 ); - Assert( nAttrIdx < MAX_SOA_FIELDS ); - Assert( m_nStrideInBytes[nAttrIdx] ); - } - - - // # of groups of 4 elements per row - FORCEINLINE int NumQuadsPerRow( void ) const - { - return m_nNumQuadsPerRow; - } - - FORCEINLINE int Count( void ) const // for 1d data - { - return NumCols(); - } - - FORCEINLINE int NumElements( void ) const - { - return NumCols() * NumRows() * NumSlices(); - } - - - // how much to step to go from the end of one row to the start of the next one. Basically, how - // many bytes to add at the end of a row when iterating over the whole 2d array with ++ - FORCEINLINE size_t RowToRowStep( int nAttrIdx ) const - { - return 0; - } - - FORCEINLINE void *RowPtr( int nAttributeIdx, int nRowNumber, int nSliceNumber = 0 ) const - { - Assert( nRowNumber < m_nRows ); - Assert( nAttributeIdx < MAX_SOA_FIELDS ); - Assert( m_nDataType[nAttributeIdx] != ATTRDATATYPE_NONE ); - Assert( m_nFieldPresentMask & ( 1 << nAttributeIdx ) ); - return m_pAttributePtrs[nAttributeIdx] + - + nRowNumber * m_nRowStrideInBytes[nAttributeIdx] - + nSliceNumber * m_nSliceStrideInBytes[nAttributeIdx]; - } - - FORCEINLINE void const *ConstRowPtr( int nAttributeIdx, int nRowNumber, int nSliceNumber = 0 ) const - { - Assert( nRowNumber < m_nRows ); - Assert( nAttributeIdx < MAX_SOA_FIELDS ); - Assert( m_nDataType[nAttributeIdx] != ATTRDATATYPE_NONE ); - return m_pAttributePtrs[nAttributeIdx] - + nRowNumber * m_nRowStrideInBytes[nAttributeIdx] - + nSliceNumber * m_nSliceStrideInBytes[nAttributeIdx]; - } - - - template FORCEINLINE T *ElementPointer( int nAttributeIdx, - int nX = 0, int nY = 0, int nZ = 0 ) const - { - Assert( nAttributeIdx < MAX_SOA_FIELDS ); - Assert( nX < m_nColumns ); - Assert( nY < m_nRows ); - Assert( nZ < m_nSlices ); - Assert( m_nDataType[nAttributeIdx] != ATTRDATATYPE_NONE ); - Assert( m_nDataType[nAttributeIdx] != ATTRDATATYPE_4V ); - return reinterpret_cast( m_pAttributePtrs[nAttributeIdx] - + nX * sizeof( float ) - + nY * m_nRowStrideInBytes[nAttributeIdx] - + nZ * m_nSliceStrideInBytes[nAttributeIdx] - ); - } - - FORCEINLINE size_t ItemByteStride( int nAttributeIdx ) const - { - Assert( nAttributeIdx < MAX_SOA_FIELDS ); - Assert( m_nDataType[nAttributeIdx] != ATTRDATATYPE_NONE ); - return m_nStrideInBytes[ nAttributeIdx ]; - } - - // copy the attribute data from another soacontainer. must be compatible geometry - void CopyAttrFrom( CSOAContainer const &other, int nAttributeIdx ); - - // copy the attribute data from another attribute. must be compatible data format - void CopyAttrToAttr( int nSrcAttributeIndex, int nDestAttributeIndex); - - // move all the data from one csoacontainer to another, leaving the source empty. - // this is just a pointer copy. - FORCEINLINE void MoveDataFrom( CSOAContainer other ) - { - (*this) = other; - other.Init(); - } - - - - void AllocateData( int nNCols, int nNRows, int nSlices = 1 ); // actually allocate the memory and set the pointers up - - // arithmetic and data filling functions. All SIMD and hopefully fast - - // set all elements of a float attribute to random #s - void RandomizeAttribute( int nAttr, float flMin, float flMax ) const ; - - // fill 2d a rectangle with values interpolated from 4 corner values. - void FillAttrWithInterpolatedValues( int nAttr, float flValue00, float flValue10, float flValue01, float flValue11 ) const; - void FillAttrWithInterpolatedValues( int nAttr, Vector flValue00, Vector flValue10, - Vector const &flValue01, Vector const &flValue11 ) const; - -}; - -class CFltX4AttributeIterator : public CStridedConstPtr -{ - FORCEINLINE CFltX4AttributeIterator( CSOAContainer const *pContainer, int nAttribute, int nRowNumber = 0 ) - : CStridedConstPtr( pContainer->ConstRowPtr( nAttribute, nRowNumber), - pContainer->ItemByteStride( nAttribute ) ) - { - } -}; - -class CFltX4AttributeWriteIterator : public CStridedPtr -{ - FORCEINLINE CFltX4AttributeWriteIterator( CSOAContainer const *pContainer, int nAttribute, int nRowNumber = 0 ) - : CStridedPtr( pContainer->RowPtr( nAttribute, nRowNumber), - pContainer->ItemByteStride( nAttribute ) ) - { - } - -}; - - -#endif diff --git a/Resources/NetHook/tier1/utlstack.h b/Resources/NetHook/tier1/utlstack.h deleted file mode 100644 index 8cacdd84..00000000 --- a/Resources/NetHook/tier1/utlstack.h +++ /dev/null @@ -1,331 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: -// -// $NoKeywords: $ -// -// A stack based on a growable array -//=============================================================================// - -#ifndef UTLSTACK_H -#define UTLSTACK_H - -#include -#include -#include "utlmemory.h" - - -//----------------------------------------------------------------------------- -// The CUtlStack class: -// A growable stack class which doubles in size by default. -// It will always keep all elements consecutive in memory, and may move the -// elements around in memory (via a realloc) when elements are pushed or -// popped. Clients should therefore refer to the elements of the stack -// by index (they should *never* maintain pointers to elements in the stack). -//----------------------------------------------------------------------------- - -template< class T, class M = CUtlMemory< T > > -class CUtlStack -{ -public: - // constructor, destructor - CUtlStack( int growSize = 0, int initSize = 0 ); - ~CUtlStack(); - - void CopyFrom( const CUtlStack &from ); - - // element access - T& operator[]( int i ); - T const& operator[]( int i ) const; - T& Element( int i ); - T const& Element( int i ) const; - - // Gets the base address (can change when adding elements!) - T* Base(); - T const* Base() const; - - // Looks at the stack top - T& Top(); - T const& Top() const; - - // Size - int Count() const; - - // Is element index valid? - bool IsIdxValid( int i ) const; - - // Adds an element, uses default constructor - int Push(); - - // Adds an element, uses copy constructor - int Push( T const& src ); - - // Pops the stack - void Pop(); - void Pop( T& oldTop ); - void PopMultiple( int num ); - - // Makes sure we have enough memory allocated to store a requested # of elements - void EnsureCapacity( int num ); - - // Clears the stack, no deallocation - void Clear(); - - // Memory deallocation - void Purge(); - -private: - // Grows the stack allocation - void GrowStack(); - - // For easier access to the elements through the debugger - void ResetDbgInfo(); - - M m_Memory; - int m_Size; - - // For easier access to the elements through the debugger - T* m_pElements; -}; - - -//----------------------------------------------------------------------------- -// For easier access to the elements through the debugger -//----------------------------------------------------------------------------- - -template< class T, class M > -inline void CUtlStack::ResetDbgInfo() -{ - m_pElements = m_Memory.Base(); -} - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- - -template< class T, class M > -CUtlStack::CUtlStack( int growSize, int initSize ) : - m_Memory(growSize, initSize), m_Size(0) -{ - ResetDbgInfo(); -} - -template< class T, class M > -CUtlStack::~CUtlStack() -{ - Purge(); -} - - -//----------------------------------------------------------------------------- -// copy into -//----------------------------------------------------------------------------- - -template< class T, class M > -void CUtlStack::CopyFrom( const CUtlStack &from ) -{ - Purge(); - EnsureCapacity( from.Count() ); - for ( int i = 0; i < from.Count(); i++ ) - { - Push( from[i] ); - } -} - -//----------------------------------------------------------------------------- -// element access -//----------------------------------------------------------------------------- - -template< class T, class M > -inline T& CUtlStack::operator[]( int i ) -{ - assert( IsIdxValid(i) ); - return m_Memory[i]; -} - -template< class T, class M > -inline T const& CUtlStack::operator[]( int i ) const -{ - assert( IsIdxValid(i) ); - return m_Memory[i]; -} - -template< class T, class M > -inline T& CUtlStack::Element( int i ) -{ - assert( IsIdxValid(i) ); - return m_Memory[i]; -} - -template< class T, class M > -inline T const& CUtlStack::Element( int i ) const -{ - assert( IsIdxValid(i) ); - return m_Memory[i]; -} - - -//----------------------------------------------------------------------------- -// Gets the base address (can change when adding elements!) -//----------------------------------------------------------------------------- - -template< class T, class M > -inline T* CUtlStack::Base() -{ - return m_Memory.Base(); -} - -template< class T, class M > -inline T const* CUtlStack::Base() const -{ - return m_Memory.Base(); -} - -//----------------------------------------------------------------------------- -// Returns the top of the stack -//----------------------------------------------------------------------------- - -template< class T, class M > -inline T& CUtlStack::Top() -{ - assert( m_Size > 0 ); - return Element(m_Size-1); -} - -template< class T, class M > -inline T const& CUtlStack::Top() const -{ - assert( m_Size > 0 ); - return Element(m_Size-1); -} - -//----------------------------------------------------------------------------- -// Size -//----------------------------------------------------------------------------- - -template< class T, class M > -inline int CUtlStack::Count() const -{ - return m_Size; -} - - -//----------------------------------------------------------------------------- -// Is element index valid? -//----------------------------------------------------------------------------- - -template< class T, class M > -inline bool CUtlStack::IsIdxValid( int i ) const -{ - return (i >= 0) && (i < m_Size); -} - -//----------------------------------------------------------------------------- -// Grows the stack -//----------------------------------------------------------------------------- - -template< class T, class M > -void CUtlStack::GrowStack() -{ - if (m_Size >= m_Memory.NumAllocated()) - m_Memory.Grow(); - - ++m_Size; - - ResetDbgInfo(); -} - -//----------------------------------------------------------------------------- -// Makes sure we have enough memory allocated to store a requested # of elements -//----------------------------------------------------------------------------- - -template< class T, class M > -void CUtlStack::EnsureCapacity( int num ) -{ - m_Memory.EnsureCapacity(num); - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Adds an element, uses default constructor -//----------------------------------------------------------------------------- - -template< class T, class M > -int CUtlStack::Push() -{ - GrowStack(); - Construct( &Element(m_Size-1) ); - return m_Size - 1; -} - -//----------------------------------------------------------------------------- -// Adds an element, uses copy constructor -//----------------------------------------------------------------------------- - -template< class T, class M > -int CUtlStack::Push( T const& src ) -{ - GrowStack(); - CopyConstruct( &Element(m_Size-1), src ); - return m_Size - 1; -} - - -//----------------------------------------------------------------------------- -// Pops the stack -//----------------------------------------------------------------------------- - -template< class T, class M > -void CUtlStack::Pop() -{ - assert( m_Size > 0 ); - Destruct( &Element(m_Size-1) ); - --m_Size; -} - -template< class T, class M > -void CUtlStack::Pop( T& oldTop ) -{ - assert( m_Size > 0 ); - oldTop = Top(); - Pop(); -} - -template< class T, class M > -void CUtlStack::PopMultiple( int num ) -{ - assert( m_Size >= num ); - for ( int i = 0; i < num; ++i ) - Destruct( &Element( m_Size - i - 1 ) ); - m_Size -= num; -} - - -//----------------------------------------------------------------------------- -// Element removal -//----------------------------------------------------------------------------- - -template< class T, class M > -void CUtlStack::Clear() -{ - for (int i = m_Size; --i >= 0; ) - Destruct(&Element(i)); - - m_Size = 0; -} - - -//----------------------------------------------------------------------------- -// Memory deallocation -//----------------------------------------------------------------------------- - -template< class T, class M > -void CUtlStack::Purge() -{ - Clear(); - m_Memory.Purge( ); - ResetDbgInfo(); -} - -#endif // UTLSTACK_H \ No newline at end of file diff --git a/Resources/NetHook/tier1/utlstring.cpp b/Resources/NetHook/tier1/utlstring.cpp deleted file mode 100644 index c9bd6e47..00000000 --- a/Resources/NetHook/tier1/utlstring.cpp +++ /dev/null @@ -1,334 +0,0 @@ -//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= -// -// Purpose: -// -//============================================================================= - -#include "tier1/utlstring.h" -#include "tier1/strtools.h" - - -//----------------------------------------------------------------------------- -// Base class, containing simple memory management -//----------------------------------------------------------------------------- -CUtlBinaryBlock::CUtlBinaryBlock( int growSize, int initSize ) : m_Memory( growSize, initSize ) -{ - m_nActualLength = 0; -} - -CUtlBinaryBlock::CUtlBinaryBlock( void* pMemory, int nSizeInBytes, int nInitialLength ) : m_Memory( (unsigned char*)pMemory, nSizeInBytes ) -{ - m_nActualLength = nInitialLength; -} - -CUtlBinaryBlock::CUtlBinaryBlock( const void* pMemory, int nSizeInBytes ) : m_Memory( (const unsigned char*)pMemory, nSizeInBytes ) -{ - m_nActualLength = nSizeInBytes; -} - -CUtlBinaryBlock::CUtlBinaryBlock( const CUtlBinaryBlock& src ) -{ - Set( src.Get(), src.Length() ); -} - -void CUtlBinaryBlock::Get( void *pValue, int nLen ) const -{ - Assert( nLen > 0 ); - if ( m_nActualLength < nLen ) - { - nLen = m_nActualLength; - } - - if ( nLen > 0 ) - { - memcpy( pValue, m_Memory.Base(), nLen ); - } -} - -void CUtlBinaryBlock::SetLength( int nLength ) -{ - Assert( !m_Memory.IsReadOnly() ); - - m_nActualLength = nLength; - if ( nLength > m_Memory.NumAllocated() ) - { - int nOverFlow = nLength - m_Memory.NumAllocated(); - m_Memory.Grow( nOverFlow ); - - // If the reallocation failed, clamp length - if ( nLength > m_Memory.NumAllocated() ) - { - m_nActualLength = m_Memory.NumAllocated(); - } - } - -#ifdef _DEBUG - if ( m_Memory.NumAllocated() > m_nActualLength ) - { - memset( ( ( char * )m_Memory.Base() ) + m_nActualLength, 0xEB, m_Memory.NumAllocated() - m_nActualLength ); - } -#endif -} - -void CUtlBinaryBlock::Set( const void *pValue, int nLen ) -{ - Assert( !m_Memory.IsReadOnly() ); - - if ( !pValue ) - { - nLen = 0; - } - - SetLength( nLen ); - - if ( m_nActualLength ) - { - if ( ( ( const char * )m_Memory.Base() ) >= ( ( const char * )pValue ) + nLen || - ( ( const char * )m_Memory.Base() ) + m_nActualLength <= ( ( const char * )pValue ) ) - { - memcpy( m_Memory.Base(), pValue, m_nActualLength ); - } - else - { - memmove( m_Memory.Base(), pValue, m_nActualLength ); - } - } -} - - -CUtlBinaryBlock &CUtlBinaryBlock::operator=( const CUtlBinaryBlock &src ) -{ - Assert( !m_Memory.IsReadOnly() ); - Set( src.Get(), src.Length() ); - return *this; -} - - -bool CUtlBinaryBlock::operator==( const CUtlBinaryBlock &src ) const -{ - if ( src.Length() != Length() ) - return false; - - return !memcmp( src.Get(), Get(), Length() ); -} - - -//----------------------------------------------------------------------------- -// Simple string class. -//----------------------------------------------------------------------------- -CUtlString::CUtlString() -{ -} - -CUtlString::CUtlString( const char *pString ) -{ - Set( pString ); -} - -CUtlString::CUtlString( const CUtlString& string ) -{ - Set( string.Get() ); -} - -// Attaches the string to external memory. Useful for avoiding a copy -CUtlString::CUtlString( void* pMemory, int nSizeInBytes, int nInitialLength ) : m_Storage( pMemory, nSizeInBytes, nInitialLength ) -{ -} - -CUtlString::CUtlString( const void* pMemory, int nSizeInBytes ) : m_Storage( pMemory, nSizeInBytes ) -{ -} - -void CUtlString::Set( const char *pValue ) -{ - Assert( !m_Storage.IsReadOnly() ); - int nLen = pValue ? Q_strlen(pValue) + 1 : 0; - m_Storage.Set( pValue, nLen ); -} - -// Returns strlen -int CUtlString::Length() const -{ - return m_Storage.Length() ? m_Storage.Length() - 1 : 0; -} - -// Sets the length (used to serialize into the buffer ) -void CUtlString::SetLength( int nLen ) -{ - Assert( !m_Storage.IsReadOnly() ); - - // Add 1 to account for the NULL - m_Storage.SetLength( nLen > 0 ? nLen + 1 : 0 ); -} - -const char *CUtlString::Get( ) const -{ - if ( m_Storage.Length() == 0 ) - { - return ""; - } - - return reinterpret_cast< const char* >( m_Storage.Get() ); -} - -// Converts to c-strings -CUtlString::operator const char*() const -{ - return Get(); -} - -char *CUtlString::Get() -{ - Assert( !m_Storage.IsReadOnly() ); - - if ( m_Storage.Length() == 0 ) - { - // In general, we optimise away small mallocs for empty strings - // but if you ask for the non-const bytes, they must be writable - // so we can't return "" here, like we do for the const version - jd - m_Storage.SetLength( 1 ); - m_Storage[ 0 ] = '\0'; - } - - return reinterpret_cast< char* >( m_Storage.Get() ); -} - -CUtlString &CUtlString::operator=( const CUtlString &src ) -{ - Assert( !m_Storage.IsReadOnly() ); - m_Storage = src.m_Storage; - return *this; -} - -CUtlString &CUtlString::operator=( const char *src ) -{ - Assert( !m_Storage.IsReadOnly() ); - Set( src ); - return *this; -} - -bool CUtlString::operator==( const CUtlString &src ) const -{ - return m_Storage == src.m_Storage; -} - -bool CUtlString::operator==( const char *src ) const -{ - return ( strcmp( Get(), src ) == 0 ); -} - -CUtlString &CUtlString::operator+=( const CUtlString &rhs ) -{ - Assert( !m_Storage.IsReadOnly() ); - - const int lhsLength( Length() ); - const int rhsLength( rhs.Length() ); - const int requestedLength( lhsLength + rhsLength ); - - SetLength( requestedLength ); - const int allocatedLength( Length() ); - const int copyLength( allocatedLength - lhsLength < rhsLength ? allocatedLength - lhsLength : rhsLength ); - memcpy( Get() + lhsLength, rhs.Get(), copyLength ); - m_Storage[ allocatedLength ] = '\0'; - - return *this; -} - -CUtlString &CUtlString::operator+=( const char *rhs ) -{ - Assert( !m_Storage.IsReadOnly() ); - - const int lhsLength( Length() ); - const int rhsLength( Q_strlen( rhs ) ); - const int requestedLength( lhsLength + rhsLength ); - - SetLength( requestedLength ); - const int allocatedLength( Length() ); - const int copyLength( allocatedLength - lhsLength < rhsLength ? allocatedLength - lhsLength : rhsLength ); - memcpy( Get() + lhsLength, rhs, copyLength ); - m_Storage[ allocatedLength ] = '\0'; - - return *this; -} - -CUtlString &CUtlString::operator+=( char c ) -{ - Assert( !m_Storage.IsReadOnly() ); - - int nLength = Length(); - SetLength( nLength + 1 ); - m_Storage[ nLength ] = c; - m_Storage[ nLength+1 ] = '\0'; - return *this; -} - -CUtlString &CUtlString::operator+=( int rhs ) -{ - Assert( !m_Storage.IsReadOnly() ); - Assert( sizeof( rhs ) == 4 ); - - char tmpBuf[ 12 ]; // Sufficient for a signed 32 bit integer [ -2147483648 to +2147483647 ] - Q_snprintf( tmpBuf, sizeof( tmpBuf ), "%d", rhs ); - tmpBuf[ sizeof( tmpBuf ) - 1 ] = '\0'; - - return operator+=( tmpBuf ); -} - -CUtlString &CUtlString::operator+=( double rhs ) -{ - Assert( !m_Storage.IsReadOnly() ); - - char tmpBuf[ 256 ]; // How big can doubles be??? Dunno. - Q_snprintf( tmpBuf, sizeof( tmpBuf ), "%lg", rhs ); - tmpBuf[ sizeof( tmpBuf ) - 1 ] = '\0'; - - return operator+=( tmpBuf ); -} - -int CUtlString::Format( const char *pFormat, ... ) -{ - Assert( !m_Storage.IsReadOnly() ); - - char tmpBuf[ 4096 ]; //< Nice big 4k buffer, as much memory as my first computer had, a Radio Shack Color Computer - - va_list marker; - - va_start( marker, pFormat ); -#ifdef _WIN32 - int len = _vsnprintf( tmpBuf, sizeof( tmpBuf ) - 1, pFormat, marker ); -#elif _LINUX - int len = vsnprintf( tmpBuf, sizeof( tmpBuf ) - 1, pFormat, marker ); -#else -#error "define vsnprintf type." -#endif - va_end( marker ); - - // Len < 0 represents an overflow - if( len < 0 ) - { - len = sizeof( tmpBuf ) - 1; - tmpBuf[sizeof( tmpBuf ) - 1] = 0; - } - - Set( tmpBuf ); - - return len; -} - -//----------------------------------------------------------------------------- -// Strips the trailing slash -//----------------------------------------------------------------------------- -void CUtlString::StripTrailingSlash() -{ - if ( IsEmpty() ) - return; - - int nLastChar = Length() - 1; - char c = m_Storage[ nLastChar ]; - if ( c == '\\' || c == '/' ) - { - m_Storage[ nLastChar ] = 0; - m_Storage.SetLength( m_Storage.Length() - 1 ); - } -} - diff --git a/Resources/NetHook/tier1/utlstring.h b/Resources/NetHook/tier1/utlstring.h deleted file mode 100644 index 6c427401..00000000 --- a/Resources/NetHook/tier1/utlstring.h +++ /dev/null @@ -1,160 +0,0 @@ -//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= -// -// Purpose: -// -//============================================================================= - -#ifndef UTLSTRING_H -#define UTLSTRING_H -#ifdef _WIN32 -#pragma once -#endif - - -#include "tier1/utlmemory.h" - - -//----------------------------------------------------------------------------- -// Base class, containing simple memory management -//----------------------------------------------------------------------------- -class CUtlBinaryBlock -{ -public: - CUtlBinaryBlock( int growSize = 0, int initSize = 0 ); - - // NOTE: nInitialLength indicates how much of the buffer starts full - CUtlBinaryBlock( void* pMemory, int nSizeInBytes, int nInitialLength ); - CUtlBinaryBlock( const void* pMemory, int nSizeInBytes ); - CUtlBinaryBlock( const CUtlBinaryBlock& src ); - - void Get( void *pValue, int nMaxLen ) const; - void Set( const void *pValue, int nLen ); - const void *Get( ) const; - void *Get( ); - - unsigned char& operator[]( int i ); - const unsigned char& operator[]( int i ) const; - - int Length() const; - void SetLength( int nLength ); // Undefined memory will result - bool IsEmpty() const; - - bool IsReadOnly() const; - - CUtlBinaryBlock &operator=( const CUtlBinaryBlock &src ); - - // Test for equality - bool operator==( const CUtlBinaryBlock &src ) const; - -private: - CUtlMemory m_Memory; - int m_nActualLength; -}; - - -//----------------------------------------------------------------------------- -// class inlines -//----------------------------------------------------------------------------- -inline const void *CUtlBinaryBlock::Get( ) const -{ - return m_Memory.Base(); -} - -inline void *CUtlBinaryBlock::Get( ) -{ - return m_Memory.Base(); -} - -inline int CUtlBinaryBlock::Length() const -{ - return m_nActualLength; -} - -inline unsigned char& CUtlBinaryBlock::operator[]( int i ) -{ - return m_Memory[i]; -} - -inline const unsigned char& CUtlBinaryBlock::operator[]( int i ) const -{ - return m_Memory[i]; -} - -inline bool CUtlBinaryBlock::IsReadOnly() const -{ - return m_Memory.IsReadOnly(); -} - -inline bool CUtlBinaryBlock::IsEmpty() const -{ - return Length() == 0; -} - - -//----------------------------------------------------------------------------- -// Simple string class. -// NOTE: This is *not* optimal! Use in tools, but not runtime code -//----------------------------------------------------------------------------- -class CUtlString -{ -public: - CUtlString(); - CUtlString( const char *pString ); - CUtlString( const CUtlString& string ); - - // Attaches the string to external memory. Useful for avoiding a copy - CUtlString( void* pMemory, int nSizeInBytes, int nInitialLength ); - CUtlString( const void* pMemory, int nSizeInBytes ); - - const char *Get( ) const; - void Set( const char *pValue ); - - // Converts to c-strings - operator const char*() const; - - // for compatibility switching items from UtlSymbol - const char *String() const { return Get(); } - - // Returns strlen - int Length() const; - bool IsEmpty() const; - - // Sets the length (used to serialize into the buffer ) - void SetLength( int nLen ); - char *Get(); - - // Strips the trailing slash - void StripTrailingSlash(); - - CUtlString &operator=( const CUtlString &src ); - CUtlString &operator=( const char *src ); - - // Test for equality - bool operator==( const CUtlString &src ) const; - bool operator==( const char *src ) const; - bool operator!=( const CUtlString &src ) const { return !operator==( src ); } - bool operator!=( const char *src ) const { return !operator==( src ); } - - CUtlString &operator+=( const CUtlString &rhs ); - CUtlString &operator+=( const char *rhs ); - CUtlString &operator+=( char c ); - CUtlString &operator+=( int rhs ); - CUtlString &operator+=( double rhs ); - - int Format( const char *pFormat, ... ); - -private: - CUtlBinaryBlock m_Storage; -}; - - -//----------------------------------------------------------------------------- -// Inline methods -//----------------------------------------------------------------------------- -inline bool CUtlString::IsEmpty() const -{ - return Length() == 0; -} - - -#endif // UTLSTRING_H diff --git a/Resources/NetHook/tier1/utlsymbol.cpp b/Resources/NetHook/tier1/utlsymbol.cpp deleted file mode 100644 index 551245ec..00000000 --- a/Resources/NetHook/tier1/utlsymbol.cpp +++ /dev/null @@ -1,395 +0,0 @@ -//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// -// -// Purpose: Defines a symbol table -// -// $Header: $ -// $NoKeywords: $ -//=============================================================================// - -#pragma warning (disable:4514) - -#include "utlsymbol.h" -#include "KeyValues.h" -#include "tier0/threadtools.h" -#include "tier0/memdbgon.h" -#include "stringpool.h" - -// memdbgon must be the last include file in a .cpp file!!! -#include "tier0/memdbgon.h" - -#define INVALID_STRING_INDEX CStringPoolIndex( 0xFFFF, 0xFFFF ) - -#define MIN_STRING_POOL_SIZE 2048 - -//----------------------------------------------------------------------------- -// globals -//----------------------------------------------------------------------------- - -CUtlSymbolTableMT* CUtlSymbol::s_pSymbolTable = 0; -bool CUtlSymbol::s_bAllowStaticSymbolTable = true; - - -//----------------------------------------------------------------------------- -// symbol methods -//----------------------------------------------------------------------------- - -void CUtlSymbol::Initialize() -{ - // If this assert fails, then the module that this call is in has chosen to disallow - // use of the static symbol table. Usually, it's to prevent confusion because it's easy - // to accidentally use the global symbol table when you really want to use a specific one. - Assert( s_bAllowStaticSymbolTable ); - - // necessary to allow us to create global symbols - static bool symbolsInitialized = false; - if (!symbolsInitialized) - { - s_pSymbolTable = new CUtlSymbolTableMT; - symbolsInitialized = true; - } -} - -//----------------------------------------------------------------------------- -// Purpose: Singleton to delete table on exit from module -//----------------------------------------------------------------------------- -class CCleanupUtlSymbolTable -{ -public: - ~CCleanupUtlSymbolTable() - { - delete CUtlSymbol::s_pSymbolTable; - CUtlSymbol::s_pSymbolTable = NULL; - } -}; - -static CCleanupUtlSymbolTable g_CleanupSymbolTable; - -CUtlSymbolTableMT* CUtlSymbol::CurrTable() -{ - Initialize(); - return s_pSymbolTable; -} - - -//----------------------------------------------------------------------------- -// string->symbol->string -//----------------------------------------------------------------------------- - -CUtlSymbol::CUtlSymbol( const char* pStr ) -{ - m_Id = CurrTable()->AddString( pStr ); -} - -const char* CUtlSymbol::String( ) const -{ - return CurrTable()->String(m_Id); -} - -void CUtlSymbol::DisableStaticSymbolTable() -{ - s_bAllowStaticSymbolTable = false; -} - -//----------------------------------------------------------------------------- -// checks if the symbol matches a string -//----------------------------------------------------------------------------- - -bool CUtlSymbol::operator==( const char* pStr ) const -{ - if (m_Id == UTL_INVAL_SYMBOL) - return false; - return strcmp( String(), pStr ) == 0; -} - - - -//----------------------------------------------------------------------------- -// symbol table stuff -//----------------------------------------------------------------------------- - -inline const char* CUtlSymbolTable::StringFromIndex( const CStringPoolIndex &index ) const -{ - Assert( index.m_iPool < m_StringPools.Count() ); - Assert( index.m_iOffset < m_StringPools[index.m_iPool]->m_TotalLen ); - - return &m_StringPools[index.m_iPool]->m_Data[index.m_iOffset]; -} - - -bool CUtlSymbolTable::CLess::operator()( const CStringPoolIndex &i1, const CStringPoolIndex &i2 ) const -{ - // Need to do pointer math because CUtlSymbolTable is used in CUtlVectors, and hence - // can be arbitrarily moved in memory on a realloc. Yes, this is portable. In reality, - // right now at least, because m_LessFunc is the first member of CUtlRBTree, and m_Lookup - // is the first member of CUtlSymbolTabke, this == pTable - CUtlSymbolTable *pTable = (CUtlSymbolTable *)( (byte *)this - offsetof(CUtlSymbolTable::CTree, m_LessFunc) ) - offsetof(CUtlSymbolTable, m_Lookup ); - const char* str1 = (i1 == INVALID_STRING_INDEX) ? pTable->m_pUserSearchString : - pTable->StringFromIndex( i1 ); - const char* str2 = (i2 == INVALID_STRING_INDEX) ? pTable->m_pUserSearchString : - pTable->StringFromIndex( i2 ); - - if ( !pTable->m_bInsensitive ) - return strcmp( str1, str2 ) < 0; - else - return strcmpi( str1, str2 ) < 0; -} - - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- -CUtlSymbolTable::CUtlSymbolTable( int growSize, int initSize, bool caseInsensitive ) : - m_Lookup( growSize, initSize ), m_bInsensitive( caseInsensitive ), m_StringPools( 8 ) -{ -} - -CUtlSymbolTable::~CUtlSymbolTable() -{ - // Release the stringpool string data - RemoveAll(); -} - - -CUtlSymbol CUtlSymbolTable::Find( const char* pString ) const -{ - if (!pString) - return CUtlSymbol(); - - // Store a special context used to help with insertion - m_pUserSearchString = pString; - - // Passing this special invalid symbol makes the comparison function - // use the string passed in the context - UtlSymId_t idx = m_Lookup.Find( INVALID_STRING_INDEX ); - -#ifdef _DEBUG - m_pUserSearchString = NULL; -#endif - - return CUtlSymbol( idx ); -} - - -int CUtlSymbolTable::FindPoolWithSpace( int len ) const -{ - for ( int i=0; i < m_StringPools.Count(); i++ ) - { - StringPool_t *pPool = m_StringPools[i]; - - if ( (pPool->m_TotalLen - pPool->m_SpaceUsed) >= len ) - { - return i; - } - } - - return -1; -} - - -//----------------------------------------------------------------------------- -// Finds and/or creates a symbol based on the string -//----------------------------------------------------------------------------- - -CUtlSymbol CUtlSymbolTable::AddString( const char* pString ) -{ - if (!pString) - return CUtlSymbol( UTL_INVAL_SYMBOL ); - - CUtlSymbol id = Find( pString ); - - if (id.IsValid()) - return id; - - int len = strlen(pString) + 1; - - // Find a pool with space for this string, or allocate a new one. - int iPool = FindPoolWithSpace( len ); - if ( iPool == -1 ) - { - // Add a new pool. - int newPoolSize = max( len, MIN_STRING_POOL_SIZE ); - StringPool_t *pPool = (StringPool_t*)malloc( sizeof( StringPool_t ) + newPoolSize - 1 ); - pPool->m_TotalLen = newPoolSize; - pPool->m_SpaceUsed = 0; - iPool = m_StringPools.AddToTail( pPool ); - } - - // Copy the string in. - StringPool_t *pPool = m_StringPools[iPool]; - Assert( pPool->m_SpaceUsed < 0xFFFF ); // This should never happen, because if we had a string > 64k, it - // would have been given its entire own pool. - - unsigned short iStringOffset = pPool->m_SpaceUsed; - - memcpy( &pPool->m_Data[pPool->m_SpaceUsed], pString, len ); - pPool->m_SpaceUsed += len; - - // didn't find, insert the string into the vector. - CStringPoolIndex index; - index.m_iPool = iPool; - index.m_iOffset = iStringOffset; - - UtlSymId_t idx = m_Lookup.Insert( index ); - return CUtlSymbol( idx ); -} - - -//----------------------------------------------------------------------------- -// Look up the string associated with a particular symbol -//----------------------------------------------------------------------------- - -const char* CUtlSymbolTable::String( CUtlSymbol id ) const -{ - if (!id.IsValid()) - return ""; - - Assert( m_Lookup.IsValidIndex((UtlSymId_t)id) ); - return StringFromIndex( m_Lookup[id] ); -} - - -//----------------------------------------------------------------------------- -// Remove all symbols in the table. -//----------------------------------------------------------------------------- - -void CUtlSymbolTable::RemoveAll() -{ - m_Lookup.Purge(); - - for ( int i=0; i < m_StringPools.Count(); i++ ) - free( m_StringPools[i] ); - - m_StringPools.RemoveAll(); -} - - -//----------------------------------------------------------------------------- -// Purpose: -// Input : *pFileName - -// Output : FileNameHandle_t -//----------------------------------------------------------------------------- -FileNameHandle_t CUtlFilenameSymbolTable::FindOrAddFileName( const char *pFileName ) -{ - if ( !pFileName ) - { - return NULL; - } - - // find first - FileNameHandle_t hFileName = FindFileName( pFileName ); - if ( hFileName ) - { - return hFileName; - } - - // Fix slashes+dotslashes and make lower case first.. - char fn[ MAX_PATH ]; - Q_strncpy( fn, pFileName, sizeof( fn ) ); - Q_RemoveDotSlashes( fn ); -#ifdef _WIN32 - strlwr( fn ); -#endif - - // Split the filename into constituent parts - char basepath[ MAX_PATH ]; - Q_ExtractFilePath( fn, basepath, sizeof( basepath ) ); - char filename[ MAX_PATH ]; - Q_strncpy( filename, fn + Q_strlen( basepath ), sizeof( filename ) ); - - // not found, lock and look again - FileNameHandleInternal_t handle; - m_lock.LockForWrite(); - handle.path = m_StringPool.FindStringHandle( basepath ); - handle.file = m_StringPool.FindStringHandle( filename ); - if ( handle.path && handle.file ) - { - // found - m_lock.UnlockWrite(); - return *( FileNameHandle_t * )( &handle ); - } - - // safely add it - handle.path = m_StringPool.ReferenceStringHandle( basepath ); - handle.file = m_StringPool.ReferenceStringHandle( filename ); - m_lock.UnlockWrite(); - - return *( FileNameHandle_t * )( &handle ); -} - -FileNameHandle_t CUtlFilenameSymbolTable::FindFileName( const char *pFileName ) -{ - if ( !pFileName ) - { - return NULL; - } - - // Fix slashes+dotslashes and make lower case first.. - char fn[ MAX_PATH ]; - Q_strncpy( fn, pFileName, sizeof( fn ) ); - Q_RemoveDotSlashes( fn ); -#ifdef _WIN32 - strlwr( fn ); -#endif - - // Split the filename into constituent parts - char basepath[ MAX_PATH ]; - Q_ExtractFilePath( fn, basepath, sizeof( basepath ) ); - char filename[ MAX_PATH ]; - Q_strncpy( filename, fn + Q_strlen( basepath ), sizeof( filename ) ); - - FileNameHandleInternal_t handle; - - m_lock.LockForRead(); - handle.path = m_StringPool.FindStringHandle(basepath); - handle.file = m_StringPool.FindStringHandle(filename); - m_lock.UnlockRead(); - - if ( handle.path == NULL || handle.file == NULL ) - return NULL; - - return *( FileNameHandle_t * )( &handle ); -} - -//----------------------------------------------------------------------------- -// Purpose: -// Input : handle - -// Output : const char -//----------------------------------------------------------------------------- -bool CUtlFilenameSymbolTable::String( const FileNameHandle_t& handle, char *buf, int buflen ) -{ - buf[ 0 ] = 0; - - FileNameHandleInternal_t *internal = ( FileNameHandleInternal_t * )&handle; - if ( !internal ) - { - return false; - } - - m_lock.LockForRead(); - const char *path = m_StringPool.HandleToString(internal->path); - const char *fn = m_StringPool.HandleToString(internal->file); - m_lock.UnlockRead(); - - if ( !path || !fn ) - { - return false; - } - - Q_strncpy( buf, path, buflen ); - Q_strncat( buf, fn, buflen, COPY_ALL_CHARACTERS ); - - return true; -} - -void CUtlFilenameSymbolTable::RemoveAll() -{ - m_StringPool.FreeAll(); -} - -void CUtlFilenameSymbolTable::SpewStrings() -{ - m_lock.LockForRead(); - m_StringPool.SpewStrings(); - m_lock.UnlockRead(); - -} diff --git a/Resources/NetHook/tier1/utlsymbol.h b/Resources/NetHook/tier1/utlsymbol.h deleted file mode 100644 index 9bfa2e27..00000000 --- a/Resources/NetHook/tier1/utlsymbol.h +++ /dev/null @@ -1,261 +0,0 @@ -//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// -// -// Purpose: Defines a symbol table -// -// $Header: $ -// $NoKeywords: $ -//===========================================================================// - -#ifndef UTLSYMBOL_H -#define UTLSYMBOL_H - -#ifdef _WIN32 -#pragma once -#endif - -#include "tier0/threadtools.h" -#include "tier1/utlrbtree.h" -#include "tier1/utlvector.h" -#include "tier1/stringpool.h" - - -//----------------------------------------------------------------------------- -// forward declarations -//----------------------------------------------------------------------------- -class CUtlSymbolTable; -class CUtlSymbolTableMT; - - -//----------------------------------------------------------------------------- -// This is a symbol, which is a easier way of dealing with strings. -//----------------------------------------------------------------------------- -typedef unsigned short UtlSymId_t; - -#define UTL_INVAL_SYMBOL ((UtlSymId_t)~0) - -class CUtlSymbol -{ -public: - // constructor, destructor - CUtlSymbol() : m_Id(UTL_INVAL_SYMBOL) {} - CUtlSymbol( UtlSymId_t id ) : m_Id(id) {} - CUtlSymbol( const char* pStr ); - CUtlSymbol( CUtlSymbol const& sym ) : m_Id(sym.m_Id) {} - - // operator= - CUtlSymbol& operator=( CUtlSymbol const& src ) { m_Id = src.m_Id; return *this; } - - // operator== - bool operator==( CUtlSymbol const& src ) const { return m_Id == src.m_Id; } - bool operator==( const char* pStr ) const; - - // Is valid? - bool IsValid() const { return m_Id != UTL_INVAL_SYMBOL; } - - // Gets at the symbol - operator UtlSymId_t const() const { return m_Id; } - - // Gets the string associated with the symbol - const char* String( ) const; - - // Modules can choose to disable the static symbol table so to prevent accidental use of them. - static void DisableStaticSymbolTable(); - -protected: - UtlSymId_t m_Id; - - // Initializes the symbol table - static void Initialize(); - - // returns the current symbol table - static CUtlSymbolTableMT* CurrTable(); - - // The standard global symbol table - static CUtlSymbolTableMT* s_pSymbolTable; - - static bool s_bAllowStaticSymbolTable; - - friend class CCleanupUtlSymbolTable; -}; - - -//----------------------------------------------------------------------------- -// CUtlSymbolTable: -// description: -// This class defines a symbol table, which allows us to perform mappings -// of strings to symbols and back. The symbol class itself contains -// a static version of this class for creating global strings, but this -// class can also be instanced to create local symbol tables. -//----------------------------------------------------------------------------- - -class CUtlSymbolTable -{ -public: - // constructor, destructor - CUtlSymbolTable( int growSize = 0, int initSize = 32, bool caseInsensitive = false ); - ~CUtlSymbolTable(); - - // Finds and/or creates a symbol based on the string - CUtlSymbol AddString( const char* pString ); - - // Finds the symbol for pString - CUtlSymbol Find( const char* pString ) const; - - // Look up the string associated with a particular symbol - const char* String( CUtlSymbol id ) const; - - // Remove all symbols in the table. - void RemoveAll(); - - int GetNumStrings( void ) const - { - return m_Lookup.Count(); - } - -protected: - class CStringPoolIndex - { - public: - inline CStringPoolIndex() - { - } - - inline CStringPoolIndex( unsigned short iPool, unsigned short iOffset ) - { - m_iPool = iPool; - m_iOffset = iOffset; - } - - inline bool operator==( const CStringPoolIndex &other ) const - { - return m_iPool == other.m_iPool && m_iOffset == other.m_iOffset; - } - - unsigned short m_iPool; // Index into m_StringPools. - unsigned short m_iOffset; // Index into the string pool. - }; - - class CLess - { - public: - CLess( int ignored = 0 ) {} // permits default initialization to NULL in CUtlRBTree - bool operator!() const { return false; } - bool operator()( const CStringPoolIndex &left, const CStringPoolIndex &right ) const; - }; - - // Stores the symbol lookup - class CTree : public CUtlRBTree - { - public: - CTree( int growSize, int initSize ) : CUtlRBTree( growSize, initSize ) {} - friend class CUtlSymbolTable::CLess; // Needed to allow CLess to calculate pointer to symbol table - }; - - struct StringPool_t - { - int m_TotalLen; // How large is - int m_SpaceUsed; - char m_Data[1]; - }; - - CTree m_Lookup; - bool m_bInsensitive; - mutable const char* m_pUserSearchString; - - // stores the string data - CUtlVector m_StringPools; - -private: - int FindPoolWithSpace( int len ) const; - const char* StringFromIndex( const CStringPoolIndex &index ) const; - - friend class CLess; -}; - -class CUtlSymbolTableMT : private CUtlSymbolTable -{ -public: - CUtlSymbolTableMT( int growSize = 0, int initSize = 32, bool caseInsensitive = false ) - : CUtlSymbolTable( growSize, initSize, caseInsensitive ) - { - } - - CUtlSymbol AddString( const char* pString ) - { - m_lock.LockForWrite(); - CUtlSymbol result = CUtlSymbolTable::AddString( pString ); - m_lock.UnlockWrite(); - return result; - } - - CUtlSymbol Find( const char* pString ) const - { - m_lock.LockForWrite(); - CUtlSymbol result = CUtlSymbolTable::Find( pString ); - m_lock.UnlockWrite(); - return result; - } - - const char* String( CUtlSymbol id ) const - { - m_lock.LockForRead(); - const char *pszResult = CUtlSymbolTable::String( id ); - m_lock.UnlockRead(); - return pszResult; - } - -private: - mutable CThreadSpinRWLock m_lock; -}; - - - -//----------------------------------------------------------------------------- -// CUtlFilenameSymbolTable: -// description: -// This class defines a symbol table of individual filenames, stored more -// efficiently than a standard symbol table. Internally filenames are broken -// up into file and path entries, and a file handle class allows convenient -// access to these. -//----------------------------------------------------------------------------- - -// The handle is a CUtlSymbol for the dirname and the same for the filename, the accessor -// copies them into a static char buffer for return. -typedef void* FileNameHandle_t; - -// Symbol table for more efficiently storing filenames by breaking paths and filenames apart. -// Refactored from BaseFileSystem.h -class CUtlFilenameSymbolTable -{ - // Internal representation of a FileHandle_t - // If we get more than 64K filenames, we'll have to revisit... - // Right now CUtlSymbol is a short, so this packs into an int/void * pointer size... - struct FileNameHandleInternal_t - { - FileNameHandleInternal_t() - { - path = 0; - file = 0; - } - - // Part before the final '/' character - unsigned short path; - // Part after the final '/', including extension - unsigned short file; - }; - -public: - FileNameHandle_t FindOrAddFileName( const char *pFileName ); - FileNameHandle_t FindFileName( const char *pFileName ); - int PathIndex(const FileNameHandle_t &handle) { return (( const FileNameHandleInternal_t * )&handle)->path; } - bool String( const FileNameHandle_t& handle, char *buf, int buflen ); - void RemoveAll(); - void SpewStrings(); - -private: - CCountedStringPool m_StringPool; - mutable CThreadSpinRWLock m_lock; -}; - - -#endif // UTLSYMBOL_H diff --git a/Resources/NetHook/tier1/utlvector.h b/Resources/NetHook/tier1/utlvector.h deleted file mode 100644 index 9dc4c6e9..00000000 --- a/Resources/NetHook/tier1/utlvector.h +++ /dev/null @@ -1,794 +0,0 @@ -//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======// -// -// Purpose: -// -// $NoKeywords: $ -// -// A growable array class that maintains a free list and keeps elements -// in the same location -//=============================================================================// - -#ifndef UTLVECTOR_H -#define UTLVECTOR_H - -#ifdef _WIN32 -#pragma once -#endif - - -#include -#include "tier0/platform.h" -#include "tier0/dbg.h" -#include "tier0/threadtools.h" -#include "tier1/utlmemory.h" -#include "tier1/utlblockmemory.h" -#include "tier1/strtools.h" - -#define FOR_EACH_VEC( vecName, iteratorName ) \ - for ( int iteratorName = 0; iteratorName < vecName.Count(); iteratorName++ ) - -//----------------------------------------------------------------------------- -// The CUtlVector class: -// A growable array class which doubles in size by default. -// It will always keep all elements consecutive in memory, and may move the -// elements around in memory (via a PvRealloc) when elements are inserted or -// removed. Clients should therefore refer to the elements of the vector -// by index (they should *never* maintain pointers to elements in the vector). -//----------------------------------------------------------------------------- -template< class T, class A = CUtlMemory > -class CUtlVector -{ - typedef A CAllocator; -public: - typedef T ElemType_t; - - // constructor, destructor - CUtlVector( int growSize = 0, int initSize = 0 ); - CUtlVector( T* pMemory, int allocationCount, int numElements = 0 ); - ~CUtlVector(); - - // Copy the array. - CUtlVector& operator=( const CUtlVector &other ); - - // element access - T& operator[]( int i ); - const T& operator[]( int i ) const; - T& Element( int i ); - const T& Element( int i ) const; - T& Head(); - const T& Head() const; - T& Tail(); - const T& Tail() const; - - // Gets the base address (can change when adding elements!) - T* Base() { return m_Memory.Base(); } - const T* Base() const { return m_Memory.Base(); } - - // Returns the number of elements in the vector - // SIZE IS DEPRECATED! - int Count() const; - int Size() const; // don't use me! - - // Is element index valid? - bool IsValidIndex( int i ) const; - static int InvalidIndex(); - - // Adds an element, uses default constructor - int AddToHead(); - int AddToTail(); - int InsertBefore( int elem ); - int InsertAfter( int elem ); - - // Adds an element, uses copy constructor - int AddToHead( const T& src ); - int AddToTail( const T& src ); - int InsertBefore( int elem, const T& src ); - int InsertAfter( int elem, const T& src ); - - // Adds multiple elements, uses default constructor - int AddMultipleToHead( int num ); - int AddMultipleToTail( int num, const T *pToCopy=NULL ); - int InsertMultipleBefore( int elem, int num, const T *pToCopy=NULL ); // If pToCopy is set, then it's an array of length 'num' and - int InsertMultipleAfter( int elem, int num ); - - // Calls RemoveAll() then AddMultipleToTail. - void SetSize( int size ); - void SetCount( int count ); - - // Calls SetSize and copies each element. - void CopyArray( const T *pArray, int size ); - - // Fast swap - void Swap( CUtlVector< T, A > &vec ); - - // Add the specified array to the tail. - int AddVectorToTail( CUtlVector const &src ); - - // Finds an element (element needs operator== defined) - int Find( const T& src ) const; - - bool HasElement( const T& src ) const; - - // Makes sure we have enough memory allocated to store a requested # of elements - void EnsureCapacity( int num ); - - // Makes sure we have at least this many elements - void EnsureCount( int num ); - - // Element removal - void FastRemove( int elem ); // doesn't preserve order - void Remove( int elem ); // preserves order, shifts elements - bool FindAndRemove( const T& src ); // removes first occurrence of src, preserves order, shifts elements - void RemoveMultiple( int elem, int num ); // preserves order, shifts elements - void RemoveAll(); // doesn't deallocate memory - - // Memory deallocation - void Purge(); - - // Purges the list and calls delete on each element in it. - void PurgeAndDeleteElements(); - - // Compacts the vector to the number of elements actually in use - void Compact(); - - // Set the size by which it grows when it needs to allocate more memory. - void SetGrowSize( int size ) { m_Memory.SetGrowSize( size ); } - - int NumAllocated() const; // Only use this if you really know what you're doing! - - void Sort( int (__cdecl *pfnCompare)(const T *, const T *) ); - -#ifdef DBGFLAG_VALIDATE - void Validate( CValidator &validator, char *pchName ); // Validate our internal structures -#endif // DBGFLAG_VALIDATE - -protected: - // Can't copy this unless we explicitly do it! - CUtlVector( CUtlVector const& vec ) { Assert(0); } - - // Grows the vector - void GrowVector( int num = 1 ); - - // Shifts elements.... - void ShiftElementsRight( int elem, int num = 1 ); - void ShiftElementsLeft( int elem, int num = 1 ); - - CAllocator m_Memory; - int m_Size; - - // For easier access to the elements through the debugger - // it's in release builds so this can be used in libraries correctly - T *m_pElements; - - inline void ResetDbgInfo() - { - m_pElements = Base(); - } -}; - - -// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice -template < class T > -class CUtlBlockVector : public CUtlVector< T, CUtlBlockMemory< T, int > > -{ -public: - CUtlBlockVector( int growSize = 0, int initSize = 0 ) - : CUtlVector< T, CUtlBlockMemory< T, int > >( growSize, initSize ) {} -}; - -//----------------------------------------------------------------------------- -// The CUtlVectorFixed class: -// A array class with a fixed allocation scheme -//----------------------------------------------------------------------------- - -template< class BASE_UTLVECTOR, class MUTEX_TYPE = CThreadFastMutex > -class CUtlVectorMT : public BASE_UTLVECTOR, public MUTEX_TYPE -{ - typedef BASE_UTLVECTOR BaseClass; -public: - MUTEX_TYPE Mutex_t; - - // constructor, destructor - CUtlVectorMT( int growSize = 0, int initSize = 0 ) : BaseClass( growSize, initSize ) {} - CUtlVectorMT( typename BaseClass::ElemType_t* pMemory, int numElements ) : BaseClass( pMemory, numElements ) {} -}; - - -//----------------------------------------------------------------------------- -// The CUtlVectorFixed class: -// A array class with a fixed allocation scheme -//----------------------------------------------------------------------------- -template< class T, size_t MAX_SIZE > -class CUtlVectorFixed : public CUtlVector< T, CUtlMemoryFixed > -{ - typedef CUtlVector< T, CUtlMemoryFixed > BaseClass; -public: - - // constructor, destructor - CUtlVectorFixed( int growSize = 0, int initSize = 0 ) : BaseClass( growSize, initSize ) {} - CUtlVectorFixed( T* pMemory, int numElements ) : BaseClass( pMemory, numElements ) {} -}; - - -//----------------------------------------------------------------------------- -// The CUtlVectorFixed class: -// A array class with a fixed allocation scheme -//----------------------------------------------------------------------------- -template< class T, size_t MAX_SIZE > -class CUtlVectorFixedGrowable : public CUtlVector< T, CUtlMemoryFixedGrowable > -{ - typedef CUtlVector< T, CUtlMemoryFixedGrowable > BaseClass; - -public: - // constructor, destructor - CUtlVectorFixedGrowable( int growSize = 0 ) : BaseClass( growSize, MAX_SIZE ) {} -}; - - -//----------------------------------------------------------------------------- -// The CCopyableUtlVector class: -// A array class that allows copy construction (so you can nest a CUtlVector inside of another one of our containers) -// WARNING - this class lets you copy construct which can be an expensive operation if you don't carefully control when it happens -// Only use this when nesting a CUtlVector() inside of another one of our container classes (i.e a CUtlMap) -//----------------------------------------------------------------------------- -template< class T > -class CCopyableUtlVector : public CUtlVector< T, CUtlMemory > -{ - typedef CUtlVector< T, CUtlMemory > BaseClass; -public: - CCopyableUtlVector( int growSize = 0, int initSize = 0 ) : BaseClass( growSize, initSize ) {} - CCopyableUtlVector( T* pMemory, int numElements ) : BaseClass( pMemory, numElements ) {} - virtual ~CCopyableUtlVector() {} - CCopyableUtlVector( CCopyableUtlVector const& vec ) { CopyArray( vec.Base(), vec.Count() ); } -}; - -//----------------------------------------------------------------------------- -// constructor, destructor -//----------------------------------------------------------------------------- -template< typename T, class A > -inline CUtlVector::CUtlVector( int growSize, int initSize ) : - m_Memory(growSize, initSize), m_Size(0) -{ - ResetDbgInfo(); -} - -template< typename T, class A > -inline CUtlVector::CUtlVector( T* pMemory, int allocationCount, int numElements ) : - m_Memory(pMemory, allocationCount), m_Size(numElements) -{ - ResetDbgInfo(); -} - -template< typename T, class A > -inline CUtlVector::~CUtlVector() -{ - Purge(); -} - -template< typename T, class A > -inline CUtlVector& CUtlVector::operator=( const CUtlVector &other ) -{ - int nCount = other.Count(); - SetSize( nCount ); - for ( int i = 0; i < nCount; i++ ) - { - (*this)[ i ] = other[ i ]; - } - return *this; -} - - -//----------------------------------------------------------------------------- -// element access -//----------------------------------------------------------------------------- -template< typename T, class A > -inline T& CUtlVector::operator[]( int i ) -{ - return m_Memory[ i ]; -} - -template< typename T, class A > -inline const T& CUtlVector::operator[]( int i ) const -{ - return m_Memory[ i ]; -} - -template< typename T, class A > -inline T& CUtlVector::Element( int i ) -{ - return m_Memory[ i ]; -} - -template< typename T, class A > -inline const T& CUtlVector::Element( int i ) const -{ - return m_Memory[ i ]; -} - -template< typename T, class A > -inline T& CUtlVector::Head() -{ - Assert( m_Size > 0 ); - return m_Memory[ 0 ]; -} - -template< typename T, class A > -inline const T& CUtlVector::Head() const -{ - Assert( m_Size > 0 ); - return m_Memory[ 0 ]; -} - -template< typename T, class A > -inline T& CUtlVector::Tail() -{ - Assert( m_Size > 0 ); - return m_Memory[ m_Size - 1 ]; -} - -template< typename T, class A > -inline const T& CUtlVector::Tail() const -{ - Assert( m_Size > 0 ); - return m_Memory[ m_Size - 1 ]; -} - - -//----------------------------------------------------------------------------- -// Count -//----------------------------------------------------------------------------- -template< typename T, class A > -inline int CUtlVector::Size() const -{ - return m_Size; -} - -template< typename T, class A > -inline int CUtlVector::Count() const -{ - return m_Size; -} - - -//----------------------------------------------------------------------------- -// Is element index valid? -//----------------------------------------------------------------------------- -template< typename T, class A > -inline bool CUtlVector::IsValidIndex( int i ) const -{ - return (i >= 0) && (i < m_Size); -} - - -//----------------------------------------------------------------------------- -// Returns in invalid index -//----------------------------------------------------------------------------- -template< typename T, class A > -inline int CUtlVector::InvalidIndex() -{ - return -1; -} - - -//----------------------------------------------------------------------------- -// Grows the vector -//----------------------------------------------------------------------------- -template< typename T, class A > -void CUtlVector::GrowVector( int num ) -{ - if (m_Size + num > m_Memory.NumAllocated()) - { - MEM_ALLOC_CREDIT_CLASS(); - m_Memory.Grow( m_Size + num - m_Memory.NumAllocated() ); - } - - m_Size += num; - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Sorts the vector -//----------------------------------------------------------------------------- -template< typename T, class A > -void CUtlVector::Sort( int (__cdecl *pfnCompare)(const T *, const T *) ) -{ - typedef int (__cdecl *QSortCompareFunc_t)(const void *, const void *); - if ( Count() <= 1 ) - return; - - if ( Base() ) - { - qsort( Base(), Count(), sizeof(T), (QSortCompareFunc_t)(pfnCompare) ); - } - else - { - Assert( 0 ); - // this path is untested - // if you want to sort vectors that use a non-sequential memory allocator, - // you'll probably want to patch in a quicksort algorithm here - // I just threw in this bubble sort to have something just in case... - - for ( int i = m_Size - 1; i >= 0; --i ) - { - for ( int j = 1; j <= i; ++j ) - { - if ( pfnCompare( &Element( j - 1 ), &Element( j ) ) < 0 ) - { - swap( Element( j - 1 ), Element( j ) ); - } - } - } - } -} - -//----------------------------------------------------------------------------- -// Makes sure we have enough memory allocated to store a requested # of elements -//----------------------------------------------------------------------------- -template< typename T, class A > -void CUtlVector::EnsureCapacity( int num ) -{ - MEM_ALLOC_CREDIT_CLASS(); - m_Memory.EnsureCapacity(num); - ResetDbgInfo(); -} - - -//----------------------------------------------------------------------------- -// Makes sure we have at least this many elements -//----------------------------------------------------------------------------- -template< typename T, class A > -void CUtlVector::EnsureCount( int num ) -{ - if (Count() < num) - AddMultipleToTail( num - Count() ); -} - - -//----------------------------------------------------------------------------- -// Shifts elements -//----------------------------------------------------------------------------- -template< typename T, class A > -void CUtlVector::ShiftElementsRight( int elem, int num ) -{ - Assert( IsValidIndex(elem) || ( m_Size == 0 ) || ( num == 0 )); - int numToMove = m_Size - elem - num; - if ((numToMove > 0) && (num > 0)) - Q_memmove( &Element(elem+num), &Element(elem), numToMove * sizeof(T) ); -} - -template< typename T, class A > -void CUtlVector::ShiftElementsLeft( int elem, int num ) -{ - Assert( IsValidIndex(elem) || ( m_Size == 0 ) || ( num == 0 )); - int numToMove = m_Size - elem - num; - if ((numToMove > 0) && (num > 0)) - { - Q_memmove( &Element(elem), &Element(elem+num), numToMove * sizeof(T) ); - -#ifdef _DEBUG - Q_memset( &Element(m_Size-num), 0xDD, num * sizeof(T) ); -#endif - } -} - - -//----------------------------------------------------------------------------- -// Adds an element, uses default constructor -//----------------------------------------------------------------------------- -template< typename T, class A > -inline int CUtlVector::AddToHead() -{ - return InsertBefore(0); -} - -template< typename T, class A > -inline int CUtlVector::AddToTail() -{ - return InsertBefore( m_Size ); -} - -template< typename T, class A > -inline int CUtlVector::InsertAfter( int elem ) -{ - return InsertBefore( elem + 1 ); -} - -template< typename T, class A > -int CUtlVector::InsertBefore( int elem ) -{ - // Can insert at the end - Assert( (elem == Count()) || IsValidIndex(elem) ); - - GrowVector(); - ShiftElementsRight(elem); - Construct( &Element(elem) ); - return elem; -} - - -//----------------------------------------------------------------------------- -// Adds an element, uses copy constructor -//----------------------------------------------------------------------------- -template< typename T, class A > -inline int CUtlVector::AddToHead( const T& src ) -{ - // Can't insert something that's in the list... reallocation may hose us - Assert( (Base() == NULL) || (&src < Base()) || (&src >= (Base() + Count()) ) ); - return InsertBefore( 0, src ); -} - -template< typename T, class A > -inline int CUtlVector::AddToTail( const T& src ) -{ - // Can't insert something that's in the list... reallocation may hose us - Assert( (Base() == NULL) || (&src < Base()) || (&src >= (Base() + Count()) ) ); - return InsertBefore( m_Size, src ); -} - -template< typename T, class A > -inline int CUtlVector::InsertAfter( int elem, const T& src ) -{ - // Can't insert something that's in the list... reallocation may hose us - Assert( (Base() == NULL) || (&src < Base()) || (&src >= (Base() + Count()) ) ); - return InsertBefore( elem + 1, src ); -} - -template< typename T, class A > -int CUtlVector::InsertBefore( int elem, const T& src ) -{ - // Can't insert something that's in the list... reallocation may hose us - Assert( (Base() == NULL) || (&src < Base()) || (&src >= (Base() + Count()) ) ); - - // Can insert at the end - Assert( (elem == Count()) || IsValidIndex(elem) ); - - GrowVector(); - ShiftElementsRight(elem); - CopyConstruct( &Element(elem), src ); - return elem; -} - - -//----------------------------------------------------------------------------- -// Adds multiple elements, uses default constructor -//----------------------------------------------------------------------------- -template< typename T, class A > -inline int CUtlVector::AddMultipleToHead( int num ) -{ - return InsertMultipleBefore( 0, num ); -} - -template< typename T, class A > -inline int CUtlVector::AddMultipleToTail( int num, const T *pToCopy ) -{ - // Can't insert something that's in the list... reallocation may hose us - Assert( (Base() == NULL) || !pToCopy || (pToCopy + num < Base()) || (pToCopy >= (Base() + Count()) ) ); - - return InsertMultipleBefore( m_Size, num, pToCopy ); -} - -template< typename T, class A > -int CUtlVector::InsertMultipleAfter( int elem, int num ) -{ - return InsertMultipleBefore( elem + 1, num ); -} - - -template< typename T, class A > -void CUtlVector::SetCount( int count ) -{ - RemoveAll(); - AddMultipleToTail( count ); -} - -template< typename T, class A > -inline void CUtlVector::SetSize( int size ) -{ - SetCount( size ); -} - -template< typename T, class A > -void CUtlVector::CopyArray( const T *pArray, int size ) -{ - // Can't insert something that's in the list... reallocation may hose us - Assert( (Base() == NULL) || !pArray || (Base() >= (pArray + size)) || (pArray >= (Base() + Count()) ) ); - - SetSize( size ); - for( int i=0; i < size; i++ ) - { - (*this)[i] = pArray[i]; - } -} - -template< typename T, class A > -void CUtlVector::Swap( CUtlVector< T, A > &vec ) -{ - m_Memory.Swap( vec.m_Memory ); - swap( m_Size, vec.m_Size ); - swap( m_pElements, vec.m_pElements ); -} - -template< typename T, class A > -int CUtlVector::AddVectorToTail( CUtlVector const &src ) -{ - Assert( &src != this ); - - int base = Count(); - - // Make space. - AddMultipleToTail( src.Count() ); - - // Copy the elements. - for ( int i=0; i < src.Count(); i++ ) - { - (*this)[base + i] = src[i]; - } - - return base; -} - -template< typename T, class A > -inline int CUtlVector::InsertMultipleBefore( int elem, int num, const T *pToInsert ) -{ - if( num == 0 ) - return elem; - - // Can insert at the end - Assert( (elem == Count()) || IsValidIndex(elem) ); - - GrowVector(num); - ShiftElementsRight(elem, num); - - // Invoke default constructors - for (int i = 0; i < num; ++i) - Construct( &Element(elem+i) ); - - // Copy stuff in? - if ( pToInsert ) - { - for ( int i=0; i < num; i++ ) - { - Element( elem+i ) = pToInsert[i]; - } - } - - return elem; -} - - -//----------------------------------------------------------------------------- -// Finds an element (element needs operator== defined) -//----------------------------------------------------------------------------- -template< typename T, class A > -int CUtlVector::Find( const T& src ) const -{ - for ( int i = 0; i < Count(); ++i ) - { - if (Element(i) == src) - return i; - } - return -1; -} - -template< typename T, class A > -bool CUtlVector::HasElement( const T& src ) const -{ - return ( Find(src) >= 0 ); -} - - -//----------------------------------------------------------------------------- -// Element removal -//----------------------------------------------------------------------------- -template< typename T, class A > -void CUtlVector::FastRemove( int elem ) -{ - Assert( IsValidIndex(elem) ); - - Destruct( &Element(elem) ); - if (m_Size > 0) - { - memcpy( &Element(elem), &Element(m_Size-1), sizeof(T) ); - --m_Size; - } -} - -template< typename T, class A > -void CUtlVector::Remove( int elem ) -{ - Destruct( &Element(elem) ); - ShiftElementsLeft(elem); - --m_Size; -} - -template< typename T, class A > -bool CUtlVector::FindAndRemove( const T& src ) -{ - int elem = Find( src ); - if ( elem != -1 ) - { - Remove( elem ); - return true; - } - return false; -} - -template< typename T, class A > -void CUtlVector::RemoveMultiple( int elem, int num ) -{ - Assert( elem >= 0 ); - Assert( elem + num <= Count() ); - - for (int i = elem + num; --i >= elem; ) - Destruct(&Element(i)); - - ShiftElementsLeft(elem, num); - m_Size -= num; -} - -template< typename T, class A > -void CUtlVector::RemoveAll() -{ - for (int i = m_Size; --i >= 0; ) - { - Destruct(&Element(i)); - } - - m_Size = 0; -} - - -//----------------------------------------------------------------------------- -// Memory deallocation -//----------------------------------------------------------------------------- - -template< typename T, class A > -inline void CUtlVector::Purge() -{ - RemoveAll(); - m_Memory.Purge(); - ResetDbgInfo(); -} - - -template< typename T, class A > -inline void CUtlVector::PurgeAndDeleteElements() -{ - for( int i=0; i < m_Size; i++ ) - { - delete Element(i); - } - Purge(); -} - -template< typename T, class A > -inline void CUtlVector::Compact() -{ - m_Memory.Purge(m_Size); -} - -template< typename T, class A > -inline int CUtlVector::NumAllocated() const -{ - return m_Memory.NumAllocated(); -} - - -//----------------------------------------------------------------------------- -// Data and memory validation -//----------------------------------------------------------------------------- -#ifdef DBGFLAG_VALIDATE -template< typename T, class A > -void CUtlVector::Validate( CValidator &validator, char *pchName ) -{ - validator.Push( typeid(*this).name(), this, pchName ); - - m_Memory.Validate( validator, "m_Memory" ); - - validator.Pop(); -} -#endif // DBGFLAG_VALIDATE - - -#endif // CCVECTOR_H diff --git a/Resources/NetHook/utils.cpp b/Resources/NetHook/utils.cpp deleted file mode 100644 index 3690d874..00000000 --- a/Resources/NetHook/utils.cpp +++ /dev/null @@ -1,6527 +0,0 @@ - - -#include "utils.h" -#include "crypto.h" - -#include -#include -#include - - -const char *k_szEUDPPktTypes[] = -{ - "Invalid EUDPPktType", - - "k_EUDPPktTypeChallengeReq", - "k_EUDPPktTypeChallenge", - "k_EUDPPktTypeConnect", - "k_EUDPPktTypeAccept", - "k_EUDPPktTypeDisconnect", - "k_EUDPPktTypeData", - "k_EUDPPktTypeDatagram", -}; - -const char *PchStringFromUDPPktHdr( const UDPPktHdr_t *pHdr ) -{ - static char szBuff[ 1024 * 8 ]; - memset( szBuff, 0, sizeof( szBuff ) ); - - sprintf_s( szBuff, sizeof( szBuff ), - - "UDPPktHdr\r\n" - " m_cbPkt = %u bytes\r\n" - " m_EUDPPktType = %s (%u)\r\n" - " m_nFlags = %s (%u)\r\n" - " m_nSrcConnectionID = %u\r\n" - " m_nDstConnectionID = %u\r\n" - " m_nSeqThis = %u\r\n" - " m_nSeqAcked = %u\r\n" - " m_nPktsInMsg = %u\r\n" - " m_nMsgStartSeq = %u\r\n" - " m_cbMsgData = %u\r\n", - - pHdr->m_cbPkt, - PchNameFromEUDPPktType( (EUDPPktType)pHdr->m_EUDPPktType ), pHdr->m_EUDPPktType, - PchNameFromNetFlags( pHdr->m_nFlags ), pHdr->m_nFlags, - pHdr->m_nSrcConnectionID, - pHdr->m_nDstConnectionID, - pHdr->m_nSeqThis, - pHdr->m_nSeqAcked, - pHdr->m_nPktsInMsg, - pHdr->m_nMsgStartSeq, - pHdr->m_cbMsgData - ); - - return szBuff; - -} - -const char *PchStringFromMsgHdr( const MsgHdr_t *pMsgHdr ) -{ - static char szBuff[ 1024 * 8 ]; - memset( szBuff, 0, sizeof( szBuff ) ); - - sprintf_s( szBuff, sizeof( szBuff ), - - " MsgHdr_t\r\n" - " m_EMsg = %s (%u)\r\n" - " m_JobIDTarget = %llu\r\n" - " m_JobIDSource = %llu\r\n", - - g_Crypto->GetMessage( (EMsg)pMsgHdr->m_EMsg ), pMsgHdr->m_EMsg, - pMsgHdr->m_JobIDTarget, - pMsgHdr->m_JobIDSource - - ); - - return szBuff; -} - -const char *PchStringFromExtendedClientMsgHdr( const ExtendedClientMsgHdr_t *pMsgHdr ) -{ - static char szBuff[ 1024 * 8 ]; - memset( szBuff, 0, sizeof( szBuff ) ); - - const CSteamID *steamId = &pMsgHdr->m_ulSteamID; - - sprintf_s( szBuff, sizeof( szBuff ), - - " ExtendedClientMsgHdr_t\r\n" - " m_EMsg = %s (%u)\r\n" - " m_nCubHdr = %u\r\n" - " m_nHdrVersion = %u\r\n" - " m_JobIDTarget = %llu\r\n" - " m_JobIDSource = %llu\r\n" - " m_nHdrCanary = %u\r\n" - " m_ulSteamID = %s %s (%llu) (id = %d, instance = %d, type = %s (%d), universe = %s (%d))\r\n" - " m_nSessionID = %u\r\n", - - g_Crypto->GetMessage( (EMsg)pMsgHdr->m_EMsg ), pMsgHdr->m_EMsg, - pMsgHdr->m_nCubHdr, - pMsgHdr->m_nHdrVersion, - pMsgHdr->m_JobIDTarget, - pMsgHdr->m_JobIDSource, - pMsgHdr->m_nHdrCanary, - steamId->Render(), steamId->SteamRender(), steamId->ConvertToUint64(), - steamId->GetAccountID(), steamId->GetUnAccountInstance(), PchNameFromEAccountType( steamId->GetEAccountType() ), steamId->GetEAccountType(), - PchNameFromEUniverse( steamId->GetEUniverse() ), steamId->GetEUniverse(), - pMsgHdr->m_nSessionID - - ); - - return szBuff; -} - -char *szData = NULL; -const char *PchStringFromData( const uint8 *pData, uint32 cubData ) -{ - if ( cubData == 0 ) - return ""; - - uint32 memSize = cubData * 4; - - szData = (char *)realloc( szData, memSize ); - memset( szData, 0, memSize ); - - for ( uint32 x = 0; x < cubData; ++x ) - { - sprintf_s( szData, memSize, "%s%02X ", szData, (uint8 )pData[ x ] ); - - if ( ( x + 1 ) % 12 == 0 ) - sprintf_s( szData, memSize, "%s\r\n ", szData ); - } - - return szData; -} - -const char *PchNameFromEUDPPktType( EUDPPktType eUdpPktType ) -{ - if ( eUdpPktType <= 0 || eUdpPktType >= k_EUDPPktTypeMax ) - return k_szEUDPPktTypes[ 0 ]; - - return k_szEUDPPktTypes[ (int)eUdpPktType ]; -} - -const char *PchNameFromNetFlags( uint32 netFlags ) -{ - static char szBuff[ 1024 ]; - memset( szBuff, 0, sizeof( szBuff ) ); - - std::string str = ""; - - if ( netFlags & k_uNetFlagNoIOCP ) - str += "k_uNetFlagNoIOCP "; - - if ( netFlags & k_uNetFlagFindAvailPort ) - str += "k_uNetFlagFindAvailPort "; - - if ( netFlags & k_uNetFlagUseAuthentication ) - str += "k_uNetFlagUseAuthentication "; - - if ( netFlags & k_uNetFlagUseEncryption ) - str += "k_uNetFlagUseEncryption "; - - if ( netFlags & k_uNetFlagRawStream ) - str += "k_uNetFlagRawStream "; - - if ( netFlags & k_uNetFlagRawStreamSend ) - str += "k_uNetFlagRawStreamSend "; - - if ( netFlags & k_uNetFlagUnboundSocket ) - str += "k_uNetFlagUnboundSocket "; - - if ( netFlags & k_uNetFlagRawIORecv ) - str += "k_uNetFlagRawIORecv "; - - const char *cStr = str.c_str(); - strcpy_s( szBuff, sizeof( szBuff ), cStr ); - - return szBuff; -} - -const char *k_szUniverse[] = -{ - "k_EUniverseInvalid", - - "k_EUniversePublic", - "k_EUniverseBeta", - "k_EUniverseInternal", - "k_EUniverseDev", - "k_EUniverseRC", - -}; - -const char *PchNameFromEUniverse( EUniverse eUniverse ) -{ - static char szBuff[ 1024 ]; - memset( szBuff, 0, sizeof( szBuff ) ); - - if ( eUniverse <= k_EUniverseInvalid || eUniverse >= k_EUniverseMax ) - return k_szUniverse[ 0 ]; - - return k_szUniverse[ (int)eUniverse ]; -} - -// fuck me. -const char *k_szEMsg[] = -{ - "k_EMsgInvalid", - "k_EMsgMulti", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgGenericReply", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgDestJobFailed", - "", - "k_EMsgAlert", - "", - "", - "", - "", - "k_EMsgSCIDRequest", - "k_EMsgSCIDResponse", - "", - "k_EMsgJobHeartbeat", - "", - "k_EMsgStats", - "k_EMsgSubscribe", - "k_EMRouteMessage", - "k_EMsgRemoteSysID", - "k_EMsgAMCreateAccountResponse", - "k_EMsgWGRequest", - "k_EMsgWGResponse", - "k_EMsgKeepAlive", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgAssignSysID", - "k_EMsgExit", - "k_EMsgDirRequest", - "k_EMsgDirResponse", - "k_EMsgZipRequest", - "k_EMsgZipResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgUpdateRecordResponse", - "", - "", - "", - "", - "", - "k_EMsgUpdateCreditCardRequest", - "", - "", - "", - "k_EMsgUpdateUserBanResponse", - "k_EMsgPrepareToExit", - "k_EMsgContentDescriptionUpdate", - "k_EMsgTestResetServer", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgHeartbeat", - "k_EMsgShellFailed", - "", - "", - "", - "", - "", - "k_EMsgExitShells", - "k_EMsgExitShell", - "k_EMsgGracefulExitShell", - "", - "", - "", - "", - "k_EMsgNotifyWatchdog", - "", - "k_EMsgLicenseProcessingComplete", - "k_EMsgSetTestFlag", - "k_EMsgQueuedEmailsComplete", - "k_EMsgGMReportPHPError", - "k_EMsgGMDRMSync", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseAIS", - "k_EMsgAISRefreshContentDescription", - "k_EMsgAISRequestContentDescription", - "k_EMsgAISUpdateAppInfo", - "k_EMsgAISUpdatePackageInfo", - "k_EMsgAISGetPackageChangeNumber", - "k_EMsgAISGetPackageChangeNumberResponse", - "k_EMsgAISAppInfoTableChanged", - "k_EMsgAISUpdatePackageInfoResponse", - "k_EMsgAISCreateMarketingMessage", - "k_EMsgAISCreateMarketingMessageResponse", - "k_EMsgAISGetMarketingMessage", - "k_EMsgAISGetMarketingMessageResponse", - "k_EMsgAISUpdateMarketingMessage", - "k_EMsgAISUpdateMarketingMessageResponse", - "k_EMsgAISRequestMarketingMessageUpdate", - "k_EMsgAISDeleteMarketingMessage", - "", - "", - "k_EMsgAISGetMarketingTreatments", - "k_EMsgAISGetMarketingTreatmentsResponse", - "k_EMsgAISRequestMarketingTreatmentUpdate", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseAM", - "", - "", - "", - "k_EMsgAMUpdateUserBanRequest", - "k_EMsgAMAddLicense", - "", - "k_EMsgAMBeginProcessingLicenses", - "k_EMsgAMSendSystemIMToUser", - "k_EMsgAMExtendLicense", - "k_EMsgAMAddMinutesToLicense", - "k_EMsgAMCancelLicense", - "k_EMsgAMInitPurchase", - "k_EMsgAMPurchaseResponse", - "k_EMsgAMGetFinalPrice", - "k_EMsgAMGetFinalPriceResponse", - "k_EMsgAMGetLegacyGameKey", - "k_EMsgAMGetLegacyGameKeyResponse", - "k_EMsgAMFindHungTransactions", - "k_EMsgAMSetAccountTrustedRequest", - "", - "k_EMsgAMCompletePurchase", - "k_EMsgAMCancelPurchase", - "k_EMsgAMNewChallenge", - "", - "", - "k_EMsgAMFixPendingPurchase", - "k_EMsgAMIsUserBanned", - "k_EMsgAMRegisterKey", - "k_EMsgAMLoadActivationCodes", - "k_EMsgAMLoadActivationCodesResponse", - "k_EMsgAMLookupKeyResponse", - "k_EMsgAMLookupKey", - "k_EMsgAMChatCleanup", - "k_EMsgAMClanCleanup", - "k_EMsgAMFixPendingRefund", - "k_EMsgAMReverseChargeback", - "k_EMsgAMReverseChargebackResponse", - "k_EMsgAMClanCleanupList", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgAllowUserToPlayQuery", - "k_EMsgAllowUserToPlayResponse", - "k_EMsgAMVerfiyUser", - "k_EMsgAMClientNotPlaying", - "k_EMsgAMClientRequestFriendship", - "k_EMsgAMRelayPublishStatus", - "k_EMsgAMResetCommunityContent", - "k_EMsgCAMPrimePersonaStateCache", - "k_EMsgAMAllowUserContentQuery", - "k_EMsgAMAllowUserContentResponse", - "k_EMsgAMInitPurchaseResponse", - "k_EMsgAMRevokePurchaseResponse", - "k_EMsgAMLockProfile", - "k_EMsgAMRefreshGuestPasses", - "k_EMsgAMInviteUserToClan", - "k_EMsgAMAcknowledgeClanInvite", - "k_EMsgAMGrantGuestPasses", - "k_EMsgAMClanDataUpdated", - "k_EMsgAMReloadAccount", - "k_EMsgAMClientChatMsgRelay", - "k_EMsgAMChatMulti", - "k_EMsgAMClientChatInviteRelay", - "k_EMsgAMChatInvite", - "k_EMsgAMClientJoinChatRelay", - "k_EMsgAMClientChatMemberInfoRelay", - "k_EMsgAMPublishChatMemberInfo", - "k_EMsgAMClientAcceptFriendInvite", - "k_EMsgAMChatEnter", - "k_EMsgAMClientPublishRemovalFromSource", - "k_EMsgAMChatActionResult", - "k_EMsgAMFindAccounts", - "k_EMsgAMFindAccountsResponse", - "", - "", - "k_EMsgAMSetAccountFlags", - "", - "k_EMsgAMCreateClan", - "k_EMsgAMCreateClanResponse", - "k_EMsgAMGetClanDetails", - "k_EMsgAMGetClanDetailsResponse", - "k_EMsgAMSetPersonaName", - "k_EMsgAMSetAvatar", - "k_EMsgAMAuthenticateUser", - "k_EMsgAMAuthenticateUserResponse", - "k_EMsgAMGetAccountFriendsCount", - "k_EMsgAMGetAccountFriendsCountResponse", - "k_EMsgAMP2PIntroducerMessage", - "k_EMsgClientChatAction", - "k_EMsgAMClientChatActionRelay", - "", - "k_EMsgReqChallenge", - "k_EMsgVACResponse", - "k_EMsgReqChallengeTest", - "k_EMsgVSInitDB", - "k_EMsgVSMarkCheat", - "k_EMsgVSAddCheat", - "k_EMsgVSPurgeCodeModDB", - "k_EMsgVSGetChallengeResults", - "k_EMsgVSChallengeResultText", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgClientCSGetDepotManifestChunk", - "", - "", - "", - "", - "k_EMsgBaseDRMS", - "", - "", - "k_EMsgDRMBuildBlobRequest", - "k_EMsgDRMBuildBlobResponse", - "k_EMsgDRMResolveGuidRequest", - "k_EMsgDRMResolveGuidResponse", - "", - "k_EMsgDRMVariabilityReport", - "k_EMsgDRMVariabilityReportResponse", - "k_EMsgDRMStabilityReport", - "k_EMsgDRMStabilityReportResponse", - "k_EMsgDRMDetailsReportRequest", - "k_EMsgDRMDetailsReportResponse", - "k_EMsgDRMProcessFile", - "k_EMsgDRMAdminUpdate", - "k_EMsgDRMAdminUpdateResponse", - "k_EMsgDRMSync", - "k_EMsgDRMSyncResposne", - "k_EMsgDRMProcessFileResponse", - "", - "", - "", - "", - "", - "k_EMsgBaseCS", - "k_EMsgCSManifestUpdate", - "k_EMsgCSUserContentRequest", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseClient", - "k_EMsgClientLogOn", - "k_EMsgClientAnonLogOn", - "k_EMsgClientHeartBeat", - "k_EMsgClientVACResponse", - "k_EMsgClientGamesPlayed_obsolete", - "k_EMsgClientLogOff", - "k_EMsgClientNoUDPConnectivity", - "k_EMsgClientInformOfCreateAccount", - "k_EMsgClientAckVACBan", - "k_EMsgClientConnectionStats", - "k_EMsgClientInitPurchase", - "k_EMsgClientPingResponse", - "k_EMsgClientAddFriend", - "k_EMsgClientRemoveFriend", - "k_EMsgClientGamesPlayedNoDataBlob", - "k_EMsgClientChangeStatus", - "k_EMsgClientVacStatusResponse", - "k_EMsgClientFriendMsg", - "k_EMsgClientGameConnect_obsolete", - "k_EMsgClientGamesPlayed2_obsolete", - "k_EMsgClientGameEnded_obsolete", - "k_EMsgClientGetFinalPrice", - "", - "", - "", - "k_EMsgClientSystemIM", - "k_EMsgClientSystemIMAck", - "k_EMsgClientGetLicenses", - "k_EMsgClientCancelLicense", - "k_EMsgClientGetLegacyGameKey", - "k_EMsgClientContentServerLogOn", - "k_EMsgClientAckVACBan2", - "k_EMsgClientCompletePurchase", - "k_EMsgClientCancelPurchase", - "k_EMsgClientAckMessageByGID", - "k_EMsgClientGetPurchaseReceipts", - "k_EMsgClientAckPurchaseReceipt", - "k_EMsgClientGamesPlayed3_obsolete", - "k_EMsgClientSendGuestPass", - "k_EMsgClientAckGuestPass", - "k_EMsgClientRedeemGuestPass", - "k_EMsgClientGamesPlayed", - "k_EMsgClientRegisterKey", - "k_EMsgClientInviteUserToClan", - "k_EMsgClientAcknowledgeClanInvite", - "k_EMsgClientPurchaseWithMachineID", - "k_EMsgClientAppUsageEvent", - "k_EMsgClientGetGiftTargetList", - "k_EMsgClientGetGiftTargetListResponse", - "", - "k_EMsgClientLogOnResponse", - "", - "k_EMsgClientVACChallenge", - "", - "k_EMsgClientSetHeartbeatRate", - "k_EMsgClientNotLoggedOnDeprecated", - "k_EMsgClientLoggedOff", - "k_EMsgGSApprove", - "k_EMsgGSDeny", - "k_EMsgGSKick", - "k_EMsgClientCreateAcctResponse", - "k_EMsgClientVACBanStatus", - "k_EMsgClientPurchaseResponse", - "k_EMsgClientPing", - "k_EMsgClientNOP", - "k_EMsgClientPersonaState", - "k_EMsgClientFriendsList", - "k_EMsgClientAccountInfo", - "k_EMsgClientAddFriendResponse", - "k_EMsgClientVacStatusQuery", - "k_EMsgClientNewsUpdate", - "", - "k_EMsgClientGameConnectDeny", - "k_EMsgGSStatusReply", - "k_EMsgClientGetFinalPriceResponse", - "", - "", - "", - "k_EMsgClientGameConnectTokens", - "k_EMsgClientLicenseList", - "k_EMsgClientCancelLicenseResponse", - "k_EMsgClientVACBanStatus2", - "k_EMsgClientCMList", - "k_EMsgClientEncryptPct", - "k_EMsgClientGetLegacyGameKeyResponse", - "k_EMsgClientFavoritesList", - "k_EMsgCSUserContentApprove", - "k_EMsgCSUserContentDeny", - "k_EMsgClientInitPurchaseResponse", - "k_EMsgClientGetPurchaseReceiptsResponse", - "k_EMsgClientAddFriend2", - "k_EMsgClientAddFriendResponse2", - "k_EMsgClientInviteFriend", - "k_EMsgClientInviteFriendResponse", - "k_EMsgClientSendGuestPassResponse", - "k_EMsgClientAckGuestPassResponse", - "k_EMsgClientRedeemGuestPassResponse", - "k_EMsgClientUpdateGuestPassesList", - "k_EMsgClientChatMsg", - "k_EMsgClientChatInvite", - "k_EMsgClientJoinChat", - "k_EMsgClientChatMemberInfo", - "k_EMsgClientLogOnWithCredentials", - "k_EMsgClientPasswordChange", - "k_EMsgClientPasswordChangeResponse", - "", - "k_EMsgClientChatEnter", - "k_EMsgClientFriendRemovedFromSource", - "k_EMsgClientCreateChat", - "k_EMsgClientCreateChatResponse", - "k_EMsgClientUpdateChatMetadata", - "k_EMsgClientP2PTrackerMessage", - "k_EMsgClientP2PIntroducerMessage", - "k_EMsgClientChatActionResult", - "k_EMsgClientRequestFriendData", - "k_EMsgClientOneTimeWGAuthPassword", - "", - "k_EMsgClientGetUserStats", - "k_EMsgClientGetUserStatsResponse", - "k_EMsgClientStoreUserStats", - "k_EMsgClientStoreUserStatsResponse", - "k_EMsgClientClanState", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgClientServiceModule", - "k_EMsgClientServiceCall", - "k_EMsgClientServiceCallResponse", - "", - "", - "", - "", - "", - "", - "k_EMsgClientNatTraversalStatEvent", - "k_EMsgClientAppInfoRequest", - "k_EMsgClientAppInfoResponse", - "k_EMsgClientSteamUsageEvent", - "k_EMsgClientEmailChange", - "k_EMsgClientPersonalQAChange", - "k_EMsgClientCheckPassword", - "k_EMsgClientResetPassword", - "", - "k_EMsgClientCheckPasswordResponse", - "k_EMsgClientResetPasswordResponse", - "k_EMsgClientSessionToken", - "k_EMsgClientDRMProblemReport", - "", - "", - "k_EMsgClientLogonBounce", - "k_EMsgClientSetIgnoreFriend", - "k_EMsgClientSetIgnoreFriendResponse", - "k_EMsgClientGetAppOwnershipTicket", - "k_EMsgClientGetAppOwnershipTicketResponse", - "", - "k_EMsgClientGetLobbyListResponse", - "k_EMsgClientGetLobbyMetadata", - "k_EMsgClientGetLobbyMetadataResponse", - "k_EMsgClientVTTCert", - "k_EMsgClientAppInfoRequestOld", - "k_EMsgClientAppInfoResponseOld", - "k_EMsgClientAppInfoUpdate", - "k_EMsgClientAppInfoChanges", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgClientServerList", - "k_EMsgClientUpdateInvPos", - "k_EMsgClientUpdateInvPosResponse", - "k_EMsgClientDeleteItem", - "k_EMsgClientDeleteItemResponse", - "k_EMsgClientLoadItems", - "k_EMsgClientLoadItemsResponse", - "k_EMsgClientItemGranted", - "k_EMsgClientGetFriendsLobbies", - "k_EMsgClientGetFriendsLobbiesResponse", - "k_EMsgClientGetLobbyList", - "k_EMsgClientEmailChangeResponse", - "k_EMsgClientSecretQAChangeResponse", - "k_EMsgClientPasswordChange2", - "k_EMsgClientEmailChange2", - "k_EMsgClientPersonalQAChange2", - "k_EMsgClientDRMBlobRequest", - "k_EMsgClientDRMBlobResponse", - "k_EMsgClientLookupKey", - "k_EMsgClientLookupKeyResponse", - "k_EMsgBaseGameServer", - "k_EMsgGSDisconnectNotice", - "", - "k_EMsgGSStatus", - "", - "k_EMsgGSUserPlaying3", - "k_EMsgGSStatus2", - "k_EMsgGSStatusUpdate", - "k_EMsgGSServerType", - "k_EMsgGSPlayerList", - "k_EMsgGSGetUserAchievementStatus", - "k_EMsgGSGetUserAchievementStatusResponse", - "k_EMsgGSCreateItem", - "k_EMsgGSCreateItemResponse", - "k_EMsgGSItemDeleted", - "k_EMsgGSItemUpdated", - "k_EMsgGSLoadItems", - "k_EMsgGSLoadItemsResponse", - "k_EMsgGSGetPlayStats", - "k_EMsgGSGetPlayStatsResponse", - "k_EMsgGSGetUserGroupStatus", - "k_EMsgAMGetUserGroupStatus", - "k_EMsgAMGetUserGroupStatusResponse", - "k_EMsgGSGetUserGroupStatusResponse", - "k_EMsgGSGrantItem", - "k_EMsgGSGrantItemResponse", - "k_EMsgGSDeleteTempItem", - "k_EMsgGSDeleteTempItemResponse", - "k_EMsgGSDeleteAllTempItems", - "k_EMsgGSDeleteAllTempItemsResponse", - "k_EMsgGSItemGranted", - "k_EMsgGSUpdateItemQuantity", - "k_EMsgGSUpdateItemQuantityResponse", - "k_EMsgGSRestoreOwnedItems", - "k_EMsgGSRestoreOwnedItemsResponse", - "k_EMsgGSItemDropped", - "k_EMsgGSGetReputation", - "k_EMsgGSGetReputationResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgAdminCmd", - "", - "", - "", - "k_EMsgAdminCmdResponse", - "k_EMsgAdminLogListenRequest", - "k_EMsgAdminLogEvent", - "k_EMsgLogSearchRequest", - "k_EMsgLogSearchResponse", - "k_EMsgLogSearchCancel", - "k_EMsgUniverseData", - "", - "", - "", - "k_EMsgRequestStatHistory", - "k_EMsgStatHistory", - "", - "k_EMsgAdminPwLogon", - "k_EMsgAdminPwLogonResponse", - "k_EMsgAdminSpew", - "k_EMsgAdminConsoleTitle", - "", - "", - "k_EMsgAdminGCSpew", - "k_EMsgAdminGCCommand", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgFBSReqVersion", - "k_EMsgFBSVersionInfo", - "k_EMsgFBSForceRefresh", - "k_EMsgFBSForceBounce", - "k_EMsgFBSDeployPackage", - "k_EMsgFBSDeployResponse", - "k_EMsgFBSUpdateBootstrapper", - "k_EMsgFBSSetState", - "k_EMsgFBSApplyOSUpdates", - "k_EMsgFBSRunCMDScript", - "k_EMsgFBSRebootBox", - "k_EMsgFBSSetBigBrotherMode", - "k_EMsgFBSMinidumpServer", - "k_EMsgFBSSetShellCount", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgFileXferRequest", - "k_EMsgFileXferResponse", - "k_EMsgFileXferData", - "k_EMsgFileXferEnd", - "k_EMsgFileXferDataAck", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgChannelAuthChallenge", - "k_EMsgChannelAuthResponse", - "k_EMsgChannelAuthResult", - "k_EMsgChannelEncryptRequest", - "k_EMsgChannelEncryptResponse", - "k_EMsgChannelEncryptResult", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseBS", - "k_EMsgBSPurchaseStart", - "k_EMsgBSPurchaseResponse", - "", - "k_EMsgBSSettleStart", - "", - "k_EMsgBSSettleComplete", - "k_EMsgBSBannedRequest", - "k_EMsgBSInitPayPalTxn", - "k_EMsgBSInitPayPalTxnResponse", - "k_EMsgBSGetPayPalUserInfo", - "k_EMsgBSGetPayPalUserInfoResponse", - "", - "k_EMsgBSRefundTxn", - "k_EMsgBSRefundTxnResponse", - "k_EMsgBSGetEvents", - "k_EMsgBSChaseRFRRequest", - "k_EMsgBSPaymentInstrBan", - "k_EMsgBSPaymentInstrBanResponse", - "k_EMsgBSProcessGCReports", - "k_EMsgBSProcessPPReports", - "k_EMsgBSInitGCPayPalTxn", - "k_EMsgBSInitGCPayPalTxnResponse", - "k_EMsgBSQueryGCPayPalTxn", - "k_EMsgBSQueryGCPayPalTxnResponse", - "k_EMsgBSCommitGCTxn", - "k_EMsgBSQueryGCOrderStatus", - "k_EMsgBSQueryGCOrderStatusResponse", - "k_EMsgBSQueryCBOrderStatus", - "k_EMsgBSQueryCBOrderStatusResponse", - "k_EMsgBSRunRedFlagReport", - "k_EMsgBSQueryPaymentInstUsage", - "k_EMsgBSQueryPaymentInstResponse", - "k_EMsgBSQueryTxnExtendedInfo", - "k_EMsgBSQueryTxnExtendedInfoResponse", - "k_EMsgBSUpdateConversionRates", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseATS", - "k_EMsgATSStartStressTest", - "k_EMsgATSStopStressTest", - "k_EMsgATSRunFailServerTest", - "k_EMsgATSUFSPerfTestTask", - "k_EMsgATSUFSPerfTestResponse", - "k_EMsgATSCycleTCM", - "k_EMsgATSInitDRMSStressTest", - "k_EMsgATSCallTest", - "k_EMsgATSCallTestReply", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseDP", - "k_EMsgDPSetPublishingState", - "k_EMsgDPGamePlayedStats", - "k_EMsgDPUniquePlayersStat", - "", - "k_EMsgDPVacInfractionStats", - "k_EMsgDPVacBanStats", - "k_EMsgDPCoplayStats", - "k_EMsgDPNatTraversalStats", - "k_EMsgDPSteamUsageEvent", - "k_EMsgDPVacCertBanStats", - "k_EMsgDPVacCafeBanStats", - "k_EMsgDPCloudStats", - "k_EMsgDPAchievementStats", - "k_EMsgDPAccountCreationStats", - "k_EMsgDPGetPlayerCount", - "k_EMsgDPGetPlayerCountResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseCM", - "k_EMsgCMSetAllowState", - "k_EMsgCMSpewAllowState", - "k_EMsgCMAppInfoResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseDSS", - "k_EMsgDSSNewFile", - "k_EMsgDSSCurrentFileList", - "k_EMsgDSSSynchList", - "k_EMsgDSSSynchListResponse", - "k_EMsgDSSSynchSubscribe", - "k_EMsgDSSSynchUnsubscribe", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseEPM", - "k_EMsgEPMStartProcess", - "k_EMsgEPMStopProcess", - "k_EMsgEPMRestartProcess", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgAMInternalAuthComplete", - "k_EMsgAMInternalRemoveAMSession", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgISCreateItem", - "k_EMsgISCreateItemResponse", - "k_EMsgISRefresh", - "k_EMsgISCreateSpecificItem", - "k_EMsgISAssignItemIDs", - "k_EMsgISAssignItemIDsResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgGCSendClient", - "k_EMsgAMRelayToGC", - "k_EMsgGCUpdatePlayedState", - "k_EMsgGCCmdRevive", - "k_EMsgGCCmdBounce", - "k_EMsgGCCmdForceBounce", - "k_EMsgGCCmdDown", - "k_EMsgGCCmdDeploy", - "k_EMsgGCCmdDeployResponse", - "k_EMsgGCCmdSwitch", - "k_EMsgAMRefreshSessions", - "k_EMsgGCUpdateGSState", - "k_EMsgGCAchievementAwarded", - "k_EMsgGCSystemMessage", - "k_EMsgGCValidateSession", - "k_EMsgGCValidateSessionResponse", - "k_EMsgGCCmdStatus", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseP2P", - "k_EMsgP2PTrackerMessage", - "k_EMsgP2PIntroducerMessage", - "k_EMsgP2PSeederUpload", - "k_EMsgP2PSeederUploadResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseSM", - "k_EMsgSMBuildUGSTables", - "k_EMsgSMExpensiveReport", - "k_EMsgSMHourlyReport", - "k_EMsgSMFishingReport", - "k_EMsgSMPartitionRenames", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgFailServer", - "k_EMsgJobHeartbeatTest", - "k_EMsgJobHeartbeatTestResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseFTSRange", - "k_EMsgFTSGetBrowseCounts", - "k_EMsgFTSGetBrowseCountsResponse", - "k_EMsgFTSBrowseClans", - "k_EMsgFTSBrowseClansResponse", - "k_EMsgFTSSearchClansByLocation", - "k_EMsgFTSSearchClansByLocationResponse", - "k_EMsgFTSSearchPlayersByLocation", - "k_EMsgFTSSearchPlayersByLocationResponse", - "k_EMsgFTSClanDeleted", - "k_EMsgFTSSearch", - "k_EMsgFTSSearchResponse", - "k_EMsgFTSSearchStatus", - "k_EMsgFTSSearchStatusResponse", - "k_EMsgFTSGetGSPlayStats", - "k_EMsgFTSGetGSPlayStatsResponse", - "k_EMsgFTSGetGSPlayStatsForServer", - "k_EMsgFTSGetGSPlayStatsForServerResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseCCSRange", - "k_EMsgCCSGetComments", - "k_EMsgCCSGetCommentsResponse", - "k_EMsgCCSAddComment", - "k_EMsgCCSAddCommentResponse", - "k_EMsgCCSDeleteComment", - "k_EMsgCCSDeleteCommentResponse", - "k_EMsgCCSPreloadComments", - "k_EMsgCCSNotifyCommentCount", - "k_EMsgCCSGetCommentsForNews", - "k_EMsgCCSGetCommentsForNewsResponse", - "k_EMsgCCSDeleteAllComments", - "k_EMsgCCSDeleteAllCommentsResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseLBSRange", - "k_EMsgLBSSetScore", - "k_EMsgLBSSetScoreResponse", - "k_EMsgLBSFindOrCreateLB", - "k_EMsgLBSFindOrCreateLBResponse", - "k_EMsgLBSGetLBEntries", - "k_EMsgLBSGetLBEntriesResponse", - "k_EMsgLBSGetLBList", - "k_EMsgLBSGetLBListResponse", - "k_EMsgLBSSetLBDetails", - "k_EMsgLBSDeleteLB", - "k_EMsgLBSDeleteLBEntry", - "k_EMsgLBSResetLB", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseOGS", - "k_EMsgOGSBeginSession", - "k_EMsgOGSBeginSessionResponse", - "k_EMsgOGSEndSession", - "k_EMsgOGSEndSessionResponse", - "k_EMsgOGSWriteRow", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseAMRange2", - "k_EMsgAMCreateChat", - "k_EMsgAMCreateChatResponse", - "k_EMsgAMUpdateChatMetadata", - "k_EMsgAMPublishChatMetadata", - "k_EMsgAMSetProfileURL", - "k_EMsgAMGetAccountEmailAddress", - "k_EMsgAMGetAccountEmailAddressResponse", - "k_EMsgAMRequestFriendData", - "k_EMsgAMRouteToClients", - "k_EMsgAMLeaveClan", - "k_EMsgAMClanPermissions", - "k_EMsgAMClanPermissionsResponse", - "k_EMsgAMCreateClanEvent", - "k_EMsgAMCreateClanEventResponse", - "k_EMsgAMUpdateClanEvent", - "k_EMsgAMUpdateClanEventResponse", - "k_EMsgAMGetClanEvents", - "k_EMsgAMGetClanEventsResponse", - "k_EMsgAMDeleteClanEvent", - "k_EMsgAMDeleteClanEventResponse", - "k_EMsgAMSetClanPermissionSettings", - "k_EMsgAMSetClanPermissionSettingsResponse", - "k_EMsgAMGetClanPermissionSettings", - "k_EMsgAMGetClanPermissionSettingsResponse", - "k_EMsgAMPublishChatRoomInfo", - "k_EMsgClientChatRoomInfo", - "k_EMsgAMCreateClanAnnouncement", - "k_EMsgAMCreateClanAnnouncementResponse", - "k_EMsgAMUpdateClanAnnouncement", - "k_EMsgAMUpdateClanAnnouncementResponse", - "k_EMsgAMGetClanAnnouncementsCount", - "k_EMsgAMGetClanAnnouncementsCountResponse", - "k_EMsgAMGetClanAnnouncements", - "k_EMsgAMGetClanAnnouncementsResponse", - "k_EMsgAMDeleteClanAnnouncement", - "k_EMsgAMDeleteClanAnnouncementResponse", - "k_EMsgAMGetSingleClanAnnouncement", - "k_EMsgAMGetSingleClanAnnouncementResponse", - "k_EMsgAMGetClanHistory", - "k_EMsgAMGetClanHistoryResponse", - "k_EMsgAMGetClanPermissionBits", - "k_EMsgAMGetClanPermissionBitsResponse", - "k_EMsgAMSetClanPermissionBits", - "k_EMsgAMSetClanPermissionBitsResponse", - "k_EMsgAMSessionInfoRequest", - "k_EMsgAMSessionInfoResponse", - "k_EMsgAMValidateWGToken", - "k_EMsgAMGetSingleClanEvent", - "k_EMsgAMGetSingleClanEventResponse", - "k_EMsgAMGetClanRank", - "k_EMsgAMGetClanRankResponse", - "k_EMsgAMSetClanRank", - "k_EMsgAMSetClanRankResponse", - "k_EMsgAMGetClanPOTW", - "k_EMsgAMGetClanPOTWResponse", - "k_EMsgAMSetClanPOTW", - "k_EMsgAMSetClanPOTWResponse", - "k_EMsgAMRequestChatMetadata", - "k_EMsgAMDumpUser", - "k_EMsgAMKickUserFromClan", - "k_EMsgAMAddFounderToClan", - "k_EMsgAMValidateWGTokenResponse", - "k_EMsgAMSetCommunityState", - "k_EMsgAMSetAccountDetails", - "k_EMsgAMGetChatBanList", - "k_EMsgAMGetChatBanListResponse", - "k_EMsgAMUnBanFromChat", - "k_EMsgAMSetClanDetails", - "k_EMsgAMGetAccountLinks", - "k_EMsgAMGetAccountLinksResponse", - "k_EMsgAMSetAccountLinks", - "k_EMsgAMSetAccountLinksResponse", - "k_EMsgAMGetUserGameStats", - "k_EMsgAMGetUserGameStatsResponse", - "k_EMsgAMCheckClanMembership", - "k_EMsgAMGetClanMembers", - "k_EMsgAMGetClanMembersResponse", - "k_EMsgAMJoinPublicClan", - "k_EMsgAMNotifyChatOfClanChange", - "k_EMsgAMResubmitPurchase", - "k_EMsgAMAddFriend", - "k_EMsgAMAddFriendResponse", - "k_EMsgAMRemoveFriend", - "k_EMsgAMGetVIPStatus", - "k_EMsgAMVIPStatusResponse", - "k_EMsgAMCancelEasyCollect", - "k_EMsgAMCancelEasyCollectResponse", - "k_EMsgAMGetClanMembershipList", - "k_EMsgAMGetClanMembershipListResponse", - "k_EMsgAMClansInCommon", - "k_EMsgAMClansInCommonResponse", - "k_EMsgAMIsValidAccountID", - "k_EMsgAMConvertClan", - "k_EMsgAMGetGiftTargetListRelay", - "k_EMsgAMWipeFriendsList", - "k_EMsgAMSetIgnored", - "k_EMsgAMClansInCommonCountResponse", - "k_EMsgAMFriendsList", - "k_EMsgAMFriendsListResponse", - "k_EMsgAMFriendsInCommon", - "k_EMsgAMFriendsInCommonResponse", - "k_EMsgAMFriendsInCommonCountResponse", - "k_EMsgAMClansInCommonCount", - "k_EMsgAMChallengeVerdict", - "k_EMsgAMChallengeNotification", - "k_EMsgAMFindGSByIP", - "k_EMsgAMFoundGSByIP", - "k_EMsgAMGiftRevoked", - "k_EMsgAMCreateAccountRecord", - "k_EMsgAMUserClanList", - "k_EMsgAMUserClanListResponse", - "k_EMsgAMGetAccountDetails2", - "k_EMsgAMGetAccountDetailsResponse2", - "k_EMsgAMSetCommunityProfileSettings", - "k_EMsgAMSetCommunityProfileSettingsResponse", - "k_EMsgAMGetCommunityPrivacyState", - "k_EMsgAMGetCommunityPrivacyStateResponse", - "k_EMsgAMCheckClanInviteRateLimiting", - "k_EMsgAMGetUserAchievementStatus", - "k_EMsgAMGetIgnored", - "k_EMsgAMGetIgnoredResponse", - "k_EMsgAMSetIgnoredResponse", - "k_EMsgAMSetFriendRelationshipNone", - "k_EMsgAMGetFriendRelationship", - "k_EMsgAMGetFriendRelationshipResponse", - "k_EMsgAMServiceModulesCache", - "k_EMsgAMServiceModulesCall", - "k_EMsgAMServiceModulesCallResponse", - "k_EMsgAMGetCaptchaDataForIP", - "k_EMsgAMGetCaptchaDataForIPResponse", - "k_EMsgAMValidateCaptchaDataForIP", - "k_EMsgAMValidateCaptchaDataForIPResponse", - "k_EMsgAMTrackFailedAuthByIP", - "k_EMsgAMGetCaptchaDataByGID", - "k_EMsgAMGetCaptchaDataByGIDResponse", - "k_EMsgAMGetLobbyList", - "k_EMsgAMGetLobbyListResponse", - "k_EMsgAMGetLobbyMetadata", - "k_EMsgAMGetLobbyMetadataResponse", - "k_EMsgAMAddFriendNews", - "k_EMsgAMAddClanNews", - "k_EMsgAMWriteNews", - "k_EMsgAMFindClanUser", - "k_EMsgAMFindClanUserResponse", - "k_EMsgAMBanFromChat", - "k_EMsgAMGetUserHistoryResponse", - "k_EMsgAMGetUserNewsSubscriptions", - "k_EMsgAMGetUserNewsSubscriptionsResponse", - "k_EMsgAMSetUserNewsSubscriptions", - "k_EMsgAMGetUserNews", - "k_EMsgAMGetUserNewsResponse", - "k_EMsgAMSendQueuedEmails", - "k_EMsgAMSetLicenseFlags", - "k_EMsgAMGetUserHistory", - "k_EMsgAMDeleteUserNews", - "k_EMsgAMAllowUserFilesRequest", - "k_EMsgAMAllowUserFilesResponse", - "k_EMsgAMGetAccountStatus", - "k_EMsgAMGetAccountStatusResponse", - "k_EMsgAMEditBanReason", - "", - "k_EMsgAMProbeClanMembershipList", - "k_EMsgAMProbeClanMembershipListResponse", - "k_EMsgAMRouteClientMsgToAM", - "k_EMsgAMGetFriendsLobbies", - "k_EMsgAMGetFriendsLobbiesResponse", - "k_EMsgAMLoadItems", - "k_EMsgAMLoadItemsResponse", - "k_EMsgAMCacheNewItem", - "k_EMsgAMRelayItemUpdateGS", - "k_EMsgAMRelayItemDeletedGS", - "k_EMsgAMGetUserFriendNewsResponse", - "k_EMsgAMGetUserFriendNews", - "k_EMsgAMGetUserClansNewsResponse", - "k_EMsgAMGetUserClansNews", - "k_EMsgAMStoreInitPurchase", - "k_EMsgAMStoreInitPurchaseResponse", - "k_EMsgAMStoreGetFinalPrice", - "k_EMsgAMStoreGetFinalPriceResponse", - "k_EMsgAMStoreCompletePurchase", - "k_EMsgAMStoreCancelPurchase", - "k_EMsgAMStorePurchaseResponse", - "k_EMsgAMCreateAccountRecordInSteam3", - "k_EMsgAMGetPreviousCBAccount", - "k_EMsgAMGetPreviousCBAccountResponse", - "k_EMsgAMUpdateBillingAddress", - "k_EMsgAMUpdateBillingAddressResponse", - "k_EMsgAMGetBillingAddress", - "k_EMsgAMGetBillingAddressResponse", - "k_EMsgAMGetUserLicenseHistory", - "k_EMsgAMGetUserLicenseHistoryResponse", - "k_EMsgAMGetUserTransactionHistory", - "k_EMsgAMGetUserTransactionHistoryResponse", - "k_EMsgAMSupportChangePassword", - "k_EMsgAMSupportChangeEmail", - "k_EMsgAMSupportChangeSecretQA", - "k_EMsgAMResetUserVerificationGSByIP", - "k_EMsgAMUpdateGSPlayStats", - "k_EMsgAMSupportEnableOrDisable", - "k_EMsgAMGetComments", - "k_EMsgAMGetCommentsResponse", - "k_EMsgAMAddComment", - "k_EMsgAMAddCommentResponse", - "k_EMsgAMDeleteComment", - "k_EMsgAMDeleteCommentResponse", - "k_EMsgAMGetPurchaseStatus", - "k_EMsgAMChatDetailsQuery", - "k_EMsgAMChatDetailsResponse", - "k_EMsgAMSupportIsAccountEnabled", - "k_EMsgAMSupportIsAccountEnabledResponse", - "k_EMsgAMGetUserStats", - "k_EMsgAMSupportKickSession", - "k_EMsgAMGSSearch", - "k_EMsgAMAwardItem", - "k_EMsgAMRelayItemAwardedGS", - "k_EMsgMarketingMessageUpdate", - "k_EMsgAMRelayItemQuantityUpdated", - "k_EMsgAMRelayItemQuantityUpdatedResponse", - "k_EMsgAMRouteFriendMsg", - "k_EMsgAMTicketAuthRequestOrResponse", - "k_EMsgAMFlushItemCaches", - "k_EMsgAMVerifyDepotManagementRights", - "k_EMsgAMVerifyDepotManagementRightsResponse", - "k_EMsgAMAddFreeLicense", - "k_EMsgAMGetUserFriendsMinutesPlayed", - "k_EMsgAMGetUserFriendsMinutesPlayedResponse", - "k_EMsgAMGetUserMinutesPlayed", - "k_EMsgAMGetUserMinutesPlayedResponse", - "k_EMsgAMReloadAccountItemSection", - "k_EMsgAMRelayCurrentCoplayCount", - "k_EMsgAMValidateEmailLink", - "k_EMsgAMValidateEmailLinkResponse", - "k_EMsgAMReportDroppedItemGS", - "k_EMsgAMAddUsersToMarketingTreatment", - "k_EMsgAMAddItemListToUser", - "k_EMsgAMStoreUserStats", - "k_EMsgAMGetUserGameplayInfo", - "k_EMsgAMGetUserGameplayInfoResponse", - "k_EMsgAMGetCardList", - "k_EMsgAMGetCardListResponse", - "k_EMsgAMDeleteStoredCard", - "k_EMsgAMRevokeLegacyGameKeys", - "k_EMsgAMCommitPurchasedItem", - "k_EMsgAMGetWalletDetails", - "k_EMsgAMGetWalletDetailsResponse", - "k_EMsgAMDeleteStoredPaymentInfo", - "k_EMsgAMGetStoredPaymentSummary", - "k_EMsgAMGetStoredPaymentSummaryResponse", - "k_EMsgAMGetWalletConversionRate", - "k_EMsgAMGetWalletConversionRateResponse", - "k_EMsgAMConvertWallet", - "k_EMsgAMConvertWalletResponse", - "k_EMsgAMRelayGetFriendsWhoPlayGame", - "k_EMsgAMRelayGetFriendsWhoPlayGameResponse", - "k_EMsgAMSetPreApproval", - "k_EMsgAMSetPreApprovalResponse", - "k_EMsgAMMarketingTreatmentUpdate", - "k_EMsgAMCreateRefund", - "k_EMsgAMCreateRefundResponse", - "k_EMsgAMCreateChargeback", - "k_EMsgAMCreateChargebackResponse", - "k_EMsgAMCreateDispute", - "k_EMsgAMCreateDisputeResponse", - "k_EMsgAMClearDispute", - "k_EMsgAMClearDisputeResponse", - "k_EMsgCAMQueryPersonaStateCache", - "k_EMsgCAMQueryPersonaStateCacheResponse", - "k_EMsgAMSetDRMTestConfig", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBasePSRange", - "k_EMsgPSCreateShoppingCart", - "k_EMsgPSCreateShoppingCartResponse", - "k_EMsgPSIsValidShoppingCart", - "k_EMsgPSIsValidShoppingCartResponse", - "k_EMsgPSAddPackageToShoppingCart", - "k_EMsgPSAddPackageToShoppingCartResponse", - "k_EMsgPSRemoveLineItemFromShoppingCart", - "k_EMsgPSRemoveLineItemFromShoppingCartResponse", - "k_EMsgPSGetShoppingCartContents", - "k_EMsgPSGetShoppingCartContentsResponse", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseUFSRange", - "", - "k_EMsgClientUFSUploadFileRequest", - "k_EMsgClientUFSUploadFileResponse", - "k_EMsgClientUFSUploadFileChunk", - "k_EMsgClientUFSUploadFileFinished", - "k_EMsgClientUFSGetFileListForApp", - "k_EMsgClientUFSGetFileListForAppResponse", - "k_EMsgRouteClientMsgToUFS", - "k_EMsgRouteUFSMsgToClient", - "k_EMsgClientUFSDownloadRequest", - "k_EMsgClientUFSDownloadResponse", - "k_EMsgClientUFSDownloadChunk", - "k_EMsgClientUFSLoginRequest", - "k_EMsgClientUFSLoginResponse", - "k_EMsgUFSReloadPartitionInfo", - "k_EMsgClientUFSTransferHeartbeat", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseClient2", - "k_EMsgClientRequestForgottenPasswordEmail", - "k_EMsgClientRequestForgottenPasswordEmailResponse", - "k_EMsgClientCreateAccountResponse", - "k_EMsgClientResetForgottenPassword", - "k_EMsgClientResetForgottenPasswordResponse", - "k_EMsgClientCreateAccount2", - "k_EMsgClientInformOfResetForgottenPassword", - "k_EMsgClientInformOfResetForgottenPasswordResponse", - "k_EMsgClientAnonUserLogOn", - "k_EMsgClientGamesPlayedWithDataBlob", - "k_EMsgClientUpdateUserGameInfo", - "k_EMsgClientFileToDownload", - "k_EMsgClientFileToDownloadResponse", - "k_EMsgClientLBSSetScore", - "k_EMsgClientLBSSetScoreResponse", - "k_EMsgClientLBSFindOrCreateLB", - "k_EMsgClientLBSFindOrCreateLBResponse", - "k_EMsgClientLBSGetLBEntries", - "k_EMsgClientLBSGetLBEntriesResponse", - "k_EMsgClientMarketingMessageUpdate", - "k_EMsgClientGetItemBlob", - "k_EMsgClientGetItemBlobResponse", - "k_EMsgClientSetItemBlob", - "k_EMsgClientSetItemBlobResponse", - "k_EMsgClientItemQuantityUpdated", - "k_EMsgClientChatDeclined", - "k_EMsgClientFriendMsgIncoming", - "k_EMsgClientAuthList", - "k_EMsgClientTicketAuthComplete", - "k_EMsgClientIsLimitedAccount", - "k_EMsgClientRequestAuthList", - "k_EMsgClientAuthList2", - "k_EMsgClientStat", - "k_EMsgClientP2PConnectionInfo", - "k_EMsgClientP2PConnectionFailInfo", - "k_EMsgClientGetNumberOfCurrentPlayers", - "k_EMsgClientGetNumberOfCurrentPlayersResponse", - "k_EMsgClientGetDepotDecryptionKey", - "k_EMsgClientGetDepotDecryptionKeyResponse", - "k_EMsgGSPerformHardwareSurvey", - "k_EMsgClientCheckForUpdatedDepotManifest", - "k_EMsgClientCheckForUpdatedDepotManifestResponse", - "k_EMsgClientEnableTestLicense", - "k_EMsgClientEnableTestLicenseResponse", - "k_EMsgClientDisableTestLicense", - "k_EMsgClientDisableTestLicenseResponse", - "", - "k_EMsgClientRequestValidationMail", - "k_EMsgClientRequestValidationMailResponse", - "k_EMsgClientDropItem", - "k_EMsgClientDropItemResponse", - "k_EMsgClientToGC", - "k_EMsgClientFromGC", - "k_EMsgClientRequestChangeMail", - "k_EMsgClientRequestChangeMailResponse", - "k_EMsgClientEmailAddrInfo", - "k_EMsgClientPasswordChange3", - "k_EMsgClientEmailChange3", - "k_EMsgClientPersonalQAChange3", - "k_EMsgClientResetForgottenPassword3", - "k_EMsgClientRequestForgottenPasswordEmail3", - "k_EMsgClientCreateAccount3", - "k_EMsgClientNewLoginKey", - "k_EMsgClientNewLoginKeyAccepted", - "k_EMsgClientLogOnWithHash", - "k_EMsgClientStoreUserStats2", - "k_EMsgClientStatsUpdated", - "k_EMsgClientActivateOEMLicense", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgClientRequestedClientStats", - "k_EMsgClientStat2Int32", - "k_EMsgClientStat2", - "k_EMsgClientVerifyPassword", - "k_EMsgClientVerifyPasswordResponse", - "k_EMsgClientDRMDownloadRequest", - "k_EMsgClientDRMDownloadResponse", - "k_EMsgClientDRMFinalResult", - "k_EMsgClientGetFriendsWhoPlayGame", - "k_EMsgClientGetFriendsWhoPlayGameResponse", - "k_EMsgClientOGSBeginSession", - "k_EMsgClientOGSBeginSessionResponse", - "k_EMsgClientOGSEndSession", - "k_EMsgClientOGSEndSessionResponse", - "k_EMsgClientOGSWriteRow", - "k_EMsgClientDRMTest", - "k_EMsgClientDRMTestResult", - "", - "", - "", - "k_EMsgClientServerUnavailable", - "k_EMsgClientServersAvailable", - "k_EMsgClientRegisterAuthTicketWithCM", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseDFS", - "k_EMsgDFSGetFile", - "k_EMsgDFSInstallLocalFile", - "k_EMsgDFSConnection", - "k_EMsgDFSConnectionReply", - "k_EMsgClientDFSAuthenticateRequest", - "k_EMsgClientDFSAuthenticateResponse", - "k_EMsgClientDFSEndSession", - "k_EMsgDFSPurgeFile", - "k_EMsgDFSRouteFile", - "k_EMsgDFSGetFileFromServer", - "k_EMsgDFSAcceptedResponse", - "k_EMsgDFSRequestPingback", - "k_EMsgDFSRecvTransmitFile", - "k_EMsgDFSSendTransmitFile", - "k_EMsgDFSRequestPingback2", - "k_EMsgDFSResponsePingback2", - "k_EMsgClientDFSDownloadStatus", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgBaseMDS", - "k_EMsgClientMDSLoginRequest", - "k_EMsgClientMDSLoginResponse", - "k_EMsgClientMDSUploadManifestRequest", - "k_EMsgClientMDSUploadManifestResponse", - "k_EMsgClientMDSTransmitManifestDataChunk", - "k_EMsgClientMDSHeartbeat", - "k_EMsgClientMDSUploadDepotChunks", - "k_EMsgClientMDSUploadDepotChunksResponse", - "k_EMsgClientMDSInitDepotBuildRequest", - "k_EMsgClientMDSInitDepotBuildResponse", - "k_EMsgClientMDSChunkListResponse", - "k_EMsgAMToMDSGetDepotDecryptionKey", - "k_EMsgMDSToAMGetDepotDecryptionKeyResponse", - "k_EMsgMDSGetVersionsForDepot", - "k_EMsgMDSGetVersionsForDepotResponse", - "k_EMsgMDSSetPublicVersionForDepot", - "k_EMsgMDSSetPublicVersionForDepotResponse", - "k_EMsgClientMDSGetDepotManifest", - "k_EMsgClientMDSGetDepotManifestResponse", - "k_EMsgClientMDSGetDepotManifestChunk", - "k_EMsgAMToMDSCheckForUpdatedDepotManifest", - "k_EMsgMDSToAMCheckForUpdatedDepotManifestResponse", - "k_EMsgClientMDSDownloadDepotChunksRequest", - "k_EMsgClientMDSDownloadDepotChunksAsync", - "k_EMsgClientMDSDownloadDepotChunksAck", - "k_EMsgMDSContentServerStatsBroadcast", - "k_EMsgMDSContentServerConfigRequest", - "k_EMsgMDSContentServerConfig", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "k_EMsgCSBase", - "k_EMsgClientCSLoginRequest", - "k_EMsgClientCSLoginResponse", - "k_EMsgClientCSGetDepotManifest", - "k_EMsgClientCSGetDepotManifestResponse", -}; - -/* -const char *PchNameFromEMsg( EMsg eMsg ) -{ - if ( eMsg <= k_EMsgInvalid || eMsg > k_EMsgClientCSGetDepotManifestResponse ) - return k_szEMsg[ 0 ]; - - return k_szEMsg[ (int)eMsg ]; -} -*/ - -const char *k_szEResult[] = -{ - "Invalid EResult", - "k_EResultOK", - "k_EResultFail", - "k_EResultNoConnection", - "k_EResultNoConnectionRetry", - "k_EResultInvalidPassword", - "k_EResultLoggedInElsewhere", - "k_EResultInvalidProtocolVer", - "k_EResultInvalidParam", - "k_EResultFileNotFound", - "k_EResultBusy", - "k_EResultInvalidState", - "k_EResultInvalidName", - "k_EResultInvalidEmail", - "k_EResultDuplicateName", - "k_EResultAccessDenied", - "k_EResultTimeout", - "k_EResultBanned", - "k_EResultAccountNotFound", - "k_EResultInvalidSteamID", - "k_EResultServiceUnavailable", - "k_EResultNotLoggedOn", - "k_EResultPending", - "k_EResultEncryptionFailure", - "k_EResultInsufficientPrivilege", - "k_EResultLimitExceeded", - "k_EResultRevoked", - "k_EResultExpired", - "k_EResultAlreadyRedeemed", - "k_EResultDuplicateRequest", - "k_EResultAlreadyOwned", - "k_EResultIPNotFound", - "k_EResultPersistFailed", - "k_EResultLockingFailed", - "k_EResultLogonSessionReplaced", - "k_EResultConnectFailed", - "k_EResultHandshakeFailed", - "k_EResultIOFailure", - "k_EResultRemoteDisconnect", - "k_EResultShoppingCartNotFound", - "k_EResultBlocked", - "k_EResultIgnored", - "k_EResultNoMatch", - "k_EResultAccountDisabled", - "k_EResultServiceReadOnly", - "k_EResultAccountNotFeatured", - "k_EResultAdministratorOK", - "k_EResultContentVersion", - "k_EResultTryAnotherCM", - "k_EResultPasswordRequiredToKickSession", - "k_EResultAlreadyLoggedInElsewhere", - "k_EResultSuspended", - "k_EResultCancelled", - "k_EResultDataCorruption", - "k_EResultDiskFull", - "k_EResultRemoteCallFailed", -}; - -const char *PchNameFromEResult( EResult eResult ) -{ - if ( eResult <= 0 || eResult >= 55 ) - return k_szEResult[ 0 ]; - - return k_szEResult[ (int)eResult ]; -} - -const char *k_szEAccountType[] = -{ - "k_EAccountTypeInvalid", - "k_EAccountTypeIndividual", - "k_EAccountTypeMultiseat", - "k_EAccountTypeGameServer", - "k_EAccountTypeAnonGameServer", - "k_EAccountTypePending", - "k_EAccountTypeContentServer", - "k_EAccountTypeClan", - "k_EAccountTypeChat", - "k_EAccountTypeP2PSuperSeeder", - "k_EAccountTypeAnonUser", -}; - -const char *PchNameFromEAccountType( EAccountType eAccountType ) -{ - if ( eAccountType <= 0 || eAccountType >= k_EAccountTypeMax ) - return k_szEAccountType[ 0 ]; - - return k_szEAccountType[ (int)eAccountType ]; -} - -const char *PchStringFromSockAddr( const sockaddr_in *sockAddr ) -{ - static char szSockAddr[ 22 ]; - memset( szSockAddr, 0, sizeof( szSockAddr ) ); - - if ( !sockAddr ) - return NULL; - - sprintf_s( szSockAddr, sizeof( szSockAddr ), "%s:%hu", inet_ntoa( sockAddr->sin_addr ), ntohs( sockAddr->sin_port ) ); - - return szSockAddr; -} \ No newline at end of file diff --git a/Resources/NetHook/utils.h b/Resources/NetHook/utils.h deleted file mode 100644 index e6e10332..00000000 --- a/Resources/NetHook/utils.h +++ /dev/null @@ -1,36 +0,0 @@ - -#ifndef UTILS_H_ -#define UTILS_H_ -#ifdef _WIN32 -#pragma once -#endif - - -#include "steam/steamtypes.h" -#include "steam/csteamid.h" -#include "steam/udppkt.h" - -#include - - - -const char *PchStringFromUDPPktHdr( const UDPPktHdr_t *pHdr ); -const char *PchStringFromMsgHdr( const MsgHdr_t *pMsgHdr ); -const char *PchStringFromExtendedClientMsgHdr( const ExtendedClientMsgHdr_t *pMsgHdr ); - - -const char *PchStringFromData( const uint8 *pData, uint32 cubData ); - -const char *PchNameFromEMsg( EMsg eMsg ); -const char *PchNameFromNetFlags( uint32 netFlags ); -const char *PchNameFromEUDPPktType( EUDPPktType eUdpPktType ); - -const char *PchNameFromEUniverse( EUniverse eUniverse ); -const char *PchNameFromEResult( EResult eResult ); -const char *PchNameFromEAccountType( EAccountType eAccountType ); - -const char *PchStringFromSockAddr( const sockaddr_in *sockAddr ); - - -#endif // !UTILS_H_ - diff --git a/Resources/NetHook/zdll.lib b/Resources/NetHook/zdll.lib deleted file mode 100644 index d6ff1bf4..00000000 Binary files a/Resources/NetHook/zdll.lib and /dev/null differ diff --git a/Resources/NetHook/zip.cpp b/Resources/NetHook/zip.cpp deleted file mode 100644 index 68724f15..00000000 --- a/Resources/NetHook/zip.cpp +++ /dev/null @@ -1,73 +0,0 @@ - -#include "zip.h" -#include "logger.h" - -#include "zlib/zlib.h" - - -#pragma pack( push, 1 ) - -struct LocalFileHeader -{ - uint32 m_Signature; - - uint16 m_VersionNeededToExtract; - uint16 m_GeneralPurposeBitFlag; - - uint16 m_CompressionMethod; - - uint16 m_LastModFileTime; - uint16 m_LastModFileDate; - - uint32 m_Crc32; - - uint32 m_CompressedSize; - uint32 m_UncompressedSize; - - uint16 m_FileNameLength; - uint16 m_ExtraFieldLength; -}; - -#pragma pack( pop ) - - -bool CZip::Inflate( const uint8 *pCompressed, uint32 cubCompressed, uint8 *pDecompressed, uint32 cubDecompressed ) -{ - LocalFileHeader *fileHeader = (LocalFileHeader *)pCompressed; - - uint32 offsetStart = sizeof( LocalFileHeader ) + fileHeader->m_FileNameLength +fileHeader->m_ExtraFieldLength; - uint32 dataSize = fileHeader->m_CompressedSize; - - return CZip::InternalInflate( pCompressed + offsetStart, dataSize, pDecompressed, cubDecompressed ); -} - -bool CZip::InternalInflate( const uint8 *pCompressed, uint32 cubCompressed, uint8 *pDecompressed, uint32 cubDecompressed ) -{ - z_stream zstrm; - - zstrm.zalloc = Z_NULL; - zstrm.zfree = Z_NULL; - zstrm.opaque = Z_NULL; - zstrm.avail_in = 0; - zstrm.next_in = Z_NULL; - - int ret = inflateInit2( &zstrm, -15 ); - - if ( ret != Z_OK ) - return false; - - zstrm.avail_in = cubCompressed; - zstrm.next_in = (Bytef *)pCompressed; - - zstrm.avail_out = cubDecompressed; - zstrm.next_out = pDecompressed; - - ret = inflate( &zstrm, Z_NO_FLUSH ); - - inflateEnd( &zstrm ); - - if ( ret != Z_STREAM_END ) - return false; - - return true; -} diff --git a/Resources/NetHook/zip.h b/Resources/NetHook/zip.h deleted file mode 100644 index 2f050fb0..00000000 --- a/Resources/NetHook/zip.h +++ /dev/null @@ -1,25 +0,0 @@ - -#ifndef ZIP_H_ -#define ZIP_H_ -#ifdef _WIN32 -#pragma once -#endif - - -#include "steam/steamtypes.h" - - -class CZip -{ - -public: - static bool Inflate( const uint8 *pCompressed, uint32 cubCompressed, uint8 *pDecompressed, uint32 cubDecompressed ); - -private: - static bool InternalInflate( const uint8 *pCompressed, uint32 cubCompressed, uint8 *pDecompressed, uint32 cubDecompressed ); - -}; - - -#endif // !ZIP_H_ - diff --git a/Resources/NetHook/zlib.def b/Resources/NetHook/zlib.def deleted file mode 100644 index 03df8bf8..00000000 --- a/Resources/NetHook/zlib.def +++ /dev/null @@ -1,74 +0,0 @@ -LIBRARY -; zlib data compression library - -EXPORTS -; basic functions - zlibVersion - deflate - deflateEnd - inflate - inflateEnd -; advanced functions - deflateSetDictionary - deflateCopy - deflateReset - deflateParams - deflateTune - deflateBound - deflatePrime - deflateSetHeader - inflateSetDictionary - inflateSync - inflateCopy - inflateReset - inflateReset2 - inflatePrime - inflateMark - inflateGetHeader - inflateBack - inflateBackEnd - zlibCompileFlags -; utility functions - compress - compress2 - compressBound - uncompress - gzopen - gzdopen - gzbuffer - gzsetparams - gzread - gzwrite - gzprintf - gzputs - gzgets - gzputc - gzgetc - gzungetc - gzflush - gzseek - gzrewind - gztell - gzoffset - gzeof - gzdirect - gzclose - gzclose_r - gzclose_w - gzerror - gzclearerr -; checksum functions - adler32 - crc32 - adler32_combine - crc32_combine -; various hacks, don't look :) - deflateInit_ - deflateInit2_ - inflateInit_ - inflateInit2_ - inflateBackInit_ - zError - inflateSyncPoint - get_crc_table - inflateUndermine diff --git a/Resources/NetHook/zlib.lib b/Resources/NetHook/zlib.lib deleted file mode 100644 index 7229b87f..00000000 Binary files a/Resources/NetHook/zlib.lib and /dev/null differ diff --git a/Resources/NetHook/zlib/zconf.h b/Resources/NetHook/zlib/zconf.h deleted file mode 100644 index 02ce56c4..00000000 --- a/Resources/NetHook/zlib/zconf.h +++ /dev/null @@ -1,428 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - * Even better than compiling with -DZ_PREFIX would be to use configure to set - * this permanently in zconf.h using "./configure --zprefix". - */ -#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ - -/* all linked symbols */ -# define _dist_code z__dist_code -# define _length_code z__length_code -# define _tr_align z__tr_align -# define _tr_flush_block z__tr_flush_block -# define _tr_init z__tr_init -# define _tr_stored_block z__tr_stored_block -# define _tr_tally z__tr_tally -# define adler32 z_adler32 -# define adler32_combine z_adler32_combine -# define adler32_combine64 z_adler32_combine64 -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define crc32 z_crc32 -# define crc32_combine z_crc32_combine -# define crc32_combine64 z_crc32_combine64 -# define deflate z_deflate -# define deflateBound z_deflateBound -# define deflateCopy z_deflateCopy -# define deflateEnd z_deflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateInit_ z_deflateInit_ -# define deflateParams z_deflateParams -# define deflatePrime z_deflatePrime -# define deflateReset z_deflateReset -# define deflateSetDictionary z_deflateSetDictionary -# define deflateSetHeader z_deflateSetHeader -# define deflateTune z_deflateTune -# define deflate_copyright z_deflate_copyright -# define get_crc_table z_get_crc_table -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite -# define inflate z_inflate -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define inflateBackInit_ z_inflateBackInit_ -# define inflateCopy z_inflateCopy -# define inflateEnd z_inflateEnd -# define inflateGetHeader z_inflateGetHeader -# define inflateInit2_ z_inflateInit2_ -# define inflateInit_ z_inflateInit_ -# define inflateMark z_inflateMark -# define inflatePrime z_inflatePrime -# define inflateReset z_inflateReset -# define inflateReset2 z_inflateReset2 -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateUndermine z_inflateUndermine -# define inflate_copyright z_inflate_copyright -# define inflate_fast z_inflate_fast -# define inflate_table z_inflate_table -# define uncompress z_uncompress -# define zError z_zError -# define zcalloc z_zcalloc -# define zcfree z_zcfree -# define zlibCompileFlags z_zlibCompileFlags -# define zlibVersion z_zlibVersion - -/* all zlib typedefs in zlib.h and zconf.h */ -# define Byte z_Byte -# define Bytef z_Bytef -# define alloc_func z_alloc_func -# define charf z_charf -# define free_func z_free_func -# define gzFile z_gzFile -# define gz_header z_gz_header -# define gz_headerp z_gz_headerp -# define in_func z_in_func -# define intf z_intf -# define out_func z_out_func -# define uInt z_uInt -# define uIntf z_uIntf -# define uLong z_uLong -# define uLongf z_uLongf -# define voidp z_voidp -# define voidpc z_voidpc -# define voidpf z_voidpf - -/* all zlib structs in zlib.h and zconf.h */ -# define gz_header_s z_gz_header_s -# define internal_state z_internal_state - -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ -# define Z_HAVE_UNISTD_H -#endif - -#ifdef STDC -# include /* for off_t */ -#endif - -/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and - * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even - * though the former does not conform to the LFS document), but considering - * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as - * equivalently requesting no 64-bit operations - */ -#if -_LARGEFILE64_SOURCE - -1 == 1 -# undef _LARGEFILE64_SOURCE -#endif - -#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t -# endif -#endif - -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif - -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 -# define z_off64_t off64_t -#else -# define z_off64_t z_off_t -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) - #pragma map(deflateInit_,"DEIN") - #pragma map(deflateInit2_,"DEIN2") - #pragma map(deflateEnd,"DEEND") - #pragma map(deflateBound,"DEBND") - #pragma map(inflateInit_,"ININ") - #pragma map(inflateInit2_,"ININ2") - #pragma map(inflateEnd,"INEND") - #pragma map(inflateSync,"INSY") - #pragma map(inflateSetDictionary,"INSEDI") - #pragma map(compressBound,"CMBND") - #pragma map(inflate_table,"INTABL") - #pragma map(inflate_fast,"INFA") - #pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/Resources/NetHook/zlib/zlib.h b/Resources/NetHook/zlib/zlib.h deleted file mode 100644 index bfbba83e..00000000 --- a/Resources/NetHook/zlib/zlib.h +++ /dev/null @@ -1,1613 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.5, April 19th, 2010 - - Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.5" -#define ZLIB_VERNUM 0x1250 -#define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 5 -#define ZLIB_VER_SUBREVISION 0 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed data. - This version of the library supports only one compression method (deflation) - but other algorithms will be added later and will have the same stream - interface. - - Compression can be done in a single step if the buffers are large enough, - or can be done by repeated calls of the compression function. In the latter - case, the application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never crash - even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has dropped - to zero. It must update next_out and avail_out when avail_out has dropped - to zero. The application must initialize zalloc, zfree and opaque before - calling the init function. All other fields are set by the compression - library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this if - the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers - returned by zalloc for objects of exactly 65536 bytes *must* have their - offset normalized to zero. The default allocation function provided by this - library ensures this (see zutil.c). To reduce memory requirements and avoid - any allocation of 64K objects, at the expense of compression ratio, compile - the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or progress - reports. After compression, total_in holds the total size of the - uncompressed data and may be saved for use in the decompressor (particularly - if the decompressor wants to decompress everything in a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -#define Z_TREES 6 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative values - * are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is not - compatible with the zlib.h header file used by the application. This check - is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. If - zalloc and zfree are set to Z_NULL, deflateInit updates them to use default - allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at all - (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION - requests a default compromise between speed and compression (currently - equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if level is not a valid compression level, or - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). msg is set to null - if there is no error message. deflateInit does not perform any compression: - this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). Some - output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating avail_in or avail_out accordingly; avail_out should - never be zero before the call. The application can consume the compressed - output when it wants, for example when the output buffer is full (avail_out - == 0), or after each call of deflate(). If deflate returns Z_OK and with - zero avail_out, it must be called again after making room in the output - buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumulate before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In - particular avail_in is zero after the call if enough output space has been - provided before the call.) Flushing may degrade compression for some - compression algorithms and so it should be used only when necessary. This - completes the current deflate block and follows it with an empty stored block - that is three bits plus filler bits to the next byte, followed by four bytes - (00 00 ff ff). - - If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the - output buffer, but the output is not aligned to a byte boundary. All of the - input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. - This completes the current deflate block and follows it with an empty fixed - codes block that is 10 bits long. This assures that enough bytes are output - in order for the decompressor to finish the block before the empty fixed code - block. - - If flush is set to Z_BLOCK, a deflate block is completed and emitted, as - for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to - seven bits of the current block are held to be written as the next byte after - the next deflate block is completed. In this case, the decompressor may not - be provided enough bits at this point in order to complete decompression of - the data provided so far to the compressor. It may need to wait for the next - block to be emitted. This is for advanced applications that need to control - the emission of deflate blocks. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there was - enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the stream - are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect the - compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, msg - may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the - exact value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit() does not process any header information -- that is deferred - until inflate() is called. -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing will - resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there is - no more input data or no more space in the output buffer (see below about - the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming more - output, and updating the next_* and avail_* values accordingly. The - application can consume the uncompressed output when it wants, for example - when the output buffer is full (avail_out == 0), or after each call of - inflate(). If inflate returns Z_OK and with zero avail_out, it must be - called again after making room in the output buffer because there might be - more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, - Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() - stop if and when it gets to the next deflate block boundary. When decoding - the zlib or gzip format, this will cause inflate() to return immediately - after the header and before the first block. When doing a raw inflate, - inflate() will go ahead and process the first block, and will return when it - gets to the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 if - inflate() is currently decoding the last block in the deflate stream, plus - 128 if inflate() returned immediately after decoding an end-of-block code or - decoding the complete header up to just before the first byte of the deflate - stream. The end-of-block will not be indicated until all of the uncompressed - data from that block has been written to strm->next_out. The number of - unused bits may in general be greater than seven, except when bit 7 of - data_type is set, in which case the number of unused bits will be less than - eight. data_type is set as noted here every time inflate() returns for all - flush options, and so can be used to determine the amount of currently - consumed input in bits. - - The Z_TREES option behaves as Z_BLOCK does, but it also returns when the - end of each deflate block header is reached, before any actual data in that - block is decoded. This allows the caller to determine the length of the - deflate block header for later use in random access within a deflate block. - 256 is added to the value of strm->data_type when inflate() returns - immediately after reaching the end of the deflate block header. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step (a - single call of inflate), the parameter flush should be set to Z_FINISH. In - this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all the uncompressed data. (The size - of the uncompressed data may have been saved by the compressor for this - purpose.) The next operation on this stream must be inflateEnd to deallocate - the decompression state. The use of Z_FINISH is never required, but can be - used to inform inflate that a faster approach may be used for the single - inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK or Z_TREES is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() can decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically, if requested when - initializing with inflateInit2(). Any information contained in the gzip - header is not retained, so applications that need that information should - instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may - then call inflateSync() to look for a good compression block if a partial - recovery of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any pending - output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by the - caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), no - header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but is - slow and reduces compression ratio; memLevel=9 uses maximum memory for - optimal speed. The default value is 8. See zconf.h for total memory usage - as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as - fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The - strategy parameter only affects the compression ratio but not the - correctness of the compressed output even if it is not set appropriately. - Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler - decoder for special applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid - method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is - incompatible with the version assumed by the caller (ZLIB_VERSION). msg is - set to null if there is no error message. deflateInit2 does not perform any - compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any call - of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size - provided in deflateInit or deflateInit2. Thus the strings most likely to be - useful should be put at the end of the dictionary, not at the front. In - addition, the current implementation of deflate will use at most the window - size minus 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and can - consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. The - stream will keep the same compression level and any other attributes that - may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different strategy. - If the compression level is changed, the input available so far is - compressed with the old level (and may be flushed); the new level will take - effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to be - compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if - strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the bits - leftover from a previous deflate stream when appending to it. As such, this - function can only be used for raw deflate, and must be used before the first - deflate() call after a deflateInit2() or deflateReset(). bits must be less - than or equal to 16, and that many of the least significant bits of value - will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be zero to request that inflate use the window size in - the zlib header of the compressed stream. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a - crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller, or Z_STREAM_ERROR if the parameters are - invalid, such as a null pointer to the structure. msg is set to null if - there is no error message. inflateInit2 does not perform any decompression - apart from possibly reading the zlib header if present: actual decompression - will be done by inflate(). (So next_in and avail_in may be modified, but - next_out and avail_out are unused and unchanged.) The current implementation - of inflateInit2() does not process any header information -- that is - deferred until inflate() is called. -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been - found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the - success case, the application may save the current current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. The - stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL). -*/ - -ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, - int windowBits)); -/* - This function is the same as inflateReset, but it also permits changing - the wrap and window size requests. The windowBits parameter is interpreted - the same as it is for inflateInit2. - - inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being Z_NULL), or if - the windowBits parameter is invalid. -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - If bits is negative, then the input stream bit buffer is emptied. Then - inflatePrime() can be called again to put bits in the buffer. This is used - to clear out bits leftover after feeding inflate a block description prior - to feeding inflate codes. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); -/* - This function returns two values, one in the lower 16 bits of the return - value, and the other in the remaining upper bits, obtained by shifting the - return value down 16 bits. If the upper value is -1 and the lower value is - zero, then inflate() is currently decoding information outside of a block. - If the upper value is -1 and the lower value is non-zero, then inflate is in - the middle of a stored block, with the lower value equaling the number of - bytes from the input remaining to copy. If the upper value is not -1, then - it is the number of bits back from the current bit position in the input of - the code (literal or length/distance pair) currently being processed. In - that case the lower value is the number of bytes already emitted for that - code. - - A code is being processed if inflate is waiting for more input to complete - decoding of the code, or if it has completed decoding but is waiting for - more output space to write the literal or match data. - - inflateMark() is used to mark locations in the input data for random - access, which may be at bit positions, and to note those cases where the - output of a code may span boundaries of random access blocks. The current - location in the input stream can be determined from avail_in and data_type - as noted in the description for the Z_BLOCK flush parameter for inflate. - - inflateMark returns the value noted above or -1 << 16 if the provided - source stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be - used to force inflate() to return immediately after header processing is - complete and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When any - of extra, name, or comment are not Z_NULL and the respective field is not - present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not be - allocated, or Z_VERSION_ERROR if the version of the library does not match - the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free the - allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects only - the raw deflate stream to decompress. This is different from the normal - behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format error - in the deflate stream (in which case strm->msg is set to indicate the nature - of the error), or Z_STREAM_ERROR if the stream was not properly initialized. - In the case of Z_BUF_ERROR, an input or output error can be distinguished - using strm->next_in which will be Z_NULL only if in() returned an error. If - strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning - non-zero. (in() will always be called before out(), so strm->next_in is - assured to be defined if out() returns non-zero.) Note that inflateBack() - cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the basic - stream-oriented functions. To simplify the interface, some default options - are assumed (compression level and memory usage, standard memory allocation - functions). The source code of these utility functions can be modified if - you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before a - compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total size - of the destination buffer, which must be large enough to hold the entire - uncompressed data. (The size of the uncompressed data must have been saved - previously by the compressor and transmitted to the decompressor by some - mechanism outside the scope of this compression library.) Upon exit, destLen - is the actual size of the uncompressed buffer. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - - /* gzip file access functions */ - -/* - This library supports reading and writing files in gzip (.gz) format with - an interface similar to that of stdio, using the functions that start with - "gz". The gzip format is different from the zlib format. gzip is a gzip - wrapper, documented in RFC 1952, wrapped around a deflate stream. -*/ - -typedef voidp gzFile; /* opaque gzip file descriptor */ - -/* -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); - - Opens a gzip (.gz) file for reading or writing. The mode parameter is as - in fopen ("rb" or "wb") but can also include a compression level ("wb9") or - a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only - compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' - for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) Also "a" - can be used instead of "w" to request that the gzip stream that will be - written be appended to the file. "+" will result in an error, since reading - and writing to the same gzip file is not supported. - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened, if there was - insufficient memory to allocate the gzFile state, or if an invalid mode was - specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). - errno can be checked to determine if the reason gzopen failed was that the - file could not be opened. -*/ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen associates a gzFile with the file descriptor fd. File descriptors - are obtained from calls like open, dup, creat, pipe or fileno (if the file - has been previously opened with fopen). The mode parameter is as in gzopen. - - The next call of gzclose on the returned gzFile will also close the file - descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor - fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, - mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. - - gzdopen returns NULL if there was insufficient memory to allocate the - gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not - provided, or '+' was provided), or if fd is -1. The file descriptor is not - used until the next gz* read, write, seek, or close operation, so gzdopen - will not detect if fd is invalid (unless fd is -1). -*/ - -ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); -/* - Set the internal buffer size used by this library's functions. The - default buffer size is 8192 bytes. This function must be called after - gzopen() or gzdopen(), and before any other calls that read or write the - file. The buffer memory allocation is always deferred to the first read or - write. Two buffers are allocated, either both of the specified size when - writing, or one of the specified size and the other twice that size when - reading. A larger buffer size of, for example, 64K or 128K bytes will - noticeably increase the speed of decompression (reading). - - The new buffer size also affects the maximum length for gzprintf(). - - gzbuffer() returns 0 on success, or -1 on failure, such as being called - too late. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. If - the input file was not in gzip format, gzread copies the given number of - bytes into the buffer. - - After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream, or failing that, reading the rest - of the input file directly without decompression. The entire input file - will be read if gzread is called until it returns less than the requested - len. - - gzread returns the number of uncompressed bytes actually read, less than - len for end of file, or -1 for error. -*/ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes written or 0 in case of - error. -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the arguments to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written, or 0 in case of error. The number of - uncompressed bytes written is limited to 8191, or one less than the buffer - size given to gzbuffer(). The caller should assure that this limit is not - exceeded. If it is exceeded, then gzprintf() will return an error (0) with - nothing written. In this case, there may also be a buffer overflow with - unpredictable consequences, which is possible only if zlib was compiled with - the insecure functions sprintf() or vsprintf() because the secure snprintf() - or vsnprintf() functions were not available. This can be determined using - zlibCompileFlags(). -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or a - newline character is read and transferred to buf, or an end-of-file - condition is encountered. If any characters are read or if len == 1, the - string is terminated with a null character. If no characters are read due - to an end-of-file or len < 1, then the buffer is left untouched. - - gzgets returns buf which is a null-terminated string, or it returns NULL - for end-of-file or in case of error. If there was an error, the contents at - buf are indeterminate. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. gzputc - returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read as the first character - on the next read. At least one character of push-back is allowed. - gzungetc() returns the character pushed, or -1 on failure. gzungetc() will - fail if c is -1, and may fail if a character has been pushed but not read - yet. If gzungetc is used immediately after gzopen or gzdopen, at least the - output buffer size of pushed characters is allowed. (See gzbuffer above.) - The pushed character will be discarded if the stream is repositioned with - gzseek() or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter flush - is as in the deflate() function. The return value is the zlib error number - (see function gzerror below). gzflush is only permitted when writing. - - If the flush parameter is Z_FINISH, the remaining data is written and the - gzip stream is completed in the output. If gzwrite() is called again, a new - gzip stream will be started in the output. gzread() is able to read such - concatented gzip streams. - - gzflush should be called only when strictly necessary because it will - degrade compression if called too often. -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); - - Sets the starting position for the next gzread or gzwrite on the given - compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); - - Returns the starting position for the next gzread or gzwrite on the given - compressed file. This position represents a number of bytes in the - uncompressed data stream, and is zero when starting, even if appending or - reading a gzip stream from the middle of a file using gzdopen(). - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -/* -ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); - - Returns the current offset in the file being read or written. This offset - includes the count of bytes that precede the gzip stream, for example when - appending or when using gzdopen() for reading. When reading, the offset - does not include as yet unused buffered input. This information can be used - for a progress indicator. On error, gzoffset() returns -1. -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns true (1) if the end-of-file indicator has been set while reading, - false (0) otherwise. Note that the end-of-file indicator is set only if the - read tried to go past the end of the input, but came up short. Therefore, - just like feof(), gzeof() may return false even if there is no more data to - read, in the event that the last read request was for the exact number of - bytes remaining in the input file. This will happen if the input file size - is an exact multiple of the buffer size. - - If gzeof() returns true, then the read functions will return no more data, - unless the end-of-file indicator is reset by gzclearerr() and the input file - has grown since the previous end of file was detected. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. This state can change from - false to true while reading the input file if the end of a gzip stream is - reached, but is followed by data that is not another gzip stream. - - If the input file is empty, gzdirect() will return true, since the input - does not contain a gzip stream. - - If gzdirect() is used immediately after gzopen() or gzdopen() it will - cause buffers to be allocated to allow reading the file to determine if it - is a gzip file. Therefore if gzbuffer() is used, it should be called before - gzdirect(). -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file and - deallocates the (de)compression state. Note that once file is closed, you - cannot call gzerror with file, since its structures have been deallocated. - gzclose must not be called more than once on the same file, just as free - must not be called more than once on the same allocation. - - gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, or Z_OK on success. -*/ - -ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); -ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); -/* - Same as gzclose(), but gzclose_r() is only for use when reading, and - gzclose_w() is only for use when writing or appending. The advantage to - using these instead of gzclose() is that they avoid linking in zlib - compression or decompression code that is not used when only reading or only - writing respectively. If gzclose() is used, then both compression and - decompression code will be included the application when linking to a static - zlib library. -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the given - compressed file. errnum is set to zlib error number. If an error occurred - in the file system and not in the compression library, errnum is set to - Z_ERRNO and the application may consult errno to get the exact error code. - - The application must not modify the returned string. Future calls to - this function may invalidate the previously returned string. If file is - closed, then the string previously returned by gzerror will no longer be - available. - - gzerror() should be used to distinguish errors from end-of-file for those - functions above that do not distinguish those cases in their return values. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the compression - library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is Z_NULL, this function returns the - required initial value for the checksum. - - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. - - Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); - - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the for the crc. Pre- and post-conditioning (one's - complement) is performed within this function so it shouldn't be done by the - application. - - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -/* -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - -/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or - * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if - * both are true, the application gets the *64 functions, and the regular - * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true - */ -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); - ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); -#endif - -#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# ifdef _LARGEFILE64_SOURCE - ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); -# endif -#else - ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); - ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); - ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); - ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); - ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); - ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); -#endif - -/* hack for buggy compilers */ -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; -#endif - -/* undocumented functions */ -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); -ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/Resources/NetHook/zlib1.dll b/Resources/NetHook/zlib1.dll deleted file mode 100644 index 869b00d4..00000000 Binary files a/Resources/NetHook/zlib1.dll and /dev/null differ