Clean up code formatting with clang-format; add a custom clang-format style that tries to approximate the existing OST code style

This commit is contained in:
Brian Cox 2018-03-24 21:28:30 -07:00
parent 184b260d9f
commit ccf8a62fa4
423 changed files with 25182 additions and 25131 deletions

115
.clang-format Normal file
View File

@ -0,0 +1,115 @@
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: true
BeforeElse: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
BreakBeforeInheritanceComma: false
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
IndentPPDirectives: AfterHash
IndentWidth: 4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
RawStringFormats:
- Delimiter: pb
Language: TextProto
BasedOnStyle: google
ReflowComments: false
SortIncludes: false
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 4
UseTab: Never
...

View File

@ -1,2 +1 @@
#define BUILD_NUM _T("0") #define BUILD_NUM _T("0")

View File

@ -49,15 +49,15 @@
#include "file.h" #include "file.h"
#include "stringutil.h" #include "stringutil.h"
#include "corestrings.h" // for: STR_ERR2_ARCH_CRYPTO_ERR #include "corestrings.h" // for: STR_ERR2_ARCH_CRYPTO_ERR
//============================================================================= //=============================================================================
// eArchiveCrypto // eArchiveCrypto
//============================================================================= //=============================================================================
TSTRING eArchiveCrypto::GetMsg( ) const TSTRING eArchiveCrypto::GetMsg() const
{ {
// RAD: Updated this to use new stringtable // RAD: Updated this to use new stringtable
return ( mMsg + TSS_GetString( cCore, core::STR_ERR2_ARCH_CRYPTO_ERR ) ); return (mMsg + TSS_GetString(cCore, core::STR_ERR2_ARCH_CRYPTO_ERR));
} }
@ -113,25 +113,25 @@ void cArchive::ReadString(TSTRING& ret) // throw(eArchive)
{ {
// read in size of string // read in size of string
int16 size; int16 size;
ReadInt16( size ); ReadInt16(size);
// create buffer for WCHAR16 string // create buffer for WCHAR16 string
wc16_string ws; wc16_string ws;
ws.resize( size ); ws.resize(size);
WCHAR16* pwc = (WCHAR16*)ws.data(); WCHAR16* pwc = (WCHAR16*)ws.data();
for( int n = 0; n < size; n++ ) for (int n = 0; n < size; n++)
{ {
int16 i16; int16 i16;
ReadInt16( i16 ); ReadInt16(i16);
*pwc++ = i16; *pwc++ = i16;
} }
// convert WCHAR16 string to a TSTRING // convert WCHAR16 string to a TSTRING
ret = cStringUtil::WstrToTstr( ws ); ret = cStringUtil::WstrToTstr(ws);
} }
int cArchive::ReadBlob(void* pBlob, int count) int cArchive::ReadBlob(void* pBlob, int count)
{ {
return Read(pBlob, count); return Read(pBlob, count);
} }
@ -163,20 +163,20 @@ void cArchive::WriteString(TSTRING s) // throw(eArchive)
{ {
// convert string to a UCS2 string // convert string to a UCS2 string
wc16_string ws; wc16_string ws;
cStringUtil::Convert( ws, s ); // Make convert "type-dispatched" cStringUtil::Convert(ws, s); // Make convert "type-dispatched"
// we assume that we can represent the size as a unsigned 16-bit number // we assume that we can represent the size as a unsigned 16-bit number
// (we actually write it as a signed number, but we cast it) // (we actually write it as a signed number, but we cast it)
if( ws.length() > TSS_INT16_MAX ) if (ws.length() > TSS_INT16_MAX)
ThrowAndAssert( eArchiveStringTooLong() ); ThrowAndAssert(eArchiveStringTooLong());
WriteInt16( static_cast<int16>( ws.length() ) ); WriteInt16(static_cast<int16>(ws.length()));
// write out each 16 bit character // write out each 16 bit character
// RAD:09/03/99 -- Optimized for performance with "const" // RAD:09/03/99 -- Optimized for performance with "const"
wc16_string::const_iterator at = ws.begin(); wc16_string::const_iterator at = ws.begin();
while ( at != ws.end() ) while (at != ws.end())
WriteInt16( *at++ ); WriteInt16(*at++);
} }
@ -193,24 +193,27 @@ int32 cArchive::GetStorageSize(const TSTRING& str)
// after the length, all of the characters in the string are written as 16-bit values, // after the length, all of the characters in the string are written as 16-bit values,
// except for the null character // except for the null character
// //
size += ( str.length() * 2 ); size += (str.length() * 2);
return size; return size;
} }
int64 cArchive::Copy(cArchive* pFrom, int64 amt) int64 cArchive::Copy(cArchive* pFrom, int64 amt)
{ {
enum { BUF_SIZE = 2048 }; enum
int8 buf[BUF_SIZE]; {
int64 amtLeft = amt; BUF_SIZE = 2048
};
int8 buf[BUF_SIZE];
int64 amtLeft = amt;
while(amtLeft > 0) while (amtLeft > 0)
{ {
int64 amtToRead = amtLeft > (int64)BUF_SIZE ? (int64)BUF_SIZE : amtLeft; int64 amtToRead = amtLeft > (int64)BUF_SIZE ? (int64)BUF_SIZE : amtLeft;
int64 amtRead = pFrom->ReadBlob(buf, static_cast<int>( amtToRead ) ); int64 amtRead = pFrom->ReadBlob(buf, static_cast<int>(amtToRead));
amtLeft -= amtRead; amtLeft -= amtRead;
WriteBlob(buf, static_cast<int>( amtRead ) ); WriteBlob(buf, static_cast<int>(amtRead));
if(amtRead < amtToRead) if (amtRead < amtToRead)
break; break;
} }
@ -224,7 +227,7 @@ int64 cArchive::Copy(cArchive* pFrom, int64 amt)
cMemMappedArchive::cMemMappedArchive() cMemMappedArchive::cMemMappedArchive()
{ {
mpMappedMem = 0; mpMappedMem = 0;
mMappedOffset = 0; mMappedOffset = 0;
mMappedLength = 0; mMappedLength = 0;
} }
@ -269,13 +272,13 @@ void cMemMappedArchive::SetNewMap(void* pMap, int64 offset, int64 length) const
{ {
if (pMap == 0) if (pMap == 0)
{ {
mpMappedMem = 0; mpMappedMem = 0;
mMappedOffset = 0; mMappedOffset = 0;
mMappedLength = 0; mMappedLength = 0;
} }
else else
{ {
mpMappedMem = pMap; mpMappedMem = pMap;
mMappedOffset = offset; mMappedOffset = offset;
mMappedLength = length; mMappedLength = length;
} }
@ -288,14 +291,13 @@ void cMemMappedArchive::SetNewMap(void* pMap, int64 offset, int64 length) const
// mapped. // mapped.
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
cMemoryArchive::cMemoryArchive(int maxSize) cMemoryArchive::cMemoryArchive(int maxSize) : mMaxAllocatedLen(maxSize)
: mMaxAllocatedLen(maxSize)
{ {
ASSERT(maxSize > 0); ASSERT(maxSize > 0);
mpMemory = 0; mpMemory = 0;
mAllocatedLen = 0; mAllocatedLen = 0;
mLogicalSize = 0; mLogicalSize = 0;
mReadHead = 0; mReadHead = 0;
} }
cMemoryArchive::~cMemoryArchive() cMemoryArchive::~cMemoryArchive()
@ -321,13 +323,15 @@ void cMemoryArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive)
offset = mLogicalSize + (int)offset; offset = mLogicalSize + (int)offset;
break; break;
default: default:
ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME),
TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR)));
} }
if (offset > mLogicalSize) if (offset > mLogicalSize)
ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME),
TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR)));
mReadHead = static_cast<int>( offset ); mReadHead = static_cast<int>(offset);
} }
int64 cMemoryArchive::CurrentPos() const int64 cMemoryArchive::CurrentPos() const
@ -350,8 +354,8 @@ void cMemoryArchive::Truncate()
void cMemoryArchive::MapArchive(int64 offset, int64 len) // throw(eArchive) void cMemoryArchive::MapArchive(int64 offset, int64 len) // throw(eArchive)
{ {
if ( offset + (int)len > mLogicalSize ) if (offset + (int)len > mLogicalSize)
AllocateMemory( static_cast<int>( offset + len ) ); AllocateMemory(static_cast<int>(offset + len));
SetNewMap(mpMemory + offset, offset, len); SetNewMap(mpMemory + offset, offset, len);
} }
@ -404,7 +408,7 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive)
ThrowAndAssert(eArchiveOutOfMem()); ThrowAndAssert(eArchiveOutOfMem());
#endif #endif
if( 0 == mAllocatedLen ) if (0 == mAllocatedLen)
mAllocatedLen = MIN_ALLOCATED_SIZE; mAllocatedLen = MIN_ALLOCATED_SIZE;
while (mAllocatedLen < len) while (mAllocatedLen < len)
@ -416,7 +420,7 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive)
memcpy(pNewMem, mpMemory, mLogicalSize); memcpy(pNewMem, mpMemory, mLogicalSize);
delete [] mpMemory; delete [] mpMemory;
} }
mpMemory = pNewMem; mpMemory = pNewMem;
mLogicalSize = len; mLogicalSize = len;
// update memory map if there is one // update memory map if there is one
@ -436,7 +440,7 @@ void cMemoryArchive::AllocateMemory(int len) // throw(eArchive)
ASSERT(mpMemory); ASSERT(mpMemory);
memcpy(pNewMem, mpMemory, len); memcpy(pNewMem, mpMemory, len);
delete [] mpMemory; delete [] mpMemory;
mpMemory = pNewMem; mpMemory = pNewMem;
mLogicalSize = len; mLogicalSize = len;
// update memory map if there is one // update memory map if there is one
@ -464,33 +468,27 @@ public:
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// cFixedMemArchive // cFixedMemArchive
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
cFixedMemArchive::cFixedMemArchive() cFixedMemArchive::cFixedMemArchive() : mpMemory(0), mSize(0), mReadHead(0)
: mpMemory (0),
mSize (0),
mReadHead (0)
{ {
} }
cFixedMemArchive::cFixedMemArchive( int8* pMem, int32 size ) cFixedMemArchive::cFixedMemArchive(int8* pMem, int32 size) : mpMemory(0), mSize(0), mReadHead(0)
: mpMemory (0),
mSize (0),
mReadHead (0)
{ {
Attach( pMem, size ); Attach(pMem, size);
} }
cFixedMemArchive::~cFixedMemArchive() cFixedMemArchive::~cFixedMemArchive()
{ {
} }
void cFixedMemArchive::Attach( int8* pMem, int32 size ) void cFixedMemArchive::Attach(int8* pMem, int32 size)
{ {
mpMemory = pMem; mpMemory = pMem;
mSize = size; mSize = size;
mReadHead = 0; mReadHead = 0;
} }
void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive) void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive)
{ {
switch (from) switch (from)
{ {
@ -503,13 +501,15 @@ void cFixedMemArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive)
offset = mSize + (int)offset; offset = mSize + (int)offset;
break; break;
default: default:
ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME),
TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR)));
} }
if (offset > mSize) if (offset > mSize)
ThrowAndAssert(eArchiveSeek(TSS_GetString( cCore, core::STR_MEMARCHIVE_FILENAME), TSS_GetString( cCore, core::STR_MEMARCHIVE_ERRSTR))); ThrowAndAssert(eArchiveSeek(TSS_GetString(cCore, core::STR_MEMARCHIVE_FILENAME),
TSS_GetString(cCore, core::STR_MEMARCHIVE_ERRSTR)));
mReadHead = static_cast<int32>( offset ); mReadHead = static_cast<int32>(offset);
} }
int64 cFixedMemArchive::CurrentPos() const int64 cFixedMemArchive::CurrentPos() const
@ -527,12 +527,12 @@ bool cFixedMemArchive::EndOfFile()
return (mReadHead >= mSize); return (mReadHead >= mSize);
} }
int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive) int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive)
{ {
ASSERT( pDest ); ASSERT(pDest);
if (mReadHead + count > mSize) if (mReadHead + count > mSize)
{ {
count = static_cast<int>( mSize - mReadHead ); count = static_cast<int>(mSize - mReadHead);
if (count <= 0) if (count <= 0)
return 0; return 0;
} }
@ -545,11 +545,11 @@ int cFixedMemArchive::Read(void* pDest, int count) // throw(eArchive)
return count; return count;
} }
int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive) int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive)
{ {
if (mReadHead + count > mSize) if (mReadHead + count > mSize)
{ {
ASSERT( false ); ASSERT(false);
throw eArchiveWrite(); throw eArchiveWrite();
} }
@ -566,11 +566,9 @@ int cFixedMemArchive::Write(const void* pDest, int count) // throw(eArchive)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
//Ctor -- Initialize member variables to 0 or NULL equivalents. //Ctor -- Initialize member variables to 0 or NULL equivalents.
cFileArchive::cFileArchive() : cFileArchive::cFileArchive() : mFileSize(0), mReadHead(0), isWritable(false)
mFileSize(0), {
mReadHead(0), }
isWritable(false)
{}
cFileArchive::~cFileArchive() cFileArchive::~cFileArchive()
{ {
@ -578,14 +576,14 @@ cFileArchive::~cFileArchive()
bool cFileArchive::EndOfFile() bool cFileArchive::EndOfFile()
{ {
return ( mReadHead >= mFileSize ); return (mReadHead >= mFileSize);
} }
//////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////
// Seek -- This is where the actual offset is performed. The default // Seek -- This is where the actual offset is performed. The default
// for each archive will be 0. // for each archive will be 0.
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
void cFileArchive::Seek( int64 offset, SeekFrom from) // throw(eArchive) void cFileArchive::Seek(int64 offset, SeekFrom from) // throw(eArchive)
{ {
try try
{ {
@ -600,19 +598,19 @@ void cFileArchive::Seek( int64 offset, SeekFrom from) // throw(eArchive)
offset = mFileSize + offset; offset = mFileSize + offset;
break; break;
default: default:
throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ; throw eArchiveSeek(mCurrentFilename, iFSServices::GetInstance()->GetErrString());
} }
if ( offset > mFileSize ) if (offset > mFileSize)
throw eArchiveSeek( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ; throw eArchiveSeek(mCurrentFilename, iFSServices::GetInstance()->GetErrString());
mReadHead = offset; mReadHead = offset;
mCurrentFile.Seek(mReadHead, cFile::SEEK_BEGIN); mCurrentFile.Seek(mReadHead, cFile::SEEK_BEGIN);
//This is where the actual read/writehead is set!! //This is where the actual read/writehead is set!!
}//try } //try
catch( eFile& fileError ) catch (eFile& fileError)
{ {
throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveSeek(mCurrentFilename, fileError.GetDescription()));
} }
} }
@ -630,9 +628,9 @@ int64 cFileArchive::Length(void) const
{ {
return mCurrentFile.GetSize(); return mCurrentFile.GetSize();
} }
catch(eFile& fileError) catch (eFile& fileError)
{ {
throw( eArchiveSeek( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveSeek(mCurrentFilename, fileError.GetDescription()));
} }
} }
@ -645,22 +643,22 @@ void cFileArchive::OpenRead(const TCHAR* filename, uint32 openFlags)
{ {
// set up open flags // set up open flags
uint32 flags = cFile::OPEN_READ; uint32 flags = cFile::OPEN_READ;
flags |= ( ( openFlags & FA_OPEN_TRUNCATE ) ? cFile::OPEN_TRUNCATE : 0 ); flags |= ((openFlags & FA_OPEN_TRUNCATE) ? cFile::OPEN_TRUNCATE : 0);
flags |= ( ( openFlags & FA_OPEN_TEXT ) ? cFile::OPEN_TEXT : 0 ); flags |= ((openFlags & FA_OPEN_TEXT) ? cFile::OPEN_TEXT : 0);
flags |= ( ( openFlags & FA_SCANNING ) ? cFile::OPEN_SCANNING : 0 ); flags |= ((openFlags & FA_SCANNING) ? cFile::OPEN_SCANNING : 0);
flags |= ( ( openFlags & FA_DIRECT ) ? cFile::OPEN_DIRECT : 0 ); flags |= ((openFlags & FA_DIRECT) ? cFile::OPEN_DIRECT : 0);
mOpenFlags = openFlags; mOpenFlags = openFlags;
mCurrentFilename = filename; mCurrentFilename = filename;
mCurrentFile.Open( filename, flags ); mCurrentFile.Open(filename, flags);
isWritable = false; isWritable = false;
mFileSize = mCurrentFile.GetSize(); mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN ); mReadHead = mCurrentFile.Seek(0, cFile::SEEK_BEGIN);
} }
catch(eFile& fileError) catch (eFile& fileError)
{ {
throw(eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveOpen(mCurrentFilename, fileError.GetDescription()));
} }
} }
@ -673,22 +671,22 @@ void cFileArchive::OpenReadWrite(const TCHAR* filename, uint32 openFlags)
{ {
// set up open flags // set up open flags
uint32 flags = cFile::OPEN_WRITE; uint32 flags = cFile::OPEN_WRITE;
flags |= ( ( openFlags & FA_OPEN_TRUNCATE ) ? cFile::OPEN_TRUNCATE : 0 ); flags |= ((openFlags & FA_OPEN_TRUNCATE) ? cFile::OPEN_TRUNCATE : 0);
flags |= ( ( openFlags & FA_OPEN_TEXT ) ? cFile::OPEN_TEXT : 0 ); flags |= ((openFlags & FA_OPEN_TEXT) ? cFile::OPEN_TEXT : 0);
flags |= ( ( openFlags & FA_SCANNING ) ? cFile::OPEN_SCANNING : 0 ); flags |= ((openFlags & FA_SCANNING) ? cFile::OPEN_SCANNING : 0);
flags |= ( ( openFlags & FA_DIRECT ) ? cFile::OPEN_DIRECT : 0 ); flags |= ((openFlags & FA_DIRECT) ? cFile::OPEN_DIRECT : 0);
mOpenFlags = openFlags; mOpenFlags = openFlags;
mCurrentFilename = filename; mCurrentFilename = filename;
mCurrentFile.Open( filename, flags ); mCurrentFile.Open(filename, flags);
isWritable = true; isWritable = true;
mFileSize = mCurrentFile.GetSize(); mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN ); mReadHead = mCurrentFile.Seek(0, cFile::SEEK_BEGIN);
} }
catch(eFile& fileError) catch (eFile& fileError)
{ {
throw( eArchiveOpen( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveOpen(mCurrentFilename, fileError.GetDescription()));
} }
} }
@ -709,14 +707,14 @@ void cFileArchive::Close()
try try
{ {
mCurrentFile.Close(); mCurrentFile.Close();
mFileSize = 0; mFileSize = 0;
mReadHead = 0; mReadHead = 0;
mCurrentFilename = _T(""); mCurrentFilename = _T("");
} }
catch(eFile& fileError) catch (eFile& fileError)
{ {
throw( eArchive( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchive(mCurrentFilename, fileError.GetDescription()));
} }
} }
@ -729,43 +727,42 @@ int cFileArchive::Read(void* pDest, int count)
try try
{ {
if ( mReadHead + count > mFileSize && !(mOpenFlags & FA_DIRECT)) if (mReadHead + count > mFileSize && !(mOpenFlags & FA_DIRECT))
count = static_cast<int>( mFileSize - mReadHead ); count = static_cast<int>(mFileSize - mReadHead);
if ( pDest != NULL ) if (pDest != NULL)
{ {
int nbRead = int nbRead = static_cast<int>(mCurrentFile.Read(pDest, count));
static_cast<int>( mCurrentFile.Read( pDest, count ) );
// 'count' may not be equal to 'nbRead' if the file is open in // 'count' may not be equal to 'nbRead' if the file is open in
// text mode. // text mode.
count = nbRead; count = nbRead;
if(count < 0) count = 0; if (count < 0)
count = 0;
} }
else else
{ {
int i; int i;
int32 dummy; int32 dummy;
for (i = count; ; i -= sizeof(int32)) for (i = count;; i -= sizeof(int32))
{ {
if (i < (int)sizeof(int32)) if (i < (int)sizeof(int32))
{ {
if (i > 0) if (i > 0)
mCurrentFile.Read( &dummy, i ); mCurrentFile.Read(&dummy, i);
break; break;
} }
mCurrentFile.Read( &dummy, i ); mCurrentFile.Read(&dummy, i);
} }
} }
mReadHead += count; mReadHead += count;
return count; return count;
} }
catch( eFile& fileError ) catch (eFile& fileError)
{ {
throw( eArchiveRead( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveRead(mCurrentFilename, fileError.GetDescription()));
} }
} }
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
@ -777,35 +774,35 @@ int cFileArchive::Write(const void* pDest, int count) // throw(eArchive)
try try
{ {
int64 actual_count = 0; int64 actual_count = 0;
ASSERT( mCurrentFile.isWritable ); ASSERT(mCurrentFile.isWritable);
actual_count = mCurrentFile.Write( pDest, count ); actual_count = mCurrentFile.Write(pDest, count);
if ( actual_count < count ) if (actual_count < count)
{ {
//Disk full?? //Disk full??
throw eArchiveWrite( mCurrentFilename, iFSServices::GetInstance()->GetErrString() ) ; throw eArchiveWrite(mCurrentFilename, iFSServices::GetInstance()->GetErrString());
} }
// increment the read/write head // increment the read/write head
mReadHead += actual_count; mReadHead += actual_count;
// increase the size, if needed // increase the size, if needed
if( mReadHead > mFileSize ) if (mReadHead > mFileSize)
{ {
#if 0 // IS_SUNPRO #if 0 // IS_SUNPRO \
// These two lines seem to be all there is between code that crashes and code that works for sunpro // These two lines seem to be all there is between code that crashes and code that works for sunpro
cDebug d("cFileArchive::Write()"); cDebug d("cFileArchive::Write()");
d.TraceDebug(_T("file(%s) adjusted mFileSize = %d mReadHead = %d\n"), mCurrentFilename.c_str(), (int)mFileSize, (int)mReadHead); d.TraceDebug(_T("file(%s) adjusted mFileSize = %d mReadHead = %d\n"), mCurrentFilename.c_str(), (int)mFileSize, (int)mReadHead);
#endif #endif
mFileSize = mReadHead; mFileSize = mReadHead;
} }
return (int)actual_count; return (int)actual_count;
} }
catch( eFile& fileError ) catch (eFile& fileError)
{ {
throw( eArchiveWrite( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveWrite(mCurrentFilename, fileError.GetDescription()));
} }
} }
@ -815,89 +812,90 @@ int cFileArchive::Write(const void* pDest, int count) // throw(eArchive)
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
void cFileArchive::Truncate() // throw(eArchive) void cFileArchive::Truncate() // throw(eArchive)
{ {
ASSERT( mCurrentFile.IsOpen() ); ASSERT(mCurrentFile.IsOpen());
ASSERT( mCurrentFile.isWritable ); ASSERT(mCurrentFile.isWritable);
try try
{ {
mCurrentFile.Truncate ( mReadHead ); mCurrentFile.Truncate(mReadHead);
} }
catch( eFile& fileError ) catch (eFile& fileError)
{ {
//TODO: create an error number for truncate... //TODO: create an error number for truncate...
throw( eArchiveWrite( mCurrentFilename, fileError.GetDescription() ) ); throw(eArchiveWrite(mCurrentFilename, fileError.GetDescription()));
} }
mFileSize = mReadHead; mFileSize = mReadHead;
} }
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
// OpenReadWrite -- Opens the file to be read or written to // OpenReadWrite -- Opens the file to be read or written to
// //
// since we'll never open an existing file, the truncateFile flag is unnecessary. // since we'll never open an existing file, the truncateFile flag is unnecessary.
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
void cLockedTemporaryFileArchive::OpenReadWrite( const TCHAR* filename, uint32 openFlags ) void cLockedTemporaryFileArchive::OpenReadWrite(const TCHAR* filename, uint32 openFlags)
{ {
TSTRING strTempFile; TSTRING strTempFile;
try { try
{
ASSERT( !mCurrentFile.IsOpen() ); // shouldn't be able to create a new file when we're already open ASSERT(!mCurrentFile.IsOpen()); // shouldn't be able to create a new file when we're already open
if ( mCurrentFile.IsOpen() ) if (mCurrentFile.IsOpen())
throw( eArchive( mCurrentFilename, _T("Internal Error") ) ); throw(eArchive(mCurrentFilename, _T("Internal Error")));
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// if filename is NULL, create a temp file for the caller // if filename is NULL, create a temp file for the caller
if( filename == NULL ) if (filename == NULL)
{ {
try try
{ {
iFSServices::GetInstance()->GetTempDirName( strTempFile ); iFSServices::GetInstance()->GetTempDirName(strTempFile);
strTempFile += _T("twtempXXXXXX"); strTempFile += _T("twtempXXXXXX");
iFSServices::GetInstance()->MakeTempFilename( strTempFile ); iFSServices::GetInstance()->MakeTempFilename(strTempFile);
} }
catch( eFSServices& fileError) catch (eFSServices& fileError)
{ {
TSTRING errStr = TSS_GetString( cCore, core::STR_BAD_TEMPDIRECTORY ); TSTRING errStr = TSS_GetString(cCore, core::STR_BAD_TEMPDIRECTORY);
throw eArchiveOpen(strTempFile, errStr); throw eArchiveOpen(strTempFile, errStr);
} }
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// create file // create file
// set up flags // set up flags
uint32 flags = cFile::OPEN_WRITE | cFile::OPEN_LOCKED_TEMP | cFile::OPEN_CREATE | cFile::OPEN_EXCLUSIVE; uint32 flags = cFile::OPEN_WRITE | cFile::OPEN_LOCKED_TEMP | cFile::OPEN_CREATE | cFile::OPEN_EXCLUSIVE;
if ( openFlags & FA_OPEN_TRUNCATE ) if (openFlags & FA_OPEN_TRUNCATE)
flags |= cFile::OPEN_TRUNCATE; flags |= cFile::OPEN_TRUNCATE;
if ( openFlags & FA_OPEN_TEXT ) if (openFlags & FA_OPEN_TEXT)
flags |= cFile::OPEN_TEXT; flags |= cFile::OPEN_TEXT;
// open file // open file
mCurrentFilename = filename ? filename : strTempFile.c_str(); mCurrentFilename = filename ? filename : strTempFile.c_str();
mCurrentFile.Open( mCurrentFilename, flags ); mCurrentFile.Open(mCurrentFilename, flags);
isWritable = true; isWritable = true;
mFileSize = mCurrentFile.GetSize(); mFileSize = mCurrentFile.GetSize();
mReadHead = mCurrentFile.Seek( 0, cFile::SEEK_BEGIN ); mReadHead = mCurrentFile.Seek(0, cFile::SEEK_BEGIN);
#if 0 // IS_SUNPRO #if 0 // IS_SUNPRO
cDebug d("cLockedTemporaryFileArchive::OpenReadWrite()"); cDebug d("cLockedTemporaryFileArchive::OpenReadWrite()");
d.TraceDebug(_T("file(%s) set mFileSize to %d mReadHead to %d\n"), mCurrentFilename.c_str(), (int)mFileSize, (int)mReadHead); d.TraceDebug(_T("file(%s) set mFileSize to %d mReadHead to %d\n"), mCurrentFilename.c_str(), (int)mFileSize, (int)mReadHead);
#endif #endif
}//try } //try
catch (eFile& fileError) { catch (eFile& fileError)
TSTRING errStr = TSS_GetString( cCore, core::STR_BAD_TEMPDIRECTORY ); {
eArchiveOpen e(strTempFile, errStr); TSTRING errStr = TSS_GetString(cCore, core::STR_BAD_TEMPDIRECTORY);
throw e; eArchiveOpen e(strTempFile, errStr);
} throw e;
}
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
} }
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
@ -907,4 +905,3 @@ void cLockedTemporaryFileArchive::Close()
// Note: this deletes the file as well // Note: this deletes the file as well
cFileArchive::Close(); cFileArchive::Close();
} }

View File

@ -56,24 +56,24 @@
//============================================================================= //=============================================================================
// eArchive exception classes // eArchive exception classes
//============================================================================= //=============================================================================
TSS_FILE_EXCEPTION( eArchive, eFileError ); TSS_FILE_EXCEPTION(eArchive, eFileError);
TSS_FILE_EXCEPTION( eArchiveOpen, eArchive ); TSS_FILE_EXCEPTION(eArchiveOpen, eArchive);
TSS_FILE_EXCEPTION( eArchiveWrite, eArchive ); TSS_FILE_EXCEPTION(eArchiveWrite, eArchive);
TSS_FILE_EXCEPTION( eArchiveRead, eArchive ); TSS_FILE_EXCEPTION(eArchiveRead, eArchive);
TSS_FILE_EXCEPTION( eArchiveEOF, eArchive ); TSS_FILE_EXCEPTION(eArchiveEOF, eArchive);
TSS_FILE_EXCEPTION( eArchiveSeek, eArchive ); TSS_FILE_EXCEPTION(eArchiveSeek, eArchive);
TSS_FILE_EXCEPTION( eArchiveMemmap, eArchive ); TSS_FILE_EXCEPTION(eArchiveMemmap, eArchive);
TSS_FILE_EXCEPTION( eArchiveOutOfMem, eArchive ); TSS_FILE_EXCEPTION(eArchiveOutOfMem, eArchive);
TSS_FILE_EXCEPTION( eArchiveInvalidOp, eArchive ); TSS_FILE_EXCEPTION(eArchiveInvalidOp, eArchive);
TSS_FILE_EXCEPTION( eArchiveFormat, eArchive ); TSS_FILE_EXCEPTION(eArchiveFormat, eArchive);
TSS_FILE_EXCEPTION( eArchiveNotRegularFile, eArchive ); TSS_FILE_EXCEPTION(eArchiveNotRegularFile, eArchive);
TSS_BEGIN_EXCEPTION( eArchiveCrypto, eArchive ) TSS_BEGIN_EXCEPTION(eArchiveCrypto, eArchive)
virtual TSTRING GetMsg() const; virtual TSTRING GetMsg() const;
// eCryptoArchive appends a special string to the end of // eCryptoArchive appends a special string to the end of
// all exception messages // all exception messages
TSS_END_EXCEPTION() TSS_END_EXCEPTION()
TSS_EXCEPTION( eArchiveStringTooLong, eArchive ); TSS_EXCEPTION(eArchiveStringTooLong, eArchive);
// throw( eArchiveOpen( cErrorUtil::MakeFileError( fileError.GetMsg(), strTempFile ) ) ); // throw( eArchiveOpen( cErrorUtil::MakeFileError( fileError.GetMsg(), strTempFile ) ) );
@ -85,7 +85,9 @@ TSS_EXCEPTION( eArchiveStringTooLong, eArchive );
class cArchive class cArchive
{ {
public: public:
virtual ~cArchive() {} virtual ~cArchive()
{
}
// convenience methods // convenience methods
// //
@ -101,24 +103,24 @@ public:
// All write functions throw exceptions for unexpected events like // All write functions throw exceptions for unexpected events like
// running out of memory or disk space. // running out of memory or disk space.
// //
void ReadInt16(int16& ret); // throw(eArchive) void ReadInt16(int16& ret); // throw(eArchive)
void ReadInt32(int32& ret); // throw(eArchive) void ReadInt32(int32& ret); // throw(eArchive)
void ReadInt64(int64& ret); // throw(eArchive) void ReadInt64(int64& ret); // throw(eArchive)
void ReadString(TSTRING& ret); // throw(eArchive) void ReadString(TSTRING& ret); // throw(eArchive)
int ReadBlob(void* pBlob, int count); int ReadBlob(void* pBlob, int count);
void WriteInt16(int16 i); // throw(eArchive) void WriteInt16(int16 i); // throw(eArchive)
void WriteInt32(int32 i); // throw(eArchive) void WriteInt32(int32 i); // throw(eArchive)
void WriteInt64(int64 i); // throw(eArchive) void WriteInt64(int64 i); // throw(eArchive)
void WriteString(TSTRING s); // throw(eArchive) void WriteString(TSTRING s); // throw(eArchive)
void WriteBlob(const void* pBlob, int count); // throw(eArchive) void WriteBlob(const void* pBlob, int count); // throw(eArchive)
static int32 GetStorageSize(const TSTRING& str); static int32 GetStorageSize(const TSTRING& str);
// this method calculates how many bytes the given string will take up in the archive and returns // this method calculates how many bytes the given string will take up in the archive and returns
// that value // that value
// NOTE -- if the implementation of ReadString() or WriteString() ever changes, this method will also // NOTE -- if the implementation of ReadString() or WriteString() ever changes, this method will also
// need to change. // need to change.
int64 Copy(cArchive* pFrom, int64 amt); // throw(eArchive) int64 Copy(cArchive* pFrom, int64 amt); // throw(eArchive)
// this method copies amt bytes from pFrom to itself, throwing an eArchive if anything goes wrong. // this method copies amt bytes from pFrom to itself, throwing an eArchive if anything goes wrong.
// only makes sense to call for reading archives // only makes sense to call for reading archives
@ -126,7 +128,7 @@ public:
protected: protected:
// overrides // overrides
virtual int Read(void* pDest, int count) = 0; virtual int Read(void* pDest, int count) = 0;
virtual int Write(const void* pDest, int count) = 0; // throw(eArchive); virtual int Write(const void* pDest, int count) = 0; // throw(eArchive);
}; };
@ -137,15 +139,16 @@ protected:
class cBidirArchive : public cArchive class cBidirArchive : public cArchive
{ {
public: public:
enum SeekFrom { enum SeekFrom
{
BEGINNING = 0, BEGINNING = 0,
CURRENT = 1, CURRENT = 1,
END = -1 END = -1
}; };
virtual void Seek(int64 offset, SeekFrom from) = 0; // throw(eArchive); virtual void Seek(int64 offset, SeekFrom from) = 0; // throw(eArchive);
virtual int64 CurrentPos() const = 0; virtual int64 CurrentPos() const = 0;
virtual int64 Length() const = 0; virtual int64 Length() const = 0;
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -155,29 +158,30 @@ public:
class cMemMappedArchive : public cBidirArchive class cMemMappedArchive : public cBidirArchive
{ {
public: public:
enum { enum
{
MAP_TO_EOF = -1 MAP_TO_EOF = -1
}; };
cMemMappedArchive(); cMemMappedArchive();
virtual ~cMemMappedArchive(); virtual ~cMemMappedArchive();
virtual void MapArchive(int64 offset, int64 len) = 0; // throw(eArchive); virtual void MapArchive(int64 offset, int64 len) = 0; // throw(eArchive);
virtual void MapArchive(int64 offset, int64 len) const = 0; // throw(eArchive); virtual void MapArchive(int64 offset, int64 len) const = 0; // throw(eArchive);
// the const version of MapArchive() does not allow the archive to grow in size // the const version of MapArchive() does not allow the archive to grow in size
int64 GetMappedOffset() const; // throw(eArchive) int64 GetMappedOffset() const; // throw(eArchive)
int64 GetMappedLength() const; // throw(eArchive) int64 GetMappedLength() const; // throw(eArchive)
void* GetMap(); // throw(eArchive) void* GetMap(); // throw(eArchive)
const void* GetMap() const; const void* GetMap() const;
protected: protected:
mutable void* mpMappedMem; mutable void* mpMappedMem;
mutable int64 mMappedOffset; mutable int64 mMappedOffset;
mutable int64 mMappedLength; mutable int64 mMappedLength;
// call in derived class to set above vars // call in derived class to set above vars
void SetNewMap(void* pMap, int64 offset, int64 length) const; void SetNewMap(void* pMap, int64 offset, int64 length) const;
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -193,27 +197,30 @@ public:
cMemoryArchive(int maxSize = 0x8000000); // default max size == 128MB cMemoryArchive(int maxSize = 0x8000000); // default max size == 128MB
~cMemoryArchive(); ~cMemoryArchive();
virtual bool EndOfFile(); virtual bool EndOfFile();
virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive) virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive)
virtual int64 CurrentPos() const; virtual int64 CurrentPos() const;
virtual int64 Length() const; virtual int64 Length() const;
virtual void MapArchive(int64 offset, int64 len); // throw(eArchive) virtual void MapArchive(int64 offset, int64 len); // throw(eArchive)
virtual void MapArchive(int64 offset, int64 len) const; // throw(eArchive) virtual void MapArchive(int64 offset, int64 len) const; // throw(eArchive)
void Truncate(); // set the length to the current pos void Truncate(); // set the length to the current pos
int8* GetMemory() const { return mpMemory; } int8* GetMemory() const
{
return mpMemory;
}
protected: protected:
int8* mpMemory; int8* mpMemory;
int mAllocatedLen; int mAllocatedLen;
int mMaxAllocatedLen; int mMaxAllocatedLen;
int mLogicalSize; int mLogicalSize;
int mReadHead; int mReadHead;
virtual int Read(void* pDest, int count); virtual int Read(void* pDest, int count);
virtual int Write(const void* pDest, int count); // throw(eArchive) virtual int Write(const void* pDest, int count); // throw(eArchive)
virtual void AllocateMemory(int len); // throw(eArchive) virtual void AllocateMemory(int len); // throw(eArchive)
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -224,30 +231,31 @@ class cFixedMemArchive : public cBidirArchive
{ {
public: public:
cFixedMemArchive(); cFixedMemArchive();
cFixedMemArchive( int8* pMem, int32 size ); cFixedMemArchive(int8* pMem, int32 size);
virtual ~cFixedMemArchive(); virtual ~cFixedMemArchive();
void Attach( int8* pMem, int32 size ); void Attach(int8* pMem, int32 size);
// this method associates the archive with pMem and sets the size of the // this method associates the archive with pMem and sets the size of the
// archive. Unlike cMemoryArchive, this may never grow or shrink in size. // archive. Unlike cMemoryArchive, this may never grow or shrink in size.
//----------------------------------- //-----------------------------------
// cBidirArchive interface // cBidirArchive interface
//----------------------------------- //-----------------------------------
virtual void Seek (int64 offset, SeekFrom from) ; // throw(eArchive); virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive);
virtual int64 CurrentPos () const ; virtual int64 CurrentPos() const;
virtual int64 Length () const ; virtual int64 Length() const;
virtual bool EndOfFile(); virtual bool EndOfFile();
protected: protected:
//----------------------------------- //-----------------------------------
// cArchive interface // cArchive interface
//----------------------------------- //-----------------------------------
virtual int Read(void* pDest, int count); // throw(eArchive) virtual int Read(void* pDest, int count); // throw(eArchive)
virtual int Write(const void* pDest, int count); // throw(eArchive) virtual int Write(const void* pDest, int count); // throw(eArchive)
int8* mpMemory; int8* mpMemory;
int32 mSize; int32 mSize;
int32 mReadHead; int32 mReadHead;
}; };
class cFileArchive : public cBidirArchive class cFileArchive : public cBidirArchive
@ -258,42 +266,42 @@ public:
enum OpenFlags enum OpenFlags
{ {
FA_OPEN_TEXT = 0x1, FA_OPEN_TEXT = 0x1,
FA_OPEN_TRUNCATE = 0x2, FA_OPEN_TRUNCATE = 0x2,
FA_SCANNING = 0x4, FA_SCANNING = 0x4,
FA_DIRECT = 0x8 FA_DIRECT = 0x8
}; };
// TODO: Open should throw // TODO: Open should throw
virtual void OpenRead(const TCHAR* filename, uint32 openFlags = 0 ); virtual void OpenRead(const TCHAR* filename, uint32 openFlags = 0);
virtual void OpenReadWrite(const TCHAR* filename, uint32 openFlags = FA_OPEN_TRUNCATE ); virtual void OpenReadWrite(const TCHAR* filename, uint32 openFlags = FA_OPEN_TRUNCATE);
// opens a file for reading or writing; the file is always created if it doesn't exist, // opens a file for reading or writing; the file is always created if it doesn't exist,
// and is truncated to zero length if truncateFile is set to true; // and is truncated to zero length if truncateFile is set to true;
TSTRING GetCurrentFilename(void) const; TSTRING GetCurrentFilename(void) const;
virtual void Close(void); virtual void Close(void);
void Truncate(); // throw(eArchive) // set the length to the current pos void Truncate(); // throw(eArchive) // set the length to the current pos
//----------------------------------- //-----------------------------------
// cBidirArchive interface // cBidirArchive interface
//----------------------------------- //-----------------------------------
virtual bool EndOfFile(); virtual bool EndOfFile();
virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive) virtual void Seek(int64 offset, SeekFrom from); // throw(eArchive)
virtual int64 CurrentPos() const; virtual int64 CurrentPos() const;
virtual int64 Length() const; virtual int64 Length() const;
protected: protected:
int64 mFileSize; //Size of FileArchive int64 mFileSize; //Size of FileArchive
int64 mReadHead; //Current position of read/write head int64 mReadHead; //Current position of read/write head
//----------------------------------- //-----------------------------------
// cArchive interface // cArchive interface
//----------------------------------- //-----------------------------------
virtual int Read(void* pDest, int count); virtual int Read(void* pDest, int count);
virtual int Write(const void* pDest, int count); //throw(eArchive) virtual int Write(const void* pDest, int count); //throw(eArchive)
bool isWritable; bool isWritable;
cFile mCurrentFile; cFile mCurrentFile;
TSTRING mCurrentFilename; //current file TSTRING mCurrentFilename; //current file
uint32 mOpenFlags; uint32 mOpenFlags;
}; };
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
@ -307,22 +315,25 @@ protected:
class cLockedTemporaryFileArchive : public cFileArchive class cLockedTemporaryFileArchive : public cFileArchive
{ {
public: public:
virtual void OpenReadWrite ( const TCHAR* filename = NULL, uint32 openFlags = FA_OPEN_TRUNCATE ); virtual void OpenReadWrite(const TCHAR* filename = NULL, uint32 openFlags = FA_OPEN_TRUNCATE);
// creates the file. filename must not exist on the file system. // creates the file. filename must not exist on the file system.
// if filename is NULL, the class will create and use a temporary file. // if filename is NULL, the class will create and use a temporary file.
// truncateFile has no meaning // truncateFile has no meaning
//virtual void OpenReadWriteThrow ( const TCHAR* filename = NULL, bool truncateFile = true ) throw (eArchive); //virtual void OpenReadWriteThrow ( const TCHAR* filename = NULL, bool truncateFile = true ) throw (eArchive);
// this is the same as OpenReadWrite, except an exception is thrown on error (of type // this is the same as OpenReadWrite, except an exception is thrown on error (of type
// cArchive::ERR_OPEN_FAILED) // cArchive::ERR_OPEN_FAILED)
virtual void Close(); virtual void Close();
// close and delete the file // close and delete the file
private: private:
// open for read only makes no sense if we're always creating the file, // open for read only makes no sense if we're always creating the file,
// so disallow read only file opens // so disallow read only file opens
virtual void OpenRead( const TCHAR*, uint32 openFlags = 0 ) { ASSERT( false ); THROW_INTERNAL("archive.h"); } virtual void OpenRead(const TCHAR*, uint32 openFlags = 0)
{
ASSERT(false);
THROW_INTERNAL("archive.h");
}
}; };
#endif #endif

View File

@ -42,9 +42,9 @@
#include "ntmbs.h" #include "ntmbs.h"
#if IS_ANDROID #if IS_ANDROID
int mblen(const char *s, size_t n) int mblen(const char* s, size_t n)
{ {
return mbtowc(0, s, n); return mbtowc(0, s, n);
} }
#endif #endif
@ -64,26 +64,26 @@ int mblen(const char *s, size_t n)
// //
/* static */ /* static */
bool cCharUtil::PeekNextChar( const TSTRING::const_iterator& cur, bool cCharUtil::PeekNextChar(const TSTRING::const_iterator& cur,
const TSTRING::const_iterator& end, const TSTRING::const_iterator& end,
TSTRING::const_iterator& first, TSTRING::const_iterator& first,
TSTRING::const_iterator& last ) TSTRING::const_iterator& last)
{ {
// //
// do we have a valid string here? // do we have a valid string here?
// //
if( cur > end ) if (cur > end)
{ {
return false; return false;
} }
if( cur == end ) if (cur == end)
{ {
first = last = end; first = last = end;
return false; return false;
} }
if( *cur == _T('\0') ) if (*cur == _T('\0'))
{ {
first = last = cur; first = last = cur;
return false; return false;
@ -93,19 +93,19 @@ bool cCharUtil::PeekNextChar( const TSTRING::const_iterator& cur,
if (!(*cur)) if (!(*cur))
{ {
last = cur; last = cur;
} }
else else
{ {
#if !IS_AROS #if !IS_AROS
mblen (NULL, 0); mblen(NULL, 0);
int len = mblen(&*cur, MB_CUR_MAX); int len = mblen(&*cur, MB_CUR_MAX);
if (len < 0) //invalid multibyte sequence, but let's not blow up. if (len < 0) //invalid multibyte sequence, but let's not blow up.
len = 1; len = 1;
last = cur + len; last = cur + len;
#else // AROS mblen() seems broken (as of 6/2016) so don't use it. #else // AROS mblen() seems broken (as of 6/2016) so don't use it.
last = cur + 1; last = cur + 1;
#endif #endif
} }
@ -138,16 +138,14 @@ bool cCharUtil::PeekNextChar( const TSTRING::const_iterator& cur,
// //
/* static */ /* static */
bool cCharUtil::PopNextChar( TSTRING::const_iterator& cur, bool cCharUtil::PopNextChar(TSTRING::const_iterator& cur,
const TSTRING::const_iterator& end, const TSTRING::const_iterator& end,
TSTRING::const_iterator& first, TSTRING::const_iterator& first,
TSTRING::const_iterator& last ) TSTRING::const_iterator& last)
{ {
bool f = PeekNextChar( cur, end, first, last ); bool f = PeekNextChar(cur, end, first, last);
cur = last; // pop causes 'cur' to move to just beyond character ('last') cur = last; // pop causes 'cur' to move to just beyond character ('last')
return f; return f;
} }

View File

@ -44,23 +44,20 @@
class cCharUtil class cCharUtil
{ {
public: public:
// finds the next whole character in string identified by ['cur'-'end') // finds the next whole character in string identified by ['cur'-'end')
// identifies beginning of char in 'first', then end of character in 'last' // identifies beginning of char in 'first', then end of character in 'last'
// returns 'are there more characters in string?' // returns 'are there more characters in string?'
// if there are no more characters, will return 0 and first = last = end // if there are no more characters, will return 0 and first = last = end
static bool PeekNextChar( const TSTRING::const_iterator& cur, static bool PeekNextChar(const TSTRING::const_iterator& cur,
const TSTRING::const_iterator& end, const TSTRING::const_iterator& end,
TSTRING::const_iterator& first, TSTRING::const_iterator& first,
TSTRING::const_iterator& last ); TSTRING::const_iterator& last);
// same as PeekNextChar but increments 'cur' to 'last' // same as PeekNextChar but increments 'cur' to 'last'
static bool PopNextChar( TSTRING::const_iterator& cur, static bool PopNextChar(TSTRING::const_iterator& cur,
const TSTRING::const_iterator& end, const TSTRING::const_iterator& end,
TSTRING::const_iterator& first, TSTRING::const_iterator& first,
TSTRING::const_iterator& last ); TSTRING::const_iterator& last);
}; };
#endif//__CHARUTIL_H #endif //__CHARUTIL_H

View File

@ -38,9 +38,7 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ctor, dotr // ctor, dotr
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
cCmdLineParser::cCmdLineParser() : cCmdLineParser::cCmdLineParser() : mArgTable(HASH_VERY_SMALL), mLastArgInfo(-1, PARAM_NONE)
mArgTable(HASH_VERY_SMALL),
mLastArgInfo(-1, PARAM_NONE)
{ {
} }
@ -51,19 +49,20 @@ cCmdLineParser::~cCmdLineParser()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// AddArg // AddArg
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed) void cCmdLineParser::AddArg(
int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed)
{ {
if(arg.empty() && alias.empty()) if (arg.empty() && alias.empty())
{ {
// this refers to the list of parameters that comes after all the cmd line switches // this refers to the list of parameters that comes after all the cmd line switches
mLastArgInfo.mId = argId; mLastArgInfo.mId = argId;
mLastArgInfo.mNumParams = numParams; mLastArgInfo.mNumParams = numParams;
return ; return;
} }
if(! arg.empty()) if (!arg.empty())
mArgTable.Insert(arg, cArgInfo(argId, numParams)); mArgTable.Insert(arg, cArgInfo(argId, numParams));
if(! alias.empty()) if (!alias.empty())
{ {
// put the alias in the table with a '-' prepended to it so it matches '--' // put the alias in the table with a '-' prepended to it so it matches '--'
TSTRING str(_T("-")); TSTRING str(_T("-"));
@ -71,8 +70,8 @@ void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias,
mArgTable.Insert(str, cArgInfo(argId, numParams)); mArgTable.Insert(str, cArgInfo(argId, numParams));
} }
// This argument can appear more than once on the command line. // This argument can appear more than once on the command line.
if( multipleAllowed ) if (multipleAllowed)
mMultipleAllowed.insert( argId ); mMultipleAllowed.insert(argId);
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -90,43 +89,39 @@ void cCmdLineParser::AddArg(int argId, const TSTRING& arg, const TSTRING& alias,
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Parse // Parse
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::Parse(int argc, const TCHAR *const * argv) void cCmdLineParser::Parse(int argc, const TCHAR* const* argv)
{ {
// clear out any existing data // clear out any existing data
mArgData.clear(); mArgData.clear();
const TCHAR* pCurArg = 0; const TCHAR* pCurArg = 0;
bool bProcessedFinalParams = false; // gets set to true when the parameters to the command line are processed bool bProcessedFinalParams = false; // gets set to true when the parameters to the command line are processed
// I assume argv[0] is the executable name... // I assume argv[0] is the executable name...
for(int i=1; i < argc; i++) for (int i = 1; i < argc; i++)
{ {
if(argv[i][0] == _T('-')) if (argv[i][0] == _T('-'))
{ {
pCurArg = argv[i]; pCurArg = argv[i];
// this is a switch; find it in the table... // this is a switch; find it in the table...
cArgInfo argInfo; cArgInfo argInfo;
if ( !mArgTable.Lookup( TSTRING(&argv[i][1] ), argInfo ) ) if (!mArgTable.Lookup(TSTRING(&argv[i][1]), argInfo))
{ {
// unknown switch! // unknown switch!
throw eCmdLineInvalidArg( throw eCmdLineInvalidArg(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg);
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
} }
// //
// make sure this hasn't been specified yet... // make sure this hasn't been specified yet...
// //
if( ArgInList( argInfo.mId ) ) if (ArgInList(argInfo.mId))
{ {
// Make sure it isn't okay for this one to appear more than once... // Make sure it isn't okay for this one to appear more than once...
std::set<int>::iterator it = mMultipleAllowed.find( argInfo.mId ); std::set<int>::iterator it = mMultipleAllowed.find(argInfo.mId);
if( it == mMultipleAllowed.end() ) if (it == mMultipleAllowed.end())
{ {
// It wasn't in our list of allowed params, so error. // It wasn't in our list of allowed params, so error.
throw eCmdLineMultiArg( throw eCmdLineMultiArg(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + argv[i]);
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ argv[i] );
} }
} }
// //
@ -134,24 +129,22 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
// //
mArgData.push_back(cArgData(argInfo.mId, TSTRING(argv[i]))); mArgData.push_back(cArgData(argInfo.mId, TSTRING(argv[i])));
cArgData& curArg = mArgData.back(); cArgData& curArg = mArgData.back();
switch( argInfo.mNumParams ) switch (argInfo.mNumParams)
{ {
case PARAM_NONE: case PARAM_NONE:
// make sure there are no parameters to this, but be careful because // make sure there are no parameters to this, but be careful because
// it is legal to start the parameters to the executable here. // it is legal to start the parameters to the executable here.
if((i+1 < argc) && (argv[i+1][0] != _T('-'))) if ((i + 1 < argc) && (argv[i + 1][0] != _T('-')))
{ {
// search for any more parameters // search for any more parameters
// TODO: In the future we may want to support a '--' switch that specifies the start // TODO: In the future we may want to support a '--' switch that specifies the start
// of parameters to the executable. // of parameters to the executable.
for (int j = i + 2; j < argc; ++j ) for (int j = i + 2; j < argc; ++j)
{ {
if (argv[j][0] == _T('-')) if (argv[j][0] == _T('-'))
{ {
// >0 parameter passed ! // >0 parameter passed !
throw eCmdLineBadParam( throw eCmdLineBadParam(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg);
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
} }
} }
} }
@ -160,29 +153,27 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
case PARAM_ONE: case PARAM_ONE:
// get the next parameter... // get the next parameter...
i++; i++;
if ( (i >= argc) || (argv[i][0] == _T('-')) ) if ((i >= argc) || (argv[i][0] == _T('-')))
{ {
// zero parameters passed to something that needed one param // zero parameters passed to something that needed one param
throw eCmdLineBadParam( throw eCmdLineBadParam(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg);
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
} }
curArg.mParams.push_back( TSTRING(argv[i]) ); curArg.mParams.push_back(TSTRING(argv[i]));
break; break;
case PARAM_MANY: case PARAM_MANY:
i++; i++;
while((i < argc) && (argv[i][0] != _T('-'))) while ((i < argc) && (argv[i][0] != _T('-')))
{ {
curArg.mParams.push_back(TSTRING(argv[i])); curArg.mParams.push_back(TSTRING(argv[i]));
i++; i++;
} }
i--; // since we have gone too far at this point i--; // since we have gone too far at this point
break; break;
default: default:
ASSERTMSG( false, "Unknown number of arguments to parser" ); ASSERTMSG(false, "Unknown number of arguments to parser");
} }
} }
else else
@ -191,14 +182,14 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
// this must be the final "unnamed" arg // this must be the final "unnamed" arg
// first, make sure it is consistent with the current info... // first, make sure it is consistent with the current info...
bool bResult = true; bool bResult = true;
switch(mLastArgInfo.mNumParams) switch (mLastArgInfo.mNumParams)
{ {
case PARAM_NONE: case PARAM_NONE:
// this is an error; they didn't want any command line parameters... // this is an error; they didn't want any command line parameters...
bResult = false; bResult = false;
break; break;
case PARAM_ONE: case PARAM_ONE:
if(i+1 != argc) if (i + 1 != argc)
// there is >1 final parameter; it is an error // there is >1 final parameter; it is an error
bResult = false; bResult = false;
break; break;
@ -207,33 +198,28 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
break; break;
default: default:
ASSERT(false); ASSERT(false);
} }
if(! bResult) if (!bResult)
{ {
throw eCmdLineBadParam( ); throw eCmdLineBadParam();
} }
// ok, we can push the final parameter info onto the list... // ok, we can push the final parameter info onto the list...
mArgData.push_back(cArgData(mLastArgInfo.mId)); mArgData.push_back(cArgData(mLastArgInfo.mId));
cArgData& curArg = mArgData.back(); cArgData& curArg = mArgData.back();
while ( i < argc ) while (i < argc)
{ {
if ( argv[i][0] == _T('-') ) if (argv[i][0] == _T('-'))
{ {
if ( ! pCurArg ) if (!pCurArg)
{ {
throw eCmdLineBadSwitchPos( throw eCmdLineBadSwitchPos(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + argv[i]);
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ argv[i] );
} }
else else
{ {
// there was an extra parameter passed somewhere! // there was an extra parameter passed somewhere!
throw eCmdLineBadArgParam( throw eCmdLineBadArgParam(TSS_GetString(cCore, core::STR_ERR2_BAD_ARG_PARAMS) + pCurArg);
TSS_GetString( cCore, core::STR_ERR2_BAD_ARG_PARAMS )
+ pCurArg );
} }
} }
@ -241,21 +227,18 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
curArg.mParams.push_back(TSTRING(argv[i])); curArg.mParams.push_back(TSTRING(argv[i]));
i++; i++;
} }
} }
} }
// it is possible not to process the final command line parameters in the "else" case above // it is possible not to process the final command line parameters in the "else" case above
// (this only occurs if there are no command line parameters specified) so let's make sure that // (this only occurs if there are no command line parameters specified) so let's make sure that
// is consistent with what we are configured with... // is consistent with what we are configured with...
// NOTE -- it is ok to have no cmd line parameters if they specified PARAM_NONE or PARAM_MANY // NOTE -- it is ok to have no cmd line parameters if they specified PARAM_NONE or PARAM_MANY
if(! bProcessedFinalParams) if (!bProcessedFinalParams)
{ {
if(mLastArgInfo.mNumParams == PARAM_ONE) if (mLastArgInfo.mNumParams == PARAM_ONE)
{ {
throw eCmdLineBadParam( ); throw eCmdLineBadParam();
} }
} }
@ -269,28 +252,24 @@ void cCmdLineParser::Parse(int argc, const TCHAR *const * argv)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::TestMutEx() void cCmdLineParser::TestMutEx()
{ {
std::list<std::pair<int,int> >::const_iterator i; std::list<std::pair<int, int> >::const_iterator i;
cCmdLineIter iter1(*this), iter2(*this); cCmdLineIter iter1(*this), iter2(*this);
for(i = mMutExList.begin(); i != mMutExList.end(); i++) for (i = mMutExList.begin(); i != mMutExList.end(); i++)
{ {
//TODO -- there is a much more efficent way to do this (using cFCOPropVector, for example) //TODO -- there is a much more efficent way to do this (using cFCOPropVector, for example)
// the command line is presumably small enough, tho, that it probably isn't a big // the command line is presumably small enough, tho, that it probably isn't a big
// deal to do it this way. // deal to do it this way.
iter1.SeekToArg(i->first); iter1.SeekToArg(i->first);
if(! iter1.Done()) if (!iter1.Done())
{ {
iter2.SeekToArg(i->second); iter2.SeekToArg(i->second);
if(! iter2.Done()) if (!iter2.Done())
{ {
// we have a mutual exclusion violation! // we have a mutual exclusion violation!
throw eCmdLineMutEx( throw eCmdLineMutEx(iter1.ActualParam() + _T(", ") + iter2.ActualParam());
iter1.ActualParam()
+ _T(", ")
+ iter2.ActualParam() );
} }
} }
} }
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -298,51 +277,51 @@ void cCmdLineParser::TestMutEx()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::TestDependency() void cCmdLineParser::TestDependency()
{ {
std::list< std::pair< std::pair< int, int>, bool > >::const_iterator i; std::list<std::pair<std::pair<int, int>, bool> >::const_iterator i;
cCmdLineIter iter1(*this), iter2(*this); cCmdLineIter iter1(*this), iter2(*this);
for( i = mDependencyList.begin(); i != mDependencyList.end(); ++i) for (i = mDependencyList.begin(); i != mDependencyList.end(); ++i)
{ {
iter1.SeekToArg( i->first.first ); iter1.SeekToArg(i->first.first);
// was it on the command line? // was it on the command line?
if( !iter1.Done() ) if (!iter1.Done())
{ {
// it was, is the corresponding arg on the command line? // it was, is the corresponding arg on the command line?
iter2.SeekToArg( i->first.second ); iter2.SeekToArg(i->first.second);
if( iter2.Done() ) // it wasn't, dependency error if (iter2.Done()) // it wasn't, dependency error
{ {
TSTRING arg1, arg2, alias1, alias2; TSTRING arg1, arg2, alias1, alias2;
cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 ); cCmdLineParser::LookupArgInfo(i->first.first, arg1, alias1);
cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 ); cCmdLineParser::LookupArgInfo(i->first.second, arg2, alias2);
// determine in which form the user passed the arguments, // determine in which form the user passed the arguments,
// and construct the error message in the same form // and construct the error message in the same form
if ( iter1.ActualParam().length() == 2 ) if (iter1.ActualParam().length() == 2)
throw eCmdLineDependency( _T("The switch -") + arg1 + _T(" requires -") + arg2 +_T(".") ); throw eCmdLineDependency(_T("The switch -") + arg1 + _T(" requires -") + arg2 + _T("."));
else else
throw eCmdLineDependency( _T("The switch --") + alias1 + _T(" requires --") + alias2 + _T(".") ); throw eCmdLineDependency(_T("The switch --") + alias1 + _T(" requires --") + alias2 + _T("."));
} }
} }
else if( i->second ) else if (i->second)
// only make this second check if the dependencies are MUTUAL, // only make this second check if the dependencies are MUTUAL,
// as indicated (or not) by the bool value. // as indicated (or not) by the bool value.
{ {
iter2.SeekToArg( i->first.second ); iter2.SeekToArg(i->first.second);
// the first arg in the pair was not on the command line, // the first arg in the pair was not on the command line,
// so just make sure the second isn't there... // so just make sure the second isn't there...
if( !iter2.Done() ) if (!iter2.Done())
{ {
// arg2 appeared without arg1, so dependency error. // arg2 appeared without arg1, so dependency error.
TSTRING arg1, arg2, alias1, alias2; TSTRING arg1, arg2, alias1, alias2;
cCmdLineParser::LookupArgInfo( i->first.first, arg1, alias1 ); cCmdLineParser::LookupArgInfo(i->first.first, arg1, alias1);
cCmdLineParser::LookupArgInfo( i->first.second, arg2, alias2 ); cCmdLineParser::LookupArgInfo(i->first.second, arg2, alias2);
// determine in which form the user passed the arguments, // determine in which form the user passed the arguments,
// and construct the error message in the same form // and construct the error message in the same form
if ( iter1.ActualParam().length() == 2 ) if (iter1.ActualParam().length() == 2)
throw eCmdLineDependency( _T("The switch -") + arg2 + _T(" requires -") + arg1 +_T(".") ); throw eCmdLineDependency(_T("The switch -") + arg2 + _T(" requires -") + arg1 + _T("."));
else else
throw eCmdLineDependency( _T("The switch --") + alias2 + _T(" requires --") + alias1 + _T(".") ); throw eCmdLineDependency(_T("The switch --") + alias2 + _T(" requires --") + alias1 + _T("."));
} }
} }
@ -364,15 +343,15 @@ void cCmdLineParser::AddMutEx(int argId1, int argId2)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// AddDependency // AddDependency
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual ) void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual)
{ {
// again, no checking for duplicates... would a set // again, no checking for duplicates... would a set
// prove to be a better container for this operation? // prove to be a better container for this operation?
std::pair< int, int > Args( argId1, argId2 ); std::pair<int, int> Args(argId1, argId2);
std::pair< std::pair< int, int >, bool > Dep( Args, mutual ); std::pair<std::pair<int, int>, bool> Dep(Args, mutual);
ASSERT(argId1 != argId2); ASSERT(argId1 != argId2);
mDependencyList.push_back( Dep); mDependencyList.push_back(Dep);
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -382,14 +361,14 @@ void cCmdLineParser::AddDependency(int argId1, int argId2, bool mutual )
void cCmdLineParser::TraceContents(int dl) void cCmdLineParser::TraceContents(int dl)
{ {
cDebug d("cCmdLineParser::TraceContents"); cDebug d("cCmdLineParser::TraceContents");
if(dl == -1) if (dl == -1)
dl = cDebug::D_DEBUG; dl = cDebug::D_DEBUG;
std::list<cArgData>::const_iterator i; std::list<cArgData>::const_iterator i;
for(i = mArgData.begin(); i != mArgData.end(); i++) for (i = mArgData.begin(); i != mArgData.end(); i++)
{ {
d.Trace(dl, "* Item id:%d\n", i->mId); d.Trace(dl, "* Item id:%d\n", i->mId);
for(std::vector<TSTRING>::const_iterator vi = i->mParams.begin(); vi != i->mParams.end(); vi++) for (std::vector<TSTRING>::const_iterator vi = i->mParams.begin(); vi != i->mParams.end(); vi++)
{ {
d.Trace(dl, "\t%s\n", vi->c_str()); d.Trace(dl, "\t%s\n", vi->c_str());
} }
@ -398,7 +377,7 @@ void cCmdLineParser::TraceContents(int dl)
d.Trace(dl, "--- Switch id table ---\n"); d.Trace(dl, "--- Switch id table ---\n");
cHashTableIter<TSTRING, cArgInfo> iter(mArgTable); cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
for(iter.SeekBegin(); ! iter.Done(); iter.Next()) for (iter.SeekBegin(); !iter.Done(); iter.Next())
{ {
d.Trace(dl, "[%d] %s\n", iter.Val().mId, iter.Key().c_str()); d.Trace(dl, "[%d] %s\n", iter.Val().mId, iter.Key().c_str());
} }
@ -412,16 +391,16 @@ void cCmdLineParser::TraceContents(int dl)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const
{ {
arg = _T(""); arg = _T("");
alias = _T(""); alias = _T("");
cHashTableIter<TSTRING, cArgInfo> iter(mArgTable); cHashTableIter<TSTRING, cArgInfo> iter(mArgTable);
for(iter.SeekBegin(); ! iter.Done(); iter.Next()) for (iter.SeekBegin(); !iter.Done(); iter.Next())
{ {
if(iter.Val().mId == argId) if (iter.Val().mId == argId)
{ {
TSTRING str = iter.Key(); TSTRING str = iter.Key();
if((str.length() > 0) && (str[0] == _T('-'))) if ((str.length() > 0) && (str[0] == _T('-')))
{ {
// this is the alias! // this is the alias!
alias = (str.c_str() + 1); alias = (str.c_str() + 1);
@ -433,7 +412,7 @@ bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) cons
} }
} }
} }
return ((! arg.empty()) || (! alias.empty())); return ((!arg.empty()) || (!alias.empty()));
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -442,9 +421,9 @@ bool cCmdLineParser::LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) cons
bool cCmdLineParser::ArgInList(int argId) bool cCmdLineParser::ArgInList(int argId)
{ {
std::list<cArgData>::iterator i; std::list<cArgData>::iterator i;
for( i = mArgData.begin(); i != mArgData.end(); i++ ) for (i = mArgData.begin(); i != mArgData.end(); i++)
{ {
if( i->mId == argId ) if (i->mId == argId)
return true; return true;
} }
return false; return false;
@ -458,15 +437,13 @@ bool cCmdLineParser::ArgInList(int argId)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// SeekToArg // SeekToArg
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
bool cCmdLineIter::SeekToArg(int argId) const bool cCmdLineIter::SeekToArg(int argId) const
{ {
for(SeekBegin(); ! Done(); Next()) for (SeekBegin(); !Done(); Next())
{ {
if(ArgId() == argId) if (ArgId() == argId)
return true; return true;
} }
return false; return false;
} }

View File

@ -49,14 +49,15 @@
//============================================================================= //=============================================================================
// eCmdLine // eCmdLine
//============================================================================= //=============================================================================
TSS_EXCEPTION( eCmdLine, eError ) TSS_EXCEPTION(eCmdLine, eError)
TSS_EXCEPTION( eCmdLineInvalidArg, eCmdLine ) // an arg on the command line is not recognized TSS_EXCEPTION(eCmdLineInvalidArg, eCmdLine) // an arg on the command line is not recognized
TSS_EXCEPTION( eCmdLineBadArgParam, eCmdLine ) // wrong number of parameters to an argument TSS_EXCEPTION(eCmdLineBadArgParam, eCmdLine) // wrong number of parameters to an argument
TSS_EXCEPTION( eCmdLineBadParam, eCmdLine ) // wrong number of paramters to the executable (not associated with any arguments) TSS_EXCEPTION(eCmdLineBadParam,
TSS_EXCEPTION( eCmdLineBadSwitchPos,eCmdLine ) // a '-' arg appeared after the final parameter list eCmdLine) // wrong number of paramters to the executable (not associated with any arguments)
TSS_EXCEPTION( eCmdLineMutEx, eCmdLine ) // a mutual exclusion error has occured TSS_EXCEPTION(eCmdLineBadSwitchPos, eCmdLine) // a '-' arg appeared after the final parameter list
TSS_EXCEPTION( eCmdLineDependency, eCmdLine ) // a dependency error has occurred. TSS_EXCEPTION(eCmdLineMutEx, eCmdLine) // a mutual exclusion error has occured
TSS_EXCEPTION( eCmdLineMultiArg, eCmdLine ) // an arg was found twice in the command line TSS_EXCEPTION(eCmdLineDependency, eCmdLine) // a dependency error has occurred.
TSS_EXCEPTION(eCmdLineMultiArg, eCmdLine) // an arg was found twice in the command line
/* /*
@ -95,87 +96,93 @@ public:
enum ParamCount enum ParamCount
{ {
PARAM_NONE, // no parameters to arg PARAM_NONE, // no parameters to arg
PARAM_ONE, // one parameter to arg PARAM_ONE, // one parameter to arg
PARAM_MANY, // zero or more paramters to arg PARAM_MANY, // zero or more paramters to arg
PARAM_INVALID // top of enum PARAM_INVALID // top of enum
}; };
void AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed = false); void
// this method should be called for each argument that can appear on the AddArg(int argId, const TSTRING& arg, const TSTRING& alias, ParamCount numParams, bool multipleAllowed = false);
// command line. // this method should be called for each argument that can appear on the
// argId -- a number that uniquely identifies the argument; no two arguments // command line.
// may have the same id (ASSERT-enforced) // argId -- a number that uniquely identifies the argument; no two arguments
// arg -- string that comes after the '-'. can be _T("") if there is only // may have the same id (ASSERT-enforced)
// a string representation // arg -- string that comes after the '-'. can be _T("") if there is only
// alias -- string that comes after '--' which has the same meaning. Can be _T("") // a string representation
// if there is no alias. If both arg and alias are empty strings, then this arg // alias -- string that comes after '--' which has the same meaning. Can be _T("")
// represents the list of arguments that comes at the end of the command line // if there is no alias. If both arg and alias are empty strings, then this arg
// numParams -- number of parameters that this argument needs // represents the list of arguments that comes at the end of the command line
// numParams -- number of parameters that this argument needs
void AddMutEx(int argId1, int argId2); void AddMutEx(int argId1, int argId2);
// this adds a mutual exclusion constraint. When Parse() is called, if argId1 and // this adds a mutual exclusion constraint. When Parse() is called, if argId1 and
// argId2 both exist on the command line, then the parse will fail and the error // argId2 both exist on the command line, then the parse will fail and the error
// value ERR_MUTUAL_EXCLUSION will be set. // value ERR_MUTUAL_EXCLUSION will be set.
void AddDependency(int argId1, int argId2, bool mutual = false ); void AddDependency(int argId1, int argId2, bool mutual = false);
// This adds a dependency constraint. When Parse() is called, if argId1 // This adds a dependency constraint. When Parse() is called, if argId1
// exists on the command line independent from argId2, then the parse will fail. // exists on the command line independent from argId2, then the parse will fail.
// If the default param mutual is true, then the command parser will check for // If the default param mutual is true, then the command parser will check for
// argId1 if argId2 is passed. We do this, since it is possible for one arg to // argId1 if argId2 is passed. We do this, since it is possible for one arg to
// depend on another, but have the other arg alone on the command line, legally. // depend on another, but have the other arg alone on the command line, legally.
void Parse(int argc, const TCHAR *const * argv); // throw eCmdLine void Parse(int argc, const TCHAR* const* argv); // throw eCmdLine
// after AddArg() has been called for every argument that could be processed by the // after AddArg() has been called for every argument that could be processed by the
// command line, call this to tokenize argv. If the return value is false, then // command line, call this to tokenize argv. If the return value is false, then
// the input was invalid in some way; the actual error can be determined by calling // the input was invalid in some way; the actual error can be determined by calling
// GetErrorInfo() below. // GetErrorInfo() below.
// void Clear(); // void Clear();
// clear out all information that this class contains // clear out all information that this class contains
bool LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const; bool LookupArgInfo(int argId, TSTRING& arg, TSTRING& alias) const;
// given an argId, fill out the strings with the argument and alias strings. Returns false // given an argId, fill out the strings with the argument and alias strings. Returns false
// if the argId cannot be found. This method is not very fast, so don't use it often. // if the argId cannot be found. This method is not very fast, so don't use it often.
#ifdef DEBUG #ifdef DEBUG
void TraceContents(int dl = -1) ; void TraceContents(int dl = -1);
#endif #endif
private: private:
void TestMutEx(); void TestMutEx();
// tests for mutual exclusion violations; if it fails, the current error is set and false // tests for mutual exclusion violations; if it fails, the current error is set and false
// is returned. // is returned.
void TestDependency(); void TestDependency();
// tests for all dependency violations. // tests for all dependency violations.
bool ArgInList(int argId); bool ArgInList(int argId);
// returns true if an argument with the specified id already exists in the list; this is used // returns true if an argument with the specified id already exists in the list; this is used
// to make sure the same arg doesn't appear >1 time on the command line // to make sure the same arg doesn't appear >1 time on the command line
// for storing information on paramers // for storing information on paramers
struct cArgInfo struct cArgInfo
{ {
int mId; int mId;
ParamCount mNumParams; ParamCount mNumParams;
cArgInfo(int i = -1, ParamCount p = PARAM_INVALID) : mId(i), mNumParams(p) {} cArgInfo(int i = -1, ParamCount p = PARAM_INVALID) : mId(i), mNumParams(p)
{
}
}; };
// for storing parsed argv information // for storing parsed argv information
struct cArgData struct cArgData
{ {
int mId; int mId;
std::vector<TSTRING> mParams; std::vector<TSTRING> mParams;
TSTRING mActualParam; // a string representation of what was actually on the command line TSTRING mActualParam; // a string representation of what was actually on the command line
cArgData(int id = -1, const TSTRING& actualParam = TSTRING(_T(""))) : mId(id), mActualParam(actualParam) {} cArgData(int id = -1, const TSTRING& actualParam = TSTRING(_T(""))) : mId(id), mActualParam(actualParam)
{
}
}; };
cHashTable<TSTRING, cArgInfo> mArgTable; cHashTable<TSTRING, cArgInfo> mArgTable;
cArgInfo mLastArgInfo; // info on the argument that comes at the end of the command line (with no associated '-x' or '--x') cArgInfo
std::list<cArgData> mArgData; mLastArgInfo; // info on the argument that comes at the end of the command line (with no associated '-x' or '--x')
std::list<std::pair<int,int> > mMutExList; // all of the mutual exclusions std::list<cArgData> mArgData;
std::list< std::pair < std::pair<int,int>, bool > > mDependencyList; // all of the dependencies std::list<std::pair<int, int> > mMutExList; // all of the mutual exclusions
std::set< int > mMultipleAllowed; std::list<std::pair<std::pair<int, int>, bool> > mDependencyList; // all of the dependencies
std::set<int> mMultipleAllowed;
friend class cCmdLineIter; friend class cCmdLineIter;
}; };
@ -190,36 +197,35 @@ public:
cCmdLineIter(const cCmdLineParser& parser); cCmdLineIter(const cCmdLineParser& parser);
// iteration // iteration
void SeekBegin() const; void SeekBegin() const;
bool Done() const; bool Done() const;
bool IsEmpty() const; bool IsEmpty() const;
void Next() const; void Next() const;
bool SeekToArg(int argId) const; bool SeekToArg(int argId) const;
// seeks to the argument with the given argId. returns // seeks to the argument with the given argId. returns
// false and Done() == true if it couldn't find it. // false and Done() == true if it couldn't find it.
// access to the argument data // access to the argument data
int ArgId() const; int ArgId() const;
// returns the id of this arg; ASSERTs if Done() == true // returns the id of this arg; ASSERTs if Done() == true
int NumParams() const; int NumParams() const;
// returns the number of parameters this argument has // returns the number of parameters this argument has
const TSTRING& ActualParam() const; const TSTRING& ActualParam() const;
// returns exactly what was passed on the command line (ie -- what the user typed) // returns exactly what was passed on the command line (ie -- what the user typed)
const TSTRING& ParamAt(int index) const; const TSTRING& ParamAt(int index) const;
// returns the parameter at the specified index. ASSERTs if // returns the parameter at the specified index. ASSERTs if
// the index is out of range. // the index is out of range.
private: private:
const std::list<cCmdLineParser::cArgData>& mList; const std::list<cCmdLineParser::cArgData>& mList;
mutable std::list<cCmdLineParser::cArgData>::const_iterator mIter; mutable std::list<cCmdLineParser::cArgData>::const_iterator mIter;
}; };
//############################################################################# //#############################################################################
// inline implementation // inline implementation
//############################################################################# //#############################################################################
inline cCmdLineIter::cCmdLineIter(const cCmdLineParser& parser) : inline cCmdLineIter::cCmdLineIter(const cCmdLineParser& parser) : mList(parser.mArgData)
mList(parser.mArgData)
{ {
SeekBegin(); SeekBegin();
} }
@ -241,22 +247,22 @@ inline void cCmdLineIter::Next() const
} }
inline int cCmdLineIter::ArgId() const inline int cCmdLineIter::ArgId() const
{ {
ASSERT(! Done()); ASSERT(!Done());
return mIter->mId; return mIter->mId;
} }
inline int cCmdLineIter::NumParams() const inline int cCmdLineIter::NumParams() const
{ {
ASSERT(! Done()); ASSERT(!Done());
return mIter->mParams.size(); return mIter->mParams.size();
} }
inline const TSTRING& cCmdLineIter::ActualParam() const inline const TSTRING& cCmdLineIter::ActualParam() const
{ {
ASSERT(! Done()); ASSERT(!Done());
return mIter->mActualParam; return mIter->mActualParam;
} }
inline const TSTRING& cCmdLineIter::ParamAt(int index) const inline const TSTRING& cCmdLineIter::ParamAt(int index) const
{ {
ASSERT((index >= 0) && (index < NumParams())); ASSERT((index >= 0) && (index < NumParams()));
return mIter->mParams[index]; return mIter->mParams[index];
@ -264,4 +270,3 @@ inline const TSTRING& cCmdLineIter::ParamAt(int index) const
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -60,17 +60,17 @@
/// Requirements /// Requirements
#include "platform.h" // for: Platform specific code #include "platform.h" // for: Platform specific code
#include "ntmbs.h" // for: NTBS, NTMBS, NTWCS, and NTDBS types #include "ntmbs.h" // for: NTBS, NTMBS, NTWCS, and NTDBS types
/// Exceptions /// Exceptions
TSS_EXCEPTION( eConverter, eError ); TSS_EXCEPTION(eConverter, eError);
TSS_EXCEPTION( eConverterReset, eConverter ); TSS_EXCEPTION(eConverterReset, eConverter);
TSS_EXCEPTION( eConverterFatal, eConverter ); TSS_EXCEPTION(eConverterFatal, eConverter);
TSS_EXCEPTION( eConverterUnsupportedConversion, eConverter ); TSS_EXCEPTION(eConverterUnsupportedConversion, eConverter);
TSS_EXCEPTION( eConverterUnknownCodepage, eConverter ); TSS_EXCEPTION(eConverterUnknownCodepage, eConverter);
/// Classes /// Classes
@ -90,45 +90,38 @@ TSS_EXCEPTION( eConverterUnknownCodepage, eConverter );
*/ */
class iCodeConverter class iCodeConverter
{ {
public: public:
static iCodeConverter* GetInstance(); // Singleton
static iCodeConverter* GetInstance(); // Singleton static void Finit();
static void Finit();
/// Subclass Responsibilities
/// Subclass Responsibilities virtual int Convert(ntmbs_t, // NTMBS buffer
virtual size_t, // Capacity in mbchar_t's (bytes)
int const_ntdbs_t, // null terminated two-byte wide character (UCS2 rep)
Convert( size_t nCount) = 0; // Amount to convert in dbchar_t's
ntmbs_t, // NTMBS buffer // returns number of buffer items converted, -1 on error
size_t, // Capacity in mbchar_t's (bytes)
const_ntdbs_t, // null terminated two-byte wide character (UCS2 rep)
size_t nCount ) = 0; // Amount to convert in dbchar_t's
// returns number of buffer items converted, -1 on error
virtual virtual int Convert(ntdbs_t, // NTDBS (Null-terminated two byte sequence) buf
int size_t, // Capacity in dbchar_t's
Convert( const_ntmbs_t, // Null-terminated multi-byte sequence
ntdbs_t, // NTDBS (Null-terminated two byte sequence) buf size_t) = 0; // Capacity in mbchar_t's (bytes)
size_t, // Capacity in dbchar_t's // returns number of buffer items converted, -1 on error
const_ntmbs_t, // Null-terminated multi-byte sequence
size_t ) = 0; // Capacity in mbchar_t's (bytes)
// returns number of buffer items converted, -1 on error
protected: protected:
iCodeConverter()
{
}
virtual ~iCodeConverter()
{
}
iCodeConverter() {} private:
virtual ~iCodeConverter() {} static iCodeConverter* CreateConverter();
static iCodeConverter* CreateGoodEnoughConverter();
private:
static iCodeConverter* CreateConverter();
static iCodeConverter* CreateGoodEnoughConverter();
static iCodeConverter* m_pInst;
static iCodeConverter* m_pInst;
}; };
@ -139,68 +132,64 @@ class iCodeConverter
#ifdef HAVE_ICONV_H #ifdef HAVE_ICONV_H
#include <iconv.h> #include <iconv.h>
#ifdef HAVE_LANGINFO_H # ifdef HAVE_LANGINFO_H
#ifndef __USE_XOPEN # ifndef __USE_XOPEN
#define __USE_XOPEN 1 # define __USE_XOPEN 1
#endif # endif
#include <langinfo.h> # include <langinfo.h>
#endif # endif
class cIconvUtil class cIconvUtil
{ {
public: public:
static const char* GetCodePageID(); // gets code page id for current locale, throws if error
static const char* GetCodePageID(); // gets code page id for current locale, throws if error static bool GetCodePageID(const char** ppCP);
static bool GetCodePageID( const char** ppCP ); static const char* GetIconvDbIdentifier();
static const char* GetIconvDbIdentifier(); static const char* GetMiddleIdentifier();
static const char* GetMiddleIdentifier(); static void ResetConverter(iconv_t);
static void ResetConverter( iconv_t ); static bool TestConverter(const char* pTo, const char* pFrom);
static bool TestConverter( const char* pTo, const char* pFrom ); static iconv_t OpenHandle(const char* pTo, const char* pFrom); // throws
static iconv_t OpenHandle( const char* pTo, const char* pFrom ); // throws static void CloseHandle(iconv_t ic);
static void CloseHandle( iconv_t ic );
}; };
class cIconvConverter : public iCodeConverter class cIconvConverter : public iCodeConverter
{ {
public: public:
static bool Test(); // is there a conversion for the current codepage?
static bool Test(); // is there a conversion for the current codepage? virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t);
virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t);
virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); cIconvConverter();
virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); virtual ~cIconvConverter();
cIconvConverter(); private:
virtual ~cIconvConverter(); void Init();
private: iconv_t icToDb;
void Init(); iconv_t icFromDb;
iconv_t icToDb;
iconv_t icFromDb;
}; };
class cDoubleIconvConverter : public iCodeConverter class cDoubleIconvConverter : public iCodeConverter
{ {
public: public:
static bool Test(); // is there a conversion for the current codepage?
static bool Test(); // is there a conversion for the current codepage? virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t);
virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t);
virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); cDoubleIconvConverter();
virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); virtual ~cDoubleIconvConverter();
cDoubleIconvConverter(); private:
virtual ~cDoubleIconvConverter(); void Init();
private: iconv_t icMbToUTF8;
iconv_t icUTF8ToDb;
void Init(); iconv_t icDbToUTF8;
iconv_t icUTF8ToMb;
iconv_t icMbToUTF8;
iconv_t icUTF8ToDb;
iconv_t icDbToUTF8;
iconv_t icUTF8ToMb;
}; };
#endif // HAVE_ICONV_H #endif // HAVE_ICONV_H
@ -220,10 +209,12 @@ class cDoubleIconvConverter : public iCodeConverter
class cWcharIs32BitUcs2Converterer : public iCodeConverter class cWcharIs32BitUcs2Converterer : public iCodeConverter
{ {
public: public:
virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t);
virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t);
virtual ~cWcharIs32BitUcs2Converterer() {} virtual ~cWcharIs32BitUcs2Converterer()
{
}
}; };
#endif // WCHAR_IS_32_BITS #endif // WCHAR_IS_32_BITS
@ -240,10 +231,12 @@ public:
class cWcharIs16BitUcs2Converterer : public iCodeConverter class cWcharIs16BitUcs2Converterer : public iCodeConverter
{ {
public: public:
virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t);
virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t);
virtual ~cWcharIs16BitUcs2Converterer() {} virtual ~cWcharIs16BitUcs2Converterer()
{
}
}; };
#endif // WCHAR_IS_16_BITS #endif // WCHAR_IS_16_BITS
@ -253,10 +246,12 @@ public:
class cGoodEnoughConverterer : public iCodeConverter class cGoodEnoughConverterer : public iCodeConverter
{ {
public: public:
virtual int Convert( ntmbs_t, size_t, const_ntdbs_t, size_t ); virtual int Convert(ntmbs_t, size_t, const_ntdbs_t, size_t);
virtual int Convert( ntdbs_t, size_t, const_ntmbs_t, size_t ); virtual int Convert(ntdbs_t, size_t, const_ntmbs_t, size_t);
virtual ~cGoodEnoughConverterer() {} virtual ~cGoodEnoughConverterer()
{
}
}; };
@ -269,14 +264,14 @@ class cConvertUtil
TSS_HIGH_ASCII_START = 0x0080u, TSS_HIGH_ASCII_START = 0x0080u,
TSS_HIGH_ASCII_END = 0x00FFu TSS_HIGH_ASCII_END = 0x00FFu
}; };
public:
static dbchar_t ConvertNonChar( mbchar_t ch );
static mbchar_t ConvertNonChar( dbchar_t ch );
static bool ValueInReservedRange( mbchar_t ch ); public:
static bool ValueInReservedRange( dbchar_t ch ); static dbchar_t ConvertNonChar(mbchar_t ch);
static mbchar_t ConvertNonChar(dbchar_t ch);
static bool ValueInReservedRange(mbchar_t ch);
static bool ValueInReservedRange(dbchar_t ch);
}; };
#endif //__CODECONVERT_H #endif //__CODECONVERT_H

View File

@ -39,21 +39,21 @@
#include "core.h" #include "core.h"
#include "coreerrors.h" #include "coreerrors.h"
#include "codeconvert.h" // for: iCodeConverter::GetInstance #include "codeconvert.h" // for: iCodeConverter::GetInstance
#include "twlocale.h" // for: cTWLocale::InitGlobalLocale #include "twlocale.h" // for: cTWLocale::InitGlobalLocale
TSS_ImplementPackage( cCore ) TSS_ImplementPackage(cCore)
cCore::cCore() cCore::cCore()
{ {
TSS_REGISTER_PKG_ERRORS( core ); TSS_REGISTER_PKG_ERRORS(core);
// NOTE: Initialize code converter when cCore is a dependency // NOTE: Initialize code converter when cCore is a dependency
// of another package (created on first call to GetInstance(), // of another package (created on first call to GetInstance(),
// forcing creation here to hasten the display of any errors) // forcing creation here to hasten the display of any errors)
cDebug::SetDebugLevel( cDebug::D_DEBUG ); cDebug::SetDebugLevel(cDebug::D_DEBUG);
cDebug::AddOutTarget( cDebug::OUT_STDOUT ); cDebug::AddOutTarget(cDebug::OUT_STDOUT);
cTWLocale::InitGlobalLocale(); cTWLocale::InitGlobalLocale();
@ -64,4 +64,3 @@ cCore::~cCore()
{ {
iCodeConverter::Finit(); iCodeConverter::Finit();
} }

View File

@ -43,20 +43,18 @@
//--Requirements //--Requirements
#include "package.h" // for: Packaging Abstraction #include "package.h" // for: Packaging Abstraction
//--Classes //--Classes
TSS_BeginPackage( cCore ) TSS_BeginPackage(cCore)
TSS_DECLARE_STRINGTABLE; TSS_DECLARE_STRINGTABLE;
public: public:
cCore();
~cCore();
cCore(); TSS_EndPackage(cCore)
~cCore();
TSS_EndPackage( cCore )
#endif //__CORE_H #endif //__CORE_H

View File

@ -49,118 +49,118 @@
#include "ntmbs.h" #include "ntmbs.h"
#include "displayencoder.h" #include "displayencoder.h"
TSS_BEGIN_ERROR_REGISTRATION( core ) TSS_BEGIN_ERROR_REGISTRATION(core)
/// Internal /// Internal
TSS_REGISTER_ERROR( eInternal(), _T("Internal error.") ) TSS_REGISTER_ERROR(eInternal(), _T("Internal error."))
/// General /// General
TSS_REGISTER_ERROR( eErrorGeneral(), _T("General Error") ); TSS_REGISTER_ERROR(eErrorGeneral(), _T("General Error"));
TSS_REGISTER_ERROR( eOpen(), _T("File could not be opened.") ); TSS_REGISTER_ERROR(eOpen(), _T("File could not be opened."));
TSS_REGISTER_ERROR( eOpenRead(), _T("File could not be opened for reading.") ); TSS_REGISTER_ERROR(eOpenRead(), _T("File could not be opened for reading."));
TSS_REGISTER_ERROR( eOpenWrite(), _T("File could not be opened for writing.") ); TSS_REGISTER_ERROR(eOpenWrite(), _T("File could not be opened for writing."));
TSS_REGISTER_ERROR( eBadModeSwitch(), _T("Unknown mode specified.") ); TSS_REGISTER_ERROR(eBadModeSwitch(), _T("Unknown mode specified."));
TSS_REGISTER_ERROR( eBadCmdLine(), _T("Command line error.") ); TSS_REGISTER_ERROR(eBadCmdLine(), _T("Command line error."));
/// Archive /// Archive
TSS_REGISTER_ERROR( eArchive(), _T("Archive error.") ) TSS_REGISTER_ERROR(eArchive(), _T("Archive error."))
TSS_REGISTER_ERROR( eArchiveOpen(), _T("File could not be opened.") ) TSS_REGISTER_ERROR(eArchiveOpen(), _T("File could not be opened."))
TSS_REGISTER_ERROR( eArchiveWrite(), _T("File could not be written.") ) TSS_REGISTER_ERROR(eArchiveWrite(), _T("File could not be written."))
TSS_REGISTER_ERROR( eArchiveRead(), _T("File could not be read.") ) TSS_REGISTER_ERROR(eArchiveRead(), _T("File could not be read."))
TSS_REGISTER_ERROR( eArchiveEOF(), _T("End of file reached.") ) TSS_REGISTER_ERROR(eArchiveEOF(), _T("End of file reached."))
TSS_REGISTER_ERROR( eArchiveSeek(), _T("File seek failed.") ) TSS_REGISTER_ERROR(eArchiveSeek(), _T("File seek failed."))
TSS_REGISTER_ERROR( eArchiveMemmap(), _T("Memory mapped archive file invalid.") ) TSS_REGISTER_ERROR(eArchiveMemmap(), _T("Memory mapped archive file invalid."))
TSS_REGISTER_ERROR( eArchiveOutOfMem(), _T("Archive ran out of memory.") ) TSS_REGISTER_ERROR(eArchiveOutOfMem(), _T("Archive ran out of memory."))
TSS_REGISTER_ERROR( eArchiveInvalidOp(),_T("Archive logic error.") ) TSS_REGISTER_ERROR(eArchiveInvalidOp(), _T("Archive logic error."))
TSS_REGISTER_ERROR( eArchiveFormat(), _T("Archive file format invalid.") ) TSS_REGISTER_ERROR(eArchiveFormat(), _T("Archive file format invalid."))
TSS_REGISTER_ERROR( eArchiveNotRegularFile(), _T("File is not a regular file.") ) TSS_REGISTER_ERROR(eArchiveNotRegularFile(), _T("File is not a regular file."))
TSS_REGISTER_ERROR( eArchiveCrypto(), _T("File could not be decrypted.") ) TSS_REGISTER_ERROR(eArchiveCrypto(), _T("File could not be decrypted."))
TSS_REGISTER_ERROR( eArchiveStringTooLong(), _T("String was too long.") ) TSS_REGISTER_ERROR(eArchiveStringTooLong(), _T("String was too long."))
/// File /// File
TSS_REGISTER_ERROR( eFile(), _T("File error.") ) TSS_REGISTER_ERROR(eFile(), _T("File error."))
TSS_REGISTER_ERROR( eFileOpen(), _T("File could not be opened.") ) TSS_REGISTER_ERROR(eFileOpen(), _T("File could not be opened."))
TSS_REGISTER_ERROR( eFileWrite(), _T("File could not be written.") ) TSS_REGISTER_ERROR(eFileWrite(), _T("File could not be written."))
TSS_REGISTER_ERROR( eFileRead(), _T("File could not be read.") ) TSS_REGISTER_ERROR(eFileRead(), _T("File could not be read."))
TSS_REGISTER_ERROR( eFileEOF(), _T("End of file reached.") ) TSS_REGISTER_ERROR(eFileEOF(), _T("End of file reached."))
TSS_REGISTER_ERROR( eFileSeek(), _T("File seek failed.") ) TSS_REGISTER_ERROR(eFileSeek(), _T("File seek failed."))
TSS_REGISTER_ERROR( eFileInvalidOp(), _T("File logic error.") ) TSS_REGISTER_ERROR(eFileInvalidOp(), _T("File logic error."))
TSS_REGISTER_ERROR( eFileTrunc(), _T("File could not be truncated.") ) TSS_REGISTER_ERROR(eFileTrunc(), _T("File could not be truncated."))
TSS_REGISTER_ERROR( eFileClose(), _T("File could not be closed.") ) TSS_REGISTER_ERROR(eFileClose(), _T("File could not be closed."))
TSS_REGISTER_ERROR( eFileFlush(), _T("File could not be flushed.") ) TSS_REGISTER_ERROR(eFileFlush(), _T("File could not be flushed."))
TSS_REGISTER_ERROR( eFileRewind(), _T("File could not be rewound.") ) TSS_REGISTER_ERROR(eFileRewind(), _T("File could not be rewound."))
/// General API failures /// General API failures
TSS_REGISTER_ERROR(eUnix(), _T("Unix API failure.") ) TSS_REGISTER_ERROR(eUnix(), _T("Unix API failure."))
/// FSServices /// FSServices
TSS_REGISTER_ERROR( eFSServices(), _T("File system error.") ) TSS_REGISTER_ERROR(eFSServices(), _T("File system error."))
TSS_REGISTER_ERROR( eFSServicesGeneric(),_T("File system error.") ) TSS_REGISTER_ERROR(eFSServicesGeneric(), _T("File system error."))
/// Serializer /// Serializer
TSS_REGISTER_ERROR( eSerializerUnknownType(), _T("Unknown type encountered in file.\nFile format may not be valid for this platform.") ) TSS_REGISTER_ERROR(eSerializerUnknownType(),
TSS_REGISTER_ERROR( eSerializerInputStreamFmt(), _T("Invalid input stream format.") ) _T("Unknown type encountered in file.\nFile format may not be valid for this platform."))
TSS_REGISTER_ERROR( eSerializerOutputStreamFmt(), _T("Invalid output stream format.") ) TSS_REGISTER_ERROR(eSerializerInputStreamFmt(), _T("Invalid input stream format."))
TSS_REGISTER_ERROR( eSerializerInputStremTypeArray(), _T("A bad index was encountered in file.") ) TSS_REGISTER_ERROR(eSerializerOutputStreamFmt(), _T("Invalid output stream format."))
TSS_REGISTER_ERROR( eSerializerArchive(), _T("File read encountered an archive error.") ) TSS_REGISTER_ERROR(eSerializerInputStremTypeArray(), _T("A bad index was encountered in file."))
TSS_REGISTER_ERROR( eSerializerVersionMismatch(), _T("File version mismatch.") ) TSS_REGISTER_ERROR(eSerializerArchive(), _T("File read encountered an archive error."))
TSS_REGISTER_ERROR( eSerializerEncryption(), _T("File encryption error.") ) TSS_REGISTER_ERROR(eSerializerVersionMismatch(), _T("File version mismatch."))
TSS_REGISTER_ERROR( eSerializer(), _T("File format error.") ) TSS_REGISTER_ERROR(eSerializerEncryption(), _T("File encryption error."))
TSS_REGISTER_ERROR(eSerializer(), _T("File format error."))
/// Command Line /// Command Line
TSS_REGISTER_ERROR( eCmdLine(), _T("Command line parsing error.") ) TSS_REGISTER_ERROR(eCmdLine(), _T("Command line parsing error."))
TSS_REGISTER_ERROR( eCmdLineInvalidArg(), _T("Invalid argument passed on command line.") ) TSS_REGISTER_ERROR(eCmdLineInvalidArg(), _T("Invalid argument passed on command line."))
TSS_REGISTER_ERROR( eCmdLineBadArgParam(), _T("Incorrect number of parameters to a command line argument.") ) TSS_REGISTER_ERROR(eCmdLineBadArgParam(), _T("Incorrect number of parameters to a command line argument."))
TSS_REGISTER_ERROR( eCmdLineBadParam(), _T("Incorrect number of parameters on command line.") ) TSS_REGISTER_ERROR(eCmdLineBadParam(), _T("Incorrect number of parameters on command line."))
TSS_REGISTER_ERROR( eCmdLineBadSwitchPos(), _T("Switch appears after final command line parameter.") ) TSS_REGISTER_ERROR(eCmdLineBadSwitchPos(), _T("Switch appears after final command line parameter."))
TSS_REGISTER_ERROR( eCmdLineMutEx(), _T("Specified command line switches are mutually exclusive.") ) TSS_REGISTER_ERROR(eCmdLineMutEx(), _T("Specified command line switches are mutually exclusive."))
TSS_REGISTER_ERROR( eCmdLineDependency(), _T("Command line parameter missing.") ) TSS_REGISTER_ERROR(eCmdLineDependency(), _T("Command line parameter missing."))
TSS_REGISTER_ERROR( eCmdLineMultiArg(), _T("Command line argument specified more than once.") ) TSS_REGISTER_ERROR(eCmdLineMultiArg(), _T("Command line argument specified more than once."))
/// TWLocale /// TWLocale
TSS_REGISTER_ERROR( eTWLocale(), _T("Localization error.") ) TSS_REGISTER_ERROR(eTWLocale(), _T("Localization error."))
TSS_REGISTER_ERROR( eTWLocaleBadNumFormat(),_T("Bad number format.") ) TSS_REGISTER_ERROR(eTWLocaleBadNumFormat(), _T("Bad number format."))
/// Character Handling (defined in ntmbs.h) /// Character Handling (defined in ntmbs.h)
TSS_REGISTER_ERROR( eCharacter(), _T("General Character Handling Error.") ) TSS_REGISTER_ERROR(eCharacter(), _T("General Character Handling Error."))
TSS_REGISTER_ERROR( eCharacterEncoding(), _T("Character Encoding Error.") ) TSS_REGISTER_ERROR(eCharacterEncoding(), _T("Character Encoding Error."))
/// Character Conversion Handling (defined in <codeconvert.h>) /// Character Conversion Handling (defined in <codeconvert.h>)
TSS_REGISTER_ERROR( eConverter(), _T("General conversion error.") ) TSS_REGISTER_ERROR(eConverter(), _T("General conversion error."))
TSS_REGISTER_ERROR( eConverterReset(), _T("Converter handle could not be reset.") ) TSS_REGISTER_ERROR(eConverterReset(), _T("Converter handle could not be reset."))
TSS_REGISTER_ERROR( eConverterFatal(), _T("Catastrophic conversion error.") ) TSS_REGISTER_ERROR(eConverterFatal(), _T("Catastrophic conversion error."))
TSS_REGISTER_ERROR( eConverterUnsupportedConversion(), _T("Unsupported character conversion.") ) TSS_REGISTER_ERROR(eConverterUnsupportedConversion(), _T("Unsupported character conversion."))
TSS_REGISTER_ERROR( eConverterUnknownCodepage(), _T("Could not identify code page.") ) TSS_REGISTER_ERROR(eConverterUnknownCodepage(), _T("Could not identify code page."))
// //
// Display Encoder // Display Encoder
// //
TSS_REGISTER_ERROR( eEncoder(), _T("Display encoder error.") ) TSS_REGISTER_ERROR(eEncoder(), _T("Display encoder error."))
TSS_REGISTER_ERROR( eBadDecoderInput(), _T("Bad input to display encoder.") ) TSS_REGISTER_ERROR(eBadDecoderInput(), _T("Bad input to display encoder."))
TSS_REGISTER_ERROR( eBadHexConversion(), _T("Bad hex conversion in display encoder.") ) TSS_REGISTER_ERROR(eBadHexConversion(), _T("Bad hex conversion in display encoder."))
TSS_REGISTER_ERROR( eUnknownEscapeEncoding(), _T("Unknown encoding in display encoder input.") ) TSS_REGISTER_ERROR(eUnknownEscapeEncoding(), _T("Unknown encoding in display encoder input."))
TSS_END_ERROR_REGISTRATION() TSS_END_ERROR_REGISTRATION()

View File

@ -41,8 +41,7 @@
#include "core/errortable.h" #include "core/errortable.h"
TSS_DECLARE_ERROR_REGISTRATION( core ) TSS_DECLARE_ERROR_REGISTRATION(core)
#endif//__COREERRORS_H #endif //__COREERRORS_H

View File

@ -35,39 +35,35 @@
// Creator.: Robert DiFalco (rdifalco) // Creator.: Robert DiFalco (rdifalco)
// //
#include "stdcore.h" // for: pch (required by all core source modules) #include "stdcore.h" // for: pch (required by all core source modules)
#include "corestrings.h" // for: cCore and core::STR_IDS #include "corestrings.h" // for: cCore and core::STR_IDS
TSS_BeginStringtable( cCore ) TSS_BeginStringtable(cCore)
TSS_StringEntry( core::STR_ERR2_ARCH_CRYPTO_ERR, _T("File could not be decrypted.") ), TSS_StringEntry(core::STR_ERR2_ARCH_CRYPTO_ERR, _T("File could not be decrypted.")),
TSS_StringEntry( core::STR_ERR2_BAD_ARG_PARAMS, _T("Argument: ") ), TSS_StringEntry(core::STR_ERR2_BAD_ARG_PARAMS, _T("Argument: ")),
TSS_StringEntry( core::STR_ERROR_ERROR, _T("### Error") ), TSS_StringEntry(core::STR_ERROR_ERROR, _T("### Error")),
TSS_StringEntry( core::STR_ERROR_WARNING, _T("### Warning") ), TSS_StringEntry(core::STR_ERROR_WARNING, _T("### Warning")), TSS_StringEntry(core::STR_ERROR_COLON, _T(":")),
TSS_StringEntry( core::STR_ERROR_COLON, _T(":") ), TSS_StringEntry(core::STR_ERROR_HEADER, _T("### ")), TSS_StringEntry(core::STR_ERROR_EXITING, _T("Exiting...")),
TSS_StringEntry( core::STR_ERROR_HEADER, _T("### ") ), TSS_StringEntry(core::STR_ERROR_CONTINUING, _T("Continuing...")),
TSS_StringEntry( core::STR_ERROR_EXITING, _T("Exiting...") ), TSS_StringEntry(core::STR_ERR2_FILENAME, _T("Filename: ")),
TSS_StringEntry( core::STR_ERROR_CONTINUING, _T("Continuing...") ), TSS_StringEntry(core::STR_ERROR_FILENAME, _T("Filename: ")), TSS_StringEntry(core::STR_UNKNOWN, _T("Unknown")),
TSS_StringEntry( core::STR_ERR2_FILENAME, _T("Filename: ") ), TSS_StringEntry(core::STR_NUMBER_TOO_BIG, _T("Number too big")),
TSS_StringEntry( core::STR_ERROR_FILENAME, _T("Filename: ") ), TSS_StringEntry(core::STR_SIGNAL, _T("Software interrupt forced exit:")),
TSS_StringEntry( core::STR_UNKNOWN, _T("Unknown") ), TSS_StringEntry(core::STR_NEWLINE, _T("\n")),
TSS_StringEntry( core::STR_NUMBER_TOO_BIG, _T("Number too big") ), TSS_StringEntry(core::STR_MEMARCHIVE_FILENAME, _T("Error occured in internal memory file")),
TSS_StringEntry( core::STR_SIGNAL, _T("Software interrupt forced exit:") ), TSS_StringEntry(core::STR_MEMARCHIVE_ERRSTR, _T("")),
TSS_StringEntry( core::STR_NEWLINE, _T("\n") ), TSS_StringEntry(core::STR_ENDOFTIME, _T("Tripwire is not designed to run past the year 2038.\nNow exiting...")),
TSS_StringEntry( core::STR_MEMARCHIVE_FILENAME, _T("Error occured in internal memory file") ), TSS_StringEntry(core::STR_UNKNOWN_TIME, _T("Unknown time")),
TSS_StringEntry( core::STR_MEMARCHIVE_ERRSTR, _T("") ), TSS_StringEntry(
TSS_StringEntry( core::STR_ENDOFTIME, _T("Tripwire is not designed to run past the year 2038.\nNow exiting...") ), core::STR_BAD_TEMPDIRECTORY,
TSS_StringEntry( core::STR_UNKNOWN_TIME, _T("Unknown time") ), _T("Solution: Check existence/permissions for directory specified by TEMPDIRECTORY in config file")),
TSS_StringEntry( core::STR_BAD_TEMPDIRECTORY, _T("Solution: Check existence/permissions for directory specified by TEMPDIRECTORY in config file") ),
/// Particularly useful for eCharacter and eCharacterEncoding /// Particularly useful for eCharacter and eCharacterEncoding
TSS_StringEntry( core::STR_ERR_ISNULL, _T("Argument cannot be null.") ), TSS_StringEntry(core::STR_ERR_ISNULL, _T("Argument cannot be null.")),
TSS_StringEntry( core::STR_ERR_OVERFLOW, _T("An overflow has been detected.") ), TSS_StringEntry(core::STR_ERR_OVERFLOW, _T("An overflow has been detected.")),
TSS_StringEntry( core::STR_ERR_UNDERFLOW, _T("An underflow has been detected.") ), TSS_StringEntry(core::STR_ERR_UNDERFLOW, _T("An underflow has been detected.")),
TSS_StringEntry( core::STR_ERR_BADCHAR, _T("Input contained an invalid character.") ) TSS_StringEntry(core::STR_ERR_BADCHAR, _T("Input contained an invalid character."))
TSS_EndStringtable( cCore )
TSS_EndStringtable(cCore)

View File

@ -40,42 +40,24 @@
#define __CORESTRINGS_H #define __CORESTRINGS_H
#include "core.h" // for: STRINGTABLE syntax #include "core.h" // for: STRINGTABLE syntax
//--Message Keys //--Message Keys
TSS_BeginStringIds( core ) TSS_BeginStringIds(core)
STR_ERR2_ARCH_CRYPTO_ERR, STR_ERR2_ARCH_CRYPTO_ERR,
STR_ERR2_BAD_ARG_PARAMS, STR_ERR2_BAD_ARG_PARAMS, STR_ERROR_ERROR, STR_ERROR_WARNING, STR_ERROR_COLON, STR_ERROR_HEADER, STR_ERROR_EXITING,
STR_ERROR_ERROR, STR_ERROR_CONTINUING, STR_ERR2_FILENAME, STR_ERROR_FILENAME, STR_NUMBER_TOO_BIG, STR_UNKNOWN, STR_SIGNAL,
STR_ERROR_WARNING, STR_NEWLINE, STR_MEMARCHIVE_FILENAME, STR_MEMARCHIVE_ERRSTR, STR_ENDOFTIME, STR_UNKNOWN_TIME, STR_BAD_TEMPDIRECTORY,
STR_ERROR_COLON,
STR_ERROR_HEADER,
STR_ERROR_EXITING,
STR_ERROR_CONTINUING,
STR_ERR2_FILENAME,
STR_ERROR_FILENAME,
STR_NUMBER_TOO_BIG,
STR_UNKNOWN,
STR_SIGNAL,
STR_NEWLINE,
STR_MEMARCHIVE_FILENAME,
STR_MEMARCHIVE_ERRSTR,
STR_ENDOFTIME,
STR_UNKNOWN_TIME,
STR_BAD_TEMPDIRECTORY,
/// Particularly useful for eCharacterSet and eCharacterEncoding /// Particularly useful for eCharacterSet and eCharacterEncoding
STR_ERR_ISNULL, STR_ERR_ISNULL, STR_ERR_OVERFLOW, STR_ERR_UNDERFLOW,
STR_ERR_OVERFLOW,
STR_ERR_UNDERFLOW,
STR_ERR_BADCHAR STR_ERR_BADCHAR
TSS_EndStringIds( core ) TSS_EndStringIds(core)
#endif //__CORESTRINGS_H #endif //__CORESTRINGS_H

View File

@ -37,17 +37,17 @@
#ifdef DEBUG #ifdef DEBUG
#ifndef va_start # ifndef va_start
#include <cstdarg> # include <cstdarg>
#endif # endif
#include <cwchar> #include <cwchar>
#include <fstream> #include <fstream>
#include <cstdio> #include <cstdio>
int cDebug::mDebugLevel(10); int cDebug::mDebugLevel(10);
uint32 cDebug::mOutMask(cDebug::OUT_TRACE); uint32 cDebug::mOutMask(cDebug::OUT_TRACE);
std::ofstream cDebug::logfile; std::ofstream cDebug::logfile;
//mDebugLevel default == 10, mOutMask default == OUT_TRACE. //mDebugLevel default == 10, mOutMask default == OUT_TRACE.
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Constructors and Destructor // Constructors and Destructor
@ -61,14 +61,14 @@ cDebug::cDebug(const char* label)
mLabel[cnt] = '\0'; mLabel[cnt] = '\0';
} }
cDebug::cDebug(const cDebug &rhs) cDebug::cDebug(const cDebug& rhs)
{ {
strncpy(mLabel, rhs.mLabel, MAX_LABEL); strncpy(mLabel, rhs.mLabel, MAX_LABEL);
} }
cDebug::~cDebug() cDebug::~cDebug()
{ {
if(logfile) if (logfile)
logfile.close(); logfile.close();
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -86,7 +86,6 @@ void cDebug::Trace(int levelNum, const char* format, ...)
va_start(args, format); va_start(args, format);
DoTrace(format, args); DoTrace(format, args);
va_end(args); va_end(args);
} }
@ -96,10 +95,10 @@ void cDebug::Trace(int levelNum, const char* format, ...)
// console, etc... // console, etc...
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cDebug::DoTrace(const char *format, va_list &args) void cDebug::DoTrace(const char* format, va_list& args)
{ {
size_t guard1 = 0xBABABABA; size_t guard1 = 0xBABABABA;
char out[2048]; char out[2048];
size_t guard2 = 0xBABABABA; size_t guard2 = 0xBABABABA;
vsnprintf(out, 2048, format, args); vsnprintf(out, 2048, format, args);
@ -135,14 +134,14 @@ void cDebug::DoTrace(const char *format, va_list &args)
logfile.flush(); logfile.flush();
} }
} }
#ifdef DEBUG # ifdef DEBUG
// //
// wrappers around Trace() that requires less typing // wrappers around Trace() that requires less typing
// TODO: this is quick and dirty, but lets me check in all these files right away. --ghk // TODO: this is quick and dirty, but lets me check in all these files right away. --ghk
// //
void cDebug::TraceAlways(const char *format, ...) void cDebug::TraceAlways(const char* format, ...)
{ {
if (D_ALWAYS > mDebugLevel) if (D_ALWAYS > mDebugLevel)
return; return;
@ -154,7 +153,7 @@ void cDebug::TraceAlways(const char *format, ...)
va_end(args); va_end(args);
} }
void cDebug::TraceError(const char *format, ...) void cDebug::TraceError(const char* format, ...)
{ {
if (D_ERROR > mDebugLevel) if (D_ERROR > mDebugLevel)
return; return;
@ -166,7 +165,7 @@ void cDebug::TraceError(const char *format, ...)
va_end(args); va_end(args);
} }
void cDebug::TraceWarning(const char *format, ...) void cDebug::TraceWarning(const char* format, ...)
{ {
if (D_WARNING > mDebugLevel) if (D_WARNING > mDebugLevel)
return; return;
@ -178,7 +177,7 @@ void cDebug::TraceWarning(const char *format, ...)
va_end(args); va_end(args);
} }
void cDebug::TraceDebug(const char *format, ...) void cDebug::TraceDebug(const char* format, ...)
{ {
if (D_DEBUG > mDebugLevel) if (D_DEBUG > mDebugLevel)
return; return;
@ -190,7 +189,7 @@ void cDebug::TraceDebug(const char *format, ...)
va_end(args); va_end(args);
} }
void cDebug::TraceDetail(const char *format, ...) void cDebug::TraceDetail(const char* format, ...)
{ {
if (D_DETAIL > mDebugLevel) if (D_DETAIL > mDebugLevel)
return; return;
@ -202,7 +201,7 @@ void cDebug::TraceDetail(const char *format, ...)
va_end(args); va_end(args);
} }
void cDebug::TraceNever(const char *format, ...) void cDebug::TraceNever(const char* format, ...)
{ {
if (D_NEVER > mDebugLevel) if (D_NEVER > mDebugLevel)
return; return;
@ -214,12 +213,12 @@ void cDebug::TraceNever(const char *format, ...)
va_end(args); va_end(args);
} }
void cDebug::TraceVaArgs( int iDebugLevel, const char *format, va_list &args ) void cDebug::TraceVaArgs(int iDebugLevel, const char* format, va_list& args)
{ {
if ( iDebugLevel <= mDebugLevel ) if (iDebugLevel <= mDebugLevel)
DoTrace( format, args); DoTrace(format, args);
} }
#endif // DEBUG # endif // DEBUG
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// AddOutTarget -- Attempts to add a new target for trace/debug output. // AddOutTarget -- Attempts to add a new target for trace/debug output.
@ -231,7 +230,8 @@ bool cDebug::AddOutTarget(OutTarget target)
mOutMask |= OUT_STDOUT; mOutMask |= OUT_STDOUT;
if (target == OUT_TRACE) if (target == OUT_TRACE)
mOutMask |= OUT_TRACE; mOutMask |= OUT_TRACE;
if (target == OUT_FILE) { if (target == OUT_FILE)
{
mOutMask |= OUT_FILE; mOutMask |= OUT_FILE;
return false; return false;
} }
@ -283,13 +283,15 @@ bool cDebug::SetOutputFile(const char* filename)
logfile.open(filename, std::ios_base::out | std::ios_base::ate | std::ios_base::app); logfile.open(filename, std::ios_base::out | std::ios_base::ate | std::ios_base::app);
else else
logfile.setf(std::ios_base::hex, std::ios_base::basefield); logfile.setf(std::ios_base::hex, std::ios_base::basefield);
//make sure info. will not be clobbered. //make sure info. will not be clobbered.
//Should be open now- if not, abort. //Should be open now- if not, abort.
if (!logfile) { if (!logfile)
{
mOutMask ^= OUT_FILE; mOutMask ^= OUT_FILE;
return false; return false;
} else }
else
mOutMask |= OUT_FILE; mOutMask |= OUT_FILE;
return true; return true;
} }
@ -298,7 +300,7 @@ bool cDebug::SetOutputFile(const char* filename)
// DebugOut -- Works just like TRACE. note: there is an internal buffer size // DebugOut -- Works just like TRACE. note: there is an internal buffer size
// of 1024; traces larger than that will have unpredictable results. // of 1024; traces larger than that will have unpredictable results.
////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
void cDebug::DebugOut( const char* lpOutputString, ... ) void cDebug::DebugOut(const char* lpOutputString, ...)
{ {
char buf[2048]; char buf[2048];
// create the output buffer // create the output buffer
@ -307,9 +309,9 @@ void cDebug::DebugOut( const char* lpOutputString, ... )
vsnprintf(buf, 2048, lpOutputString, args); vsnprintf(buf, 2048, lpOutputString, args);
va_end(args); va_end(args);
#ifdef DEBUG # ifdef DEBUG
TCERR << buf; TCERR << buf;
#endif //_DEBUG # endif //_DEBUG
TCOUT.flush(); TCOUT.flush();
} }
@ -318,4 +320,3 @@ void cDebug::DebugOut( const char* lpOutputString, ... )
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
// ASSERT macro support function // ASSERT macro support function
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////

View File

@ -40,19 +40,17 @@
#include <assert.h> #include <assert.h>
#include <iostream> #include <iostream>
/* Do it in this order, because autoconf checks for <stdarg.h> /* Do it in this order, because autoconf checks for <stdarg.h>
* first i.e. if HAVE_VARARGS_H is defined, it is only because * first i.e. if HAVE_VARARGS_H is defined, it is only because
* <stdarg.h> couldn't be found. * <stdarg.h> couldn't be found.
*/ */
#ifdef HAVE_VARARGS_H #ifdef HAVE_VARARGS_H
# include <varargs.h> #include <varargs.h>
#else #else
# ifdef HAVE_STDARG_H # ifdef HAVE_STDARG_H
# include <stdarg.h> # include <stdarg.h>
# endif # endif
#endif #endif
#include "types.h" #include "types.h"
@ -80,19 +78,19 @@ class cDebug
public: public:
enum OutTarget enum OutTarget
{ {
OUT_STDOUT = 1, OUT_STDOUT = 1,
OUT_TRACE = 2, OUT_TRACE = 2,
OUT_FILE = 4 OUT_FILE = 4
}; };
enum DebugLevel enum DebugLevel
{ {
D_ALWAYS = 0, D_ALWAYS = 0,
D_ERROR = 1, D_ERROR = 1,
D_WARNING = 4, D_WARNING = 4,
D_DEBUG = 8, D_DEBUG = 8,
D_DETAIL = 16, D_DETAIL = 16,
D_NEVER = 1000 D_NEVER = 1000
}; };
cDebug(const char* pLabel); cDebug(const char* pLabel);
@ -107,59 +105,61 @@ public:
// The wide character overloads of these functions will expect wide strings // The wide character overloads of these functions will expect wide strings
// for %s options. // for %s options.
// //
void TraceAlways (const char *format, ...); void TraceAlways(const char* format, ...);
void TraceError (const char *format, ...); void TraceError(const char* format, ...);
void TraceWarning (const char *format, ...); void TraceWarning(const char* format, ...);
void TraceDebug (const char *format, ...); void TraceDebug(const char* format, ...);
void TraceDetail (const char *format, ...); void TraceDetail(const char* format, ...);
void TraceNever (const char *format, ...); void TraceNever(const char* format, ...);
// these are of use if you are inside a function with a "..." as an argument // these are of use if you are inside a function with a "..." as an argument
// and you want to trace those args // and you want to trace those args
void TraceVaArgs (int iDebugLevel, const char *format, va_list &args); void TraceVaArgs(int iDebugLevel, const char* format, va_list& args);
// ...but you can still choose to use this interface... // ...but you can still choose to use this interface...
void Trace(int levelNum, const char* format, ...); void Trace(int levelNum, const char* format, ...);
// Outputs based on levelnum. If levelnum <= global debug, print. // Outputs based on levelnum. If levelnum <= global debug, print.
public: public:
static bool AddOutTarget(OutTarget target);
static bool RemoveOutTarget(OutTarget target);
// used to specify the out target....
static bool HasOutTarget(OutTarget target);
static bool AddOutTarget (OutTarget target); static bool SetOutputFile(const char* filename);
static bool RemoveOutTarget (OutTarget target); // specifies the output file name used when OUT_FILE is set
// used to specify the out target.... static void SetDebugLevel(int level);
static bool HasOutTarget (OutTarget target); static int GetDebugLevel(void);
// gets and sets the global debug level. Trace output at or below this
// level will be output.
static bool SetOutputFile (const char* filename); static void DebugOut(const char* lpOutputString, ...);
// specifies the output file name used when OUT_FILE is set // Works just like TRACE
static void SetDebugLevel (int level); // note: there is an internal buffer size of 1024; traces larger
static int GetDebugLevel (void); // than that will have unpredictable and probably bad results
// gets and sets the global debug level. Trace output at or below this
// level will be output.
static void DebugOut ( const char* lpOutputString, ... );
// Works just like TRACE
// note: there is an internal buffer size of 1024; traces larger
// than that will have unpredictable and probably bad results
private: private:
#ifdef DEBUG #ifdef DEBUG
enum { MAX_LABEL = 128 }; enum
{
MAX_LABEL = 128
};
static int mDebugLevel; static int mDebugLevel;
static uint32 mOutMask; static uint32 mOutMask;
static std::ofstream logfile; static std::ofstream logfile;
char mLabel[MAX_LABEL]; char mLabel[MAX_LABEL];
// helper functions // helper functions
void DoTrace(const char *format, va_list &args); void DoTrace(const char* format, va_list& args);
#endif #endif
}; };
#ifdef DEBUG #ifdef DEBUG
#define TRACE cDebug::DebugOut # define TRACE cDebug::DebugOut
#else #else
#define TRACE 1 ? (void)0 : cDebug::DebugOut # define TRACE 1 ? (void)0 : cDebug::DebugOut
#endif // DEBUG #endif // DEBUG
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
@ -179,51 +179,90 @@ inline int cDebug::GetDebugLevel()
return mDebugLevel; return mDebugLevel;
} }
#else // DEBUG # else // DEBUG
inline cDebug::cDebug (const char *) {} inline cDebug::cDebug(const char*)
inline cDebug::~cDebug () {} {
inline cDebug::cDebug (const cDebug&) {} }
inline void cDebug::TraceAlways (const char *, ...) {} inline cDebug::~cDebug()
inline void cDebug::TraceError (const char *, ...) {} {
inline void cDebug::TraceWarning (const char *, ...) {} }
inline void cDebug::TraceDebug (const char *, ...) {} inline cDebug::cDebug(const cDebug&)
inline void cDebug::TraceDetail (const char *, ...) {} {
inline void cDebug::TraceNever (const char *, ...) {} }
inline void cDebug::TraceVaArgs (int, const char *, va_list &) {} inline void cDebug::TraceAlways(const char*, ...)
inline void cDebug::Trace (int, const char*, ...) {} {
inline bool cDebug::AddOutTarget (OutTarget) { return false; } }
inline bool cDebug::RemoveOutTarget (OutTarget) { return false; } inline void cDebug::TraceError(const char*, ...)
inline bool cDebug::HasOutTarget (OutTarget) { return false; } {
inline bool cDebug::SetOutputFile (const char*) { return false; } }
inline void cDebug::SetDebugLevel (int) {} inline void cDebug::TraceWarning(const char*, ...)
inline int cDebug::GetDebugLevel (void) { return 0; } {
inline void cDebug::DebugOut ( const char*, ... ) {} }
inline void cDebug::TraceDebug(const char*, ...)
#endif // DEBUG {
}
inline void cDebug::TraceDetail(const char*, ...)
{
}
inline void cDebug::TraceNever(const char*, ...)
{
}
inline void cDebug::TraceVaArgs(int, const char*, va_list&)
{
}
inline void cDebug::Trace(int, const char*, ...)
{
}
inline bool cDebug::AddOutTarget(OutTarget)
{
return false;
}
inline bool cDebug::RemoveOutTarget(OutTarget)
{
return false;
}
inline bool cDebug::HasOutTarget(OutTarget)
{
return false;
}
inline bool cDebug::SetOutputFile(const char*)
{
return false;
}
inline void cDebug::SetDebugLevel(int)
{
}
inline int cDebug::GetDebugLevel(void)
{
return 0;
}
inline void cDebug::DebugOut(const char*, ...)
{
}
# endif // DEBUG
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
// ASSERT macro // ASSERT macro
////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////
#define ASSERTMSG( exp, s ) assert( (exp) != 0 ) # define ASSERTMSG(exp, s) assert((exp) != 0)
#define ASSERT( exp ) assert( (exp) != 0 ) # define ASSERT(exp) assert((exp) != 0)
// if we are not windows we will just use the standard assert() // if we are not windows we will just use the standard assert()
#define TSS_DebugBreak() ASSERT( false ); # define TSS_DebugBreak() ASSERT(false);
#ifndef ASSERT # ifndef ASSERT
#error ASSERT did not get defined!!! # error ASSERT did not get defined!!!
#endif # endif
#ifndef ASSERTMSG # ifndef ASSERTMSG
#error ASSERTMSG did not get defined!!! # error ASSERTMSG did not get defined!!!
#endif # endif
#ifndef TSS_DebugBreak # ifndef TSS_DebugBreak
#error TSS_DebugBreak did not get defined!!! # error TSS_DebugBreak did not get defined!!!
#endif # endif
#endif //__DEBUG_H #endif //__DEBUG_H

File diff suppressed because it is too large Load Diff

View File

@ -40,10 +40,10 @@
// EXCEPTION DECLARATION // EXCEPTION DECLARATION
//========================================================================= //=========================================================================
TSS_EXCEPTION( eEncoder, eError ); TSS_EXCEPTION(eEncoder, eError);
TSS_EXCEPTION( eBadDecoderInput, eEncoder ); TSS_EXCEPTION(eBadDecoderInput, eEncoder);
TSS_EXCEPTION( eBadHexConversion, eEncoder ); TSS_EXCEPTION(eBadHexConversion, eEncoder);
TSS_EXCEPTION( eUnknownEscapeEncoding, eEncoder ); TSS_EXCEPTION(eUnknownEscapeEncoding, eEncoder);
//========================================================================= //=========================================================================
// DECLARATION OF CLASSES // DECLARATION OF CLASSES
@ -59,102 +59,97 @@ class iCharEncoder;
// as long as AllIdentifiersUnique and OnlyOneCatagoryPerChar are true // as long as AllIdentifiersUnique and OnlyOneCatagoryPerChar are true
class cEncoder class cEncoder
{ {
public: public:
enum Encodings enum Encodings
{ {
NON_NARROWABLE = 0x01, // WC -> MB, MB alway narrowable: NON_NARROWABLE = 0x01, // WC -> MB, MB alway narrowable:
NON_PRINTABLE = 0x02, NON_PRINTABLE = 0x02,
BACKSLASH = 0x04, BACKSLASH = 0x04,
DBL_QUOTE = 0x08 DBL_QUOTE = 0x08
}; };
enum Flags enum Flags
{ {
ROUNDTRIP = 0x01, ROUNDTRIP = 0x01,
NON_ROUNDTRIP = 0x02, NON_ROUNDTRIP = 0x02,
ALLOW_WHITESPACE = 0x04 ALLOW_WHITESPACE = 0x04
}; };
cEncoder( int e, int f ); // mask of Encodings cEncoder(int e, int f); // mask of Encodings
virtual ~cEncoder(); virtual ~cEncoder();
void Encode( TSTRING& str ) const; void Encode(TSTRING& str) const;
void Decode( TSTRING& str ) const; // TODO:BAM -- throw error! void Decode(TSTRING& str) const; // TODO:BAM -- throw error!
void ValidateSchema() const; void ValidateSchema() const;
bool OnlyOneCatagoryPerChar() const; bool OnlyOneCatagoryPerChar() const;
bool AllIdentifiersUnique() const; bool AllIdentifiersUnique() const;
bool AllTestsRunOnEncodedString( const TSTRING& str ) const; bool AllTestsRunOnEncodedString(const TSTRING& str) const;
private: private:
typedef std::vector< iCharEncoder* > sack_type; typedef std::vector<iCharEncoder*> sack_type;
TSTRING Encode( TSTRING::const_iterator first, TSTRING
TSTRING::const_iterator last, Encode(TSTRING::const_iterator first, TSTRING::const_iterator last, sack_type::const_iterator encoding) const;
sack_type::const_iterator encoding ) const;
bool RoundTrip() const; bool RoundTrip() const;
bool AllowWhiteSpace() const; bool AllowWhiteSpace() const;
sack_type m_encodings; sack_type m_encodings;
int m_fFlags; int m_fFlags;
}; };
// encodes ( BACKSLASH | DBL_QUOTE | NON_NARROWABLE | NON_PRINTABLE ) // encodes ( BACKSLASH | DBL_QUOTE | NON_NARROWABLE | NON_PRINTABLE )
class cDisplayEncoder : public cEncoder class cDisplayEncoder : public cEncoder
{ {
public: public:
cDisplayEncoder( Flags f = NON_ROUNDTRIP ); cDisplayEncoder(Flags f = NON_ROUNDTRIP);
void Encode( TSTRING& str ) const; void Encode(TSTRING& str) const;
bool Decode( TSTRING& str ) const; bool Decode(TSTRING& str) const;
static TSTRING EncodeInline( const TSTRING& sIn ) static TSTRING EncodeInline(const TSTRING& sIn)
{ {
TSTRING sOut = sIn; TSTRING sOut = sIn;
cDisplayEncoder e; cDisplayEncoder e;
e.Encode( sOut ); e.Encode(sOut);
return sOut; return sOut;
} }
static TSTRING EncodeInlineAllowWS( const TSTRING& sIn ) static TSTRING EncodeInlineAllowWS(const TSTRING& sIn)
{ {
TSTRING sOut = sIn; TSTRING sOut = sIn;
cDisplayEncoder e( (Flags)( NON_ROUNDTRIP | ALLOW_WHITESPACE ) ); cDisplayEncoder e((Flags)(NON_ROUNDTRIP | ALLOW_WHITESPACE));
e.Encode( sOut ); e.Encode(sOut);
return sOut; return sOut;
} }
}; };
class cCharEncoderUtil class cCharEncoderUtil
{ {
public: public:
static bool IsPrintable(TCHAR ch);
static bool IsWhiteSpace(TCHAR ch);
static bool IsPrintable( TCHAR ch ); static TSTRING CharStringToHexValue(const TSTRING& str);
static bool IsWhiteSpace( TCHAR ch );
static TSTRING CharStringToHexValue( const TSTRING& str ); static TSTRING HexValueToCharString(const TSTRING& str);
static TSTRING HexValueToCharString( const TSTRING& str ); static TCHAR hex_to_char(TSTRING::const_iterator first, TSTRING::const_iterator last);
static TCHAR hex_to_char( TSTRING::const_iterator first, static TSTRING char_to_hex(TCHAR ch);
TSTRING::const_iterator last );
static TSTRING char_to_hex( TCHAR ch ); static TSTRING DecodeHexToChar(TSTRING::const_iterator* pcur, const TSTRING::const_iterator end);
static TSTRING DecodeHexToChar( TSTRING::const_iterator* pcur,
const TSTRING::const_iterator end );
enum enum
{ {
BYTE_AS_HEX__IN_TCHARS = 2, BYTE_AS_HEX__IN_TCHARS = 2,
BYTES_PER_TCHAR = sizeof( TCHAR ), BYTES_PER_TCHAR = sizeof(TCHAR),
TCHAR_AS_HEX__IN_TCHARS = BYTE_AS_HEX__IN_TCHARS * BYTES_PER_TCHAR TCHAR_AS_HEX__IN_TCHARS = BYTE_AS_HEX__IN_TCHARS * BYTES_PER_TCHAR
}; };
}; };
#endif //__DISPLAYENCODER_H #endif //__DISPLAYENCODER_H
@ -241,4 +236,3 @@ typedef cDisplayEncoder_<TCHAR> cDisplayEncoder;
#endif //__DISPLAYENCODER_H #endif //__DISPLAYENCODER_H
*/ */

View File

@ -40,29 +40,29 @@
#include "ntmbs.h" #include "ntmbs.h"
#include <iomanip> #include <iomanip>
TSTRING cDisplayUtil::FormatMultiLineString( const TSTRING& str, int nOffset, int nWidth ) TSTRING cDisplayUtil::FormatMultiLineString(const TSTRING& str, int nOffset, int nWidth)
{ {
TOSTRINGSTREAM sstr; TOSTRINGSTREAM sstr;
TSTRING strT; TSTRING strT;
bool fFirstLine = true; bool fFirstLine = true;
for( TSTRING::const_iterator i = str.begin(); i != str.end(); i = *i ? i + 1 : i ) for (TSTRING::const_iterator i = str.begin(); i != str.end(); i = *i ? i + 1 : i)
{ {
// return found -- add line to output string // return found -- add line to output string
if( _T('\n') == *i ) if (_T('\n') == *i)
{ {
// only do offset for strings after the first // only do offset for strings after the first
if( fFirstLine ) if (fFirstLine)
{ {
fFirstLine = false; fFirstLine = false;
} }
else else
{ {
// add offset // add offset
for( int j = 0; j < nOffset; j++ ) for (int j = 0; j < nOffset; j++)
sstr << _T(" "); sstr << _T(" ");
// set width // set width
sstr << std::setw( nWidth ); sstr << std::setw(nWidth);
} }
// add to stringstream // add to stringstream
@ -74,7 +74,7 @@ TSTRING cDisplayUtil::FormatMultiLineString( const TSTRING& str, int nOffset, in
else else
{ {
// add char to string // add char to string
strT.append( i, (TSTRING::const_iterator)(*i ? i + 1 : i) ); strT.append(i, (TSTRING::const_iterator)(*i ? i + 1 : i));
} }
} }
@ -82,19 +82,17 @@ TSTRING cDisplayUtil::FormatMultiLineString( const TSTRING& str, int nOffset, in
// we want our client to be able to say "out << PropAsString() << endl;" // we want our client to be able to say "out << PropAsString() << endl;"
// add offset // add offset
if( ! fFirstLine ) if (!fFirstLine)
{ {
for( int j = 0; j < nOffset; j++ ) for (int j = 0; j < nOffset; j++)
sstr << _T(" "); sstr << _T(" ");
} }
// set width // set width
sstr << std::setw( nWidth ); sstr << std::setw(nWidth);
// now add last string // now add last string
sstr << strT; sstr << strT;
return( sstr.str() ); return (sstr.str());
} }

View File

@ -41,7 +41,7 @@
class cDisplayUtil class cDisplayUtil
{ {
public: public:
static TSTRING FormatMultiLineString( const TSTRING& str, int nOffset, int nWidth ); static TSTRING FormatMultiLineString(const TSTRING& str, int nOffset, int nWidth);
}; };
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -98,4 +98,3 @@ public:
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#endif // #ifndef __DISPLAYUTIL_H #endif // #ifndef __DISPLAYUTIL_H

View File

@ -49,9 +49,9 @@ bool CheckEpoch()
// Rather than crashing, we will exit with a nice message // Rather than crashing, we will exit with a nice message
memset(&time_struct, 0, sizeof(time_struct)); memset(&time_struct, 0, sizeof(time_struct));
time_struct.tm_mday = 1; time_struct.tm_mday = 1;
time_struct.tm_mon = 0; time_struct.tm_mon = 0;
time_struct.tm_year = 138; time_struct.tm_year = 138;
int64 endoftime = cTimeUtil::DateToTime( &time_struct ); int64 endoftime = cTimeUtil::DateToTime(&time_struct);
if (time(0) > endoftime) if (time(0) > endoftime)
{ {
@ -64,4 +64,3 @@ bool CheckEpoch()
return false; return false;
#endif #endif
} }

View File

@ -42,4 +42,3 @@
bool CheckEpoch(); bool CheckEpoch();
#endif #endif

View File

@ -39,13 +39,11 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// CalcHash // CalcHash
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
uint32 eError::CalcHash( const char* name ) uint32 eError::CalcHash(const char* name)
{ {
CRC_INFO crc; CRC_INFO crc;
crcInit( crc ); crcInit(crc);
crcUpdate( crc, (const uint8*)name, strlen( name ) ); crcUpdate(crc, (const uint8*)name, strlen(name));
crcFinit( crc ); crcFinit(crc);
return crc.crc; return crc.crc;
} }

View File

@ -42,14 +42,13 @@
class eError class eError
{ {
public: public:
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Construction and Assignment // Construction and Assignment
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
eError( const TSTRING& msg, uint32 flags = 0 ); eError(const TSTRING& msg, uint32 flags = 0);
explicit eError( const eError& rhs ); explicit eError(const eError& rhs);
explicit eError(); explicit eError();
void operator=( const eError& rhs ); void operator=(const eError& rhs);
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Destruction // Destruction
@ -60,54 +59,54 @@ public:
// Data Access // Data Access
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
virtual uint32 GetID() const = 0; virtual uint32 GetID() const = 0;
// returns a system wide unique identifier for this exception. See the // returns a system wide unique identifier for this exception. See the
// macro below for the typical implementation of this method. // macro below for the typical implementation of this method.
// This is used to associate the error with a string description of the // This is used to associate the error with a string description of the
// error via the global error table. // error via the global error table.
virtual TSTRING GetMsg() const; virtual TSTRING GetMsg() const;
// returns specific information about the error that occured. Provides // returns specific information about the error that occured. Provides
// additional information about the error described by GetID(). It should // additional information about the error described by GetID(). It should
// not provide any information redundant with GetID(). // not provide any information redundant with GetID().
// //
// The string passed to the constructor should be formated properly to // The string passed to the constructor should be formated properly to
// be displayed as the "Second" part of an error message, or the derived // be displayed as the "Second" part of an error message, or the derived
// class should override GetMsg() and return a string appropriate for display. // class should override GetMsg() and return a string appropriate for display.
uint32 GetFlags() const; uint32 GetFlags() const;
// Flags are defined below. Currently, these only have an impact on how errors are // Flags are defined below. Currently, these only have an impact on how errors are
// displayed. // displayed.
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Flags // Flags
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
enum Flag enum Flag
{ {
NON_FATAL = 0x00000001, // displays "Error" or "Warning" ? NON_FATAL = 0x00000001, // displays "Error" or "Warning" ?
SUPRESS_THIRD_MSG = 0x00000002 // supresses the "continuing" or "exiting" message SUPRESS_THIRD_MSG = 0x00000002 // supresses the "continuing" or "exiting" message
}; };
void SetFlags( uint32 flags ); void SetFlags(uint32 flags);
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Flag Convenience Methods // Flag Convenience Methods
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
void SetFatality(bool fatal); void SetFatality(bool fatal);
bool IsFatal() const; bool IsFatal() const;
// Fatality is set to true by default when eError is constructed. But when an error // Fatality is set to true by default when eError is constructed. But when an error
// it is put in an cErrorBucket chain it the code doing so may wish to set the fatality // it is put in an cErrorBucket chain it the code doing so may wish to set the fatality
// to non-fatal to indicate that the error is actually a warning and program flow // to non-fatal to indicate that the error is actually a warning and program flow
// is going to continue. // is going to continue.
void SetSupressThird(bool supressThird); void SetSupressThird(bool supressThird);
bool SupressThird() const; bool SupressThird() const;
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Utility Methods // Utility Methods
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
static uint32 CalcHash( const char* name ); static uint32 CalcHash(const char* name);
// calculates the CRC32 of the string passed in as name. This methods // calculates the CRC32 of the string passed in as name. This methods
// asserts that name is non null. This is used to generate unique IDs // asserts that name is non null. This is used to generate unique IDs
// for errors. // for errors.
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Private Implementation // Private Implementation
@ -129,44 +128,51 @@ protected:
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#if HAVE_GCC #if HAVE_GCC
#define TSS_BEGIN_EXCEPTION_EXPLICIT # define TSS_BEGIN_EXCEPTION_EXPLICIT
#else #else
#define TSS_BEGIN_EXCEPTION_EXPLICIT explicit # define TSS_BEGIN_EXCEPTION_EXPLICIT explicit
#endif #endif
#define TSS_BEGIN_EXCEPTION( except, base ) \ #define TSS_BEGIN_EXCEPTION(except, base) \
class except : public base \ class except : public base \
{\ { \
public:\ public: \
except( const TSTRING& msg, uint32 flags = 0 ) \ except(const TSTRING& msg, uint32 flags = 0) : base(msg, flags) \
: base( msg, flags ) {} \ { \
TSS_BEGIN_EXCEPTION_EXPLICIT except( const except& rhs ) \ } \
: base( rhs ) {} \ TSS_BEGIN_EXCEPTION_EXPLICIT except(const except& rhs) : base(rhs) \
explicit except() : base() {} \ { \
\ } \
virtual uint32 GetID() const \ explicit except() : base() \
{\ { \
return CalcHash( #except ); \ } \
}\ \
virtual uint32 GetID() const \
{ \
return CalcHash(#except); \
}
#define TSS_END_EXCEPTION( ) \ #define TSS_END_EXCEPTION() \
}; } \
;
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// TSS_BEGIN_EXCEPTION_NO_CTOR // TSS_BEGIN_EXCEPTION_NO_CTOR
// //
// Same as TSS_BEGIN_EXCEPTION, but doesn't define any ctors. // Same as TSS_BEGIN_EXCEPTION, but doesn't define any ctors.
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#define TSS_BEGIN_EXCEPTION_NO_CTOR( except, base ) \ #define TSS_BEGIN_EXCEPTION_NO_CTOR(except, base) \
class except : public base \ class except : public base \
{\ { \
public:\ public: \
explicit except() : base() {} \ explicit except() : base() \
\ { \
virtual uint32 GetID() const \ } \
{\ \
return CalcHash( #except ); \ virtual uint32 GetID() const \
}\ { \
return CalcHash(#except); \
}
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// TSS_EXCEPTION // TSS_EXCEPTION
@ -178,8 +184,8 @@ protected:
// TODO (mdb) -- do we want to cache the CRC? if we store it in a class static // TODO (mdb) -- do we want to cache the CRC? if we store it in a class static
// variable, then we will need to define it in the cpp file as well ... // variable, then we will need to define it in the cpp file as well ...
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#define TSS_EXCEPTION( except, base ) \ #define TSS_EXCEPTION(except, base) \
TSS_BEGIN_EXCEPTION( except, base ) \ TSS_BEGIN_EXCEPTION(except, base) \
TSS_END_EXCEPTION() TSS_END_EXCEPTION()
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -189,41 +195,32 @@ protected:
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// eError // eError
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline eError::eError( const TSTRING& msg, uint32 flags ) inline eError::eError(const TSTRING& msg, uint32 flags) : mMsg(msg), mFlags(flags)
: mMsg ( msg ),
mFlags ( flags )
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// eError // eError
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline eError::eError( const eError& rhs ) inline eError::eError(const eError& rhs) : mMsg(rhs.mMsg), mFlags(rhs.mFlags)
: mMsg ( rhs.mMsg ),
mFlags ( rhs.mFlags )
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// eError // eError
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline eError::eError( ) inline eError::eError() : mMsg(_T("")), mFlags(0)
: mMsg ( _T("") ),
mFlags ( 0 )
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// operator= // operator=
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline void eError::operator=( const eError& rhs ) inline void eError::operator=(const eError& rhs)
{ {
mMsg = rhs.mMsg; mMsg = rhs.mMsg;
mFlags = rhs.mFlags; mFlags = rhs.mFlags;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -231,7 +228,6 @@ inline void eError::operator=( const eError& rhs )
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline eError::~eError() inline eError::~eError()
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -253,7 +249,7 @@ inline uint32 eError::GetFlags() const
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// SetFlags // SetFlags
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline void eError::SetFlags( uint32 flags ) inline void eError::SetFlags(uint32 flags)
{ {
mFlags = flags; mFlags = flags;
} }
@ -275,7 +271,6 @@ inline void eError::SetFatality(bool fatal)
inline bool eError::IsFatal() const inline bool eError::IsFatal() const
{ {
return (mFlags & (uint32)NON_FATAL) == 0; return (mFlags & (uint32)NON_FATAL) == 0;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -298,6 +293,4 @@ inline bool eError::SupressThird() const
} }
#endif //__ERROR_H #endif //__ERROR_H

View File

@ -57,21 +57,23 @@ class cErrorBucket
{ {
public: public:
cErrorBucket(); cErrorBucket();
virtual ~cErrorBucket() {} virtual ~cErrorBucket()
{
}
virtual void AddError(const eError& error); virtual void AddError(const eError& error);
// add an error to the bucket // add an error to the bucket
cErrorBucket* GetChild(); cErrorBucket* GetChild();
// returns the bucket that the current bucket is chained to, or // returns the bucket that the current bucket is chained to, or
// NULL if nothing is attached to it. // NULL if nothing is attached to it.
cErrorBucket* SetChild(cErrorBucket* pNewChild); cErrorBucket* SetChild(cErrorBucket* pNewChild);
// sets the child link of this bucket; returns the old link value // sets the child link of this bucket; returns the old link value
protected: protected:
virtual void HandleError(const eError& error) = 0; virtual void HandleError(const eError& error) = 0;
// override this to implement error handling functionality specific to // override this to implement error handling functionality specific to
// the derived class // the derived class
cErrorBucket* mpChild; cErrorBucket* mpChild;
}; };
@ -81,8 +83,7 @@ protected:
/////////////////// ///////////////////
// cErrorBucket // cErrorBucket
/////////////////// ///////////////////
inline cErrorBucket::cErrorBucket() : inline cErrorBucket::cErrorBucket() : mpChild(0)
mpChild(0)
{ {
} }
@ -94,9 +95,8 @@ inline cErrorBucket* cErrorBucket::GetChild()
inline cErrorBucket* cErrorBucket::SetChild(cErrorBucket* pNewChild) inline cErrorBucket* cErrorBucket::SetChild(cErrorBucket* pNewChild)
{ {
cErrorBucket* pOldChild = mpChild; cErrorBucket* pOldChild = mpChild;
mpChild = pNewChild; mpChild = pNewChild;
return pOldChild; return pOldChild;
} }
#endif #endif

View File

@ -43,7 +43,7 @@
void cErrorBucket::AddError(const eError& error) void cErrorBucket::AddError(const eError& error)
{ {
HandleError(error); HandleError(error);
if(mpChild) if (mpChild)
mpChild->AddError(error); mpChild->AddError(error);
} }
@ -52,10 +52,8 @@ void cErrorBucket::AddError(const eError& error)
//############################################################################# //#############################################################################
void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra) void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
{ {
cDisplayEncoder e( cDisplayEncoder e((cDisplayEncoder::Flags)(cDisplayEncoder::NON_ROUNDTRIP | cDisplayEncoder::ALLOW_WHITESPACE));
(cDisplayEncoder::Flags) ( cDisplayEncoder::NON_ROUNDTRIP | TSTRING errStr;
cDisplayEncoder::ALLOW_WHITESPACE ) );
TSTRING errStr;
// //
// if the ID is zero, just return. // if the ID is zero, just return.
@ -68,19 +66,18 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
// point is when we throw ePoly() with no constructor arguments. At some point we want // point is when we throw ePoly() with no constructor arguments. At some point we want
// to stop using the mechanism have non-printing errors, thus we leave in the ASSERT below. // to stop using the mechanism have non-printing errors, thus we leave in the ASSERT below.
// But we don't want to break any release code, thus we return on the next line - June 2, 1999 DMB. // But we don't want to break any release code, thus we return on the next line - June 2, 1999 DMB.
ASSERT( error.GetID() != 0 ); ASSERT(error.GetID() != 0);
if( error.GetID() == 0 ) if (error.GetID() == 0)
return; return;
// "First Part" header // "First Part" header
errStr = TSS_GetString( cCore, error.IsFatal() ? core::STR_ERROR_ERROR errStr = TSS_GetString(cCore, error.IsFatal() ? core::STR_ERROR_ERROR : core::STR_ERROR_WARNING);
: core::STR_ERROR_WARNING );
if (errStr.empty()) if (errStr.empty())
{ {
TOSTRINGSTREAM strm; TOSTRINGSTREAM strm;
ASSERT( sizeof( uint32 ) == sizeof(unsigned int) ); // for cast on next line ASSERT(sizeof(uint32) == sizeof(unsigned int)); // for cast on next line
strm << _T("Unknown Error ID ") << (unsigned int)error.GetID(); strm << _T("Unknown Error ID ") << (unsigned int)error.GetID();
errStr = strm.str(); errStr = strm.str();
} }
@ -91,10 +88,10 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
// "First Part" error string // "First Part" error string
TSTRING prependToSecond; TSTRING prependToSecond;
// #pragma message("errorbucketimpl.cpp needs a little help in the mb arena, with the findfirst/last and such") // #pragma message("errorbucketimpl.cpp needs a little help in the mb arena, with the findfirst/last and such")
errStr = cErrorTable::GetInstance()->Get( error.GetID() ); errStr = cErrorTable::GetInstance()->Get(error.GetID());
if(! errStr.empty()) if (!errStr.empty())
{ {
// If the first part has a '\n' in it, we take everything following and prepend it to the // If the first part has a '\n' in it, we take everything following and prepend it to the
// second part. This was added to allow specifing a verbose string as the second part // second part. This was added to allow specifing a verbose string as the second part
@ -108,7 +105,7 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
ASSERT(errStr.length() + len + 6 < 80); // line too big for terminal? ASSERT(errStr.length() + len + 6 < 80); // line too big for terminal?
// Add 6 to account for "### ' and ': ' // Add 6 to account for "### ' and ': '
TCERR << TSS_GetString( cCore, core::STR_ERROR_COLON ) << _T(" ") << errStr; TCERR << TSS_GetString(cCore, core::STR_ERROR_COLON) << _T(" ") << errStr;
TCERR << std::endl; TCERR << std::endl;
} }
@ -117,14 +114,14 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
const TCHAR SPACE = _T(' '); const TCHAR SPACE = _T(' ');
errStr = prependToSecond + error.GetMsg() + strExtra; errStr = prependToSecond + error.GetMsg() + strExtra;
e.Encode( errStr ); e.Encode(errStr);
if (! errStr.empty()) if (!errStr.empty())
{ {
do do
{ {
// look for newline chars // look for newline chars
TSTRING::size_type firstNewLine; TSTRING::size_type firstNewLine;
TSTRING currentStr = errStr.substr(0, (firstNewLine = errStr.find_first_of(_T('\n')))); TSTRING currentStr = errStr.substr(0, (firstNewLine = errStr.find_first_of(_T('\n'))));
errStr.erase(0, (firstNewLine < errStr.length() ? firstNewLine + 1 : firstNewLine)); errStr.erase(0, (firstNewLine < errStr.length() ? firstNewLine + 1 : firstNewLine));
// break up the error string in case it is larger than screen width // break up the error string in case it is larger than screen width
@ -132,11 +129,12 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
{ {
if (currentStr.length() <= (unsigned int)WIDTH) if (currentStr.length() <= (unsigned int)WIDTH)
{ {
TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER ) << currentStr << std::endl; TCERR << TSS_GetString(cCore, core::STR_ERROR_HEADER) << currentStr << std::endl;
break; break;
} }
TSTRING::size_type lastSpace = currentStr.find_last_of(SPACE, currentStr.length() >= WIDTH - 1 ? WIDTH - 1 : TSTRING::npos); TSTRING::size_type lastSpace =
currentStr.find_last_of(SPACE, currentStr.length() >= WIDTH - 1 ? WIDTH - 1 : TSTRING::npos);
if (lastSpace == TSTRING::npos) if (lastSpace == TSTRING::npos)
{ {
// can't find space to break at so this string will just have to be longer than screen width. // can't find space to break at so this string will just have to be longer than screen width.
@ -148,28 +146,21 @@ void cErrorReporter::PrintErrorMsg(const eError& error, const TSTRING& strExtra)
lastSpace = currentStr.length(); lastSpace = currentStr.length();
} }
TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER ) TCERR << TSS_GetString(cCore, core::STR_ERROR_HEADER) << currentStr.substr(0, lastSpace) << std::endl;
<< currentStr.substr( 0, lastSpace )
<< std::endl;
currentStr.erase( 0, lastSpace + 1 ); currentStr.erase(0, lastSpace + 1);
} } while (!currentStr.empty());
while ( !currentStr.empty() ); } while (!errStr.empty());
}
while ( !errStr.empty() );
} }
// "Third Part" print 'exiting' or 'continuing' // "Third Part" print 'exiting' or 'continuing'
// note that we supress this part if the appropriate flag is set... // note that we supress this part if the appropriate flag is set...
// //
if( (error.GetFlags() & eError::SUPRESS_THIRD_MSG) == 0 ) if ((error.GetFlags() & eError::SUPRESS_THIRD_MSG) == 0)
{ {
TCERR << TSS_GetString( cCore, core::STR_ERROR_HEADER) TCERR << TSS_GetString(cCore, core::STR_ERROR_HEADER)
<< TSS_GetString( << TSS_GetString(cCore, error.IsFatal() ? core::STR_ERROR_EXITING : core::STR_ERROR_CONTINUING)
cCore, << std::endl;
error.IsFatal()
? core::STR_ERROR_EXITING
: core::STR_ERROR_CONTINUING ) << std::endl;
} }
} }
@ -185,9 +176,7 @@ void cErrorTracer::HandleError(const eError& error)
{ {
cDebug d("cErrorTracer::HandleError"); cDebug d("cErrorTracer::HandleError");
d.TraceError( _T("%s : %s\n"), d.TraceError(_T("%s : %s\n"), cErrorTable::GetInstance()->Get(error.GetID()).c_str(), error.GetMsg().c_str());
cErrorTable::GetInstance()->Get( error.GetID() ).c_str(),
error.GetMsg().c_str() );
} }
//############################################################################# //#############################################################################
@ -207,17 +196,15 @@ int cErrorQueue::GetNumErrors() const
void cErrorQueue::HandleError(const eError& error) void cErrorQueue::HandleError(const eError& error)
{ {
mList.push_back( ePoly( error ) ); mList.push_back(ePoly(error));
} }
cErrorQueueIter::cErrorQueueIter(cErrorQueue& queue) : cErrorQueueIter::cErrorQueueIter(cErrorQueue& queue) : mList(queue.mList)
mList(queue.mList)
{ {
SeekBegin(); SeekBegin();
} }
cErrorQueueIter::cErrorQueueIter(const cErrorQueue& queue) cErrorQueueIter::cErrorQueueIter(const cErrorQueue& queue) : mList(((cErrorQueue*)&queue)->mList)
: mList( ((cErrorQueue*)&queue)->mList )
{ {
SeekBegin(); SeekBegin();
} }
@ -240,7 +227,7 @@ bool cErrorQueueIter::Done() const
const ePoly& cErrorQueueIter::GetError() const const ePoly& cErrorQueueIter::GetError() const
{ {
ASSERT(! Done()); ASSERT(!Done());
return (*mIter); return (*mIter);
} }
@ -255,19 +242,18 @@ void cErrorQueue::Read(iSerializer* pSerializer, int32 version)
int32 size; int32 size;
mList.clear(); mList.clear();
pSerializer->ReadInt32(size); pSerializer->ReadInt32(size);
for(int i = 0; i < size; ++i) for (int i = 0; i < size; ++i)
{ {
int32 errorNumber; int32 errorNumber;
TSTRING errorString; TSTRING errorString;
int32 flags; int32 flags;
pSerializer->ReadInt32 (errorNumber); pSerializer->ReadInt32(errorNumber);
pSerializer->ReadString (errorString); pSerializer->ReadString(errorString);
pSerializer->ReadInt32 (flags); pSerializer->ReadInt32(flags);
mList.push_back( ePoly( errorNumber, errorString, flags ) ); mList.push_back(ePoly(errorNumber, errorString, flags));
} }
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -277,13 +263,12 @@ void cErrorQueue::Write(iSerializer* pSerializer) const
{ {
pSerializer->WriteInt32(mList.size()); pSerializer->WriteInt32(mList.size());
ListType::const_iterator i; ListType::const_iterator i;
for( i = mList.begin(); i != mList.end(); ++i) for (i = mList.begin(); i != mList.end(); ++i)
{ {
pSerializer->WriteInt32 ((*i).GetID()); pSerializer->WriteInt32((*i).GetID());
pSerializer->WriteString((*i).GetMsg()); pSerializer->WriteString((*i).GetMsg());
pSerializer->WriteInt32 ((*i).GetFlags()); pSerializer->WriteInt32((*i).GetFlags());
} }
} }
@ -292,15 +277,14 @@ void cErrorQueue::Write(iSerializer* pSerializer) const
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cErrorQueue::TraceContents(int dl) const void cErrorQueue::TraceContents(int dl) const
{ {
if(dl < 0) if (dl < 0)
dl = cDebug::D_DEBUG; dl = cDebug::D_DEBUG;
cDebug d("cFCOErrorQueue::TraceContents"); cDebug d("cFCOErrorQueue::TraceContents");
ListType::const_iterator i; ListType::const_iterator i;
int counter = 0; int counter = 0;
for(i = mList.begin(); i != mList.end(); i++, counter++) for (i = mList.begin(); i != mList.end(); i++, counter++)
{ {
d.Trace(dl, _T("Error[%d]: num = %x string = %s\n") , counter, (*i).GetID(), (*i).GetMsg().c_str()); d.Trace(dl, _T("Error[%d]: num = %x string = %s\n"), counter, (*i).GetID(), (*i).GetMsg().c_str());
} }
} }

View File

@ -67,15 +67,15 @@ class cErrorReporter : public cErrorBucket
{ {
public: public:
static void PrintErrorMsg(const eError& error, const TSTRING& strExtra = _T("")); static void PrintErrorMsg(const eError& error, const TSTRING& strExtra = _T(""));
// function that HandleError() uses to print the error messages to stderr. // function that HandleError() uses to print the error messages to stderr.
// this function uses the current authoritative format for error reporting, so // this function uses the current authoritative format for error reporting, so
// other functions needing to display errors to the user should use this. // other functions needing to display errors to the user should use this.
// //
// NOTE:bam 5/7/99 -- I don't think the below is true anymore? // NOTE:bam 5/7/99 -- I don't think the below is true anymore?
// NOTE:mdb -- if the error has an ID of zero, nothing will be printed. This // NOTE:mdb -- if the error has an ID of zero, nothing will be printed. This
// is a way to throw a fatal error where the error reporting has already // is a way to throw a fatal error where the error reporting has already
// occurred. // occurred.
protected: protected:
virtual void HandleError(const eError& error); virtual void HandleError(const eError& error);
@ -100,17 +100,18 @@ protected:
class cErrorQueue : public cErrorBucket, public iTypedSerializable class cErrorQueue : public cErrorBucket, public iTypedSerializable
{ {
friend class cErrorQueueIter; friend class cErrorQueueIter;
public: public:
void Clear(); void Clear();
// remove all errors from the queue // remove all errors from the queue
int GetNumErrors() const; int GetNumErrors() const;
// returns how many errors are in the queue // returns how many errors are in the queue
// //
// iSerializable interface // iSerializable interface
// //
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
// //
// Debugging // Debugging
@ -119,9 +120,10 @@ public:
protected: protected:
virtual void HandleError(const eError& error); virtual void HandleError(const eError& error);
private: private:
typedef std::list<ePoly> ListType; typedef std::list<ePoly> ListType;
ListType mList; ListType mList;
DECLARE_TYPEDSERIALIZABLE() DECLARE_TYPEDSERIALIZABLE()
}; };
@ -131,7 +133,9 @@ class cErrorQueueIter
public: public:
cErrorQueueIter(cErrorQueue& queue); cErrorQueueIter(cErrorQueue& queue);
cErrorQueueIter(const cErrorQueue& queue); cErrorQueueIter(const cErrorQueue& queue);
~cErrorQueueIter() {} ~cErrorQueueIter()
{
}
// iteration methods // iteration methods
void SeekBegin(); void SeekBegin();
@ -139,9 +143,9 @@ public:
bool Done() const; bool Done() const;
// access to the error // access to the error
const ePoly& GetError() const; const ePoly& GetError() const;
// both of these return results are undefined if the iterator // both of these return results are undefined if the iterator
// is not valid (ie - IsDone() == true) // is not valid (ie - IsDone() == true)
private: private:
cErrorQueue::ListType& mList; cErrorQueue::ListType& mList;
cErrorQueue::ListType::iterator mIter; cErrorQueue::ListType::iterator mIter;
@ -153,9 +157,14 @@ private:
////////////////////////////////////////////////////// //////////////////////////////////////////////////////
class cErrorBucketNull : public cErrorBucket class cErrorBucketNull : public cErrorBucket
{ {
virtual void AddError(const eError& ) {} virtual void AddError(const eError&)
{
}
protected: protected:
virtual void HandleError(const eError& ) {} virtual void HandleError(const eError&)
{
}
}; };
////////////////////////////////////////////////////// //////////////////////////////////////////////////////
@ -165,10 +174,10 @@ protected:
class cErrorBucketPassThru : public cErrorBucket class cErrorBucketPassThru : public cErrorBucket
{ {
protected: protected:
virtual void HandleError(const eError& ) {} virtual void HandleError(const eError&)
{
}
}; };
#endif #endif

View File

@ -38,12 +38,11 @@
#include "error.h" #include "error.h"
TSS_EXCEPTION( eErrorGeneral, eError ); TSS_EXCEPTION(eErrorGeneral, eError);
TSS_EXCEPTION( eOpen, eErrorGeneral ); TSS_EXCEPTION(eOpen, eErrorGeneral);
TSS_EXCEPTION( eOpenRead, eErrorGeneral ); TSS_EXCEPTION(eOpenRead, eErrorGeneral);
TSS_EXCEPTION( eOpenWrite, eErrorGeneral ); TSS_EXCEPTION(eOpenWrite, eErrorGeneral);
TSS_EXCEPTION( eBadCmdLine, eErrorGeneral ); TSS_EXCEPTION(eBadCmdLine, eErrorGeneral);
TSS_EXCEPTION( eBadModeSwitch, eErrorGeneral ); TSS_EXCEPTION(eBadModeSwitch, eErrorGeneral);
#endif //#ifndef __ERRORGENERAL_H #endif //#ifndef __ERRORGENERAL_H

View File

@ -64,18 +64,18 @@ void cErrorTable::AssertMsgValidity(const TCHAR* msg)
if (errSize == TSTRING::npos) if (errSize == TSTRING::npos)
errSize = errStr.length(); errSize = errStr.length();
#if 0 //TODO: Figure out how to do this properly. # if 0 //TODO: Figure out how to do this properly.
TSTRING::size_type errorSize = TSS_GetString( cCore, core::STR_ERROR_ERROR ).length(); TSTRING::size_type errorSize = TSS_GetString( cCore, core::STR_ERROR_ERROR ).length();
TSTRING::size_type warningSize = TSS_GetString( cCore, core::STR_ERROR_WARNING ).length(); TSTRING::size_type warningSize = TSS_GetString( cCore, core::STR_ERROR_WARNING ).length();
TSTRING::size_type maxHeaderSize = (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': ' TSTRING::size_type maxHeaderSize = (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': '
#else # else
// Sunpro got stuck in an infinite loop when we called GetString from this func; // Sunpro got stuck in an infinite loop when we called GetString from this func;
TSTRING::size_type errorSize = 9; TSTRING::size_type errorSize = 9;
TSTRING::size_type warningSize = 10; TSTRING::size_type warningSize = 10;
TSTRING::size_type maxHeaderSize = (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': ' TSTRING::size_type maxHeaderSize =
#endif (errorSize > warningSize ? errorSize : warningSize) + 6; // Add 6 to account for "### ' and ': '
# endif
ASSERT(maxHeaderSize + errSize < 80); ASSERT(maxHeaderSize + errSize < 80);
} }
#endif #endif

View File

@ -59,25 +59,25 @@ public:
// //
// Convenience Methods // Convenience Methods
// //
void Put( const eError& e, const TCHAR* msg ); void Put(const eError& e, const TCHAR* msg);
// //
// Singleton Interface // Singleton Interface
// //
static cErrorTable* GetInstance(); static cErrorTable* GetInstance();
private: private:
#ifdef DEBUG #ifdef DEBUG
static void AssertMsgValidity(const TCHAR* msg); static void AssertMsgValidity(const TCHAR* msg);
#endif #endif
}; };
inline void cErrorTable::Put( const eError& e, const TCHAR* msg ) inline void cErrorTable::Put(const eError& e, const TCHAR* msg)
{ {
#ifdef DEBUG #ifdef DEBUG
AssertMsgValidity(msg); AssertMsgValidity(msg);
#endif #endif
inherited::Put( e.GetID(), msg ); inherited::Put(e.GetID(), msg);
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -109,32 +109,27 @@ inline void cErrorTable::Put( const eError& e, const TCHAR* msg )
//=================== //===================
// cpp file macros // cpp file macros
//=================== //===================
#define TSS_BEGIN_ERROR_REGISTRATION( pkgName ) \ # define TSS_BEGIN_ERROR_REGISTRATION(pkgName) \
RegisterErrors##pkgName::RegisterErrors##pkgName() \ RegisterErrors##pkgName::RegisterErrors##pkgName() \
{ {
#define TSS_REGISTER_ERROR( err, str ) \ # define TSS_REGISTER_ERROR(err, str) cErrorTable::GetInstance()->Put(err, str);
cErrorTable::GetInstance()->Put \
( err, str );
#define TSS_END_ERROR_REGISTRATION() \ # define TSS_END_ERROR_REGISTRATION() }
}
//=================== //===================
// h file macros // h file macros
//=================== //===================
#define TSS_DECLARE_ERROR_REGISTRATION( pkgName ) \ # define TSS_DECLARE_ERROR_REGISTRATION(pkgName) \
struct RegisterErrors##pkgName \ struct RegisterErrors##pkgName \
{\ { \
RegisterErrors##pkgName(); \ RegisterErrors##pkgName(); \
}; };
//=================== //===================
// package init macros // package init macros
//=================== //===================
#define TSS_REGISTER_PKG_ERRORS( pkgName ) \ # define TSS_REGISTER_PKG_ERRORS(pkgName) RegisterErrors##pkgName register##pkgName;
RegisterErrors##pkgName register##pkgName;
#endif //__ERRORTABLE_H #endif //__ERRORTABLE_H

View File

@ -42,15 +42,14 @@
namespace //unique namespace //unique
{ {
TCHAR* tw_itot( int value, TCHAR* string, int radix, int size) TCHAR* tw_itot(int value, TCHAR* string, int radix, int size)
{ {
snprintf( string, size, "%d", value ); snprintf(string, size, "%d", value);
return string; return string;
}
} }
} // namespace
eInternal::eInternal(TCHAR* sourceFile, int lineNum) eInternal::eInternal(TCHAR* sourceFile, int lineNum) : eError(_T(""))
: eError(_T(""))
{ {
TCHAR buf[256]; TCHAR buf[256];
@ -67,18 +66,17 @@ eInternal::eInternal(TCHAR* sourceFile, int lineNum)
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// MakeFileError // MakeFileError
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
TSTRING cErrorUtil::MakeFileError( const TSTRING& msg, const TSTRING& fileName ) TSTRING cErrorUtil::MakeFileError(const TSTRING& msg, const TSTRING& fileName)
{ {
TSTRING ret; TSTRING ret;
ret = TSS_GetString( cCore, core::STR_ERR2_FILENAME ); ret = TSS_GetString(cCore, core::STR_ERR2_FILENAME);
ret.append( fileName ); ret.append(fileName);
ret.append( 1, _T('\n') ); ret.append(1, _T('\n'));
if ( msg.length() > 0 ) if (msg.length() > 0)
{ {
ret.append(msg); ret.append(msg);
} }
return ret; return ret;
} }

View File

@ -58,27 +58,27 @@ public:
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Construction and Assignment // Construction and Assignment
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
ePoly( uint32 id, const TSTRING& msg, uint32 flags = 0 ); ePoly(uint32 id, const TSTRING& msg, uint32 flags = 0);
explicit ePoly( const eError& rhs ); explicit ePoly(const eError& rhs);
explicit ePoly(); explicit ePoly();
void operator=( const eError& rhs ); void operator=(const eError& rhs);
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// ID manipulation // ID manipulation
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
virtual uint32 GetID() const; virtual uint32 GetID() const;
void SetID( uint32 id ); void SetID(uint32 id);
private: private:
uint32 mID; uint32 mID;
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// eInternal // eInternal
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
TSS_BEGIN_EXCEPTION( eInternal, eError ) TSS_BEGIN_EXCEPTION(eInternal, eError)
public: public:
eInternal( TCHAR* file, int lineNum ); eInternal(TCHAR* file, int lineNum);
TSS_END_EXCEPTION() TSS_END_EXCEPTION()
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -87,11 +87,11 @@ TSS_END_EXCEPTION()
class cErrorUtil class cErrorUtil
{ {
public: public:
static TSTRING MakeFileError( const TSTRING& msg, const TSTRING& fileName ); static TSTRING MakeFileError(const TSTRING& msg, const TSTRING& fileName);
// constructs an error message of the form: // constructs an error message of the form:
// File: <fileName> \n <msg> // File: <fileName> \n <msg>
// This is useful for constructing strings to pass as the msg parameter // This is useful for constructing strings to pass as the msg parameter
// to eError constructors. // to eError constructors.
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -102,13 +102,17 @@ public:
// __FILE__ because that includes the full path to the file, which we // __FILE__ because that includes the full path to the file, which we
// would not like to display to the user. // would not like to display to the user.
// //
#define INTERNAL_ERROR(filename) eInternal((TCHAR*)_T(filename), __LINE__) #define INTERNAL_ERROR(filename) eInternal((TCHAR*)_T(filename), __LINE__)
#define THROW_INTERNAL(filename) throw eInternal((TCHAR*)_T(filename), __LINE__) #define THROW_INTERNAL(filename) throw eInternal((TCHAR*)_T(filename), __LINE__)
// TODO: ASSERT is always fatal in Unix, perhaps we could #ifdef the ASSERT // TODO: ASSERT is always fatal in Unix, perhaps we could #ifdef the ASSERT
// to echo to cout the line number the exception occured at? // to echo to cout the line number the exception occured at?
#define ThrowAndAssert(exception) { ASSERT(false); throw exception; } #define ThrowAndAssert(exception) \
{ \
ASSERT(false); \
throw exception; \
}
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -118,17 +122,14 @@ public:
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ePoly // ePoly
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline ePoly::ePoly( uint32 id, const TSTRING& msg, uint32 flags ) inline ePoly::ePoly(uint32 id, const TSTRING& msg, uint32 flags) : eError(msg, flags), mID(id)
: eError( msg, flags ),
mID( id )
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ePoly // ePoly
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline ePoly::ePoly( const eError& rhs ) inline ePoly::ePoly(const eError& rhs)
{ {
*this = rhs; *this = rhs;
} }
@ -136,21 +137,18 @@ inline ePoly::ePoly( const eError& rhs )
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ePoly // ePoly
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline ePoly::ePoly() inline ePoly::ePoly() : eError(_T("")), mID(0)
: eError( _T("") ),
mID( 0 )
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// operator= // operator=
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline void ePoly::operator=( const eError& rhs ) inline void ePoly::operator=(const eError& rhs)
{ {
mMsg = rhs.GetMsg(); mMsg = rhs.GetMsg();
mFlags = rhs.GetFlags(); mFlags = rhs.GetFlags();
mID = rhs.GetID(); mID = rhs.GetID();
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@ -164,10 +162,9 @@ inline uint32 ePoly::GetID() const
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// SetID // SetID
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline void ePoly::SetID( uint32 id ) inline void ePoly::SetID(uint32 id)
{ {
mID = id; mID = id;
} }
#endif //__ERRORUTIL_H #endif //__ERRORUTIL_H

View File

@ -55,86 +55,88 @@
// eFile exception class // eFile exception class
//============================================================================= //=============================================================================
TSS_FILE_EXCEPTION( eFile, eFileError ); TSS_FILE_EXCEPTION(eFile, eFileError);
TSS_FILE_EXCEPTION( eFileOpen, eFile ); TSS_FILE_EXCEPTION(eFileOpen, eFile);
TSS_FILE_EXCEPTION( eFileWrite, eFile ); TSS_FILE_EXCEPTION(eFileWrite, eFile);
TSS_FILE_EXCEPTION( eFileRead, eFile ); TSS_FILE_EXCEPTION(eFileRead, eFile);
TSS_FILE_EXCEPTION( eFileEOF, eFile ); // never used! TSS_FILE_EXCEPTION(eFileEOF, eFile); // never used!
TSS_FILE_EXCEPTION( eFileSeek, eFile ); TSS_FILE_EXCEPTION(eFileSeek, eFile);
TSS_FILE_EXCEPTION( eFileInvalidOp, eFile ); // never used! TSS_FILE_EXCEPTION(eFileInvalidOp, eFile); // never used!
TSS_FILE_EXCEPTION( eFileTrunc, eFile ); TSS_FILE_EXCEPTION(eFileTrunc, eFile);
TSS_FILE_EXCEPTION( eFileClose, eFile ); // never used! TSS_FILE_EXCEPTION(eFileClose, eFile); // never used!
TSS_FILE_EXCEPTION( eFileFlush, eFile ); TSS_FILE_EXCEPTION(eFileFlush, eFile);
TSS_FILE_EXCEPTION( eFileRewind, eFile ); TSS_FILE_EXCEPTION(eFileRewind, eFile);
//============================================================================= //=============================================================================
// cFile // cFile
//============================================================================= //=============================================================================
struct cFile_i; struct cFile_i;
class cFile class cFile
{ {
public: public:
typedef off_t File_t; typedef off_t File_t;
enum SeekFrom enum SeekFrom
{ {
SEEK_BEGIN = 0, SEEK_BEGIN = 0,
SEEK_CURRENT, SEEK_CURRENT,
SEEK_EOF SEEK_EOF
}; };
enum OpenFlags enum OpenFlags
{ {
// note that reading from the file is implicit // note that reading from the file is implicit
OPEN_READ = 0x00000001, // not needed, but makes calls nice... OPEN_READ = 0x00000001, // not needed, but makes calls nice...
OPEN_WRITE = 0x00000002, // we will be writing to the file OPEN_WRITE = 0x00000002, // we will be writing to the file
OPEN_LOCKED_TEMP = 0x00000004, // the file should not be readable by other processes and should be removed when closed OPEN_LOCKED_TEMP =
OPEN_TRUNCATE = 0x00000008, // opens an empty file. creates it if it doesn't exist. Doesn't make much sense without OF_WRITE 0x00000004, // the file should not be readable by other processes and should be removed when closed
OPEN_CREATE = 0x00000010, // create the file if it doesn't exist; this is implicit if OF_TRUNCATE is set OPEN_TRUNCATE =
OPEN_TEXT = 0x00000020, 0x00000008, // opens an empty file. creates it if it doesn't exist. Doesn't make much sense without OF_WRITE
OPEN_EXCLUSIVE = 0x00000040, // Use O_CREAT | O_EXCL OPEN_CREATE = 0x00000010, // create the file if it doesn't exist; this is implicit if OF_TRUNCATE is set
OPEN_SCANNING = 0x00000080, // Open for scanning; set nonblocking & caching accordingly, where available OPEN_TEXT = 0x00000020,
OPEN_DIRECT = 0x00000100 // Use O_DIRECT or platform equivalent OPEN_EXCLUSIVE = 0x00000040, // Use O_CREAT | O_EXCL
OPEN_SCANNING = 0x00000080, // Open for scanning; set nonblocking & caching accordingly, where available
OPEN_DIRECT = 0x00000100 // Use O_DIRECT or platform equivalent
}; };
//Ctor, Dtor, CpyCtor, Operator=: //Ctor, Dtor, CpyCtor, Operator=:
cFile ( void ); cFile(void);
~cFile ( void ); ~cFile(void);
/************ User Interface **************************/ /************ User Interface **************************/
// Both Open methods ALWAYS open files in BINARY mode! // Both Open methods ALWAYS open files in BINARY mode!
void Open ( const TSTRING& sFileName, uint32 flags = OPEN_READ ); //throw(eFile) void Open(const TSTRING& sFileName, uint32 flags = OPEN_READ); //throw(eFile)
void Close ( void ); //throw(eFile) void Close(void); //throw(eFile)
bool IsOpen ( void ) const; bool IsOpen(void) const;
File_t Seek ( File_t offset, SeekFrom From ) const; //throw(eFile) File_t Seek(File_t offset, SeekFrom From) const; //throw(eFile)
// Seek returns the current offset after completion // Seek returns the current offset after completion
File_t Read ( void* buffer, File_t nBytes ) const; //throw(eFile) File_t Read(void* buffer, File_t nBytes) const; //throw(eFile)
// Read returns the number of bytes that are actually read. If the nBytes // Read returns the number of bytes that are actually read. If the nBytes
// parameter is 0, 0 bytes will be read and buffer will remain untouched. // parameter is 0, 0 bytes will be read and buffer will remain untouched.
// If the read head is at EOF, no bytes will be read and 0 will be returned. // If the read head is at EOF, no bytes will be read and 0 will be returned.
File_t Write ( const void* buffer, File_t nBytes ); //throw(eFile) File_t Write(const void* buffer, File_t nBytes); //throw(eFile)
// Write returns the number of bytes that are actually written. // Write returns the number of bytes that are actually written.
File_t Tell ( void ) const; File_t Tell(void) const;
// Tell returns the current offset. // Tell returns the current offset.
bool Flush ( void ); //throw(eFile) bool Flush(void); //throw(eFile)
// Flush returns 0 if the currently defined stream is successfully flushed. // Flush returns 0 if the currently defined stream is successfully flushed.
void Rewind ( void ) const; //throw(eFile) void Rewind(void) const; //throw(eFile)
// Sets the offset to 0. // Sets the offset to 0.
File_t GetSize ( void ) const; File_t GetSize(void) const;
// Returns the size of the current file in bytes. Returns -1 if no file is defined. // Returns the size of the current file in bytes. Returns -1 if no file is defined.
void Truncate ( File_t offset ); // throw(eFile) void Truncate(File_t offset); // throw(eFile)
private: private:
cFile ( const cFile& rhs ); //not impl. cFile(const cFile& rhs); //not impl.
cFile& operator= ( const cFile& rhs); //not impl. cFile& operator=(const cFile& rhs); //not impl.
//Pointer to the insulated implementation //Pointer to the insulated implementation
cFile_i* mpData; cFile_i* mpData;
public: public:
bool isWritable; bool isWritable;
}; };
@ -143,7 +145,7 @@ class cDosPath
public: public:
static TSTRING AsPosix(const TSTRING& in); static TSTRING AsPosix(const TSTRING& in);
static TSTRING AsNative(const TSTRING& in); static TSTRING AsNative(const TSTRING& in);
static bool IsAbsolutePath(const TSTRING& in); static bool IsAbsolutePath(const TSTRING& in);
static TSTRING BackupName(const TSTRING& in); static TSTRING BackupName(const TSTRING& in);
}; };
@ -152,7 +154,7 @@ class cArosPath
public: public:
static TSTRING AsPosix(const TSTRING& in); static TSTRING AsPosix(const TSTRING& in);
static TSTRING AsNative(const TSTRING& in); static TSTRING AsNative(const TSTRING& in);
static bool IsAbsolutePath(const TSTRING& in); static bool IsAbsolutePath(const TSTRING& in);
}; };
class cRiscosPath class cRiscosPath
@ -160,7 +162,7 @@ class cRiscosPath
public: public:
static TSTRING AsPosix(const TSTRING& in); static TSTRING AsPosix(const TSTRING& in);
static TSTRING AsNative(const TSTRING& in); static TSTRING AsNative(const TSTRING& in);
static bool IsAbsolutePath(const TSTRING& in); static bool IsAbsolutePath(const TSTRING& in);
}; };
class cRedoxPath class cRedoxPath
@ -168,19 +170,18 @@ class cRedoxPath
public: public:
static TSTRING AsPosix(const TSTRING& in); static TSTRING AsPosix(const TSTRING& in);
static TSTRING AsNative(const TSTRING& in); static TSTRING AsNative(const TSTRING& in);
static bool IsAbsolutePath(const TSTRING& in); static bool IsAbsolutePath(const TSTRING& in);
}; };
#if IS_DOS_DJGPP # if IS_DOS_DJGPP
#define cDevicePath cDosPath # define cDevicePath cDosPath
#elif IS_AROS # elif IS_AROS
#define cDevicePath cArosPath # define cDevicePath cArosPath
#elif IS_RISCOS # elif IS_RISCOS
#define cDevicePath cRiscosPath # define cDevicePath cRiscosPath
#elif IS_REDOX # elif IS_REDOX
#define cDevicePath cRedoxPath # define cDevicePath cRedoxPath
#endif # endif
#endif //__FILE_H #endif //__FILE_H

View File

@ -35,13 +35,13 @@
/* On GNU/Hurd, need to define _GNU_SOURCE in order to use O_NOATIME /* On GNU/Hurd, need to define _GNU_SOURCE in order to use O_NOATIME
which technically is still a nonstandard extension to open() */ which technically is still a nonstandard extension to open() */
#if IS_HURD #if IS_HURD
# define _GNU_SOURCE # define _GNU_SOURCE
#endif #endif
#include "core/stdcore.h" #include "core/stdcore.h"
#if !IS_UNIX #if !IS_UNIX
#error Need to be unix to use unixfsservices # error Need to be unix to use unixfsservices
#endif #endif
#include "core/file.h" #include "core/file.h"
@ -54,7 +54,7 @@
#include <errno.h> #include <errno.h>
#if HAVE_SYS_FS_VX_IOCTL_H #if HAVE_SYS_FS_VX_IOCTL_H
# include <sys/fs/vx_ioctl.h> #include <sys/fs/vx_ioctl.h>
#endif #endif
#include "core/debug.h" #include "core/debug.h"
@ -75,32 +75,32 @@ struct cFile_i
cFile_i(); cFile_i();
~cFile_i(); ~cFile_i();
int m_fd; //underlying file descriptor int m_fd; //underlying file descriptor
FILE* mpCurrStream; //currently defined file stream FILE* mpCurrStream; //currently defined file stream
TSTRING mFileName; //the name of the file we are currently referencing. TSTRING mFileName; //the name of the file we are currently referencing.
uint32 mFlags; //Flags used to open the file uint32 mFlags; //Flags used to open the file
}; };
//Ctor //Ctor
cFile_i::cFile_i() : cFile_i::cFile_i() : m_fd(-1), mpCurrStream(NULL), mFlags(0)
m_fd(-1), mpCurrStream(NULL), mFlags(0) {
{} }
//Dtor //Dtor
cFile_i::~cFile_i() cFile_i::~cFile_i()
{ {
if (mpCurrStream != NULL) if (mpCurrStream != NULL)
{ {
fclose( mpCurrStream ); fclose(mpCurrStream);
mpCurrStream = NULL; mpCurrStream = NULL;
#if !CAN_UNLINK_WHILE_OPEN // so unlink after close instead #if !CAN_UNLINK_WHILE_OPEN // so unlink after close instead
if( mFlags & cFile::OPEN_LOCKED_TEMP ) if (mFlags & cFile::OPEN_LOCKED_TEMP)
{ {
// unlink this file // unlink this file
if( 0 != unlink(mFileName.c_str())) if (0 != unlink(mFileName.c_str()))
{ {
throw( eFileOpen( mFileName, iFSServices::GetInstance()->GetErrString() ) ); throw(eFileOpen(mFileName, iFSServices::GetInstance()->GetErrString()));
} }
} }
#endif #endif
@ -113,15 +113,14 @@ cFile_i::~cFile_i()
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
cFile::cFile() : cFile::cFile() : mpData(NULL), isWritable(false)
mpData(NULL), isWritable(false)
{ {
mpData = new cFile_i; mpData = new cFile_i;
} }
cFile::~cFile() cFile::~cFile()
{ {
if( mpData != NULL) if (mpData != NULL)
{ {
delete mpData; delete mpData;
mpData = NULL; mpData = NULL;
@ -133,10 +132,10 @@ cFile::~cFile()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
#if !USES_DEVICE_PATH #if !USES_DEVICE_PATH
void cFile::Open( const TSTRING& sFileName, uint32 flags ) void cFile::Open(const TSTRING& sFileName, uint32 flags)
{ {
#else #else
void cFile::Open( const TSTRING& sFileNameC, uint32 flags ) void cFile::Open(const TSTRING& sFileNameC, uint32 flags)
{ {
TSTRING sFileName = cDevicePath::AsNative(sFileNameC); TSTRING sFileName = cDevicePath::AsNative(sFileNameC);
#endif #endif
@ -155,9 +154,9 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
if (flags & OPEN_WRITE) if (flags & OPEN_WRITE)
{ {
perm |= O_RDWR; perm |= O_RDWR;
isWritable = true; isWritable = true;
mode = _T("rb"); mode = _T("rb");
if (flags & OPEN_TRUNCATE) if (flags & OPEN_TRUNCATE)
{ {
perm |= O_TRUNC; perm |= O_TRUNC;
@ -169,14 +168,15 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
} }
else else
{ {
perm |= O_RDONLY; perm |= O_RDONLY;
isWritable = false; isWritable = false;
mode = _T("rb"); mode = _T("rb");
} }
if (flags & OPEN_EXCLUSIVE) { if (flags & OPEN_EXCLUSIVE)
{
perm |= O_CREAT | O_EXCL; perm |= O_CREAT | O_EXCL;
openmode = (mode_t) 0600; // Make sure only root can read the file openmode = (mode_t)0600; // Make sure only root can read the file
} }
if (flags & OPEN_CREATE) if (flags & OPEN_CREATE)
@ -196,28 +196,28 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
//Only use O_DIRECT for scanning, since cfg/policy/report reads //Only use O_DIRECT for scanning, since cfg/policy/report reads
// don't happen w/ a nice round block size. // don't happen w/ a nice round block size.
if ((flags & OPEN_DIRECT) && (flags & OPEN_SCANNING)) if ((flags & OPEN_DIRECT) && (flags & OPEN_SCANNING))
perm |= O_DIRECT; perm |= O_DIRECT;
#endif #endif
// //
// actually open the file // actually open the file
// //
int fh = _topen( sFileName.c_str(), perm, openmode ); int fh = _topen(sFileName.c_str(), perm, openmode);
if( fh == -1 ) if (fh == -1)
{ {
throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) ); throw(eFileOpen(sFileName, iFSServices::GetInstance()->GetErrString()));
} }
mpData->m_fd = fh; mpData->m_fd = fh;
#if CAN_UNLINK_WHILE_OPEN #if CAN_UNLINK_WHILE_OPEN
if( flags & OPEN_LOCKED_TEMP ) if (flags & OPEN_LOCKED_TEMP)
{ {
// unlink this file // unlink this file
if( 0 != unlink( sFileName.c_str() ) ) if (0 != unlink(sFileName.c_str()))
{ {
// we weren't able to unlink file, so close handle and fail // we weren't able to unlink file, so close handle and fail
close( fh ); close(fh);
throw( eFileOpen( sFileName, iFSServices::GetInstance()->GetErrString() ) ); throw(eFileOpen(sFileName, iFSServices::GetInstance()->GetErrString()));
} }
} }
#endif #endif
@ -227,7 +227,7 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
// //
mpData->mpCurrStream = _tfdopen(fh, mode.c_str()); mpData->mpCurrStream = _tfdopen(fh, mode.c_str());
mpData->mFileName = sFileName; //Set mFileName to the newly opened file. mpData->mFileName = sFileName; //Set mFileName to the newly opened file.
cFile::Rewind(); cFile::Rewind();
@ -244,8 +244,8 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
#if HAVE_POSIX_FADVISE #if HAVE_POSIX_FADVISE
if (flags & OPEN_SCANNING && !(flags & OPEN_DIRECT)) if (flags & OPEN_SCANNING && !(flags & OPEN_DIRECT))
{ {
posix_fadvise(fh,0,0, POSIX_FADV_SEQUENTIAL); posix_fadvise(fh, 0, 0, POSIX_FADV_SEQUENTIAL);
posix_fadvise(fh,0,0, POSIX_FADV_NOREUSE); posix_fadvise(fh, 0, 0, POSIX_FADV_NOREUSE);
} }
#elif HAVE_SYS_FS_VX_IOCTL_H #elif HAVE_SYS_FS_VX_IOCTL_H
@ -257,7 +257,6 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
ioctl(fh, VX_SETCACHE, VX_SEQ | VX_NOREUSE); ioctl(fh, VX_SETCACHE, VX_SEQ | VX_NOREUSE);
} }
#endif #endif
} }
@ -266,13 +265,13 @@ void cFile::Open( const TSTRING& sFileNameC, uint32 flags )
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
void cFile::Close() //throw(eFile) void cFile::Close() //throw(eFile)
{ {
if(mpData->mpCurrStream != NULL) if (mpData->mpCurrStream != NULL)
{ {
#ifdef HAVE_POSIX_FADVISE #ifdef HAVE_POSIX_FADVISE
posix_fadvise(fileno(mpData->mpCurrStream),0,0, POSIX_FADV_DONTNEED); posix_fadvise(fileno(mpData->mpCurrStream), 0, 0, POSIX_FADV_DONTNEED);
#endif #endif
fclose( mpData->mpCurrStream ); fclose(mpData->mpCurrStream);
mpData->mpCurrStream = NULL; mpData->mpCurrStream = NULL;
} }
@ -280,23 +279,23 @@ void cFile::Close() //throw(eFile)
mpData->mFileName.empty(); mpData->mFileName.empty();
} }
bool cFile::IsOpen( void ) const bool cFile::IsOpen(void) const
{ {
return( mpData->mpCurrStream != NULL ); return (mpData->mpCurrStream != NULL);
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// Seek -- Positions the read/write offset in mpCurrStream. Returns the // Seek -- Positions the read/write offset in mpCurrStream. Returns the
// current offset upon completion. Returns 0 if no stream is defined. // current offset upon completion. Returns 0 if no stream is defined.
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile) cFile::File_t cFile::Seek(File_t offset, SeekFrom From) const //throw(eFile)
{ {
//Check to see if a file as been opened yet... //Check to see if a file as been opened yet...
ASSERT( mpData->mpCurrStream != 0); ASSERT(mpData->mpCurrStream != 0);
int apiFrom; int apiFrom;
switch( From ) switch (From)
{ {
case cFile::SEEK_BEGIN: case cFile::SEEK_BEGIN:
apiFrom = SEEK_SET; apiFrom = SEEK_SET;
@ -309,11 +308,11 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile)
break; break;
default: default:
//An invalid SeekFrom parameter was passed. //An invalid SeekFrom parameter was passed.
throw( eInternal( _T("file_unix") ) ); throw(eInternal(_T("file_unix")));
} }
// this is a hack to simulate running out of disk space // this is a hack to simulate running out of disk space
#if 0 #if 0
static int blowupCount = 1; static int blowupCount = 1;
if (++blowupCount == 1075) if (++blowupCount == 1075)
{ {
@ -322,14 +321,14 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile)
throw std::bad_alloc(); throw std::bad_alloc();
} }
fprintf(stderr, "%d\n", blowupCount); fprintf(stderr, "%d\n", blowupCount);
#endif #endif
if (fseeko( mpData->mpCurrStream, offset, apiFrom ) != 0) if (fseeko(mpData->mpCurrStream, offset, apiFrom) != 0)
{ {
#ifdef DEBUG #ifdef DEBUG
cDebug d("cFile::Seek"); cDebug d("cFile::Seek");
d.TraceDebug("Seek failed!\n"); d.TraceDebug("Seek failed!\n");
#endif #endif
throw eFileSeek(); throw eFileSeek();
} }
@ -340,26 +339,31 @@ cFile::File_t cFile::Seek( File_t offset, SeekFrom From) const //throw(eFile)
// Read -- Returns the actual bytes read from mpCurrStream. Returns 0 if // Read -- Returns the actual bytes read from mpCurrStream. Returns 0 if
// mpCurrStream is undefined. // mpCurrStream is undefined.
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
cFile::File_t cFile::Read( void* buffer, File_t nBytes ) const //throw(eFile) cFile::File_t cFile::Read(void* buffer, File_t nBytes) const //throw(eFile)
{ {
File_t iBytesRead; File_t iBytesRead;
// Has a file been opened? // Has a file been opened?
ASSERT( mpData->mpCurrStream != NULL ); ASSERT(mpData->mpCurrStream != NULL);
// Is the nBytes parameter 0? If so, return without touching buffer: // Is the nBytes parameter 0? If so, return without touching buffer:
if( nBytes == 0 ) if (nBytes == 0)
return 0; return 0;
if (mpData->mFlags & OPEN_DIRECT) { if (mpData->mFlags & OPEN_DIRECT)
{
iBytesRead = read(mpData->m_fd, buffer, nBytes); iBytesRead = read(mpData->m_fd, buffer, nBytes);
if (iBytesRead<0) { if (iBytesRead < 0)
{
throw eFileRead(mpData->mFileName, iFSServices::GetInstance()->GetErrString()); throw eFileRead(mpData->mFileName, iFSServices::GetInstance()->GetErrString());
} }
} else { }
iBytesRead = fread( buffer, sizeof(byte), nBytes, mpData->mpCurrStream ); else
if( ferror( mpData->mpCurrStream ) != 0 ) { {
throw eFileRead( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ; iBytesRead = fread(buffer, sizeof(byte), nBytes, mpData->mpCurrStream);
if (ferror(mpData->mpCurrStream) != 0)
{
throw eFileRead(mpData->mFileName, iFSServices::GetInstance()->GetErrString());
} }
} }
@ -370,16 +374,16 @@ cFile::File_t cFile::Read( void* buffer, File_t nBytes ) const //throw(eFile)
// Write -- Returns the actual number of bytes written to mpCurrStream // Write -- Returns the actual number of bytes written to mpCurrStream
// Returns 0 if no file has been opened. // Returns 0 if no file has been opened.
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
cFile::File_t cFile::Write( const void* buffer, File_t nBytes ) //throw(eFile) cFile::File_t cFile::Write(const void* buffer, File_t nBytes) //throw(eFile)
{ {
File_t actual_count = 0; File_t actual_count = 0;
// Has a file been opened? Is it writable? // Has a file been opened? Is it writable?
ASSERT( mpData->mpCurrStream != NULL ); ASSERT(mpData->mpCurrStream != NULL);
ASSERT( isWritable ); ASSERT(isWritable);
if( ( actual_count = fwrite( buffer, sizeof(byte), nBytes, mpData->mpCurrStream ) ) < nBytes ) if ((actual_count = fwrite(buffer, sizeof(byte), nBytes, mpData->mpCurrStream)) < nBytes)
throw eFileWrite( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ); throw eFileWrite(mpData->mFileName, iFSServices::GetInstance()->GetErrString());
else else
return actual_count; return actual_count;
} }
@ -390,9 +394,9 @@ cFile::File_t cFile::Write( const void* buffer, File_t nBytes ) //throw(eFil
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
cFile::File_t cFile::Tell() const cFile::File_t cFile::Tell() const
{ {
ASSERT( mpData->mpCurrStream != 0); ASSERT(mpData->mpCurrStream != 0);
return ftell( mpData->mpCurrStream ); return ftell(mpData->mpCurrStream);
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@ -400,23 +404,23 @@ cFile::File_t cFile::Tell() const
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
bool cFile::Flush() //throw(eFile) bool cFile::Flush() //throw(eFile)
{ {
if ( mpData->mpCurrStream == NULL ) if (mpData->mpCurrStream == NULL)
throw eFileFlush( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ); throw eFileFlush(mpData->mFileName, iFSServices::GetInstance()->GetErrString());
return ( fflush( mpData->mpCurrStream) == 0 ); return (fflush(mpData->mpCurrStream) == 0);
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
// Rewind -- Sets the offset to the beginning of the file. If mpCurrStream // Rewind -- Sets the offset to the beginning of the file. If mpCurrStream
// is NULL, this method returns false. If the rewind operation fails, // is NULL, this method returns false. If the rewind operation fails,
// an exception is thrown. // an exception is thrown.
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
void cFile::Rewind() const //throw(eFile) void cFile::Rewind() const //throw(eFile)
{ {
ASSERT( mpData->mpCurrStream != 0); ASSERT(mpData->mpCurrStream != 0);
rewind( mpData->mpCurrStream ); rewind(mpData->mpCurrStream);
if( ftell( mpData->mpCurrStream ) != 0 ) if (ftell(mpData->mpCurrStream) != 0)
throw( eFileRewind( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ); throw(eFileRewind(mpData->mFileName, iFSServices::GetInstance()->GetErrString()));
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@ -429,12 +433,12 @@ cFile::File_t cFile::GetSize() const
File_t ret; File_t ret;
//Has a file been opened? If not, return -1 //Has a file been opened? If not, return -1
if( mpData->mpCurrStream == NULL ) if (mpData->mpCurrStream == NULL)
return -1; return -1;
ret = Seek( 0, cFile::SEEK_EOF ); ret = Seek(0, cFile::SEEK_EOF);
Seek( vCurrentOffset, cFile::SEEK_BEGIN ); Seek(vCurrentOffset, cFile::SEEK_BEGIN);
//return the offset to it's position prior to GetSize call. //return the offset to it's position prior to GetSize call.
return ret; return ret;
} }
@ -442,14 +446,14 @@ cFile::File_t cFile::GetSize() const
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
// Truncate // Truncate
///////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////
void cFile::Truncate( File_t offset ) // throw(eFile) void cFile::Truncate(File_t offset) // throw(eFile)
{ {
ASSERT( mpData->mpCurrStream != 0); ASSERT(mpData->mpCurrStream != 0);
ASSERT( isWritable ); ASSERT(isWritable);
ftruncate( fileno(mpData->mpCurrStream), offset ); ftruncate(fileno(mpData->mpCurrStream), offset);
if( GetSize() != offset ) if (GetSize() != offset)
throw( eFileTrunc( mpData->mFileName, iFSServices::GetInstance()->GetErrString() ) ); throw(eFileTrunc(mpData->mFileName, iFSServices::GetInstance()->GetErrString()));
} }
@ -472,7 +476,7 @@ bool cDosPath::IsAbsolutePath(const TSTRING& in)
} }
// For paths of type C:\DOS // For paths of type C:\DOS
TSTRING cDosPath::AsPosix( const TSTRING& in ) TSTRING cDosPath::AsPosix(const TSTRING& in)
{ {
if (in[0] == '/') if (in[0] == '/')
{ {
@ -481,12 +485,12 @@ TSTRING cDosPath::AsPosix( const TSTRING& in )
TSTRING out = (cDosPath::IsAbsolutePath(in)) ? ("/dev/" + in) : in; TSTRING out = (cDosPath::IsAbsolutePath(in)) ? ("/dev/" + in) : in;
std::replace(out.begin(), out.end(), '\\', '/'); std::replace(out.begin(), out.end(), '\\', '/');
out.erase( std::remove(out.begin(), out.end(), ':'), out.end()); out.erase(std::remove(out.begin(), out.end(), ':'), out.end());
return out; return out;
} }
TSTRING cDosPath::AsNative( const TSTRING& in ) TSTRING cDosPath::AsNative(const TSTRING& in)
{ {
if (in[0] != '/') if (in[0] != '/')
{ {
@ -497,7 +501,7 @@ TSTRING cDosPath::AsNative( const TSTRING& in )
return in; return in;
TSTRING out = "?:/"; TSTRING out = "?:/";
out[0] = in[5]; out[0] = in[5];
if (in.length() >= 8) if (in.length() >= 8)
out.append(in.substr(7)); out.append(in.substr(7));
@ -507,15 +511,15 @@ TSTRING cDosPath::AsNative( const TSTRING& in )
return out; return out;
} }
TSTRING cDosPath::BackupName( const TSTRING& in ) TSTRING cDosPath::BackupName(const TSTRING& in)
{ {
TSTRING out = in; TSTRING out = in;
std::string::size_type pos = out.find_last_of("\\"); std::string::size_type pos = out.find_last_of("\\");
if( std::string::npos == pos) if (std::string::npos == pos)
return in; return in;
TSTRING path = in.substr(0, pos); TSTRING path = in.substr(0, pos);
TSTRING name = in.substr(pos,9); TSTRING name = in.substr(pos, 9);
std::replace(name.begin(), name.end(), '.', '_'); std::replace(name.begin(), name.end(), '.', '_');
path.append(name); path.append(name);
@ -538,7 +542,7 @@ bool cArosPath::IsAbsolutePath(const TSTRING& in)
} }
// For paths of type DH0:dir/file // For paths of type DH0:dir/file
TSTRING cArosPath::AsPosix( const TSTRING& in ) TSTRING cArosPath::AsPosix(const TSTRING& in)
{ {
if (in[0] == '/') if (in[0] == '/')
{ {
@ -551,7 +555,7 @@ TSTRING cArosPath::AsPosix( const TSTRING& in )
return out; return out;
} }
TSTRING cArosPath::AsNative( const TSTRING& in ) TSTRING cArosPath::AsNative(const TSTRING& in)
{ {
if (in[0] != '/') if (in[0] != '/')
{ {
@ -559,9 +563,9 @@ TSTRING cArosPath::AsNative( const TSTRING& in )
} }
std::string::size_type drive = in.find_first_not_of("/"); std::string::size_type drive = in.find_first_not_of("/");
TSTRING out = (drive != std::string::npos) ? in.substr(drive) : in; TSTRING out = (drive != std::string::npos) ? in.substr(drive) : in;
TSTRING::size_type t = out.find_first_of('/'); TSTRING::size_type t = out.find_first_of('/');
if(t != std::string::npos) if (t != std::string::npos)
out[t] = ':'; out[t] = ':';
else else
out.append(":"); out.append(":");
@ -585,7 +589,7 @@ bool cRiscosPath::IsAbsolutePath(const TSTRING& in)
} }
// For paths of type SDFS::Volume.$.dir.file // For paths of type SDFS::Volume.$.dir.file
TSTRING cRiscosPath::AsPosix( const TSTRING& in ) TSTRING cRiscosPath::AsPosix(const TSTRING& in)
{ {
#if IS_RISCOS #if IS_RISCOS
if (in[0] == '/') if (in[0] == '/')
@ -594,8 +598,8 @@ TSTRING cRiscosPath::AsPosix( const TSTRING& in )
} }
TSTRING out; TSTRING out;
char* unixified = __unixify(in.c_str(), 0,0,0,0); char* unixified = __unixify(in.c_str(), 0, 0, 0, 0);
if(unixified) if (unixified)
{ {
out.assign(unixified); out.assign(unixified);
free(unixified); free(unixified);
@ -608,7 +612,7 @@ TSTRING cRiscosPath::AsPosix( const TSTRING& in )
#endif #endif
} }
TSTRING cRiscosPath::AsNative( const TSTRING& in ) TSTRING cRiscosPath::AsNative(const TSTRING& in)
{ {
#if IS_RISCOS #if IS_RISCOS
if (in[0] != '/') if (in[0] != '/')
@ -616,11 +620,11 @@ TSTRING cRiscosPath::AsNative( const TSTRING& in )
return in; return in;
} }
TSTRING out; TSTRING out;
int buf_size = in.length() + 100; // examples pad by 100 int buf_size = in.length() + 100; // examples pad by 100
std::vector<char> buf(buf_size); std::vector<char> buf(buf_size);
__riscosify(in.c_str(), 0,0, &buf[0], buf_size, 0); __riscosify(in.c_str(), 0, 0, &buf[0], buf_size, 0);
if(buf[0]) if (buf[0])
{ {
out.assign(&buf[0]); out.assign(&buf[0]);
return out; return out;
@ -648,21 +652,21 @@ bool cRedoxPath::IsAbsolutePath(const TSTRING& in)
} }
// For paths of type file:/dir/file // For paths of type file:/dir/file
TSTRING cRedoxPath::AsPosix( const TSTRING& in ) TSTRING cRedoxPath::AsPosix(const TSTRING& in)
{ {
if (in[0] == '/') if (in[0] == '/')
{ {
return in; return in;
} }
TSTRING out = IsAbsolutePath(in) ? '/' + in : in; TSTRING out = IsAbsolutePath(in) ? '/' + in : in;
std::string::size_type colon = out.find_first_of(":"); std::string::size_type colon = out.find_first_of(":");
if( colon != std::string::npos ) if (colon != std::string::npos)
out.erase(colon, 1); out.erase(colon, 1);
return out; return out;
} }
TSTRING cRedoxPath::AsNative( const TSTRING& in ) TSTRING cRedoxPath::AsNative(const TSTRING& in)
{ {
if (in[0] != '/') if (in[0] != '/')
{ {
@ -670,9 +674,9 @@ TSTRING cRedoxPath::AsNative( const TSTRING& in )
} }
std::string::size_type drive = in.find_first_not_of("/"); std::string::size_type drive = in.find_first_not_of("/");
TSTRING out = (drive != std::string::npos) ? in.substr(drive) : in; TSTRING out = (drive != std::string::npos) ? in.substr(drive) : in;
TSTRING::size_type slash = out.find_first_of('/'); TSTRING::size_type slash = out.find_first_of('/');
if(slash != std::string::npos) if (slash != std::string::npos)
out.insert(slash, ":"); out.insert(slash, ":");
else else
out.append(":/"); out.append(":/");

View File

@ -37,11 +37,10 @@
#include "corestrings.h" #include "corestrings.h"
// TODO: Make this use MakeFileError() for consistency // TODO: Make this use MakeFileError() for consistency
eFileError::eFileError( const TSTRING& filename, const TSTRING& description, uint32 flags ) eFileError::eFileError(const TSTRING& filename, const TSTRING& description, uint32 flags) : eError(_T(""), flags)
: eError( _T(""), flags )
{ {
mFilename = filename; mFilename = filename;
mMsg = description; mMsg = description;
} }
TSTRING eFileError::GetFilename() const TSTRING eFileError::GetFilename() const
@ -58,14 +57,14 @@ TSTRING eFileError::GetDescription() const
{ {
TSTRING ret; TSTRING ret;
if( ! mFilename.empty() ) if (!mFilename.empty())
{ {
ret = TSS_GetString( cCore, core::STR_ERROR_FILENAME ) + mFilename; ret = TSS_GetString(cCore, core::STR_ERROR_FILENAME) + mFilename;
} }
if( ! mMsg.empty() ) if (!mMsg.empty())
{ {
if ( ! mFilename.empty() ) if (!mFilename.empty())
ret += _T("\n"); ret += _T("\n");
ret += mMsg; ret += mMsg;
@ -73,4 +72,3 @@ TSTRING eFileError::GetDescription() const
return ret; return ret;
} }

View File

@ -51,30 +51,33 @@
// ### Insufficient permission to open file. <-- constructor parameter "msg" // ### Insufficient permission to open file. <-- constructor parameter "msg"
// ### Exiting... <-- appropriate third message // ### Exiting... <-- appropriate third message
//============================================================================= //=============================================================================
TSS_BEGIN_EXCEPTION_NO_CTOR( eFileError, eError ) TSS_BEGIN_EXCEPTION_NO_CTOR(eFileError, eError)
private: private:
TSTRING mFilename; TSTRING mFilename;
public: public:
eFileError( const TSTRING& filename, const TSTRING& description, uint32 flags = 0 ); eFileError(const TSTRING& filename, const TSTRING& description, uint32 flags = 0);
explicit eFileError( const eFileError& rhs ) explicit eFileError(const eFileError& rhs) : eError(rhs)
: eError( rhs ) { mFilename = rhs.mFilename; } {
eFileError( const TSTRING& msg, uint32 flags = 0 ) mFilename = rhs.mFilename;
: eError( msg, flags ) {} }
eFileError(const TSTRING& msg, uint32 flags = 0) : eError(msg, flags)
{
}
TSTRING GetFilename() const; TSTRING GetFilename() const;
TSTRING GetDescription() const; TSTRING GetDescription() const;
virtual TSTRING GetMsg() const; virtual TSTRING GetMsg() const;
TSS_END_EXCEPTION() TSS_END_EXCEPTION()
#define TSS_FILE_EXCEPTION( except, base ) \ # define TSS_FILE_EXCEPTION(except, base) \
TSS_BEGIN_EXCEPTION( except, base ) \ TSS_BEGIN_EXCEPTION(except, base) \
except( const TSTRING& filename, const TSTRING& msg, uint32 flags = 0 ) \ except(const TSTRING& filename, const TSTRING& msg, uint32 flags = 0) : base(filename, msg, flags) \
: base( filename, msg, flags ) {} \ { \
TSS_END_EXCEPTION() } \
TSS_END_EXCEPTION()
#endif #endif

View File

@ -50,7 +50,7 @@ cFileHeaderID::~cFileHeaderID()
{ {
} }
void cFileHeaderID::operator=( const TCHAR* pszId ) void cFileHeaderID::operator=(const TCHAR* pszId)
{ {
// RAD:10/1/99 -- Not Needed // RAD:10/1/99 -- Not Needed
// TODO:BAM -- I'm pretty sure that there's a bug hiding here... // TODO:BAM -- I'm pretty sure that there's a bug hiding here...
@ -62,36 +62,34 @@ void cFileHeaderID::operator=( const TCHAR* pszId )
// return; // return;
//} //}
size_t N = ::strlen( pszId ); size_t N = ::strlen(pszId);
if ( !(N < cFileHeaderID::MAXBYTES) ) if (!(N < cFileHeaderID::MAXBYTES))
throw eCharacter( TSS_GetString( cCore, core::STR_ERR_OVERFLOW ) ); throw eCharacter(TSS_GetString(cCore, core::STR_ERR_OVERFLOW));
mIDLen = static_cast<int16>( N ); // know len is less than MAXBYTES mIDLen = static_cast<int16>(N); // know len is less than MAXBYTES
::memcpy( mID, pszId, N * sizeof(char) ); ::memcpy(mID, pszId, N * sizeof(char));
} }
void cFileHeaderID::operator=( const cFileHeaderID& rhs ) void cFileHeaderID::operator=(const cFileHeaderID& rhs)
{ {
ASSERT( rhs.mIDLen < cFileHeaderID::MAXBYTES ); ASSERT(rhs.mIDLen < cFileHeaderID::MAXBYTES);
mIDLen = rhs.mIDLen; mIDLen = rhs.mIDLen;
memcpy(mID, rhs.mID, mIDLen * sizeof(char)); memcpy(mID, rhs.mID, mIDLen * sizeof(char));
} }
int cFileHeaderID::operator==( const cFileHeaderID& rhs ) const int cFileHeaderID::operator==(const cFileHeaderID& rhs) const
{ {
return return (mIDLen == rhs.mIDLen) && (::memcmp(mID, rhs.mID, mIDLen * sizeof(char)) == 0);
( mIDLen == rhs.mIDLen ) &&
( ::memcmp( mID, rhs.mID, mIDLen * sizeof(char) ) == 0 );
} }
void cFileHeaderID::Read(iSerializer* pSerializer, int32 /*version*/ ) // throw (eSerializer, eArchive) void cFileHeaderID::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eSerializer, eArchive)
{ {
int16 len; int16 len;
pSerializer->ReadInt16( len ); pSerializer->ReadInt16(len);
if ( (len < 0) || (len >= cFileHeaderID::MAXBYTES )) if ((len < 0) || (len >= cFileHeaderID::MAXBYTES))
{ {
// this is invalid! // this is invalid!
throw eSerializerInputStreamFmt( _T("File Header ID invalid") ); throw eSerializerInputStreamFmt(_T("File Header ID invalid"));
} }
pSerializer->ReadBlob(mID, len * sizeof(char)); pSerializer->ReadBlob(mID, len * sizeof(char));
mIDLen = len; mIDLen = len;
@ -99,17 +97,16 @@ void cFileHeaderID::Read(iSerializer* pSerializer, int32 /*version*/ ) // throw
void cFileHeaderID::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive) void cFileHeaderID::Write(iSerializer* pSerializer) const // throw (eSerializer, eArchive)
{ {
ASSERT( mIDLen >= 0 && mIDLen < cFileHeaderID::MAXBYTES ); ASSERT(mIDLen >= 0 && mIDLen < cFileHeaderID::MAXBYTES);
pSerializer->WriteInt16( mIDLen ); pSerializer->WriteInt16(mIDLen);
pSerializer->WriteBlob( mID, mIDLen * sizeof(char) ); pSerializer->WriteBlob(mID, mIDLen * sizeof(char));
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// class cFileHeader // class cFileHeader
cFileHeader::cFileHeader() cFileHeader::cFileHeader() : mVersion(0)
: mVersion(0)
{ {
#ifdef DEBUG #ifdef DEBUG
mEncoding = LAST_ENCODING; // set to invalid value so we can assert on write mEncoding = LAST_ENCODING; // set to invalid value so we can assert on write
@ -119,20 +116,14 @@ cFileHeader::cFileHeader()
} }
cFileHeader::cFileHeader(const cFileHeader& rhs) cFileHeader::cFileHeader(const cFileHeader& rhs)
: iSerializable(), : iSerializable(), mID(rhs.mID), mVersion(rhs.mVersion), mEncoding(rhs.mEncoding)
mID(rhs.mID),
mVersion(rhs.mVersion),
mEncoding(rhs.mEncoding)
{ {
if (rhs.mBaggage.Length() > 0) if (rhs.mBaggage.Length() > 0)
{ {
mBaggage.MapArchive(0, rhs.mBaggage.Length()); mBaggage.MapArchive(0, rhs.mBaggage.Length());
rhs.mBaggage.MapArchive(0, rhs.mBaggage.Length()); rhs.mBaggage.MapArchive(0, rhs.mBaggage.Length());
::memcpy( ::memcpy(mBaggage.GetMap(), rhs.mBaggage.GetMap(), static_cast<size_t>(rhs.mBaggage.Length()));
mBaggage.GetMap(),
rhs.mBaggage.GetMap(),
static_cast<size_t>( rhs.mBaggage.Length() ) );
mBaggage.MapArchive(0, 0); mBaggage.MapArchive(0, 0);
rhs.mBaggage.MapArchive(0, 0); rhs.mBaggage.MapArchive(0, 0);
@ -171,7 +162,7 @@ void cFileHeader::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eS
if ((unsigned int)magicNumber != FILE_HEADER_MAGIC_NUMBER) if ((unsigned int)magicNumber != FILE_HEADER_MAGIC_NUMBER)
{ {
d.TraceDebug("Bad magic number"); d.TraceDebug("Bad magic number");
throw eSerializerInputStreamFmt(pSerializer->GetFileName() ); throw eSerializerInputStreamFmt(pSerializer->GetFileName());
} }
// Note this version refers to the format of this data structure in the // Note this version refers to the format of this data structure in the
@ -182,7 +173,7 @@ void cFileHeader::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eS
{ {
// don't understand the version // don't understand the version
d.TraceDebug("Bad version"); d.TraceDebug("Bad version");
throw eSerializerInputStreamFmt(pSerializer->GetFileName() ); throw eSerializerInputStreamFmt(pSerializer->GetFileName());
} }
mID.Read(pSerializer); mID.Read(pSerializer);
@ -196,7 +187,7 @@ void cFileHeader::Read(iSerializer* pSerializer, int32 /*version*/) // throw (eS
pSerializer->ReadInt32(len); pSerializer->ReadInt32(len);
if (len < 0 || len > 0xffff) if (len < 0 || len > 0xffff)
throw eSerializerInputStreamFmt(pSerializer->GetFileName() ); throw eSerializerInputStreamFmt(pSerializer->GetFileName());
mBaggage.MapArchive(0, len); mBaggage.MapArchive(0, len);
@ -233,14 +224,14 @@ void cFileHeader::Write(iSerializer* pSerializer) const // throw (eSerializer, e
pSerializer->WriteInt32(mVersion); pSerializer->WriteInt32(mVersion);
pSerializer->WriteInt16( static_cast<int16>(mEncoding) ); pSerializer->WriteInt16(static_cast<int16>(mEncoding));
int32 len = static_cast<int32>( mBaggage.Length() ); int32 len = static_cast<int32>(mBaggage.Length());
ASSERT(len >= 0); ASSERT(len >= 0);
ASSERT(len <= 0xFFFF); ASSERT(len <= 0xFFFF);
if ( len < 0 || len > 0xFFFF ) if (len < 0 || len > 0xFFFF)
throw eSerializerOutputStreamFmt(); throw eSerializerOutputStreamFmt();
pSerializer->WriteInt32(len); pSerializer->WriteInt32(len);
@ -250,4 +241,3 @@ void cFileHeader::Write(iSerializer* pSerializer) const // throw (eSerializer, e
pSerializer->WriteBlob(mBaggage.GetMap(), len); pSerializer->WriteBlob(mBaggage.GetMap(), len);
} }
} }

View File

@ -54,13 +54,13 @@ public:
cFileHeaderID(const cFileHeaderID& rhs); cFileHeaderID(const cFileHeaderID& rhs);
virtual ~cFileHeaderID(); virtual ~cFileHeaderID();
void operator = (const TCHAR* id); void operator=(const TCHAR* id);
void operator = (const cFileHeaderID& rhs); void operator=(const cFileHeaderID& rhs);
int operator == (const cFileHeaderID& rhs) const; int operator==(const cFileHeaderID& rhs) const;
int operator != (const cFileHeaderID& rhs) const; int operator!=(const cFileHeaderID& rhs) const;
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
private: private:
// For now we will store the id as a string. // For now we will store the id as a string.
@ -68,10 +68,13 @@ private:
// the way we implemented cFCONames. // the way we implemented cFCONames.
// Note: We store the string as narrow chars, since // Note: We store the string as narrow chars, since
// the program is the only person who will see them. // the program is the only person who will see them.
int16 mIDLen; int16 mIDLen;
enum { MAXBYTES = 256 }; enum
char mID[ MAXBYTES ]; {
MAXBYTES = 256
};
char mID[MAXBYTES];
}; };
inline cFileHeaderID::cFileHeaderID() inline cFileHeaderID::cFileHeaderID()
@ -84,14 +87,12 @@ inline cFileHeaderID::cFileHeaderID(const TCHAR* id)
*this = id; *this = id;
} }
inline inline cFileHeaderID::cFileHeaderID(const cFileHeaderID& rhs) : iSerializable(), mIDLen(rhs.mIDLen)
cFileHeaderID::cFileHeaderID( const cFileHeaderID& rhs ) :
iSerializable(), mIDLen( rhs.mIDLen )
{ {
memcpy( mID, rhs.mID, MAXBYTES ); memcpy(mID, rhs.mID, MAXBYTES);
} }
inline int cFileHeaderID::operator != (const cFileHeaderID& rhs) const inline int cFileHeaderID::operator!=(const cFileHeaderID& rhs) const
{ {
return !(*this == rhs); return !(*this == rhs);
} }
@ -115,26 +116,26 @@ public:
LAST_ENCODING LAST_ENCODING
}; };
void SetID(const cFileHeaderID& id); void SetID(const cFileHeaderID& id);
const cFileHeaderID& GetID() const; const cFileHeaderID& GetID() const;
void SetVersion(uint32 v); void SetVersion(uint32 v);
uint32 GetVersion() const; uint32 GetVersion() const;
void SetEncoding(Encoding e); void SetEncoding(Encoding e);
Encoding GetEncoding() const; Encoding GetEncoding() const;
cMemoryArchive& GetBaggage(); cMemoryArchive& GetBaggage();
const cMemoryArchive& GetBaggage() const; const cMemoryArchive& GetBaggage() const;
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
protected: protected:
cFileHeaderID mID; cFileHeaderID mID;
uint32 mVersion; uint32 mVersion;
Encoding mEncoding; Encoding mEncoding;
cMemoryArchive mBaggage; // items that have been serialized to this object cMemoryArchive mBaggage; // items that have been serialized to this object
}; };
inline const cFileHeaderID& cFileHeader::GetID() const inline const cFileHeaderID& cFileHeader::GetID() const
@ -163,4 +164,3 @@ inline const cMemoryArchive& cFileHeader::GetBaggage() const
} }
#endif #endif

View File

@ -47,5 +47,4 @@
#include <fstream> #include <fstream>
#define fixed_basic_ofstream std::basic_ofstream #define fixed_basic_ofstream std::basic_ofstream
#endif//__FIXED_FILEBUF_H #endif //__FIXED_FILEBUF_H

View File

@ -43,5 +43,3 @@ iFSServices* iFSServices::mpInstance = 0;
//############################################################################# //#############################################################################
// eFSServices // eFSServices
//############################################################################# //#############################################################################

View File

@ -66,11 +66,11 @@
//========================================================================= //=========================================================================
#if HAVE_SYS_PARAM_H #if HAVE_SYS_PARAM_H
# include <sys/param.h> #include <sys/param.h>
#endif #endif
#if HAVE_SYS_STAT_H #if HAVE_SYS_STAT_H
# include <sys/stat.h> #include <sys/stat.h>
#endif #endif
@ -80,26 +80,26 @@
// macros for extracting the major and minor portions of int64's: // macros for extracting the major and minor portions of int64's:
#if !defined(major) #if !defined(major)
#if !USES_GLIBC # if !USES_GLIBC
#define major(x) ((int)((x) >> 8) & 0xff) # define major(x) ((int)((x) >> 8) & 0xff)
#define minor(x) ((int)((x) & 0xff)) # define minor(x) ((int)((x)&0xff))
#else # else
#ifdef WORDS_BIGENDIAN # ifdef WORDS_BIGENDIAN
#define major(x) (int)(((char*)&(x))[2]) # define major(x) (int)(((char*)&(x))[2])
#define minor(x) (int)(((char*)&(x))[3]) # define minor(x) (int)(((char*)&(x))[3])
#else # else
#define major(x) (int)(((char*)&(x))[1]) # define major(x) (int)(((char*)&(x))[1])
#define minor(x) (int)(((char*)&(x))[0]) # define minor(x) (int)(((char*)&(x))[0])
#endif # endif
#endif # endif
#endif /* !major */ #endif /* !major */
//========================================================================= //=========================================================================
// TYPEDEFS // TYPEDEFS
//========================================================================= //=========================================================================
typedef int64 cFSTime; typedef int64 cFSTime;
typedef int64 cFSType; typedef int64 cFSType;
//========================================================================= //=========================================================================
// GLOBALS // GLOBALS
@ -122,57 +122,58 @@ typedef int64 cFSType;
// this class is used only to pass arguments to iFSServices // this class is used only to pass arguments to iFSServices
// it is the union of MAX(elem) for all the file systems that we support // it is the union of MAX(elem) for all the file systems that we support
struct cFSStatArgs { struct cFSStatArgs
enum FileType { {
TY_INVALID, // lazy evaluation enum FileType
TY_FILE, {
TY_DIR, TY_INVALID, // lazy evaluation
TY_BLOCKDEV, TY_FILE,
TY_CHARDEV, TY_DIR,
TY_SYMLINK, TY_BLOCKDEV,
TY_FIFO, TY_CHARDEV,
TY_SOCK, TY_SYMLINK,
TY_DOOR, TY_FIFO,
TY_PORT, TY_SOCK,
TY_NAMED TY_DOOR,
}; TY_PORT,
TY_NAMED
};
// attr is fs dependent? // attr is fs dependent?
uint64 dev; // dep uint64 dev; // dep
int64 ino; // dep int64 ino; // dep
int64 mode; // dep int64 mode; // dep
int64 nlink; // indep int64 nlink; // indep
int64 uid; // dep int64 uid; // dep
int64 gid; // dep int64 gid; // dep
uint64 rdev; // dep uint64 rdev; // dep
int64 size; // indep int64 size; // indep
cFSTime atime; // indep cFSTime atime; // indep
cFSTime mtime; // indep cFSTime mtime; // indep
cFSTime ctime; // indep cFSTime ctime; // indep
int64 blksize; // indep int64 blksize; // indep
int64 blocks; // dep int64 blocks; // dep
int64 fstype; // dep int64 fstype; // dep
TSTRING usid; // dep TSTRING usid; // dep
TSTRING gsid; // dep TSTRING gsid; // dep
// int64 mFileType; // Matt's addition... // int64 mFileType; // Matt's addition...
FileType mFileType; // redundant with other information in this struct, but FileType mFileType; // redundant with other information in this struct, but
// broken out for convenience // broken out for convenience
//TODO: access control list should go here, too //TODO: access control list should go here, too
//std::list <cACLElem> mACL; // indep //std::list <cACLElem> mACL; // indep
}; };
//========================================================================= //=========================================================================
// //
// eFSServices -- exception class // eFSServices -- exception class
// //
//========================================================================= //=========================================================================
TSS_FILE_EXCEPTION( eFSServices, eFileError ); TSS_FILE_EXCEPTION(eFSServices, eFileError);
TSS_FILE_EXCEPTION( eFSServicesGeneric, eFSServices ); TSS_FILE_EXCEPTION(eFSServicesGeneric, eFSServices);
//========================================================================= //=========================================================================
// //
@ -184,159 +185,161 @@ TSS_FILE_EXCEPTION( eFSServicesGeneric, eFSServices );
class iFSServices class iFSServices
{ {
public: public:
virtual ~iFSServices() {} virtual ~iFSServices()
/////////////////////////////////////////////////////////////// {
// ENUMS }
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
// ENUMS
///////////////////////////////////////////////////////////////
//////////////////////////////////////// ////////////////////////////////////////
// file creation modes // file creation modes
//////////////////////////////////////// ////////////////////////////////////////
enum Mode enum Mode
{ {
MODE_DEFAULT = 0, MODE_DEFAULT = 0,
MODE_READ = 1, MODE_READ = 1,
MODE_WRITE = 2, MODE_WRITE = 2,
MODE_SHARE_DELETE = 4, MODE_SHARE_DELETE = 4,
MODE_SHARE_READ = 8, MODE_SHARE_READ = 8,
MODE_SHARE_WRITE = 16, MODE_SHARE_WRITE = 16,
MODE_CREATE_EXCL = 32, MODE_CREATE_EXCL = 32,
MODE_CREATE_TRUNCATE = 64 MODE_CREATE_TRUNCATE = 64
}; };
//////////////////////////////////////// ////////////////////////////////////////
// maximum path length on platform // maximum path length on platform
//////////////////////////////////////// ////////////////////////////////////////
enum enum
{ {
#ifdef MAXPATHLEN #ifdef MAXPATHLEN
TW_MAX_PATH = MAXPATHLEN TW_MAX_PATH = MAXPATHLEN
#else #else
TW_MAX_PATH = 1024 TW_MAX_PATH = 1024
#endif #endif
}; };
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
// MEMBER FUNCTIONS // MEMBER FUNCTIONS
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
//////////////////////////////////////// ////////////////////////////////////////
// platform specific functions // platform specific functions
//////////////////////////////////////// ////////////////////////////////////////
virtual bool IsCaseSensitive() const = 0; virtual bool IsCaseSensitive() const = 0;
// returns true if the file system is case sensitive // returns true if the file system is case sensitive
virtual TCHAR GetPathSeparator() const = 0; virtual TCHAR GetPathSeparator() const = 0;
// returns "/" for unix and "\\" for win32 // returns "/" for unix and "\\" for win32
virtual const TCHAR* GetStandardBackupExtension() const = 0; virtual const TCHAR* GetStandardBackupExtension() const = 0;
// returns normal string to append to backup files for this os. // returns normal string to append to backup files for this os.
//////////////////////////////////////// ////////////////////////////////////////
// process functions // process functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void Sleep( int nSeconds ) const = 0; virtual void Sleep(int nSeconds) const = 0;
// makes the current process sleep for the specified number of seconds // makes the current process sleep for the specified number of seconds
//////////////////////////////////////// ////////////////////////////////////////
// major filesystem functions // major filesystem functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void Stat( const TSTRING& strFileName, cFSStatArgs& pStat ) const = 0; virtual void Stat(const TSTRING& strFileName, cFSStatArgs& pStat) const = 0;
// fills out the cFSStatArgs structure with the stat info for the named file // fills out the cFSStatArgs structure with the stat info for the named file
virtual void GetTempDirName( TSTRING& strName ) const = 0; virtual void GetTempDirName(TSTRING& strName) const = 0;
// makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' ) // makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' )
virtual void SetTempDirName( TSTRING& tmpName ) = 0; virtual void SetTempDirName(TSTRING& tmpName) = 0;
virtual TSTRING& MakeTempFilename( TSTRING& strName ) const = 0; virtual TSTRING& MakeTempFilename(TSTRING& strName) const = 0;
// create temporary file // create temporary file
// TSTRING must have the form ("baseXXXXXX"), where the X's are replaced with // TSTRING must have the form ("baseXXXXXX"), where the X's are replaced with
// characters to make it a unique file. There must be at least 6 Xs. // characters to make it a unique file. There must be at least 6 Xs.
//////////////////////////////////////// ////////////////////////////////////////
// minor filesystem functions // minor filesystem functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void GetHostID( TSTRING& name ) const = 0; virtual void GetHostID(TSTRING& name) const = 0;
virtual void GetMachineName( TSTRING& name ) const = 0; virtual void GetMachineName(TSTRING& name) const = 0;
virtual void GetMachineNameFullyQualified( TSTRING& name ) const = 0; virtual void GetMachineNameFullyQualified(TSTRING& name) const = 0;
virtual bool GetCurrentUserName( TSTRING& tstrName ) const = 0; virtual bool GetCurrentUserName(TSTRING& tstrName) const = 0;
virtual bool GetIPAddress( uint32& uiIPAddress ) = 0; virtual bool GetIPAddress(uint32& uiIPAddress) = 0;
//////////////////////////////////////// ////////////////////////////////////////
// directory specific functions // directory specific functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void ReadDir( const TSTRING& strName, std::vector<TSTRING> &vDirContents, bool bFullPaths = true ) const = 0; virtual void ReadDir(const TSTRING& strName, std::vector<TSTRING>& vDirContents, bool bFullPaths = true) const = 0;
// puts the contents of the specified directory, except for . and .., into the supplied vector. // puts the contents of the specified directory, except for . and .., into the supplied vector.
// if bFullPaths is true, then the vector contains fully qualified path names; otherwise, it only contains the // if bFullPaths is true, then the vector contains fully qualified path names; otherwise, it only contains the
// short names. // short names.
virtual void GetCurrentDir( TSTRING& strCurDir ) const = 0; virtual void GetCurrentDir(TSTRING& strCurDir) const = 0;
// returns the current working directory // returns the current working directory
//////////////////////////////////////// ////////////////////////////////////////
// file specific functions // file specific functions
//////////////////////////////////////// ////////////////////////////////////////
virtual bool FileDelete( const TSTRING& name ) const = 0; virtual bool FileDelete(const TSTRING& name) const = 0;
//////////////////////////////////////// ////////////////////////////////////////
// directory and file functions // directory and file functions
//////////////////////////////////////// ////////////////////////////////////////
virtual bool Rename( const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true ) const = 0; virtual bool Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true) const = 0;
// rename a file // rename a file
virtual bool GetUserName( uid_t user_id, TSTRING& tstrUser ) const = 0; virtual bool GetUserName(uid_t user_id, TSTRING& tstrUser) const = 0;
virtual bool GetGroupName( gid_t group_id, TSTRING& tstrGroup ) const = 0; virtual bool GetGroupName(gid_t group_id, TSTRING& tstrGroup) const = 0;
//Set whether we try to resolve uid/gid to a name, since Linux static binaries can //Set whether we try to resolve uid/gid to a name, since Linux static binaries can
//have trouble (read: segfaulting) with name resolution given the right nsswitch.conf setup. //have trouble (read: segfaulting) with name resolution given the right nsswitch.conf setup.
//This defaults to true if not specified. //This defaults to true if not specified.
virtual void SetResolveNames(bool resolve)=0; virtual void SetResolveNames(bool resolve) = 0;
//////////////////////////////////////// ////////////////////////////////////////
// miscellaneous utility functions // miscellaneous utility functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) const = 0; virtual void ConvertModeToString(uint64 perm, TSTRING& tstrPerm) const = 0;
// takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx) // takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx)
virtual bool FullPath( TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("") ) const = 0; virtual bool FullPath(TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("")) const = 0;
// converts relPath into a fully qualified path, storing it in FullPath. If this // converts relPath into a fully qualified path, storing it in FullPath. If this
// fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom. // fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom.
// TODO: In some places we have depended on the behaviour that if relPath.empty() == true then we // TODO: In some places we have depended on the behaviour that if relPath.empty() == true then we
// fail or return an empty string. Should we add this behaviour to the interface? // fail or return an empty string. Should we add this behaviour to the interface?
virtual bool GetExecutableFilename( TSTRING& strFullPath, const TSTRING& strFilename ) const = 0; virtual bool GetExecutableFilename(TSTRING& strFullPath, const TSTRING& strFilename) const = 0;
// get the path to the current executable file // get the path to the current executable file
virtual bool IsRoot( const TSTRING& strPath ) const = 0; virtual bool IsRoot(const TSTRING& strPath) const = 0;
// returns true if strPath denotes a root path // returns true if strPath denotes a root path
//////////////////////////////////////// ////////////////////////////////////////
// error functions // error functions
//////////////////////////////////////// ////////////////////////////////////////
virtual TSTRING GetErrString() const = 0; virtual TSTRING GetErrString() const = 0;
// Returns an error string that is appropriate for the system, (e.g. errorstr(errno) // Returns an error string that is appropriate for the system, (e.g. errorstr(errno)
// on UNIX and FormatError( ..., GetLastError(), ...) in Win32 // on UNIX and FormatError( ..., GetLastError(), ...) in Win32
// Call this immediately after a failed system call to get a string // Call this immediately after a failed system call to get a string
// representation of the error event. // representation of the error event.
//////////////////////////////////////// ////////////////////////////////////////
// singleton manipulation // singleton manipulation
//////////////////////////////////////// ////////////////////////////////////////
static iFSServices* GetInstance(); static iFSServices* GetInstance();
static void SetInstance( iFSServices* pInst ); static void SetInstance(iFSServices* pInst);
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
// PRIVATE DATA // PRIVATE DATA
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
private: private:
static iFSServices* mpInstance; static iFSServices* mpInstance;
}; };
@ -345,16 +348,15 @@ class iFSServices
//========================================================================= //=========================================================================
inline iFSServices* iFSServices::GetInstance() inline iFSServices* iFSServices::GetInstance()
{ {
ASSERT(mpInstance != 0); ASSERT(mpInstance != 0);
return mpInstance; return mpInstance;
} }
inline void iFSServices::SetInstance( iFSServices* pInst ) inline void iFSServices::SetInstance(iFSServices* pInst)
{ {
mpInstance = pInst; mpInstance = pInst;
} }
#endif #endif

View File

@ -44,48 +44,51 @@ public:
class cHeap class cHeap
{ {
public: public:
size_t mSize; size_t mSize;
int8* mpData; int8* mpData;
cHeap( size_t size ) : mSize( size ), mpData( new int8[size] ) { ASSERT(mpData != 0); } cHeap(size_t size) : mSize(size), mpData(new int8[size])
// Note: The above ASSERT should never occur! If the new failed we should have thrown a bad_alloc(). {
ASSERT(mpData != 0);
}
// Note: The above ASSERT should never occur! If the new failed we should have thrown a bad_alloc().
}; };
typedef std::vector<cHeap> HeapList; typedef std::vector<cHeap> HeapList;
size_t mInitialSize; size_t mInitialSize;
size_t mGrowBy; size_t mGrowBy;
HeapList mHeaps; HeapList mHeaps;
TSTRING mName; TSTRING mName;
size_t mCurOff; size_t mCurOff;
cGrowHeap_i( size_t initialSize, size_t growBy, const TCHAR* name ); cGrowHeap_i(size_t initialSize, size_t growBy, const TCHAR* name);
~cGrowHeap_i() { Clear(); } ~cGrowHeap_i()
{
Clear();
}
size_t AlignSizeRequest( size_t size, size_t alignSize ); size_t AlignSizeRequest(size_t size, size_t alignSize);
void* Malloc( size_t size ); void* Malloc(size_t size);
void Clear(); void Clear();
}; };
cGrowHeap_i::cGrowHeap_i( size_t initialSize, size_t growBy, const TCHAR* name ) cGrowHeap_i::cGrowHeap_i(size_t initialSize, size_t growBy, const TCHAR* name)
: mInitialSize( initialSize ), : mInitialSize(initialSize), mGrowBy(growBy), mName(name), mCurOff(0)
mGrowBy ( growBy ),
mName ( name ),
mCurOff ( 0 )
{ {
// assure that initial size and growby are aligned // assure that initial size and growby are aligned
ASSERT( 0 == ( initialSize % BYTE_ALIGN ) ); ASSERT(0 == (initialSize % BYTE_ALIGN));
ASSERT( 0 == ( growBy % BYTE_ALIGN ) ); ASSERT(0 == (growBy % BYTE_ALIGN));
} }
size_t cGrowHeap::TotalMemUsage() const size_t cGrowHeap::TotalMemUsage() const
{ {
size_t usage = 0; size_t usage = 0;
for( cGrowHeap_i::HeapList::const_iterator i = mpData->mHeaps.begin(); i != mpData->mHeaps.end(); i++ ) for (cGrowHeap_i::HeapList::const_iterator i = mpData->mHeaps.begin(); i != mpData->mHeaps.end(); i++)
{ {
usage += i->mSize; usage += i->mSize;
} }
if( ! mpData->mHeaps.empty() ) if (!mpData->mHeaps.empty())
{ {
// take off the unused portion... // take off the unused portion...
usage -= (mpData->mHeaps.back().mSize - mpData->mCurOff); usage -= (mpData->mHeaps.back().mSize - mpData->mCurOff);
@ -94,23 +97,23 @@ size_t cGrowHeap::TotalMemUsage() const
} }
void* cGrowHeap_i::Malloc( size_t size ) void* cGrowHeap_i::Malloc(size_t size)
{ {
size = AlignSizeRequest( size, BYTE_ALIGN ); size = AlignSizeRequest(size, BYTE_ALIGN);
ASSERT( ( size > 0 ) && ( size < mGrowBy ) ); ASSERT((size > 0) && (size < mGrowBy));
if( size >= mGrowBy ) if (size >= mGrowBy)
return NULL; return NULL;
if( mHeaps.empty() ) if (mHeaps.empty())
{ {
mHeaps.push_back( cHeap( mInitialSize ) ); mHeaps.push_back(cHeap(mInitialSize));
ASSERT(mHeaps.back().mpData != 0); ASSERT(mHeaps.back().mpData != 0);
mCurOff = 0; mCurOff = 0;
} }
if( mCurOff + size < mHeaps.back().mSize ) if (mCurOff + size < mHeaps.back().mSize)
{ {
// we have room to add this to the current heap. // we have room to add this to the current heap.
// //
@ -122,43 +125,43 @@ void* cGrowHeap_i::Malloc( size_t size )
} }
else else
{ {
mHeaps.push_back( cHeap( mGrowBy ) ); mHeaps.push_back(cHeap(mGrowBy));
ASSERT(mHeaps.back().mpData != 0); ASSERT(mHeaps.back().mpData != 0);
mCurOff = 0; mCurOff = 0;
#ifdef _DEUBG #ifdef _DEUBG
void* ret = Malloc( size ); void* ret = Malloc(size);
ASSERT(ret != 0); ASSERT(ret != 0);
return ret; return ret;
#else #else
return Malloc( size ); return Malloc(size);
#endif #endif
} }
} }
size_t cGrowHeap_i::AlignSizeRequest( size_t size, size_t alignSize ) size_t cGrowHeap_i::AlignSizeRequest(size_t size, size_t alignSize)
{ {
// The two's complement algorithm requires a non-zero size request size, // The two's complement algorithm requires a non-zero size request size,
// so make make all requests require it so that this function // so make make all requests require it so that this function
// acts the same no matter what the integer representation // acts the same no matter what the integer representation
if( 0 == size ) if (0 == size)
size = 1; size = 1;
#if USES_2S_COMPLEMENT #if USES_2S_COMPLEMENT
// This efficient algorithm assumes alignSize is power of two AND a // This efficient algorithm assumes alignSize is power of two AND a
// 2's complement representation. Requires non-zero size request // 2's complement representation. Requires non-zero size request
ASSERT( 0 == ( alignSize % 2 ) ); ASSERT(0 == (alignSize % 2));
ASSERT( size > 0 ); ASSERT(size > 0);
return( ( size + alignSize - 1 ) & ~( alignSize - 1 ) ); return ((size + alignSize - 1) & ~(alignSize - 1));
#else #else
// this makes no assumption about BYTE_ALIGN or hardware integer representation // this makes no assumption about BYTE_ALIGN or hardware integer representation
return( ( ( size / alignSize ) + ( ( size % alignSize ) ? 1 : 0 ) ) * alignSize ); return (((size / alignSize) + ((size % alignSize) ? 1 : 0)) * alignSize);
#endif #endif
} }
void cGrowHeap_i::Clear() void cGrowHeap_i::Clear()
{ {
for( HeapList::iterator i = mHeaps.begin(); i != mHeaps.end(); i++ ) for (HeapList::iterator i = mHeaps.begin(); i != mHeaps.end(); i++)
{ {
delete [] i->mpData; delete [] i->mpData;
} }
@ -168,27 +171,25 @@ void cGrowHeap_i::Clear()
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// cGrowHeap // cGrowHeap
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
cGrowHeap::cGrowHeap( size_t initialSize, size_t growBy, const TCHAR* name ) : cGrowHeap::cGrowHeap(size_t initialSize, size_t growBy, const TCHAR* name)
mpData( new cGrowHeap_i( initialSize, growBy, name ) ) : mpData(new cGrowHeap_i(initialSize, growBy, name))
{ {
} }
cGrowHeap::~cGrowHeap() cGrowHeap::~cGrowHeap()
{ {
cDebug d("FCO name heap stats"); cDebug d("FCO name heap stats");
d.TraceDebug( _T("Total heap memory usage for %s: %d\n"), mpData->mName.c_str(), TotalMemUsage() ); d.TraceDebug(_T("Total heap memory usage for %s: %d\n"), mpData->mName.c_str(), TotalMemUsage());
delete mpData; delete mpData;
} }
void* cGrowHeap::Malloc( size_t size ) void* cGrowHeap::Malloc(size_t size)
{ {
return mpData->Malloc( size ); return mpData->Malloc(size);
} }
void cGrowHeap::Clear() void cGrowHeap::Clear()
{ {
mpData->Clear(); mpData->Clear();
} }

View File

@ -52,21 +52,20 @@ class cGrowHeap_i;
class cGrowHeap class cGrowHeap
{ {
public: public:
cGrowHeap( size_t initialSize, size_t growby, const TCHAR* name ); cGrowHeap(size_t initialSize, size_t growby, const TCHAR* name);
// creates a heap that is initially initialSize big, and increases the // creates a heap that is initially initialSize big, and increases the
// size by growBy every time there is no more room. // size by growBy every time there is no more room.
// initialSize and growby must be a multiple of BYTE_ALIGN // initialSize and growby must be a multiple of BYTE_ALIGN
~cGrowHeap(); ~cGrowHeap();
void* Malloc( size_t size ); void* Malloc(size_t size);
void Clear(); void Clear();
// resets the grow heap's state. // resets the grow heap's state.
size_t TotalMemUsage() const; size_t TotalMemUsage() const;
// returns the total memory usage of this heap // returns the total memory usage of this heap
private: private:
cGrowHeap_i* mpData; cGrowHeap_i* mpData;
}; };
#endif #endif

View File

@ -32,5 +32,3 @@
//hashtable.cpp : implementation for hashtable which maps const TCHAR*'s to void*'s //hashtable.cpp : implementation for hashtable which maps const TCHAR*'s to void*'s
#include "stdcore.h" #include "stdcore.h"
#include "hashtable.h" #include "hashtable.h"

View File

@ -67,8 +67,7 @@
// equality. There is also a specialization for TSTRINGS. If neither of these // equality. There is also a specialization for TSTRINGS. If neither of these
// fit your needs, you must pass the hash table your own fn pointer or class // fit your needs, you must pass the hash table your own fn pointer or class
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template<class T> template<class T> class cDefaultCompare
class cDefaultCompare
{ {
public: public:
bool operator()(const T& lhs, const T& rhs) bool operator()(const T& lhs, const T& rhs)
@ -79,8 +78,7 @@ public:
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
// specialization for TSTRINGS // specialization for TSTRINGS
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
template<> template<> inline bool cDefaultCompare<TSTRING>::operator()(const TSTRING& lhs, const TSTRING& rhs)
inline bool cDefaultCompare<TSTRING>::operator()(const TSTRING& lhs, const TSTRING& rhs)
{ {
return (lhs.compare(rhs) == 0); return (lhs.compare(rhs) == 0);
} }
@ -90,8 +88,7 @@ inline bool cDefaultCompare<TSTRING>::operator()(const TSTRING& lhs, const TSTRI
// into a byte* and a key length (for hashing purposes). The default implementation // into a byte* and a key length (for hashing purposes). The default implementation
// just does a cast. A specialization is also provided for TSTRINGs. // just does a cast. A specialization is also provided for TSTRINGs.
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template<class T> template<class T> class cDefaultConvert
class cDefaultConvert
{ {
public: public:
const byte* operator()(const T& obj, int* const pcbKeyLen) const byte* operator()(const T& obj, int* const pcbKeyLen)
@ -104,8 +101,7 @@ public:
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
// specialization for TSTRINGS // specialization for TSTRINGS
///////////////////////////////////////////////////////// /////////////////////////////////////////////////////////
template<> template<> inline const byte* cDefaultConvert<TSTRING>::operator()(const TSTRING& obj, int* const pcbKeyLen)
inline const byte* cDefaultConvert<TSTRING>::operator()(const TSTRING& obj, int* const pcbKeyLen )
{ {
*pcbKeyLen = sizeof(TCHAR) * obj.length(); *pcbKeyLen = sizeof(TCHAR) * obj.length();
return (byte*)obj.c_str(); return (byte*)obj.c_str();
@ -123,7 +119,8 @@ inline const byte* cDefaultConvert<TSTRING>::operator()(const TSTRING& obj, int*
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// these were moved outside of the class because it sucks to have to name the class with template parameters // these were moved outside of the class because it sucks to have to name the class with template parameters
// ie -- mTable(cHashTable<TSTRING, int>::MEDIUM // ie -- mTable(cHashTable<TSTRING, int>::MEDIUM
enum cHashTable_TableSize { enum cHashTable_TableSize
{
HASH_VERY_SMALL = 17, HASH_VERY_SMALL = 17,
HASH_SMALL = 2007, HASH_SMALL = 2007,
HASH_MEDIUM = 6007, HASH_MEDIUM = 6007,
@ -132,155 +129,165 @@ enum cHashTable_TableSize {
}; };
// forward declaration // forward declaration
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP = cDefaultCompare<KEY_TYPE>, class CONVERTER = cDefaultConvert<KEY_TYPE> > template<class KEY_TYPE,
class VAL_TYPE,
class COMPARE_OP = cDefaultCompare<KEY_TYPE>,
class CONVERTER = cDefaultConvert<KEY_TYPE> >
class cHashTableIter; class cHashTableIter;
//General version of cHashTable template: //General version of cHashTable template:
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP = cDefaultCompare<KEY_TYPE>, class CONVERTER = cDefaultConvert<KEY_TYPE> > template<class KEY_TYPE,
class VAL_TYPE,
class COMPARE_OP = cDefaultCompare<KEY_TYPE>,
class CONVERTER = cDefaultConvert<KEY_TYPE> >
class cHashTable class cHashTable
{ {
friend class cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>; friend class cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>;
public: public:
//structure for hash table nodes. //structure for hash table nodes.
struct node { struct node
{
KEY_TYPE nKey; KEY_TYPE nKey;
VAL_TYPE nData; VAL_TYPE nData;
node* next; node* next;
}; };
cHashTable(int tblSize = HASH_MEDIUM); cHashTable(int tblSize = HASH_MEDIUM);
~cHashTable(); ~cHashTable();
bool Insert(KEY_TYPE key, VAL_TYPE data_in); bool Insert(KEY_TYPE key, VAL_TYPE data_in);
// The pointer, data_in, is stored in a node based on string_in's hashing. // The pointer, data_in, is stored in a node based on string_in's hashing.
// //
// if (key) already exists in the table, then it's value is replaced by (data_in) // if (key) already exists in the table, then it's value is replaced by (data_in)
// returns true if (key) already existed in table. otherwise, returns false // returns true if (key) already existed in table. otherwise, returns false
bool Lookup(KEY_TYPE key, VAL_TYPE& data_out) const; bool Lookup(KEY_TYPE key, VAL_TYPE& data_out) const;
//bool Lookup(TSTRING key, VAL_TYPE& data_out) const; //bool Lookup(TSTRING key, VAL_TYPE& data_out) const;
//Lookup returns true if a match is found for string_check. A reference //Lookup returns true if a match is found for string_check. A reference
//to the node in the table that matches string_check is passed back (by ref). //to the node in the table that matches string_check is passed back (by ref).
bool Remove(KEY_TYPE key); bool Remove(KEY_TYPE key);
//The node that matches string_out is de-allocated. //The node that matches string_out is de-allocated.
bool Clear(void); bool Clear(void);
//Clears the entire table and sets all node pointers to NULL //Clears the entire table and sets all node pointers to NULL
bool IsEmpty(void) const; bool IsEmpty(void) const;
uint32 Hash( const KEY_TYPE& key ) const; uint32 Hash(const KEY_TYPE& key) const;
//The hashing function, taken from old Tripwire //The hashing function, taken from old Tripwire
int32 GetNumValues() const { return mValuesInTable; }; int32 GetNumValues() const
{
return mValuesInTable;
};
// returns number of table entries filled // returns number of table entries filled
#ifdef DEBUG #ifdef DEBUG
void TraceDiagnostics() const; void TraceDiagnostics() const;
// traces hash table statistics // traces hash table statistics
#endif #endif
private: private:
cHashTable(const cHashTable& rhs); // not impl cHashTable(const cHashTable& rhs); // not impl
void operator=(const cHashTable& rhs); // not impl void operator=(const cHashTable& rhs); // not impl
node** mTable; node** mTable;
int mTableSize; int mTableSize;
int32 mValuesInTable; int32 mValuesInTable;
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// cHashTableIter // cHashTableIter
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> class cHashTableIter
class cHashTableIter
{ {
public: public:
cHashTableIter(const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& hashTbl); cHashTableIter(const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& hashTbl);
void SeekBegin() const; void SeekBegin() const;
bool Done() const; bool Done() const;
void Next() const; void Next() const;
const KEY_TYPE& Key() const; const KEY_TYPE& Key() const;
const VAL_TYPE& Val() const; const VAL_TYPE& Val() const;
VAL_TYPE& Val(); VAL_TYPE& Val();
private: private:
mutable int mCurIndex; mutable int mCurIndex;
mutable typename cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::node* mpCurNode; mutable typename cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::node* mpCurNode;
const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& mHashTable; const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& mHashTable;
// helper function // helper function
void SeekNextValid() const; void SeekNextValid() const;
}; };
//############################################################################# //#############################################################################
// implementation // implementation
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// iterator // iterator
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::cHashTableIter( const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& hashTbl) : inline cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::cHashTableIter(
mHashTable(hashTbl) const cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>& hashTbl)
: mHashTable(hashTbl)
{ {
SeekBegin(); SeekBegin();
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::SeekBegin() const inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::SeekBegin() const
{ {
mCurIndex = 0; mCurIndex = 0;
mpCurNode = mHashTable.mTable[0]; mpCurNode = mHashTable.mTable[0];
if(! mpCurNode) if (!mpCurNode)
SeekNextValid(); SeekNextValid();
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline bool cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Done() const inline bool cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Done() const
{ {
return ((mCurIndex < 0) || (mCurIndex >= mHashTable.mTableSize)); return ((mCurIndex < 0) || (mCurIndex >= mHashTable.mTableSize));
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Next() const inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Next() const
{ {
SeekNextValid(); SeekNextValid();
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::SeekNextValid() const inline void cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::SeekNextValid() const
{ {
if(mpCurNode) if (mpCurNode)
mpCurNode = mpCurNode->next; mpCurNode = mpCurNode->next;
// if we're out of range, bail out w/o incrementing index // if we're out of range, bail out w/o incrementing index
if(mCurIndex >= mHashTable.mTableSize) if (mCurIndex >= mHashTable.mTableSize)
return; return;
while((! mpCurNode) && (++mCurIndex < mHashTable.mTableSize)) while ((!mpCurNode) && (++mCurIndex < mHashTable.mTableSize))
{ {
mpCurNode = mHashTable.mTable[mCurIndex]; mpCurNode = mHashTable.mTable[mCurIndex];
} }
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline const KEY_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Key() const inline const KEY_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Key() const
{ {
ASSERT(! Done()); ASSERT(!Done());
return mpCurNode->nKey; return mpCurNode->nKey;
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline const VAL_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Val() const inline const VAL_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Val() const
{ {
ASSERT(! Done()); ASSERT(!Done());
return mpCurNode->nData; return mpCurNode->nData;
} }
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
inline VAL_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Val() inline VAL_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Val()
{ {
ASSERT(! Done()); ASSERT(!Done());
return mpCurNode->nData; return mpCurNode->nData;
} }
@ -289,32 +296,32 @@ inline VAL_TYPE& cHashTableIter<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Val(
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
//Default value for tblSize == 6007 //Default value for tblSize == 6007
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::cHashTable(int tblSize) cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::cHashTable(int tblSize)
{ {
mValuesInTable = 0; mValuesInTable = 0;
mTableSize = tblSize; mTableSize = tblSize;
mTable = new node*[mTableSize]; mTable = new node*[mTableSize];
for (int i=0; i < mTableSize; ++i) for (int i = 0; i < mTableSize; ++i)
mTable[i] = NULL; mTable[i] = NULL;
} }
//Destructor steps through table and deallocates all dynamic memory //Destructor steps through table and deallocates all dynamic memory
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::~cHashTable() cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::~cHashTable()
{ {
for (int i=0; i<mTableSize; ++i) for (int i = 0; i < mTableSize; ++i)
{ {
if (mTable[i] != NULL) if (mTable[i] != NULL)
{ {
//delete the entire chain: //delete the entire chain:
node* curr = mTable[i]; node* curr = mTable[i];
node* del; node* del;
while(curr != NULL) while (curr != NULL)
{ {
del = curr; del = curr;
curr=curr->next; curr = curr->next;
delete del; delete del;
} }
@ -328,17 +335,18 @@ cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::~cHashTable()
// using seperate chaining (link lists). // using seperate chaining (link lists).
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// General Version: // General Version:
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Insert(KEY_TYPE key, VAL_TYPE d_in) bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Insert(KEY_TYPE key, VAL_TYPE d_in)
{ {
COMPARE_OP compare; COMPARE_OP compare;
int hindex = Hash( key ); int hindex = Hash(key);
if (mTable[hindex] == NULL) { if (mTable[hindex] == NULL)
{
//open index, perform insert //open index, perform insert
mTable[hindex] = new node; mTable[hindex] = new node;
(mTable[hindex])->nKey = key; (mTable[hindex])->nKey = key;
(mTable[hindex])->next = NULL; (mTable[hindex])->next = NULL;
(mTable[hindex])->nData = d_in; (mTable[hindex])->nData = d_in;
mValuesInTable++; mValuesInTable++;
@ -354,7 +362,7 @@ bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Insert(KEY_TYPE key,
bool found = false; bool found = false;
while (true) while (true)
{ {
if ( compare(nodeptr->nKey, key)) if (compare(nodeptr->nKey, key))
{ {
// we found a duplicate! // we found a duplicate!
found = true; found = true;
@ -362,7 +370,7 @@ bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Insert(KEY_TYPE key,
} }
// break if this is the last node in the list // break if this is the last node in the list
if(! nodeptr->next) if (!nodeptr->next)
break; break;
// otherwise, keep traversing // otherwise, keep traversing
@ -370,13 +378,13 @@ bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Insert(KEY_TYPE key,
} }
// add a node if the key was not found // add a node if the key was not found
if (! found) if (!found)
{ {
node *prev = nodeptr; node* prev = nodeptr;
nodeptr = new node; nodeptr = new node;
nodeptr->nKey = key; nodeptr->nKey = key;
nodeptr->next = NULL; nodeptr->next = NULL;
prev->next = nodeptr; prev->next = nodeptr;
mValuesInTable++; mValuesInTable++;
} }
@ -392,27 +400,28 @@ bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Insert(KEY_TYPE key,
// Lookup -- Attempts to find 'string' in the hash table. // Lookup -- Attempts to find 'string' in the hash table.
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// General Version: // General Version:
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Lookup(KEY_TYPE key, VAL_TYPE& d_out) const
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Lookup(KEY_TYPE key, VAL_TYPE& d_out) const
{ {
COMPARE_OP compare; COMPARE_OP compare;
int hindex = Hash( key ); int hindex = Hash(key);
if (mTable[hindex] == NULL) if (mTable[hindex] == NULL)
return false; return false;
else { else
{
node* nodeptr = mTable[hindex]; node* nodeptr = mTable[hindex];
while (nodeptr != NULL) while (nodeptr != NULL)
{ {
if( compare(nodeptr->nKey, key)) { if (compare(nodeptr->nKey, key))
{
d_out = nodeptr->nData; d_out = nodeptr->nData;
return true; return true;
} }
nodeptr = nodeptr->next; nodeptr = nodeptr->next;
} }
} }
return false; //mTable entries exhausted without a match return false; //mTable entries exhausted without a match
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
@ -420,24 +429,26 @@ cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Lookup(KEY_TYPE key, VAL_
// the nKey is not found in the table. // the nKey is not found in the table.
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// General Version - // General Version -
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Remove(KEY_TYPE key)
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Remove(KEY_TYPE key)
{ {
COMPARE_OP compare; COMPARE_OP compare;
int hindex = Hash( key ); int hindex = Hash(key);
if (mTable[hindex] == NULL) { if (mTable[hindex] == NULL)
{
delete (mTable[hindex]); delete (mTable[hindex]);
mTable[hindex] = NULL; mTable[hindex] = NULL;
return true; return true;
} }
else { else
{
node* nodeptr = mTable[hindex]; node* nodeptr = mTable[hindex];
node* prev; node* prev;
while(nodeptr != NULL) { while (nodeptr != NULL)
{
prev = nodeptr; prev = nodeptr;
if(compare(mTable[hindex]->nKey, key)) if (compare(mTable[hindex]->nKey, key))
{ {
prev->next = nodeptr->next; prev->next = nodeptr->next;
delete nodeptr; delete nodeptr;
@ -445,48 +456,48 @@ cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Remove(KEY_TYPE key)
mTable[hindex] = NULL; mTable[hindex] = NULL;
nodeptr = NULL; nodeptr = NULL;
return true; return true;
}//end if } //end if
nodeptr = nodeptr->next; nodeptr = nodeptr->next;
}//end while } //end while
}//end else } //end else
return false; //match was not found, no node deleted return false; //match was not found, no node deleted
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// Clear -- Clears entire hash table so that all indices are NULL // Clear -- Clears entire hash table so that all indices are NULL
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Clear(void)
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Clear(void)
{ {
for (int i=0; i<mTableSize; ++i) for (int i = 0; i < mTableSize; ++i)
{ {
if (mTable[i] != NULL) { if (mTable[i] != NULL)
{
node* curr = mTable[i]; node* curr = mTable[i];
node* del; node* del;
while(curr != NULL) { while (curr != NULL)
del = curr; {
curr=curr->next; del = curr;
curr = curr->next;
delete del; delete del;
if (del == mTable[i]) if (del == mTable[i])
mTable[i] = NULL; mTable[i] = NULL;
del = NULL; del = NULL;
}//end delete chain loop } //end delete chain loop
}//end if mTable[i]!= NULL } //end if mTable[i]!= NULL
}//end for } //end for
return (IsEmpty()); return (IsEmpty());
} }
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// IsEmpty -- // IsEmpty --
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
bool bool cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::IsEmpty(void) const
cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::IsEmpty(void) const
{ {
bool ret = true; bool ret = true;
for(int i=0; i< mTableSize; ++i) for (int i = 0; i < mTableSize; ++i)
ret &= (mTable[i] == NULL); ret &= (mTable[i] == NULL);
return ret; return ret;
} }
@ -494,13 +505,13 @@ cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::IsEmpty(void) const
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
// Hash -- performs hashing on key, returns an integer index val. // Hash -- performs hashing on key, returns an integer index val.
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
uint32 cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Hash( const KEY_TYPE& key ) const uint32 cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Hash(const KEY_TYPE& key) const
{ {
CONVERTER converter; CONVERTER converter;
int len; int len;
const byte* pb = converter( key, &len ); //locates key const byte* pb = converter(key, &len); //locates key
uint32 hindex; uint32 hindex;
hindex = *pb; hindex = *pb;
while (len-- > 0) while (len-- > 0)
@ -510,24 +521,24 @@ uint32 cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::Hash( const KEY_TY
#ifdef DEBUG #ifdef DEBUG
template <class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER> template<class KEY_TYPE, class VAL_TYPE, class COMPARE_OP, class CONVERTER>
void cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::TraceDiagnostics() const void cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::TraceDiagnostics() const
{ {
cDebug d("cHashTable::Diagnostics"); cDebug d("cHashTable::Diagnostics");
int slotsFilled = 0, numItems = 0, numMultiSlot = 0; int slotsFilled = 0, numItems = 0, numMultiSlot = 0;
node* pNode; node* pNode;
for(int i=0; i < mTableSize; i++) for (int i = 0; i < mTableSize; i++)
{ {
if(mTable[i] != NULL) if (mTable[i] != NULL)
{ {
slotsFilled++; slotsFilled++;
numItems++; numItems++;
pNode = (mTable[i])->next; pNode = (mTable[i])->next;
if(pNode != NULL) if (pNode != NULL)
numMultiSlot++; numMultiSlot++;
while(pNode) while (pNode)
{ {
numItems++; numItems++;
pNode = pNode->next; pNode = pNode->next;
@ -536,14 +547,17 @@ void cHashTable<KEY_TYPE, VAL_TYPE, COMPARE_OP, CONVERTER>::TraceDiagnostics() c
} }
d.TraceDebug("---------------Hash Table Statisics---------------\n"); d.TraceDebug("---------------Hash Table Statisics---------------\n");
d.TraceDebug("-- Number of slots: %d\n", mTableSize); d.TraceDebug("-- Number of slots: %d\n", mTableSize);
d.TraceDebug("-- Number of items: %d\n", numItems); d.TraceDebug("-- Number of items: %d\n", numItems);
d.TraceDebug("-- Slots filled: %d (%lf %%)\n",slotsFilled, ((double)slotsFilled / (double)mTableSize) * 100.0); d.TraceDebug("-- Slots filled: %d (%lf %%)\n",
d.TraceDebug("-- Slots with >1 item: %d (%lf %%)\n",numMultiSlot, ((double)numMultiSlot / (double)slotsFilled) * 100.0); slotsFilled,
((double)slotsFilled / (double)mTableSize) * 100.0);
d.TraceDebug("-- Slots with >1 item: %d (%lf %%)\n",
numMultiSlot,
((double)numMultiSlot / (double)slotsFilled) * 100.0);
d.TraceDebug("--------------------------------------------------\n"); d.TraceDebug("--------------------------------------------------\n");
} }
#endif // DEBUG # endif // DEBUG
#endif //__HASHTABLE_H #endif //__HASHTABLE_H

View File

@ -51,13 +51,13 @@
#include "ntmbs.h" #include "ntmbs.h"
#if IS_KAI #if IS_KAI
#define IS_STDLIB_MODENA 1 // Has special char_traits req's! # define IS_STDLIB_MODENA 1 // Has special char_traits req's!
#ifdef MSIPL_WCHART # ifdef MSIPL_WCHART
#define MBSTATE_T_DEFINED # define MBSTATE_T_DEFINED
#endif # endif
#else #else
#define IS_STDLIB_MODENA 0 # define IS_STDLIB_MODENA 0
#define MBSTATE_T_DEFINED # define MBSTATE_T_DEFINED
#endif #endif
@ -65,15 +65,24 @@
// Char traits for WCHAR16 (aka dbchar_t) and NTMBCS (mctype_t) // Char traits for WCHAR16 (aka dbchar_t) and NTMBCS (mctype_t)
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#if ( WCHAR_IS_16_BITS ) #if (WCHAR_IS_16_BITS)
namespace tss { typedef std::wstring dbstring; } namespace tss
{
typedef std::wstring dbstring;
}
#elif ( WCHAR_IS_32_BITS ) #elif (WCHAR_IS_32_BITS)
namespace std { template <> struct char_traits< dbchar_t >; } namespace std
namespace tss { typedef std::basic_string<dbchar_t> dbstring; } {
template<> struct char_traits<dbchar_t>;
}
namespace tss
{
typedef std::basic_string<dbchar_t> dbstring;
}
#else #else
#error "wchar_t is not correctly factored!" # error "wchar_t is not correctly factored!"
#endif #endif
@ -84,151 +93,140 @@
// specialize *std*::char_traits!!! // specialize *std*::char_traits!!!
template<> template<> struct std::char_traits<dbchar_t>
struct std::char_traits< dbchar_t >
{ {
typedef dbchar_t char_type; typedef dbchar_t char_type;
typedef wint_t int_type; typedef wint_t int_type;
typedef streampos pos_type; typedef streampos pos_type;
typedef streamoff off_type; typedef streamoff off_type;
#ifdef MBSTATE_T_DEFINED # ifdef MBSTATE_T_DEFINED
typedef mbstate_t state_type; typedef mbstate_t state_type;
#else # else
typedef int state_type; // Shame on you KAI! This is ANSI-C! typedef int state_type; // Shame on you KAI! This is ANSI-C!
#endif # endif
static static void assign(char_type& lhs, const char_type& rhs)
void assign( char_type& lhs, const char_type& rhs ) { {
lhs = rhs; lhs = rhs;
} }
static static bool eq(const char_type& lhs, const char_type& rhs)
bool eq( const char_type& lhs, const char_type& rhs ) { {
return lhs == rhs; return lhs == rhs;
} }
static static bool lt(const char_type& lhs, const char_type& rhs)
bool lt( const char_type& lhs, const char_type& rhs ) { {
return lhs < rhs; return lhs < rhs;
} }
static static int compare(const char_type* lhs, const char_type* rhs, size_t N)
int compare( const char_type* lhs, const char_type* rhs, size_t N )
{ {
for ( ; N; ++lhs, ++rhs, --N ) for (; N; ++lhs, ++rhs, --N)
if ( *lhs != *rhs ) if (*lhs != *rhs)
return ( *lhs < *rhs ) ? -1 : +1; return (*lhs < *rhs) ? -1 : +1;
return 0; return 0;
} }
static static size_t length(const char_type* psz)
size_t length( const char_type* psz )
{ {
if ( psz == 0 ) if (psz == 0)
return 0; return 0;
else else
{ {
const char_type* end; const char_type* end;
for ( end = psz; *end; end++ ); for (end = psz; *end; end++)
return (size_t)( end - psz ); ;
return (size_t)(end - psz);
} }
} }
static static char_type* copy(char_type* lhs, const char_type* rhs, size_t N)
char_type* copy( char_type* lhs, const char_type* rhs, size_t N )
{ {
for ( char_type* at = lhs; N; ++at, ++rhs, --N ) for (char_type* at = lhs; N; ++at, ++rhs, --N)
*at = *rhs; *at = *rhs;
return lhs; return lhs;
} }
static static const char_type* find(const char_type* psz, size_t N, const char_type& ch)
const char_type*
find( const char_type* psz, size_t N, const char_type& ch )
{ {
for ( ; N; ++psz, --N ) for (; N; ++psz, --N)
if ( *psz == ch ) if (*psz == ch)
return psz; return psz;
return 0; return 0;
} }
static static char_type* move(char_type* lhs, const char_type* rhs, size_t N)
char_type* move( char_type* lhs, const char_type* rhs, size_t N ) { {
return (char_type*)memmove( lhs, rhs, N * sizeof(char_type) ); return (char_type*)memmove(lhs, rhs, N * sizeof(char_type));
} }
static static char_type* assign(char_type* lhs, size_t N, char_type ch)
char_type* assign( char_type* lhs, size_t N, char_type ch )
{ {
for ( char_type* at = lhs; N; ++at, --N ) for (char_type* at = lhs; N; ++at, --N)
*at = ch; *at = ch;
return lhs; return lhs;
} }
static static int_type not_eof(const int_type& ch)
int_type not_eof( const int_type& ch ) {
return int_type( !eq( ch, eof() ) ? ch : ~ch );
}
static
char_type to_char_type( const int_type& ch )
{ {
return return int_type(!eq(ch, eof()) ? ch : ~ch);
eq_int_type( ch, to_int_type( ch ) )
? ch
: char_type(0);
} }
static static char_type to_char_type(const int_type& ch)
int_type to_int_type( const char_type& ch ) { {
return eq_int_type(ch, to_int_type(ch)) ? ch : char_type(0);
}
static int_type to_int_type(const char_type& ch)
{
return (int_type)ch; return (int_type)ch;
} }
static static bool eq_int_type(const int_type& lhs, const int_type& rhs)
bool eq_int_type( const int_type& lhs, const int_type& rhs ) { {
return lhs == rhs; return lhs == rhs;
} }
#if IS_STDLIB_MODENA # if IS_STDLIB_MODENA
// CAUTION:RAD -- Extra members required by Modena!! // CAUTION:RAD -- Extra members required by Modena!!
#ifdef MBSTATE_T_DEFINED // This is ANSI-C *not* ANSI-C++!! # ifdef MBSTATE_T_DEFINED // This is ANSI-C *not* ANSI-C++!!
static static state_type get_state(pos_type pos)
state_type get_state( pos_type pos ) { {
return pos.state(); return pos.state();
} }
static static pos_type get_pos(pos_type pos, state_type state)
pos_type get_pos( pos_type pos, state_type state ) { {
return pos_type( pos.offset(), state ); return pos_type(pos.offset(), state);
} }
#endif//MBSTATE_T_DEFINED # endif //MBSTATE_T_DEFINED
static static char_type newline()
char_type newline() { {
return L'\n'; return L'\n';
} }
static static char_type eos()
char_type eos() { {
return 0; return 0;
} }
#endif//IS_STDLIB_MODENA # endif //IS_STDLIB_MODENA
static static int_type eof()
int_type eof() { {
return (wint_t)(0xFFFF); return (wint_t)(0xFFFF);
} }
}; };
#endif//WCHAR_IS_16_BITS // We already have a dbstring implicitly in wstring!!! # endif //WCHAR_IS_16_BITS // We already have a dbstring implicitly in wstring!!!
#endif//__NTDBS_H #endif //__NTDBS_H

View File

@ -38,20 +38,18 @@
* Routines to make NTMBS processing easier. * Routines to make NTMBS processing easier.
*/ */
#include "stdcore.h" // for: pch #include "stdcore.h" // for: pch
#include "ntmbs.h" // for: These Declarations #include "ntmbs.h" // for: These Declarations
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Module-wide Helpers // Module-wide Helpers
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#ifndef TSS_Raise // Should add file and line info in DEBUG mode!!!! #ifndef TSS_Raise // Should add file and line info in DEBUG mode!!!!
#define TSS_Raise( Xcpt, pkg, ids ) \ # define TSS_Raise(Xcpt, pkg, ids) throw Xcpt(TSS_GetString(pkg, ids))
throw Xcpt( TSS_GetString( pkg, ids ) )
#endif//TSS_Raise
#endif //TSS_Raise
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -134,32 +132,28 @@ tss::mbsdec( const_ntmbs_t beg, const_ntmbs_t curr )
* POSTCONDITIONS: * POSTCONDITIONS:
* Returns non-const pointer after moving it. * Returns non-const pointer after moving it.
*/ */
ntmbs_t ntmbs_t tss::mbsinc(const_ntmbs_t psz)
tss::mbsinc( const_ntmbs_t psz )
{ {
cDebug dbg( "tss::mbsinc -" ); cDebug dbg("tss::mbsinc -");
if ( psz == 0 ) if (psz == 0)
throw eCharacter( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); throw eCharacter(TSS_GetString(cCore, core::STR_ERR_ISNULL));
int nBytes = ::mblen( (char*)psz, MB_CUR_MAX ); int nBytes = ::mblen((char*)psz, MB_CUR_MAX);
if ( nBytes == -1 ) if (nBytes == -1)
{ {
dbg.TraceDebug( "Character Fault: %c\n", *psz ); dbg.TraceDebug("Character Fault: %c\n", *psz);
if ( (unsigned char)*psz > 0x7F ) if ((unsigned char)*psz > 0x7F)
{ {
dbg.TraceDebug( "Normalizing.\n" ); dbg.TraceDebug("Normalizing.\n");
return (((ntmbs_t)psz) + 1 ); return (((ntmbs_t)psz) + 1);
} }
dbg.TraceDebug( "Incorrectly Formed, Cannot Normalize!\n" ); dbg.TraceDebug("Incorrectly Formed, Cannot Normalize!\n");
TSS_Raise( TSS_Raise(eCharacterEncoding, cCore, core::STR_ERR_BADCHAR);
eCharacterEncoding,
cCore,
core::STR_ERR_BADCHAR );
} }
return ( ((ntmbs_t)psz) + nBytes ); return (((ntmbs_t)psz) + nBytes);
} }
@ -180,33 +174,30 @@ tss::mbsinc( const_ntmbs_t psz )
* POSTCONDITIONS: * POSTCONDITIONS:
* Returns size_t value indicating bytes in the range of [0,nCount). * Returns size_t value indicating bytes in the range of [0,nCount).
*/ */
size_t size_t tss::mbsbytes(const_ntmbs_t psz, size_t nCount)
tss::mbsbytes( const_ntmbs_t psz, size_t nCount )
{ {
const_ntmbs_t at = psz; const_ntmbs_t at = psz;
while ( nCount-- ) while (nCount--)
at = tss::mbsinc( at ); at = tss::mbsinc(at);
return (size_t)((char*)at - (char*)psz); return (size_t)((char*)at - (char*)psz);
} }
/// To Null terminator /// To Null terminator
size_t size_t tss::mbsbytes(const_ntmbs_t psz)
tss::mbsbytes( const_ntmbs_t psz )
{ {
if ( psz == 0 ) if (psz == 0)
throw eCharacter( TSS_GetString( cCore, core::STR_ERR_ISNULL ) ); throw eCharacter(TSS_GetString(cCore, core::STR_ERR_ISNULL));
const_ntmbs_t at; const_ntmbs_t at;
for ( at = psz; *at; ++at ); for (at = psz; *at; ++at)
;
return (size_t)((char*)at - (char*)psz); return (size_t)((char*)at - (char*)psz);
} }
/* /*
* TSS::mbscount * TSS::mbscount
* *
@ -224,25 +215,22 @@ tss::mbsbytes( const_ntmbs_t psz )
* POSTCONDITIONS: * POSTCONDITIONS:
* Returns size_t value indicating characters in the range of [psz + 0, psz + nBytes). * Returns size_t value indicating characters in the range of [psz + 0, psz + nBytes).
*/ */
size_t size_t tss_mbscount(const_ntmbs_t psz, size_t nBytes)
tss_mbscount( const_ntmbs_t psz, size_t nBytes )
{ {
size_t nCount = 0; size_t nCount = 0;
const_ntmbs_t at = psz; const_ntmbs_t at = psz;
const_ntmbs_t end = psz + nBytes; const_ntmbs_t end = psz + nBytes;
for ( ; at < end; nCount++, at = tss::mbsinc( at ) ); for (; at < end; nCount++, at = tss::mbsinc(at))
;
return nCount; return nCount;
} }
/// To Null terminator /// To Null terminator
size_t size_t tss::mbscount(const_ntmbs_t psz)
tss::mbscount( const_ntmbs_t psz )
{ {
size_t nCount = 0; size_t nCount = 0;
for ( ; *psz; psz = tss::mbsinc( psz ), nCount++ ); for (; *psz; psz = tss::mbsinc(psz), nCount++)
;
return nCount; return nCount;
} }

View File

@ -45,9 +45,9 @@
/// Requirements. /// Requirements.
#include "error.h" // for: TSS_EXCEPTION #include "error.h" // for: TSS_EXCEPTION
#include "package.h" // for: TSS_GetString #include "package.h" // for: TSS_GetString
#include "corestrings.h" // for: Utility Strings #include "corestrings.h" // for: Utility Strings
/// Type Definitions for Multiple (?), Double (16), and Wide Characters (32) /// Type Definitions for Multiple (?), Double (16), and Wide Characters (32)
@ -55,28 +55,27 @@
//--Null-terminated Multibyte Character Sequence //--Null-terminated Multibyte Character Sequence
#ifndef NTMBS_T_DEFINED #ifndef NTMBS_T_DEFINED
#define NTMBS_T_DEFINED # define NTMBS_T_DEFINED
#ifdef TSS_NTMBS_IS_UNSIGNED // Natural-sign by default # ifdef TSS_NTMBS_IS_UNSIGNED // Natural-sign by default
typedef unsigned char mbchar_t; typedef unsigned char mbchar_t;
typedef unsigned char* ntmbs_t; typedef unsigned char* ntmbs_t;
typedef const unsigned char* const_ntmbs_t; typedef const unsigned char* const_ntmbs_t;
#else //TSS_NTMBS_IS_UNSIGNED # else //TSS_NTMBS_IS_UNSIGNED
typedef char mbchar_t; typedef char mbchar_t;
typedef char* ntmbs_t; typedef char* ntmbs_t;
typedef const char* const_ntmbs_t; typedef const char* const_ntmbs_t;
#endif//TSS_NTMBS_IS_UNSIGNED # endif //TSS_NTMBS_IS_UNSIGNED
#endif//NTMBS_T_DEFINED #endif //NTMBS_T_DEFINED
//--Null-terminated Wide Character Sequence (Could be double or quad byte) //--Null-terminated Wide Character Sequence (Could be double or quad byte)
#ifndef NTWCS_T_DEFINED #ifndef NTWCS_T_DEFINED
#define NTWCS_T_DEFINED # define NTWCS_T_DEFINED
//typedef wchar_t wchar_t; //typedef wchar_t wchar_t;
typedef wchar_t* ntwcs_t; typedef wchar_t* ntwcs_t;
typedef const wchar_t* const_ntwcs_t; typedef const wchar_t* const_ntwcs_t;
#endif//NTWCS_T_DEFINED #endif //NTWCS_T_DEFINED
/// NOTE: Size Specific (2 [double] or 4 [quad] byte wide characters) /// NOTE: Size Specific (2 [double] or 4 [quad] byte wide characters)
@ -84,57 +83,57 @@
//--Null-terminated double(2)-byte Character Sequence //--Null-terminated double(2)-byte Character Sequence
#ifndef NTDBS_T_DEFINED #ifndef NTDBS_T_DEFINED
#define NTDBS_T_DEFINED # define NTDBS_T_DEFINED
#if WCHAR_IS_16_BITS # if WCHAR_IS_16_BITS
typedef wchar_t dbchar_t; // Same size but use NT's type typedef wchar_t dbchar_t; // Same size but use NT's type
#else # else
typedef uint16 dbchar_t; typedef uint16 dbchar_t;
#endif # endif
typedef dbchar_t* ntdbs_t; typedef dbchar_t* ntdbs_t;
typedef const dbchar_t* const_ntdbs_t; typedef const dbchar_t* const_ntdbs_t;
#endif//NTDBS_T_DEFINED #endif //NTDBS_T_DEFINED
//--Internal, "size-specific" types for type dispatched specializations //--Internal, "size-specific" types for type dispatched specializations
#ifndef NTQBS_T_DEFINED #ifndef NTQBS_T_DEFINED
#define NTQBS_T_DEFINED # define NTQBS_T_DEFINED
#if WCHAR_IS_32_BITS # if WCHAR_IS_32_BITS
typedef wchar_t qbchar_t; // Same size but use NT's type typedef wchar_t qbchar_t; // Same size but use NT's type
#else # else
typedef uint32 qbchar_t; typedef uint32 qbchar_t;
#endif # endif
typedef qbchar_t* ntqbs_t; typedef qbchar_t* ntqbs_t;
typedef const qbchar_t* const_ntqbs_t; typedef const qbchar_t* const_ntqbs_t;
#endif//NTQBS_T_DEFINED #endif //NTQBS_T_DEFINED
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// NTMBS Manipulators // NTMBS Manipulators
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TSS_EXCEPTION( eCharacter, eError ); TSS_EXCEPTION(eCharacter, eError);
TSS_EXCEPTION( eCharacterEncoding, eCharacter ); TSS_EXCEPTION(eCharacterEncoding, eCharacter);
namespace tss namespace tss
{ {
/// Specific Routines (Add as needed) /// Specific Routines (Add as needed)
//ntmbs_t mbsdec( const_ntmbs_t, const_ntmbs_t ); //ntmbs_t mbsdec( const_ntmbs_t, const_ntmbs_t );
ntmbs_t mbsinc( const_ntmbs_t ); ntmbs_t mbsinc(const_ntmbs_t);
size_t mbsbytes( const_ntmbs_t, size_t ); size_t mbsbytes(const_ntmbs_t, size_t);
size_t mbscount( const_ntmbs_t, size_t ); size_t mbscount(const_ntmbs_t, size_t);
size_t mbsbytes( const_ntmbs_t ); size_t mbsbytes(const_ntmbs_t);
size_t mbscount( const_ntmbs_t ); size_t mbscount(const_ntmbs_t);
inline size_t mbslen( const_ntmbs_t psz ) { // RAD: Yeesh! inline size_t mbslen(const_ntmbs_t psz)
return tss::mbscount( psz ); { // RAD: Yeesh!
} return tss::mbscount(psz);
}//tss:: }
} // namespace tss
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -145,15 +144,14 @@ namespace tss
namespace tss namespace tss
{ {
/// Increment and Decrement Pointers by (N) /// Increment and Decrement Pointers by (N)
//--DEC //--DEC
template< class CT > template<class CT> inline CT* strdec(const CT*, const CT* psz)
inline {
CT* strdec( const CT*, const CT* psz ) { return const_cast<CT*>(psz - 1);
return const_cast<CT*>( psz - 1 ); }
}
#if 0 #if 0
template<> template<>
@ -164,96 +162,86 @@ namespace tss
#endif #endif
//--INC //--INC
template< class CT > template<class CT> inline CT* strinc(const CT* psz)
inline {
CT* strinc( const CT* psz ) ASSERT(psz);
{ return const_cast<CT*>((*psz ? psz + 1 : psz));
ASSERT( psz ); }
return const_cast<CT*>( ( *psz ? psz + 1 : psz ) );
}
template< class CT, class SIZET > template<class CT, class SIZET> inline CT* strinc(const CT* psz, SIZET N)
inline {
CT* strinc( const CT* psz, SIZET N ) ASSERT(psz);
{ return const_cast<CT*>((*psz ? psz + N : psz));
ASSERT( psz ); }
return const_cast<CT*>( ( *psz ? psz + N : psz ) );
}
template<> template<> inline ntmbs_t strinc(const_ntmbs_t psz)
inline {
ntmbs_t strinc( const_ntmbs_t psz ) return tss::mbsinc(psz);
{ }
return tss::mbsinc( psz );
}
template<> template<> inline ntmbs_t strinc(const_ntmbs_t psz, size_t N)
inline {
ntmbs_t strinc( const_ntmbs_t psz, size_t N ) ntmbs_t at = const_cast<ntmbs_t>(psz);
{ while (N--)
ntmbs_t at = const_cast<ntmbs_t>( psz ); at = tss::mbsinc(at);
while ( N-- ) return at;
at = tss::mbsinc( at ); }
return at;
}
/// Byte and Character Count Mappings /// Byte and Character Count Mappings
//--BYTES //--BYTES
template< class CT > template<class CT> size_t strsize(const CT* psz)
size_t strsize( const CT* psz ) {
{ const CT* at = psz;
const CT* at = psz; while (*at)
while ( *at ) at++; at++;
return (size_t)((char*)at - (char*)psz); return (size_t)((char*)at - (char*)psz);
} }
template< class CT > template<class CT> size_t strsize(const CT*, size_t N)
size_t strsize( const CT*, size_t N ) {
{ return N * sizeof(CT);
return N * sizeof(CT); }
}
template<> template<> inline size_t strsize(const_ntmbs_t psz)
inline size_t strsize( const_ntmbs_t psz ) { {
return mbsbytes( psz ); return mbsbytes(psz);
} }
template<> template<> inline size_t strsize(const_ntmbs_t psz, size_t N)
inline size_t strsize( const_ntmbs_t psz, size_t N ) { {
return mbsbytes( psz, N ); return mbsbytes(psz, N);
} }
//--COUNT //--COUNT
template< class CT > template<class CT> size_t strcount(const CT* psz)
size_t strcount( const CT* psz ) {
{ const CT* at = psz;
const CT* at = psz; while (*at)
while ( *at ) at++; at++;
return (size_t)(at - psz); return (size_t)(at - psz);
} }
template< class CT > template<class CT> size_t strcount(const CT*, size_t N)
size_t strcount( const CT*, size_t N ) {
{ return N;
return N; }
}
template<> template<> inline size_t strcount(const_ntmbs_t psz)
inline size_t strcount( const_ntmbs_t psz ) { {
return mbscount( psz ); return mbscount(psz);
} }
template<> template<> inline size_t strcount(const_ntmbs_t psz, size_t N)
inline size_t strcount( const_ntmbs_t psz, size_t N ) { {
return mbscount( psz, N ); return mbscount(psz, N);
} }
/* These are needed! However, it would be better to just create /* These are needed! However, it would be better to just create
@ -262,7 +250,7 @@ done with it */
#ifdef TSS_NTMBS_AWARE_SEACH_COMPLETE #ifdef TSS_NTMBS_AWARE_SEACH_COMPLETE
/* CAUTION:RAD -- I changed the traversal logic from "!=" to /* CAUTION:RAD -- I changed the traversal logic from "!=" to
"<" to accomodate a basic_string whose end() member does not "<" to accomodate a basic_string whose end() member does not
correctly point after the last valid trail-byte in a string. correctly point after the last valid trail-byte in a string.
Really, at != end should be correct, but I don't want to leave Really, at != end should be correct, but I don't want to leave
@ -270,243 +258,209 @@ done with it */
under unit test and have all occurances of "at < end" changed under unit test and have all occurances of "at < end" changed
to the "more on-purpose" "at != end". */ to the "more on-purpose" "at != end". */
/// Various MULTIBYTE aware string searching routines.. /// Various MULTIBYTE aware string searching routines..
//--FIND_FIRST: ITER //--FIND_FIRST: ITER
template< class InputT, class E > template<class InputT, class E> InputT find_first(InputT beg, InputT end, const E& item)
InputT {
find_first( InputT beg, InputT end, const E& item ) for (; beg < end && *beg != item; beg = (InputT)tss::strinc(beg))
{ ;
for ( ; beg < end && *beg != item; beg = (InputT)tss::strinc( beg ) ); return beg;
return beg; }
}
//--FIND_LAST: ITER //--FIND_LAST: ITER
template< class InputT, class E > template<class InputT, class E> InputT find_last(InputT beg, InputT end, const E& item)
InputT {
find_last( InputT beg, InputT end, const E& item ) InputT at = end;
{ for (; beg < end; beg = (InputT)tss::strinc(beg))
InputT at = end; ;
for ( ; beg < end ; beg = (InputT)tss::strinc( beg ) ); if (*beg == item)
if ( *beg == item ) at = beg;
at = beg;
return at; return at;
} }
//--FIND_FIRST: STRING //--FIND_FIRST: STRING
template< class StrT > template<class StrT> StrT::size_type find_first(const StrT& sin, StrT::const_reference item)
StrT::size_type {
find_first( const StrT& sin, StrT::const_reference item ) StrT::const_iterator beg = sin.begin();
{ end = sin.end();
StrT::const_iterator
beg = sin.begin();
end = sin.end();
StrT::size_type N; StrT::size_type N;
for ( N = 0; beg < end; ++N, beg = (InputT)tss::strinc( beg ) ) for (N = 0; beg < end; ++N, beg = (InputT)tss::strinc(beg))
if ( *beg == item ) if (*beg == item)
return N;
return StrT::npos;
}
//--FIND_LAST: STRING
template<class StrT> StrT::size_type find_last(const StrT& sin, StrT::const_reference item)
{
StrT::size_type N = 0;
StrT::size_type nResult = StrT::npos;
StrT::const_iterator beg = sin.begin();
end = sin.end();
for (; beg < end; beg = (InputT)tss::strinc(beg))
;
if (*beg == item)
nResult = N;
return N;
}
//--FIND_FIRST_OF: ITER
template<class InputT> InputT find_first_of(InputT beg, InputT end, InputT setbeg, InputT setend)
{
InputT at;
for (; beg < end; beg = (InputT)tss::strinc(beg))
;
for (at = setbeg; setbeg < setend; at = (InputT)tss::strinc(at))
if (*beg == *at)
return beg;
return end;
}
//--FIND_FIRST_OF: STRING (SAFE!!!)
template<class StrT> StrT::size_type find_first_of(const StrT& sin, StrT::const_iterator set)
{
// Point to beg of input
StrT::iterator beg = sin.begin();
// Start Search
StrT::size_type N = 0;
for (; beg < sin.end(); ++N, beg = tss::strinc(beg))
for (StrT::const_iterator at = set; *at; at = tss::strinc(at))
if (*beg == *at)
return N; return N;
return StrT::npos; return StrT::npos;
} }
//--FIND_LAST: STRING //--FIND_FIRST_OF: STRING (NOT SAFE!!!)
template< class StrT > template<class StrT>
StrT::size_type StrT::size_type find_first_of(const StrT& sin, StrT::const_iterator set, StrT::size_type nPos, StrT::size_type nCount)
find_last( const StrT& sin, StrT::const_reference item ) {
{
StrT::size_type N = 0;
StrT::size_type nResult = StrT::npos;
StrT::const_iterator
beg = sin.begin();
end = sin.end();
for ( ; beg < end ; beg = (InputT)tss::strinc( beg ) );
if ( *beg == item )
nResult = N;
return N;
}
//--FIND_FIRST_OF: ITER
template< class InputT >
InputT
find_first_of(
InputT beg,
InputT end,
InputT setbeg,
InputT setend )
{
InputT at;
for ( ; beg < end; beg = (InputT)tss::strinc( beg ) );
for ( at = setbeg; setbeg < setend; at = (InputT)tss::strinc( at ) )
if ( *beg == *at )
return beg;
return end;
}
//--FIND_FIRST_OF: STRING (SAFE!!!)
template< class StrT >
StrT::size_type
find_first_of( const StrT& sin, StrT::const_iterator set )
{
// Point to beg of input
StrT::iterator beg = sin.begin();
// Start Search
StrT::size_type N = 0;
for ( ; beg < sin.end(); ++N, beg = tss::strinc( beg ) )
for ( StrT::const_iterator at = set; *at; at = tss::strinc( at ) )
if ( *beg == *at )
return N;
return StrT::npos;
}
//--FIND_FIRST_OF: STRING (NOT SAFE!!!)
template< class StrT >
StrT::size_type
find_first_of(
const StrT& sin,
StrT::const_iterator set,
StrT::size_type nPos,
StrT::size_type nCount )
{
ASSERT( nPos < tss::strcount( sin.begin() ); ASSERT( nPos < tss::strcount( sin.begin() );
if ( nCount > 0 && nPos < sin.size() ) if ( nCount > 0 && nPos < sin.size() )
{ {
ASSERT( nCount > tss::strcount( set ) ); ASSERT(nCount > tss::strcount(set));
StrT::const_iterator endset; // Get end of set StrT::const_iterator endset; // Get end of set
while ( nCount-- ) endset++; while (nCount--)
endset++;
// Advance to nPos // Advance to nPos
StrT::const_iterator at = tss::strinc( sin.begin(), nPos ); StrT::const_iterator at = tss::strinc(sin.begin(), nPos);
StrT::const_iterator end = sin.end(); StrT::const_iterator end = sin.end();
// Start Search // Start Search
StrT::size_type N = 0;
for ( ; at < end; ++N, at = tss::strinc( at ) )
{
if ( tss::find( set, endset, *at ) != 0 )
return N;
}
}
return StrT::npos;
}
//--FIND_LAST_OF: ITER
template< class InputT1, class InputT2 >
InputT
find_last_of(
const InputT1 beg, const InputT1 end,
const InputT2 setbeg, const InputT2 setend )
{
const InputT1 ans = end;
for ( ; beg < end; beg = tss::strinc( beg ) );
for ( InputT2 at = setbeg; setbeg != setend; at = tss::strinc( at ) )
if ( *beg == *at )
ans = beg;
return ans;
}
//--FIND_LAST_OF: STRING (SAFE!!!)
template< class StrT >
StrT::size_type
find_last_of( const StrT& sin, StrT::const_iterator set )
{
StrT::size_type nResult = StrT::npos;
StrT::size_type N = 0; StrT::size_type N = 0;
for ( ; at < end; ++N, at = tss::strinc( at ) ) for (; at < end; ++N, at = tss::strinc(at))
{ {
for ( StrT::const_iterator at = set; *at; at = tss::strinc( at ) ) if (tss::find(set, endset, *at) != 0)
if ( *beg == *at ) return N;
nResult = N;
} }
return nResult;
}
template< class StrT >
StrT::size_type
find_last_of(
const StrT& sin,
StrT::const_iterator set,
StrT::size_type nStart,
StrT::size_type nCount )
{
if ( nCount > 0 && sin.size() )
{
for ( StrT::const_iterator at = sin.begin()
+ (nStart < _Len ? nStart : _Len - 1); ; --_U)
if (_Tr::find(set, nCount, *_U) != 0)
return (_U - _Ptr);
else if (_U == _Ptr)
break;
} }
return StrT::npos; return StrT::npos;
} }
// TODO:RAD -- find_first_not_of;
// TODO:RAD -- find_last_not_of;
#endif//TSS_NTMBS_AWARE_SEACH_COMPLETE //--FIND_LAST_OF: ITER
namespace util template<class InputT1, class InputT2>
InputT find_last_of(const InputT1 beg, const InputT1 end, const InputT2 setbeg, const InputT2 setend)
{
const InputT1 ans = end;
for (; beg < end; beg = tss::strinc(beg))
;
for (InputT2 at = setbeg; setbeg != setend; at = tss::strinc(at))
if (*beg == *at)
ans = beg;
return ans;
}
//--FIND_LAST_OF: STRING (SAFE!!!)
template<class StrT> StrT::size_type find_last_of(const StrT& sin, StrT::const_iterator set)
{
StrT::size_type nResult = StrT::npos;
StrT::size_type N = 0;
for (; at < end; ++N, at = tss::strinc(at))
{ {
// Preserves bit values when enlarging a type to a size_t for (StrT::const_iterator at = set; *at; at = tss::strinc(at))
// Good for preventing sign extension if (*beg == *at)
template< class E > nResult = N;
inline
size_t
char_to_size( E ch )
{
// if this fails, 'ch' can't be cast to a
// size_t and preserve bit values
// if this fails, then you must find another way
ASSERT( sizeof( size_t ) >= sizeof( E ) );
// assert that either 'ch' is an unsigned value (no sign extension possible)
// or that 'ch' is the same size as a size_t (no sign extension is possible as well)
// if this fails, then you must specialize this function like we did for 'char'
ASSERT( (int)(E)-1 > (int)0 || sizeof( size_t ) == sizeof( E ) );
return (size_t)ch;
}
inline
size_t
char_to_size( char ch )
{
return (size_t)(unsigned char)ch;
}
} }
}//tss::
return nResult;
}
#endif//__NTMBS_H template<class StrT>
StrT::size_type find_last_of(const StrT& sin, StrT::const_iterator set, StrT::size_type nStart, StrT::size_type nCount)
{
if (nCount > 0 && sin.size())
{
for (StrT::const_iterator at = sin.begin() + (nStart < _Len ? nStart : _Len - 1);; --_U)
if (_Tr::find(set, nCount, *_U) != 0)
return (_U - _Ptr);
else if (_U == _Ptr)
break;
}
return StrT::npos;
}
// TODO:RAD -- find_first_not_of;
// TODO:RAD -- find_last_not_of;
#endif //TSS_NTMBS_AWARE_SEACH_COMPLETE
namespace util
{
// Preserves bit values when enlarging a type to a size_t
// Good for preventing sign extension
template<class E> inline size_t char_to_size(E ch)
{
// if this fails, 'ch' can't be cast to a
// size_t and preserve bit values
// if this fails, then you must find another way
ASSERT(sizeof(size_t) >= sizeof(E));
// assert that either 'ch' is an unsigned value (no sign extension possible)
// or that 'ch' is the same size as a size_t (no sign extension is possible as well)
// if this fails, then you must specialize this function like we did for 'char'
ASSERT((int)(E)-1 > (int)0 || sizeof(size_t) == sizeof(E));
return (size_t)ch;
}
inline size_t char_to_size(char ch)
{
return (size_t)(unsigned char)ch;
}
} // namespace util
} // namespace tss
#endif //__NTMBS_H

View File

@ -82,7 +82,7 @@
#ifndef __PACKAGE_H #ifndef __PACKAGE_H
#define __PACKAGE_H #define __PACKAGE_H
#include "resources.h" // for: cMessage_<KEY,CHAR> #include "resources.h" // for: cMessage_<KEY,CHAR>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -91,84 +91,86 @@
//--PACKAGE Helpers //--PACKAGE Helpers
#define TSS_Package( pkg ) \ #define TSS_Package(pkg) pkg::GetInstance() // Access "the" Package obj
pkg::GetInstance() // Access "the" Package obj
#define TSS_Dependency( pkg ) \ #define TSS_Dependency(pkg) TSS_Package(pkg) // Declare a Package Depend.
TSS_Package( pkg ) // Declare a Package Depend.
#define TSS_BeginPackage(pkg) \
#define TSS_BeginPackage( pkg ) \ class pkg : public cPackageBase_<TCHAR> \
class pkg : public cPackageBase_< TCHAR > \ { \
{ \ public: \
public: \
static pkg& GetInstance(); static pkg& GetInstance();
#define TSS_EndPackage( pkg ) \ #define TSS_EndPackage(pkg) \
}; } \
;
#define TSS_ImplementPackage( pkg ) \ #define TSS_ImplementPackage(pkg) \
pkg& pkg::GetInstance() \ pkg& pkg::GetInstance() \
{ \ { \
static bool bConstructed = false; \ static bool bConstructed = false; \
static pkg x; \ static pkg x; \
if ( !bConstructed ) \ if (!bConstructed) \
{ \ { \
bConstructed = true; \ bConstructed = true; \
x.LoadStrings(); \ x.LoadStrings(); \
} \ } \
return x; \ return x; \
} }
//--STRINGTABLE Helperfs //--STRINGTABLE Helperfs
#define TSS_GetString( pkg, id ) \ #define TSS_GetString(pkg, id) TSS_Package(pkg).GetString(id) // Access the Message String
TSS_Package( pkg ).GetString( id ) // Access the Message String
#define TSS_DECLARE_STRINGTABLE \ #define TSS_DECLARE_STRINGTABLE \
public: \ public: \
Messages::String \ Messages::String GetString(Messages::ConstKeyRef id) const \
GetString( \ { \
Messages::ConstKeyRef id ) const { \ return m_messages.Get(id); \
return m_messages.Get( id ); } \ } \
void LoadStrings(); \ void LoadStrings(); \
private: \ \
Messages m_messages // Decare a Stringtable private: \
Messages m_messages // Decare a Stringtable
#ifdef DEBUG #ifdef DEBUG
#define TSS_BeginStringtable( pkg ) \ # define TSS_BeginStringtable(pkg) \
void pkg::LoadStrings() \ void pkg::LoadStrings() \
{ cDebug d( #pkg "::LoadStrings()" ); \ { \
d.TraceDebug("Loading strings for " #pkg " package.\n"); \ cDebug d(#pkg "::LoadStrings()"); \
Messages::Pair astr[] = { // Define a Stringtable d.TraceDebug("Loading strings for " #pkg " package.\n"); \
#else // DEBUG Messages::Pair astr[] = { // Define a Stringtable
#define TSS_BeginStringtable( pkg ) \ #else // DEBUG
void pkg::LoadStrings() \ # define TSS_BeginStringtable(pkg) \
{ Messages::Pair astr[] = { // Define a Stringtable void pkg::LoadStrings() \
#endif // DEBUG { \
Messages::Pair astr[] = { // Define a Stringtable
#endif // DEBUG
#define TSS_EndStringtable( pkg ) \ #define TSS_EndStringtable(pkg) \
}; m_messages.Put( \ } \
astr, astr + countof(astr) ); } // End define Strintable ; \
m_messages.Put(astr, astr + countof(astr)); \
} // End define Strintable
#define TSS_StringEntry( id, s ) \ #define TSS_StringEntry(id, s) Messages::Pair(id, s) // Stringtable Entry
Messages::Pair( id, s ) // Stringtable Entry
#define TSS_BeginStringIds( pns ) \ #define TSS_BeginStringIds(pns) \
namespace pns { \ namespace pns \
enum { // Define String IDs { \
enum \
#define TSS_EndStringIds( pns ) \ { // Define String IDs
}; } // End define String IDs
#define TSS_EndStringIds(pns) \
} \
; \
} // End define String IDs
//============================================================================= //=============================================================================
@ -194,18 +196,15 @@
// //
// //
template< class CharT > template<class CharT> class cPackageBase_
class cPackageBase_
{ {
public: public:
typedef cMessages_<int, CharT> Messages;
typedef cMessages_< int, CharT > Messages; void LoadStrings()
{
void LoadStrings() }
{
}
}; };
#endif//__PACKAGE_H #endif //__PACKAGE_H

View File

@ -34,11 +34,11 @@
// //
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
# include <config.h> #include <config.h>
#endif #endif
#ifndef __PLATFORM_H #ifndef __PLATFORM_H
#define __PLATFORM_H # define __PLATFORM_H
//NOTE: Autoconf is strongly preferred as the Right Way to detect platform-specific features/behaviors. //NOTE: Autoconf is strongly preferred as the Right Way to detect platform-specific features/behaviors.
// These macros should really only be used when autoconf can't get the job done. // These macros should really only be used when autoconf can't get the job done.
@ -49,57 +49,57 @@
// For each of these "enumerations" we create unique integers identifying each // For each of these "enumerations" we create unique integers identifying each
// variation. We group similar items together, such as OS_REDHAT and OS_SLACKWARE // variation. We group similar items together, such as OS_REDHAT and OS_SLACKWARE
#define OS_UNKNOWN 0 # define OS_UNKNOWN 0
#define OS_WIN32 0x0101 # define OS_WIN32 0x0101
#define OS_CYGWIN 0x0102 # define OS_CYGWIN 0x0102
#define OS_DOS_DJGPP 0x0103 # define OS_DOS_DJGPP 0x0103
#define OS_LINUX 0x0201 # define OS_LINUX 0x0201
#define OS_ANDROID 0x0202 # define OS_ANDROID 0x0202
#define OS_FREEBSD 0x0301 # define OS_FREEBSD 0x0301
#define OS_NETBSD 0x0302 # define OS_NETBSD 0x0302
#define OS_OPENBSD 0x0303 # define OS_OPENBSD 0x0303
#define OS_DARWIN 0x0304 # define OS_DARWIN 0x0304
#define OS_DRAGONFLYBSD 0x0305 # define OS_DRAGONFLYBSD 0x0305
#define OS_MIDNIGHTBSD 0x0306 # define OS_MIDNIGHTBSD 0x0306
#define OS_MIRBSD 0x0307 # define OS_MIRBSD 0x0307
#define OS_BITRIG 0x0308 # define OS_BITRIG 0x0308
#define OS_LIBERTYBSD 0x0309 # define OS_LIBERTYBSD 0x0309
#define OS_SOLARIS 0x0400 # define OS_SOLARIS 0x0400
#define OS_AIX 0x0401 # define OS_AIX 0x0401
#define OS_HPUX 0x0402 # define OS_HPUX 0x0402
#define OS_IRIX 0x0403 # define OS_IRIX 0x0403
#define OS_OSF1 0x0404 # define OS_OSF1 0x0404
#define OS_MINIX 0x0501 # define OS_MINIX 0x0501
#define OS_HURD 0x0502 # define OS_HURD 0x0502
#define OS_HAIKU 0x0503 # define OS_HAIKU 0x0503
#define OS_SYLLABLE 0x0504 # define OS_SYLLABLE 0x0504
#define OS_SKYOS 0x0505 # define OS_SKYOS 0x0505
#define OS_SORTIX 0x0506 # define OS_SORTIX 0x0506
#define OS_MINT 0x0507 # define OS_MINT 0x0507
#define OS_AROS 0x0508 # define OS_AROS 0x0508
#define OS_RTEMS 0x0509 # define OS_RTEMS 0x0509
#define OS_RISCOS 0x050A # define OS_RISCOS 0x050A
#define OS_REDOX 0x050B # define OS_REDOX 0x050B
#define OS_QNX 0x050C # define OS_QNX 0x050C
#define COMP_UNKNOWN 0 # define COMP_UNKNOWN 0
#define COMP_GCC 0x0001 # define COMP_GCC 0x0001
#define COMP_CLANG 0x0002 # define COMP_CLANG 0x0002
#define COMP_MSVC 0x0101 # define COMP_MSVC 0x0101
#define COMP_KAI_GCC 0x0201 # define COMP_KAI_GCC 0x0201
#define COMP_KAI_SUNPRO 0x0202 # define COMP_KAI_SUNPRO 0x0202
#define COMP_KAI_GLIBC 0x0203 # define COMP_KAI_GLIBC 0x0203
#define COMP_KAI_VISUALAGE 0x0204 # define COMP_KAI_VISUALAGE 0x0204
#define COMP_KAI_HPANSIC 0x0205 # define COMP_KAI_HPANSIC 0x0205
#define COMP_KAI_IRIX 0x0206 # define COMP_KAI_IRIX 0x0206
#define COMP_KAI_OSF1ALPHA 0x0207 # define COMP_KAI_OSF1ALPHA 0x0207
#define COMP_SUNPRO 0x0301 # define COMP_SUNPRO 0x0301
//============================================================================= //=============================================================================
// Platform detection // Platform detection
@ -116,138 +116,137 @@
// section. Use the following sections for anything that does not fall into // section. Use the following sections for anything that does not fall into
// the above catagories. // the above catagories.
#if defined(_WIN32) # if defined(_WIN32)
#define OS OS_WIN32 # define OS OS_WIN32
#define IS_WIN32 1 # define IS_WIN32 1
#elif defined(__CYGWIN__) # elif defined(__CYGWIN__)
#define OS OS_CYGWIN # define OS OS_CYGWIN
#define IS_CYGWIN 1 # define IS_CYGWIN 1
#elif defined(__DJGPP__) # elif defined(__DJGPP__)
#define OS OS_DOS_DJGPP # define OS OS_DOS_DJGPP
#define IS_DOS_DJGPP 1 # define IS_DOS_DJGPP 1
#elif defined(__ANDROID__) # elif defined(__ANDROID__)
#define OS OS_ANDROID # define OS OS_ANDROID
#define IS_ANDROID 1 # define IS_ANDROID 1
#elif defined(__linux__) # elif defined(__linux__)
#define OS OS_LINUX # define OS OS_LINUX
#define IS_LINUX 1 # define IS_LINUX 1
// A herd of BSDs. Have to detect MidnightBSD before FreeBSD, and MirOS & Bitrig before OpenBSD // A herd of BSDs. Have to detect MidnightBSD before FreeBSD, and MirOS & Bitrig before OpenBSD
// because they also define symbols for their ancestor BSDs. // because they also define symbols for their ancestor BSDs.
#elif defined(__DragonFly__) # elif defined(__DragonFly__)
#define OS OS_DRAGONFLYBSD # define OS OS_DRAGONFLYBSD
#define IS_DRAGONFLYBSD 1 # define IS_DRAGONFLYBSD 1
#elif defined(__MidnightBSD__) # elif defined(__MidnightBSD__)
#define OS OS_MIDNIGHTBSD # define OS OS_MIDNIGHTBSD
#define IS_MIDNIGHTBSD 1 # define IS_MIDNIGHTBSD 1
#elif defined(__FreeBSD__) # elif defined(__FreeBSD__)
#define OS OS_FREEBSD # define OS OS_FREEBSD
#define IS_FREEBSD 1 # define IS_FREEBSD 1
#elif defined(__NetBSD__) # elif defined(__NetBSD__)
#define OS OS_NETBSD # define OS OS_NETBSD
#define IS_NETBSD 1 # define IS_NETBSD 1
#elif defined(__MirBSD__) # elif defined(__MirBSD__)
#define OS OS_MIRBSD # define OS OS_MIRBSD
#define IS_MIRBSD 1 # define IS_MIRBSD 1
#elif defined(__Bitrig__) # elif defined(__Bitrig__)
#define OS OS_BITRIG # define OS OS_BITRIG
#define IS_BITRIG 1 # define IS_BITRIG 1
#elif defined(TW_LibertyBSD) # elif defined(TW_LibertyBSD)
#define OS OS_LIBERTYBSD # define OS OS_LIBERTYBSD
#define IS_LIBERTYBSD 1 # define IS_LIBERTYBSD 1
#elif defined(__OpenBSD__) # elif defined(__OpenBSD__)
#define OS OS_OPENBSD # define OS OS_OPENBSD
#define IS_OPENBSD 1 # define IS_OPENBSD 1
#elif defined(__APPLE__) # elif defined(__APPLE__)
#define OS OS_DARWIN # define OS OS_DARWIN
#define IS_DARWIN 1 # define IS_DARWIN 1
#elif defined(__sun) # elif defined(__sun)
#define OS OS_SOLARIS # define OS OS_SOLARIS
#define IS_SOLARIS 1 # define IS_SOLARIS 1
#elif defined(_AIX) # elif defined(_AIX)
#define OS OS_AIX # define OS OS_AIX
#define IS_AIX 1 # define IS_AIX 1
#elif defined (__hpux) # elif defined(__hpux)
#define OS OS_HPUX # define OS OS_HPUX
#define IS_HPUX 1 # define IS_HPUX 1
#elif defined(__sgi) # elif defined(__sgi)
#define OS OS_IRIX # define OS OS_IRIX
#define IS_IRIX 1 # define IS_IRIX 1
#elif defined(TRU64) || defined(__OSF1__) # elif defined(TRU64) || defined(__OSF1__)
#define OS OS_OSF1 # define OS OS_OSF1
#define IS_OSF1 1 # define IS_OSF1 1
#elif defined(__minix__) # elif defined(__minix__)
#define OS OS_MINIX # define OS OS_MINIX
#define IS_MINIX 1 # define IS_MINIX 1
#elif defined(__gnu_hurd__) # elif defined(__gnu_hurd__)
#define OS OS_HURD # define OS OS_HURD
#define IS_HURD 1 # define IS_HURD 1
#elif defined(__HAIKU__) # elif defined(__HAIKU__)
#define OS OS_HAIKU # define OS OS_HAIKU
#define IS_HAIKU 1 # define IS_HAIKU 1
#elif defined(__SYLLABLE__) # elif defined(__SYLLABLE__)
#define OS OS_SYLLABLE # define OS OS_SYLLABLE
#define IS_SYLLABLE 1 # define IS_SYLLABLE 1
#elif defined(SKYOS) # elif defined(SKYOS)
#define OS OS_SKYOS # define OS OS_SKYOS
#define IS_SKYOS 1 # define IS_SKYOS 1
#elif defined(_SORTIX_SOURCE) # elif defined(_SORTIX_SOURCE)
#define OS OS_SORTIX # define OS OS_SORTIX
#define IS_SORTIX 1 # define IS_SORTIX 1
#elif defined(__MINT__) # elif defined(__MINT__)
#define OS OS_MINT # define OS OS_MINT
#define IS_MINT 1 # define IS_MINT 1
#elif defined(__AROS__) # elif defined(__AROS__)
#define OS OS_AROS # define OS OS_AROS
#define IS_AROS 1 # define IS_AROS 1
#elif defined(__rtems__) # elif defined(__rtems__)
#define OS OS_RTEMS # define OS OS_RTEMS
#define IS_RTEMS 1 # define IS_RTEMS 1
#elif defined(__riscos__) # elif defined(__riscos__)
#define OS OS_RISCOS # define OS OS_RISCOS
#define IS_RISCOS 1 # define IS_RISCOS 1
#elif defined(__redox__) # elif defined(__redox__)
#define OS OS_REDOX # define OS OS_REDOX
#define IS_REDOX 1 # define IS_REDOX 1
#elif defined(__QNX__) # elif defined(__QNX__)
#define OS OS_QNX # define OS OS_QNX
#define IS_QNX 1 # define IS_QNX 1
#endif
# endif
/* XXX: COMP may now not resolve, because autoconf may /* XXX: COMP may now not resolve, because autoconf may
@ -262,9 +261,9 @@
* *
* PH - 20010311 * PH - 20010311
*/ */
#if !defined(COMP) && !defined(HAVE_GCC) # if !defined(COMP) && !defined(HAVE_GCC)
#error COMP definition did not resolve. Check "platform.h". # error COMP definition did not resolve. Check "platform.h".
#endif # endif
//============================================================================= //=============================================================================
// Platform Macros (a.k.a. "IS_" macros) // Platform Macros (a.k.a. "IS_" macros)
@ -293,89 +292,91 @@
// complier detection // complier detection
#define IS_KAI (COMP == COMP_KAI_GCC || COMP == COMP_KAI_SUNPRO || COMP == COMP_KAI_GLIBC || COMP == COMP_KAI_VISUALAGE || COMP == COMP_KAI_HPANSIC || COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA) # define IS_KAI \
#define IS_MSVC (COMP == COMP_MSVC) (COMP == COMP_KAI_GCC || COMP == COMP_KAI_SUNPRO || COMP == COMP_KAI_GLIBC || COMP == COMP_KAI_VISUALAGE || \
#define IS_SUNPRO (COMP == COMP_SUNPRO) COMP == COMP_KAI_HPANSIC || COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA)
# define IS_MSVC (COMP == COMP_MSVC)
# define IS_SUNPRO (COMP == COMP_SUNPRO)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Unicode // Unicode
#define SUPPORTS_UNICODE IS_WIN32 // The OS supports Unicode # define SUPPORTS_UNICODE IS_WIN32 // The OS supports Unicode
// KAI 3.4 uses a much improved stl // KAI 3.4 uses a much improved stl
#define IS_KAI_3_4 (IS_KAI && (COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA || COMP == COMP_KAI_GLIBC)) # define IS_KAI_3_4 (IS_KAI && (COMP == COMP_KAI_IRIX || COMP == COMP_KAI_OSF1ALPHA || COMP == COMP_KAI_GLIBC))
// Used in twlocale // Used in twlocale
#define USE_STD_CPP_LOCALE_WORKAROUND (IS_SUNPRO || (IS_KAI && !IS_KAI_3_4)) // TODO:BAM -- name this something more general. # define USE_STD_CPP_LOCALE_WORKAROUND \
#define USE_CLIB_LOCALE IS_KAI || HAVE_GCC (IS_SUNPRO || (IS_KAI && !IS_KAI_3_4)) // TODO:BAM -- name this something more general.
#define USES_CLIB_DATE_FUNCTION ( USE_CLIB_LOCALE || IS_SUNPRO || IS_MSVC ) // if we use clib, can't use C++ time_put, and SUNPRO and MSVC add characters # define USE_CLIB_LOCALE IS_KAI || HAVE_GCC
# define USES_CLIB_DATE_FUNCTION \
(USE_CLIB_LOCALE || IS_SUNPRO || \
IS_MSVC) // if we use clib, can't use C++ time_put, and SUNPRO and MSVC add characters
//#define USE_CLIB_LOCALE (IS_ALPHA || IS_IRIX || (IS_KAI && !IS_KAI_3_4)) //#define USE_CLIB_LOCALE (IS_ALPHA || IS_IRIX || (IS_KAI && !IS_KAI_3_4))
// Threading API // Threading API
// TODO:mdb -- this is not complete or rigorous on the unix side!!! // TODO:mdb -- this is not complete or rigorous on the unix side!!!
#define SUPPORTS_WIN32_THREADS IS_WIN32 # define SUPPORTS_WIN32_THREADS IS_WIN32
#define SUPPORTS_POSIX_THREADS (!SUPPORTS_WIN32_THREADS) # define SUPPORTS_POSIX_THREADS (!SUPPORTS_WIN32_THREADS)
// Miscellaneous // Miscellaneous
#define WCHAR_IS_16_BITS IS_WIN32 # define WCHAR_IS_16_BITS IS_WIN32
#define WCHAR_IS_32_BITS IS_UNIX # define WCHAR_IS_32_BITS IS_UNIX
#define WCHAR_REP_IS_UCS2 IS_WIN32 # define WCHAR_REP_IS_UCS2 IS_WIN32
// msystem+mpopen fail on Syllable, so use the libc equivalents until we figure out why. // msystem+mpopen fail on Syllable, so use the libc equivalents until we figure out why.
// TODO: Figure out why. // TODO: Figure out why.
#define USES_MPOPEN (IS_UNIX && !IS_SYLLABLE) # define USES_MPOPEN (IS_UNIX && !IS_SYLLABLE)
#define USES_MSYSTEM (IS_UNIX && !IS_SYLLABLE) # define USES_MSYSTEM (IS_UNIX && !IS_SYLLABLE)
#define SUPPORTS_WCHART IS_WIN32 // TODO: Remove after getting new ver of KAI # define SUPPORTS_WCHART IS_WIN32 // TODO: Remove after getting new ver of KAI
#define USES_GLIBC ((COMP == COMP_KAI_GLIBC) || HAVE_GCC) # define USES_GLIBC ((COMP == COMP_KAI_GLIBC) || HAVE_GCC)
#define SUPPORTS_MEMBER_TEMPLATES ( ! IS_SUNPRO ) # define SUPPORTS_MEMBER_TEMPLATES (!IS_SUNPRO)
#define SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST ( ! IS_SUNPRO ) # define SUPPORTS_EXPLICIT_TEMPLATE_FUNC_INST (!IS_SUNPRO)
#define SUPPORTS_POSIX_SIGNALS (!IS_DOS_DJGPP) # define SUPPORTS_POSIX_SIGNALS (!IS_DOS_DJGPP)
#define SUPPORTS_NETWORKING (!IS_SORTIX && !IS_DOS_DJGPP && !IS_REDOX) # define SUPPORTS_NETWORKING (!IS_SORTIX && !IS_DOS_DJGPP && !IS_REDOX)
#define SUPPORTS_SYSLOG (HAVE_SYSLOG_H && !IS_SKYOS && !IS_RISCOS) # define SUPPORTS_SYSLOG (HAVE_SYSLOG_H && !IS_SKYOS && !IS_RISCOS)
#define NEEDS_SWAB_IMPL (IS_CYGWIN || IS_SYLLABLE || IS_ANDROID || IS_SORTIX) # define NEEDS_SWAB_IMPL (IS_CYGWIN || IS_SYLLABLE || IS_ANDROID || IS_SORTIX)
#define USES_MBLEN (!IS_ANDROID && !IS_AROS) # define USES_MBLEN (!IS_ANDROID && !IS_AROS)
#define USES_DEVICE_PATH (IS_AROS || IS_DOS_DJGPP || IS_RISCOS || IS_REDOX) # define USES_DEVICE_PATH (IS_AROS || IS_DOS_DJGPP || IS_RISCOS || IS_REDOX)
#define ICONV_CONST_SOURCE (IS_MINIX) # define ICONV_CONST_SOURCE (IS_MINIX)
#define SUPPORTS_DIRECT_IO (IS_LINUX) # define SUPPORTS_DIRECT_IO (IS_LINUX)
// Linux is the only platform where direct i/o hashing has been tested & works properly so far. // Linux is the only platform where direct i/o hashing has been tested & works properly so far.
#define SUPPORTS_TERMIOS (!IS_RTEMS && !IS_REDOX) # define SUPPORTS_TERMIOS (!IS_RTEMS && !IS_REDOX)
// RTEMS errors are probably just a buildsys issue & this will change or go away. // RTEMS errors are probably just a buildsys issue & this will change or go away.
// Redox will probably implement this in the future. // Redox will probably implement this in the future.
#define CAN_UNLINK_WHILE_OPEN (!IS_AROS && !IS_RISCOS && !IS_REDOX && !IS_DOS_DJGPP) # define CAN_UNLINK_WHILE_OPEN (!IS_AROS && !IS_RISCOS && !IS_REDOX && !IS_DOS_DJGPP)
#define SUPPORTS_DOUBLE_SLASH_PATH (IS_CYGWIN) # define SUPPORTS_DOUBLE_SLASH_PATH (IS_CYGWIN)
// POSIX standard says paths beginning with 2 slashes are "implementation defined" // POSIX standard says paths beginning with 2 slashes are "implementation defined"
// (see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11 ) // (see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11 )
// The only platform OST works on (afaik) that actually defines a double-slash behavior is Cygwin // The only platform OST works on (afaik) that actually defines a double-slash behavior is Cygwin
// which uses this syntax for UNC paths. So we'll allow leading double slashes there, but // which uses this syntax for UNC paths. So we'll allow leading double slashes there, but
// continue removing them on all other platforms // continue removing them on all other platforms
#define USE_DEV_URANDOM (HAVE_DEV_URANDOM && ENABLE_DEV_URANDOM) # define USE_DEV_URANDOM (HAVE_DEV_URANDOM && ENABLE_DEV_URANDOM)
//============================================================================= //=============================================================================
// Miscellaneous // Miscellaneous
// //
// Put all items that are not an "IS_" macro here. // Put all items that are not an "IS_" macro here.
#if IS_BYTE_ALIGNED # if IS_BYTE_ALIGNED
#define BYTE_ALIGN 8 # define BYTE_ALIGN 8
#else # else
#error Unknown Byte alignment # error Unknown Byte alignment
#endif # endif
// A scalar that matches the sizeof a pointer // A scalar that matches the sizeof a pointer
typedef unsigned long ptr_size_type; // true for all of our current platforms typedef unsigned long ptr_size_type; // true for all of our current platforms
// TODO: I would like to use a XXXX_t like name // TODO: I would like to use a XXXX_t like name
// Check integer representation // Check integer representation
#if !(USES_2S_COMPLEMENT) # if !(USES_2S_COMPLEMENT)
#error "Tripwire will only work on a 2's complement CPU. Check \"platform.h\"." # error "Tripwire will only work on a 2's complement CPU. Check \"platform.h\"."
#endif # endif
#endif // __PLATFORM_H #endif // __PLATFORM_H

View File

@ -42,14 +42,14 @@
#include "errorutil.h" #include "errorutil.h"
#ifdef DEBUG #ifdef DEBUG
int cRefCountObj::objectCounter = 0; int cRefCountObj::objectCounter = 0;
int cRefCountObj::referenceCounter = 0; int cRefCountObj::referenceCounter = 0;
#include <typeinfo> #include <typeinfo>
// ok, this is getting serious! // ok, this is getting serious!
#include <set> #include <set>
typedef std::set<void*> RefSet; // collection of addresses of all reference counted objects typedef std::set<void*> RefSet; // collection of addresses of all reference counted objects
RefSet* gpRefCountObj_Objects = 0; RefSet* gpRefCountObj_Objects = 0;
// a way to see what hasn't been accounted for.... // a way to see what hasn't been accounted for....
struct cRefCountObj_Debug struct cRefCountObj_Debug
@ -57,10 +57,10 @@ struct cRefCountObj_Debug
~cRefCountObj_Debug() ~cRefCountObj_Debug()
{ {
RefSet::iterator i; RefSet::iterator i;
cDebug d("cRefCountObj_Debug"); cDebug d("cRefCountObj_Debug");
if(gpRefCountObj_Objects) if (gpRefCountObj_Objects)
{ {
for(i = gpRefCountObj_Objects->begin(); i != gpRefCountObj_Objects->end(); i++) for (i = gpRefCountObj_Objects->begin(); i != gpRefCountObj_Objects->end(); i++)
{ {
d.TraceNever("Refrence Counted Object %p still exists\n", *i); d.TraceNever("Refrence Counted Object %p still exists\n", *i);
} }
@ -74,7 +74,7 @@ cRefCountObj::cRefCountObj()
{ {
mRefCount = 1; mRefCount = 1;
//std::cout << "Allocated RefObj(" << std::hex << (int)this << ")\n"; //std::cout << "Allocated RefObj(" << std::hex << (int)this << ")\n";
#ifdef DEBUG #ifdef DEBUG
++objectCounter; ++objectCounter;
@ -83,7 +83,7 @@ cRefCountObj::cRefCountObj()
cDebug d("cRefCountObj::cRefCountObj"); cDebug d("cRefCountObj::cRefCountObj");
d.TraceNever("Object Created[%p] %s\n", this, typeid(*this).name()); d.TraceNever("Object Created[%p] %s\n", this, typeid(*this).name());
if(! gpRefCountObj_Objects) if (!gpRefCountObj_Objects)
gpRefCountObj_Objects = new RefSet; gpRefCountObj_Objects = new RefSet;
gpRefCountObj_Objects->insert(this); gpRefCountObj_Objects->insert(this);
#endif #endif
@ -93,22 +93,22 @@ cRefCountObj::~cRefCountObj()
{ {
ASSERT(mRefCount == 0); ASSERT(mRefCount == 0);
//std::cout << "Deleted RefObj(" << std::hex << (int)this << ")\n"; //std::cout << "Deleted RefObj(" << std::hex << (int)this << ")\n";
#ifdef DEBUG #ifdef DEBUG
--objectCounter; --objectCounter;
cDebug d("cRefCountObj::~cRefCountObj"); cDebug d("cRefCountObj::~cRefCountObj");
d.TraceNever("Object Destroyed[%p] %s Objects Left = %d\n", this, typeid(*this).name(), objectCounter); d.TraceNever("Object Destroyed[%p] %s Objects Left = %d\n", this, typeid(*this).name(), objectCounter);
if(objectCounter == 0) if (objectCounter == 0)
{ {
d.TraceDebug("****** All Reference Counted Objects Destroyed! ******\n") ; d.TraceDebug("****** All Reference Counted Objects Destroyed! ******\n");
} }
ASSERT(gpRefCountObj_Objects); ASSERT(gpRefCountObj_Objects);
RefSet::const_iterator i = gpRefCountObj_Objects->find(this); RefSet::const_iterator i = gpRefCountObj_Objects->find(this);
ASSERT(i != gpRefCountObj_Objects->end()); ASSERT(i != gpRefCountObj_Objects->end());
gpRefCountObj_Objects->erase(this); gpRefCountObj_Objects->erase(this);
if(gpRefCountObj_Objects->size() == 0) if (gpRefCountObj_Objects->size() == 0)
{ {
delete gpRefCountObj_Objects; delete gpRefCountObj_Objects;
gpRefCountObj_Objects = 0; gpRefCountObj_Objects = 0;
@ -128,9 +128,9 @@ void cRefCountObj::AddRef() const
++mRefCount; ++mRefCount;
#ifdef DEBUG #ifdef DEBUG
++referenceCounter; ++referenceCounter;
#endif #endif
} }
void cRefCountObj::Release() const void cRefCountObj::Release() const
@ -140,13 +140,12 @@ void cRefCountObj::Release() const
Delete(); Delete();
} }
#ifdef DEBUG #ifdef DEBUG
--referenceCounter; --referenceCounter;
#endif #endif
} }
void cRefCountObj::Delete() const void cRefCountObj::Delete() const
{ {
delete this; delete this;
} }

View File

@ -67,21 +67,25 @@ public:
virtual void AddRef() const; virtual void AddRef() const;
virtual void Release() const; virtual void Release() const;
int GetRefCount() const { return mRefCount; } int GetRefCount() const
// sometimes it is useful to know an object's refrence {
return mRefCount;
}
// sometimes it is useful to know an object's refrence
protected: protected:
virtual ~cRefCountObj(); virtual ~cRefCountObj();
virtual void Delete() const; virtual void Delete() const;
// override this if you don't want to be destroyed by "delete this"! // override this if you don't want to be destroyed by "delete this"!
private: private:
mutable int mRefCount; mutable int mRefCount;
#ifdef DEBUG #ifdef DEBUG
private: private:
static int objectCounter; static int objectCounter;
static int referenceCounter; static int referenceCounter;
friend void TestRefCountObj(); friend void TestRefCountObj();
public: public:
static bool AllRefCountObjDestoryed() static bool AllRefCountObjDestoryed()
{ {
@ -91,4 +95,3 @@ public:
}; };
#endif #endif

View File

@ -46,18 +46,17 @@
// Dependencies // Dependencies
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#include <map> // for: Resource Table Implementation #include <map> // for: Resource Table Implementation
#include "debug.h" // for: ASSERT and Trace #include "debug.h" // for: ASSERT and Trace
#include "error.h" // for: eInternal #include "error.h" // for: eInternal
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Classes Declared in this module // Classes Declared in this module
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template< class KEY, class RSC > class cResources_; template<class KEY, class RSC> class cResources_;
template< class KEY, class CHR > class cMessages_; template<class KEY, class CHR> class cMessages_;
//============================================================================= //=============================================================================
@ -75,61 +74,52 @@ template< class KEY, class CHR > class cMessages_;
// INVARIANTS: // INVARIANTS:
// //
// //
template< class KeyT, class RscT > template<class KeyT, class RscT> class cResources_
class cResources_
{ {
//--Type Definitions //--Type Definitions
private: private:
typedef std::map<KeyT, RscT> Table; // Storage Rep
typedef
std::map< KeyT, RscT > Table; // Storage Rep
public: public:
// Type definitions
// Type definitions typedef KeyT Key; // The resource id
typedef KeyT& KeyRef;
typedef const KeyT& ConstKeyRef;
typedef KeyT Key; // The resource id typedef RscT Value; // The managed resource
typedef KeyT& KeyRef; typedef Value& ValueRef;
typedef const KeyT& ConstKeyRef; typedef const Value& ConstValueRef;
typedef RscT Value; // The managed resource
typedef Value& ValueRef;
typedef const Value& ConstValueRef;
typedef typename Table::value_type Pair;
typedef typename Table::value_type Pair;
//--Interface. //--Interface.
public: public:
// Observers
// Observers ConstValueRef Get(ConstKeyRef) const;
ConstValueRef Get( ConstKeyRef ) const;
// Modifiers // Modifiers
void Put( const Pair*, const Pair* ); void Put(const Pair*, const Pair*);
void Put( ConstKeyRef, Value ); void Put(ConstKeyRef, Value);
//--Implementation. //--Implementation.
protected: protected:
static ConstValueRef DefaultValueRef(); // NOTE:
static ConstValueRef DefaultValueRef(); // NOTE: private:
Table m_table;
private:
Table m_table;
}; };
//============================================================================= //=============================================================================
// cMessages_<KEY,CHAR> -- Specialization of Resources_ for message strings // cMessages_<KEY,CHAR> -- Specialization of Resources_ for message strings
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -168,82 +158,70 @@ class cResources_
// must be a valid character type as defined by the STDCPP standard. // must be a valid character type as defined by the STDCPP standard.
// //
// //
template< class KeyT, class CharT > template<class KeyT, class CharT> class cMessages_ : public cResources_<KeyT, const CharT*>
class cMessages_ : public cResources_< KeyT, const CharT* >
{ {
//--Type definitions //--Type definitions
protected: protected:
typedef cResources_<KeyT, const CharT*> Resources;
typedef public:
cResources_<KeyT, const CharT* > typedef std::basic_string<CharT> String;
Resources; typedef const KeyT& ConstKeyRef;
public:
typedef std::basic_string<CharT> String;
typedef const KeyT& ConstKeyRef;
//--Interface. //--Interface.
public: public:
String Get(ConstKeyRef) const;
String Get ( ConstKeyRef ) const; std::string GetAnsi(ConstKeyRef) const;
std::string GetAnsi( ConstKeyRef ) const;
#if SUPPORTS_WCHART #if SUPPORTS_WCHART
std::wstring GetWide( ConstKeyRef ) const; std::wstring GetWide(ConstKeyRef) const;
#endif//SUPPORTS_WCHART #endif //SUPPORTS_WCHART
}; };
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// IMPLEMENTATION: cResources_<KEY_TYPE, RESOURCE_TYPE> // IMPLEMENTATION: cResources_<KEY_TYPE, RESOURCE_TYPE>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// NOTE: Macros to ease any changes in template arguments // NOTE: Macros to ease any changes in template arguments
#define Resource_Template template< class KeyT, class RscT > #define Resource_Template template<class KeyT, class RscT>
#define Resource_Class cResources_< KeyT, RscT > #define Resource_Class cResources_<KeyT, RscT>
Resource_Template Resource_Template void Resource_Class::Put(const Pair* beg, const Pair* end)
void Resource_Class::Put( const Pair* beg, const Pair* end )
{ {
for ( const Pair* at = beg; at != end; ++at ) for (const Pair* at = beg; at != end; ++at)
{ {
if ( !m_table.insert( *at ).second ) if (!m_table.insert(*at).second)
{ {
ASSERTMSG( 0, "Resource key already exists!" ); ASSERTMSG(0, "Resource key already exists!");
// throw eInternal( "Resource key already exists!" ); // throw eInternal( "Resource key already exists!" );
} }
} }
} }
// By value allows the user to Resource_table.Put( 6, "Literal" ); // By value allows the user to Resource_table.Put( 6, "Literal" );
Resource_Template Resource_Template inline void Resource_Class::Put(ConstKeyRef id, Value sResource)
inline
void Resource_Class::Put( ConstKeyRef id, Value sResource )
{ {
if ( m_table.insert( Pair( id, sResource ) ).second == false ) if (m_table.insert(Pair(id, sResource)).second == false)
{ {
ASSERTMSG( 0, "Resource key already exists!" ); ASSERTMSG(0, "Resource key already exists!");
// throw eInternal( "Resource key already exists!" ); // throw eInternal( "Resource key already exists!" );
} }
} }
Resource_Template Resource_Template typename Resource_Class::ConstValueRef Resource_Class::Get(ConstKeyRef id) const
typename Resource_Class::ConstValueRef
Resource_Class::Get( ConstKeyRef id ) const
{ {
typename Table::const_iterator at = m_table.find( id ); typename Table::const_iterator at = m_table.find(id);
if ( at == m_table.end() ) if (at == m_table.end())
{ {
#ifdef DEBUG #ifdef DEBUG
std::cerr << "*** Error Resource_Class::Get() [" __FILE__ ":" << __LINE__ << "]: Resource not found\n"; std::cerr << "*** Error Resource_Class::Get() [" __FILE__ ":" << __LINE__ << "]: Resource not found\n";
#endif #endif
return DefaultValueRef(); return DefaultValueRef();
} }
@ -253,18 +231,15 @@ Resource_Class::Get( ConstKeyRef id ) const
} }
} }
Resource_Template Resource_Template typename Resource_Class::ConstValueRef Resource_Class::DefaultValueRef()
typename Resource_Class::ConstValueRef
Resource_Class::DefaultValueRef()
{ {
static Value _default; static Value _default;
return _default; return _default;
} }
#undef Resource_Template //template< class KeyT, class RscT > #undef Resource_Template //template< class KeyT, class RscT >
#undef Resource_Class //Resources_<KeyT,RscT> #undef Resource_Class //Resources_<KeyT,RscT>
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -273,20 +248,14 @@ Resource_Class::DefaultValueRef()
// NOTE: Macros to ease any changes in template arguments // NOTE: Macros to ease any changes in template arguments
#define Message_Template template< class KeyT, class CharT > #define Message_Template template<class KeyT, class CharT>
#define Message_Class cMessages_< KeyT, CharT > #define Message_Class cMessages_<KeyT, CharT>
Message_Template Message_Template inline typename Message_Class::String Message_Class::Get(ConstKeyRef id) const
inline
typename Message_Class::String
Message_Class::Get( ConstKeyRef id ) const
{ {
typename Message_Class::Value msg = Resources::Get( id ); typename Message_Class::Value msg = Resources::Get(id);
return return (msg == this->DefaultValueRef()) ? String() : String(msg);
( msg == this->DefaultValueRef() )
? String()
: String( msg );
} }
@ -294,86 +263,69 @@ Message_Class::Get( ConstKeyRef id ) const
namespace tss namespace tss
{ {
namespace rsc namespace rsc
{ {
/* WARNING:RAD -- Cannot use StringUtil or CodeConvert since /* WARNING:RAD -- Cannot use StringUtil or CodeConvert since
these use ErrorMessages and String Resources! */ these use ErrorMessages and String Resources! */
inline inline void ToNTMBS(std::string& nbs, const std::string& src)
void
ToNTMBS( std::string& nbs, const std::string& src )
{
nbs.assign( src );
}
#if SUPPORTS_WCHART
inline
void
ToNTMBS( std::string& nbs, const std::wstring& wcs )
{
nbs.resize( MB_CUR_MAX * wcs.size() );
size_t nWrote =
::wcstombs(
const_cast< char * >( nbs.c_str() ),
wcs.c_str(), nbs.size() + 1 );
if ( nWrote == (size_t)-1 )
{
ASSERTMSG( false, "Conversion error in cMessages_!" );
// throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) );
}
nbs.resize( nWrote );
}
inline
void
ToNTWCS( std::wstring& dst, const std::wstring& src )
{
dst.assign( src );
}
inline
void
ToNTWCS( std::wstring& wcs, const std::string& nbs )
{
wcs.resize( nbs.size() );
size_t nWrote =
::mbstowcs(
const_cast< wchar_t * >( wcs.c_str() ),
nbs.c_str(), wcs.size() + 1 );
if ( nWrote == (size_t)-1 )
{
ASSERTMSG( false, "Conversion error in cMessages_!" );
// throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) );
}
wcs.resize( nWrote );
}
#endif//SUPPORTS_WCHART
}//rsc::
}//tss::
Message_Template
inline
std::string
Message_Class::GetAnsi( ConstKeyRef id ) const
{ {
typename Message_Class::Value msg = Resources::Get( id ); nbs.assign(src);
}
if ( msg == this->DefaultValueRef() ) #if SUPPORTS_WCHART
inline void ToNTMBS(std::string& nbs, const std::wstring& wcs)
{
nbs.resize(MB_CUR_MAX * wcs.size());
size_t nWrote = ::wcstombs(const_cast<char*>(nbs.c_str()), wcs.c_str(), nbs.size() + 1);
if (nWrote == (size_t)-1)
{
ASSERTMSG(false, "Conversion error in cMessages_!");
// throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) );
}
nbs.resize(nWrote);
}
inline void ToNTWCS(std::wstring& dst, const std::wstring& src)
{
dst.assign(src);
}
inline void ToNTWCS(std::wstring& wcs, const std::string& nbs)
{
wcs.resize(nbs.size());
size_t nWrote = ::mbstowcs(const_cast<wchar_t*>(wcs.c_str()), nbs.c_str(), wcs.size() + 1);
if (nWrote == (size_t)-1)
{
ASSERTMSG(false, "Conversion error in cMessages_!");
// throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) );
}
wcs.resize(nWrote);
}
#endif //SUPPORTS_WCHART
} // namespace rsc
} // namespace tss
Message_Template inline std::string Message_Class::GetAnsi(ConstKeyRef id) const
{
typename Message_Class::Value msg = Resources::Get(id);
if (msg == this->DefaultValueRef())
{ {
return std::string(); return std::string();
} }
else else
{ {
std::string nbs; std::string nbs;
tss::rsc::ToNTMBS( nbs, String( msg ) ); tss::rsc::ToNTMBS(nbs, String(msg));
return nbs; return nbs;
} }
} }
@ -381,33 +333,29 @@ Message_Class::GetAnsi( ConstKeyRef id ) const
#if SUPPORTS_WCHART #if SUPPORTS_WCHART
Message_Template Message_Template inline std::wstring Message_Class::GetWide(ConstKeyRef id) const
inline
std::wstring
Message_Class::GetWide( ConstKeyRef id ) const
{ {
Value msg = Resources::Get( id ); Value msg = Resources::Get(id);
if ( msg == DefaultValueRef() ) if (msg == DefaultValueRef())
{ {
return std::string(); return std::string();
} }
else else
{ {
std::wstring wcs; std::wstring wcs;
tss::rsc::ToNTWCS( wcs, String( msg ) ); tss::rsc::ToNTWCS(wcs, String(msg));
return wcs; return wcs;
} }
} }
#endif//SUPPORTS_WCHART #endif //SUPPORTS_WCHART
#undef Message_Template #undef Message_Template
#undef Message_Class #undef Message_Class
#endif//__RESOURCES_H #endif //__RESOURCES_H
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -426,118 +374,100 @@ Message_Class::GetWide( ConstKeyRef id ) const
// for SUNPro enums are ints, not const ints // for SUNPro enums are ints, not const ints
#if IS_SUNPRO #if IS_SUNPRO
#define ENUM_TYPE int # define ENUM_TYPE int
#else #else
#define ENUM_TYPE const int # define ENUM_TYPE const int
#endif #endif
template<> template<> class cMessages_<ENUM_TYPE, char> : public cResources_<ENUM_TYPE, const char*>
class cMessages_<ENUM_TYPE, char> :
public cResources_< ENUM_TYPE, const char* >
{ {
protected: protected:
typedef cResources_<ENUM_TYPE, const char*> Resources;
typedef public:
cResources_< ENUM_TYPE, const char* > typedef std::string String;
Resources; typedef int ConstKeyRef; // Better than <const int&>
public:
typedef std::string String;
typedef int ConstKeyRef; // Better than <const int&>
String Get( ConstKeyRef id ) const String Get(ConstKeyRef id) const
{ {
Value msg = Resources::Get( id ); Value msg = Resources::Get(id);
return ( msg != DefaultValueRef() ) return (msg != DefaultValueRef()) ? String(msg) : String();
? String( msg ) }
: String();
}
String GetAnsi( ConstKeyRef id ) const String GetAnsi(ConstKeyRef id) const
{ {
return Get( id ); return Get(id);
} }
#if SUPPORTS_WCHART #if SUPPORTS_WCHART
std::wstring GetWide( ConstKeyRef id ) const std::wstring GetWide(ConstKeyRef id) const
{
Value msg = Resources::Get(id);
if (msg == DefaultValueRef())
{ {
Value msg = Resources::Get( id ); return std::wstring();
if ( msg == DefaultValueRef() )
{
return std::wstring();
}
else
{
String::size_type
N = String::traits_type::length( msg );
std::wstring dst( N, 0x00 );
std::ctype< wchar_t >().widen( msg, msg + N, dst.begin() );
return dst;
}
} }
#endif//SUPPORTS_WCHART else
{
String::size_type N = String::traits_type::length(msg);
std::wstring dst(N, 0x00);
std::ctype<wchar_t>().widen(msg, msg + N, dst.begin());
return dst;
}
}
#endif //SUPPORTS_WCHART
}; };
#if SUPPORTS_WCHART #if SUPPORTS_WCHART
template<> template<> class cMessages_<const int, wchar_t> : public cResources_<const int, const wchar_t*>
class cMessages_<const int, wchar_t> :
public cResources_< const int, const wchar_t* >
{ {
protected: protected:
typedef cResources_<const int, const wchar_t*> Resources;
typedef public:
cResources_<const int, const wchar_t* > typedef std::wstring String;
Resources; typedef int ConstKeyRef; // Better than <const int&>
public:
typedef std::wstring String;
typedef int ConstKeyRef; // Better than <const int&>
String Get( ConstKeyRef id ) const String Get(ConstKeyRef id) const
{
Value msg = Resources::Get(id);
if (msg != DefaultValueRef())
return String(msg);
else
return String();
}
std::string GetAnsi(ConstKeyRef id) const
{
Value msg = Resources::Get(id);
if (msg == DefaultValueRef())
{ {
Value msg = Resources::Get( id ); return std::string();
if( msg != DefaultValueRef() )
return String( msg );
else
return String();
} }
else
std::string GetAnsi( ConstKeyRef id ) const
{ {
Value msg = Resources::Get( id ); String::size_type N = String::traits_type::length(msg);
if ( msg == DefaultValueRef() ) std::string dst(N, 0x00);
{ std::ctype<CharT>().narrow(msg, msg + N, '?', dst.begin());
return std::string();
}
else
{
String::size_type
N = String::traits_type::length( msg );
std::string dst( N, 0x00 ); return dst;
std::ctype<CharT>().narrow( msg, msg + N, '?', dst.begin() );
return dst;
}
} }
}
String GetWide( ConstKeyRef id ) const String GetWide(ConstKeyRef id) const
{ {
return Get( id ); return Get(id);
} }
}; };
#endif//SUPPORTS_WCHART # endif //SUPPORTS_WCHART
#endif//RAD_OLDCODE
#endif //RAD_OLDCODE

View File

@ -36,8 +36,13 @@
#include "serializable.h" #include "serializable.h"
#if IS_SUNPRO #if IS_SUNPRO
iTypedSerializable::~iTypedSerializable() {} iTypedSerializable::~iTypedSerializable()
iSerializable::~iSerializable() {} {
iTyped::~iTyped() {} }
iSerializable::~iSerializable()
{
}
iTyped::~iTyped()
{
}
#endif #endif

View File

@ -78,48 +78,60 @@ class iSerializer;
class iSerializable class iSerializable
{ {
public: public:
virtual void Read (iSerializer* pSerializer, int32 version = 0) = 0; // throw (eSerializer, eArchive) virtual void Read(iSerializer* pSerializer, int32 version = 0) = 0; // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const = 0; // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const = 0; // throw (eSerializer, eArchive)
// objects implement these methods to read and write themselves to a serializer. // objects implement these methods to read and write themselves to a serializer.
virtual ~iSerializable() {} virtual ~iSerializable()
{
}
}; };
class iTypedSerializable : public iTyped, public iSerializable class iTypedSerializable : public iTyped, public iSerializable
{ {
public: public:
typedef iTypedSerializable* (*CreateFunc)(); typedef iTypedSerializable* (*CreateFunc)();
// Pointer to a function that creates an empty version of each typed serializable object // Pointer to a function that creates an empty version of each typed serializable object
virtual int32 Version() const = 0; virtual int32 Version() const = 0;
// Return the current version of that this serializable object writes. // Return the current version of that this serializable object writes.
// As a convention version number should be (major_version << 16) | minor_version. // As a convention version number should be (major_version << 16) | minor_version.
static int32 MkVersion(int16 major, int16 minor) { return (int32)(((uint32)major << 16) | (uint32)minor); } static int32 MkVersion(int16 major, int16 minor)
static int16 MajorVersion(int32 version) { return (int16)((uint32)version >> 16); } {
static int16 MinorVersion(int32 version) { return (int16)version; } return (int32)(((uint32)major << 16) | (uint32)minor);
}
static int16 MajorVersion(int32 version)
{
return (int16)((uint32)version >> 16);
}
static int16 MinorVersion(int32 version)
{
return (int16)version;
}
virtual ~iTypedSerializable() {} virtual ~iTypedSerializable()
{
}
}; };
////////////////////////////// //////////////////////////////
// convenience macros // convenience macros
#define DECLARE_TYPEDSERIALIZABLE() \ # define DECLARE_TYPEDSERIALIZABLE() \
DECLARE_TYPED() \ DECLARE_TYPED() \
public: \ public: \
static iTypedSerializable* Create(); \ static iTypedSerializable* Create(); \
virtual int32 Version() const; virtual int32 Version() const;
#define IMPLEMENT_TYPEDSERIALIZABLE(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \ # define IMPLEMENT_TYPEDSERIALIZABLE(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \
IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \ IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \
iTypedSerializable* CLASS::Create() \ iTypedSerializable* CLASS::Create() \
{ \ { \
return new CLASS; \ return new CLASS; \
} \ } \
int32 CLASS::Version() const \ int32 CLASS::Version() const \
{ \ { \
return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \ return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \
} }
#endif // __SERIALIZABLE_H #endif // __SERIALIZABLE_H

View File

@ -47,38 +47,38 @@
{ {
TSTRING ret; TSTRING ret;
if( !eSerializer::mDataSource.empty() ) if (!eSerializer::mDataSource.empty())
{ {
ret = mMsg; ret = mMsg;
switch( eSerializer::mSourceType ) switch (eSerializer::mSourceType)
{ {
case TY_UNDEFINED: case TY_UNDEFINED:
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
case TY_FILE: case TY_FILE:
ret.append( _T("\nFile: ") ); ret.append(_T("\nFile: "));
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
case TY_TEMPFILE: case TY_TEMPFILE:
ret.append( _T("\nTemporary File: ") ); ret.append(_T("\nTemporary File: "));
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
case TY_MEMORY: case TY_MEMORY:
ret.append( _T("\nMemory Block: ") ); //uhhh...?? ret.append(_T("\nMemory Block: ")); //uhhh...??
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
case TY_PIPE: case TY_PIPE:
ret.append( _T("\nNamed Pipe: ")); ret.append(_T("\nNamed Pipe: "));
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
case TY_SOCKET: case TY_SOCKET:
ret.append( _T("\nNetwork Socket: ")); ret.append(_T("\nNetwork Socket: "));
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
default: default:
ret.append( _T("\n")); ret.append(_T("\n"));
ret.append( mDataSource ); ret.append(mDataSource);
break; break;
} }
} }

View File

@ -46,52 +46,51 @@ class iSerializable;
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
// Serializer Base Exception // Serializer Base Exception
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
TSS_BEGIN_EXCEPTION_NO_CTOR( eSerializer, eError ) TSS_BEGIN_EXCEPTION_NO_CTOR(eSerializer, eError)
// TODO: What else to add to this enumeration? Locked File? Temp file? // TODO: What else to add to this enumeration? Locked File? Temp file?
enum DataSourceType { enum DataSourceType
TY_UNDEFINED = 0, {
TY_FILE, TY_UNDEFINED = 0,
TY_TEMPFILE, TY_FILE,
TY_MEMORY, TY_TEMPFILE,
TY_PIPE, TY_MEMORY,
TY_SOCKET TY_PIPE,
}; TY_SOCKET
};
eSerializer( const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED ) eSerializer(const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED)
: eError( msg ), : eError(msg), mDataSource(dataSource), mSourceType(paramType)
mDataSource( dataSource ), {
mSourceType( paramType ) }
{}
virtual TSTRING GetMsg() const; virtual TSTRING GetMsg() const;
private: private:
TSTRING mDataSource; TSTRING mDataSource;
// TSTRING indentifier of the datasource associated with a particular error // TSTRING indentifier of the datasource associated with a particular error
// (if one exists) EX: a filename. // (if one exists) EX: a filename.
DataSourceType mSourceType; DataSourceType mSourceType;
TSS_END_EXCEPTION(); TSS_END_EXCEPTION();
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
// Helper Macro For Serializer Exceptions // Helper Macro For Serializer Exceptions
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
#define TSS_SERIALIZER_EXCEPTION( except ) \ #define TSS_SERIALIZER_EXCEPTION(except) \
TSS_BEGIN_EXCEPTION_NO_CTOR( except, eSerializer ) \ TSS_BEGIN_EXCEPTION_NO_CTOR(except, eSerializer) \
except( const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED ) \ except(const TSTRING& msg, const TSTRING& dataSource = _T(""), DataSourceType paramType = TY_UNDEFINED) \
: eSerializer( msg, dataSource, paramType ) \ : eSerializer(msg, dataSource, paramType){}; \
{}; \
TSS_END_EXCEPTION() TSS_END_EXCEPTION()
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
// Specific Exceptions // Specific Exceptions
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
TSS_SERIALIZER_EXCEPTION( eSerializerUnknownType ); TSS_SERIALIZER_EXCEPTION(eSerializerUnknownType);
TSS_SERIALIZER_EXCEPTION( eSerializerInputStreamFmt); TSS_SERIALIZER_EXCEPTION(eSerializerInputStreamFmt);
TSS_SERIALIZER_EXCEPTION( eSerializerOutputStreamFmt ); TSS_SERIALIZER_EXCEPTION(eSerializerOutputStreamFmt);
TSS_SERIALIZER_EXCEPTION( eSerializerInputStremTypeArray ); TSS_SERIALIZER_EXCEPTION(eSerializerInputStremTypeArray);
TSS_SERIALIZER_EXCEPTION( eSerializerArchive ); // not used TSS_SERIALIZER_EXCEPTION(eSerializerArchive); // not used
TSS_SERIALIZER_EXCEPTION( eSerializerVersionMismatch ); TSS_SERIALIZER_EXCEPTION(eSerializerVersionMismatch);
TSS_SERIALIZER_EXCEPTION( eSerializerEncryption ); TSS_SERIALIZER_EXCEPTION(eSerializerEncryption);
/* /*
E_UNKNOWN_TYPE = 700, E_UNKNOWN_TYPE = 700,
@ -107,59 +106,62 @@ class iSerializer
{ {
public: public:
// Initializing and closing the archive // Initializing and closing the archive
virtual void Init() = 0; // throw eSerializer virtual void Init() = 0; // throw eSerializer
// initializes the serializer; must be called before any reading or writing is done // initializes the serializer; must be called before any reading or writing is done
virtual void Finit() = 0; virtual void Finit() = 0;
// called after a session of serialization is done; called implicitely by the destructor // called after a session of serialization is done; called implicitely by the destructor
// if not called explicitely before destruction // if not called explicitely before destruction
//Reading and writing objects Init() should have already been called or all these will fail. //Reading and writing objects Init() should have already been called or all these will fail.
virtual void WriteObjectDynCreate(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) virtual void WriteObjectDynCreate(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive)
// writes an object such that it can be dynamically created when read back in with // writes an object such that it can be dynamically created when read back in with
// ReadObject. // ReadObject.
virtual iTypedSerializable* ReadObjectDynCreate() = 0; // throw (eSerializer, eArchive); virtual iTypedSerializable* ReadObjectDynCreate() = 0; // throw (eSerializer, eArchive);
// reads an object from the archive, returning a pointer to it. The caller is responsible for // reads an object from the archive, returning a pointer to it. The caller is responsible for
// deleteing or Release()ing it when done. // deleteing or Release()ing it when done.
virtual void WriteObject(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) virtual void WriteObject(const iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive)
// writes an object to the archive that will not be dynamically created // writes an object to the archive that will not be dynamically created
virtual void ReadObject(iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive) virtual void ReadObject(iTypedSerializable* pObj) = 0; // throw (eSerializer, eArchive)
// reads an object that was written with WriteObject() // reads an object that was written with WriteObject()
// writing interface // writing interface
// all of these can throw eArchive // all of these can throw eArchive
virtual void ReadInt16(int16& ret) = 0; virtual void ReadInt16(int16& ret) = 0;
virtual void ReadInt32(int32& ret) = 0; virtual void ReadInt32(int32& ret) = 0;
virtual void ReadInt64(int64& ret) = 0; virtual void ReadInt64(int64& ret) = 0;
virtual void ReadString(TSTRING& ret) = 0; virtual void ReadString(TSTRING& ret) = 0;
virtual int ReadBlob(void* pBlob, int count) = 0; virtual int ReadBlob(void* pBlob, int count) = 0;
virtual void WriteInt16(int16 i) = 0; virtual void WriteInt16(int16 i) = 0;
virtual void WriteInt32(int32 i) = 0; virtual void WriteInt32(int32 i) = 0;
virtual void WriteInt64(int64 i) = 0; virtual void WriteInt64(int64 i) = 0;
virtual void WriteString(const TSTRING& s) = 0; virtual void WriteString(const TSTRING& s) = 0;
virtual void WriteBlob(const void* pBlob, int count) = 0; virtual void WriteBlob(const void* pBlob, int count) = 0;
virtual TSTRING GetFileName() const { return _T(""); } virtual TSTRING GetFileName() const
// derived classes can implement this to return the file name associated with the serializer. {
// it is only used in error reporting. return _T("");
}
// derived classes can implement this to return the file name associated with the serializer.
// it is only used in error reporting.
// the error enumeration: 700-799 // the error enumeration: 700-799
enum ErrorNum enum ErrorNum
{ {
E_UNKNOWN_TYPE = 700, E_UNKNOWN_TYPE = 700,
E_INPUT_STREAM_FORMAT = 701, E_INPUT_STREAM_FORMAT = 701,
E_INPUT_STR_TYPEARRAY = 702, // bad index in to type array E_INPUT_STR_TYPEARRAY = 702, // bad index in to type array
E_ARCHIVE = 703, E_ARCHIVE = 703,
E_VERSION_MISMATCH = 704, E_VERSION_MISMATCH = 704,
E_ENCRYPTION_ERROR = 705, E_ENCRYPTION_ERROR = 705,
E_OUTPUT_STREAM_FORMAT = 706, E_OUTPUT_STREAM_FORMAT = 706,
E_NUMITEMS E_NUMITEMS
}; };
virtual ~iSerializer() {} virtual ~iSerializer()
{
}
}; };
#endif #endif

View File

@ -34,17 +34,17 @@
#include "serializerimpl.h" #include "serializerimpl.h"
#include "debug.h" #include "debug.h"
#include "archive.h" #include "archive.h"
#include "ntmbs.h" // for: eCharacterEncoding #include "ntmbs.h" // for: eCharacterEncoding
#include "crc32.h" #include "crc32.h"
// static members // static members
cSerializerImpl::SerMap cSerializerImpl::mSerCreateMap ; cSerializerImpl::SerMap cSerializerImpl::mSerCreateMap;
cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap ; cSerializerImpl::SerRefCountMap cSerializerImpl::mSerRefCountCreateMap;
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// util_GetCrc -- calculates the crc for the narrow version of the type's AsString() // util_GetCrc -- calculates the crc for the narrow version of the type's AsString()
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
static uint32 util_GetCRC( const cType& type ) static uint32 util_GetCRC(const cType& type)
{ {
// //
// convert this to narrow... // convert this to narrow...
@ -59,19 +59,19 @@ static uint32 util_GetCRC( const cType& type )
// We only need to count the characters // We only need to count the characters
// RAD: Yeesh! This is already done for us in cType::mString!!! // RAD: Yeesh! This is already done for us in cType::mString!!!
const uint8* pszType = (const uint8*)( type.AsString() ); const uint8* pszType = (const uint8*)(type.AsString());
int nBytes = ::strlen( (const char*)pszType ); int nBytes = ::strlen((const char*)pszType);
ASSERT( sizeof(uint8) == sizeof(byte) ); ASSERT(sizeof(uint8) == sizeof(byte));
ASSERT( pszType && *pszType ); ASSERT(pszType && *pszType);
// //
// calculate the crc... // calculate the crc...
// //
CRC_INFO crc; CRC_INFO crc;
crcInit( crc ); crcInit(crc);
crcUpdate( crc, pszType, nBytes ); crcUpdate(crc, pszType, nBytes);
crcFinit( crc ); crcFinit(crc);
return crc.crc; return crc.crc;
} }
@ -79,11 +79,8 @@ static uint32 util_GetCRC( const cType& type )
//############################################################################# //#############################################################################
// class cSerializerImpl // class cSerializerImpl
//############################################################################# //#############################################################################
cSerializerImpl::cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName) : cSerializerImpl::cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName)
mpArchive(&archive), : mpArchive(&archive), mMode(action), mbInit(false), mFileName(fileName)
mMode(action),
mbInit(false),
mFileName( fileName )
{ {
} }
@ -107,13 +104,13 @@ bool cSerializerImpl::IsWriting() const
void cSerializerImpl::RegisterSerializable(const cType& type, iTypedSerializable::CreateFunc pFunc) void cSerializerImpl::RegisterSerializable(const cType& type, iTypedSerializable::CreateFunc pFunc)
{ {
uint32 crc = util_GetCRC( type ); uint32 crc = util_GetCRC(type);
if( cSerializerImpl::mSerCreateMap.find( crc ) != cSerializerImpl::mSerCreateMap.end() ) if (cSerializerImpl::mSerCreateMap.find(crc) != cSerializerImpl::mSerCreateMap.end())
{ {
// duplicate entry! // duplicate entry!
// //
ASSERT( false ); ASSERT(false);
TOSTRINGSTREAM str; TOSTRINGSTREAM str;
str << _T("Duplicate entry in type table: ") << type.AsString() << std::endl; str << _T("Duplicate entry in type table: ") << type.AsString() << std::endl;
throw eInternal(str.str()); throw eInternal(str.str());
@ -123,13 +120,13 @@ void cSerializerImpl::RegisterSerializable(const cType& type, iTypedSerializable
void cSerializerImpl::RegisterSerializableRefCt(const cType& type, iSerRefCountObj::CreateFunc pFunc) void cSerializerImpl::RegisterSerializableRefCt(const cType& type, iSerRefCountObj::CreateFunc pFunc)
{ {
uint32 crc = util_GetCRC( type ); uint32 crc = util_GetCRC(type);
if( cSerializerImpl::mSerRefCountCreateMap.find( crc ) != cSerializerImpl::mSerRefCountCreateMap.end() ) if (cSerializerImpl::mSerRefCountCreateMap.find(crc) != cSerializerImpl::mSerRefCountCreateMap.end())
{ {
// duplicate entry! // duplicate entry!
// //
ASSERT( false ); ASSERT(false);
TOSTRINGSTREAM str; TOSTRINGSTREAM str;
str << _T("Duplicate entry in type table: ") << type.AsString() << std::ends; str << _T("Duplicate entry in type table: ") << type.AsString() << std::ends;
throw eInternal(str.str()); throw eInternal(str.str());
@ -184,23 +181,23 @@ void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj)
// get the ident for this class type // get the ident for this class type
// //
uint32 crc = util_GetCRC( pObj->GetType() ); uint32 crc = util_GetCRC(pObj->GetType());
// //
// make sure this type is registered, and figure out if it is refrence counted // make sure this type is registered, and figure out if it is refrence counted
// //
SerRefCountMap::iterator i = mSerRefCountCreateMap.find( crc ); SerRefCountMap::iterator i = mSerRefCountCreateMap.find(crc);
bool bRefCount = true; bool bRefCount = true;
if( i == mSerRefCountCreateMap.end() ) if (i == mSerRefCountCreateMap.end())
{ {
// //
// maybe it is not refrence counted... // maybe it is not refrence counted...
// //
SerMap::iterator si = mSerCreateMap.find( crc ); SerMap::iterator si = mSerCreateMap.find(crc);
if( si == mSerCreateMap.end() ) if (si == mSerCreateMap.end())
{ {
d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString()); d.TraceError("Attempt to serialize unregistered type : %s\n", pObj->GetType().AsString());
ThrowAndAssert(eSerializerUnknownType( pObj->GetType().AsString(), mFileName, eSerializer::TY_FILE )); ThrowAndAssert(eSerializerUnknownType(pObj->GetType().AsString(), mFileName, eSerializer::TY_FILE));
} }
bRefCount = false; bRefCount = false;
} }
@ -210,11 +207,11 @@ void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj)
// write a placeholder for the size; we will come back and fill in the right value later... // write a placeholder for the size; we will come back and fill in the right value later...
mpArchive->WriteInt32(0xffffffff); mpArchive->WriteInt32(0xffffffff);
if(bRefCount) if (bRefCount)
{ {
// see if the object has already been serialized... // see if the object has already been serialized...
int idx; int idx;
if((idx = mRefCtObjTbl.Lookup(static_cast<const iSerRefCountObj*>(pObj))) == 0) if ((idx = mRefCtObjTbl.Lookup(static_cast<const iSerRefCountObj*>(pObj))) == 0)
{ {
// it is not in the table yet; add it and serialize the object // it is not in the table yet; add it and serialize the object
idx = mRefCtObjTbl.Add(static_cast<const iSerRefCountObj*>(pObj)); idx = mRefCtObjTbl.Add(static_cast<const iSerRefCountObj*>(pObj));
@ -235,7 +232,6 @@ void cSerializerImpl::WriteObjectDynCreate(const iTypedSerializable* pObj)
mpArchive->WriteInt32(0); mpArchive->WriteInt32(0);
// ... then write the object. // ... then write the object.
pObj->Write(this); pObj->Write(this);
} }
} }
@ -247,7 +243,7 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
cDebug d("cSerializerImpl::ReadObjectDynCreate"); cDebug d("cSerializerImpl::ReadObjectDynCreate");
//d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos()); //d.TraceDetail("Entering... archive offset = %d\n", mpArchive->CurrentPos());
int32 size, objIdx; int32 size, objIdx;
uint32 crc; uint32 crc;
// first, get the type... // first, get the type...
mpArchive->ReadInt32(reinterpret_cast<int32&>(crc)); mpArchive->ReadInt32(reinterpret_cast<int32&>(crc));
@ -263,21 +259,21 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
//int64 sizePos = mpArchive->CurrentPos(); //int64 sizePos = mpArchive->CurrentPos();
mpArchive->ReadInt32(objIdx); mpArchive->ReadInt32(objIdx);
if(objIdx == 0) if (objIdx == 0)
{ {
// the object is not reference counted; create and read in the object // the object is not reference counted; create and read in the object
// first, we need to create the object. // first, we need to create the object.
SerMap::iterator si; SerMap::iterator si;
si = mSerCreateMap.find(crc); si = mSerCreateMap.find(crc);
if(si == mSerCreateMap.end()) if (si == mSerCreateMap.end())
{ {
// unable to find the creation function... // unable to find the creation function...
d.TraceError("Unable to find creation function for non-ref counted object %d\n", crc); d.TraceError("Unable to find creation function for non-ref counted object %d\n", crc);
TOSTRINGSTREAM str; TOSTRINGSTREAM str;
#ifdef DEBUG #ifdef DEBUG
// Let's only report the actual crc in debug mode // Let's only report the actual crc in debug mode
str << (int32)crc << std::ends; str << (int32)crc << std::ends;
#endif #endif
ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE)); ThrowAndAssert(eSerializerUnknownType(str.str(), mFileName, eSerializer::TY_FILE));
} }
iTypedSerializable* pObj = ((*si).second)(); iTypedSerializable* pObj = ((*si).second)();
@ -294,12 +290,12 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
// refrence counted... // refrence counted...
iSerRefCountObj* pObj; iSerRefCountObj* pObj;
pObj = mRefCtObjTbl.Lookup(objIdx); pObj = mRefCtObjTbl.Lookup(objIdx);
if(pObj == NULL) if (pObj == NULL)
{ {
// not in table yet...first find the creation function // not in table yet...first find the creation function
SerRefCountMap::iterator rci; SerRefCountMap::iterator rci;
rci = mSerRefCountCreateMap.find(crc); rci = mSerRefCountCreateMap.find(crc);
if(rci == mSerRefCountCreateMap.end()) if (rci == mSerRefCountCreateMap.end())
{ {
// unable to find the creation function... // unable to find the creation function...
d.TraceError("Unable to find creation function for ref counted object %d\n", crc); d.TraceError("Unable to find creation function for ref counted object %d\n", crc);
@ -320,7 +316,10 @@ iTypedSerializable* cSerializerImpl::ReadObjectDynCreate()
else else
{ {
// already serialized; just return this object. // already serialized; just return this object.
d.TraceDetail("Adding refrence to previously serialized object [%d] %s(%p)\n", objIdx, pObj->GetType().AsString(), pObj); d.TraceDetail("Adding refrence to previously serialized object [%d] %s(%p)\n",
objIdx,
pObj->GetType().AsString(),
pObj);
pObj->AddRef(); pObj->AddRef();
} }
@ -354,7 +353,7 @@ void cSerializerImpl::WriteObject(const iTypedSerializable* pObj)
// the object is already created when ReadObject() happens. The only good it might serve is in asserting that // the object is already created when ReadObject() happens. The only good it might serve is in asserting that
// the input stream is valid, but I can do that with the 0xffffffff size below (asserting that it is the same // the input stream is valid, but I can do that with the 0xffffffff size below (asserting that it is the same
// when it is read back in) // when it is read back in)
/* int i = 0; /* int i = 0;
for(; i < mTypeArray.size(); i++) for(; i < mTypeArray.size(); i++)
{ {
if(pObj->GetType() == *mTypeArray[i]) if(pObj->GetType() == *mTypeArray[i])
@ -373,7 +372,7 @@ void cSerializerImpl::WriteObject(const iTypedSerializable* pObj)
mpArchive->WriteInt32(i); mpArchive->WriteInt32(i);
*/ */
mpArchive->WriteInt32(0); // place holder for type array index mpArchive->WriteInt32(0); // place holder for type array index
mpArchive->WriteInt32(pObj->Version()); mpArchive->WriteInt32(pObj->Version());
// write a placeholder for the size; we will come back and fill in the right value later... // write a placeholder for the size; we will come back and fill in the right value later...
//int64 sizePos = mpArchive->CurrentPos(); //int64 sizePos = mpArchive->CurrentPos();
@ -410,14 +409,14 @@ void cSerializerImpl::ReadObject(iTypedSerializable* pObj)
// read in the version // read in the version
int32 dummy, version; int32 dummy, version;
mpArchive->ReadInt32(dummy); // old type array index mpArchive->ReadInt32(dummy); // old type array index
mpArchive->ReadInt32(version); mpArchive->ReadInt32(version);
// read in the size and the index... // read in the size and the index...
mpArchive->ReadInt32(size); mpArchive->ReadInt32(size);
// use the size to assert that the file format is correct // use the size to assert that the file format is correct
if(size != (int)0xffffffff) if (size != (int)0xffffffff)
{ {
// unknown type index! // unknown type index!
d.TraceError("Encountered bad size: %d\n", size); d.TraceError("Encountered bad size: %d\n", size);
@ -495,4 +494,3 @@ TSTRING cSerializerImpl::GetFileName() const
{ {
return mFileName; return mFileName;
} }

View File

@ -60,75 +60,76 @@ class cArchive;
class cSerializerImpl : public iSerializer class cSerializerImpl : public iSerializer
{ {
public: public:
enum Mode { S_READ, S_WRITE }; enum Mode
cSerializerImpl (cArchive& archive, Mode action, const TSTRING& fileName = _T("") ); {
// fileName is only used for error reporting purposes S_READ,
S_WRITE
};
cSerializerImpl(cArchive& archive, Mode action, const TSTRING& fileName = _T(""));
// fileName is only used for error reporting purposes
virtual ~cSerializerImpl(); virtual ~cSerializerImpl();
bool IsWriting() const; bool IsWriting() const;
// Initializing and closing the archive // Initializing and closing the archive
virtual void Init(); // throw eSerializer virtual void Init(); // throw eSerializer
// initializes the serializer; must be called before any reading or writing is done // initializes the serializer; must be called before any reading or writing is done
virtual void Finit(); virtual void Finit();
// called after a session of serialization is done; called implicitely by the destructor // called after a session of serialization is done; called implicitely by the destructor
// if not called explicitely before destruction // if not called explicitely before destruction
//Reading and writing objects Init() should have already been called or all these will fail. //Reading and writing objects Init() should have already been called or all these will fail.
virtual void WriteObjectDynCreate(const iTypedSerializable* pObj); // throw (eSerializer, eArchive) virtual void WriteObjectDynCreate(const iTypedSerializable* pObj); // throw (eSerializer, eArchive)
// writes an object such that it can be dynamically created when read back in with // writes an object such that it can be dynamically created when read back in with
// ReadObject. // ReadObject.
virtual iTypedSerializable* ReadObjectDynCreate(); // throw (eSerializer, eArchive); virtual iTypedSerializable* ReadObjectDynCreate(); // throw (eSerializer, eArchive);
// reads an object from the archive, returning a pointer to it. The caller is responsible for // reads an object from the archive, returning a pointer to it. The caller is responsible for
// deleteing or Release()ing it when done. // deleteing or Release()ing it when done.
virtual void WriteObject(const iTypedSerializable* pObj); // throw (eSerializer, eArchive) virtual void WriteObject(const iTypedSerializable* pObj); // throw (eSerializer, eArchive)
// writes an object to the archive that will not be dynamically created // writes an object to the archive that will not be dynamically created
virtual void ReadObject(iTypedSerializable* pObj); // throw (eSerializer, eArchive) virtual void ReadObject(iTypedSerializable* pObj); // throw (eSerializer, eArchive)
// reads an object that was written with WriteObject() // reads an object that was written with WriteObject()
// members for registering classes to be serialized. One of these must be called exactly once // members for registering classes to be serialized. One of these must be called exactly once
// for each class that is to be serialized. // for each class that is to be serialized.
static void RegisterSerializable (const cType& type, iTypedSerializable::CreateFunc pFunc); static void RegisterSerializable(const cType& type, iTypedSerializable::CreateFunc pFunc);
static void RegisterSerializableRefCt (const cType& type, iSerRefCountObj::CreateFunc pFunc); static void RegisterSerializableRefCt(const cType& type, iSerRefCountObj::CreateFunc pFunc);
// writing interface // writing interface
// TODO -- I am not sure if I want to keep these or just have the serializer expose the archive. Actually, // TODO -- I am not sure if I want to keep these or just have the serializer expose the archive. Actually,
// I think the best thing might be to have iSerializable only know about the archive // I think the best thing might be to have iSerializable only know about the archive
// Standard data read/write // Standard data read/write
// (All functions can throw eArchave exceptions). // (All functions can throw eArchave exceptions).
virtual void ReadInt16(int16& ret); virtual void ReadInt16(int16& ret);
virtual void ReadInt32(int32& ret); virtual void ReadInt32(int32& ret);
virtual void ReadInt64(int64& ret); virtual void ReadInt64(int64& ret);
virtual void ReadString(TSTRING& ret); virtual void ReadString(TSTRING& ret);
virtual int ReadBlob(void* pBlob, int count); virtual int ReadBlob(void* pBlob, int count);
virtual void WriteInt16(int16 i); virtual void WriteInt16(int16 i);
virtual void WriteInt32(int32 i); virtual void WriteInt32(int32 i);
virtual void WriteInt64(int64 i); virtual void WriteInt64(int64 i);
virtual void WriteString(const TSTRING& s); virtual void WriteString(const TSTRING& s);
virtual void WriteBlob(const void* pBlob, int count); virtual void WriteBlob(const void* pBlob, int count);
virtual TSTRING GetFileName() const; virtual TSTRING GetFileName() const;
private: private:
cArchive* mpArchive; // the archive we are serializing to cArchive* mpArchive; // the archive we are serializing to
Mode mMode; // are we writing or reading? Mode mMode; // are we writing or reading?
bool mbInit; // has init been called? bool mbInit; // has init been called?
cSerRefCountTable mRefCtObjTbl; // keeps track of all ref counted objects that cSerRefCountTable mRefCtObjTbl; // keeps track of all ref counted objects that
// have been read or written during serialization // have been read or written during serialization
TSTRING mFileName; TSTRING mFileName;
// creation function maps // creation function maps
typedef std::map<uint32, iTypedSerializable::CreateFunc> SerMap; typedef std::map<uint32, iTypedSerializable::CreateFunc> SerMap;
typedef std::map<uint32, iSerRefCountObj::CreateFunc> SerRefCountMap; typedef std::map<uint32, iSerRefCountObj::CreateFunc> SerRefCountMap;
static SerMap mSerCreateMap; static SerMap mSerCreateMap;
static SerRefCountMap mSerRefCountCreateMap; static SerRefCountMap mSerRefCountCreateMap;
static void InitSerializableMaps(); static void InitSerializableMaps();
static void FinitSerializableMaps(); static void FinitSerializableMaps();
}; };
#endif #endif

View File

@ -35,39 +35,41 @@
#include "archive.h" #include "archive.h"
#include "serializer.h" #include "serializer.h"
namespace { namespace
template<class FROM, class TO>
int64 CopyImpl(TO* pTo, FROM* pFrom, int64 amt)
{ {
enum { BUF_SIZE = 8192 }; template<class FROM, class TO> int64 CopyImpl(TO* pTo, FROM* pFrom, int64 amt)
int8 buf[BUF_SIZE]; {
int64 amtLeft = amt; enum
{
BUF_SIZE = 8192
};
int8 buf[BUF_SIZE];
int64 amtLeft = amt;
while(amtLeft > 0) while (amtLeft > 0)
{ {
// NOTE: We use int's here rather than int64 because iSerializer and cArchive // NOTE: We use int's here rather than int64 because iSerializer and cArchive
// only take int's as their size parameter - dmb // only take int's as their size parameter - dmb
int amtToRead = amtLeft > BUF_SIZE ? BUF_SIZE : (int)amtLeft; int amtToRead = amtLeft > BUF_SIZE ? BUF_SIZE : (int)amtLeft;
int amtRead = pFrom->ReadBlob(buf, amtToRead ); int amtRead = pFrom->ReadBlob(buf, amtToRead);
amtLeft -= amtRead; amtLeft -= amtRead;
pTo->WriteBlob(buf, amtRead); pTo->WriteBlob(buf, amtRead);
if(amtRead < amtToRead) if (amtRead < amtToRead)
break; break;
} }
// return the amount copied ... // return the amount copied ...
return (amt - amtLeft); return (amt - amtLeft);
} }
} } // namespace
int64 cSerializerUtil::Copy( iSerializer* pDest, cArchive* pSrc, int64 amt ) int64 cSerializerUtil::Copy(iSerializer* pDest, cArchive* pSrc, int64 amt)
{ {
return CopyImpl( pDest, pSrc, amt ); return CopyImpl(pDest, pSrc, amt);
} }
int64 cSerializerUtil::Copy( cArchive* pDest, iSerializer* pSrc, int64 amt ) int64 cSerializerUtil::Copy(cArchive* pDest, iSerializer* pSrc, int64 amt)
{ {
return CopyImpl( pDest, pSrc, amt ); return CopyImpl(pDest, pSrc, amt);
} }

View File

@ -44,11 +44,10 @@ class iSerializer;
class cSerializerUtil class cSerializerUtil
{ {
public: public:
static int64 Copy( iSerializer* pDest, cArchive* pSrc, int64 amt ); // throw( eArchvie, eSerilaizer ) static int64 Copy(iSerializer* pDest, cArchive* pSrc, int64 amt); // throw( eArchvie, eSerilaizer )
static int64 Copy( cArchive* pDest, iSerializer* pSrc, int64 amt ); // throw( eArchvie, eSerilaizer ) static int64 Copy(cArchive* pDest, iSerializer* pSrc, int64 amt); // throw( eArchvie, eSerilaizer )
// these two methods copy data from archives to serializers and vice-versa. They // these two methods copy data from archives to serializers and vice-versa. They
// throw exceptions on error; the return value is the amount that was copied. // throw exceptions on error; the return value is the amount that was copied.
}; };
#endif #endif

View File

@ -37,7 +37,7 @@
IMPLEMENT_TYPEDSERIALIZABLE(cSerializableNString, _T("cSerializableNString"), 0, 1) IMPLEMENT_TYPEDSERIALIZABLE(cSerializableNString, _T("cSerializableNString"), 0, 1)
void cSerializableNString::Read (iSerializer* pSerializer, int32 version) void cSerializableNString::Read(iSerializer* pSerializer, int32 version)
{ {
int32 len; int32 len;
pSerializer->ReadInt32(len); pSerializer->ReadInt32(len);
@ -55,7 +55,7 @@ void cSerializableNString::Write(iSerializer* pSerializer) const
IMPLEMENT_TYPEDSERIALIZABLE(cSerializableWString, _T("cSerializableWString"), 0, 1) IMPLEMENT_TYPEDSERIALIZABLE(cSerializableWString, _T("cSerializableWString"), 0, 1)
void cSerializableWString::Read (iSerializer* pSerializer, int32 version) void cSerializableWString::Read(iSerializer* pSerializer, int32 version)
{ {
int32 len; int32 len;
pSerializer->ReadInt32(len); pSerializer->ReadInt32(len);
@ -69,4 +69,3 @@ void cSerializableWString::Write(iSerializer* pSerializer) const
pSerializer->WriteInt32(len); pSerializer->WriteInt32(len);
pSerializer->WriteBlob(mString.data(), len); pSerializer->WriteBlob(mString.data(), len);
} }

View File

@ -56,8 +56,8 @@ class cSerializableNString : public iTypedSerializable
public: public:
std::string mString; std::string mString;
virtual ~cSerializableNString() {}; virtual ~cSerializableNString(){};
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
DECLARE_TYPEDSERIALIZABLE() DECLARE_TYPEDSERIALIZABLE()
@ -71,14 +71,13 @@ class cSerializableWString : public iTypedSerializable
public: public:
std::string mString; std::string mString;
virtual ~cSerializableWString() {}; virtual ~cSerializableWString(){};
virtual void Read (iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive) virtual void Read(iSerializer* pSerializer, int32 version = 0); // throw (eSerializer, eArchive)
virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive) virtual void Write(iSerializer* pSerializer) const; // throw (eSerializer, eArchive)
DECLARE_TYPEDSERIALIZABLE() DECLARE_TYPEDSERIALIZABLE()
}; };
typedef cSerializableNString cSerializableTSTRING; typedef cSerializableNString cSerializableTSTRING;
#endif #endif

View File

@ -42,4 +42,3 @@
iSerRefCountObj::~iSerRefCountObj() iSerRefCountObj::~iSerRefCountObj()
{ {
} }

View File

@ -59,28 +59,26 @@ public:
protected: protected:
virtual ~iSerRefCountObj(); virtual ~iSerRefCountObj();
}; };
////////////////////////////// //////////////////////////////
// convenience macros // convenience macros
#define DECLARE_SERREFCOUNT() \ # define DECLARE_SERREFCOUNT() \
DECLARE_TYPED() \ DECLARE_TYPED() \
public: \ public: \
static iSerRefCountObj* Create(); \ static iSerRefCountObj* Create(); \
virtual int32 Version() const; virtual int32 Version() const;
#define IMPLEMENT_SERREFCOUNT(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \ # define IMPLEMENT_SERREFCOUNT(CLASS, TYPEDSTRING, VERSION_MAJOR, VERSION_MINOR) \
IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \ IMPLEMENT_TYPED(CLASS, TYPEDSTRING) \
iSerRefCountObj* CLASS::Create() \ iSerRefCountObj* CLASS::Create() \
{ \ { \
return new CLASS; \ return new CLASS; \
} \ } \
int32 CLASS::Version() const \ int32 CLASS::Version() const \
{ \ { \
return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \ return iTypedSerializable::MkVersion(VERSION_MAJOR, VERSION_MINOR); \
} }
#endif #endif

View File

@ -100,8 +100,8 @@ int cSerRefCountTable::Add(iSerRefCountObj* pObj, int id)
ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed ID already in table."))); ThrowAndAssert(eInternal(_T("cSerRefCountTable::Add() passed ID already in table.")));
} }
mIDToObjTbl.insert( MapIDTObj::value_type(id, pObj)); mIDToObjTbl.insert(MapIDTObj::value_type(id, pObj));
mObjToIdTbl.insert( MapObjIDT::value_type(pObj, id)); mObjToIdTbl.insert(MapObjIDT::value_type(pObj, id));
return id; return id;
} }
@ -154,4 +154,3 @@ cSerRefCountTableMap::~cSerRefCountTableMap()
} }
} }
*/ */

View File

@ -54,13 +54,13 @@ public:
// Add an object to the table, optionally specifying an ID. Returns a // Add an object to the table, optionally specifying an ID. Returns a
// unique ID for the object. ASSERTs and throws exception if object is // unique ID for the object. ASSERTs and throws exception if object is
// already in table or the ID is already taken. // already in table or the ID is already taken.
int Add( iSerRefCountObj* pObj, int id = 0); int Add(iSerRefCountObj* pObj, int id = 0);
int Add(const iSerRefCountObj* pObj, int id = 0); int Add(const iSerRefCountObj* pObj, int id = 0);
// TODO -- Note that this class is not really const-correct in that the const version of // TODO -- Note that this class is not really const-correct in that the const version of
// Add() just casts away the constness. The right thing to do is to make the serializer // Add() just casts away the constness. The right thing to do is to make the serializer
// use different versions of this class (const and non-const) depending on whether it is // use different versions of this class (const and non-const) depending on whether it is
// reading or writing and (maybe?) make this class a template class so that it can map // reading or writing and (maybe?) make this class a template class so that it can map
// to either const or non-const objects. // to either const or non-const objects.
// clears out the table // clears out the table
@ -89,4 +89,3 @@ public:
}; };
*/ */
#endif #endif

View File

@ -36,5 +36,3 @@
// //
#include "stdcore.h" #include "stdcore.h"

View File

@ -49,42 +49,42 @@
#if IS_MSVC #if IS_MSVC
#define NOMINMAX //--Disable min/max macros # define NOMINMAX //--Disable min/max macros
#include <xstddef> // ARGH!! This resumes certain warnings! #include <xstddef> // ARGH!! This resumes certain warnings!
#pragma warning( disable: 4786 ) // Token Name > 255 # pragma warning(disable : 4786) // Token Name > 255
#pragma warning( disable: 4127 ) // constant expression (e.g. ASSERT) # pragma warning(disable : 4127) // constant expression (e.g. ASSERT)
#pragma warning( disable: 4291 ) // Incorrectly called when new(nothrow)!!! # pragma warning(disable : 4291) // Incorrectly called when new(nothrow)!!!
#pragma warning( disable: 4097 ) // Type synonyms are good! # pragma warning(disable : 4097) // Type synonyms are good!
#pragma warning( disable: 4511 ) // Can't create copy ctor! (e.g.Private CTOR) # pragma warning(disable : 4511) // Can't create copy ctor! (e.g.Private CTOR)
#pragma warning( disable: 4512 ) // Can't create assignment!(e.g.Private CTOR) # pragma warning(disable : 4512) // Can't create assignment!(e.g.Private CTOR)
#pragma warning( disable: 4100 ) // Formal argument not used # pragma warning(disable : 4100) // Formal argument not used
#pragma warning( disable: 4710 ) // Compiler did not inline function # pragma warning(disable : 4710) // Compiler did not inline function
#ifndef DEBUG // ASSERT's are disabled give a lot of these # ifndef DEBUG // ASSERT's are disabled give a lot of these
#pragma warning( disable: 4702 ) // ---Unreachable Code # pragma warning(disable : 4702) // ---Unreachable Code
#endif # endif
/* NOTE:RAD:05/09/1999 -- Plaguers STDCPP implementation is SOOO bad /* NOTE:RAD:05/09/1999 -- Plaguers STDCPP implementation is SOOO bad
it creates all these errors when compiling at W4. By doing a push it creates all these errors when compiling at W4. By doing a push
before disabling them, we can still generate them for ourselves before disabling them, we can still generate them for ourselves
without a lot of noise. The warnings before this push, we want to without a lot of noise. The warnings before this push, we want to
always disable. */ always disable. */
#pragma warning( push ) # pragma warning(push)
#pragma warning( disable: 4663 ) // Old template specialization syntax # pragma warning(disable : 4663) // Old template specialization syntax
#pragma warning( disable: 4018 ) // Signed unsigned mismatch # pragma warning(disable : 4018) // Signed unsigned mismatch
#pragma warning( disable: 4245 ) // Signed unsigned mismatch # pragma warning(disable : 4245) // Signed unsigned mismatch
#pragma warning( disable: 4663 ) // Use new template specialization syntax: template<> # pragma warning(disable : 4663) // Use new template specialization syntax: template<>
#pragma warning( disable: 4701 ) // local variable 'X' may be used without having been initialized # pragma warning(disable : 4701) // local variable 'X' may be used without having been initialized
#pragma warning( disable: 4510 ) // 'X' : default constructor could not be generated # pragma warning(disable : 4510) // 'X' : default constructor could not be generated
#pragma warning( disable: 4610 ) // struct 'X' can never be instantiated - user defined constructor required # pragma warning(disable : 4610) // struct 'X' can never be instantiated - user defined constructor required
#pragma warning( disable: 4146 ) // unary minus operator applied to unsigned type, result still unsigned # pragma warning(disable : 4146) // unary minus operator applied to unsigned type, result still unsigned
#pragma warning( disable: 4244 ) // '=' : conversion from 'unsigned int' to 'char', possible loss of data # pragma warning(disable : 4244) // '=' : conversion from 'unsigned int' to 'char', possible loss of data
#pragma warning( disable: 4511 ) # pragma warning(disable : 4511)
#pragma warning( disable: 4503 ) # pragma warning(disable : 4503)
#endif // #if IS_MSVC #endif // #if IS_MSVC
@ -108,13 +108,12 @@
#include <limits> #include <limits>
#if IS_MSVC #if IS_MSVC
#pragma warning( pop ) // Resume W4 msgs for TSS code # pragma warning(pop) // Resume W4 msgs for TSS code
#endif #endif
//--Include Platform Specific Declarations //--Include Platform Specific Declarations
//--Include Common Core Declarations //--Include Common Core Declarations
#include "./tchar.h" #include "./tchar.h"
@ -123,5 +122,4 @@
#include "./debug.h" #include "./debug.h"
#endif//__STDCORE_H #endif //__STDCORE_H

View File

@ -66,16 +66,15 @@
/// Requirements /// Requirements
#include "stdcore.h" // for: pch #include "stdcore.h" // for: pch
#include "stringutil.h" // for: These Declarations #include "stringutil.h" // for: These Declarations
#include "debug.h" // for: Debugging Interface #include "debug.h" // for: Debugging Interface
#include "codeconvert.h" // for: iconv abstractions #include "codeconvert.h" // for: iconv abstractions
#include "ntmbs.h" // for: eCharacterEncoding #include "ntmbs.h" // for: eCharacterEncoding
#include "hashtable.h" #include "hashtable.h"
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// String Cache // String Cache
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@ -85,7 +84,7 @@
class tss_hash_key_convert class tss_hash_key_convert
{ {
public: public:
const byte* operator()( const wc16_string& s, int* const pcbKeyLen ) const byte* operator()(const wc16_string& s, int* const pcbKeyLen)
{ {
*pcbKeyLen = sizeof(WCHAR16) * s.length(); *pcbKeyLen = sizeof(WCHAR16) * s.length();
return (byte*)s.c_str(); return (byte*)s.c_str();
@ -95,37 +94,32 @@ public:
class tss_hash_key_compare class tss_hash_key_compare
{ {
public: public:
bool operator()( const wc16_string& lhs, const wc16_string& rhs ) bool operator()(const wc16_string& lhs, const wc16_string& rhs)
{ {
return ( lhs.compare( rhs ) == 0 ); return (lhs.compare(rhs) == 0);
} }
}; };
namespace /* Module Local */ namespace /* Module Local */
{ {
typedef typedef cHashTable<wc16_string, TSTRING, tss_hash_key_compare, tss_hash_key_convert> hashtable_t;
cHashTable< wc16_string,
TSTRING,
tss_hash_key_compare,
tss_hash_key_convert >
hashtable_t;
hashtable_t& tss_GetHashTable() hashtable_t& tss_GetHashTable()
{
static hashtable_t s_table;
return s_table;
}
}//Anon.
inline void tss_insert_in_hash( const wc16_string& lhs, const TSTRING& rhs )
{ {
tss_GetHashTable().Insert( lhs, rhs ); static hashtable_t s_table;
return s_table;
}
} // namespace
inline void tss_insert_in_hash(const wc16_string& lhs, const TSTRING& rhs)
{
tss_GetHashTable().Insert(lhs, rhs);
} }
inline bool tss_find_in_hash( const wc16_string& lhs, TSTRING& rhs ) inline bool tss_find_in_hash(const wc16_string& lhs, TSTRING& rhs)
{ {
return( tss_GetHashTable().Lookup( lhs, rhs ) ); return (tss_GetHashTable().Lookup(lhs, rhs));
} }
@ -134,30 +128,29 @@ inline bool tss_find_in_hash( const wc16_string& lhs, TSTRING& rhs )
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*static*/ /*static*/
std::string::const_iterator std::string::const_iterator cStringUtil::Convert(std::string& nbs, const wc16_string& dbs)
cStringUtil::Convert( std::string& nbs, const wc16_string& dbs )
{ {
#if IS_AROS #if IS_AROS
nbs.resize(dbs.length()); nbs.resize(dbs.length());
for (int x=0; x<dbs.length(); ++x) for (int x = 0; x < dbs.length(); ++x)
nbs[x] = (unsigned char)dbs[x]; nbs[x] = (unsigned char)dbs[x];
#else #else
cDebug d("cStringUtil::Convert( char, w16 )"); cDebug d("cStringUtil::Convert( char, w16 )");
ASSERT( (void*)nbs.c_str() != (void*)dbs.c_str() ); ASSERT((void*)nbs.c_str() != (void*)dbs.c_str());
if ( dbs.empty() ) if (dbs.empty())
nbs.erase(); nbs.erase();
else else
{ {
if( tss_find_in_hash( dbs, nbs ) ) if (tss_find_in_hash(dbs, nbs))
{ {
d.TraceNever( _T("found string in hash table\n") ); d.TraceNever(_T("found string in hash table\n"));
return nbs.begin(); return nbs.begin();
} }
else else
{ {
d.TraceNever( _T("didn't find string in hash table\n") ); d.TraceNever(_T("didn't find string in hash table\n"));
} }
/* /*
@ -167,21 +160,19 @@ cStringUtil::Convert( std::string& nbs, const wc16_string& dbs )
d.TraceDebug( _T("----\n") ); d.TraceDebug( _T("----\n") );
*/ */
nbs.resize( dbs.size() * MB_CUR_MAX ); nbs.resize(dbs.size() * MB_CUR_MAX);
int nWrote = int nWrote = iCodeConverter::GetInstance()->Convert(
iCodeConverter::GetInstance()->Convert( (char*)nbs.c_str(), nbs.size(), dbs.c_str(), dbs.size()); // c_str() because must be null terminated
(char*)nbs.c_str(), nbs.size(),
dbs.c_str(), dbs.size() ); // c_str() because must be null terminated
d.TraceDetail( _T("iCodeConverter returned %d\n"), nWrote ); d.TraceDetail(_T("iCodeConverter returned %d\n"), nWrote);
if ( nWrote == -1 ) if (nWrote == -1)
throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR));
nbs.resize( nWrote ); nbs.resize(nWrote);
tss_insert_in_hash( dbs, nbs ); tss_insert_in_hash(dbs, nbs);
} }
#endif #endif
@ -189,36 +180,33 @@ cStringUtil::Convert( std::string& nbs, const wc16_string& dbs )
} }
/*static*/ /*static*/
wc16_string::const_iterator wc16_string::const_iterator cStringUtil::Convert(wc16_string& dbs, const std::string& nbs)
cStringUtil::Convert( wc16_string& dbs, const std::string& nbs )
{ {
#if IS_AROS #if IS_AROS
dbs.resize(nbs.length()); dbs.resize(nbs.length());
for (int x=0; x<nbs.length(); x++) for (int x = 0; x < nbs.length(); x++)
dbs[x] = (unsigned short)nbs[x]; dbs[x] = (unsigned short)nbs[x];
#else #else
cDebug d("cStringUtil::Convert( w16, char )"); cDebug d("cStringUtil::Convert( w16, char )");
if (nbs.size() != 0) if (nbs.size() != 0)
{ {
dbs.resize( nbs.size() ); dbs.resize(nbs.size());
// d.TraceDebug( "converting <%s>\n", nbs.c_str() ); // d.TraceDebug( "converting <%s>\n", nbs.c_str() );
int nWrote = int nWrote = iCodeConverter::GetInstance()->Convert(
iCodeConverter::GetInstance()->Convert( (WCHAR16*)dbs.c_str(), dbs.length(), nbs.c_str(), nbs.size()); // c_str() because must be null terminated
(WCHAR16*)dbs.c_str(), dbs.length(),
nbs.c_str(), nbs.size() ); // c_str() because must be null terminated
d.TraceDetail( _T("iCodeConverter returned %d\n"), nWrote ); d.TraceDetail(_T("iCodeConverter returned %d\n"), nWrote);
if ( nWrote == -1 ) if (nWrote == -1)
{ {
throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR));
} }
dbs.resize( nWrote ); dbs.resize(nWrote);
/* /*
d.TraceDebug( _T("converted to: \n") ); d.TraceDebug( _T("converted to: \n") );
@ -237,18 +225,17 @@ cStringUtil::Convert( wc16_string& dbs, const std::string& nbs )
#if SUPPORTS_WCHART && WCHAR_REP_IS_UCS2 #if SUPPORTS_WCHART && WCHAR_REP_IS_UCS2
/*static*/ /*static*/
std::wstring::const_iterator std::wstring::const_iterator cStringUtil::Convert(std::wstring& wcs, const wc16_string& dbs)
cStringUtil::Convert( std::wstring& wcs, const wc16_string& dbs )
{ {
if (dbs.size() != 0) if (dbs.size() != 0)
{ {
if( tss_find_in_hash( dbs, wcs ) ) if (tss_find_in_hash(dbs, wcs))
return wcs.begin(); return wcs.begin();
wcs.resize( dbs.size() ); wcs.resize(dbs.size());
std::copy( dbs.begin(), dbs.end(), wcs.begin() ); std::copy(dbs.begin(), dbs.end(), wcs.begin());
tss_insert_in_hash( dbs, wcs ); tss_insert_in_hash(dbs, wcs);
} }
else else
wcs.erase(); wcs.erase();
@ -257,13 +244,12 @@ cStringUtil::Convert( std::wstring& wcs, const wc16_string& dbs )
} }
/*static*/ /*static*/
wc16_string::const_iterator wc16_string::const_iterator cStringUtil::Convert(wc16_string& dbs, const std::wstring& wcs)
cStringUtil::Convert( wc16_string& dbs, const std::wstring& wcs )
{ {
if (wcs.size() != 0) if (wcs.size() != 0)
{ {
dbs.resize( wcs.size() ); dbs.resize(wcs.size());
std::copy( wcs.begin(), wcs.end(), dbs.begin() ); std::copy(wcs.begin(), wcs.end(), dbs.begin());
} }
else else
dbs.resize(0); dbs.resize(0);
@ -272,18 +258,17 @@ cStringUtil::Convert( wc16_string& dbs, const std::wstring& wcs )
} }
/*static*/ /*static*/
std::wstring::const_iterator std::wstring::const_iterator cStringUtil::Convert(std::wstring& wcs, const std::string& nbs)
cStringUtil::Convert( std::wstring& wcs, const std::string& nbs )
{ {
if (nbs.size() != 0) if (nbs.size() != 0)
{ {
wcs.resize( nbs.size() ); wcs.resize(nbs.size());
size_t nWrote = ::mbstowcs( (wchar_t*)wcs.c_str(), nbs.c_str(), wcs.size() + 1 ); size_t nWrote = ::mbstowcs((wchar_t*)wcs.c_str(), nbs.c_str(), wcs.size() + 1);
if ( nWrote == (size_t)-1 ) if (nWrote == (size_t)-1)
throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR));
wcs.resize( nWrote ); wcs.resize(nWrote);
} }
else else
wcs.erase(); wcs.erase();
@ -292,22 +277,21 @@ cStringUtil::Convert( std::wstring& wcs, const std::string& nbs )
} }
/*static*/ /*static*/
std::string::const_iterator std::string::const_iterator cStringUtil::Convert(std::string& nbs, const std::wstring& wcs)
cStringUtil::Convert( std::string& nbs, const std::wstring& wcs )
{ {
if (wcs.size() != 0) if (wcs.size() != 0)
{ {
if( tss_find_in_hash( wc16_string( wcs.c_str() ), nbs ) ) if (tss_find_in_hash(wc16_string(wcs.c_str()), nbs))
return nbs.begin(); return nbs.begin();
nbs.resize( MB_CUR_MAX * wcs.size() ); nbs.resize(MB_CUR_MAX * wcs.size());
size_t nWrote = ::wcstombs( (char*)nbs.c_str(), wcs.c_str(), nbs.size() + 1 ); size_t nWrote = ::wcstombs((char*)nbs.c_str(), wcs.c_str(), nbs.size() + 1);
if ( nWrote == (size_t)-1 ) if (nWrote == (size_t)-1)
throw eCharacterEncoding( TSS_GetString( cCore, core::STR_ERR_BADCHAR ) ); throw eCharacterEncoding(TSS_GetString(cCore, core::STR_ERR_BADCHAR));
nbs.resize( nWrote ); nbs.resize(nWrote);
tss_insert_in_hash( wc16_string( wcs.c_str() ), nbs ); tss_insert_in_hash(wc16_string(wcs.c_str()), nbs);
} }
else else
nbs.erase(); nbs.erase();
@ -324,40 +308,39 @@ cStringUtil::Convert( std::string& nbs, const std::wstring& wcs )
// TstrToStr // TstrToStr
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
std::string std::string cStringUtil::TstrToStr(const TSTRING& tstr)
cStringUtil::TstrToStr( const TSTRING& tstr )
{ {
std::string s; std::string s;
cStringUtil::Convert( s, tstr ); cStringUtil::Convert(s, tstr);
return s; return s;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// StrToTstr // StrToTstr
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
TSTRING cStringUtil::StrToTstr( const std::string& rhs ) TSTRING cStringUtil::StrToTstr(const std::string& rhs)
{ {
TSTRING lhs; TSTRING lhs;
cStringUtil::Convert( lhs, rhs ); cStringUtil::Convert(lhs, rhs);
return lhs; return lhs;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// WstrToTstr // WstrToTstr
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
TSTRING cStringUtil::WstrToTstr(const wc16_string& rhs ) TSTRING cStringUtil::WstrToTstr(const wc16_string& rhs)
{ {
TSTRING lhs; TSTRING lhs;
cStringUtil::Convert( lhs, rhs ); cStringUtil::Convert(lhs, rhs);
return lhs; return lhs;
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// TstrToWstr // TstrToWstr
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
wc16_string cStringUtil::TstrToWstr( const TSTRING& rhs ) wc16_string cStringUtil::TstrToWstr(const TSTRING& rhs)
{ {
wc16_string lhs; wc16_string lhs;
cStringUtil::Convert( lhs, rhs ); cStringUtil::Convert(lhs, rhs);
return lhs; return lhs;
} }

View File

@ -55,97 +55,83 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
namespace cStringUtil namespace cStringUtil
{ {
//--Type Dispatched Conversion (Generalization away from TCHAR) //--Type Dispatched Conversion (Generalization away from TCHAR)
/// Handle Like-Types (xstring to xstring) /// Handle Like-Types (xstring to xstring)
inline inline const char* Convert(std::string& lhs, const std::string& rhs)
const char * {
Convert( std::string& lhs, const std::string& rhs ) lhs = rhs;
{ return lhs.c_str();
lhs = rhs; }
return lhs.c_str();
}
/// Specialize Everything Else /// Specialize Everything Else
std::string::const_iterator std::string::const_iterator Convert(std::string&, const wc16_string&);
Convert( std::string&, const wc16_string& );
wc16_string::const_iterator wc16_string::const_iterator Convert(wc16_string&, const std::string&);
Convert( wc16_string&, const std::string& );
#if SUPPORTS_WCHART && WCHAR_REP_IS_UCS2 #if SUPPORTS_WCHART && WCHAR_REP_IS_UCS2
inline inline std::wstring::const_iterator Convert(std::wstring& lhs, const std::wstring& rhs)
std::wstring::const_iterator {
Convert( std::wstring& lhs, const std::wstring& rhs ) lhs = rhs;
{ return lhs.c_str();
lhs = rhs; }
return lhs.c_str();
}
std::wstring::const_iterator std::wstring::const_iterator Convert(std::wstring&, const wc16_string&);
Convert( std::wstring&, const wc16_string& );
std::wstring::const_iterator std::wstring::const_iterator Convert(std::wstring&, const std::string&);
Convert( std::wstring&, const std::string& );
std::string::const_iterator std::string::const_iterator Convert(std::string&, const std::wstring&);
Convert( std::string&, const std::wstring& );
wc16_string::const_iterator wc16_string::const_iterator Convert(wc16_string&, const std::wstring&);
Convert( wc16_string&, const std::wstring& );
#endif//SUPPORTS_WCHART #endif //SUPPORTS_WCHART
/// WARNING: These are deprecated, please use Convert()! /// WARNING: These are deprecated, please use Convert()!
std::string TstrToStr( const TSTRING& tstr ); std::string TstrToStr(const TSTRING& tstr);
// converts a tstring to a narrow string; useful for passphrase input, which must always be // converts a tstring to a narrow string; useful for passphrase input, which must always be
// the same format, regardless of what TCHAR is defined to. // the same format, regardless of what TCHAR is defined to.
TSTRING StrToTstr( const std::string& str ); TSTRING StrToTstr(const std::string& str);
// converts a narrow string to a TSTRING // converts a narrow string to a TSTRING
TSTRING WstrToTstr( const wc16_string& src ); TSTRING WstrToTstr(const wc16_string& src);
// convert wc16_string to a TSTRING // convert wc16_string to a TSTRING
wc16_string TstrToWstr( const TSTRING& tstr ); wc16_string TstrToWstr(const TSTRING& tstr);
// convert a TSTRING to a wc16_string // convert a TSTRING to a wc16_string
template <class IterT> template<class IterT> void splitstring(IterT& iter, const TSTRING& str, const TSTRING& delims)
void splitstring(IterT& iter, {
const TSTRING& str,
const TSTRING& delims) {
TSTRING::size_type where; TSTRING::size_type where;
TSTRING tmpStr; TSTRING tmpStr;
TSTRING workingString = str; TSTRING workingString = str;
while (workingString.length() > 0) { while (workingString.length() > 0)
{
where = workingString.find_first_of(delims, 0); where = workingString.find_first_of(delims, 0);
// in the case of no delimeters, setp to // in the case of no delimeters, setp to
// grab the entire string. // grab the entire string.
// //
if (where == TSTRING::npos) if (where == TSTRING::npos)
where = workingString.length(); where = workingString.length();
tmpStr = workingString.substr(0, where); tmpStr = workingString.substr(0, where);
workingString.erase(0, where+1); workingString.erase(0, where + 1);
iter.push_back(tmpStr);
iter.push_back(tmpStr);
} }
} }
} // namespace cStringUtil
}//cStringUtil::
/* /*
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -202,5 +188,4 @@ namespace std
} }
*/ */
#endif//__STRINGUTIL_H #endif //__STRINGUTIL_H

View File

@ -57,12 +57,14 @@ class cTaskTimer
public: public:
cTaskTimer(const TSTRING& name) : mName(name), mTotalTime(0), mStartTime(0), mNumStarts(0) {} cTaskTimer(const TSTRING& name) : mName(name), mTotalTime(0), mStartTime(0), mNumStarts(0)
{
}
inline ~cTaskTimer() inline ~cTaskTimer()
{ {
// stop the timer if it is currently running // stop the timer if it is currently running
if(IsRunning()) if (IsRunning())
Stop(); Stop();
// trace out the time contents... // trace out the time contents...
@ -72,34 +74,47 @@ public:
inline void Start() inline void Start()
{ {
ASSERT(! IsRunning()); ASSERT(!IsRunning());
time_t dummy; time_t dummy;
mStartTime = time(&dummy); mStartTime = time(&dummy);
mNumStarts++; mNumStarts++;
} }
void Stop() void Stop()
{ {
ASSERT(IsRunning()); ASSERT(IsRunning());
time_t dummy; time_t dummy;
mTotalTime += ( time(&dummy) - mStartTime ); mTotalTime += (time(&dummy) - mStartTime);
mStartTime = 0; mStartTime = 0;
} }
bool IsRunning() { return (mStartTime != 0); } bool IsRunning()
void Reset() { mNumStarts = mStartTime = mTotalTime = 0; } {
uint32 GetTotalTime() const { return mTotalTime; } return (mStartTime != 0);
uint32 GetNumTimesStarted() const { return mNumStarts; } }
const std::string& GetName() const { return mName; } void Reset()
{
mNumStarts = mStartTime = mTotalTime = 0;
}
uint32 GetTotalTime() const
{
return mTotalTime;
}
uint32 GetNumTimesStarted() const
{
return mNumStarts;
}
const std::string& GetName() const
{
return mName;
}
private: private:
TSTRING mName; TSTRING mName;
uint32 mTotalTime; uint32 mTotalTime;
uint32 mStartTime; uint32 mStartTime;
uint32 mNumStarts; uint32 mNumStarts;
}; };
#endif #endif

View File

@ -58,7 +58,7 @@
#define __TCHAR_H #define __TCHAR_H
// A little macro that's useful for finding the number of characters in a TCHAR ARRAY // A little macro that's useful for finding the number of characters in a TCHAR ARRAY
#define countof( x ) ( sizeof( x ) / sizeof( x[0] ) ) #define countof(x) (sizeof(x) / sizeof(x[0]))
#include <string.h> #include <string.h>
@ -66,64 +66,63 @@
#include <sstream> #include <sstream>
#include <iostream> #include <iostream>
#define TCHAR char #define TCHAR char
#define _tmain main #define _tmain main
typedef std::string TSTRING; typedef std::string TSTRING;
typedef std::stringstream TSTRINGSTREAM; typedef std::stringstream TSTRINGSTREAM;
typedef std::ostringstream TOSTRINGSTREAM; typedef std::ostringstream TOSTRINGSTREAM;
typedef std::istringstream TISTRINGSTREAM; typedef std::istringstream TISTRINGSTREAM;
typedef std::ostream TOSTREAM; typedef std::ostream TOSTREAM;
typedef std::istream TISTREAM; typedef std::istream TISTREAM;
typedef std::ofstream TOFSTREAM; typedef std::ofstream TOFSTREAM;
typedef std::ifstream TIFSTREAM; typedef std::ifstream TIFSTREAM;
// iostream abstractions // iostream abstractions
#define TCIN std::cin # define TCIN std::cin
#define TCOUT std::cout # define TCOUT std::cout
#define TCERR std::cerr # define TCERR std::cerr
// other functions // other functions
#define _ftprintf fprintf # define _ftprintf fprintf
#define _stprintf sprintf # define _stprintf sprintf
#define _itot itoa # define _itot itoa
#define _ttoi atoi # define _ttoi atoi
#define _istdigit isdigit # define _istdigit isdigit
#define _tcsftime strftime # define _tcsftime strftime
#define _vtprintf vprintf # define _vtprintf vprintf
#define _vftprintf vfprintf # define _vftprintf vfprintf
#define _topen open # define _topen open
#define _tfdopen fdopen # define _tfdopen fdopen
#define _tfopen fopen # define _tfopen fopen
#define _tmkdir mkdir # define _tmkdir mkdir
#define _tcscpy strcpy # define _tcscpy strcpy
#define _tgetenv getenv # define _tgetenv getenv
#define _taccess access # define _taccess access
#define _tcreat creat # define _tcreat creat
#define _tunlink unlink # define _tunlink unlink
#define _tcscmp strcmp # define _tcscmp strcmp
#define _tcsicmp strcasecmp # define _tcsicmp strcasecmp
#define _totlower tolower # define _totlower tolower
#define _totupper toupper # define _totupper toupper
#define _tcslen strlen # define _tcslen strlen
#define _tcscat strcat # define _tcscat strcat
#define _tcsncmp strncmp # define _tcsncmp strncmp
// other abstractions // other abstractions
#define TUNLINK unlink # define TUNLINK unlink
// string representation // string representation
#if defined(_T) # if defined(_T)
// run it right over with a bulldozer, tripwire doesn't seem // run it right over with a bulldozer, tripwire doesn't seem
// to use ctype.h's _T -PH // to use ctype.h's _T -PH
#undef _T # undef _T
#endif # endif
#define _T(x) x # define _T(x) x
// misc... // misc...
#ifndef __cdecl # ifndef __cdecl
#define __cdecl # define __cdecl
#endif # endif
#endif // __TCHAR_H #endif // __TCHAR_H

View File

@ -52,36 +52,34 @@
// METHOD CODE // METHOD CODE
//========================================================================= //=========================================================================
#define TIME_MAX 2147483647L // largest signed 32 bit number #define TIME_MAX 2147483647L // largest signed 32 bit number
#if IS_AROS #if IS_AROS
#define tzset() # define tzset()
#endif #endif
struct tm* cTimeUtil::TimeToDateGMT( const int64& seconds ) struct tm* cTimeUtil::TimeToDateGMT(const int64& seconds)
{ {
ASSERT( seconds < TIME_MAX );// this assumes time_t size is 32 bit. Yikes! ASSERT(seconds < TIME_MAX); // this assumes time_t size is 32 bit. Yikes!
time_t t = static_cast<time_t>(seconds); time_t t = static_cast<time_t>(seconds);
return gmtime( &t ); return gmtime(&t);
} }
struct tm* cTimeUtil::TimeToDateLocal( const int64& seconds ) struct tm* cTimeUtil::TimeToDateLocal(const int64& seconds)
{ {
ASSERT( seconds < TIME_MAX );// this assumes time_t size is 32 bit. Yikes! ASSERT(seconds < TIME_MAX); // this assumes time_t size is 32 bit. Yikes!
time_t t = static_cast<time_t>(seconds); time_t t = static_cast<time_t>(seconds);
tzset(); tzset();
return localtime( &t ); return localtime(&t);
} }
int64 cTimeUtil::DateToTime( struct tm* ptm ) int64 cTimeUtil::DateToTime(struct tm* ptm)
{ {
tzset(); tzset();
return mktime( ptm ); return mktime(ptm);
} }
int64 cTimeUtil::GetTime() int64 cTimeUtil::GetTime()
{ {
return time( NULL ); return time(NULL);
} }

View File

@ -62,15 +62,14 @@
class cTimeUtil class cTimeUtil
{ {
public: public:
static int64 DateToTime( struct tm* ptm ); static int64 DateToTime(struct tm* ptm);
// simple conversion. ptm is considered to be in localtime. // simple conversion. ptm is considered to be in localtime.
static struct tm* TimeToDateGMT( const int64& seconds ); static struct tm* TimeToDateGMT(const int64& seconds);
// simple conversion // simple conversion
static struct tm* TimeToDateLocal( const int64& seconds ); static struct tm* TimeToDateLocal(const int64& seconds);
// conversion with timezone and daylight // conversion with timezone and daylight
static int64 GetTime(); static int64 GetTime();
// returns current time in UTC // returns current time in UTC
}; };
#endif//__TIMECONVERT_H #endif //__TIMECONVERT_H

View File

@ -36,9 +36,9 @@
#include <signal.h> #include <signal.h>
#include <stdlib.h> #include <stdlib.h>
static void util_SignalHandler( int sig ); static void util_SignalHandler(int sig);
static void tw_psignal( int sig, const TCHAR* s ); static void tw_psignal(int sig, const TCHAR* s);
tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc) tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc)
{ {
@ -58,66 +58,62 @@ tw_sighandler_t tw_sigign(int sig)
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// tw_HandleSignal -- Take a given signal and install a handler for // tw_HandleSignal -- Take a given signal and install a handler for
// it, which will then exit with the supplied exit value // it, which will then exit with the supplied exit value
tw_sighandler_t tw_HandleSignal( int sig ) tw_sighandler_t tw_HandleSignal(int sig)
{ {
return signal( sig, util_SignalHandler ); return signal(sig, util_SignalHandler);
} }
void util_SignalHandler( int sig ) void util_SignalHandler(int sig)
{ {
//If we're on unix, let's print out a nice error message telling //If we're on unix, let's print out a nice error message telling
//the user which signal we've recieved. //the user which signal we've recieved.
tw_psignal( sig, (TSS_GetString( cCore, core::STR_SIGNAL).c_str() ) ); tw_psignal(sig, (TSS_GetString(cCore, core::STR_SIGNAL).c_str()));
exit( 8 ); exit(8);
} }
/* For the morbidly curious, here's a thread where a POSIX standards committee /* For the morbidly curious, here's a thread where a POSIX standards committee
wrings its hands about how to define NSIG: http://austingroupbugs.net/view.php?id=741#c1834 */ wrings its hands about how to define NSIG: http://austingroupbugs.net/view.php?id=741#c1834 */
#ifndef NSIG #ifndef NSIG
# ifdef SIGMAX # ifdef SIGMAX
# define NSIG (SIGMAX+1) # define NSIG (SIGMAX + 1)
# else # else
# define NSIG 32 # define NSIG 32
# endif # endif
#endif #endif
void tw_psignal(int sig, const TCHAR *str) void tw_psignal(int sig, const TCHAR* str)
{ {
const TCHAR *siglist[NSIG] = { const TCHAR* siglist[NSIG] = {_T("Unknown Signal"),
_T("Unknown Signal"), _T("Hangup"),
_T("Hangup"), _T("Interrupt"),
_T("Interrupt"), _T("Quit"),
_T("Quit"), _T("Illegal Instruction"),
_T("Illegal Instruction"), _T("Trace/Breakpoint Trap"),
_T("Trace/Breakpoint Trap"), _T("Abort"),
_T("Abort"), _T("Emulation Trap"),
_T("Emulation Trap"), _T("Arithmetic Exception"),
_T("Arithmetic Exception"), _T("Killed"),
_T("Killed"), _T("Bus Error"),
_T("Bus Error"), _T("Segmentation Fault"),
_T("Segmentation Fault"), _T("Bad System Call"),
_T("Bad System Call"), _T("Broken Pipe"),
_T("Broken Pipe"), _T("Alarm Clock"),
_T("Alarm Clock"), _T("Terminated"),
_T("Terminated"), _T("User Signal 1"),
_T("User Signal 1"), _T("User Signal 2"),
_T("User Signal 2"), _T("Child Status Changed"),
_T("Child Status Changed"), _T("Power-Fail/Restart"),
_T("Power-Fail/Restart"), _T("Virtual Timer Expired"),
_T("Virtual Timer Expired"), _T("Profiling Timer Expired"),
_T("Profiling Timer Expired"), _T("Pollable Event"),
_T("Pollable Event"), _T("Window Size Change"),
_T("Window Size Change"), _T("Stopped (signal)"),
_T("Stopped (signal)"), _T("Stopped (user)"),
_T("Stopped (user)"), _T("Continued"),
_T("Continued"), _T("Stopped (tty input)"),
_T("Stopped (tty input)"), _T("Stopped (tty output)"),
_T("Stopped (tty output)"), _T("Urgent Socket Condition"),
_T("Urgent Socket Condition"), _T("File Lock Lost")};
_T("File Lock Lost")
};
_ftprintf(stderr, _T("%s %s\n"), str, sig < NSIG ? siglist[sig] : siglist[0]); _ftprintf(stderr, _T("%s %s\n"), str, sig < NSIG ? siglist[sig] : siglist[0]);
} }

View File

@ -39,18 +39,19 @@
#include <signal.h> #include <signal.h>
#ifdef HAVE_SIGNUM_H #ifdef HAVE_SIGNUM_H
#include <signum.h> // the signal number constants #include <signum.h> // the signal number constants
#endif #endif
#ifdef HAVE_BITS_SIGNUM_H #ifdef HAVE_BITS_SIGNUM_H
#include <bits/signum.h> #include <bits/signum.h>
#endif #endif
extern "C" { extern "C"
typedef void (*tw_sighandler_t)(int); {
typedef void (*tw_sighandler_t)(int);
} }
tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc); tw_sighandler_t tw_signal(int sig, tw_sighandler_t pFunc);
int tw_raise (int sig); int tw_raise(int sig);
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// tw_sigign -- wrapper around tw_signal(XXX, SIG_IGN) // tw_sigign -- wrapper around tw_signal(XXX, SIG_IGN)
@ -60,8 +61,7 @@ tw_sighandler_t tw_sigign(int sig);
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// tw_HandleSignal --wrapper around signal( XXX, <our handler function> ) // tw_HandleSignal --wrapper around signal( XXX, <our handler function> )
// //
tw_sighandler_t tw_HandleSignal( int sig ); tw_sighandler_t tw_HandleSignal(int sig);
#endif //__TW_SIGNAL_H #endif //__TW_SIGNAL_H

View File

@ -44,9 +44,9 @@
// METHOD CODE // METHOD CODE
//========================================================================= //=========================================================================
bool cInterpretInt::InterpretInt( const TSTRING& str, int* pi ) bool cInterpretInt::InterpretInt(const TSTRING& str, int* pi)
{ {
ASSERT( pi != 0); ASSERT(pi != 0);
bool fFormatOK = true; bool fFormatOK = true;
@ -55,21 +55,21 @@ bool cInterpretInt::InterpretInt( const TSTRING& str, int* pi )
// //
TOSTRINGSTREAM sstr; TOSTRINGSTREAM sstr;
sstr << cInterpretInt::LIMIT_MAX; sstr << cInterpretInt::LIMIT_MAX;
if( str.length() > sstr.str().length() ) if (str.length() > sstr.str().length())
fFormatOK = false; fFormatOK = false;
// //
// make sure string is not too short // make sure string is not too short
// //
if( fFormatOK && str.length() <= 0 ) if (fFormatOK && str.length() <= 0)
fFormatOK = false; fFormatOK = false;
// //
// make sure first character is a digit or the minus sign // make sure first character is a digit or the minus sign
// //
if( fFormatOK ) if (fFormatOK)
{ {
if( ! ( _T('-') == str[0] || std::isdigit<TCHAR>( str[0], std::locale() ) ) ) if (!(_T('-') == str[0] || std::isdigit<TCHAR>(str[0], std::locale())))
fFormatOK = false; fFormatOK = false;
} }
@ -77,23 +77,22 @@ bool cInterpretInt::InterpretInt( const TSTRING& str, int* pi )
// make sure all other characters are digits // make sure all other characters are digits
// NOTE:BAM -- this assumes that all digits in all locales are SB characters. // NOTE:BAM -- this assumes that all digits in all locales are SB characters.
// TODO:BAM -- check this... // TODO:BAM -- check this...
for( TSTRING::size_type j = 1; fFormatOK && j < str.length(); j++ ) for (TSTRING::size_type j = 1; fFormatOK && j < str.length(); j++)
{ {
if( ! std::isdigit<TCHAR>( str[j], std::locale() ) ) if (!std::isdigit<TCHAR>(str[j], std::locale()))
fFormatOK = false; fFormatOK = false;
} }
// //
// do _ttoi conversion and check that it is within allowable limits // do _ttoi conversion and check that it is within allowable limits
// //
if( fFormatOK ) if (fFormatOK)
{ {
*pi = _ttoi( str.c_str() ); *pi = _ttoi(str.c_str());
if( *pi < GetMin() || *pi > GetMax() ) if (*pi < GetMin() || *pi > GetMax())
fFormatOK = false; fFormatOK = false;
} }
return fFormatOK; return fFormatOK;
} }

View File

@ -68,10 +68,10 @@ public:
// //
// basic functionality // basic functionality
// //
bool InterpretInt( const TSTRING& str, int* pi ); bool InterpretInt(const TSTRING& str, int* pi);
// converts the string into an int value, returned in *pi. // converts the string into an int value, returned in *pi.
// returns true if successfully converted value. // returns true if successfully converted value.
// *pi is undefined if function returns false. // *pi is undefined if function returns false.
private: private:
// //
@ -86,11 +86,19 @@ private:
// //
// private functionality // private functionality
// //
virtual int GetMax() { return LIMIT_MAX; }; virtual int GetMax()
virtual int GetMin() { return LIMIT_MIN; }; {
return LIMIT_MAX;
};
virtual int GetMin()
{
return LIMIT_MIN;
};
public: public:
virtual ~cInterpretInt() {} virtual ~cInterpretInt()
{
}
}; };
/////////////////////////////////////////////// ///////////////////////////////////////////////
@ -105,11 +113,19 @@ private:
LIMIT_MAX = 1000000 LIMIT_MAX = 1000000
}; };
virtual int GetMax() { return LIMIT_MAX; }; virtual int GetMax()
virtual int GetMin() { return LIMIT_MIN; }; {
return LIMIT_MAX;
};
virtual int GetMin()
{
return LIMIT_MIN;
};
public: public:
virtual ~cSeverityLimits() {} virtual ~cSeverityLimits()
{
}
}; };
/////////////////////////////////////////////// ///////////////////////////////////////////////
@ -124,12 +140,19 @@ private:
LIMIT_MAX = 1000000 LIMIT_MAX = 1000000
}; };
virtual int GetMax() { return LIMIT_MAX; }; virtual int GetMax()
virtual int GetMin() { return LIMIT_MIN; }; {
return LIMIT_MAX;
};
virtual int GetMin()
{
return LIMIT_MIN;
};
public: public:
virtual ~cRecurseDepthLimits() {} virtual ~cRecurseDepthLimits()
{
}
}; };
#endif //__TWLIMITS_H #endif //__TWLIMITS_H

View File

@ -57,11 +57,11 @@
//========================================================================= //=========================================================================
// UTIL FUNCTION PROTOTYPES // UTIL FUNCTION PROTOTYPES
//========================================================================= //=========================================================================
static TSTRING& util_FormatTimeC( struct tm* ptm, TSTRING& strBuf ); static TSTRING& util_FormatTimeC(struct tm* ptm, TSTRING& strBuf);
static TSTRING& util_FormatTime( struct tm* ptm, TSTRING& strBuf ); static TSTRING& util_FormatTime(struct tm* ptm, TSTRING& strBuf);
#if !USES_CLIB_DATE_FUNCTION #if !USES_CLIB_DATE_FUNCTION
static TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf ); static TSTRING& util_FormatTimeCPlusPlus(struct tm* ptm, TSTRING& strBuf);
#endif #endif
//========================================================================= //=========================================================================
@ -69,39 +69,38 @@ static TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf );
//========================================================================= //=========================================================================
#if IS_AROS #if IS_AROS
#define tzset() # define tzset()
#endif #endif
void cTWLocale::InitGlobalLocale() void cTWLocale::InitGlobalLocale()
{ {
cDebug d("cTWLocale::InitGlobalLocale"); cDebug d("cTWLocale::InitGlobalLocale");
d.TraceDetail( "Attempting to set the program locale from the" d.TraceDetail("Attempting to set the program locale from the"
"default \"C\" locale to the system-default locale." ); "default \"C\" locale to the system-default locale.");
#if USE_CLIB_LOCALE #if USE_CLIB_LOCALE
char* pchLocale = setlocale( LC_ALL, "" ); char* pchLocale = setlocale(LC_ALL, "");
d.TraceDetail( "C++ locale is incomplete or unavailable with this compiler, so" d.TraceDetail("C++ locale is incomplete or unavailable with this compiler, so"
"only changing the C-language locale. Some C++ locale-specific functionality" "only changing the C-language locale. Some C++ locale-specific functionality"
"may not function properly." ); "may not function properly.");
if( pchLocale ) if (pchLocale)
{ {
d.TraceDebug( "locale changed to the system-default locale (non-C++): <%s>\n", pchLocale ); d.TraceDebug("locale changed to the system-default locale (non-C++): <%s>\n", pchLocale);
} }
else else
{ {
d.TraceDebug( "Error: unable to change locale to the system-default.\n" d.TraceDebug("Error: unable to change locale to the system-default.\n"
"It is possible that there is no other locale than\n" "It is possible that there is no other locale than\n"
"the \"C\" locale on this platform.\n" ); "the \"C\" locale on this platform.\n");
} }
#else #else
std::locale l(""); std::locale l("");
std::locale::global( l ); std::locale::global(l);
d.TraceDebug( "locale changed to the system default std::locale (C++): <%s>\n", l.name().c_str() ); d.TraceDebug("locale changed to the system default std::locale (C++): <%s>\n", l.name().c_str());
#endif #endif
} }
/* /*
@ -128,11 +127,9 @@ TSTRING cTWLocale::FormatNumberAsHex( int32 i )
} }
*/ */
template< class numT, class CharT > template<class numT, class CharT> class cFormatNumberUtil
class cFormatNumberUtil
{ {
public: public:
// TODO:BAM -- these functions should really maybe take a stringstream that has been // TODO:BAM -- these functions should really maybe take a stringstream that has been
// already set up for formatting (basefield, locale, etc.) that way we can merge // already set up for formatting (basefield, locale, etc.) that way we can merge
//. the FormatNumberAsHex function as well //. the FormatNumberAsHex function as well
@ -143,30 +140,23 @@ public:
// cFormatNumberUtil::FormatNumber( const std::basic_string< CharT >& s, bool fCStyleFormatting = false ) // cFormatNumberUtil::FormatNumber( const std::basic_string< CharT >& s, bool fCStyleFormatting = false )
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// EFFECTS: Does all actual formatting for FormatNumber methods // EFFECTS: Does all actual formatting for FormatNumber methods
static static numT Format(const std::basic_string<CharT>& s, bool fCStyleFormatting)
numT
Format( const std::basic_string< CharT >& s, bool fCStyleFormatting )
{ {
static const std::num_get< CharT >* png; static const std::num_get<CharT>* png;
std::basic_istringstream< CharT > ss( s ); std::basic_istringstream<CharT> ss(s);
std::ios_base::iostate state; std::ios_base::iostate state;
numT n; numT n;
if( fCStyleFormatting ) if (fCStyleFormatting)
ss.imbue( std::locale::classic() ); ss.imbue(std::locale::classic());
tss::GetFacet( ss.getloc(), png ).get( tss::GetFacet(ss.getloc(), png).get(ss, std::istreambuf_iterator<CharT>(), ss, state, n);
ss,
std::istreambuf_iterator< CharT >(),
ss,
state,
n );
if( ( state & std::ios_base::failbit ) != 0 ) if ((state & std::ios_base::failbit) != 0)
throw eTWLocaleBadNumFormat(); throw eTWLocaleBadNumFormat();
return( n ); return (n);
} }
//============================================================================= //=============================================================================
@ -175,20 +165,18 @@ public:
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// EFFECTS: Does all actual formatting for FormatNumber methods // EFFECTS: Does all actual formatting for FormatNumber methods
// //
static static std::basic_string<CharT>& Format(numT n, std::basic_string<CharT>& sBuf, bool fCStyleFormatting = false)
std::basic_string< CharT >&
Format( numT n, std::basic_string< CharT >& sBuf, bool fCStyleFormatting = false )
{ {
static const std::num_put< CharT >* pnp; static const std::num_put<CharT>* pnp;
std::basic_ostringstream< CharT > ss; std::basic_ostringstream<CharT> ss;
if( fCStyleFormatting ) if (fCStyleFormatting)
ss.imbue( std::locale::classic() ); ss.imbue(std::locale::classic());
tss::GetFacet( ss.getloc(), pnp ).put( ss, ss, ss.fill(), n ); tss::GetFacet(ss.getloc(), pnp).put(ss, ss, ss.fill(), n);
sBuf = ss.str(); sBuf = ss.str();
return( sBuf ); return (sBuf);
} }
}; };
@ -205,102 +193,102 @@ int32 cTWLocale::FormatNumberClassic( const TSTRING& s )
} }
*/ */
TSTRING& cTWLocale::FormatNumber( uint64 ui, TSTRING& strBuf ) TSTRING& cTWLocale::FormatNumber(uint64 ui, TSTRING& strBuf)
{ {
// try to use the int64 version // try to use the int64 version
if( ui <= (uint64)TSS_INT64_MAX ) if (ui <= (uint64)TSS_INT64_MAX)
return( FormatNumber( (int64)ui, strBuf ) ); return (FormatNumber((int64)ui, strBuf));
else else
{ {
#if IS_MSVC #if IS_MSVC
// MSVC can't convert from uint64 to a double for some reason // MSVC can't convert from uint64 to a double for some reason
strBuf = TSS_GetString( cCore, core::STR_NUMBER_TOO_BIG ); strBuf = TSS_GetString(cCore, core::STR_NUMBER_TOO_BIG);
return( strBuf ); return (strBuf);
#else #else
ASSERT( std::numeric_limits<double>::max() >= TSS_UINT64_MAX ); ASSERT(std::numeric_limits<double>::max() >= TSS_UINT64_MAX);
return( cFormatNumberUtil< double, TCHAR >::Format( (double)ui, strBuf ) ); return (cFormatNumberUtil<double, TCHAR>::Format((double)ui, strBuf));
#endif #endif
} }
} }
TSTRING& cTWLocale::FormatNumber( int64 i, TSTRING& strBuf ) TSTRING& cTWLocale::FormatNumber(int64 i, TSTRING& strBuf)
{ {
// try to use the int32 version // try to use the int32 version
if( i <= (int64)TSS_INT32_MAX ) if (i <= (int64)TSS_INT32_MAX)
return( FormatNumber( (int32)i, strBuf ) ); return (FormatNumber((int32)i, strBuf));
else else
{ {
ASSERT( std::numeric_limits<double>::max() >= TSS_INT64_MAX ); ASSERT(std::numeric_limits<double>::max() >= TSS_INT64_MAX);
return( cFormatNumberUtil< double, TCHAR >::Format( (double)i, strBuf ) ); return (cFormatNumberUtil<double, TCHAR>::Format((double)i, strBuf));
} }
} }
TSTRING& cTWLocale::FormatNumber( uint32 ui, TSTRING& strBuf ) TSTRING& cTWLocale::FormatNumber(uint32 ui, TSTRING& strBuf)
{ {
ASSERT( sizeof(unsigned long) >= sizeof(uint32) ); // must be able to cast to 'ulong' ASSERT(sizeof(unsigned long) >= sizeof(uint32)); // must be able to cast to 'ulong'
return( cFormatNumberUtil< unsigned long, TCHAR >::Format( (unsigned long)ui, strBuf ) ); return (cFormatNumberUtil<unsigned long, TCHAR>::Format((unsigned long)ui, strBuf));
} }
TSTRING& cTWLocale::FormatNumber( int32 i, TSTRING& strBuf ) TSTRING& cTWLocale::FormatNumber(int32 i, TSTRING& strBuf)
{ {
ASSERT( sizeof(long) >= sizeof(int32) ); // must be able to cast to 'long' ASSERT(sizeof(long) >= sizeof(int32)); // must be able to cast to 'long'
return( cFormatNumberUtil< long, TCHAR >::Format( (long)i, strBuf ) ); return (cFormatNumberUtil<long, TCHAR>::Format((long)i, strBuf));
} }
TSTRING& cTWLocale::FormatTime( int64 t, TSTRING& strBuf ) TSTRING& cTWLocale::FormatTime(int64 t, TSTRING& strBuf)
{ {
// clear return string // clear return string
strBuf.erase(); strBuf.erase();
tzset(); tzset();
time_t tmpTime = t; time_t tmpTime = t;
struct tm * ptm = localtime( &tmpTime ); struct tm* ptm = localtime(&tmpTime);
if( ptm ) if (ptm)
{ {
util_FormatTime( ptm, strBuf ); util_FormatTime(ptm, strBuf);
} }
else else
{ {
strBuf = TSS_GetString( cCore, core::STR_UNKNOWN_TIME ); strBuf = TSS_GetString(cCore, core::STR_UNKNOWN_TIME);
} }
return( strBuf ); return (strBuf);
} }
//========================================================================= //=========================================================================
// UTIL FUNCTION IMPLEMENTATION // UTIL FUNCTION IMPLEMENTATION
//========================================================================= //=========================================================================
TSTRING& util_FormatTime( struct tm* ptm, TSTRING& strBuf ) TSTRING& util_FormatTime(struct tm* ptm, TSTRING& strBuf)
{ {
ASSERT( ptm ); ASSERT(ptm);
#if USES_CLIB_DATE_FUNCTION #if USES_CLIB_DATE_FUNCTION
return util_FormatTimeC( ptm, strBuf ); return util_FormatTimeC(ptm, strBuf);
#else #else
return util_FormatTimeCPlusPlus( ptm, strBuf ); return util_FormatTimeCPlusPlus(ptm, strBuf);
#endif #endif
} }
#if !USES_CLIB_DATE_FUNCTION #if !USES_CLIB_DATE_FUNCTION
TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf ) TSTRING& util_FormatTimeCPlusPlus(struct tm* ptm, TSTRING& strBuf)
{ {
ASSERT( ptm ); ASSERT(ptm);
TOSTRINGSTREAM sstr; TOSTRINGSTREAM sstr;
static const std::time_put<TCHAR>* ptp; static const std::time_put<TCHAR>* ptp;
// //
// format date // format date
// //
#if IS_MSVC // MSVC uses old put() signature which didn't have the fill character, (and uses proprietary '#') # if IS_MSVC // MSVC uses old put() signature which didn't have the fill character, (and uses proprietary '#')
tss::GetFacet( sstr.getloc(), ptp ).put( sstr, sstr, ptm, 'c', '#' ); tss::GetFacet(sstr.getloc(), ptp).put(sstr, sstr, ptm, 'c', '#');
#else # else
tss::GetFacet( sstr.getloc(), ptp ).put( sstr, sstr, sstr.fill(), ptm, 'c' ); tss::GetFacet(sstr.getloc(), ptp).put(sstr, sstr, sstr.fill(), ptm, 'c');
#endif # endif
strBuf = sstr.str(); strBuf = sstr.str();
return strBuf; return strBuf;
@ -308,27 +296,27 @@ TSTRING& util_FormatTimeCPlusPlus( struct tm* ptm, TSTRING& strBuf )
#endif #endif
TSTRING& util_FormatTimeC( struct tm* ptm, TSTRING& strBuf ) TSTRING& util_FormatTimeC(struct tm* ptm, TSTRING& strBuf)
{ {
ASSERT( ptm ); ASSERT(ptm);
TCHAR achTimeBuf[256]; TCHAR achTimeBuf[256];
/* XXX: This should check (#ifdef) for strftime - PH */ /* XXX: This should check (#ifdef) for strftime - PH */
size_t nbWritten = _tcsftime( achTimeBuf, countof( achTimeBuf ), size_t nbWritten = _tcsftime(achTimeBuf,
countof(achTimeBuf),
#if IS_MSVC // MSVC uses proprietary '#' #if IS_MSVC // MSVC uses proprietary '#'
_T("%#c"), _T("%#c"),
#else #else
_T("%c"), _T("%c"),
#endif #endif
ptm ); ptm);
if( nbWritten ) if (nbWritten)
strBuf = achTimeBuf; strBuf = achTimeBuf;
else else
strBuf = TSS_GetString( cCore, core::STR_UNKNOWN_TIME ); strBuf = TSS_GetString(cCore, core::STR_UNKNOWN_TIME);
return strBuf; return strBuf;
} }

View File

@ -52,8 +52,8 @@
// DECLARATION OF CLASSES // DECLARATION OF CLASSES
//========================================================================= //=========================================================================
TSS_EXCEPTION( eTWLocale, eError ); TSS_EXCEPTION(eTWLocale, eError);
TSS_EXCEPTION( eTWLocaleBadNumFormat, eError ); TSS_EXCEPTION(eTWLocaleBadNumFormat, eError);
/////////////////////////////////////////////// ///////////////////////////////////////////////
// cTWLocale // cTWLocale
@ -68,30 +68,30 @@ class cTWLocale
{ {
public: public:
static void InitGlobalLocale(); static void InitGlobalLocale();
// initializes global locale to the default locale // initializes global locale to the default locale
// //
// basic functionality // basic functionality
// //
static TSTRING& FormatNumber( int32 i, TSTRING& strBuf ); static TSTRING& FormatNumber(int32 i, TSTRING& strBuf);
static TSTRING& FormatNumber( int64 i, TSTRING& strBuf ); static TSTRING& FormatNumber(int64 i, TSTRING& strBuf);
static TSTRING& FormatNumber( uint32 ui, TSTRING& strBuf ); static TSTRING& FormatNumber(uint32 ui, TSTRING& strBuf);
static TSTRING& FormatNumber( uint64 ui, TSTRING& strBuf ); static TSTRING& FormatNumber(uint64 ui, TSTRING& strBuf);
static TSTRING& FormatNumber( double d, TSTRING& strBuf ); static TSTRING& FormatNumber(double d, TSTRING& strBuf);
// returns the locale-specific representation of the given cardinal number // returns the locale-specific representation of the given cardinal number
/* /*
static TSTRING FormatNumberClassic( int32 i ); static TSTRING FormatNumberClassic( int32 i );
static int32 FormatNumberClassic( const TSTRING& s ); static int32 FormatNumberClassic( const TSTRING& s );
// returns the C-locale representation of the given cardinal number // returns the C-locale representation of the given cardinal number
*/ */
// disabled this since nobody's using it // disabled this since nobody's using it
// static TSTRING FormatNumberAsHex( int32 x ); // static TSTRING FormatNumberAsHex( int32 x );
// locale-independant // locale-independant
static TSTRING& FormatTime( int64 t, TSTRING& strBuf ); static TSTRING& FormatTime(int64 t, TSTRING& strBuf);
// returns the local time and date formatted according to the current locale. // returns the local time and date formatted according to the current locale.
// t is the number of seconds elapsed since midnight (00:00:00), // t is the number of seconds elapsed since midnight (00:00:00),
// January 1, 1970, coordinated universal time // January 1, 1970, coordinated universal time
}; };
//========================================================================= //=========================================================================
@ -100,22 +100,21 @@ public:
namespace tss namespace tss
{ {
//////////////////////////////////////////////// ////////////////////////////////////////////////
// GetFacet // GetFacet
// //
// Abstracts std::use_facet since Win32 and KAI // Abstracts std::use_facet since Win32 and KAI
// each implement it in a non-standard way. // each implement it in a non-standard way.
//////////////////////////////////////////////// ////////////////////////////////////////////////
template< class FacetT > inline const FacetT& GetFacet( const std::locale& l, const FacetT* pf ) template<class FacetT> inline const FacetT& GetFacet(const std::locale& l, const FacetT* pf)
{ {
#if USE_STD_CPP_LOCALE_WORKAROUND #if USE_STD_CPP_LOCALE_WORKAROUND
return std::use_facet( l, pf ); return std::use_facet(l, pf);
#else #else
return std::use_facet< FacetT >( l ); (void)pf; // This is C++ standard return std::use_facet<FacetT>(l);
(void)pf; // This is C++ standard
#endif #endif
}
} }
} // namespace tss
#endif //__TWLOCALE_H #endif //__TWLOCALE_H

View File

@ -42,4 +42,3 @@ enum Languages
}; };
#endif #endif

View File

@ -47,8 +47,9 @@ public:
cType(const TCHAR* name); cType(const TCHAR* name);
const TCHAR* AsString() const; const TCHAR* AsString() const;
bool operator==(const cType& rhs) const; bool operator==(const cType& rhs) const;
bool operator!=(const cType& rhs) const; bool operator!=(const cType& rhs) const;
private: private:
TSTRING mString; TSTRING mString;
}; };
@ -57,33 +58,35 @@ class iTyped
{ {
public: public:
virtual const cType& GetType() const = 0; virtual const cType& GetType() const = 0;
// the type of an FCO; classes that implement this interface need to // the type of an FCO; classes that implement this interface need to
// (a) declare a public static const cType member mType and // (a) declare a public static const cType member mType and
// (b) returning that object in their implementation of GetType() // (b) returning that object in their implementation of GetType()
// You can use the macros below to simplify the process // You can use the macros below to simplify the process
virtual ~iTyped() {} virtual ~iTyped()
{
}
}; };
////////////////////////////////////////////// //////////////////////////////////////////////
// convenience macros for implementing iTyped // convenience macros for implementing iTyped
////////////////////////////////////////////// //////////////////////////////////////////////
#define DECLARE_TYPED()\ #define DECLARE_TYPED() \
public:\ public: \
static const cType mType;\ static const cType mType; \
virtual const cType& GetType() const; virtual const cType& GetType() const;
// put DECLARE_TYPED in the class definition // put DECLARE_TYPED in the class definition
#define IMPLEMENT_TYPED(CLASS, STRING)\ #define IMPLEMENT_TYPED(CLASS, STRING) \
const cType CLASS::mType(STRING);\ const cType CLASS::mType(STRING); \
const cType& CLASS::GetType() const\ const cType& CLASS::GetType() const \
{\ { \
return mType;\ return mType; \
} }
// put IMPLEMENT_TYPED in the .cpp file where the class is implemented // put IMPLEMENT_TYPED in the .cpp file where the class is implemented
#define CLASS_TYPE(CLASS) CLASS::mType #define CLASS_TYPE(CLASS) CLASS::mType
// a convienent way to specify a class's type // a convienent way to specify a class's type
/////////////////////////////////////////////// ///////////////////////////////////////////////
// iTyped Example // iTyped Example
@ -116,8 +119,7 @@ const cType& CLASS::GetType() const\
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// inline implementation // inline implementation
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
inline cType::cType(const TCHAR* name) : inline cType::cType(const TCHAR* name) : mString(name)
mString(name)
{ {
ASSERT(!mString.empty()); ASSERT(!mString.empty());
} }
@ -140,4 +142,3 @@ inline bool cType::operator!=(const cType& rhs) const
#endif //__TYPED_H #endif //__TYPED_H

View File

@ -41,46 +41,45 @@
#endif #endif
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// standard TSS types // standard TSS types
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
typedef unsigned char byte ; // platform-independent typedef unsigned char byte; // platform-independent
typedef signed char int8 ; typedef signed char int8;
typedef short int16 ; typedef short int16;
typedef float float32 ; typedef float float32;
typedef double float64 ; typedef double float64;
typedef unsigned char uint8 ; typedef unsigned char uint8;
typedef unsigned short uint16 ; typedef unsigned short uint16;
#if HAVE_STDINT_H #if HAVE_STDINT_H
typedef int32_t int32 ; typedef int32_t int32;
typedef uint32_t uint32 ; typedef uint32_t uint32;
#elif SIZEOF_INT == 4 #elif SIZEOF_INT == 4
typedef int int32 ; typedef int int32;
typedef unsigned int uint32 ; typedef unsigned int uint32;
#elif SIZEOF_LONG == 4 #elif SIZEOF_LONG == 4
typedef long int32 ; typedef long int32;
typedef unsigned long uint32 ; typedef unsigned long uint32;
#else #else
# error "I don't seem to have a 32-bit integer type on this system." # error "I don't seem to have a 32-bit integer type on this system."
#endif #endif
#if HAVE_STDINT_H #if HAVE_STDINT_H
typedef int64_t int64 ; typedef int64_t int64;
typedef uint64_t uint64 ; typedef uint64_t uint64;
#elif SIZEOF_LONG == 8 #elif SIZEOF_LONG == 8
typedef long int64 ; typedef long int64;
typedef unsigned long uint64 ; typedef unsigned long uint64;
#elif SIZEOF_LONG_LONG == 8 #elif SIZEOF_LONG_LONG == 8
typedef long long int64 ; typedef long long int64;
typedef unsigned long long uint64 ; typedef unsigned long long uint64;
#else #else
# error "I don't seem to have a 64-bit integer type on this system." # error "I don't seem to have a 64-bit integer type on this system."
#endif #endif
// other Win32 definitions // other Win32 definitions
@ -93,23 +92,23 @@ typedef unsigned long long uint64 ;
#if (!(USES_2S_COMPLEMENT)) #if (!(USES_2S_COMPLEMENT))
#error limits.h depends on 2s complement integers. Check core/types.h # error limits.h depends on 2s complement integers. Check core/types.h
#endif #endif
#include <limits.h> // defines limits for built-in types #include <limits.h> // defines limits for built-in types
#define TSS_INT8_MIN (-127 - 1) #define TSS_INT8_MIN (-127 - 1)
#define TSS_INT8_MAX 127 #define TSS_INT8_MAX 127
#define TSS_UINT8_MAX 0xFFU #define TSS_UINT8_MAX 0xFFU
#define TSS_INT16_MIN (-32767 - 1) #define TSS_INT16_MIN (-32767 - 1)
#define TSS_INT16_MAX 32767 #define TSS_INT16_MAX 32767
#define TSS_UINT16_MAX 0xFFFFU #define TSS_UINT16_MAX 0xFFFFU
#define TSS_INT32_MIN (-2147483647 - 1) #define TSS_INT32_MIN (-2147483647 - 1)
#define TSS_INT32_MAX 2147483647 #define TSS_INT32_MAX 2147483647
#define TSS_UINT32_MAX 0xFFFFFFFFU #define TSS_UINT32_MAX 0xFFFFFFFFU
#define TSS_INT64_MIN (-9223372036854775807LL - 1) #define TSS_INT64_MIN (-9223372036854775807LL - 1)
#define TSS_INT64_MAX 9223372036854775807LL #define TSS_INT64_MAX 9223372036854775807LL
#define TSS_UINT64_MAX 0xFFFFFFFFFFFFFFFFULL #define TSS_UINT64_MAX 0xFFFFFFFFFFFFFFFFULL
/* /*
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@ -157,60 +156,49 @@ inline int16 SWAPBYTES16(int16 i)
{ {
return ((uint16)i >> 8) | ((uint16)i << 8); return ((uint16)i >> 8) | ((uint16)i << 8);
} }
inline int32 SWAPBYTES32(int32 i) inline int32 SWAPBYTES32(int32 i)
{ {
return ((uint32)i >> 24) | return ((uint32)i >> 24) | (((uint32)i & 0x00ff0000) >> 8) | (((uint32)i & 0x0000ff00) << 8) | ((uint32)i << 24);
(((uint32)i & 0x00ff0000) >> 8) |
(((uint32)i & 0x0000ff00) << 8) |
((uint32)i << 24);
} }
inline int64 SWAPBYTES64(int64 i) inline int64 SWAPBYTES64(int64 i)
{ {
return ((uint64)i >> 56) | return ((uint64)i >> 56) | (((uint64)i & 0x00ff000000000000ULL) >> 40) |
(((uint64)i & 0x00ff000000000000ULL) >> 40) | (((uint64)i & 0x0000ff0000000000ULL) >> 24) | (((uint64)i & 0x000000ff00000000ULL) >> 8) |
(((uint64)i & 0x0000ff0000000000ULL) >> 24) | (((uint64)i & 0x00000000ff000000ULL) << 8) | (((uint64)i & 0x0000000000ff0000ULL) << 24) |
(((uint64)i & 0x000000ff00000000ULL) >> 8) | (((uint64)i & 0x000000000000ff00ULL) << 40) | ((uint64)i << 56);
(((uint64)i & 0x00000000ff000000ULL) << 8) |
(((uint64)i & 0x0000000000ff0000ULL) << 24) |
(((uint64)i & 0x000000000000ff00ULL) << 40) |
((uint64)i << 56);
} }
#ifdef WORDS_BIGENDIAN # ifdef WORDS_BIGENDIAN
#define tw_htonl(x) (x) # define tw_htonl(x) (x)
#define tw_ntohl(x) (x) # define tw_ntohl(x) (x)
#define tw_htons(x) (x) # define tw_htons(x) (x)
#define tw_ntohs(x) (x) # define tw_ntohs(x) (x)
#define tw_htonll(x) (x) // int64 versions # define tw_htonll(x) (x) // int64 versions
#define tw_ntohll(x) (x) # define tw_ntohll(x) (x)
#else //!WORDS_BIGENDIAN # else //!WORDS_BIGENDIAN
#define tw_htonl(x) SWAPBYTES32((x)) # define tw_htonl(x) SWAPBYTES32((x))
#define tw_ntohl(x) SWAPBYTES32((x)) # define tw_ntohl(x) SWAPBYTES32((x))
#define tw_htons(x) SWAPBYTES16((x)) # define tw_htons(x) SWAPBYTES16((x))
#define tw_ntohs(x) SWAPBYTES16((x)) # define tw_ntohs(x) SWAPBYTES16((x))
#define tw_htonll(x) SWAPBYTES64((x)) // int64 versions # define tw_htonll(x) SWAPBYTES64((x)) // int64 versions
#define tw_ntohll(x) SWAPBYTES64((x)) # define tw_ntohll(x) SWAPBYTES64((x))
#endif //WORDS_BIGENDIAN # endif //WORDS_BIGENDIAN
//////////////////////////////////////////// ////////////////////////////////////////////
#if __cplusplus >= 201103L # if __cplusplus >= 201103L
# define TW_UNIQUE_PTR std::unique_ptr # define TW_UNIQUE_PTR std::unique_ptr
#else # else
# define TW_UNIQUE_PTR std::auto_ptr # define TW_UNIQUE_PTR std::auto_ptr
#endif # endif
#endif // __TYPES_H #endif // __TYPES_H

View File

@ -38,27 +38,26 @@
#include <errno.h> #include <errno.h>
// TODO: JEB: make this look like eFileError // TODO: JEB: make this look like eFileError
eUnix::eUnix( const TCHAR* szFunctionName, const TCHAR* szObjectName, bool fCallGetLastError) eUnix::eUnix(const TCHAR* szFunctionName, const TCHAR* szObjectName, bool fCallGetLastError) : eError(_T(""))
: eError( _T(""))
{ {
ASSERT( szFunctionName || szObjectName || fCallGetLastError ); ASSERT(szFunctionName || szObjectName || fCallGetLastError);
// //
// construct the error message: // construct the error message:
// //
// it will be of the form: FuncName() failed for Object: <FormatMessage output> // it will be of the form: FuncName() failed for Object: <FormatMessage output>
// //
if( szFunctionName ) if (szFunctionName)
{ {
mMsg = szFunctionName; mMsg = szFunctionName;
mMsg += _T(" failed"); mMsg += _T(" failed");
if( szObjectName ) if (szObjectName)
{ {
mMsg += _T(" for "); mMsg += _T(" for ");
mMsg += szObjectName; mMsg += szObjectName;
} }
} }
else if( szObjectName ) else if (szObjectName)
{ {
mMsg = szObjectName; mMsg = szObjectName;
} }
@ -67,11 +66,11 @@ eUnix::eUnix( const TCHAR* szFunctionName, const TCHAR* szObjectName, bool fCall
mMsg = _T("Error"); mMsg = _T("Error");
} }
if( fCallGetLastError ) if (fCallGetLastError)
{ {
TSTRING strErr = strerror(errno); TSTRING strErr = strerror(errno);
if( ! strErr.empty() ) if (!strErr.empty())
{ {
mMsg += _T(": "); mMsg += _T(": ");
mMsg += strErr; mMsg += strErr;

View File

@ -41,18 +41,16 @@
#include "error.h" #include "error.h"
#endif #endif
TSS_BEGIN_EXCEPTION( eUnix, eError ) TSS_BEGIN_EXCEPTION(eUnix, eError)
eUnix( const TCHAR* functionName, const TCHAR* objectName, bool displayErrorNumber = true ); eUnix(const TCHAR* functionName, const TCHAR* objectName, bool displayErrorNumber = true);
// construct one of these to indicate a unix api failure. both functionName and // construct one of these to indicate a unix api failure. both functionName and
// objectName can be NULL. This method will construct a string to pass to eError // objectName can be NULL. This method will construct a string to pass to eError
// that contains all of the above information plus whatever errno returns if the dusplayErrorNumber // that contains all of the above information plus whatever errno returns if the dusplayErrorNumber
// parameter is true. // parameter is true.
TSS_END_EXCEPTION() TSS_END_EXCEPTION()
#endif //__unixexcept_H #endif //__unixexcept_H

File diff suppressed because it is too large Load Diff

View File

@ -56,113 +56,111 @@
class cUnixFSServices : public iFSServices class cUnixFSServices : public iFSServices
{ {
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
// MEMBER FUNCTIONS // MEMBER FUNCTIONS
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
public: public:
cUnixFSServices(); cUnixFSServices();
virtual ~cUnixFSServices(); virtual ~cUnixFSServices();
//////////////////////////////////////// ////////////////////////////////////////
// platform specific functions // platform specific functions
//////////////////////////////////////// ////////////////////////////////////////
virtual bool IsCaseSensitive() const; virtual bool IsCaseSensitive() const;
// returns true if the file system is case sensitive // returns true if the file system is case sensitive
virtual const TCHAR* GetStandardBackupExtension() const; virtual const TCHAR* GetStandardBackupExtension() const;
// returns normal string to append to backup files for this os. // returns normal string to append to backup files for this os.
// (e.g. "~" for unix and ".bak" for winos) // (e.g. "~" for unix and ".bak" for winos)
virtual TCHAR GetPathSeparator() const; virtual TCHAR GetPathSeparator() const;
//////////////////////////////////////// ////////////////////////////////////////
// process functions // process functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void Sleep( int nSeconds ) const; virtual void Sleep(int nSeconds) const;
// makes the current process sleep for the specified number of seconds // makes the current process sleep for the specified number of seconds
//////////////////////////////////////// ////////////////////////////////////////
// major filesystem functions // major filesystem functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void Stat( const TSTRING& strFileName, cFSStatArgs& pStat ) const ; virtual void Stat(const TSTRING& strFileName, cFSStatArgs& pStat) const;
// fills out the cFSStatArgs structure with the stat info for the named file // fills out the cFSStatArgs structure with the stat info for the named file
virtual void GetTempDirName( TSTRING& strName ) const ; virtual void GetTempDirName(TSTRING& strName) const;
// makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' ) // makes directory if it doesn't exist already. Dirname will end with a delimiter ( '/' )
virtual void SetTempDirName(TSTRING& tmpName); virtual void SetTempDirName(TSTRING& tmpName);
// set the default dir name which GetTempDirName will use... // set the default dir name which GetTempDirName will use...
virtual TSTRING& MakeTempFilename( TSTRING& strName ) const ; virtual TSTRING& MakeTempFilename(TSTRING& strName) const;
// create temporary file // create temporary file
// strName must have the form ("baseXXXXXX"), where the X's are replaced with // strName must have the form ("baseXXXXXX"), where the X's are replaced with
// characters to make it a unique file. There must be at least 6 Xs. // characters to make it a unique file. There must be at least 6 Xs.
//////////////////////////////////////// ////////////////////////////////////////
// minor filesystem functions // minor filesystem functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void GetHostID( TSTRING& name ) const; virtual void GetHostID(TSTRING& name) const;
virtual void GetMachineName( TSTRING& name) const; virtual void GetMachineName(TSTRING& name) const;
virtual void GetMachineNameFullyQualified( TSTRING& name ) const; virtual void GetMachineNameFullyQualified(TSTRING& name) const;
virtual bool GetCurrentUserName( TSTRING& tstrName ) const; virtual bool GetCurrentUserName(TSTRING& tstrName) const;
virtual bool GetIPAddress( uint32& uiIPAddress ); virtual bool GetIPAddress(uint32& uiIPAddress);
//////////////////////////////////////// ////////////////////////////////////////
// directory specific functions // directory specific functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void ReadDir( const TSTRING& strName, std::vector<TSTRING> &vDirContents, bool bFullPaths = true ) const; virtual void ReadDir(const TSTRING& strName, std::vector<TSTRING>& vDirContents, bool bFullPaths = true) const;
// puts the contents of the specified directory, except for . and .., into the supplied vector. // puts the contents of the specified directory, except for . and .., into the supplied vector.
virtual void GetCurrentDir( TSTRING& strCurDir ) const; virtual void GetCurrentDir(TSTRING& strCurDir) const;
// returns the current working directory // returns the current working directory
//////////////////////////////////////// ////////////////////////////////////////
// file specific functions // file specific functions
//////////////////////////////////////// ////////////////////////////////////////
virtual bool FileDelete( const TSTRING& name ) const; virtual bool FileDelete(const TSTRING& name) const;
//////////////////////////////////////// ////////////////////////////////////////
// directory and file functions // directory and file functions
//////////////////////////////////////// ////////////////////////////////////////
virtual bool Rename( const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true ) const; virtual bool Rename(const TSTRING& strOldName, const TSTRING& strNewName, bool fOverWrite = true) const;
// rename a file // rename a file
virtual bool GetUserName( uid_t user_id, TSTRING& tstrUser ) const; virtual bool GetUserName(uid_t user_id, TSTRING& tstrUser) const;
virtual bool GetGroupName( gid_t group_id, TSTRING& tstrGroup ) const; virtual bool GetGroupName(gid_t group_id, TSTRING& tstrGroup) const;
//Set whether we try to resolve uid/gid to a name, since Linux static binaries can //Set whether we try to resolve uid/gid to a name, since Linux static binaries can
//have trouble (read: segfaulting) with name resolution given the right nsswitch.conf setup. //have trouble (read: segfaulting) with name resolution given the right nsswitch.conf setup.
//This defaults to true if not specified. //This defaults to true if not specified.
virtual void SetResolveNames(bool resolve); virtual void SetResolveNames(bool resolve);
//////////////////////////////////////// ////////////////////////////////////////
// miscellaneous utility functions // miscellaneous utility functions
//////////////////////////////////////// ////////////////////////////////////////
virtual void ConvertModeToString( uint64 perm, TSTRING& tstrPerm ) const; virtual void ConvertModeToString(uint64 perm, TSTRING& tstrPerm) const;
// takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx) // takes a int64 permission (from stat) and changes it to look like UNIX's 'ls -l' (e.g. drwxrwxrwx)
virtual bool FullPath( TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("") ) const; virtual bool FullPath(TSTRING& fullPath, const TSTRING& relPath, const TSTRING& pathRelFrom = _T("")) const;
// converts relPath into a fully qualified path, storing it in FullPath. If this // converts relPath into a fully qualified path, storing it in FullPath. If this
// fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom. // fails, false is returned. if the path to which relPath is relative is not CWD, put it in pathRelFrom.
virtual bool GetExecutableFilename( TSTRING& strFullPath, const TSTRING& strFilename ) const; virtual bool GetExecutableFilename(TSTRING& strFullPath, const TSTRING& strFilename) const;
// get the path to the current executable file // get the path to the current executable file
virtual bool IsRoot( const TSTRING& strPath ) const; virtual bool IsRoot(const TSTRING& strPath) const;
// returns true if strPath is all '/'s // returns true if strPath is all '/'s
//////////////////////////////////////// ////////////////////////////////////////
// error functions // error functions
//////////////////////////////////////// ////////////////////////////////////////
virtual TSTRING GetErrString() const; virtual TSTRING GetErrString() const;
private: private:
TSTRING mTempPath;
TSTRING mTempPath; bool mResolveNames;
bool mResolveNames;
}; };
#endif //__UNIXFSSERVICES_H #endif //__UNIXFSSERVICES_H

View File

@ -54,25 +54,26 @@
// Argument : CmpFuncT less : Comparison function. Must return as 'std::less'. // Argument : CmpFuncT less : Comparison function. Must return as 'std::less'.
// Will be called as: 'bool less( *FwdIterT, CmpObjT )'. // Will be called as: 'bool less( *FwdIterT, CmpObjT )'.
///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////
template< class FwdIterT, class CmpObjT, class CmpFuncT > FwdIterT UpperBound( FwdIterT first, FwdIterT last, const CmpObjT& obj, CmpFuncT less ) template<class FwdIterT, class CmpObjT, class CmpFuncT>
FwdIterT UpperBound(FwdIterT first, FwdIterT last, const CmpObjT& obj, CmpFuncT less)
{ {
// count elements in set // count elements in set
int nElemsInSet = 0; int nElemsInSet = 0;
FwdIterT iCur = first; FwdIterT iCur = first;
for (; iCur != last; ++iCur ) for (; iCur != last; ++iCur)
++nElemsInSet; ++nElemsInSet;
iCur = first; iCur = first;
while( 0 < nElemsInSet ) while (0 < nElemsInSet)
{ {
// go to halfway point // go to halfway point
int iHalfWay = nElemsInSet/2; int iHalfWay = nElemsInSet / 2;
FwdIterT iTemp = iCur; FwdIterT iTemp = iCur;
for( int j = 0; j < iHalfWay; j++ ) for (int j = 0; j < iHalfWay; j++)
iTemp++; iTemp++;
if( less( *iTemp, obj ) ) if (less(*iTemp, obj))
{ {
// start next search set at next elem with half of the last search set's elements // start next search set at next elem with half of the last search set's elements
iCur = ++iTemp; iCur = ++iTemp;
@ -89,4 +90,3 @@ template< class FwdIterT, class CmpObjT, class CmpFuncT > FwdIterT UpperBound( F
} }
#endif // __UPPERBOUND_H #endif // __UPPERBOUND_H

View File

@ -36,20 +36,17 @@
// There was a problem with varargs on some combo of old OpenBSD & old compiler. // There was a problem with varargs on some combo of old OpenBSD & old compiler.
// Not needed with current, but it's here if you need it. // Not needed with current, but it's here if you need it.
#ifdef TW_OLD_OPENBSD_VARARGS #ifdef TW_OLD_OPENBSD_VARARGS
# undef va_start # undef va_start
# ifdef __GNUC__ # ifdef __GNUC__
# define va_start(ap, last) \ # define va_start(ap, last) ((ap) = (va_list)__builtin_next_arg(last))
((ap) = (va_list)__builtin_next_arg(last)) # else
# else # define va_start(ap, last) ((ap) = (va_list) & (last) + __va_size(last))
# define va_start(ap, last) \ # endif
((ap) = (va_list)&(last) + __va_size(last))
# endif
#endif // TW_OLD_OPENBSD_VARARGS #endif // TW_OLD_OPENBSD_VARARGS
iUserNotify* iUserNotify::mpInstance = 0; iUserNotify* iUserNotify::mpInstance = 0;
iUserNotify::iUserNotify(int verboseLevel) : iUserNotify::iUserNotify(int verboseLevel) : mVerboseLevel(verboseLevel)
mVerboseLevel(verboseLevel)
{ {
} }
@ -70,33 +67,33 @@ int iUserNotify::GetVerboseLevel() const
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// NotifySilent // NotifySilent
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void iUserNotify::NotifySilent( const TCHAR* format, ... ) void iUserNotify::NotifySilent(const TCHAR* format, ...)
{ {
va_list args; va_list args;
va_start(args, format); va_start(args, format);
HandleNotify( V_SILENT, format, args ); HandleNotify(V_SILENT, format, args);
va_end(args); va_end(args);
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// NotifyNormal // NotifyNormal
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void iUserNotify::NotifyNormal( const TCHAR* format, ... ) void iUserNotify::NotifyNormal(const TCHAR* format, ...)
{ {
va_list args; va_list args;
va_start(args, format); va_start(args, format);
HandleNotify( V_NORMAL, format, args ); HandleNotify(V_NORMAL, format, args);
va_end(args); va_end(args);
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// NotifyVerbose // NotifyVerbose
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void iUserNotify::NotifyVerbose( const TCHAR* format, ... ) void iUserNotify::NotifyVerbose(const TCHAR* format, ...)
{ {
va_list args; va_list args;
va_start(args, format); va_start(args, format);
HandleNotify( V_VERBOSE, format, args ); HandleNotify(V_VERBOSE, format, args);
va_end(args); va_end(args);
} }
@ -107,8 +104,6 @@ void iUserNotify::Notify(int verboseLevel, const TCHAR* format, ...)
{ {
va_list args; va_list args;
va_start(args, format); va_start(args, format);
HandleNotify( verboseLevel, format, args ); HandleNotify(verboseLevel, format, args);
va_end(args); va_end(args);
} }

View File

@ -50,18 +50,18 @@ public:
static iUserNotify* GetInstance(); static iUserNotify* GetInstance();
static void SetInstance(iUserNotify* pInst); static void SetInstance(iUserNotify* pInst);
virtual void Notify(int verboseLevel, const TCHAR* format, ...) ; virtual void Notify(int verboseLevel, const TCHAR* format, ...);
// notify the user that an event has occured. The outcome of this operation is // notify the user that an event has occured. The outcome of this operation is
// dependant on the type of object that is implementing this interface (for example, // dependant on the type of object that is implementing this interface (for example,
// a console application would want an iUserNotify that prints things to stdout) // a console application would want an iUserNotify that prints things to stdout)
// If the current verbosity level is less than verboseLevel, nothing will happen. // If the current verbosity level is less than verboseLevel, nothing will happen.
// All output should be sent through the cDisplayEncoder beforehand // All output should be sent through the cDisplayEncoder beforehand
// TODO:BAM -- enforce this somehow? // TODO:BAM -- enforce this somehow?
virtual void SetVerboseLevel(int level); virtual void SetVerboseLevel(int level);
virtual int GetVerboseLevel() const; virtual int GetVerboseLevel() const;
// get/set the current verbosity level. Notify()s that occur whose verbosity level // get/set the current verbosity level. Notify()s that occur whose verbosity level
// is greater than the current level will not be processed. // is greater than the current level will not be processed.
// a convenience enumeration; no one is bound by law to use these // a convenience enumeration; no one is bound by law to use these
enum VerboseLevel enum VerboseLevel
@ -73,19 +73,21 @@ public:
// //
// convenience methods for notifying at these three levels... // convenience methods for notifying at these three levels...
// //
void NotifySilent ( const TCHAR* format, ... ); void NotifySilent(const TCHAR* format, ...);
void NotifyNormal ( const TCHAR* format, ... ); void NotifyNormal(const TCHAR* format, ...);
void NotifyVerbose ( const TCHAR* format, ... ); void NotifyVerbose(const TCHAR* format, ...);
iUserNotify(int verboseLevel = 0); iUserNotify(int verboseLevel = 0);
virtual ~iUserNotify(); virtual ~iUserNotify();
protected: protected:
virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) = 0; virtual void HandleNotify(int level, const TCHAR* format, va_list& args) = 0;
// this is implemented in derived classes to implement the specific type of // this is implemented in derived classes to implement the specific type of
// notification desired // notification desired
int mVerboseLevel; int mVerboseLevel;
private: private:
static iUserNotify* mpInstance; static iUserNotify* mpInstance;
}; };
@ -101,17 +103,17 @@ private:
// //
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
#define TW_NOTIFY_SILENT\ #define TW_NOTIFY_SILENT \
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_SILENT )\ if (iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_SILENT) \
iUserNotify::GetInstance()->NotifySilent iUserNotify::GetInstance()->NotifySilent
#define TW_NOTIFY_NORMAL\ #define TW_NOTIFY_NORMAL \
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL )\ if (iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_NORMAL) \
iUserNotify::GetInstance()->NotifyNormal iUserNotify::GetInstance()->NotifyNormal
#define TW_NOTIFY_VERBOSE\ #define TW_NOTIFY_VERBOSE \
if( iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_VERBOSE )\ if (iUserNotify::GetInstance()->GetVerboseLevel() >= iUserNotify::V_VERBOSE) \
iUserNotify::GetInstance()->NotifyVerbose iUserNotify::GetInstance()->NotifyVerbose
//############################################################################# //#############################################################################
// inline implementation // inline implementation
@ -129,4 +131,3 @@ inline void iUserNotify::SetInstance(iUserNotify* pInst)
#endif //__USERNOTIFY_H #endif //__USERNOTIFY_H

View File

@ -36,21 +36,20 @@
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// HandleNotify // HandleNotify
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
void cUserNotifyStdout::HandleNotify( int level, const TCHAR* format, va_list& args ) void cUserNotifyStdout::HandleNotify(int level, const TCHAR* format, va_list& args)
{ {
if(GetVerboseLevel() < level) if (GetVerboseLevel() < level)
return; return;
// all verbose output now goes to stderr // all verbose output now goes to stderr
if(level < iUserNotify::V_VERBOSE) if (level < iUserNotify::V_VERBOSE)
{ {
_vtprintf(format, args); _vtprintf(format, args);
fflush( stdout ); fflush(stdout);
} }
else else
{ {
_vftprintf(stderr, format, args); _vftprintf(stderr, format, args);
fflush( stderr ); fflush(stderr);
} }
} }

View File

@ -43,11 +43,10 @@
class cUserNotifyStdout : public iUserNotify class cUserNotifyStdout : public iUserNotify
{ {
public: public:
virtual void HandleNotify( int level, const TCHAR* format, va_list& args ) ; virtual void HandleNotify(int level, const TCHAR* format, va_list& args);
// formats the string and sends it to stdout // formats the string and sends it to stdout
// NOTE -- a little tripwire specific hack has been applied that makes all output // NOTE -- a little tripwire specific hack has been applied that makes all output
// at or above iUserNotify::V_VERBOSE go to stderr instead of stdout // at or above iUserNotify::V_VERBOSE go to stderr instead of stdout
}; };
#endif /* __USERNOTIFYSTDOUT_H */ #endif /* __USERNOTIFYSTDOUT_H */

View File

@ -167,4 +167,3 @@ void cUserStringMemBased::AddString(int setID, int stringID, TCHAR* string)
setItr->second->insert(std::pair<int, TCHAR*>(stringID, string)); setItr->second->insert(std::pair<int, TCHAR*>(stringID, string));
} }

View File

@ -40,16 +40,16 @@
#endif #endif
#ifndef __USERSTRINGMEM_H #ifndef __USERSTRINGMEM_H
#define __USERSTRINGMEM_H # define __USERSTRINGMEM_H
#ifdef _MSC_VER # ifdef _MSC_VER
#pragma warning(disable:4786) /* disable unwanted C++ /W4 warning */ # pragma warning(disable : 4786) /* disable unwanted C++ /W4 warning */
/* #pragma warning(default:4786) */ /* use this to reenable, if necessary */ /* #pragma warning(default:4786) */ /* use this to reenable, if necessary */
#endif /* _MSC_VER */ # endif /* _MSC_VER */
#ifndef __USERSTRING_H # ifndef __USERSTRING_H
#include "userstring.h" # include "userstring.h"
#endif # endif
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// class cUserStringMemBased -- A implementation where the various string // class cUserStringMemBased -- A implementation where the various string
@ -69,23 +69,22 @@ public:
~cUserStringMemBased(); ~cUserStringMemBased();
// the abstract interface // the abstract interface
virtual bool SelectStringSet (int setID); virtual bool SelectStringSet(int setID);
virtual const TCHAR* GetString (int stringID) const; virtual const TCHAR* GetString(int stringID) const;
virtual void ClearStringSet (int id); virtual void ClearStringSet(int id);
virtual void AddStringSet (int setID, const iUserString::tStringPair* pPairArray); virtual void AddStringSet(int setID, const iUserString::tStringPair* pPairArray);
virtual void AddString (int setID, int stringID, TCHAR* string); virtual void AddString(int setID, int stringID, TCHAR* string);
private: private:
typedef std::map<int, TCHAR*> StringSet; typedef std::map<int, TCHAR*> StringSet;
int mCurrentStringSet; int mCurrentStringSet;
std::map<int, StringSet*> mStringSets; std::map<int, StringSet*> mStringSets;
}; };
#ifdef _MSC_VER # ifdef _MSC_VER
//#pragma warning(default:4786) //#pragma warning(default:4786)
#endif /* _MSC_VER */ # endif /* _MSC_VER */
#endif // __USERSTRINGMEM_H #endif // __USERSTRINGMEM_H

View File

@ -40,7 +40,7 @@
#include "debug.h" #include "debug.h"
#include <stdexcept> // for stl::out_of_range #include <stdexcept> // for stl::out_of_range
#ifdef HAVE_MEMORY_H #ifdef HAVE_MEMORY_H
# include <memory.h> #include <memory.h>
#endif #endif
int wchar16len(const WCHAR16* s) int wchar16len(const WCHAR16* s)
@ -76,17 +76,19 @@ public:
void Release(); void Release();
void Resize(int newlen); void Resize(int newlen);
void CopyString(const wc16_string_impl& rhs); void CopyString(const wc16_string_impl& rhs);
// note: does not alter this->referenceCount, and ASSERTs that refcount == 1 // note: does not alter this->referenceCount, and ASSERTs that refcount == 1
~wc16_string_impl(); // call Release() to delete ~wc16_string_impl(); // call Release() to delete
private: private:
void operator = (const wc16_string_impl& rhs) { return; } // don't call void operator=(const wc16_string_impl& rhs)
{
return;
} // don't call
}; };
static WCHAR16 NULL_WCHAR16 = 0; static WCHAR16 NULL_WCHAR16 = 0;
wc16_string::wc16_string() wc16_string::wc16_string() : mpData(0)
: mpData(0)
{ {
} }
@ -112,42 +114,39 @@ wc16_string::~wc16_string()
mpData->Release(); mpData->Release();
} }
void wc16_string::operator = (const wc16_string& rhs) void wc16_string::operator=(const wc16_string& rhs)
{ {
if (mpData) if (mpData)
mpData->Release(); mpData->Release();
mpData = rhs.mpData; mpData = rhs.mpData;
if( mpData ) if (mpData)
mpData->AddRef(); mpData->AddRef();
} }
int wc16_string::compare(const wc16_string& rhs) const int wc16_string::compare(const wc16_string& rhs) const
{ {
if( length() > rhs.length() ) if (length() > rhs.length())
return 1; return 1;
else if ( length() < rhs.length() ) else if (length() < rhs.length())
return -1; return -1;
else else
return memcmp( c_str(), rhs.c_str(), length()*sizeof( WCHAR16 ) ); return memcmp(c_str(), rhs.c_str(), length() * sizeof(WCHAR16));
} }
wc16_string::size_type wc16_string::size_type wc16_string::length() const
wc16_string::length() const
{ {
return mpData ? mpData->length : 0; return mpData ? mpData->length : 0;
} }
wc16_string::size_type wc16_string::size_type wc16_string::size() const
wc16_string::size() const
{ {
return mpData ? mpData->length : 0; return mpData ? mpData->length : 0;
} }
wc16_string::const_iterator wc16_string::const_iterator wc16_string::c_str() const
wc16_string::c_str() const
{ {
if (mpData == 0) if (mpData == 0)
return &NULL_WCHAR16; return &NULL_WCHAR16;
@ -157,35 +156,24 @@ wc16_string::c_str() const
return mpData->pString; return mpData->pString;
} }
wc16_string::const_iterator wc16_string::const_iterator wc16_string::begin() const
wc16_string::begin() const
{ {
return (const_cast<wc16_string*>(this))->begin(); return (const_cast<wc16_string*>(this))->begin();
} }
wc16_string::iterator wc16_string::iterator wc16_string::begin()
wc16_string::begin()
{ {
return mpData ? mpData->pString : &NULL_WCHAR16; return mpData ? mpData->pString : &NULL_WCHAR16;
} }
wc16_string::const_iterator wc16_string::const_iterator wc16_string::end() const
wc16_string::end() const
{ {
return return const_cast<iterator>(mpData ? mpData->pString + mpData->length : &NULL_WCHAR16);
const_cast< iterator >(
mpData
? mpData->pString + mpData->length
: &NULL_WCHAR16 );
} }
wc16_string::iterator wc16_string::iterator wc16_string::end()
wc16_string::end()
{ {
return return mpData ? mpData->pString + mpData->length : &NULL_WCHAR16;
mpData
? mpData->pString + mpData->length
: &NULL_WCHAR16;
} }
wc16_string::const_iterator wc16_string::data() const wc16_string::const_iterator wc16_string::data() const
@ -193,7 +181,7 @@ wc16_string::const_iterator wc16_string::data() const
return begin(); return begin();
} }
const wc16_string::value_type& wc16_string::operator [] (int i) const const wc16_string::value_type& wc16_string::operator[](int i) const
{ {
ASSERT(i >= 0); ASSERT(i >= 0);
@ -206,7 +194,7 @@ const wc16_string::value_type& wc16_string::operator [] (int i) const
return mpData->pString[i]; return mpData->pString[i];
} }
wc16_string::value_type& wc16_string::operator [] (int i) wc16_string::value_type& wc16_string::operator[](int i)
{ {
ASSERT(i >= 0); ASSERT(i >= 0);
@ -226,20 +214,20 @@ wc16_string::value_type& wc16_string::operator [] (int i)
return mpData->pString[i]; return mpData->pString[i];
} }
void wc16_string::resize( size_type nCount ) void wc16_string::resize(size_type nCount)
{ {
if ( mpData == 0 ) if (mpData == 0)
{ {
mpData = new wc16_string_impl; mpData = new wc16_string_impl;
} }
else if ( mpData->refCount > 1 ) else if (mpData->refCount > 1)
{ {
wc16_string_impl* newImpl = new wc16_string_impl( *mpData ); wc16_string_impl* newImpl = new wc16_string_impl(*mpData);
mpData->Release(); mpData->Release();
mpData = newImpl; mpData = newImpl;
} }
mpData->Resize( nCount ); mpData->Resize(nCount);
} }
// useful to convert to network byte order // useful to convert to network byte order
@ -264,17 +252,17 @@ void wc16_string::swapbytes()
wc16_string_impl::wc16_string_impl() wc16_string_impl::wc16_string_impl()
{ {
length = 0; length = 0;
pString = new WCHAR16[1]; pString = new WCHAR16[1];
refCount = 1; refCount = 1;
} }
wc16_string_impl::wc16_string_impl(const wc16_string_impl& rhs) wc16_string_impl::wc16_string_impl(const wc16_string_impl& rhs)
{ {
int newlen = rhs.length; int newlen = rhs.length;
pString = new WCHAR16[newlen + 1]; pString = new WCHAR16[newlen + 1];
length = newlen; length = newlen;
refCount = 1; refCount = 1;
memcpy(pString, rhs.pString, newlen * sizeof(WCHAR16)); memcpy(pString, rhs.pString, newlen * sizeof(WCHAR16));
} }
@ -312,7 +300,7 @@ void wc16_string_impl::Resize(int newlen)
memcpy(newString, pString, newlen * sizeof(WCHAR16)); memcpy(newString, pString, newlen * sizeof(WCHAR16));
delete [] pString; delete [] pString;
pString = newString; pString = newString;
length = newlen; length = newlen;
} }
else else
{ {
@ -320,7 +308,7 @@ void wc16_string_impl::Resize(int newlen)
memset(newString + length, 0, (newlen - length) * sizeof(WCHAR16)); memset(newString + length, 0, (newlen - length) * sizeof(WCHAR16));
delete [] pString; delete [] pString;
pString = newString; pString = newString;
length = newlen; length = newlen;
} }
} }
@ -333,10 +321,9 @@ void wc16_string_impl::CopyString(const wc16_string_impl& rhs)
if (rhs.length != this->length) if (rhs.length != this->length)
{ {
delete [] pString; delete [] pString;
pString = new WCHAR16[newlen + 1]; pString = new WCHAR16[newlen + 1];
this->length = newlen; this->length = newlen;
} }
memcpy(this->pString, rhs.pString, newlen * sizeof(WCHAR16)); memcpy(this->pString, rhs.pString, newlen * sizeof(WCHAR16));
} }

View File

@ -44,9 +44,9 @@
#endif #endif
#if WCHAR_IS_16_BITS #if WCHAR_IS_16_BITS
typedef unsigned short WCHAR16; typedef unsigned short WCHAR16;
#else #else
typedef uint16 WCHAR16; // unix has 4 byte wchar_t, but we want to standardize on 16 bit wide chars typedef uint16 WCHAR16; // unix has 4 byte wchar_t, but we want to standardize on 16 bit wide chars
#endif #endif
//============================================================================= //=============================================================================
@ -70,49 +70,46 @@ class wc16_string_impl;
class wc16_string class wc16_string
{ {
public: public:
typedef WCHAR16 value_type;
typedef WCHAR16 value_type; typedef value_type* iterator;
typedef value_type* iterator; typedef const value_type* const_iterator;
typedef const value_type* const_iterator; typedef size_t size_type;
typedef size_t size_type;
wc16_string(); wc16_string();
wc16_string( const wc16_string& rhs); wc16_string(const wc16_string& rhs);
wc16_string( const_iterator pStr); wc16_string(const_iterator pStr);
~wc16_string(); ~wc16_string();
void operator=( const wc16_string& rhs ); void operator=(const wc16_string& rhs);
int compare( const wc16_string& rhs ) const; int compare(const wc16_string& rhs) const;
size_type length() const; size_type length() const;
size_type size() const; size_type size() const;
const_iterator begin() const; const_iterator begin() const;
iterator begin(); iterator begin();
const_iterator end() const; const_iterator end() const;
iterator end(); iterator end();
const_iterator c_str() const; const_iterator c_str() const;
const_iterator data() const; const_iterator data() const;
bool empty() const bool empty() const
{ {
return length() == 0; return length() == 0;
} }
const value_type& operator[]( int i ) const; // throw std::out_of_range const value_type& operator[](int i) const; // throw std::out_of_range
value_type& operator[]( int i ); // throw std::out_of_range value_type& operator[](int i); // throw std::out_of_range
void resize( size_type ); void resize(size_type);
void swapbytes(); // useful to convert to network byte order void swapbytes(); // useful to convert to network byte order
private: private:
wc16_string_impl* mpData; wc16_string_impl* mpData;
}; };
#endif #endif

View File

@ -45,78 +45,87 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// cBlock // cBlock
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template <int SIZE> template<int SIZE> class cBlock
class cBlock
{ {
public: public:
enum { INVALID_NUM = -1 }; enum
{
INVALID_NUM = -1
};
cBlock(); cBlock();
void SetDirty () { mbDirty = true; } void SetDirty()
bool IsDirty () const { return mbDirty; } {
int GetBlockNum () const { return mBlockNum; } mbDirty = true;
int8* GetData() { return mpData; } }
bool IsDirty() const
{
return mbDirty;
}
int GetBlockNum() const
{
return mBlockNum;
}
int8* GetData()
{
return mpData;
}
bool AssertValid() const; bool AssertValid() const;
// this asserts and returns false if the guard bytes have been corrupted // this asserts and returns false if the guard bytes have been corrupted
bool IsValidAddr(int8* pAddr) const; bool IsValidAddr(int8* pAddr) const;
// returns true if pAddr falls within mpData // returns true if pAddr falls within mpData
protected: protected:
enum { NUM_GUARD_BLOCKS = 8, // associated with BYTE_ALIGN: see ctor for info enum
GUARD_BLOCK_VAL = 0xAB }; // odd, non-zero value for debugging {
NUM_GUARD_BLOCKS = 8, // associated with BYTE_ALIGN: see ctor for info
GUARD_BLOCK_VAL = 0xAB
}; // odd, non-zero value for debugging
// guardMin and guardMax are used to detect bad writes // guardMin and guardMax are used to detect bad writes
uint8 mGuardMin[NUM_GUARD_BLOCKS]; uint8 mGuardMin[NUM_GUARD_BLOCKS];
int8 mpData[SIZE]; int8 mpData[SIZE];
uint8 mGuardMax[NUM_GUARD_BLOCKS]; uint8 mGuardMax[NUM_GUARD_BLOCKS];
bool mbDirty; bool mbDirty;
int mBlockNum; int mBlockNum;
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ctor // ctor
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <int SIZE> template<int SIZE> inline cBlock<SIZE>::cBlock() : mbDirty(false), mBlockNum(cBlock::INVALID_NUM)
inline cBlock<SIZE>::cBlock()
: mbDirty (false),
mBlockNum (cBlock::INVALID_NUM)
{ {
// To prevent misaligned memory access, the size of the data and the // To prevent misaligned memory access, the size of the data and the
// number of guard blocks must be a multiple of the byte alignment // number of guard blocks must be a multiple of the byte alignment
// and they both must be at least as large as the byte alignment // and they both must be at least as large as the byte alignment
ASSERT( 0 == ( SIZE % BYTE_ALIGN ) ); ASSERT(0 == (SIZE % BYTE_ALIGN));
ASSERT( 0 == ( NUM_GUARD_BLOCKS % BYTE_ALIGN ) ); ASSERT(0 == (NUM_GUARD_BLOCKS % BYTE_ALIGN));
ASSERT( SIZE >= BYTE_ALIGN ); ASSERT(SIZE >= BYTE_ALIGN);
ASSERT( NUM_GUARD_BLOCKS >= BYTE_ALIGN ); ASSERT(NUM_GUARD_BLOCKS >= BYTE_ALIGN);
// init guard blocks to dummy value // init guard blocks to dummy value
for( int i = 0; i < NUM_GUARD_BLOCKS; i++ ) for (int i = 0; i < NUM_GUARD_BLOCKS; i++)
{ {
mGuardMin[i] = (uint8)GUARD_BLOCK_VAL; mGuardMin[i] = (uint8)GUARD_BLOCK_VAL;
mGuardMax[i] = (uint8)GUARD_BLOCK_VAL; mGuardMax[i] = (uint8)GUARD_BLOCK_VAL;
} }
// zero out memory // zero out memory
memset( mpData, 0, SIZE ); memset(mpData, 0, SIZE);
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ctor // ctor
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <int SIZE> template<int SIZE> inline bool cBlock<SIZE>::AssertValid() const
inline bool cBlock<SIZE>::AssertValid() const
{ {
// determine if guard bites have been accidentally overwritten // determine if guard bites have been accidentally overwritten
for( int i = 0; i < NUM_GUARD_BLOCKS; i++ ) for (int i = 0; i < NUM_GUARD_BLOCKS; i++)
{ {
if( if ((mGuardMin[i] != (uint8)GUARD_BLOCK_VAL) || (mGuardMax[i] != (uint8)GUARD_BLOCK_VAL))
( mGuardMin[i] != (uint8) GUARD_BLOCK_VAL )
||
( mGuardMax[i] != (uint8) GUARD_BLOCK_VAL )
)
{ {
ASSERT( false ); ASSERT(false);
return false; return false;
} }
} }
@ -124,56 +133,62 @@ inline bool cBlock<SIZE>::AssertValid() const
return true; return true;
} }
template <int SIZE> template<int SIZE> inline bool cBlock<SIZE>::IsValidAddr(int8* pAddr) const
inline bool cBlock<SIZE>::IsValidAddr(int8* pAddr) const
{ {
return ( (pAddr >= &mpData[0]) && (pAddr <= &mpData[SIZE-1]) ); return ((pAddr >= &mpData[0]) && (pAddr <= &mpData[SIZE - 1]));
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// cBlockImpl // cBlockImpl
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
template <int SIZE> template<int SIZE> class cBlockImpl : public cBlock<SIZE>
class cBlockImpl : public cBlock<SIZE>
{ {
public: public:
enum { INVALID_NUM = -1 }; enum
{
INVALID_NUM = -1
};
cBlockImpl(); cBlockImpl();
void SetBlockNum ( int blockNum ) { cBlock<SIZE>::mBlockNum = blockNum; } void SetBlockNum(int blockNum)
void SetTimestamp( uint32 timestamp ) { mTimestamp = timestamp; } {
uint32 GetTimestamp() const { return mTimestamp; } cBlock<SIZE>::mBlockNum = blockNum;
}
void SetTimestamp(uint32 timestamp)
{
mTimestamp = timestamp;
}
uint32 GetTimestamp() const
{
return mTimestamp;
}
void Write ( cBidirArchive& arch ); //throw( eArchive ) void Write(cBidirArchive& arch); //throw( eArchive )
void Read ( cBidirArchive& arch, int blockNum = INVALID_NUM ); //throw( eArchive ) void Read(cBidirArchive& arch, int blockNum = INVALID_NUM); //throw( eArchive )
// if blockNum is INVALID_NUM, then it reads in the current block number // if blockNum is INVALID_NUM, then it reads in the current block number
protected: protected:
uint32 mTimestamp; uint32 mTimestamp;
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// ctor // ctor
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <int SIZE> template<int SIZE> inline cBlockImpl<SIZE>::cBlockImpl() : cBlock<SIZE>(), mTimestamp(0)
inline cBlockImpl<SIZE>::cBlockImpl()
: cBlock<SIZE> ( ),
mTimestamp (0)
{ {
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Write // Write
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <int SIZE> template<int SIZE> inline void cBlockImpl<SIZE>::Write(cBidirArchive& arch) //throw( eArchive )
inline void cBlockImpl<SIZE>::Write( cBidirArchive& arch ) //throw( eArchive )
{ {
ASSERT( mbDirty ); ASSERT(mbDirty);
ASSERT( (mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length()) ); ASSERT((mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length()));
arch.Seek ( (cBlock<SIZE>::mBlockNum * SIZE), cBidirArchive::BEGINNING ); arch.Seek((cBlock<SIZE>::mBlockNum * SIZE), cBidirArchive::BEGINNING);
arch.WriteBlob ( cBlock<SIZE>::mpData, SIZE ); arch.WriteBlob(cBlock<SIZE>::mpData, SIZE);
cBlock<SIZE>::mbDirty = false; cBlock<SIZE>::mbDirty = false;
} }
@ -181,21 +196,19 @@ inline void cBlockImpl<SIZE>::Write( cBidirArchive& arch ) //throw( eArchive )
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
// Read // Read
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
template <int SIZE> template<int SIZE> inline void cBlockImpl<SIZE>::Read(cBidirArchive& arch, int blockNum) //throw( eArchive )
inline void cBlockImpl<SIZE>::Read( cBidirArchive& arch, int blockNum ) //throw( eArchive )
{ {
if( blockNum != INVALID_NUM ) if (blockNum != INVALID_NUM)
cBlock<SIZE>::mBlockNum = blockNum; cBlock<SIZE>::mBlockNum = blockNum;
ASSERT( (mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length()) ); ASSERT((mBlockNum >= 0) && (((mBlockNum + 1) * SIZE) <= arch.Length()));
// std::cout << "cBlockImpl<SIZE>::Read() mBlockNum = " << mBlockNum << " arch.Length() = " << arch.Length() << std::endl; // std::cout << "cBlockImpl<SIZE>::Read() mBlockNum = " << mBlockNum << " arch.Length() = " << arch.Length() << std::endl;
arch.Seek ( (cBlock<SIZE>::mBlockNum * SIZE), cBidirArchive::BEGINNING ); arch.Seek((cBlock<SIZE>::mBlockNum * SIZE), cBidirArchive::BEGINNING);
arch.ReadBlob ( cBlock<SIZE>::mpData, SIZE ); arch.ReadBlob(cBlock<SIZE>::mpData, SIZE);
cBlock<SIZE>::mbDirty = false; cBlock<SIZE>::mbDirty = false;
} }
#endif #endif

Some files were not shown because too many files have changed in this diff Show More